# FormControl

## Introduction

FormControl is a wrapper component that provides context to form elements such as Input, Textarea, Select, and more. It manages shared states like `error`, `disabled`, `required`, and `size`, passing them down to its children automatically. Use it with FormLabel and FormHelperText to build accessible, consistent form fields.

```tsx
<FormControl {...args}>
    <FormLabel>Label</FormLabel>
    <Input placeholder="Enter text…" />
    <FormHelperText>This is helper text.</FormHelperText>
  </FormControl>
```

| Field       | Description | Default |
| ----------- | ----------- | ------- |
| size        | —           | —       |
| error       | —           | —       |
| disabled    | —           | —       |
| required    | —           | —       |
| orientation | —           | —       |

## Usage

```tsx
import { FormControl, FormLabel, FormHelperText, Input } from '@ceed/cds';

function MyForm() {
  return (
    <FormControl>
      <FormLabel>Username</FormLabel>
      <Input placeholder="Enter username" />
      <FormHelperText>Choose a unique username.</FormHelperText>
    </FormControl>
  );
}
```

## With Input

The most common pattern — wrapping an Input with a label and helper text.

```tsx
<FormControl>
    <FormLabel>Username</FormLabel>
    <Input placeholder="Enter username" />
    <FormHelperText>Choose a unique username.</FormHelperText>
  </FormControl>
```

## With Textarea

FormControl works equally well with Textarea components.

```tsx
<FormControl>
    <FormLabel>Description</FormLabel>
    <Textarea placeholder="Enter description…" minRows={3} />
    <FormHelperText>Provide a detailed description.</FormHelperText>
  </FormControl>
```

## With Select

Use FormControl with Select for dropdown fields.

```tsx
<FormControl>
    <FormLabel>Role</FormLabel>
    <Select placeholder="Select a role" options={roleOptions} />
    <FormHelperText>Select the user role.</FormHelperText>
  </FormControl>
```

## Error State

Set `error` on FormControl to propagate the error state to all child components. FormHelperText automatically changes color to indicate the error.

```tsx
<FormControl error>
    <FormLabel>Email</FormLabel>
    <Input placeholder="email@example.com" defaultValue="invalid-email" />
    <FormHelperText>Please enter a valid email address.</FormHelperText>
  </FormControl>
```

```tsx
<FormControl error>
  <FormLabel>Email</FormLabel>
  <Input placeholder="email@example.com" value="invalid-email" />
  <FormHelperText>Please enter a valid email address.</FormHelperText>
</FormControl>
```

## Disabled State

Set `disabled` to disable all child form elements at once.

```tsx
<FormControl disabled>
    <FormLabel>Name</FormLabel>
    <Input placeholder="Enter name" defaultValue="John Doe" />
    <FormHelperText>This field is disabled.</FormHelperText>
  </FormControl>
```

```tsx
<FormControl disabled>
  <FormLabel>Name</FormLabel>
  <Input placeholder="Enter name" value="John Doe" />
  <FormHelperText>This field is disabled.</FormHelperText>
</FormControl>
```

## Required Field

Set `required` to add an asterisk (\*) to the label and mark the field as required.

```tsx
<FormControl required>
    <FormLabel>Full Name</FormLabel>
    <Input placeholder="Enter your full name" />
    <FormHelperText>This field is required.</FormHelperText>
  </FormControl>
```

```tsx
<FormControl required>
  <FormLabel>Full Name</FormLabel>
  <Input placeholder="Enter your full name" />
</FormControl>
```

## Sizes

FormControl supports `sm`, `md`, and `lg` sizes. The size is inherited by child components.

```tsx
<Stack gap={3}>
    <FormControl size="sm">
      <FormLabel>Small</FormLabel>
      <Input placeholder="Small input" />
    </FormControl>
    <FormControl size="md">
      <FormLabel>Medium</FormLabel>
      <Input placeholder="Medium input" />
    </FormControl>
    <FormControl size="lg">
      <FormLabel>Large</FormLabel>
      <Input placeholder="Large input" />
    </FormControl>
  </Stack>
```

## Horizontal Layout

Use `orientation="horizontal"` for inline form controls, such as Switch or Checkbox toggles.

```tsx
<FormControl
    orientation="horizontal"
    sx={{
      gap: 2
    }}
  >
    <FormLabel>Subscribe</FormLabel>
    <Switch />
  </FormControl>
```

```tsx
<FormControl orientation="horizontal" sx={{ gap: 2 }}>
  <FormLabel>Subscribe</FormLabel>
  <Switch />
</FormControl>
```

## Form Example

A complete form demonstrating FormControl with multiple input types.

```tsx
<Stack
    gap={2}
    sx={{
      maxWidth: 400
    }}
  >
    <FormControl required>
      <FormLabel>Name</FormLabel>
      <Input placeholder="Enter your name" />
    </FormControl>
    <FormControl required>
      <FormLabel>Email</FormLabel>
      <Input type="email" placeholder="email@example.com" />
      <FormHelperText>We will never share your email.</FormHelperText>
    </FormControl>
    <FormControl>
      <FormLabel>Role</FormLabel>
      <Select placeholder="Select a role" options={roleOptions} />
    </FormControl>
    <FormControl>
      <FormLabel>Bio</FormLabel>
      <Textarea placeholder="Tell us about yourself…" minRows={3} />
      <FormHelperText>Maximum 500 characters.</FormHelperText>
    </FormControl>
  </Stack>
```

## FormLabel

FormLabel renders a `<label>` element associated with its sibling input. It automatically displays an asterisk when the parent FormControl has `required` set.

```tsx
<FormControl required>
  <FormLabel>Email</FormLabel>
  <Input />
</FormControl>
```

## FormHelperText

FormHelperText provides supplementary guidance below the input. It automatically switches to the error color when the parent FormControl has `error` set.

```tsx
<FormControl error>
  <FormLabel>Password</FormLabel>
  <Input type="password" />
  <FormHelperText>Password must be at least 8 characters.</FormHelperText>
</FormControl>
```

## Common Use Cases

### Registration Form

```tsx
function RegistrationForm() {
  const [errors, setErrors] = React.useState({});

  return (
    <Stack gap={2} component="form">
      <FormControl required error={!!errors.name}>
        <FormLabel>Name</FormLabel>
        <Input placeholder="Enter your name" />
        {errors.name && <FormHelperText>{errors.name}</FormHelperText>}
      </FormControl>

      <FormControl required error={!!errors.email}>
        <FormLabel>Email</FormLabel>
        <Input type="email" placeholder="email@example.com" />
        {errors.email && <FormHelperText>{errors.email}</FormHelperText>}
      </FormControl>

      <FormControl required error={!!errors.password}>
        <FormLabel>Password</FormLabel>
        <Input type="password" placeholder="Enter password" />
        <FormHelperText>{errors.password || 'Must be at least 8 characters.'}</FormHelperText>
      </FormControl>

      <FormControl orientation="horizontal">
        <Checkbox label="I agree to the terms and conditions" />
      </FormControl>
    </Stack>
  );
}
```

### Settings Form with Mixed Controls

```tsx
function SettingsForm() {
  return (
    <Stack gap={2}>
      <FormControl orientation="horizontal" sx={{ justifyContent: 'space-between' }}>
        <FormLabel>Email notifications</FormLabel>
        <Switch />
      </FormControl>

      <FormControl>
        <FormLabel>Language</FormLabel>
        <Select
          defaultValue="en"
          options={[
            { value: 'en', label: 'English' },
            { value: 'ko', label: 'Korean' },
          ]}
        />
      </FormControl>

      <FormControl>
        <FormLabel>Notes</FormLabel>
        <Textarea minRows={3} placeholder="Additional notes…" />
        <FormHelperText>Optional</FormHelperText>
      </FormControl>
    </Stack>
  );
}
```

> **Tip: Use built-in form props instead**
>
> Input-family components such as Input, Select, Textarea, and DatePicker support `label` and `helperText` props directly.
> For simple form fields, using each component's built-in props is more concise.
>
> ```tsx
> // ✅ Simpler: built-in props
> <Input label="Username" helperText="Choose a unique username." />
>
> // ⬆️ Equivalent to:
> <FormControl>
>   <FormLabel>Username</FormLabel>
>   <Input placeholder="Enter username" />
>   <FormHelperText>Choose a unique username.</FormHelperText>
> </FormControl>
> ```
>
> FormControl is most useful when you need to compose multiple elements, share state across siblings, or use horizontal orientation.

## Best Practices

1. **Always pair with FormLabel**: Every form field should have a label for accessibility. Use FormLabel inside FormControl.

```tsx
// ✅ Accessible — label is associated with input
<FormControl>
  <FormLabel>Email</FormLabel>
  <Input />
</FormControl>

// ❌ No label — screen readers cannot identify the input
<FormControl>
  <Input placeholder="Email" />
</FormControl>
```

2. **Use `error` prop on FormControl, not children**: Set error state on FormControl so all children react consistently.

```tsx
// ✅ Error propagated from FormControl
<FormControl error>
  <FormLabel>Email</FormLabel>
  <Input />
  <FormHelperText>Invalid email</FormHelperText>
</FormControl>

// ❌ Inconsistent — only Input shows error
<FormControl>
  <FormLabel>Email</FormLabel>
  <Input error />
  <FormHelperText>Invalid email</FormHelperText>
</FormControl>
```

3. **Use consistent sizing**: Set `size` on FormControl to ensure all children (label, input, helper text) are proportionally sized.

4. **Mark required fields**: Use the `required` prop to automatically add visual indicators and `aria-required` attributes.

5. **Provide helpful error messages**: When using the error state, always include a FormHelperText explaining what went wrong and how to fix it.

## Props and Customization

### FormControl Props

| Prop          | Type                                                           | Default      | Description                                                       |
| ------------- | -------------------------------------------------------------- | ------------ | ----------------------------------------------------------------- |
| `children`    | `ReactNode`                                                    | -            | Form field elements (FormLabel, Input, FormHelperText, etc.)      |
| `error`       | `boolean`                                                      | `false`      | Applies error styling to child components                         |
| `disabled`    | `boolean`                                                      | `false`      | Disables all child form elements                                  |
| `required`    | `boolean`                                                      | `false`      | Adds required indicator to FormLabel and `aria-required` to input |
| `size`        | `'sm' \| 'md' \| 'lg'`                                         | `'md'`       | Size applied to child components                                  |
| `color`       | `'primary' \| 'neutral' \| 'danger' \| 'success' \| 'warning'` | `'neutral'`  | Color scheme                                                      |
| `orientation` | `'horizontal' \| 'vertical'`                                   | `'vertical'` | Layout direction                                                  |
| `sx`          | `SxProps`                                                      | -            | Custom styles using the MUI system                                |

### FormLabel Props

| Prop       | Type        | Default | Description                                             |
| ---------- | ----------- | ------- | ------------------------------------------------------- |
| `children` | `ReactNode` | -       | Label text                                              |
| `required` | `boolean`   | -       | Shows asterisk (inherited from FormControl when nested) |

### FormHelperText Props

| Prop       | Type        | Default | Description                  |
| ---------- | ----------- | ------- | ---------------------------- |
| `children` | `ReactNode` | -       | Helper or error message text |

> **Note**: FormControl, FormLabel, and FormHelperText accept all their respective Joy UI props.

## Accessibility

- FormControl automatically associates FormLabel with the input using `htmlFor` and `id`.
- The `required` prop adds `aria-required="true"` to the input and an asterisk to the label.
- The `error` prop adds `aria-invalid="true"` to the input.
- FormHelperText is linked to the input via `aria-describedby` so screen readers announce it.
- Use the `disabled` prop on FormControl to set `aria-disabled` on child elements.
