{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "pages-write-form-core",
  "title": "Write form core",
  "description": "What the record write pages share: the answers a form holds and the errors shown against them, the route's preset and return path, the action a form opened with, and the form of a write taken from an action.",
  "dependencies": [
    "@registrystack/app-runtime@~0.43.0-next.0"
  ],
  "registryDependencies": [
    "@registrystack/field-value-errors",
    "@registrystack/lib-content",
    "@registrystack/lib-format",
    "@registrystack/pages-content",
    "@registrystack/pages-record",
    "@registrystack/pages-record-route-query",
    "@registrystack/pages-register-routes",
    "@registrystack/pages-task-feedback",
    "@registrystack/record-form",
    "@registrystack/shell-content",
    "@registrystack/shell-error-panel",
    "@registrystack/shell-loading",
    "@registrystack/shell-routing",
    "@registrystack/ui-button"
  ],
  "files": [
    {
      "path": "pages/write-form-core.tsx",
      "content": "import { useRef, useState, type FormEvent, type ReactNode } from \"react\";\nimport {\n  problemView,\n  type EntityModel,\n  type FieldModel,\n  type JsonValue,\n  type RecordActionReference,\n  type RecordTask,\n} from \"@registrystack/app-runtime\";\nimport {\n  formValues,\n  recordTask,\n  useActionInputValues,\n  useRecord,\n  useRecords,\n  useStarts,\n} from \"@registrystack/app-runtime/react\";\nimport { Button } from \"@/components/ui/button\";\nimport { useBlockContent, useLocale } from \"@/blocks/lib/content\";\nimport { valueErrors } from \"@/blocks/fields/value-errors\";\nimport {\n  ErrorSummary,\n  RecordFormFields,\n  soleChoice,\n} from \"@/blocks/record/record-form\";\nimport { navigate, splitRoute, useRoute } from \"@/blocks/shell/routing\";\nimport { fill } from \"@/blocks/lib/format\";\nimport { usePagesContent } from \"@/blocks/pages/pages-content\";\nimport {\n  backPathOf,\n  presetOf,\n  returnPathOf,\n} from \"@/blocks/pages/record-route-query\";\nimport { TaskFeedback } from \"@/blocks/pages/task-feedback\";\nimport {\n  recordPath,\n  recordTitle,\n  useOptionLabel,\n  type RecordTaskState,\n  type RegisterEntities,\n} from \"@/blocks/pages/record\";\nimport type { RegisterRoutes } from \"@/blocks/pages/register-routes\";\nimport { Loading } from \"@/blocks/shell/loading\";\nimport { ErrorPanel } from \"@/blocks/shell/error-panel\";\nimport { useShellContent } from \"@/blocks/shell/shell-content\";\nimport { UnavailableWrite } from \"@/blocks/pages/record\";\n\n/**\n * The answers a route presets for `fields`, the path it asks to return to,\n * and the page it was opened from. A preset for a field the form does not offer is dropped, so a link can\n * never send an answer the action does not ask for.\n */\nexport function useFormRoute(fields: readonly FieldModel[]) {\n  const { query } = splitRoute(useRoute());\n  const asked = presetOf(query);\n  const preset: Record<string, JsonValue> = {};\n  for (const field of fields)\n    if (field.id in asked) preset[field.id] = asked[field.id]!;\n  return {\n    preset,\n    returnPath: returnPathOf(query),\n    backPath: backPathOf(query),\n  };\n}\n\n/**\n * The action a write form opened with, for as long as the form stays open.\n * The reread after a confirmed write may stop offering it (the record now\n * exists), and the form's outcome must outlive that.\n */\nexport function useOpenedAction(action: RecordActionReference | undefined) {\n  const opened = useRef(action);\n  if (action) opened.current = action;\n  return opened.current;\n}\n\n/**\n * The start a form with no existing record opens: the one the entity's record\n * list offers, else, where that list cannot be read, the one the session's\n * starts offer. A session may start an entity's records without being able to\n * list them. `matches` picks the action from either; BReg still decides the call.\n */\nexport function OfferedStart({\n  entity,\n  matches,\n  children,\n}: {\n  entity: string;\n  matches: (action: RecordActionReference) => boolean;\n  children: (action: RecordActionReference) => ReactNode;\n}) {\n  // The same read as the record list, so the action it offered is the one used.\n  const query = useRecords(entity, {});\n  const action = useOpenedAction(query.data?.actions?.find(matches));\n  if (query.isPending) return <Loading />;\n  if (!query.data && query.error)\n    return (\n      <UnlistedStart\n        error={query.error}\n        retry={() => void query.refetch()}\n        matches={matches}\n      >\n        {children}\n      </UnlistedStart>\n    );\n  if (!query.data || query.error)\n    return (\n      <ErrorPanel error={query.error} retry={() => void query.refetch()} />\n    );\n  if (!action) return <UnavailableWrite />;\n  return <>{children(action)}</>;\n}\n\nfunction UnlistedStart({\n  error,\n  retry,\n  matches,\n  children,\n}: {\n  error: unknown;\n  retry: () => void;\n  matches: (action: RecordActionReference) => boolean;\n  children: (action: RecordActionReference) => ReactNode;\n}) {\n  const starts = useStarts();\n  const action = useOpenedAction(starts.data?.find(matches));\n  if (starts.isPending) return <Loading />;\n  if (!action) return <ErrorPanel error={error} retry={retry} />;\n  return <>{children(action)}</>;\n}\n\n/** The register's entity of this id, record or request, if it has one. */\nfunction entityOf(\n  entities: RegisterEntities,\n  id: string,\n): EntityModel | undefined {\n  return [\n    entities.record,\n    ...(entities.records ?? []),\n    ...(entities.requests ?? []),\n  ].find((entity) => entity.id === id);\n}\n\n/**\n * Where a confirmed write opens the record it wrote, from the receipt's own\n * record type: null where the session may not read that record type by id, so\n * no link is offered to a record the reader cannot open.\n */\nexport function readableRecordPath(\n  routes: RegisterRoutes,\n  entities: RegisterEntities,\n  resource: { entity: string; id: string },\n): string | null {\n  const known = entityOf(entities, resource.entity);\n  return known?.operations.get\n    ? recordPath(routes, entities, resource.entity, resource.id)\n    : null;\n}\n\n/**\n * A confirmed write's notice, whose button opens the record it wrote and names\n * it by its title. The record is read once the write is confirmed; while it\n * loads, when the read fails and when the record has no title, the button\n * keeps the plain \"View record\".\n */\nfunction WrittenRecordFeedback({\n  task,\n  entities,\n  written,\n  onOpen,\n}: {\n  task: RecordTaskState<RecordTask>;\n  entities: RegisterEntities | null;\n  written: { entity: string; id: string };\n  onOpen: () => void;\n}) {\n  const pages = usePagesContent(),\n    block = useBlockContent(),\n    locale = useLocale();\n  const entity = entities && entityOf(entities, written.entity);\n  const read = useRecord(entity ? written.entity : \"\", written.id);\n  const title =\n    entity && read.data ? recordTitle(entity, read.data, locale) : undefined;\n  return (\n    <TaskFeedback\n      task={task}\n      recordWrite\n      focusConfirmed\n      confirmedLabel={\n        title\n          ? fill(pages.viewRecordTitled, { title }, locale)\n          : block.viewRecord\n      }\n      onConfirmed={onOpen}\n    />\n  );\n}\n\n/** The answers every write form starts with for its inputs, before the app's own. */\nexport function startingAnswers(\n  fields: readonly FieldModel[],\n  preset: Record<string, JsonValue>,\n): Record<string, JsonValue> {\n  // A required answer that may be blank starts blank, so it is always sent.\n  return formValues(\n    fields,\n    Object.fromEntries(\n      fields.map((field) => [\n        field.id,\n        preset[field.id] ??\n          soleChoice(field) ??\n          (field.required && field.acceptsBlank ? \"\" : undefined),\n      ]),\n    ),\n  );\n}\n\n/**\n * The answers a write form holds and the errors shown against them. Changing\n * an answer clears its error; `showErrors` takes a check's result and says\n * whether it passed, asking the summary to take focus where it did not.\n */\nexport function useFormAnswers(initial: () => Record<string, JsonValue>) {\n  const first = useRef(initial);\n  const [values, setValues] = useState<Record<string, JsonValue>>(initial);\n  const [errors, setErrors] = useState<Record<string, string>>({});\n  const [errorFocusRequest, setErrorFocusRequest] = useState(0);\n  function setValue(field: FieldModel, value: JsonValue | undefined) {\n    setValues((previous) => {\n      const next = { ...previous };\n      if (value === undefined) delete next[field.id];\n      else next[field.id] = value;\n      return next;\n    });\n    setErrors((previous) => {\n      if (!(field.id in previous)) return previous;\n      const next = { ...previous };\n      delete next[field.id];\n      return next;\n    });\n  }\n  function showErrors(next: Record<string, string>): boolean {\n    setErrors(next);\n    if (Object.keys(next).length) {\n      setErrorFocusRequest((request) => request + 1);\n      return false;\n    }\n    return true;\n  }\n  /** Returns the form to the answers it opened with. */\n  function reset() {\n    setValues(first.current());\n    setErrors({});\n  }\n  return { values, errors, errorFocusRequest, setValue, showErrors, reset };\n}\n\n/**\n * The inputs the registry fills from a field of a chosen record, as read for\n * this form. `sources` names the record an input's source is when the form is\n * not asked for it, such as the record an action is taken on, by the id of\n * the reference input; `fieldLabel` words the field read. An input shows its\n * value only once it is read; until then, and where it cannot be read, it has\n * no value and holds the form back with the reason. A read the registry failed,\n * rather than one the record does not allow, says so and can be tried again;\n * an expired action or session cannot, so it asks to be opened or signed in again.\n * The value is read once, when the record is chosen, and is submitted as read.\n */\nfunction useAnchors(\n  action: RecordActionReference,\n  fields: readonly FieldModel[],\n  chosen: Record<string, JsonValue>,\n  sources: Record<string, string>,\n  fieldLabel: (field: FieldModel) => string,\n) {\n  const pages = usePagesContent(),\n    shell = useShellContent(),\n    locale = useLocale();\n  const anchored = fields.filter((field) => field.fillFrom);\n  const reads = useActionInputValues(\n    action.ref,\n    anchored.map((field) => {\n      const named = chosen[field.fillFrom!.input];\n      return {\n        input: field.id,\n        record: typeof named === \"string\" ? named : sources[field.fillFrom!.input],\n      };\n    }),\n  );\n  const shown: Record<\n    string,\n    {\n      value?: JsonValue;\n      note: string;\n      retry?: { label: string; run: () => void };\n    }\n  > = {};\n  const values: Record<string, JsonValue> = {};\n  const holds: Record<string, string> = {};\n  anchored.forEach((field, index) => {\n    const from = field.fillFrom!;\n    const source = fields.find((item) => item.id === from.input);\n    const read = reads[index]!;\n    const input = source?.label ?? from.input;\n    const label = fieldLabel(field);\n    const failure =\n      read.isError && !read.isFetching\n        ? problemView(read.error).kind\n        : undefined;\n    // An empty value fills only an input that takes a blank answer; elsewhere\n    // the person could not correct it, so it is held back like an unreadable one.\n    if (read.data && (read.data.value !== \"\" || field.acceptsBlank)) {\n      values[field.id] = read.data.value;\n      shown[field.id] = {\n        value: read.data.value,\n        note: fill(\n          source ? pages.anchorFromChosen : pages.anchorFromThis,\n          { field: label, input },\n          locale,\n        ),\n      };\n    } else if (failure === \"service\" || failure === \"capacity\") {\n      // The registry failed, not the record: no other record would help.\n      const note = pages.anchorFailed;\n      shown[field.id] = {\n        note,\n        retry: { label: shell.retry, run: () => void read.refetch() },\n      };\n      holds[field.id] = note;\n    } else if (\n      failure === \"conflict\" ||\n      failure === \"session-ended\" ||\n      failure === \"contract-changed\"\n    ) {\n      // Reading again sends the same expired action or session: only reopening it helps.\n      const note =\n        failure === \"conflict\"\n          ? pages.anchorExpired\n          : failure === \"session-ended\"\n            ? shell.expiredBody\n            : shell.contractChangedBody;\n      shown[field.id] = { note };\n      holds[field.id] = note;\n    } else {\n      const note = read.isFetching\n        ? pages.anchorLoading\n        : read.isError || read.data\n          ? pages.anchorUnavailable\n          : fill(pages.anchorWaiting, { input }, locale);\n      shown[field.id] = { note };\n      holds[field.id] = note;\n    }\n  });\n  return { shown, values, holds };\n}\n\n/**\n * The form of a record write that takes its inputs from an action: the\n * answers, their check against the fields' schema, the submission, and the\n * outcome the server confirms. The page around it words the headings and says where the\n * form leaves to.\n */\nexport function ActionWriteForm({\n  action,\n  fields,\n  preset,\n  task,\n  submitLabel,\n  cancelHref,\n  returnPath,\n  confirmedPath,\n  anchorSources = {},\n  anchorLabel = (field) => field.fillFrom!.field,\n  entities = null,\n}: {\n  action: RecordActionReference;\n  fields: readonly FieldModel[];\n  preset: Record<string, JsonValue>;\n  task: RecordTaskState<RecordTask>;\n  submitLabel: string;\n  cancelHref: string;\n  /** The path the route asked to return to, if any. */\n  returnPath: string | null;\n  /**\n   * Where a confirmed write goes, given the record the receipt names, unless\n   * the route asked for a return path; null where the reader cannot open it.\n   */\n  confirmedPath: (resource: { entity: string; id: string }) => string | null;\n  /**\n   * The record an input filled from a record is read from, by the id of the\n   * reference input, where the form holds no such input: the record the action\n   * is taken on.\n   */\n  anchorSources?: Record<string, string>;\n  /** The words for the field an input is filled from. */\n  anchorLabel?: (field: FieldModel) => string;\n  /** The register's entities, which name a written record by its title. */\n  entities?: RegisterEntities | null;\n}) {\n  const pages = usePagesContent(),\n    block = useBlockContent(),\n    locale = useLocale(),\n    word = useOptionLabel();\n  const answers = useFormAnswers(() => startingAnswers(fields, preset));\n  const anchors = useAnchors(\n    action,\n    fields,\n    { ...answers.values, ...preset },\n    anchorSources,\n    anchorLabel,\n  );\n  const [checked, setChecked] = useState<Record<string, JsonValue>>({});\n  // A filled input keeps the error the last check gave it only while it holds\n  // the value that check saw: a value read since clears it, as an answer\n  // changed since does.\n  const errors = Object.fromEntries(\n    Object.entries(answers.errors).filter(\n      ([id]) => !(id in anchors.values) || anchors.values[id] === checked[id],\n    ),\n  );\n  const written =\n    task.result?.outcome === \"confirmed\" ? task.result.resource : undefined;\n  const opens = returnPath ?? (written ? confirmedPath(written) : null);\n  async function submit(e: FormEvent) {\n    e.preventDefault();\n    const sent = { ...answers.values, ...preset, ...anchors.values };\n    const found = { ...valueErrors(fields, sent, block, locale), ...anchors.holds };\n    setChecked(sent);\n    if (!answers.showErrors(found)) return;\n    await task.submit(recordTask(action, undefined, { values: sent }));\n  }\n  return (\n    <form\n      className=\"card form-card\"\n      noValidate\n      onSubmit={(e) => void submit(e)}\n    >\n      {/* Once the server confirms, the answers are done: the notice and its next steps stand alone. */}\n      {!written && (\n        <>\n          <ErrorSummary\n            errors={{ ...errors, ...task.fieldErrors }}\n            fields={fields}\n            focusRequest={answers.errorFocusRequest}\n          />\n          <p className=\"muted\">{pages.required}</p>\n          <fieldset disabled={task.locked}>\n            <RecordFormFields\n              fields={fields}\n              values={answers.values}\n              errors={{ ...task.fieldErrors, ...errors }}\n              onChange={answers.setValue}\n              optionLabel={word}\n              preset={preset}\n              anchored={anchors.shown}\n            />\n            <div className=\"actions\">\n              <Button type=\"submit\">{submitLabel}</Button>\n              <Button render={<a href={`#${cancelHref}`} />} variant=\"ghost\">\n                {pages.cancel}\n              </Button>\n            </div>\n          </fieldset>\n        </>\n      )}\n      {written && opens && !returnPath ? (\n        <WrittenRecordFeedback\n          task={task}\n          entities={entities}\n          written={written}\n          onOpen={() => navigate(opens)}\n        />\n      ) : (\n        <TaskFeedback\n          task={task}\n          recordWrite\n          focusConfirmed\n          confirmedLabel={pages.continueAfterWrite}\n          onConfirmed={opens ? () => navigate(opens) : undefined}\n        />\n      )}\n      {written && !opens && (\n        // The session cannot read what it wrote, so the registry's own\n        // identifier is all it can keep; the form can be entered again.\n        <div>\n          {task.reset && (\n            <Button\n              type=\"button\"\n              variant=\"outline\"\n              onClick={() => {\n                task.reset?.();\n                answers.reset();\n              }}\n            >\n              {pages.recordAnother}\n            </Button>\n          )}\n          <details className=\"reference\">\n            <summary>{pages.registryReference}</summary>\n            <p>{pages.registryReferenceHelp}</p>\n            <p className=\"font-mono\">{written.id}</p>\n          </details>\n        </div>\n      )}\n    </form>\n  );\n}\n",
      "type": "registry:block",
      "target": "@components/pages/write-form-core.tsx"
    }
  ],
  "type": "registry:block"
}