{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "casework-subject",
  "title": "Review subject",
  "description": "What a reviewer sees of a task's subject: a BReg record's live fields, or the fields its display schema describes, with a record a request patches compared as it was when submitted and as it would be.",
  "dependencies": [
    "@registrystack/app-runtime@~0.43.0-next.0"
  ],
  "registryDependencies": [
    "@registrystack/casework-content",
    "@registrystack/casework-shared",
    "@registrystack/field-renderers",
    "@registrystack/lib-content",
    "@registrystack/request-changes"
  ],
  "files": [
    {
      "path": "casework/subject.tsx",
      "content": "import type {\n  EntityModel,\n  FieldModel,\n  JsonSchema,\n  RegistryModel,\n  ReviewChangedField,\n  ReviewJson,\n  ReviewTaskDetail,\n} from \"@registrystack/app-runtime\";\nimport {\n  bregReviewSubjectSource,\n  fieldsFromJsonSchema,\n  reviewChangedFields,\n  reviewShownValues,\n  reviewSubjectEntity,\n  reviewSubjectFromRegister,\n  reviewSubjectTarget,\n  reviewSubjectTitle,\n} from \"@registrystack/app-runtime\";\nimport { useModel, useRecord } from \"@registrystack/app-runtime/react\";\nimport { FieldValue } from \"@/blocks/fields/field-value\";\nimport { recordTitle } from \"@/blocks/fields/reference-value\";\nimport {\n  ChangeTable,\n  sameValue,\n  type ChangeRow,\n} from \"@/blocks/request/request-changes\";\nimport { Loading, Notice } from \"@/blocks/casework/shared\";\nimport { useCaseworkContent } from \"@/blocks/casework/casework-content\";\nimport { useBlockContent, useLocale } from \"@/blocks/lib/content\";\n\n/**\n * What a reviewer sees of a task's subject. A BReg record reads its own live\n * fields; anything else, including a Casework queue with no BReg behind it at\n * all, reads the values the requester submitted or the source projected,\n * through the review policy's own display schema. A request of the register\n * reads those values under the model's own labels, option words and item\n * fields, a BReg `changes` field reads as the request fields that write a\n * record it creates, or a record it patches as it was when the request was\n * submitted beside as it would be (`ChangeTable`), and a value that names a\n * register record reads as that record's title (`ReferenceValue`). Given no\n * model, only `BregSubject` calls `useModel`, and only a register subject\n * calls `useRecord`: a host with no BReg never mounts either, so it never\n * needs the model or record routes.\n */\n\n/** The display schema as an object schema, whatever shape a policy served it in. */\nfunction asObjectSchema(value: ReviewJson): JsonSchema {\n  return typeof value === \"object\" && value !== null && !Array.isArray(value)\n    ? value\n    : {};\n}\n\nfunction SchemaSubject({\n  task,\n  entity,\n  model,\n}: {\n  task: ReviewTaskDetail;\n  entity?: EntityModel;\n  model?: RegistryModel;\n}) {\n  const c = useCaseworkContent();\n  const block = useBlockContent();\n  const shown = { ...reviewShownValues(task.context) };\n  // The register's own field, where it has one by the same API name, carries\n  // the model's label, option words and item fields; the schema has only names.\n  // A changes field stands for the record fields the request writes.\n  // The UI model may choose which of the policy's display projection to show,\n  // and in what order; a name outside the projection is never shown.\n  const projection = fieldsFromJsonSchema(\n    asObjectSchema(task.policy.displaySchema),\n  );\n  const chosen = model?.casework?.context?.[task.policy.id];\n  const parts = (\n    chosen\n      ? chosen.flatMap((name) => projection.filter((f) => f.apiName === name))\n      : projection\n  ).flatMap((field): SubjectPart[] => {\n    const changed =\n      entity && model\n        ? reviewChangedFields(shown[field.apiName], entity, model)\n        : undefined;\n    if (entity && changed) {\n      // A record the request creates reads as the request's own fields; a\n      // record it patches, as it was when submitted beside as it would be.\n      const created = changed.filter((row) => !(\"before\" in row));\n      for (const row of created)\n        shown[row.requestField.apiName] = row.after;\n      const patched = changed.filter((row) => \"before\" in row);\n      return [\n        ...entity.fields\n          .filter((own) => created.some((row) => row.requestField.id === own.id))\n          .map((own) => ({ field: own })),\n        ...[...new Set(patched.map((row) => row.recordId))].map((recordId) => ({\n          recordId,\n          rows: patched.filter((row) => row.recordId === recordId),\n        })),\n      ];\n    }\n    return [\n      {\n        field:\n          entity?.fields.find((own) => own.apiName === field.apiName) ?? field,\n      },\n    ];\n  });\n  if (parts.length === 0) return <p className=\"muted\">{c.contextEmpty}</p>;\n  return (\n    <>\n      {segments(parts).map((segment, index) =>\n        \"fields\" in segment ? (\n          <dl key={index}>\n            {segment.fields.map((field) => (\n              <div className=\"definition\" key={field.id}>\n                <dt>{field.label}</dt>\n                <dd>\n                  <FieldValue field={field} value={shown[field.apiName]} />\n                </dd>\n              </div>\n            ))}\n          </dl>\n        ) : (\n          // BReg froze each patched record's values when the request was\n          // submitted: the record as it was then, not as it is now.\n          <ChangeTable\n            key={index}\n            rows={segment.rows.map(changeRow)}\n            labels={{\n              caption: block.proposedHeading,\n              current: block.beforeColumn,\n              proposed: block.proposedColumn,\n            }}\n          />\n        ),\n      )}\n    </>\n  );\n}\n\n/** A record the request patches, by the fields it writes there. */\ninterface PatchedRecord {\n  recordId: string;\n  rows: ReviewChangedField[];\n}\n\n/** One thing the subject shows: a field, or a record the request patches. */\ntype SubjectPart = { field: FieldModel } | PatchedRecord;\n\n/** The parts in order, with each run of fields read as one list. */\nfunction segments(\n  parts: readonly SubjectPart[],\n): ({ fields: FieldModel[] } | PatchedRecord)[] {\n  const all: ({ fields: FieldModel[] } | PatchedRecord)[] = [];\n  for (const part of parts) {\n    const last = all[all.length - 1];\n    if (!(\"field\" in part)) all.push(part);\n    else if (last && \"fields\" in last) last.fields.push(part.field);\n    else all.push({ fields: [part.field] });\n  }\n  return all;\n}\n\n/** A patched field as a comparison row, under the record's own label. */\nfunction changeRow(row: ReviewChangedField): ChangeRow {\n  return {\n    key: `${row.recordId}/${row.targetField.id}`,\n    label: row.targetField.label,\n    current: <FieldValue field={row.targetField} value={row.before} />,\n    proposed: <FieldValue field={row.targetField} value={row.after} />,\n    comparison: sameValue(row.before, row.after) ? \"unchanged\" : \"changed\",\n  };\n}\n\nfunction BregRecordSubject({\n  entity,\n  subjectId,\n}: {\n  entity: EntityModel;\n  subjectId: string;\n}) {\n  const c = useCaseworkContent();\n  const record = useRecord(entity.id, subjectId);\n  if (record.isPending) return <Loading />;\n  if (record.error || !record.data)\n    return <Notice tone=\"warning\">{c.recordUnavailable}</Notice>;\n  if (entity.fields.length === 0)\n    return <p className=\"muted\">{c.contextEmpty}</p>;\n  const values = record.data.values;\n  return (\n    <dl>\n      {entity.fields.map((field) => (\n        <div className=\"definition\" key={field.id}>\n          <dt>{field.label}</dt>\n          <dd>\n            <FieldValue field={field} value={values[field.id]} />\n          </dd>\n        </div>\n      ))}\n    </dl>\n  );\n}\n\n/** A subject read against the registry model: the register's own, or anything else. */\nfunction RegisterSubject({\n  task,\n  model,\n}: {\n  task: ReviewTaskDetail;\n  model: RegistryModel;\n}) {\n  const entity = reviewSubjectEntity(\n    task.subject,\n    model,\n    task.sourceRequestEntity,\n  );\n  if (entity?.kind === \"record\")\n    return <BregRecordSubject entity={entity} subjectId={task.subject.id} />;\n  return <SchemaSubject task={task} entity={entity} model={model} />;\n}\n\nfunction BregSubject({ task }: { task: ReviewTaskDetail }) {\n  const model = useModel();\n  // A model still loading, or one with no matching record entity, falls back\n  // to what the task itself carries: a task always has a submitted snapshot\n  // or a source projection, so the reviewer is never left with nothing.\n  if (model.isPending) return <Loading />;\n  if (!model.data) return <SchemaSubject task={task} />;\n  return <RegisterSubject task={task} model={model.data} />;\n}\n\n/**\n * The task's subject, rendered for a reviewer to read before deciding. A page\n * that already read the registry model passes it; without one, a subject\n * whose source is not BReg's never reads the model.\n */\nexport function Subject({\n  task,\n  model,\n}: {\n  task: ReviewTaskDetail;\n  model?: RegistryModel;\n}) {\n  if (model) return <RegisterSubject task={task} model={model} />;\n  return task.subject.source === bregReviewSubjectSource ? (\n    <BregSubject task={task} />\n  ) : (\n    <SchemaSubject task={task} />\n  );\n}\n\n/**\n * The words a review task is named by, from what the host serves. A subject\n * of the register is named by the human reference the host joins onto the\n * task, then the title of the record it is about, then its own title; never\n * by the context's display reference, which BReg sets to a machine string\n * (`breg:{registry}:{action}:{proposal}:{version}`). A subject another\n * producer submitted is named by the source's own display reference, then by\n * its requester reference, which such a producer sets to its own reference;\n * BReg sets that to a keyed pseudonym, which names nobody a reviewer knows,\n * so a subject of the register never is.\n * `loading` holds while the record's title is first read. Once that read has\n * settled it never holds again: the subject reads the same record, and when\n * the read failed its own mount reads it once more, which would otherwise\n * take the page away and remount the subject in a loop.\n */\nexport function useSubjectReference(\n  task: ReviewTaskDetail,\n  model: RegistryModel | undefined,\n): {\n  reference: string | undefined;\n  entity: EntityModel | undefined;\n  loading: boolean;\n} {\n  const locale = useLocale();\n  const fromRegister =\n    model !== undefined && reviewSubjectFromRegister(task.subject, model);\n  const entity = model\n    ? reviewSubjectEntity(task.subject, model, task.sourceRequestEntity)\n    : undefined;\n  const target = entity ? reviewSubjectTarget(task, entity) : undefined;\n  const targetEntity = target\n    ? model?.entities.find((e) => e.id === target.entity)\n    : undefined;\n  const record = useRecord(\n    targetEntity?.id ?? \"\",\n    targetEntity && target ? target.id : \"\",\n  );\n  const displayReference =\n    task.context.strategy === \"source\" && task.context.displayReference\n      ? task.context.displayReference\n      : undefined;\n  const title =\n    targetEntity && record.data\n      ? recordTitle(targetEntity, record.data.values, locale)\n      : undefined;\n  const reference = fromRegister\n    ? ((task.reference?.trim() || undefined) ??\n      title ??\n      (entity ? reviewSubjectTitle(task, entity, locale) : undefined))\n    : (displayReference ?? (task.requesterReference || undefined));\n  return {\n    reference,\n    entity,\n    loading:\n      Boolean(targetEntity) && record.isLoading && !record.isFetchedAfterMount,\n  };\n}\n",
      "type": "registry:block",
      "target": "@components/casework/subject.tsx"
    }
  ],
  "type": "registry:block"
}