{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "form",
  "title": "Form",
  "description": "A form that validates with the browser's own constraints (`required`, `type=\"email\"`, `pattern`) and shows server errors on the matching fields.",
  "dependencies": [
    "@base-ui/react@^1.8.0"
  ],
  "registryDependencies": [
    "@ouro/lib-class-name-check",
    "@ouro/lib-cn",
    "@ouro/lib-env",
    "@ouro/lib-form-answer",
    "@ouro/lib-refs",
    "@ouro/lib-use-dev-messages",
    "@ouro/lib-use-field"
  ],
  "files": [
    {
      "path": "registry/ouro/components/ouro/form/form.tsx",
      "content": "\"use client\";\n\nimport { Form as BaseForm } from \"@base-ui/react/form\";\nimport { isValidElement, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type JSX, type ReactNode, type Ref } from \"react\";\nimport { useAppearanceClassNameCheck } from \"@/registry/ouro/lib/ouro/class-name-check\";\nimport { cn } from \"@/registry/ouro/lib/ouro/cn\";\nimport { formErrorIdentity, type FormErrorIdentity, type FormErrorValue, type ReadonlyFormErrors } from \"@/registry/ouro/lib/ouro/form-answer\";\nimport { useDevWarnings } from \"@/registry/ouro/lib/ouro/use-dev-messages\";\nimport { useMergedRef } from \"@/registry/ouro/lib/ouro/refs\";\nimport { errorMessageKey, errorMessages, FormErrorsContext, type ErrorMessage } from \"@/registry/ouro/lib/ouro/use-field\";\n\n/**\n * Errors by field name: one message, or several as an array. A React Router action returns\n * this shape. A message is text or a React node, so it can carry a link. The `form` key holds\n * messages about the whole form. A key may hold nothing (`undefined`, `null`, an empty string\n * or list), so an object mapped from an action's answer needs no cleanup.\n * @claim \"A key may hold nothing (`undefined`\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form > treats no errors, null and an empty object as the same, and an element with a loop in its props as new)\n * @claim \"A key may hold nothing (`undefined`\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form-level messages (review fix round 1, finding 3) > follows its own fix: an object mapped key by key shows the message once and warns about nothing, whatever is missing)\n */\nexport type { FormErrors } from \"@/registry/ouro/lib/ouro/form-answer\";\n\n/** A read-only error projection, including the frozen arrays returned by `formErrors`. */\nexport type { ReadonlyFormErrors } from \"@/registry/ouro/lib/ouro/form-answer\";\n\n/** What a {@link FormProps.errorSummary} receives: the number of problems, and the first one in page order. */\nexport type FormErrorSummary = (\n  count: number,\n  first: {\n    label: string | undefined;\n    message: string;\n  },\n) => string;\n\n/** Props for {@link Form}: a `<form>`'s attributes, one complete `errors` value, and Base UI Form's `render`. */\nexport type FormProps = Omit<BaseForm.Props, \"className\" | \"errors\" | \"children\"> & {\n  /**\n   * Errors by field name, from your action or submit handler: `errors={formErrors(actionData, actionData?.errors)}`\n   * (import `formErrors` from `@/lib/ouro/form-answer`). Each changed answer, including an equal one, shows its\n   * messages again and moves focus once. Rebuilding the value or its mapped messages with\n   * the same answer is not a new answer: nothing moves.\n   * Each one shows on the field with that `name`, which gets `aria-invalid` and links the\n   * message, in the server HTML too. A field's own `error` prop wins over it, and a message\n   * goes away once the user changes that field. When new errors arrive, focus moves to the\n   * first field with one, in page order. The `form` key shows in an alert at the top of\n   * the form, in the server HTML too; a key no rendered field is named joins it once the\n   * page hydrates, and warns in development. A message is text or a React node (a message\n   * with a link), and an array is several messages.\n   *\n   * With the same answer, a message the user cleared stays cleared, even if its key goes away and comes\n   * back; messages the user hasn't cleared update in place (new text, a new React node), without moving\n   * focus or replacing the alert, though a screen reader may read changed alert text.\n   * No answer (`null`/`undefined`) is not a new answer either, and keeps what the user cleared.\n   * Cached/reused or primitive answers need `{ key }`, changed only when a new answer comes in, never\n   * when a submit starts: `formErrors(data, data.errors, { key: savedAt })`. Form doesn't work out which of\n   * a router's data belongs to this form: pass this form's own.\n   *\n   * A plain object (`errors={{ email: \"Taken.\" }}`) works for errors you show yourself, compared by\n   * content, so the same mistake twice doesn't show again; use `formErrors` for answers, from the first\n   * render: switching between the two is not a new answer, and keeps what the user cleared. JSON, a\n   * spread, structured cloning or a server component's props keep only the messages:\n   * build the value beside Form, on the server and in the browser.\n   *\n   * These errors only show: they never block the next submit, so the user can always send\n   * the form again (a server error may be fixed by changing another field, or by trying\n   * again). The browser's own checks (`required`, `type=\"email\"`) still block a submit.\n   * @claim \"works for errors you show yourself, compared by\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form > compares errors by content: an equal object rebuilt on every render shows nothing again and moves no focus)\n   * @claim \"works for errors you show yourself, compared by\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form > answer-bearing errors > seeds representation switches without inventing arrival, losing a clear or moving focus)\n   * @claim \"Each changed answer, including an equal\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form > a new answer and a re-render > keeps a cleared message cleared through the next submit's own re-render, then shows the equal answer and moves focus once when it arrives)\n   * @claim \"Rebuilding the value or its mapped\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form > compares errors by content: an equal object rebuilt on every render shows nothing again and moves no focus)\n   * @claim \"Each one shows on the field\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form server rendering > links a form error to its control in the server HTML (task 1 review, finding 1))\n   * @claim \"The `form` key shows in an\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form-level messages (review fix round 1, finding 3) > shows a form error and keys no field claims in an alert at the top of the form)\n   * @claim \"The `form` key shows in an\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form-level messages (review fix round 1, finding 3) > warns in development about a key no field claims, naming the key, the form's fields and both fixes)\n   * @claim \"No answer (`null`/`undefined`) is not a new answer\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form > answer-bearing errors > preserves a clear through omission, empty projections and absent answers, then restores it on the next accepted answer)\n   * @claim \"Cached/reused or primitive answers need `{\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form > answer-bearing errors > keeps a cached answer cleared for key zero, including rebuilt sources, and restores once for its next acceptance key)\n   * @claim \"These errors only show: they never\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form errors are display-only (review fix round 1, finding 1) > resubmits a TextField after a server error, with the field unchanged)\n   */\n  errors?: ReadonlyFormErrors | FormErrorValue | null | undefined;\n  /** Not a prop. Bind the accepted answer inside `errors`: `errors={formErrors(answer, messages)}`. */\n  result?: { 'Use errors={formErrors(answer, messages)}': never };\n  /**\n   * Translates the summary a screen reader hears first after a submit that leaves field errors:\n   * how many problems there are, and the first in page order, which is the field focus moves to.\n   * `label` is that field's label text, or `undefined` when it cannot be read; `message` is its\n   * error, or `\"\"` when that cannot be read. A message at the top of the form counts as one\n   * problem. The summary is visually hidden: each field shows its own error.\n   * @example\n   * <Form errors={errors} errorSummary={(count, first) => `No se pudo guardar: ${count}. ${first.label ?? \"\"}: ${first.message}`}>\n   * @claim \"Translates the summary a screen reader\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form error summary > translates the summary through errorSummary, with the count, label and message)\n   * @claim \"A message at the top of the form counts as one problem\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form error summary > counts a message at the top of the form as one problem, and shows it as well)\n   * @claim \"The summary is visually hidden\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form error summary > says how many problems there are, and the first in page order, once per submit)\n   */\n  errorSummary?: FormErrorSummary | undefined;\n  /** The fields and the submit button. */\n  children: ReactNode;\n  /**\n   * Layout only: margins, width, grid placement. Fields stack with a gap by default;\n   * appearance classes warn in development.\n   */\n  className?: string | undefined;\n\n  /** Not a prop. Ouro UI uses `errors`: `<Form errors={actionData?.errors}>`. */\n  validationErrors?: { 'Use <Form errors={actionData?.errors}>': never };\n};\n\nconst EMPTY: ReadonlyFormErrors = {};\n\nfunction maskErrors(projection: ReadonlyFormErrors | null | undefined, cleared: Set<string>): ReadonlyFormErrors {\n  return Object.fromEntries(Object.entries(projection ?? EMPTY).filter(([name]) => !cleared.has(name)));\n}\n\n/**\n * The message at the top of the form, for the `form` key and keys no field claims: the\n * destructive color, with an outline only while focused.\n * @claim \"The message at the top of\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form-level messages (review fix round 1, finding 3) > shows a form error and keys no field claims in an alert at the top of the form)\n */\nconst formMessageClass =\n  \"grid gap-1 text-sm leading-5 text-destructive outline-ring outline-offset-2 focus-visible:outline-2 focus-visible:outline-solid\";\n\n/** The key for a message about the whole form, shown at its top. */\nconst FORM_KEY = \"form\";\n\n/**\n * How deep `sameContent` looks before it calls two values different: past any real message, short of a loop.\n *\n * @claim \"How deep `sameContent` looks before it\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form > treats no errors, null and an empty object as the same, and an element with a loop in its props as new)\n */\nconst MAX_DEPTH = 40;\n\n/**\n * Whether two error values hold the same content: equal text, arrays and plain objects with\n * equal entries, and React elements of the same type and key with equal props. An app that\n * builds its errors object while rendering passes a new, equal one on every render.\n * @claim \"Whether two error values hold the\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form > compares errors by content: an equal object rebuilt on every render shows nothing again and moves no focus)\n * @claim \"An app that builds its errors\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form > compares errors by content: an equal object rebuilt on every render shows nothing again and moves no focus)\n */\nfunction sameContent(a: unknown, b: unknown, depth = 0): boolean {\n  if (Object.is(a, b)) return true;\n  if (typeof a !== \"object\" || typeof b !== \"object\" || a === null || b === null || depth === MAX_DEPTH) return false;\n  if (isValidElement(a) || isValidElement(b)) {\n    return isValidElement(a) && isValidElement(b) && a.type === b.type && a.key === b.key && sameContent(a.props, b.props, depth + 1);\n  }\n  const keys = Object.keys(a);\n  return (\n    Array.isArray(a) === Array.isArray(b) &&\n    keys.length === Object.keys(b).length &&\n    keys.every((key) => Object.hasOwn(b, key) && sameContent((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key], depth + 1))\n  );\n}\n\n/**\n * Whether an element takes focus: hidden inputs and hidden copies of a control do not, and\n * neither does a disabled control, which the user cannot change (a disabled checkbox or\n * radio is a `<span aria-disabled>` that would otherwise accept focus).\n */\nconst focusable = (element: HTMLElement) =>\n  !element.matches('input[type=\"hidden\"], [aria-hidden=\"true\"], [hidden], :disabled, [aria-disabled=\"true\"]');\n\n/** In a radio group, the picked radio is the way in, when it can take focus; otherwise the element itself. */\nfunction entryPoint(element: HTMLElement): HTMLElement {\n  if (element.getAttribute(\"role\") !== \"radio\") return element;\n  const picked = element.closest('[role=\"radiogroup\"]')!.querySelector<HTMLElement>('[role=\"radio\"][aria-checked=\"true\"]');\n  return picked && focusable(picked) ? picked : element;\n}\n\n/**\n * The summary a screen reader hears first: how many problems there are, then the first one's label\n * and message. The message is dropped when its text cannot be read.\n */\nconst defaultErrorSummary: FormErrorSummary = (count, first) => {\n  const problems = `Couldn't save: ${count} ${count === 1 ? \"problem\" : \"problems\"}.`;\n  return first.message === \"\" ? problems : `${problems} ${first.label ? `${first.label}: ` : \"\"}${first.message}`;\n};\n\n/**\n * The element that shows a control's error: the one its `aria-describedby` names with an\n * `-error` id, which a Field renders. A radio in a group shares the group's, so the group counts once.\n */\nfunction errorElementOf(control: HTMLElement): HTMLElement | undefined {\n  return control\n    .getAttribute(\"aria-describedby\")\n    ?.split(\" \")\n    .map((id) => control.ownerDocument.getElementById(id))\n    .find((element): element is HTMLElement => element?.id.endsWith(\"-error\") === true);\n}\n\n/**\n * A control's label text, read from the page: its radio group's `aria-labelledby`, its own, or\n * its `<label>`. `undefined` for a control whose label cannot be read.\n */\nfunction labelOf(control: HTMLElement): string | undefined {\n  const named = control.closest<HTMLElement>('[role=\"radiogroup\"]') ?? control;\n  const labelledBy = named.getAttribute(\"aria-labelledby\");\n  const text =\n    labelledBy === null\n      ? (control as Partial<HTMLInputElement>).labels?.[0]?.textContent\n      : labelledBy\n          .split(\" \")\n          .map((id) => control.ownerDocument.getElementById(id)?.textContent)\n          .filter(Boolean)\n          .join(\" \");\n  return text?.trim() || undefined;\n}\n\n/** A control's error text: its first message when several are listed, or \"\" for a control whose error cannot be read. */\nfunction messageOf(control: HTMLElement): string {\n  const error = errorElementOf(control);\n  return ((error?.querySelector(\"li\") ?? error)?.textContent ?? \"\").trim();\n}\n\n/** Whether a form's errors hold any message to show: a field's, or one at the top. */\nfunction hasMessages(errors: ReadonlyFormErrors): boolean {\n  return Object.values(errors).some((message) => errorMessages(message).length > 0);\n}\n\n/**\n * The messages at the top of the form: the `form` key's first, then the keys no field claims.\n * @claim \"The messages at the top of the form\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form-level messages (review fix round 1, finding 3) > shows a form error and keys no field claims in an alert at the top of the form)\n */\nfunction topMessagesOf(errors: ReadonlyFormErrors, showsAtTop: (key: string) => boolean): ErrorMessage[] {\n  const keys = Object.keys(errors).filter(showsAtTop);\n  return [...keys.filter((key) => key === FORM_KEY), ...keys.filter((key) => key !== FORM_KEY)].flatMap((key) =>\n    errorMessages(errors[key]),\n  );\n}\n\n/**\n * The summary of a submit's errors, or `undefined` when no focusable field shows one. Counts each\n * field once, plus one for the messages at the top of the form, and reads the first field in page\n * order: the one focus moves to.\n * @claim \"The summary of a submit's errors\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form error summary > has no summary and no alert when the only field with an error cannot take focus)\n * @claim \"Counts each field once\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form error summary > counts a radio group once and names it by its legend)\n * @claim \"reads the first field in page order\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form error summary > counts several problems and reads the first in page order, not the order the action lists them)\n * @claim \"plus one for the messages at the top of the form\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form error summary > counts a message at the top of the form as one problem, and shows it as well)\n */\nfunction summarize(form: HTMLFormElement, topMessages: number, summary: FormErrorSummary): string | undefined {\n  const invalid = [...form.querySelectorAll<HTMLElement>('[aria-invalid=\"true\"]')].filter(focusable);\n  const first = invalid[0];\n  if (!first) return undefined;\n  const fields = new Set(invalid.map((control) => errorElementOf(control) ?? control)).size;\n  return summary(fields + (topMessages > 0 ? 1 : 0), { label: labelOf(first), message: messageOf(first) });\n}\n\n/**\n * A form that validates with the browser's own constraints (`required`, `type=\"email\"`,\n * `pattern`) and shows server errors on the matching fields. Pass `errors` straight from\n * your action; each message lands on the field with that `name`, and focus moves to the\n * first field with an error. Bind an accepted action answer with the framework-free\n * `formErrors` constructor in `@/lib/ouro/form-answer`. Server errors only show: unlike the browser's checks they\n * never block the next submit, so the user can always send the form again. A Form submits\n * only itself: its submit event stops there, so a Form in a sheet inside another Form\n * never submits the outer one. It renders a `<form>`, so `action` and `method` pass\n * through; to submit through React Router, render its `Form`: `render={<RouterForm />}`.\n *\n * A submit is checked in this order. First the browser's own checks (`required`,\n * `type=\"email\"`, `pattern`): a failure stops the submit, marks each failing field with the\n * browser's message and moves focus to the first. Then your `onSubmit`, which runs only when\n * those pass and can still call `event.preventDefault()`. Then the server, whose answer\n * comes back as `errors`.\n *\n * The keys of `errors` are your fields' `name`s, and `form` is the message about the whole\n * form. An action that answers with other keys is mapped where you pass them:\n * `errors={formErrors(data, { form: data?.errors?.general, email: data?.errors?.email })}`. A key that no field\n * in this form is named shows at the top of the form and warns in development with the key,\n * this form's field names and the fix; with two forms on one route, pass each only its own\n * keys.\n *\n * Why `formErrors(answer, messages)`: Form has to tell a new answer from the same one rendered again. `answer`\n * is the object your action or submit handler gave back for this submit, and `messages` are its errors by\n * field name. Each new `answer` object is a new answer, even with the same messages: every message shows\n * again, including one the user cleared, and focus moves once. Rendering again with the same `answer` is not: a\n * message the user cleared by editing its field stays cleared, and focus stays put. So build the value\n * in the render, as the examples do. Form never guesses that an answer arrived from a submit starting, a wait\n * or a navigation. You choose which answer belongs to this form, so with two Forms on one route, pass\n * each its own. When the answer is the same object every time (a cache) or not an object at all, add a\n * key you change when a new answer comes in: `formErrors(data, data.errors, { key: savedAt })`.\n *\n * A plain object, `errors={{ email: \"Taken.\" }}`, still works, but Form compares it by its content: the\n * same mistake made twice looks like no change, so it does not show again. Use `formErrors` for answers,\n * from the first render, while the answer is still `undefined`: switching between a plain object and\n * `formErrors` is not a new answer, so it moves no focus and keeps what the user cleared. The answer lives in memory only: JSON,\n * a spread, structured cloning and passing it from a server component keep the messages and lose the\n * answer. Reconstruct beside Form in each environment, from the answer or key you have there; the value\n * never keeps or serializes the rest of the answer.\n *\n * The message about the whole form is an alert (`role=\"alert\"`). It is in the page only\n * while there is a message, and each answer adds a new one with its text already in it,\n * which is what screen readers announce; `getByRole(\"alert\")` finds nothing on a form\n * without one. A field's message is not an alert: it is that control's description, so\n * assert it with `toHaveAccessibleDescription`.\n *\n * After a submit that leaves field errors, the alert opens with a visually hidden summary, such as\n * \"Couldn't save: 1 problem. Name: You already have a recipe called Pasta.\", which screen readers hear\n * before focus moves to the first field. The same summary is not announced again while the errors stand,\n * and a changed error, or one the user fixed and got back, announces again. Pass `errorSummary` to translate it.\n * A message at the top of the form counts as one problem.\n *\n * Focus moves to the first field with an error when errors arrive after a submit. A page\n * that loads with `errors` already set (a post without JavaScript, or a reload) shows them\n * in the server HTML and moves no focus: nothing was submitted from this page, and taking\n * focus on load would drop a keyboard or screen-reader user into the middle of a page they\n * have not read. To send them to the errors on load, put an in-page link to the form in\n * your page's own error summary.\n *\n * Use `EditSheet` instead for a form in a dialog that saves and closes, and a plain\n * `<form>` when nothing needs validating.\n *\n * @group Forms\n * @see https://ui.ouroboros.bot/docs/form\n *\n * @example\n * // Checked in the browser, with no router or server: each submit's own answer, so the same mistake shows again.\n * import { formErrors } from \"@/lib/ouro/form-answer\";\n * const [answer, setAnswer] = useState<{ errors: FormErrors }>();\n * <Form\n *   errors={formErrors(answer, answer?.errors)}\n *   onSubmit={(event) => {\n *     event.preventDefault();\n *     const name = String(new FormData(event.currentTarget).get(\"name\"));\n *     setAnswer({ errors: name === \"admin\" ? { name: \"That name is taken.\" } : {} });\n *   }}\n * >\n *   <TextField label=\"Display name\" name=\"name\" required />\n *   <Button type=\"submit\">Save</Button>\n * </Form>\n *\n * @example\n * // With a router: the action's answer.\n * import { formErrors } from \"@/lib/ouro/form-answer\";\n * const actionData = useActionData<typeof action>();\n * <Form method=\"post\" errors={formErrors(actionData, actionData?.errors)} render={<RouterForm />}>\n *   <TextField label=\"Email\" name=\"email\" type=\"email\" required />\n *   <Button type=\"submit\">Save</Button>\n * </Form>\n *\n * @example\n * // The action answers { errors: { general, email } }: map its keys to this form's field names.\n * const errors = actionData?.errors;\n * <Form method=\"post\" errors={formErrors(actionData, { form: errors?.general, email: errors?.email })} render={<RouterForm />}>\n *   <TextField label=\"Email\" name=\"email\" type=\"email\" required />\n *   <Button type=\"submit\">Subscribe</Button>\n * </Form>\n * @claim \"Each new `answer` object is a new answer\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form > a new answer and a re-render > keeps a cleared message cleared through the next submit's own re-render, then shows the equal answer and moves focus once when it arrives)\n * @claim \"Rendering again with the same `answer` is not\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form > answer-bearing errors > renders new uncleared node props and handlers without restoring a masked error or replacing its alert)\n * @claim \"but Form compares it by its content\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form > compares errors by content: an equal object rebuilt on every render shows nothing again and moves no focus)\n * @claim \"switching between a plain object and\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form > answer-bearing errors > seeds representation switches without inventing arrival, losing a clear or moving focus)\n * @claim \"Server errors only show: unlike the\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form errors are display-only (review fix round 1, finding 1) > still blocks a submit on the browser's own constraints)\n * @claim \"Server errors only show: unlike the\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form errors are display-only (review fix round 1, finding 1) > resubmits a TextField after a server error, with the field unchanged)\n * @claim \"A Form submits only itself: its\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form submits only itself (review fix round 1, finding 2) > stops its submit event from reaching a Form around it in the React tree)\n * @claim \"First the browser's own checks (`required`\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form > validates with the browser's constraints and focuses the first invalid control)\n * @claim \"A key that no field in\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form-level messages (review fix round 1, finding 3) > warns in development about a key no field claims, naming the key, the form's fields and both fixes)\n * @claim \"A key that no field in\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form-level messages (review fix round 1, finding 3) > shows a form error and keys no field claims in an alert at the top of the form)\n * @claim \"Form never guesses that an answer arrived\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form > a new answer and a re-render > keeps a cleared message cleared through the next submit's own re-render, then shows the equal answer and moves focus once when it arrives)\n * @claim \"You choose which answer belongs to this form\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form-level messages (review fix round 1, finding 3) > warns in development about a key no field claims, naming the key, the form's fields and both fixes)\n * @claim \"Reconstruct beside Form in each environment\" registry/ouro/lib/ouro/form-answer.test.ts verify:testExists(registry/ouro/lib/ouro/form-answer.test.ts::formErrors answer value > enumerates and serializes only selected messages, never a cyclic private answer or its getter)\n * @claim \"Reconstruct beside Form in each environment\" registry/ouro/lib/ouro/form-answer.test.ts verify:testExists(registry/ouro/lib/ouro/form-answer.test.ts::formErrors answer value > interns object keys without retaining the key payload and lets the key override source identity)\n * @claim \"It is in the page only\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form-level messages (review fix round 1, finding 3) > adds the alert to the page with its message already in it, each time an answer arrives, so screen readers announce it)\n * @claim \"A page that loads with `errors`\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form-level messages (review fix round 1, finding 3) > leaves focus where the browser put it when the page loads with errors)\n * @claim \"A page that loads with `errors`\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form-level messages (review fix round 1, finding 3) > puts the form error in the server HTML)\n * @claim \"After a submit that leaves field errors\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form error summary > says how many problems there are, and the first in page order, once per submit)\n * @claim \"The same summary is not announced again\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form error summary > does not announce an unchanged summary again, but announces a changed one)\n * @claim \"and a changed error, or one the user fixed\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form error summary > announces the same error again once the user has changed the field)\n * @claim \"A message at the top of the form counts as one problem\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form error summary > counts a message at the top of the form as one problem, and shows it as well)\n */\nexport function Form(props: FormProps): JSX.Element {\n  const {\n    errors: errorsProp,\n    result,\n    onSubmit,\n    children,\n    className,\n    errorSummary = defaultErrorSummary,\n    // Guard props (hint types), dropped here so they never reach the DOM.\n    validationErrors,\n    ...rest\n  } = props;\n\n  useAppearanceClassNameCheck(\n    \"Form\",\n    className,\n    process.env.NODE_ENV !== \"production\"\n      ? \"style fields in your theme (--input, --ring, --radius)\"\n      : /* istanbul ignore next @preserve -- production only */ \"\",\n  );\n  const identity = formErrorIdentity(errorsProp);\n  const mode = identity ? \"answer\" : \"raw\";\n  const accepted = identity?.kind === \"none\" ? undefined : identity;\n  const [shown, setShown] = useState({\n    mode,\n    source: errorsProp,\n    identity: accepted as FormErrorIdentity | undefined,\n    rawErrors: errorsProp,\n    cleared: new Set<string>(),\n    arrivals: 0,\n  });\n  if (mode !== shown.mode) {\n    // A representation switch establishes a baseline, not an accepted answer.\n    setShown({ ...shown, mode, source: errorsProp, identity: accepted, rawErrors: maskErrors(errorsProp, shown.cleared) });\n  } else if (accepted && (!shown.identity || accepted.kind !== shown.identity.kind || !Object.is(accepted.value, shown.identity.value))) {\n    // Answer identity is the sole arrival authority; projection changes never reset a mask.\n    setShown({ ...shown, source: errorsProp, identity: accepted, cleared: new Set(), arrivals: shown.arrivals + 1 });\n  } else if (mode === \"raw\" && errorsProp !== shown.source && !sameContent(errorsProp ?? EMPTY, shown.source ?? EMPTY)) {\n    setShown({ ...shown, source: errorsProp, rawErrors: errorsProp, cleared: new Set(), arrivals: shown.arrivals + 1 });\n  }\n  const errors = useMemo(\n    () => mode === \"answer\" ? maskErrors(errorsProp, shown.cleared) : shown.rawErrors,\n    [mode, errorsProp, shown.cleared, shown.rawErrors],\n  );\n  // The alert's state: the arrival it was decided for, its key (a new key is a new element, so a\n  // new announcement) and the summary it opens with. A summary equal to the one shown keeps its key,\n  // so an unchanged refusal is not announced again.\n  const [alert, setAlert] = useState<{ arrival: number; key: number; summary: string | undefined }>({\n    arrival: 0,\n    key: 0,\n    summary: undefined,\n  });\n  const clear = useCallback((name: string) => {\n    if (!errors || !Object.hasOwn(errors, name)) return;\n    // Once the user changes a field, its problem is gone: a later identical error is news.\n    setAlert((current) => ({ ...current, summary: undefined }));\n    setShown((current) => {\n      if (current.cleared.has(name)) return current;\n      const next: Record<string, ReadonlyFormErrors[string]> = { ...current.rawErrors };\n      delete next[name];\n      return { ...current, rawErrors: next, cleared: new Set([...current.cleared, name]) };\n    });\n  }, [errors, setShown]);\n\n  // The names of the fields in the form, which claim their errors. Fields register once\n  // mounted, so the server and the first client render show only the `form` key at the\n  // top; keys no field claims (a typo, a field that is not rendered) join it after\n  // hydration. A message never shows twice.\n  const names = useRef(new Map<string, number>());\n  const [claims, setClaims] = useState<{ ready: boolean; names: string[] }>({ ready: false, names: [] });\n  const sync = useCallback(() => setClaims({ ready: true, names: [...names.current.keys()] }), []);\n  const register = useCallback(\n    (name: string) => {\n      names.current.set(name, (names.current.get(name) ?? 0) + 1);\n      sync();\n      return () => {\n        const count = names.current.get(name)! - 1;\n        if (count === 0) names.current.delete(name);\n        else names.current.set(name, count);\n        sync();\n      };\n    },\n    [sync],\n  );\n  useEffect(sync, [sync]);\n  const value = useMemo(() => ({ errors: errors ?? EMPTY, clear, register }), [errors, clear, register]);\n  const showsAtTop = useCallback(\n    (key: string) => key === FORM_KEY || (claims.ready && !claims.names.includes(key)),\n    [claims],\n  );\n\n  useDevWarnings(\n    \"Form\",\n    process.env.NODE_ENV !== \"production\"\n      ? () => [\n          validationErrors !== undefined && [\"validationErrors is not a prop\", \"<Form errors={actionData?.errors}>\"],\n          (result !== undefined || Object.hasOwn(props, \"result\")) && [\"result is not a prop\", \"errors={formErrors(answer, messages)}\"],\n          ...Object.keys(errorsProp ?? EMPTY)\n            .filter((key) => key !== FORM_KEY && !names.current.has(key) && errorMessages(errorsProp![key]).length > 0)\n            .map((key) => unclaimedWarning(key, [...names.current.keys()])),\n        ]\n      : /* istanbul ignore next @preserve -- production only */ undefined,\n  );\n\n  // When new errors arrive, focus the first field showing one, in page order, or the\n  // message at the top when no field has one. Not on the first render: a page that loads\n  // with errors leaves focus where the browser puts it. The summary is decided first, right\n  // after the commit that shows the errors (before paint, in the same task): the alert is then\n  // inserted with the summary already in it, and focus follows it.\n  const formRef = useRef<HTMLFormElement>(null);\n  const messageRef = useRef<HTMLDivElement>(null);\n  const focusedFor = useRef(0);\n  useLayoutEffect(() => {\n    if (alert.arrival === shown.arrivals) return;\n    const shownErrors = errors ?? EMPTY;\n    const summary = hasMessages(shownErrors)\n      ? summarize(formRef.current!, topMessagesOf(shownErrors, showsAtTop).length, errorSummary)\n      : undefined;\n    setAlert((current) => ({\n      arrival: shown.arrivals,\n      key: summary === current.summary ? current.key : shown.arrivals,\n      summary,\n    }));\n  }, [alert.arrival, shown.arrivals, errors, showsAtTop, errorSummary]);\n  useEffect(() => {\n    if (focusedFor.current === alert.arrival) return;\n    focusedFor.current = alert.arrival;\n    if (!hasMessages(errors ?? EMPTY)) return;\n    const invalid = [...formRef.current!.querySelectorAll<HTMLElement>('[aria-invalid=\"true\"]')].find(focusable);\n    (invalid ? entryPoint(invalid) : messageRef.current)?.focus();\n  }, [alert.arrival, errors]);\n\n  // A submit stops at its own Form: React bubbles events through portals, so a Form in a\n  // sheet would otherwise reach the Form the sheet sits in.\n  const submit: NonNullable<BaseForm.Props[\"onSubmit\"]> = (event) => {\n    event.stopPropagation();\n    onSubmit?.(event);\n  };\n  const setFormRef = useMergedRef(rest.ref, formRef);\n\n  return (\n    <FormErrorsContext.Provider value={value}>\n      {/* Base UI's Form runs the browser's checks: it blocks a submit while a constraint\n          fails and focuses the first such control. Ouro's errors never reach it, so they\n          never block a submit. */}\n      <BaseForm {...rest} ref={setFormRef} onSubmit={submit} data-ouro=\"form\" className={cn(\"grid min-w-0 gap-5\", className)}>\n        {/* A new element for each announcement: each arrival, unless its summary repeats the last one. While an\n            arrival has no summary decided, an alert without one stays out of the page, so it is inserted whole. */}\n        <FormMessage\n          key={alert.key}\n          ref={messageRef}\n          errors={errors ?? EMPTY}\n          showsAtTop={showsAtTop}\n          summary={alert.summary}\n          pending={alert.arrival !== shown.arrivals && alert.summary === undefined}\n        />\n        {children}\n      </BaseForm>\n    </FormErrorsContext.Provider>\n  );\n}\n\n/**\n * The development message for an `errors` key no field in the form is named: the key, the\n * fields there are, and both fixes. Development only.\n * @claim \"The development message for an `errors`\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form-level messages (review fix round 1, finding 3) > warns in development about a key no field claims, naming the key, the form's fields and both fixes)\n */\nfunction unclaimedWarning(key: string, fields: string[]): readonly [string, string] {\n  const property = (name: string) => (/^[A-Za-z_$][\\w$]*$/.test(name) ? name : JSON.stringify(name));\n  const read = (name: string) => (property(name) === name ? `errors.${name}` : `errors[${property(name)}]`);\n  const own = fields.map((name) => `${property(name)}: ${read(name)}`).join(\", \");\n  return fields.length === 0\n    ? [\n        `errors has the key \"${key}\", but the form has no named field, so the message shows at the top of the form`,\n        `a message about the whole form goes under the \"${FORM_KEY}\" key: errors={{ ${FORM_KEY}: ${read(key)} }}`,\n      ]\n    : [\n        `errors has the key \"${key}\", but the form's fields are named ${fields.join(\", \")}, so the message shows at the top of the form`,\n        `a message about the whole form goes under the \"${FORM_KEY}\" key: errors={{ ${FORM_KEY}: ${read(key)}, ${own} }}; ` +\n          `one that belongs to another form is left out: errors={{ ${own} }}`,\n      ];\n}\n\n/**\n * The message at the top of the form. It is in the page only while it has a message or a summary,\n * and it arrives with its text already in it: an element added with `role=\"alert\"` and its text\n * is what screen readers announce, and a test's `getByRole(\"alert\")` finds a message or nothing.\n * The summary comes first and is visually hidden, so an alert whose only text is that summary takes\n * no room.\n * @claim \"The summary comes first and is visually hidden\" registry/ouro/components/ouro/form/form.test.tsx verify:testExists(registry/ouro/components/ouro/form/form.test.tsx::Form error summary > says how many problems there are, and the first in page order, once per submit)\n */\nfunction FormMessage({\n  ref,\n  errors,\n  showsAtTop,\n  summary,\n  pending,\n}: {\n  ref: Ref<HTMLDivElement>;\n  errors: ReadonlyFormErrors;\n  showsAtTop: (key: string) => boolean;\n  summary: string | undefined;\n  pending: boolean;\n}): JSX.Element | null {\n  const messages = topMessagesOf(errors, showsAtTop);\n  if (pending || (messages.length === 0 && summary === undefined)) return null;\n  return (\n    <div ref={ref} role=\"alert\" tabIndex={-1} data-ouro=\"form-message\" className={cn(formMessageClass, messages.length === 0 && \"sr-only\")}>\n      {summary !== undefined && <span className=\"sr-only\">{summary}</span>}\n      {messages.map((message, index) => (\n        <p key={errorMessageKey(message, index)} className=\"m-0\">\n          {message}\n        </p>\n      ))}\n    </div>\n  );\n}\n",
      "type": "registry:ui",
      "target": "@components/ouro/form/form.tsx"
    }
  ],
  "docs": "A form that validates with the browser's own constraints (`required`, `type=\"email\"`, `pattern`) and shows server errors on the matching fields. Import: import { Form } from \"@/components/ouro/form/form\", with @/components replaced by your components alias (aliases.components in components.json, such as ~/components). Also installed: the helpers it imports in lib/ouro. Needs ouro-base in your stylesheet: add that item once per app, from the same place as this one, if you have not. Docs: https://ui.ouroboros.bot/docs/form.md Ouro UI v1.3.257.",
  "type": "registry:ui"
}