# FilterableCheckboxGroup

## Introduction

FilterableCheckboxGroup is a multi-select component that combines a search input with a scrollable list of checkboxes. It is designed for scenarios where users need to select multiple items from a potentially large dataset. The built-in search filter narrows down visible options in real time, and virtual scrolling ensures smooth performance even with hundreds of items.

Key capabilities include a "Select all" toggle for bulk selection, automatic sorting (selected items first, then alphabetical), customizable list height, and built-in form integration via `label`, `helperText`, and `required` props. The component accepts options as either simple strings or `{ value, label }` objects.

> **Using built-in props is recommended when building forms**
>
> This component provides built-in form-related props such as `label` and `helperText`.
> When building a form, use the component's built-in props instead of creating separate labels or helper text with Typography.

```tsx
<FilterableCheckboxGroup
  label="Select Fruits"
  placeholder="Search fruits..."
  options={defaultOptions}
/>
```

| Field       | Description | Default |
| ----------- | ----------- | ------- |
| size        | —           | —       |
| label       | —           | —       |
| helperText  | —           | —       |
| required    | —           | —       |
| value       | —           | —       |
| onChange    | —           | —       |
| placeholder | —           | —       |
| options     | —           | —       |
| maxHeight   | —           | —       |

## Usage

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

function MyComponent() {
  const [selectedValues, setSelectedValues] = useState<string[]>([]);

  const options = [
    { value: 'apple', label: 'Apple' },
    { value: 'banana', label: 'Banana' },
    { value: 'cherry', label: 'Cherry' },
  ];

  return (
    <FilterableCheckboxGroup
      label="Select Fruits"
      placeholder="Search fruits..."
      options={options}
      value={selectedValues}
      onChange={setSelectedValues}
    />
  );
}
```

## Sizes

Three sizes are available: `sm`, `md`, and `lg`. The size affects the search input, checkboxes, and overall spacing.

```tsx
<Stack spacing={3}>
    <FilterableCheckboxGroup {...args} size="lg" label="Large" />
    <FilterableCheckboxGroup {...args} size="md" label="Medium" />
    <FilterableCheckboxGroup {...args} size="sm" label="Small" />
  </Stack>
```

## Label and Helper Text

### With Label

Use the `label` prop to describe the purpose of the checkbox group.

```tsx
<FilterableCheckboxGroup
  label="Select your favorite fruits"
  placeholder="Search fruits..."
  options={defaultOptions}
/>
```

### With Helper Text

Add a `helperText` prop to provide additional guidance below the component.

```tsx
<FilterableCheckboxGroup
  label="Select Fruits"
  placeholder="Search fruits..."
  helperText="You can select multiple options"
  options={defaultOptions}
/>
```

### Required Field

Set `required` to append a required indicator to the label.

```tsx
<FilterableCheckboxGroup
  label="Required Field"
  placeholder="Search..."
  required
  helperText="This field is required"
  options={defaultOptions}
/>
```

## Custom Max Height

Control the visible height of the options list with the `maxHeight` prop (default: 300px). A smaller height is useful when screen space is limited.

```tsx
<Stack spacing={3}>
    <FilterableCheckboxGroup
      label="Custom Height (150px)"
      placeholder="Search..."
      options={defaultOptions}
      maxHeight={150}
    />
    <FilterableCheckboxGroup
      label="Default Height (300px)"
      placeholder="Search..."
      options={defaultOptions}
    />
  </Stack>
```

## Long List with Virtual Scrolling

When the options list is large, the component uses virtual scrolling to render only the visible items. This keeps the UI performant regardless of the total number of options.

```tsx
<FilterableCheckboxGroup
  label="Countries"
  placeholder="Search countries..."
  options={countryNames.map(name => ({
  value: name.toLowerCase().replace(/ /g, '-'),
  label: name
}))}
/>
```

## Empty State

When no options are provided, the component displays an empty state. This is useful for dynamically loaded option lists that may start empty.

```tsx
<FilterableCheckboxGroup
  label="No Options Available"
  placeholder="Search..."
  options={[]}
/>
```

## Controlled Mode

Pass `value` and `onChange` to manage the selection state externally. This is the recommended approach when the component is part of a form or when the selected values need to be used by other parts of the UI.

```tsx
<Stack spacing={2}>
    <FilterableCheckboxGroup
      label="Select Fruits"
      placeholder="Search fruits..."
      options={defaultOptions}
      value={value}
      onChange={setValue}
    />
    <Typography level="body-sm">
      Selected:{" "}
      {value.length > 0
        ? value.map((v) => defaultOptions.find((o) => o.value === v)?.label).join(", ")
        : "None"}
    </Typography>
  </Stack>
```

## Sorting Behavior

The component automatically sorts options on initial render: selected items appear first, followed by unselected items in alphabetical order. When new options are added dynamically, they are inserted in the correct sorted position.

```tsx
<Stack spacing={2}>
    <Stack direction="row" spacing={1}>
      <button
        type="button"
        onClick={() => {
          setOptions([
            ...options,
            {
              value: `new-${Date.now()}`,
              label: `New Item ${options.length - 11}`
            }
          ]);
        }}
        style={{
          padding: "4px 12px",
          cursor: "pointer"
        }}
      >
        Add New Option
      </button>
      <button
        type="button"
        onClick={() => {
          setKey((prev) => prev + 1);
        }}
        style={{
          padding: "4px 12px",
          cursor: "pointer"
        }}
      >
        Force Re-render
      </button>
    </Stack>
    <FilterableCheckboxGroup
      key={key}
      label="Sorting Demo"
      placeholder="Search..."
      helperText="Click 'Add New Option' to test sorting when options change"
      options={options}
      value={value}
      onChange={setValue}
    />
    <Typography
      level="body-sm"
      sx={{
        whiteSpace: "pre-line"
      }}
    >
      {`Selected: ${value.length > 0 ? value.join(", ") : "None"}\n\nOptions count: ${options.length}\n\n- Add New Option: Add new item to test sorting when options change\n- Force Re-render: Remount component to test initial sorting\n\nAlphabet items (A-Z) appear first, then numbers (1-9).`}
    </Typography>
  </Stack>
```

## Disabled State

The component supports both full and partial disabling.

- **Full disable**: Set `disabled` on the component to disable the search input, "Select all" toggle, and all checkboxes.
- **Partial disable**: Set `disabled: true` on individual option objects to disable specific items while keeping the rest interactive.
- **"Select all" behavior**: Disabled options are excluded from the "Select all" toggle. Their selected state is preserved regardless of bulk actions.

```tsx
<Stack spacing={3}>
    <FilterableCheckboxGroup
      label="Entirely Disabled"
      placeholder="Search..."
      helperText="All inputs are disabled"
      options={defaultOptions.slice(0, 5)}
      disabled
    />
    <FilterableCheckboxGroup
      label="Partially Disabled Options"
      placeholder="Search..."
      helperText="Some options are disabled"
      options={disabledOptions}
    />
    <Stack spacing={2}>
      <FilterableCheckboxGroup
        label="Controlled + Partially Disabled"
        placeholder="Search..."
        helperText="Disabled options (Banana, Date) maintain their selected state"
        options={disabledOptions}
        value={controlledValue}
        onChange={setControlledValue}
      />
      <Typography level="body-sm">
        Selected: {controlledValue.length > 0 ? controlledValue.join(", ") : "None"}
      </Typography>
      <Typography
        level="body-sm"
        sx={{
          color: "text.secondary"
        }}
      >
        Try "Select all" - it will only affect enabled options (Apple, Cherry, Elderberry)
      </Typography>
    </Stack>
  </Stack>
```

## Common Use Cases

### Filter Panel

Use FilterableCheckboxGroup in a sidebar or panel to let users filter a data table or list by multiple criteria.

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

function FilterPanel({ categories, onFilterChange }) {
  const [selected, setSelected] = useState<string[]>([]);

  const handleChange = (values: string[]) => {
    setSelected(values);
    onFilterChange(values);
  };

  return (
    <FilterableCheckboxGroup
      label="Categories"
      placeholder="Search categories..."
      options={categories}
      value={selected}
      onChange={handleChange}
      maxHeight={200}
    />
  );
}
```

### User Role Assignment

Assign multiple roles to a user from a searchable list.

```tsx
<FilterableCheckboxGroup
  label="Assign Roles"
  placeholder="Search roles..."
  helperText="Select all roles that apply to this user"
  options={[
    { value: 'admin', label: 'Administrator' },
    { value: 'editor', label: 'Editor' },
    { value: 'viewer', label: 'Viewer' },
    { value: 'moderator', label: 'Moderator' },
    { value: 'billing', label: 'Billing Manager' },
  ]}
  required
  value={selectedRoles}
  onChange={setSelectedRoles}
/>
```

### Region / Country Selection

When dealing with a large set of options like countries, the search filter and virtual scrolling work together for fast selection.

```tsx
<FilterableCheckboxGroup
  label="Service Regions"
  placeholder="Search countries..."
  options={allCountries.map((c) => ({ value: c.code, label: c.name }))}
  value={selectedCountries}
  onChange={setSelectedCountries}
/>
```

## Best Practices

1. **Provide a meaningful placeholder.** The search input placeholder should hint at the type of content being filtered (e.g., "Search countries..." instead of a generic "Search...").

```tsx
// ✅ Specific and helpful
<FilterableCheckboxGroup placeholder="Search countries..." />

// ❌ Too generic
<FilterableCheckboxGroup placeholder="Type here..." />
```

2. **Use `maxHeight` to fit the layout.** In tight spaces like sidebars or modals, set a smaller `maxHeight` to prevent the component from dominating the layout.

3. **Prefer controlled mode for form integration.** Always pass `value` and `onChange` when the selected values participate in form submission or affect other UI state.

4. **Leverage individual `disabled` for permissions.** When some options should be visible but not selectable (e.g., due to user permissions), disable them individually rather than hiding them. This communicates availability without surprising users.

5. **Keep option labels concise.** Long labels will be truncated with an ellipsis. If detailed descriptions are needed, consider using a tooltip or a separate detail view.

## Props and Customization

### Key Props

| Prop          | Type                                                     | Default    | Description                                         |
| ------------- | -------------------------------------------------------- | ---------- | --------------------------------------------------- |
| `options`     | `{ value: string; label: string; disabled?: boolean }[]` | (required) | Array of checkbox options                           |
| `value`       | `string[] \| null`                                       | -          | Selected values (controlled mode)                   |
| `onChange`    | `(value: string[]) => void`                              | -          | Callback when selection changes                     |
| `label`       | `ReactNode`                                              | -          | Group label displayed above the component           |
| `helperText`  | `ReactNode`                                              | -          | Helper text displayed below the component           |
| `placeholder` | `string`                                                 | -          | Placeholder text for the search input               |
| `required`    | `boolean`                                                | `false`    | Marks the field as required                         |
| `disabled`    | `boolean`                                                | `false`    | Disables all checkboxes                             |
| `size`        | `'sm' \| 'md' \| 'lg'`                                   | `'md'`     | Component size                                      |
| `maxHeight`   | `string \| number`                                       | `300`      | Maximum height of the options list before scrolling |

> **Note**: For a **controlled** field that starts empty, pass `null` as `value`. Passing `undefined` makes the field uncontrolled from the first render, so later external updates (including resetting it to an empty value) are not reflected on screen.

## Accessibility

- The search input is labeled by the component's `label` prop, ensuring screen readers announce its purpose.
- Each checkbox option uses a native `<input type="checkbox">` with an associated `<label>`, enabling click-on-label and proper screen reader announcements.
- The "Select all" toggle clearly communicates its tri-state behavior (all, none, indeterminate) to assistive technologies.
- Keyboard navigation is fully supported: Tab to move between the search input and the checkbox list, Space to toggle individual checkboxes, and standard arrow keys to navigate within the list.
