{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "pages-record",
  "title": "Record model helpers",
  "description": "Reads a session model's record and request entities, the fields a request writes and what they hold now, checks a proposed change's answers against the fields' schema, and shows the unresolved write and unavailable-write notices a record or request page needs.",
  "dependencies": [
    "@registrystack/app-runtime@~0.43.0-next.0"
  ],
  "registryDependencies": [
    "@registrystack/lib-content",
    "@registrystack/lib-notice",
    "@registrystack/shell-content",
    "@registrystack/shell-error-panel",
    "@registrystack/shell-routing",
    "@registrystack/pages-content",
    "@registrystack/pages-register-routes",
    "@registrystack/pages-task-feedback",
    "@registrystack/ui-button",
    "@registrystack/shell-loading",
    "@registrystack/lib-format"
  ],
  "files": [
    {
      "path": "pages/record.tsx",
      "content": "import type { ReactNode } from \"react\";\nimport {\n  entityTitle,\n  unavailableError,\n  type EntityModel,\n  type FieldModel,\n  type JsonValue,\n  type RecordView,\n  type RequestView,\n} from \"@registrystack/app-runtime\";\nimport {\n  useModel,\n  usePendingRecordWrite,\n  type RecoveryReference,\n} from \"@registrystack/app-runtime/react\";\nimport { Button } from \"@/components/ui/button\";\nimport { useBlockContent, useLocale } from \"@/blocks/lib/content\";\nimport { fillNodes } from \"@/blocks/lib/format\";\nimport { Notice } from \"@/blocks/lib/notice\";\nimport { ErrorPanel } from \"@/blocks/shell/error-panel\";\nimport { Loading } from \"@/blocks/shell/loading\";\nimport { useShellContent } from \"@/blocks/shell/shell-content\";\nimport { navigate, useRoute } from \"@/blocks/shell/routing\";\nimport {\n  useRegisterRoutes,\n  type EntityRoutes,\n  type RegisterRoutes,\n} from \"@/blocks/pages/register-routes\";\nimport { usePagesContent } from \"@/blocks/pages/pages-content\";\nimport type { TaskFeedbackState } from \"@/blocks/pages/task-feedback\";\n\n/**\n * The register's entities as the session model names them, and the words a\n * record's values are shown in. Which entity is which comes from the model,\n * never from an entity id in this code.\n */\nexport interface RegisterEntities {\n  /** The records this service is about: the first record entity a request changes. */\n  record: EntityModel;\n  /** The request that changes one of those records, when the session has one. */\n  request?: EntityModel;\n  /**\n   * The requests the session lists and follows: `request`, or else the model's\n   * only request entity. A profile that may follow its requests without reading\n   * the records they change sees that request target none of them.\n   */\n  followedRequest?: EntityModel;\n  /**\n   * Every record entity the model holds, the register's own among them. The\n   * staff nav offers the listable ones as places when the model names none.\n   */\n  records?: readonly EntityModel[];\n  /** Every request entity the model names, `request` and `followedRequest` among them. */\n  requests?: readonly EntityModel[];\n}\n\n/** Whether a request starts from or patches a record of this entity. */\nfunction belongsToRecord(request: EntityModel, entity: string): boolean {\n  return (\n    request.request?.entry?.entity === entity ||\n    request.request?.targets.some(\n      (target) => target.entity === entity && target.operation === \"patch\",\n    ) === true\n  );\n}\n\n/** The record and request entities of a session model, or null when it has no record entity. */\nexport function registerEntities(\n  entities: EntityModel[],\n): RegisterEntities | null {\n  const requests = entities.filter((entity) => entity.kind === \"request\");\n  const targeted = (entity: EntityModel) =>\n    requests.find((request) => belongsToRecord(request, entity.id));\n  const records = entities.filter((entity) => entity.kind === \"record\");\n  const record = records.find(targeted) ?? records[0];\n  if (!record) return null;\n  const request = targeted(record);\n  return {\n    record,\n    request,\n    followedRequest:\n      request ?? (requests.length === 1 ? requests[0] : undefined),\n    records,\n    requests,\n  };\n}\n\n/** The request entities whose requests change a record of `entity`, in the model's order. */\nexport function requestsTargeting(\n  entities: RegisterEntities,\n  entity: string,\n): readonly EntityModel[] {\n  const requests =\n    entities.requests ?? (entities.request ? [entities.request] : []);\n  return requests.filter((request) => belongsToRecord(request, entity));\n}\n\n/** The request entities whose ordinary list this session may read. */\nexport function listableRequests(\n  entities: RegisterEntities,\n): readonly EntityModel[] {\n  const requests =\n    entities.requests ?? (entities.request ? [entities.request] : []);\n  return requests.filter((request) => request.operations.list === true);\n}\n\n/** Request lists the app offers as standalone places; contextual-only lists keep their routes and authority. */\nexport function navigationRequests(\n  entities: RegisterEntities,\n): readonly EntityModel[] {\n  return listableRequests(entities).filter(\n    (request) => request.navigation !== false,\n  );\n}\n\n/** The list that keeps the plain request route, else the first list served. */\nexport function defaultListRequest(\n  entities: RegisterEntities,\n): EntityModel | undefined {\n  const requests = listableRequests(entities);\n  return (\n    requests.find((request) => request.id === entities.followedRequest?.id) ??\n    requests[0]\n  );\n}\n\n/** The query parameter that names the request entity a request route is about. */\nconst REQUEST_PARAM = \"request\";\n\n/**\n * `path` for a request of `request`: the followed entity's requests keep the\n * plain path, any other names its entity in the query, so one set of request\n * routes serves every request entity.\n */\nexport function requestRoute(\n  entities: RegisterEntities,\n  path: string,\n  request: string,\n): string {\n  return request === entities.followedRequest?.id\n    ? path\n    : `${path}?${REQUEST_PARAM}=${encodeURIComponent(request)}`;\n}\n\n/** The request entity a request route names in its query, else the followed one. */\nexport function routedRequest(\n  entities: RegisterEntities,\n  query: URLSearchParams,\n): EntityModel | undefined {\n  const named = query.get(REQUEST_PARAM);\n  return named === null\n    ? entities.followedRequest\n    : entities.requests?.find((request) => request.id === named);\n}\n\n/** The session model's register entities; `entities` is null until read, or when absent. */\nexport function useRegister() {\n  const model = useModel();\n  return {\n    ...model,\n    entities: model.data ? registerEntities(model.data.entities) : null,\n  };\n}\n\n/**\n * The routes of one record entity: the register's own record entity keeps the\n * register's routes, any other the app's `entity` routes. Null for an entity\n * the session reads no records of, or where the app names no routes for it.\n */\nexport function entityRoutes(\n  routes: RegisterRoutes,\n  entities: RegisterEntities,\n  entity: string,\n): EntityRoutes | null {\n  if (entity === entities.record.id)\n    return {\n      records: routes.records,\n      createRecord: routes.createRecord,\n      record: routes.record,\n      recordAction: routes.recordAction,\n      action: routes.action,\n    };\n  if (!entities.records?.some((item) => item.id === entity)) return null;\n  return routes.entity?.(entity) ?? null;\n}\n\n/**\n * The route a record opens on: a request on its request page (naming its\n * request entity unless it is the followed one), a record of any\n * record entity on that entity's record page, and null for an entity this app\n * has no page for.\n */\nexport function recordPath(\n  routes: RegisterRoutes,\n  entities: RegisterEntities,\n  entity: string,\n  id: string,\n): string | null {\n  if (\n    entity === entities.followedRequest?.id ||\n    entities.requests?.some((request) => request.id === entity)\n  )\n    return requestRoute(entities, routes.request(id), entity);\n  return entityRoutes(routes, entities, entity)?.record(id) ?? null;\n}\n\n/**\n * The register's entities and one record entity of the page's own: the\n * register's record entity when `entityId` is left out, else the record entity\n * the model names. `entity` is undefined where the model has no such entity.\n */\nexport function useRecordEntity(entityId?: string) {\n  const register = useRegister();\n  const entities = register.entities;\n  const entity = !entities\n    ? undefined\n    : entityId === undefined\n      ? entities.record\n      : entities.records?.find((item) => item.id === entityId);\n  return { ...register, entity };\n}\n\n/**\n * The gate every record page stands behind: loading while the model is read,\n * a refusal with a retry when it cannot be, and the unavailable refusal for\n * an entity it does not carry. Once through, `children` gets the register's\n * entities and the page's own entity.\n */\nexport function RecordEntityGate({\n  entity: entityId,\n  children,\n}: {\n  /** The page's entity id; the register's own record entity when left out. */\n  entity?: string;\n  children: (entities: RegisterEntities, entity: EntityModel) => ReactNode;\n}) {\n  const register = useRecordEntity(entityId);\n  const shell = useShellContent();\n  if (register.isPending) return <Loading />;\n  if (register.error)\n    return (\n      <ErrorPanel\n        error={register.error}\n        retry={() => void register.refetch()}\n      />\n    );\n  // A model read in full that holds no record type the session reads.\n  if (!register.entities || !register.entity)\n    return <ErrorPanel error={unavailableError(shell.unavailable)} />;\n  return <>{children(register.entities, register.entity)}</>;\n}\n\n/**\n * The id of the readable record that gives a request its page context. A\n * declared entry wins over an effect target because an Action may create a\n * different record from the one where the request started.\n */\nexport function readableTarget(\n  entities: RegisterEntities,\n  request: RequestView | undefined,\n): string {\n  const target = request?.entry ?? request?.target;\n  return target &&\n    target.entity === entities.record.id &&\n    target.available !== false\n    ? target.id\n    : \"\";\n}\n\n/** Whether two values are the same answer; a list is the same in any order. */\nexport function sameAnswer(\n  left: JsonValue | undefined,\n  right: JsonValue | undefined,\n): boolean {\n  if (Array.isArray(left) && Array.isArray(right))\n    return (\n      JSON.stringify(left.map((item) => JSON.stringify(item)).sort()) ===\n      JSON.stringify(right.map((item) => JSON.stringify(item)).sort())\n    );\n  return JSON.stringify(left) === JSON.stringify(right);\n}\n\nexport function fieldOf(\n  entity: EntityModel,\n  id: string,\n): FieldModel | undefined {\n  return entity.fields.find((field) => field.id === id);\n}\n\n/**\n * The words a record is named by: its title template or title field, or\n * undefined when it has neither. A calendar date in it is written in `locale`.\n */\nexport function recordTitle(\n  entity: EntityModel,\n  record: RecordView,\n  locale: string,\n): string | undefined {\n  return entityTitle(entity, (field) => record.values[field.id], locale);\n}\n\n/**\n * Words for a coded value: the content's own wording first, then the word the\n * model carries for the field's option, and the raw code only when neither exists.\n */\nexport function useOptionLabel(): (field: FieldModel, code: string) => string {\n  const c = useBlockContent();\n  return (field, code) =>\n    c.terms[code] ??\n    field.options?.find((option) => option.value === code)?.label ??\n    code;\n}\n\n/** The refusal shown where the session is offered no write for this request. */\nexport function UnavailableWrite() {\n  const c = useShellContent();\n  return <ErrorPanel error={unavailableError(c.unavailable)} />;\n}\n\n/**\n * The state a record or request write task exposes to its page: the outcome\n * `TaskFeedback` shows, plus the lock and field errors a form checks before\n * letting the session submit again. Generic over the command's input, so a\n * page can instantiate it against whichever write it hosts.\n */\nexport interface RecordTaskState<Input> extends TaskFeedbackState {\n  locked: boolean;\n  fieldErrors: Readonly<Record<string, string>>;\n  /** The write was refused because the record changed since it was read. */\n  staleConflict?: boolean;\n  /** Clears the refusal so the same form can send again. */\n  reset?: () => void;\n  submit: (input: Input) => Promise<unknown>;\n}\n\n/**\n * What checking a pending write found: its own identifier, ready to show as a\n * support reference, and the actions this session has for it. The identifier\n * a fresh check or retry runs against is an implementation detail of the\n * write itself, never a page's own concern, so a page's `useRecovery` hook\n * carries it in under this generic name.\n */\nexport interface RecoveryOutcome {\n  reference: string | null;\n  busy: boolean;\n  unknown: boolean;\n  error: unknown;\n  check: () => void;\n  retry: () => void;\n  leave: () => void;\n}\n\n/** The unresolved submission of this session that needs checking. */\nexport function RecoveryNotice({\n  useRecovery,\n}: {\n  /** Checks a pending write's outcome; a page supplies this over its own host. */\n  useRecovery: (\n    reference: RecoveryReference,\n    options: {\n      onSettled: () => void;\n      open: (resource: { id: string; entity: string }) => void;\n    },\n  ) => RecoveryOutcome;\n}) {\n  const route = useRoute();\n  const { reference, settled } = usePendingRecordWrite(route);\n  if (!reference) return null;\n  return (\n    <PendingRecovery\n      reference={reference}\n      onSettled={settled}\n      useRecovery={useRecovery}\n    />\n  );\n}\n\nfunction PendingRecovery({\n  reference,\n  onSettled,\n  useRecovery,\n}: {\n  reference: RecoveryReference;\n  onSettled: () => void;\n  useRecovery: (\n    reference: RecoveryReference,\n    options: {\n      onSettled: () => void;\n      open: (resource: { id: string; entity: string }) => void;\n    },\n  ) => RecoveryOutcome;\n}) {\n  const shell = useShellContent(),\n    pages = usePagesContent(),\n    block = useBlockContent(),\n    locale = useLocale(),\n    routes = useRegisterRoutes(),\n    register = useRegister();\n  const outcome = useRecovery(reference, {\n    onSettled,\n    /** A settled write opens on the record it wrote. */\n    open(resource) {\n      const path =\n        register.entities &&\n        recordPath(routes, register.entities, resource.entity, resource.id);\n      if (path) navigate(path);\n    },\n  });\n  return (\n    <Notice tone=\"warning\" title={shell.recoveryTitle}>\n      <p>\n        {outcome.reference ? pages.recoveryBody : shell.previousContextBody}\n      </p>\n      {outcome.reference && (\n        <p className=\"reference\">\n          {fillNodes(\n            block.labelled,\n            {\n              label: block.receipt,\n              value: <span className=\"font-mono\">{outcome.reference}</span>,\n            },\n            locale,\n          )}\n        </p>\n      )}\n      <div className=\"actions\">\n        {outcome.reference ? (\n          <Button\n            variant=\"outline\"\n            onClick={() => void outcome.check()}\n            disabled={outcome.busy}\n          >\n            {pages.checkOutcome}\n          </Button>\n        ) : (\n          <Button render={<a href={`#${routes.requests}`} />} variant=\"outline\">\n            {block.reconcile}\n          </Button>\n        )}\n        {outcome.reference && outcome.unknown && (\n          <Button onClick={() => void outcome.retry()} disabled={outcome.busy}>\n            {block.exactRetry}\n          </Button>\n        )}\n        <Button variant=\"ghost\" onClick={outcome.leave}>\n          {pages.leaveRecovery}\n        </Button>\n      </div>\n      {!!outcome.error && <ErrorPanel error={outcome.error} />}\n    </Notice>\n  );\n}\n",
      "type": "registry:block",
      "target": "@components/pages/record.tsx"
    }
  ],
  "type": "registry:block"
}