# @zuilib/form

React Hook Form integration for ZUI: typed `Form` wrapper, accessible `FormField` with render props, optional debounced autosave.

## When to use

- Any form validated or submitted via [react-hook-form](https://react-hook-form.com/)
- You already use `@zuilib/components` inputs and want consistent field layout + error display

## Prerequisites

| Package | Version |
|---------|---------|
| `react`, `react-dom` | `^18.0.0` |
| `react-hook-form` | `^7.0.0` |
| `@zuilib/components` | (workspace or published) — **import `@zuilib/components/styles.css` in the app** |

## Installation

```bash
pnpm add @zuilib/form @zuilib/components @headlessui/react react-hook-form
```

Monorepo:

```json
{
  "dependencies": {
    "@zuilib/form": "workspace:*",
    "@zuilib/components": "workspace:*",
    "react-hook-form": "^7.0.0"
  }
}
```

## Import rules

| Rule | Detail |
|------|--------|
| **Root barrel** | `import { Form, FormField, useAutosave } from '@zuilib/form'` |
| **Subpaths** | Each module also has its own entry (see below) |
| **Core primitives** | `Label`, `Input`, `FieldError`, etc. come from `@zuilib/components/*`, not this package |

## Exports

| Subpath | Export | Purpose |
|---------|--------|---------|
| `@zuilib/form` | `Form`, `FormField`, `useAutosave` + types | Root barrel |
| `@zuilib/form/form` | `Form` | `<form>` + `FormProvider` |
| `@zuilib/form/form-field` | `FormField` | Controller wrapper + a11y IDs |
| `@zuilib/form/use-autosave` | `useAutosave` | Debounced save hook (also used inside `FormField`) |

## Quick start

```tsx
import { useForm } from 'react-hook-form'
import '@zuilib/components/styles.css'
import { Form, FormField } from '@zuilib/form'
import Label from '@zuilib/components/label'
import Input from '@zuilib/components/input'
import FieldError from '@zuilib/components/field-error'
import Button from '@zuilib/components/button'

type FormData = { email: string }

function LoginForm() {
  const form = useForm<FormData>({ defaultValues: { email: '' } })

  return (
    <Form form={form} onSubmit={(data) => console.log(data)}>
      <FormField control={form.control} name="email">
        {({ field, error }) => (
          <>
            <Label>Email</Label>
            <Input type="email" {...field} />
            <FieldError error={error} />
          </>
        )}
      </FormField>
      <Button type="submit">Login</Button>
    </Form>
  )
}
```

## API

### Form — `@zuilib/form/form`

Wraps `FormProvider` and wires `onSubmit` to `form.handleSubmit`.

| Prop | Type | Required |
|------|------|----------|
| `form` | `UseFormReturn<TFieldValues>` | yes |
| `onSubmit` | `(data: TFieldValues) => void \| Promise<void>` | yes |
| `children` | `ReactNode` | yes |

Forwards other native `<form>` attributes (`className`, `id`, etc.). Supports `ref` on the `<form>` element.

### FormField — `@zuilib/form/form-field`

Connects a field via react-hook-form `Controller`. Uses a **function child** (not `render`).

| Prop | Type | Notes |
|------|------|-------|
| `control` | `Control<T>` | From `useForm()` |
| `name` | `FieldPath<T>` | Field name |
| `children` | `(props: FormFieldRenderProps) => ReactNode` | See below |
| `onAutosave` | `(value) => Promise<void>` | Optional; enables debounced save |
| `autosaveDebounceMs` | `number` | ms, default `1000` |
| … | | Other `Controller` props (`rules`, `defaultValue`, etc.) |

**`FormFieldRenderProps`:**

| Property | Type | Use |
|----------|------|-----|
| `field` | `ControllerRenderProps` | Spread on inputs: `{...field}` |
| `error` | `FieldError \| undefined` | Pass to `<FieldError error={error} />` |
| `ids` | `{ control, description, message }` | Optional `htmlFor` / `id` wiring by hand |
| `autosave` | `AutosaveState \| undefined` | When `onAutosave` is set |

`FormField` wraps its content in `@zuilib/components/field`, a Headless UI `Field`: `Label`, `FieldDescription`, `FieldError` and the control rendered inside are associated automatically (`for`, `aria-labelledby`, `aria-describedby`), and the field is marked `invalid` whenever it has an `error`, so every control inside gets `aria-invalid` and the error styling without extra props. The `ids` render prop is kept for consumers who wire ids by hand; an explicit `id` / `htmlFor` wins over the generated one, so passing them never produces duplicates.

### useAutosave — `@zuilib/form/use-autosave`

Standalone debounced save (same logic as `FormField`’s `onAutosave`):

```tsx
import { useAutosave } from '@zuilib/form/use-autosave'

const { status, lastSaved, error, retry } = useAutosave({
  value: watchedValue,
  onAutosave: async (value) => api.save(value),
  debounceMs: 1000,
})
// status: 'idle' | 'unsaved' | 'saving' | 'saved' | 'error'
```

Show unsaved state on labels: `<Label unsaved={status === 'unsaved'}>`.

## Recipes

### Zod validation

```tsx
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'

const schema = z.object({
  email: z.string().email(),
})

const form = useForm({ resolver: zodResolver(schema), defaultValues: { email: '' } })
```

### Controlled core components (Checkbox, Switch, Select, Combobox, RadioGroup)

Do **not** rely on `{...field}` alone — wire `checked` / `value` and the change handler:

```tsx
<FormField control={form.control} name="terms">
  {({ field }) => (
    <Checkbox
      checked={field.value}
      onCheckedChange={field.onChange}
      label="I agree"
    />
  )}
</FormField>
```

### Field with autosave

```tsx
<FormField
  control={form.control}
  name="bio"
  onAutosave={async (value) => api.patchBio(value)}
  autosaveDebounceMs={800}
>
  {({ field, autosave, error, ids }) => (
    <>
      <Label htmlFor={ids.control} unsaved={autosave?.status === 'unsaved'}>Bio</Label>
      <Textarea id={ids.control} {...field} />
      <FieldError error={error} />
    </>
  )}
</FormField>
```

### Description vs error

Show helper text only when there is no error:

```tsx
{!error && <FieldDescription id={ids.description}>Optional hint</FieldDescription>}
<FieldError id={ids.message} error={error} />
```

## Related packages

- `@zuilib/components` — all visual components and `styles.css`
- `@zuilib/text-editor` — use `MarkdownEditor` inside `FormField` with controlled `value` / `onValueChange`

## Build (maintainers)

```bash
pnpm --filter @zuilib/form build
```

Tests (vitest + jsdom + axe, mirroring `@zuilib/components`):

```bash
pnpm --filter @zuilib/form test
pnpm --filter @zuilib/form typecheck
```
