# Picker behavior and forms

> What DatePicker, DateRangePicker and TimePicker share: open state, popup modes, ref methods, focus events, disabled and read-only, clear button, placeholder, form values, validation and reset.

Canonical: https://salmonui.dev/docs/calendars/picker-behavior

These props and behaviors are the same on `DatePicker`, `DateRangePicker`
and `TimePicker`.

## Open state and popup

- `open` / `defaultOpen` / `onOpenChange(open, { source, reason })`.
  `reason` is `'trigger'`, `'keyboard'`, `'focus'`, `'field'`, `'escape'`,
  `'outside'`, `'tab'`, `'select'`, `'apply'`, `'cancel'` or `'api'`. To veto
  an open or close, control
  `open` and do not update it. `defaultOpen` takes effect after
  hydration: the server never renders a popup.
- `openOnFocus` opens when focus enters the field.
- `ref` receives `{ element, focus(), blur(), open(), close() }`.
- `onFocus` / `onBlur` fire once when focus enters or leaves the whole field
  group, popup included.
- `popupMode: 'popover' | 'modal' | 'auto'`:
  `'popover'` is a top-layer popup anchored to the field; `'modal'` a
  `<dialog>` bottom sheet with a Close button; `'auto'` (default) decides
  when opening, in the event handler, with
  `matchMedia('(pointer: coarse) and (max-width: 640px)')`.
- Keys: Alt+Down opens, Alt+Up and Escape close and return focus
  to the field; in popover mode Tab leaves the popup and closes it, in modal
  mode Tab stays inside.

## Field

- `disabled`: no tab stops, no popup.
`readOnly`: focusable, no edits, no popup.
- `placeholder` is a watermark shown while the field is empty and not
  focused.
- `clearable` renders a clear button; clearing fires `onValueChange(null)`
  with `reason: 'clear'` and `onClear`.
- `editable={false}` makes the segments
  read-only; a click on the field opens the popup.
- `label`, `description` and `errorMessage` are wired to the field group
  (`aria-labelledby`, `aria-describedby`). There is no floating label.
- `className` and `style` go on the root; other DOM props (`data-*`,
  `aria-*`, `title`, DOM event handlers) go on the field group.
  There is no `width` prop: size the root with `style` or a class.
- `size` (`'sm' | 'md' | 'lg'`, default `'md'`) sets the control to 24,
  32 or 40 px tall with the Button metrics; see
  [Theme and sizing](https://salmonui.dev/docs/calendars/platform#theme-and-sizing).
- Direction is inherited (`dir` on an ancestor) or set with `dir`: the popup
  aligns to the inline end and arrow keys mirror in RTL.

### Live demo: Field states, popup control and events

Live demo: https://salmonui.dev/demos/calendars/calendar-picker-behavior

Disabled, read-only, placeholder, pick-only and open-on-focus pickers; a controlled popup that can veto opening; ref open, close, focus and blur; focus, view and value events; placeholderValue seeds; RTL.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { DatePicker, type CalendarView, type PickerHandle } from '@salmonui/calendars/date-picker';
import { TimePicker } from '@salmonui/calendars/time-picker';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';

/** Disabled, read-only, placeholder, pick-only and open-on-focus fields; a controlled popup with a veto; ref methods; focus, view and change events; RTL. */
export default function CalendarPickerBehaviorDemo() {
  const pickerRef = useRef<PickerHandle>(null);
  const [open, setOpen] = useState(false);
  const [locked, setLocked] = useState(false);
  const [rtl, setRtl] = useState(false);
  const [view, setView] = useState<CalendarView>('month');
  const [log, setLog] = useState<string[]>([]);
  const add = (line: string) => setLog((lines) => [line, ...lines].slice(0, 8));
  return (
    <div style={{ display: 'grid', gap: 16 }}>
      <div className="demo-toolbar">
        <Button variant="outline" type="button" onClick={() => pickerRef.current?.open()}>
          ref.open()
        </Button>
        <Button variant="outline" type="button" onClick={() => pickerRef.current?.close()}>
          ref.close()
        </Button>
        <Button variant="outline" type="button" onClick={() => pickerRef.current?.focus()}>
          ref.focus()
        </Button>
        <Button variant="outline" type="button" onClick={() => pickerRef.current?.blur()}>
          ref.blur()
        </Button>
        <Checkbox checked={locked} onCheckedChange={(checked) => setLocked(checked)}>
          Keep the popup closed (veto)
        </Checkbox>
        <Checkbox checked={rtl} onCheckedChange={(checked) => setRtl(checked)}>
          Right to left
        </Checkbox>
      </div>
      <div dir={rtl ? 'rtl' : 'ltr'} style={{ display: 'flex', flexWrap: 'wrap', gap: 24, alignItems: 'flex-start' }}>
        <DatePicker
          ref={pickerRef}
          label="Due date (controlled popup)"
          description={`Calendar view: ${view}`}
          defaultValue="2026-11-23"
          clearable
          open={open}
          onOpenChange={(next, details) => {
            add(`onOpenChange(${String(next)}, reason ${details.reason}, source ${details.source})${locked && next ? ': vetoed' : ''}`);
            if (!(locked && next)) setOpen(next);
          }}
          onViewChange={(v) => {
            setView(v);
            add(`onViewChange(${v})`);
          }}
          onFocusedValueChange={(d) => add(`onFocusedValueChange(${String(d)})`)}
          onFocus={() => add('onFocus')}
          onBlur={() => add('onBlur')}
          onValueChange={(value, details) => add(`onValueChange(${String(value)}, source ${details.source}, reason ${details.reason}, iso ${details.iso || "''"})`)}
          className="demo-due-date"
          style={{ inlineSize: 260 }}
          data-testid="due-date"
          title="Due date"
        />
        <DatePicker label="Pick from the calendar only" editable={false} placeholder="Choose a date" onValueChange={(value) => add(`pick only: ${String(value)}`)} />
        <DatePicker label="Opens on focus" openOnFocus placeholder="Tab into me" defaultFocusedValue="2027-01-15" />
        <DatePicker label="Read-only" readOnly defaultValue="2026-12-24" />
        <DatePicker label="Disabled" disabled defaultValue="2026-12-31" />
        <DatePicker label="Meeting (no value yet)" granularity="minute" placeholderValue="2026-11-23T13:00" timeStep={15} description="The time list starts at 13:00." />
        <TimePicker label="Reminder" placeholderValue="18:00" step={15} style={{ inlineSize: 140 }} description="A narrow field; the list is at least as wide." />
      </div>
      <div className="demo-log" aria-live="polite">
        <ol>
          {log.length ? log.map((line, i) => <li key={`${i}-${line}`}>{line}</li>) : <li>Interact with a field</li>}
        </ol>
      </div>
    </div>
  );
}
```

## Values and events

`onValueChange(value, details)` fires for user changes only, never for a
new `value` prop, so a controlled picker works with any
form library: pass `value`, update it in `onValueChange`, use `onBlur` and
`ref.focus()`. `details.iso` is the form value; zoned date-times also carry
`details.epochMilliseconds`. Instants are read in `timeZone` (an IANA name;
a fixed minute offset could not follow DST).

## Forms

- `name` posts an ISO string, not the displayed text: `YYYY-MM-DD`,
  `YYYY-MM`, `YYYY`, `YYYY-MM-DDTHH:mm[:ss]` (plus the offset when `timeZone`
  is given), `HH:mm[:ss]`. The server parses one format whatever
  the user's locale.
- The form value is a visually hidden `<input>` (not `type="hidden"`), so
  `required` and the custom validity (out of range, unavailable date or time)
  take part in constraint validation; an `invalid` event focuses the first
  segment.
- `invalid`, `errorMessage` and `onInvalid` integrate with your own
  validation.
- A form `reset` restores `defaultValue`.

### Live demo: Controlled form validation

Live demo: https://salmonui.dev/demos/calendars/calendar-picker-validation

Check-in and check-out pickers bound to external form state with a cross-field rule, invalid and errorMessage, onBlur touch tracking, onInvalid from native constraint validation and ref.focus() on the first error.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState, type FormEvent } from 'react';
import { DatePicker, type PickerHandle, type PlainDate } from '@salmonui/calendars/date-picker';
import { TimePicker, type PlainTime } from '@salmonui/calendars/time-picker';
import { Button } from '@salmonui/buttons/button';

type Booking = { checkIn: PlainDate | null; checkOut: PlainDate | null; arrival: PlainTime | null };

const initial: Booking = { checkIn: null, checkOut: null, arrival: null };

/** Pickers bound to external form state: controlled values, custom validation with invalid / errorMessage, onInvalid and ref.focus(). */
export default function CalendarPickerValidationDemo() {
  const checkInRef = useRef<PickerHandle>(null);
  const checkOutRef = useRef<PickerHandle>(null);
  const [form, setForm] = useState<Booking>(initial);
  const [submitted, setSubmitted] = useState(false);
  const [changes, setChanges] = useState(0);
  const [touched, setTouched] = useState<Record<string, boolean>>({});
  const [status, setStatus] = useState('');
  const set = <K extends keyof Booking>(key: K, value: Booking[K]) => {
    setChanges((n) => n + 1);
    setForm((f) => ({ ...f, [key]: value }));
  };
  const errors = {
    checkIn: form.checkIn ? '' : 'Choose a check-in date.',
    checkOut: !form.checkOut ? 'Choose a check-out date.' : form.checkIn && form.checkOut.toString() <= form.checkIn.toString() ? 'Check-out must be after check-in.' : '',
  };
  const show = (key: keyof typeof errors) => (submitted || touched[key]) && errors[key] !== '';
  const onSubmit = (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setSubmitted(true);
    if (errors.checkIn) return checkInRef.current?.focus();
    if (errors.checkOut) return checkOutRef.current?.focus();
    setStatus(`Booked ${String(form.checkIn)} to ${String(form.checkOut)}, arriving ${form.arrival ? String(form.arrival) : 'any time'}`);
  };
  return (
    <form noValidate onSubmit={onSubmit} style={{ display: 'grid', gap: 16 }}>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 24, alignItems: 'flex-start' }}>
        <DatePicker
          ref={checkInRef}
          label="Check-in"
          name="checkIn"
          required
          value={form.checkIn}
          onValueChange={(value) => set('checkIn', value as PlainDate | null)}
          onBlur={() => setTouched((t) => ({ ...t, checkIn: true }))}
          invalid={show('checkIn')}
          errorMessage={errors.checkIn}
          onInvalid={() => setStatus('onInvalid: check-in failed constraint validation')}
          min="2026-11-01"
        />
        <DatePicker
          ref={checkOutRef}
          label="Check-out"
          name="checkOut"
          required
          value={form.checkOut}
          onValueChange={(value) => set('checkOut', value as PlainDate | null)}
          onBlur={() => setTouched((t) => ({ ...t, checkOut: true }))}
          invalid={show('checkOut')}
          errorMessage={errors.checkOut}
          placeholderValue={form.checkIn ?? undefined}
          min="2026-11-01"
        />
        <TimePicker label="Arrival time" name="arrival" value={form.arrival} onValueChange={(value) => set('arrival', value)} min="14:00" max="22:00" errorMessage="Arrival is between 14:00 and 22:00." onInvalid={() => setStatus('onInvalid: arrival time is out of range')} />
      </div>
      <div className="demo-toolbar">
        <Button variant="outline" type="submit">Book</Button>
        <Button variant="outline" type="button" onClick={() => setForm({ checkIn: null, checkOut: null, arrival: null })}>
          Clear from outside
        </Button>
        <Button variant="outline"
          type="button"
          onClick={() => {
            setForm((f) => ({ ...f, checkIn: null }));
            setStatus('');
          }}
        >
          Reset check-in
        </Button>
        <Button variant="outline" type="button" onClick={(e) => e.currentTarget.form?.reportValidity()}>
          Check native validity
        </Button>
      </div>
      <p className="demo-status" aria-live="polite">
        State: {JSON.stringify(form)} · onValueChange calls: {changes}
        {status ? ` · ${status}` : ''}
      </p>
    </form>
  );
}
```

## Not offered

- Built-in value persistence: store the value yourself
  (`localStorage`, URL) and pass it as `value` or `defaultValue`.
- Remappable keys: the keys follow the WAI-ARIA patterns.
- A popup z-index option: popups use the top layer, above every
  z-index.
- Lifecycle events and methods: use React effects.

## API reference

The API reference for
[`@salmonui/calendars/date-picker`](https://salmonui.dev/docs/reference/calendars/date-picker),
[`@salmonui/calendars/date-range-picker`](https://salmonui.dev/docs/reference/calendars/date-range-picker)
and [`@salmonui/calendars/time-picker`](https://salmonui.dev/docs/reference/calendars/time-picker) lists
every prop, method and type.

### Live demo: Pickers in a form

Live demo: https://salmonui.dev/demos/calendars/calendar-picker-forms

Pickers post ISO values, take part in required and range validation, and restore their default values on reset.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { DatePicker } from '@salmonui/calendars/date-picker';
import { DateRangePicker } from '@salmonui/calendars/date-range-picker';
import { TimePicker } from '@salmonui/calendars/time-picker';
import { Button } from '@salmonui/buttons/button';

export default function CalendarPickerFormsDemo() {
  const [posted, setPosted] = useState('');
  return (
    <form
      style={{ display: 'flex', flexWrap: 'wrap', gap: 16, alignItems: 'flex-end' }}
      onSubmit={(e) => {
        e.preventDefault();
        setPosted(JSON.stringify(Object.fromEntries(new FormData(e.currentTarget).entries()), null, 2));
      }}
    >
      <DatePicker label="Due" name="due" required clearable defaultValue="2026-11-23" min="2026-11-01" max="2026-11-30" locale="de-DE" />
      <DatePicker label="Meeting" name="meeting" granularity="minute" defaultValue="2026-11-23T14:30" />
      <DateRangePicker label="Stay" name="stay" defaultValue={{ start: '2026-11-02', end: '2026-11-06' }} />
      <TimePicker label="Alarm" name="alarm" defaultValue="07:30" />
      <DatePicker label="Sheet" name="sheet" popupMode="modal" />
      <div style={{ display: 'flex', gap: 8 }}>
        <Button variant="outline" type="submit">Submit</Button>
        <Button variant="outline" type="reset">Reset</Button>
      </div>
      <pre style={{ flexBasis: '100%', margin: 0 }}>{posted || 'Nothing posted yet'}</pre>
    </form>
  );
}
```
