{"slug":"date-picker","name":"Date Picker","description":"Month-grid calendar with a selection pill that glides between days, directional month slides, single, range, week or multiple-day selection across one or several side-by-side months, ISO week numbers, per-day labels, min/max and per-day disabling, full keyboard grid navigation, a date field, a two-month range field with presets, a booking calendar with nightly prices, time and date-time wheels and a month picker. Locale-aware, reduced-motion safe.","category":"motion","source_url":"https://karaui.kamisama-v0.my.id/r/date-picker/raw","detail_url":"https://karaui.kamisama-v0.my.id/r/date-picker","raw_url":"https://karaui.kamisama-v0.my.id/r/date-picker/raw","page_url":"https://karaui.kamisama-v0.my.id/components/motion/date-picker","markdown_url":"https://karaui.kamisama-v0.my.id/components/motion/date-picker.md","published_at":"2026-10-14","updated_at":"2026-10-14","dependencies":["clsx","lucide-react","motion","react","react-dom","tailwind-merge"],"internal":["@/components/motion/calendar","@/components/motion/date-picker","@/components/motion/popover-morph","@/components/motion/popover-position","@/lib/ease","@/lib/utils"],"files":[{"path":"components/motion/date-picker.tsx","type":"component","content":"\"use client\";\n// karaui.kamisama-v0.my.id/components/motion/date-picker\n\nimport { CalendarDays } from \"lucide-react\";\nimport { useMemo, useState } from \"react\";\nimport { Calendar } from \"@/components/motion/calendar\";\nimport {\n  MorphPopover,\n  MorphPopoverContent,\n  MorphPopoverTrigger,\n} from \"@/components/motion/popover-morph\";\nimport { cn } from \"@/lib/utils\";\n\nconst MEDIUM_DATE: Intl.DateTimeFormatOptions = { dateStyle: \"medium\" };\n\nexport interface DatePickerProps {\n  value?: Date | null;\n  defaultValue?: Date | null;\n  onValueChange?: (date: Date) => void;\n  placeholder?: string;\n  /** Intl options for the trigger label. Default: medium date. */\n  formatOptions?: Intl.DateTimeFormatOptions;\n  /** Default \"en-US\". */\n  locale?: string;\n  minDate?: Date;\n  maxDate?: Date;\n  isDateDisabled?: (date: Date) => boolean;\n  weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6;\n  align?: \"start\" | \"end\";\n  disabled?: boolean;\n  className?: string;\n  \"aria-label\"?: string;\n}\n\n/**\n * Date field whose calendar morphs open from the trigger corner and closes\n * as soon as a day is picked. Controlled or uncontrolled.\n */\nexport function DatePicker({\n  value: controlledValue,\n  defaultValue = null,\n  onValueChange,\n  placeholder = \"Pick a date\",\n  formatOptions = MEDIUM_DATE,\n  locale = \"en-US\",\n  minDate,\n  maxDate,\n  isDateDisabled,\n  weekStartsOn,\n  align = \"start\",\n  disabled,\n  className,\n  \"aria-label\": ariaLabel = \"Choose date\",\n}: DatePickerProps) {\n  const [open, setOpen] = useState(false);\n  const [internalValue, setInternalValue] = useState<Date | null>(\n    defaultValue,\n  );\n  const value =\n    controlledValue !== undefined ? controlledValue : internalValue;\n\n  const label = useMemo(\n    () =>\n      value\n        ? new Intl.DateTimeFormat(locale, formatOptions).format(value)\n        : null,\n    [value, locale, formatOptions],\n  );\n\n  return (\n    <MorphPopover open={open} onOpenChange={setOpen}>\n      <MorphPopoverTrigger>\n        <button\n          type=\"button\"\n          disabled={disabled}\n          aria-label={label ? `${ariaLabel}, ${label}` : ariaLabel}\n          className={cn(\n            \"inline-flex h-10 min-w-48 items-center gap-2 rounded-xl border border-border bg-background px-3 text-left text-sm outline-none transition-colors hover:border-border-strong focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50\",\n            label ? \"text-foreground\" : \"text-muted-foreground\",\n            className,\n          )}\n        >\n          <CalendarDays className=\"h-4 w-4 shrink-0 text-muted-foreground\" />\n          <span className=\"flex-1 truncate tabular-nums\">\n            {label ?? placeholder}\n          </span>\n        </button>\n      </MorphPopoverTrigger>\n\n      <MorphPopoverContent align={align} className=\"p-0\">\n        <Calendar\n          value={value}\n          onValueChange={(d) => {\n            if (controlledValue === undefined) setInternalValue(d);\n            onValueChange?.(d);\n            setOpen(false);\n          }}\n          locale={locale}\n          minDate={minDate}\n          maxDate={maxDate}\n          isDateDisabled={isDateDisabled}\n          weekStartsOn={weekStartsOn}\n          className=\"border-0 bg-transparent\"\n        />\n      </MorphPopoverContent>\n    </MorphPopover>\n  );\n}\n"},{"path":"components/motion/calendar.tsx","type":"util","content":"\"use client\";\n\nimport { ChevronLeft, ChevronRight } from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport {\n  type KeyboardEvent,\n  useCallback,\n  useEffect,\n  useId,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { EASE_OUT, SPRING_LAYOUT, SPRING_PRESS } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\nexport type DateRange = { from: Date; to?: Date };\n/** A whole week row: `from` is its first day, `to` its seventh. */\nexport type WeekRange = { from: Date; to: Date };\n\n/** Per-day extras from `getDayMeta`. */\nexport type CalendarDayMeta = {\n  /** Short text under the day number (a price, a count). Cells grow taller\n   * when any day has meta; the label is also read after the date. */\n  label?: string;\n  /** \"accent\" tints the label (deals, highlights); \"muted\" fades it. */\n  tone?: \"muted\" | \"accent\";\n  /** Blocks the day and strikes it through, like `isDateDisabled`. */\n  disabled?: boolean;\n};\n\ntype CalendarBaseProps = {\n  /** Earliest selectable day (inclusive). */\n  minDate?: Date;\n  /** Latest selectable day (inclusive). */\n  maxDate?: Date;\n  /** Extra per-day rule, e.g. weekends or booked dates. */\n  isDateDisabled?: (date: Date) => boolean;\n  /** 0 = Sunday … 6 = Saturday. Default 0. */\n  weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6;\n  /** BCP 47 locale for month, weekday and day labels. Default \"en-US\" — a\n   * fixed default keeps server and client output identical for hydration. */\n  locale?: string;\n  /** Controlled visible month (any day inside it). */\n  month?: Date;\n  /** Uncontrolled initial visible month. Default: the selection or today. */\n  defaultMonth?: Date;\n  onMonthChange?: (month: Date) => void;\n  /** Months shown side by side (stacked below `sm`). Default 1. With more\n   * than one, days outside each month are left blank so none repeats. */\n  numberOfMonths?: number;\n  /** Adds an ISO 8601 week-number column (\"Wk\") before each row. */\n  showWeekNumber?: boolean;\n  /** Per-day label, tone and blocking, e.g. nightly prices or booked days.\n   * Passing it switches the grid to taller cells that fit the label. */\n  getDayMeta?: (date: Date) => CalendarDayMeta | null | undefined;\n  className?: string;\n  \"aria-label\"?: string;\n};\n\nexport type CalendarSingleProps = CalendarBaseProps & {\n  mode?: \"single\";\n  value?: Date | null;\n  defaultValue?: Date | null;\n  onValueChange?: (date: Date) => void;\n};\n\nexport type CalendarRangeProps = CalendarBaseProps & {\n  mode: \"range\";\n  value?: DateRange | null;\n  defaultValue?: DateRange | null;\n  onValueChange?: (range: DateRange) => void;\n  /** Fewest nights (days between start and end) a finished range may span.\n   * While the end is being chosen, days too close are blocked. */\n  minNights?: number;\n  /** Most nights a finished range may span; farther days are blocked. */\n  maxNights?: number;\n};\n\nexport type CalendarWeekProps = CalendarBaseProps & {\n  mode: \"week\";\n  value?: WeekRange | null;\n  defaultValue?: WeekRange | null;\n  /** Called with the picked day's whole row, honouring `weekStartsOn`. */\n  onValueChange?: (week: WeekRange) => void;\n};\n\nexport type CalendarMultipleProps = CalendarBaseProps & {\n  mode: \"multiple\";\n  value?: Date[] | null;\n  defaultValue?: Date[] | null;\n  /** Called with the selection sorted by date. */\n  onValueChange?: (dates: Date[]) => void;\n  /** Most days that can be picked; further picks are ignored. */\n  max?: number;\n};\n\nexport type CalendarProps =\n  | CalendarSingleProps\n  | CalendarRangeProps\n  | CalendarWeekProps\n  | CalendarMultipleProps;\n\n// ── date helpers (local time, day precision) ──────────────────────────────\n\nconst startOfDay = (d: Date) =>\n  new Date(d.getFullYear(), d.getMonth(), d.getDate());\nconst startOfMonth = (d: Date) => new Date(d.getFullYear(), d.getMonth(), 1);\nconst addDays = (d: Date, n: number) =>\n  new Date(d.getFullYear(), d.getMonth(), d.getDate() + n);\n/** Adds months, clamping the day so Jan 31 + 1 month lands on Feb 28/29. */\nfunction addMonths(d: Date, n: number) {\n  const target = new Date(d.getFullYear(), d.getMonth() + n, 1);\n  const lastDay = new Date(\n    target.getFullYear(),\n    target.getMonth() + 1,\n    0,\n  ).getDate();\n  target.setDate(Math.min(d.getDate(), lastDay));\n  return target;\n}\nconst sameDay = (a?: Date | null, b?: Date | null) =>\n  !!a &&\n  !!b &&\n  a.getFullYear() === b.getFullYear() &&\n  a.getMonth() === b.getMonth() &&\n  a.getDate() === b.getDate();\nconst sameMonth = (a: Date, b: Date) =>\n  a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth();\nconst dayKey = (d: Date) =>\n  `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, \"0\")}-${String(d.getDate()).padStart(2, \"0\")}`;\nconst monthKey = (d: Date) =>\n  `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, \"0\")}`;\n/** Whole days from `a` to `b`; rounding absorbs DST hour shifts. */\nconst daysBetween = (a: Date, b: Date) =>\n  Math.round((startOfDay(b).getTime() - startOfDay(a).getTime()) / 86_400_000);\n/** ISO 8601 week number: weeks start Monday, week 1 holds Jan 4. */\nfunction isoWeek(d: Date) {\n  const thursday = addDays(d, 3 - ((d.getDay() + 6) % 7));\n  const jan4 = new Date(thursday.getFullYear(), 0, 4);\n  const firstThursday = addDays(jan4, 3 - ((jan4.getDay() + 6) % 7));\n  return 1 + Math.round(daysBetween(firstThursday, thursday) / 7);\n}\n\n/** Always 6 weeks, so the panel never changes height between months. */\nfunction buildWeeks(month: Date, weekStartsOn: number) {\n  const first = startOfMonth(month);\n  const offset = (first.getDay() - weekStartsOn + 7) % 7;\n  const start = addDays(first, -offset);\n  return Array.from({ length: 6 }, (_, w) =>\n    Array.from({ length: 7 }, (_, d) => addDays(start, w * 7 + d)),\n  );\n}\n\n// Month swap is a short directional slide; the exit is quicker than the entry.\nconst MONTH_ENTER = { duration: 0.26, ease: EASE_OUT } as const;\nconst MONTH_EXIT = { duration: 0.16, ease: EASE_OUT } as const;\n\n/**\n * Month-grid calendar for single dates, ranges, whole weeks or several\n * separate days, one or more months wide. The selected day is a pill that\n * glides between days on a shared-layout spring; a picked week is one pill\n * across its row; months slide in from the direction you travel. Optional ISO\n * week numbers, per-day labels (`getDayMeta`) and night limits for ranges.\n * Full keyboard grid navigation (arrows, Home/End, PageUp/PageDown,\n * Shift+Page for years). Controlled or uncontrolled for both the selection\n * and the visible month; reduced-motion safe.\n */\nexport function Calendar(props: CalendarProps) {\n  const {\n    minDate,\n    maxDate,\n    isDateDisabled,\n    weekStartsOn = 0,\n    locale = \"en-US\",\n    month: controlledMonth,\n    defaultMonth,\n    onMonthChange,\n    numberOfMonths = 1,\n    showWeekNumber = false,\n    getDayMeta,\n    className,\n    \"aria-label\": ariaLabel,\n  } = props;\n  const isRange = props.mode === \"range\";\n  const isWeek = props.mode === \"week\";\n  const isMultiple = props.mode === \"multiple\";\n  const count = Math.max(1, Math.floor(numberOfMonths));\n  const minNights = isRange ? ((props as CalendarRangeProps).minNights ?? 0) : 0;\n  const maxNights = isRange ? (props as CalendarRangeProps).maxNights : undefined;\n  // Taller cells only when there is something to put under the number.\n  const tall = !!getDayMeta;\n\n  const uid = useId();\n  const reduce = useReducedMotion();\n\n  // ── selection ──\n  const [internalValue, setInternalValue] = useState<\n    Date | DateRange | WeekRange | Date[] | null\n  >(props.defaultValue ?? null);\n  const valueControlled = props.value !== undefined;\n  const value = valueControlled ? (props.value ?? null) : internalValue;\n  const single =\n    isRange || isWeek || isMultiple ? null : (value as Date | null);\n  const range = isRange ? (value as DateRange | null) : null;\n  const week = isWeek ? (value as WeekRange | null) : null;\n  const picked = isMultiple ? ((value as Date[] | null) ?? []) : [];\n  const isPicked = (d: Date) => picked.some((p) => sameDay(p, d));\n\n  // ── visible months ──\n  const anchor = single ?? range?.from ?? week?.from ?? picked[0] ?? null;\n  const [internalMonth, setInternalMonth] = useState(() =>\n    startOfMonth(defaultMonth ?? anchor ?? new Date()),\n  );\n  const month = controlledMonth\n    ? startOfMonth(controlledMonth)\n    : internalMonth;\n  const [direction, setDirection] = useState(1);\n  const lastMonth = addMonths(month, count - 1);\n  const inWindow = (d: Date) => {\n    const m = startOfMonth(d);\n    return m >= month && m <= lastMonth;\n  };\n\n  const setMonth = useCallback(\n    (next: Date) => {\n      const m = startOfMonth(next);\n      if (sameMonth(m, month)) return;\n      setDirection(m > month ? 1 : -1);\n      if (!controlledMonth) setInternalMonth(m);\n      onMonthChange?.(m);\n    },\n    [month, controlledMonth, onMonthChange],\n  );\n\n  // \"Today\" is read after mount: the server's clock and timezone can disagree\n  // with the viewer's, and a mismatched marker would break hydration.\n  const [today, setToday] = useState<Date | null>(null);\n  useEffect(() => setToday(startOfDay(new Date())), []);\n\n  // ── roving focus ──\n  const [focused, setFocused] = useState<Date>(() =>\n    startOfDay(anchor ?? defaultMonth ?? new Date()),\n  );\n  const gridRef = useRef<HTMLDivElement>(null);\n  const shouldFocus = useRef(false);\n  // Range hover preview: the band follows the pointer until the end is picked.\n  // In week mode it is the row under the pointer or keyboard focus.\n  const [hovered, setHovered] = useState<Date | null>(null);\n\n  // Keep the tab stop inside the visible months when they change by buttons.\n  const focusInMonth = inWindow(focused)\n    ? focused\n    : anchor && inWindow(anchor)\n      ? anchor\n      : month;\n\n  useEffect(() => {\n    if (!shouldFocus.current) return;\n    shouldFocus.current = false;\n    gridRef.current\n      ?.querySelector<HTMLButtonElement>(\n        `[data-month=\"${monthKey(focusInMonth)}\"] [data-date=\"${dayKey(focusInMonth)}\"]`,\n      )\n      ?.focus();\n  }, [focusInMonth]);\n\n  const isDisabled = useCallback(\n    (d: Date) =>\n      (minDate && d < startOfDay(minDate)) ||\n      (maxDate && d > startOfDay(maxDate)) ||\n      !!isDateDisabled?.(d) ||\n      !!getDayMeta?.(d)?.disabled,\n    [minDate, maxDate, isDateDisabled, getDayMeta],\n  );\n\n  // While a range end is being chosen, days that would make it too short or\n  // too long are blocked (earlier days stay open: they restart the range).\n  const choosingEnd = !!range && !range.to;\n  const nightsAllowed = (n: number) =>\n    n >= minNights && (maxNights === undefined || n <= maxNights);\n  const blockedByNights = (d: Date) =>\n    choosingEnd &&\n    !!range &&\n    d > range.from &&\n    !nightsAllowed(daysBetween(range.from, d));\n\n  const weekStart = (d: Date) =>\n    addDays(d, -((d.getDay() - weekStartsOn + 7) % 7));\n\n  const select = (d: Date) => {\n    if (isDisabled(d) || blockedByNights(d)) return;\n    if (!inWindow(d)) setMonth(d);\n    setFocused(d);\n\n    if (isWeek) {\n      const from = weekStart(d);\n      const next: WeekRange = { from, to: addDays(from, 6) };\n      if (!valueControlled) setInternalValue(next);\n      (props as CalendarWeekProps).onValueChange?.(next);\n      return;\n    }\n\n    if (isMultiple) {\n      const max = (props as CalendarMultipleProps).max;\n      const next = isPicked(d)\n        ? picked.filter((p) => !sameDay(p, d))\n        : max !== undefined && picked.length >= max\n          ? null\n          : [...picked, d].sort((a, b) => a.getTime() - b.getTime());\n      if (!next) return;\n      if (!valueControlled) setInternalValue(next);\n      (props as CalendarMultipleProps).onValueChange?.(next);\n      return;\n    }\n    if (!isRange) {\n      if (!valueControlled) setInternalValue(d);\n      (props as CalendarSingleProps).onValueChange?.(d);\n      return;\n    }\n    // First click starts a range; a later day closes it; an earlier day, the\n    // start again when it would be too short, or a click on a finished range\n    // starts over.\n    const next: DateRange =\n      range &&\n      !range.to &&\n      d >= range.from &&\n      nightsAllowed(daysBetween(range.from, d))\n        ? { from: range.from, to: d }\n        : { from: d };\n    if (!valueControlled) setInternalValue(next);\n    (props as CalendarRangeProps).onValueChange?.(next);\n  };\n\n  const onGridKeyDown = (e: KeyboardEvent) => {\n    const base = focusInMonth;\n    let next: Date | null = null;\n    switch (e.key) {\n      case \"ArrowLeft\":\n        next = addDays(base, -1);\n        break;\n      case \"ArrowRight\":\n        next = addDays(base, 1);\n        break;\n      case \"ArrowUp\":\n        next = addDays(base, -7);\n        break;\n      case \"ArrowDown\":\n        next = addDays(base, 7);\n        break;\n      case \"Home\":\n        next = addDays(base, -((base.getDay() - weekStartsOn + 7) % 7));\n        break;\n      case \"End\":\n        next = addDays(base, 6 - ((base.getDay() - weekStartsOn + 7) % 7));\n        break;\n      case \"PageUp\":\n        next = addMonths(base, e.shiftKey ? -12 : -1);\n        break;\n      case \"PageDown\":\n        next = addMonths(base, e.shiftKey ? 12 : 1);\n        break;\n      default:\n        return;\n    }\n    e.preventDefault();\n    shouldFocus.current = true;\n    setFocused(next);\n    // Scroll the window only when focus leaves it, by as little as needed.\n    if (!inWindow(next))\n      setMonth(next < month ? next : addMonths(startOfMonth(next), 1 - count));\n  };\n\n  // ── labels ──\n  const monthFormat = useMemo(\n    () => new Intl.DateTimeFormat(locale, { month: \"long\", year: \"numeric\" }),\n    [locale],\n  );\n  const weekdays = useMemo(() => {\n    const short = new Intl.DateTimeFormat(locale, { weekday: \"short\" });\n    const long = new Intl.DateTimeFormat(locale, { weekday: \"long\" });\n    // 2023-01-01 was a Sunday.\n    return Array.from({ length: 7 }, (_, i) => {\n      const d = new Date(2023, 0, 1 + ((i + weekStartsOn) % 7));\n      return { short: short.format(d).slice(0, 2), long: long.format(d) };\n    });\n  }, [locale, weekStartsOn]);\n  const dayLabel = useMemo(\n    () =>\n      new Intl.DateTimeFormat(locale, {\n        weekday: \"long\",\n        day: \"numeric\",\n        month: \"long\",\n        year: \"numeric\",\n      }),\n    [locale],\n  );\n\n  const prevDisabled =\n    !!minDate && startOfMonth(minDate) >= month;\n  const nextDisabled =\n    !!maxDate && startOfMonth(maxDate) <= lastMonth;\n\n  // Range band end: the picked end, or the hovered day while choosing one.\n  // A day that can't close the range doesn't stretch the band to it.\n  const bandEnd =\n    range &&\n    !range.to &&\n    hovered &&\n    hovered > range.from &&\n    !isDisabled(hovered) &&\n    !blockedByNights(hovered)\n      ? hovered\n      : range?.to;\n  // Week mode: the row being previewed (pointer or keyboard focus).\n  const previewWeek = isWeek && hovered ? weekStart(hovered) : null;\n\n  const navButton =\n    \"inline-flex size-8 items-center justify-center rounded-lg text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40\";\n\n  const months = Array.from({ length: count }, (_, i) => addMonths(month, i));\n  // Weekday index of the column, so connecting bands stop at the row ends.\n  const column = (d: Date) => (d.getDay() - weekStartsOn + 7) % 7;\n  const cellSize = tall ? \"h-12 w-10\" : \"size-9\";\n\n  return (\n    <div\n      className={cn(\n        \"w-fit rounded-2xl border border-border bg-card p-3 text-foreground\",\n        className,\n      )}\n    >\n      <div\n        ref={gridRef}\n        onPointerLeave={() => setHovered(null)}\n        className=\"flex flex-col gap-x-6 gap-y-4 sm:flex-row\"\n      >\n        {months.map((m, i) => {\n          const mk = monthKey(m);\n          const weeks = buildWeeks(m, weekStartsOn);\n          const labelId = `${uid}-label-${i}`;\n          return (\n            <div\n              // biome-ignore lint/suspicious/noArrayIndexKey: columns are positional; each keeps its own month transition.\n              key={i}\n              className=\"min-w-0\"\n            >\n              <div className=\"mb-2 flex items-center justify-between gap-2 px-1\">\n                {i === 0 ? (\n                  <button\n                    type=\"button\"\n                    aria-label=\"Previous month\"\n                    disabled={prevDisabled}\n                    onClick={() => setMonth(addMonths(month, -1))}\n                    className={navButton}\n                  >\n                    <ChevronLeft className=\"h-4 w-4\" />\n                  </button>\n                ) : (\n                  <span aria-hidden className=\"size-8\" />\n                )}\n                <h2\n                  id={labelId}\n                  aria-live={i === 0 ? \"polite\" : undefined}\n                  className=\"text-sm font-medium tabular-nums\"\n                >\n                  {monthFormat.format(m)}\n                </h2>\n                {i === count - 1 ? (\n                  <button\n                    type=\"button\"\n                    aria-label=\"Next month\"\n                    disabled={nextDisabled}\n                    onClick={() => setMonth(addMonths(month, 1))}\n                    className={navButton}\n                  >\n                    <ChevronRight className=\"h-4 w-4\" />\n                  </button>\n                ) : (\n                  <span aria-hidden className=\"size-8\" />\n                )}\n              </div>\n\n              <div className=\"relative overflow-hidden\">\n                <AnimatePresence\n                  initial={false}\n                  mode=\"popLayout\"\n                  custom={direction}\n                >\n                  <motion.table\n                    key={mk}\n                    data-month={mk}\n                    custom={direction}\n                    aria-labelledby={ariaLabel ? undefined : labelId}\n                    aria-label={ariaLabel ? `${ariaLabel}, ${monthFormat.format(m)}` : undefined}\n                    onKeyDown={onGridKeyDown}\n                    variants={{\n                      enter: (dir: number) => ({\n                        opacity: 0,\n                        x: reduce ? 0 : dir * 28,\n                        filter: reduce ? \"blur(0px)\" : \"blur(4px)\",\n                      }),\n                      center: {\n                        opacity: 1,\n                        x: 0,\n                        filter: \"blur(0px)\",\n                        transition: MONTH_ENTER,\n                      },\n                      exit: (dir: number) => ({\n                        opacity: 0,\n                        x: reduce ? 0 : dir * -28,\n                        filter: reduce ? \"blur(0px)\" : \"blur(4px)\",\n                        transition: MONTH_EXIT,\n                      }),\n                    }}\n                    initial=\"enter\"\n                    animate=\"center\"\n                    exit=\"exit\"\n                    className=\"border-collapse\"\n                  >\n                    <thead>\n                      <tr>\n                        {showWeekNumber && (\n                          <th\n                            scope=\"col\"\n                            abbr=\"Week\"\n                            className=\"h-8 w-8 text-[11px] font-medium text-muted-foreground/70\"\n                          >\n                            Wk\n                          </th>\n                        )}\n                        {weekdays.map((w) => (\n                          <th\n                            key={w.long}\n                            scope=\"col\"\n                            abbr={w.long}\n                            className={cn(\n                              \"h-8 text-[11px] font-medium text-muted-foreground\",\n                              tall ? \"w-10\" : \"w-9\",\n                            )}\n                          >\n                            {w.short}\n                          </th>\n                        ))}\n                      </tr>\n                    </thead>\n                    <tbody>\n                      {weeks.map((row) => {\n                        // Days this row actually draws: side-by-side months\n                        // leave the other month's days blank.\n                        const shown =\n                          count > 1 ? row.filter((d) => sameMonth(d, m)) : row;\n                        const weekSelected =\n                          !!week && sameDay(row[0], weekStart(week.from));\n                        const weekPreview =\n                          !weekSelected && sameDay(row[0], previewWeek);\n                        // ISO weeks run Monday–Sunday; the row's Thursday\n                        // decides which one a differently started row is.\n                        const thursday =\n                          row.find((d) => d.getDay() === 4) ?? row[0];\n                        return (\n                          <tr key={dayKey(row[0])}>\n                            {showWeekNumber && (\n                              <th\n                                scope=\"row\"\n                                className={cn(\n                                  \"p-0 text-center text-[11px] font-normal tabular-nums transition-colors\",\n                                  weekSelected\n                                    ? \"font-medium text-foreground\"\n                                    : \"text-muted-foreground/70\",\n                                )}\n                              >\n                                {shown.length > 0 ? isoWeek(thursday) : null}\n                              </th>\n                            )}\n                            {row.map((d) => {\n                              const outside = !sameMonth(d, m);\n                              // Side-by-side months would show these days twice.\n                              if (outside && count > 1)\n                                return (\n                                  <td key={dayKey(d)} className=\"p-0\">\n                                    <span className={cn(\"block\", cellSize)} />\n                                  </td>\n                                );\n                              const meta = getDayMeta?.(d) ?? null;\n                              const disabled = isDisabled(d);\n                              const nightsBlocked =\n                                !disabled && blockedByNights(d);\n                              const isToday = sameDay(d, today);\n                              const isFrom = sameDay(d, range?.from);\n                              const isTo = sameDay(d, bandEnd);\n                              const inBand =\n                                !!range?.from &&\n                                !!bandEnd &&\n                                d > range.from &&\n                                d < bandEnd;\n                              const chosen = isMultiple && isPicked(d);\n                              const inWeek =\n                                !!week &&\n                                d >= startOfDay(week.from) &&\n                                d <= startOfDay(week.to);\n                              const selected = isRange\n                                ? isFrom || (isTo && !!range?.to)\n                                : isWeek\n                                  ? inWeek\n                                  : isMultiple\n                                    ? chosen\n                                    : sameDay(d, single);\n                              const endpoint = isFrom || isTo;\n                              // Picked neighbours in the same row merge into one\n                              // pill, so a run of days reads as a block.\n                              const joinPrev =\n                                chosen &&\n                                column(d) > 0 &&\n                                sameMonth(addDays(d, -1), m) &&\n                                isPicked(addDays(d, -1));\n                              const joinNext =\n                                chosen &&\n                                column(d) < 6 &&\n                                sameMonth(addDays(d, 1), m) &&\n                                isPicked(addDays(d, 1));\n                              // The week pill lives in the row's first drawn\n                              // cell and spans every drawn day after it.\n                              const weekPill =\n                                isWeek &&\n                                (weekSelected || weekPreview) &&\n                                sameDay(d, shown[0]);\n\n                              return (\n                                <td key={dayKey(d)} className=\"relative p-0\">\n                                  {(inBand ||\n                                    (endpoint &&\n                                      bandEnd &&\n                                      !sameDay(range?.from, bandEnd))) && (\n                                    <span\n                                      aria-hidden\n                                      className={cn(\n                                        \"absolute inset-y-0.5 bg-primary/10\",\n                                        inBand && \"inset-x-0\",\n                                        isFrom && \"left-1/2 right-0\",\n                                        isTo && \"left-0 right-1/2\",\n                                      )}\n                                    />\n                                  )}\n                                  {weekPill && (\n                                    <motion.span\n                                      aria-hidden\n                                      // Selected and previewed rows each glide\n                                      // between weeks, scoped per month.\n                                      layoutId={`${uid}-${mk}-${weekSelected ? \"week\" : \"week-preview\"}`}\n                                      transition={\n                                        reduce ? { duration: 0 } : SPRING_LAYOUT\n                                      }\n                                      style={{ width: `${shown.length * 100}%` }}\n                                      className={cn(\n                                        \"pointer-events-none absolute inset-y-0 left-0 rounded-lg\",\n                                        weekSelected ? \"bg-primary\" : \"bg-muted\",\n                                      )}\n                                    />\n                                  )}\n                                  <button\n                                    type=\"button\"\n                                    data-date={dayKey(d)}\n                                    tabIndex={\n                                      sameDay(d, focusInMonth) && !outside\n                                        ? 0\n                                        : -1\n                                    }\n                                    aria-label={\n                                      meta?.label\n                                        ? `${dayLabel.format(d)}, ${meta.label}`\n                                        : dayLabel.format(d)\n                                    }\n                                    aria-pressed={selected}\n                                    aria-disabled={\n                                      disabled || nightsBlocked || undefined\n                                    }\n                                    aria-current={isToday ? \"date\" : undefined}\n                                    title={\n                                      nightsBlocked\n                                        ? daysBetween(range?.from ?? d, d) <\n                                          minNights\n                                          ? `Minimum ${minNights} nights`\n                                          : `Maximum ${maxNights} nights`\n                                        : undefined\n                                    }\n                                    onClick={() => select(d)}\n                                    onFocus={() => {\n                                      setFocused(d);\n                                      if (isWeek) setHovered(d);\n                                    }}\n                                    onBlur={() => isWeek && setHovered(null)}\n                                    onPointerEnter={() =>\n                                      (isRange || isWeek) && setHovered(d)\n                                    }\n                                    className={cn(\n                                      \"relative isolate flex items-center justify-center rounded-lg text-sm tabular-nums outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring\",\n                                      cellSize,\n                                      tall && \"flex-col gap-0.5\",\n                                      outside\n                                        ? \"text-muted-foreground/50\"\n                                        : \"text-foreground\",\n                                      !selected &&\n                                        !disabled &&\n                                        !nightsBlocked &&\n                                        !isWeek &&\n                                        \"hover:bg-muted\",\n                                      selected && \"text-primary-foreground\",\n                                      selected &&\n                                        outside &&\n                                        \"text-primary-foreground/60\",\n                                      isTo && !range?.to && \"text-foreground\",\n                                      nightsBlocked &&\n                                        \"cursor-not-allowed text-muted-foreground/40\",\n                                      disabled &&\n                                        \"cursor-not-allowed text-muted-foreground/40 line-through\",\n                                    )}\n                                  >\n                                    {selected &&\n                                      !isWeek &&\n                                      (isRange || isMultiple ? (\n                                        <motion.span\n                                          aria-hidden\n                                          initial={\n                                            reduce ? false : { scale: 0.7 }\n                                          }\n                                          animate={{ scale: 1 }}\n                                          transition={SPRING_PRESS}\n                                          className={cn(\n                                            \"absolute inset-0 -z-10 rounded-lg bg-primary\",\n                                            joinPrev && \"rounded-l-none\",\n                                            joinNext && \"rounded-r-none\",\n                                          )}\n                                        />\n                                      ) : (\n                                        <motion.span\n                                          aria-hidden\n                                          // Scoped per month so the pill glides\n                                          // between days but never across the\n                                          // sliding grids.\n                                          layoutId={`${uid}-${mk}-selected`}\n                                          transition={\n                                            reduce\n                                              ? { duration: 0 }\n                                              : SPRING_LAYOUT\n                                          }\n                                          className=\"absolute inset-0 -z-10 rounded-lg bg-primary\"\n                                        />\n                                      ))}\n                                    {isTo && !range?.to && (\n                                      <span\n                                        aria-hidden\n                                        className=\"absolute inset-0 -z-10 rounded-lg border border-primary/40\"\n                                      />\n                                    )}\n                                    {tall ? (\n                                      <span className=\"leading-none\">\n                                        {d.getDate()}\n                                      </span>\n                                    ) : (\n                                      d.getDate()\n                                    )}\n                                    {tall && (\n                                      <span\n                                        aria-hidden\n                                        className={cn(\n                                          \"h-2.5 text-[10px] leading-none\",\n                                          meta?.tone === \"accent\"\n                                            ? // Tinted toward the foreground so\n                                              // the green keeps contrast on\n                                              // light and dark cards.\n                                              \"font-medium text-[color:color-mix(in_oklab,var(--chart-3)_70%,var(--foreground))]\"\n                                            : meta?.tone === \"muted\"\n                                              ? \"text-muted-foreground/60\"\n                                              : \"text-muted-foreground\",\n                                          selected &&\n                                            \"text-primary-foreground/75\",\n                                          (disabled || nightsBlocked) &&\n                                            \"text-muted-foreground/40\",\n                                        )}\n                                      >\n                                        {meta?.label}\n                                      </span>\n                                    )}\n                                    {isToday && (\n                                      <span\n                                        aria-hidden\n                                        className={cn(\n                                          \"absolute size-1 rounded-full\",\n                                          tall ? \"top-1.5 right-1.5\" : \"bottom-1\",\n                                          selected\n                                            ? \"bg-primary-foreground\"\n                                            : \"bg-primary\",\n                                        )}\n                                      />\n                                    )}\n                                  </button>\n                                </td>\n                              );\n                            })}\n                          </tr>\n                        );\n                      })}\n                    </tbody>\n                  </motion.table>\n                </AnimatePresence>\n              </div>\n            </div>\n          );\n        })}\n      </div>\n    </div>\n  );\n}\n"},{"path":"components/motion/popover-morph.tsx","type":"util","content":"\"use client\";\n\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport {\n  cloneElement,\n  createContext,\n  isValidElement,\n  type ReactElement,\n  type ReactNode,\n  type Ref,\n  useCallback,\n  useContext,\n  useEffect,\n  useId,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { usePopoverPortalPosition } from \"@/components/motion/popover-position\";\nimport { EASE_OUT, SPRING_PANEL } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\ntype Side = \"top\" | \"bottom\";\ntype Align = \"start\" | \"end\";\n\ntype MorphContextValue = {\n  open: boolean;\n  setOpen: (open: boolean) => void;\n  toggle: () => void;\n  triggerId: string;\n  contentId: string;\n  /** The element the panel measures against — see `registerTrigger`. */\n  triggerRef: React.MutableRefObject<HTMLElement | null>;\n  registerTrigger: (node: HTMLElement | null) => void;\n  contentRef: React.MutableRefObject<HTMLDivElement | null>;\n};\n\nconst MorphContext = createContext<MorphContextValue | null>(null);\n\nfunction useMorphContext(component: string) {\n  const ctx = useContext(MorphContext);\n  if (!ctx) throw new Error(`${component} must be used within <MorphPopover>`);\n  return ctx;\n}\n\nexport interface MorphPopoverProps {\n  children: ReactNode;\n  /** Controlled open state. */\n  open?: boolean;\n  /** Uncontrolled initial open state. */\n  defaultOpen?: boolean;\n  onOpenChange?: (open: boolean) => void;\n  className?: string;\n}\n\n/**\n * A popover whose panel morphs open from the trigger corner: it's laid out at\n * full size but clipped to the corner nearest the trigger, then unclips as one\n * piece. Closes on outside pointer / Escape. Controlled or uncontrolled.\n */\nexport function MorphPopover({\n  children,\n  open: controlledOpen,\n  defaultOpen = false,\n  onOpenChange,\n  className,\n}: MorphPopoverProps) {\n  const baseId = useId();\n  const [root, setRoot] = useState<HTMLDivElement | null>(null);\n  const [trigger, setTrigger] = useState<HTMLElement | null>(null);\n  const contentRef = useRef<HTMLDivElement | null>(null);\n  const [internalOpen, setInternalOpen] = useState(defaultOpen);\n  const controlled = controlledOpen !== undefined;\n  const open = controlled ? controlledOpen : internalOpen;\n\n  const setOpen = useCallback(\n    (next: boolean) => {\n      if (!controlled) setInternalOpen(next);\n      onOpenChange?.(next);\n    },\n    [controlled, onOpenChange],\n  );\n  const toggle = useCallback(() => setOpen(!open), [setOpen, open]);\n\n  // A trigger normally registers itself through MorphPopoverTrigger. It can't\n  // when something else already clones the element — a Tooltip wrapping the\n  // button, say — and an unregistered trigger leaves the panel with nothing to\n  // measure against, so it renders permanently invisible. The root boxes the\n  // trigger exactly (the content portals out of it), so it stands in until a\n  // real trigger registers, and stands in again if that one unmounts. Both are\n  // state, so a trigger arriving while the panel is open re-anchors it.\n  const anchorRef = useMemo<React.MutableRefObject<HTMLElement | null>>(\n    () => ({ current: trigger ?? root }),\n    [root, trigger],\n  );\n\n  // The panel is a `role=\"dialog\"` and goes inert the moment it closes, so\n  // focus cannot be left sitting inside it: a dismissal hands it back to the\n  // trigger, the way the ARIA dialog pattern asks. A pointer dismissal takes\n  // the focus onward itself when it lands on something focusable — this only\n  // catches the case where it would otherwise be stranded. When no trigger has\n  // registered, the root anchor stands in only if it can actually hold focus;\n  // there is nowhere better than where the keyboard already is, so leave it.\n  const close = useCallback(() => {\n    setOpen(false);\n    const focused = document.activeElement;\n    const inPanel =\n      focused instanceof HTMLElement && contentRef.current?.contains(focused);\n    if (!inPanel) return;\n    const restore = trigger ?? (root && root.tabIndex >= 0 ? root : null);\n    restore?.focus();\n  }, [root, setOpen, trigger]);\n\n  useEffect(() => {\n    if (!open) return;\n    const onKey = (e: KeyboardEvent) => e.key === \"Escape\" && close();\n    const onPointer = (e: PointerEvent) => {\n      const target = e.target as Node;\n      if (\n        root &&\n        !root.contains(target) &&\n        !contentRef.current?.contains(target)\n      )\n        close();\n    };\n    window.addEventListener(\"keydown\", onKey);\n    window.addEventListener(\"pointerdown\", onPointer);\n    return () => {\n      window.removeEventListener(\"keydown\", onKey);\n      window.removeEventListener(\"pointerdown\", onPointer);\n    };\n  }, [open, root, close]);\n\n  const ctx = useMemo<MorphContextValue>(\n    () => ({\n      open,\n      setOpen,\n      toggle,\n      triggerId: `${baseId}-trigger`,\n      contentId: `${baseId}-content`,\n      triggerRef: anchorRef,\n      registerTrigger: setTrigger,\n      contentRef,\n    }),\n    [open, setOpen, toggle, baseId, anchorRef],\n  );\n\n  return (\n    <MorphContext.Provider value={ctx}>\n      <div ref={setRoot} className={cn(\"relative inline-flex\", className)}>\n        {children}\n      </div>\n    </MorphContext.Provider>\n  );\n}\n\nexport interface MorphPopoverTriggerProps {\n  children: ReactElement;\n}\n\nfunction mergeRefs<T>(...refs: Array<Ref<T> | undefined>) {\n  return (node: T | null) => {\n    for (const ref of refs) {\n      if (typeof ref === \"function\") ref(node);\n      else if (ref && typeof ref === \"object\")\n        (ref as React.MutableRefObject<T | null>).current = node;\n    }\n  };\n}\n\n/** Wraps a single element, toggling the popover on click. */\nexport function MorphPopoverTrigger({ children }: MorphPopoverTriggerProps) {\n  const ctx = useMorphContext(\"MorphPopoverTrigger\");\n  if (!isValidElement(children)) return children;\n\n  const child = children as ReactElement<Record<string, unknown>>;\n  const childOnClick = child.props.onClick as\n    | ((e: unknown) => void)\n    | undefined;\n  const childRef = (child.props as { ref?: Ref<HTMLElement> }).ref;\n\n  return cloneElement(child, {\n    id: ctx.triggerId,\n    ref: mergeRefs(childRef, ctx.registerTrigger),\n    onClick: (e: unknown) => {\n      childOnClick?.(e);\n      ctx.toggle();\n    },\n    \"aria-haspopup\": \"dialog\",\n    \"aria-expanded\": ctx.open,\n    \"aria-controls\": ctx.open ? ctx.contentId : undefined,\n  });\n}\n\nconst originFor = (side: Side, align: Align) =>\n  `${side === \"bottom\" ? \"top\" : \"bottom\"} ${align === \"end\" ? \"right\" : \"left\"}`;\n\n// A clip that hides everything but the corner nearest the trigger, so the\n// panel appears to grow out of it. inset(top right bottom left).\nfunction clipHidden(side: Side, align: Align, radius: number) {\n  const top = side === \"bottom\" ? \"0%\" : \"92%\";\n  const bottom = side === \"bottom\" ? \"92%\" : \"0%\";\n  const right = align === \"end\" ? \"0%\" : \"92%\";\n  const left = align === \"end\" ? \"92%\" : \"0%\";\n  return `inset(${top} ${right} ${bottom} ${left} round ${radius}px)`;\n}\nconst clipShown = (radius: number) => `inset(0% 0% 0% 0% round ${radius}px)`;\n\n// Preserve the original spring character on the wrapper, but tween the complex\n// clip-path so it cannot snap when the spring resolves its final distance.\nconst MORPH_CLIP_TRANSITION = { duration: 0.32, ease: EASE_OUT } as const;\n\nexport interface MorphPopoverContentProps {\n  children: ReactNode;\n  side?: Side;\n  align?: Align;\n  /** Gap between trigger and panel, in px. Default 8. */\n  sideOffset?: number;\n  /** Panel corner radius, in px. Default 16. */\n  radius?: number;\n  className?: string;\n}\n\nexport function MorphPopoverContent({\n  children,\n  side = \"bottom\",\n  align = \"end\",\n  sideOffset = 8,\n  radius = 16,\n  className,\n}: MorphPopoverContentProps) {\n  const ctx = useMorphContext(\"MorphPopoverContent\");\n  const reduce = useReducedMotion() ?? false;\n  const [portalReady, setPortalReady] = useState(false);\n  const layout = usePopoverPortalPosition(\n    ctx.triggerRef,\n    ctx.contentRef,\n    portalReady && ctx.open,\n  );\n\n  useEffect(() => setPortalReady(true), []);\n  const left = layout\n    ? align === \"end\"\n      ? layout.trigger.left + layout.trigger.width - layout.content.width\n      : layout.trigger.left\n    : 0;\n  const top = layout\n    ? side === \"bottom\"\n      ? layout.trigger.top + layout.trigger.height + sideOffset\n      : layout.trigger.top - layout.content.height - sideOffset\n    : 0;\n\n  // Both directions travel between the exact same hidden/show states. Exit\n  // targets \"hidden\" directly instead of introducing separate choreography.\n  const wrap = reduce\n    ? undefined\n    : {\n        hidden: { opacity: 0, scale: 0.96, transition: SPRING_PANEL },\n        show: { opacity: 1, scale: 1, transition: SPRING_PANEL },\n      };\n  const clip = reduce\n    ? undefined\n    : {\n        hidden: {\n          clipPath: clipHidden(side, align, radius),\n          transition: MORPH_CLIP_TRANSITION,\n        },\n        show: {\n          clipPath: clipShown(radius),\n          transition: MORPH_CLIP_TRANSITION,\n        },\n      };\n\n  // Keep the server and first client render identical, then mount the portal.\n  if (!portalReady) return null;\n\n  return createPortal(\n    <AnimatePresence>\n      {ctx.open ? (\n        <motion.div\n          data-morph-popover-portal=\"\"\n          // Wrapper carries the shadow as a drop-shadow filter, which hugs the\n          // clipped shape below (box-shadow would just get clipped away).\n          variants={wrap}\n          initial={reduce ? { opacity: 0 } : \"hidden\"}\n          animate={reduce ? { opacity: 1 } : \"show\"}\n          exit={reduce ? { opacity: 0 } : \"hidden\"}\n          transition={reduce ? { duration: 0.12 } : undefined}\n          style={{\n            left,\n            top,\n            visibility: layout ? \"visible\" : \"hidden\",\n            transformOrigin: originFor(side, align),\n          }}\n          className=\"fixed z-[9999] [filter:drop-shadow(0_10px_18px_rgba(0,0,0,0.14))]\"\n        >\n          <motion.div\n            ref={ctx.contentRef}\n            id={ctx.contentId}\n            role=\"dialog\"\n            aria-labelledby={ctx.triggerId}\n            variants={clip}\n            style={{ borderRadius: radius }}\n            className={cn(\n              \"overflow-hidden border border-border bg-background\",\n              className,\n            )}\n          >\n            {children}\n          </motion.div>\n        </motion.div>\n      ) : null}\n    </AnimatePresence>,\n    document.body,\n  );\n}\n"},{"path":"lib/utils.ts","type":"util","content":"import { clsx, type ClassValue } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs))\n}\n"},{"path":"lib/ease.ts","type":"util","content":"// Shared motion tokens. Easing curves mirror the CSS custom properties in\n// globals.css; springs are the canonical physics used across components.\n// Strong custom variants — defaults like `ease-in`/`ease-out` feel weak.\n\nexport const EASE_OUT = [0.16, 1, 0.3, 1] as const;\nexport const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;\nexport const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;\n\n/** CSS string form of EASE_OUT for inline style transitions. */\nexport const EASE_OUT_CSS = \"cubic-bezier(0.16, 1, 0.3, 1)\";\n\n/** Press feedback on buttons and other tappable surfaces. */\nexport const SPRING_PRESS = {\n  type: \"spring\",\n  stiffness: 500,\n  damping: 30,\n  mass: 0.6,\n} as const;\n\n/** Content swaps — label/icon slots trading places inside a control. */\nexport const SPRING_SWAP = {\n  type: \"spring\",\n  stiffness: 460,\n  damping: 30,\n  mass: 0.55,\n} as const;\n\n/** Overlay panel entrances — modals and sheets summoned by pointer. */\nexport const SPRING_PANEL = {\n  type: \"spring\",\n  stiffness: 420,\n  damping: 40,\n  mass: 0.5,\n} as const;\n\n/** Shared-layout glides — pills, indicators and panels morphing between positions. */\nexport const SPRING_LAYOUT = {\n  type: \"spring\",\n  stiffness: 360,\n  damping: 32,\n  mass: 0.6,\n} as const;\n\n/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */\nexport const SPRING_MOUSE = {\n  stiffness: 200,\n  damping: 15,\n  mass: 0.3,\n} as const;\n\n/** Dragged handles and fills (sliders) — critically damped `useSpring` config,\n * so the value follows the pointer butterily and never rebounds off an end. */\nexport const SPRING_GLIDE = {\n  stiffness: 700,\n  damping: 50,\n  mass: 0.5,\n} as const;\n"},{"path":"components/motion/popover-position.ts","type":"util","content":"\"use client\";\n\nimport {\n  type MutableRefObject,\n  useCallback,\n  useLayoutEffect,\n  useState,\n} from \"react\";\n\nexport type PortalLayout = {\n  trigger: {\n    left: number;\n    top: number;\n    width: number;\n    height: number;\n  };\n  content: {\n    width: number;\n    height: number;\n  };\n};\n\nfunction sameLayout(a: PortalLayout | null, b: PortalLayout) {\n  return (\n    a?.trigger.left === b.trigger.left &&\n    a.trigger.top === b.trigger.top &&\n    a.trigger.width === b.trigger.width &&\n    a.trigger.height === b.trigger.height &&\n    a.content.width === b.content.width &&\n    a.content.height === b.content.height\n  );\n}\n\n/** Measures a trigger and portalled panel in viewport coordinates. */\nexport function usePopoverPortalPosition<\n  TriggerElement extends HTMLElement,\n  ContentElement extends HTMLElement,\n>(\n  triggerRef: MutableRefObject<TriggerElement | null>,\n  contentRef: MutableRefObject<ContentElement | null>,\n  active: boolean,\n) {\n  const [layout, setLayout] = useState<PortalLayout | null>(null);\n\n  const update = useCallback(() => {\n    const trigger = triggerRef.current;\n    const content = contentRef.current;\n    if (!trigger || !content) return;\n\n    const rect = trigger.getBoundingClientRect();\n    const next: PortalLayout = {\n      trigger: {\n        left: rect.left,\n        top: rect.top,\n        width: rect.width,\n        height: rect.height,\n      },\n      content: {\n        width: content.offsetWidth,\n        height: content.offsetHeight,\n      },\n    };\n    setLayout((current) => (sameLayout(current, next) ? current : next));\n  }, [contentRef, triggerRef]);\n\n  useLayoutEffect(() => {\n    update();\n    if (!active) return;\n\n    const trigger = triggerRef.current;\n    const content = contentRef.current;\n    const observer = new ResizeObserver(update);\n    if (trigger) observer.observe(trigger);\n    if (content) observer.observe(content);\n\n    window.addEventListener(\"scroll\", update, true);\n    window.addEventListener(\"resize\", update);\n    return () => {\n      observer.disconnect();\n      window.removeEventListener(\"scroll\", update, true);\n      window.removeEventListener(\"resize\", update);\n    };\n  }, [active, contentRef, triggerRef, update]);\n\n  return layout;\n}\n"},{"path":"components/previews/motion/date-picker.preview.tsx","type":"preview","content":"\"use client\";\n\nimport { useState } from \"react\";\nimport { DatePicker } from \"@/components/motion/date-picker\";\n\nexport function DatePickerPreview() {\n  const [date, setDate] = useState<Date | null>(null);\n\n  return (\n    <div className=\"flex min-h-[26rem] flex-col items-center gap-2 pt-8\">\n      <span className=\"text-sm text-muted-foreground\">Due date</span>\n      <DatePicker value={date} onValueChange={setDate} />\n    </div>\n  );\n}\n"}]}