# Checkbox

## Introduction

Checkbox is an input element that allows users to select one or more options from a set. Built on Joy UI's Checkbox with Framer Motion animation support, it is used in settings screens, forms, filters, multi-select lists, and agreement flows. It supports indeterminate state for "select all" patterns, decorators for custom content, and overlay mode for clickable card patterns.

```tsx
<Checkbox />
```

| Field          | Description | Default |
| -------------- | ----------- | ------- |
| checked        | —           | —       |
| defaultChecked | —           | —       |
| disabled       | —           | —       |
| indeterminate  | —           | —       |
| required       | —           | —       |
| label          | —           | —       |
| variant        | —           | —       |
| color          | —           | —       |
| size           | —           | —       |

## Usage

```tsx
import { Checkbox } from '@ceed/cds';

function MyComponent() {
  const [checked, setChecked] = useState(false);

  return <Checkbox label="I agree" checked={checked} onChange={(e) => setChecked(e.target.checked)} />;
}
```

## Examples

### Basic Usage

A simple checkbox with a label.

```tsx
<Checkbox
  label="Label"
  onChange={fn()}
/>
```

### Variants

Four visual styles are available: `solid` (default when checked), `soft`, `outlined`, and `plain`.

```tsx
<Stack spacing={2}>
  <Checkbox label="Solid" variant="solid" defaultChecked />
  <Checkbox label="Soft" variant="soft" defaultChecked />
  <Checkbox label="Outlined" variant="outlined" defaultChecked />
  <Checkbox label="Plain" variant="plain" defaultChecked />
</Stack>
```

### Sizes

Three sizes are available: `sm`, `md` (default), and `lg`.

```tsx
<Stack direction="row" spacing={2} alignItems="center">
  <Checkbox label="Small" size="sm" defaultChecked />
  <Checkbox label="Medium" size="md" defaultChecked />
  <Checkbox label="Large" size="lg" defaultChecked />
</Stack>
```

### Colors

Apply semantic colors to communicate meaning.

```tsx
<Stack spacing={2}>
  <Checkbox label="Primary" color="primary" defaultChecked />
  <Checkbox label="Success" color="success" defaultChecked />
  <Checkbox label="Warning" color="warning" defaultChecked />
  <Checkbox label="Danger" color="danger" defaultChecked />
  <Checkbox label="Neutral" color="neutral" defaultChecked />
</Stack>
```

## States

### Indeterminate

Represents a partially selected state, commonly used in "select all" patterns where some but not all children are selected.

```tsx
<Checkbox label="Partially selected" indeterminate onChange={handleChange} />
```

### Disabled

A disabled checkbox cannot be interacted with.

```tsx
<Stack spacing={1}>
  <Checkbox label="Disabled (unchecked)" disabled />
  <Checkbox label="Disabled (checked)" disabled defaultChecked />
  <Checkbox label="Disabled (indeterminate)" disabled indeterminate />
</Stack>
```

### Error

Use with `FormControl` to show validation errors.

```tsx
<FormControl error>
  <Checkbox label="Required agreement" required />
  <FormHelperText>
    <InfoOutlinedIcon />
    This field is required.
  </FormHelperText>
</FormControl>
```

## Common Use Cases

### Terms and Conditions

```tsx
function TermsForm() {
  const [agreements, setAgreements] = useState({
    terms: false,
    privacy: false,
    marketing: false,
  });

  const handleChange = (key: keyof typeof agreements) => (event: React.ChangeEvent<HTMLInputElement>) => {
    setAgreements((prev) => ({ ...prev, [key]: event.target.checked }));
  };

  return (
    <Stack spacing={2}>
      <Typography level="title-md">Agreements</Typography>

      <Checkbox
        label={
          <Typography>
            <strong>(Required)</strong> I agree to the Terms of Service.
            <Link href="/terms" target="_blank" sx={{ ml: 1 }}>
              View Terms
            </Link>
          </Typography>
        }
        checked={agreements.terms}
        onChange={handleChange('terms')}
        required
      />

      <Checkbox
        label={
          <Typography>
            <strong>(Required)</strong> I agree to the Privacy Policy.
            <Link href="/privacy" target="_blank" sx={{ ml: 1 }}>
              View Policy
            </Link>
          </Typography>
        }
        checked={agreements.privacy}
        onChange={handleChange('privacy')}
        required
      />

      <Checkbox
        label="(Optional) I agree to receive marketing communications."
        checked={agreements.marketing}
        onChange={handleChange('marketing')}
        color="neutral"
      />

      <Button disabled={!agreements.terms || !agreements.privacy} sx={{ mt: 2 }}>
        Sign Up
      </Button>
    </Stack>
  );
}
```

### Select All Pattern

```tsx
function SelectAllExample() {
  const [items, setItems] = useState([
    { id: 1, name: 'Item 1', selected: false },
    { id: 2, name: 'Item 2', selected: true },
    { id: 3, name: 'Item 3', selected: false },
    { id: 4, name: 'Item 4', selected: false },
  ]);

  const selectedCount = items.filter((item) => item.selected).length;
  const isAllSelected = selectedCount === items.length;
  const isIndeterminate = selectedCount > 0 && selectedCount < items.length;

  const handleSelectAll = (event: React.ChangeEvent<HTMLInputElement>) => {
    setItems((prev) => prev.map((item) => ({ ...item, selected: event.target.checked })));
  };

  const handleItemToggle = (id: number) => {
    setItems((prev) => prev.map((item) => (item.id === id ? { ...item, selected: !item.selected } : item)));
  };

  return (
    <Stack spacing={2}>
      <Checkbox
        label={`Select All (${selectedCount}/${items.length})`}
        checked={isAllSelected}
        indeterminate={isIndeterminate}
        onChange={handleSelectAll}
        variant="outlined"
        sx={{ fontWeight: 'bold' }}
      />

      <Divider />

      <Stack spacing={1} sx={{ pl: 2 }}>
        {items.map((item) => (
          <Checkbox
            key={item.id}
            label={item.name}
            checked={item.selected}
            onChange={() => handleItemToggle(item.id)}
            size="sm"
          />
        ))}
      </Stack>
    </Stack>
  );
}
```

### Filter Options

```tsx
function ProductFilter() {
  const [filters, setFilters] = useState({
    categories: [] as string[],
  });

  const handleCategoryChange = (category: string) => (event: React.ChangeEvent<HTMLInputElement>) => {
    setFilters((prev) => ({
      ...prev,
      categories: event.target.checked ? [...prev.categories, category] : prev.categories.filter((c) => c !== category),
    }));
  };

  return (
    <Stack spacing={2}>
      <Typography level="title-sm">Categories</Typography>
      <Stack spacing={1} sx={{ pl: 1 }}>
        <Checkbox
          label="Electronics"
          checked={filters.categories.includes('electronics')}
          onChange={handleCategoryChange('electronics')}
          size="sm"
        />
        <Checkbox
          label="Clothing"
          checked={filters.categories.includes('clothing')}
          onChange={handleCategoryChange('clothing')}
          size="sm"
        />
        <Checkbox
          label="Books"
          checked={filters.categories.includes('books')}
          onChange={handleCategoryChange('books')}
          size="sm"
        />
      </Stack>
    </Stack>
  );
}
```

## Props and Customization

### Key Props

| Prop                | Type                                                           | Default     | Description                                                                               |
| ------------------- | -------------------------------------------------------------- | ----------- | ----------------------------------------------------------------------------------------- |
| `checked`           | `boolean`                                                      | -           | Whether the checkbox is checked (controlled)                                              |
| `defaultChecked`    | `boolean`                                                      | `false`     | Initial checked state (uncontrolled)                                                      |
| `indeterminate`     | `boolean`                                                      | `false`     | Shows a partial selection state (dash icon instead of checkmark)                          |
| `label`             | `ReactNode`                                                    | -           | Label content displayed next to the checkbox                                              |
| `onChange`          | `(event: ChangeEvent<HTMLInputElement>) => void`               | -           | Callback when the checked state changes                                                   |
| `ref`               | `React.Ref<HTMLElement>`                                       | -           | Ref to the checkbox root element (a `span` by default).                                   |
| `color`             | `'primary' \| 'neutral' \| 'danger' \| 'success' \| 'warning'` | `'neutral'` | Color scheme                                                                              |
| `size`              | `'sm' \| 'md' \| 'lg'`                                         | `'md'`      | Checkbox size                                                                             |
| `variant`           | `'solid' \| 'soft' \| 'outlined' \| 'plain'`                   | `'solid'`   | Visual style when checked                                                                 |
| `disabled`          | `boolean`                                                      | `false`     | Disables the checkbox                                                                     |
| `readOnly`          | `boolean`                                                      | `false`     | Makes the checkbox read-only                                                              |
| `required`          | `boolean`                                                      | `false`     | Marks the field as required                                                               |
| `name`              | `string`                                                       | -           | HTML name attribute for form submission                                                   |
| `value`             | `string \| number`                                             | -           | Value attribute for form submission                                                       |
| `overlay`           | `boolean`                                                      | `false`     | Extends the clickable area to cover the parent container (useful for card-click patterns) |
| `disableIcon`       | `boolean`                                                      | `false`     | Hides the checkbox icon                                                                   |
| `checkedIcon`       | `ReactNode`                                                    | -           | Custom icon for the checked state                                                         |
| `uncheckedIcon`     | `ReactNode`                                                    | -           | Custom icon for the unchecked state                                                       |
| `indeterminateIcon` | `ReactNode`                                                    | -           | Custom icon for the indeterminate state                                                   |
| `endDecorator`      | `ReactNode`                                                    | -           | Content rendered after the checkbox label                                                 |
| `sx`                | `SxProps`                                                      | -           | Custom styles using the MUI system                                                        |

> **Note**: Checkbox also accepts all Joy UI Checkbox props and Framer Motion props.

## Best Practices

1. **Use clear, descriptive labels.** The label should make it obvious what the user is agreeing to or selecting.

```tsx
// ✅ Good
<Checkbox label="I agree to receive marketing emails" />

// ❌ Bad
<Checkbox label="Agree" />
```

2. **Group related checkboxes logically.** Use headings and indentation to create visual hierarchy.

```tsx
<Stack spacing={3}>
  <Typography level="title-md">Notification Settings</Typography>
  <Stack spacing={1} sx={{ pl: 1 }}>
    <Checkbox label="Email notifications" />
    <Checkbox label="SMS notifications" />
    <Checkbox label="Push notifications" />
  </Stack>
</Stack>
```

3. **Distinguish required from optional.** Make it clear which selections are mandatory.

```tsx
<Checkbox label={<><strong>(Required)</strong> Accept Terms</>} required />
<Checkbox label="(Optional) Subscribe to newsletter" color="neutral" />
```

4. **Use the indeterminate state correctly.** Only apply it to a parent checkbox that represents a group of child checkboxes with mixed selection.

5. **Prefer Checkbox over Switch** when the setting is a binary choice that is not applied immediately. Use Switch for instant toggle actions.

## Accessibility

- **Keyboard navigation**: Tab to focus, Space to toggle checked state.
- **ARIA attributes**: `role="checkbox"`, `aria-checked` reflects the current state (including `mixed` for indeterminate).
- **Label association**: The `label` prop is automatically associated with the checkbox input.
- **Error state**: When used inside `FormControl` with `error`, `aria-invalid` is applied.
- **Screen reader**: Announces as "\[label], checkbox, checked/unchecked/mixed".

## Performance Tips

Use `Set` instead of arrays for managing selection state in large lists:

```tsx
// ✅ Good: O(1) lookup with Set
const [selected, setSelected] = useState(new Set<number>());

// ❌ Bad: O(n) lookup with Array
const [selected, setSelected] = useState<number[]>([]);
```
