{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"calendar","type":"registry:ui","title":"Calendar","description":"Dependency-free date picker grid with single or range selection, springy month slides, range preview on hover and full keyboard navigation.","dependencies":["motion","lucide-react"],"registryDependencies":["utils"],"files":[{"path":"registry/ui/calendar.tsx","type":"registry:ui","content":"\"use client\";\n\nimport { useEffect, useId, useRef, useState, useSyncExternalStore, type KeyboardEvent, type ReactNode } from \"react\";\nimport { AnimatePresence, MotionConfig, motion, useIsPresent } from \"motion/react\";\nimport { ChevronLeft, ChevronRight } from \"lucide-react\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface DateRange {\n  from: Date;\n  to?: Date;\n}\n\ninterface BaseProps {\n  /** Month shown first. Defaults to the selection, else the current month. */\n  defaultMonth?: Date;\n  onMonthChange?: (month: Date) => void;\n  /** 0 = Sunday, 1 = Monday. */\n  weekStartsOn?: 0 | 1;\n  /** BCP 47 locale for month and weekday names. Fixed default keeps SSR and client in sync. */\n  locale?: string;\n  /** Earliest selectable day. */\n  min?: Date;\n  /** Latest selectable day. */\n  max?: Date;\n  isDateDisabled?: (date: Date) => boolean;\n  className?: string;\n}\n\nexport interface CalendarSingleProps extends BaseProps {\n  mode?: \"single\";\n  selected?: Date | null;\n  defaultSelected?: Date | null;\n  onSelect?: (date: Date) => void;\n}\n\nexport interface CalendarRangeProps extends BaseProps {\n  mode: \"range\";\n  selected?: DateRange | null;\n  defaultSelected?: DateRange | null;\n  onSelect?: (range: DateRange) => void;\n}\n\nexport type CalendarProps = CalendarSingleProps | CalendarRangeProps;\n\n// Tiny date helpers: local-time calendar days, no library.\nconst mk = (y: number, m: number, d: number) => new Date(y, m, d);\nconst addDays = (d: Date, n: number) => mk(d.getFullYear(), d.getMonth(), d.getDate() + n);\nconst monthStart = (d: Date) => mk(d.getFullYear(), d.getMonth(), 1);\nconst addMonths = (d: Date, n: number) =>\n  mk(d.getFullYear(), d.getMonth() + n, Math.min(d.getDate(), mk(d.getFullYear(), d.getMonth() + n + 1, 0).getDate()));\nconst num = (d: Date) => d.getFullYear() * 10000 + d.getMonth() * 100 + d.getDate();\nconst same = (a?: Date | null, b?: Date | null) => !!a && !!b && num(a) === num(b);\nconst ymd = (d: Date) =>\n  `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, \"0\")}-${String(d.getDate()).padStart(2, \"0\")}`;\nconst toRange = (v?: Date | DateRange | null): DateRange | null => (v instanceof Date ? { from: v, to: v } : (v ?? null));\n\n// \"Today\" only exists on the client; the server snapshot is empty so hydration never mismatches.\nconst noSubscribe = () => () => {};\nfunction useToday() {\n  const key = useSyncExternalStore(noSubscribe, () => ymd(new Date()), () => \"\");\n  if (!key) return null;\n  const [y, m, d] = key.split(\"-\").map(Number);\n  return mk(y, m - 1, d);\n}\n\nconst slide = {\n  enter: (dir: number) => ({ x: `${dir * 45}%`, opacity: 0 }),\n  center: { x: \"0%\", opacity: 1 },\n  exit: (dir: number) => ({ x: `${dir * -45}%`, opacity: 0 }),\n};\n\nfunction MonthBody({ monthKey, dir, children }: { monthKey: string; dir: number; children: ReactNode }) {\n  const present = useIsPresent(); // the outgoing month stays visible while sliding, but not interactive\n  return (\n    <motion.div\n      role=\"rowgroup\"\n      data-month={monthKey}\n      inert={!present}\n      custom={dir}\n      variants={slide}\n      initial=\"enter\"\n      animate=\"center\"\n      exit=\"exit\"\n      transition={{ x: { type: \"spring\", stiffness: 420, damping: 40 }, opacity: { duration: 0.2 } }}\n      className=\"grid w-full gap-y-1\"\n    >\n      {children}\n    </motion.div>\n  );\n}\n\nexport function Calendar(props: CalendarProps) {\n  const { defaultMonth, onMonthChange, weekStartsOn = 0, locale = \"en-US\", min, max, isDateDisabled, className } = props;\n  const range = props.mode === \"range\";\n  const [innerSel, setInnerSel] = useState(() => toRange(props.defaultSelected));\n  const sel = props.selected !== undefined ? toRange(props.selected) : innerSel;\n  const today = useToday();\n  const [monthState, setMonthState] = useState(() => {\n    const anchor = defaultMonth ?? sel?.from;\n    return anchor ? monthStart(anchor) : null;\n  });\n  const month = monthState ?? (today && monthStart(today));\n  const [dir, setDir] = useState(1);\n  const [focused, setFocused] = useState<Date | null>(null);\n  const [hover, setHover] = useState<Date | null>(null);\n  const focusPending = useRef(false);\n  const gridRef = useRef<HTMLDivElement>(null);\n  const labelId = useId();\n\n  const fmt = (o: Intl.DateTimeFormatOptions) => new Intl.DateTimeFormat(locale, o);\n  const monthFmt = fmt({ month: \"long\", year: \"numeric\" });\n  const dayFmt = fmt({ weekday: \"long\", month: \"long\", day: \"numeric\", year: \"numeric\" });\n  const weekdayShort = fmt({ weekday: \"short\" });\n  const weekdayLong = fmt({ weekday: \"long\" });\n  const weekdays = Array.from({ length: 7 }, (_, i) => mk(2024, 0, 7 + ((i + weekStartsOn) % 7))); // 2024-01-07 is a Sunday\n\n  const inMonth = (d: Date) => !!month && d.getMonth() === month.getMonth() && d.getFullYear() === month.getFullYear();\n  const disabled = (d: Date) => (!!min && num(d) < num(min)) || (!!max && num(d) > num(max)) || !!isDateDisabled?.(d);\n\n  const goto = (target: Date) => {\n    const m = monthStart(target);\n    if (month && same(m, month)) return;\n    setDir(month && num(m) < num(month) ? -1 : 1);\n    setMonthState(m);\n    onMonthChange?.(m);\n  };\n\n  const select = (d: Date) => {\n    if (disabled(d)) return;\n    setFocused(d);\n    goto(d);\n    let next: DateRange;\n    if (!range) next = { from: d, to: d };\n    else if (!sel || sel.to) next = { from: d };\n    else next = num(d) < num(sel.from) ? { from: d, to: sel.from } : { from: sel.from, to: d };\n    if (props.selected === undefined) setInnerSel(next);\n    if (props.mode === \"range\") props.onSelect?.(next);\n    else props.onSelect?.(d);\n  };\n\n  // WAI-ARIA date grid keys: arrows by day/week, Home/End within the week, PageUp/Down by month (Shift: year).\n  const onKey = (e: KeyboardEvent<HTMLButtonElement>, d: Date) => {\n    const col = (d.getDay() - weekStartsOn + 7) % 7;\n    const moves: Record<string, Date> = {\n      ArrowLeft: addDays(d, -1),\n      ArrowRight: addDays(d, 1),\n      ArrowUp: addDays(d, -7),\n      ArrowDown: addDays(d, 7),\n      Home: addDays(d, -col),\n      End: addDays(d, 6 - col),\n      PageUp: addMonths(d, e.shiftKey ? -12 : -1),\n      PageDown: addMonths(d, e.shiftKey ? 12 : 1),\n    };\n    const next = moves[e.key];\n    if (!next) return;\n    e.preventDefault();\n    focusPending.current = true;\n    setFocused(next);\n    goto(next);\n  };\n\n  useEffect(() => {\n    if (!focusPending.current || !focused || !month) return;\n    focusPending.current = false;\n    gridRef.current\n      ?.querySelector<HTMLElement>(`[data-month=\"${ymd(month)}\"] [data-date=\"${ymd(focused)}\"]`)\n      ?.focus({ preventScroll: true });\n  }, [focused, month]);\n\n  const tabDate = [focused, sel?.from, today].find((d) => d && inMonth(d)) ?? month;\n\n  // While picking a range end, preview it under the pointer (or keyboard focus).\n  const picking = range && !!sel && !sel.to;\n  const preview = picking ? (hover ?? focused) : null;\n  let lo = sel?.from;\n  let hi = sel?.to;\n  if (picking && sel && preview) [lo, hi] = num(preview) < num(sel.from) ? [preview, sel.from] : [sel.from, preview];\n\n  const days = month\n    ? Array.from({ length: 42 }, (_, i) => addDays(month, i - ((month.getDay() - weekStartsOn + 7) % 7)))\n    : [];\n\n  const renderDay = (d: Date, col: number) => {\n    const outside = !inMonth(d);\n    const off = disabled(d);\n    const isStart = same(d, lo);\n    const isEnd = same(d, hi);\n    const between = !!lo && !!hi && num(d) > num(lo) && num(d) < num(hi);\n    const selected = range ? isStart || isEnd : same(d, sel?.from);\n    const tentative = picking && !same(d, sel?.from);\n    const band = range && lo && hi && !same(lo, hi) && (between || isStart || isEnd);\n\n    return (\n      <div key={ymd(d)} role=\"gridcell\" aria-selected={selected || between || undefined} className=\"relative grid h-10 place-items-center\">\n        {band && (\n          <span\n            aria-hidden\n            className={cn(\n              \"absolute inset-y-0.5 bg-primary/15\",\n              between && \"inset-x-0\",\n              isStart && \"left-1/2 right-0\",\n              isEnd && \"left-0 right-1/2\",\n              col === 0 && \"rounded-l-lg\",\n              col === 6 && \"rounded-r-lg\",\n              tentative && \"bg-primary/10\",\n            )}\n          />\n        )}\n        <button\n          type=\"button\"\n          data-date={ymd(d)}\n          tabIndex={tabDate && same(d, tabDate) && !outside ? 0 : -1}\n          aria-label={dayFmt.format(d)}\n          aria-current={same(d, today) ? \"date\" : undefined}\n          aria-disabled={off || undefined}\n          onClick={() => select(d)}\n          onKeyDown={(e) => onKey(e, d)}\n          onMouseEnter={range ? () => setHover(d) : undefined}\n          className={cn(\n            \"relative isolate grid size-10 place-items-center rounded-lg text-sm tabular-nums outline-none transition-colors\",\n            \"focus-visible:ring-2 focus-visible:ring-ring/70 focus-visible:ring-offset-1 focus-visible:ring-offset-card\",\n            outside ? \"text-muted-foreground/45\" : \"text-foreground\",\n            !selected && !off && \"hover:bg-muted\",\n            selected && \"font-semibold text-primary-foreground\",\n            off && \"cursor-not-allowed text-muted-foreground/35 line-through\",\n          )}\n        >\n          {selected && (\n            <motion.span\n              aria-hidden\n              initial={{ scale: 0.4, opacity: 0 }}\n              animate={{ scale: 1, opacity: 1 }}\n              transition={{ type: \"spring\", stiffness: 520, damping: 28 }}\n              className={cn(\"absolute inset-0 -z-10 rounded-lg bg-primary\", tentative && \"bg-primary/70\", outside && \"opacity-60\")}\n            />\n          )}\n          {d.getDate()}\n          {same(d, today) && (\n            <span\n              aria-hidden\n              className={cn(\n                \"absolute bottom-1 left-1/2 size-1 -translate-x-1/2 rounded-full\",\n                selected ? \"bg-primary-foreground\" : \"bg-primary\",\n              )}\n            />\n          )}\n        </button>\n      </div>\n    );\n  };\n\n  const navBtn =\n    \"grid size-8 place-items-center rounded-lg border border-border text-muted-foreground outline-none transition-[background-color,color,scale] hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60 active:scale-90 disabled:pointer-events-none disabled:opacity-40\";\n\n  return (\n    <MotionConfig reducedMotion=\"user\">\n      <div className={cn(\"inline-block w-fit rounded-xl border border-border bg-card p-3 text-card-foreground\", className)}>\n        <div className=\"mb-2 flex items-center justify-between gap-2 px-1\">\n          <button\n            type=\"button\"\n            aria-label=\"Previous month\"\n            disabled={!month || (!!min && num(addDays(month, -1)) < num(min))}\n            onClick={() => month && goto(addMonths(month, -1))}\n            className={navBtn}\n          >\n            <ChevronLeft className=\"size-4\" />\n          </button>\n          <div id={labelId} aria-live=\"polite\" className=\"overflow-hidden text-sm font-semibold\">\n            {month && (\n              <motion.span\n                key={ymd(month)}\n                className=\"block\"\n                initial={{ opacity: 0, y: dir * 8 }}\n                animate={{ opacity: 1, y: 0 }}\n                transition={{ duration: 0.25 }}\n              >\n                {monthFmt.format(month)}\n              </motion.span>\n            )}\n          </div>\n          <button\n            type=\"button\"\n            aria-label=\"Next month\"\n            disabled={!month || (!!max && num(monthStart(addMonths(month, 1))) > num(max))}\n            onClick={() => month && goto(addMonths(month, 1))}\n            className={navBtn}\n          >\n            <ChevronRight className=\"size-4\" />\n          </button>\n        </div>\n\n        <div ref={gridRef} role=\"grid\" aria-labelledby={labelId} onMouseLeave={() => setHover(null)}>\n          <div role=\"row\" className=\"grid grid-cols-7\">\n            {weekdays.map((w) => (\n              <div\n                key={w.getDay()}\n                role=\"columnheader\"\n                aria-label={weekdayLong.format(w)}\n                className=\"grid h-8 w-10 place-items-center text-xs font-medium text-muted-foreground\"\n              >\n                {weekdayShort.format(w)}\n              </div>\n            ))}\n          </div>\n          <div className=\"relative overflow-hidden\" style={{ height: 6 * 40 + 5 * 4 }}>\n            <AnimatePresence initial={false} mode=\"popLayout\" custom={dir}>\n              {month && (\n                <MonthBody key={ymd(month)} monthKey={ymd(month)} dir={dir}>\n                  {Array.from({ length: 6 }, (_, r) => (\n                    <div key={r} role=\"row\" className=\"grid grid-cols-7\">\n                      {days.slice(r * 7, r * 7 + 7).map(renderDay)}\n                    </div>\n                  ))}\n                </MonthBody>\n              )}\n            </AnimatePresence>\n          </div>\n        </div>\n      </div>\n    </MotionConfig>\n  );\n}\n"}]}