# Date Picker
A date field that understands typed dates like next fri.
Source page: https://dinachi.dev/docs/components/date-picker

## Installation
```bash
npx @dinachi/cli@latest add date-picker
```
Adds to your project:
- `components/ui/date-picker/date-picker.tsx`
- `components/ui/date-picker/index.ts`
Installs:
- `@base-ui/react` ^1.9.0
- `date-fns` ^4.4.0
- `lucide-react` ^0.552.0

## Usage
```tsx
import { useState } from "react"
import { DatePicker } from "@/components/ui/date-picker"

export function DueDate() {
  const [due, setDue] = useState<Date | null>(null)
  return <DatePicker aria-label="Due date" value={due} onValueChange={setDue} min={new Date()} />
}
```

## Examples

### Default
Due from today on.
```tsx
import { useState } from 'react';
import { DatePicker } from '@/components/ui/date-picker';

export function Example() {
  const [due, setDue] = useState<Date | null>(null);
  return <DatePicker aria-label="Due date" label="Due date" value={due} onValueChange={setDue} min={new Date()} />;
}
```

### Weekdays only
Weekends are refused, typed or picked.
```tsx
import { DatePicker } from '@/components/ui/date-picker';

export function Example() {
  return (
    <DatePicker
      aria-label="Delivery day"
      label="Delivery day"
      min={new Date()}
      isDateDisabled={(d) => d.getDay() === 0 || d.getDay() === 6}
      placeholder="mon or 24 nov"
    />
  );
}
```

## Notes

### Server rendering
Pass `today` when the page renders on a server, so the server and the browser agree on which day it is.

### Typing first
The line under the field shows the day it reads before anything commits, and how far away it is. Text that isn't a date, or a day that can't be picked, says why there and marks the field invalid; it is never thrown away. So does a value set from outside that can't be picked. A two-digit year lands inside `min` and `max` when it can, so 75 in a birth date field is 1975. Esc puts back the last committed day.

### On phones
Below 768px the calendar opens in a drawer with its own field, preset chips and a confirm button. Nothing commits until that button is pressed, so swiping the drawer away leaves the value as it was.

## API reference
Props marked **agent** change what an agent reads or may do.

### DatePicker
The field, the calendar button, the line under the field, and the popover or drawer.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` **agent** | `Date \| null` | - | Controlled value, a day at local midnight. |
| `defaultValue` | `Date \| null` | - | Starting value when uncontrolled. |
| `onValueChange` **agent** | `(value, details) => void` | - | Runs when a day commits: on Enter, on leaving the field, on a calendar pick, or on the drawer's button. `details.cancel()` refuses it. |
| `min` **agent** | `Date` | - | The earliest day. Typing an earlier one shows why it can't be used. |
| `max` **agent** | `Date` | - | The latest day. |
| `isDateDisabled` **agent** | `(date: Date) => boolean` | - | Blocks single days, typed or picked. |
| `parseDate` | `(text, { today, min, max }) => Date \| null` | - | Replaces the parser, for other languages or formats. |
| `captionLayout` | `"label" \| "dropdown"` | `"label"` | `dropdown` gives the calendar month and year selects, for days years away such as a birth date. |
| `formatDate` | `(date: Date) => string` | `Fri, 21 Nov 2026` | How a committed day reads in the field. |
| `presets` | `{ label: string; value: Date }[]` | - | Chips in the phone drawer. Defaults to today, tomorrow, Saturday, next Monday and in a week. Blocked ones are dropped. |
| `presentation` | `"auto" \| "popover" \| "drawer"` | `"auto"` | A popover from 768px up and a drawer below, unless one is named. |
| `label` | `string` | `"Choose a date"` | Names the calendar button and popover, and titles the drawer. |
| `confirmLabel` | `string` | `"Set date"` | The drawer's button. |
| `placeholder` | `string` | `"next fri or 21 nov"` | Shows what can be typed. |
| `name` | `string` | - | Submits the day with a form as `YYYY-MM-DD`. |
| `required` | `boolean` | `false` | Validated on the field itself, so the browser points at it. |
| `disabled` **agent** | `boolean` | `false` | Blocks people and agents. |
| `weekNumbers, locale, weekStartsOn, dir, today` | `As Calendar` | - | Passed to the calendar. `locale` also sets how 3/12 is read. |

## Agent
Inside an `AgentProvider`, Date Picker appears in `agent.snapshot()` as `date`.
Reads:
- `label`: The field's aria-label.
- `value`: YYYY-MM-DD, or absent when empty.
- `invalid, errors`: Set while the field holds text that doesn't read, with the message the person sees.
- `disabled`: True when the picker is blocked.
Actions:
- `setValue("2026-12-24")`: Commits the day. Phrases work too: next fri, in 2 weeks, 21 nov.
- `clear()`: Empties the value.
An agent's change runs through `onValueChange` like anyone's. `isAgentChange(details)` is true for it; `details.cancel()` refuses it. Days the field would refuse are refused with the same words.
```ts
await agent.act({
  steps: [{ ref: "Due date", action: "setValue", args: ["next fri"] }],
})
```

## Accessibility
- The line under the field is a live region tied to the field by aria-describedby, so the reading is announced as you type.
- An unreadable entry sets aria-invalid and the field's validation message.
- The calendar button's name includes the committed day.
- Picking a day returns focus to the field.
### Keyboard
| Keys | Does |
| --- | --- |
| `Enter` | Commits what the field reads |
| `↓` | Opens the calendar on the picked day |
| `Esc` | Closes the calendar, or puts back the last committed day |
| `Tab` | Commits and moves on |

## Source
`components/ui/date-picker/date-picker.tsx`
```tsx
"use client"

import * as React from "react";
import { Input as BaseInput } from "@base-ui/react/input";
import { format, type Locale } from "date-fns";
import { CalendarDays } from "lucide-react";
import { cn } from "@/lib/utils";
import { type Agent, AgentProvider, changeAsAgent, useAgentControl, useAgentState, useMergedRef } from "@/components/ui/agent";
import { Button } from "@/components/ui/button";
import {
  Calendar,
  type CalendarChangeDetails,
  addDays,
  dayFirst,
  daysBetween,
  fromISODate,
  isSameDay,
  parseDate as readDate,
  startOfDay,
  toISODate,
} from "@/components/ui/calendar";
import { Drawer, DrawerContent, DrawerTitle, DrawerTrigger } from "@/components/ui/drawer";
import { Popover, PopoverPopup, PopoverPortal, PopoverPositioner, PopoverTrigger } from "@/components/ui/popover";

/** The picker is one control to an agent, so the parts inside it don't register their own. */
const Unlisted = ({ children }: { children: React.ReactNode }) => (
  <AgentProvider agent={null as unknown as Agent}>{children}</AgentProvider>
);

const WIDE = "(min-width: 768px)";

/** `popover` from 768px up, `drawer` below, unless one is asked for. */
function usePresentation(presentation: "auto" | "popover" | "drawer"): "popover" | "drawer" {
  const wide = React.useSyncExternalStore(
    (onChange) => {
      const query = window.matchMedia?.(WIDE);
      query?.addEventListener("change", onChange);
      return () => query?.removeEventListener("change", onChange);
    },
    () => window.matchMedia?.(WIDE).matches ?? true,
    () => true
  );
  return presentation === "auto" ? (wide ? "popover" : "drawer") : presentation;
}

function changeDetails(reason: string, event?: Event): CalendarChangeDetails {
  const details: CalendarChangeDetails = {
    reason,
    event,
    isCanceled: false,
    cancel() {
      details.isCanceled = true;
    },
  };
  return details;
}

/** How far `day` is from today in words the browser's language uses: tomorrow, in 4 days. */
function relative(day: Date, today: Date, locale?: Locale): string {
  const n = daysBetween(today, day);
  const words = new Intl.RelativeTimeFormat(locale?.code ?? "en-US", { numeric: "auto" });
  if (Math.abs(n) < 60) return words.format(n, "day");
  // Whole months and years passed, as an age is counted: 53 years and 8 months is 53 years.
  if (Math.abs(n) < 730) return words.format(Math.trunc(n / 30.44), "month");
  return words.format(Math.trunc(n / 365.25), "year");
}

export interface DatePickerPreset {
  label: string;
  value: Date;
}

export interface DatePickerProps
  extends Omit<React.ComponentProps<"input">, "value" | "defaultValue" | "onChange" | "min" | "max" | "type" | "dir" | "children" | "size"> {
  value?: Date | null;
  defaultValue?: Date | null;
  onValueChange?: (value: Date | null, details: CalendarChangeDetails) => void;
  /** The earliest day that can be picked or typed. */
  min?: Date;
  /** The latest day that can be picked or typed. */
  max?: Date;
  /** Days that can't be picked, besides those outside `min` and `max`. */
  isDateDisabled?: (date: Date) => boolean;
  weekNumbers?: boolean;
  /** A date-fns locale, for names, the first day of the week and how 3/12 is read. */
  locale?: Locale;
  weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6;
  dir?: "ltr" | "rtl";
  /** Defaults to the current day. */
  today?: Date;
  /** Replaces the parser, for other languages or formats. Return null for text that isn't a date. */
  parseDate?: (text: string, options: { today: Date; min?: Date; max?: Date }) => Date | null;
  /** How a committed day reads in the field. Defaults to `Fri, 21 Nov 2026`. */
  formatDate?: (date: Date) => string;
  /** One-tap answers shown on phones. Defaults to today, tomorrow, Saturday, next Monday and in a week. */
  presets?: DatePickerPreset[];
  /** `auto` uses a popover from 768px up and a drawer below. */
  presentation?: "auto" | "popover" | "drawer";
  /** `dropdown` gives the calendar month and year selects, for days years away such as a birth date. */
  captionLayout?: "label" | "dropdown";
  /** Names the calendar's popover and titles the drawer. */
  label?: string;
  /** The drawer's confirm button. */
  confirmLabel?: string;
}

interface Reading {
  kind: "empty" | "set" | "preview" | "error";
  date?: Date;
  message?: string;
}

/**
 * A date field you type into first: next fri, 21 nov and in 2 weeks all read. The day it
 * reads shows under the field before it commits, on Enter or on leaving the field. The
 * calendar is one button away, in a popover on wide screens and a drawer on phones.
 */
const DatePicker = React.forwardRef<HTMLInputElement, DatePickerProps>((props, ref) => {
  const {
    value: valueProp,
    defaultValue,
    onValueChange,
    min: minProp,
    max: maxProp,
    isDateDisabled,
    weekNumbers,
    locale,
    weekStartsOn = locale?.options?.weekStartsOn ?? 1,
    dir,
    today: todayProp,
    parseDate,
    formatDate,
    presets: presetsProp,
    presentation: presentationProp = "auto",
    captionLayout,
    label = "Choose a date",
    confirmLabel = "Set date",
    name,
    required,
    disabled,
    readOnly,
    placeholder = "next fri or 21 nov",
    className,
    onBlur,
    onKeyDown,
    "aria-describedby": describedBy,
    ...inputProps
  } = props;

  const today = React.useMemo(() => startOfDay(todayProp ?? new Date()), [todayProp ? toISODate(todayProp) : null]);
  const min = minProp && startOfDay(minProp);
  const max = maxProp && startOfDay(maxProp);
  const presentation = usePresentation(presentationProp);
  const [value, change] = useAgentState<Date | null, CalendarChangeDetails>(valueProp, defaultValue ?? null, onValueChange);
  const [open, setOpenState] = React.useState(false);
  // Each opening starts the drawer's draft afresh, from the value as it is then.
  const [round, setRound] = React.useState(0);
  const setOpen = (next: boolean) => {
    if (next && !open) setRound((r) => r + 1);
    setOpenState(next);
  };
  const [focused, setFocused] = React.useState(false);
  const input = React.useRef<HTMLInputElement>(null);
  const box = React.useRef<HTMLDivElement>(null);
  const popup = React.useRef<HTMLDivElement>(null);
  const hintId = React.useId();

  const fmt = formatDate ?? ((d: Date) => format(d, "EEE, d MMM yyyy", { locale }));
  const read = (text: string) =>
    parseDate
      ? parseDate(text, { today, min, max })
      : readDate(text, { today, order: dayFirst(locale) ? "day-first" : "month-first", weekStartsOn, min, max });

  /** Why `d` can't be picked, in the words the field shows. */
  const refusal = (d: Date): string | null => {
    if (min && d < min) return isSameDay(min, today) ? `${fmt(d)} has passed.` : `The earliest is ${fmt(min)}.`;
    if (max && d > max) return `The latest is ${fmt(max)}.`;
    if (isDateDisabled?.(d)) return `${fmt(d)} isn't available.`;
    return null;
  };

  /** While `typing`, a word of two letters is on its way rather than wrong. */
  const reading = (text: string, current: Date | null, typing = true): Reading => {
    const t = text.trim();
    if (!t) return { kind: "empty" };
    if (current && text === fmt(current)) {
      const why = refusal(current);
      return why ? { kind: "error", message: why } : { kind: "set", date: current };
    }
    const d = read(t);
    if (!d) return t.length > 2 || !typing ? { kind: "error", message: "Not a date. Try 21 nov or next fri." } : { kind: "empty" };
    const why = refusal(d);
    return why ? { kind: "error", message: why } : { kind: "preview", date: d };
  };

  /* ---- the field ---- */
  const [text, setText] = React.useState(() => (value ? fmt(value) : ""));
  // A value set from outside, by the app or an agent, rewrites the field.
  const key = value ? toISODate(value) : "";
  const [seen, setSeen] = React.useState(key);
  if (seen !== key) {
    setSeen(key);
    setText(value ? fmt(value) : "");
  }
  const now = reading(text, value, focused);

  React.useEffect(() => {
    input.current?.setCustomValidity(now.kind === "error" ? now.message! : "");
  }, [now.kind, now.message]);

  const commit = (d: Date | null, details: CalendarChangeDetails) => {
    if (!isSameDay(d, value) && (d || value)) {
      change(d, details);
      // The app said no, so the field goes back to what it holds.
      if (details.isCanceled) d = value;
    }
    setText(d ? fmt(d) : "");
  };

  /** Commits what the field reads, if it reads as a day or as nothing. */
  const settle = (event?: Event): boolean => {
    if (now.kind === "set") return true;
    if (now.kind === "error") return false;
    if (now.kind === "empty" && text.trim()) return false;
    commit(now.date ?? null, changeDetails("input-commit", event));
    return true;
  };

  /* ---- agent ---- */
  useAgentControl(() => ({
    kind: "date",
    element: input.current,
    value: value ? toISODate(value) : undefined,
    disabled,
    required,
    invalid: now.kind === "error" || undefined,
    errors: now.kind === "error" ? [now.message!] : undefined,
    actions: {
      setValue: (wanted: unknown) => {
        if (readOnly) return "The field is read-only.";
        if (wanted === null || wanted === "") return changeAsAgent(commit, null);
        const d =
          wanted instanceof Date
            ? isNaN(wanted.getTime()) ? null : startOfDay(wanted)
            : typeof wanted === "string" ? fromISODate(wanted) ?? read(wanted) : null;
        if (!d) return `"${String(wanted)}" is not a date. Send YYYY-MM-DD, or a phrase such as next fri.`;
        return refusal(d) ?? changeAsAgent(commit, d);
      },
      clear: () => (readOnly ? "The field is read-only." : changeAsAgent(commit, null)),
    },
  }));

  /* ---- render ---- */
  const calendarProps = { min, max, isDateDisabled, weekNumbers, locale, weekStartsOn, dir, today, captionLayout };
  const iconButton = (
    <button
      type="button"
      aria-label={value ? `${label}, ${fmt(value)}` : label}
      disabled={disabled || readOnly}
      data-slot="date-picker-trigger"
      className={cn(
        "me-1 inline-flex size-7 shrink-0 items-center justify-center rounded-[calc(var(--radius)-4px)] text-muted-foreground",
        "hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
        "disabled:pointer-events-none disabled:opacity-50"
      )}
    >
      <CalendarDays className="size-4" aria-hidden />
    </button>
  );

  return (
    <div data-slot="date-picker" dir={dir} className={cn("w-full", className)}>
      <div
        ref={box}
        data-slot="date-picker-field"
        data-invalid={now.kind === "error" || undefined}
        data-disabled={disabled || undefined}
        className={cn(
          "flex h-9 items-center rounded-md border border-input bg-transparent shadow-xs dark:bg-input/30",
          "transition-[color,box-shadow] focus-within:border-ring focus-within:ring-[3px] focus-within:ring-ring/50",
          "data-[invalid]:border-destructive data-[invalid]:focus-within:ring-destructive/20",
          "data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50"
        )}
      >
        <BaseInput
          {...inputProps}
          ref={useMergedRef(ref, input)}
          data-slot="date-picker-input"
          autoComplete="off"
          value={text}
          placeholder={placeholder}
          required={required}
          disabled={disabled}
          readOnly={readOnly}
          aria-invalid={now.kind === "error" || undefined}
          aria-describedby={cn(describedBy, hintId) || undefined}
          onValueChange={(next) => setText(next)}
          onFocus={(e) => {
            setFocused(true);
            inputProps.onFocus?.(e);
          }}
          onBlur={(e) => {
            setFocused(false);
            settle(e.nativeEvent);
            onBlur?.(e);
          }}
          onKeyDown={(e) => {
            onKeyDown?.(e);
            if (e.defaultPrevented) return;
            // An empty field with nothing to clear lets Enter submit the form.
            if (e.key === "Enter" && now.kind !== "set" && (text.trim() || value)) {
              e.preventDefault();
              if (settle(e.nativeEvent)) setOpen(false);
            } else if (e.key === "ArrowDown" && !readOnly) {
              e.preventDefault();
              // Commit first, so the calendar opens on the day the field reads.
              settle(e.nativeEvent);
              setOpen(true);
            } else if (e.key === "Escape" && !open && text !== (value ? fmt(value) : "")) {
              e.stopPropagation();
              setText(value ? fmt(value) : "");
            }
          }}
          className="h-full min-w-0 flex-1 bg-transparent px-3 text-base outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed md:text-sm"
        />
        <Unlisted>
          {presentation === "popover" ? (
            <Popover open={open} onOpenChange={setOpen}>
              <PopoverTrigger render={iconButton} />
              <PopoverPortal>
                <PopoverPositioner anchor={box} align="start" sideOffset={6}>
                  <PopoverPopup
                    ref={popup}
                    dir={dir}
                    aria-label={label}
                    data-slot="date-picker-popup"
                    initialFocus={() => focusableDay(popup.current)}
                    finalFocus={input}
                    className="p-2"
                  >
                    <Calendar
                      {...calendarProps}
                      required
                      value={value}
                      onValueChange={(d, details) => {
                        commit(d, details);
                        setOpen(false);
                      }}
                      className="[--calendar-bg:var(--popover)] [--calendar-height:18.75rem]"
                    />
                  </PopoverPopup>
                </PopoverPositioner>
              </PopoverPortal>
            </Popover>
          ) : (
            <Drawer open={open} onOpenChange={setOpen}>
              <DrawerTrigger render={iconButton} />
              <DrawerContent
                ref={popup}
                dir={dir}
                side="bottom"
                data-slot="date-picker-drawer"
                // The calendar takes focus, so a phone keeps its keyboard down.
                initialFocus={() => focusableDay(popup.current)}
                finalFocus={input}
                className="max-h-[92dvh] gap-0 rounded-t-2xl px-0 pb-6 pt-4"
              >
                <DrawerPick
                    key={`${round}:${key}`}
                    label={label}
                    confirmLabel={confirmLabel}
                    placeholder={placeholder}
                    initial={value}
                    presets={(presetsProp ?? phonePresets(today)).filter((p) => !refusal(p.value))}
                    reading={reading}
                    fmt={fmt}
                    relative={(d) => relative(d, today, locale)}
                    calendarProps={calendarProps}
                    onConfirm={(d) => {
                      commit(d, changeDetails("confirm"));
                      setOpen(false);
                    }}
                  />
              </DrawerContent>
            </Drawer>
          )}
        </Unlisted>
      </div>
      <p id={hintId} data-slot="date-picker-hint" aria-live="polite" className={cn("mt-1.5 flex min-h-5 items-center gap-2 text-[0.8125rem] text-muted-foreground", now.kind === "error" && "text-destructive")}>
        {now.kind === "error" && now.message}
        {now.kind === "preview" && (
          <>
            <b className="font-medium text-foreground">{fmt(now.date!)}</b>
            <span className="sr-only">, </span>
            <span>{relative(now.date!, today, locale)}</span>
          </>
        )}
        {now.kind === "set" && <span>{relative(now.date!, today, locale)}</span>}
      </p>
      {name && <input type="hidden" name={name} form={inputProps.form} disabled={disabled} value={value ? toISODate(value) : ""} />}
    </div>
  );
});
DatePicker.displayName = "DatePicker";

function focusableDay(root: HTMLElement | null): HTMLElement | true {
  const days = root?.querySelectorAll<HTMLElement>("[data-slot=calendar-day][tabindex='0']") ?? [];
  return days[days.length - 1] ?? true;
}

function phonePresets(today: Date): DatePickerPreset[] {
  const saturday = readDate("sat", { today })!;
  const monday = readDate("next mon", { today })!;
  const all = [
    { label: "Today", value: today },
    { label: "Tomorrow", value: addDays(today, 1) },
    { label: "Saturday", value: saturday },
    { label: "Next Mon", value: monday },
    { label: "In a week", value: addDays(today, 7) },
  ];
  return all.filter((p, i) => all.findIndex((q) => isSameDay(q.value, p.value)) === i);
}

/** The drawer's own field, chips and calendar. Nothing commits until its button is pressed. */
function DrawerPick(props: {
  label: string;
  confirmLabel: string;
  placeholder: string;
  initial: Date | null;
  presets: DatePickerPreset[];
  reading: (text: string, current: Date | null) => Reading;
  fmt: (d: Date) => string;
  relative: (d: Date) => string;
  calendarProps: Omit<React.ComponentProps<typeof Calendar>, "mode" | "value" | "defaultValue" | "onValueChange">;
  onConfirm: (d: Date | null) => void;
}) {
  const { label, confirmLabel, placeholder, initial, presets, reading, fmt, relative, calendarProps, onConfirm } = props;
  const [draft, setDraft] = React.useState(initial);
  const [text, setText] = React.useState(initial ? fmt(initial) : "");
  const hintId = React.useId();
  const now = reading(text, draft);
  const ready = now.kind !== "error" && !(now.kind === "empty" && text.trim());
  const hit = presets.findIndex((p) => isSameDay(p.value, draft));
  const set = (d: Date) => {
    setDraft(d);
    setText(fmt(d));
  };
  return (
    <div className="flex min-h-0 flex-col">
      <DrawerTitle className="px-5 pb-3 text-[1.0625rem] font-semibold">{label}</DrawerTitle>
      <div className="px-5 pb-2.5">
        <BaseInput
          aria-label={label}
          aria-describedby={hintId}
          data-slot="date-picker-drawer-input"
          autoComplete="off"
          value={text}
          placeholder={placeholder}
          aria-invalid={now.kind === "error" || undefined}
          onValueChange={(next) => {
            setText(next);
            if (!next.trim()) return setDraft(null);
            const r = reading(next, null);
            if (r.kind === "preview") setDraft(r.date!);
          }}
          onKeyDown={(e) => {
            if (e.key !== "Enter") return;
            e.preventDefault();
            if (ready) onConfirm(draft);
          }}
          className={cn(
            "h-12 w-full rounded-xl border border-input bg-background px-3.5 text-[1.0625rem] outline-none placeholder:text-muted-foreground",
            "focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-destructive"
          )}
        />
        <p id={hintId} data-slot="date-picker-drawer-hint" aria-live="polite" className={cn("mt-1.5 flex min-h-5 items-center gap-2 text-[0.8125rem] text-muted-foreground", now.kind === "error" && "text-destructive")}>
          {now.kind === "error" && now.message}
          {now.kind === "preview" && hit < 0 && (
            <>
              <b className="font-medium text-foreground">{fmt(now.date!)}</b>
              <span className="sr-only">, </span>
              <span>{relative(now.date!)}</span>
            </>
          )}
          {/* A lit chip already says when it is. */}
          {now.kind === "set" && hit < 0 && <span>{relative(now.date!)}</span>}
        </p>
      </div>
      {presets.length > 0 && (
        <div data-slot="date-picker-presets" className="flex gap-2 overflow-x-auto px-5 pb-3 [scrollbar-width:none]">
          {presets.map((p, i) => (
            <button
              key={p.label}
              type="button"
              aria-pressed={i === hit}
              data-slot="date-picker-preset"
              onClick={() => set(p.value)}
              className={cn(
                "shrink-0 whitespace-nowrap rounded-full border border-border bg-background px-3 py-1.5 text-[0.8125rem]",
                "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
                "aria-pressed:border-transparent aria-pressed:bg-primary aria-pressed:text-primary-foreground"
              )}
            >
              {p.label}
            </button>
          ))}
        </div>
      )}
      <div className="flex justify-center px-3">
        <Calendar
          {...calendarProps}
          required
          value={draft}
          onValueChange={(d) => d && set(d)}
          className="w-full [--calendar-bg:var(--background)] [--calendar-cell:2.75rem] [--calendar-height:18.75rem]"
        />
      </div>
      <div className="px-5 pt-3">
        <Button className="w-full" data-slot="date-picker-confirm" disabled={!ready} onClick={() => onConfirm(draft)}>
          {confirmLabel}
        </Button>
      </div>
    </div>
  );
}

export { DatePicker };
```
