{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "request-changes",
  "title": "Change comparison tables",
  "description": "A three-column before-and-after table for reviewing proposed field changes, the rows a request's written fields make against the record they change, and a two-column comparison for a person to check their own proposal before it is sent.",
  "dependencies": [
    "@registrystack/app-runtime@~0.43.0-next.0"
  ],
  "registryDependencies": [
    "@registrystack/field-renderers",
    "@registrystack/ui-button",
    "@registrystack/lib-content",
    "@registrystack/lib-format"
  ],
  "files": [
    {
      "path": "request/request-changes.tsx",
      "content": "import { Fragment, useId, useState, type ReactNode } from \"react\";\nimport type {\n  EntityModel,\n  FieldModel,\n  JsonValue,\n  RecordView,\n  RequestView,\n} from \"@registrystack/app-runtime\";\nimport { Button } from \"@/components/ui/button\";\nimport { useBlockContent, useLocale } from \"@/blocks/lib/content\";\nimport { fill, inSentence } from \"@/blocks/lib/format\";\nimport { FieldValue } from \"@/blocks/fields/field-value\";\nimport { ValueScope } from \"@/blocks/fields/group-field\";\n\nexport interface ChangeRow {\n  key: string;\n  label: string;\n  current: ReactNode;\n  proposed: ReactNode;\n  comparison: \"changed\" | \"unchanged\" | \"unknown\";\n}\n\n/**\n * The three-column before-and-after comparison. Changed rows carry the word\n * \"Changed\" in their accessible content, never colour alone; unchanged rows\n * are muted and can be hidden. The caller decides what a row is and what\n * counts as changed. Children are the caller's own controls for this\n * comparison and share the one action row below the table with the\n * unchanged-rows toggle. `labels` names the table and its two value\n * columns, where they are not the proposal's current and proposed.\n */\nexport function ChangeTable({\n  rows,\n  labels,\n  children,\n}: {\n  rows: ChangeRow[];\n  labels?: { caption: string; current: string; proposed: string };\n  children?: ReactNode;\n}) {\n  const c = useBlockContent();\n  const locale = useLocale();\n  const tableId = useId();\n  const [showUnchangedRows, setShowUnchangedRows] = useState(true);\n  const unchangedCount = rows.filter(\n    (row) => row.comparison === \"unchanged\",\n  ).length;\n  const { caption, current, proposed } = labels ?? {\n    caption: c.proposedHeading,\n    current: c.currentColumn,\n    proposed: c.proposedColumn,\n  };\n  return (\n    <div className=\"change-comparison\">\n      <table className=\"change-table\" role=\"table\">\n        <caption className=\"sr-only\">{caption}</caption>\n        <thead>\n          <tr>\n            <th scope=\"col\">{c.fieldColumn}</th>\n            <th scope=\"col\" id={`${tableId}-current`}>\n              {current}\n            </th>\n            <th scope=\"col\" id={`${tableId}-proposed`}>\n              {proposed}\n            </th>\n          </tr>\n        </thead>\n        <tbody>\n          {rows\n            .filter(\n              (row) => row.comparison !== \"unchanged\" || showUnchangedRows,\n            )\n            .map((row) => (\n              <tr\n                key={row.key}\n                className={\n                  row.comparison === \"changed\"\n                    ? \"changed-cell\"\n                    : row.comparison === \"unchanged\"\n                      ? \"muted-row\"\n                      : undefined\n                }\n              >\n                <td role=\"rowheader\">\n                  {row.label}\n                  {row.comparison === \"changed\" && (\n                    <span className=\"changed-marker\">{c.changedMarker}</span>\n                  )}\n                </td>\n                <td data-label={current} headers={`${tableId}-current`}>\n                  <ValueScope label={current}>{row.current}</ValueScope>\n                </td>\n                <td data-label={proposed} headers={`${tableId}-proposed`}>\n                  <ValueScope label={proposed}>{row.proposed}</ValueScope>\n                </td>\n              </tr>\n            ))}\n        </tbody>\n      </table>\n      {(unchangedCount > 0 || children) && (\n        <div className=\"actions\">\n          {unchangedCount > 0 && (\n            <Button\n              variant=\"outline\"\n              aria-pressed={showUnchangedRows}\n              onClick={() => setShowUnchangedRows(!showUnchangedRows)}\n            >\n              {showUnchangedRows\n                ? c.hideUnchanged\n                : fill(c.showUnchanged, { count: unchangedCount }, locale)}\n            </Button>\n          )}\n          {children}\n        </div>\n      )}\n    </div>\n  );\n}\n\n/**\n * The record entity a request changes: the one its read names as its target\n * when it names one the session reads, else the first the request entity\n * targets, else the register's own record entity. A register with several record entities has a\n * request entity for each.\n */\nexport function recordOfRequest(\n  entities: { record: EntityModel; records?: readonly EntityModel[] },\n  request: EntityModel,\n  targetEntity?: string,\n): EntityModel {\n  const records = entities.records ?? [entities.record];\n  return (\n    records.find((record) => record.id === targetEntity) ??\n    records.find((record) =>\n      request.request?.targets.some((target) => target.entity === record.id),\n    ) ??\n    entities.record\n  );\n}\n\n/** One field a request writes, with the target field it lands in. */\nexport interface WrittenField {\n  field: FieldModel;\n  target: FieldModel;\n}\n\n/**\n * The fields a request writes on its target record, in the order the request\n * model names them. A write whose field either model lacks is left out. The\n * writes are the named request entity's own, so a register with several\n * request entities pairs each with its own.\n */\nexport function writtenFields(\n  entities: { record: EntityModel; request: EntityModel },\n  requestFields: readonly FieldModel[],\n): WrittenField[] {\n  return (entities.request.request?.writes ?? []).flatMap((write) => {\n    const field = requestFields.find((item) => item.id === write.requestField);\n    const target = entities.record.fields.find((item) => item.id === write.targetField);\n    return write.targetEntity === entities.record.id && field && target\n      ? [{ field, target }]\n      : [];\n  });\n}\n\n/**\n * What a target field holds now: the live target record when it was read,\n * else the value the request retained, unless the host marked the target\n * unavailable. An applied request is compared with what the field held\n * before it, from the record's history, since the live record already holds\n * what it wrote. Undefined where none is known.\n */\nexport function currentValue(\n  targetField: FieldModel,\n  target: RecordView | undefined,\n  request: RequestView | undefined,\n): JsonValue | undefined {\n  if (request?.state === \"applied\") return request.before?.[targetField.id];\n  if (target) return target.values[targetField.id];\n  return request?.target?.available === false\n    ? undefined\n    : request?.previous?.[targetField.id];\n}\n\n/** Exact, order-sensitive equality: a reordered list is a change. */\nexport function sameValue(current: unknown, proposed: unknown): boolean {\n  return JSON.stringify(current) === JSON.stringify(proposed);\n}\n\n/**\n * The comparison rows for one request, one for each field it writes. Current\n * values come from the live target record, so before-values survive the\n * decision that removes the pending lifecycle action; the values the request\n * retained stand in only while the target is not marked unavailable. An\n * applied request's come from the record's history (`currentValue`). A row\n * is labelled by its target field unless `labelOf` words it otherwise.\n */\nexport function writtenChangeRows(\n  written: readonly WrittenField[],\n  view: RecordView,\n  target: RecordView | undefined,\n  currentUnavailable: string,\n  labelOf?: (item: WrittenField) => string,\n): ChangeRow[] {\n  return written.map((item) => {\n    const { field, target: targetField } = item;\n    const current = currentValue(targetField, target, view.request);\n    const proposed = view.values[field.id];\n    return {\n      key: targetField.id,\n      label: labelOf ? labelOf(item) : targetField.label,\n      current:\n        current === undefined ? (\n          <p className=\"muted\">{currentUnavailable}</p>\n        ) : (\n          <FieldValue field={targetField} value={current} />\n        ),\n      proposed: <FieldValue field={targetField} value={proposed} />,\n      comparison:\n        current === undefined\n          ? \"unknown\"\n          : sameValue(current, proposed)\n            ? \"unchanged\"\n            : \"changed\",\n    };\n  });\n}\n\nexport interface ProposedChangeItem {\n  key: string;\n  label: string;\n  before: ReactNode;\n  after: ReactNode;\n  /** Omitted where the answer can no longer be changed. */\n  onChangeAnswer?: () => void;\n}\n\n/**\n * The two-column before-and-after a person checks before sending a proposal:\n * every answer that will change a record, read against what it changes from.\n * `beforeLabel`/`afterLabel` are the caller's own, since \"before\" and \"after\"\n * may need to name what kind of record this changes.\n */\nexport function ProposedChangesReview({\n  items,\n  beforeLabel,\n  afterLabel,\n}: {\n  items: ProposedChangeItem[];\n  beforeLabel: string;\n  afterLabel: string;\n}) {\n  const c = useBlockContent();\n  const locale = useLocale();\n  return (\n    <div className=\"comparison\">\n      <section>\n        <h2 className=\"eyebrow\">{beforeLabel}</h2>\n        {items.map((item) => (\n          <Fragment key={item.key}>\n            <h3>{item.label}</h3>\n            <ValueScope label={beforeLabel}>{item.before}</ValueScope>\n          </Fragment>\n        ))}\n      </section>\n      <section>\n        <h2 className=\"eyebrow\">{afterLabel}</h2>\n        {items.map((item) => (\n          <Fragment key={item.key}>\n            <h3>{item.label}</h3>\n            <ValueScope label={afterLabel}>{item.after}</ValueScope>\n            {item.onChangeAnswer && (\n              <Button\n                variant=\"ghost\"\n                className=\"change-answer\"\n                onClick={item.onChangeAnswer}\n              >\n                {fill(\n                  c.changeAnswer,\n                  { field: inSentence(item.label, locale) },\n                  locale,\n                )}\n              </Button>\n            )}\n          </Fragment>\n        ))}\n      </section>\n    </div>\n  );\n}\n",
      "type": "registry:block",
      "target": "@components/request/request-changes.tsx"
    }
  ],
  "type": "registry:block"
}