{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"returns-calendar","type":"registry:component","title":"Returns Calendar","description":"Composable monthly returns calendar with Grid and Tooltip parts, controlled month or year selections, and compounded totals. Supply your own years and monthly percentages.","author":"Saurabh <saurabh10102@gmail.com>","dependencies":["clsx","motion","tailwind-merge"],"registryDependencies":[],"files":[{"path":"components/charts/returns-calendar.tsx","type":"registry:component","target":"@components/charts/returns-calendar.tsx","content":"\"use client\";\n// beui.dev/charts/returns-calendar\n\nimport { cn } from \"@/lib/utils\";\nimport { ReturnsCalendarContext, useReturnsCalendarModel } from \"./returns-calendar/context\";\nimport { ReturnsCalendarGrid } from \"./returns-calendar/grid\";\nimport { ReturnsCalendarTooltip } from \"./returns-calendar/tooltip\";\nimport type { ReturnsCalendarProps } from \"./returns-calendar/types\";\n\n/** Compose Grid and Tooltip, or omit children for the complete chart. */\nexport function ReturnsCalendar({ children, className, ...props }: ReturnsCalendarProps) {\n  const model = useReturnsCalendarModel(props);\n  return (\n    <ReturnsCalendarContext.Provider value={model}>\n      <div className={cn(\"w-[480px] max-w-full [--ink-l:0.5] dark:[--ink-l:1]\", className)}>\n        {children === undefined ? (\n          <ReturnsCalendarGrid>\n            <ReturnsCalendarTooltip />\n          </ReturnsCalendarGrid>\n        ) : (\n          children\n        )}\n      </div>\n    </ReturnsCalendarContext.Provider>\n  );\n}\n\nexport { useReturnsCalendar } from \"./returns-calendar/context\";\nexport { ReturnsCalendarGrid } from \"./returns-calendar/grid\";\nexport { ReturnsCalendarTooltip } from \"./returns-calendar/tooltip\";\nexport type {\n  ReturnsCalendarProps,\n  ReturnsCalendarSelection,\n  ReturnsCalendarTooltipData,\n} from \"./returns-calendar/types\";\n\n// A local type alias keeps docgen from listing this data shape as a component.\nexport type ReturnsCalendarCell = import(\"./returns-calendar/types\").ReturnsCalendarCell;\n"},{"path":"components/charts/returns-calendar/context.ts","type":"registry:component","target":"@components/charts/returns-calendar/context.ts","content":"\"use client\";\n\nimport { useReducedMotion } from \"motion/react\";\nimport {\n  createContext,\n  useContext,\n  useEffect,\n  useId,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { useHoverCapable } from \"@/lib/hooks/use-hover-capable\";\nimport type { ReturnsCalendarCell, ReturnsCalendarProps, ReturnsCalendarSelection } from \"./types\";\nimport { compound, MONTHS, same, YEAR } from \"./utils\";\n\n/**\n * Monthly returns as a years by months grid. Each cell tints toward the up or\n * down color by magnitude, and a compounded year column closes every row.\n * Cells spring in on a diagonal wave. Hovering a month glides a tooltip with\n * its value and dims everything that shares neither its row nor its column;\n * hovering a year total replays that row month by month. Clicking a month\n * anchors a span: the grid dims, hovering previews the run from that month to\n * the pointer with its compounded return, a second click locks it and a third\n * clears it. The Year column selects the same way but by whole years — anchor a\n * year, a second year spans every month between them. Hover lifts are gated to\n * pointer devices, and reduced motion keeps the fades only.\n */\nexport function useReturnsCalendarModel({\n  years = [],\n  returns = [],\n  selection: controlledSelection,\n  defaultSelection = null,\n  onSelectionChange,\n}: ReturnsCalendarProps) {\n  const reduce = useReducedMotion();\n  const canHover = useHoverCapable();\n  const [storedHover, setHover] = useState<ReturnsCalendarCell | null>(null);\n  const [internalSelection, setInternalSelection] = useState(defaultSelection);\n  const requestedSelection = controlledSelection === undefined ? internalSelection : controlledSelection;\n  const validCell = (cell: ReturnsCalendarCell) =>\n    Number.isInteger(cell.y) &&\n    Number.isInteger(cell.m) &&\n    cell.y >= 0 &&\n    cell.y < years.length &&\n    cell.m >= 0 &&\n    cell.m <= YEAR;\n  const selection =\n    requestedSelection &&\n    validCell(requestedSelection.start) &&\n    (!requestedSelection.end ||\n      (validCell(requestedSelection.end) &&\n        (requestedSelection.start.m === YEAR) === (requestedSelection.end.m === YEAR)))\n      ? requestedSelection\n      : null;\n  if (requestedSelection && !selection && controlledSelection === undefined) setInternalSelection(null);\n  const hover = storedHover && validCell(storedHover) ? storedHover : null;\n  if (storedHover && !hover) setHover(null);\n  const pinned = selection?.start ?? null;\n  const spanEnd = selection?.end ?? null;\n  const setSelection = (next: ReturnsCalendarSelection | null) => {\n    if (controlledSelection === undefined) setInternalSelection(next);\n    onSelectionChange?.(next);\n  };\n  const gridRef = useRef<HTMLDivElement>(null);\n  const tooltipId = useId();\n  // the entrance wave owns the cells until it has landed; hover lifts take over after\n  const [settled, setSettled] = useState(false);\n  useEffect(() => {\n    const t = setTimeout(() => setSettled(true), reduce ? 0 : (years.length + 13) * 20 + 500);\n    return () => clearTimeout(t);\n  }, [years.length, reduce]);\n\n  // Normalize each displayed row to twelve months so missing values never\n  // shift the following year's positions when a span is compounded.\n  const rows = useMemo(\n    () => years.map((_, y) => MONTHS.map((_, m) => returns[y]?.[m] ?? 0)),\n    [years, returns],\n  );\n  const totals = useMemo(() => rows.map(compound), [rows]);\n  /** every month in order, so a span is one slice */\n  const flat = useMemo(() => rows.flat(), [rows]);\n\n  const valueAt = (y: number, m: number) => returns[y]?.[m] ?? 0;\n  /** percent that saturates a month's tint */\n  const range = 8;\n\n  // one click on a month anchors a span and dims everything else; hovering then\n  // previews the run from the anchor to the pointer and compounds it live, a\n  // second click locks it, and the next click anywhere clears it\n  const ci = (c: ReturnsCalendarCell) => c.y * 12 + c.m;\n  const clear = () => {\n    setSelection(null);\n  };\n  const anchored = pinned !== null && pinned.m !== YEAR;\n  const spanTo = spanEnd ?? (anchored && hover && hover.m !== YEAR ? hover : null);\n  const span =\n    anchored && pinned\n      ? spanTo\n        ? { lo: Math.min(ci(pinned), ci(spanTo)), hi: Math.max(ci(pinned), ci(spanTo)) }\n        : { lo: ci(pinned), hi: ci(pinned) }\n      : null;\n  const spanValue = span ? compound(flat.slice(span.lo, span.hi + 1)) : 0;\n\n  // the Year column runs its own selection: anchor a year, then a second year\n  // spans whole years and compounds every month between them\n  const yearAnchored = pinned !== null && pinned.m === YEAR;\n  const yearTo = spanEnd ?? (yearAnchored && hover && hover.m === YEAR ? hover : null);\n  const yearSpan =\n    yearAnchored && pinned\n      ? { lo: Math.min(pinned.y, (yearTo ?? pinned).y), hi: Math.max(pinned.y, (yearTo ?? pinned).y) }\n      : null;\n  const yearSpanValue = yearSpan ? compound(flat.slice(yearSpan.lo * 12, (yearSpan.hi + 1) * 12)) : 0;\n\n  const select = (cell: ReturnsCalendarCell) => {\n    if (spanEnd || same(pinned, cell.y, cell.m)) clear();\n    // extend within the same track — month→month or year→year; a different track re-anchors\n    else if (pinned && (pinned.m === YEAR) === (cell.m === YEAR)) setSelection({ start: pinned, end: cell });\n    else {\n      setSelection({ start: cell });\n    }\n  };\n\n  /** the cell the grid reacts to: lift, labels and the year replay follow the pointer */\n  const hot = hover ?? spanEnd ?? pinned;\n  /** the cell the tooltip hangs from: a locked span keeps it on its end */\n  const tip = spanEnd ?? hover ?? pinned;\n  // the year replay is a plain-hover flourish; hold it back while a year span is being built\n  const sweepRow = !yearAnchored && hot?.m === YEAR ? hot.y : null;\n  const showSpan = span !== null && span.lo !== span.hi;\n  const showYearSpan = yearSpan !== null && yearSpan.lo !== yearSpan.hi;\n  const tipValue = showYearSpan\n    ? yearSpanValue\n    : showSpan && span\n      ? spanValue\n      : tip\n        ? tip.m === YEAR\n          ? totals[tip.y]\n          : valueAt(tip.y, tip.m)\n        : 0;\n  const tipLabel =\n    showYearSpan && yearSpan\n      ? `${years[yearSpan.lo]} – ${years[yearSpan.hi]}`\n      : showSpan && span\n        ? `${MONTHS[span.lo % 12]} ${years[Math.floor(span.lo / 12)]} – ${MONTHS[span.hi % 12]} ${years[Math.floor(span.hi / 12)]}`\n        : tip\n          ? tip.m === YEAR\n            ? `${years[tip.y]}`\n            : `${MONTHS[tip.m]} ${years[tip.y]}`\n          : \"\";\n  const tipNote =\n    showYearSpan && yearSpan\n      ? `${yearSpan.hi - yearSpan.lo + 1} years`\n      : showSpan && span\n        ? `${span.hi - span.lo + 1} months`\n        : tip?.m === YEAR\n          ? \"for the year\"\n          : null;\n  const enter = (y: number, m: number) => () => setHover({ y, m });\n  const press = (y: number, m: number) => () => select({ y, m });\n  const clearOnEscape = (e: { key: string }) => {\n    if (e.key === \"Escape\") clear();\n  };\n\n  return {\n    years,\n    reduce,\n    canHover,\n    hover,\n    pinned,\n    spanEnd,\n    settled,\n    totals,\n    valueAt,\n    range,\n    clear,\n    span,\n    yearSpan,\n    hot,\n    tip,\n    sweepRow,\n    tipValue,\n    tipLabel,\n    tipNote,\n    enter,\n    press,\n    clearOnEscape,\n    setHover,\n    gridRef,\n    tooltipId,\n    selection,\n    setSelection,\n  };\n}\n\n\nexport const ReturnsCalendarContext = createContext<ReturnType<typeof useReturnsCalendarModel> | null>(null);\n\nexport function useReturnsCalendar() {\n  const context = useContext(ReturnsCalendarContext);\n  if (!context) throw new Error(\"ReturnsCalendar parts must be inside ReturnsCalendar\");\n  return context;\n}\n\n\n"},{"path":"components/charts/returns-calendar/grid.tsx","type":"registry:component","target":"@components/charts/returns-calendar/grid.tsx","content":"\"use client\";\n\nimport { AnimatePresence, motion } from \"motion/react\";\nimport type { ReactNode } from \"react\";\nimport { EASE_OUT, SPRING_PRESS } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\nimport { useReturnsCalendar } from \"./context\";\nimport { COLS, DOWN, ink, MONTHS, RING, same, signed, tint, UP, YEAR } from \"./utils\";\n\nexport function ReturnsCalendarGrid({ children, className }: { children?: ReactNode; className?: string }) {\n  const {\n    years,\n    reduce,\n    canHover,\n    pinned,\n    settled,\n    totals,\n    valueAt,\n    range,\n    span,\n    yearSpan,\n    hot,\n    sweepRow,\n    enter,\n    press,\n    clearOnEscape,\n    setHover,\n    gridRef,\n    tooltipId,\n  } = useReturnsCalendar();\n  return (\n    <div\n      ref={gridRef}\n      className={cn(\"relative grid gap-1\", className)}\n      style={{ gridTemplateColumns: \"32px repeat(12, 1fr) 52px\" }}\n      onPointerLeave={() => setHover(null)}\n    >\n      <span />\n      {COLS.map((c) => (\n        <span\n          key={c.name}\n          className={cn(\n            \"pb-1 text-center text-[10px] transition-colors duration-200\",\n            hot?.m === c.m ? \"text-foreground\" : \"text-muted-foreground\",\n          )}\n        >\n          {c.initial}\n        </span>\n      ))}\n      <span\n        className={cn(\n          \"pb-1 text-center text-[10px] transition-colors duration-200\",\n          hot?.m === YEAR ? \"text-foreground\" : \"text-muted-foreground\",\n        )}\n      >\n        Year\n      </span>\n\n      {years.map((year, y) => (\n        <div key={year} className=\"contents\">\n          <span\n            className={cn(\n              \"flex items-center justify-end pr-1.5 font-mono text-[10px] tabular-nums transition-colors duration-200\",\n              hot?.y === y ? \"text-foreground\" : \"text-muted-foreground\",\n            )}\n          >\n            {`’${String(year).slice(2)}`}\n          </span>\n\n          {COLS.map(({ name, m }) => {\n            const v = valueAt(y, m);\n            const i = y * 12 + m;\n            const on = same(hot, y, m);\n            const isEnd = span ? i === span.lo || i === span.hi : same(pinned, y, m);\n            // a year span lights whole rows; months in the picked years stay lit, the rest dim\n            const dim = span\n              ? i < span.lo || i > span.hi\n              : yearSpan\n                ? y < yearSpan.lo || y > yearSpan.hi\n                : !!hot && !on && hot.y !== y && hot.m !== m;\n            const lift = settled && on && canHover && !reduce ? 1.15 : 1;\n            return (\n              // the outer span owns the dim so it never fights the transforms inside\n              <span\n                key={`${year}-${name}`}\n                className=\"relative block aspect-square w-full transition-opacity duration-200\"\n                style={{ opacity: dim ? 0.35 : 1 }}\n              >\n                {/* the hit area is the cell plus half the gap on every side, so the grid\n                      has no dead space; the visual inside never takes pointer events */}\n                <motion.button\n                  type=\"button\"\n                  data-return-cell={`${y}-${m}`}\n                  aria-describedby={on ? tooltipId : undefined}\n                  aria-label={`${MONTHS[m]} ${year} ${signed(v, 1)}%`}\n                  aria-pressed={isEnd}\n                  onPointerEnter={enter(y, m)}\n                  onFocus={enter(y, m)}\n                  onBlur={() => setHover(null)}\n                  onClick={press(y, m)}\n                  onKeyDown={clearOnEscape}\n                  className=\"absolute -inset-0.5 block rounded-[5px] outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n                  whileTap={reduce ? undefined : { scale: 0.92, transition: SPRING_PRESS }}\n                >\n                  <motion.span\n                    className=\"pointer-events-none absolute inset-0.5 grid place-items-center rounded-[4px] font-mono text-[9px] font-medium tabular-nums\"\n                    style={{\n                      background: tint(v, range, on),\n                      color: `color-mix(in srgb, var(--foreground) ${Math.round(85 + Math.min(Math.abs(v) / range, 1) * 15)}%, transparent)`,\n                      boxShadow: isEnd ? RING : \"none\",\n                      transition: \"background 150ms, box-shadow 150ms\",\n                    }}\n                    initial={reduce ? false : { opacity: 0, scale: 0.6 }}\n                    // the diagonal wave on entrance; after it lands the hovered cell lifts,\n                    // and hovering the year total replays the row Jan to Dec\n                    animate={\n                      sweepRow === y && !reduce\n                        ? {\n                            opacity: 1,\n                            // a gentle pulse: kept under the cell gap so a peaking cell\n                            // never grows into its neighbours as the wave passes\n                            scale: [1, 1.1, 1],\n                            transition: { duration: 0.36, ease: EASE_OUT, delay: m * 0.035 },\n                          }\n                        : settled\n                          ? { opacity: 1, scale: lift, transition: SPRING_PRESS }\n                          : {\n                              opacity: 1,\n                              scale: 1,\n                              transition: reduce\n                                ? { duration: 0 }\n                                : { ...SPRING_PRESS, delay: (y + m) * 0.02 },\n                            }\n                    }\n                  >\n                    {/* the ring lives INSIDE the cell: inset-0 fills its box and\n                          borderRadius:inherit copies its corner, so it always shares the\n                          cell's exact size, scale (hover lift included) and roundness and\n                          cannot drift however the cells are restyled */}\n                    <AnimatePresence>\n                      {on && !isEnd ? (\n                        <motion.span\n                          className=\"pointer-events-none absolute inset-0 border-[1.5px]\"\n                          style={{ borderRadius: \"inherit\", borderColor: v >= 0 ? UP : DOWN }}\n                          initial={reduce ? false : { opacity: 0 }}\n                          animate={{ opacity: 1 }}\n                          exit={{ opacity: 0 }}\n                          transition={{ duration: 0.12, ease: EASE_OUT }}\n                        />\n                      ) : null}\n                    </AnimatePresence>\n                    {Math.abs(v) >= 4 ? Math.round(v) : \"\"}\n                  </motion.span>\n                </motion.button>\n              </span>\n            );\n          })}\n\n          <span\n            className=\"relative block transition-opacity duration-200\"\n            style={{\n              opacity: (\n                span\n                  ? y < Math.floor(span.lo / 12) || y > Math.floor(span.hi / 12)\n                  : yearSpan\n                    ? y < yearSpan.lo || y > yearSpan.hi\n                    : hot && hot.y !== y\n              )\n                ? 0.35\n                : 1,\n            }}\n          >\n            <motion.button\n              type=\"button\"\n              data-return-cell={`${y}-${YEAR}`}\n              aria-describedby={same(hot, y, YEAR) ? tooltipId : undefined}\n              aria-label={`${year} ${signed(totals[y], 1)}% for the year`}\n              aria-pressed={yearSpan ? y === yearSpan.lo || y === yearSpan.hi : same(pinned, y, YEAR)}\n              onPointerEnter={enter(y, YEAR)}\n              onFocus={enter(y, YEAR)}\n              onBlur={() => setHover(null)}\n              onClick={press(y, YEAR)}\n              onKeyDown={clearOnEscape}\n              className=\"absolute -inset-0.5 block rounded-[5px] outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n              whileTap={reduce ? undefined : { scale: 0.96, transition: SPRING_PRESS }}\n            >\n              <motion.span\n                className=\"pointer-events-none absolute inset-0.5 grid place-items-center rounded-[4px] font-mono text-[11px] font-medium tabular-nums\"\n                // a neutral cell under the colored number: the tint of the same hue ate its contrast\n                style={{\n                  background: same(hot, y, YEAR)\n                    ? \"var(--background)\"\n                    : \"color-mix(in srgb, var(--foreground) 6%, transparent)\",\n                  color: ink(totals[y] >= 0 ? UP : DOWN),\n                  // the ends of a year span carry the locked ring, like a month span's ends\n                  boxShadow: (yearSpan ? y === yearSpan.lo || y === yearSpan.hi : same(pinned, y, YEAR))\n                    ? RING\n                    : same(hot, y, YEAR)\n                      ? \"inset 0 0 0 1px var(--border-strong)\"\n                      : \"none\",\n                  transition: \"background 150ms, box-shadow 150ms\",\n                }}\n                initial={reduce ? false : { opacity: 0 }}\n                animate={{ opacity: 1 }}\n                transition={\n                  reduce ? { duration: 0 } : { duration: 0.4, ease: EASE_OUT, delay: 0.02 * (y + 13) }\n                }\n              >\n                {/* the year total gets the same flush hover ring as the month cells,\n                      unless it already carries a span-end ring */}\n                <AnimatePresence>\n                  {same(hot, y, YEAR) &&\n                  !(yearSpan ? y === yearSpan.lo || y === yearSpan.hi : same(pinned, y, YEAR)) ? (\n                    <motion.span\n                      className=\"pointer-events-none absolute inset-0 border-[1.5px]\"\n                      style={{ borderRadius: \"inherit\", borderColor: totals[y] >= 0 ? UP : DOWN }}\n                      initial={reduce ? false : { opacity: 0 }}\n                      animate={{ opacity: 1 }}\n                      exit={{ opacity: 0 }}\n                      transition={{ duration: 0.12, ease: EASE_OUT }}\n                    />\n                  ) : null}\n                </AnimatePresence>\n                {signed(totals[y], 0)}%\n              </motion.span>\n            </motion.button>\n          </span>\n        </div>\n      ))}\n\n      {children}\n    </div>\n  );\n}\n"},{"path":"components/charts/returns-calendar/tooltip.tsx","type":"registry:component","target":"@components/charts/returns-calendar/tooltip.tsx","content":"\"use client\";\nimport { type ReactNode, useMemo, useState } from \"react\";\nimport { NumberTicker } from \"@/components/motion/number-ticker\";\nimport { Tooltip } from \"@/components/motion/tooltip\";\nimport { cn } from \"@/lib/utils\";\nimport { useReturnsCalendar } from \"./context\";\nimport type { ReturnsCalendarCell, ReturnsCalendarTooltipData } from \"./types\";\nimport { DOWN, ink, UP } from \"./utils\";\n\nexport function ReturnsCalendarTooltip({\n  children,\n  className,\n}: {\n  children?: ReactNode | ((data: ReturnsCalendarTooltipData) => ReactNode);\n  className?: string;\n}) {\n  const { gridRef, tooltipId, tip, tipValue, tipLabel, tipNote } = useReturnsCalendar();\n  const [dismissed, setDismissed] = useState<ReturnsCalendarCell | null>(null);\n  const anchorRef = useMemo(\n    () => ({\n      get current() {\n        return tip\n          ? (gridRef.current?.querySelector<HTMLElement>(`[data-return-cell=\"${tip.y}-${tip.m}\"]`) ?? null)\n          : null;\n      },\n    }),\n    [gridRef, tip],\n  );\n  const data = { label: tipLabel, value: tipValue, note: tipNote };\n  return (\n    <Tooltip\n      key={tip ? `${tip.y}-${tip.m}` : \"closed\"}\n      open={tip !== null && dismissed !== tip}\n      onOpenChange={(open) => {\n        if (!open) setDismissed(tip);\n      }}\n      id={tooltipId}\n      anchorRef={anchorRef}\n      className={cn(\"flex items-center gap-1.5\", className)}\n      content={\n        typeof children === \"function\"\n          ? children(data)\n          : (children ?? (\n              <>\n                <span className=\"text-muted-foreground\">{tipLabel}</span>\n                <span\n                  className=\"inline-flex items-center font-mono tabular-nums\"\n                  style={{ color: ink(tipValue >= 0 ? UP : DOWN) }}\n                >\n                  <NumberTicker\n                    value={Math.round(Math.abs(tipValue) * 10)}\n                    format={(v) => (v / 10).toFixed(1)}\n                    prefix={tipValue >= 0 ? \"+\" : \"−\"}\n                    suffix=\"%\"\n                    duration={0.35}\n                    startOnView={false}\n                  />\n                </span>\n                {tipNote ? <span className=\"text-muted-foreground\">{tipNote}</span> : null}\n              </>\n            ))\n      }\n    />\n  );\n}\n"},{"path":"components/charts/returns-calendar/types.ts","type":"registry:component","target":"@components/charts/returns-calendar/types.ts","content":"import type { ReactNode } from \"react\";\n\n/** Zero-based row and month; month 12 selects the year total. */\nexport type ReturnsCalendarCell = { y: number; m: number };\n\nexport interface ReturnsCalendarSelection {\n  start: ReturnsCalendarCell;\n  end?: ReturnsCalendarCell;\n}\n\nexport interface ReturnsCalendarProps {\n  /** Row labels, one per row of `returns`. */\n  years?: number[];\n  /** `returns[year][month]` in percent, twelve months per row. */\n  returns?: number[][];\n  className?: string;\n  children?: ReactNode;\n  selection?: ReturnsCalendarSelection | null;\n  defaultSelection?: ReturnsCalendarSelection | null;\n  onSelectionChange?: (selection: ReturnsCalendarSelection | null) => void;\n}\n\nexport interface ReturnsCalendarTooltipData {\n  label: string;\n  value: number;\n  note: string | null;\n}\n"},{"path":"lib/utils.ts","type":"registry:lib","target":"@lib/utils.ts","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":"components/charts/returns-calendar/utils.ts","type":"registry:component","target":"@components/charts/returns-calendar/utils.ts","content":"import type { ReturnsCalendarCell } from \"./types\";\n\nexport const UP = \"var(--success)\";\n\nexport const DOWN = \"var(--destructive)\";\n\nexport const MONTHS = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"];\n\nexport const COLS = MONTHS.map((name, m) => ({ name, initial: name[0], m }));\n\n/** The compounded column, addressed like a thirteenth month. */\nexport const YEAR = 12;\n\n/** Compounded return of a run of percentages, in percent. */\nexport const compound = (run: number[]) => (run.reduce((acc, r) => acc * (1 + r / 100), 1) - 1) * 100;\n\nexport const signed = (v: number, dp: number) => `${v >= 0 ? \"+\" : \"−\"}${Math.abs(v).toFixed(dp)}`;\n\n/** A hue as text: on the light page its lightness is capped so 11px numbers reach AA while the chroma stays, in dark it is native (`--ink-l` flips per theme on the root). */\nexport const ink = (c: string) => `oklch(from ${c} min(l, var(--ink-l, 1)) c h)`;\n\n/** magnitude → strength of the one up or down hue, never a second color */\nexport const tint = (v: number, range: number, on: boolean) =>\n  `color-mix(in srgb, ${v >= 0 ? UP : DOWN} ${Math.round(Math.min(Math.abs(v) / range, 1) * 55 + (on ? 24 : 8))}%, transparent)`;\n\nexport const same = (a: ReturnsCalendarCell | null, y: number, m: number) => a?.y === y && a?.m === m;\n\nexport const RING = \"inset 0 0 0 1.5px var(--foreground)\";\n"},{"path":"lib/hooks/use-hover-capable.ts","type":"registry:hook","target":"@lib/hooks/use-hover-capable.ts","content":"\"use client\";\n\nimport { useEffect, useState } from \"react\";\n\n/**\n * Returns true only on devices that have a true hover (mouse / trackpad).\n * Touch devices fire phantom `:hover` on tap that sticks until tap-elsewhere\n * — gate hover-only effects (scale lifts, magnetic pulls) behind this.\n */\nexport function useHoverCapable() {\n  const [canHover, setCanHover] = useState(false);\n\n  useEffect(() => {\n    if (typeof window === \"undefined\" || !window.matchMedia) return;\n    const mq = window.matchMedia(\"(hover: hover) and (pointer: fine)\");\n    const update = () => setCanHover(mq.matches);\n    update();\n    mq.addEventListener?.(\"change\", update);\n    return () => mq.removeEventListener?.(\"change\", update);\n  }, []);\n\n  return canHover;\n}\n"},{"path":"lib/ease.ts","type":"registry:lib","target":"@lib/ease.ts","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/number-ticker.tsx","type":"registry:component","target":"@components/motion/number-ticker.tsx","content":"\"use client\";\n\nimport { animate, motion, useInView, useReducedMotion } from \"motion/react\";\nimport { useEffect, useMemo, useRef, useState } from \"react\";\nimport { EASE_OUT } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface NumberTickerProps {\n  value: number;\n  /** Digits to pad to (left). */\n  pad?: number;\n  /** Per-digit roll duration in seconds. */\n  duration?: number;\n  /** Stagger between digits. */\n  stagger?: number;\n  /** Render only after the element enters the viewport. */\n  startOnView?: boolean;\n  prefix?: string;\n  suffix?: string;\n  /** Add a small blur during digit rolls. */\n  blur?: boolean;\n  className?: string;\n  digitClassName?: string;\n  /** Insert locale group separators (commas). Server-component safe. */\n  locale?: boolean;\n  /** Custom formatter. Client-only — server components must use `locale` instead. */\n  format?: (value: number) => string;\n}\n\nconst DIGIT_HEIGHT_EM = 1.1;\nconst DIGITS = Array.from({ length: 10 }, (_, n) => n);\n\nexport function NumberTicker({\n  value,\n  pad,\n  duration = 0.9,\n  stagger = 0.04,\n  startOnView = true,\n  prefix,\n  suffix,\n  blur = false,\n  className,\n  digitClassName,\n  locale,\n  format,\n}: NumberTickerProps) {\n  const containerRef = useRef<HTMLSpanElement>(null);\n  const inView = useInView(containerRef, { once: true, amount: 0.6 });\n  const [armed, setArmed] = useState(!startOnView);\n\n  useEffect(() => {\n    if (startOnView && inView) setArmed(true);\n  }, [startOnView, inView]);\n\n  const text = useMemo(() => {\n    const rounded = Math.round(value);\n    const formatted = format\n      ? format(rounded)\n      : locale\n        ? rounded.toLocaleString()\n        : rounded.toString();\n    return pad ? formatted.padStart(pad, \"0\") : formatted;\n  }, [value, pad, format, locale]);\n  const glyphs = useMemo(() => {\n    const chars = text.split(\"\");\n    // Key by place value (position from the right): a changing digit keeps its\n    // identity and rolls to the new value instead of remounting and replaying\n    // from 0. Growing numbers add glyphs on the left without re-keying the\n    // ones, tens, hundreds already on screen.\n    return chars.map((char, i) => ({ char, id: `g-${chars.length - 1 - i}` }));\n  }, [text]);\n  const readableText = `${prefix ?? \"\"}${text}${suffix ?? \"\"}`;\n\n  // Stagger is an entrance flourish. Once the reveal has played, value\n  // changes roll every digit immediately — a per-digit delay on live updates\n  // reads as lag.\n  const [entered, setEntered] = useState(false);\n  useEffect(() => {\n    if (!armed || entered) return;\n    const total = (duration + glyphs.length * stagger) * 1000;\n    const t = window.setTimeout(() => setEntered(true), total);\n    return () => window.clearTimeout(t);\n  }, [armed, entered, duration, stagger, glyphs.length]);\n\n  return (\n    <span\n      ref={containerRef}\n      className={cn(\"inline-flex items-center tabular-nums\", className)}\n    >\n      <span className=\"sr-only\">{readableText}</span>\n      <span aria-hidden=\"true\" className=\"inline-flex items-center\">\n        {prefix ? <span>{prefix}</span> : null}\n        {glyphs.map(({ char, id }, i) => {\n          const isDigit = /\\d/.test(char);\n          if (!isDigit) {\n            return (\n              <span key={id} className=\"inline-block\">\n                {char}\n              </span>\n            );\n          }\n          const digit = Number(char);\n          return (\n            <Digit\n              key={id}\n              digit={armed ? digit : 0}\n              delay={entered ? 0 : i * stagger}\n              duration={duration}\n              blur={blur}\n              className={digitClassName}\n            />\n          );\n        })}\n        {suffix ? <span>{suffix}</span> : null}\n      </span>\n    </span>\n  );\n}\n\nfunction Digit({\n  digit,\n  delay,\n  duration,\n  blur,\n  className,\n}: {\n  digit: number;\n  delay: number;\n  duration: number;\n  blur: boolean;\n  className?: string;\n}) {\n  const reduce = useReducedMotion();\n  const columnRef = useRef<HTMLSpanElement>(null);\n\n  useEffect(() => {\n    if (reduce || !blur || !columnRef.current || !Number.isFinite(digit)) {\n      return;\n    }\n\n    const node = columnRef.current;\n    const controls = animate(\n      node,\n      { filter: [\"blur(10px)\", \"blur(0px)\"] },\n      {\n        duration: Math.min(duration * 0.75, 0.32),\n        delay,\n        ease: EASE_OUT,\n      },\n    );\n\n    return () => {\n      controls.stop();\n      node.style.filter = \"blur(0px)\";\n    };\n  }, [blur, delay, digit, duration, reduce]);\n\n  return (\n    <span\n      className={cn(\"relative inline-block overflow-hidden\", className)}\n      style={{ height: `${DIGIT_HEIGHT_EM}em`, width: \"1ch\" }}\n    >\n      <motion.span\n        ref={columnRef}\n        initial={{ y: 0 }}\n        animate={{ y: `-${digit * DIGIT_HEIGHT_EM}em` }}\n        transition={\n          reduce\n            ? { duration: 0 }\n            : { duration, delay, ease: EASE_OUT }\n        }\n        className=\"absolute inset-x-0 top-0 flex flex-col items-center will-change-[transform,filter]\"\n      >\n        {DIGITS.map((n) => (\n          <span\n            key={n}\n            className=\"flex h-[1.1em] items-center justify-center leading-none\"\n          >\n            {n}\n          </span>\n        ))}\n      </motion.span>\n    </span>\n  );\n}\n"},{"path":"components/motion/tooltip.tsx","type":"registry:component","target":"@components/motion/tooltip.tsx","content":"\"use client\";\n\nimport { AnimatePresence } from \"motion/react\";\nimport {\n  cloneElement,\n  isValidElement,\n  type PointerEvent,\n  type ReactElement,\n  type ReactNode,\n  type RefObject,\n  useCallback,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { TooltipSurface } from \"@/components/motion/tooltip-surface\";\nimport { useDismiss } from \"@/lib/hooks/use-dismiss\";\nimport { useHoverGesture } from \"@/lib/hooks/use-hover-gesture\";\nimport { useTapGesture } from \"@/lib/hooks/use-tap-gesture\";\nimport { cn } from \"@/lib/utils\";\n\ntype Side = \"top\" | \"right\" | \"bottom\" | \"left\";\n\nexport interface TooltipProps {\n  content: ReactNode;\n  children?: ReactElement;\n  /** Existing trigger for controlled integrations such as chart cells. */\n  anchorRef?: RefObject<HTMLElement | SVGElement | null>;\n  /** Point within the anchor, as fractions of its rendered width and height. */\n  anchorPoint?: { x: number; y: number };\n  open?: boolean;\n  onOpenChange?: (open: boolean) => void;\n  id?: string;\n  side?: Side;\n  /** Delay before showing (ms). Default 120. */\n  delay?: number;\n  className?: string;\n  /** Classes for the outer wrapper span. Use to fix baseline / fill parent. */\n  wrapperClassName?: string;\n}\n\n// Gap between trigger and tooltip, in px.\nconst GAP = 8;\n\n// Centering transform for the fixed-positioned anchor point, per side.\nconst anchorTransform: Record<Side, string> = {\n  top: \"translate(-50%, -100%)\",\n  bottom: \"translate(-50%, 0)\",\n  left: \"translate(-100%, -50%)\",\n  right: \"translate(0, -50%)\",\n};\n\nconst transformOrigin: Record<Side, string> = {\n  top: \"center bottom\",\n  bottom: \"center top\",\n  left: \"right center\",\n  right: \"left center\",\n};\n\n// Once any tooltip has just closed, neighbouring tooltips open without the\n// initial delay — moving along a toolbar feels instant after the first one.\nconst WARM_WINDOW_MS = 300;\nlet lastHiddenAt = 0;\n\nexport function Tooltip({\n  content,\n  children,\n  side = \"top\",\n  delay = 120,\n  className,\n  wrapperClassName,\n  anchorRef: externalAnchorRef,\n  anchorPoint,\n  open: controlledOpen,\n  onOpenChange,\n  id: providedId,\n}: TooltipProps) {\n  const [internalOpen, setInternalOpen] = useState(false);\n  const open = controlledOpen ?? internalOpen;\n  const setOpen = useCallback(\n    (next: boolean) => {\n      if (controlledOpen === undefined) setInternalOpen(next);\n      onOpenChange?.(next);\n    },\n    [controlledOpen, onOpenChange],\n  );\n  const [coords, setCoords] = useState<{ top: number; left: number } | null>(null);\n  const generatedId = useId();\n  const id = providedId ?? generatedId;\n  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);\n  const wrapperRef = useRef<HTMLSpanElement>(null);\n  const anchorRef = externalAnchorRef ?? wrapperRef;\n  const hover = useHoverGesture();\n  const surfaceRef = useRef<HTMLSpanElement>(null);\n\n  // Anchor point in viewport coords, on the edge of the trigger facing `side`.\n  // Position:fixed means these viewport coords place the tooltip directly, so\n  // it escapes every ancestor's stacking context and overflow.\n  const place = useCallback(() => {\n    const el = anchorRef.current;\n    if (!el) return;\n    const r = el.getBoundingClientRect();\n    const cx = r.left + r.width * (anchorPoint?.x ?? 0.5);\n    const cy = r.top + r.height * (anchorPoint?.y ?? 0.5);\n    const point: Record<Side, { top: number; left: number }> = {\n      top: { top: (anchorPoint ? cy : r.top) - GAP, left: cx },\n      bottom: { top: (anchorPoint ? cy : r.bottom) + GAP, left: cx },\n      left: { top: cy, left: (anchorPoint ? cx : r.left) - GAP },\n      right: { top: cy, left: (anchorPoint ? cx : r.right) + GAP },\n    };\n    const next = point[side];\n    const width = surfaceRef.current?.offsetWidth ?? 0;\n    const height = surfaceRef.current?.offsetHeight ?? 0;\n    const dx = side === \"left\" ? width : side === \"right\" ? 0 : width / 2;\n    const dy = side === \"top\" ? height : side === \"bottom\" ? 0 : height / 2;\n    next.left = Math.max(GAP + dx, Math.min(next.left, window.innerWidth - GAP - width + dx));\n    next.top = Math.max(GAP + dy, Math.min(next.top, window.innerHeight - GAP - height + dy));\n    setCoords(previous => previous?.top === next.top && previous.left === next.left ? previous : next);\n  }, [side, anchorRef, anchorPoint]);\n\n  const positioned = coords !== null;\n  useLayoutEffect(() => {\n    if (!open) return;\n    place();\n    const observer = new ResizeObserver(place);\n    if (anchorRef.current) observer.observe(anchorRef.current);\n    if (positioned && surfaceRef.current) observer.observe(surfaceRef.current);\n    return () => observer.disconnect();\n  }, [open, place, anchorRef, positioned]);\n\n  const show = useCallback(() => {\n    if (timer.current) clearTimeout(timer.current);\n    const warm = Date.now() - lastHiddenAt < WARM_WINDOW_MS;\n    timer.current = setTimeout(\n      () => {\n        place();\n        setOpen(true);\n      },\n      warm ? 0 : delay,\n    );\n  }, [delay, place, setOpen]);\n\n  const hide = useCallback(() => {\n    if (timer.current) {\n      clearTimeout(timer.current);\n      timer.current = null;\n    }\n    if (open) lastHiddenAt = Date.now();\n    setOpen(false);\n  }, [open, setOpen]);\n\n  // A finger never hovers, and Safari does not focus a button on tap either, so\n  // the label is only reachable if the tap itself opens the tooltip. A click\n  // carries no pointerType, so the pointerdown that preceded it is what says\n  // whether this was a tap; keyboard activation arrives with no pointerdown at\n  // all, and focus has already shown the label there.\n  const tap = useTapGesture<boolean>();\n\n  const toggleOnTap = useCallback(() => {\n    const gesture = tap.take();\n    if (!gesture || gesture.pointerType === \"mouse\") return;\n    if (gesture.state) {\n      hide();\n      return;\n    }\n    if (timer.current) clearTimeout(timer.current);\n    place();\n    setOpen(true);\n  }, [hide, place, tap, setOpen]);\n\n  // ...and closed again by the next tap that lands somewhere else. The label\n  // covers nothing interactive, so that tap passes through to what it hit.\n  useDismiss(open, hide, anchorRef);\n\n  // Keep the tooltip pinned to the trigger while it's open and the page scrolls\n  // or resizes (fixed coords are viewport-relative).\n  useEffect(() => {\n    if (!open) return;\n    const onMove = () => place();\n    window.addEventListener(\"scroll\", onMove, true);\n    window.addEventListener(\"resize\", onMove);\n    return () => {\n      window.removeEventListener(\"scroll\", onMove, true);\n      window.removeEventListener(\"resize\", onMove);\n    };\n  }, [open, place]);\n\n  useEffect(\n    () => () => {\n      if (timer.current) clearTimeout(timer.current);\n    },\n    [],\n  );\n\n  if (!externalAnchorRef && !isValidElement(children)) return children;\n\n  // The label describes the trigger, so it has to name the trigger itself.\n  // Everything else the tooltip needs is read off the anchor below instead of\n  // cloned on: a handler written onto the child is the child's handler as far\n  // as that child can tell, and a component that owns its activation —\n  // hard-wiring onClick and spreading the rest of its props over it, as\n  // ThemeToggle does — then runs the tooltip's instead of its own. Composing\n  // with `props.onClick` cannot save it either, because a component element's\n  // props hold nothing the component does internally.\n  const trigger = isValidElement(children)\n    ? cloneElement(children as ReactElement<Record<string, unknown>>, {\n        \"aria-describedby\": id,\n      })\n    : null;\n\n  return (\n    <>\n      {!externalAnchorRef ? (\n        // biome-ignore lint/a11y/noStaticElementInteractions: This wrapper observes bubbling trigger events without replacing the control's handlers.\n        <span\n          ref={wrapperRef}\n          className={cn(\"relative inline-flex align-middle\", wrapperClassName)}\n          // Pointer events, not the mouse pair: a tap fires compatibility\n          // mouseenter/mouseleave that carry no pointerType, which raced the tap\n          // path into opening and closing the same label.\n          onPointerEnter={(event: PointerEvent) => {\n            if (hover.enter(event)) show();\n          }}\n          onPointerLeave={(event: PointerEvent) => {\n            if (hover.leave(event)) hide();\n          }}\n          onFocus={show}\n          onBlur={hide}\n          onPointerDown={(event: PointerEvent) => tap.start(event, open)}\n          // A gesture the platform took away sends no click, and a key press\n          // starts an activation that never had a pointer behind it. Either way\n          // the record has to go, or the next click reads a finger that has long\n          // since lifted.\n          onPointerCancel={tap.drop}\n          onKeyDown={tap.drop}\n          onClick={toggleOnTap}\n        >\n          {trigger}\n        </span>\n      ) : null}\n      {typeof document !== \"undefined\"\n        ? createPortal(\n            <AnimatePresence>\n              {open && coords ? (\n                <span\n                  className=\"pointer-events-none fixed z-[9999]\"\n                  style={{\n                    top: coords.top,\n                    left: coords.left,\n                    transform: anchorTransform[side],\n                  }}\n                >\n                  <TooltipSurface\n                    ref={surfaceRef}\n                    id={id}\n                    side={side}\n                    style={{ transformOrigin: transformOrigin[side], maxWidth: \"calc(100vw - 16px)\", whiteSpace: \"normal\" }}\n                    className={className}\n                  >\n                    {content}\n                  </TooltipSurface>\n                </span>\n              ) : null}\n            </AnimatePresence>,\n            document.body,\n          )\n        : null}\n    </>\n  );\n}\n"},{"path":"components/motion/tooltip-surface.tsx","type":"registry:component","target":"@components/motion/tooltip-surface.tsx","content":"\"use client\";\n\nimport { motion, useReducedMotion, type Variants } from \"motion/react\";\nimport { useMemo, type ComponentProps, type ReactNode, type Ref } from \"react\";\nimport { EASE_OUT } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\ntype Side = \"top\" | \"right\" | \"bottom\" | \"left\";\n\n// Offset is in the direction *away* from the trigger — content originates near\n// the trigger and rises into resting position.\nconst offsetFrom: Record<Side, { x?: number; y?: number }> = {\n  top: { y: 8 },\n  bottom: { y: -8 },\n  left: { x: 8 },\n  right: { x: -8 },\n};\n\n// Small tooltip surfaces need the lighter spawn used by the original Tooltip.\nconst TOOLTIP_SPRING = { type: \"spring\", stiffness: 380, damping: 30, mass: 0.7 } as const;\n\nfunction buildVariants(side: Side): Variants {\n  const o = offsetFrom[side];\n  return {\n    initial: {\n      opacity: 0,\n      scale: 0.9,\n      filter: \"blur(5px)\",\n      x: o.x ?? 0,\n      y: o.y ?? 0,\n    },\n    animate: {\n      opacity: 1,\n      scale: 1,\n      filter: \"blur(0px)\",\n      x: 0,\n      y: 0,\n      transition: {\n        ...TOOLTIP_SPRING,\n        opacity: { duration: 0.14, ease: EASE_OUT },\n        filter: { duration: 0.18, ease: EASE_OUT },\n      },\n    },\n    exit: {\n      opacity: 0,\n      scale: 0.94,\n      filter: \"blur(3px)\",\n      x: (o.x ?? 0) * 0.6,\n      y: (o.y ?? 0) * 0.6,\n      transition: { duration: 0.12, ease: EASE_OUT },\n    },\n  };\n}\n\nconst REDUCED_VARIANTS: Variants = {\n  initial: { opacity: 0 },\n  animate: { opacity: 1, transition: { duration: 0.14, ease: EASE_OUT } },\n  exit: { opacity: 0, transition: { duration: 0.1, ease: EASE_OUT } },\n};\n\n/** The shared visual surface for trigger tooltips and chart readouts. Positioning belongs to the caller. */\nexport function TooltipSurface({\n  children,\n  side = \"top\",\n  className,\n  ref,\n  ...props\n}: Omit<ComponentProps<typeof motion.span>, \"children\"> & {\n  children?: ReactNode;\n  side?: Side;\n  ref?: Ref<HTMLSpanElement>;\n}) {\n  const reduce = useReducedMotion();\n  const variants = useMemo(() => reduce ? REDUCED_VARIANTS : buildVariants(side), [reduce, side]);\n  return (\n    <motion.span\n      ref={ref}\n      role=\"tooltip\"\n      variants={variants}\n      initial=\"initial\"\n      animate=\"animate\"\n      exit=\"exit\"\n      className={cn(\n        \"block whitespace-nowrap rounded-lg border border-border bg-background px-2.5 py-1 text-xs font-medium text-foreground shadow-lg\",\n        className,\n      )}\n      {...props}\n    >\n      {children}\n    </motion.span>\n  );\n}\n"},{"path":"lib/hooks/use-dismiss.ts","type":"registry:hook","target":"@lib/hooks/use-dismiss.ts","content":"\"use client\";\n\nimport { type RefObject, useEffect } from \"react\";\n\n/**\n * What the dismissing gesture does to the control it landed on.\n *\n * `\"pass-through\"` is the platform norm (native popover light-dismiss): the\n * tap closes the overlay *and* activates whatever was under it. Use\n * `\"consume\"` where the open overlay sits over or beside controls that would\n * be costly to trigger by accident — the dismissal then swallows the\n * activation too, so the gesture only closes.\n */\nexport type DismissBehavior = \"pass-through\" | \"consume\";\n\nexport interface DismissOptions {\n  /** Default `\"pass-through\"`. */\n  behavior?: DismissBehavior;\n  /** Dismiss on Escape as well. Default true. */\n  escape?: boolean;\n  /** Return true for an outside target that should *not* dismiss. Must be stable. */\n  ignore?: (target: Element) => boolean;\n}\n\n/**\n * What every currently open dismiss scope counts as inside itself. A consumed\n * dismissal reads this to tell a stray gesture from one that belongs to an\n * overlay in front of it: overlays have no shared z-order to consult, but the\n * one the gesture landed in has said as much by registering it.\n */\nconst openScopes = new Set<(target: Element) => boolean>();\n\nfunction claimedByAnotherScope(\n  self: (target: Element) => boolean,\n  target: Element,\n) {\n  for (const scope of openScopes) {\n    if (scope !== self && scope(target)) return true;\n  }\n  return false;\n}\n\n// preventDefault on pointerdown does not suppress the click that follows, so\n// consuming a gesture means swallowing that click itself. The swallower\n// deliberately outlives the effect that installed it — the dismissal it\n// belongs to has already unmounted or re-rendered by the time the click lands.\n// It releases on that click, or on the next gesture if the pointer is dragged\n// away and no click ever arrives, so it can never eat a later one. A keydown\n// releases it too: a gesture that ends with neither a click nor a cancel would\n// otherwise leave it armed, and the click Enter synthesizes on some focused\n// control is not the one this dismissal was owed.\nfunction consumeActivation(source: Event) {\n  const swallow = (event: MouseEvent) => {\n    event.preventDefault();\n    event.stopPropagation();\n    release();\n  };\n  const restart = (event: Event) => {\n    if (event !== source) release();\n  };\n  const release = () => {\n    window.removeEventListener(\"click\", swallow, true);\n    window.removeEventListener(\"pointerdown\", restart, true);\n    window.removeEventListener(\"pointercancel\", restart, true);\n    window.removeEventListener(\"keydown\", release, true);\n  };\n  window.addEventListener(\"click\", swallow, true);\n  window.addEventListener(\"pointerdown\", restart, true);\n  window.addEventListener(\"pointercancel\", restart, true);\n  window.addEventListener(\"keydown\", release, true);\n}\n\n/**\n * Close an open overlay on Escape or a pointerdown outside `ref`. Pass `null`\n * for `ref` when what counts as inside isn't one element, and say so with\n * `ignore` instead.\n *\n * The pointerdown listener is capture-phase: a bubble-phase one is blinded by\n * any handler in between that stops propagation, and an overlay cannot know\n * what it is layered over. `onDismiss` and `ignore` must be stable (wrap in\n * useCallback) so the listeners aren't re-bound every render while open.\n */\nexport function useDismiss(\n  open: boolean,\n  onDismiss: () => void,\n  ref: RefObject<HTMLElement | SVGElement | null> | null,\n  {\n    behavior = \"pass-through\",\n    escape: dismissOnEscape = true,\n    ignore,\n  }: DismissOptions = {},\n) {\n  useEffect(() => {\n    if (!open) return;\n    const inside = (target: Element) =>\n      Boolean(ref?.current?.contains(target)) || Boolean(ignore?.(target));\n    const onKey = (event: KeyboardEvent) => {\n      if (dismissOnEscape && event.key === \"Escape\") onDismiss();\n    };\n    const onPointer = (event: PointerEvent) => {\n      const target = event.target as Element | null;\n      if (!target || inside(target)) return;\n      // Outside this overlay, but inside one that is also open: the gesture is\n      // that overlay's to answer, and swallowing its click from behind would\n      // cost the user the control they actually aimed at.\n      if (behavior === \"consume\" && !claimedByAnotherScope(inside, target)) {\n        consumeActivation(event);\n      }\n      onDismiss();\n    };\n    openScopes.add(inside);\n    window.addEventListener(\"keydown\", onKey);\n    window.addEventListener(\"pointerdown\", onPointer, true);\n    return () => {\n      openScopes.delete(inside);\n      window.removeEventListener(\"keydown\", onKey);\n      window.removeEventListener(\"pointerdown\", onPointer, true);\n    };\n  }, [open, onDismiss, ref, behavior, dismissOnEscape, ignore]);\n}\n"},{"path":"lib/hooks/use-hover-gesture.ts","type":"registry:hook","target":"@lib/hooks/use-hover-gesture.ts","content":"\"use client\";\n\nimport { useMemo, useRef } from \"react\";\nimport { isHoveringPointer } from \"@/lib/touch\";\n\ninterface BoundaryEvent {\n  pointerId: number;\n  pointerType: string;\n  buttons: number;\n}\n\nexport interface HoverGesture {\n  /** True when this enter starts a hover: the pointer arrived resting, not pressing. */\n  enter: (event: BoundaryEvent) => boolean;\n  /** True when this leave ends a hover that entered as one. */\n  leave: (event: BoundaryEvent) => boolean;\n}\n\n/**\n * Pairs a surface's enter with its leave, per pointer.\n *\n * `isHoveringPointer` answers the question the *enter* asks — is this pointer\n * resting on the surface or pressing it — and both boundary cases go wrong if\n * the leave is asked the same question again:\n *\n * - A pen with no hover never rests. It arrives in contact, taps, and the spec\n *   then requires its boundary events after `pointerup`, so the leave carries\n *   `buttons: 0` and reads as a mouse gliding off. Hover teardown then undid\n *   the tap — the panel the pen had just opened closed under it.\n * - A mouse pressed on the surface and dragged off leaves with `buttons: 1`.\n *   Skipping teardown there strands the surface open: the release happens\n *   outside, and no second leave ever comes.\n *\n * So the state a hover holds is released by the pointer that took it, whatever\n * the buttons say at the boundary, and a pointer that arrived in contact never\n * took it in the first place. Contact is the exception tracked here, not\n * hover: a leave from a pointer this surface never saw enter — mounted under\n * the cursor, say — still counts, since the alternative is state with no way\n * out.\n */\nexport function useHoverGesture(): HoverGesture {\n  const contact = useRef(new Set<number>());\n\n  return useMemo(\n    () => ({\n      enter: (event) => {\n        if (isHoveringPointer(event)) {\n          contact.current.delete(event.pointerId);\n          return true;\n        }\n        contact.current.add(event.pointerId);\n        return false;\n      },\n      leave: (event) => {\n        const arrivedInContact = contact.current.delete(event.pointerId);\n        return !arrivedInContact && event.pointerType !== \"touch\";\n      },\n    }),\n    [],\n  );\n}\n"},{"path":"lib/hooks/use-tap-gesture.ts","type":"registry:hook","target":"@lib/hooks/use-tap-gesture.ts","content":"\"use client\";\n\nimport { useMemo, useRef } from \"react\";\n\n/** What a pointerdown recorded, read back by the click that ends its gesture. */\nexport interface TapRecord<S> {\n  /** Which input started the gesture. */\n  pointerType: string;\n  /** What the surface was showing when it started. */\n  state: S;\n}\n\nexport interface TapGesture<S> {\n  /** Record the gesture a pointerdown starts, with the state it starts in. */\n  start: (event: { pointerType: string }, state: S) => void;\n  /** Read the record and clear it. `null` when no pointer is behind this click. */\n  take: () => TapRecord<S> | null;\n  /** Drop the record: this gesture will never spend it on a click. */\n  drop: () => void;\n}\n\n/**\n * The pointer gesture behind a click, recorded where the click cannot report\n * it. A `click` carries no `pointerType` in the engines that matter, so the\n * `pointerdown` before it is the only thing that says which input activated\n * the control — and whether one did at all, since keyboard activation\n * synthesizes a click with no pointer behind it.\n *\n * State goes in with the record because a click reports that no better: a\n * browser that focuses a control on contact can open the very panel the tap\n * was meant to open, and reading \"is it open\" at click time then undoes it.\n * What the gesture started against is what it acts on.\n *\n * The record is spent by one click and dropped by everything else, because a\n * record that outlives its gesture is worse than none:\n *\n * - A scroll or an OS gesture takes the touch away — `pointercancel`, no click\n *   ever — and the finger would sit in the record until some later click.\n * - That later click is often `Enter` on a keyboard, which arrives with no\n *   pointerdown of its own and would inherit the abandoned finger. A keydown\n *   is the start of a keyboard activation and never part of a tap, so it drops\n *   the record too.\n *\n * Both ends have to be wired by the surface: `drop` on `onPointerCancel` and\n * on `onKeyDown`.\n */\nexport function useTapGesture<S>(): TapGesture<S> {\n  const record = useRef<TapRecord<S> | null>(null);\n\n  return useMemo(\n    () => ({\n      start: (event, state) => {\n        record.current = { pointerType: event.pointerType, state };\n      },\n      take: () => {\n        const spent = record.current;\n        record.current = null;\n        return spent;\n      },\n      drop: () => {\n        record.current = null;\n      },\n    }),\n    [],\n  );\n}\n"},{"path":"lib/touch.ts","type":"registry:lib","target":"@lib/touch.ts","content":"// Shared touch primitives. iOS and iPadOS run their own gestures on top of the\n// page — the long-press selection callout and the selection it drags in with\n// it — and they win: once the platform claims a touch it cancels ours\n// mid-gesture, so a press-and-hold or a drag simply dies. Surfaces that own\n// their gesture have to opt out.\n//\n// What the two classes below cover, precisely:\n// - `-webkit-touch-callout: none` stops iOS's long-press callout. WebKit-only:\n//   it is not a property other engines have, so it is inert everywhere else.\n// - `user-select: none` stops the long-press selection on every engine,\n//   Android included, and stops a drag from painting a selection under the\n//   cursor. It is inherited, so it reaches every descendant — which is why the\n//   two classes differ only in whether they apply it unconditionally.\n// What neither covers:\n// - Chrome for Android's long-press menu on a link or an image. No CSS\n//   suppresses it; a gesture surface that wraps one needs its own\n//   `onContextMenu` with `preventDefault()`.\n// - The native drag of an `<img>` or `<a>` descendant. `-webkit-user-drag` is\n//   not inherited and plain divs and buttons are not drag sources, so setting\n//   it on the surface does nothing — the child itself needs `draggable={false}`.\n\n/**\n * Classes for a surface that *is* the control: a thumb, a drum, a stage, a\n * handle, a hold button. Selection is suppressed on every input, because a\n * drag that highlights the control's own label is wrong on a mouse too.\n * Compose with `touch-none` when the surface also owns the scroll axis — leave\n * it off when the page must still scroll from there.\n */\nexport const TOUCH_GESTURE_CLASS = \"select-none [-webkit-touch-callout:none]\";\n\n/**\n * The same opt-out for a gesture surface that wraps content the consumer owns:\n * a scroller, a context-menu trigger, a sheet header, a list row. Selection is\n * suppressed only where the platform runs its own press gestures — a coarse\n * pointer — so a mouse user can still select and copy that content. If the\n * gesture itself would paint a selection under the cursor, add `select-none`\n * for the duration of the gesture rather than reaching for\n * `TOUCH_GESTURE_CLASS`.\n *\n * `pointer: coarse` describes the *primary* pointer and nothing else, so a\n * hybrid machine reads it wrong in both directions: a tablet with a mouse\n * plugged in keeps touch as primary and loses mouse selection, and a laptop\n * with a touchscreen keeps the mouse as primary and leaves selection live\n * under a finger. No media query can answer per interaction — the query is\n * about the device, and the question is about the gesture in progress. The\n * default stays here because it is right on the machines that are one thing or\n * the other, and losing a selection is a nuisance; where the miss costs a\n * *gesture* instead, the surface pairs it with `holdSelection` on the press.\n */\nexport const TOUCH_GESTURE_CONTENT_CLASS =\n  \"[-webkit-touch-callout:none] pointer-coarse:select-none\";\n\n/**\n * Suppress selection on `element` for as long as a gesture is running on it,\n * whatever the primary pointer of the machine happens to be. Returns the\n * release. Inline, so it wins over the class above and is gone again the\n * moment the gesture ends.\n *\n * For the press gestures a native selection would otherwise steal — a\n * long-press that opens a menu. Elsewhere prefer the classes: a surface that\n * takes selection away for the whole session is a surface whose text nobody\n * can copy.\n */\nexport function holdSelection(element: HTMLElement) {\n  element.style.setProperty(\"user-select\", \"none\");\n  element.style.setProperty(\"-webkit-user-select\", \"none\");\n  return () => {\n    element.style.removeProperty(\"user-select\");\n    element.style.removeProperty(\"-webkit-user-select\");\n  };\n}\n\n/**\n * Pointer capture, best effort. WebKit throws `NotFoundError` when the pointer\n * is already gone by the time the handler runs — routine on iOS, where the\n * system can claim the touch first — and an uncaught throw takes the rest of\n * the handler, the gesture included, down with it. Touch pointers carry\n * implicit capture anyway, so losing it is never fatal.\n */\nexport function capturePointer(element: Element, pointerId: number) {\n  try {\n    element.setPointerCapture(pointerId);\n  } catch {\n    // Pointer is no longer active — implicit capture still applies on touch.\n  }\n}\n\n/** Release a capture taken with `capturePointer`, ignoring a stale pointer. */\nexport function releasePointer(element: Element, pointerId: number) {\n  try {\n    if (element.hasPointerCapture(pointerId)) {\n      element.releasePointerCapture(pointerId);\n    }\n  } catch {\n    // Capture was already dropped by the browser.\n  }\n}\n\n/**\n * Whether this event came from a pointer that is *hovering*: not a touch, and\n * not currently pressed. Which input the user is holding right now is not\n * something a device capability can answer — a touchscreen laptop hovers and\n * taps, and iPadOS reports a fine hovering pointer for a finger — so both\n * paths stay live and each handler branches on the event it was given.\n *\n * A pen resting on the glass is making contact, not hovering: `buttons` is the\n * tell, and it sends a pen tap down the same route a finger takes.\n *\n * This answers what an *enter* asks. A leave is the other half of a pair and\n * has to be read against the enter that started it — `useHoverGesture` in\n * `lib/hooks/use-hover-gesture` does that, and hover surfaces should use it\n * rather than asking this question twice.\n */\nexport const isHoveringPointer = (event: {\n  pointerType: string;\n  buttons: number;\n}) => event.pointerType !== \"touch\" && event.buttons === 0;\n"}]}