{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "pages-record-attachments",
  "title": "Record attachments",
  "description": "A record's governed attachment slots: upload, replace, remove and an on-demand preview, plus the notice of this session's uploads still waiting to be confirmed.",
  "dependencies": [
    "@registrystack/app-runtime@~0.43.0-next.0"
  ],
  "registryDependencies": [
    "@registrystack/pages-record",
    "@registrystack/pages-content",
    "@registrystack/pages-register-routes",
    "@registrystack/lib-content",
    "@registrystack/lib-format",
    "@registrystack/lib-notice",
    "@registrystack/request-attachment-slots",
    "@registrystack/request-status",
    "@registrystack/document-preview",
    "@registrystack/shell-error-panel",
    "@registrystack/shell-routing",
    "@registrystack/ui-button"
  ],
  "files": [
    {
      "path": "pages/record-attachments.tsx",
      "content": "import type { AttachmentSlot } from \"@registrystack/app-runtime\";\nimport { documentPreviewTypes } from \"@registrystack/app-runtime\";\nimport { useAttachmentHref } from \"@registrystack/app-runtime/react\";\nimport { Button } from \"@/components/ui/button\";\nimport { useBlockContent, useLocale } from \"@/blocks/lib/content\";\nimport { fill, fillNodes, inSentence } from \"@/blocks/lib/format\";\nimport { Notice } from \"@/blocks/lib/notice\";\nimport {\n  SlotView,\n  SupportingDocuments as AttachmentSlots,\n  type UploadOutcome,\n} from \"@/blocks/request/attachment-slots\";\nimport type { CommandOutcome } from \"@/blocks/request/request-status\";\nimport { DocumentPreview } from \"@/blocks/documents/document-preview\";\nimport {\n  useDocumentSelection,\n  version,\n} from \"@/blocks/documents/document-selection\";\nimport type { DocumentSource } from \"@/blocks/documents/document-view\";\nimport { ErrorPanel } from \"@/blocks/shell/error-panel\";\nimport { splitRoute, useRoute } from \"@/blocks/shell/routing\";\nimport {\n  usePagesContent,\n  type PagesContent,\n} from \"@/blocks/pages/pages-content\";\nimport { useRegisterRoutes } from \"@/blocks/pages/register-routes\";\nimport {\n  recordPath,\n  useRegister,\n  type RegisterEntities,\n} from \"@/blocks/pages/record\";\n\nexport { useDocumentSelection };\n\n/** A record whose slots these are, at the revision it was read. */\nexport interface AttachmentsRecord {\n  entity: string;\n  id: string;\n  revision: string;\n}\n\n/** The entity-specific slot words from the served model, with app-wide fallbacks. */\nfunction attachmentLabel(\n  entities: RegisterEntities | null,\n  entity: string,\n  slot: string,\n  pages: PagesContent,\n): string {\n  const model =\n    entities &&\n    [\n      entities.record,\n      ...(entities.records ?? []),\n      ...(entities.requests ?? []),\n    ].find((candidate) => candidate.id === entity);\n  return (\n    model?.operations.attachments?.find((item) => item.slot === slot)?.label ??\n    pages.attachmentSlots[slot] ??\n    pages.attachmentSlotFallback\n  );\n}\n\n/** A slot's removal command, in the shape every command reads. */\nexport type RemovalOutcome = CommandOutcome & {\n  reset(): void;\n  submit(removeRef: string, expectedRevision: string): Promise<unknown>;\n};\n\n/**\n * A record's governed attachment slots, over `@/blocks/request/attachment-slots`.\n * The host lists only the slots this profile may read, and carries an upload\n * or remove reference only where the registry grants one, so the section\n * offers exactly what this person may do. Available PDFs and raster images\n * may be read in an inert, on-demand viewer.\n *\n * A slot's upload and removal are commands, one instance per slot, so they\n * are injected as hooks rather than as a single write: `useUpload` and\n * `useRemoval` already speak in `reference`, never the runtime's own attempt\n * id, which by convention only the host that names it may show a page.\n */\nexport function SupportingDocuments({\n  record,\n  slots,\n  readOnly = false,\n  onPreview,\n  openPdf,\n  useUpload,\n  useRemoval,\n  writesDisabled = false,\n  onWritingChange,\n}: {\n  record: AttachmentsRecord;\n  slots?: AttachmentSlot[];\n  readOnly?: boolean;\n  onPreview?: (slot: AttachmentSlot, trigger: HTMLButtonElement) => void;\n  /** Opens a PDF slot's bytes in the preview; without it, a PDF stays download-only. */\n  openPdf?: (\n    bytes: ArrayBuffer,\n    signal: AbortSignal,\n  ) => Promise<DocumentSource>;\n  useUpload: (slot: string) => UploadOutcome;\n  useRemoval: (slot: string) => RemovalOutcome;\n  /** Prevents a write while the record revision is being refreshed. */\n  writesDisabled?: boolean;\n  /** Reports writes for this record so another action cannot race them. */\n  onWritingChange?: (slot: string, writing: boolean) => void;\n}) {\n  const pages = usePagesContent();\n  const register = useRegister();\n  const attachmentHref = useAttachmentHref();\n  const selection = useDocumentSelection(slots);\n  if (!slots?.length) return null;\n  const owner = `${record.entity}:${record.id}`;\n  const href = (slot: string) => attachmentHref(record.entity, record.id, slot);\n  return (\n    <AttachmentSlots\n      slots={slots}\n      renderSlot={(slot) => (\n        <RecordSlot\n          record={record}\n          slot={slot}\n          readOnly={readOnly}\n          onPreview={onPreview ?? selection.select}\n          useUpload={useUpload}\n          useRemoval={useRemoval}\n          writesDisabled={writesDisabled}\n          onWritingChange={onWritingChange}\n        />\n      )}\n    >\n      {!onPreview && selection.slot?.file && (\n        <DocumentPreview\n          key={`${owner}:${selection.slot.slot}:${version(selection.slot.file)}`}\n          href={href(selection.slot.slot)}\n          file={selection.slot.file}\n          label={attachmentLabel(\n            register.entities,\n            record.entity,\n            selection.slot.slot,\n            pages,\n          )}\n          onClose={selection.close}\n          openPdf={openPdf}\n        />\n      )}\n    </AttachmentSlots>\n  );\n}\n\ninterface SlotProps {\n  slot: AttachmentSlot;\n  readOnly: boolean;\n  onPreview: (slot: AttachmentSlot, trigger: HTMLButtonElement) => void;\n}\n\n/**\n * A record's slot, removed at the revision the record was read. Binds this\n * slot's upload and removal commands, the register's own words for it, and\n * error display to the block's SlotView, which walks the choose/upload/\n * remove controls themselves.\n */\nfunction RecordSlot({\n  record,\n  useUpload,\n  useRemoval,\n  writesDisabled,\n  onWritingChange,\n  ...props\n}: SlotProps & {\n  record: AttachmentsRecord;\n  useUpload: (slot: string) => UploadOutcome;\n  useRemoval: (slot: string) => RemovalOutcome;\n  writesDisabled?: boolean;\n  onWritingChange?: (slot: string, writing: boolean) => void;\n}) {\n  const pages = usePagesContent(),\n    routes = useRegisterRoutes(),\n    register = useRegister(),\n    attachmentHref = useAttachmentHref(),\n    upload = useUpload(props.slot.slot),\n    removal = useRemoval(props.slot.slot);\n  const path =\n    register.entities &&\n    recordPath(routes, register.entities, record.entity, record.id);\n  return (\n    <SlotView\n      {...props}\n      upload={upload}\n      removal={removal}\n      remove={(removeRef) => removal.submit(removeRef, record.revision)}\n      downloadHref={attachmentHref(record.entity, record.id, props.slot.slot)}\n      reconcileHref={path ? `#${path}` : \"#/\"}\n      renderError={(error) => <ErrorPanel error={error} />}\n      slotLabel={(slot) =>\n        attachmentLabel(register.entities, record.entity, slot, pages)\n      }\n      typeLabel={(contentType) =>\n        pages.attachmentTypes[contentType] ?? contentType\n      }\n      statusNote={(status) =>\n        pages.attachmentStatus[status as keyof typeof pages.attachmentStatus]\n      }\n      canPreview={(contentType) => documentPreviewTypes.includes(contentType)}\n      writesDisabled={writesDisabled}\n      onWritingChange={onWritingChange}\n    />\n  );\n}\n\n/** One unresolved upload this session can still point to, in the shape every command reads. */\nexport interface PendingUploadItem {\n  key: string;\n  slot: string;\n  reference: string;\n  /** The entity of the resource the file was placed on; null for a first-version upload. */\n  entity: string | null;\n  resourceId: string;\n}\n\nexport interface PendingUploadsState {\n  live: readonly PendingUploadItem[];\n  /** Whether a previous session left an upload whose reference it took with it. */\n  orphaned: boolean;\n  forgetOrphaned: () => void;\n}\n\n/**\n * Every unresolved upload of this session, for the notice of writes that\n * need checking. The record or request that is open shows its own uploads\n * in their slots, so they are left out here; an upload from the first\n * marker version stays, since no slot claims it.\n */\nexport function PendingUploadsNotice({\n  usePending,\n}: {\n  /** This session's unresolved uploads; a page supplies this over its own host. */\n  usePending: () => PendingUploadsState;\n}) {\n  const pending = usePending();\n  if (!pending.live.length && !pending.orphaned) return null;\n  return <PendingUploads pending={pending} />;\n}\n\nfunction PendingUploads({ pending }: { pending: PendingUploadsState }) {\n  const pages = usePagesContent(),\n    block = useBlockContent(),\n    locale = useLocale(),\n    routes = useRegisterRoutes(),\n    register = useRegister(),\n    { path, query } = splitRoute(useRoute());\n  // Whether `open` is the page in view: the same path naming the same request entity.\n  const isPage = (open: string) => {\n    const target = splitRoute(open);\n    return (\n      target.path === path &&\n      target.query.get(\"request\") === query.get(\"request\")\n    );\n  };\n  const uploads = pending.live.flatMap((upload) => {\n    // A first-version upload names no entity; every such upload was on a\n    // request, from when a register had one request entity: the followed one.\n    // A later upload names its own entity, a request entity included.\n    const firstVersion = upload.entity === null;\n    const entity = firstVersion\n      ? register.entities?.followedRequest?.id\n      : upload.entity;\n    const open =\n      register.entities && entity\n        ? recordPath(routes, register.entities, entity, upload.resourceId)\n        : null;\n    // No slot claims a first-version upload, so it stays here on its own page.\n    return open && isPage(open) && !firstVersion ? [] : [{ upload, open }];\n  });\n  const previous = pending.orphaned;\n  if (!uploads.length && !previous) return null;\n  return (\n    <Notice tone=\"warning\" title={pages.attachmentPendingTitle}>\n      {uploads.map(({ upload, open }) => {\n        const label = attachmentLabel(\n          register.entities,\n          upload.entity ?? register.entities?.followedRequest?.id ?? \"\",\n          upload.slot,\n          pages,\n        );\n        return (\n          <div key={upload.key}>\n            <p>\n              {fill(\n                pages.attachmentPendingBody,\n                { document: inSentence(label, locale) },\n                locale,\n              )}\n            </p>\n            <p className=\"reference\">\n              {fillNodes(\n                block.labelled,\n                {\n                  label: block.receipt,\n                  value: <span className=\"font-mono\">{upload.reference}</span>,\n                },\n                locale,\n              )}\n            </p>\n            {open && (\n              <div className=\"actions\">\n                <Button render={<a href={`#${open}`} />} variant=\"outline\">\n                  {pages.attachmentPendingOpen}\n                </Button>\n              </div>\n            )}\n          </div>\n        );\n      })}\n      {previous && (\n        <>\n          <p>{pages.attachmentPendingPrevious}</p>\n          <div className=\"actions\">\n            <Button variant=\"ghost\" onClick={pending.forgetOrphaned}>\n              {pages.leaveRecovery}\n            </Button>\n          </div>\n        </>\n      )}\n    </Notice>\n  );\n}\n",
      "type": "registry:block",
      "target": "@components/pages/record-attachments.tsx"
    }
  ],
  "type": "registry:block"
}