# Select

## Introduction

The Select component is a form input that allows users to choose one or multiple options from a predefined list. Built on Joy UI's Select, it provides a dropdown interface for picking values within forms, filters, and configuration settings.

Select accepts options as an array of objects (with `value`, `label`, and optional `secondaryText` / `disabled` fields) or as simple string/number arrays. It wraps the underlying select element with built-in `FormControl`, `FormLabel`, and `FormHelperText` so you can compose complete form fields with a single component.

```tsx
<Select options={options} />
```

| Field          | Description | Default |
| -------------- | ----------- | ------- |
| variant        | —           | —       |
| color          | —           | —       |
| size           | —           | —       |
| autoFocus      | —           | —       |
| placeholder    | —           | —       |
| startDecorator | —           | —       |
| endDecorator   | —           | —       |
| error          | —           | —       |
| helperText     | —           | —       |
| value          | —           | —       |
| defaultValue   | —           | —       |
| onChange       | —           | —       |
| options        | —           | options |

> **Don't confuse Select with Dropdown**
>
> - **Select**: For form value selection -- the selected value becomes form data.
> - **Dropdown**: For menus and action lists -- triggers actions or navigation.
>
> Choosing the right component:
>
> - Fewer than 5 options -- consider RadioButton or RadioGroup
> - More than 20 options -- consider Autocomplete with search
> - Actions / navigation -- use Dropdown with Menu

> **Use built-in form props**
>
> This component natively supports `label` and `helperText` props.
> When building forms, use these built-in props instead of manually composing labels and helper text with Typography.

## Usage

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

const options = [
  { value: 'dog', label: 'Dog' },
  { value: 'cat', label: 'Cat' },
  { value: 'fish', label: 'Fish' },
];

function MyComponent() {
  return <Select label="Choose a pet" options={options} defaultValue="dog" />;
}
```

## Variants

Select supports four visual styles: `outlined` (default), `plain`, `soft`, and `solid`.

```tsx
<Stack spacing={4}>
    <Select defaultValue="dog" options={options} />
    <Select defaultValue="dog" variant="plain" options={options} />
    <Select defaultValue="dog" variant="soft" options={options} />
    <Select defaultValue="dog" variant="solid" options={options} />
  </Stack>
```

```tsx
<Select options={options} defaultValue="dog" />
<Select options={options} defaultValue="dog" variant="plain" />
<Select options={options} defaultValue="dog" variant="soft" />
<Select options={options} defaultValue="dog" variant="solid" />
```

## Sizes

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

```tsx
<Stack spacing={4}>
    <Select defaultValue="dog" size="sm" options={options} />
    <Select defaultValue="dog" size="md" options={options} />
    <Select defaultValue="dog" size="lg" options={options} />
  </Stack>
```

```tsx
<Select options={options} defaultValue="dog" size="sm" />
<Select options={options} defaultValue="dog" size="md" />
<Select options={options} defaultValue="dog" size="lg" />
```

## Colors

Apply semantic colors to communicate intent or state.

```tsx
<Stack spacing={4}>
    <Select defaultValue="dog" color="primary" options={options} />
    <Select defaultValue="dog" color="neutral" options={options} />
    <Select defaultValue="dog" color="success" options={options} />
    <Select defaultValue="dog" color="danger" options={options} />
    <Select defaultValue="dog" color="warning" options={options} />
  </Stack>
```

```tsx
<Select options={options} defaultValue="dog" color="primary" />
<Select options={options} defaultValue="dog" color="neutral" />
<Select options={options} defaultValue="dog" color="success" />
<Select options={options} defaultValue="dog" color="danger" />
<Select options={options} defaultValue="dog" color="warning" />
```

## Decorators

Use `startDecorator` and `endDecorator` to add icons, badges, or other elements beside the select trigger.

```tsx
<Select
    placeholder="Select a pet…"
    startDecorator={<FavoriteBorder />}
    endDecorator={
      <Chip size="sm" color="danger" variant="soft">
        +5
      </Chip>
    }
    sx={{
      width: 240
    }}
    options={options}
  />
```

```tsx
import FavoriteBorder from '@mui/icons-material/FavoriteBorder';
import { Chip } from '@ceed/cds';

<Select
  placeholder="Select a pet..."
  startDecorator={<FavoriteBorder />}
  endDecorator={
    <Chip size="sm" color="danger" variant="soft">
      +5
    </Chip>
  }
  options={options}
  sx={{ width: 240 }}
/>;
```

## Label and Helper Text

The `label` prop renders a form label above the select. The `helperText` prop renders descriptive text below it. Both are built into the component so you do not need to compose them separately.

```tsx
<>
    <Select label="Label" defaultValue="dog" options={options} />
  </>
```

```tsx
<>
    <Select label="Select" helperText="I'm helper text" defaultValue="dog" options={options} />
  </>
```

```tsx
<Select label="Pet" options={options} defaultValue="dog" />

<Select
  label="Pet"
  helperText="Choose your favorite animal"
  options={options}
  defaultValue="dog"
/>
```

## Error State

Set `error` to `true` to visually indicate a validation error. Combine with `helperText` to display an error message.

```tsx
<>
    <Select label="label" error defaultValue="dog" options={options} />
  </>
```

```tsx
<Select label="Pet" error helperText="This field is required" options={options} />
```

## Form Control

Combining `label`, `helperText`, and `error` produces a complete form field. Here is a normal field next to one with an error.

```tsx
<>
    <Select label="Label" helperText="I'm helper text" defaultValue="dog" options={options} />
    <Select label="Label" helperText="I'm helper text" defaultValue="dog" error options={options} />
  </>
```

## Slot Props and Deterministic Ids

The `slotProps` prop targets both Joy Select's own slots (`button`, `listbox`, `root`, …) and the wrapper slots that `Select` composes around it (`formControl`, `formLabel`, `formHelperText`). Pass `id` (or `slotProps.formControl.id`) to pin the field's ids deterministically — `FormControl` derives the button `id` and the label `id` (`${id}-label`) from it, which keeps `byLabelText` / `byRole('combobox', { name })` queries stable in tests.

```tsx
<Stack
    spacing={3}
    sx={{
      minWidth: 240
    }}
  >
    {/* id seeds deterministic FormControl ids: button#pet, label#pet-label (testable via byLabelText/byRole) */}
    <Select
      id="pet"
      label="Pet"
      defaultValue="cat"
      options={options}
      slotProps={{
        formLabel: {
          sx: {
            color: "primary.500"
          }
        },
        formHelperText: {
          sx: {
            fontStyle: "italic"
          }
        },
        button: {
          "aria-describedby": "pet-extra"
        }
      }}
      helperText="Wired via slotProps"
    />
  </Stack>
```

```tsx
<Select
  id="pet"
  label="Pet"
  helperText="Wired via slotProps"
  options={options}
  slotProps={{
    formLabel: { sx: { color: 'primary.500' } },
    formHelperText: { sx: { fontStyle: 'italic' } },
    button: { 'aria-describedby': 'pet-extra' },
  }}
/>
// → renders button#pet and label#pet-label, connected via aria-labelledby
```

## Required Field

Set `required` to mark the field as required. An asterisk is added to the label automatically.

```tsx
<Select
  options={options}
  label="Label"
  helperText="I'm helper text"
  required
/>
```

```tsx
<Select label="Pet" helperText="This field is required" required options={options} />
```

## Multiple Selection

Set `multiple` to allow selecting more than one option. The value becomes an array.

```tsx
<Select
  options={options}
  label="Label"
  helperText="I'm helper text"
  defaultValue={['dog']}
  multiple
/>
```

```tsx
<Select label="Pets" multiple defaultValue={['dog']} options={options} />
```

## Controlled Select

Use the `value` and `onChange` props for controlled behavior when you need to synchronize the selected value with other state.

```tsx
<div>
    <Select
      {...args}
      options={options}
      value={value}
      onChange={(event, newValue) => {
        setValue(newValue);
        args.onChange?.(event, newValue);
      }}
    />
    <Select
      {...args}
      options={["dog", "cat", "fish", "bird"] as string[]}
      value={value}
      onChange={(event, newValue) => {
        setValue(newValue);
        args.onChange?.(event, newValue);
      }}
    />
    <Select
      {...args}
      options={["dog", "cat", "fish", "bird"] as string[]}
      value={[value]}
      onChange={(event, newValue) => {
        setValue(newValue);
        args.onChange?.(event, newValue);
      }}
      multiple
    />
  </div>
```

```tsx
const [value, setValue] = useState('dog');

<Select label="Pet" value={value} onChange={(event, newValue) => setValue(newValue)} options={options} />;
```

## Disabled Options

Individual options can be disabled by setting `disabled: true` on the option object.

```tsx
<Select
  options={options.map((option, idx) => ({
  ...option,
  disabled: idx % 2 === 0
}))}
  label="Disabled Options"
  defaultValue="dog"
/>
```

```tsx
const options = [
  { value: 'dog', label: 'Dog', disabled: true },
  { value: 'cat', label: 'Cat' },
  { value: 'fish', label: 'Fish', disabled: true },
  { value: 'bird', label: 'Bird' },
];

<Select label="Pet" options={options} defaultValue="dog" />;
```

## Options with Secondary Text

Add a `secondaryText` field to display supplementary information below each option label. The secondary text size scales proportionally with the component `size`.

```tsx
<Stack spacing={4} direction="row" alignItems="flex-start">
    {sizes.map((size) => (
      <Stack key={size} spacing={1}>
        <span
          style={{
            color: "#6366f1",
            fontSize: 12
          }}
        >
          {size}
        </span>
        <Select
          placeholder="Placeholder"
          options={optionsWithSecondaryText}
          sx={{
            minWidth: 200
          }}
          size={size}
        />
      </Stack>
    ))}
  </Stack>
```

```tsx
const userOptions = [
  { value: 'emily', label: 'Emily Carter', secondaryText: '(415) 555-0198' },
  { value: 'daniel', label: 'Daniel Kim', secondaryText: '(212) 555-0421' },
  { value: 'sophia', label: 'Sophia Martinez', secondaryText: '(646) 555-0734' },
];

<Select placeholder="Select a contact" options={userOptions} />;
```

## Numeric Values

Select supports both string and numeric option values. When using numeric values, TypeScript infers the correct type automatically.

```tsx
<Stack spacing={4}>
    <Select defaultValue={1} options={numericOptions} />
    <Select defaultValue={1} variant="plain" options={numericOptions} />
    <Select defaultValue={1} variant="soft" options={numericOptions} />
    <Select defaultValue={1} variant="solid" options={numericOptions} />
  </Stack>
```

```tsx
const numericOptions = [
  { value: 1, label: 'Option 1' },
  { value: 2, label: 'Option 2' },
  { value: 3, label: 'Option 3' },
];

<Select options={numericOptions} defaultValue={1} />;
```

## Form with Validation

```tsx
import { useState } from 'react';
import { Select, Button, Stack } from '@ceed/cds';

function UserForm() {
  const [role, setRole] = useState<string | null>(null);
  const [submitted, setSubmitted] = useState(false);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitted(true);
    if (role) {
      // submit form
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <Stack spacing={2}>
        <Select
          label="Role"
          required
          value={role}
          onChange={(e, val) => setRole(val)}
          error={submitted && !role}
          helperText={submitted && !role ? 'Please select a role' : undefined}
          options={[
            { value: 'admin', label: 'Administrator' },
            { value: 'editor', label: 'Editor' },
            { value: 'viewer', label: 'Viewer' },
          ]}
          placeholder="Select a role..."
        />
        <Button type="submit">Submit</Button>
      </Stack>
    </form>
  );
}
```

## Filter Bar

```tsx
import { Select, Stack } from '@ceed/cds';

function ProductFilter({ onFilterChange }) {
  const [category, setCategory] = useState('all');
  const [sortBy, setSortBy] = useState('newest');

  useEffect(() => {
    onFilterChange({ category, sortBy });
  }, [category, sortBy]);

  return (
    <Stack direction="row" spacing={2}>
      <Select
        label="Category"
        size="sm"
        value={category}
        onChange={(e, val) => setCategory(val)}
        options={[
          { value: 'all', label: 'All Categories' },
          { value: 'electronics', label: 'Electronics' },
          { value: 'clothing', label: 'Clothing' },
        ]}
      />
      <Select
        label="Sort By"
        size="sm"
        value={sortBy}
        onChange={(e, val) => setSortBy(val)}
        options={[
          { value: 'newest', label: 'Newest First' },
          { value: 'price-low', label: 'Price: Low to High' },
          { value: 'price-high', label: 'Price: High to Low' },
        ]}
      />
    </Stack>
  );
}
```

## Dependent Selects

```tsx
import { useState, useMemo } from 'react';
import { Select, Stack } from '@ceed/cds';

function LocationSelect() {
  const [country, setCountry] = useState<string | null>(null);
  const [city, setCity] = useState<string | null>(null);

  const cities = useMemo(() => {
    if (!country) return [];
    return getCitiesByCountry(country);
  }, [country]);

  return (
    <Stack spacing={2}>
      <Select
        label="Country"
        value={country}
        onChange={(e, val) => {
          setCountry(val);
          setCity(null);
        }}
        options={countries}
        placeholder="Select a country"
      />
      <Select
        label="City"
        value={city}
        onChange={(e, val) => setCity(val)}
        options={cities}
        disabled={!country}
        placeholder={country ? 'Select a city' : 'Select a country first'}
      />
    </Stack>
  );
}
```

## Best Practices

1. **Use clear, specific labels.** The label should describe exactly what the user is choosing.

```tsx
// ✅ Good
<Select label="Preferred contact method" options={contactMethods} />

// ❌ Bad
<Select label="Select" options={contactMethods} />
```

2. **Provide meaningful option text.** Each option label should be immediately understandable.

```tsx
// ✅ Good
{ value: 'express', label: 'Express Shipping (1-2 days)' }

// ❌ Bad
{ value: 'exp', label: 'EXP' }
```

3. **Do not use Select for actions.** Select is for data input. For action menus (Edit, Delete, etc.), use Dropdown with Menu.

```tsx
// ✅ Good: Select for data
<Select
  label="Country"
  options={countries}
/>

// ❌ Bad: Select for actions
<Select
  options={[
    { value: 'edit', label: 'Edit' },
    { value: 'delete', label: 'Delete' },
  ]}
/>
```

4. **Choose the right component for the option count.** For 2--4 visible choices, use RadioGroup. For 20+ options that need searching, use Autocomplete. Select works best with roughly 5--20 options.

5. **Use the built-in `label` and `helperText` props** instead of manually wrapping Select with FormControl, FormLabel, and FormHelperText. The component handles the composition and accessibility wiring internally.

```tsx
// ✅ Good
<Select label="Timezone" helperText="Used for report scheduling" options={timezones} />

// ❌ Bad
<FormControl>
  <FormLabel>Timezone</FormLabel>
  <Select options={timezones} />
  <FormHelperText>Used for report scheduling</FormHelperText>
</FormControl>
```

## Props and Customization

### Key Props

| Prop             | Type                                                                    | Default           | Description                                                    |
| ---------------- | ----------------------------------------------------------------------- | ----------------- | -------------------------------------------------------------- |
| `options`        | `OptionType[]`                                                          | `[]`              | Array of options (objects or primitives)                       |
| `value`          | `InferOptionValue<OptionType> \| InferOptionValue<OptionType>[]`        | -                 | Selected value(s) for controlled mode                          |
| `defaultValue`   | `InferOptionValue<OptionType> \| InferOptionValue<OptionType>[]`        | -                 | Initial value for uncontrolled mode                            |
| `onChange`       | `(event: { target: { name?, value } }, newValue) => void`               | -                 | Callback when selection changes                                |
| `multiple`       | `boolean`                                                               | `false`           | Allow multiple selections (value becomes an array)             |
| `label`          | `string`                                                                | -                 | Form label displayed above the select                          |
| `helperText`     | `string`                                                                | -                 | Helper text displayed below the select                         |
| `error`          | `boolean`                                                               | `false`           | Applies danger color to indicate validation error              |
| `required`       | `boolean`                                                               | `false`           | Marks the field as required (adds asterisk to label)           |
| `disabled`       | `boolean`                                                               | `false`           | Disables the select                                            |
| `placeholder`    | `string`                                                                | `'Choose one...'` | Placeholder text when no value is selected                     |
| `size`           | `'sm' \| 'md' \| 'lg'`                                                  | `'md'`            | Select size                                                    |
| `variant`        | `'outlined' \| 'plain' \| 'solid' \| 'soft'`                            | `'outlined'`      | Visual style variant                                           |
| `color`          | `'primary' \| 'neutral' \| 'danger' \| 'success' \| 'warning'`          | `'neutral'`       | Color scheme                                                   |
| `startDecorator` | `ReactNode`                                                             | -                 | Content rendered before the select trigger text                |
| `endDecorator`   | `ReactNode`                                                             | -                 | Content rendered after the select trigger text                 |
| `id`             | `string`                                                                | -                 | Seeds deterministic ids: button `id`, label `${id}-label`      |
| `slotProps`      | `{ formControl?, formLabel?, formHelperText?, button?, listbox?, ... }` | -                 | Props forwarded to composed wrapper slots and Joy Select slots |
| `sx`             | `SxProps`                                                               | -                 | Custom styles using the MUI system                             |

### Option Type

Options can be objects or primitives:

```tsx
type OptionType =
  | { label: string; value: string | number; disabled?: boolean; secondaryText?: string }
  | string
  | number;
```

### Generic Type Support

Select supports TypeScript generics for type-safe value handling:

```tsx
// Type-safe with object options
const options = [
  { value: 1, label: 'Option 1' },
  { value: 2, label: 'Option 2' },
] as const;

<Select<(typeof options)[number], false>
  options={options}
  onChange={(e, val) => {
    // val is typed as number
  }}
/>;
```

> **Note**: Select also accepts all Joy UI Select props.

## Accessibility

- **Label association**: When you use the `label` prop, the component automatically connects the label to the select element via `aria-labelledby` (the internal `FormControl` propagates a `labelId` to both the label and the button slot). You do not need to wire `useId` or a custom `FormLabel` externally. Always provide a label for screen reader users.
- **Deterministic ids for tests**: Pass `id` (or `slotProps.formControl.id`) to fix the generated ids, so `byLabelText` / `byRole('combobox', { name })` resolve to a stable accessible name.
- **Keyboard navigation**: The select can be opened with Enter or Space, navigated with Arrow Up/Down and Home/End, confirmed with Enter, and dismissed with Escape.
- **Error announcement**: When `error` is set, `aria-invalid` is applied. Pair it with a descriptive `helperText` so assistive technology can announce the error reason.
- **Required state**: The `required` prop adds `aria-required` and a visible asterisk to the label, communicating the requirement both visually and programmatically.
