{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "record-form",
  "title": "Record form",
  "description": "Renders a record's editable fields from its entity model, with a self-focusing validation error summary and handling for a field that is the record's sole required choice.",
  "dependencies": [
    "@registrystack/app-runtime@~0.43.0-next.0"
  ],
  "registryDependencies": [
    "@registrystack/field-renderers",
    "@registrystack/lib-content",
    "@registrystack/lib-format",
    "@registrystack/ui-button"
  ],
  "files": [
    {
      "path": "record/record-form.tsx",
      "content": "import { useEffect, useRef } from \"react\";\nimport type { FieldModel, JsonValue } from \"@registrystack/app-runtime\";\nimport { FieldValue } from \"@/blocks/fields/field-value\";\nimport { FieldControl } from \"@/blocks/fields/field-control\";\nimport { FieldError } from \"@/blocks/fields/input-field\";\nimport { useBlockContent, useLocale } from \"@/blocks/lib/content\";\nimport { fill } from \"@/blocks/lib/format\";\nimport { Button } from \"@/components/ui/button\";\n\nfunction fieldLabel(\n  fields: readonly FieldModel[] | undefined,\n  id: string,\n): string | undefined {\n  return fields?.find((field) => field.id === id)?.label;\n}\n\n/**\n * The errors a submitted form found, one link per field, under a generic\n * heading. Renders nothing while there are none; moves focus to itself when\n * errors first appear or the form explicitly reports another failed attempt.\n * Removing an error while somebody corrects a field must not steal focus.\n */\nexport function ErrorSummary({\n  errors,\n  fields,\n  focusRequest,\n}: {\n  errors: Record<string, string>;\n  /** Names each error's field; an error whose field is not listed shows its message alone. */\n  fields?: readonly FieldModel[];\n  /** Change this value for each failed submit that should return focus to the summary. */\n  focusRequest?: string | number;\n}) {\n  const c = useBlockContent(),\n    locale = useLocale(),\n    ref = useRef<HTMLDivElement>(null),\n    previousErrors = useRef<Record<string, string>>({}),\n    previousRequest = useRef(focusRequest);\n  const errorSignature = JSON.stringify(errors);\n  useEffect(() => {\n    const hasErrors = Object.keys(errors).length > 0;\n    const newOrChangedError = Object.entries(errors).some(\n      ([id, message]) => previousErrors.current[id] !== message,\n    );\n    const requestedAgain =\n      focusRequest !== undefined &&\n      !Object.is(previousRequest.current, focusRequest);\n    if (hasErrors && (newOrChangedError || requestedAgain))\n      ref.current?.focus();\n    previousErrors.current = { ...errors };\n    previousRequest.current = focusRequest;\n  }, [errorSignature, focusRequest]);\n  if (!Object.keys(errors).length) return null;\n  return (\n    <div className=\"error-summary\" role=\"alert\" tabIndex={-1} ref={ref}>\n      <h2>{c.validationTitle}</h2>\n      <ul>\n        {Object.entries(errors).map(([id, error]) => (\n          <li key={id}>\n            <a\n              href={`#${id}`}\n              onClick={(e) => {\n                e.preventDefault();\n                document.getElementById(id)?.focus();\n              }}\n            >\n              {fieldLabel(fields, id)\n                ? fill(\n                    c.labelled,\n                    { label: fieldLabel(fields, id)!, value: error },\n                    locale,\n                  )\n                : error}\n            </a>\n          </li>\n        ))}\n      </ul>\n    </div>\n  );\n}\n\n/**\n * The one value a required choice allows, when the field offers exactly one:\n * the form takes it as given and shows it as text.\n */\nexport function soleChoice(field: FieldModel): string | undefined {\n  return field.type === \"string\" &&\n    field.required &&\n    field.options?.length === 1\n    ? field.options[0]!.value\n    : undefined;\n}\n\n/**\n * The grid of controls a record form offers, one per field: a preset field\n * shows as read-only text, a sole required\n * choice shows as text, everything else takes the control its kind renders.\n * `optionLabel` reads an option's word from the app's own model helper, since\n * a block does not know how a register names its options.\n */\nexport function RecordFormFields({\n  fields,\n  values,\n  errors,\n  onChange,\n  optionLabel,\n  preset,\n  anchored,\n}: {\n  fields: readonly FieldModel[];\n  values: Readonly<Record<string, JsonValue>>;\n  /** One message per field id; a field with none renders without an error. */\n  errors: Readonly<Record<string, string>>;\n  onChange: (field: FieldModel, value: JsonValue | undefined) => void;\n  optionLabel: (field: FieldModel, code: string) => string;\n  /** Values the form takes as given: each shows as read-only text and is never editable. */\n  preset?: Readonly<Record<string, JsonValue>>;\n  /**\n   * Fields filled from elsewhere: each shows as read-only text, its value\n   * once read, with a note saying where the value comes from or why it has\n   * none, and a way to read it again where the read failed for a reason the\n   * record does not explain.\n   */\n  anchored?: Readonly<\n    Record<\n      string,\n      {\n        value?: JsonValue;\n        note: string;\n        retry?: { label: string; run: () => void };\n      }\n    >\n  >;\n}) {\n  return (\n    <div className=\"form-grid\">\n      {fields.map((field) => {\n        const anchor = anchored?.[field.id];\n        if (anchor)\n          return (\n            <div\n              className={`field ${errors[field.id] ? \"field-error\" : \"\"}`}\n              key={field.id}\n              id={field.id}\n              tabIndex={-1}\n            >\n              <p className=\"field-label\">{field.label}</p>\n              {anchor.value !== undefined && (\n                <div className=\"field-value\">\n                  <FieldValue field={field} value={anchor.value} />\n                </div>\n              )}\n              <p className=\"muted\">{anchor.note}</p>\n              {anchor.retry && (\n                <Button\n                  type=\"button\"\n                  variant=\"outline\"\n                  onClick={anchor.retry.run}\n                >\n                  {anchor.retry.label}\n                </Button>\n              )}\n              {errors[field.id] && (\n                <FieldError name={field.id} error={errors[field.id]!} />\n              )}\n            </div>\n          );\n        if (preset && Object.hasOwn(preset, field.id))\n          return (\n            <div className=\"field\" key={field.id}>\n              <p className=\"field-label\">{field.label}</p>\n              <div className=\"field-value\">\n                <FieldValue field={field} value={preset[field.id]} />\n              </div>\n            </div>\n          );\n        const sole = soleChoice(field);\n        if (sole !== undefined && values[field.id] === sole)\n          return (\n            <div className=\"field\" key={field.id}>\n              <p className=\"field-label\">{field.label}</p>\n              <p>{optionLabel(field, sole)}</p>\n            </div>\n          );\n        return (\n          <FieldControl\n            key={field.id}\n            field={field}\n            value={values[field.id]}\n            onChange={(value) => onChange(field, value)}\n            error={errors[field.id]}\n          />\n        );\n      })}\n    </div>\n  );\n}\n",
      "type": "registry:block",
      "target": "@components/record/record-form.tsx"
    }
  ],
  "type": "registry:block"
}