{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "form",
  "type": "registry:ui",
  "title": "Form",
  "description": "A form that checks itself with the browser's own rules (required, type, length, range, pattern) and the project's, shows each field's message in words under it, and after a failed submit lists every fault at the top as links to the fields, said once.",
  "categories": [
    "ui"
  ],
  "dependencies": [
    "radix-ui"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/announce",
    "@rivier-ui/cn"
  ],
  "files": [
    {
      "path": "registry/ui/form.tsx",
      "type": "registry:ui",
      "target": "components/ui/form.tsx",
      "content": "\"use client\";\n/**\n * @name form\n * @category ui\n * @description A form that checks itself with the browser's own rules (required, type, length, range, pattern) and the project's, shows each field's message in words under it, and after a failed submit lists every fault at the top as links to the fields, said once.\n * @when Any form with rules: sign-up, checkout, settings. The rules live on the controls (`required`, `type=\"email\"`, `min`) or in a `match` function; a server's answer goes in `serverInvalid` with its message. For a single field with no rules, field is enough; for a guided form over several steps use wizard.\n * @example\n * <Form onSubmit={(event) => { event.preventDefault(); save(new FormData(event.currentTarget)); }}>\n *   <FormErrorSummary title=\"There is a problem\" />\n *   <FormField name=\"email\">\n *     <FormLabel>Email</FormLabel>\n *     <FormControl asChild><Input type=\"email\" required /></FormControl>\n *     <FormMessage match=\"valueMissing\">Enter your email address.</FormMessage>\n *     <FormMessage match=\"typeMismatch\">Enter an email address like name@example.com.</FormMessage>\n *   </FormField>\n *   <FormSubmit asChild><Button>Create account</Button></FormSubmit>\n * </Form>\n */\nimport { Form as FormPrimitive } from \"radix-ui\";\nimport { createContext, use, useRef, useState, type ComponentProps } from \"react\";\nimport { announce } from \"@/lib/announce\";\nimport { cn } from \"@/lib/cn\";\n\ntype Fault = { id: string; label: string; message: string };\ntype FormContextValue = { faults: readonly Fault[] };\nconst FormContext = createContext<FormContextValue | null>(null);\n\nexport type FormProps = ComponentProps<typeof FormPrimitive.Root> & {\n  /** Said after a failed submit: \"2 problems\". */\n  faultCount?: (count: number) => string;\n};\n\n/** The form. On a failed submit it gathers every field that is not valid for FormErrorSummary and says how many. */\nexport function Form({ className, onInvalidCapture, onSubmit, faultCount = (count) => `${count} ${count === 1 ? \"problem\" : \"problems\"} to fix`, children, ...props }: FormProps) {\n  const [faults, setFaults] = useState<readonly Fault[]>([]);\n  const pending = useRef(false);\n  const gather = (form: HTMLFormElement): void => {\n    const controls = [...form.elements].filter((element): element is HTMLInputElement => \"validity\" in element && !(element as HTMLInputElement).validity.valid);\n    const found = controls.map((control) => {\n      const label = control.labels?.[0]?.textContent?.trim() || control.getAttribute(\"aria-label\") || control.name;\n      // The field's own visible messages, when the project wrote them; else the browser's.\n      const field = control.closest(\"[data-slot=form-field]\");\n      const written = field ? [...field.querySelectorAll(\"[data-slot=form-message]\")].map((node) => node.textContent?.trim()).filter(Boolean).join(\" \") : \"\";\n      return { id: control.id, label, message: written || control.validationMessage };\n    });\n    setFaults(found);\n    if (found.length > 0) announce(faultCount(found.length), \"assertive\");\n  };\n  return (\n    <FormContext value={{ faults }}>\n      <FormPrimitive.Root\n        data-slot=\"form\"\n        className={cn(\"flex flex-col gap-5\", className)}\n        onInvalidCapture={(event) => {\n          onInvalidCapture?.(event);\n          // One gathering for all the fields that report in this submit.\n          if (pending.current) return;\n          pending.current = true;\n          const form = event.currentTarget;\n          // Two frames: the fields first show their own messages, which the summary repeats.\n          requestAnimationFrame(() =>\n            requestAnimationFrame(() => {\n              pending.current = false;\n              gather(form);\n            }),\n          );\n        }}\n        onSubmit={(event) => {\n          setFaults([]);\n          onSubmit?.(event);\n        }}\n        {...props}\n      >\n        {children}\n      </FormPrimitive.Root>\n    </FormContext>\n  );\n}\n\nexport type FormErrorSummaryProps = Omit<ComponentProps<\"div\">, \"title\"> & {\n  /** The heading: \"There is a problem\". */\n  title: string;\n};\n\n/** After a failed submit: every fault as a link that takes focus to its field. Nothing is drawn while all is well. */\nexport function FormErrorSummary({ title, className, ...props }: FormErrorSummaryProps) {\n  const context = use(FormContext);\n  if (!context || context.faults.length === 0) return null;\n  return (\n    <div data-slot=\"form-error-summary\" role=\"alert\" className={cn(\"rounded-surface border-2 border-destructive p-4\", className)} {...props}>\n      <p className=\"font-medium\">{title}</p>\n      <ul className=\"mt-2 flex list-disc flex-col gap-1 ps-5 text-sm\">\n        {context.faults.map((fault) => (\n          <li key={fault.id || fault.label}>\n            <a\n              href={fault.id ? `#${fault.id}` : undefined}\n              className=\"text-destructive underline underline-offset-4\"\n              onClick={(event) => {\n                const target = fault.id ? document.getElementById(fault.id) : null;\n                if (!target) return;\n                event.preventDefault();\n                // At once: a smooth scroll still running would move the page under the person's next click.\n                target.focus({ preventScroll: true });\n                target.scrollIntoView({ block: \"center\", behavior: \"instant\" });\n              }}\n            >\n              {fault.label}: {fault.message}\n            </a>\n          </li>\n        ))}\n      </ul>\n    </div>\n  );\n}\n\n/** One field: its label, control, description and messages share the name. */\nexport function FormField({ className, ...props }: ComponentProps<typeof FormPrimitive.Field>) {\n  return <FormPrimitive.Field data-slot=\"form-field\" className={cn(\"group/field flex flex-col gap-1.5\", className)} {...props} />;\n}\n\nexport function FormLabel({ className, ...props }: ComponentProps<typeof FormPrimitive.Label>) {\n  return <FormPrimitive.Label data-slot=\"form-label\" className={cn(\"text-sm font-medium data-[invalid]:text-destructive\", className)} {...props} />;\n}\n\n/** The control. With `asChild`, any input of the library: Input, Textarea, a select of the project's. */\nexport function FormControl({ className, ...props }: ComponentProps<typeof FormPrimitive.Control>) {\n  return <FormPrimitive.Control data-slot=\"form-control\" className={cn(\"data-[invalid]:border-destructive\", className)} {...props} />;\n}\n\n/** A line under the control that helps before anything goes wrong. */\nexport function FormDescription({ className, ...props }: ComponentProps<\"p\">) {\n  return <p data-slot=\"form-description\" className={cn(\"text-sm text-muted-foreground\", className)} {...props} />;\n}\n\n/** Shown when the field breaks the rule in `match` (a browser rule, or a function of the value). The control is described by it. */\nexport function FormMessage({ className, ...props }: ComponentProps<typeof FormPrimitive.Message>) {\n  return <FormPrimitive.Message data-slot=\"form-message\" className={cn(\"flex items-start gap-1 text-sm text-destructive before:content-['!'] before:font-bold\", className)} {...props} />;\n}\n\n/**\n * The submit button. A field is checked when it is left, so its message can appear just as the button is\n * pressed and move it down: the press then ends off the button and the browser sends no click. A press that\n * ends where the button was when it began still submits.\n */\nexport function FormSubmit({ onPointerDown, ...props }: ComponentProps<typeof FormPrimitive.Submit>) {\n  return (\n    <FormPrimitive.Submit\n      data-slot=\"form-submit\"\n      onPointerDown={(event) => {\n        onPointerDown?.(event);\n        if (event.button !== 0) return;\n        const button = event.currentTarget as HTMLButtonElement;\n        const before = button.getBoundingClientRect();\n        const finish = (up: PointerEvent): void => {\n          const inside = up.clientX >= before.left && up.clientX <= before.right && up.clientY >= before.top && up.clientY <= before.bottom;\n          // Only when the release missed the button: a release on it is an ordinary click.\n          if (inside && !button.contains(up.target as Node) && !button.disabled) button.form?.requestSubmit(button);\n        };\n        window.addEventListener(\"pointerup\", finish, { once: true });\n      }}\n      {...props}\n    />\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "ui",
    "when": "Any form with rules: sign-up, checkout, settings. The rules live on the controls (`required`, `type=\"email\"`, `min`) or in a `match` function; a server's answer goes in `serverInvalid` with its message. For a single field with no rules, field is enough; for a guided form over several steps use wizard.",
    "example": "<Form onSubmit={(event) => { event.preventDefault(); save(new FormData(event.currentTarget)); }}>\n  <FormErrorSummary title=\"There is a problem\" />\n  <FormField name=\"email\">\n    <FormLabel>Email</FormLabel>\n    <FormControl asChild><Input type=\"email\" required /></FormControl>\n    <FormMessage match=\"valueMissing\">Enter your email address.</FormMessage>\n    <FormMessage match=\"typeMismatch\">Enter an email address like name@example.com.</FormMessage>\n  </FormField>\n  <FormSubmit asChild><Button>Create account</Button></FormSubmit>\n</Form>",
    "client": true
  }
}
