{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "date-picker",
  "title": "Date picker",
  "description": "A date field and calendar popover on react-aria-components. Adapted from BoardUI (MIT).",
  "dependencies": [
    "@internationalized/date@^3.12.1",
    "@keyline-icons/react@^2.2.0",
    "motion@^12.23.12",
    "react-aria-components@^1.17.0"
  ],
  "registryDependencies": [
    "@khaeli/button",
    "@khaeli/popover",
    "@khaeli/utils"
  ],
  "files": [
    {
      "path": "registry/khaeli/ui/date-picker.tsx",
      "content": "\"use client\"\n\n/*\n * Adapted from BoardUI's free Date Picker, https://github.com/BoardUI/boardui\n * Copyright (c) 2026 Mertcan Dundar Esmergul (BoardUI)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\n * of the Software, and to permit persons to whom the Software is furnished to do\n * so, subject to the following conditions:\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\nimport * as React from \"react\"\nimport { CalendarIcon } from \"@keyline-icons/react\"\nimport {\n  Button as AriaButton,\n  Calendar as AriaCalendar,\n  CalendarCell,\n  CalendarGrid,\n  CalendarGridBody,\n  CalendarGridHeader,\n  CalendarHeaderCell,\n  CalendarStateContext,\n  I18nProvider,\n  type CalendarCellRenderProps,\n} from \"react-aria-components\"\nimport { CalendarDate, getLocalTimeZone, parseDate, today as todayIn } from \"@internationalized/date\"\nimport { AnimatePresence } from \"motion/react\"\nimport * as m from \"motion/react-m\"\nimport { cn } from \"@/lib/utils\"\n\nimport { Button } from \"@/components/ui/button\"\nimport { Popover, PopoverContent, PopoverTrigger } from \"@/components/ui/popover\"\n\n/*\n * BoardUI Date Picker (https://www.boardui.com/components/date-picker, Figma\n * \"Calendar_single\"): a month on a card inside a grey popover, an editable\n * DD/MM/YYYY chip, and Cancel/Apply, so a pick is pending until applied.\n * Ported onto this library: theme tokens for BoardUI's, `cn` for `cx`, and\n * the base-ui Popover for React Aria's, so it layers and dismisses correctly\n * inside the app's base-ui dialogs and popovers.\n *\n * Dates cross this module as ISO calendar dates (\"2026-10-21\"), the shape the\n * app stores and validates; React Aria works in `CalendarDate`, which has no\n * time zone, so no zone can shift a picked day.\n */\n\n/** en-SG formats, Monday first, whatever the browser's locale. */\nconst LOCALE = \"en-SG\"\nconst ISO_DATE = /^\\d{4}-\\d{2}-\\d{2}$/\n\nfunction toCalendarDate(value: string | null | undefined): CalendarDate | null {\n  if (!value || !ISO_DATE.test(value)) return null\n  try {\n    return parseDate(value)\n  } catch {\n    return null\n  }\n}\n\nfunction inRange(date: CalendarDate, min: CalendarDate | null, max: CalendarDate | null) {\n  return (!min || date.compare(min) >= 0) && (!max || date.compare(max) <= 0)\n}\n\n/**\n * A calendar day as the UTC midnight Date that formatters read with\n * `timeZone: \"UTC\"`. Unlike `toDate(zone)` this reads no clock, so a server\n * prerender (Next.js `cacheComponents`) never sees a current-time read, and no\n * zone offset can shift the printed day.\n */\nfunction utcDate({ year, month, day }: { year: number; month: number; day: number }) {\n  return new Date(Date.UTC(year, month - 1, day))\n}\n\n/** \"21 Oct 2026\", as the app's formatDate writes a calendar date. */\nconst LABEL = new Intl.DateTimeFormat(LOCALE, { day: \"numeric\", month: \"short\", year: \"numeric\", timeZone: \"UTC\" })\n\nfunction formatLabel(date: CalendarDate) {\n  return LABEL.format(utcDate(date))\n}\n\nfunction formatChipDate(date: CalendarDate) {\n  return `${String(date.day).padStart(2, \"0\")}/${String(date.month).padStart(2, \"0\")}/${date.year}`\n}\n\n/** Reads the chip's own DD/MM/YYYY back, or null when it isn't a date.\n *  CalendarDate constrains an impossible day-in-month (30/02) to the month's last. */\nfunction parseChipDate(text: string): CalendarDate | null {\n  const match = /^(\\d{1,2})\\/(\\d{1,2})\\/(\\d{4})$/.exec(text.trim())\n  if (!match) return null\n  const day = Number(match[1])\n  const month = Number(match[2])\n  const year = Number(match[3])\n  if (month < 1 || month > 12 || day < 1 || day > 31) return null\n  return new CalendarDate(year, month, day)\n}\n\n// ---- Month panel ----\n\n/** BoardUI's month-nav chevrons: a 16×16 glyph, 2px round-capped stroke. */\nfunction Chevron({ direction }: { direction: \"previous\" | \"next\" }) {\n  return (\n    <svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\">\n      <path\n        d={\n          direction === \"previous\"\n            ? \"M9 4L5.70711 7.29289C5.31658 7.68342 5.31658 8.31658 5.70711 8.70711L9 12\"\n            : \"M7 4L10.2929 7.29289C10.6834 7.68342 10.6834 8.31658 10.2929 8.70711L7 12\"\n        }\n        stroke=\"currentColor\"\n        strokeWidth=\"2\"\n        strokeLinecap=\"round\"\n      />\n    </svg>\n  )\n}\n\nconst NAV_BUTTON =\n  \"flex size-6 cursor-pointer items-center justify-center rounded-sm text-muted-foreground outline-none transition-colors duration-150 ease-out hover:bg-accent hover:text-foreground data-focus-visible:ring-2 data-focus-visible:ring-ring/60 data-disabled:pointer-events-none data-disabled:opacity-40\"\n\nconst CAPTION = new Intl.DateTimeFormat(LOCALE, { month: \"long\", year: \"numeric\", timeZone: \"UTC\" })\n\nfunction DayCell({\n  formattedDate,\n  isSelected,\n  isHovered,\n  isFocusVisible,\n  isDisabled,\n  isUnavailable,\n  isOutsideMonth,\n  isToday,\n}: CalendarCellRenderProps) {\n  if (isOutsideMonth) return <div className=\"size-8\" />\n\n  // The fill fades on opacity rather than mounting, so changing the pick is a\n  // plain CSS transition across every cell.\n  return (\n    <div\n      className={cn(\n        \"relative flex size-8 items-center justify-center rounded-lg transition-colors duration-100 ease-out\",\n        !isSelected && isHovered && \"bg-accent\",\n        isFocusVisible && \"ring-2 ring-ring/60 ring-inset\"\n      )}\n    >\n      <span\n        aria-hidden=\"true\"\n        className={cn(\n          \"absolute inset-0 rounded-lg bg-primary/25 transition-opacity duration-100 ease-out dark:bg-primary/45\",\n          isSelected ? \"opacity-100\" : \"opacity-0\"\n        )}\n      />\n      <span\n        className={cn(\n          \"relative text-base font-medium text-foreground tabular-nums\",\n          isToday && !isSelected && \"text-link\",\n          (isDisabled || isUnavailable) && \"text-subtle-foreground opacity-50\"\n        )}\n      >\n        {formattedDate}\n      </span>\n    </div>\n  )\n}\n\n/**\n * One month: title between the chevrons over the day grid. `bare` drops the\n * card (BoardUI's option for embedding the grid in a caller's own surface)\n * and the 12px column gap, so the grid is seven 32px cells (224px) and fits\n * menus and grid-cell editors.\n * Must render inside a React Aria `Calendar`.\n */\nfunction MonthPanel({ bare = false }: { bare?: boolean }) {\n  const state = React.useContext(CalendarStateContext)\n  const title = state ? CAPTION.format(utcDate(state.visibleRange.start)) : \"\"\n\n  return (\n    <div className={bare ? \"w-56 shrink-0\" : \"w-[326px] shrink-0 rounded-2xl bg-card p-[15px] shadow-control\"}>\n      <div className={cn(\"flex flex-col\", bare ? \"gap-3\" : \"gap-5\")}>\n        <div className=\"flex items-center justify-between\">\n          <AriaButton slot=\"previous\" className={NAV_BUTTON}>\n            <Chevron direction=\"previous\" />\n          </AriaButton>\n          <span className=\"flex-1 text-center text-base font-medium text-foreground\">{title}</span>\n          <AriaButton slot=\"next\" className={NAV_BUTTON}>\n            <Chevron direction=\"next\" />\n          </AriaButton>\n        </div>\n        <CalendarGrid\n          weekdayStyle=\"short\"\n          className={cn(\"self-start border-separate outline-none\", bare ? \"-my-1\" : \"-m-3\")}\n          style={{ borderSpacing: bare ? \"0 4px\" : \"12px 12px\" }}\n        >\n          <CalendarGridHeader>\n            {(day) => (\n              <CalendarHeaderCell className=\"size-6 pb-0 text-center text-base font-medium text-muted-foreground\">\n                {day.slice(0, 2)}\n              </CalendarHeaderCell>\n            )}\n          </CalendarGridHeader>\n          <CalendarGridBody>\n            {(date) => (\n              <CalendarCell date={date} className=\"cursor-pointer p-0 outline-none data-disabled:cursor-default\">\n                {(cell) => <DayCell {...cell} />}\n              </CalendarCell>\n            )}\n          </CalendarGridBody>\n        </CalendarGrid>\n      </div>\n    </div>\n  )\n}\n\n// ---- Calendar ----\n\ntype CalendarProps = {\n  className?: string\n  /** The picked day, as an ISO date. */\n  value?: string | null\n  onValueChange?: (value: string) => void\n  /** Earliest and latest pickable days, as ISO dates. */\n  min?: string\n  max?: string\n  /** Controlled visible month, for a caller that moves it (typed input). */\n  month?: Date\n  onMonthChange?: (month: Date) => void\n  \"aria-label\"?: string\n}\n\n/** The bare month grid, committing on every pick: for pickers that already sit in a menu. */\nfunction Calendar({\n  className,\n  value,\n  onValueChange,\n  min,\n  max,\n  month,\n  onMonthChange,\n  \"aria-label\": ariaLabel = \"Date\",\n}: CalendarProps) {\n  return (\n    <I18nProvider locale={LOCALE}>\n      <AriaCalendar\n        aria-label={ariaLabel}\n        firstDayOfWeek=\"mon\"\n        value={toCalendarDate(value)}\n        onChange={(date) => onValueChange?.(date.toString())}\n        minValue={toCalendarDate(min)}\n        maxValue={toCalendarDate(max)}\n        // React Aria shows the month of its focused day, so a controlled month\n        // drives that day; a Date crosses as its local calendar day.\n        focusedValue={month ? new CalendarDate(month.getFullYear(), month.getMonth() + 1, month.getDate()) : undefined}\n        onFocusChange={onMonthChange ? (date) => onMonthChange(date.toDate(getLocalTimeZone())) : undefined}\n        className={cn(\"p-3\", className)}\n      >\n        <MonthPanel bare />\n      </AriaCalendar>\n    </I18nProvider>\n  )\n}\n\n// ---- DatePicker ----\n\n/** One editable DD/MM/YYYY chip. Keeps its own draft while typing; commits on\n *  blur or Enter, reverting when the text isn't a date. Enter leaves the focus\n *  in the chip. */\nfunction DateChipInput({ date, onCommit }: { date: CalendarDate; onCommit: (date: CalendarDate) => void }) {\n  const formatted = formatChipDate(date)\n  const [text, setText] = React.useState(formatted)\n\n  React.useEffect(() => {\n    setText(formatted)\n  }, [formatted])\n\n  function commit() {\n    const parsed = parseChipDate(text)\n    if (parsed) onCommit(parsed)\n    else setText(formatted)\n  }\n\n  return (\n    <input\n      type=\"text\"\n      dir=\"ltr\"\n      inputMode=\"numeric\"\n      enterKeyHint=\"done\"\n      aria-label=\"Date, DD/MM/YYYY\"\n      value={text}\n      onChange={(event) => setText(event.target.value)}\n      onBlur={commit}\n      onKeyDown={(event) => {\n        if (event.key === \"Enter\") {\n          event.preventDefault()\n          commit()\n        }\n        if (event.key === \"Escape\") setText(formatted)\n      }}\n      className=\"w-[104px] rounded-control border border-input bg-card px-2 py-1.5 text-base font-medium text-foreground tabular-nums shadow-xs outline-none transition-colors duration-100 ease-out focus-visible:border-ring max-md:w-32\"\n    />\n  )\n}\n\ninterface DatePickerProps {\n  /** Id of the trigger, so a `<label htmlFor>` names the picker. */\n  id?: string\n  /** Submits the ISO date with the surrounding form under this name. */\n  name?: string\n  /** Controlled ISO date; `null` is empty. Omit for an uncontrolled picker. */\n  value?: string | null\n  defaultValue?: string\n  onValueChange?: (value: string | null) => void\n  min?: string\n  max?: string\n  required?: boolean\n  disabled?: boolean\n  /** Show Clear in the popover. Defaults to `!required`. */\n  clearable?: boolean\n  placeholder?: string\n  /**\n   * `field` (default) reads like the inputs beside it. `ghost` reads like an\n   * InlineEdit value in a record's attribute list: no chrome, no icon.\n   */\n  variant?: \"field\" | \"ghost\"\n  className?: string\n  /** Focus the trigger on mount, as `autoFocus` does on an input. */\n  autoFocus?: boolean\n  \"aria-label\"?: string\n  \"aria-describedby\"?: string\n  \"aria-invalid\"?: boolean\n}\n\n/**\n * A date field: a trigger that reads like the inputs beside it (foundation.css\n * gives `date-picker-trigger` the field rules) over BoardUI's month popover.\n * Picking a day or typing in the chip only stages it; Apply commits, Cancel\n * or dismissing discards. Native form validation still works through `name`\n * and `required`.\n */\nfunction DatePicker({\n  id,\n  name,\n  value: controlled,\n  defaultValue,\n  onValueChange,\n  min,\n  max,\n  required,\n  disabled,\n  clearable = !required,\n  placeholder = \"Pick a date\",\n  variant = \"field\",\n  className,\n  autoFocus,\n  ...aria\n}: DatePickerProps) {\n  const [open, setOpen] = React.useState(false)\n  const [uncontrolled, setUncontrolled] = React.useState<string | null>(defaultValue ?? null)\n  const value = controlled !== undefined ? controlled : uncontrolled\n  const committed = toCalendarDate(value)\n  const minDate = toCalendarDate(min)\n  const maxDate = toCalendarDate(max)\n\n  const [pending, setPending] = React.useState<CalendarDate | null>(committed)\n  // Controlled so a date typed into the chip also moves the grid to its month.\n  // Set when the popover opens, so a closed picker never reads today's date.\n  const [focused, setFocused] = React.useState<CalendarDate | null>(committed)\n  const canApply = pending !== null && inRange(pending, minDate, maxDate)\n  const triggerRef = React.useRef<HTMLButtonElement>(null)\n\n  function openChange(next: boolean) {\n    if (next) {\n      setPending(committed)\n      setFocused(committed ?? todayIn(getLocalTimeZone()))\n    }\n    setOpen(next)\n  }\n\n  function commit(next: CalendarDate | null) {\n    const iso = next ? next.toString() : null\n    if (controlled === undefined) setUncontrolled(iso)\n    onValueChange?.(iso)\n    setOpen(false)\n  }\n\n  return (\n    <Popover open={open} onOpenChange={openChange}>\n      <span className={cn(\"relative inline-flex min-w-0\", className)}>\n        <PopoverTrigger\n          render={\n            <button\n              ref={triggerRef}\n              type=\"button\"\n              // A labelled combobox announces its text as the value: \"Drafted\n              // from, combobox, 21 Oct 2026\", where a button would drop it.\n              role=\"combobox\"\n              id={id}\n              disabled={disabled}\n              autoFocus={autoFocus}\n              data-slot={variant === \"field\" ? \"date-picker-trigger\" : undefined}\n              {...aria}\n              className={cn(\n                variant === \"field\"\n                  ? \"flex h-7 w-full min-w-0 items-center gap-2 rounded-md border border-input bg-transparent px-2 text-left text-sm outline-none disabled:pointer-events-none disabled:opacity-50\"\n                  : \"flex h-8 w-full min-w-0 items-center rounded-nav px-2 text-left text-base font-medium outline-none transition-[background-color] duration-100 ease-out hover:bg-accent focus-visible:bg-accent focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none\",\n                !committed && (variant === \"field\" ? \"text-muted-foreground\" : \"text-subtle-foreground\")\n              )}\n            >\n              {variant === \"field\" ? (\n                <CalendarIcon aria-hidden=\"true\" className=\"size-4 shrink-0 text-subtle-foreground\" />\n              ) : null}\n              <span className=\"min-w-0 flex-1 truncate tabular-nums\">{committed ? formatLabel(committed) : placeholder}</span>\n            </button>\n          }\n        />\n        {name || required ? (\n          // Carries the value into FormData and lets `required` block submit;\n          // the browser's message anchors over the trigger. The browser also\n          // focuses the control it rejects: that focus is handed to the trigger.\n          <input\n            tabIndex={-1}\n            onFocus={() => triggerRef.current?.focus()}\n            aria-hidden=\"true\"\n            name={name}\n            required={required}\n            disabled={disabled}\n            value={value ?? \"\"}\n            onChange={() => {}}\n            className=\"pointer-events-none absolute inset-0 opacity-0\"\n          />\n        ) : null}\n      </span>\n      <PopoverContent\n        align=\"start\"\n        aria-label={aria[\"aria-label\"] ?? \"Choose date\"}\n        // On phones the month sets the width and the actions wrap under the\n        // chip; side by side they are wider than a 390px screen. The extra\n        // row makes the popover taller, so it scrolls where it would be cut.\n        className=\"w-auto gap-0 rounded-3xl bg-secondary p-0 text-foreground shadow-popover ring-0 max-md:max-h-(--available-height) max-md:w-min max-md:overflow-y-auto motion-safe:data-starting-style:blur-[2px] motion-safe:data-ending-style:blur-[2px]\"\n      >\n        <I18nProvider locale={LOCALE}>\n          <AriaCalendar\n            aria-label={aria[\"aria-label\"] ?? \"Date\"}\n            autoFocus\n            firstDayOfWeek=\"mon\"\n            value={pending}\n            onChange={setPending}\n            focusedValue={focused ?? undefined}\n            onFocusChange={setFocused}\n            minValue={minDate}\n            maxValue={maxDate}\n            className=\"flex flex-col p-2 pb-3\"\n          >\n            <MonthPanel />\n            <div className=\"flex items-center justify-between gap-2 px-4 pt-3 max-md:flex-wrap\">\n              <div>\n                <AnimatePresence initial={false}>\n                  {pending ? (\n                    <m.div\n                      key=\"date-summary\"\n                      initial={{ opacity: 0, y: -12 }}\n                      animate={{ opacity: 1, y: 0 }}\n                      exit={{ opacity: 0, y: -12 }}\n                      transition={{ duration: 0.25, ease: [0.34, 1.2, 0.64, 1] }}\n                    >\n                      <DateChipInput\n                        date={pending}\n                        onCommit={(date) => {\n                          setPending(date)\n                          setFocused(date)\n                        }}\n                      />\n                    </m.div>\n                  ) : null}\n                </AnimatePresence>\n              </div>\n              <div className=\"flex items-center gap-2 max-md:ml-auto\">\n                {clearable && value ? (\n                  <Button variant=\"ghost\" className=\"text-muted-foreground\" onClick={() => commit(null)}>\n                    Clear\n                  </Button>\n                ) : null}\n                <Button variant=\"outline\" onClick={() => setOpen(false)}>\n                  Cancel\n                </Button>\n                <Button disabled={!canApply} onClick={() => commit(pending)}>\n                  Apply\n                </Button>\n              </div>\n            </div>\n          </AriaCalendar>\n        </I18nProvider>\n      </PopoverContent>\n    </Popover>\n  )\n}\n\nexport { Calendar, DatePicker, type CalendarProps, type DatePickerProps }\n",
      "type": "registry:ui"
    }
  ],
  "docs": "Install @khaeli/foundation first: this item's styling lives in its tokens and [data-slot] rules.",
  "type": "registry:ui"
}