# DatePicker

DatePicker is a form input component that allows users to select a single date from a calendar popup or by typing directly into the input field. It provides flexible date formatting options, date range restrictions, and supports both controlled and uncontrolled modes.

DatePicker is essential for any form that requires date input -- booking systems, scheduling interfaces, data filtering, and record keeping. It handles the complexity of date parsing, formatting, and validation so consumers can focus on business logic.

```tsx
<DatePicker onChange={fn()} />
```

| Field           | Description | Default |
| --------------- | ----------- | ------- |
| size            | —           | —       |
| name            | —           | —       |
| required        | —           | —       |
| format          | —           | —       |
| displayFormat   | —           | —       |
| label           | —           | —       |
| helperText      | —           | —       |
| error           | —           | —       |
| inputReadOnly   | —           | —       |
| readOnly        | —           | —       |
| hideClearButton | —           | —       |
| value           | —           | —       |
| defaultValue    | —           | —       |
| minDate         | —           | —       |
| maxDate         | —           | —       |
| disableFuture   | —           | —       |
| disablePast     | —           | —       |

## Usage

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

function DateForm() {
  const [date, setDate] = useState('');

  return <DatePicker label="Select Date" value={date} onChange={(e) => setDate(e.target.value)} />;
}
```

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

## Sizes

DatePicker supports three sizes (`sm`, `md`, `lg`) to fit different layout densities.

```tsx
<Stack gap={2}>
    <DatePicker {...args} size="sm" />
    <DatePicker {...args} size="md" />
    <DatePicker {...args} size="lg" />
  </Stack>
```

## Label and Helper Text

Use the `label` prop to provide a visible label, and `helperText` to give users additional guidance about expected input.

```tsx
<DatePicker
  onChange={fn()}
  label="Date"
/>
```

```tsx
<DatePicker
  onChange={fn()}
  label="Date"
  helperText="Please select a date"
/>
```

## Validation and Error State

Set `error` to `true` and combine with `helperText` to communicate validation failures. Use the `required` prop to indicate mandatory fields.

```tsx
<DatePicker
  onChange={fn()}
  label="Date"
  helperText="Please select a date"
  error
/>
```

```tsx
<DatePicker
  onChange={fn()}
  label="Label"
  helperText="I'm helper text"
  required
/>
```

## Disabled and Read-Only States

The `disabled` prop prevents all interaction. The `readOnly` prop displays the value but blocks changes, while `inputReadOnly` disables keyboard typing but still allows calendar selection -- useful for mobile scenarios. When `inputReadOnly` is set, clicking the input opens the calendar (not just the calendar button).

```tsx
<DatePicker
  onChange={fn()}
  disabled
/>
```

```tsx
<DatePicker
  onChange={fn()}
  value="2024/04/01"
  readOnly
/>
```

```tsx
<DatePicker
  onChange={fn()}
  value="2024/04/01"
  inputReadOnly
/>
```

## Date Restrictions

Restrict selectable dates using `minDate`, `maxDate`, `disablePast`, `disableFuture`, or the flexible `shouldDisableDate` callback for custom logic such as disabling weekends or holidays.

```tsx
<DatePicker
  onChange={fn()}
  minDate="2024-04-10"
/>
```

```tsx
<DatePicker
  onChange={fn()}
  maxDate="2024-04-10"
/>
```

```tsx
<DatePicker
  onChange={fn()}
  disableFuture
/>
```

```tsx
<DatePicker
  onChange={fn()}
  disablePast
/>
```

```tsx
<DatePicker
  onChange={fn()}
  disablePast
  shouldDisableDate={date => [0, 6].includes(new Date(date).getDay()) || new Date(date).getTime() >= new Date().getTime() + 7 * 24 * 60 * 60 * 1000}
/>
```

## Controlled vs Uncontrolled

DatePicker works in both controlled mode (you manage `value` via state) and uncontrolled mode (component manages its own state via `defaultValue`).

```tsx
<Stack gap={2}>
    <DatePicker {...args} value={value} onChange={(e) => setValue(e.target.value)} />
    <Button
      onClick={() => {
        const currentValue = new Date(value);
        currentValue.setDate(currentValue.getDate() + 1);
        const year = currentValue.getFullYear();
        const month = String(currentValue.getMonth() + 1).padStart(2, "0");
        const day = String(currentValue.getDate()).padStart(2, "0");
        setValue(`${year}/${month}/${day}`);
      }}
    >
      Next Day
    </Button>
  </Stack>
```

```tsx
<DatePicker
  onChange={fn()}
  label="Uncontrolled DatePicker"
  helperText="Please select a date"
  defaultValue="2024/04/01"
/>
```

## Format and Display Format

The `format` prop determines the shape of the value emitted through `onChange`, while `displayFormat` controls what users see in the input field. This separation lets you keep a consistent API format (e.g. `YYYY-MM-DD`) while displaying a locale-appropriate format (e.g. `MM/DD/YYYY`).

```tsx
<Stack gap={2}>
    <DatePicker
      {...args}
      value={value["YYYY.MM.DD"]}
      label="YYYY.MM.DD"
      name="YYYY.MM.DD"
      format="YYYY.MM.DD"
      onChange={handleChange}
    />
    <DatePicker
      {...args}
      value={value["YYYY/MM/DD"]}
      label="YYYY/MM/DD"
      name="YYYY/MM/DD"
      format="YYYY/MM/DD"
      onChange={handleChange}
    />
    <DatePicker
      {...args}
      value={value["MM/DD/YYYY"]}
      label="MM/DD/YYYY"
      name="MM/DD/YYYY"
      format="MM/DD/YYYY"
      onChange={handleChange}
    />
    <DatePicker
      {...args}
      value={value["YYYY-MM-DD"]}
      label="YYYY-MM-DD"
      name="YYYY-MM-DD"
      format="YYYY-MM-DD"
      onChange={handleChange}
    />
    <DatePicker
      {...args}
      value={value["DD/MM/YYYY"]}
      label="DD/MM/YYYY"
      name="DD/MM/YYYY"
      format="DD/MM/YYYY"
      onChange={handleChange}
    />
    <DatePicker
      {...args}
      value={value["DD.MM.YYYY"]}
      label="DD.MM.YYYY"
      name="DD.MM.YYYY"
      format="DD.MM.YYYY"
      onChange={handleChange}
    />
  </Stack>
```

```tsx
<Stack gap={2}>
    <DatePicker
      {...args}
      value={value1}
      label="YYYY.MM.DD"
      name="YYYY.MM.DD"
      displayFormat="YYYY.MM.DD"
      onChange={(e) => {
        setValue1(e.target.value);
        args.onChange?.(e);
      }}
    />
    <DatePicker
      {...args}
      value={value2}
      label="YYYY/MM/DD"
      name="YYYY/MM/DD"
      displayFormat="YYYY/MM/DD"
      onChange={(e) => {
        setValue2(e.target.value);
        args.onChange?.(e);
      }}
    />
    <DatePicker
      {...args}
      value={value3}
      label="MM/DD/YYYY"
      name="MM/DD/YYYY"
      displayFormat="MM/DD/YYYY"
      onChange={(e) => {
        setValue3(e.target.value);
        args.onChange?.(e);
      }}
    />
    <DatePicker
      {...args}
      value={value4}
      label="YYYY-MM-DD"
      name="YYYY-MM-DD"
      displayFormat="YYYY-MM-DD"
      onChange={(e) => {
        setValue4(e.target.value);
        args.onChange?.(e);
      }}
    />
    <DatePicker
      {...args}
      value={value5}
      label="DD/MM/YYYY"
      name="DD/MM/YYYY"
      displayFormat="DD/MM/YYYY"
      onChange={(e) => {
        setValue5(e.target.value);
        args.onChange?.(e);
      }}
    />
    <DatePicker
      {...args}
      value={value6}
      label="DD.MM.YYYY"
      name="DD.MM.YYYY"
      displayFormat="DD.MM.YYYY"
      onChange={(e) => {
        setValue6(e.target.value);
        args.onChange?.(e);
      }}
    />
  </Stack>
```

**Supported format tokens:**

| Token  | Description   | Example |
| ------ | ------------- | ------- |
| `YYYY` | 4-digit year  | 2024    |
| `MM`   | 2-digit month | 04      |
| `DD`   | 2-digit day   | 15      |

Common patterns: `YYYY/MM/DD` (default), `YYYY-MM-DD` (ISO 8601), `MM/DD/YYYY` (US), `DD/MM/YYYY` (EU), `DD.MM.YYYY` (German), `YYYY.MM.DD` (East Asian).

## Additional Features

### Presets

Use the `presets` prop to display a list of quick-select options alongside the calendar. This is useful when users frequently select common dates like "Today" or a specific day offset. The preset panel appears to the right of the calendar inside the popup.

Each preset's `value` must match the component's `format` prop. When the current value matches a preset, that preset is automatically highlighted -- regardless of whether the value was set via the preset button or by selecting the same date on the calendar.

```tsx
<DatePicker
    {...args}
    value={value}
    onChange={(e) => {
      setValue(e.target.value);
      args.onChange?.(e);
    }}
    presets={[
      {
        label: "Today",
        value: fmt(today)
      },
      {
        label: "Yesterday",
        value: daysAgo(1)
      },
      {
        label: "3 days ago",
        value: daysAgo(3)
      },
      {
        label: "1 week ago",
        value: daysAgo(7)
      }
    ]}
  />
```

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

function QuickDateSelect() {
  const [date, setDate] = useState('');
  const today = new Date();
  const fmt = (d: Date) =>
    `${d.getFullYear()}/${String(d.getMonth() + 1).padStart(2, '0')}/${String(d.getDate()).padStart(2, '0')}`;

  return (
    <DatePicker
      label="Select Date"
      value={date}
      onChange={(e) => setDate(e.target.value)}
      presets={[
        { label: 'Today', value: fmt(today) },
        { label: 'Yesterday', value: fmt(new Date(today.getTime() - 86400000)) },
      ]}
    />
  );
}
```

### Reset Button

Pair DatePicker with an external reset button to programmatically clear the value.

```tsx
<div
    style={{
      display: "flex",
      gap: "10px"
    }}
  >
    <DatePicker
      {...props}
      value={value}
      onChange={(event) => {
        onChange?.(event);
        setValue(event.target.value);
      }}
    />
    <Button onClick={() => setValue("")}>Reset</Button>
  </div>
```

### Hide Clear Button

Remove the built-in clear button from the calendar popup when clearing is not desired.

```tsx
<DatePicker
  onChange={fn()}
  value="2024/04/01"
  hideClearButton
/>
```

### Synchronized Date Pickers

Multiple DatePicker instances can share the same value for dependent field scenarios.

```tsx
<Stack gap={2}>
    <DatePicker
      label="Select Date"
      value={value}
      inputReadOnly
      onChange={(e) => {
        setValue(e.target.value);
        setValue2(e.target.value);
      }}
    />
    <DatePicker label="Synchronized" value={value2} disabled />
  </Stack>
```

## Form with Validation

```tsx
function BookingForm() {
  const [checkIn, setCheckIn] = useState('');
  const [error, setError] = useState('');

  const handleSubmit = () => {
    if (!checkIn) {
      setError('Please select a check-in date');
      return;
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <DatePicker
        label="Check-in Date"
        value={checkIn}
        onChange={(e) => {
          setCheckIn(e.target.value);
          setError('');
        }}
        error={!!error}
        helperText={error || 'Select your arrival date'}
        disablePast
        required
      />
    </form>
  );
}
```

## Custom Date Disabling (Weekdays Only)

```tsx
function AppointmentPicker() {
  const [date, setDate] = useState('');

  const shouldDisableDate = useCallback((dateString: string) => {
    const day = new Date(dateString).getDay();
    return day === 0 || day === 6; // Disable weekends
  }, []);

  return (
    <DatePicker
      label="Appointment Date"
      value={date}
      onChange={(e) => setDate(e.target.value)}
      shouldDisableDate={shouldDisableDate}
      disablePast
      helperText="Weekdays only"
    />
  );
}
```

## Locale-Aware Display

```tsx
function RegionalDateField({ locale }: { locale: string }) {
  const [date, setDate] = useState('');

  const displayFormat = locale === 'en-US' ? 'MM/DD/YYYY' : locale === 'en-GB' ? 'DD/MM/YYYY' : 'YYYY-MM-DD';

  return (
    <DatePicker
      label="Date"
      value={date}
      onChange={(e) => setDate(e.target.value)}
      format="YYYY/MM/DD"
      displayFormat={displayFormat}
    />
  );
}
```

## Best Practices

1. **Always provide a label**

```tsx
{
  /* Do */
}
<DatePicker label="Birth Date" />;

{
  /* Don't */
}
<DatePicker placeholder="Birth Date" />;
```

2. **Keep value format consistent with the `format` prop**

```tsx
{
  /* Do */
}
<DatePicker format="YYYY/MM/DD" value="2024/04/15" />;

{
  /* Don't -- mismatched format causes unexpected behavior */
}
<DatePicker format="YYYY/MM/DD" value="04/15/2024" />;
```

3. **Use `displayFormat` to separate API format from UI format**

```tsx
{
  /* Do -- consistent API format, locale-appropriate display */
}
<DatePicker format="YYYY-MM-DD" displayFormat="MM/DD/YYYY" />;

{
  /* Don't -- changing format just for display affects onChange values */
}
<DatePicker format="MM/DD/YYYY" />;
```

4. **Set appropriate date boundaries for your use case**

```tsx
{
  /* Do */
}
<DatePicker label="Birth Date" disableFuture minDate="1900/01/01" />;

{
  /* Don't -- unrestricted date range for a birth date field */
}
<DatePicker label="Birth Date" />;
```

5. **Show validation feedback with error and helperText**

```tsx
{
  /* Do */
}
<DatePicker error={!isValid} helperText={errorMessage} />;

{
  /* Don't -- silently ignore invalid state */
}
<DatePicker value={invalidDate} />;
```

## Props and Customization

### Key Props

| Prop                | Type                                                    | Default        | Description                                                                                                                                             |
| ------------------- | ------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `value`             | `string \| null`                                        | -              | Selected date string in `format` (controlled mode)                                                                                                      |
| `defaultValue`      | `string`                                                | -              | Initial date string (uncontrolled mode)                                                                                                                 |
| `onChange`          | `(event: { target: { name?, value: string } }) => void` | -              | Callback when the date changes. Value is in `format`                                                                                                    |
| `format`            | `string`                                                | `'YYYY/MM/DD'` | Format of the `value` and `onChange` value. Determines the internal data format                                                                         |
| `displayFormat`     | `string`                                                | `'YYYY/MM/DD'` | Format displayed in the input field. Can differ from `format` for locale display. Supports `MMM` (short month name) and `MMMM` (full month name) tokens |
| `locale`            | `string`                                                | `'default'`    | Locale for month names when using `MMM`/`MMMM` tokens in `displayFormat` (BCP 47 format, e.g., `'en-US'`, `'ko-KR'`)                                    |
| `label`             | `ReactNode`                                             | -              | Form label displayed above the input                                                                                                                    |
| `helperText`        | `ReactNode`                                             | -              | Helper text displayed below the input                                                                                                                   |
| `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 entire component                                                                                                                           |
| `name`              | `string`                                                | -              | HTML name attribute for form submission                                                                                                                 |
| `minDate`           | `string`                                                | -              | Minimum selectable date (in `format`)                                                                                                                   |
| `maxDate`           | `string`                                                | -              | Maximum selectable date (in `format`)                                                                                                                   |
| `disableFuture`     | `boolean`                                               | `false`        | Disables all future dates                                                                                                                               |
| `disablePast`       | `boolean`                                               | `false`        | Disables all past dates                                                                                                                                 |
| `shouldDisableDate` | `(date: string) => boolean`                             | -              | Custom function to disable specific dates. Receives date in `format`. Return `true` to disable                                                          |
| `inputReadOnly`     | `boolean`                                               | `false`        | Prevents keyboard typing in the input; users select via the calendar, which opens on clicking either the input or the calendar button                   |
| `hideClearButton`   | `boolean`                                               | `false`        | Hides the clear button in the calendar popup                                                                                                            |

> **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.

### format vs displayFormat

| Prop            | Controls                                               | Example                                           |
| --------------- | ------------------------------------------------------ | ------------------------------------------------- |
| `format`        | Value in `onChange`, `value`, and `defaultValue` props | `'YYYY-MM-DD'` → onChange receives `'2024-05-03'` |
| `displayFormat` | What the user sees in the input field                  | `'MM/DD/YYYY'` → input shows `05/03/2024`         |

When both are set, the component converts between formats internally. This lets you keep a consistent API format while showing locale-appropriate display.

### Alphabetic Month Tokens (MMM / MMMM)

The `displayFormat` prop supports alphabetic month tokens for more human-readable date display:

| Token  | Output                 | Example                        |
| ------ | ---------------------- | ------------------------------ |
| `MMM`  | Abbreviated month name | `Jan`, `Feb`, `Apr`            |
| `MMMM` | Full month name        | `January`, `February`, `April` |

When `displayFormat` contains `MMM` or `MMMM`, the input becomes **read-only** and the user must select a date through the calendar popup. Use the `locale` prop to control the language of month names (e.g., `locale="ko-KR"` for Korean month names).

```tsx
<DatePicker displayFormat="MMM DD, YYYY" locale="en-US" />
// → "Apr 09, 2026"

<DatePicker displayFormat="MMMM DD, YYYY" locale="ko-KR" />
// → "4월 09, 2026"
```

> **Note**: DatePicker also accepts all Input props (e.g., `size`, `variant`, `color`, `startDecorator`, `placeholder`, `sx`). `sx` and `className` are applied to the root element, so layout styles like `width` work as expected when DatePicker is a direct flex child.

## Accessibility

- **Keyboard navigation**: Tab moves focus between the input and the calendar toggle button. Arrow keys navigate dates within the open calendar. Enter selects the focused date, and Escape closes the calendar popup.
- **ARIA attributes**: The calendar toggle button has `aria-label="Toggle Calendar"`. The calendar popup uses `role="tooltip"` with descriptive labeling. Each date button announces the full date to screen readers.
- **Focus management**: Focus moves into the calendar when opened and returns to the input when the calendar closes. All interactive elements have clear focus indicators.
- **Use `inputReadOnly` on mobile**: When targeting touch devices, set `inputReadOnly` to prevent the virtual keyboard from appearing and guide users toward the calendar picker instead.
