{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"mini-calendar","type":"registry:component","title":"Mini calendar","description":"Months slide past in the direction you travel.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/mini-calendar.tsx","type":"registry:component","content":"\"use client\";\n\nimport {\n  useEffect,\n  useId,\n  useRef,\n  useState,\n  useSyncExternalStore,\n} from \"react\";\nimport {\n  AnimatePresence,\n  LayoutGroup,\n  MotionConfig,\n  motion,\n  useIsPresent,\n  type Variants,\n} from \"motion/react\";\nimport { cn } from \"@/lib/utils\";\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\n// Far enough to read as travel, short enough that the fade does most of the\n// work and the grid never looks like it is leaving the card.\nconst SLIDE = 56;\nconst GRID: Variants = {\n  enter: (dir: number) => ({ x: dir * SLIDE, opacity: 0, filter: \"blur(4px)\" }),\n  center: {\n    x: 0,\n    opacity: 1,\n    filter: \"blur(0px)\",\n    transition: { duration: 0.25, ease: EASE_OUT },\n  },\n  // Leaves quicker and travels less than the incoming grid arrives, so the\n  // eye goes straight to the new month.\n  exit: (dir: number) => ({\n    x: dir * -SLIDE * 0.6,\n    opacity: 0,\n    filter: \"blur(2px)\",\n    transition: { duration: 0.18, ease: EASE_OUT },\n  }),\n};\nconst TITLE: Variants = {\n  enter: { opacity: 0, filter: \"blur(4px)\" },\n  center: {\n    opacity: 1,\n    filter: \"blur(0px)\",\n    transition: { duration: 0.25, ease: EASE_OUT },\n  },\n  exit: {\n    opacity: 0,\n    filter: \"blur(2px)\",\n    transition: { duration: 0.15, ease: EASE_OUT },\n  },\n};\n// No bounce: a circle that overshoots would briefly mark the wrong day.\nconst SELECT = { type: \"spring\", duration: 0.3, bounce: 0 } as const;\n\nconst WEEKDAYS = [\n  \"Sunday\",\n  \"Monday\",\n  \"Tuesday\",\n  \"Wednesday\",\n  \"Thursday\",\n  \"Friday\",\n  \"Saturday\",\n];\n// Six weeks covers every month, so the grid is always the same height and\n// the month buttons never move.\nconst CELLS = 42;\n\nconst pad = (n: number) => String(n).padStart(2, \"0\");\nconst toIso = (date: Date) =>\n  `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;\nconst fromIso = (iso: string) => {\n  const [y, m, d] = iso.split(\"-\").map(Number);\n  return new Date(y, m - 1, d);\n};\n// Months as one running number, so comparing two tells the direction.\nconst monthIndex = (date: Date) => date.getFullYear() * 12 + date.getMonth();\nconst addDays = (iso: string, days: number) => {\n  const date = fromIso(iso);\n  return toIso(\n    new Date(date.getFullYear(), date.getMonth(), date.getDate() + days),\n  );\n};\n// Keeps the day of month, clamped so Jan 31 plus one month is Feb 28.\nconst addMonths = (iso: string, months: number) => {\n  const date = fromIso(iso);\n  const y = date.getFullYear();\n  const m = date.getMonth() + months;\n  const last = new Date(y, m + 1, 0).getDate();\n  return toIso(new Date(y, m, Math.min(date.getDate(), last)));\n};\nconst monthTitle = (month: number) =>\n  new Date(Math.floor(month / 12), month % 12, 1).toLocaleDateString(\"en-US\", {\n    month: \"long\",\n    year: \"numeric\",\n  });\nconst dayLabel = (date: Date) =>\n  date.toLocaleDateString(\"en-US\", {\n    weekday: \"long\",\n    month: \"long\",\n    day: \"numeric\",\n    year: \"numeric\",\n  });\n\n// The server can't know the viewer's date or time zone, so it renders an\n// empty shell of the same size and the client fills it in on hydration.\nconst noSubscribe = () => () => {};\nconst useToday = () =>\n  useSyncExternalStore(\n    noSubscribe,\n    () => toIso(new Date()),\n    () => null,\n  );\n\nexport function MiniCalendar({\n  onSelect,\n  className,\n}: {\n  onSelect?: (iso: string) => void;\n  className?: string;\n}) {\n  const today = useToday();\n  // Null until the user acts, meaning \"today\" and \"today's month\".\n  const [selected, setSelected] = useState<string | null>(null);\n  const [focused, setFocused] = useState<string | null>(null);\n  const [month, setMonth] = useState<number | null>(null);\n  const [direction, setDirection] = useState(1);\n  const moveFocus = useRef(false);\n  const gridRef = useRef<HTMLDivElement>(null);\n  const titleId = useId();\n\n  const selectedIso = selected ?? today;\n  const focusedIso = focused ?? selectedIso;\n  const shownMonth =\n    month ?? (selectedIso ? monthIndex(fromIso(selectedIso)) : null);\n\n  // After a keyboard move, focus follows to the day's button, which may be\n  // in a grid that has only just mounted.\n  useEffect(() => {\n    if (!moveFocus.current) return;\n    moveFocus.current = false;\n    gridRef.current\n      ?.querySelector<HTMLButtonElement>(\n        `[data-month=\"${shownMonth}\"] [data-date=\"${focusedIso}\"]`,\n      )\n      ?.focus({ preventScroll: true });\n  }, [focusedIso, shownMonth]);\n\n  if (!today || !focusedIso || shownMonth === null) {\n    return <Shell className={className} />;\n  }\n\n  const showMonth = (next: number) => {\n    if (next === shownMonth) return;\n    setDirection(next > shownMonth ? 1 : -1);\n    setMonth(next);\n  };\n\n  const goTo = (iso: string, takeFocus: boolean) => {\n    setFocused(iso);\n    showMonth(monthIndex(fromIso(iso)));\n    moveFocus.current = takeFocus;\n  };\n\n  const select = (iso: string) => {\n    setSelected(iso);\n    goTo(iso, false);\n    onSelect?.(iso);\n  };\n\n  // The buttons move the grid a month and carry the roving focus with it,\n  // without pulling focus off the button itself.\n  const step = (months: number) => {\n    const iso = addMonths(focusedIso, months);\n    setFocused(iso);\n    showMonth(monthIndex(fromIso(iso)));\n  };\n\n  const onKeyDown = (event: React.KeyboardEvent) => {\n    const weekday = fromIso(focusedIso).getDay();\n    const years = event.shiftKey ? 12 : 1;\n    const moves: Record<string, () => string> = {\n      ArrowLeft: () => addDays(focusedIso, -1),\n      ArrowRight: () => addDays(focusedIso, 1),\n      ArrowUp: () => addDays(focusedIso, -7),\n      ArrowDown: () => addDays(focusedIso, 7),\n      Home: () => addDays(focusedIso, -weekday),\n      End: () => addDays(focusedIso, 6 - weekday),\n      PageUp: () => addMonths(focusedIso, -years),\n      PageDown: () => addMonths(focusedIso, years),\n    };\n    const move = moves[event.key];\n    if (!move) return;\n    event.preventDefault();\n    goTo(move(), true);\n  };\n\n  return (\n    <MotionConfig reducedMotion=\"user\">\n      <div\n        className={cn(\n          \"w-[340px] max-w-full rounded-[28px] bg-background p-4 shadow-raised\",\n          className,\n        )}\n      >\n        <div className=\"mb-2 flex h-10 items-center justify-between\">\n          {/* Its own positioning context, so the outgoing title can sit on\n              top of the incoming one while they crossfade. */}\n          <div aria-hidden className=\"relative flex-1 pl-3\">\n            <AnimatePresence mode=\"popLayout\" initial={false}>\n              <motion.span\n                key={shownMonth}\n                variants={TITLE}\n                initial=\"enter\"\n                animate=\"center\"\n                exit=\"exit\"\n                className=\"block text-[16px] font-medium whitespace-nowrap text-foreground\"\n              >\n                {monthTitle(shownMonth)}\n              </motion.span>\n            </AnimatePresence>\n          </div>\n          <span id={titleId} className=\"sr-only\" aria-live=\"polite\">\n            {monthTitle(shownMonth)}\n          </span>\n          <div className=\"flex\">\n            <MonthButton label=\"Previous month\" onClick={() => step(-1)}>\n              <path d=\"M10 3.5 5.5 8l4.5 4.5\" />\n            </MonthButton>\n            <MonthButton label=\"Next month\" onClick={() => step(1)}>\n              <path d=\"m6 3.5 4.5 4.5L6 12.5\" />\n            </MonthButton>\n          </div>\n        </div>\n\n        {/* Clips the sliding grids at the card edge. The 4px of padding\n            buys back room for focus outlines on the outer days. */}\n        <div\n          ref={gridRef}\n          className=\"relative -m-1 overflow-hidden p-1\"\n          onKeyDown={onKeyDown}\n        >\n          <AnimatePresence mode=\"popLayout\" initial={false} custom={direction}>\n            <MonthGrid\n              key={shownMonth}\n              month={shownMonth}\n              direction={direction}\n              today={today}\n              selected={selectedIso}\n              focused={focusedIso}\n              labelledBy={titleId}\n              onSelect={select}\n            />\n          </AnimatePresence>\n        </div>\n      </div>\n    </MotionConfig>\n  );\n}\n\nfunction MonthGrid({\n  ref,\n  month,\n  direction,\n  today,\n  selected,\n  focused,\n  labelledBy,\n  onSelect,\n}: {\n  // popLayout measures the outgoing grid through this ref.\n  ref?: React.Ref<HTMLDivElement>;\n  month: number;\n  direction: number;\n  today: string;\n  selected: string | null;\n  focused: string;\n  labelledBy: string;\n  onSelect: (iso: string) => void;\n}) {\n  // The outgoing grid stays in the DOM while it fades, but is gone as far as\n  // focus and screen readers are concerned.\n  const present = useIsPresent();\n  const first = new Date(Math.floor(month / 12), month % 12, 1);\n  const start = first.getDay();\n  const days = Array.from(\n    { length: CELLS },\n    (_, i) =>\n      new Date(first.getFullYear(), first.getMonth(), i - start + 1),\n  );\n  const weeks = Array.from({ length: CELLS / 7 }, (_, w) =>\n    days.slice(w * 7, w * 7 + 7),\n  );\n\n  return (\n    <motion.div\n      ref={ref}\n      custom={direction}\n      variants={GRID}\n      initial=\"enter\"\n      animate=\"center\"\n      exit=\"exit\"\n      data-month={month}\n      inert={!present}\n    >\n      {/* Scoped per month, so the selection springs between days of one\n          month but never flies across from the outgoing grid. */}\n      <LayoutGroup id={`${labelledBy}-${month}`}>\n        <table\n          role=\"grid\"\n          aria-labelledby={labelledBy}\n          className=\"w-full border-collapse\"\n        >\n          <thead>\n            <tr>\n              {WEEKDAYS.map((day) => (\n                <th\n                  key={day}\n                  scope=\"col\"\n                  abbr={day}\n                  className=\"h-8 p-0 text-center text-xs font-medium text-muted-foreground\"\n                >\n                  {day.slice(0, 2)}\n                </th>\n              ))}\n            </tr>\n          </thead>\n          <tbody>\n            {weeks.map((week, w) => (\n              <tr key={w}>\n                {week.map((date) => {\n                  const iso = toIso(date);\n                  const isSelected = iso === selected;\n                  const outside = monthIndex(date) !== month;\n                  return (\n                    <td\n                      key={iso}\n                      role=\"gridcell\"\n                      aria-selected={isSelected}\n                      className=\"p-0\"\n                    >\n                      <button\n                        type=\"button\"\n                        data-date={iso}\n                        tabIndex={iso === focused ? 0 : -1}\n                        aria-label={dayLabel(date)}\n                        aria-current={iso === today ? \"date\" : undefined}\n                        onClick={() => onSelect(iso)}\n                        className={cn(\n                          \"relative flex size-11 touch-manipulation items-center justify-center rounded-full text-sm tabular-nums outline-hidden select-none\",\n                          \"transition-[scale,color,background-color] duration-150 ease-out active:scale-[0.96] motion-reduce:transition-[color,background-color]\",\n                          \"focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-foreground\",\n                          isSelected\n                            ? \"text-background\"\n                            : cn(\n                                \"hover:bg-foreground/[0.06]\",\n                                outside ? \"text-muted-foreground/60\" : \"text-foreground\",\n                              ),\n                        )}\n                      >\n                        {isSelected && (\n                          <motion.span\n                            layoutId=\"selected\"\n                            aria-hidden\n                            transition={SELECT}\n                            className=\"absolute inset-0 rounded-full bg-foreground\"\n                          />\n                        )}\n                        <span className=\"relative\">{date.getDate()}</span>\n                        {iso === today && (\n                          <span\n                            aria-hidden\n                            className=\"absolute bottom-1.5 left-1/2 size-1 -translate-x-1/2 rounded-full bg-current\"\n                          />\n                        )}\n                      </button>\n                    </td>\n                  );\n                })}\n              </tr>\n            ))}\n          </tbody>\n        </table>\n      </LayoutGroup>\n    </motion.div>\n  );\n}\n\n// Same footprint as the real calendar, for the server render.\nfunction Shell({ className }: { className?: string }) {\n  return (\n    <div\n      className={cn(\n        \"w-[340px] max-w-full rounded-[28px] bg-background p-4 shadow-raised\",\n        className,\n      )}\n    >\n      {/* Header row plus the 32px weekday row and six 44px weeks. */}\n      <div className=\"mb-2 h-10\" />\n      <div className=\"h-[296px]\" />\n    </div>\n  );\n}\n\nfunction MonthButton({\n  label,\n  onClick,\n  children,\n}: {\n  label: string;\n  onClick: () => void;\n  children: React.ReactNode;\n}) {\n  return (\n    <button\n      type=\"button\"\n      aria-label={label}\n      onClick={onClick}\n      className=\"flex size-10 touch-manipulation items-center justify-center rounded-full text-muted-foreground outline-hidden transition-[scale,color,background-color] duration-150 ease-out select-none hover:bg-foreground/[0.06] hover:text-foreground focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-foreground active:scale-[0.96] motion-reduce:transition-[color,background-color]\"\n    >\n      <svg\n        viewBox=\"0 0 16 16\"\n        className=\"size-5\"\n        fill=\"none\"\n        stroke=\"currentColor\"\n        strokeWidth={1.5}\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n        aria-hidden\n      >\n        {children}\n      </svg>\n    </button>\n  );\n}\n\nexport default function MiniCalendarDemo() {\n  return <MiniCalendar />;\n}\n"}],"cssVars":{"light":{"shadow-raised":"0 0 0 1px oklch(0 0 0 / 0.06), 0 1px 2px oklch(0 0 0 / 0.06), 0 6px 16px -6px oklch(0 0 0 / 0.12)"},"dark":{"shadow-raised":"0 0 0 1px oklch(1 0 0 / 0.08), 0 1px 2px oklch(0 0 0 / 0.4), 0 6px 16px -6px oklch(0 0 0 / 0.6)"},"theme":{"shadow-raised":"var(--shadow-raised)"}},"categories":["inputs"],"docs":"From ui lab: https://lab.xevrion.dev/lab/mini-calendar"}