{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "field-renderers",
  "title": "Field renderers",
  "description": "Renders and edits a record field by its kind: text, number, date, boolean, enum, multi-enum, a repeatable group, a single structured object of sub-fields, a reference chosen from, and shown as, the title of the record it names, or a raw JSON value read only. Provides the per-kind renderer map, the labelled controls, and the read-only value views, with a context to override or extend the kinds a project needs.",
  "dependencies": [
    "@registrystack/app-runtime@~0.43.0-next.0"
  ],
  "registryDependencies": [
    "@registrystack/lib-format",
    "@registrystack/lib-content",
    "@registrystack/lib-scroll-region",
    "@registrystack/ui-input",
    "@registrystack/ui-button",
    "@registrystack/lib-format"
  ],
  "files": [
    {
      "path": "fields/renderers.ts",
      "content": "import {\n  createContext,\n  createElement,\n  useContext,\n  useMemo,\n  type ComponentType,\n  type ReactNode,\n} from \"react\";\nimport type { FieldModel, JsonValue } from \"@registrystack/app-runtime\";\nimport {\n  BooleanControl,\n  ChoicesControl,\n  Crs84PointControl,\n  DateControl,\n  EnumControl,\n  NumberControl,\n  TextControl,\n  TextareaControl,\n} from \"@/blocks/fields/controls\";\nimport {\n  BooleanValue,\n  DateValue,\n  EnumValue,\n  JsonValueView,\n  NumberValue,\n  TextValue,\n} from \"@/blocks/fields/values\";\nimport {\n  GroupControl,\n  GroupValue,\n  StructuredControl,\n} from \"@/blocks/fields/group-field\";\nimport { ReferenceValue } from \"@/blocks/fields/reference-value\";\nimport { ReferenceControl } from \"@/blocks/fields/reference-picker\";\n\n/** A recorded value to show; missing, blank and empty values never reach it. */\nexport interface FieldValueProps {\n  field: FieldModel;\n  value: JsonValue;\n}\n\nexport interface FieldControlProps {\n  field: FieldModel;\n  value: JsonValue | undefined;\n  /** The answer as the form keeps it: undefined when there is none. */\n  onChange: (value: JsonValue | undefined) => void;\n  error?: string;\n  /** A line shown under the control. */\n  note?: ReactNode;\n}\n\n/**\n * How one kind of field shows a value and, when it can be entered, takes one.\n * A kind without a `Control` is shown read-only in a form.\n */\nexport interface FieldRenderer {\n  Value: ComponentType<FieldValueProps>;\n  Control?: ComponentType<FieldControlProps>;\n}\n\nexport type FieldRenderers = Readonly<Record<string, FieldRenderer>>;\n\n/** An override of some kinds, or of one half of a kind. */\nexport type FieldRendererOverrides = Readonly<\n  Record<string, Partial<FieldRenderer>>\n>;\n\nexport const defaultRenderers: FieldRenderers = {\n  text: { Value: TextValue, Control: TextControl },\n  textarea: { Value: TextValue, Control: TextareaControl },\n  integer: { Value: NumberValue, Control: NumberControl },\n  number: { Value: NumberValue, Control: NumberControl },\n  boolean: { Value: BooleanValue, Control: BooleanControl },\n  date: { Value: DateValue, Control: DateControl },\n  enum: { Value: EnumValue, Control: EnumControl },\n  \"multi-enum\": { Value: JsonValueView, Control: ChoicesControl },\n  reference: { Value: ReferenceValue, Control: ReferenceControl },\n  \"json-value\": { Value: JsonValueView },\n  group: { Value: GroupValue, Control: GroupControl },\n  structured: { Value: JsonValueView, Control: StructuredControl },\n  \"crs84-point\": { Value: JsonValueView, Control: Crs84PointControl },\n};\n\n/**\n * The renderer a field uses: the one its widget names when the map has it,\n * otherwise the one its type, options, reference and format choose.\n */\nexport function fieldKind(\n  field: FieldModel,\n  renderers: FieldRenderers = defaultRenderers,\n): string {\n  if (field.widget && Object.hasOwn(renderers, field.widget))\n    return field.widget;\n  if (field.type === \"group\") return \"group\";\n  if (field.type === \"structured\") return \"structured\";\n  if (field.type === \"crs84-point\") return \"crs84-point\";\n  if (field.type === \"object\") return \"json-value\";\n  if (field.type === \"array\")\n    return field.options ? \"multi-enum\" : \"json-value\";\n  if (field.type === \"boolean\") return \"boolean\";\n  if (field.options) return \"enum\";\n  if (field.type === \"integer\" || field.type === \"number\") return field.type;\n  if (field.reference) return \"reference\";\n  if (field.format === \"date\") return \"date\";\n  return \"text\";\n}\n\nconst FieldRenderersContext = createContext<FieldRenderers>(defaultRenderers);\n\nexport function useFieldRenderers(): FieldRenderers {\n  return useContext(FieldRenderersContext);\n}\n\n/**\n * Replaces renderers for the blocks inside it. An override may add a kind a\n * widget can name, or replace only the `Value` or the `Control` of a kind and\n * keep the other half.\n */\nexport function FieldRenderersProvider({\n  renderers,\n  children,\n}: {\n  renderers: FieldRendererOverrides;\n  children?: ReactNode;\n}) {\n  const outer = useFieldRenderers();\n  const merged = useMemo(() => {\n    const next: Record<string, FieldRenderer> = { ...outer };\n    for (const [kind, override] of Object.entries(renderers)) {\n      const renderer = { ...outer[kind], ...override };\n      if (!renderer.Value)\n        throw new Error(`The field renderer \"${kind}\" needs a Value.`);\n      next[kind] = renderer as FieldRenderer;\n    }\n    return next;\n  }, [outer, renderers]);\n  return createElement(\n    FieldRenderersContext.Provider,\n    { value: merged },\n    children,\n  );\n}\n",
      "type": "registry:component",
      "target": "@components/fields/renderers.ts"
    },
    {
      "path": "fields/controls.tsx",
      "content": "import {\n  crs84PointContract,\n  type FieldModel,\n  type JsonValue,\n} from \"@registrystack/app-runtime\";\nimport {\n  ChoiceField,\n  describedBy,\n  FieldError,\n  InputField,\n  YesNoField,\n} from \"@/blocks/fields/input-field\";\nimport type { FieldControlProps } from \"@/blocks/fields/renderers\";\nimport { useBlockContent } from \"@/blocks/lib/content\";\n\n/**\n * The answer a typed text stands for. A cleared answer is blank when the\n * field needs one or keeps a blank answer, and undefined otherwise. A number\n * stays the text typed, so every digit reaches the host.\n */\nexport function controlValue(\n  field: FieldModel,\n  typed: string,\n): JsonValue | undefined {\n  if (typed !== \"\") return typed;\n  return field.required || field.acceptsBlank ? \"\" : undefined;\n}\n\nfunction typedText(value: JsonValue | undefined): string {\n  return value === undefined || value === null\n    ? \"\"\n    : typeof value === \"string\"\n      ? value\n      : String(value);\n}\n\nfunction bound(field: FieldModel, keyword: string): number | undefined {\n  const limit = field.schema[keyword];\n  return typeof limit === \"number\" ? limit : undefined;\n}\n\n/** A single-line input, or a textarea or option list, answering one field. */\nfunction ModelInput({\n  field,\n  value,\n  onChange,\n  error,\n  type = \"text\",\n  multiline = false,\n  step,\n}: FieldControlProps & {\n  type?: string;\n  multiline?: boolean;\n  step?: number | \"any\";\n}) {\n  const numeric = step !== undefined;\n  const min = numeric ? bound(field, \"minimum\") : undefined,\n    max = numeric ? bound(field, \"maximum\") : undefined;\n  return (\n    <InputField\n      name={field.id}\n      label={field.label}\n      {...(field.hint ? { hint: field.hint } : {})}\n      value={typedText(value)}\n      multiline={multiline}\n      type={type}\n      required={field.required && !field.acceptsBlank}\n      {...(field.options ? { options: field.options } : {})}\n      {...(min !== undefined ? { min } : {})}\n      {...(max !== undefined ? { max } : {})}\n      {...(step !== undefined ? { step } : {})}\n      onChange={(next) => onChange(controlValue(field, next))}\n      {...(error ? { error } : {})}\n    />\n  );\n}\n\nexport function TextControl(props: FieldControlProps) {\n  return <ModelInput {...props} />;\n}\n\nexport function TextareaControl(props: FieldControlProps) {\n  return <ModelInput {...props} multiline />;\n}\n\nexport function DateControl(props: FieldControlProps) {\n  return <ModelInput {...props} type=\"date\" />;\n}\n\nexport function EnumControl(props: FieldControlProps) {\n  return <ModelInput {...props} />;\n}\n\n/** A number input bounded by the schema, stepping by whole numbers for an integer. */\nexport function NumberControl(props: FieldControlProps) {\n  return (\n    <ModelInput\n      {...props}\n      type=\"number\"\n      step={props.field.type === \"integer\" ? 1 : \"any\"}\n    />\n  );\n}\n\nfunction pointCoordinates(value: JsonValue | undefined): [string, string] {\n  if (value === null || typeof value !== \"object\" || Array.isArray(value))\n    return [\"\", \"\"];\n  const coordinates = value.coordinates;\n  if (!Array.isArray(coordinates) || coordinates.length !== 2) return [\"\", \"\"];\n  const text = (coordinate: JsonValue): string =>\n    typeof coordinate === \"string\" || typeof coordinate === \"number\"\n      ? String(coordinate)\n      : \"\";\n  return [text(coordinates[0]!), text(coordinates[1]!)];\n}\n\n/**\n * One coordinate changed in a native GeoJSON Point. Form state keeps exact\n * decimal text; the app host turns each validated coordinate into a JSON\n * number without sending it through a lossy JavaScript number.\n */\nexport function withPointCoordinate(\n  field: FieldModel,\n  current: JsonValue | undefined,\n  index: 0 | 1,\n  typed: string,\n): JsonValue | undefined {\n  const coordinates = pointCoordinates(current);\n  coordinates[index] = typed;\n  if (!field.required && coordinates.every((coordinate) => coordinate === \"\"))\n    return undefined;\n  return { type: \"Point\", coordinates };\n}\n\n/** Longitude and latitude controls for BReg's strict CRS84 GeoJSON Point. */\nexport function Crs84PointControl({\n  field,\n  value,\n  onChange,\n  error,\n}: FieldControlProps) {\n  const content = useBlockContent(),\n    contract = crs84PointContract(field.schema) ?? {\n      precision: 9,\n      longitude: { minimum: -180, maximum: 180 },\n      latitude: { minimum: -90, maximum: 90 },\n    },\n    coordinates = pointCoordinates(value),\n    step = contract.precision === 0 ? 1 : 10 ** -contract.precision;\n  return (\n    <fieldset\n      id={field.id}\n      tabIndex={-1}\n      className={`field group-field ${error ? \"field-error\" : \"\"}`}\n      aria-describedby={describedBy(field.id, field.hint, error)}\n      aria-invalid={!!error}\n    >\n      <legend>{field.label}</legend>\n      {field.hint && (\n        <p className=\"field-hint\" id={`${field.id}-hint`}>\n          {field.hint}\n        </p>\n      )}\n      {error && <FieldError name={field.id} error={error} />}\n      <InputField\n        name={`${field.id}-longitude`}\n        label={content.longitudeLabel}\n        value={coordinates[0]}\n        type=\"number\"\n        min={contract.longitude.minimum}\n        max={contract.longitude.maximum}\n        step={step}\n        required={field.required}\n        onChange={(typed) =>\n          onChange(withPointCoordinate(field, value, 0, typed))\n        }\n      />\n      <InputField\n        name={`${field.id}-latitude`}\n        label={content.latitudeLabel}\n        value={coordinates[1]}\n        type=\"number\"\n        min={contract.latitude.minimum}\n        max={contract.latitude.maximum}\n        step={step}\n        required={field.required}\n        onChange={(typed) =>\n          onChange(withPointCoordinate(field, value, 1, typed))\n        }\n      />\n    </fieldset>\n  );\n}\n\nexport function BooleanControl({\n  field,\n  value,\n  onChange,\n  error,\n  note,\n}: FieldControlProps) {\n  return (\n    <YesNoField\n      name={field.id}\n      label={field.label}\n      {...(field.hint ? { hint: field.hint } : {})}\n      value={typeof value === \"boolean\" ? value : undefined}\n      onChange={onChange}\n      required={field.required}\n      {...(error ? { error } : {})}\n      note={note}\n    />\n  );\n}\n\nexport function ChoicesControl({\n  field,\n  value,\n  onChange,\n  error,\n}: FieldControlProps) {\n  return (\n    <ChoiceField\n      name={field.id}\n      label={field.label}\n      {...(field.hint ? { hint: field.hint } : {})}\n      value={\n        Array.isArray(value)\n          ? value.filter((item) => typeof item === \"string\")\n          : []\n      }\n      options={field.options ?? []}\n      onChange={(next) => onChange(next)}\n      {...(error ? { error } : {})}\n    />\n  );\n}\n",
      "type": "registry:component",
      "target": "@components/fields/controls.tsx"
    },
    {
      "path": "fields/field-control.tsx",
      "content": "import { FieldValue } from \"@/blocks/fields/field-value\";\nimport { FieldError } from \"@/blocks/fields/input-field\";\nimport {\n  fieldKind,\n  useFieldRenderers,\n  type FieldControlProps,\n} from \"@/blocks/fields/renderers\";\n\nimport { controlValue } from \"@/blocks/fields/controls\";\nexport { controlValue };\n\n/**\n * The control that answers one field, chosen by its kind. A read-only field,\n * or a kind with no control, shows its label, any refusal and its recorded\n * value instead.\n */\nexport function FieldControl(props: FieldControlProps) {\n  const renderers = useFieldRenderers();\n  const { field } = props;\n  const { Control } = renderers[fieldKind(field, renderers)]!;\n  if (field.readOnly || !Control)\n    return (\n      <div\n        className={`field ${props.error ? \"field-error\" : \"\"}`}\n        id={field.id}\n      >\n        <p className=\"field-label\">{field.label}</p>\n        {props.error && <FieldError name={field.id} error={props.error} />}\n        <div>\n          <FieldValue field={field} value={props.value} />\n        </div>\n      </div>\n    );\n  return <Control {...props} />;\n}\n",
      "type": "registry:component",
      "target": "@components/fields/field-control.tsx"
    },
    {
      "path": "fields/field-value.tsx",
      "content": "import type { FieldModel, JsonValue } from \"@registrystack/app-runtime\";\nimport { useBlockContent, useLocale } from \"@/blocks/lib/content\";\nimport { fieldKind, useFieldRenderers } from \"@/blocks/fields/renderers\";\nimport { QuantityValue, quantityPresentation } from \"@/blocks/fields/values\";\n\n/**\n * One recorded value, in the words and format its field model describes. A\n * missing value or an empty list reads as the field's own empty label, else\n * as not recorded, and a blank answer in the words the content keeps for that\n * field; any other value goes to the\n * renderer the field's kind chooses.\n */\nexport function FieldValue({\n  field,\n  value,\n}: {\n  field: FieldModel;\n  value: JsonValue | undefined;\n}) {\n  const c = useBlockContent(),\n    locale = useLocale(),\n    renderers = useFieldRenderers();\n  const none = field.emptyLabel ?? c.notRecorded;\n  if (value === undefined || value === null) return <>{none}</>;\n  if (value === \"\") return <>{c.blankValues[field.id] ?? none}</>;\n  if (Array.isArray(value) && value.length === 0) return <>{none}</>;\n  const quantity = quantityPresentation(value, field, locale);\n  if (quantity) return <QuantityValue {...quantity} />;\n  const { Value } = renderers[fieldKind(field, renderers)]!;\n  return <Value field={field} value={value} />;\n}\n",
      "type": "registry:component",
      "target": "@components/fields/field-value.tsx"
    },
    {
      "path": "fields/group-field.tsx",
      "content": "import { createContext, useContext, useEffect, useState, type ReactNode } from \"react\";\nimport type { FieldModel, JsonValue } from \"@registrystack/app-runtime\";\nimport { blockContent, useBlockContent, useLocale } from \"@/blocks/lib/content\";\nimport { fill } from \"@/blocks/lib/format\";\nimport { ScrollRegion } from \"@/blocks/lib/scroll-region\";\nimport { describedBy } from \"@/blocks/fields/input-field\";\nimport { FieldControl } from \"@/blocks/fields/field-control\";\nimport { FieldValue } from \"@/blocks/fields/field-value\";\nimport { useInPhrase } from \"@/blocks/fields/values\";\nimport type {\n  FieldControlProps,\n  FieldValueProps,\n} from \"@/blocks/fields/renderers\";\n\ntype GroupItem = Record<string, JsonValue>;\n\n/** A group's own value, read as a list of item objects; anything else as none. */\nfunction asItems(value: JsonValue | undefined): GroupItem[] {\n  if (!Array.isArray(value)) return [];\n  return value.map((item) =>\n    item !== null && typeof item === \"object\" && !Array.isArray(item)\n      ? (item as GroupItem)\n      : {},\n  );\n}\n\n/** One item's own sub-field id, scoped to its item so items never collide. */\nfunction itemFieldId(field: FieldModel, index: number, subId: string): string {\n  return `${field.id}-${index}-${subId}`;\n}\n\n/** An object with one sub-field set, or removed when the answer is undefined. */\nfunction withSub(\n  item: GroupItem,\n  subId: string,\n  subValue: JsonValue | undefined,\n): GroupItem {\n  const next = { ...item };\n  if (subValue === undefined) delete next[subId];\n  else next[subId] = subValue;\n  return next;\n}\n\n/** A value read as an object of sub-field answers; anything else as none. */\nfunction asObject(value: JsonValue | undefined): GroupItem {\n  return value !== null && typeof value === \"object\" && !Array.isArray(value)\n    ? (value as GroupItem)\n    : {};\n}\n\n/**\n * A structured field's own object with one sub-field set. An optional field\n * whose sub-fields are all blank is no answer at all, so it reads back as\n * undefined and nothing is sent for it; a required field keeps its object so\n * the form can refuse the blanks.\n */\nexport function withSubValue(\n  field: FieldModel,\n  current: JsonValue | undefined,\n  subId: string,\n  subValue: JsonValue | undefined,\n): GroupItem | undefined {\n  const next = withSub(asObject(current), subId, subValue);\n  const blank = Object.values(next).every((value) => value === \"\");\n  return !field.required && blank ? undefined : next;\n}\n\n/** One labelled control per sub-field, each scoped to an id of its own. */\nfunction SubFieldControls({\n  subs,\n  item,\n  idOf,\n  onChange,\n}: {\n  subs: readonly FieldModel[];\n  item: GroupItem;\n  idOf: (subId: string) => string;\n  onChange: (subId: string, value: JsonValue | undefined) => void;\n}) {\n  return subs.map((sub) => (\n    <FieldControl\n      key={sub.id}\n      field={{ ...sub, id: idOf(sub.id) }}\n      value={item[sub.id]}\n      onChange={(next) => onChange(sub.id, next)}\n    />\n  ));\n}\n\n/** The fieldset, legend, hint and single error a group and a structured field share. */\nfunction GroupFieldset({\n  field,\n  error,\n  children,\n}: {\n  field: FieldModel;\n  error?: string | undefined;\n  children: ReactNode;\n}) {\n  const c = useBlockContent();\n  return (\n    <fieldset\n      id={field.id}\n      tabIndex={-1}\n      className={`field group-field ${error ? \"field-error\" : \"\"}`}\n      aria-describedby={describedBy(field.id, field.hint, error)}\n      aria-invalid={!!error}\n    >\n      <legend>{field.label}</legend>\n      {field.hint && (\n        <p className=\"field-hint\" id={`${field.id}-hint`}>\n          {field.hint}\n        </p>\n      )}\n      {error && (\n        <p className=\"field-error-message\" id={`${field.id}-error`}>\n          <span className=\"sr-only\">{c.errorPrefix} </span>\n          {error}\n        </p>\n      )}\n      {children}\n    </fieldset>\n  );\n}\n\n/**\n * A single structured object's sub-fields: one labelled control per\n * sub-field, the same control a top-level field of that kind uses, scoped to\n * an id under the field's own. The field carries a single error message at\n * its own fieldset, as a group does.\n */\nexport function StructuredControl({\n  field,\n  value,\n  onChange,\n  error,\n}: FieldControlProps) {\n  return (\n    <GroupFieldset field={field} error={error}>\n      <SubFieldControls\n        subs={field.items ?? []}\n        item={asObject(value)}\n        idOf={(subId) => `${field.id}-${subId}`}\n        onChange={(subId, next) =>\n          onChange(withSubValue(field, value, subId, next))\n        }\n      />\n    </GroupFieldset>\n  );\n}\n\nconst ValueScopeContext = createContext<string | undefined>(undefined);\n\n/**\n * Names the side of a comparison the values inside belong to (\"Current\",\n * \"Proposed\"), so two scroll regions for the same group on one page carry\n * different labels.\n */\nexport function ValueScope({\n  label,\n  children,\n}: {\n  label: string;\n  children: ReactNode;\n}) {\n  return (\n    <ValueScopeContext.Provider value={label}>\n      {children}\n    </ValueScopeContext.Provider>\n  );\n}\n\n/**\n * A repeatable group's items, as a table with one column per sub-field. Each\n * cell reads through that sub-field's own renderer, so a coded value shows\n * its label the same way a top-level field's does. Inside a link or a line\n * of text, which can hold no table or scroll region, it is the number of its\n * items.\n */\nexport function GroupValue({ field, value }: FieldValueProps) {\n  const c = useBlockContent();\n  const locale = useLocale();\n  const items = asItems(value);\n  const subs = field.items ?? [];\n  const scope = useContext(ValueScopeContext);\n  const inPhrase = useInPhrase();\n  if (inPhrase)\n    return (\n      <>\n        {fill(\nc.groupEntryCount ?? blockContent.groupEntryCount!,\n          { count: items.length },\n          locale,\n        )}\n      </>\n    );\n  return (\n    <ScrollRegion\n      className=\"value-table-scroll\"\n      label={scope ? `${field.label}, ${scope}` : field.label}\n    >\n      <table className=\"value-table group-value\">\n        <thead>\n          <tr>\n            {subs.map((sub) => (\n              <th key={sub.id} scope=\"col\">\n                {sub.label}\n              </th>\n            ))}\n          </tr>\n        </thead>\n        <tbody>\n          {items.map((item, index) => (\n            <tr key={index}>\n              {subs.map((sub) => (\n                <td key={sub.id}>\n                  <FieldValue field={sub} value={item[sub.id]} />\n                </td>\n              ))}\n            </tr>\n          ))}\n        </tbody>\n      </table>\n    </ScrollRegion>\n  );\n}\n\n/**\n * A repeatable group's items: one fieldset per item, holding a labelled\n * control per sub-field (the same control a top-level field of that kind\n * uses, scoped to a per-item id so items never collide), a button to remove\n * that item, and a button to add another, in the field's own words where the\n * UI model gives them. The group carries a single error\n * message at its own fieldset, the way a checkbox group does; a sub-field's\n * own refusal is reported there rather than beside that sub-field, since the\n * host validates a write as a whole and does not say which item failed.\n *\n * Focus moves to the new item's first editable sub-field after an add, and\n * after a remove to the item that took the removed one's place, or to the\n * add button when none did.\n */\nexport function GroupControl({\n  field,\n  value,\n  onChange,\n  error,\n}: FieldControlProps) {\n  const c = useBlockContent();\n  const locale = useLocale();\n  const [pendingFocus, setPendingFocus] = useState<string | null>(null);\n  const items = asItems(value);\n  const subs = field.items ?? [];\n  const firstEditable = subs.find((sub) => !sub.readOnly)?.id;\n  const addButtonId = `${field.id}-add`;\n\n  // Retries each render until the focus target has mounted, then focuses it\n  // once and stops. The target only exists once the parent has re-rendered\n  // this control with the updated value, which happens after this effect is\n  // first scheduled.\n  useEffect(() => {\n    if (!pendingFocus) return;\n    const target = document.getElementById(pendingFocus);\n    if (target) {\n      target.focus();\n      setPendingFocus(null);\n    }\n  });\n\n  function updateItem(\n    index: number,\n    subId: string,\n    subValue: JsonValue | undefined,\n  ) {\n    onChange(\n      items.map((item, i) =>\n        i === index ? withSub(item, subId, subValue) : item,\n      ),\n    );\n  }\n\n  function addItem() {\n    const index = items.length;\n    onChange([...items, {}]);\n    setPendingFocus(\n      firstEditable ? itemFieldId(field, index, firstEditable) : addButtonId,\n    );\n  }\n\n  function removeItem(index: number) {\n    const next = items.filter((_, i) => i !== index);\n    onChange(next);\n    setPendingFocus(\n      index < next.length && firstEditable\n        ? itemFieldId(field, index, firstEditable)\n        : addButtonId,\n    );\n  }\n\n  return (\n    <GroupFieldset field={field} error={error}>\n      {items.map((item, index) => (\n        <fieldset key={index} className=\"group-item\">\n          <legend>\n            {fill(\n              c.groupItemLegend ?? blockContent.groupItemLegend!,\n              { index: index + 1 },\n              locale,\n            )}\n          </legend>\n          <SubFieldControls\n            subs={subs}\n            item={item}\n            idOf={(subId) => itemFieldId(field, index, subId)}\n            onChange={(subId, next) => updateItem(index, subId, next)}\n          />\n          <button type=\"button\" onClick={() => removeItem(index)}>\n            {fill(\n              c.removeGroupItem ?? blockContent.removeGroupItem!,\n              { index: index + 1 },\n              locale,\n            )}\n          </button>\n        </fieldset>\n      ))}\n      <button type=\"button\" id={addButtonId} onClick={addItem}>\n        {field.addItemLabel ?? c.addGroupItem ?? blockContent.addGroupItem}\n      </button>\n    </GroupFieldset>\n  );\n}\n",
      "type": "registry:component",
      "target": "@components/fields/group-field.tsx"
    },
    {
      "path": "fields/input-field.tsx",
      "content": "import type { ChangeEvent, ComponentProps, ReactNode } from \"react\";\nimport { Input, Textarea } from \"@/components/ui/input\";\nimport { useBlockContent, type BlockContent } from \"@/blocks/lib/content\";\n\nexport interface FieldOptionWords {\n  value: string;\n  label: string;\n}\n\n/** The words for one option: the content's term first, then the option's own. */\nexport function optionWords(content: BlockContent, option: FieldOptionWords) {\n  return content.terms[option.value] ?? option.label;\n}\n\n/** The ids of a control's hint and error, for `aria-describedby`. */\nexport function describedBy(name: string, hint: ReactNode, error?: string) {\n  return (\n    [hint ? `${name}-hint` : \"\", error ? `${name}-error` : \"\"]\n      .filter(Boolean)\n      .join(\" \") || undefined\n  );\n}\n\n/** The message a field was refused with, announced with the error prefix. */\nexport function FieldError({ name, error }: { name: string; error: string }) {\n  const c = useBlockContent();\n  return (\n    <p className=\"field-error-message\" id={`${name}-error`}>\n      <span className=\"sr-only\">{c.errorPrefix} </span>\n      {error}\n    </p>\n  );\n}\n\n/** A labelled field's label, hint and error, above its control. */\nexport function FieldFrame({\n  name,\n  label,\n  labelId,\n  hint,\n  error,\n  required,\n  children,\n}: {\n  name: string;\n  label: string;\n  /** An id for the label, for controls that name themselves by it beside their own label. */\n  labelId?: string;\n  hint?: ReactNode;\n  error?: string;\n  required: boolean;\n  children: ReactNode;\n}) {\n  const c = useBlockContent();\n  return (\n    <div className={`field ${error ? \"field-error\" : \"\"}`}>\n      <label htmlFor={name} id={labelId}>\n        {label}\n        {!required && <span className=\"optional\"> ({c.optional})</span>}\n      </label>\n      {hint && (\n        <p className=\"field-hint\" id={`${name}-hint`}>\n          {hint}\n        </p>\n      )}\n      {error && <FieldError name={name} error={error} />}\n      {children}\n    </div>\n  );\n}\n\n/**\n * One labelled text input, textarea or option list, with its hint and error\n * tied to it. The input's id and name are the field's name.\n */\nexport function InputField({\n  name,\n  label,\n  value,\n  onChange,\n  error,\n  hint,\n  multiline = false,\n  type = \"text\",\n  required = true,\n  options,\n  min,\n  max,\n  step,\n}: {\n  name: string;\n  label: string;\n  value: string;\n  onChange: (v: string) => void;\n  error?: string;\n  hint?: string;\n  multiline?: boolean;\n  type?: string;\n  required?: boolean;\n  options?: readonly FieldOptionWords[];\n  /** Numeric and date bounds, passed to the input as written. */\n  min?: number;\n  max?: number;\n  step?: number | \"any\";\n}) {\n  const c = useBlockContent();\n  const props = {\n    id: name,\n    name,\n    value,\n    onChange: (\n      e: ChangeEvent<\n        HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement\n      >,\n    ) => onChange(e.target.value),\n    \"aria-invalid\": !!error,\n    \"aria-describedby\": describedBy(name, hint, error),\n    required,\n  };\n  return (\n    <FieldFrame\n      name={name}\n      label={label}\n      hint={hint}\n      error={error}\n      required={required}\n    >\n      {options?.length ? (\n        <select {...props}>\n          <option value=\"\">{c.selectOption}</option>\n          {options.map((option) => (\n            <option key={option.value} value={option.value}>\n              {optionWords(c, option)}\n            </option>\n          ))}\n        </select>\n      ) : multiline ? (\n        <Textarea {...props} />\n      ) : (\n        <Input\n          {...props}\n          type={type}\n          {...(min !== undefined ? { min } : {})}\n          {...(max !== undefined ? { max } : {})}\n          {...(step !== undefined ? { step } : {})}\n        />\n      )}\n    </FieldFrame>\n  );\n}\n\n/** A yes or no choice that may be left unanswered, with a line under it. */\nexport function YesNoField({\n  name,\n  label,\n  value,\n  onChange,\n  error,\n  hint,\n  required,\n  note,\n}: {\n  name: string;\n  label: string;\n  value: boolean | undefined;\n  onChange: (value: boolean | undefined) => void;\n  error?: string;\n  hint?: string;\n  required: boolean;\n  note?: ReactNode;\n}) {\n  return (\n    <FieldFrame\n      name={name}\n      label={label}\n      hint={hint}\n      error={error}\n      required={required}\n    >\n      <YesNoSelect\n        id={name}\n        value={value}\n        onChange={onChange}\n        aria-invalid={!!error}\n        aria-describedby={describedBy(name, hint, error)}\n      />\n      {note}\n    </FieldFrame>\n  );\n}\n\n/**\n * The yes or no select itself, whose empty choice leaves the answer unset; a\n * page that lays out its own label uses it in place of `YesNoField`.\n */\nexport function YesNoSelect({\n  value,\n  onChange,\n  ...props\n}: Omit<ComponentProps<\"select\">, \"value\" | \"onChange\" | \"children\"> & {\n  value: boolean | undefined;\n  onChange: (value: boolean | undefined) => void;\n}) {\n  const c = useBlockContent();\n  return (\n    <select\n      {...props}\n      value={value === undefined ? \"\" : String(value)}\n      onChange={(event) =>\n        onChange(\n          event.target.value === \"\" ? undefined : event.target.value === \"true\",\n        )\n      }\n    >\n      <option value=\"\">{c.notSupplied}</option>\n      <option value=\"true\">{c.yes}</option>\n      <option value=\"false\">{c.no}</option>\n    </select>\n  );\n}\n\n/** A group of checkboxes, one per option, whose answer is the checked values. */\nexport function ChoiceField({\n  name,\n  label,\n  value,\n  options,\n  onChange,\n  error,\n  hint,\n}: {\n  name: string;\n  label: string;\n  value: readonly string[];\n  options: readonly FieldOptionWords[];\n  onChange: (value: string[]) => void;\n  error?: string;\n  hint?: string;\n}) {\n  const c = useBlockContent();\n  return (\n    <fieldset\n      id={name}\n      tabIndex={-1}\n      className={`field choice-field ${error ? \"field-error\" : \"\"}`}\n      aria-describedby={`${name}-hint${error ? ` ${name}-error` : \"\"}`}\n      aria-invalid={!!error}\n    >\n      <legend>{label}</legend>\n      <p className=\"field-hint\" id={`${name}-hint`}>\n        {hint ?? c.choicesHint}\n      </p>\n      {error && (\n        <p className=\"field-error-message\" id={`${name}-error`}>\n          <span className=\"sr-only\">{c.errorPrefix} </span>\n          {error}\n        </p>\n      )}\n      {options.map((option) => (\n        <label className=\"checkbox-option\" key={option.value}>\n          <input\n            type=\"checkbox\"\n            name={name}\n            value={option.value}\n            checked={value.includes(option.value)}\n            onChange={(event) =>\n              onChange(\n                event.target.checked\n                  ? [...value, option.value]\n                  : value.filter((item) => item !== option.value),\n              )\n            }\n          />\n          <span>{optionWords(c, option)}</span>\n        </label>\n      ))}\n    </fieldset>\n  );\n}\n",
      "type": "registry:component",
      "target": "@components/fields/input-field.tsx"
    },
    {
      "path": "fields/reference-picker.tsx",
      "content": "import { useEffect, useReducer, useState, type ReactNode } from \"react\";\nimport {\n  problemView,\n  type EntityModel,\n  type LookupModel,\n  type RecordView,\n} from \"@registrystack/app-runtime\";\nimport {\n  useModel,\n  useRecord,\n  useRecordLookup,\n  useRecordPages,\n} from \"@registrystack/app-runtime/react\";\nimport { Button } from \"@/components/ui/button\";\nimport { Input } from \"@/components/ui/input\";\nimport {\n  blockContent,\n  useBlockContent,\n  useLocale,\n} from \"@/blocks/lib/content\";\nimport { fill, listOf } from \"@/blocks/lib/format\";\nimport { controlValue } from \"@/blocks/fields/controls\";\nimport {\n  describedBy,\n  FieldFrame,\n  YesNoSelect,\n} from \"@/blocks/fields/input-field\";\nimport {\n  recordTitle,\n  ReferenceHrefProvider,\n  ReferenceValue,\n  useChosenReferences,\n} from \"@/blocks/fields/reference-value\";\nimport type { FieldControlProps } from \"@/blocks/fields/renderers\";\nimport { mentions, namedFor, selectorNamedFor } from \"@/blocks/lib/format\";\n\n/** Milliseconds a typed search waits for the next keystroke before it is read. */\nconst searchDelay = 250;\n\nfunction useDebounced(value: string): string {\n  const [settled, setSettled] = useState(value);\n  useEffect(() => {\n    const timer = setTimeout(() => setSettled(value), searchDelay);\n    return () => clearTimeout(timer);\n  }, [value]);\n  return settled;\n}\n\n/** The most columns, besides the title, an option shows to tell records apart. */\nconst detailColumns = 2;\n\n/**\n * The values of the target's list columns, besides its title, that a record\n * holds, in the words of the field's own options: what the session's own list\n * already shows.\n */\nfunction detailOf(\n  entity: EntityModel,\n  values: Record<string, unknown>,\n): string[] {\n  return entity.list.columns\n    .filter((id) => id !== entity.title)\n    .flatMap((id) => {\n      const held = values[id];\n      if (typeof held !== \"string\" && typeof held !== \"number\") return [];\n      const word = entity.fields\n        .find((field) => field.id === id)\n        ?.options?.find((option) => option.value === held)?.label;\n      return word ?? String(held);\n    })\n    .filter((held) => held !== \"\")\n    .slice(0, detailColumns);\n}\n\n/**\n * Authorized pages of a target entity a reference can be answered with, each\n * by its title (its id where the entity has no title). Records that share a\n * title also carry the values that tell them apart. A continuation keeps the\n * earlier choices and follows only the host's opaque cursor.\n */\nfunction useCandidates(entity: EntityModel, search: string) {\n  const c = useBlockContent(),\n    locale = useLocale();\n  const records = useRecordPages(entity.id, {\n    size: entity.list.pageSize,\n    ...(search ? { search } : {}),\n  });\n  const titled = records.error\n    ? []\n    : (records.data?.pages.flatMap((page) =>\n        page.items.map((record) => ({\n          id: record.id,\n          title: recordTitle(entity, record.values, locale) ?? record.id,\n          values: record.values,\n        })),\n      ) ?? []);\n  const options = titled.map(({ values, ...option }) => ({\n    ...option,\n    detail:\n      titled.filter((other) => other.title === option.title).length > 1\n        ? detailOf(entity, values)\n        : [],\n  }));\n  const status = records.isPending\n    ? c.loading\n    : records.error\n      ? (c.referenceLoadFailed ?? blockContent.referenceLoadFailed)\n      : options.length === 0\n        ? (c.referenceNoMatch ?? blockContent.referenceNoMatch)\n        : undefined;\n  return {\n    options,\n    status,\n    hasMore: !records.error && records.hasNextPage,\n    loadingMore: records.isFetchingNextPage,\n    restarting: records.isFetching && !records.isFetchingNextPage,\n    loadMore: records.fetchNextPage,\n    advanced: records.advanced,\n    restart: records.restart,\n  };\n}\n\ninterface Candidate {\n  id: string;\n  title: string;\n  /** Other list values of the record, to tell it from one with the same title. */\n  detail?: string[];\n}\n\ntype PickerProps = FieldControlProps & {\n  entity: EntityModel;\n  select: (candidate: Candidate) => void;\n};\n\nfunction MoreCandidates({\n  candidates,\n}: {\n  candidates: ReturnType<typeof useCandidates>;\n}) {\n  const c = useBlockContent();\n  return candidates.hasMore || candidates.advanced ? (\n    <>\n      {candidates.hasMore && (\n        <Button\n          type=\"button\"\n          variant=\"outline\"\n          disabled={candidates.loadingMore || candidates.restarting}\n          onClick={() => void candidates.loadMore()}\n        >\n          {candidates.loadingMore\n            ? c.loading\n            : (c.referenceMore ?? blockContent.referenceMore)}\n        </Button>\n      )}\n      {candidates.advanced && (\n        <Button\n          type=\"button\"\n          variant=\"outline\"\n          disabled={candidates.loadingMore || candidates.restarting}\n          onClick={() => void candidates.restart()}\n        >\n          {candidates.restarting\n            ? c.loading\n            : (c.referenceRestart ?? blockContent.referenceRestart)}\n        </Button>\n      )}\n    </>\n  ) : null;\n}\n\n/** A search input over the target's records; a match is chosen from the list under it. */\nfunction SearchPicker({ field, error, entity, select }: PickerProps) {\n  const locale = useLocale();\n  const [typed, setTyped] = useState(\"\");\n  const candidates = useCandidates(entity, useDebounced(typed.trim()));\n  return (\n    <>\n      <Input\n        id={field.id}\n        name={field.id}\n        type=\"search\"\n        value={typed}\n        autoComplete=\"off\"\n        aria-invalid={!!error}\n        aria-describedby={describedBy(field.id, field.hint, error)}\n        onChange={(event) => setTyped(event.target.value)}\n      />\n      {candidates.status && <p role=\"status\">{candidates.status}</p>}\n      <ul className=\"reference-options\">\n        {candidates.options.map((option) => (\n          <li key={option.id}>\n            <button type=\"button\" onClick={() => select(option)}>\n              {option.title}\n              {option.detail?.length ? (\n                <span className=\"reference-detail\">\n                  {\" \"}\n                  {listOf(option.detail, locale)}\n                </span>\n              ) : null}\n            </button>\n          </li>\n        ))}\n      </ul>\n      <MoreCandidates candidates={candidates} />\n    </>\n  );\n}\n\nfunction ChoicePicker({\n  field,\n  error,\n  select,\n  candidates: { options, status },\n}: PickerProps & { candidates: ReturnType<typeof useCandidates> }) {\n  const c = useBlockContent();\n  const locale = useLocale();\n  return (\n    <>\n      <select\n        id={field.id}\n        name={field.id}\n        value=\"\"\n        aria-invalid={!!error}\n        aria-describedby={describedBy(field.id, field.hint, error)}\n        onChange={(event) => {\n          const option = options.find(\n            (candidate) => candidate.id === event.target.value,\n          );\n          if (option) select(option);\n        }}\n      >\n        <option value=\"\">\n          {c.referenceChoose ?? blockContent.referenceChoose}\n        </option>\n        {options.map((option) => (\n          <option key={option.id} value={option.id}>\n            {option.detail?.length\n              ? fill(\n                  c.referenceOption ?? blockContent.referenceOption!,\n                  {\n                    title: option.title,\n                    detail: listOf(option.detail, locale),\n                  },\n                  locale,\n                )\n              : option.title}\n          </option>\n        ))}\n      </select>\n      {status && <p role=\"status\">{status}</p>}\n    </>\n  );\n}\n\n/**\n * A bounded, paged choice for a target without a supported search.\n */\nfunction ChoiceReference(props: PickerProps) {\n  const candidates = useCandidates(props.entity, \"\");\n  return (\n    <>\n      <ChoicePicker {...props} candidates={candidates} />\n      <MoreCandidates candidates={candidates} />\n    </>\n  );\n}\n\n/** The id of the reference field's own label, which lookup controls are named by. */\nconst frameLabelId = (field: { id: string }) => `${field.id}-label`;\n\n/**\n * An exact identifier lookup for a target the session may get but not list.\n * Typed text is never the answer: only the record returned by the authorized\n * host route can be selected. Alone, the input is the field's own control;\n * after lookup selectors it has an id and a label of its own. A record the\n * host does not hold, or will not show, reads as the neutral unavailable\n * answer; any other failure reads as a failure with a retry.\n */\nfunction ExactReference({\n  field,\n  error,\n  entity,\n  select,\n  afterSelectors = false,\n}: PickerProps & { afterSelectors?: boolean }) {\n  const c = useBlockContent(),\n    locale = useLocale();\n  const inputId = afterSelectors ? `${field.id}-identifier` : field.id;\n  const [typed, setTyped] = useState(\"\");\n  const [lookupId, setLookupId] = useState(\"\");\n  const record = useRecord(entity.id, lookupId);\n  const requested = lookupId !== \"\" && lookupId === typed.trim();\n  const candidate =\n    requested && !record.error && !record.isFetching && record.data\n      ? {\n          id: record.data.id,\n          title: recordTitle(entity, record.data.values, locale) ?? record.data.id,\n        }\n      : undefined;\n  const find = () => {\n    const id = typed.trim();\n    if (!id) return;\n    if (id === lookupId) void record.refetch();\n    else setLookupId(id);\n  };\n  const lookupHint = c.referenceLookupHint ?? blockContent.referenceLookupHint;\n  return (\n    <>\n      {afterSelectors && (\n        <label htmlFor={inputId} id={`${inputId}-label`}>\n          {c.referenceIdentifier ?? blockContent.referenceIdentifier}\n        </label>\n      )}\n      <Input\n        id={inputId}\n        name={inputId}\n        type=\"search\"\n        value={typed}\n        autoComplete=\"off\"\n        aria-invalid={!!error}\n        {...(afterSelectors\n          ? {\n              \"aria-labelledby\": `${frameLabelId(field)} ${inputId}-label`,\n            }\n          : {})}\n        aria-describedby={[\n          describedBy(field.id, field.hint, error),\n          `${inputId}-lookup-hint`,\n        ]\n          .filter(Boolean)\n          .join(\" \")}\n        onChange={(event) => setTyped(event.target.value)}\n        onKeyDown={(event) => {\n          if (event.key !== \"Enter\") return;\n          event.preventDefault();\n          find();\n        }}\n      />\n      <p id={`${inputId}-lookup-hint`}>{lookupHint}</p>\n      <Button\n        type=\"button\"\n        variant=\"outline\"\n        disabled={!typed.trim()}\n        onClick={find}\n      >\n        {c.referenceFind ?? blockContent.referenceFind}\n      </Button>\n      {requested && record.isFetching && <p role=\"status\">{c.loading}</p>}\n      {requested &&\n        !record.isFetching &&\n        record.error &&\n        (problemView(record.error).kind === \"unavailable\" ? (\n          <p role=\"status\">\n            {c.referenceLookupUnavailable ??\n              blockContent.referenceLookupUnavailable}\n          </p>\n        ) : (\n          <div role=\"alert\">\n            <p>{c.referenceLoadFailed ?? blockContent.referenceLoadFailed}</p>\n            <Button\n              type=\"button\"\n              variant=\"outline\"\n              onClick={() => void record.refetch()}\n            >\n              {c.referenceRetry ?? blockContent.referenceRetry}\n            </Button>\n          </div>\n        ))}\n      {candidate && (\n        <ul className=\"reference-options\">\n          <li>\n            <button type=\"button\" onClick={() => select(candidate)}>\n              {candidate.title}\n            </button>\n          </li>\n        </ul>\n      )}\n    </>\n  );\n}\n\ntype LookupSelector = LookupModel[\"selectors\"][number];\n\n/** What one selector lookup holds: the values typed and the find they were sent in. */\ninterface LookupState {\n  values: Record<string, string>;\n  /** The values the latest find sent, until any value changes. */\n  asked: Record<string, string> | null;\n  /** The record that find returned, while its values stand. */\n  found: RecordView | null;\n}\n\ntype LookupStep =\n  | { kind: \"typed\"; field: string; value: string }\n  | { kind: \"asked\"; values: Record<string, string> }\n  | {\n      kind: \"answered\";\n      values: Record<string, string>;\n      record: RecordView | null;\n    };\n\nconst noLookup: LookupState = { values: {}, asked: null, found: null };\n\n/**\n * A changed value is a new question, so it drops the earlier find and its\n * answer. An answer counts only for the values it was asked with, while they\n * still stand.\n */\nfunction lookupStep(state: LookupState, step: LookupStep): LookupState {\n  switch (step.kind) {\n    case \"typed\":\n      return {\n        values: { ...state.values, [step.field]: step.value },\n        asked: null,\n        found: null,\n      };\n    case \"asked\":\n      return { ...state, asked: step.values, found: null };\n    case \"answered\":\n      return step.values === state.asked\n        ? { ...state, found: step.record }\n        : state;\n  }\n}\n\n/**\n * One BReg lookup selector of the target, grouped under its label: a control\n * per selector field and Find. The values go to the host's lookup route only\n * when the person asks to find. Typed values are never the answer: only the\n * record the host returns can be chosen. A miss reads as the neutral\n * unavailable answer; any other failure reads as a failure with a retry.\n */\nfunction SelectorLookup({\n  field,\n  error,\n  entity,\n  select,\n  selector,\n  index,\n}: PickerProps & { selector: LookupSelector; index: number }) {\n  const c = useBlockContent(),\n    locale = useLocale();\n  const { lookup, pending, error: failure } = useRecordLookup(entity.id);\n  const [state, step] = useReducer(lookupStep, noLookup);\n  // The first control replaces the chosen view, so it carries the field's id.\n  const controlId = (at: number) =>\n    index === 0 && at === 0 ? field.id : `${field.id}-lookup-${index}-${at}`;\n  const ready =\n    !pending &&\n    selector.fields.every(\n      (input) =>\n        !input.required || (state.values[input.id] ?? \"\").trim() !== \"\",\n    );\n  async function find() {\n    if (!ready) return;\n    const values = state.values;\n    step({ kind: \"asked\", values });\n    const record = await lookup(selector.id, values);\n    step({ kind: \"answered\", values, record });\n  }\n  const answered = !pending && state.asked === state.values;\n  const candidate = state.found && {\n    id: state.found.id,\n    title: recordTitle(entity, state.found.values, locale) ?? state.found.id,\n  };\n  // An exact match of the values asked is the answer: it is chosen without a\n  // further click. The candidate stays below in case the choice is undone.\n  useEffect(() => {\n    if (candidate) select(candidate);\n  }, [state.found]);\n  // A label the registry derived (\"By record code\") names the target type,\n  // and so do its controls; a declared label stays as the model words it.\n  const legend = selectorNamedFor(selector, entity.label, locale);\n  const derived = legend !== selector.label;\n  const ownLabel = (label: string) =>\n    derived ? namedFor(label, entity.label, locale) : label;\n  // A field already labelled with the target type is not named by it twice.\n  const fieldNamesType = derived && mentions(field.label, entity.label);\n  return (\n    <fieldset>\n      <legend className=\"field-label\">{legend}</legend>\n      <div className=\"search-form\">\n        {selector.fields.map((input, at) => {\n          const id = controlId(at);\n          const value = state.values[input.id] ?? \"\";\n          const change = (typed: string) =>\n            step({ kind: \"typed\", field: input.id, value: typed });\n          const named = {\n            \"aria-labelledby\": fieldNamesType\n              ? `${id}-own-label`\n              : `${frameLabelId(field)} ${id}-own-label`,\n            ...(index === 0 && at === 0\n              ? {\n                  \"aria-invalid\": !!error,\n                  \"aria-describedby\": describedBy(field.id, field.hint, error),\n                }\n              : {}),\n          };\n          return (\n            <div key={input.id}>\n              {/* The field's own label already points at the first control. */}\n              <label\n                id={`${id}-own-label`}\n                {...(id === field.id ? {} : { htmlFor: id })}\n              >\n                {ownLabel(input.label)}\n              </label>\n              {input.type === \"boolean\" ? (\n                // The host sends the choice's \"true\" or \"false\" as JSON.\n                <YesNoSelect\n                  id={id}\n                  value={value === \"\" ? undefined : value === \"true\"}\n                  disabled={pending}\n                  onChange={(chosen) =>\n                    change(chosen === undefined ? \"\" : String(chosen))\n                  }\n                  {...named}\n                />\n              ) : (\n                <Input\n                  id={id}\n                  value={value}\n                  readOnly={pending}\n                  autoComplete=\"off\"\n                  {...(input.type === \"integer\"\n                    ? { inputMode: \"numeric\" as const }\n                    : {})}\n                  onChange={(event) => change(event.target.value)}\n                  onKeyDown={(event) => {\n                    if (event.key !== \"Enter\") return;\n                    // The picker sits in the form it answers; Enter here finds.\n                    event.preventDefault();\n                    void find();\n                  }}\n                  {...named}\n                />\n              )}\n            </div>\n          );\n        })}\n        <Button\n          type=\"button\"\n          variant=\"outline\"\n          disabled={!ready}\n          onClick={() => void find()}\n        >\n          {c.referenceFind ?? blockContent.referenceFind}\n        </Button>\n      </div>\n      {pending && <p role=\"status\">{c.loading}</p>}\n      {answered &&\n        failure != null &&\n        (problemView(failure).kind === \"unavailable\" ? (\n          <p role=\"status\">\n            {c.referenceLookupUnavailable ??\n              blockContent.referenceLookupUnavailable}\n          </p>\n        ) : (\n          <div role=\"alert\">\n            <p>{c.referenceLoadFailed ?? blockContent.referenceLoadFailed}</p>\n            <Button type=\"button\" variant=\"outline\" onClick={() => void find()}>\n              {c.referenceRetry ?? blockContent.referenceRetry}\n            </Button>\n          </div>\n        ))}\n      {candidate && (\n        <ul className=\"reference-options\">\n          <li>\n            <button type=\"button\" onClick={() => select(candidate)}>\n              {candidate.title}\n            </button>\n          </li>\n        </ul>\n      )}\n    </fieldset>\n  );\n}\n\n/**\n * The lookups for a target the session may not list: one per BReg lookup\n * selector, then the exact identifier lookup where the session may also get.\n */\nfunction LookupReference(props: PickerProps & { lookup: LookupModel }) {\n  const c = useBlockContent();\n  const { lookup, ...picker } = props;\n  return (\n    <>\n      {lookup.selectors.map((selector, index) => (\n        <SelectorLookup\n          key={selector.id}\n          {...picker}\n          selector={selector}\n          index={index}\n        />\n      ))}\n      {picker.entity.operations.get && (\n        <details className=\"alternative\">\n          <summary>\n            {c.referenceIdentifierOther ??\n              blockContent.referenceIdentifierOther}\n          </summary>\n          <ExactReference {...picker} afterSelectors />\n        </details>\n      )}\n    </>\n  );\n}\n\n/**\n * The control that answers a reference field with a record of its target\n * entity, never an id typed or pasted. A listable entity offers authorized\n * cursor pages, with search when the contract supports it. A non-listable\n * entity with BReg lookup selectors offers one lookup per selector, then the\n * exact identifier lookup where it is also exactly readable; one that is only\n * exactly readable accepts an identifier only as a lookup. Either way the\n * returned record is offered to choose. A target with none of these is neutral.\n */\nexport function ReferenceControl(props: FieldControlProps) {\n  const { field, value, error } = props;\n  const c = useBlockContent(),\n    model = useModel(),\n    chosenReferences = useChosenReferences();\n  const entity = model.data?.entities.find(\n    (e) => e.id === field.reference?.entity,\n  );\n  const chosen = typeof value === \"string\" && value !== \"\";\n  const [selected, setSelected] = useState<Candidate | null>(null);\n  // The chosen state of the answer that focus is waiting for. Choosing a record\n  // and changing it swap the control for the other one, so focus moves to the\n  // control that replaces it, which carries the field's id in both states.\n  const [focusWhenChosen, setFocusWhenChosen] = useState<boolean | null>(null);\n  useEffect(() => {\n    if (focusWhenChosen === null || focusWhenChosen !== chosen) return;\n    document.getElementById(field.id)?.focus();\n    setFocusWhenChosen(null);\n  });\n  const onChange: FieldControlProps[\"onChange\"] = (next) => {\n    setFocusWhenChosen(typeof next === \"string\" && next !== \"\");\n    if (typeof next !== \"string\" || next === \"\") setSelected(null);\n    props.onChange(next);\n  };\n  const select = (candidate: Candidate) => {\n    setSelected(candidate);\n    // A record the session cannot open was picked from a list read; its title\n    // is kept for a step that shows the answer once this control is gone.\n    if (entity && !entity.operations.get)\n      chosenReferences?.remember({\n        entity: entity.id,\n        id: candidate.id,\n        title: candidate.title,\n      });\n    onChange(controlValue(field, candidate.id));\n  };\n  // A record picked here before the control was last swapped out keeps its title.\n  const chosenTitle =\n    entity && typeof value === \"string\"\n      ? chosenReferences?.titleOf(entity.id, value)\n      : undefined;\n  const lookup =\n    entity &&\n    !entity.operations.list &&\n    entity.operations.lookup?.selectors.length\n      ? entity.operations.lookup\n      : undefined;\n  const frame = (children: ReactNode) => (\n    <FieldFrame\n      name={field.id}\n      label={field.label}\n      {...(lookup && !chosen ? { labelId: frameLabelId(field) } : {})}\n      hint={field.hint}\n      error={error}\n      required={field.required && !field.acceptsBlank}\n    >\n      {children}\n    </FieldFrame>\n  );\n  const chosenView = (\n    <p>\n      {/* The chosen title is text here; the page it names is not a way to answer the field. */}\n      <ReferenceHrefProvider href={() => null}>\n        <span id={`${field.id}-chosen`}>\n          {selected && selected.id === value ? (\n            selected.title\n          ) : entity?.operations.get || chosenTitle !== undefined ? (\n            <ReferenceValue field={field} value={value ?? \"\"} />\n          ) : (\n            (c.referenceUnavailable ?? blockContent.referenceUnavailable)\n          )}\n        </span>\n      </ReferenceHrefProvider>{\" \"}\n      <Button\n        type=\"button\"\n        variant=\"outline\"\n        id={field.id}\n        aria-describedby={`${field.id}-chosen`}\n        onClick={() => onChange(controlValue(field, \"\"))}\n      >\n        {c.referenceChange ?? blockContent.referenceChange}\n      </Button>\n    </p>\n  );\n  return frame(\n    model.isPending ? (\n      <p role=\"status\">{c.loading}</p>\n    ) : chosen ? (\n      chosenView\n    ) : !entity ? (\n      <p role=\"status\">\n        {c.referenceSelectionUnavailable ??\n          blockContent.referenceSelectionUnavailable}\n      </p>\n    ) : entity.operations.list ? (\n      entity.list.search?.length ? (\n        <SearchPicker\n          {...props}\n          onChange={onChange}\n          entity={entity}\n          select={select}\n        />\n      ) : (\n        <ChoiceReference\n          {...props}\n          onChange={onChange}\n          entity={entity}\n          select={select}\n        />\n      )\n    ) : lookup ? (\n      <LookupReference\n        {...props}\n        onChange={onChange}\n        entity={entity}\n        select={select}\n        lookup={lookup}\n      />\n    ) : entity.operations.get ? (\n      <ExactReference\n        {...props}\n        onChange={onChange}\n        entity={entity}\n        select={select}\n      />\n    ) : (\n      <p role=\"status\">\n        {c.referenceSelectionUnavailable ??\n          blockContent.referenceSelectionUnavailable}\n      </p>\n    ),\n  );\n}\n",
      "type": "registry:component",
      "target": "@components/fields/reference-picker.tsx"
    },
    {
      "path": "fields/reference-value.tsx",
      "content": "import {\n  createContext,\n  useContext,\n  useMemo,\n  useState,\n  type ReactNode,\n} from \"react\";\nimport type { EntityModel } from \"@registrystack/app-runtime\";\nimport { entityTitle } from \"@registrystack/app-runtime\";\nimport { useModel, useRecord } from \"@registrystack/app-runtime/react\";\nimport {\n  blockContent,\n  useBlockContent,\n  useLocale,\n} from \"@/blocks/lib/content\";\nimport type { FieldValueProps } from \"@/blocks/fields/renderers\";\n\n/**\n * A record's title: its entity's title template or field, as a record page\n * titles it, with a calendar date in `locale`.\n */\nexport function recordTitle(\n  entity: EntityModel,\n  values: Readonly<Record<string, unknown>>,\n  locale: string,\n): string | undefined {\n  return entityTitle(entity, (field) => values[field.id], locale);\n}\n\n/** Makes the href of a record's page, or null when it has none. */\nexport type ReferenceHref = (entity: string, id: string) => string | null;\n\nconst ReferenceHrefContext = createContext<ReferenceHref>(() => null);\n\n/** The link maker the blocks inside use for a shown reference; none without a provider. */\nexport function useReferenceHref(): ReferenceHref {\n  return useContext(ReferenceHrefContext);\n}\n\n/**\n * Gives the blocks inside a way to link a shown reference to its target's\n * page. A block does not know the app's routes, so the app supplies `href`,\n * which returns a full `#/...` href or null for a record with no page.\n */\nexport function ReferenceHrefProvider({\n  href,\n  children,\n}: {\n  href: ReferenceHref;\n  children?: ReactNode;\n}) {\n  return (\n    <ReferenceHrefContext.Provider value={href}>\n      {children}\n    </ReferenceHrefContext.Provider>\n  );\n}\n\n/** A record chosen on a form from an authorized list read, with the title it was listed under. */\nexport interface ChosenReference {\n  entity: string;\n  id: string;\n  title: string;\n}\n\ninterface ChosenReferences {\n  titleOf(entity: string, id: string): string | undefined;\n  remember(chosen: ChosenReference): void;\n}\n\nconst ChosenReferencesContext = createContext<ChosenReferences | null>(null);\nconst chosenKey = (entity: string, id: string) => JSON.stringify([entity, id]);\n\n/** The records chosen on the form inside; none without a provider. */\nexport function useChosenReferences(): ChosenReferences | null {\n  return useContext(ChosenReferencesContext);\n}\n\n/**\n * Holds the records chosen on the form inside, so a step that shows an answer\n * after its control is gone can still name a record the session may list but\n * not open. `initial` holds records already chosen.\n */\nexport function ChosenReferencesProvider({\n  initial = [],\n  children,\n}: {\n  initial?: readonly ChosenReference[];\n  children?: ReactNode;\n}) {\n  const [titles, setTitles] = useState<ReadonlyMap<string, string>>(\n    () =>\n      new Map(\n        initial.map((chosen) => [\n          chosenKey(chosen.entity, chosen.id),\n          chosen.title,\n        ]),\n      ),\n  );\n  const value = useMemo<ChosenReferences>(\n    () => ({\n      titleOf: (entity, id) => titles.get(chosenKey(entity, id)),\n      remember: ({ entity, id, title }) =>\n        setTitles((held) => {\n          const key = chosenKey(entity, id);\n          return held.get(key) === title ? held : new Map(held).set(key, title);\n        }),\n    }),\n    [titles],\n  );\n  return (\n    <ChosenReferencesContext.Provider value={value}>\n      {children}\n    </ChosenReferencesContext.Provider>\n  );\n}\n\n/**\n * A value that names a register record, shown as that record's title. The\n * record is read under the caller's own session, so a record the caller may\n * not read, an entity the model does not carry and a field that names no\n * target all read as the content's unavailable wording, never as the id. The\n * title links to the target's page when a `ReferenceHrefProvider` gives one.\n * A record chosen on this form, held by a `ChosenReferencesProvider`, is shown\n * by the title it was chosen under, as text, since the session may not open it.\n */\nexport function ReferenceValue({ field, value }: FieldValueProps) {\n  const c = useBlockContent(),\n    locale = useLocale(),\n    hrefOf = useReferenceHref(),\n    chosen = useChosenReferences();\n  const model = useModel();\n  const entity = model.data?.entities.find(\n    (e) => e.id === field.reference?.entity,\n  );\n  const id = typeof value === \"string\" ? value : \"\";\n  const canRead = entity?.operations.get === true;\n  // A read with no advertised exact-read operation is never enabled. List\n  // authority does not imply authority to retrieve a chosen reference by id.\n  const record = useRecord(entity?.id ?? \"\", canRead ? id : \"\");\n  const unavailable =\n    c.referenceUnavailable ?? blockContent.referenceUnavailable;\n  if (model.isPending) return <>{c.loading}</>;\n  const chosenTitle = entity && id ? chosen?.titleOf(entity.id, id) : undefined;\n  if (chosenTitle !== undefined) return <>{chosenTitle}</>;\n  if (!entity || !id || !canRead) return <>{unavailable}</>;\n  if (record.isPending) return <>{c.loading}</>;\n  if (record.error || !record.data) return <>{unavailable}</>;\n  const title = recordTitle(entity, record.data.values, locale) ?? id;\n  const href = hrefOf(entity.id, id);\n  return href ? <a href={href}>{title}</a> : <>{title}</>;\n}\n",
      "type": "registry:component",
      "target": "@components/fields/reference-value.tsx"
    },
    {
      "path": "fields/values.tsx",
      "content": "import { createContext, useContext, type ReactNode } from \"react\";\nimport { displayDate, type JsonValue } from \"@registrystack/app-runtime\";\nimport { fill, listOf, recordedNumber } from \"@/blocks/lib/format\";\nimport {\n  useBlockContent,\n  useLocale,\n  type BlockContent,\n} from \"@/blocks/lib/content\";\nimport type { FieldValueProps } from \"@/blocks/fields/renderers\";\n\n/** The words for a code: the content's term, the field's option, or the code. */\nfunction codeWords(\n  c: BlockContent,\n  field: FieldValueProps[\"field\"],\n  code: string,\n) {\n  return (\n    c.terms[code] ??\n    field.options?.find((option) => option.value === code)?.label ??\n    code\n  );\n}\n\nfunction titleOf(schema: JsonValue | undefined, key: string): string {\n  const properties =\n    schema && typeof schema === \"object\" && !Array.isArray(schema)\n      ? schema.properties\n      : undefined;\n  const property =\n    properties && typeof properties === \"object\" && !Array.isArray(properties)\n      ? properties[key]\n      : undefined;\n  const title =\n    property && typeof property === \"object\" && !Array.isArray(property)\n      ? property.title\n      : undefined;\n  return typeof title === \"string\" ? title : key;\n}\n\n/** A value inside a list or an object: plain words, or its JSON text. */\nfunction inner(c: BlockContent, locale: string, value: JsonValue) {\n  if (value === null) return c.notRecorded;\n  if (typeof value === \"boolean\") return value ? c.yes : c.no;\n  if (typeof value === \"string\") return value;\n  if (typeof value === \"number\") return recordedNumber(value, locale);\n  return JSON.stringify(value);\n}\n\n/** A list item: a code in the field's words, not recorded, or its JSON text. */\nfunction itemWords(\n  c: BlockContent,\n  field: FieldValueProps[\"field\"],\n  item: JsonValue,\n) {\n  return typeof item === \"string\"\n    ? codeWords(c, field, item)\n    : item === null\n      ? c.notRecorded\n      : JSON.stringify(item);\n}\n\n/**\n * Any value by its own shape: a list, the titled properties of an object, a\n * yes or no, or its text. Coded list items read in the field's words. Inside\n * a link or a line of text, which can hold no list, a list is its items\n * joined and an object its `Title: value` pairs.\n */\nexport function JsonValueView({ field, value }: FieldValueProps) {\n  const c = useBlockContent(),\n    locale = useLocale(),\n    inPhrase = useContext(InPhraseContext);\n  if (Array.isArray(value))\n    return inPhrase ? (\n      <>\n        {listOf(\n          value.map((item) => itemWords(c, field, item)),\n          locale,\n        )}\n      </>\n    ) : (\n      <ul className=\"value-list\">\n        {value.map((item, index) => (\n          <li key={typeof item === \"string\" ? item : index}>\n            {itemWords(c, field, item)}\n          </li>\n        ))}\n      </ul>\n    );\n  if (value !== null && typeof value === \"object\")\n    return inPhrase ? (\n      <>\n        {Object.entries(value)\n          .map(\n            ([key, item]) =>\n              fill(\n                c.labelled,\n                {\n                  label: titleOf(field.schema, key),\n                  value: inner(c, locale, item),\n                },\n                locale,\n              ),\n          )\n          .join(\"; \")}\n      </>\n    ) : (\n      <dl className=\"value-object\">\n        {Object.entries(value).map(([key, item]) => (\n          <div key={key}>\n            <dt>{titleOf(field.schema, key)}</dt>\n            <dd>{inner(c, locale, item)}</dd>\n          </div>\n        ))}\n      </dl>\n    );\n  return <>{inner(c, locale, value)}</>;\n}\n\n/**\n * A text value that is a whole http(s) URI, shortened to show: its host and\n * last path segment, with any path between them as an ellipsis, and its\n * fragment. The segment reads decoded where it decodes. It stays the value a\n * person would quote, never a name made from it. Any other text has no\n * presentation of its own.\n */\nexport function uriPresentation(value: string): string | undefined {\n  if (!/^https?:\\/\\/\\S+$/i.test(value) || !URL.canParse(value))\n    return undefined;\n  const url = new URL(value);\n  const segments = url.pathname.split(\"/\").filter(Boolean);\n  const last = segments.at(-1);\n  let shown = url.hostname;\n  if (last !== undefined) {\n    let decoded = last;\n    try {\n      decoded = decodeURIComponent(last);\n    } catch {\n      // A segment that does not decode is shown as recorded.\n    }\n    shown += `${segments.length > 1 ? \"/…\" : \"\"}/${decoded}`;\n  }\n  return shown + url.hash;\n}\n\nconst InPhraseContext = createContext(false);\n\n/**\n * Marks the values inside as part of a link or a line of text, such as a\n * record's linked title cell or card, or a sentence that names a value. Both\n * can hold only phrasing content, so a value there renders as text and adds\n * no disclosure or control of its own: a disclosure cannot sit in a\n * paragraph, and a control nested in a link is invalid markup and activating\n * it can follow the link.\n */\nexport function InPhrase({ children }: { children?: ReactNode }) {\n  return (\n    <InPhraseContext.Provider value={true}>{children}</InPhraseContext.Provider>\n  );\n}\n\n/** Whether the values inside are part of a link or a line of text (`InPhrase`). */\nexport function useInPhrase(): boolean {\n  return useContext(InPhraseContext);\n}\n\n/**\n * A URI shortened, with the full identifier shown on demand. Inside a link or\n * a line of text, which can hold no disclosure, it is the URI as recorded:\n * the shortened form alone would hide the exact value, and two URIs can\n * shorten alike.\n */\nfunction UriValue({ words, uri }: { words: string; uri: string }) {\n  const c = useBlockContent(),\n    inPhrase = useContext(InPhraseContext);\n  if (inPhrase) return <span>{uri}</span>;\n  return (\n    <>\n      <span>{words}</span>\n      <details>\n        <summary>{c.fullIdentifier}</summary>\n        {uri}\n      </details>\n    </>\n  );\n}\n\nexport function TextValue(props: FieldValueProps) {\n  if (typeof props.value !== \"string\") return <JsonValueView {...props} />;\n  const words = uriPresentation(props.value);\n  return words === undefined ? (\n    <>{props.value}</>\n  ) : (\n    <UriValue words={words} uri={props.value} />\n  );\n}\n\n/** A number as recorded, keeping every digit of a lexical number. */\nexport function NumberValue(props: FieldValueProps) {\n  const locale = useLocale();\n  return typeof props.value === \"number\" || typeof props.value === \"string\" ? (\n    <>{recordedNumber(props.value, locale)}</>\n  ) : (\n    <JsonValueView {...props} />\n  );\n}\n\nexport function BooleanValue(props: FieldValueProps) {\n  return <JsonValueView {...props} />;\n}\n\nexport function DateValue(props: FieldValueProps) {\n  const c = useBlockContent(),\n    locale = useLocale();\n  if (props.value === \"\") return <>{c.notRecorded}</>;\n  return typeof props.value === \"string\" ? (\n    <>{displayDate(props.value, locale)}</>\n  ) : (\n    <JsonValueView {...props} />\n  );\n}\n\nexport function EnumValue(props: FieldValueProps) {\n  const c = useBlockContent();\n  return typeof props.value === \"string\" ? (\n    <>{codeWords(c, props.field, props.value)}</>\n  ) : (\n    <JsonValueView {...props} />\n  );\n}\n\n/**\n * A read-only structured field the UI model gives the `quantity` widget, when\n * it holds exactly a quantity value, a unit code and a unit scheme: the value\n * as recorded in `locale`'s notation and the unit as recorded, and the scheme\n * apart. Anything else, or a field without the widget, keeps the generic\n * display.\n */\nexport function quantityPresentation(\n  value: JsonValue | undefined,\n  field: FieldValueProps[\"field\"],\n  locale: string,\n): { summary: string; unitScheme: string } | undefined {\n  if (\n    field.type !== \"structured\" ||\n    field.widget !== \"quantity\" ||\n    !field.readOnly\n  )\n    return undefined;\n  if (value === null || typeof value !== \"object\" || Array.isArray(value))\n    return undefined;\n  const names = [\"quantityValue\", \"unitCode\", \"unitScheme\"];\n  if (\n    Object.keys(value).length !== names.length ||\n    names.some((name) => !Object.hasOwn(value, name))\n  )\n    return undefined;\n  const { quantityValue, unitCode, unitScheme } = value;\n  const valid =\n    typeof quantityValue === \"number\"\n      ? Number.isFinite(quantityValue)\n      : typeof quantityValue === \"string\" &&\n        /^-?\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$/.test(quantityValue);\n  if (\n    !valid ||\n    typeof unitCode !== \"string\" ||\n    !unitCode.trim() ||\n    typeof unitScheme !== \"string\" ||\n    !unitScheme.trim()\n  )\n    return undefined;\n  return {\n    summary: `${recordedNumber(String(quantityValue), locale)} ${unitCode}`,\n    unitScheme,\n  };\n}\n\n/**\n * A quantity as recorded, with its unit scheme shown on demand. Inside a link\n * or a line of text, which can hold no disclosure, it is the value and unit\n * alone.\n */\nexport function QuantityValue({\n  summary,\n  unitScheme,\n}: NonNullable<ReturnType<typeof quantityPresentation>>) {\n  const c = useBlockContent(),\n    inPhrase = useContext(InPhraseContext);\n  if (inPhrase) return <span>{summary}</span>;\n  return (\n    <>\n      <span>{summary}</span>\n      <details>\n        <summary>{c.quantityUnitStandard}</summary>\n        {unitScheme}\n      </details>\n    </>\n  );\n}\n",
      "type": "registry:component",
      "target": "@components/fields/values.tsx"
    }
  ],
  "type": "registry:component"
}