Aadi

Upload Queue

Component

About

An upload queue for chat attachments: per file progress with speed and time left, a dropped connection with resume, processing steps after upload, and a header total with Cancel all.

Built with React and Tailwind. Copy the prompt and paste it into Claude Code, Cursor or Lovable: your agent adds Upload Queue to your project and fits it to your theme.

Code

How Upload Queue is used: the demo's code. The component's own source comes with a free account.

Usage.tsx

"use client"

import * as React from "react"
import { UploadQueue, UploadQueueFile } from "@/components/ui/upload-queue"

const FIT_CSS = "html,body{overflow:hidden}[data-fit-small] [data-fit-hide]{display:none!important}"

/**
 * 21st shows a demo in a small frame: about 674 by 421 on a component page, 358 by 224 on a
 * phone and 245 by 139 on a profile card. A demo taller than its frame gets scrollbars, which
 * render white on dark pages. FitFrame fills the frame exactly instead.
 *
 * - "scale": the content shrinks until it fits, centered. For visuals such as orbs.
 * - "crop": the content stays at full size from the top and fades out at the bottom. For text
 *   that streams in, where a changing scale would make the page breathe.
 *
 * `minWidth` lays out a wide demo (a table, a two column panel) at that width and scales it down
 * to the frame, instead of letting it collapse to a narrow layout. The frame centers it, so it
 * shrinks evenly on both sides.
 *
 * Anything marked `data-fit-hide` (state buttons, the chatcn.dev line) drops out in frames
 * shorter than `hideBelow`, so a profile card shows the visual alone.
 */
function FitFrame({
  children,
  mode = "scale",
  hideBelow = 360,
  minWidth,
}: {
  children: React.ReactNode
  mode?: "scale" | "crop"
  hideBelow?: number
  minWidth?: string
}) {
  const content = React.useRef<HTMLDivElement>(null)
  const [cropped, setCropped] = React.useState(false)

  React.useLayoutEffect(() => {
    const el = content.current
    if (!el) return
    const measure = () => {
      const vw = window.innerWidth
      const vh = window.innerHeight
      el.toggleAttribute("data-fit-small", vh < hideBelow)
      // Layout sizes ignore the transform, so measuring never feeds back.
      const w = Math.max(el.offsetWidth, el.scrollWidth)
      const h = Math.max(el.offsetHeight, el.scrollHeight)
      const scale = mode === "scale" ? Math.min(1, vw / w, vh / h) : 1
      el.style.transform = scale < 1 ? `scale(${scale})` : ""
      setCropped(mode === "crop" && h > vh + 1)
    }
    measure()
    const observer = new ResizeObserver(measure)
    observer.observe(el)
    // Content that changes inside a fixed width box (a headline that cycles words) never resizes
    // the box itself, so changes below it measure again on the next frame.
    let frame = 0
    const mutations = new MutationObserver(() => {
      cancelAnimationFrame(frame)
      frame = requestAnimationFrame(measure)
    })
    mutations.observe(el, { subtree: true, childList: true, characterData: true })
    window.addEventListener("resize", measure)
    return () => {
      observer.disconnect()
      mutations.disconnect()
      cancelAnimationFrame(frame)
      window.removeEventListener("resize", measure)
    }
  }, [mode, hideBelow])

  const fade = "linear-gradient(to bottom, #000 calc(100% - 40px), transparent)"
  return (
    <div
      className="flex w-full justify-center overflow-hidden"
      style={{
        height: "100dvh",
        alignItems: mode === "crop" ? "flex-start" : "center",
        maskImage: cropped ? fade : undefined,
        WebkitMaskImage: cropped ? fade : undefined,
      }}
    >
      <style>{FIT_CSS}</style>
      <div
        ref={content}
        className="w-full shrink-0"
        style={{ transformOrigin: mode === "crop" ? "top center" : "center", minWidth }}
      >
        {children}
      </div>
    </div>
  )
}

/** A file in the demo uploader: how fast it moves, and whether it fails or needs processing. */
interface SimFile {
  id: string
  name: string
  size: number
  type?: string
  /** Average bytes per second. */
  speed: number
  /** Fails once when progress passes this point. */
  failAt?: number
  failError?: string
  /** Time spent in `processing` after the bytes land. */
  processMs?: number
  processingLabel?: string
}

interface SimState {
  file: SimFile
  status: UploadQueueFile["status"]
  progress: number
  rate?: number
  failed?: boolean
  processingSince?: number
}

const TICK = 200

/**
 * A scripted uploader for the examples: two files transfer at a time, rates wobble the way real
 * networks do, one file can fail once and some files process after their bytes land.
 */
function useUploadSim(initial: SimFile[], { concurrency = 2, paused = false } = {}) {
  const make = React.useCallback(
    (files: SimFile[]): SimState[] =>
      files.map((file) => ({ file, status: "queued", progress: 0 })),
    [],
  )
  const [items, setItems] = React.useState<SimState[]>(() => make(initial))

  React.useEffect(() => {
    if (paused) return
    const id = window.setInterval(() => {
      setItems((prev) => {
        const now = Date.now()
        let slots = concurrency - prev.filter((s) => s.status === "uploading").length
        return prev.map((s) => {
          if (s.status === "queued" && slots > 0) {
            slots -= 1
            return { ...s, status: "uploading" }
          }
          if (s.status === "uploading") {
            const wobble = 0.8 + Math.random() * 0.4
            const rate = s.file.speed * wobble
            const progress = Math.min(1, s.progress + (rate * (TICK / 1000)) / s.file.size)
            if (s.file.failAt !== undefined && !s.failed && progress >= s.file.failAt) {
              return {
                ...s,
                status: "failed",
                progress: s.file.failAt,
                rate: undefined,
                failed: true,
              }
            }
            if (progress >= 1) {
              return s.file.processMs
                ? { ...s, status: "processing", progress: 1, rate: undefined, processingSince: now }
                : { ...s, status: "done", progress: 1, rate: undefined }
            }
            return { ...s, progress, rate }
          }
          if (
            s.status === "processing" &&
            now - (s.processingSince ?? now) >= (s.file.processMs ?? 0)
          ) {
            return { ...s, status: "done" }
          }
          return s
        })
      })
    }, TICK)
    return () => window.clearInterval(id)
  }, [concurrency, paused])

  const files: UploadQueueFile[] = items.map((s) => ({
    id: s.file.id,
    name: s.file.name,
    size: s.file.size,
    type: s.file.type,
    status: s.status,
    progress: s.progress,
    bytesPerSecond: s.rate,
    error: s.status === "failed" ? s.file.failError : undefined,
    processingLabel: s.file.processingLabel,
  }))

  const actions = React.useMemo(() => {
    const update = (id: string, fn: (s: SimState) => SimState) =>
      setItems((prev) => prev.map((s) => (s.file.id === id ? fn(s) : s)))
    const stop = (s: SimState): SimState =>
      s.status === "queued" || s.status === "uploading"
        ? { ...s, status: "canceled", rate: undefined }
        : s
    return {
      cancel: (id: string) => update(id, stop),
      cancelAll: () => setItems((prev) => prev.map(stop)),
      // Failed uploads resume from where they stopped; canceled ones start over.
      retry: (id: string) =>
        update(id, (s) => ({
          ...s,
          status: "queued",
          progress: s.status === "canceled" ? 0 : s.progress,
        })),
      remove: (id: string) => setItems((prev) => prev.filter((s) => s.file.id !== id)),
      add: (files: SimFile[]) => setItems((prev) => [...prev, ...make(files)]),
      reset: (files: SimFile[]) => setItems(make(files)),
    }
  }, [make])

  return { files, ...actions }
}

const MB = 1_000_000

const analyticsFiles: SimFile[] = [
  {
    id: "subscriptions",
    name: "subscriptions_2026_q1.csv",
    type: "text/csv",
    size: 48.2 * MB,
    speed: 7.8 * MB,
    processMs: 1800,
    processingLabel: "Reading 182,406 rows",
  },
  {
    id: "interviews",
    name: "churn-interviews-transcripts.zip",
    type: "application/zip",
    size: 31.6 * MB,
    speed: 6.4 * MB,
    failAt: 0.37,
    failError: "Connection lost at 37%. Retry to resume from where it stopped.",
  },
  {
    id: "deck",
    name: "Board deck March 2026.pdf",
    type: "application/pdf",
    size: 12.6 * MB,
    speed: 5.2 * MB,
    processMs: 2600,
    processingLabel: "Extracting text",
  },
  {
    id: "cohorts",
    name: "cohort-retention.png",
    type: "image/png",
    size: 1.84 * MB,
    speed: 2.6 * MB,
  },
  {
    id: "notes",
    name: "Q1 2026 renewal call notes from the customer success team, EU and APAC accounts (final).docx",
    type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    size: 2.31 * MB,
    speed: 3.1 * MB,
  },
]

/**
 * Five files for the analytics agent: two transfer at a time, the PDF extracts its text, the
 * archive drops its connection once and resumes on Retry, and the finished queue folds into the
 * attached row. Then it replays.
 */
function UploadQueueDemo() {
  const sim = useUploadSim(analyticsFiles)
  const { files, retry, reset } = sim
  const failedId = files.find((f) => f.status === "failed")?.id
  const allDone = files.length > 0 && files.every((f) => f.status === "done")
  const stopped =
    files.length > 0 && files.every((f) => f.status === "canceled" || f.status === "done")

  // Nobody pressed Retry: the demo does it after a moment.
  React.useEffect(() => {
    if (!failedId) return
    const id = window.setTimeout(() => retry(failedId), 2600)
    return () => window.clearTimeout(id)
  }, [failedId, retry])

  React.useEffect(() => {
    if (!allDone && !stopped) return
    const id = window.setTimeout(() => reset(analyticsFiles), allDone ? 5200 : 3000)
    return () => window.clearTimeout(id)
  }, [allDone, stopped, reset])

  return (
    <div className="w-full max-w-lg">
      <UploadQueue
        files={files}
        onCancel={sim.cancel}
        onCancelAll={sim.cancelAll}
        onRetry={sim.retry}
        onRemove={sim.remove}
      />
    </div>
  )
}

/** The line under each 21st demo that points back to the kit. */
function MoreOn({ slug, children }: { slug: string; children: React.ReactNode }) {
  return (
    <p data-fit-hide className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-faint) text-center text-balance">
      {children}{" "}
      <a
        href={`https://chatcn.dev/docs/components/${slug}`}
        target="_blank"
        rel="noopener"
        className="text-(color:--chatcn-fg-subtle) hover:text-(color:--chatcn-fg) underline underline-offset-2"
      >
        chatcn.dev
      </a>
    </p>
  )
}

/** The kit's own example, framed for the 21st preview. */
export default function UploadQueuePreview() {
  return (
    <FitFrame minWidth="34rem">
      <div className="flex w-full flex-col items-center justify-center gap-4 p-6">
        <div className="flex w-full max-w-2xl justify-center">
          <UploadQueueDemo />
        </div>
        <MoreOn slug="upload-queue">Uploads with progress, retries and cancel. On</MoreOn>
      </div>
    </FitFrame>
  )
}

Dependencies

More by Aadi

View all
  • Dither Orb

    Dither Orb

    12
  • Audio Visualizer

    Audio Visualizer

    9
  • Voice Orb

    Voice Orb

    8
  • Agent Lanes

    Agent Lanes

    6
  • Computer View

    Computer View

    3
  • Waveform

    Waveform

    2
  • Reasoning

    Reasoning

    2
  • Voice Session

    Voice Session

    1

Explore more

Part of chatcn — browse the full library on 21st.dev.