{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "request-actions",
  "title": "Request decision form",
  "description": "Walks an officer through choosing one of a request's offered actions, checking it, and confirming it, with the focus and announcement each step needs. The caller supplies the actions, their reasons, and the submit and refetch behaviour.",
  "dependencies": [
    "@registrystack/app-runtime@~0.43.0-next.0"
  ],
  "registryDependencies": [
    "@registrystack/ui-button",
    "@registrystack/lib-notice",
    "@registrystack/lib-content",
    "@registrystack/record-form",
    "@registrystack/field-renderers",
    "@registrystack/request-status"
  ],
  "files": [
    {
      "path": "request/request-actions.tsx",
      "content": "import {\n  useEffect,\n  useRef,\n  useState,\n  type FormEvent,\n  type ReactNode,\n} from \"react\";\nimport type { RecordActionReference } from \"@registrystack/app-runtime\";\nimport { Button } from \"@/components/ui/button\";\nimport { Notice } from \"@/blocks/lib/notice\";\nimport { ConfirmedReceipt, useBlockContent } from \"@/blocks/lib/content\";\nimport { ErrorSummary } from \"@/blocks/record/record-form\";\nimport { InputField } from \"@/blocks/fields/input-field\";\nimport {\n  CommandFeedback,\n  type CommandOutcome,\n} from \"@/blocks/request/request-status\";\n\n/** An action named by its lifecycle action when it has one, else by its kind. */\nfunction actionKey(action: RecordActionReference): string {\n  return action.action ?? action.name;\n}\n\nexport interface DecisionOutcome extends CommandOutcome {\n  reset: () => void;\n  /** The fields of a refusal that failed validation, keyed by field id. */\n  validationErrors: Record<string, string>;\n  /** The decision itself was refused as stale: another officer decided. */\n  staleConflict: boolean;\n  confirmed: Extract<CommandOutcome[\"result\"], { outcome: \"confirmed\" }> | null;\n}\n\n/**\n * A decision on a request: pick one of the offered actions (or go straight to\n * the check step for one that needs no reason), check it, then confirm. The\n * caller names its actions, their reasons and their outcome; this only walks\n * the choose/check/confirm steps and their focus and announcement.\n */\nexport function DecisionForm({\n  title,\n  hint,\n  reference,\n  choices,\n  primaryAction = null,\n  primaryReason,\n  secondaryActions = [],\n  hasActions,\n  needsReason,\n  describeAction,\n  checkDetails,\n  header,\n  task,\n  submit,\n  refetch,\n  announce,\n  choiceLabel,\n  openerLabel = choiceLabel,\n  reconcileHref,\n  renderError,\n  refreshing,\n  decidedBody,\n  choiceDisabled,\n  choiceNote,\n  answerFields,\n  serverAnswerErrors,\n  validateAnswers,\n}: {\n  /** The heading, the fieldset legend and the choice-step title. */\n  title: string;\n  hint: string;\n  /** The human reference for the thing being decided, shown on the check step. */\n  reference: string;\n  /** The radio choices, in the order they should be read. */\n  choices: RecordActionReference[];\n  /** Takes no reason and goes straight to the check step. */\n  primaryAction?: RecordActionReference | null;\n  /**\n   * An optional reason the person may give with the primary action. The server\n   * decides what it accepts; the caller decides what to send with which action.\n   */\n  primaryReason?: { label: string; hint: string };\n  /** Also straight to the check step, rendered as outline buttons. */\n  secondaryActions?: RecordActionReference[];\n  /** False renders the \"no actions available\" sentence. */\n  hasActions: boolean;\n  needsReason: (action: RecordActionReference) => boolean;\n  describeAction: (action: RecordActionReference) => string;\n  /** Extra context on the check step, under the reference. */\n  checkDetails?: ReactNode;\n  /** Controls above the form; hidden while an outcome is unknown. */\n  header?: ReactNode;\n  task: DecisionOutcome;\n  submit: (action: RecordActionReference, reason: string) => Promise<unknown>;\n  refetch: () => Promise<unknown>;\n  announce: (message: string) => void;\n  choiceLabel: (action: RecordActionReference) => string;\n  /**\n   * The label of the primary and secondary buttons, which only open the check\n   * step; the check step's confirm button keeps `choiceLabel`, so the two never\n   * read alike. Defaults to `choiceLabel`.\n   */\n  openerLabel?: (action: RecordActionReference) => string;\n  reconcileHref: string;\n  renderError: (error: Error) => ReactNode;\n  /**\n   * A held view of this request is stale and already being refetched: the\n   * choices and the confirm step wait for the fresh view rather than send a\n   * decision against a revision that is about to be overtaken.\n   */\n  refreshing: boolean;\n  /** Confirmed-outcome wording, optionally chosen from the action just sent. */\n  decidedBody: string | ((action: RecordActionReference | null) => string);\n  /** True renders the choice unselectable, with its note explaining why. */\n  choiceDisabled?: (action: RecordActionReference) => boolean;\n  /** A sentence shown under one choice's label, naming why it is disabled. */\n  choiceNote?: (action: RecordActionReference) => string | undefined;\n  /**\n   * The structured answers that travel with the outcome, rendered on the\n   * choice step under the radios. The render prop receives every answer\n   * field error in play, keyed by the field element id, so client and\n   * server refusals land on the same control the summary links to.\n   */\n  answerFields?: (fieldErrors: Record<string, string>) => ReactNode;\n  /**\n   * Server refusals of the structured answers, keyed by field element id.\n   * Present only for callers that pass answerFields; like a refused reason\n   * it returns the officer to the choice step.\n   */\n  serverAnswerErrors?: Record<string, string>;\n  /** Answer errors checked before the check step, keyed by field element id. */\n  validateAnswers?: (action: RecordActionReference) => Record<string, string>;\n}) {\n  const c = useBlockContent();\n  const [selected, setSelected] = useState<RecordActionReference | null>(null);\n  const [reason, setReason] = useState(\"\");\n  const [errors, setErrors] = useState<Record<string, string>>({});\n  const [checking, setChecking] = useState(false);\n  const checkRef = useRef<HTMLHeadingElement>(null);\n  const decidedRef = useRef<HTMLHeadingElement>(null);\n  const choiceRef = useRef<HTMLFieldSetElement>(null);\n  const focusChoiceNext = useRef(false);\n  const handledReceipt = useRef<string | null>(null);\n  const submittedAction = useRef<RecordActionReference | null>(null);\n\n  // A reread mints fresh references for the same actions, so the choice\n  // follows its action by name; one the item no longer offers is dropped.\n  const offered = [\n    ...choices,\n    ...(primaryAction ? [primaryAction] : []),\n    ...secondaryActions,\n  ];\n  const current = selected\n    ? (offered.find((action) => action.ref === selected.ref) ??\n      offered.find((action) => actionKey(action) === actionKey(selected)) ??\n      null)\n    : null;\n  const reasonRequired = current ? needsReason(current) : false;\n\n  const serverReasonError = task.validationErrors.reason;\n  const serverRefusedAnswers = Boolean(\n    serverAnswerErrors && Object.keys(serverAnswerErrors).length > 0,\n  );\n  // Only a refusal of the decision itself says another officer decided; a\n  // 412 refusing the recovery retry leaves the uncertain attempt in charge.\n  const staleConflict = task.staleConflict;\n  const confirmed = task.confirmed;\n  const hasFeedback = Boolean(\n    task.pending ||\n    task.unknown ||\n    task.error ||\n    task.result ||\n    staleConflict ||\n    confirmed,\n  );\n\n  // A server-side reason or answer refusal returns to the choice step with\n  // the field error wired to the same element the summary links to.\n  useEffect(() => {\n    if (serverReasonError || serverRefusedAnswers) setChecking(false);\n  }, [serverReasonError, serverRefusedAnswers]);\n  // The check step closes on a choice the item stopped offering, and focus\n  // returns to the choices it came from.\n  useEffect(() => {\n    if (!selected || current) return;\n    setSelected(null);\n    if (checking) {\n      focusChoiceNext.current = true;\n      setChecking(false);\n    }\n  }, [selected, current]);\n  // Focus follows the step: the check heading on entry, the choice group only\n  // when the officer chooses to go back — never when a confirmed outcome\n  // resets the step, which would steal focus from the outcome heading.\n  useEffect(() => {\n    if (checking) {\n      checkRef.current?.focus({ preventScroll: true });\n      return;\n    }\n    if (focusChoiceNext.current) {\n      focusChoiceNext.current = false;\n      choiceRef.current?.focus({ preventScroll: true });\n    }\n  }, [checking]);\n  // On success move focus to the outcome heading and announce it.\n  useEffect(() => {\n    if (!confirmed || handledReceipt.current === confirmed.receipt) return;\n    handledReceipt.current = confirmed.receipt;\n    setSelected(null);\n    setChecking(false);\n    announce(c.decisionAnnounced);\n    void refetch();\n    decidedRef.current?.focus({ preventScroll: true });\n  }, [confirmed]);\n\n  function choose(action: RecordActionReference) {\n    task.reset();\n    setSelected(action);\n    setErrors({});\n  }\n  /** The primary and secondary actions go straight to the check step: they\n      take no reason, so there is nothing to choose between first. */\n  function straightToCheck(action: RecordActionReference) {\n    choose(action);\n    setChecking(true);\n  }\n\n  function continueToCheck(event: FormEvent) {\n    event.preventDefault();\n    if (!choices.length) return;\n    if (!current) {\n      choiceRef.current?.focus();\n      return;\n    }\n    const next: Record<string, string> = {};\n    if (reasonRequired && !reason.trim())\n      next[\"decision-reason\"] = c.requiredError;\n    if (validateAnswers) Object.assign(next, validateAnswers(current));\n    if (Object.keys(next).length) {\n      setErrors(next);\n      return;\n    }\n    setErrors({});\n    setChecking(true);\n  }\n\n  async function perform() {\n    if (!current) return;\n    submittedAction.current = current;\n    await submit(current, reason);\n  }\n\n  return (\n    <section className=\"card\">\n      <h2>{title}</h2>\n      <p className=\"muted\">{hint}</p>\n      {!task.unknown && header}\n      {!hasActions && !hasFeedback && <p>{c.noActions}</p>}\n      {hasActions && checking && current ? (\n        <div className=\"decision-confirm\">\n          <h2 ref={checkRef} tabIndex={-1}>\n            {c.decisionCheckHeading}\n          </h2>\n          <h3>{choiceLabel(current)}</h3>\n          <p className=\"muted\">{reference}</p>\n          {checkDetails}\n          <p>{describeAction(current)}</p>\n          {(reasonRequired || primaryReason) && reason.trim() && (\n            <blockquote>\n              <p>{reason}</p>\n            </blockquote>\n          )}\n          <div className=\"actions\">\n            <Button\n              onClick={() => void perform()}\n              disabled={task.pending || task.unknown || refreshing}\n            >\n              {choiceLabel(current)}\n            </Button>\n            <Button\n              variant=\"ghost\"\n              onClick={() => {\n                focusChoiceNext.current = true;\n                setChecking(false);\n              }}\n              disabled={task.pending || task.unknown}\n            >\n              {c.decisionChange}\n            </Button>\n          </div>\n        </div>\n      ) : hasActions ? (\n        <form noValidate onSubmit={continueToCheck}>\n          <ErrorSummary\n            errors={{\n              ...errors,\n              ...(serverReasonError\n                ? { \"decision-reason\": serverReasonError }\n                : {}),\n              ...(serverAnswerErrors ?? {}),\n            }}\n          />\n          <fieldset\n            ref={choiceRef}\n            tabIndex={-1}\n            disabled={task.pending || task.unknown || refreshing}\n          >\n            {/* The heading above already shows the title; the legend only names the group. */}\n            <legend className=\"sr-only\">{title}</legend>\n            {choices.length > 0 && (\n              <div className=\"decision-radios\">\n                {choices.map((action) => {\n                  const note = choiceNote?.(action);\n                  return (\n                    <label\n                      key={action.ref}\n                      htmlFor={`decision-${actionKey(action)}`}\n                    >\n                      <input\n                        type=\"radio\"\n                        id={`decision-${actionKey(action)}`}\n                        name=\"decision-choice\"\n                        value={actionKey(action)}\n                        checked={current?.ref === action.ref}\n                        onChange={() => choose(action)}\n                        disabled={choiceDisabled?.(action) ?? false}\n                      />\n                      <span>{choiceLabel(action)}</span>\n                      {note && <span className=\"radio-hint\">{note}</span>}\n                    </label>\n                  );\n                })}\n              </div>\n            )}\n            {answerFields &&\n              answerFields({\n                ...errors,\n                ...(serverAnswerErrors ?? {}),\n              })}\n            {primaryReason && !reasonRequired && (\n              <InputField\n                name=\"decision-reason\"\n                label={primaryReason.label}\n                hint={primaryReason.hint}\n                value={reason}\n                multiline\n                onChange={setReason}\n                error={serverReasonError}\n              />\n            )}\n            {reasonRequired && (\n              <InputField\n                name=\"decision-reason\"\n                label={`${c.decisionReasonLabel}. ${c.decisionReasonAudience}`}\n                hint={c.decisionReasonHint}\n                value={reason}\n                multiline\n                onChange={setReason}\n                error={errors[\"decision-reason\"] ?? serverReasonError}\n              />\n            )}\n            <div className=\"actions\">\n              {choices.length > 0 && (\n                <Button type=\"submit\">{c.decisionContinue}</Button>\n              )}\n              {primaryAction && (\n                <Button onClick={() => straightToCheck(primaryAction)}>\n                  {openerLabel(primaryAction)}\n                </Button>\n              )}\n              {secondaryActions.map((action) => (\n                <Button\n                  key={action.ref}\n                  variant=\"outline\"\n                  onClick={() => straightToCheck(action)}\n                >\n                  {openerLabel(action)}\n                </Button>\n              ))}\n            </div>\n          </fieldset>\n        </form>\n      ) : null}\n      {staleConflict ? (\n        <Notice tone=\"warning\" title={c.staleDecidedTitle}>\n          <p>{c.staleDecidedBody}</p>\n          <Button\n            variant=\"outline\"\n            onClick={() => {\n              task.reset();\n              setSelected(null);\n              setChecking(false);\n              void refetch();\n            }}\n          >\n            {c.reloadRequest}\n          </Button>\n        </Notice>\n      ) : confirmed ? (\n        <Notice tone=\"success\">\n          <h2 ref={decidedRef} tabIndex={-1}>\n            {c.decidedTitle}\n          </h2>\n          <p>\n            {typeof decidedBody === \"function\"\n              ? decidedBody(submittedAction.current)\n              : decidedBody}\n          </p>\n          <ConfirmedReceipt receipt={confirmed.receipt} />\n        </Notice>\n      ) : (\n        <CommandFeedback\n          task={task}\n          reconcileHref={reconcileHref}\n          renderError={renderError}\n        />\n      )}\n    </section>\n  );\n}\n",
      "type": "registry:block",
      "target": "@components/request/request-actions.tsx"
    }
  ],
  "type": "registry:block"
}