{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "media-row-list",
  "type": "registry:ui",
  "title": "Media Row List",
  "description": "The pictures or clips a person has added, as rows they can put in order, describe and choose a cover from: each row shows its state in words (an upload's, or one the project names), its progress or its error with pause, resume and retry, a field for its text alternative that can be required, a \"cover\" choice, a remove button, and room for a status line and controls of the project's own.",
  "categories": [
    "ui"
  ],
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/announce",
    "@rivier-ui/cn",
    "@rivier-ui/dropzone",
    "@rivier-ui/input",
    "@rivier-ui/sortable-list",
    "@rivier-ui/use-controllable-state"
  ],
  "files": [
    {
      "path": "registry/ui/media-row-list.tsx",
      "type": "registry:ui",
      "target": "components/ui/media-row-list.tsx",
      "content": "\"use client\";\n/**\n * @name media-row-list\n * @category ui\n * @description The pictures or clips a person has added, as rows they can put in order, describe and choose a cover from: each row shows its state in words (an upload's, or one the project names), its progress or its error with pause, resume and retry, a field for its text alternative that can be required, a \"cover\" choice, a remove button, and room for a status line and controls of the project's own.\n * @when After a dropzone, when the order of the files matters and each needs a description: the photos of a listing, the slides of a story, the pages of a document. It is ready-made from sortable-list (drag by the handle, lift and move with the keyboard, or the move buttons; every move is read out) and the upload rows of dropzone, and contains no upload engine: the project uploads and passes each row its state. For files whose order does not matter use the dropzone's own UploadList; to reorder things that are not files use sortable-list.\n * @example\n * const [rows, setRows] = useState<MediaRow[]>([\n *   { id: \"a\", name: \"kitchen.jpg\", size: 1_200_000, state: \"done\", alt: \"The kitchen, from the door\" },\n *   { id: \"b\", name: \"garden.jpg\", size: 2_400_000, state: \"uploading\", progress: 40 },\n *   { id: \"c\", name: \"stairs.jpg\", state: \"failed\", error: \"The connection dropped.\" },\n * ]);\n * const [cover, setCover] = useState<string | null>(\"a\");\n * <MediaRowList\n *   aria-label=\"Pictures, in order\"\n *   items={rows}\n *   onItemsChange={setRows}\n *   cover={cover}\n *   onCoverChange={setCover}\n *   onAltChange={(id, alt) => setRows((all) => all.map((row) => (row.id === id ? { ...row, alt } : row)))}\n *   onRemove={(id) => setRows((all) => all.filter((row) => row.id !== id))}\n *   onRetry={(id) => upload(id)}\n * />\n *\n * // A state of the project's own, a status line, a control of its own, no cover choice, and a description that is required\n * const row: MediaRow = {\n *   id: \"d\", name: \"walk.mp4\", state: \"checking\", stateLabel: \"Being checked\", stateTone: \"warning\",\n *   status: \"Usually takes a minute.\", controls: <Button size=\"sm\" variant=\"ghost\">Trim</Button>,\n *   hideCover: true, altRequired: true, altError: \"Say what the clip shows.\",\n * };\n * <MediaRowList aria-label=\"Clips\" items={[row]} variant=\"lines\" onAltChange={describe} onPause={pause} onResume={resume} onDropped={({ values }) => save(values)} />\n */\nimport { CircleAlert } from \"lucide-react\";\nimport { useEffect, useId, useRef, type ComponentProps, type ReactNode } from \"react\";\nimport { UploadActions, UploadItem, UploadPause, UploadProgress, UploadRemove, UploadResume, UploadRetry, type UploadState, type UploadTone } from \"@/components/ui/dropzone\";\nimport { Input } from \"@/components/ui/input\";\nimport { SortableHandle, SortableItem, SortableList, SortableMoveButtons, type SortableDrop, type SortableMessages } from \"@/components/ui/sortable-list\";\nimport { announce } from \"@/lib/announce\";\nimport { cn } from \"@/lib/cn\";\nimport { useControllableState } from \"@/lib/use-controllable-state\";\n\n/** One file, as plain data. */\nexport type MediaRow = {\n  /** Unique among the rows. */\n  id: string;\n  /** The file's name: shown, and used in the names of the row's controls. */\n  name: string;\n  /** Its size in bytes. */\n  size?: number;\n  /** Where its upload is (a file that is already stored is \"done\"), or a state of the project's own (\"checking\", \"published\"): give that one a `stateLabel`. */\n  state: UploadState | (string & {});\n  /** The word for this row's state: it replaces the list's `stateLabels`. Needed for a state of the project's own. */\n  stateLabel?: string;\n  /** How the state reads: \"neutral\", \"success\", \"warning\" or \"destructive\", each with its own mark. Default: by the state. */\n  stateTone?: UploadTone;\n  /** How much has been sent, 0 to 100. The bar shows while the row is not \"done\". */\n  progress?: number;\n  /** Why it failed, in the project's words, shown after the state's word on a failed row (or one whose tone is \"destructive\"). */\n  error?: ReactNode;\n  /** A line of the row's own under its name and state: what is happening to it, or what it is waiting for. */\n  status?: ReactNode;\n  /** Controls of the project's own for this row (buttons, a menu), beside the cover choice. Name each after the file. */\n  controls?: ReactNode;\n  /** Leave the cover choice out of this row: a clip that cannot be a cover, a file still being checked. */\n  hideCover?: boolean;\n  /** The description must be given: the field says so in words and to a screen reader. */\n  altRequired?: boolean;\n  /** The description is not acceptable. Default: true when there is an `altError`. */\n  altInvalid?: boolean;\n  /** What is wrong with the description, in words the person can act on: shown under the field, tied to it, and read out when it appears. */\n  altError?: string;\n  /** A small picture of it (an `<img alt=\"\">`: the name is beside it). */\n  thumbnail?: ReactNode;\n  /** Its text alternative: what the picture shows, for people who cannot see it. */\n  alt?: string;\n};\n\n/** The words shown and read out. Translate them with the interface. */\nexport type MediaRowLabels = {\n  /** The visible label of the text-alternative field. */\n  alt: string;\n  /** The field's name for a screen reader, which must tell the rows apart. */\n  altFor: (name: string) => string;\n  /** The hint inside an empty field. */\n  altPlaceholder: string;\n  /** The word after the field's label when a description must be given. */\n  required: string;\n  /** Read out when a description's error appears. */\n  altErrorFor: (name: string, error: string) => string;\n  /** The visible label of the cover choice. */\n  cover: string;\n  /** The choice's name for a screen reader. */\n  coverFor: (name: string) => string;\n  /** The words on the row that is the cover. */\n  isCover: string;\n  /** Read out when the cover changes. */\n  coverChanged: (name: string) => string;\n  retry: string;\n  pause: string;\n  resume: string;\n  remove: string;\n  /** Read out when a row is removed. */\n  removed: (name: string) => string;\n};\n\nexport const MEDIA_ROW_LABELS: MediaRowLabels = {\n  alt: \"Description\",\n  altFor: (name) => `Description of ${name}`,\n  altPlaceholder: \"What the picture shows\",\n  required: \"required\",\n  altErrorFor: (name, error) => `${name}: ${error}`,\n  cover: \"Cover\",\n  coverFor: (name) => `Cover: ${name}`,\n  isCover: \"Cover picture\",\n  coverChanged: (name) => `${name} is now the cover.`,\n  retry: \"Try again\",\n  pause: \"Pause\",\n  resume: \"Resume\",\n  remove: \"Remove\",\n  removed: (name) => `${name} removed.`,\n};\n\nexport type MediaRowListProps = Omit<ComponentProps<\"div\">, \"children\" | \"onChange\" | \"onPause\"> & {\n  /** The rows, in order. */\n  items: readonly MediaRow[];\n  /** The rows in their new order, after a move. */\n  onItemsChange?: (items: MediaRow[]) => void;\n  /** The ids in their new order, after a move (the same moment as `onItemsChange`). */\n  onReorder?: (ids: string[]) => void;\n  /** Called once when a move ends (a dragged row is let go, a lifted row is dropped, a move button is pressed), with the row, where it was, where it is and the new order: the place to save. */\n  onDropped?: (drop: SortableDrop) => void;\n  /** Take the row out. Left out, rows have no remove button. */\n  onRemove?: (id: string) => void;\n  /** Try a failed row again. Left out, failed rows have no retry button. */\n  onRetry?: (id: string) => void;\n  /** Pause a row that is \"uploading\". Left out, there is no pause button. */\n  onPause?: (id: string) => void;\n  /** Carry on a row that is \"paused\". Left out, there is no resume button. */\n  onResume?: (id: string) => void;\n  /** The text alternative was edited. Left out, rows have no description field. */\n  onAltChange?: (id: string, alt: string) => void;\n  /** The id of the cover row, or null for none: controlled. */\n  cover?: string | null;\n  /** The cover when uncontrolled. Default: none. */\n  defaultCover?: string | null;\n  /** Called with the new cover. When the cover row is removed, it is called with the first row left (or null). */\n  onCoverChange?: (id: string | null) => void;\n  /** Leave out the cover choice in every row. One row leaves it out with its own `hideCover`. */\n  hideCover?: boolean;\n  /** Every row's description must be given. One row says so with its own `altRequired`. */\n  altRequired?: boolean;\n  /** \"cards\" (default): each row a bordered surface. \"lines\": rows with a hairline between them and no box, for a list inside a card or a panel. */\n  variant?: \"cards\" | \"lines\";\n  /** Stops reordering and every control. */\n  disabled?: boolean;\n  /** The words, where the English defaults are not wanted. */\n  labels?: Partial<MediaRowLabels>;\n  /** The words of the reordering (lifted, moved, dropped, the handle and the move buttons). */\n  sortableMessages?: Partial<SortableMessages>;\n  /** The word for each upload state. */\n  stateLabels?: Partial<Record<UploadState, string>>;\n  /** For sizes and percentages. Default: the browser's. */\n  locale?: string;\n  /** Shown instead of the list when there are no rows. */\n  empty?: ReactNode;\n};\n\ntype AltFieldProps = {\n  id: string;\n  row: MediaRow;\n  words: MediaRowLabels;\n  required: boolean;\n  disabled: boolean;\n  onChange: (alt: string) => void;\n};\n\n/** The description field of one row: labelled, required or not, and with its error tied to it and read out when it appears. */\nfunction AltField({ id, row, words, required, disabled, onChange }: AltFieldProps) {\n  const error = row.altError?.trim() || undefined;\n  const invalid = row.altInvalid ?? error !== undefined;\n  const errorId = `${id}-error`;\n  const { name } = row;\n  const say = words.altErrorFor;\n  // An error that arrives is said once. One that is already there when the row is first shown is not: a page that opens with ten of them would read ten.\n  const said = useRef(error);\n  useEffect(() => {\n    if (said.current === error) return;\n    said.current = error;\n    if (error) announce(say(name, error));\n  }, [error, name, say]);\n\n  return (\n    <div className=\"flex min-w-40 flex-1 flex-col gap-1\">\n      <label htmlFor={id} className=\"text-xs font-medium text-muted-foreground\">\n        {words.alt}\n        {required ? <span data-slot=\"media-row-alt-required\"> ({words.required})</span> : null}\n      </label>\n      <Input\n        id={id}\n        data-slot=\"media-row-alt\"\n        size=\"sm\"\n        dir=\"auto\"\n        autoComplete=\"off\"\n        aria-label={words.altFor(name)}\n        aria-invalid={invalid || undefined}\n        aria-describedby={error ? errorId : undefined}\n        required={required}\n        placeholder={words.altPlaceholder}\n        value={row.alt ?? \"\"}\n        disabled={disabled}\n        onChange={(event) => onChange(event.target.value)}\n        className=\"pointer-coarse:h-control\"\n      />\n      {error ? (\n        <p id={errorId} data-slot=\"media-row-alt-error\" className=\"flex items-start gap-1 text-xs text-destructive\">\n          <CircleAlert aria-hidden=\"true\" strokeWidth={1.5} className=\"mt-0.5 size-3.5 shrink-0\" />\n          <span>{error}</span>\n        </p>\n      ) : null}\n    </div>\n  );\n}\n\n/**\n * An ordered list, so a row is read as \"2 of 5\". Name it with `aria-label` or `aria-labelledby`. The\n * cover choices are radio buttons that share one name: exactly one row can be the cover, Tab stops on the\n * chosen one and the arrow keys move the choice between rows, as in any radio group. A failed row cannot\n * be the cover. After a row is removed, focus goes to the row that took its place (or the one before, or\n * the list itself when it was the last), and the removal is read out. A row is a surface, with the\n * surface's corners at every roundness (never a pill), or a line with a hairline under it.\n */\nexport function MediaRowList({\n  className,\n  items,\n  onItemsChange,\n  onReorder,\n  onDropped,\n  onRemove,\n  onRetry,\n  onPause,\n  onResume,\n  onAltChange,\n  cover,\n  defaultCover = null,\n  onCoverChange,\n  hideCover = false,\n  altRequired = false,\n  variant = \"cards\",\n  disabled = false,\n  labels,\n  sortableMessages,\n  stateLabels,\n  locale,\n  empty,\n  \"aria-label\": ariaLabel,\n  \"aria-labelledby\": ariaLabelledBy,\n  ...props\n}: MediaRowListProps) {\n  const words = { ...MEDIA_ROW_LABELS, ...labels };\n  const group = useId();\n  const root = useRef<HTMLDivElement>(null);\n  const [chosen, setChosen] = useControllableState<string | null>({ value: cover, defaultValue: defaultCover, onChange: onCoverChange });\n  const ids = items.map((item) => item.id);\n\n  const reorder = (next: string[]): void => {\n    onReorder?.(next);\n    const byId = new Map(items.map((item) => [item.id, item]));\n    onItemsChange?.(next.flatMap((id) => byId.get(id) ?? []));\n  };\n\n  const remove = (item: MediaRow): void => {\n    const at = ids.indexOf(item.id);\n    const neighbour = ids[at + 1] ?? ids[at - 1];\n    if (chosen === item.id) setChosen(items.find((other) => other.id !== item.id && other.state !== \"failed\" && !other.hideCover)?.id ?? null);\n    onRemove?.(item.id);\n    announce(words.removed(item.name));\n    // Once the row is gone, the keyboard's place is the row that took its place.\n    requestAnimationFrame(() => {\n      const box = root.current;\n      if (!box) return;\n      const row = neighbour === undefined ? null : [...box.querySelectorAll<HTMLElement>(\"[data-slot=media-row]\")].find((node) => node.dataset[\"row\"] === neighbour);\n      (row?.querySelector<HTMLElement>(\"[data-slot=sortable-handle]:not(:disabled), [data-slot=upload-remove]\") ?? box).focus();\n    });\n  };\n\n  return (\n    <div ref={root} data-slot=\"media-row-list\" data-variant={variant} tabIndex={-1} className={cn(\"w-full min-w-0\", className)} {...props}>\n      {items.length === 0 && empty ? (\n        <div data-slot=\"media-row-empty\" className=\"text-sm text-muted-foreground\">\n          {empty}\n        </div>\n      ) : (\n        <SortableList\n          values={ids}\n          onValuesChange={reorder}\n          disabled={disabled}\n          aria-label={ariaLabel}\n          aria-labelledby={ariaLabelledBy}\n          className={variant === \"lines\" ? \"gap-0\" : undefined}\n          {...(onDropped ? { onDropped } : {})}\n          {...(sortableMessages ? { messages: sortableMessages } : {})}\n        >\n          {items.map((item) => {\n            const isCover = chosen === item.id;\n            const failed = item.state === \"failed\";\n            const showError = item.error !== undefined && (failed || item.stateTone === \"destructive\");\n            const withCover = !hideCover && !item.hideCover;\n            const altId = `${group}-alt-${item.id}`;\n            return (\n              <SortableItem\n                key={item.id}\n                value={item.id}\n                label={item.name}\n                data-slot=\"media-row\"\n                data-row={item.id}\n                data-cover={isCover ? \"\" : undefined}\n                // A row holds several lines: it takes the surface's corners, which stay corners when controls become pills.\n                className={cn(\"items-start gap-1 p-2\", variant === \"lines\" ? \"rounded-none border-0 border-b bg-transparent px-0 last:border-b-0\" : \"rounded-surface\")}\n              >\n                <SortableHandle className=\"mt-1\" />\n                <UploadItem\n                  as=\"div\"\n                  name={item.name}\n                  state={item.state}\n                  className=\"min-w-0 flex-1 rounded-none border-0 bg-transparent p-1\"\n                  {...(item.stateLabel !== undefined ? { stateLabel: item.stateLabel } : {})}\n                  {...(item.stateTone !== undefined ? { stateTone: item.stateTone } : {})}\n                  {...(item.size !== undefined ? { size: item.size } : {})}\n                  {...(item.thumbnail ? { thumbnail: item.thumbnail } : {})}\n                  {...(stateLabels ? { stateLabels } : {})}\n                  {...(locale ? { locale } : {})}\n                  detail={\n                    showError || isCover ? (\n                      <>\n                        {showError ? item.error : null}\n                        {isCover ? (\n                          <span data-slot=\"media-row-cover-mark\" className=\"rounded-control border border-border-strong px-1.5 font-medium text-foreground\">\n                            {words.isCover}\n                          </span>\n                        ) : null}\n                      </>\n                    ) : undefined\n                  }\n                >\n                  {item.state !== \"done\" && item.progress !== undefined ? <UploadProgress value={item.progress} /> : null}\n                  <UploadActions className=\"self-start\">\n                    {item.state === \"uploading\" && onPause ? <UploadPause label={words.pause} disabled={disabled} onClick={() => onPause(item.id)} /> : null}\n                    {item.state === \"paused\" && onResume ? <UploadResume label={words.resume} disabled={disabled} onClick={() => onResume(item.id)} /> : null}\n                    {failed && onRetry ? <UploadRetry label={words.retry} disabled={disabled} onClick={() => onRetry(item.id)} /> : null}\n                    {onRemove ? <UploadRemove label={words.remove} disabled={disabled} onClick={() => remove(item)} /> : null}\n                  </UploadActions>\n                  {item.status ? (\n                    <p data-slot=\"media-row-status\" className=\"col-span-full min-w-0 text-xs text-muted-foreground\">\n                      {item.status}\n                    </p>\n                  ) : null}\n                  <div data-slot=\"media-row-details\" className=\"col-span-full flex min-w-0 flex-wrap items-end gap-x-3 gap-y-2 pt-1\">\n                    {onAltChange ? <AltField id={altId} row={item} words={words} required={altRequired || item.altRequired === true} disabled={disabled} onChange={(alt) => onAltChange(item.id, alt)} /> : null}\n                    <div className=\"ms-auto flex shrink-0 flex-wrap items-center justify-end gap-1\">\n                      {item.controls ? (\n                        <div data-slot=\"media-row-controls\" className=\"flex shrink-0 items-center gap-1\">\n                          {item.controls}\n                        </div>\n                      ) : null}\n                      {withCover ? (\n                        <label\n                          data-slot=\"media-row-cover\"\n                          className={cn(\n                            \"inline-flex h-control-sm items-center gap-2 rounded-control px-2 text-sm text-foreground hover:bg-accent has-disabled:pointer-events-none has-disabled:opacity-50 pointer-coarse:h-control\",\n                            isCover && \"font-medium\",\n                          )}\n                        >\n                          <input\n                            type=\"radio\"\n                            name={`${group}-cover`}\n                            value={item.id}\n                            checked={isCover}\n                            disabled={disabled || failed}\n                            aria-label={words.coverFor(item.name)}\n                            onChange={() => {\n                              setChosen(item.id);\n                              announce(words.coverChanged(item.name));\n                            }}\n                            className=\"size-4 shrink-0 accent-primary\"\n                          />\n                          {words.cover}\n                        </label>\n                      ) : null}\n                      <SortableMoveButtons className=\"ms-0\" />\n                    </div>\n                  </div>\n                </UploadItem>\n              </SortableItem>\n            );\n          })}\n        </SortableList>\n      )}\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "ui",
    "when": "After a dropzone, when the order of the files matters and each needs a description: the photos of a listing, the slides of a story, the pages of a document. It is ready-made from sortable-list (drag by the handle, lift and move with the keyboard, or the move buttons; every move is read out) and the upload rows of dropzone, and contains no upload engine: the project uploads and passes each row its state. For files whose order does not matter use the dropzone's own UploadList; to reorder things that are not files use sortable-list.",
    "example": "const [rows, setRows] = useState<MediaRow[]>([\n  { id: \"a\", name: \"kitchen.jpg\", size: 1_200_000, state: \"done\", alt: \"The kitchen, from the door\" },\n  { id: \"b\", name: \"garden.jpg\", size: 2_400_000, state: \"uploading\", progress: 40 },\n  { id: \"c\", name: \"stairs.jpg\", state: \"failed\", error: \"The connection dropped.\" },\n]);\nconst [cover, setCover] = useState<string | null>(\"a\");\n<MediaRowList\n  aria-label=\"Pictures, in order\"\n  items={rows}\n  onItemsChange={setRows}\n  cover={cover}\n  onCoverChange={setCover}\n  onAltChange={(id, alt) => setRows((all) => all.map((row) => (row.id === id ? { ...row, alt } : row)))}\n  onRemove={(id) => setRows((all) => all.filter((row) => row.id !== id))}\n  onRetry={(id) => upload(id)}\n/>\n\n// A state of the project's own, a status line, a control of its own, no cover choice, and a description that is required\nconst row: MediaRow = {\n  id: \"d\", name: \"walk.mp4\", state: \"checking\", stateLabel: \"Being checked\", stateTone: \"warning\",\n  status: \"Usually takes a minute.\", controls: <Button size=\"sm\" variant=\"ghost\">Trim</Button>,\n  hideCover: true, altRequired: true, altError: \"Say what the clip shows.\",\n};\n<MediaRowList aria-label=\"Clips\" items={[row]} variant=\"lines\" onAltChange={describe} onPause={pause} onResume={resume} onDropped={({ values }) => save(values)} />",
    "client": true
  }
}
