{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"file-upload","type":"registry:block","title":"File upload","description":"A complete file selection flow with constraints, progress, and error feedback.","categories":["blocks"],"dependencies":["lucide-react","motion"],"registryDependencies":["https://uiarc.dev/r/arc-motion-tokens.json"],"files":[{"path":"registry/components/file-upload/file-upload.tsx","type":"registry:component","target":"@components/arc/file-upload/file-upload.tsx","content":"\"use client\";\n\nimport { useEffect, useId, useRef, useState } from \"react\";\nimport type { ChangeEvent, DragEvent, KeyboardEvent } from \"react\";\nimport { AnimatePresence, animate, motion, useIsPresent, useMotionValue, useMotionValueEvent, useReducedMotion, useTransform, type HTMLMotionProps, type MotionProps, type TargetAndTransition, type Transition } from \"motion/react\";\nimport { File, FileArchive, FileImage, FileText, RotateCw, UploadCloud, X } from \"lucide-react\";\nimport { motionTokens } from \"../lib/motion-tokens\";\nimport styles from \"./file-upload.module.css\";\n\nexport type FileUploadItem = { id: string; file: File; error?: string };\n\nexport interface FileUploadProps {\n  accept?: string;\n  disabled?: boolean;\n  label?: string;\n  description?: string;\n  multiple?: boolean;\n  maxSize?: number;\n  value?: FileUploadItem[];\n  onChange?: (files: FileUploadItem[]) => void;\n  /** Uploads each accepted file. Report progress from 0 to 100, resolve when done, or reject to mark the file as failed. Removing a file aborts its signal. */\n  onUpload?: (file: File, options: { onProgress: (percent: number) => void; signal: AbortSignal }) => Promise<void>;\n}\n\ntype Upload = { status: \"uploading\" | \"done\" | \"failed\"; progress: number };\n\nconst enter: Transition = { duration: motionTokens.duration.standard, ease: [...motionTokens.ease.enter] };\nconst exitFast: Transition = { duration: motionTokens.duration.fast, ease: [...motionTokens.ease.standard] };\nconst instant: Transition = { duration: 0 };\nconst textIn: TargetAndTransition = { opacity: 0, y: \"0.3em\", filter: `blur(${motionTokens.blur.soft}px)` };\nconst textOut: TargetAndTransition = { opacity: 0, y: \"-0.3em\", filter: `blur(${motionTokens.blur.subtle}px)`, transition: exitFast };\nconst iconIn: TargetAndTransition = { opacity: 0, scale: .6, filter: `blur(${motionTokens.blur.subtle}px)` };\nconst shown: TargetAndTransition = { opacity: 1, y: \"0em\", scale: 1, filter: \"blur(0px)\" };\nconst fadeOut: TargetAndTransition = { opacity: 0, transition: { duration: motionTokens.duration.instant } };\n\nfunction FileTypeIcon({ file }: { file: File }) {\n  const props = { size: 16, strokeWidth: 1.8, \"aria-hidden\": true } as const;\n  if (file.type.startsWith(\"image/\")) return <FileImage {...props} />;\n  if (file.type.startsWith(\"text/\")) return <FileText {...props} />;\n  if (file.type.includes(\"zip\") || file.name.endsWith(\".gz\")) return <FileArchive {...props} />;\n  return <File {...props} />;\n}\n\nfunction formatSize(bytes: number) {\n  if (bytes < 1024) return `${bytes} B`;\n  if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;\n  const mb = bytes / (1024 * 1024);\n  return `${mb >= 10 ? Math.round(mb) : Number(mb.toFixed(1))} MB`;\n}\n\n/** Outgoing copies are hidden from assistive tech while they fade, so live text reads only the current message. */\nfunction Swap(props: HTMLMotionProps<\"span\">) {\n  const present = useIsPresent();\n  return <motion.span {...props} aria-hidden={present ? props[\"aria-hidden\"] : true} />;\n}\n\nfunction FileRow({ item, upload, reduce, onRemove, onRetry, removeRef }: { item: FileUploadItem; upload?: Upload; reduce: boolean | null; onRemove: () => void; onRetry: () => void; removeRef: (node: HTMLButtonElement | null) => void }) {\n  const status = upload?.status;\n  // A finished upload keeps its bar until the spring reaches the end, so 100% is seen before the label turns to Uploaded.\n  const [filled, setFilled] = useState(status !== \"uploading\");\n  const [seen, setSeen] = useState(status);\n  if (seen !== status) { setSeen(status); if (status === \"uploading\") setFilled(false); }\n  const shownStatus = status === \"done\" && !filled && !reduce ? \"uploading\" : status;\n  const phase = item.error ? \"invalid\" : shownStatus ?? \"ready\";\n  // One spring drives the bar and the counted percentage, so both always agree.\n  const progress = useMotionValue(upload?.progress ?? 0);\n  // The fill slides in from the left instead of scaling, so its rounded end keeps its shape at every value.\n  const x = useTransform(progress, latest => `${Math.min(Math.max(latest, 0), 100) - 100}%`);\n  const percent = useTransform(progress, latest => `${Math.round(Math.min(Math.max(latest, 0), 100))}%`);\n  const target = status === \"done\" ? 100 : upload?.progress ?? 0;\n  useEffect(() => {\n    // Every upload starts from an empty bar, even a retry that failed halfway.\n    if (reduce || (status === \"uploading\" && target === 0)) { progress.jump(target); return; }\n    const controls = animate(progress, target, { ...motionTokens.spring.smooth, onComplete: status === \"done\" ? () => setFilled(true) : undefined });\n    return () => controls.stop();\n  }, [status, target, progress, reduce]);\n  // The label turns as soon as the count reads 100%, without waiting out the spring's last fraction of a pixel.\n  useMotionValueEvent(progress, \"change\", latest => { if (status === \"done\" && latest >= 99.5) setFilled(true); });\n  const swap: MotionProps = { initial: reduce ? { opacity: 0 } : textIn, animate: shown, exit: reduce ? fadeOut : textOut, transition: reduce ? instant : enter };\n  return <div className={styles.fileItem}>\n    <span className={styles.fileIcon}><FileTypeIcon file={item.file} /></span>\n    <span className={styles.fileCopy}>\n      <strong title={item.file.name}>{item.file.name}</strong>\n      <span className={styles.meta}>{formatSize(item.file.size)}{shownStatus ? <><span className={styles.dot} aria-hidden=\"true\">·</span><span className={styles.phase}><AnimatePresence mode=\"popLayout\" initial={false}>\n        <Swap key={shownStatus} className={shownStatus === \"failed\" ? `${styles.phaseText} ${styles.error}` : styles.phaseText} {...swap}>{shownStatus === \"uploading\" ? <>Uploading <motion.span className={styles.percent}>{percent}</motion.span></> : shownStatus === \"done\" ? \"Uploaded\" : \"Upload failed\"}</Swap>\n      </AnimatePresence></span></> : null}</span>\n      {item.error && <span className={styles.error}>{item.error}</span>}\n      {/* The bar fills on a spring, then folds away once the file lands. */}\n      <AnimatePresence initial={false}>{shownStatus === \"uploading\" && <motion.span key=\"bar\" className={styles.barFrame} initial={reduce ? { opacity: 0 } : { height: 0, opacity: 0 }} animate={{ height: \"auto\", opacity: 1 }} exit={reduce ? fadeOut : { height: 0, opacity: 0, transition: { height: { ...motionTokens.spring.smooth, delay: .24 }, opacity: { ...exitFast, delay: .24 } } }} transition={reduce ? instant : { height: motionTokens.spring.smooth, opacity: enter }}>\n        <span className={styles.bar}><motion.span className={styles.barFill} style={{ x }} /></span>\n      </motion.span>}</AnimatePresence>\n    </span>\n    <span className={styles.statusSlot}>\n      <AnimatePresence mode=\"popLayout\" initial={false}>\n        {(phase === \"ready\" || phase === \"done\") && <motion.span key=\"ready\" className={styles.ready} initial={reduce ? { opacity: 0 } : { opacity: 0, scale: .8 }} animate={{ opacity: 1, scale: 1 }} exit={fadeOut} transition={reduce ? instant : motionTokens.spring.snappy}>\n          <svg width={14} height={14} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth={2} strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\"><motion.path d=\"M4 12.5l5 5L20 6.5\" initial={reduce ? false : { pathLength: 0 }} animate={{ pathLength: 1 }} transition={{ ...enter, delay: .08 }} /></svg>\n          <span className={styles.srOnly}>{phase === \"done\" ? \"Uploaded\" : \"Ready\"}</span>\n        </motion.span>}\n        {/* The wrapper carries the entrance, so the button's own press scale never competes with it. */}\n        {phase === \"failed\" && <motion.span key=\"retry\" className={styles.retrySlot} initial={reduce ? { opacity: 0 } : iconIn} animate={shown} exit={reduce ? fadeOut : { ...iconIn, transition: exitFast }} transition={reduce ? instant : motionTokens.spring.snappy}>\n          <button type=\"button\" className={styles.retry} aria-label={`Retry ${item.file.name}`} onClick={onRetry}><RotateCw size={14} strokeWidth={1.8} aria-hidden=\"true\" /></button>\n        </motion.span>}\n      </AnimatePresence>\n    </span>\n    <button ref={removeRef} type=\"button\" className={styles.remove} aria-label={`Remove ${item.file.name}`} onClick={onRemove}><X size={15} aria-hidden=\"true\" /></button>\n  </div>;\n}\n\nexport function FileUpload({\n  accept,\n  disabled = false,\n  label = \"Upload files\",\n  description = \"Drop files here or browse from your device.\",\n  multiple = true,\n  maxSize,\n  value,\n  onChange,\n  onUpload,\n}: FileUploadProps) {\n  const inputId = useId();\n  const reduce = useReducedMotion();\n  const inputRef = useRef<HTMLInputElement>(null);\n  const dropzoneRef = useRef<HTMLDivElement>(null);\n  const [internalFiles, setInternalFiles] = useState<FileUploadItem[]>([]);\n  const [dragging, setDragging] = useState(false);\n  const [status, setStatus] = useState(\"\");\n  const [uploads, setUploads] = useState<Record<string, Upload>>({});\n  const dragDepth = useRef(0);\n  const nextId = useRef(0);\n  const controllers = useRef(new Map<string, AbortController>());\n  const removeRefs = useRef(new Map<string, HTMLButtonElement>());\n  const files = value ?? internalFiles;\n\n  useEffect(() => {\n    const active = controllers.current;\n    return () => active.forEach(controller => controller.abort());\n  }, []);\n\n  function update(next: FileUploadItem[]) {\n    if (value === undefined) setInternalFiles(next);\n    onChange?.(next);\n  }\n\n  function startUpload(item: FileUploadItem) {\n    if (!onUpload) return;\n    controllers.current.get(item.id)?.abort();\n    const controller = new AbortController();\n    controllers.current.set(item.id, controller);\n    const set = (next: (current?: Upload) => Upload) => setUploads(current => ({ ...current, [item.id]: next(current[item.id]) }));\n    set(() => ({ status: \"uploading\", progress: 0 }));\n    onUpload(item.file, {\n      signal: controller.signal,\n      onProgress: percent => { if (!controller.signal.aborted) set(current => ({ status: \"uploading\", progress: Math.min(Math.max(percent, current?.progress ?? 0), 100) })); },\n    }).then(() => {\n      if (controller.signal.aborted) return;\n      set(() => ({ status: \"done\", progress: 100 }));\n      setStatus(`${item.file.name} uploaded.`);\n    }, () => {\n      if (controller.signal.aborted) return;\n      set(current => ({ status: \"failed\", progress: current?.progress ?? 0 }));\n      setStatus(`${item.file.name} could not be uploaded.`);\n    }).finally(() => { if (controllers.current.get(item.id) === controller) controllers.current.delete(item.id); });\n  }\n\n  function addFiles(fileList: FileList | File[]) {\n    const incoming = Array.from(fileList).slice(0, multiple ? undefined : 1);\n    const acceptedTypes = accept?.split(\",\").map(type => type.trim().toLowerCase()).filter(Boolean) ?? [];\n    const matchesAccept = (file: File) => acceptedTypes.length === 0 || acceptedTypes.some(type => type.startsWith(\".\")\n      ? file.name.toLowerCase().endsWith(type)\n      : type.endsWith(\"/*\") ? file.type.startsWith(type.slice(0, -1)) : file.type === type);\n    const accepted = incoming.map(file => ({\n      id: `${file.name}-${file.lastModified}-${nextId.current++}`,\n      file,\n      error: !matchesAccept(file)\n        ? \"This file type is not accepted.\"\n        : maxSize && file.size > maxSize ? `File is larger than ${formatSize(maxSize)}.` : undefined,\n    }));\n    if (!multiple) controllers.current.forEach(controller => controller.abort());\n    update(multiple ? [...files, ...accepted] : accepted);\n    const invalidCount = accepted.filter(item => item.error).length;\n    const validCount = accepted.length - invalidCount;\n    const added = `${validCount} file${validCount === 1 ? \"\" : \"s\"} added.`;\n    const attention = `${invalidCount} file${invalidCount === 1 ? \" needs\" : \"s need\"} attention.`;\n    setStatus(!invalidCount ? added : validCount ? `${added} ${attention}` : attention);\n    accepted.filter(item => !item.error).forEach(startUpload);\n  }\n\n  function removeFile(item: FileUploadItem) {\n    controllers.current.get(item.id)?.abort();\n    controllers.current.delete(item.id);\n    // Keep keyboard focus in the list: the next row's remove button, else the previous one, else the dropzone.\n    const index = files.findIndex(file => file.id === item.id);\n    const neighbor = files[index + 1] ?? files[index - 1];\n    update(files.filter(file => file.id !== item.id));\n    setStatus(`${item.file.name} removed.`);\n    requestAnimationFrame(() => (neighbor ? removeRefs.current.get(neighbor.id) : dropzoneRef.current)?.focus());\n  }\n\n  function handleInput(event: ChangeEvent<HTMLInputElement>) {\n    if (event.target.files) addFiles(event.target.files);\n    event.target.value = \"\";\n  }\n\n  function handleDrop(event: DragEvent<HTMLDivElement>) {\n    event.preventDefault();\n    dragDepth.current = 0;\n    setDragging(false);\n    if (!disabled && event.dataTransfer.files.length) addFiles(event.dataTransfer.files);\n  }\n\n  function handleDragEnter(event: DragEvent<HTMLDivElement>) {\n    event.preventDefault();\n    if (!disabled) {\n      dragDepth.current += 1;\n      setDragging(true);\n    }\n  }\n\n  function handleDragLeave(event: DragEvent<HTMLDivElement>) {\n    event.preventDefault();\n    dragDepth.current = Math.max(0, dragDepth.current - 1);\n    if (dragDepth.current === 0) setDragging(false);\n  }\n\n  function handleKeyDown(event: KeyboardEvent<HTMLDivElement>) {\n    if (disabled) return;\n    if (event.key === \"Enter\" || event.key === \" \") {\n      event.preventDefault();\n      inputRef.current?.click();\n    }\n  }\n\n  const height: Transition = reduce ? instant : { height: motionTokens.spring.smooth, opacity: enter };\n  return <div className={styles.root}>\n    <input ref={inputRef} id={inputId} className={styles.input} type=\"file\" accept={accept} multiple={multiple} disabled={disabled} tabIndex={-1} aria-hidden=\"true\" onChange={handleInput} />\n    <div\n      ref={dropzoneRef}\n      className={[styles.dropzone, dragging ? styles.dragging : \"\", disabled ? styles.disabled : \"\"].filter(Boolean).join(\" \")}\n      role=\"button\"\n      tabIndex={disabled ? -1 : 0}\n      aria-disabled={disabled}\n      aria-describedby={`${inputId}-description`}\n      onClick={() => !disabled && inputRef.current?.click()}\n      onKeyDown={handleKeyDown}\n      onDragEnter={handleDragEnter}\n      onDragOver={event => event.preventDefault()}\n      onDragLeave={handleDragLeave}\n      onDrop={handleDrop}\n    >\n      <span className={styles.uploadIcon}><UploadCloud size={20} strokeWidth={1.8} aria-hidden=\"true\" /></span>\n      {/* While a file hovers over the target the label says what releasing it will do. */}\n      <span className={styles.copy}><strong className={styles.label}><AnimatePresence mode=\"popLayout\" initial={false}><Swap key={dragging ? \"drop\" : \"idle\"} className={styles.labelText} initial={reduce ? { opacity: 0 } : textIn} animate={shown} exit={reduce ? fadeOut : textOut} transition={reduce ? instant : enter}>{dragging ? `Drop to add ${multiple ? \"files\" : \"a file\"}` : label}</Swap></AnimatePresence></strong><span id={`${inputId}-description`}>{description}</span></span>\n      <span className={styles.browse}>Browse</span>\n    </div>\n    {/* The live region stays mounted; its frame opens on the first message and each new message rises in. */}\n    <motion.div className={styles.statusFrame} initial={false} animate={{ height: status ? \"auto\" : 0 }} transition={height}>\n      <p className={styles.status} aria-live=\"polite\" aria-atomic=\"true\"><AnimatePresence mode=\"popLayout\" initial={false}>{status ? <Swap key={status} className={styles.statusText} initial={reduce ? { opacity: 0 } : textIn} animate={shown} exit={reduce ? fadeOut : textOut} transition={reduce ? instant : enter}>{status}</Swap> : null}</AnimatePresence></p>\n    </motion.div>\n    {/* Rows open and close their own height, so the list closes the gap when a file is removed. */}\n    <motion.ul className={styles.fileList} aria-label=\"Selected files\" aria-hidden={files.length === 0 ? true : undefined} initial={false} animate={{ paddingTop: files.length ? 6 : 0 }} transition={reduce ? instant : motionTokens.spring.smooth}>\n      <AnimatePresence initial={false}>\n        {files.map(item => <motion.li key={item.id} className={styles.fileRow} initial={reduce ? { opacity: 0 } : { height: 0, opacity: 0 }} animate={{ height: \"auto\", opacity: 1 }} exit={reduce ? fadeOut : { height: 0, opacity: 0, transition: { height: motionTokens.spring.smooth, opacity: exitFast } }} transition={height}>\n          <FileRow item={item} upload={uploads[item.id]} reduce={reduce} onRemove={() => removeFile(item)} onRetry={() => startUpload(item)} removeRef={node => { if (node) removeRefs.current.set(item.id, node); else removeRefs.current.delete(item.id); }} />\n        </motion.li>)}\n      </AnimatePresence>\n    </motion.ul>\n  </div>;\n}\n\nexport default FileUpload;\n"},{"path":"registry/components/file-upload/file-upload.module.css","type":"registry:component","target":"@components/arc/file-upload/file-upload.module.css","content":".root { display: grid; width: 100%; min-width: 0; color: var(--foreground); }\n.input { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; clip-path: inset(50%); }\n/* A full-width drop target: press feedback is color only, never a scale. */\n.dropzone { display: flex; min-height: 92px; align-items: center; gap: 12px; padding: 16px; border: 1px dashed var(--border-strong); border-radius: var(--radius-panel); background: var(--surface); cursor: pointer; transition: border-color var(--duration-standard) var(--ease-standard), background-color var(--duration-standard) var(--ease-standard); }\n.dropzone.dragging, .dropzone:not(.disabled):active { border-color: var(--accent); background: var(--accent-subtle); }\n.dropzone.disabled { cursor: not-allowed; opacity: .52; }\n.uploadIcon, .fileIcon { display: grid; flex: 0 0 auto; place-items: center; color: var(--accent-strong); }\n/* The cloud lifts toward the file while it hovers over the drop target. */\n.uploadIcon { width: 24px; height: 24px; transition: transform var(--duration-spring) var(--ease-spring); }\n.dragging .uploadIcon { transform: translateY(-3px); }\n.copy { display: grid; min-width: 0; gap: 3px; flex: 1; }\n.copy strong { font-size: var(--text-sm); font-weight: 500; line-height: var(--leading-body); }\n.label { position: relative; display: block; min-width: 0; }\n.labelText { display: block; }\n.copy > span { color: var(--text-muted); font-size: var(--text-xs); line-height: var(--leading-body); overflow-wrap: anywhere; }\n.browse { flex: 0 0 auto; color: var(--accent-strong); font-size: var(--text-xs); font-weight: 500; }\n.statusFrame { overflow: hidden; }\n.status { position: relative; min-height: 16px; margin: 0; padding-top: 8px; color: var(--text-muted); font-size: var(--text-xs); line-height: var(--leading-body); }\n.statusText { display: block; }\n.fileList { display: grid; margin: 0; padding: 0; list-style: none; }\n/* The gap lives inside the clipped row, so a collapsing row reaches zero height instead of stopping at its padding. */\n.fileRow { overflow: hidden; }\n.fileItem { display: flex; margin-top: 6px; min-width: 0; align-items: center; gap: 12px; padding: 10px 10px 10px 12px; border: 1px solid var(--border-subtle); border-radius: var(--radius-control); background: var(--surface-muted); }\n.fileIcon { width: 24px; height: 24px; color: var(--text-secondary); }\n.fileCopy { display: grid; min-width: 0; flex: 1; gap: 2px; }\n.fileCopy strong { overflow: hidden; font-size: var(--text-sm); font-weight: 500; line-height: var(--leading-body); text-overflow: ellipsis; white-space: nowrap; }\n.fileCopy > span { color: var(--text-muted); font-size: var(--text-xs); line-height: var(--leading-body); }\n.meta { display: flex; min-width: 0; white-space: nowrap; font-variant-numeric: tabular-nums; }\n.dot { padding-inline: 5px; }\n.phase { position: relative; display: inline-block; }\n.phaseText { display: block; }\n.percent { display: inline-block; min-width: 4ch; }\n.fileCopy .error { color: var(--danger); }\n.barFrame { display: block; }\n.bar { display: block; height: 3px; margin: 5px 0 1px; overflow: hidden; border-radius: 99px; background: var(--border); }\n.barFill { display: block; width: 100%; height: 100%; border-radius: inherit; background: var(--accent); }\n.statusSlot { position: relative; display: grid; width: 26px; height: 26px; flex: 0 0 auto; place-items: center; }\n.retrySlot { display: grid; place-items: center; }\n.ready { display: grid; width: 22px; height: 22px; place-items: center; color: var(--success); }\n.remove, .retry { display: grid; width: 26px; height: 26px; flex: 0 0 auto; place-items: center; border: 0; border-radius: var(--radius-pill); background: transparent; color: var(--text-muted); cursor: pointer; transition: transform var(--duration-spring) var(--ease-spring), background-color var(--duration-fast) var(--ease-standard), color var(--duration-fast) var(--ease-standard); }\n.retry { color: var(--text-secondary); }\n/* Quick press, spring release. */\n.remove:active, .retry:active { transform: scale(.96); transition-duration: var(--duration-instant); transition-timing-function: var(--ease-standard); }\n@media (hover: hover) and (pointer: fine) {\n  .dropzone:not(.disabled):hover { border-color: var(--accent); background: var(--accent-subtle); }\n  .remove:hover, .retry:hover { background: var(--surface); color: var(--foreground); }\n}\n.srOnly { position: absolute; width: 1px; height: 1px; padding: 0; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }\n@media (prefers-reduced-motion: reduce) { .dropzone, .uploadIcon, .remove, .retry { transition: none; } .dragging .uploadIcon, .remove:active, .retry:active { transform: none; } }\n"}],"docs":"Use it for documents or media when people need to see upload progress and recover from invalid files.","meta":{"tier":"free","kind":"block","builtFrom":["File picker","Progress","Feedback"],"docs":"https://uiarc.dev/components/blocks/file-upload"}}