# Date Picker

> A calendar popover that picks a civil date stored as YYYY-MM-DD.

```tsx title="hero.tsx"
import {
  DatePicker,
  DatePickerClear,
  DatePickerContent,
  DatePickerLabel,
  DatePickerTrigger,
} from '@langgenius/dify-ui/date-picker'

export function DatePickerHeroDemo() {
  return (
    <DatePicker defaultValue="2026-11-18">
      <div className="flex w-full max-w-60 flex-col gap-1">
        <DatePickerLabel>Logs since</DatePickerLabel>
        <div className="flex items-center gap-1">
          <DatePickerTrigger className="w-auto min-w-0 flex-1" />
          <div className="size-8 shrink-0">
            <DatePickerClear aria-label="Clear logs since" />
          </div>
        </div>
      </div>
      <DatePickerContent />
    </DatePicker>
  )
}
```

## Usage guidelines

- Use `DatePicker` for a civil date stored as `YYYY-MM-DD`, such as a report day or an expiry date. Use `TimePicker` for a wall time `HH:mm` and `DateTimePicker` for an instant (`Date`) shown in an IANA time zone. The pickers do not accept typed text.
- A date-only value has no time zone. Parse API payloads and convert business values outside the picker.
- **Name the field at the call site**: prefer one visible picker Label. It names both the trigger and the popup through `aria-labelledby`, and clicking its text focuses the trigger without opening it. A Label with `className="sr-only"` names a compact field without visible text. `FieldLabel nativeLabel={false} render={<div />}` also works. Do not point a native `label[for]` at the trigger: activating it clicks the button.
- Without a Label, name the trigger and the content with `aria-label` or `aria-labelledby`. The trigger's name appends its visible value (or placeholder) to label text; an explicit `aria-label` replaces the whole name, so include the visible value in it. Put meaningful annotations inside the Value part so they join the name.
- **Name Clear explicitly**: Clear follows the `IconButton` naming contract, so give it an `aria-label` such as "Clear start date". Place it next to the trigger, never inside the trigger button.
- Use `defaultValue`, or `value` with `onValueChange`, and keep that choice for the field's lifetime. `null` means empty, and Clear emits `null`. `details.reason` is `item-press`, `clear-press` or `reset`; `details.cancel()` rejects that change and its follow-up close. Unchanged values do not emit again.
- Selecting a day commits it and closes the popup. The month and year selector only changes the displayed month; it does not select a date. Days from adjacent months stay selectable.
- Restrict dates with `minDate`, `maxDate` (both `YYYY-MM-DD`) and `isDateUnavailable`. Unavailable days are skipped by the keyboard and cannot be selected.
- Content keeps its natural height and flips above or below the trigger; it does not shrink on small screens. Pass `maxHeight` only to opt into scrolling the body while the actions stay visible.
- `locale` takes a DayPicker locale object and changes formatting and digits, not the calendar system or the stored value. Translate action labels through `labels`, plus placeholders, `requiredLabel` and `validationMessage`. Direction comes from the nearest `DirectionProvider`; for a local RTL region, also set `dir` on the wrapper and on the content.
- With `name`, the committed value joins native `FormData`, and an empty field submits `''`. Inside a `Field`, `Field.name` takes precedence, `validate` receives the domain value, and `Form.onFormSubmit` receives the same strings as `FormData`. Required and invalid fields block submission and focus the first invalid trigger. Reset restores `defaultValue`. Disabled fields are left out; read-only fields open for browsing and still submit.

## Anatomy

```tsx
import {
  DatePicker,
  DatePickerClear,
  DatePickerContent,
  DatePickerLabel,
  DatePickerTrigger,
  DatePickerValue,
} from '@langgenius/dify-ui/date-picker'
```

```tsx
<DatePicker>
  <DatePickerLabel />
  <DatePickerTrigger>
    <DatePickerValue />
  </DatePickerTrigger>
  <DatePickerClear />
  <DatePickerContent />
</DatePicker>
```

`DatePickerTrigger` is a native button whose default children are the Value and a decorative icon. When you replace them, include exactly one `DatePickerValue`; its render callback receives the formatted text, not the raw value. `DatePickerContent` owns the portal, initial focus and calendar.

## Examples

### Available dates

`minDate` and `maxDate` bound the calendar, and `isDateUnavailable` rules out single days such as weekends.

```tsx title="constraints.tsx"
import {
  DatePicker,
  DatePickerContent,
  DatePickerLabel,
  DatePickerTrigger,
} from '@langgenius/dify-ui/date-picker'
import * as React from 'react'

function isWeekend(date: string) {
  const year = Number(date.slice(0, 4))
  const monthIndex = Number(date.slice(5, 7)) - 1
  const day = Number(date.slice(8, 10))
  const weekday = new Date(Date.UTC(year, monthIndex, day)).getUTCDay()
  return weekday === 0 || weekday === 6
}

export function DatePickerConstraintsDemo() {
  const hintId = React.useId()

  return (
    <DatePicker
      defaultValue="2026-12-07"
      minDate="2026-12-01"
      maxDate="2027-01-31"
      isDateUnavailable={isWeekend}
    >
      <div className="flex w-full max-w-60 flex-col gap-1">
        <DatePickerLabel>Maintenance date</DatePickerLabel>
        <DatePickerTrigger className="w-full" aria-describedby={hintId} />
        <p id={hintId} className="system-xs-regular text-text-tertiary">
          Weekdays only, Dec 2026–Jan 2027.
        </p>
      </div>
      <DatePickerContent />
    </DatePicker>
  )
}
```

### Controlled value

Control the value with `value` and `onValueChange` when another part of the page reads it. The callback's `details.reason` tells a day selection from Clear or a form reset.

```tsx title="controlled.tsx"
import type { DatePickerChangeEventReason } from '@langgenius/dify-ui/date-picker'
import {
  DatePicker,
  DatePickerClear,
  DatePickerContent,
  DatePickerLabel,
  DatePickerTrigger,
} from '@langgenius/dify-ui/date-picker'
import * as React from 'react'

export function DatePickerControlledDemo() {
  const [expiresOn, setExpiresOn] = React.useState<string | null>('2027-03-31')
  const [reason, setReason] = React.useState<DatePickerChangeEventReason | null>(null)

  return (
    <div className="flex w-full max-w-64 flex-col gap-2">
      <DatePicker
        value={expiresOn}
        onValueChange={(value, details) => {
          setExpiresOn(value)
          setReason(details.reason)
        }}
      >
        <div className="flex flex-col gap-1">
          <DatePickerLabel>API key expires on</DatePickerLabel>
          <div className="flex items-center gap-1">
            <DatePickerTrigger className="w-auto min-w-0 flex-1" />
            <div className="size-8 shrink-0">
              <DatePickerClear aria-label="Clear expiry date" />
            </div>
          </div>
        </div>
        <DatePickerContent />
      </DatePicker>
      <p aria-live="polite" className="system-xs-regular text-text-tertiary tabular-nums">
        Value: {expiresOn ?? 'null'}
        {reason && ` · Last change: ${reason}`}
      </p>
    </div>
  )
}
```

### Read-only and disabled

A read-only picker stays focusable and opens for browsing, but you cannot change its value. A disabled picker leaves the tab order and form submission.

```tsx title="read-only-disabled.tsx"
import {
  DatePicker,
  DatePickerContent,
  DatePickerLabel,
  DatePickerTrigger,
} from '@langgenius/dify-ui/date-picker'
import * as React from 'react'

export function DatePickerReadOnlyDisabledDemo() {
  const readOnlyHintId = React.useId()
  const disabledHintId = React.useId()

  return (
    <div className="grid w-full max-w-lg grid-cols-1 gap-4 sm:grid-cols-2">
      <DatePicker readOnly defaultValue="2026-06-01">
        <div className="flex flex-col gap-1">
          <DatePickerLabel>Plan started on</DatePickerLabel>
          <DatePickerTrigger className="w-full" aria-describedby={readOnlyHintId} />
          <p id={readOnlyHintId} className="system-xs-regular text-text-tertiary">
            Read-only — opens for browsing, cannot be changed.
          </p>
        </div>
        <DatePickerContent />
      </DatePicker>
      <DatePicker disabled defaultValue="2027-01-01">
        <div className="flex flex-col gap-1">
          <DatePickerLabel>Next invoice date</DatePickerLabel>
          <DatePickerTrigger className="w-full" aria-describedby={disabledHintId} />
          <p id={disabledHintId} className="system-xs-regular text-text-tertiary">
            Disabled — skipped by keyboard and form submission.
          </p>
        </div>
        <DatePickerContent />
      </DatePicker>
    </div>
  )
}
```

### Field and Form

Inside a `Field`, the picker registers with `Form`. `FieldError` shows the required message, and `onFormSubmit` receives the serialized date.

```tsx title="form.tsx"
import { Button } from '@langgenius/dify-ui/button'
import {
  DatePicker,
  DatePickerContent,
  DatePickerLabel,
  DatePickerTrigger,
} from '@langgenius/dify-ui/date-picker'
import { Field, FieldDescription, FieldError } from '@langgenius/dify-ui/field'
import { Form } from '@langgenius/dify-ui/form'
import * as React from 'react'

export function DatePickerFormDemo() {
  const [submitted, setSubmitted] = React.useState('')

  return (
    <Form
      aria-label="Export usage report"
      className="flex w-full max-w-72 flex-col gap-4"
      onFormSubmit={(values) => setSubmitted(JSON.stringify(values))}
      onReset={() => setSubmitted('')}
    >
      <Field name="reportDate">
        <DatePicker required>
          <DatePickerLabel>Usage report date</DatePickerLabel>
          <DatePickerTrigger className="w-full" />
          <DatePickerContent />
        </DatePicker>
        <FieldDescription>Submitted as YYYY-MM-DD, without a time zone.</FieldDescription>
        <FieldError match="valueMissing">Choose a report date.</FieldError>
      </Field>
      <div className="flex gap-2">
        <Button type="submit" variant="primary">
          Export
        </Button>
        <Button type="reset" variant="secondary">
          Reset
        </Button>
      </div>
      {submitted && (
        <p
          aria-live="polite"
          className="system-xs-regular break-all text-text-tertiary tabular-nums"
        >
          Submitted: {submitted}
        </p>
      )}
    </Form>
  )
}
```

## Keyboard

| Key                                      | Action                                                                                                       |
| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| `Enter`, `Space`                         | Opens the popup from the trigger and focuses the selected day, or today when empty.                          |
| `ArrowLeft`, `ArrowRight`                | Moves focus one day, skipping unavailable days and crossing into adjacent months. Reversed in right-to-left. |
| `ArrowUp`, `ArrowDown`                   | Moves focus one week.                                                                                        |
| `PageUp`, `PageDown`                     | Moves focus one month.                                                                                       |
| `Shift` + `PageUp`, `Shift` + `PageDown` | Moves focus one year.                                                                                        |
| `Home`, `End`                            | Moves focus to the start or end of the week.                                                                 |
| `Enter`, `Space`                         | Selects the focused day, closes the popup and returns focus to the trigger.                                  |
| `Tab`                                    | Moves between the month title, the month buttons and the grid, wrapping inside the popup.                    |
| `Escape`                                 | Closes the popup without a change and returns focus to the trigger.                                          |

In the month and year selector, `ArrowUp` and `ArrowDown` move one option, `PageUp` and `PageDown` move five, and `Home` and `End` reach the ends. Digits locate a year and letters locate a month. `Escape` discards the selection and returns focus to the month title.

## API reference

### DatePicker

Groups all parts of a calendar date picker storing a Gregorian `YYYY-MM-DD` value. Doesn't render its own HTML element.

Commits changes on day selection, clearing, or form reset; integrates with `Field` and native form validation.

**Props**

| Prop                 | Type                                                                       | Default      | Description                                                                                                                                                                                                               |
| -------------------- | -------------------------------------------------------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `placeholder?`       | `string`                                                                   | —            | The text shown in the trigger when no value is selected.                                                                                                                                                                  |
| `disabled?`          | `boolean`                                                                  | `false`      | Whether the component should ignore user interaction.                                                                                                                                                                     |
| `readOnly?`          | `boolean`                                                                  | `false`      | Whether the user should be unable to change the value.                                                                                                                                                                    |
| `required?`          | `boolean`                                                                  | `false`      | Whether the user must choose a value before submitting a form.                                                                                                                                                            |
| `requiredLabel?`     | `string`                                                                   | `'Required'` | Visually hidden text that announces the field as required.                                                                                                                                                                |
| `invalid?`           | `boolean`                                                                  | `false`      | Whether to mark the value as invalid regardless of native validation.                                                                                                                                                     |
| `name?`              | `string`                                                                   | —            | Identifies the field when a form is submitted.                                                                                                                                                                            |
| `form?`              | `string`                                                                   | —            | Identifies the form that owns the hidden input. Useful when the picker is rendered outside the form.                                                                                                                      |
| `validationMessage?` | `string`                                                                   | —            | The error message reported when `invalid` is set or a required value is missing. Falls back to `'Choose a valid value.'` and `'Choose a value.'` respectively; an unavailable value reports `labels.unavailable` instead. |
| `onOpenChange?`      | `((open: boolean, details: PickerOpenChangeDetails) => void)`              | —            | Event handler called when the popup is opened or closed.                                                                                                                                                                  |
| `children`           | `React.ReactNode`                                                          | —            | The picker parts.                                                                                                                                                                                                         |
| `locale?`            | `Partial<DayPickerLocale>`                                                 | —            | The `@daypicker/react` locale used for month names, weekdays, and the first day of the week. Defaults to US English.                                                                                                      |
| `minDate?`           | `string`                                                                   | —            | The earliest selectable date, as `YYYY-MM-DD`.                                                                                                                                                                            |
| `maxDate?`           | `string`                                                                   | —            | The latest selectable date, as `YYYY-MM-DD`.                                                                                                                                                                              |
| `isDateUnavailable?` | `((date: string) => boolean)`                                              | —            | Returns `true` for a `YYYY-MM-DD` date that cannot be selected.                                                                                                                                                           |
| `value?`             | `string \| null`                                                           | —            | The controlled value, a Gregorian `YYYY-MM-DD` civil date; `null` represents an empty field. To render an uncontrolled date picker, use the `defaultValue` prop instead.                                                  |
| `defaultValue?`      | `string \| null`                                                           | `null`       | The uncontrolled value when the picker is initially rendered. To render a controlled date picker, use the `value` prop instead.                                                                                           |
| `onValueChange?`     | `((value: string \| null, details: DatePickerChangeEventDetails) => void)` | —            | Called on day confirmation, clearing or form reset.                                                                                                                                                                       |
| `labels?`            | `Partial<DatePickerLabels>`                                                | —            | Text for the built-in controls and messages, usually translated strings. Missing entries fall back to English.                                                                                                            |

Inherits `defaultOpen`, `open` from [Base UI Popover.Root](https://base-ui.com/react/components/popover#root).

### DatePickerClear

A button component that can be used to trigger actions. Renders a `<button>` element.

**Props**

| Prop               | Type                                                                                                     | Default     | Description                                                                                          |
| ------------------ | -------------------------------------------------------------------------------------------------------- | ----------- | ---------------------------------------------------------------------------------------------------- |
| `aria-label?`      | `string`                                                                                                 | —           | Names the element for assistive technology. Pass either this or `aria-labelledby`.                   |
| `aria-labelledby?` | `string`                                                                                                 | —           | Identifies the element that names this one. Pass either this or `aria-label`.                        |
| `variant?`         | `'default' \| 'ghost' \| 'ghost-accent' \| 'primary' \| 'secondary' \| 'secondary-accent' \| 'tertiary'` | `'default'` | The visual emphasis of the button. The accent variants cannot be combined with `tone="destructive"`. |
| `tone?`            | `'default' \| 'destructive'`                                                                             | `'default'` | Whether the button represents a destructive action.                                                  |
| `ref?`             | `React.Ref<HTMLButtonElement>`                                                                           | —           | —                                                                                                    |

Valid prop combinations:

- `aria-label: string`, `aria-labelledby?: undefined`, `variant?: 'default' | 'ghost' | 'primary' | 'secondary' | 'tertiary'`, `tone?: 'default' | 'destructive'`
- `aria-label: string`, `aria-labelledby?: undefined`, `variant: 'ghost-accent' | 'secondary-accent'`, `tone?: 'default'`
- `aria-label?: undefined`, `aria-labelledby: string`, `variant?: 'default' | 'ghost' | 'primary' | 'secondary' | 'tertiary'`, `tone?: 'default' | 'destructive'`
- `aria-label?: undefined`, `aria-labelledby: string`, `variant: 'ghost-accent' | 'secondary-accent'`, `tone?: 'default'`

Inherits `className`, `style`, `focusableWhenDisabled` from [Base UI Button](https://base-ui.com/react/components/button).

**Data attributes**

| Attribute       | Description                          |
| --------------- | ------------------------------------ |
| `data-disabled` | Present when the button is disabled. |

### DatePickerContent

A container for the popover contents. Renders a `<div>` element.

**Props**

| Prop          | Type                           | Default   | Description                                                                                             |
| ------------- | ------------------------------ | --------- | ------------------------------------------------------------------------------------------------------- |
| `sideOffset?` | `number \| OffsetFunction`     | `8`       | Distance between the anchor and the popup in pixels. Also accepts a function that returns the distance. |
| `align?`      | `'center' \| 'end' \| 'start'` | `'start'` | How to align the popup relative to the specified side.                                                  |

Inherits `className`, `style`, `side`, `alignOffset`, `finalFocus` from [Base UI Popover.Popup](https://base-ui.com/react/components/popover#popup).

**Data attributes**

| Attribute             | Description                                                           |
| --------------------- | --------------------------------------------------------------------- |
| `data-open`           | Present when the popup is open.                                       |
| `data-closed`         | Present when the popup is closed.                                     |
| `data-starting-style` | Present when the popup begins animating in.                           |
| `data-ending-style`   | Present when the popup is animating out.                              |
| `data-side`           | Indicates which side the popup is positioned relative to the trigger. |
| `data-align`          | Indicates how the popup is aligned relative to specified side.        |
| `data-instant`        | Present if animations should be instant.                              |

**CSS variables**

| Variable         | Type | Description              |
| ---------------- | ---- | ------------------------ |
| `--popup-width`  | —    | The width of the popup.  |
| `--popup-height` | —    | The height of the popup. |

### DatePickerLabel

Inherits `className`, `style` from [Base UI null](https://base-ui.com/react/handbook/composition).

**Data attributes**

| Attribute       | Description                                                      |
| --------------- | ---------------------------------------------------------------- |
| `data-disabled` | Present when the component should ignore user interaction.       |
| `data-touched`  | Present when the field has been touched.                         |
| `data-dirty`    | Present when the field value has changed from its initial value. |
| `data-filled`   | Present when the field has a value.                              |
| `data-focused`  | Present when the field is focused.                               |

### DatePickerTrigger

A button that opens the popover. Renders a `<button>` element.

**Props**

| Prop   | Type                           | Default | Description |
| ------ | ------------------------------ | ------- | ----------- |
| `ref?` | `React.Ref<HTMLButtonElement>` | —       | —           |

Inherits `id`, `className`, `style` from [Base UI Popover.Trigger](https://base-ui.com/react/components/popover#trigger).

**Data attributes**

| Attribute         | Description                                     |
| ----------------- | ----------------------------------------------- |
| `data-readonly`   | Present when the picker is read-only.           |
| `data-required`   | Present when the picker requires a value.       |
| `data-popup-open` | Present when the corresponding popover is open. |
| `data-pressed`    | Present when the trigger is pressed.            |
| `data-disabled`   | Present when the trigger is disabled.           |

### DatePickerValue

**Props**

| Prop        | Type                                                             | Default | Description                                                            |
| ----------- | ---------------------------------------------------------------- | ------- | ---------------------------------------------------------------------- |
| `children?` | `((displayValue: string) => React.ReactNode) \| React.ReactNode` | —       | Receives the formatted committed value, or the placeholder when empty. |
