{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "pages-record-detail",
  "title": "Record detail page",
  "description": "One record of the register's record entity: its sections, a change action, its revision history and the requests already made on it.",
  "dependencies": [
    "@registrystack/app-runtime@~0.43.0-next.0",
    "lucide-react@1.43.0"
  ],
  "registryDependencies": [
    "@registrystack/pages-record",
    "@registrystack/pages-content",
    "@registrystack/pages-register-routes",
    "@registrystack/record-sections",
    "@registrystack/shell-page-heading",
    "@registrystack/shell-back-link",
    "@registrystack/shell-loading",
    "@registrystack/shell-error-panel",
    "@registrystack/shell-status-badge",
    "@registrystack/request-status",
    "@registrystack/ui-button",
    "@registrystack/field-renderers",
    "@registrystack/lib-content",
    "@registrystack/lib-format",
    "@registrystack/record-table",
    "@registrystack/pages-record-route-query",
    "@registrystack/casework-content",
    "@registrystack/casework-shared"
  ],
  "files": [
    {
      "path": "pages/record-detail-page.tsx",
      "content": "import { useId } from \"react\";\nimport { ArrowRight, Plus } from \"lucide-react\";\nimport {\n  relatedFields,\n  type EntityModel,\n  type FieldModel,\n  type RecordRevision,\n  type RecordView,\n} from \"@registrystack/app-runtime\";\nimport {\n  useModel,\n  useRecord,\n  useRecordHistory,\n  useRecords,\n  useRecordsOf,\n} from \"@registrystack/app-runtime/react\";\nimport { Button } from \"@/components/ui/button\";\nimport { FieldValue } from \"@/blocks/fields/field-value\";\nimport { InPhrase } from \"@/blocks/fields/values\";\nimport { useLocale } from \"@/blocks/lib/content\";\nimport { fill } from \"@/blocks/lib/format\";\nimport { PageHeading } from \"@/blocks/shell/page-heading\";\nimport { BackLink } from \"@/blocks/shell/back-link\";\nimport { Loading } from \"@/blocks/shell/loading\";\nimport { ErrorPanel } from \"@/blocks/shell/error-panel\";\nimport { StatusBadge } from \"@/blocks/shell/status-badge\";\nimport { approvedNotApplied } from \"@/blocks/request/request-status\";\nimport { RecordSections } from \"@/blocks/record/record-sections\";\nimport { RecordTable } from \"@/blocks/record/record-table\";\nimport {\n  backToListOf,\n  createWords,\n  usePagesContent,\n} from \"@/blocks/pages/pages-content\";\nimport { formRoute, listRoute } from \"@/blocks/pages/record-route-query\";\nimport { useRegisterRoutes } from \"@/blocks/pages/register-routes\";\nimport { useCaseworkContent } from \"@/blocks/casework/casework-content\";\nimport { unavailableText } from \"@/blocks/casework/shared\";\nimport {\n  entityRoutes,\n  fieldOf,\n  recordTitle,\n  RecordEntityGate,\n  requestRoute,\n  requestsTargeting,\n  sameAnswer,\n  type RegisterEntities,\n} from \"@/blocks/pages/record\";\n\n/**\n * One record of one record entity, the register's own when `entity` is left\n * out, in the sections the session model gives it, with the governed actions\n * its record read offers, the records that refer to it, its history, the\n * requests its record read offers and the requests already made on it, of\n * every request entity that targets it.\n */\nexport function RecordDetailPage({\n  id,\n  entity,\n}: {\n  id: string;\n  /** The entity's id; the register's own record entity when left out. */\n  entity?: string;\n}) {\n  return (\n    <RecordEntityGate entity={entity}>\n      {(entities, model) => (\n        <RecordDetail entities={entities} entity={model} id={id} />\n      )}\n    </RecordEntityGate>\n  );\n}\n\nfunction RecordDetail({\n  entities,\n  entity,\n  id,\n}: {\n  entities: RegisterEntities;\n  entity: EntityModel;\n  id: string;\n}) {\n  const pages = usePagesContent(),\n    unavailableWords = useCaseworkContent(),\n    locale = useLocale(),\n    appRoutes = useRegisterRoutes(),\n    routes = entityRoutes(appRoutes, entities, entity.id),\n    ownEntity = entity.id === entities.record.id,\n    requests = requestsTargeting(entities, entity.id),\n    query = useRecord(entity.id, id);\n  if (query.isPending) return <Loading />;\n  if (query.error || !query.data)\n    return (\n      <ErrorPanel error={query.error} retry={() => void query.refetch()} />\n    );\n  const record = query.data;\n  // One button per request entity the session may open a request of for this\n  // record; a register with one request entity keeps the generic wording.\n  const changes = requests.flatMap((item) => {\n    const create = record.actions.find(\n      (action) => action.name === \"create\" && action.entity === item.id,\n    );\n    return create ? [{ request: item, create }] : [];\n  });\n  // A governed action is offered only where the app names a form for it. One\n  // the registry would refuse for this record now is shown disabled, with the\n  // registry's reason, never hidden.\n  const governed = record.actions.flatMap((action) =>\n    action.name === \"invoke\" && action.actionId && routes?.action\n      ? [\n          {\n            id: action.actionId,\n            label: action.label ?? action.actionId,\n            href: `#${routes.action(id, action.actionId)}`,\n            unavailable: action.availability\n              ? unavailableText(unavailableWords, action.availability, locale)\n              : undefined,\n          },\n        ]\n      : [],\n  );\n  const changeButtons = changes.map(({ request: item, create }) => (\n    <Button\n      key={item.id}\n      render={\n        <a\n          href={`#${requestRoute(entities, appRoutes.changeRecord(id), item.id)}`}\n        />\n      }\n    >\n      {requests.length === 1\n        ? pages.requestChange\n        : createWords(\n            pages,\n            \"requestChangeOf\",\n            create.label,\n            item.label,\n            locale,\n          )}\n      <ArrowRight />\n    </Button>\n  ));\n  return (\n    <>\n      <BackLink href={routes?.records ?? appRoutes.records}>\n        {backToListOf(pages, entity, ownEntity, locale)}\n      </BackLink>\n      <PageHeading\n        eyebrow={entity.label}\n        title={recordTitle(entity, record, locale) ?? entity.label}\n        action={\n          governed.length > 0 || changeButtons.length > 1 ? (\n            <div className=\"actions\">\n              {changeButtons}\n              {governed.map((action) => (\n                <GovernedAction key={action.id} {...action} />\n              ))}\n            </div>\n          ) : (\n            changeButtons[0]\n          )\n        }\n      />\n      <div\n        className={\n          entity.operations.revisions\n            ? \"record-layout\"\n            : \"record-layout record-layout-single\"\n        }\n      >\n        <div className=\"record-main\">\n          <RecordSections entity={entity} record={record} />\n          <p className=\"muted\">{pages.recordNotice}</p>\n          {routes &&\n            relatedFields(entities.records ?? [], entity.id).map(\n              ({ related, field, several }) => (\n                <RelatedRecords\n                  key={`${related.id}:${field.id}`}\n                  entities={entities}\n                  entity={entity}\n                  id={id}\n                  related={related}\n                  field={field}\n                  several={several}\n                  returnPath={routes.record(id)}\n                  offered={governed.map((action) => action.id)}\n                  unavailable={record.relatedActionAvailability}\n                />\n              ),\n            )}\n          {requests.length > 0 && (\n            <RecordRequestsBlock\n              entities={entities}\n              requests={requests}\n              id={id}\n            />\n          )}\n        </div>\n        {/* Absent where the profile has no revision access. */}\n        {entity.operations.revisions && (\n          <aside className=\"record-aside\" aria-label={pages.historyHeading}>\n            <RecordHistoryBlock\n              entity={entity}\n              id={id}\n              currentRevision={record.revision}\n            />\n          </aside>\n        )}\n      </div>\n    </>\n  );\n}\n\n/** How many related records a section lists before it says more exist and links to the rest. */\nconst RELATED_SHOWN = 5;\n\n/**\n * The records of another entity that refer to this one through `field`,\n * linked to their own pages, with the creates and governed actions the list\n * offers for adding one that already refers to this record, less those the\n * record page already offers. Where the registry does not advertise the\n * filter for this profile, the section is absent rather than an error.\n */\nfunction RelatedRecords({\n  entities,\n  entity,\n  id,\n  related,\n  field,\n  several,\n  returnPath,\n  offered,\n  unavailable,\n}: {\n  entities: RegisterEntities;\n  entity: EntityModel;\n  id: string;\n  related: EntityModel;\n  field: FieldModel;\n  several: boolean;\n  returnPath: string;\n  /** The ids of the governed actions the record page itself offers. */\n  offered: readonly string[];\n  /** The registry's answers that it would refuse an action with this record, by action id. */\n  unavailable: RecordView[\"relatedActionAvailability\"];\n}) {\n  const pages = usePagesContent(),\n    unavailableWords = useCaseworkContent(),\n    locale = useLocale(),\n    appRoutes = useRegisterRoutes(),\n    routes = entityRoutes(appRoutes, entities, related.id),\n    query = useRecords(related.id, { filters: { [field.id]: id } });\n  if (!routes) return null;\n  const heading = several\n    ? fill(\n        pages.relatedRecordsBy,\n        { records: related.pluralLabel, field: field.label },\n        locale,\n      )\n    : related.pluralLabel;\n  if (query.error) {\n    if (query.unsupported) return null;\n    return (\n      <section className=\"card section-card\">\n        <h2>{heading}</h2>\n        <div className=\"section-card-body\">\n          <ErrorPanel error={query.error} retry={() => void query.refetch()} />\n        </div>\n      </section>\n    );\n  }\n  if (query.isPending || !query.data) return null;\n  const create = query.data.actions?.find(\n    (action) => action.name === \"create\" && action.entity === related.id,\n  );\n  // An action that adds one of these records is offered here when it takes\n  // this record as an input; each such input is preset with it. One the\n  // record page already offers is not offered twice. One the registry would\n  // refuse with this record is shown disabled, with its reason, never hidden.\n  const governed = (query.data.actions ?? []).flatMap((action) => {\n    if (\n      action.name !== \"invoke\" ||\n      action.entity !== related.id ||\n      !action.actionId ||\n      offered.includes(action.actionId) ||\n      !routes.recordAction\n    )\n      return [];\n    const preset = Object.fromEntries(\n      (action.fields ?? [])\n        .filter((input) => input.reference?.entity === entity.id)\n        .map((input) => [input.id, id]),\n    );\n    return Object.keys(preset).length === 0\n      ? []\n      : [\n          {\n            id: action.actionId,\n            label: action.label ?? action.actionId,\n            href: `#${formRoute(routes.recordAction(action.actionId), preset, returnPath)}`,\n            unavailable: unavailable?.[action.actionId]\n              ? unavailableText(\n                  unavailableWords,\n                  unavailable[action.actionId],\n                  locale,\n                )\n              : undefined,\n          },\n        ];\n  });\n  const columns = related.list.columns\n    .filter((column) => column !== field.id)\n    .map((column) => fieldOf(related, column))\n    .filter((column) => column !== undefined);\n  const items = query.data.items.slice(0, RELATED_SHOWN);\n  const more =\n    query.data.items.length > RELATED_SHOWN || query.data.nextCursor !== undefined;\n  return (\n    <section className=\"card section-card\">\n      <h2>{heading}</h2>\n      <div className=\"section-card-body\">\n        {items.length === 0 ? (\n          !create &&\n          governed.length === 0 && (\n            <p className=\"muted\">{pages.relatedEmpty}</p>\n          )\n        ) : (\n          <>\n            <RecordTable\n              caption={heading}\n              columns={columns}\n              linkColumn={\n                columns.find((column) => column.id === related.title) ??\n                columns[0]\n              }\n              records={items}\n              recordHref={(item) => `#${routes.record(item.id)}`}\n              viewLabel={(item) => recordTitle(related, item, locale) ?? item.id}\n            />\n            {more && (\n              <p className=\"muted related-bounds\">\n                {fill(pages.relatedBounds, { count: items.length }, locale)}\n              </p>\n            )}\n            <a\n              className=\"related-all\"\n              href={`#${listRoute(routes.records, { filters: { [field.id]: id } })}`}\n            >\n              {fill(pages.relatedShowAll, { label: related.pluralLabel }, locale)}\n              <ArrowRight />\n            </a>\n          </>\n        )}\n        {(create || governed.length > 0) && (\n          <div className=\"actions\">\n            {create && (\n              <Button\n                variant=\"outline\"\n                render={\n                  <a\n                    href={`#${formRoute(routes.createRecord, { [field.id]: id }, returnPath)}`}\n                  />\n                }\n              >\n                <Plus />\n                {createWords(\n                  pages,\n                  \"addRecord\",\n                  create.label,\n                  related.label,\n                  locale,\n                )}\n              </Button>\n            )}\n            {governed.map((action) => (\n              <GovernedAction key={action.id} {...action} />\n            ))}\n          </div>\n        )}\n      </div>\n    </section>\n  );\n}\n\n/**\n * A governed action: a link to its form or, where the registry would refuse\n * it now, a disabled button with the registry's reason beside it.\n */\nfunction GovernedAction({\n  label,\n  href,\n  unavailable,\n}: {\n  label: string;\n  href: string;\n  unavailable?: string;\n}) {\n  const reason = useId();\n  if (!unavailable)\n    return (\n      <Button variant=\"outline\" render={<a href={href} />}>\n        {label}\n      </Button>\n    );\n  return (\n    <span className=\"action-unavailable\">\n      <Button variant=\"outline\" disabled aria-describedby={reason}>\n        {label}\n      </Button>\n      <span id={reason} className=\"muted\">\n        {unavailable}\n      </span>\n    </span>\n  );\n}\n\n/**\n * The time a revision was recorded, in the reader's own zone and named, read\n * like every other time the kit shows (\"2 October 2026 at 18:53 BST\") and\n * written in `locale`; to the second when `seconds`, so revisions recorded in\n * one minute read apart.\n */\nfunction recordedAt(value: string, locale: string, seconds = false): string {\n  const when = new Date(value);\n  if (Number.isNaN(when.valueOf())) return value;\n  return new Intl.DateTimeFormat(locale, {\n    day: \"numeric\",\n    month: \"long\",\n    year: \"numeric\",\n    hour: \"2-digit\",\n    minute: \"2-digit\",\n    ...(seconds ? { second: \"2-digit\" } : {}),\n    hour12: false,\n    timeZoneName: \"short\",\n  }).format(when);\n}\n\n/** Whether two of the revisions read the same to the minute in `locale`. */\nfunction sharesMinute(\n  revisions: readonly RecordRevision[],\n  locale: string,\n): boolean {\n  const minutes = revisions\n    .filter((revision) => revision.recordedAt)\n    .map((revision) => recordedAt(revision.recordedAt!, locale));\n  return new Set(minutes).size < minutes.length;\n}\n\n/**\n * The states the record has held, newest first, each with the values that\n * changed from the one before it, in the model's own words. A history the\n * host cannot read shows the wording for a missing history and nothing else.\n */\nfunction RecordHistoryBlock({\n  entity,\n  id,\n  currentRevision,\n}: {\n  entity: EntityModel;\n  id: string;\n  /** The revision the record holds now, to mark its entry. */\n  currentRevision: string;\n}) {\n  const pages = usePagesContent(),\n    locale = useLocale(),\n    history = useRecordHistory(entity.id, id),\n    seconds = sharesMinute(history.data?.items ?? [], locale);\n  return (\n    <section className=\"card section-card\">\n      <h2>{pages.historyHeading}</h2>\n      <div className=\"section-card-body\">\n        {history.isPending ? (\n          <Loading />\n        ) : history.error || !history.data ? (\n          <>\n            <h3>{pages.historyGapTitle}</h3>\n            <p>{pages.historyGapBody}</p>\n          </>\n        ) : history.data.items.length === 0 ? (\n          <p className=\"muted\">{pages.historyNone}</p>\n        ) : (\n          <>\n            <p className=\"muted\">{pages.historyIntro}</p>\n            <ol className=\"history-list\">\n              {history.data.items.map((revision, index) => (\n                <HistoryEntry\n                  key={revision.revision}\n                  entity={entity}\n                  revision={revision}\n                  earlier={history.data.items[index + 1]}\n                  seconds={seconds}\n                  current={revision.revision === currentRevision}\n                />\n              ))}\n            </ol>\n          </>\n        )}\n      </div>\n    </section>\n  );\n}\n\n/** One revision: when it was recorded and what it changed from `earlier`; every value it holds when there is no earlier one. */\nfunction HistoryEntry({\n  entity,\n  revision,\n  earlier,\n  seconds,\n  current,\n}: {\n  entity: EntityModel;\n  revision: RecordRevision;\n  earlier?: RecordRevision;\n  seconds: boolean;\n  current: boolean;\n}) {\n  const pages = usePagesContent();\n  const locale = useLocale();\n  const changed = entity.fields.filter((field) =>\n    earlier\n      ? !sameAnswer(revision.values[field.id], earlier.values[field.id])\n      : revision.values[field.id] !== undefined &&\n        revision.values[field.id] !== null,\n  );\n  return (\n    <li>\n      {(revision.recordedAt || current) && (\n        <p className=\"history-when\">\n          {revision.recordedAt && (\n            <time dateTime={revision.recordedAt}>\n              {recordedAt(revision.recordedAt, locale, seconds)}\n            </time>\n          )}\n          {current && (\n            <span className=\"badge badge-current\">{pages.historyCurrent}</span>\n          )}\n        </p>\n      )}\n      {changed.length === 0 ? (\n        <p className=\"muted\">{pages.historyUnchanged}</p>\n      ) : (\n        <dl className=\"facts\">\n          {changed.map((field) => (\n            <div className=\"definition\" key={field.id}>\n              <dt>{field.label}</dt>\n              <dd>\n                <FieldValue field={field} value={revision.values[field.id]} />\n                {earlier && (\n                  <span className=\"muted\">\n                    {\" \"}\n                    ({pages.historyWas}{\" \"}\n                    <InPhrase>\n                      <FieldValue\n                        field={field}\n                        value={earlier.values[field.id]}\n                      />\n                    </InPhrase>\n                    )\n                  </span>\n                )}\n              </dd>\n            </div>\n          ))}\n        </dl>\n      )}\n    </li>\n  );\n}\n\n/**\n * The record's requests of every request entity that targets it, each linked\n * to its own page and naming its type. The model decides which request kinds\n * can be listed by target. The others link to their ordinary request list,\n * while an advertised read that fails shows its refusal with a retry.\n */\nfunction RecordRequestsBlock({\n  entities,\n  requests,\n  id,\n}: {\n  entities: RegisterEntities;\n  requests: readonly EntityModel[];\n  id: string;\n}) {\n  const pages = usePagesContent(),\n    locale = useLocale(),\n    routes = useRegisterRoutes(),\n    targetListable = requests.filter(\n      (request) =>\n        request.operations.list === true &&\n        request.request?.listByTarget === true,\n    ),\n    browseable = requests.filter(\n      (request) =>\n        request.operations.list === true &&\n        request.request?.listByTarget !== true,\n    ),\n    queries = useRecordsOf(\n      targetListable.map((request) => request.id),\n      { target: id },\n    ),\n    reads = targetListable.map((request, index) => ({\n      request,\n      query: queries[index]!,\n    }));\n  if (targetListable.length === 0 && browseable.length === 0) return null;\n  const pending = reads.some(({ query }) => query.isPending);\n  if (pending && browseable.length === 0) return null;\n  const failed = reads.filter(({ query }) => query.error);\n  const items = reads.flatMap(({ request, query }) =>\n    (query.data?.items ?? []).map((item) => ({ request, item })),\n  );\n  const refusals = failed.map(({ request, query }) => (\n    <ErrorPanel\n      key={request.id}\n      error={query.error}\n      retry={() => void query.refetch()}\n    />\n  ));\n  if (failed.length === reads.length && browseable.length === 0)\n    return (\n      <section className=\"card section-card\">\n        <h2>{pages.recordRequestsHeading}</h2>\n        <div className=\"section-card-body\">{refusals}</div>\n      </section>\n    );\n  return (\n    <section className=\"card section-card\">\n      <h2>{pages.recordRequestsHeading}</h2>\n      <div className=\"section-card-body\">\n        <p className=\"sr-only\">{pages.recordRequestsNote}</p>\n        {items.length === 0 &&\n        !pending &&\n        failed.length < reads.length &&\n        browseable.length === 0 ? (\n          <p className=\"muted\">{pages.recordRequestsEmpty}</p>\n        ) : items.length > 0 ? (\n          <ul className=\"value-list\">\n            {items.map(({ request, item }) => {\n              const state = item.request?.state;\n              return (\n                <li key={`${request.id}:${item.id}`}>\n                  <a\n                    className=\"record-link\"\n                    href={`#${requestRoute(entities, routes.request(item.id), request.id)}`}\n                  >\n                    {recordTitle(request, item, locale) ?? pages.unnamedRequest}\n                  </a>{\" \"}\n                  {state && (\n                    <StatusBadge\n                      state={state}\n                      served={request.request?.stateLabels[state]}\n                    />\n                  )}\n                  {\" \"}\n                  <span className=\"muted\">{request.label}</span>\n                  {item.request?.applyOffered &&\n                    approvedNotApplied(item.request) && (\n                      <p className=\"muted\">{pages.recordRequestApply}</p>\n                    )}\n                </li>\n              );\n            })}\n          </ul>\n        ) : null}\n        {browseable.length > 0 && (\n          <ul className=\"value-list\">\n            {browseable.map((request) => (\n              <li key={request.id}>\n                <a\n                  className=\"record-link\"\n                  href={`#${requestRoute(entities, routes.requests, request.id)}`}\n                >\n                  {fill(\n                    pages.recordRequestsBrowse,\n                    { label: request.pluralLabel },\n                    locale,\n                  )}\n                </a>\n              </li>\n            ))}\n          </ul>\n        )}\n        {refusals}\n      </div>\n    </section>\n  );\n}\n",
      "type": "registry:block",
      "target": "@components/pages/record-detail-page.tsx"
    }
  ],
  "type": "registry:block"
}