{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "date-range",
  "title": "Date range picker",
  "description": "Range calendar on react-day-picker (pinned) styled as a Keyline grid: a flooded range with ink ends, row-break notches, hover and keyboard preview, hatched unavailable days, month and year dropdowns, min/max, presets and a day count.",
  "dependencies": [
    "@base-ui/react@1.9.0",
    "react-day-picker@9.14.0"
  ],
  "registryDependencies": [
    "@keyline-ui/keyline",
    "utils",
    "@keyline-ui/keyline-scope",
    "@keyline-ui/keyline-render",
    "@keyline-ui/keyline-motion",
    "@keyline-ui/select",
    "@keyline-ui/calendar"
  ],
  "files": [
    {
      "path": "src/registry/keyline/ui/date-range.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { Popover } from \"@base-ui/react/popover\";\nimport { Select as SelectPrimitive } from \"@base-ui/react/select\";\nimport { Field as FieldPrimitive } from \"@base-ui/react/field\";\n\nimport {\n  DayPicker,\n  type ClassNames,\n  type DayButtonProps,\n  type DropdownProps,\n  type Matcher,\n  type Modifiers,\n} from \"react-day-picker\";\n\nimport { cn } from \"@/lib/utils\";\nimport { mergeProps } from \"@base-ui/react/merge-props\";\nimport { useRender } from \"@base-ui/react/use-render\";\nimport { dockGeometry, scopeProps, useDomDirection, useKeylineScope } from \"../lib/keyline-scope\";\nimport { resolveClassName, resolveStyle, type PartProps } from \"../lib/keyline-render\";\nimport { floodFromPointer } from \"../lib/keyline-motion\";\nimport { SelectItem, SelectList, SelectPopup, SelectRoot } from \"./select\";\nimport {\n  between,\n  countAvailable,\n  formatRange,\n  order,\n  sameDay,\n  sod,\n  type DateRange,\n  type Unavailable,\n} from \"../lib/calendar\";\n\nexport type { DateRange };\nexport { formatRange, countAvailable };\n\ntype Bounds = {\n  /** Earliest and latest choosable day. Navigation stops at their months; days outside are disabled. */\n  min?: Date;\n  max?: Date;\n};\n\nconst Chevron = ({\n  orientation = \"left\",\n  className,\n}: {\n  orientation?: \"up\" | \"down\" | \"left\" | \"right\";\n  className?: string;\n}) => (\n  <svg\n    viewBox=\"0 0 16 16\"\n    width=\"16\"\n    height=\"16\"\n    fill=\"none\"\n    stroke=\"currentColor\"\n    strokeWidth=\"1.75\"\n    strokeLinecap=\"square\"\n    className={className}\n    aria-hidden\n  >\n    <path\n      d={\n        {\n          left: \"m10 4-4 4 4 4\",\n          right: \"m6 4 4 4-4 4\",\n          up: \"m4 10 4-4 4 4\",\n          down: \"m4 6 4 4 4-4\",\n        }[orientation]\n      }\n    />\n  </svg>\n);\n\n/* ------------------------------------------------------------------ calendar styles */\n\n/*\n * The calendar is react-day-picker's DOM. Every element it renders takes a class from its `classNames` map, so the\n * map carries Keyline's utilities and nothing needs a stylesheet: a month of [‹ prev] [month ▾ · year ▾] [next ›] over\n * a table grid, seams on the table cells, and the day button filling its cell and carrying the flood. --kl-day is the\n * day's size (34px under compact density). The calendar sets Keyline's type and ink itself: on its own it is the\n * outermost Keyline element, and its root carries no foundation class.\n */\nconst calendarRoot = cn(\n  \"block w-[calc(7*var(--kl-day))] text-kl-ink [--kl-day:44px] in-data-[kl-density=compact]:[--kl-day:34px]\",\n  \"font-(family-name:--kl-font) text-(length:--kl-fs)/[1.4] tabular-nums antialiased\",\n);\n\n/** A nav arrow and a month/year cell draw their own ring: neither carries a foundation class. */\nconst ownRing =\n  \"focus-visible:outline-(length:--kl-ring) focus-visible:outline-solid focus-visible:outline-kl-focus focus-visible:outline-offset-(--kl-ring-in)\";\n\n/** The month and year cells' title. */\nconst title = \"inline-flex min-h-10 items-center gap-1 px-2 text-[15px] font-(--kl-weight-display) whitespace-nowrap\";\n\nconst nav = cn(\n  \"grid min-h-10 cursor-pointer place-items-center border-b-(length:--kl-k1) border-b-kl-seam bg-none p-0 text-inherit\",\n  \"hover:not-aria-disabled:bg-kl-tint active:not-aria-disabled:bg-kl-press active:not-aria-disabled:*:translate-y-px\",\n  \"aria-disabled:cursor-default aria-disabled:text-kl-dis\",\n  ownRing,\n);\n\n/** A blank cell before the first or after the last day (outside the month): a day's height, no button. */\nconst blank = \"h-[calc(var(--kl-day)-var(--kl-k1))]\";\n\nconst classNames: Partial<ClassNames> = {\n  root: \"\",\n  months: \"\",\n  month: \"grid grid-cols-[var(--kl-day)_minmax(0,1fr)_var(--kl-day)]\",\n  month_caption: cn(\n    \"relative flex min-w-0 justify-center border-b-(length:--kl-k1) border-b-kl-seam\",\n    \"border-x-(length:--kl-k1) border-x-kl-line-soft\",\n  ),\n  // the two cells share the whole header between the arrows: each is the target edge to edge\n  dropdowns: \"flex min-w-0 flex-1\",\n  caption_label: title,\n  button_previous: nav,\n  button_next: nav,\n  chevron: \"\",\n  month_grid: \"col-span-full w-full table-fixed border-separate border-spacing-0\",\n  weekdays: \"\",\n  weekday: cn(\n    \"h-[26px] border-b-(length:--kl-k1) border-b-kl-seam p-0 text-center text-kl-ink-2\",\n    \"font-(family-name:--kl-font-mono) text-[11px]/none font-medium not-italic normal-nums\",\n  ),\n  weeks: \"\",\n  week: \"\",\n  // seams on the cells: the soft rule after each but the last of a row, and under each but the last row\n  day: cn(\n    \"border-e-(length:--kl-k1) border-b-(length:--kl-k1) border-e-kl-line-soft border-b-kl-line-soft p-0\",\n    \"last:border-e-0 [tr:last-child>&]:border-b-0\",\n  ),\n  day_button: \"\",\n  hidden: blank,\n  outside: blank,\n};\n\n/**\n * A day (and a time slot, DateTimePicker's): a flood cell (a press grows it from the press point; on is ink for a\n * chosen day or a range end, yellow inside a range), hatched and struck when unavailable, a lighter yellow while a\n * range is previewed, and a notch pointing on where a range breaks across week rows. It sets no fill or ink of its\n * own beyond hover: the flood's state rules own those. Its label is `dayLabel`.\n */\nconst dayStyles = cn(\n  \"group/day kl-flood relative grid h-[calc(var(--kl-day)-var(--kl-k1))] w-full cursor-pointer place-items-center p-0\",\n  \"font-(family-name:--kl-font) text-[15px] font-medium\",\n  \"hover:not-data-in-range:not-data-unavailable:bg-kl-tint\",\n  \"focus-visible:z-2 focus-visible:outline-offset-(--kl-ring-in)\",\n  \"data-unavailable:cursor-not-allowed data-unavailable:bg-(image:--kl-hatch) data-unavailable:text-kl-dis\",\n  \"data-unavailable:data-in-range:bg-[color-mix(in_oklab,var(--kl-yellow)_35%,var(--kl-cell))]\",\n  \"data-unavailable:data-in-range:text-kl-ink-2\",\n  \"data-preview:not-[.kl-sig-ink]:[--kl-fc:color-mix(in_oklab,var(--kl-yellow)_45%,var(--kl-cell))]\",\n  // row-break rule: a range cut by the frame edge carries a notch pointing in reading direction\n  \"[&:is([data-cont-next],[data-cont-prev])]:after:absolute [&:is([data-cont-next],[data-cont-prev])]:after:top-[calc(50%-6px)]\",\n  \"[&:is([data-cont-next],[data-cont-prev])]:after:size-0\",\n  \"[&:is([data-cont-next],[data-cont-prev])]:after:border-y-[6px] [&:is([data-cont-next],[data-cont-prev])]:after:border-y-transparent\",\n  \"[&:is([data-cont-next],[data-cont-prev])]:after:border-s-[6px] [&:is([data-cont-next],[data-cont-prev])]:after:border-s-kl-ink\",\n  \"data-cont-next:after:end-0 data-cont-prev:after:start-0\",\n  \"forced-colors:[&:is([data-cont-next],[data-cont-prev])]:after:forced-color-adjust-none\",\n  \"forced-colors:[&:is([data-cont-next],[data-cont-prev])]:after:border-s-[CanvasText]\",\n  \"forced-colors:data-unavailable:text-[GrayText]\",\n);\n\n/** The day's numeral (or the slot's time): travels 1px under a press, underlined today, struck when unavailable. */\nconst dayLabel = cn(\n  \"group-[:active:not([data-unavailable])]/day:translate-y-px\",\n  \"group-data-today/day:border-b-[3px] group-data-today/day:border-b-current group-data-today/day:pb-px group-data-today/day:leading-none\",\n  \"group-data-unavailable/day:line-through group-data-unavailable/day:decoration-[1.5px]\",\n);\n\n/** The calendar's look, for a component that renders react-day-picker or a day-like cell itself. */\nconst calendarStyles = { root: calendarRoot, day: dayStyles, dayLabel, classNames };\n\n/** The day cell's button: Keyline's flood, hatch, notch and today mark, read from DayPicker's modifiers. */\nfunction DayButton({ day, modifiers, className, children, ...props }: DayButtonProps) {\n  const ref = React.useRef<HTMLButtonElement>(null);\n  const focused = modifiers[\"focused\"];\n  React.useEffect(() => {\n    if (focused) ref.current?.focus();\n  }, [focused]);\n  const m = modifiers as Record<string, boolean>;\n  const flag = (b: boolean | undefined) => (b ? \"\" : undefined);\n  return (\n    <button\n      ref={ref}\n      {...props}\n      // the flood (and its seed under a held press) starts where the day was pressed\n      onPointerDown={(e) => {\n        props.onPointerDown?.(e);\n        if (!m[\"disabled\"]) floodFromPointer(e);\n      }}\n      aria-current={m[\"today\"] ? \"date\" : undefined}\n      className={cn(dayStyles, m[\"kl_ink\"] && !m[\"disabled\"] && \"kl-sig-ink\", className)}\n      data-kl-flood=\"manual\"\n      data-kl-on={flag(m[\"kl_on\"] && !m[\"disabled\"])}\n      data-preview={flag(m[\"kl_preview\"])}\n      data-unavailable={flag(m[\"disabled\"])}\n      data-in-range={flag(m[\"kl_in\"])}\n      data-end={flag(m[\"kl_end\"])}\n      data-cont-prev={flag(m[\"kl_cont_prev\"])}\n      data-cont-next={flag(m[\"kl_cont_next\"])}\n      data-today={flag(m[\"today\"])}\n    >\n      <span className={dayLabel}>{children}</span>\n    </button>\n  );\n}\n\n/**\n * Month and year as cells of the calendar's header, each opening Keyline's Select list docked under it (Base UI\n * Select: typeahead, arrows, Home/End, Escape back to the cell). DayPicker hands over its options and a\n * native-select change handler; the chosen value is passed back in that shape.\n */\nfunction Dropdown({ options = [], value, onChange, disabled, \"aria-label\": ariaLabel }: DropdownProps) {\n  const items = React.useMemo(() => Object.fromEntries(options.map((o) => [String(o.value), o.label])), [options]);\n  const choose = (v: string | null) => {\n    if (v != null)\n      onChange?.({\n        target: { value: v },\n        currentTarget: { value: v },\n      } as unknown as React.ChangeEvent<HTMLSelectElement>);\n  };\n  // Keyline's Select (its own Field, so inside a DatePicker that is a Form's field it never registers as that\n  // field's control); only the trigger is the calendar's: the whole header cell is the button. Day-picker passes\n  // every month with the ones out of bounds disabled, so it is a choice only when two can be chosen. The field steps\n  // aside (display: contents): its trigger is the cell.\n  return (\n    <FieldPrimitive.Root\n      data-slot=\"select\"\n      data-kl-layout=\"cell\"\n      disabled={disabled || options.filter((o) => !o.disabled).length < 2}\n      className=\"kl-field contents\"\n    >\n      <SelectRoot<string>\n        items={items}\n        value={value == null ? null : String(value)}\n        onValueChange={choose}\n        disabled={disabled || options.filter((o) => !o.disabled).length < 2}\n      >\n        <SelectPrimitive.Trigger\n          aria-label={ariaLabel}\n          data-slot=\"calendar-dropdown\"\n          className={cn(\n            \"group/cal-dd m-0 flex min-w-0 flex-auto cursor-pointer items-center justify-center bg-none p-0 pe-2\",\n            \"font-(family-name:--kl-font) text-inherit\",\n            // the year cell after the month cell: a soft seam between them\n            \"[:is([data-slot=select]+[data-slot=select])>&]:border-s-(length:--kl-k1)\",\n            \"[:is([data-slot=select]+[data-slot=select])>&]:border-s-kl-line-soft\",\n            \"hover:not-disabled:not-data-popup-open:bg-kl-tint\",\n            \"data-popup-open:bg-kl-inverse data-popup-open:text-kl-on-inverse\",\n            ownRing,\n            \"focus-visible:z-1\",\n            // one choice (bounds inside a single year) is a label, not a list: no caret, nothing to open\n            \"disabled:cursor-default disabled:pe-0\",\n            \"forced-colors:data-popup-open:bg-[Highlight] forced-colors:data-popup-open:text-[HighlightText]\",\n            \"forced-colors:data-popup-open:forced-color-adjust-none\",\n          )}\n        >\n          <SelectPrimitive.Value className={title} />\n          <SelectPrimitive.Icon\n            className={cn(\n              \"flex-none text-kl-ink-2 group-disabled/cal-dd:hidden group-data-popup-open/cal-dd:text-inherit\",\n            )}\n          >\n            <Chevron orientation=\"down\" />\n          </SelectPrimitive.Icon>\n        </SelectPrimitive.Trigger>\n        {/* a narrower minimum and a shorter list than a field's */}\n        <SelectPopup layout=\"cell\" className=\"max-h-[min(var(--available-height),320px)] [--kl-dock-w:9rem]\">\n          <SelectList>\n            {options.map((o) => (\n              <SelectItem key={o.value} value={String(o.value)} disabled={o.disabled}>\n                {o.label}\n              </SelectItem>\n            ))}\n          </SelectList>\n        </SelectPopup>\n      </SelectRoot>\n    </FieldPrimitive.Root>\n  );\n}\n\n/**\n * Everything both calendars hand DayPicker: Keyline's class names and day button, Intl wording for any\n * BCP 47 locale (DayPicker's own formatters want a date-fns locale object), month and year dropdowns, the\n * DOM's reading direction (arrow keys follow it), and min/max as navigation bounds plus disabled days.\n */\nfunction useDayPicker({\n  locale,\n  weekStartsOn,\n  today,\n  min,\n  max,\n  isDateUnavailable,\n  anchorMonth,\n  label,\n}: Bounds & {\n  locale: string;\n  weekStartsOn: number;\n  today: Date;\n  isDateUnavailable?: Unavailable;\n  anchorMonth: Date;\n  label: (d: Date, m: Modifiers) => string;\n}) {\n  const wrap = React.useRef<HTMLDivElement>(null);\n  const [dir] = useDomDirection(wrap);\n  const f = React.useMemo(\n    () => ({\n      caption: new Intl.DateTimeFormat(locale, {\n        month: \"long\",\n        year: \"numeric\",\n      }),\n      month: new Intl.DateTimeFormat(locale, { month: \"long\" }),\n      year: new Intl.DateTimeFormat(locale, { year: \"numeric\" }),\n      wdShort: new Intl.DateTimeFormat(locale, { weekday: \"short\" }),\n      wdNarrow: new Intl.DateTimeFormat(locale, { weekday: \"narrow\" }),\n      wdLong: new Intl.DateTimeFormat(locale, { weekday: \"long\" }),\n      full: new Intl.DateTimeFormat(locale, {\n        weekday: \"long\",\n        day: \"numeric\",\n        month: \"long\",\n        year: \"numeric\",\n      }),\n    }),\n    [locale],\n  );\n  // ten years either side of what is shown, unless bounded: the year dropdown's span\n  const y = anchorMonth.getFullYear();\n  const startMonth = min ?? new Date(Math.min(y, today.getFullYear()) - 10, 0, 1);\n  const endMonth = max ?? new Date(Math.max(y, today.getFullYear()) + 10, 11, 31);\n  const disabled: Matcher[] = [];\n  if (isDateUnavailable) disabled.push((d: Date) => !!isDateUnavailable(d));\n  if (min) disabled.push({ before: sod(min) });\n  if (max) disabled.push({ after: sod(max) });\n  const props = {\n    dir,\n    lang: locale,\n    today,\n    weekStartsOn: weekStartsOn as 0 | 1 | 2 | 3 | 4 | 5 | 6,\n    startMonth,\n    endMonth,\n    disabled,\n    captionLayout: \"dropdown\" as const,\n    navLayout: \"around\" as const,\n    classNames,\n    components: { DayButton, Chevron, Dropdown },\n    formatters: {\n      formatCaption: (d: Date) => f.caption.format(d),\n      formatMonthDropdown: (d: Date) => f.month.format(d),\n      formatYearDropdown: (d: Date) => f.year.format(d),\n      // \"Mon\" where it fits a column; locales whose short names are long (ar: \"الاثنين\") use the narrow form\n      formatWeekdayName: (d: Date) => {\n        const s = f.wdShort.format(d);\n        // oxlint-disable-next-line typescript/no-misused-spread -- counts code points, which is the width measure wanted here\n        return [...s].length > 3 ? f.wdNarrow.format(d) : s;\n      },\n    },\n    labels: {\n      labelGrid: (d: Date) => f.caption.format(d),\n      labelPrevious: () => \"Previous month\",\n      labelNext: () => \"Next month\",\n      labelMonthDropdown: () => \"Month\",\n      labelYearDropdown: () => \"Year\",\n      labelWeekday: (d: Date) => f.wdLong.format(d),\n      labelDayButton: (d: Date, m: Modifiers) => {\n        const why = isDateUnavailable?.(d);\n        const out = min && d < sod(min) ? \"before the first date\" : max && d > sod(max) ? \"after the last date\" : \"\";\n        return [\n          f.full.format(d),\n          label(d, m),\n          why ? `unavailable${typeof why === \"string\" ? ` (${why})` : \"\"}` : out ? `unavailable (${out})` : \"\",\n        ]\n          .filter(Boolean)\n          .join(\", \");\n      },\n    },\n  };\n  return { wrap, props };\n}\n\ntype RangeCalendarProps = Bounds & {\n  value: DateRange | null;\n  onValueChange: (r: DateRange) => void;\n  isDateUnavailable?: Unavailable;\n  today?: Date;\n  defaultMonth?: Date;\n  weekStartsOn?: number;\n  locale?: string;\n  className?: string;\n  /** Called when the user presses Escape with no pending start (lets a popover close). */\n  onEscape?: () => void;\n};\n\n/**\n * Keyline range calendar on react-day-picker (the grid, keyboard, focus and month navigation are the\n * library's). The committed range FLOODS yellow, endpoints flood ink. Where the range breaks across week\n * rows, the cut cells carry a notch pointing in reading direction (\"continues\"). Unavailable days are\n * hatched, disabled and skipped by the arrow keys. A press or Enter sets the start, then the end; moving\n * after the start (pointer or keys) previews the range; Escape drops the pending start.\n */\nfunction RangeCalendar({\n  value,\n  onValueChange,\n  isDateUnavailable,\n  today = sod(new Date()),\n  defaultMonth,\n  weekStartsOn = 1,\n  locale = \"en-GB\",\n  min,\n  max,\n  className,\n  onEscape,\n}: RangeCalendarProps) {\n  const [anchor, setAnchor] = React.useState<Date | null>(null);\n  const [end, setEnd] = React.useState<Date | null>(null);\n  const preview = anchor ? order(anchor, end ?? anchor) : null;\n  const shown = preview ?? value;\n  const startMonth = sod(defaultMonth ?? value?.from ?? today);\n  const inR = (d: Date) => !!shown && between(d, shown.from, shown.to);\n  const role = (d: Date) => {\n    if (!shown || !inR(d)) return \"\";\n    const r = sameDay(shown.from, shown.to)\n      ? \"range start and end\"\n      : sameDay(d, shown.from)\n        ? \"range start\"\n        : sameDay(d, shown.to)\n          ? \"range end\"\n          : \"in range\";\n    return preview ? `${r}, preview` : r;\n  };\n  const { wrap, props } = useDayPicker({\n    locale,\n    weekStartsOn,\n    today,\n    min,\n    max,\n    isDateUnavailable,\n    anchorMonth: startMonth,\n    label: role,\n  });\n  const col = (d: Date) => (d.getDay() - weekStartsOn + 7) % 7;\n  return (\n    <div\n      ref={wrap}\n      data-slot=\"range-calendar\"\n      className={cn(calendarRoot, className)}\n      data-pending={anchor ? \"\" : undefined}\n      onPointerLeave={() => anchor && setEnd(null)}\n    >\n      <DayPicker\n        {...props}\n        mode=\"range\"\n        selected={shown ?? undefined}\n        onSelect={() => {}}\n        defaultMonth={startMonth}\n        modifiers={{\n          kl_in: inR,\n          kl_on: inR,\n          kl_preview: (d: Date) => !!preview && inR(d),\n          kl_end: (d: Date) => !!shown && (sameDay(d, shown.from) || sameDay(d, shown.to)),\n          kl_ink: (d: Date) => !!shown && (sameDay(d, shown.from) || sameDay(d, shown.to)),\n          kl_cont_prev: (d: Date) => inR(d) && col(d) === 0 && !!shown && d > shown.from,\n          kl_cont_next: (d: Date) => inR(d) && col(d) === 6 && !!shown && d < shown.to,\n        }}\n        onDayClick={(d, m) => {\n          if (m[\"disabled\"]) return;\n          if (!anchor) {\n            setAnchor(d);\n            setEnd(d);\n          } else {\n            onValueChange(order(anchor, d));\n            setAnchor(null);\n            setEnd(null);\n          }\n        }}\n        onDayMouseEnter={(d, m) => anchor && !m[\"disabled\"] && setEnd(d)}\n        onDayFocus={(d) => anchor && setEnd(d)}\n        onDayKeyDown={(_, __, e) => {\n          if (e.key !== \"Escape\" || !(anchor || onEscape)) return;\n          e.preventDefault();\n          e.stopPropagation();\n          if (anchor) {\n            setAnchor(null);\n            setEnd(null);\n          } else onEscape?.();\n        }}\n      />\n    </div>\n  );\n}\n\n/* ------------------------------------------------------------------ picker parts */\n\n/*\n * The pickers' look, shared by DateRangePicker's parts here and DatePicker's in date-picker.tsx (each names its own\n * parts and slots):\n *\n *   Stay\n *   ┌────┬───────────────────────────────┬────────┐\n *   │ ▦  │ 12 – 18 Nov 2026               │ 7 days │   trigger: a field frame of cells (affix · value · count)\n *   ├────┴───────────────────────────────┴────────┤\n *   │ calendar …                                   │   popup: docked to the trigger, seven days wide\n *   ├──────────┬───────────────────────────────────┤\n *   │ 7 DAYS   │ 12 – 18 Nov 2026                  │   footer: total · caption\n *   ├──────────┴──────┬────────────────────────────┤\n *   │ This week        │ Next week                  │   presets: a row of key cells\n *   └──────────────────┴────────────────────────────┘\n */\nconst pickerStyles = {\n  /** The trigger: a field frame of cells. Its own edge takes keyboard focus; it answers a press before the popup\n   * unfolds, and while open its edge is the plain line (the popup continues it). */\n  trigger: cn(\n    \"kl-ctl kl-cells kl-field-frame kl-edge w-full cursor-pointer p-0 text-start font-(family-name:--kl-font) text-inherit\",\n    \"data-popup-open:not-in-data-invalid:border-kl-line\",\n    // the old trigger rule lost its pointer to the field's disabled frame rule; a utility would win, so state it here\n    \"data-disabled:cursor-not-allowed\",\n    \"active:not-data-disabled:not-disabled:bg-kl-press\",\n  ),\n  /** The calendar glyph's affix cell. */\n  affix: \"kl-field-affix\",\n  /** The value cell: the chosen day or range, on one line. */\n  value: \"flex flex-1 items-center px-(--kl-inset) text-[15px] font-(--kl-weight-strong) whitespace-nowrap\",\n  /** What the value cell says before anything is chosen. */\n  placeholder: \"font-normal text-kl-ink-3\",\n  /** The popup: docked to the trigger (dock geometry; no cut), its natural width seven days and its sides. Within\n   * --kl-snap of the trigger's width it takes that width and the days share the difference; otherwise it keeps its\n   * own and meets the trigger's edge in a T. The calendar inside fills it. */\n  popup: cn(\n    \"kl-attached kl-dock kl-dock-fit grid bg-kl-cell text-kl-ink outline-0\",\n    \"[--kl-day:44px] [--kl-dock-w:calc(7*var(--kl-day)+2*var(--kl-k2))] in-data-[kl-density=compact]:[--kl-day:34px]\",\n    \"*:data-[slot=calendar]:w-auto *:data-[slot=range-calendar]:w-auto\",\n  ),\n  /** A row of quick choices under the calendar. */\n  presets: \"kl-cells border-t-(length:--kl-k1) border-t-kl-seam\",\n  /** One quick choice: a key cell sharing the row. */\n  preset: \"kl-cell kl-key min-h-9 flex-1 justify-center px-1.5 text-[13px] font-(--kl-weight-strong)\",\n};\n\ntype EmptyState = Record<string, never>;\nconst EMPTY: EmptyState = {};\ntype Layout = \"control\" | \"cell\";\n\n/** A part Keyline renders itself (useRender), with its slot and classes. */\nfunction usePart<Tag extends \"div\" | \"span\" | \"button\">(\n  tag: Tag,\n  slot: string,\n  base: string,\n  { render, className, style, ...props }: PartProps<Tag, EmptyState>,\n  extra?: Record<string, unknown>,\n): React.ReactElement {\n  const own = {\n    ...extra,\n    \"data-slot\": slot,\n    className: resolveClassName(base, className)(EMPTY),\n    style: resolveStyle(undefined, style)(EMPTY),\n  };\n  return useRender({ defaultTagName: tag, render, state: EMPTY, props: mergeProps<Tag>(props as never, own as never) });\n}\n\n/** Base UI's Popover.Root: open state and its event details pass through untouched. */\nconst DateRangeRoot = Popover.Root;\n\n/** The trigger: a field frame of cells (pass the affix, value and count). `layout=\"cell\"`: a cell of an enclosing frame. */\nfunction DateRangeTrigger({\n  layout = \"control\",\n  className,\n  ...props\n}: Popover.Trigger.Props & { layout?: Layout }): React.ReactElement {\n  return (\n    <Popover.Trigger\n      data-kl-layout={layout}\n      className={resolveClassName(pickerStyles.trigger, className)}\n      {...props}\n      data-slot=\"date-range-trigger\"\n    />\n  );\n}\n\nconst CalendarGlyph = () => (\n  <svg\n    viewBox=\"0 0 16 16\"\n    width=\"16\"\n    height=\"16\"\n    fill=\"none\"\n    stroke=\"currentColor\"\n    strokeWidth=\"1.75\"\n    strokeLinecap=\"square\"\n  >\n    <path d=\"M2.5 3.5h11v10h-11zM2.5 7h11M5.5 2v3M10.5 2v3\" />\n  </svg>\n);\n\n/** The calendar glyph's cell at the trigger's start (hidden from assistive tech). Children replace the glyph. */\nfunction DateRangeAffix({ children, ...props }: PartProps<\"span\", EmptyState>): React.ReactElement {\n  return usePart(\"span\", \"date-range-affix\", pickerStyles.affix, props, {\n    \"aria-hidden\": true,\n    children: children ?? <CalendarGlyph />,\n  });\n}\n\ntype ValueProps = PartProps<\"span\", EmptyState> & {\n  /** Shown, in the placeholder's ink, while there are no children. */\n  placeholder?: React.ReactNode;\n};\n\n/** The value cell: the chosen range, or the placeholder. */\nfunction DateRangeValue({ placeholder, children, ...props }: ValueProps): React.ReactElement {\n  return usePart(\"span\", \"date-range-value\", pickerStyles.value, props, {\n    children:\n      children ??\n      (placeholder != null ? (\n        <span data-slot=\"date-range-placeholder\" className={pickerStyles.placeholder}>\n          {placeholder}\n        </span>\n      ) : null),\n  });\n}\n\n/** The day count at the trigger's end: the number, then its unit in the Code voice. */\nfunction DateRangeCount(props: PartProps<\"span\", EmptyState>): React.ReactElement {\n  return usePart(\n    \"span\",\n    \"date-range-count\",\n    \"flex flex-none items-baseline gap-[5px] self-center px-2.5 text-[17px] font-(--kl-weight-display)\",\n    props,\n  );\n}\n\ntype PopupProps = Popover.Popup.Props &\n  Pick<Popover.Positioner.Props, \"anchor\" | \"side\" | \"align\" | \"sideOffset\" | \"alignOffset\" | \"collisionPadding\"> & {\n    /** The frame the popup docks to: `cell` when the trigger has `layout=\"cell\"`. */\n    layout?: Layout;\n    /** Where the portal renders (defaults to <body>). */\n    container?: Popover.Portal.Props[\"container\"];\n    /** Props for Base UI's Popover.Portal. */\n    portalProps?: Omit<Popover.Portal.Props, \"container\" | \"children\">;\n  };\n\n/** Focus the grid's focusable day when the popup opens (the chosen day, else today or the first). */\nconst gridDay = (popup: HTMLElement | null) =>\n  popup?.querySelector<HTMLElement>('[role=\"grid\"] [tabindex=\"0\"]') ?? true;\n\n/**\n * The calendar's surface: Base UI's Portal, Positioner and Popup in one part, with the positioner's placement props\n * lifted. It docks to the trigger and carries the configuration (density, motion, theme, dir) of the place it is\n * written. Focus lands on the grid's day.\n */\nfunction DateRangePopup({\n  layout = \"control\",\n  anchor,\n  side,\n  align = \"start\",\n  sideOffset,\n  alignOffset,\n  collisionPadding = 12,\n  container,\n  portalProps,\n  className,\n  style,\n  initialFocus,\n  ref,\n  ...props\n}: PopupProps): React.ReactElement {\n  const dock = dockGeometry(layout);\n  const [marker, scope, probe] = useKeylineScope(false, container);\n  const own = React.useRef<HTMLDivElement>(null);\n  const refs = useRefs(own, ref);\n  return (\n    <>\n      {marker}\n      <Popover.Portal container={container} {...portalProps}>\n        {probe}\n        <Popover.Positioner\n          anchor={anchor}\n          side={side}\n          align={align}\n          sideOffset={sideOffset ?? dock.sideOffset}\n          alignOffset={alignOffset ?? dock.alignOffset}\n          collisionPadding={collisionPadding}\n          {...scopeProps(scope, { className: \"kl-positioner\" })}\n        >\n          <Popover.Popup\n            ref={refs}\n            className={resolveClassName(pickerStyles.popup, className)}\n            style={resolveStyle(dock.style, style)}\n            initialFocus={initialFocus ?? (() => gridDay(own.current))}\n            {...props}\n            data-slot=\"date-range-popup\"\n          />\n        </Popover.Positioner>\n      </Popover.Portal>\n    </>\n  );\n}\n\n/** One callback ref for the part's own ref and the consumer's. */\nfunction useRefs<T>(own: React.RefObject<T | null>, theirs: React.Ref<T> | undefined): React.RefCallback<T> {\n  return React.useCallback(\n    (el: T | null) => {\n      own.current = el;\n      if (typeof theirs === \"function\") theirs(el);\n      else if (theirs) theirs.current = el;\n    },\n    [own, theirs],\n  );\n}\n\n/** The row under the calendar: the total, then the caption. */\nfunction DateRangeFooter(props: PartProps<\"div\", EmptyState>): React.ReactElement {\n  return usePart(\"div\", \"date-range-footer\", \"kl-cells border-t-(length:--kl-k1) border-t-kl-seam\", props);\n}\n\n/** The footer's count of days: a Count (`kl-count`) over its unit in the Code voice. */\nfunction DateRangeTotal(props: PartProps<\"div\", EmptyState>): React.ReactElement {\n  return usePart(\"div\", \"date-range-total\", \"grid min-w-[76px] content-center gap-[3px] px-(--kl-inset) py-2\", props);\n}\n\n/** The footer's caption: the range in words, or what the consumer's `caption` says. */\nfunction DateRangeCaption(props: PartProps<\"div\", EmptyState>): React.ReactElement {\n  return usePart(\n    \"div\",\n    \"date-range-caption\",\n    \"flex max-w-[232px] items-center px-(--kl-inset) py-1.5 text-[13px] text-kl-ink-2\",\n    props,\n  );\n}\n\n/** A row of quick choices under the calendar. */\nfunction DateRangePresets(props: PartProps<\"div\", EmptyState>): React.ReactElement {\n  return usePart(\"div\", \"date-range-presets\", pickerStyles.presets, props);\n}\n\n/** One quick choice: a key cell (its label travels under a press). */\nfunction DateRangePreset({ children, ...props }: PartProps<\"button\", EmptyState>): React.ReactElement {\n  return usePart(\n    \"button\",\n    \"date-range-preset\",\n    pickerStyles.preset,\n    { type: \"button\", ...props },\n    {\n      children: <span>{children}</span>,\n    },\n  );\n}\n\ntype DateRangePickerProps = Omit<RangeCalendarProps, \"onEscape\"> & {\n  label: React.ReactNode;\n  presets?: { label: string; range: () => DateRange }[];\n  caption?: (r: DateRange | null) => React.ReactNode;\n  /** control: its own 2px frame. cell: a cell of an enclosing frame (e.g. a toolbar); the label is visually hidden. */\n  layout?: Layout;\n  container?: Popover.Portal.Props[\"container\"];\n};\n\n/** Trigger field + docked calendar panel with presets and a day count, built from the parts above. */\nfunction DateRangePicker({\n  label,\n  value,\n  onValueChange,\n  presets = [],\n  caption,\n  layout = \"control\",\n  container,\n  className,\n  ...cal\n}: DateRangePickerProps) {\n  const [open, setOpen] = React.useState(false);\n  const id = React.useId();\n  const n = countAvailable(value, cal.isDateUnavailable);\n  return (\n    <DateRangeRoot open={open} onOpenChange={setOpen}>\n      <div data-slot=\"date-range\" data-kl-layout={layout} className={cn(\"kl-field\", className)}>\n        <span className={cn(\"kl-field-label\", layout === \"cell\" && \"kl-sr\")} id={id}>\n          {label}\n        </span>\n        {/* named by the label, the range and the day count: everything it shows is in its name */}\n        <DateRangeTrigger aria-labelledby={`${id} ${id}v ${id}n`} layout={layout}>\n          <DateRangeAffix />\n          <DateRangeValue id={`${id}v`} placeholder=\"Any date\">\n            {value ? formatRange(value, cal.locale) : null}\n          </DateRangeValue>\n          {/* the spaces keep the words apart in the text (and so the name); flex layout drops them */}{\" \"}\n          <DateRangeCount id={`${id}n`}>\n            <b>{n}</b> <span className=\"kl-code\">{n === 1 ? \"day\" : \"days\"}</span>\n          </DateRangeCount>\n        </DateRangeTrigger>\n        <DateRangePopup layout={layout} container={container} aria-labelledby={id}>\n          <RangeCalendar\n            value={value}\n            onValueChange={(r) => {\n              onValueChange(r);\n              setOpen(false);\n            }}\n            onEscape={() => setOpen(false)}\n            {...cal}\n          />\n          <DateRangeFooter>\n            <DateRangeTotal>\n              <span className=\"kl-count\">{n}</span>\n              <span className=\"kl-code\">{n === 1 ? \"DAY\" : \"DAYS\"}</span>\n            </DateRangeTotal>\n            <DateRangeCaption>\n              {caption ? caption(value) : value ? formatRange(value, cal.locale) : \"No range\"}\n            </DateRangeCaption>\n          </DateRangeFooter>\n          {presets.length ? (\n            <DateRangePresets>\n              {presets.map((p) => (\n                <DateRangePreset\n                  key={p.label}\n                  onClick={() => {\n                    onValueChange(p.range());\n                    setOpen(false);\n                  }}\n                >\n                  {p.label}\n                </DateRangePreset>\n              ))}\n            </DateRangePresets>\n          ) : null}\n        </DateRangePopup>\n      </div>\n    </DateRangeRoot>\n  );\n}\n\nexport {\n  RangeCalendar,\n  DateRangePicker,\n  DateRangeRoot,\n  DateRangeTrigger,\n  DateRangeAffix,\n  DateRangeValue,\n  DateRangeCount,\n  DateRangePopup,\n  DateRangeFooter,\n  DateRangeTotal,\n  DateRangeCaption,\n  DateRangePresets,\n  DateRangePreset,\n  useDayPicker,\n  useRefs,\n  usePart,\n  gridDay,\n  calendarStyles,\n  pickerStyles,\n  CalendarGlyph,\n  type Bounds,\n  type DateRangePickerProps,\n  type EmptyState,\n};\n",
      "type": "registry:ui",
      "target": "components/keyline/ui/date-range.tsx"
    }
  ],
  "type": "registry:ui"
}