{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "file-input",
  "title": "File input",
  "description": "Files picked, dropped or pasted, on ui-sdk's File input, checked for their type, size and count, and listed with their upload progress. Given an upload function, each file uploads as it's added, with cancel and retry, the form sends what the uploads gave back, and a submit waits for them; without one, the files themselves go with the form. Saved files open an edit form. The drop target answers a dragged file before it lands, the files turned away are listed with why, a status bar carries the batch, a row that arrives rises into place, and one that leaves fades while the rows below close its gap. A box the height of a text field fits a form where a file is one answer among others.",
  "dependencies": [
    "@ui-sdk/react",
    "@ui-sdk/core",
    "class-variance-authority"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/icon-tile.json",
    "https://kinoui.com/r/alert.json",
    "https://kinoui.com/r/button.json",
    "https://kinoui.com/r/collapsible.json",
    "https://kinoui.com/r/empty.json",
    "https://kinoui.com/r/input.json",
    "https://kinoui.com/r/progress.json",
    "https://kinoui.com/r/dates.json",
    "https://kinoui.com/r/announce.json",
    "https://kinoui.com/r/field-control.json",
    "https://kinoui.com/r/flow.json",
    "https://kinoui.com/r/number-format.json",
    "https://kinoui.com/r/refs.json",
    "https://kinoui.com/r/resize.json",
    "https://kinoui.com/r/swap.json",
    "https://kinoui.com/r/uploads.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/components/kino/file-input.tsx",
      "content": "'use client'\n\nimport { Alert, AlertDescription, AlertTitle } from '@/registry/components/kino/alert'\nimport { Button, buttonVariants } from '@/registry/components/kino/button'\nimport { Collapsible, CollapsiblePanel } from '@/registry/components/kino/collapsible'\nimport { emptyVariants } from '@/registry/components/kino/empty'\nimport { IconTile } from '@/registry/components/kino/icon-tile'\nimport { InputInvalidIcon, inputBoxClassName } from '@/registry/components/kino/input'\nimport { Progress } from '@/registry/components/kino/progress'\nimport { IconPlaceholder } from '@/registry/icons/icon-placeholder'\nimport { announce } from '@/registry/lib/announce'\nimport { useLocale } from '@/registry/lib/dates'\nimport { FieldValues } from '@/registry/lib/field-control'\nimport { useFlow } from '@/registry/lib/flow'\nimport { formatFileSize } from '@/registry/lib/number-format'\nimport { markMounted, mergeRefs } from '@/registry/lib/refs'\nimport { transitionsSettled } from '@/registry/lib/resize'\nimport { Swap, SwapText } from '@/registry/lib/swap'\nimport {\n  rowProgress,\n  type SavedFile,\n  savedFileOf,\n  settledAnnouncement,\n  type Upload,\n  type UploadFile,\n  type UploadOptions,\n  type UploadSummary,\n  useUploads,\n} from '@/registry/lib/uploads'\nimport { useFieldControl } from '@ui-sdk/react/field'\nimport {\n  createFileInputController,\n  type FileInputController,\n  FileInputDropzone as FileInputDropzonePrimitive,\n  type FileInputDropzoneState as DropzoneState,\n  FileInputItem as FileInputItemPrimitive,\n  FileInputItemRemove as FileInputItemRemovePrimitive,\n  FileInputList as FileInputListPrimitive,\n  FileInput as FileInputPrimitive,\n  FileInputTrigger as FileInputTriggerPrimitive,\n  type FileInputValueChangeDetails,\n  type FileRejection,\n  type FileRejectionReason,\n  type FileRules,\n} from '@ui-sdk/react/file-input'\nimport type { VariantProps } from 'class-variance-authority'\nimport {\n  type ComponentProps,\n  createContext,\n  type MouseEvent,\n  type ReactNode,\n  type Ref,\n  use,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n  useSyncExternalStore,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * Files picked, dropped or pasted, on ui-sdk's File input: it checks them\n * against `accept`, the sizes and the count, takes drops and pastes, says\n * what was added, removed or turned away, and submits them through its own\n * native input. Kino adds the look, the uploads (`registry/lib/uploads`)\n * with their status, the warning for files turned away, and the motion: a\n * row that arrives rises into place, and one that leaves fades where it was\n * while the rows below close its gap (`useFlow`).\n *\n * Files come in through a drop target: `FileInputDropzone`, an area of its\n * own in the Empty state's outlined look, or `FileInputBox`, a box the size\n * of a text field for a form where a file is one answer among others.\n */\n\n/** The same file picked twice: same name, size and time it was last changed. */\nfunction sameFile(a: File, b: File) {\n  return a.name === b.name && a.size === b.size && a.lastModified === b.lastModified\n}\n\nconst TYPE_NAMES: Record<string, string> = {\n  'image/*': 'images',\n  'video/*': 'videos',\n  'audio/*': 'audio',\n  'text/*': 'text files',\n  'application/pdf': 'PDF',\n  'image/jpeg': 'JPG',\n  'image/svg+xml': 'SVG',\n  'image/webp': 'WebP',\n  'text/plain': 'TXT',\n  'text/csv': 'CSV',\n  'application/zip': 'ZIP',\n}\n\n/** The names of the types `accept` takes, deduplicated: `image/jpeg,.jpg` is one JPG. */\nfunction typeNames(accept: FileRules['accept']): string[] {\n  const rules = typeof accept === 'string' ? accept.split(',') : (accept ?? [])\n  const names = rules\n    .map((rule) => rule.trim().toLowerCase())\n    .filter(Boolean)\n    .map((rule) => {\n      if (TYPE_NAMES[rule]) return TYPE_NAMES[rule]\n      if (rule.startsWith('.'))\n        return rule === '.jpeg' ? 'JPG' : rule.slice(1).toUpperCase()\n      const subtype = rule.split('/')[1] ?? rule\n      return subtype.split(/[.+-]/).pop()!.toUpperCase()\n    })\n  return [...new Set(names)]\n}\n\n/** “PDF, PNG or SVG”: the types `accept` takes, as a list a person reads. */\nfunction typesText(accept: FileRules['accept'], locale?: string) {\n  const names = typeNames(accept)\n  if (names.length === 0) return ''\n  return new Intl.ListFormat(locale, { type: 'disjunction' }).format(names)\n}\n\nfunction capitalize(text: string) {\n  return text.charAt(0).toUpperCase() + text.slice(1)\n}\n\n/** Whether these rules hold one file at most. */\nfunction holdsOne({ multiple, maxFiles }: FileRules) {\n  return !multiple || maxFiles === 1\n}\n\n/** The limits, stated up front: “PDF, PNG or SVG, up to 50 MB each, 20 files at most”. */\nfunction limitsText(rules: FileRules, locale?: string) {\n  const { accept, maxSize, maxFiles } = rules\n  const one = holdsOne(rules)\n  return capitalize(\n    [\n      typesText(accept, locale),\n      maxSize === undefined\n        ? ''\n        : `up to ${formatFileSize(maxSize, locale)}${one ? '' : ' each'}`,\n      maxFiles === undefined || one ? '' : `${maxFiles} files at most`,\n    ]\n      .filter(Boolean)\n      .join(', '),\n  )\n}\n\n/**\n * Why a file wasn't added, in a few words, from the first of its reasons:\n * ui-sdk's, `duplicate` from the File input's own check, or a reason a\n * `validate` gave, which reads as it is.\n */\nfunction rejectionText(rejection: FileRejection, rules: FileRules, locale?: string) {\n  const [reason] = rejection.reasons\n  switch (reason) {\n    case 'file-type': {\n      const types = typesText(rules.accept, locale)\n      return types ? `Only ${types}` : 'This type isn’t taken'\n    }\n    case 'file-too-large':\n      return rules.maxSize === undefined\n        ? 'Too large'\n        : `${formatFileSize(rejection.file.size, locale)}, over ${formatFileSize(rules.maxSize, locale)}`\n    case 'file-too-small':\n      return rules.minSize === undefined\n        ? 'Too small'\n        : `${formatFileSize(rejection.file.size, locale)}, under ${formatFileSize(rules.minSize, locale)}`\n    case 'duplicate':\n      return 'Already in the list'\n    case 'too-many-files':\n      if (holdsOne(rules)) return 'Only one file goes here'\n      return rules.maxFiles === undefined\n        ? 'Too many files'\n        : `Over the ${rules.maxFiles}-file limit`\n    default:\n      return reason ?? ''\n  }\n}\n\n/** The title of the files turned away: “brief.key wasn’t added”, or “3 files weren’t added”. */\nfunction rejectedTitle(rejected: readonly FileRejection[]) {\n  if (rejected.length === 1) return `${rejected[0].file.name} wasn’t added`\n  return `${rejected.length} files weren’t added`\n}\n\n/** The batch's line while it runs: “2 of 5 uploaded, 12 of 20 MB”. */\nfunction progressText(summary: UploadSummary, locale?: string) {\n  return `${summary.done} of ${summary.count} uploaded, ${formatFileSize(summary.loaded, locale)} of ${formatFileSize(summary.total, locale)}`\n}\n\n/** The batch's line once nothing is left uploading: “5 files uploaded, 20 MB”, or what failed. */\nfunction settledText(summary: UploadSummary, locale?: string) {\n  const files = (count: number) => (count === 1 ? '1 file' : `${count} files`)\n  if (summary.failed === 0)\n    return `${files(summary.done)} uploaded, ${formatFileSize(summary.total, locale)}`\n  if (summary.done === 0)\n    return summary.failed === 1 ? 'The upload failed' : `${files(summary.failed)} failed`\n  return `${summary.done} uploaded, ${summary.failed} failed`\n}\n\n/** The line for files that go with the form: “3 files, 4.2 MB”. */\nfunction heldText(summary: UploadSummary, locale?: string) {\n  const files = summary.count === 1 ? '1 file' : `${summary.count} files`\n  return `${files}, ${formatFileSize(summary.total, locale)}`\n}\n\n/** The field's error while files that failed hold its form back. */\nfunction failedMessage(failed: number) {\n  return failed === 1\n    ? '1 file couldn’t be uploaded. Retry it or remove it.'\n    : `${failed} files couldn’t be uploaded. Retry them or remove them.`\n}\n\n/** What is said while a submit waits for the uploads. */\nfunction waitingText(active: number) {\n  return active === 1\n    ? 'Sending once the last file is up'\n    : `Sending once ${active} files are up`\n}\n\n/** What the status says: the batch going up, how it went, or the files that go with the form. */\ntype StatusState = 'empty' | 'held' | 'uploading' | 'waiting' | 'failed' | 'done'\n\nfunction statusState(\n  summary: UploadSummary,\n  uploading: boolean,\n  waiting: boolean,\n): StatusState {\n  if (summary.count === 0) return 'empty'\n  if (summary.active > 0) return waiting ? 'waiting' : 'uploading'\n  if (!uploading || summary.done + summary.failed < summary.count) return 'held'\n  return summary.failed > 0 ? 'failed' : 'done'\n}\n\nconst fileKeys = new WeakMap<File, string>()\nlet fileCount = 0\n\n/** A key that stays with a `File` object for as long as it lives. */\nfunction fileKey(file: File) {\n  let key = fileKeys.get(file)\n  if (!key) {\n    fileCount += 1\n    key = `file-${fileCount}`\n    fileKeys.set(file, key)\n  }\n  return key\n}\n\ninterface FileInputContextValue {\n  files: readonly File[]\n  /** The rules it checks files by, for the words that state them. */\n  rules: FileRules\n  /** Whether files upload as they're added, rather than going with the form. */\n  uploading: boolean\n  /** Each file's upload. */\n  uploads: ReadonlyMap<File, Upload>\n  summary: UploadSummary\n  retry: (file: File) => void\n  retryFailed: () => void\n  /** Cancels every upload still waiting or going up, and takes those files out. */\n  cancelActive: () => void\n  /** A submit is waiting for the uploads, and goes once they are up. */\n  waiting: boolean\n  /** What the last pick, drop or paste turned away. */\n  rejected: readonly FileRejection[]\n  dismissRejected: () => void\n  disabled: boolean\n  locale: string\n  controller: FileInputController\n  /** Opens the picker from a press on a drop target, unless it landed on a control of its own. */\n  openPicker: (event: MouseEvent<HTMLElement>) => void\n}\n\nconst FileInputContext = createContext<FileInputContextValue | null>(null)\n\nfunction useFileInput() {\n  const context = use(FileInputContext)\n  if (!context) throw new Error('File input parts go inside a FileInput.')\n  return context\n}\n\ntype FileInputProps = Omit<\n  ComponentProps<typeof FileInputPrimitive>,\n  'className' | 'defaultValue'\n> & {\n  className?: string\n  /** The files it starts with, and goes back to on a form's reset. A saved file, `{ value, name, size }`, shows as uploaded and never uploads. */\n  defaultValue?: (File | SavedFile)[]\n  /**\n   * Sends each file as it's added, calling `onProgress` with the bytes\n   * sent, and resolves with what the form sends for it, such as its id;\n   * a thrown `Error`'s message shows on its row. A submit waits for the\n   * uploads. Left out, the files themselves go with the form.\n   */\n  upload?: UploadFile\n  /** How many files upload at once. */\n  concurrency?: number\n  /** Formats the files' sizes; the browser's language when left out. */\n  locale?: string\n}\n\n/** The reasons a change of files is a pick, a drop or a paste, which say again what was turned away. */\nconst ARRIVALS = new Set(['picker', 'drop', 'paste'])\n\n/**\n * Holds the files, on ui-sdk's File input. A file pasted anywhere inside it,\n * such as on its button, is added as a picked one is, and a file that is\n * already in the list is turned away as `duplicate`.\n */\nfunction FileInput({\n  value,\n  defaultValue,\n  onValueChange,\n  onReject,\n  validate,\n  upload,\n  concurrency,\n  accept,\n  maxSize,\n  minSize,\n  maxFiles,\n  multiple = false,\n  name,\n  disabled: disabledProp = false,\n  locale: localeProp,\n  controller: controllerProp,\n  className,\n  onPaste,\n  children,\n  ref,\n  ...props\n}: FileInputProps) {\n  // The server writes sizes in en-US, then the visitor's own once the page has loaded.\n  const locale = useLocale(localeProp)\n  const field = useFieldControl()\n  const disabled = disabledProp || field?.disabled === true\n  // A saved file stands in the list as a File that holds no bytes.\n  const [defaults] = useState(() =>\n    (defaultValue ?? []).map((entry) =>\n      entry instanceof File ? entry : savedFileOf(entry),\n    ),\n  )\n  const [own, setOwn] = useState<File[]>(defaults)\n  const files = value ?? own\n  const [ownController] = useState(createFileInputController)\n  const controller = controllerProp ?? ownController\n  const rootRef = useRef<HTMLDivElement>(null)\n  const refs = useMemo(() => mergeRefs(rootRef, ref), [ref])\n  // The last change put a file in another's place.\n  const [swapping, setSwapping] = useState(false)\n  const [rejected, setRejected] = useState<FileRejection[]>([])\n  const [waiting, setWaiting] = useState<{ submitter: HTMLElement | null } | null>(null)\n  const rules: FileRules = { accept, maxSize, minSize, maxFiles, multiple }\n  const uploads = useUploads({ files, upload, concurrency })\n  const { summary } = uploads\n  // A batch ended by a cancel isn't told as one that went up.\n  const [cancelled, setCancelled] = useState(false)\n\n  // The files held now, ahead of the render: two picks in one go each check against the last.\n  const held = useRef(files)\n  // Only a render's new files: an effect that runs again on the same render, as Strict Mode's does, would put back files older than a pick's.\n  const rendered = useRef(files)\n  useLayoutEffect(() => {\n    if (rendered.current === files) return\n    rendered.current = files\n    held.current = files\n  })\n\n  const change = (next: File[], details: FileInputValueChangeDetails) => {\n    onValueChange?.(next, details)\n    if (details.canceled) return\n    held.current = next\n    if (value === undefined) setOwn(next)\n    setSwapping(details.added.length > 0 && details.removed.length > 0)\n    setCancelled(\n      details.added.length === 0 &&\n        details.removed.some((file) => uploads.active.includes(file)),\n    )\n    // What this pick turned away, or nothing once a pick adds them all.\n    if (ARRIVALS.has(details.reason)) setRejected(details.rejected)\n    if (details.reason === 'reset') setRejected([])\n  }\n\n  const cancelActive = () => {\n    const active = uploads.active\n    if (disabled || active.length === 0) return\n    setWaiting(null)\n    controller.setValue(files.filter((file) => !active.includes(file)))\n  }\n\n  /** The native input ui-sdk keeps the files in, which the form checks. */\n  const control = () =>\n    rootRef.current?.querySelector<HTMLInputElement>(':scope > input[type=file]') ?? null\n\n  // A file that failed to upload holds the form back, as an invalid field\n  // does; the Field reads the input's message again whenever it changes.\n  const failure = summary.failed > 0 ? failedMessage(summary.failed) : ''\n  useLayoutEffect(() => {\n    const input = control()\n    if (!input) return\n    const message = disabled ? '' : failure\n    if (input.validationMessage === message) return\n    input.setCustomValidity(message)\n    input.dispatchEvent(new Event('input', { bubbles: true }))\n  }, [failure, disabled])\n\n  // A submit that comes while files go up waits for them, then goes again;\n  // then the field's check stops it if one failed.\n  const latest = useRef(summary)\n  useLayoutEffect(() => {\n    latest.current = summary\n  })\n  useEffect(() => {\n    const form = rootRef.current?.closest('form')\n    if (!form || !upload) return\n    const onSubmit = (event: SubmitEvent) => {\n      const now = latest.current\n      if (now.active === 0) return\n      const own = control()\n      // A form that fails elsewhere goes on to say so; the wait is for one that's ready.\n      const others = [...form.elements].filter(\n        (element): element is HTMLInputElement =>\n          'validity' in element && element !== own,\n      )\n      if (others.some((element) => !element.validity.valid)) return\n      event.preventDefault()\n      event.stopImmediatePropagation()\n      setWaiting({ submitter: event.submitter })\n      announce(waitingText(now.active))\n    }\n    form.addEventListener('submit', onSubmit, { capture: true })\n    return () => form.removeEventListener('submit', onSubmit, { capture: true })\n  }, [upload])\n  const resumed = useRef<typeof waiting>(null)\n  useEffect(() => {\n    if (!waiting || summary.active > 0 || resumed.current === waiting) return\n    resumed.current = waiting\n    // The uploads ending, from outside React, ends the wait: once this commit is done.\n    queueMicrotask(() => {\n      setWaiting(null)\n      const form = rootRef.current?.closest('form')\n      const { submitter } = waiting\n      form?.requestSubmit(submitter && form.contains(submitter) ? submitter : undefined)\n    })\n  }, [waiting, summary])\n\n  const wasActive = useRef(summary.active > 0)\n  useEffect(() => {\n    if (wasActive.current && summary.active === 0 && !cancelled)\n      announce(settledAnnouncement(summary))\n    wasActive.current = summary.active > 0\n  })\n\n  const openPicker = (event: MouseEvent<HTMLElement>) => {\n    if (disabled || event.defaultPrevented) return\n    const target = event.target as HTMLElement\n    if (target.closest('button, a, input, label, select, textarea, [role=listitem], li'))\n      return\n    controller.open()\n  }\n\n  return (\n    <FileInputContext\n      value={{\n        files,\n        rules,\n        uploading: upload !== undefined,\n        uploads: uploads.uploads,\n        summary,\n        retry: uploads.retry,\n        retryFailed: uploads.retryFailed,\n        cancelActive,\n        waiting: waiting !== null,\n        rejected,\n        dismissRejected: () => setRejected([]),\n        disabled,\n        locale,\n        controller,\n        openPicker,\n      }}\n    >\n      <FileInputPrimitive\n        {...props}\n        ref={refs}\n        value={value}\n        // A form's reset goes back to the defaults; one held with none keeps its files, as ui-sdk's do.\n        defaultValue={defaultValue === undefined ? undefined : defaults}\n        onValueChange={change}\n        onReject={(turnedAway, details) => {\n          setRejected(turnedAway)\n          onReject?.(turnedAway, details)\n        }}\n        validate={(file, batch) => {\n          if (\n            multiple &&\n            (held.current.some((each) => sameFile(each, file)) ||\n              batch.accepted.some((taken) => sameFile(taken, file)))\n          )\n            return 'duplicate'\n          return validate?.(file, batch)\n        }}\n        accept={accept}\n        maxSize={maxSize}\n        minSize={minSize}\n        maxFiles={maxFiles}\n        multiple={multiple}\n        // Files that upload send what each upload resolved with instead, so\n        // the native input sends nothing; an empty name keeps the Field's.\n        name={upload ? '' : name}\n        disabled={disabled}\n        controller={controller}\n        data-swapping={swapping || undefined}\n        onPaste={(event) => {\n          onPaste?.(event)\n          const pasted = [...event.clipboardData.files]\n          if (event.defaultPrevented || pasted.length === 0) return\n          event.preventDefault()\n          controller.addFiles(pasted, { reason: 'paste', event: event.nativeEvent })\n        }}\n        className={cn('group/file-input flex min-w-0 flex-col gap-3', className)}\n      >\n        {(state) => (\n          <>\n            {typeof children === 'function' ? children(state) : children}\n            {upload ? (\n              // A disabled field sends nothing, as a disabled input doesn't.\n              <FieldValues\n                name={disabled ? undefined : (name ?? field?.name)}\n                values={uploads.values}\n                many={!holdsOne(rules)}\n              />\n            ) : null}\n          </>\n        )}\n      </FileInputPrimitive>\n    </FileInputContext>\n  )\n}\n\ntype FileInputTriggerProps = Omit<\n  ComponentProps<typeof FileInputTriggerPrimitive>,\n  'className'\n> & {\n  className?: string\n} & VariantProps<typeof buttonVariants>\n\n/**\n * The way in by keyboard and pointer: ui-sdk's trigger, in a Kino Button's\n * look, which opens the browser's file picker. In a Field, the Field's label\n * and its own text name it (\"Receipts, Choose files\").\n */\n/** Each look's own edge, which an invalid Button would turn red. */\nconst keptBorder = {\n  default:\n    'in-data-[slot=file-input-dropzone]:aria-invalid:not-focus-visible:border-transparent',\n  outline:\n    'in-data-[slot=file-input-dropzone]:aria-invalid:not-focus-visible:border-border dark:in-data-[slot=file-input-dropzone]:aria-invalid:not-focus-visible:border-input',\n  secondary:\n    'in-data-[slot=file-input-dropzone]:aria-invalid:not-focus-visible:border-transparent',\n  ghost:\n    'in-data-[slot=file-input-dropzone]:aria-invalid:not-focus-visible:border-transparent',\n  destructive:\n    'in-data-[slot=file-input-dropzone]:aria-invalid:not-focus-visible:border-transparent',\n  link: 'in-data-[slot=file-input-dropzone]:aria-invalid:not-focus-visible:border-transparent',\n} satisfies Record<NonNullable<FileInputTriggerProps['variant']>, string>\n\nfunction FileInputTrigger({\n  className,\n  variant = 'outline',\n  size = 'default',\n  ...props\n}: FileInputTriggerProps) {\n  return (\n    <FileInputTriggerPrimitive\n      {...props}\n      className={cn(\n        buttonVariants({ variant, size }),\n        // In a box, the box's ring shows the focus, as a text field's does,\n        // and a disabled box or zone fades once, not twice.\n        'in-data-file-input-box:focus-visible:border-transparent in-data-file-input-box:focus-visible:ring-0 in-data-file-input-box:data-disabled:opacity-100 in-data-[slot=file-input-dropzone]:data-disabled:opacity-100',\n        // It is the Field's control, so it says it's invalid; the zone or box around it shows it, once.\n        'in-data-[slot=file-input-dropzone]:aria-invalid:not-focus-visible:ring-0',\n        keptBorder[variant ?? 'default'],\n        className,\n      )}\n    />\n  )\n}\n\ninterface PageDrag {\n  /** A file is being dragged somewhere over the page. */\n  dragging: boolean\n  /** How many files it carries; 0 when the browser doesn't say. */\n  count: number\n}\n\n/*\n * Whether a file is being dragged over the page, and how many, shared by\n * every drop target on it: one listener on the window while any is mounted.\n * It is for the look only: ui-sdk takes the drop, and stops one that lands\n * outside every drop target from opening the file in place of the page.\n */\nconst pageDrag = {\n  depth: 0,\n  state: { dragging: false, count: 0 } as PageDrag,\n  listeners: new Set<() => void>(),\n}\n\nfunction hasFiles(event: globalThis.DragEvent) {\n  return event.dataTransfer?.types.includes('Files') ?? false\n}\n\nfunction setPageDrag(state: PageDrag) {\n  if (pageDrag.state.dragging === state.dragging && pageDrag.state.count === state.count)\n    return\n  pageDrag.state = state\n  for (const listener of pageDrag.listeners) listener()\n}\n\nfunction onPageDragEnter(event: globalThis.DragEvent) {\n  if (!hasFiles(event)) return\n  pageDrag.depth += 1\n  const items = [...(event.dataTransfer?.items ?? [])]\n  setPageDrag({\n    dragging: true,\n    count: items.filter((item) => item.kind === 'file').length,\n  })\n}\n\nfunction onPageDragLeave(event: globalThis.DragEvent) {\n  if (!hasFiles(event)) return\n  pageDrag.depth = Math.max(0, pageDrag.depth - 1)\n  // Leaving the window has no element to go to.\n  if (pageDrag.depth === 0 || event.relatedTarget === null) onPageDragEnd()\n}\n\nfunction onPageDragEnd() {\n  pageDrag.depth = 0\n  setPageDrag({ dragging: false, count: 0 })\n}\n\nconst pageEvents = [\n  ['dragenter', onPageDragEnter],\n  ['dragleave', onPageDragLeave],\n  ['drop', onPageDragEnd],\n  ['dragend', onPageDragEnd],\n] as const\n\nfunction subscribePageDrag(listener: () => void) {\n  if (pageDrag.listeners.size === 0) {\n    for (const [type, handler] of pageEvents)\n      window.addEventListener(type, handler, { capture: true })\n  }\n  pageDrag.listeners.add(listener)\n  return () => {\n    pageDrag.listeners.delete(listener)\n    if (pageDrag.listeners.size > 0) return\n    for (const [type, handler] of pageEvents)\n      window.removeEventListener(type, handler, { capture: true })\n    pageDrag.depth = 0\n    pageDrag.state = { dragging: false, count: 0 }\n  }\n}\n\nconst notDragging: PageDrag = { dragging: false, count: 0 }\n\nfunction usePageDrag() {\n  return useSyncExternalStore(\n    subscribePageDrag,\n    () => pageDrag.state,\n    () => notDragging,\n  )\n}\n\n/** A drop target's state: ui-sdk's, with how many files the drag carries. */\ntype FileInputDropzoneState = DropzoneState & {\n  /** How many files are being dragged; 0 when the browser doesn't say. */\n  count: number\n}\n\n/**\n * The files, one row each, from `children`: a function that takes a file and\n * returns its `FileInputItem`. A row that arrives rises into place, and one\n * that leaves fades where it was while the rest close its gap. The list is\n * one tab stop: the arrow keys move between rows, and Delete removes one.\n */\nfunction FileInputList({\n  className,\n  children,\n  ...props\n}: Omit<ComponentProps<typeof FileInputListPrimitive>, 'className' | 'children'> & {\n  className?: string\n  children: (file: File, index: number) => ReactNode\n}) {\n  const { files } = useFileInput()\n  const { frame: frameRef, row: listRef } = useFlow<HTMLDivElement, HTMLUListElement>(\n    'li',\n  )\n  useEffect(() => markMounted(listRef.current), [listRef])\n  return (\n    <div\n      ref={frameRef}\n      data-slot='file-input-list-frame'\n      // Its rows' rings show past its edges as it changes height. It is\n      // never hidden: the root's gap above it is taken back here (`-mt-4`)\n      // and given again inside the height that moves, while it holds a row.\n      className='-m-1 -mt-4 overflow-clip p-1 transition-[height] duration-(--motion-layout-duration) ease-(--motion-layout-easing) motion-reduce:transition-none'\n    >\n      <FileInputListPrimitive\n        {...props}\n        className={cn(\n          'group/file-input-list relative isolate flex flex-col gap-2 has-[>li:not([data-leaving])]:pt-3',\n          className,\n        )}\n        // ui-sdk types a part's ref by its default tag; this one is the list element.\n        ref={listRef as unknown as Ref<HTMLDivElement>}\n        // Each row is what `children` makes of its file, in a list element.\n        render={\n          <ul>\n            {files.map((file, index) => (\n              <FileItemContext key={fileKey(file)} value={file}>\n                {children(file, index)}\n              </FileItemContext>\n            ))}\n          </ul>\n        }\n      />\n    </div>\n  )\n}\n\nconst FileItemContext = createContext<File | null>(null)\n\ninterface Preview {\n  url: string\n  users: number\n}\n\nconst previews = new WeakMap<File, Preview>()\n\n/** The object URL a picture's rows share, made the first time one asks. */\nfunction previewOf(file: File) {\n  let preview = previews.get(file)\n  if (!preview) {\n    preview = { url: URL.createObjectURL(file), users: 0 }\n    previews.set(file, preview)\n  }\n  return preview\n}\n\n/**\n * Lets go of a picture's URL once nothing shows it: a row's leaving copy\n * shows the same picture while it fades, so it waits for that to go.\n */\nfunction releasePreview(file: File, preview: Preview) {\n  preview.users -= 1\n  const check = () => {\n    if (preview.users > 0) return\n    if (document.querySelector(`img[src=\"${preview.url}\"]`)) {\n      setTimeout(check, 1000)\n      return\n    }\n    URL.revokeObjectURL(preview.url)\n    if (previews.get(file) === preview) previews.delete(file)\n  }\n  setTimeout(check, 0)\n}\n\nfunction noChanges() {\n  return () => {}\n}\n\n/** An object URL for a picture's preview, revoked once nothing shows it. */\nfunction usePreview(file: File) {\n  const picture = file.type.startsWith('image/')\n  // None on the server, so a page that opens with pictures hydrates the same.\n  const url = useSyncExternalStore(\n    noChanges,\n    () => (picture ? previewOf(file).url : undefined),\n    () => undefined,\n  )\n  useEffect(() => {\n    if (!picture) return\n    const preview = previewOf(file)\n    preview.users += 1\n    return () => releasePreview(file, preview)\n  }, [file, picture])\n  return url\n}\n\ntype FileItemState = 'idle' | 'uploading' | 'complete' | 'failed'\n\n/** Where a row's upload is, from its progress and error. */\nfunction itemState(progress: number | null | undefined, failed: boolean): FileItemState {\n  if (failed) return 'failed'\n  if (progress === undefined) return 'idle'\n  if (progress !== null && progress >= 100) return 'complete'\n  return 'uploading'\n}\n\n/** What a row's end button is called: it cancels an upload still going, and removes the file otherwise. */\nfunction removeLabel(name: string, state: FileItemState) {\n  return state === 'uploading' ? `Cancel upload of ${name}` : `Remove ${name}`\n}\n\n/** What a screen reader hears when a row's upload ends. */\nfunction uploadAnnouncement(name: string, state: FileItemState) {\n  if (state === 'complete') return `${name} uploaded`\n  if (state === 'failed') return `${name} failed to upload`\n  return ''\n}\n\n/**\n * A file's row, on ui-sdk's item: its picture or icon, its name and size,\n * and a button that removes it. Given `progress`, it shows the upload\n * drawing on its track, then a tick once it reaches 100; given `error`, it\n * says why it failed. While it uploads, its end button cancels the upload,\n * and says so. `children` are more actions, such as a Retry button, before\n * the remove one.\n */\nfunction FileInputItem({\n  className,\n  progress: progressProp,\n  error: errorProp,\n  children,\n  ref,\n  ...props\n}: Omit<\n  ComponentProps<typeof FileInputItemPrimitive>,\n  'className' | 'children' | 'file'\n> & {\n  className?: string\n  /** How far its upload has got, from 0 to 100; `null` while that isn't known. Left out, it shows its own upload's, if the FileInput has `upload`, or no track. */\n  progress?: number | null\n  /** Why its upload failed. Left out, it shows why its own upload did. */\n  error?: ReactNode\n  children?: ReactNode\n}) {\n  const file = use(FileItemContext)\n  if (!file) throw new Error('A FileInputItem goes inside a FileInputList.')\n  const { disabled, locale, uploads, retry } = useFileInput()\n  // Its own upload, when the FileInput runs them and nothing is given in its place.\n  const upload = uploads.get(file)\n  const progress =\n    progressProp !== undefined ? progressProp : rowProgress(upload, file.size)\n  const ownError = errorProp === undefined && upload?.status === 'failed'\n  const error = ownError ? upload.error : errorProp\n  const preview = usePreview(file)\n  // A picture the browser can't draw, such as a HEIC on most of them, keeps the icon.\n  const [broken, setBroken] = useState<string>()\n  const failed = error != null && error !== false && error !== ''\n  const state = itemState(progress, failed)\n  const size = formatFileSize(file.size, locale)\n  const id = useId()\n\n  // A finished upload's line comes once its track has drawn to the end; any\n  // other state shows at once.\n  const lineRef = useRef<HTMLSpanElement>(null)\n  const [shown, setShown] = useState(state)\n  const drawing = state === 'complete' && shown === 'uploading'\n  if (shown !== state && !drawing) setShown(state)\n  useEffect(() => {\n    const line = lineRef.current\n    if (!drawing || !line) return\n    let cancelled = false\n    void transitionsSettled(line, { subtree: true }).then(() => {\n      if (!cancelled) setShown('complete')\n    })\n    return () => {\n      cancelled = true\n    }\n  }, [drawing])\n\n  // An upload the FileInput runs is told once for the whole batch; one the\n  // caller drives is told here, row by row.\n  const own = progressProp === undefined && upload !== undefined\n  const lastState = useRef(state)\n  useEffect(() => {\n    if (lastState.current === state) return\n    lastState.current = state\n    if (!own) announce(uploadAnnouncement(file.name, state))\n  }, [state, file, own])\n\n  // A control that goes with a state, such as Retry, takes the focus with\n  // it: the row keeps it.\n  const rowRef = useRef<HTMLDivElement>(null)\n  const refs = useMemo(() => mergeRefs(rowRef, ref), [ref])\n  const focused = useRef<Element | null>(null)\n  useEffect(() => {\n    const row = rowRef.current\n    if (!row) return\n    const enter = (event: FocusEvent) => {\n      focused.current = event.target as Element\n    }\n    row.addEventListener('focusin', enter)\n    return () => row.removeEventListener('focusin', enter)\n  }, [])\n  useLayoutEffect(() => {\n    const row = rowRef.current\n    const last = focused.current\n    if (!row || !last || last.isConnected) return\n    focused.current = null\n    const active = document.activeElement\n    if (active === null || active === document.body) row.focus()\n  }, [state])\n\n  return (\n    <FileInputItemPrimitive\n      {...props}\n      ref={refs}\n      file={file}\n      data-state={state}\n      // Named by its file and its line, read apart: \"receipt.pdf, 1.2 MB, uploaded\".\n      aria-labelledby={`${id}-name ${id}-status`}\n      render={<li />}\n      className={cn(\n        // A container, so a row too narrow for its picture gives that room to its words.\n        'group/file-item @container/file-item bg-card flex min-w-0 items-center gap-3 rounded-(--surface-radius) border p-(--control-padding) shadow-xs',\n        // The list's one tab stop: the row that has it shows the controls' ring.\n        'focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 focus-visible:outline-hidden',\n        // Once the list has painted, it fades in on `enter` and rises on\n        // `layout`, the role its glides to a new place take too (`useFlow`);\n        // its copy fades where it was on `exit`.\n        '[transition:opacity_var(--motion-enter-duration)_var(--motion-enter-easing),translate_var(--motion-layout-duration)_var(--motion-layout-easing)] group-data-mounted/file-input-list:starting:opacity-0 motion-safe:group-data-mounted/file-input-list:starting:translate-y-(--file-input-rise,0.5rem)',\n        'data-[flow=start]:[transition:opacity_var(--motion-enter-duration)_var(--motion-enter-easing)] motion-reduce:[transition:opacity_var(--motion-enter-duration)_var(--motion-enter-easing)]',\n        // A copy that leaves mid-glide finishes its glide as it fades.\n        'data-leaving:opacity-0 data-leaving:[transition:opacity_var(--motion-exit-duration)_var(--motion-exit-easing),translate_var(--motion-layout-duration)_var(--motion-layout-easing)] motion-reduce:data-leaving:[transition:opacity_var(--motion-exit-duration)_var(--motion-exit-easing)]',\n        // A file that takes another's place waits for it to fade, so the two never overlap.\n        'group-data-swapping/file-input:not-data-leaving:not-data-flowing:[transition-delay:var(--motion-exit-duration)]',\n        'data-[state=failed]:border-destructive/40 forced-colors:data-[state=failed]:border-dashed',\n        // A failed row whose reason wraps grows at once: it sits above the row\n        // below while that one glides out of its way, so its reason never hides.\n        'data-[state=failed]:relative data-[state=failed]:z-1',\n        className,\n      )}\n    >\n      <IconTile\n        size='md'\n        // Under 15rem a row keeps its name and status, and leaves its picture out.\n        className='@max-[15rem]/file-item:hidden'\n      >\n        {preview && broken !== preview ? (\n          // oxlint-disable-next-line next/no-img-element -- a picture from the user's own disk, as an object URL: next/image can't load it.\n          <img\n            src={preview}\n            alt=''\n            onError={() => setBroken(preview)}\n            className='size-full object-cover'\n          />\n        ) : (\n          <IconPlaceholder\n            lucide='FileIcon'\n            tabler='IconFile'\n            hugeicons='File01Icon'\n            phosphor='FileIcon'\n            remixicon='RiFileLine'\n            aria-hidden\n          />\n        )}\n      </IconTile>\n      <span className='flex min-w-0 flex-1 flex-col gap-0.5'>\n        <span\n          id={`${id}-name`}\n          data-slot='file-input-item-name'\n          // A name keeps its own direction, and sits at the row's start\n          // (`self-start` follows the row's direction). A long one wraps, at\n          // any character, so the whole of it shows.\n          dir='auto'\n          className='max-w-full self-start text-sm leading-5 font-medium wrap-anywhere'\n        >\n          {file.name}\n        </span>\n        {/* The size, the track while it uploads and what happened, in one\n            line that stays one height, so nothing beside it moves. A new\n            state rolls in through `Swap`. An agent reads the row by its\n            file's name alone, as ui-sdk lists the files, so a step that names\n            a file still finds it while its status changes. */}\n        <span\n          ref={lineRef}\n          id={`${id}-status`}\n          data-slot='file-input-item-status'\n          data-agent-hidden=''\n          className='text-muted-foreground flex min-h-5 items-center text-xs'\n        >\n          <Swap roll fill align='start' id={shown}>\n            {shown === 'uploading' ? (\n              <span className='flex min-w-0 flex-1 items-center gap-2'>\n                <Progress\n                  value={progress ?? null}\n                  aria-label={`Uploading ${file.name}`}\n                  className='min-w-0 flex-1'\n                />\n                <span className='shrink-0 tabular-nums'>\n                  <bdi>{progress == null ? size : `${Math.round(progress)}%`}</bdi>\n                </span>\n              </span>\n            ) : shown === 'failed' ? (\n              // The reason takes the line, and wraps under itself in a narrow row, so all of it shows.\n              <span className='text-destructive flex min-w-0 items-start gap-1 [&_svg:not([class*=\"size-\"])]:size-3.5 [&>svg]:mt-0.5'>\n                <IconPlaceholder\n                  lucide='CircleAlertIcon'\n                  tabler='IconAlertCircle'\n                  hugeicons='AlertCircleIcon'\n                  phosphor='WarningCircleIcon'\n                  remixicon='RiErrorWarningLine'\n                  aria-hidden\n                  className='shrink-0'\n                />\n                <span className='min-w-0 wrap-break-word'>{error}</span>\n              </span>\n            ) : (\n              <span className='flex min-w-0 items-center gap-2'>\n                <bdi className='shrink-0 tabular-nums'>{size}</bdi>\n                {shown === 'complete' ? (\n                  <span className='text-foreground inline-flex shrink-0 items-center gap-1 [&_svg:not([class*=\"size-\"])]:size-3.5'>\n                    <IconPlaceholder\n                      lucide='CheckIcon'\n                      tabler='IconCheck'\n                      hugeicons='Tick02Icon'\n                      phosphor='CheckIcon'\n                      remixicon='RiCheckLine'\n                      aria-hidden\n                    />\n                    Uploaded\n                  </span>\n                ) : null}\n              </span>\n            )}\n          </Swap>\n        </span>\n      </span>\n      {/* Its own failed upload's Retry: the file's name is in its label, so the reason keeps the room. */}\n      {ownError ? (\n        <Button\n          variant='ghost'\n          size='icon-sm'\n          data-file-input-item-retry=''\n          aria-label={`Retry ${file.name}`}\n          disabled={disabled}\n          onClick={() => retry(file)}\n        >\n          <IconPlaceholder\n            lucide='RotateCwIcon'\n            tabler='IconRotateClockwise'\n            hugeicons='RotateClockwiseIcon'\n            phosphor='ArrowClockwiseIcon'\n            remixicon='RiRestartLine'\n            aria-hidden\n          />\n        </Button>\n      ) : null}\n      {children}\n      {/* Out of the tab order, as Delete on the row does the same. */}\n      <FileInputItemRemovePrimitive\n        data-file-input-item-remove=''\n        aria-label={removeLabel(file.name, state)}\n        className={buttonVariants({ variant: 'ghost', size: 'icon-sm' })}\n      >\n        <IconPlaceholder\n          lucide='XIcon'\n          tabler='IconX'\n          hugeicons='Cancel01Icon'\n          phosphor='XIcon'\n          remixicon='RiCloseLine'\n          aria-hidden\n        />\n      </FileInputItemRemovePrimitive>\n    </FileInputItemPrimitive>\n  )\n}\n\n/*\n * The files turned away: what the last pick, drop or paste didn't add, each\n * with why, in a warning that closes once a pick adds them all, or with its\n * close button. Where nothing was turned away it takes no room.\n */\n\nfunction FileInputRejected({\n  className,\n  ...props\n}: Omit<ComponentProps<'div'>, 'children'>) {\n  const { rejected, dismissRejected, rules, locale } = useFileInput()\n  return (\n    <div\n      data-slot='file-input-rejected'\n      // Closed, it gives back the gap above it; open, the gap is inside what it measures.\n      className={cn(\n        '-mt-3 [&_[data-alert-panel]]:flow-root [&_[data-slot=alert-surface]]:mt-3',\n        className,\n      )}\n      {...props}\n    >\n      <FileRejections\n        rejected={rejected}\n        rules={rules}\n        locale={locale}\n        onDismiss={dismissRejected}\n      />\n    </div>\n  )\n}\n\n/**\n * The files turned away and why, as a warning that closes once they're\n * dismissed: the File input's, and any part's that takes files by its rules.\n */\nfunction FileRejections({\n  rejected,\n  rules,\n  locale,\n  onDismiss,\n}: {\n  /** Empty closes it. */\n  rejected: readonly FileRejection[]\n  rules: FileRules\n  locale?: string\n  onDismiss: () => void\n}) {\n  // What it said, kept while it closes.\n  const [shown, setShown] = useState(rejected)\n  if (rejected.length > 0 && shown !== rejected) setShown(rejected)\n  return (\n    <Alert\n      type='warning'\n      open={rejected.length > 0}\n      onOpenChange={(open) => {\n        if (!open) onDismiss()\n      }}\n      showCloseButton\n      // Closed, it holds nothing for an agent to read or open: only files turned away open it.\n      data-agent-hidden={rejected.length > 0 ? undefined : ''}\n    >\n      <AlertTitle dir='auto'>{rejectedTitle(shown)}</AlertTitle>\n      <AlertDescription>\n        {shown.length === 1 ? (\n          // The title names the file: the reason is all that's left to say.\n          <span dir='auto'>{rejectionText(shown[0], rules, locale)}</span>\n        ) : (\n          <ul className='flex flex-col gap-0.5'>\n            {shown.slice(0, 4).map((rejection) => (\n              <li\n                key={`${rejection.file.name}-${rejection.reasons.join()}`}\n                className='flex min-w-0 flex-col'\n              >\n                <span dir='auto' className='max-w-full font-medium wrap-anywhere'>\n                  {rejection.file.name}\n                  <span className='sr-only'>: </span>\n                </span>\n                <span dir='auto'>{rejectionText(rejection, rules, locale)}</span>\n              </li>\n            ))}\n            {shown.length > 4 ? <li>And {shown.length - 4} more</li> : null}\n          </ul>\n        )}\n      </AlertDescription>\n    </Alert>\n  )\n}\n\nconst STATUS_DONE_ICON = (\n  <IconPlaceholder\n    lucide='CircleCheckIcon'\n    tabler='IconCircleCheck'\n    hugeicons='CheckmarkCircle02Icon'\n    phosphor='CheckCircleIcon'\n    remixicon='RiCheckboxCircleLine'\n    aria-hidden\n    className='text-success shrink-0'\n  />\n)\n\nconst STATUS_FAILED_ICON = (\n  <IconPlaceholder\n    lucide='CircleAlertIcon'\n    tabler='IconAlertCircle'\n    hugeicons='AlertCircleIcon'\n    phosphor='WarningCircleIcon'\n    remixicon='RiErrorWarningLine'\n    aria-hidden\n    className='text-destructive shrink-0'\n  />\n)\n\nconst STATUS_FILES_ICON = (\n  <IconPlaceholder\n    lucide='PaperclipIcon'\n    tabler='IconPaperclip'\n    hugeicons='Attachment01Icon'\n    phosphor='PaperclipIcon'\n    remixicon='RiAttachment2'\n    aria-hidden\n    className='text-muted-foreground shrink-0'\n  />\n)\n\n/*\n * The status: the whole batch in one bar under the rows. While files go up\n * it shows one bar for all of them and Cancel uploads; once they are, how\n * it went, with Retry failed if one failed; for files that go with the\n * form, how many and how big. It opens with the first file and closes with\n * the last, keeping its line as it goes. The bar stays while only its words\n * change; its button fades out on `exit` rather than vanishing.\n */\n\nfunction FileInputStatus({\n  className,\n  ...props\n}: Omit<ComponentProps<'div'>, 'children'>) {\n  const {\n    summary,\n    uploading,\n    waiting,\n    locale,\n    disabled,\n    cancelActive,\n    retryFailed,\n    files,\n    controller,\n  } = useFileInput()\n  const state = statusState(summary, uploading, waiting)\n  // The last line, kept while it closes, so it leaves as it was.\n  const [kept, setKept] = useState({ state, summary })\n  const keptKey = (entry: typeof kept) =>\n    `${entry.state}|${entry.summary.count}|${entry.summary.done}|${entry.summary.failed}|${entry.summary.active}`\n  if (state !== 'empty' && keptKey(kept) !== keptKey({ state, summary }))\n    setKept({ state, summary })\n  const shown = state === 'empty' ? kept : { state, summary }\n  const going = shown.state === 'uploading' || shown.state === 'waiting'\n  // Cancel uploads while files go up, Retry failed once one has failed.\n  const action = state === 'uploading' || state === 'waiting' || state === 'failed'\n  // What the button last was, kept while it fades out, so it leaves as it was.\n  const kind = state === 'failed' ? 'retry' : 'cancel'\n  const [buttonKind, setButtonKind] = useState(kind)\n  if (action && buttonKind !== kind) setButtonKind(kind)\n  const rootRef = useRef<HTMLDivElement>(null)\n  const actionRef = useRef<HTMLButtonElement>(null)\n\n  const rowOf = (states: string) =>\n    rootRef.current\n      ?.closest('[data-slot=file-input]')\n      ?.querySelector<HTMLElement>(`[data-slot=file-input-item]:is(${states})`)\n  /** Where the focus goes when the button goes: the first row left, or the way in. */\n  const focusAfterAction = () => {\n    const row = rowOf('[data-state=complete],[data-state=failed],[data-state=idle]')\n    if (row) row.focus()\n    else controller.focus()\n  }\n  // The button goes once nothing is left to cancel or retry: the focus goes with it.\n  useEffect(() => {\n    if (!action && actionRef.current?.contains(document.activeElement)) focusAfterAction()\n  })\n  const cancel = () => {\n    const left = files.length - summary.active\n    cancelActive()\n    if (left === 0) controller.focus()\n    else focusAfterAction()\n  }\n  // Retry goes with the failures: the focus goes to the first file it retries.\n  const retry = () => {\n    rowOf('[data-state=failed]')?.focus()\n    retryFailed()\n  }\n\n  return (\n    <div\n      ref={rootRef}\n      data-slot='file-input-status'\n      // Closed, it gives back the gap above it; open, the gap is inside what it measures.\n      className={cn('@container -mt-3', className)}\n      {...props}\n    >\n      <Collapsible\n        open={state !== 'empty'}\n        // The files open and close it, so an agent can't either; it reads as the uploads' summary.\n        disabled\n        role='group'\n        aria-label='Uploads'\n      >\n        <CollapsiblePanel className='p-0 pt-3'>\n          <div\n            // As tall with its button as without, so nothing moves when the button comes or goes.\n            className='bg-muted/50 relative flex min-h-(--control-height) flex-wrap items-center justify-between gap-x-3 gap-y-1 rounded-(--surface-radius) border px-(--control-padding) py-1'\n          >\n            <div className='flex min-w-0 flex-1 basis-48 text-xs'>\n              {/* The bar stays while only its words change; it rolls out when the batch settles. */}\n              <Swap roll fill align='start' id={going ? 'going' : shown.state}>\n                {going ? (\n                  <span className='flex min-w-0 flex-1 items-center gap-3'>\n                    <Progress\n                      value={shown.summary.percent}\n                      aria-label='All uploads'\n                      className='w-16 shrink-0 @sm:w-24'\n                    />\n                    <span className='text-muted-foreground flex min-w-0 flex-1'>\n                      <Swap roll fill align='start' id={shown.state}>\n                        <span dir='auto' className='min-w-0 text-pretty tabular-nums'>\n                          {shown.state === 'waiting'\n                            ? waitingText(shown.summary.active)\n                            : progressText(shown.summary, locale)}\n                        </span>\n                      </Swap>\n                    </span>\n                  </span>\n                ) : (\n                  <span className='flex min-w-0 items-center gap-1.5 font-medium [&_svg:not([class*=\"size-\"])]:size-4'>\n                    {shown.state === 'failed'\n                      ? STATUS_FAILED_ICON\n                      : shown.state === 'done'\n                        ? STATUS_DONE_ICON\n                        : STATUS_FILES_ICON}\n                    <span dir='auto' className='min-w-0 text-pretty tabular-nums'>\n                      {shown.state === 'held'\n                        ? heldText(shown.summary, locale)\n                        : settledText(shown.summary, locale)}\n                    </span>\n                  </span>\n                )}\n              </Swap>\n            </div>\n            {/* Files that go with the form have nothing to cancel or retry. */}\n            {uploading ? (\n              // Kept in place while it's open, so it fades out on `exit` rather than vanishing.\n              <Button\n                ref={actionRef}\n                variant={buttonKind === 'retry' ? 'outline' : 'ghost'}\n                size='xs'\n                data-hidden={action ? undefined : ''}\n                inert={!action}\n                aria-hidden={action ? undefined : true}\n                disabled={disabled}\n                // Hidden, it leaves the flow, so the line gets its room; it still fades where it was.\n                className='ms-auto shrink-0 data-hidden:absolute data-hidden:end-(--control-padding) data-hidden:invisible data-hidden:opacity-0 data-hidden:[transition:opacity_var(--motion-exit-duration)_var(--motion-exit-easing),visibility_0s_var(--motion-exit-duration)]'\n                onClick={buttonKind === 'retry' ? retry : cancel}\n              >\n                <SwapText\n                  text={buttonKind === 'retry' ? 'Retry failed' : 'Cancel uploads'}\n                />\n              </Button>\n            ) : null}\n          </div>\n        </CollapsiblePanel>\n      </Collapsible>\n    </div>\n  )\n}\n\n/** A drop target's look from its state: ui-sdk's attributes, and ours for a drag anywhere on the page. */\nfunction useDropzone(className: string, own: string | undefined) {\n  const { openPicker, disabled } = useFileInput()\n  const page = usePageDrag()\n  return {\n    page,\n    props: {\n      'data-page-drag': page.dragging || undefined,\n      // Says the faded words are off, as the button inside does.\n      'aria-disabled': disabled || undefined,\n      onClick: openPicker,\n      className: cn(\n        className,\n        'data-disabled:pointer-events-none data-disabled:opacity-50',\n        own,\n      ),\n    },\n  }\n}\n\n/*\n * The dropzone: ui-sdk's drop target, above the list, in the Empty state's\n * outlined look. While a file is dragged anywhere on the page its edge\n * darkens, so it says where to go; over it, the edge and a tint come in on\n * `press` and its picture lifts on `enter`. A press anywhere on it opens\n * the picker, as its button does.\n */\n\nconst dropzoneClassName = cn(\n  emptyVariants({ variant: 'outline' }),\n  'group/dropzone relative transition-[background-color,border-color,box-shadow] duration-(--motion-press-duration) ease-(--motion-press-fade-easing)',\n  'has-aria-invalid:border-destructive/60 forced-colors:has-aria-invalid:outline-2 forced-colors:has-aria-invalid:outline-offset-1 forced-colors:has-aria-invalid:outline-dashed',\n  'data-page-drag:border-foreground/30',\n  'data-dragging:border-primary data-dragging:bg-primary/[0.02] data-dragging:ring-3 data-dragging:ring-ring/30 dark:data-dragging:bg-primary/[0.07] forced-colors:data-dragging:border-[Highlight] forced-colors:data-dragging:border-solid',\n  'data-drag-reject:border-destructive data-drag-reject:bg-destructive/[0.02] data-drag-reject:ring-destructive/20 dark:data-drag-reject:bg-destructive/[0.08] forced-colors:data-drag-reject:border-[Mark]',\n  // The picture lifts towards the file over it, and settles when it leaves.\n  '[&_[data-slot=empty-media]]:transition-[scale,translate] [&_[data-slot=empty-media]]:duration-(--motion-enter-duration) [&_[data-slot=empty-media]]:ease-(--motion-enter-easing) motion-safe:data-dragging:[&_[data-slot=empty-media]]:-translate-y-1 motion-safe:data-dragging:[&_[data-slot=empty-media]]:scale-110',\n)\n\nfunction FileInputDropzone({\n  className,\n  children,\n  ...props\n}: Omit<ComponentProps<typeof FileInputDropzonePrimitive>, 'className' | 'children'> & {\n  className?: string\n  /** Its content, or a function of the drag's state, to say something else while a file is over it. */\n  children?: ReactNode | ((state: FileInputDropzoneState) => ReactNode)\n}) {\n  const { page, props: own } = useDropzone(dropzoneClassName, className)\n  return (\n    <FileInputDropzonePrimitive {...props} {...own}>\n      {(state) =>\n        typeof children === 'function'\n          ? children({ ...state, count: page.count })\n          : children\n      }\n    </FileInputDropzonePrimitive>\n  )\n}\n\n/*\n * The box: ui-sdk's drop target as a box the size of a text field, with the\n * Input's edge and focus ring, for a form where a file is one answer among\n * others. It says what to do, and while a file is over it, what the drop\n * will do; the words change in place (`SwapText`). The button at its end is\n * the way in by keyboard.\n */\n\nconst boxClassName = cn(\n  inputBoxClassName,\n  'h-(--control-height) gap-2 ps-(--control-padding) pe-[calc((var(--control-height)-var(--control-height-xs))/2-1px)]',\n  'data-page-drag:border-dashed data-page-drag:border-foreground/30',\n  'data-dragging:border-solid data-dragging:border-ring data-dragging:ring-3 data-dragging:ring-ring/50 forced-colors:data-dragging:outline-2 forced-colors:data-dragging:outline-[Highlight]',\n  'data-drag-reject:border-destructive data-drag-reject:ring-destructive/20 dark:data-drag-reject:ring-destructive/40',\n)\n\n/** What the box says: what to do, or what a drop of the files over it will do. */\nfunction boxText(\n  state: FileInputDropzoneState,\n  one: boolean,\n  placeholder: string | undefined,\n) {\n  if (!state.dragging)\n    return placeholder ?? (one ? 'Drop a file here' : 'Drop files here')\n  if (state.dragReject)\n    return `Can’t add ${state.count === 1 ? 'this type' : 'these types'}`\n  if (one || state.count === 1) return 'Drop to add it'\n  return state.count > 1 ? `Drop to add ${state.count} files` : 'Drop to add them'\n}\n\nfunction FileInputBox({\n  className,\n  placeholder,\n  children,\n  ...props\n}: Omit<ComponentProps<typeof FileInputDropzonePrimitive>, 'className' | 'children'> & {\n  className?: string\n  /** What it says while no file is over it: “Drop files here”, or “Drop a file here” for one file. */\n  placeholder?: string\n  children?: ReactNode\n}) {\n  const { rules } = useFileInput()\n  const { page, props: own } = useDropzone(boxClassName, className)\n  return (\n    <FileInputDropzonePrimitive\n      {...props}\n      {...own}\n      // A box, not a zone: the trigger inside it reads which.\n      data-file-input-box=''\n    >\n      {(state) => {\n        const drag = { ...state, count: page.count }\n        return (\n          <>\n            <IconPlaceholder\n              lucide='PaperclipIcon'\n              tabler='IconPaperclip'\n              hugeicons='Attachment01Icon'\n              phosphor='PaperclipIcon'\n              remixicon='RiAttachment2'\n              aria-hidden\n            />\n            <span\n              className={cn(\n                'text-muted-foreground flex min-w-0 flex-1 text-sm transition-colors duration-(--motion-press-duration) ease-(--motion-press-fade-easing)',\n                drag.dragging && 'text-foreground',\n                drag.dragReject && 'text-destructive',\n              )}\n            >\n              <SwapText text={boxText(drag, holdsOne(rules), placeholder)} />\n            </span>\n            <InputInvalidIcon className='pe-0' />\n            {children}\n          </>\n        )\n      }}\n    </FileInputDropzonePrimitive>\n  )\n}\n\nexport {\n  createFileInputController,\n  FileInput,\n  FileInputBox,\n  FileInputDropzone,\n  FileInputItem,\n  FileInputList,\n  FileInputRejected,\n  FileInputStatus,\n  FileInputTrigger,\n  FileRejections,\n}\n\nexport type {\n  FileInputController,\n  FileInputDropzoneState,\n  FileInputValueChangeDetails,\n  FileRejection,\n  FileRejectionReason,\n  FileRules,\n  SavedFile,\n  UploadFile,\n  UploadOptions,\n}\n\nexport {\n  boxText,\n  sameFile,\n  failedMessage,\n  formatFileSize,\n  heldText,\n  itemState,\n  limitsText,\n  progressText,\n  rejectedTitle,\n  rejectionText,\n  removeLabel,\n  settledText,\n  statusState,\n  typeNames,\n  typesText,\n  uploadAnnouncement,\n  waitingText,\n}\n",
      "type": "registry:component",
      "target": "@components/kino/file-input.tsx"
    }
  ],
  "type": "registry:component"
}