{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "date-picker",
  "type": "registry:ui",
  "title": "Date Picker",
  "description": "An accessible React date picker for Next.js and Tailwind CSS: a calendar in a popover for a date or a date range, with presets and Intl formatting.",
  "author": "FewTone <https://fewtone.com>",
  "dependencies": [
    "lucide-react@^1.52.0",
    "motion@^14.0.0"
  ],
  "registryDependencies": [
    "https://ui.fewtone.com/r/tokens.json",
    "https://ui.fewtone.com/r/motion.json",
    "https://ui.fewtone.com/r/calendar.json",
    "https://ui.fewtone.com/r/popover.json"
  ],
  "files": [
    {
      "path": "registry/fewtone/ui/date-picker.tsx",
      "type": "registry:ui",
      "content": "\"use client\";\n\nimport {\n  Calendar,\n  type CalendarLabels,\n  type DateRange,\n  type Matcher,\n  type Weekday,\n} from \"@/components/ui/calendar\";\nimport { Popover, PopoverContent, PopoverTrigger } from \"@/components/ui/popover\";\nimport { duration, ease, spring, swap } from \"@/lib/motion\";\nimport { cn } from \"@/lib/utils\";\nimport { CalendarIcon } from \"lucide-react\";\nimport { AnimatePresence, LayoutGroup, motion, useReducedMotion } from \"motion/react\";\nimport { type ComponentProps, type ReactNode, useEffect, useId, useRef, useState } from \"react\";\n\n/*\n * Date Picker and Date Range Picker (roadmap, 2026-10-16: \"A calendar in a popover, for dates and ranges\").\n * - Our Calendar in our Popover, opened from a trigger drawn like Select's: a calendar icon, then the date or\n *   a placeholder. The trigger is a combobox that pops up a dialog (the WAI-ARIA date picker pattern), so a\n *   <label htmlFor> names it and screen readers read the date as its value.\n * - Opening moves the focus to the picked day (or today), ready for the arrow keys. Escape, a click outside\n *   or the trigger closes it, and the focus goes back to the trigger.\n * - Motion (.agents/rules/motion.md): the popover opens from the trigger through the blur (Popover), and the\n *   trigger's text swaps through `swap` when the date changes. DatePicker closes a beat after a pick\n *   (duration.base), once the circle has landed on the new day. DateRangePicker stays open, so the band can\n *   be seen growing and the range picked again.\n * - Presets (\"Today\", \"Next 7 days\") are a small list beside the calendar, with one highlight gliding between\n *   them (Select's pill). Their values can be functions, worked out when picked, so nothing reads the clock\n *   while rendering (no hydration mismatch).\n * - Dates are formatted by Intl: dateStyle \"medium\" by default, and formatRange for ranges (\"Oct 12 – 18, 2026\").\n */\n\nexport type DatePreset<T> = {\n  label: string;\n  /** The date (or range) it picks, or a function that works it out when it's picked */\n  value: T | (() => T);\n};\n\nexport type DatePickerLabels = CalendarLabels & {\n  /** Names the popup, a dialog */\n  dialog: string;\n  /** Names the list of presets */\n  presets: string;\n};\n\nconst triggerSizes = {\n  sm: \"h-(--size-control-sm) rounded-md px-2.5\",\n  md: \"h-(--size-control-md) px-3\",\n} as const;\n\ntype PickerProps = Omit<\n  ComponentProps<\"button\">,\n  \"value\" | \"defaultValue\" | \"onChange\" | \"children\" | \"name\"\n> & {\n  /** Shown in the trigger while nothing is picked */\n  placeholder?: string;\n  size?: keyof typeof triggerSizes;\n  /** Whether it's open, when you control it */\n  open?: boolean;\n  defaultOpen?: boolean;\n  onOpenChange?: (open: boolean) => void;\n  /** A BCP 47 language tag for the trigger's date and the calendar */\n  locale?: string;\n  /** How the trigger writes the date, as Intl.DateTimeFormat options */\n  formatOptions?: Intl.DateTimeFormatOptions;\n  /** The earliest day that can be picked */\n  min?: Date;\n  /** The latest day that can be picked */\n  max?: Date;\n  /** Days that can't be picked: Calendar's `disabled` */\n  disabledDates?: Matcher | Matcher[];\n  weekStartsOn?: Weekday;\n  numberOfMonths?: number;\n  /** The day marked as today. Defaults to the browser's today. */\n  today?: Date;\n  /** How the popover lines up with the trigger */\n  align?: \"start\" | \"center\" | \"end\";\n  labels?: Partial<DatePickerLabels>;\n};\n\nexport type DatePickerProps = PickerProps & {\n  /** The picked day, when you control it */\n  value?: Date | undefined;\n  defaultValue?: Date;\n  onChange?: (date: Date | undefined) => void;\n  presets?: DatePreset<Date>[];\n  /** Submits the day with a form, as YYYY-MM-DD */\n  name?: string;\n};\n\nexport type DateRangePickerProps = PickerProps & {\n  /** The picked range, when you control it */\n  value?: DateRange | undefined;\n  defaultValue?: DateRange;\n  onChange?: (range: DateRange | undefined) => void;\n  presets?: DatePreset<DateRange>[];\n};\n\nconst monthOf = (date: Date) => new Date(date.getFullYear(), date.getMonth(), 1);\nconst monthIndex = (date: Date) => date.getFullYear() * 12 + date.getMonth();\nconst pad = (value: number, length = 2) => String(value).padStart(length, \"0\");\nconst keyOf = (date: Date) =>\n  `${pad(date.getFullYear(), 4)}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;\nconst resolve = <T,>(value: T | (() => T)) => (typeof value === \"function\" ? (value as () => T)() : value);\n\n/**\n * What both pickers share: whether they're open, the month the calendar shows, and closing a beat after a\n * pick. Each opening starts on the picked month, or on today's (which Calendar knows).\n */\nfunction usePicker(\n  openProp: boolean | undefined,\n  defaultOpen: boolean | undefined,\n  onOpenChange: ((open: boolean) => void) | undefined,\n  anchor: Date | undefined,\n  count: number,\n  today: Date | undefined,\n) {\n  const reduce = useReducedMotion() ?? false;\n  const [ownOpen, setOwnOpen] = useState(defaultOpen ?? false);\n  const open = openProp ?? ownOpen;\n  const [month, setMonth] = useState<Date | undefined>(() => (anchor ? monthOf(anchor) : undefined));\n  const closing = useRef<ReturnType<typeof setTimeout>>(undefined);\n\n  useEffect(() => () => clearTimeout(closing.current), []);\n\n  const setOpen = (next: boolean) => {\n    clearTimeout(closing.current);\n    if (next) setMonth(anchor ? monthOf(anchor) : undefined);\n    if (openProp === undefined) setOwnOpen(next);\n    onOpenChange?.(next);\n  };\n\n  return {\n    open,\n    setOpen,\n    month,\n    setMonth,\n    /** Closes once the circle has landed on the picked day */\n    closeSoon: () => {\n      clearTimeout(closing.current);\n      closing.current = setTimeout(() => setOpen(false), reduce ? 0 : duration.base * 1000);\n    },\n    /** Pages the calendar to a picked day it isn't showing (a preset's) */\n    reveal: (date: Date) => {\n      // With no month set, the calendar is on today's (yours, or the clock's: this runs on a click, not a render)\n      const shown = month ?? monthOf(today ?? new Date());\n      const offset = monthIndex(date) - monthIndex(shown);\n      if (offset < 0 || offset >= count) setMonth(monthOf(date));\n    },\n  };\n}\n\n/** The list of presets, with one highlight gliding to the row under the mouse or with the focus */\nfunction PresetList<T>({\n  presets,\n  label,\n  onPick,\n}: {\n  presets: DatePreset<T>[];\n  label: string;\n  onPick: (value: T) => void;\n}) {\n  const groupId = useId();\n  const reduce = useReducedMotion() ?? false;\n  const [hovered, setHovered] = useState<string | null>(null);\n  const [focused, setFocused] = useState<string | null>(null);\n  const active = hovered ?? focused;\n\n  return (\n    <ul\n      data-slot=\"date-picker-presets\"\n      aria-label={label}\n      className=\"relative isolate flex shrink-0 flex-col gap-0.5 py-3 ps-3\"\n      onPointerLeave={() => setHovered(null)}\n      onBlur={(event) => {\n        if (!event.currentTarget.contains(event.relatedTarget)) setFocused(null);\n      }}\n    >\n      <LayoutGroup id={groupId}>\n        {presets.map((preset) => (\n          <li key={preset.label}>\n            <button\n              type=\"button\"\n              data-slot=\"date-picker-preset\"\n              onPointerEnter={(event) => {\n                // Hover highlights follow the mouse only\n                if (event.pointerType === \"mouse\") setHovered(preset.label);\n              }}\n              onFocus={() => setFocused(preset.label)}\n              onClick={() => onPick(resolve(preset.value))}\n              className={cn(\n                \"relative flex w-full cursor-pointer items-center rounded-md px-2 py-1.5 text-start text-sm whitespace-nowrap\",\n                \"transition-colors duration-(--duration-fast) ease-out\",\n                \"outline-ring focus-visible:outline-(length:--focus-ring-width) focus-visible:outline-offset-(--focus-ring-offset)\",\n                active === preset.label && \"text-accent-foreground\",\n              )}\n            >\n              {/* The rows aren't stacking contexts: the pill joins the list's layer (it's `isolate`), behind every label */}\n              {active === preset.label ? (\n                <motion.span\n                  layoutId=\"date-picker-preset-highlight\"\n                  aria-hidden\n                  className=\"pointer-events-none absolute inset-0 -z-10 rounded-md bg-accent\"\n                  transition={reduce ? { duration: 0 } : spring.snappy}\n                />\n              ) : null}\n              {preset.label}\n            </button>\n          </li>\n        ))}\n      </LayoutGroup>\n    </ul>\n  );\n}\n\n/** The trigger, drawn like Select's, and the popover round whatever the picker puts in it */\nfunction PickerFrame({\n  open,\n  onOpenChange,\n  text,\n  empty,\n  size = \"md\",\n  align,\n  dialogLabel,\n  className,\n  children,\n  ...props\n}: Omit<ComponentProps<\"button\">, \"children\"> & {\n  open: boolean;\n  onOpenChange: (open: boolean) => void;\n  text: string;\n  empty: boolean;\n  size?: keyof typeof triggerSizes;\n  align: \"start\" | \"center\" | \"end\";\n  dialogLabel: string;\n  children: ReactNode;\n}) {\n  const reduce = useReducedMotion() ?? false;\n  const content = useRef<HTMLDivElement>(null);\n\n  return (\n    <Popover open={open} onOpenChange={onOpenChange}>\n      <PopoverTrigger asChild>\n        <button\n          type=\"button\"\n          // A combobox that pops up a dialog (Radix adds aria-haspopup=\"dialog\" and aria-controls)\n          role=\"combobox\"\n          aria-expanded={open}\n          data-slot=\"date-picker-trigger\"\n          data-size={size}\n          data-placeholder={empty ? \"\" : undefined}\n          className={cn(\n            \"group flex w-full min-w-0 cursor-pointer items-center gap-2 rounded-lg border border-input bg-transparent text-start text-sm whitespace-nowrap shadow-xs\",\n            \"transition duration-(--duration-fast) ease-out\",\n            \"outline-ring focus-visible:border-ring focus-visible:outline-(length:--focus-ring-width) focus-visible:outline-offset-(--focus-ring-offset)\",\n            \"aria-invalid:border-destructive aria-invalid:outline-destructive\",\n            \"disabled:cursor-not-allowed disabled:opacity-(--opacity-disabled)\",\n            triggerSizes[size],\n            className,\n          )}\n          {...props}\n        >\n          <CalendarIcon aria-hidden className=\"size-(--size-icon-md) shrink-0 text-muted-foreground\" />\n          {/* Screen readers read this as the combobox's value; what's drawn swaps through the blur */}\n          <span data-slot=\"date-picker-value\" className=\"sr-only\">\n            {text}\n          </span>\n          <span aria-hidden className=\"grid min-w-0 flex-1\">\n            <AnimatePresence initial={false}>\n              <motion.span\n                key={text}\n                {...(reduce\n                  ? { initial: { opacity: 0 }, animate: { opacity: 1 }, exit: { opacity: 0 } }\n                  : swap)}\n                transition={\n                  reduce\n                    ? { duration: duration.fast }\n                    : { duration: duration.base, ease: ease.out, y: spring.snappy }\n                }\n                // Each text keeps its own colour as it leaves, so the placeholder goes out muted\n                className={cn(\"col-start-1 row-start-1 truncate\", empty && \"text-muted-foreground\")}\n              >\n                {text}\n              </motion.span>\n            </AnimatePresence>\n          </span>\n        </button>\n      </PopoverTrigger>\n      <PopoverContent\n        ref={content}\n        align={align}\n        aria-label={dialogLabel}\n        // Focus goes to the picked day (or today), not to the first button, as in the WAI-ARIA date picker\n        onOpenAutoFocus={(event) => {\n          event.preventDefault();\n          content.current?.querySelector<HTMLElement>(\"[data-slot=calendar-day][tabindex='0']\")?.focus();\n        }}\n        // Where two months or the presets don't fit, the calendar wraps under them\n        className=\"flex w-auto max-w-(--radix-popover-content-available-width) flex-wrap p-0\"\n      >\n        {children}\n      </PopoverContent>\n    </Popover>\n  );\n}\n\n/**\n * A date field: a trigger showing the picked day (or a placeholder) that opens a Calendar in a Popover.\n * Picking a day closes it. Give it a visible label (`<label htmlFor>`) or an aria-label.\n */\nfunction DatePicker(props: DatePickerProps) {\n  const {\n    value: valueProp,\n    defaultValue,\n    onChange,\n    presets,\n    name,\n    placeholder = \"Pick a date\",\n    locale = \"en-US\",\n    formatOptions = { dateStyle: \"medium\" },\n    min,\n    max,\n    disabledDates,\n    weekStartsOn,\n    numberOfMonths = 1,\n    today,\n    labels,\n    open: openProp,\n    defaultOpen,\n    onOpenChange,\n    align = \"start\",\n    ...trigger\n  } = props;\n  const controlled = \"value\" in props;\n  const [own, setOwn] = useState(defaultValue);\n  const value = controlled ? valueProp : own;\n  const picker = usePicker(openProp, defaultOpen, onOpenChange, value, numberOfMonths, today);\n\n  const commit = (next: Date | undefined) => {\n    if (!controlled) setOwn(next);\n    onChange?.(next);\n  };\n\n  return (\n    <>\n      <PickerFrame\n        open={picker.open}\n        onOpenChange={picker.setOpen}\n        text={value ? new Intl.DateTimeFormat(locale, formatOptions).format(value) : placeholder}\n        empty={!value}\n        align={align}\n        dialogLabel={labels?.dialog ?? \"Choose date\"}\n        {...trigger}\n      >\n        {presets?.length ? (\n          <PresetList\n            presets={presets}\n            label={labels?.presets ?? \"Presets\"}\n            onPick={(date) => {\n              commit(date);\n              picker.reveal(date);\n              picker.closeSoon();\n            }}\n          />\n        ) : null}\n        <Calendar\n          mode=\"single\"\n          // Picking the same day again keeps it and closes, rather than clearing the field\n          required\n          selected={value}\n          onSelect={(date) => {\n            commit(date);\n            picker.closeSoon();\n          }}\n          month={picker.month}\n          onMonthChange={picker.setMonth}\n          numberOfMonths={numberOfMonths}\n          min={min}\n          max={max}\n          disabled={disabledDates}\n          weekStartsOn={weekStartsOn}\n          locale={locale}\n          today={today}\n          labels={labels}\n        />\n      </PickerFrame>\n      {name ? <input type=\"hidden\" name={name} value={value ? keyOf(value) : \"\"} /> : null}\n    </>\n  );\n}\n\n/**\n * A date range field: a trigger showing the picked range (or a placeholder) that opens a Calendar in range\n * mode, two months side by side by default. It stays open while you pick. Give it a visible label or an\n * aria-label.\n */\nfunction DateRangePicker(props: DateRangePickerProps) {\n  const {\n    value: valueProp,\n    defaultValue,\n    onChange,\n    presets,\n    placeholder = \"Pick a date range\",\n    locale = \"en-US\",\n    formatOptions = { dateStyle: \"medium\" },\n    min,\n    max,\n    disabledDates,\n    weekStartsOn,\n    numberOfMonths = 2,\n    today,\n    labels,\n    open: openProp,\n    defaultOpen,\n    onOpenChange,\n    align = \"start\",\n    ...trigger\n  } = props;\n  const controlled = \"value\" in props;\n  const [own, setOwn] = useState(defaultValue);\n  const value = controlled ? valueProp : own;\n  const picker = usePicker(openProp, defaultOpen, onOpenChange, value?.from, numberOfMonths, today);\n  const from = value?.from;\n  const to = value?.to;\n  const format = new Intl.DateTimeFormat(locale, formatOptions);\n\n  const commit = (next: DateRange | undefined) => {\n    if (!controlled) setOwn(next);\n    onChange?.(next);\n  };\n\n  return (\n    <PickerFrame\n      open={picker.open}\n      onOpenChange={picker.setOpen}\n      // Intl writes a range the short way: \"Oct 12 – 18, 2026\"\n      text={from && to ? format.formatRange(from, to) : from ? `${format.format(from)} – …` : placeholder}\n      empty={!from}\n      align={align}\n      dialogLabel={labels?.dialog ?? \"Choose dates\"}\n      {...trigger}\n    >\n      {presets?.length ? (\n        <PresetList\n          presets={presets}\n          label={labels?.presets ?? \"Presets\"}\n          onPick={(range) => {\n            commit(range);\n            if (range.from) picker.reveal(range.from);\n          }}\n        />\n      ) : null}\n      <Calendar\n        mode=\"range\"\n        selected={value}\n        onSelect={commit}\n        month={picker.month}\n        onMonthChange={picker.setMonth}\n        numberOfMonths={numberOfMonths}\n        min={min}\n        max={max}\n        disabled={disabledDates}\n        weekStartsOn={weekStartsOn}\n        locale={locale}\n        today={today}\n        labels={labels}\n      />\n    </PickerFrame>\n  );\n}\n\nexport { DatePicker, DateRangePicker };\n"
    }
  ],
  "categories": [
    "forms"
  ],
  "docs": "Usage and examples: https://ui.fewtone.com/components/date-picker"
}
