{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "dropzone",
  "type": "registry:ui",
  "title": "Dropzone",
  "description": "A place to choose files to upload, by dropping them, pasting them or pressing a button, and the rows that show each file's progress with slots for pause, resume, retry and remove.",
  "categories": [
    "ui"
  ],
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/announce",
    "@rivier-ui/button",
    "@rivier-ui/cn",
    "@rivier-ui/progress"
  ],
  "files": [
    {
      "path": "registry/ui/dropzone.tsx",
      "type": "registry:ui",
      "target": "components/ui/dropzone.tsx",
      "content": "\"use client\";\n/**\n * @name dropzone\n * @category ui\n * @description A place to choose files to upload, by dropping them, pasting them or pressing a button, and the rows that show each file's progress with slots for pause, resume, retry and remove.\n * @when Adding pictures, documents or other files where progress matters: a listing's photos, attachments, an import. It contains no upload engine: the project uploads (plain, or resumable such as tus) and tells each row its state and progress. For one small file in a form, an input with type=\"file\" is enough. Name the dropzone with `aria-label` or `aria-labelledby`, and word rejected files yourself from the reason given to `onReject`.\n * @example\n * <Dropzone accept=\"image/*\" maxSize={10_000_000} onFiles={start} onReject={explain} aria-label=\"Add pictures\">\n *   <DropzoneHint>Drop pictures here, or</DropzoneHint>\n *   <DropzoneButton>Choose pictures</DropzoneButton>\n * </Dropzone>\n * <UploadList aria-label=\"Pictures being added\">\n *   {uploads.map((upload) => (\n *     <UploadItem key={upload.id} name={upload.file.name} size={upload.file.size} state={upload.state}>\n *       <UploadProgress value={upload.percent} />\n *       <UploadActions>\n *         {upload.state === \"uploading\" ? <UploadPause onClick={() => pause(upload.id)} /> : null}\n *         {upload.state === \"paused\" ? <UploadResume onClick={() => resume(upload.id)} /> : null}\n *         {upload.state === \"failed\" ? <UploadRetry onClick={() => retry(upload.id)} /> : null}\n *         <UploadRemove onClick={() => remove(upload.id)} />\n *       </UploadActions>\n *     </UploadItem>\n *   ))}\n * </UploadList>\n *\n * // A state of the project's own, with its word and tone; and a row that is not a list item\n * <UploadItem as=\"div\" name=\"walk.mp4\" state=\"checking\" stateLabel=\"Being checked\" stateTone=\"warning\" />\n */\nimport { CircleAlert, CircleCheck, CircleDashed, Clock, File as FileIcon, Pause, Play, RotateCw, TriangleAlert, Upload, X } from \"lucide-react\";\nimport {\n  createContext,\n  use,\n  useEffect,\n  useRef,\n  useState,\n  type ClipboardEvent,\n  type ComponentProps,\n  type ComponentType,\n  type DragEvent,\n  type ReactNode,\n} from \"react\";\nimport { Button, type ButtonProps } from \"@/components/ui/button\";\nimport { Progress } from \"@/components/ui/progress\";\nimport { announce } from \"@/lib/announce\";\nimport { cn } from \"@/lib/cn\";\n\n/** Why a file was not taken: its type is not in `accept`, it is larger than `maxSize`, or it is beyond `maxFiles`. */\nexport type FileRejectionReason = \"type\" | \"size\" | \"count\";\nexport type FileRejection = { file: File; reason: FileRejectionReason };\n\ntype DropzoneContextValue = { open: () => void; dragging: boolean; disabled: boolean };\n\nconst DropzoneContext = createContext<DropzoneContextValue | null>(null);\n\nfunction useDropzone(part: string): DropzoneContextValue {\n  const context = use(DropzoneContext);\n  if (!context) throw new Error(`<${part}> must be used inside <Dropzone>.`);\n  return context;\n}\n\n/** Whether a file matches an `accept` list as the browser reads it: \".png\", \"image/*\", \"application/pdf\". */\nfunction accepts(file: File, accept: string | undefined): boolean {\n  if (!accept || accept.trim() === \"\") return true;\n  const name = file.name.toLowerCase();\n  const type = file.type.toLowerCase();\n  return accept\n    .split(\",\")\n    .map((token) => token.trim().toLowerCase())\n    .filter(Boolean)\n    .some((token) => (token.startsWith(\".\") ? name.endsWith(token) : token.endsWith(\"/*\") ? type.startsWith(token.slice(0, -1)) : type === token));\n}\n\nexport type DropzoneProps = Omit<ComponentProps<\"div\">, \"onDrop\"> & {\n  /** The types taken, as for a file input: \"image/*,.pdf\". */\n  accept?: string;\n  /** The largest file taken, in bytes. */\n  maxSize?: number;\n  /** The most files taken in one go. The project counts what it already holds and passes what is left. */\n  maxFiles?: number;\n  /** Take more than one file at a time. Default true. */\n  multiple?: boolean;\n  disabled?: boolean;\n  /** The files that passed, each time some are dropped, pasted or chosen. */\n  onFiles?: (files: File[]) => void;\n  /** The files that did not pass, each with the reason, for the project to say in its own words. */\n  onReject?: (rejections: FileRejection[]) => void;\n};\n\n/**\n * The region. Files arrive three ways, all through the same rules: dropped on it, pasted while focus is\n * inside it, or chosen in the file dialog its DropzoneButton opens (the way that works by keyboard and\n * screen reader, so always include one). While files are dragged over it, it changes its look and its\n * DropzoneHint changes its words.\n */\nexport function Dropzone({ accept, maxSize, maxFiles, multiple = true, disabled = false, onFiles, onReject, className, children, onPaste, ...props }: DropzoneProps) {\n  const input = useRef<HTMLInputElement>(null);\n  const [dragging, setDragging] = useState(false);\n  /** dragenter and dragleave fire for every child crossed: only the outermost pair counts. */\n  const depth = useRef(0);\n\n  const take = (list: FileList | null | undefined): void => {\n    if (disabled || !list || list.length === 0) return;\n    const accepted: File[] = [];\n    const rejected: FileRejection[] = [];\n    const limit = multiple ? (maxFiles ?? Number.POSITIVE_INFINITY) : 1;\n    for (const file of list) {\n      if (!accepts(file, accept)) rejected.push({ file, reason: \"type\" });\n      else if (maxSize !== undefined && file.size > maxSize) rejected.push({ file, reason: \"size\" });\n      else if (accepted.length >= limit) rejected.push({ file, reason: \"count\" });\n      else accepted.push(file);\n    }\n    if (accepted.length > 0) onFiles?.(accepted);\n    if (rejected.length > 0) onReject?.(rejected);\n  };\n\n  const hasFiles = (event: DragEvent): boolean => event.dataTransfer.types.includes(\"Files\");\n\n  return (\n    <DropzoneContext value={{ open: () => input.current?.click(), dragging, disabled }}>\n      <div\n        data-slot=\"dropzone\"\n        data-dragging={dragging ? \"\" : undefined}\n        data-disabled={disabled ? \"\" : undefined}\n        role=\"group\"\n        onDragEnter={(event) => {\n          if (disabled || !hasFiles(event)) return;\n          depth.current += 1;\n          setDragging(true);\n        }}\n        onDragOver={(event) => {\n          // Without this the browser opens the file instead of handing it over.\n          if (!disabled && hasFiles(event)) event.preventDefault();\n        }}\n        onDragLeave={(event) => {\n          if (disabled || !hasFiles(event)) return;\n          depth.current = Math.max(0, depth.current - 1);\n          if (depth.current === 0) setDragging(false);\n        }}\n        onDrop={(event) => {\n          if (disabled || !hasFiles(event)) return;\n          event.preventDefault();\n          depth.current = 0;\n          setDragging(false);\n          take(event.dataTransfer.files);\n        }}\n        onPaste={(event: ClipboardEvent<HTMLDivElement>) => {\n          onPaste?.(event);\n          if (event.defaultPrevented || event.clipboardData.files.length === 0) return;\n          event.preventDefault();\n          take(event.clipboardData.files);\n        }}\n        className={cn(\n          \"flex w-full min-w-0 flex-col items-center justify-center gap-3 rounded-surface border border-dashed border-border-strong bg-background p-6 text-center text-sm transition-[background-color,border-color] duration-instant ease-out data-[disabled]:opacity-50 data-[dragging]:border-solid data-[dragging]:border-primary data-[dragging]:bg-highlight-soft motion-reduce:transition-none\",\n          className,\n        )}\n        {...props}\n      >\n        {children}\n        <input\n          ref={input}\n          data-slot=\"dropzone-input\"\n          type=\"file\"\n          hidden\n          tabIndex={-1}\n          accept={accept}\n          multiple={multiple}\n          disabled={disabled}\n          onChange={(event) => {\n            take(event.target.files);\n            // Cleared so that choosing the same file again is still a change.\n            event.target.value = \"\";\n          }}\n        />\n      </div>\n    </DropzoneContext>\n  );\n}\n\n/** The button that opens the file dialog. A real button, so it works by keyboard, switch and screen reader. */\nexport function DropzoneButton({ children, variant = \"outline\", onClick, disabled, ...props }: ButtonProps) {\n  const context = useDropzone(\"DropzoneButton\");\n  return (\n    <Button\n      data-slot=\"dropzone-button\"\n      variant={variant}\n      disabled={disabled || context.disabled}\n      onClick={(event) => {\n        onClick?.(event);\n        if (!event.defaultPrevented) context.open();\n      }}\n      {...props}\n    >\n      <Upload aria-hidden=\"true\" strokeWidth={1.5} />\n      {children}\n    </Button>\n  );\n}\n\nexport type DropzoneHintProps = ComponentProps<\"p\"> & {\n  /** The words shown in its place while files are dragged over the dropzone. Default \"Drop the files to add them\". */\n  draggingText?: ReactNode;\n};\n\n/** The line that says what to do, and what may be added (types, largest size). It changes its words while files are over the dropzone. */\nexport function DropzoneHint({ className, children, draggingText = \"Drop the files to add them\", ...props }: DropzoneHintProps) {\n  const { dragging } = useDropzone(\"DropzoneHint\");\n  return (\n    <p data-slot=\"dropzone-hint\" className={cn(\"max-w-prose text-muted-foreground\", dragging && \"font-medium text-foreground\", className)} {...props}>\n      {dragging ? draggingText : children}\n    </p>\n  );\n}\n\n/** A size in bytes as people read it (\"3.4 MB\"), in the locale's digits and unit names. */\nexport function formatFileSize(bytes: number, locale?: string): string {\n  const units = [\"byte\", \"kilobyte\", \"megabyte\", \"gigabyte\", \"terabyte\"] as const;\n  let value = Math.max(0, bytes);\n  let unit = 0;\n  while (value >= 1000 && unit < units.length - 1) {\n    value /= 1000;\n    unit += 1;\n  }\n  return new Intl.NumberFormat(locale, { style: \"unit\", unit: units[unit], unitDisplay: \"short\", maximumFractionDigits: unit === 0 || value >= 100 ? 0 : 1 }).format(value);\n}\n\nexport type UploadState = \"queued\" | \"uploading\" | \"paused\" | \"done\" | \"failed\";\n\n/** How a state reads: plain, good news, something to look at, or a failure. Each has its own mark as well as its colour. */\nexport type UploadTone = \"neutral\" | \"success\" | \"warning\" | \"destructive\";\n\ntype Mark = ComponentType<{ className?: string; strokeWidth?: number; \"aria-hidden\"?: \"true\" }>;\n\nconst STATE_WORDS: Record<UploadState, string> = { queued: \"Waiting\", uploading: \"Uploading\", paused: \"Paused\", done: \"Uploaded\", failed: \"Failed\" };\nconst STATE_ICONS: Record<UploadState, Mark> = {\n  queued: Clock,\n  uploading: Upload,\n  paused: Pause,\n  done: CircleCheck,\n  failed: CircleAlert,\n};\nconst STATE_TONES: Record<UploadState, UploadTone> = { queued: \"neutral\", uploading: \"neutral\", paused: \"neutral\", done: \"success\", failed: \"destructive\" };\n/** The mark of a state the project names itself, by its tone. */\nconst TONE_ICONS: Record<UploadTone, Mark> = { neutral: CircleDashed, success: CircleCheck, warning: TriangleAlert, destructive: CircleAlert };\nconst TONE_CLASSES: Record<UploadTone, string> = { neutral: \"\", success: \"text-success\", warning: \"text-warning\", destructive: \"text-destructive\" };\n\nconst isUploadState = (state: string): state is UploadState => state in STATE_WORDS;\n\nconst UploadItemContext = createContext<{ name: string; state: string; locale: string | undefined } | null>(null);\n\nfunction useUploadItem(part: string): { name: string; state: string; locale: string | undefined } {\n  const context = use(UploadItemContext);\n  if (!context) throw new Error(`<${part}> must be used inside <UploadItem>.`);\n  return context;\n}\n\n/** The list of files chosen. Name it with `aria-label` (\"Files being added\"). */\nexport function UploadList({ className, ...props }: ComponentProps<\"ul\">) {\n  return <ul data-slot=\"upload-list\" className={cn(\"flex w-full min-w-0 flex-col gap-2\", className)} {...props} />;\n}\n\nexport type UploadItemProps = Omit<ComponentProps<\"li\">, \"children\"> & {\n  /** The element the row is. \"li\" (default) inside an UploadList; \"div\" where the row is not an item of a list of its own (inside another list's row, or alone). */\n  as?: \"li\" | \"div\";\n  /** The file's name. */\n  name: string;\n  /** Its size in bytes. */\n  size?: number;\n  /** One of the five upload states, or a state of the project's own (\"checking\", \"published\"): give that one a `stateLabel`. */\n  state: UploadState | (string & {});\n  /** The word for each state, to translate or reword. Defaults: Waiting, Uploading, Paused, Uploaded, Failed. */\n  stateLabels?: Partial<Record<UploadState, string>>;\n  /** The word for this row's state, whatever it is: it replaces the one from `stateLabels`. Needed for a state of the project's own. */\n  stateLabel?: string;\n  /** How this row's state reads. Default: by the state (\"done\" is success, \"failed\" is destructive, anything else neutral). */\n  stateTone?: UploadTone;\n  /** The mark beside the word, in place of the one the state or the tone gives (an icon, `aria-hidden`). */\n  stateIcon?: ReactNode;\n  /** More about the state, after its word: why it failed, what is left. */\n  detail?: ReactNode;\n  /** A small picture of the file. Without one, a file mark is shown. */\n  thumbnail?: ReactNode;\n  /** For the size and the percentage. Default: the browser's. */\n  locale?: string;\n  /** Say \"name: Uploaded\" or \"name: Failed\" to screen readers when the row reaches that state (or a state of the project's own whose tone is success or destructive). Default true. */\n  announceChanges?: boolean;\n  /** UploadProgress and UploadActions. */\n  children?: ReactNode;\n};\n\n/**\n * One file: a picture or mark, its name, its state in words with a mark (never colour alone), its size,\n * then its progress and its buttons. Reaching \"done\" or \"failed\" is announced once; progress on the way is\n * not, because a screen reader would read every step. The state may be one of the project's own, with the\n * word and the tone it gives.\n */\nexport function UploadItem({ as = \"li\", name, size, state, stateLabels, stateLabel, stateTone, stateIcon, detail, thumbnail, locale, announceChanges = true, className, children, ...props }: UploadItemProps) {\n  // One set of props for either element: a list item and a div take the same attributes here.\n  const Row = as as \"div\";\n  const known = isUploadState(state);\n  const word = stateLabel ?? (known ? (stateLabels?.[state] ?? STATE_WORDS[state]) : state);\n  const tone = stateTone ?? (known ? STATE_TONES[state] : \"neutral\");\n  // A known state keeps its own mark unless the project gives it another tone.\n  const Mark = known && stateTone === undefined ? STATE_ICONS[state] : TONE_ICONS[tone];\n  const final = known ? state === \"done\" || state === \"failed\" : tone === \"success\" || tone === \"destructive\";\n  const previous = useRef(state);\n  useEffect(() => {\n    if (previous.current === state) return;\n    previous.current = state;\n    if (announceChanges && final) announce(`${name}: ${word}`);\n  }, [state, name, word, announceChanges, final]);\n\n  return (\n    <UploadItemContext value={{ name, state, locale }}>\n      <Row\n        data-slot=\"upload-item\"\n        data-state={state}\n        data-tone={tone}\n        className={cn(\"grid min-w-0 grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-x-3 gap-y-1.5 rounded-control border bg-card p-3 text-sm data-[tone=destructive]:border-destructive\", className)}\n        {...(props as ComponentProps<\"div\">)}\n      >\n        <span\n          data-slot=\"upload-thumbnail\"\n          aria-hidden={thumbnail ? undefined : \"true\"}\n          className=\"row-span-2 flex size-10 shrink-0 items-center justify-center self-start overflow-hidden rounded-control bg-muted text-muted-foreground [&_img]:size-full [&_img]:object-cover [&_svg]:size-4\"\n        >\n          {thumbnail ?? <FileIcon aria-hidden=\"true\" strokeWidth={1.5} />}\n        </span>\n        <div className=\"col-start-2 min-w-0\">\n          <p data-slot=\"upload-name\" className=\"truncate font-medium\">\n            {/* Isolated: a name in another script keeps its own direction without moving the row. */}\n            <bdi>{name}</bdi>\n          </p>\n          <p className=\"flex flex-wrap items-center gap-x-1.5 text-xs text-muted-foreground\">\n            <span data-slot=\"upload-state\" className={cn(\"inline-flex items-center gap-1 [&_svg]:size-3.5 [&_svg]:shrink-0\", TONE_CLASSES[tone])}>\n              {stateIcon ?? <Mark aria-hidden=\"true\" strokeWidth={1.5} />}\n              {word}\n            </span>\n            {detail ? <span data-slot=\"upload-detail\">{detail}</span> : null}\n            {size !== undefined ? <bdi data-slot=\"upload-size\">{formatFileSize(size, locale)}</bdi> : null}\n          </p>\n        </div>\n        {children}\n      </Row>\n    </UploadItemContext>\n  );\n}\n\nexport type UploadProgressProps = Omit<ComponentProps<typeof Progress>, \"value\" | \"max\"> & {\n  /** How much has been sent, from 0 to 100. A paused or failed resumable upload keeps the value it reached. */\n  value: number;\n};\n\n/**\n * The row's bar, with the percentage beside it in figures. The bar is named after the file and says the\n * percentage, so a screen reader can ask for it; it is not a live region.\n */\nexport function UploadProgress({ value, className, \"aria-label\": ariaLabel, ...props }: UploadProgressProps) {\n  const { name, locale } = useUploadItem(\"UploadProgress\");\n  const percent = new Intl.NumberFormat(locale, { style: \"percent\", maximumFractionDigits: 0 }).format(Math.min(100, Math.max(0, value)) / 100);\n  return (\n    <div data-slot=\"upload-progress\" className={cn(\"col-start-2 row-start-2 flex min-w-0 items-center gap-2\", className)}>\n      <Progress size=\"sm\" value={Math.min(100, Math.max(0, value))} max={100} aria-label={ariaLabel ?? name} getValueLabel={() => percent} {...props} />\n      <span aria-hidden=\"true\" className=\"w-10 shrink-0 text-end text-xs text-muted-foreground tabular-nums\">\n        {percent}\n      </span>\n    </div>\n  );\n}\n\n/** Holds the row's buttons at its end. */\nexport function UploadActions({ className, ...props }: ComponentProps<\"div\">) {\n  return <div data-slot=\"upload-actions\" className={cn(\"col-start-3 row-span-2 row-start-1 flex shrink-0 items-center self-center\", className)} {...props} />;\n}\n\nexport type UploadActionProps = Omit<ComponentProps<\"button\">, \"type\"> & {\n  /** The verb, joined to the file's name for the button's accessible name (\"Pause: plan.pdf\"). An `aria-label` replaces the whole name. */\n  label?: string;\n};\n\nfunction UploadAction({ label, className, children, \"aria-label\": ariaLabel, ...props }: UploadActionProps & { label: string }) {\n  const { name } = useUploadItem(\"UploadAction\");\n  return (\n    <button\n      type=\"button\"\n      aria-label={ariaLabel ?? `${label}: ${name}`}\n      className={cn(\n        \"inline-flex size-8 shrink-0 items-center justify-center rounded-control text-muted-foreground transition-[background-color,color] duration-instant ease-out hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none pointer-coarse:size-10 [&_svg]:size-4\",\n        className,\n      )}\n      {...props}\n    >\n      {children}\n    </button>\n  );\n}\n\n/** Pauses a resumable upload. The project decides what pausing means; the row keeps its progress. */\nexport function UploadPause({ label = \"Pause\", children, ...props }: UploadActionProps) {\n  return (\n    <UploadAction data-slot=\"upload-pause\" label={label} {...props}>\n      {children ?? <Pause aria-hidden=\"true\" strokeWidth={1.5} />}\n    </UploadAction>\n  );\n}\n\n/** Carries on a paused upload from where it stopped. */\nexport function UploadResume({ label = \"Resume\", children, ...props }: UploadActionProps) {\n  return (\n    <UploadAction data-slot=\"upload-resume\" label={label} {...props}>\n      {children ?? <Play aria-hidden=\"true\" strokeWidth={1.5} />}\n    </UploadAction>\n  );\n}\n\n/** Tries a failed upload again. */\nexport function UploadRetry({ label = \"Try again\", children, ...props }: UploadActionProps) {\n  return (\n    <UploadAction data-slot=\"upload-retry\" label={label} {...props}>\n      {children ?? <RotateCw aria-hidden=\"true\" strokeWidth={1.5} />}\n    </UploadAction>\n  );\n}\n\n/** Takes the file off the list, cancelling it if it is on its way. Move focus to a neighbouring row or to the dropzone's button afterwards. */\nexport function UploadRemove({ label = \"Remove\", children, ...props }: UploadActionProps) {\n  return (\n    <UploadAction data-slot=\"upload-remove\" label={label} {...props}>\n      {children ?? <X aria-hidden=\"true\" strokeWidth={1.5} />}\n    </UploadAction>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "ui",
    "when": "Adding pictures, documents or other files where progress matters: a listing's photos, attachments, an import. It contains no upload engine: the project uploads (plain, or resumable such as tus) and tells each row its state and progress. For one small file in a form, an input with type=\"file\" is enough. Name the dropzone with `aria-label` or `aria-labelledby`, and word rejected files yourself from the reason given to `onReject`.",
    "example": "<Dropzone accept=\"image/*\" maxSize={10_000_000} onFiles={start} onReject={explain} aria-label=\"Add pictures\">\n  <DropzoneHint>Drop pictures here, or</DropzoneHint>\n  <DropzoneButton>Choose pictures</DropzoneButton>\n</Dropzone>\n<UploadList aria-label=\"Pictures being added\">\n  {uploads.map((upload) => (\n    <UploadItem key={upload.id} name={upload.file.name} size={upload.file.size} state={upload.state}>\n      <UploadProgress value={upload.percent} />\n      <UploadActions>\n        {upload.state === \"uploading\" ? <UploadPause onClick={() => pause(upload.id)} /> : null}\n        {upload.state === \"paused\" ? <UploadResume onClick={() => resume(upload.id)} /> : null}\n        {upload.state === \"failed\" ? <UploadRetry onClick={() => retry(upload.id)} /> : null}\n        <UploadRemove onClick={() => remove(upload.id)} />\n      </UploadActions>\n    </UploadItem>\n  ))}\n</UploadList>\n\n// A state of the project's own, with its word and tone; and a row that is not a list item\n<UploadItem as=\"div\" name=\"walk.mp4\" state=\"checking\" stateLabel=\"Being checked\" stateTone=\"warning\" />",
    "client": true
  }
}
