{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "request-attachment-slots",
  "title": "Attachment slots",
  "description": "Lists a record's governed attachment slots and their readiness, with one slot's upload, replace, remove and preview presentation. The caller supplies each slot's commands and this profile's authority over it.",
  "dependencies": [
    "@registrystack/app-runtime@~0.43.0-next.0",
    "lucide-react@1.43.0"
  ],
  "registryDependencies": [
    "@registrystack/ui-button",
    "@registrystack/ui-input",
    "@registrystack/ui-field",
    "@registrystack/lib-content",
    "@registrystack/lib-format",
    "@registrystack/lib-notice",
    "@registrystack/request-status"
  ],
  "files": [
    {
      "path": "request/attachment-slots.tsx",
      "content": "import { Fragment, useEffect, useState, type ReactNode } from \"react\";\nimport { Download, FileImage, FileText, Eye } from \"lucide-react\";\nimport {\n  problemView,\n  type AttachmentFile,\n  type AttachmentSlot,\n} from \"@registrystack/app-runtime\";\nimport { Button } from \"@/components/ui/button\";\nimport { Input } from \"@/components/ui/input\";\nimport {\n  Field,\n  FieldDescription,\n  FieldError,\n  FieldLabel,\n} from \"@/components/ui/field\";\nimport {\n  useBlockContent,\n  useLocale,\n  type BlockContent,\n} from \"@/blocks/lib/content\";\nimport { fill, fillNodes, inSentence, longDate } from \"@/blocks/lib/format\";\nimport { Notice } from \"@/blocks/lib/notice\";\nimport {\n  CommandFeedback,\n  type CommandOutcome,\n} from \"@/blocks/request/request-status\";\n\n/**\n * The outcome of one upload: a plain command plus what only an upload can\n * say, since the file it sends lives in the browser, not on the server.\n */\nexport interface UploadOutcome extends CommandOutcome {\n  reset(): void;\n  notRetained: boolean;\n  bytesUnavailable: boolean;\n  /** Why the last retry of an unresolved attempt was refused; the caller does not classify it further. */\n  lastRefusal: unknown;\n  upload(uploadRef: string, file: Blob): Promise<unknown>;\n  dismissUnknown(): void;\n}\n\n/**\n * A record's governed attachment slots, listed with the readiness of the\n * slots the registry requires. Each slot's own upload, replace or remove\n * form, and the commands behind it, are entirely the caller's: `renderSlot`\n * renders one slot, so it can bind that slot's commands and this profile's\n * authority over it. `children` renders after the slots, at the same place\n * the caller's own preview surface belongs.\n */\nexport function SupportingDocuments({\n  slots,\n  renderSlot,\n  children,\n}: {\n  slots?: AttachmentSlot[];\n  renderSlot: (slot: AttachmentSlot) => ReactNode;\n  children?: ReactNode;\n}) {\n  const c = useBlockContent();\n  const locale = useLocale();\n  if (!slots?.length) return null;\n  const required = slots.filter((slot) => slot.required);\n  return (\n    <section aria-labelledby=\"supporting-documents\">\n      <h2 id=\"supporting-documents\">{c.attachmentsHeading}</h2>\n      {required.length > 0 && (\n        <p role=\"status\">\n          {fill(\n            c.attachmentReadiness,\n            {\n              ready: required.filter((slot) => slot.file?.status === \"available\")\n                .length,\n              total: required.length,\n            },\n            locale,\n          )}\n        </p>\n      )}\n      <div className=\"flex flex-col divide-y border-y\">\n        {slots.map((slot) => (\n          <Fragment key={slot.slot}>{renderSlot(slot)}</Fragment>\n        ))}\n      </div>\n      {children}\n    </section>\n  );\n}\n\nexport interface SlotProps {\n  slot: AttachmentSlot;\n  readOnly: boolean;\n  /** Prevents starting a write against a record whose revision is refreshing. */\n  writesDisabled?: boolean;\n  onPreview: (slot: AttachmentSlot, trigger: HTMLButtonElement) => void;\n  /** Reports whether this slot has an in-flight or unresolved write. */\n  onWritingChange?: (slot: string, writing: boolean) => void;\n  slotLabel: (slot: string) => string;\n  typeLabel: (contentType: string) => string;\n  statusNote: (status: string) => string;\n  canPreview: (contentType: string) => boolean;\n}\n\n/**\n * One slot's presentation: what it holds, and the upload, replace or remove\n * form this profile may use. The upload and removal are each one command,\n * already in the shape every command in a request reads. `renderError`\n * renders a plain refusal exactly as the caller's other command errors do.\n */\nexport function SlotView({\n  slot,\n  readOnly,\n  writesDisabled = false,\n  onPreview,\n  upload,\n  removal,\n  remove,\n  downloadHref,\n  reconcileHref,\n  renderError,\n  slotLabel,\n  typeLabel,\n  statusNote,\n  canPreview,\n  onWritingChange,\n}: SlotProps & {\n  upload: UploadOutcome;\n  removal: CommandOutcome & { reset: () => void };\n  remove: (removeRef: string) => Promise<unknown>;\n  downloadHref: string;\n  reconcileHref: string;\n  renderError: (error: Error) => ReactNode;\n}) {\n  const c = useBlockContent();\n  const locale = useLocale();\n  const [chosen, setChosen] = useState<File | null>(null);\n  // Keep the surrounding request locked until the command's cache refresh has\n  // completed. The command state itself becomes confirmed before that await.\n  const [dispatches, setDispatches] = useState(0);\n  // Remounting the input is the only way to clear a file input's selection.\n  const [inputKey, setInputKey] = useState(0);\n  useEffect(() => {\n    if (upload.result?.outcome !== \"confirmed\") return;\n    setChosen(null);\n    setInputKey((key) => key + 1);\n  }, [upload.result]);\n\n  const label = slotLabel(slot.slot);\n  const types = new Intl.ListFormat(locale, { type: \"disjunction\" }).format(\n    slot.contentTypes.map((type) => typeLabel(type)),\n  );\n  // The host checks both again; these only save sending a file it would refuse.\n  const problem = !chosen\n    ? null\n    : !slot.contentTypes.includes(chosen.type)\n      ? fill(c.attachmentWrongType, { types }, locale)\n      : chosen.size > slot.maximumBytes\n        ? fill(\n            c.attachmentTooLarge,\n            {\n              size: fileSize(chosen.size, c, locale),\n              limit: fileSize(slot.maximumBytes, c, locale),\n            },\n            locale,\n          )\n        : null;\n  const file = slot.file;\n  const busy = dispatches > 0 || upload.pending || removal.pending;\n  // An unresolved upload or removal holds the slot until it settles.\n  const held = upload.unknown || removal.unknown;\n  const writing = busy || held;\n  const inputId = `attachment-${slot.slot}`;\n\n  useEffect(() => {\n    onWritingChange?.(slot.slot, writing);\n  }, [onWritingChange, slot.slot, writing]);\n  useEffect(\n    () => () => onWritingChange?.(slot.slot, false),\n    [onWritingChange, slot.slot],\n  );\n\n  async function track<T>(command: () => Promise<T>): Promise<T> {\n    setDispatches((count) => count + 1);\n    try {\n      return await command();\n    } finally {\n      setDispatches((count) => Math.max(0, count - 1));\n    }\n  }\n\n  const trackedUpload = {\n    ...upload,\n    retry: () => track(upload.retry),\n  };\n  const trackedRemoval = {\n    ...removal,\n    retry: () => track(removal.retry),\n  };\n\n  return (\n    <div className=\"flex flex-col gap-3 py-3\">\n      <div className=\"flex flex-wrap items-start justify-between gap-3\">\n        <div className=\"document-slot-heading\">\n          {file?.contentType.startsWith(\"image/\") ? (\n            <FileImage className=\"document-slot-icon\" aria-hidden=\"true\" />\n          ) : (\n            <FileText className=\"document-slot-icon\" aria-hidden=\"true\" />\n          )}\n          <div className=\"flex flex-col gap-1\">\n            <h3 className=\"m-0\">{label}</h3>\n            {file ? (\n              <>\n                {file.status !== \"erased\" && (\n                  <p className=\"m-0\">{fileLine(file, c, locale, typeLabel)}</p>\n                )}\n                {file.status !== \"available\" && (\n                  <p className=\"muted m-0\">{statusNote(file.status)}</p>\n                )}\n              </>\n            ) : (\n              <p className=\"muted m-0\">{c.attachmentNone}</p>\n            )}\n            {slot.required && file?.status !== \"available\" && (\n              <p className=\"muted m-0\">{c.attachmentRequired}</p>\n            )}\n          </div>\n        </div>\n        <div className=\"actions\">\n          {file?.status === \"available\" && canPreview(file.contentType) && (\n            <Button\n              variant=\"outline\"\n              onClick={(event) => onPreview(slot, event.currentTarget)}\n            >\n              <Eye aria-hidden=\"true\" />\n              {fill(c.documentView, { document: inSentence(label, locale) }, locale)}\n            </Button>\n          )}\n          {file?.status === \"available\" && (\n            <Button\n              variant=\"outline\"\n              render={<a href={downloadHref} download />}\n            >\n              <Download />\n              {fill(\n                c.attachmentDownload,\n                { document: inSentence(label, locale) },\n                locale,\n              )}\n            </Button>\n          )}\n          {!readOnly && file && slot.removeRef && !upload.unknown && (\n            <Button\n              variant=\"outline\"\n              disabled={writesDisabled || busy || held}\n              onClick={() => {\n                upload.reset();\n                void track(() => remove(slot.removeRef!));\n              }}\n            >\n              {c.attachmentRemove}\n            </Button>\n          )}\n        </div>\n      </div>\n      {!readOnly && slot.uploadRef && (\n        <form\n          className=\"flex flex-col gap-3\"\n          onSubmit={(event) => {\n            event.preventDefault();\n            if (writesDisabled || !chosen || problem || !slot.uploadRef) return;\n            removal.reset();\n            void track(() => upload.upload(slot.uploadRef!, chosen));\n          }}\n        >\n          <Field data-invalid={problem ? true : undefined}>\n            <FieldLabel htmlFor={inputId}>\n              {file ? c.attachmentChooseReplacement : c.attachmentChoose}\n            </FieldLabel>\n            <Input\n              key={inputKey}\n              id={inputId}\n              type=\"file\"\n              accept={slot.contentTypes.join(\",\")}\n              aria-describedby={\n                problem\n                  ? `${inputId}-hint ${inputId}-problem`\n                  : `${inputId}-hint`\n              }\n              aria-invalid={problem ? true : undefined}\n              onChange={(event) =>\n                setChosen(event.currentTarget.files?.[0] ?? null)\n              }\n            />\n            <FieldDescription id={`${inputId}-hint`}>\n              {fill(\n                c.attachmentAllowed,\n                {\n                  types,\n                  size: fileSize(slot.maximumBytes, c, locale),\n                },\n                locale,\n              )}\n            </FieldDescription>\n            {problem && (\n              <FieldError id={`${inputId}-problem`}>{problem}</FieldError>\n            )}\n          </Field>\n          {chosen && !problem && (\n            <p className=\"attachment-selection muted\" role=\"status\">\n              {fill(\n                file ? c.documentSelectedReplacement : c.documentSelected,\n                {\n                  name: chosen.name,\n                  type: typeLabel(chosen.type),\n                  size: fileSize(chosen.size, c, locale),\n                },\n                locale,\n              )}\n            </p>\n          )}\n          <div className=\"actions\">\n            <Button\n              type=\"submit\"\n              disabled={writesDisabled || !chosen || !!problem || busy || held}\n            >\n              {file ? c.attachmentReplace : c.attachmentUpload}\n            </Button>\n          </div>\n        </form>\n      )}\n      <UploadFeedback\n        upload={trackedUpload}\n        reconcileHref={reconcileHref}\n        renderError={renderError}\n      />\n      <CommandFeedback\n        task={trackedRemoval}\n        reconcileHref={reconcileHref}\n        renderError={renderError}\n      />\n    </div>\n  );\n}\n\n/**\n * The upload's own feedback. A file the browser could not keep was never sent. A retry the\n * service refused leaves the upload unresolved; once the person has checked the slots they\n * may stop waiting for it, and a file the browser no longer holds cannot be retried.\n */\nfunction UploadFeedback({\n  upload,\n  reconcileHref,\n  renderError,\n}: {\n  upload: UploadOutcome;\n  reconcileHref: string;\n  renderError: (error: Error) => ReactNode;\n}) {\n  const c = useBlockContent();\n  const locale = useLocale();\n  const viewedCode = problemView(upload.error).code;\n  // An adopter may bundle its transport separately from these blocks, making\n  // its HostError a different class instance. Read only the typed problem code\n  // in that case; the copy below remains maintained page content.\n  const carriedCode = (upload.error as { problem?: { code?: unknown } } | null)\n    ?.problem?.code;\n  const code =\n    viewedCode ?? (typeof carriedCode === \"string\" ? carriedCode : null);\n  const localRefusal =\n    code === \"attachment.empty\"\n      ? c.attachmentEmpty\n      : code === \"attachment.content\"\n        ? c.attachmentContentMismatch\n        : null;\n  if (upload.notRetained)\n    return (\n      <Notice tone=\"warning\" title={c.attachmentNotRetainedTitle}>\n        <p>{c.attachmentNotRetained}</p>\n      </Notice>\n    );\n  if (localRefusal)\n    return (\n      <Notice tone=\"warning\" title={c.attachmentNotRetainedTitle}>\n        <p>{localRefusal}</p>\n      </Notice>\n    );\n  const stopWaiting = (\n    <Button variant=\"ghost\" onClick={upload.dismissUnknown}>\n      {c.attachmentStopWaiting}\n    </Button>\n  );\n  if (upload.bytesUnavailable)\n    return (\n      <Notice tone=\"warning\" title={c.unknownTitle}>\n        <p>{c.attachmentFileLost}</p>\n        <p className=\"reference\">\n          {fillNodes(\n            c.labelled,\n            {\n              label: c.receipt,\n              value: <span className=\"font-mono\">{upload.reference}</span>,\n            },\n            locale,\n          )}\n        </p>\n        <div className=\"actions\">\n          <Button render={<a href={reconcileHref} />} variant=\"outline\">\n            {c.reconcile}\n          </Button>\n          {stopWaiting}\n        </div>\n      </Notice>\n    );\n  return (\n    <>\n      <CommandFeedback\n        task={upload}\n        reconcileHref={reconcileHref}\n        renderError={renderError}\n      />\n      {Boolean(upload.lastRefusal) && !upload.pending && (\n        <div className=\"actions\">{stopWaiting}</div>\n      )}\n    </>\n  );\n}\n\n/**\n * What is in the slot, in the caller's words and written in `locale`: kind,\n * size and when it came.\n */\nfunction fileLine(\n  file: AttachmentFile,\n  c: BlockContent,\n  locale: string,\n  typeLabel: (contentType: string) => string,\n): string {\n  const type = typeLabel(file.contentType);\n  const size = fileSize(file.byteSize, c, locale);\n  const date = file.uploadedAt ? longDate(file.uploadedAt, locale) : null;\n  return date\n    ? fill(c.attachmentFileLine, { type, size, date }, locale)\n    : fill(c.attachmentFileLineUndated, { type, size }, locale);\n}\n\n/**\n * Whole kilobytes below a megabyte, megabytes to one decimal place above,\n * written in `locale`.\n */\nfunction fileSize(bytes: number, c: BlockContent, locale: string): string {\n  const megabyte = 1024 * 1024;\n  if (bytes < megabyte)\n    return fill(\n      c.fileSizeKilobytes,\n      { size: Math.max(1, Math.round(bytes / 1024)) },\n      locale,\n    );\n  return fill(\n    c.fileSizeMegabytes,\n    {\n      size: new Intl.NumberFormat(locale, { maximumFractionDigits: 1 }).format(\n        bytes / megabyte,\n      ),\n    },\n    locale,\n  );\n}\n",
      "type": "registry:block",
      "target": "@components/request/attachment-slots.tsx"
    }
  ],
  "type": "registry:block"
}