import * as React from 'react'; import * as LabelPrimitive from '@radix-ui/react-label'; import { Slot } from '@radix-ui/react-slot'; import { Controller, FormProvider, useFormContext, useFormState, type ControllerProps, type FieldPath, type FieldValues, } from 'react-hook-form'; import { cn } from '../../shared/utils'; import { Label } from '../label'; /** * Root form provider and field controller layer for React Hook Form. * * @description * Wraps `react-hook-form` instances and provides the form context to all * child primitives (`FormField`, `FormControl`, `FormMessage`). Handles * field validation state, ARIA attributes, and error messaging automatically. * * @ai-rules * 1. Always initialize with `const form = useForm({ resolver: zodResolver(schema) })` before rendering. * 2. Do NOT create stateful inputs with `useState` if they are already inside a `
`. * 3. Structure: ` > > > + + `. */ const Form = FormProvider; type FormFieldContextValue< TFieldValues extends FieldValues = FieldValues, TName extends FieldPath = FieldPath, > = { name: TName; }; const FormFieldContext = React.createContext({} as FormFieldContextValue); const FormField = < TFieldValues extends FieldValues = FieldValues, TName extends FieldPath = FieldPath, >({ ...props }: ControllerProps) => { return ( ); }; const useFormField = () => { const fieldContext = React.useContext(FormFieldContext); const itemContext = React.useContext(FormItemContext); const { getFieldState } = useFormContext(); const formState = useFormState({ name: fieldContext.name }); const fieldState = getFieldState(fieldContext.name, formState); if (!fieldContext) { throw new Error('useFormField should be used within '); } const { id } = itemContext; return { id, name: fieldContext.name, formItemId: `${id}-form-item`, formDescriptionId: `${id}-form-item-description`, formMessageId: `${id}-form-item-message`, ...fieldState, }; }; type FormItemContextValue = { id: string; }; const FormItemContext = React.createContext({} as FormItemContextValue); function FormItem({ className, ...props }: React.ComponentProps<'div'>) { const id = React.useId(); return (
); } function FormLabel({ className, ...props }: React.ComponentProps) { const { error, formItemId } = useFormField(); return (