{"slug":"availability-scheduler","name":"Availability Scheduler","description":"Weekly availability editor where each day springs between available and unavailable, time ranges add and remove with blur-slide motion, times pick from a scrollable dropdown, and a copy menu clones hours to other days.","category":"blocks","source_url":"https://beui.dev/r/availability-scheduler/raw","detail_url":"https://beui.dev/r/availability-scheduler","raw_url":"https://beui.dev/r/availability-scheduler/raw","page_url":"https://beui.dev/components/blocks/availability-scheduler","markdown_url":"https://beui.dev/components/blocks/availability-scheduler.md","published_at":"2026-07-10","updated_at":"2026-11-28","dependencies":["@floating-ui/dom","clsx","lucide-react","motion","react","react-dom","tailwind-merge"],"internal":["./copy-menu","./day-row","./engine","./icon-button","./messages","./time-select","./tooltip/grace","./tooltip/positioner","./tooltip/use-position","./types","./use-position","@/components/motion/availability-scheduler","@/components/motion/checkbox","@/components/motion/menu/menu-item-highlight","@/components/motion/popover-morph","@/components/motion/popover-position","@/components/motion/select","@/components/motion/switch","@/components/motion/tooltip","@/components/motion/tooltip-surface","@/lib/audio-context","@/lib/ease","@/lib/focusable","@/lib/hooks/use-dismiss","@/lib/hooks/use-hover-gesture","@/lib/hooks/use-listbox","@/lib/hooks/use-on-open","@/lib/hooks/use-row-cursor","@/lib/hooks/use-tap-gesture","@/lib/i18n","@/lib/layers","@/lib/merge-refs","@/lib/sound","@/lib/sounds/close","@/lib/sounds/engine","@/lib/sounds/open","@/lib/sounds/select","@/lib/sounds/toggle","@/lib/touch","@/lib/utils"],"install_slugs":["availability-scheduler"],"requires_theme":true,"props":[{"displayName":"AvailabilityScheduler","props":[{"name":"value","type":"WeekAvailability","required":false,"defaultValue":null,"description":"The weekly hours, for controlled use."},{"name":"defaultValue","type":"WeekAvailability","required":false,"defaultValue":null,"description":"The initial weekly hours when uncontrolled. Defaults to weekdays 09:00 to 17:00."},{"name":"onChange","type":"((value: WeekAvailability) => void)","required":false,"defaultValue":null,"description":"Called with the whole week when any day or time range changes."},{"name":"step","type":"number","required":false,"defaultValue":"30","description":"Minutes between selectable times. Default 30."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."},{"name":"labels","type":"Partial<{ toggleDay: string; unavailable: string; addTime: string; addRange: string; remove: string; removeRange: string; copyTimes: string; copyDay: string; copyTo: string; everyDay: string; apply: string; }>","required":false,"defaultValue":null,"description":"Override any built-in string."}]}],"types":[],"files":[{"path":"components/motion/availability-scheduler/index.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/blocks/availability-scheduler\n\nimport { LayoutGroup, useReducedMotion } from \"motion/react\";\nimport {\n  useCallback,\n  useEffect,\n  useId,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { useLocale, useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\nimport { DayRow } from \"./day-row\";\nimport {\n  type AvailabilitySchedulerMessages,\n  availabilitySchedulerMessages,\n} from \"./messages\";\nimport {\n  buildOptions,\n  type DayAvailability,\n  type DayKey,\n  defaultWeek,\n  panelKey,\n  WEEKDAYS,\n  type WeekAvailability,\n  weekdayLabel,\n} from \"./types\";\n\nexport {\n  type AvailabilitySchedulerMessages,\n  availabilitySchedulerMessages,\n} from \"./messages\";\nexport type {\n  DayAvailability,\n  DayKey,\n  TimeRange,\n  WeekAvailability,\n} from \"./types\";\nexport { defaultWeek } from \"./types\";\n\nexport interface AvailabilitySchedulerProps {\n  /** The weekly hours, for controlled use. */\n  value?: WeekAvailability;\n  /** The initial weekly hours when uncontrolled. Defaults to weekdays 09:00 to 17:00. */\n  defaultValue?: WeekAvailability;\n  /** Called with the whole week when any day or time range changes. */\n  onChange?: (value: WeekAvailability) => void;\n  /** Minutes between selectable times. Default 30. */\n  step?: number;\n  /** Classes merged onto the root element. */\n  className?: string;\n  /** Override any built-in string. */\n  labels?: Partial<AvailabilitySchedulerMessages>;\n}\n\nexport function AvailabilityScheduler({\n  value,\n  defaultValue,\n  onChange,\n  step = 30,\n  className,\n  labels,\n}: AvailabilitySchedulerProps) {\n  const reduce = useReducedMotion() ?? false;\n  const groupId = useId();\n  const { locale } = useLocale();\n  const t = useMessages(\n    \"availabilityScheduler\",\n    availabilitySchedulerMessages,\n    labels,\n  );\n  const options = useMemo(() => buildOptions(step, locale), [step, locale]);\n  const idRef = useRef(0);\n\n  const [internal, setInternal] = useState<WeekAvailability>(\n    () => defaultValue ?? defaultWeek(),\n  );\n  // The row that last opened a dropdown paints above the rest - see DayRow.\n  const [openDay, setOpenDay] = useState<DayKey | null>(null);\n  // Exactly one time panel is open at a time, and the scheduler is the one that\n  // knows which. A panel is absolutely positioned inside its own field, so two\n  // open at once paint over each other's options - and nothing else can close\n  // the first: a Select only dismisses on an outside *pointerdown*, which\n  // keyboard and assistive-technology activation never fires.\n  const [openPanel, setOpenPanel] = useState<string | null>(null);\n  const controlled = value !== undefined;\n  const week = controlled ? value : internal;\n\n  // Which panels the week currently puts on screen. A field that leaves - its\n  // day switched off, its range removed - never reports its panel closed: the\n  // only thing that dismisses a controlled Select is an outside pointerdown,\n  // and a field on its way out is no longer there to hear one. Keeping its id\n  // would reopen the panel the moment the same range came back.\n  const livePanels = useMemo(() => {\n    const ids = new Set<string>();\n    for (const { key } of WEEKDAYS) {\n      if (!week[key].enabled) continue;\n      for (const range of week[key].ranges) {\n        ids.add(panelKey(key, range.id, \"start\"));\n        ids.add(panelKey(key, range.id, \"end\"));\n      }\n    }\n    return ids;\n  }, [week]);\n\n  useEffect(() => {\n    if (openPanel !== null && !livePanels.has(openPanel)) setOpenPanel(null);\n  }, [livePanels, openPanel]);\n\n  const commit = useCallback(\n    (next: WeekAvailability) => {\n      if (!controlled) setInternal(next);\n      onChange?.(next);\n    },\n    [controlled, onChange],\n  );\n\n  const setDay = useCallback(\n    (day: DayKey, next: DayAvailability) => {\n      commit({ ...week, [day]: next });\n    },\n    [commit, week],\n  );\n\n  const panelOpenChange = useCallback(\n    (day: DayKey, id: string, open: boolean) => {\n      setOpenPanel((current) =>\n        open ? id : current === id ? null : current,\n      );\n      // Elevation stays on the row that opened last so the panel's collapse\n      // animation finishes above its neighbours.\n      if (open) setOpenDay(day);\n    },\n    [],\n  );\n\n  const copyDay = useCallback(\n    (from: DayKey, targets: DayKey[]) => {\n      const source = week[from];\n      const next = { ...week };\n      for (const t of targets) {\n        next[t] = {\n          enabled: source.enabled,\n          ranges: source.ranges.map((r) => ({\n            ...r,\n            id: `${t}-c${idRef.current++}`,\n          })),\n        };\n      }\n      commit(next);\n    },\n    [commit, week],\n  );\n\n  return (\n    <LayoutGroup id={groupId}>\n      <div className={cn(\"w-full max-w-xl divide-y divide-border\", className)}>\n        {WEEKDAYS.map(({ key }, index) => (\n          <DayRow\n            key={key}\n            day={key}\n            label={weekdayLabel(index, locale)}\n            t={t}\n            state={week[key]}\n            options={options}\n            reduce={reduce}\n            elevated={openDay === key}\n            openPanel={openPanel}\n            onChange={(next) => setDay(key, next)}\n            onCopy={(targets) => copyDay(key, targets)}\n            onPanelOpenChange={(id, open) => panelOpenChange(key, id, open)}\n          />\n        ))}\n      </div>\n    </LayoutGroup>\n  );\n}\n"},{"path":"components/motion/availability-scheduler/day-row.tsx","type":"util","content":"\"use client\";\n\nimport { Plus, X } from \"lucide-react\";\nimport { AnimatePresence, motion } from \"motion/react\";\nimport { useRef, useState } from \"react\";\nimport { Switch } from \"@/components/motion/switch\";\nimport { Tooltip } from \"@/components/motion/tooltip\";\nimport { SPRING_LAYOUT } from \"@/lib/ease\";\nimport { useLocale } from \"@/lib/i18n\";\nimport { CopyMenu } from \"./copy-menu\";\nimport { IconButton } from \"./icon-button\";\nimport type { AvailabilitySchedulerTranslate } from \"./messages\";\nimport { TimeSelect } from \"./time-select\";\nimport {\n  clampRange,\n  type DayAvailability,\n  type DayKey,\n  endOptions,\n  panelKey,\n  startOptions,\n  type TimeOption,\n  type TimeRange,\n  toMinutes,\n  toValue,\n} from \"./types\";\n\nexport function DayRow({\n  day,\n  label,\n  t,\n  state,\n  options,\n  reduce,\n  elevated,\n  openPanel,\n  onChange,\n  onCopy,\n  onPanelOpenChange,\n}: {\n  day: DayKey;\n  label: string;\n  t: AvailabilitySchedulerTranslate;\n  state: DayAvailability;\n  options: TimeOption[];\n  reduce: boolean;\n  // True while this row holds the dropdown that opened last, which paints it\n  // above every other row. A time panel opens downward when there is room and\n  // upward when there isn't, so it has to clear the rows on either side of it\n  // - no fixed paint order can satisfy both directions. The flag stays on\n  // after the panel closes so the collapse animation stays on top too.\n  elevated: boolean;\n  /** Id of the one time panel the scheduler is holding open, if any. */\n  openPanel: string | null;\n  onChange: (next: DayAvailability) => void;\n  onCopy: (targets: DayKey[]) => void;\n  onPanelOpenChange: (panelId: string, open: boolean) => void;\n}) {\n  const { locale } = useLocale();\n  const idRef = useRef(0);\n  // The counter restarts per mount, so skip ids a saved value already holds.\n  const nextId = () => {\n    let id = `${day}-n${idRef.current++}`;\n    while (state.ranges.some((r) => r.id === id)) {\n      id = `${day}-n${idRef.current++}`;\n    }\n    return id;\n  };\n  // Same rule one level down: ranges stack against each other inside the row.\n  const [openRangeId, setOpenRangeId] = useState<string | null>(null);\n\n  const panelId = (rangeId: string, edge: \"start\" | \"end\") =>\n    panelKey(day, rangeId, edge);\n\n  const onRangePanelOpenChange = (\n    rangeId: string,\n    id: string,\n    open: boolean,\n  ) => {\n    if (open) setOpenRangeId(rangeId);\n    onPanelOpenChange(id, open);\n  };\n\n  const setEnabled = (enabled: boolean) => {\n    if (enabled && state.ranges.length === 0) {\n      onChange({\n        enabled,\n        ranges: [{ id: nextId(), start: \"09:00\", end: \"17:00\" }],\n      });\n    } else {\n      onChange({ ...state, enabled });\n    }\n  };\n\n  const updateRange = (id: string, patch: Partial<TimeRange>) => {\n    const changed: \"start\" | \"end\" = patch.start !== undefined ? \"start\" : \"end\";\n    onChange({\n      ...state,\n      ranges: state.ranges.map((r) => {\n        if (r.id !== id) return r;\n        const next = { ...r, ...patch };\n        return { ...next, ...clampRange(next.start, next.end, options, changed) };\n      }),\n    });\n  };\n\n  const addRange = () => {\n    const last = state.ranges[state.ranges.length - 1];\n    const start = last ? Math.min(toMinutes(last.end) + 60, 24 * 60 - 60) : 540;\n    onChange({\n      enabled: true,\n      ranges: [\n        ...state.ranges,\n        { id: nextId(), start: toValue(start), end: toValue(start + 60) },\n      ],\n    });\n  };\n\n  const removeRange = (id: string) => {\n    const ranges = state.ranges.filter((r) => r.id !== id);\n    // Removing the last slot marks the day unavailable.\n    onChange({ enabled: ranges.length > 0, ranges });\n  };\n\n  const actions = (\n    <>\n      <Tooltip content={t(\"addTime\")}>\n        <IconButton\n          label={t(\"addRange\", { day: label })}\n          reduce={reduce}\n          onClick={addRange}\n        >\n          <Plus className=\"h-4 w-4\" />\n        </IconButton>\n      </Tooltip>\n      <CopyMenu\n        from={day}\n        fromLabel={label}\n        t={t}\n        reduce={reduce}\n        onApply={onCopy}\n      />\n    </>\n  );\n\n  return (\n    <motion.div\n      layout={reduce ? false : \"position\"}\n      transition={SPRING_LAYOUT}\n      style={{ zIndex: elevated ? 1 : undefined }}\n      className=\"relative flex flex-col gap-3 py-4 sm:flex-row sm:items-start sm:gap-4\"\n    >\n      {/* toggle + label; actions ride along on mobile */}\n      <div className=\"flex items-center justify-between sm:w-36 sm:shrink-0 sm:justify-start sm:pt-1\">\n        <div className=\"flex items-center gap-2.5\">\n          <Switch\n            checked={state.enabled}\n            onCheckedChange={setEnabled}\n            ariaLabel={t(\"toggleDay\", { day: label })}\n            className=\"scale-90\"\n          />\n          <span className=\"text-sm font-medium text-foreground\">{label}</span>\n        </div>\n        <div className=\"flex items-center gap-1 sm:hidden\">{actions}</div>\n      </div>\n\n      {/* ranges or unavailable */}\n      <div className=\"flex min-w-0 flex-1 flex-col gap-2\">\n        <AnimatePresence initial={false} mode=\"popLayout\">\n          {state.enabled ? (\n            state.ranges.map((r) => (\n              <motion.div\n                key={r.id}\n                layout={reduce ? false : \"position\"}\n                style={{ zIndex: openRangeId === r.id ? 1 : undefined }}\n                initial={\n                  reduce\n                    ? { opacity: 0 }\n                    : { opacity: 0, y: -6, filter: \"blur(4px)\" }\n                }\n                animate={\n                  reduce\n                    ? { opacity: 1 }\n                    : { opacity: 1, y: 0, filter: \"blur(0px)\" }\n                }\n                exit={\n                  reduce\n                    ? { opacity: 0 }\n                    : { opacity: 0, y: -4, filter: \"blur(4px)\" }\n                }\n                transition={SPRING_LAYOUT}\n                className=\"relative flex items-center gap-2\"\n              >\n                <div className=\"min-w-0 flex-1 sm:max-w-[132px]\">\n                  <TimeSelect\n                    value={r.start}\n                    options={startOptions(options, r.end, r.start, locale)}\n                    onChange={(v) => updateRange(r.id, { start: v })}\n                    open={openPanel === panelId(r.id, \"start\")}\n                    onOpenChange={(open) =>\n                      onRangePanelOpenChange(r.id, panelId(r.id, \"start\"), open)\n                    }\n                  />\n                </div>\n                <span className=\"text-muted-foreground\">–</span>\n                <div className=\"min-w-0 flex-1 sm:max-w-[132px]\">\n                  <TimeSelect\n                    value={r.end}\n                    options={endOptions(options, r.start, r.end, locale)}\n                    onChange={(v) => updateRange(r.id, { end: v })}\n                    open={openPanel === panelId(r.id, \"end\")}\n                    onOpenChange={(open) =>\n                      onRangePanelOpenChange(r.id, panelId(r.id, \"end\"), open)\n                    }\n                  />\n                </div>\n                <Tooltip content={t(\"remove\")}>\n                  <IconButton\n                    label={t(\"removeRange\")}\n                    reduce={reduce}\n                    onClick={() => removeRange(r.id)}\n                  >\n                    <X className=\"h-4 w-4\" />\n                  </IconButton>\n                </Tooltip>\n              </motion.div>\n            ))\n          ) : (\n            <motion.span\n              key=\"unavailable\"\n              layout={reduce ? false : \"position\"}\n              initial={reduce ? { opacity: 0 } : { opacity: 0, y: -4 }}\n              animate={reduce ? { opacity: 1 } : { opacity: 1, y: 0 }}\n              exit={reduce ? { opacity: 0 } : { opacity: 0, y: -4 }}\n              transition={SPRING_LAYOUT}\n              className=\"py-1 text-sm text-muted-foreground sm:py-2\"\n            >\n              {t(\"unavailable\")}\n            </motion.span>\n          )}\n        </AnimatePresence>\n      </div>\n\n      {/* actions (desktop) */}\n      <div className=\"hidden shrink-0 items-center gap-1 pt-0.5 sm:flex\">\n        {actions}\n      </div>\n    </motion.div>\n  );\n}\n"},{"path":"components/motion/availability-scheduler/messages.ts","type":"util","content":"import type { useMessages } from \"@/lib/i18n\";\n\n/**\n * English defaults. Override per instance with `labels`, or app-wide with\n * `LocaleProvider`. `{day}` is the weekday name.\n */\nexport const availabilitySchedulerMessages = {\n  toggleDay: \"Toggle {day} availability\",\n  unavailable: \"Unavailable\",\n  addTime: \"Add time\",\n  addRange: \"Add time range to {day}\",\n  remove: \"Remove\",\n  removeRange: \"Remove time range\",\n  copyTimes: \"Copy times\",\n  copyDay: \"Copy {day} hours to other days\",\n  copyTo: \"Copy times to\",\n  everyDay: \"Every day\",\n  apply: \"Apply\",\n};\n\nexport type AvailabilitySchedulerMessages = typeof availabilitySchedulerMessages;\n\n/** The resolved translator the root hands to its parts. */\nexport type AvailabilitySchedulerTranslate = ReturnType<\n  typeof useMessages<AvailabilitySchedulerMessages>\n>;\n"},{"path":"components/motion/availability-scheduler/types.ts","type":"util","content":"export type DayKey = \"mon\" | \"tue\" | \"wed\" | \"thu\" | \"fri\" | \"sat\" | \"sun\";\n\nexport type TimeRange = { id: string; start: string; end: string };\nexport type DayAvailability = { enabled: boolean; ranges: TimeRange[] };\nexport type WeekAvailability = Record<DayKey, DayAvailability>;\nexport type TimeOption = { value: string; label: string };\n\nexport const WEEKDAYS: { key: DayKey; label: string }[] = [\n  { key: \"mon\", label: \"Monday\" },\n  { key: \"tue\", label: \"Tuesday\" },\n  { key: \"wed\", label: \"Wednesday\" },\n  { key: \"thu\", label: \"Thursday\" },\n  { key: \"fri\", label: \"Friday\" },\n  { key: \"sat\", label: \"Saturday\" },\n  { key: \"sun\", label: \"Sunday\" },\n];\n\n// ─── panels ──────────────────────────────────────────────────────────────────\n\n/**\n * Names one time field week-wide, because the scheduler holds a single open\n * panel for the whole week. Range ids belong to the value and are only unique\n * within a day, so the day is part of the name - and the scheduler builds the\n * same keys to ask whether the panel it is holding is still on screen.\n */\nexport const panelKey = (day: DayKey, rangeId: string, edge: \"start\" | \"end\") =>\n  `${day}:${rangeId}:${edge}`;\n\n// ─── time helpers ────────────────────────────────────────────────────────────\n\nexport const toMinutes = (v: string) => {\n  const [h, m] = v.split(\":\").map(Number);\n  return h * 60 + m;\n};\n\nexport const toValue = (mins: number) => {\n  const clamped = Math.max(0, Math.min(24 * 60 - 1, mins));\n  const h = Math.floor(clamped / 60);\n  const m = clamped % 60;\n  return `${String(h).padStart(2, \"0\")}:${String(m).padStart(2, \"0\")}`;\n};\n\n/** Without a locale, keeps the English `9:00 AM` form so server and client agree. */\nexport const timeLabel = (v: string, locale?: string) => {\n  const [h, m] = v.split(\":\").map(Number);\n  if (locale) {\n    return new Intl.DateTimeFormat(locale, {\n      hour: \"numeric\",\n      minute: \"2-digit\",\n      timeZone: \"UTC\",\n    }).format(new Date(Date.UTC(2024, 0, 1, h, m)));\n  }\n  const ap = h < 12 ? \"AM\" : \"PM\";\n  const h12 = h % 12 === 0 ? 12 : h % 12;\n  return `${h12}:${String(m).padStart(2, \"0\")} ${ap}`;\n};\n\n/** Weekday name for the locale; English `WEEKDAYS` labels without one. */\nexport const weekdayLabel = (index: number, locale?: string) =>\n  locale\n    ? new Intl.DateTimeFormat(locale, { weekday: \"long\", timeZone: \"UTC\" }).format(\n        // 1 Jan 2024 was a Monday, matching WEEKDAYS order.\n        new Date(Date.UTC(2024, 0, 1 + index)),\n      )\n    : WEEKDAYS[index].label;\n\nexport function buildOptions(step: number, locale?: string): TimeOption[] {\n  const out: TimeOption[] = [];\n  for (let m = 0; m < 24 * 60; m += step) {\n    const value = toValue(m);\n    out.push({ value, label: timeLabel(value, locale) });\n  }\n  return out;\n}\n\nfunction snapToOption(mins: number, slots: number[]) {\n  let best = slots[0];\n  for (const slot of slots) {\n    if (Math.abs(slot - mins) < Math.abs(best - mins)) best = slot;\n  }\n  return best;\n}\n\nfunction withCurrentOption(\n  filtered: TimeOption[],\n  all: TimeOption[],\n  current?: string,\n  locale?: string,\n) {\n  if (!current || filtered.some((o) => o.value === current)) return filtered;\n  const extra =\n    all.find((o) => o.value === current) ??\n    ({ value: current, label: timeLabel(current, locale) } satisfies TimeOption);\n  return [...filtered, extra].sort(\n    (a, b) => toMinutes(a.value) - toMinutes(b.value),\n  );\n}\n\n/**\n * Same-day ranges only. A valid pair is left alone so an off-grid persisted\n * end (17:00 with `step={720}`) is not rewritten. When the invariant fails,\n * the just-selected endpoint stays and only the opposite side moves onto a\n * neighboring generated option.\n */\nexport function clampRange(\n  start: string,\n  end: string,\n  options: TimeOption[],\n  changed: \"start\" | \"end\" = \"start\",\n): { start: string; end: string } {\n  const slots = options.map((o) => toMinutes(o.value));\n  if (slots.length === 0) return { start, end };\n\n  const startM = toMinutes(start);\n  const endM = toMinutes(end);\n  if (endM > startM) return { start, end };\n\n  const keepOrSnap = (value: string) => {\n    const mins = toMinutes(value);\n    return slots.includes(mins) ? mins : snapToOption(mins, slots);\n  };\n\n  if (changed === \"end\") {\n    const e = keepOrSnap(end);\n    const earlier = [...slots].reverse().find((slot) => slot < e);\n    if (earlier === undefined && slots.length > 1) {\n      // Midnight cannot end a positive same-day range, so use the first pair.\n      return { start: toValue(slots[0]), end: toValue(slots[1]) };\n    }\n    return {\n      start: toValue(earlier ?? keepOrSnap(start)),\n      end: toValue(e),\n    };\n  }\n\n  const s = keepOrSnap(start);\n  const later = slots.find((slot) => slot > s);\n  if (later === undefined && slots.length > 1) {\n    // The last slot cannot start a positive range, so use the final pair.\n    return {\n      start: toValue(slots[slots.length - 2]),\n      end: toValue(slots[slots.length - 1]),\n    };\n  }\n  return {\n    start: toValue(s),\n    end: toValue(later ?? keepOrSnap(end)),\n  };\n}\n\nexport function startOptions(\n  options: TimeOption[],\n  end: string,\n  current?: string,\n  locale?: string,\n) {\n  const filtered = options.filter(\n    (o) => toMinutes(o.value) < toMinutes(end),\n  );\n  // An invalid midnight end has no earlier option; expose midnight so choosing\n  // it can move the end forward through clampRange instead of trapping the row.\n  const recovery = filtered.length === 0 ? options.slice(0, 1) : filtered;\n  return withCurrentOption(\n    recovery,\n    options,\n    current,\n    locale,\n  );\n}\n\nexport function endOptions(\n  options: TimeOption[],\n  start: string,\n  current?: string,\n  locale?: string,\n) {\n  const filtered = options.filter(\n    (o) => toMinutes(o.value) > toMinutes(start),\n  );\n  // An invalid last-slot start has no later option; expose the last slot so\n  // choosing it can move the start backward through clampRange.\n  const recovery = filtered.length === 0 ? options.slice(-1) : filtered;\n  return withCurrentOption(\n    recovery,\n    options,\n    current,\n    locale,\n  );\n}\n\n// Default: Mon–Fri 9–5, weekend off. Fixed ids so SSR and first client render\n// agree (new ranges get counter ids afterwards).\nexport function defaultWeek(): WeekAvailability {\n  const workday = (day: DayKey): DayAvailability => ({\n    enabled: true,\n    ranges: [{ id: `${day}-0`, start: \"09:00\", end: \"17:00\" }],\n  });\n  const off = (day: DayKey): DayAvailability => ({\n    enabled: false,\n    ranges: [{ id: `${day}-0`, start: \"09:00\", end: \"17:00\" }],\n  });\n  return {\n    mon: workday(\"mon\"),\n    tue: workday(\"tue\"),\n    wed: workday(\"wed\"),\n    thu: workday(\"thu\"),\n    fri: workday(\"fri\"),\n    sat: off(\"sat\"),\n    sun: off(\"sun\"),\n  };\n}\n"},{"path":"lib/i18n.tsx","type":"util","content":"\"use client\";\n\nimport {\n  createContext,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useMemo,\n} from \"react\";\n\n/**\n * A component's messages. Plain strings with `{name}` placeholders, so a\n * dictionary stays JSON-serializable and can be passed from a server layout.\n * There are no plural forms: write messages that read correctly for any count.\n */\nexport type Messages = Record<string, string>;\n\n/** A language file: component namespace → any subset of that component's messages. */\nexport type LocaleMessages = Record<string, Partial<Messages>>;\n\ntype LocaleContextValue = {\n  locale?: string;\n  messages: LocaleMessages;\n};\n\nconst NO_MESSAGES: LocaleMessages = {};\n\nconst LocaleContext = createContext<LocaleContextValue>({ messages: NO_MESSAGES });\n\n/** Without a locale, digits stay plain so server and client render the same text. */\nexport function formatNumber(value: number, locale?: string) {\n  return locale ? new Intl.NumberFormat(locale).format(value) : String(value);\n}\n\nexport interface LocaleProviderProps {\n  /** BCP 47 tag, e.g. `de`, `pt-BR`. Drives `Intl` number formatting. */\n  locale: string;\n  /**\n   * Component namespace → translated strings. Missing keys fall back to English.\n   * Pass a stable object (a module constant, imported JSON or a memoized value):\n   * a new object each render gives every translated component a new `t`.\n   */\n  messages?: LocaleMessages;\n  children: ReactNode;\n}\n\nexport function LocaleProvider({ locale, messages = NO_MESSAGES, children }: LocaleProviderProps) {\n  const value = useMemo(() => ({ locale, messages }), [locale, messages]);\n  return <LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>;\n}\n\nexport function useLocale(): { locale?: string } {\n  return { locale: useContext(LocaleContext).locale };\n}\n\n/**\n * Resolves a component's strings: `labels` prop, then the provider's\n * messages for `namespace`, then the component's English `defaults`.\n * Numbers passed as values are formatted for the provider's locale.\n */\nexport function useMessages<T extends Messages>(\n  namespace: string,\n  defaults: T,\n  labels?: Partial<T>,\n) {\n  const { locale, messages } = useContext(LocaleContext);\n  const provided = messages[namespace];\n  // Inline `labels={{ … }}` is a new object every render. Keying it by content\n  // keeps `t` one identity until a label changes, so effects and memos that\n  // depend on `t` don't re-run per render, and render-time reads never lag.\n  const labelsKey = labels ? JSON.stringify(labels) : \"\";\n  const stableLabels = useMemo(\n    () => (labelsKey ? (JSON.parse(labelsKey) as Partial<T>) : undefined),\n    [labelsKey],\n  );\n\n  return useCallback(\n    (key: keyof T & string, values?: Record<string, string | number>) => {\n      const template = stableLabels?.[key] ?? provided?.[key] ?? defaults[key];\n      if (!values) return template;\n      return template.replace(/\\{(\\w+)\\}/g, (match, name: string) => {\n        const value = values[name];\n        if (value === undefined) return match;\n        return typeof value === \"number\" ? formatNumber(value, locale) : value;\n      });\n    },\n    [defaults, stableLabels, locale, provided],\n  );\n}\n"},{"path":"lib/utils.ts","type":"util","content":"import { clsx, type ClassValue } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs))\n}\n"},{"path":"components/motion/availability-scheduler/copy-menu.tsx","type":"util","content":"\"use client\";\n\nimport { Check, Copy } from \"lucide-react\";\nimport { AnimatePresence, motion } from \"motion/react\";\nimport { useEffect, useRef, useState } from \"react\";\nimport { Checkbox } from \"@/components/motion/checkbox\";\nimport {\n  MorphPopover,\n  MorphPopoverContent,\n} from \"@/components/motion/popover-morph\";\nimport { Tooltip } from \"@/components/motion/tooltip\";\nimport { SPRING_PRESS } from \"@/lib/ease\";\nimport { useLocale } from \"@/lib/i18n\";\nimport { IconButton } from \"./icon-button\";\nimport type { AvailabilitySchedulerTranslate } from \"./messages\";\nimport { type DayKey, WEEKDAYS, weekdayLabel } from \"./types\";\n\n// Copy this day's hours to other days: a morph popover with a day picker.\nexport function CopyMenu({\n  from,\n  fromLabel,\n  t,\n  reduce,\n  onApply,\n}: {\n  from: DayKey;\n  fromLabel: string;\n  t: AvailabilitySchedulerTranslate;\n  reduce: boolean;\n  onApply: (targets: DayKey[]) => void;\n}) {\n  const [open, setOpen] = useState(false);\n  const [copied, setCopied] = useState(false);\n  const [picked, setPicked] = useState<Set<DayKey>>(new Set());\n  const { locale } = useLocale();\n  const copiedTimer = useRef<number | undefined>(undefined);\n  useEffect(() => () => window.clearTimeout(copiedTimer.current), []);\n  const others = WEEKDAYS.flatMap((d, index) =>\n    d.key === from ? [] : [{ key: d.key, label: weekdayLabel(index, locale) }],\n  );\n\n  const toggle = (k: DayKey) =>\n    setPicked((prev) => {\n      const next = new Set(prev);\n      if (next.has(k)) next.delete(k);\n      else next.add(k);\n      return next;\n    });\n\n  const apply = (targets: DayKey[]) => {\n    if (!targets.length) return;\n    onApply(targets);\n    setOpen(false);\n    setPicked(new Set());\n    setCopied(true);\n    window.clearTimeout(copiedTimer.current);\n    copiedTimer.current = window.setTimeout(() => setCopied(false), 1200);\n  };\n\n  return (\n    <MorphPopover open={open} onOpenChange={setOpen}>\n      <Tooltip content={t(\"copyTimes\")}>\n        <IconButton\n          label={t(\"copyDay\", { day: fromLabel })}\n          reduce={reduce}\n          expanded={open}\n          onClick={() => setOpen(!open)}\n        >\n          <AnimatePresence mode=\"popLayout\" initial={false}>\n            {copied ? (\n              <motion.span\n                key=\"done\"\n                initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.5 }}\n                animate={{ opacity: 1, scale: 1 }}\n                exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.5 }}\n                transition={SPRING_PRESS}\n                className=\"text-foreground\"\n              >\n                <Check className=\"h-4 w-4\" />\n              </motion.span>\n            ) : (\n              <motion.span\n                key=\"copy\"\n                initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.5 }}\n                animate={{ opacity: 1, scale: 1 }}\n                exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.5 }}\n                transition={SPRING_PRESS}\n              >\n                <Copy className=\"h-4 w-4\" />\n              </motion.span>\n            )}\n          </AnimatePresence>\n        </IconButton>\n      </Tooltip>\n\n      <MorphPopoverContent align=\"end\" className=\"w-52 p-2\">\n        <p className=\"px-2 py-1.5 text-xs font-medium text-muted-foreground\">\n          {t(\"copyTo\")}\n        </p>\n        <div className=\"flex flex-col\">\n          {others.map((d) => (\n            <Checkbox\n              key={d.key}\n              checked={picked.has(d.key)}\n              onCheckedChange={() => toggle(d.key)}\n              label={d.label}\n              className=\"w-full flex-row-reverse justify-between rounded-full px-3 py-1.5 transition-colors hover:bg-muted [&_button]:size-4 [&_button]:rounded-[5px] [&_button]:border [&_button[data-state=unchecked]]:border-border-strong\"\n            />\n          ))}\n        </div>\n        <div className=\"mt-1 flex items-center gap-2 border-t border-border px-1 pt-2\">\n          <button\n            type=\"button\"\n            onClick={() => apply(others.map((d) => d.key))}\n            className=\"flex-1 rounded-full px-2 py-1.5 text-xs font-medium text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:bg-muted\"\n          >\n            {t(\"everyDay\")}\n          </button>\n          <button\n            type=\"button\"\n            onClick={() => apply([...picked])}\n            disabled={picked.size === 0}\n            className=\"flex-1 rounded-full bg-primary px-2 py-1.5 text-xs font-medium text-primary-foreground outline-none transition-opacity hover:opacity-90 focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-40\"\n          >\n            {t(\"apply\")}\n          </button>\n        </div>\n      </MorphPopoverContent>\n    </MorphPopover>\n  );\n}\n"},{"path":"components/motion/availability-scheduler/icon-button.tsx","type":"util","content":"\"use client\";\n\nimport { motion } from \"motion/react\";\nimport type { ReactNode } from \"react\";\nimport { SPRING_PRESS } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\nexport function IconButton({\n  onClick,\n  label,\n  disabled,\n  expanded,\n  reduce,\n  children,\n  className,\n  // Rest props let a wrapping Tooltip inject its hover/focus handlers.\n  ...rest\n}: {\n  onClick: () => void;\n  label: string;\n  disabled?: boolean;\n  expanded?: boolean;\n  reduce: boolean;\n  children: ReactNode;\n  className?: string;\n  [key: string]: unknown;\n}) {\n  return (\n    <motion.button\n      {...rest}\n      type=\"button\"\n      aria-label={label}\n      aria-expanded={expanded}\n      onClick={onClick}\n      disabled={disabled}\n      whileTap={reduce || disabled ? undefined : { scale: 0.86 }}\n      transition={SPRING_PRESS}\n      className={cn(\n        \"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40\",\n        className,\n      )}\n    >\n      {children}\n    </motion.button>\n  );\n}\n"},{"path":"components/motion/availability-scheduler/time-select.tsx","type":"util","content":"\"use client\";\n\nimport {\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectTrigger,\n  SelectValue,\n} from \"@/components/motion/select\";\nimport type { TimeOption } from \"./types\";\n\n// Time field: the library Select, with the option list capped so the panel\n// measures a small height and scrolls instead of unfolding all 48 options.\nexport function TimeSelect({\n  value,\n  onChange,\n  open,\n  onOpenChange,\n  options,\n}: {\n  value: string;\n  onChange: (v: string) => void;\n  open: boolean;\n  onOpenChange: (open: boolean) => void;\n  options: TimeOption[];\n}) {\n  return (\n    <Select\n      value={value}\n      onValueChange={onChange}\n      open={open}\n      onOpenChange={onOpenChange}\n      className=\"w-full\"\n    >\n      <SelectTrigger className=\"tabular-nums\">\n        <SelectValue className=\"whitespace-nowrap\" />\n      </SelectTrigger>\n      <SelectContent>\n        <div className=\"max-h-56 overflow-y-auto overscroll-contain\">\n          {options.map((o) => (\n            <SelectItem key={o.value} value={o.value} className=\"tabular-nums\">\n              {o.label}\n            </SelectItem>\n          ))}\n        </div>\n      </SelectContent>\n    </Select>\n  );\n}\n"},{"path":"components/motion/switch.tsx","type":"util","content":"\"use client\";\n\nimport { animate, motion, MotionConfig, useReducedMotion } from \"motion/react\";\nimport { useEffect, useId, useRef, useState } from \"react\";\nimport { useSound } from \"@/lib/sound\";\nimport { toggleOffSound, toggleOnSound } from \"@/lib/sounds/toggle\";\nimport { cn } from \"@/lib/utils\";\n\n// Heavy, deliberate thumb - high mass keeps the travel weighty without wobble.\nconst THUMB_SPRING = { type: \"spring\", stiffness: 800, damping: 80, mass: 4 } as const;\n\nexport interface SwitchProps {\n  /** Whether the switch is on. */\n  checked: boolean;\n  /** Called with the new state when the switch is toggled. */\n  onCheckedChange: (checked: boolean) => void;\n  /** Dims the switch and stops it from toggling. */\n  disabled?: boolean;\n  /** Visible text beside the switch, also its accessible name. */\n  label?: string;\n  /** Accessible name when there is no visible `label`. */\n  ariaLabel?: string;\n  /** Play a rising blip on, a falling one off. Off by default; a `SoundProvider` can mute it app-wide. */\n  sound?: boolean;\n  /** Classes merged onto the root element. */\n  className?: string;\n}\n\nexport function Switch({\n  checked,\n  onCheckedChange,\n  disabled,\n  label,\n  ariaLabel,\n  sound = false,\n  className,\n}: SwitchProps) {\n  const id = useId();\n  const playOn = useSound(toggleOnSound, { enabled: sound });\n  const playOff = useSound(toggleOffSound, { enabled: sound });\n  const thumbRef = useRef<HTMLDivElement>(null);\n  const reduce = useReducedMotion();\n  const [isPressed, setIsPressed] = useState(false);\n\n  // Disabled shake feedback when pressed.\n  useEffect(() => {\n    if (!thumbRef.current || reduce) return;\n    if (disabled && isPressed) {\n      animate(\n        thumbRef.current,\n        { x: [0, -2, 2, -1, 0] },\n        { delay: 0.2, duration: 0.6 },\n      );\n    }\n  }, [disabled, isPressed, reduce]);\n\n  const squish = !disabled && isPressed && !reduce;\n\n  return (\n    <MotionConfig transition={reduce ? { duration: 0 } : THUMB_SPRING}>\n      <span className={cn(\"inline-flex items-center gap-3\", className)}>\n        <motion.button\n          id={id}\n          type=\"button\"\n          role=\"switch\"\n          aria-checked={checked}\n          aria-label={ariaLabel}\n          disabled={disabled}\n          onClick={() => {\n            if (disabled) return;\n            if (checked) playOff();\n            else playOn();\n            onCheckedChange(!checked);\n          }}\n          onPointerDown={() => setIsPressed(true)}\n          onPointerUp={() => setIsPressed(false)}\n          onPointerLeave={() => setIsPressed(false)}\n          initial={false}\n          data-state={checked ? \"checked\" : \"unchecked\"}\n          className={cn(\n            \"group peer inline-flex h-7 w-12 shrink-0 cursor-pointer items-center px-1 rounded-full outline-none transition-colors duration-200\",\n            \"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background\",\n            \"disabled:cursor-not-allowed disabled:opacity-60\",\n            checked ? \"justify-end bg-primary\" : \"justify-start bg-muted-foreground/60\",\n          )}\n        >\n          <motion.div\n            ref={thumbRef}\n            layout\n            animate={{ scale: squish ? 0.9 : 1 }}\n            className=\"pointer-events-none block h-5 w-5 rounded-full bg-background shadow-md\"\n          >\n            {/* Stretch toward the destination while active. */}\n            <div\n              className={cn(\n                \"size-5\",\n                squish && (checked ? \"ml-1\" : \"mr-1\"),\n              )}\n            />\n          </motion.div>\n        </motion.button>\n        {label ? (\n          <label htmlFor={id} className=\"cursor-pointer text-sm text-foreground\">\n            {label}\n          </label>\n        ) : null}\n      </span>\n    </MotionConfig>\n  );\n}\n"},{"path":"components/motion/tooltip.tsx","type":"util","content":"\"use client\";\n\nimport { AnimatePresence } from \"motion/react\";\nimport {\n  type ComponentProps,\n  type PointerEvent as ReactPointerEvent,\n  cloneElement,\n  createContext,\n  isValidElement,\n  type ReactElement,\n  type ReactNode,\n  type Ref,\n  type RefObject,\n  useCallback,\n  useContext,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { TooltipSurface } from \"@/components/motion/tooltip-surface\";\nimport { type DismissReason, useDismiss } from \"@/lib/hooks/use-dismiss\";\nimport { useHoverGesture } from \"@/lib/hooks/use-hover-gesture\";\nimport { useTapGesture } from \"@/lib/hooks/use-tap-gesture\";\nimport { assignRef } from \"@/lib/merge-refs\";\nimport { cn } from \"@/lib/utils\";\nimport { focusFromKeyboard, graceArea, inBox, inPolygon, watchModality } from \"./tooltip/grace\";\nimport { TooltipArrow, TooltipPositioner } from \"./tooltip/positioner\";\nimport {\n  type TooltipAlign,\n  type TooltipAnchor,\n  type TooltipPoint,\n  type TooltipSide,\n  useTooltipPointer,\n} from \"./tooltip/use-position\";\n\nexport type { TooltipAlign, TooltipSide };\n\n/* -------------------------------------------------------------------------- */\n/* Provider                                                                   */\n/* -------------------------------------------------------------------------- */\n\ninterface TooltipTiming {\n  /** Delay before a hover opens a tooltip (ms). */\n  delay: number;\n  /** Delay before a tooltip closes once the pointer has left it (ms). */\n  closeDelay: number;\n  /** After one tooltip closes, others open instantly for this long (ms). */\n  skipDelay: number;\n}\n\nconst TimingContext = createContext<TooltipTiming>({ delay: 120, closeDelay: 0, skipDelay: 300 });\n\nexport interface TooltipProviderProps extends Partial<TooltipTiming> {\n  children: ReactNode;\n}\n\n/** Shared timing for every tooltip inside it. Optional: tooltips work without one. */\nexport function TooltipProvider({ children, ...timing }: TooltipProviderProps) {\n  const parent = useContext(TimingContext);\n  const { delay = parent.delay, closeDelay = parent.closeDelay, skipDelay = parent.skipDelay } =\n    timing;\n  const value = useMemo(() => ({ delay, closeDelay, skipDelay }), [delay, closeDelay, skipDelay]);\n  return <TimingContext.Provider value={value}>{children}</TimingContext.Provider>;\n}\n\n/* -------------------------------------------------------------------------- */\n/* Root                                                                       */\n/* -------------------------------------------------------------------------- */\n\n// Moving along a toolbar should feel instant after the first label, and only\n// one label may show at a time: a keyboard-focused control and a hovered one\n// would otherwise both claim the screen.\nlet lastClosedAt = 0;\nlet current: { close: () => void } | null = null;\n\nfunction isEmpty(content: ReactNode) {\n  return content == null || content === false || content === \"\";\n}\n\ninterface TooltipContextValue {\n  open: boolean;\n  /** Show and hide without animating (keyboard focus, a warm toolbar, a replaced label). */\n  instant: boolean;\n  contentId: string;\n  labelId: string;\n  asLabel: boolean;\n  empty: boolean;\n  followCursor: boolean;\n  anchor: TooltipAnchor | null;\n  /** True when a TooltipTrigger owns the anchor; false for an external `anchorRef`. */\n  triggered: boolean;\n  floatingRef: RefObject<HTMLSpanElement | null>;\n  pointer: ReturnType<typeof useTooltipPointer>;\n  setTrigger: (element: TooltipAnchor | null) => void;\n  setEmpty: (empty: boolean) => void;\n  close: () => void;\n  onContentEnter: () => void;\n  onContentLeave: (event: ReactPointerEvent) => void;\n}\n\nconst TooltipContext = createContext<TooltipContextValue | null>(null);\n\nfunction useTooltipContext(part: string) {\n  const context = useContext(TooltipContext);\n  if (!context) throw new Error(`${part} must be used inside <Tooltip>`);\n  return context;\n}\n\nexport interface TooltipRootProps {\n  children?: ReactNode;\n  /** Whether the tooltip is shown, for controlled use. */\n  open?: boolean;\n  /** Whether the tooltip starts shown when uncontrolled. Default: false */\n  defaultOpen?: boolean;\n  /** Called with the new state when the tooltip shows or hides. */\n  onOpenChange?: (open: boolean) => void;\n  /** Delay before showing on hover (ms). Keyboard focus shows immediately. */\n  delay?: number;\n  /** Delay before hiding once the pointer has left (ms). */\n  closeDelay?: number;\n  /** Never show, e.g. while the label it carries is already visible. */\n  disabled?: boolean;\n  /**\n   * Use the tooltip as the trigger's accessible name rather than its\n   * description. For icon-only controls whose only label is the tooltip.\n   */\n  asLabel?: boolean;\n  /** Follow real pointer coordinates; keyboard focus still uses the anchor. */\n  followCursor?: boolean;\n  /** Existing anchor for controlled integrations such as chart cells. */\n  anchorRef?: RefObject<TooltipAnchor | null>;\n  /** Id of the tooltip surface, for anchors that reference it themselves. */\n  id?: string;\n}\n\nfunction TooltipRoot({\n  children,\n  open: controlledOpen,\n  defaultOpen = false,\n  onOpenChange,\n  delay: delayProp,\n  closeDelay: closeDelayProp,\n  disabled = false,\n  asLabel = false,\n  followCursor = false,\n  anchorRef,\n  id,\n  initialEmpty = false,\n}: TooltipRootProps & { initialEmpty?: boolean }) {\n  const timing = useContext(TimingContext);\n  const delay = delayProp ?? timing.delay;\n  const closeDelay = closeDelayProp ?? timing.closeDelay;\n  const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen);\n  const open = controlledOpen ?? uncontrolledOpen;\n  // Keyboard focus and a warm toolbar show the label at once; animating\n  // something seen this often only makes it feel slow.\n  const [instant, setInstant] = useState(false);\n  const [empty, setEmpty] = useState(initialEmpty);\n  const [trigger, setTrigger] = useState<TooltipAnchor | null>(null);\n  const [external, setExternal] = useState<TooltipAnchor | null>(null);\n  const anchor = anchorRef ? external : trigger;\n  const generatedId = useId();\n  const contentId = id ?? `${generatedId}-content`;\n  const labelId = `${generatedId}-label`;\n  const floatingRef = useRef<HTMLSpanElement | null>(null);\n  const anchorObject = useRef<TooltipAnchor | null>(null);\n  const pointer = useTooltipPointer(anchor, followCursor);\n\n  // An external ref can attach after this component renders; read it once it has.\n  useLayoutEffect(() => {\n    if (!anchorRef) return;\n    const element = anchorRef.current ?? null;\n    if (element !== external) setExternal(element);\n  });\n\n  // Everything the event listeners read, current without re-binding them.\n  const latest = useRef({ open, delay, closeDelay, disabled, empty, onOpenChange, controlled: false });\n  useLayoutEffect(() => {\n    anchorObject.current = anchor;\n    latest.current = {\n      open,\n      delay,\n      closeDelay,\n      disabled,\n      empty,\n      onOpenChange,\n      controlled: controlledOpen !== undefined,\n    };\n  });\n\n  const openTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n  const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n  const grace = useRef<(() => void) | null>(null);\n  const self = useRef<{ close: () => void }>({ close: () => {} });\n\n  const clearTimers = useCallback(() => {\n    if (openTimer.current) clearTimeout(openTimer.current);\n    if (closeTimer.current) clearTimeout(closeTimer.current);\n    openTimer.current = null;\n    closeTimer.current = null;\n  }, []);\n\n  const stopGrace = useCallback(() => {\n    grace.current?.();\n    grace.current = null;\n  }, []);\n\n  // Only a real change reaches the consumer: a pointer leaving a closed\n  // tooltip is not news.\n  const commit = useCallback((next: boolean) => {\n    if (latest.current.open === next) return;\n    if (!latest.current.controlled) setUncontrolledOpen(next);\n    latest.current.onOpenChange?.(next);\n  }, []);\n\n  const openNow = useCallback(\n    (now = false) => {\n      clearTimers();\n      stopGrace();\n      if (latest.current.disabled || latest.current.empty) return;\n      // The label being replaced leaves at once, so two never show together.\n      if (current && current !== self.current) current.close();\n      current = self.current;\n      setInstant(now);\n      commit(true);\n    },\n    [clearTimers, stopGrace, commit],\n  );\n\n  const finish = useCallback(\n    (now: boolean) => {\n      clearTimers();\n      stopGrace();\n      if (latest.current.open) lastClosedAt = Date.now();\n      if (current === self.current) current = null;\n      if (latest.current.open) setInstant(now);\n      commit(false);\n    },\n    [clearTimers, stopGrace, commit],\n  );\n  // Also a listener (window blur, outside press), so it takes no arguments.\n  const close = useCallback(() => finish(false), [finish]);\n  useLayoutEffect(() => {\n    self.current.close = () => finish(true);\n  }, [finish]);\n\n  const requestOpen = useCallback(() => {\n    clearTimers();\n    if (latest.current.open || latest.current.disabled || latest.current.empty) return;\n    // Warm: another label is still showing (the pointer is crossing to this\n    // one), or one closed a moment ago. Either way, skip the delay and the fade.\n    const warm =\n      (current !== null && current !== self.current) ||\n      Date.now() - lastClosedAt < timing.skipDelay;\n    if (warm) openNow(true);\n    else if (latest.current.delay <= 0) openNow();\n    else openTimer.current = setTimeout(() => openNow(), latest.current.delay);\n  }, [clearTimers, openNow, timing.skipDelay]);\n\n  const requestClose = useCallback(() => {\n    clearTimers();\n    if (latest.current.closeDelay > 0) {\n      closeTimer.current = setTimeout(close, latest.current.closeDelay);\n    } else close();\n  }, [clearTimers, close]);\n\n  // Hold the label open while the pointer crosses from one box toward the other.\n  const startGrace = useCallback(\n    (exit: TooltipPoint, from: Element, to: Element | null) => {\n      stopGrace();\n      if (!to) return requestClose();\n      const target = to.getBoundingClientRect();\n      const origin = from.getBoundingClientRect();\n      const corridor = graceArea(exit, target);\n      const onMove = (event: PointerEvent) => {\n        const point = { x: event.clientX, y: event.clientY };\n        if (inBox(point, target) || inBox(point, origin)) return;\n        if (!inPolygon(point, corridor)) requestClose();\n      };\n      document.addEventListener(\"pointermove\", onMove);\n      grace.current = () => document.removeEventListener(\"pointermove\", onMove);\n    },\n    [stopGrace, requestClose],\n  );\n\n  const hover = useHoverGesture();\n  const tap = useTapGesture<boolean>();\n\n  // Listeners go on the trigger itself rather than on cloned props, so a\n  // component that owns its own handlers keeps them, and no wrapper element\n  // sits between the control and its layout.\n  useEffect(() => {\n    if (anchorRef || !trigger) return;\n    watchModality();\n    // A mouse press dismisses the label and keeps it away until the pointer\n    // leaves; hovering a control you just clicked should not bring it back.\n    let suppressed = false;\n    // Focus that came from the keyboard holds the label open on its own.\n    let keyboardFocus = false;\n\n    const onEnter = (event: PointerEvent) => {\n      if (!hover.enter(event)) return;\n      stopGrace();\n      if (closeTimer.current) clearTimeout(closeTimer.current);\n      if (!suppressed) requestOpen();\n    };\n    const onLeave = (event: PointerEvent) => {\n      if (!hover.leave(event)) return;\n      suppressed = false;\n      if (keyboardFocus) return;\n      if (openTimer.current) {\n        clearTimers();\n        return;\n      }\n      if (latest.current.open && !followCursor) {\n        startGrace({ x: event.clientX, y: event.clientY }, trigger, floatingRef.current);\n      } else requestClose();\n    };\n    const onDown = (event: PointerEvent) => {\n      tap.start(event, latest.current.open);\n      if (event.pointerType === \"mouse\") {\n        suppressed = true;\n        close();\n      }\n    };\n    // A finger never hovers, and Safari does not focus a button on tap either,\n    // so the label is only reachable if the tap itself toggles it. The click\n    // carries no pointerType; the pointerdown before it says whether it was a\n    // tap, and keyboard activation has none at all.\n    const onClick = () => {\n      const gesture = tap.take();\n      if (!gesture || gesture.pointerType === \"mouse\") return;\n      if (gesture.state) close();\n      else openNow();\n    };\n    const onKey = () => tap.drop();\n    const onFocusIn = () => {\n      if (!focusFromKeyboard()) return;\n      keyboardFocus = true;\n      openNow(true);\n    };\n    const onFocusOut = (event: FocusEvent) => {\n      if (trigger.contains(event.relatedTarget as Node | null)) return;\n      const fromKeyboard = keyboardFocus;\n      keyboardFocus = false;\n      finish(fromKeyboard);\n    };\n\n    // Both element kinds dispatch the same events; one type keeps the listeners typed.\n    const el = trigger as HTMLElement;\n    el.addEventListener(\"pointerenter\", onEnter);\n    el.addEventListener(\"pointerleave\", onLeave);\n    el.addEventListener(\"pointerdown\", onDown);\n    el.addEventListener(\"pointercancel\", tap.drop);\n    el.addEventListener(\"click\", onClick);\n    el.addEventListener(\"keydown\", onKey);\n    el.addEventListener(\"focusin\", onFocusIn);\n    el.addEventListener(\"focusout\", onFocusOut);\n    return () => {\n      el.removeEventListener(\"pointerenter\", onEnter);\n      el.removeEventListener(\"pointerleave\", onLeave);\n      el.removeEventListener(\"pointerdown\", onDown);\n      el.removeEventListener(\"pointercancel\", tap.drop);\n      el.removeEventListener(\"click\", onClick);\n      el.removeEventListener(\"keydown\", onKey);\n      el.removeEventListener(\"focusin\", onFocusIn);\n      el.removeEventListener(\"focusout\", onFocusOut);\n    };\n  }, [\n    anchorRef,\n    trigger,\n    followCursor,\n    hover,\n    tap,\n    requestOpen,\n    requestClose,\n    openNow,\n    close,\n    finish,\n    clearTimers,\n    stopGrace,\n    startGrace,\n  ]);\n\n  // While open, a trigger that turns disabled loses focus without a blur event,\n  // and a window that loses focus never reports the pointer leaving.\n  useEffect(() => {\n    if (!open || anchorRef || !trigger) return;\n    const observer = new MutationObserver(() => {\n      if (trigger.matches(\":disabled, [aria-disabled='true']\")) close();\n    });\n    observer.observe(trigger, { attributes: true, attributeFilter: [\"disabled\", \"aria-disabled\"] });\n    window.addEventListener(\"blur\", close);\n    return () => {\n      observer.disconnect();\n      window.removeEventListener(\"blur\", close);\n    };\n  }, [open, anchorRef, trigger, close]);\n\n  // A chart drives its own open state and swaps content as it goes; only a\n  // trigger-owned label closes itself for having nothing to say.\n  useEffect(() => {\n    if (disabled || (empty && !anchorRef)) close();\n  }, [disabled, empty, anchorRef, close]);\n\n  useEffect(\n    () => () => {\n      clearTimers();\n      stopGrace();\n      if (current === self.current) current = null;\n    },\n    [clearTimers, stopGrace],\n  );\n\n  const insideTooltip = useCallback(\n    (target: Element) => Boolean(floatingRef.current?.contains(target)),\n    [],\n  );\n  // ...and closed by the next tap that lands somewhere else, or Escape. The\n  // label covers nothing interactive, so that tap passes through to what it hit.\n  // Escape is a key press, so the label goes at once.\n  const dismiss = useCallback((reason: DismissReason) => finish(reason === \"escape\"), [finish]);\n  useDismiss(open, dismiss, anchorObject, { ignore: insideTooltip });\n\n  const onContentEnter = useCallback(() => {\n    stopGrace();\n    clearTimers();\n  }, [stopGrace, clearTimers]);\n\n  const onContentLeave = useCallback(\n    (event: ReactPointerEvent) => {\n      const floating = floatingRef.current;\n      if (!floating) return;\n      if (anchorRef) {\n        // Bridge the small gap back onto a chart; it reopens on its own terms.\n        clearTimers();\n        closeTimer.current = setTimeout(close, 100);\n        return;\n      }\n      startGrace({ x: event.clientX, y: event.clientY }, floating, anchorObject.current);\n    },\n    [anchorRef, clearTimers, close, startGrace],\n  );\n\n  const value = useMemo<TooltipContextValue>(\n    () => ({\n      open,\n      instant,\n      contentId,\n      labelId,\n      asLabel,\n      empty,\n      followCursor,\n      anchor,\n      triggered: !anchorRef,\n      floatingRef,\n      pointer,\n      setTrigger,\n      setEmpty,\n      close,\n      onContentEnter,\n      onContentLeave,\n    }),\n    [\n      open,\n      instant,\n      contentId,\n      labelId,\n      asLabel,\n      empty,\n      followCursor,\n      anchor,\n      anchorRef,\n      pointer,\n      close,\n      onContentEnter,\n      onContentLeave,\n    ],\n  );\n\n  return <TooltipContext.Provider value={value}>{children}</TooltipContext.Provider>;\n}\n\n/* -------------------------------------------------------------------------- */\n/* Trigger                                                                    */\n/* -------------------------------------------------------------------------- */\n\nfunction mergeIds(...ids: unknown[]) {\n  return ids.filter((value) => typeof value === \"string\" && value).join(\" \") || undefined;\n}\n\nexport interface TooltipTriggerProps extends ComponentProps<\"button\"> {\n  /** Use the single child element as the trigger instead of rendering a button. */\n  asChild?: boolean;\n}\n\nexport function TooltipTrigger({ asChild = false, children, ref, ...props }: TooltipTriggerProps) {\n  const { open, contentId, labelId, asLabel, empty, setTrigger } =\n    useTooltipContext(\"TooltipTrigger\");\n  const child = asChild && isValidElement(children) ? children : null;\n  const childProps = (child?.props ?? props) as Record<string, unknown>;\n  const childRef = child ? (childProps.ref as Ref<TooltipAnchor> | undefined) : undefined;\n  const attached = useRef<TooltipAnchor | null>(null);\n\n  const setRef = useCallback(\n    (element: TooltipAnchor | null) => {\n      attached.current = element;\n      setTrigger(element);\n      assignRef(childRef ?? (ref as Ref<TooltipAnchor> | undefined), element);\n    },\n    [setTrigger, childRef, ref],\n  );\n\n  useEffect(() => {\n    if (process.env.NODE_ENV !== \"production\" && child && !attached.current) {\n      console.warn(\n        \"TooltipTrigger: the child did not attach a ref, so the tooltip has nothing to listen to. Render a DOM element or a component that passes `ref` through.\",\n      );\n    }\n  }, [child]);\n\n  const aria = asLabel\n    ? {\n        \"aria-labelledby\": empty\n          ? (childProps[\"aria-labelledby\"] as string | undefined)\n          : labelId,\n      }\n    : {\n        \"aria-describedby\": mergeIds(\n          childProps[\"aria-describedby\"],\n          open && !empty ? contentId : undefined,\n        ),\n      };\n\n  if (asChild) {\n    if (!child) return children;\n    return cloneElement(child as ReactElement<Record<string, unknown>>, { ref: setRef, ...aria });\n  }\n\n  return (\n    <button\n      type=\"button\"\n      data-state={open ? \"open\" : \"closed\"}\n      {...props}\n      ref={setRef as Ref<HTMLButtonElement>}\n      {...aria}\n    >\n      {children}\n    </button>\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/* Content                                                                    */\n/* -------------------------------------------------------------------------- */\n\nexport interface TooltipContentProps {\n  children?: ReactNode;\n  /** Preferred side of the anchor. Flips when there is no room. Default: \"top\" */\n  side?: TooltipSide;\n  /** Alignment along the chosen side. Default: \"center\" */\n  align?: TooltipAlign;\n  /** Gap between anchor and tooltip (px). */\n  sideOffset?: number;\n  /** Draw an arrow pointing at the anchor. */\n  arrow?: boolean;\n  /** Point within the anchor, as fractions of its rendered width and height. */\n  anchorPoint?: TooltipPoint;\n  /** Classes merged onto the tooltip surface. */\n  className?: string;\n}\n\nexport function TooltipContent({\n  children,\n  side = \"top\",\n  align = \"center\",\n  sideOffset,\n  arrow = false,\n  anchorPoint,\n  className,\n}: TooltipContentProps) {\n  const {\n    open,\n    instant,\n    contentId,\n    labelId,\n    asLabel,\n    followCursor,\n    anchor,\n    floatingRef,\n    pointer,\n    setEmpty,\n    close,\n    onContentEnter,\n    onContentLeave,\n  } = useTooltipContext(\"TooltipContent\");\n  const empty = isEmpty(children);\n  const arrowRef = useRef<SVGSVGElement | null>(null);\n\n  useLayoutEffect(() => {\n    setEmpty(empty);\n  }, [empty, setEmpty]);\n\n  if (typeof document === \"undefined\") return null;\n\n  return createPortal(\n    <>\n      {/* The name has to exist while the label is closed, so it lives apart from the surface. */}\n      {asLabel && !empty ? (\n        <span id={labelId} hidden>\n          {children}\n        </span>\n      ) : null}\n      {/* `custom` reaches a surface that is already exiting, so a label closed\n          from the keyboard or replaced by a neighbour leaves without animating. */}\n      <AnimatePresence custom={instant}>\n        {open && !empty ? (\n          <TooltipPositioner\n            key=\"tooltip\"\n            anchor={anchor}\n            floatingRef={floatingRef}\n            arrowRef={arrow ? arrowRef : undefined}\n            anchorPoint={anchorPoint}\n            followCursor={followCursor}\n            side={side}\n            align={align}\n            sideOffset={sideOffset}\n            onDismiss={close}\n            pointer={pointer}\n          >\n            {(positioned, isPresent, placedSide) => (\n              <TooltipSurface\n                id={asLabel ? undefined : contentId}\n                aria-hidden={asLabel || undefined}\n                ready={positioned}\n                instant={instant}\n                onPointerEnter={onContentEnter}\n                onPointerLeave={onContentLeave}\n                style={{ pointerEvents: isPresent && !followCursor ? \"auto\" : \"none\" }}\n                className={cn(\n                  \"max-w-[min(20rem,calc(100vw-16px))] whitespace-normal break-words\",\n                  arrow && \"relative\",\n                  className,\n                )}\n              >\n                {children}\n                {arrow ? <TooltipArrow ref={arrowRef} side={placedSide} /> : null}\n              </TooltipSurface>\n            )}\n          </TooltipPositioner>\n        ) : null}\n      </AnimatePresence>\n    </>,\n    document.body,\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/* Tooltip (root, or one-line shorthand when given `content`)                 */\n/* -------------------------------------------------------------------------- */\n\nexport interface TooltipProps\n  extends TooltipRootProps,\n    Omit<TooltipContentProps, \"children\" | \"className\"> {\n  /**\n   * Shorthand: the tooltip's content. With it, `children` is the trigger\n   * element; without it, compose `TooltipTrigger` and `TooltipContent`.\n   */\n  content?: ReactNode;\n  /** Shorthand only: classes for the tooltip surface. */\n  className?: string;\n}\n\nexport function Tooltip(props: TooltipProps) {\n  if (!(\"content\" in props)) return <TooltipRoot {...props} />;\n  const {\n    content,\n    children,\n    side,\n    align,\n    sideOffset,\n    arrow,\n    anchorPoint,\n    className,\n    ...root\n  } = props;\n  if (!root.anchorRef && !isValidElement(children)) return children ?? null;\n  return (\n    <TooltipRoot {...root} initialEmpty={isEmpty(content)}>\n      {isValidElement(children) ? <TooltipTrigger asChild>{children}</TooltipTrigger> : null}\n      <TooltipContent\n        side={side}\n        align={align}\n        sideOffset={sideOffset}\n        arrow={arrow}\n        anchorPoint={anchorPoint}\n        className={className}\n      >\n        {content}\n      </TooltipContent>\n    </TooltipRoot>\n  );\n}\n"},{"path":"lib/ease.ts","type":"util","content":"// Shared motion tokens. Easing curves mirror the CSS custom properties in\n// globals.css; springs are the canonical physics used across components.\n// Strong custom variants - defaults like `ease-in`/`ease-out` feel weak.\n\nexport const EASE_OUT = [0.16, 1, 0.3, 1] as const;\n/** Accelerating curve for things that fall (a dropped ball, a toppled block). Not for UI entrances. */\nexport const EASE_IN = [0.55, 0, 1, 0.45] 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\n/** Shared-surface morphs: a trigger growing into its panel and back on one\n * weighted spring, so opening and closing travel the same path. */\nexport const SPRING_MORPH = {\n  type: \"spring\",\n  duration: 0.5,\n  bounce: 0.22,\n} as const;\n"},{"path":"components/motion/checkbox.tsx","type":"util","content":"\"use client\";\n\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { useId } from \"react\";\nimport { EASE_OUT, SPRING_PRESS } from \"@/lib/ease\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const checkboxMessages = {\n  checked: \"Selected\",\n  indeterminate: \"Partially selected\",\n};\n\nexport type CheckboxMessages = typeof checkboxMessages;\n\nconst CHECK_PATH = \"M5 13l4 4L19 7\";\nconst INDETERMINATE_PATH = \"M6 12h12\";\n\nexport interface CheckboxProps {\n  /** Whether the box is checked. */\n  checked: boolean;\n  /** Called with the new state when the box is toggled. */\n  onCheckedChange: (checked: boolean) => void;\n  /** Blocks toggling and dims the control. */\n  disabled?: boolean;\n  /** Shows a dash for a partly selected group. Announced as mixed. */\n  indeterminate?: boolean;\n  /** Visible text beside the box, also its accessible name. */\n  label?: string;\n  /** Supporting text under the label, announced as the description rather than the name. */\n  description?: string;\n  /** Classes merged onto the root label element. */\n  className?: string;\n  /** Id for the checkbox button. Generated when omitted. */\n  id?: string;\n  /** Accessible name when there is no visible label. */\n  \"aria-label\"?: string;\n  /** Associates an external message (e.g. a form error) with the control. */\n  \"aria-describedby\"?: string;\n  /** Override any built-in string. */\n  labels?: Partial<CheckboxMessages>;\n}\n\nexport function Checkbox({\n  checked,\n  onCheckedChange,\n  disabled,\n  indeterminate,\n  label,\n  description,\n  className,\n  id: idProp,\n  \"aria-label\": ariaLabel,\n  \"aria-describedby\": ariaDescribedBy,\n  labels,\n}: CheckboxProps) {\n  const t = useMessages(\"checkbox\", checkboxMessages, labels);\n  const autoId = useId();\n  const id = idProp ?? autoId;\n  const reduce = useReducedMotion();\n  const showMark = checked || indeterminate;\n  const path = indeterminate ? INDETERMINATE_PATH : CHECK_PATH;\n  const descriptionId = description ? `${id}-description` : undefined;\n  // The wrapping <label> would fold the description into the name, so name from the label text alone.\n  const labelId = description && label && !ariaLabel ? `${id}-label` : undefined;\n  const describedBy =\n    [ariaDescribedBy, descriptionId].filter(Boolean).join(\" \") || undefined;\n\n  return (\n    <label\n      htmlFor={id}\n      className={cn(\n        \"inline-flex gap-3\",\n        description ? \"items-start\" : \"items-center\",\n        disabled ? \"cursor-not-allowed\" : \"cursor-pointer\",\n        className,\n      )}\n    >\n      <motion.button\n        id={id}\n        type=\"button\"\n        role=\"checkbox\"\n        aria-checked={indeterminate ? \"mixed\" : checked}\n        aria-label={ariaLabel}\n        aria-labelledby={labelId}\n        aria-describedby={describedBy}\n        disabled={disabled}\n        onClick={() => !disabled && onCheckedChange(!checked)}\n        whileTap={reduce || disabled ? undefined : { scale: 0.92 }}\n        transition={SPRING_PRESS}\n        data-state={\n          checked ? \"checked\" : indeterminate ? \"indeterminate\" : \"unchecked\"\n        }\n        className={cn(\n          \"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-md border-2 outline-none transition-colors duration-200\",\n          \"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background\",\n          \"disabled:cursor-not-allowed disabled:opacity-60\",\n          showMark\n            ? \"border-primary bg-primary text-primary-foreground\"\n            : \"border-muted-foreground/50 bg-background hover:border-muted-foreground\",\n        )}\n      >\n        <AnimatePresence initial={false}>\n          {showMark ? (\n            <motion.svg\n              key={indeterminate ? \"indeterminate\" : \"checked\"}\n              width=\"12\"\n              height=\"12\"\n              viewBox=\"0 0 24 24\"\n              fill=\"none\"\n              stroke=\"currentColor\"\n              strokeWidth={3}\n              strokeLinecap=\"round\"\n              strokeLinejoin=\"round\"\n              initial={reduce ? { opacity: 1 } : { opacity: 0, scale: 0.5 }}\n              animate={reduce ? { opacity: 1 } : { opacity: 1, scale: 1 }}\n              exit={\n                reduce\n                  ? { opacity: 0 }\n                  : { opacity: 0, scale: 0.5, filter: \"blur(4px)\" }\n              }\n              transition={\n                reduce ? { duration: 0 } : { duration: 0.16, ease: EASE_OUT }\n              }\n              aria-hidden\n            >\n              <title>{t(indeterminate ? \"indeterminate\" : \"checked\")}</title>\n              <motion.path\n                d={path}\n                initial={reduce ? { pathLength: 1 } : { pathLength: 0 }}\n                animate={{ pathLength: 1 }}\n                transition={\n                  reduce\n                    ? { duration: 0 }\n                    : {\n                        duration: indeterminate ? 0.2 : 0.3,\n                        ease: EASE_OUT,\n                        delay: 0.04,\n                      }\n                }\n              />\n            </motion.svg>\n          ) : null}\n        </AnimatePresence>\n      </motion.button>\n      {label || description ? (\n        <span className={cn(\"flex min-w-0 flex-col gap-0.5 select-none\", disabled && \"opacity-60\")}>\n          {label ? (\n            <span\n              id={labelId}\n              // Geist sits low in a 20px line; a 16px line lifts the text onto the control.\n              className={cn(\"text-sm text-foreground\", description && \"leading-4\")}\n            >\n              {label}\n            </span>\n          ) : null}\n          {description ? (\n            <span id={descriptionId} className=\"text-xs text-muted-foreground\">\n              {description}\n            </span>\n          ) : null}\n        </span>\n      ) : null}\n    </label>\n  );\n}\n"},{"path":"components/motion/popover-morph.tsx","type":"util","content":"\"use client\";\n\nimport {\n  AnimatePresence,\n  animate,\n  motion,\n  useMotionValue,\n  usePresence,\n  useReducedMotion,\n  useTransform,\n} from \"motion/react\";\nimport {\n  cloneElement,\n  createContext,\n  isValidElement,\n  type ReactElement,\n  type ReactNode,\n  type Ref,\n  type RefObject,\n  useCallback,\n  useContext,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { usePopoverPortalPosition } from \"@/components/motion/popover-position\";\nimport { EASE_OUT } from \"@/lib/ease\";\nimport { FOCUSABLE_SELECTOR } from \"@/lib/focusable\";\nimport { useDismiss } from \"@/lib/hooks/use-dismiss\";\nimport { mergeRefs } from \"@/lib/merge-refs\";\nimport { cn } from \"@/lib/utils\";\n\ntype Side = \"top\" | \"bottom\";\ntype Align = \"start\" | \"end\";\n\ntype MorphContextValue = {\n  open: boolean;\n  setOpen: (open: boolean) => void;\n  toggle: () => void;\n  triggerId: string;\n  contentId: string;\n  /** The element the panel measures against - see `registerTrigger`. */\n  triggerRef: React.MutableRefObject<HTMLElement | null>;\n  registerTrigger: (node: HTMLElement | null) => void;\n  contentRef: React.MutableRefObject<HTMLDivElement | null>;\n  /** Arms or disarms moving focus into the panel as it next appears. */\n  armFocusOnOpen: (armed: boolean) => void;\n  /** Reads and disarms the flag set by `armFocusOnOpen`. */\n  takeFocusOnOpen: () => boolean;\n};\n\nconst MorphContext = createContext<MorphContextValue | null>(null);\n\nfunction useMorphContext(component: string) {\n  const ctx = useContext(MorphContext);\n  if (!ctx) throw new Error(`${component} must be used within <MorphPopover>`);\n  return ctx;\n}\n\nexport interface MorphPopoverProps {\n  children: ReactNode;\n  /** Controlled open state. */\n  open?: boolean;\n  /** Uncontrolled initial open state. */\n  defaultOpen?: boolean;\n  /** Called with the new open state when the panel opens or closes. */\n  onOpenChange?: (open: boolean) => void;\n  /** Classes merged onto the wrapper around the trigger. */\n  className?: string;\n}\n\n/**\n * A popover whose full-size panel reveals from the corner nearest the trigger\n * on one spring, then retraces the same clip on close. Content and surface\n * edges keep their size throughout. Closes on outside pointer / Escape.\n * Controlled or uncontrolled.\n */\nexport function MorphPopover({\n  children,\n  open: controlledOpen,\n  defaultOpen = false,\n  onOpenChange,\n  className,\n}: MorphPopoverProps) {\n  const baseId = useId();\n  const [root, setRoot] = useState<HTMLDivElement | null>(null);\n  const [trigger, setTrigger] = useState<HTMLElement | null>(null);\n  const contentRef = useRef<HTMLDivElement | null>(null);\n  const [internalOpen, setInternalOpen] = useState(defaultOpen);\n  const controlled = controlledOpen !== undefined;\n  const open = controlled ? controlledOpen : internalOpen;\n\n  const setOpen = useCallback(\n    (next: boolean) => {\n      if (!controlled) setInternalOpen(next);\n      onOpenChange?.(next);\n    },\n    [controlled, onOpenChange],\n  );\n  const toggle = useCallback(() => setOpen(!open), [setOpen, open]);\n\n  // A keyboard open arms focus for the panel to take as it appears. Any later\n  // key or pointer press disarms it, so an open the parent declined cannot\n  // leave it armed for a later open that nobody asked to focus.\n  const focusOnOpenRef = useRef(false);\n  const disarmRef = useRef<AbortController | null>(null);\n  const armFocusOnOpen = useCallback((armed: boolean) => {\n    disarmRef.current?.abort();\n    disarmRef.current = null;\n    focusOnOpenRef.current = armed;\n    if (!armed) return;\n    const controller = new AbortController();\n    const disarm = () => {\n      focusOnOpenRef.current = false;\n      controller.abort();\n    };\n    const options = { capture: true, signal: controller.signal };\n    document.addEventListener(\"keydown\", disarm, options);\n    document.addEventListener(\"pointerdown\", disarm, options);\n    disarmRef.current = controller;\n  }, []);\n  const takeFocusOnOpen = useCallback(() => {\n    const armed = focusOnOpenRef.current;\n    armFocusOnOpen(false);\n    return armed;\n  }, [armFocusOnOpen]);\n  useEffect(() => () => disarmRef.current?.abort(), []);\n\n  // A trigger normally registers itself through MorphPopoverTrigger. It can't\n  // when something else already clones the element - a Tooltip wrapping the\n  // button, say - and an unregistered trigger leaves the panel with nothing to\n  // measure against, so it renders permanently invisible. The root boxes the\n  // trigger exactly (the content portals out of it), so it stands in until a\n  // real trigger registers, and stands in again if that one unmounts. Both are\n  // state, so a trigger arriving while the panel is open re-anchors it.\n  const anchorRef = useMemo<React.MutableRefObject<HTMLElement | null>>(\n    () => ({ current: trigger ?? root }),\n    [root, trigger],\n  );\n\n  // The panel is a `role=\"dialog\"` and goes inert the moment it closes, so\n  // focus cannot be left sitting inside it: a dismissal hands it back to the\n  // trigger, the way the ARIA dialog pattern asks. A pointer dismissal takes\n  // the focus onward itself when it lands on something focusable - this only\n  // catches the case where it would otherwise be stranded. When no trigger has\n  // registered, the root anchor stands in only if it can actually hold focus;\n  // there is nowhere better than where the keyboard already is, so leave it.\n  const close = useCallback(() => {\n    setOpen(false);\n    const focused = document.activeElement;\n    const inPanel =\n      focused instanceof HTMLElement && contentRef.current?.contains(focused);\n    if (!inPanel) return;\n    const restore = trigger ?? (root && root.tabIndex >= 0 ? root : null);\n    restore?.focus();\n  }, [root, setOpen, trigger]);\n\n  // Inside is the root anchor and the portaled panel. Until the root mounts\n  // there is nothing to measure \"outside\" against, so nothing dismisses.\n  const insidePopover = useCallback(\n    (target: Element) =>\n      !root || root.contains(target) || Boolean(contentRef.current?.contains(target)),\n    [root],\n  );\n  useDismiss(open, close, null, { ignore: insidePopover });\n\n  const ctx = useMemo<MorphContextValue>(\n    () => ({\n      open,\n      setOpen,\n      toggle,\n      triggerId: `${baseId}-trigger`,\n      contentId: `${baseId}-content`,\n      triggerRef: anchorRef,\n      registerTrigger: setTrigger,\n      contentRef,\n      armFocusOnOpen,\n      takeFocusOnOpen,\n    }),\n    [open, setOpen, toggle, baseId, anchorRef, armFocusOnOpen, takeFocusOnOpen],\n  );\n\n  return (\n    <MorphContext.Provider value={ctx}>\n      <div ref={setRoot} className={cn(\"relative inline-flex\", className)}>\n        {children}\n      </div>\n    </MorphContext.Provider>\n  );\n}\n\nexport interface MorphPopoverTriggerProps {\n  children: ReactElement;\n}\n\n/** Wraps a single element, toggling the popover on click. */\nexport function MorphPopoverTrigger({ children }: MorphPopoverTriggerProps) {\n  const ctx = useMorphContext(\"MorphPopoverTrigger\");\n  const child = children as ReactElement<Record<string, unknown>>;\n  const childOnClick = child?.props?.onClick as\n    | ((e: unknown) => void)\n    | undefined;\n  const childOnKeyDown = child?.props?.onKeyDown as\n    | ((e: unknown) => void)\n    | undefined;\n  const childOnPointerDown = child?.props?.onPointerDown as\n    | ((e: unknown) => void)\n    | undefined;\n  // Set by an Enter or Space keydown on the trigger, cleared by a pointer\n  // press, read by the click that follows.\n  const keyboardRef = useRef(false);\n  const childRef = (child?.props as { ref?: Ref<HTMLElement> } | undefined)\n    ?.ref;\n  // Register once per actual ref change, not once per open-state render.\n  const mergedRef = useMemo(\n    () => mergeRefs(childRef, ctx.registerTrigger),\n    [childRef, ctx.registerTrigger],\n  );\n  if (!isValidElement(children)) return children;\n\n  return cloneElement(child, {\n    id: ctx.triggerId,\n    ref: mergedRef,\n    onKeyDown: (e: unknown) => {\n      childOnKeyDown?.(e);\n      const key = (e as { key?: string } | undefined)?.key;\n      keyboardRef.current = key === \"Enter\" || key === \" \";\n    },\n    onPointerDown: (e: unknown) => {\n      childOnPointerDown?.(e);\n      keyboardRef.current = false;\n    },\n    onClick: (e: unknown) => {\n      childOnClick?.(e);\n      // Enter and Space reach here as a click with `detail` 0 after their\n      // keydown on this element. A pointer click counts at least 1, and a\n      // scripted click() has no keydown before it. Only a keyboard open\n      // moves focus into the panel.\n      const keyboard =\n        keyboardRef.current &&\n        (e as { detail?: number } | undefined)?.detail === 0;\n      keyboardRef.current = false;\n      ctx.armFocusOnOpen(!ctx.open && keyboard);\n      ctx.toggle();\n    },\n    \"aria-haspopup\": \"dialog\",\n    \"aria-expanded\": ctx.open,\n    \"aria-controls\": ctx.open ? ctx.contentId : undefined,\n  });\n}\n\n// Full-distance clip travel needs a shorter curve than SPRING_PANEL's slow\n// overdamped tail. A non-bouncing spring reaches its rest within 260 ms.\nconst MORPH_ENTER = { type: \"spring\", duration: 0.26, bounce: 0 } as const;\nconst MORPH_EXIT = { duration: 0.2, ease: EASE_OUT } as const;\n\n// Keep the panel and content at their final size. An inset clip reveals the\n// nearest corner without scaling borders, shadows or keyboard-focus geometry.\n// A full-size clip keeps content at its final coordinates without box-to-box\n// scale correction. One progress value keeps clip and opacity synchronized;\n// clip-path and the shadow may paint, so this is not a compositor-only morph.\nfunction clipAt(side: Side, align: Align, radius: number, inset: number) {\n  return `inset(${side === \"top\" ? inset : 0}% ${align === \"start\" ? inset : 0}% ${side === \"bottom\" ? inset : 0}% ${align === \"end\" ? inset : 0}% round ${radius}px)`;\n}\n\nexport interface MorphPopoverContentProps {\n  children: ReactNode;\n  /** Preferred side of the trigger. Flips when there is no room. Default: \"bottom\" */\n  side?: Side;\n  /** Lines the panel up with the trigger's start or end edge. Default: \"end\" */\n  align?: Align;\n  /** Gap between trigger and panel, in px. Default 8. */\n  sideOffset?: number;\n  /** Panel corner radius, in px. Default 16 (rounded-2xl), like every floating panel. */\n  radius?: number;\n  /** Draw the surface shadow. Default true. */\n  shadow?: boolean;\n  /**\n   * Runs after the portalled surface is positioned and visible. Passing it\n   * hands focus to the caller: the panel then moves no focus on its own.\n   */\n  onOpenAutoFocus?: (content: HTMLDivElement) => void;\n  /**\n   * Element to focus when the trigger opens the panel by keyboard. Defaults\n   * to the first focusable element in the panel, or the panel itself. A\n   * pointer open does not move focus. Ignored with `onOpenAutoFocus`.\n   */\n  initialFocus?: RefObject<HTMLElement | null>;\n  /** Classes merged onto the panel surface. */\n  className?: string;\n}\n\nexport function MorphPopoverContent(props: MorphPopoverContentProps) {\n  const ctx = useMorphContext(\"MorphPopoverContent\");\n  const [portalReady, setPortalReady] = useState(false);\n  useEffect(() => setPortalReady(true), []);\n  if (!portalReady) return null;\n  return createPortal(\n    <AnimatePresence>\n      {ctx.open && <MorphPopoverSurface {...props} />}\n    </AnimatePresence>,\n    document.body,\n  );\n}\n\n// Measurement belongs to the mounted portal session: reopening must not start\n// an entrance at the previous session's coordinates before measuring this one.\nfunction MorphPopoverSurface({\n  children,\n  side = \"bottom\",\n  align = \"end\",\n  sideOffset = 8,\n  radius = 16,\n  shadow = true,\n  onOpenAutoFocus,\n  initialFocus,\n  className,\n}: MorphPopoverContentProps) {\n  const ctx = useMorphContext(\"MorphPopoverContent\");\n  const reduce = useReducedMotion() ?? false;\n  const [isPresent, safeToRemove] = usePresence();\n  const layout = usePopoverPortalPosition(\n    ctx.triggerRef,\n    ctx.contentRef,\n    isPresent,\n  );\n\n  const preferredLeft = layout\n    ? align === \"end\"\n      ? layout.trigger.left + layout.trigger.width - layout.content.width\n      : layout.trigger.left\n    : 0;\n  // Keep larger compositions, such as calendars, inside the viewport. Prefer\n  // the requested side, then use the roomier side when it cannot fit there.\n  const gutter = 12;\n  const below = layout\n    ? Math.max(\n        0,\n        window.innerHeight -\n          layout.trigger.top -\n          layout.trigger.height -\n          sideOffset -\n          gutter,\n      )\n    : 0;\n  const above = layout\n    ? Math.max(0, layout.trigger.top - sideOffset - gutter)\n    : 0;\n  const requestedSpace = side === \"bottom\" ? below : above;\n  const otherSpace = side === \"bottom\" ? above : below;\n  const resolvedSide =\n    layout &&\n    layout.content.height > requestedSpace &&\n    otherSpace > requestedSpace\n      ? side === \"bottom\"\n        ? \"top\"\n        : \"bottom\"\n      : side;\n  const availableHeight = resolvedSide === \"bottom\" ? below : above;\n  const left = layout\n    ? Math.max(\n        gutter,\n        Math.min(\n          preferredLeft,\n          window.innerWidth - layout.content.width - gutter,\n        ),\n      )\n    : 0;\n  const top = layout\n    ? resolvedSide === \"bottom\"\n      ? layout.trigger.top + layout.trigger.height + sideOffset\n      : Math.max(\n          gutter,\n          layout.trigger.top - layout.content.height - sideOffset,\n        )\n    : 0;\n\n  const progress = useMotionValue(0);\n  const clipPath = useTransform(progress, (p) =>\n    clipAt(resolvedSide, align, radius, 92 * (1 - p)),\n  );\n  const surfaceOpacity = useTransform(progress, [0, 0.15], [0, 1]);\n  // Reduced motion has no travel, so a short fade carries the whole entrance\n  // and exit on its own.\n  const fade = useMotionValue(reduce ? 0 : 1);\n  const ready = layout !== null;\n  const focusedOnOpen = useRef(false);\n  useEffect(() => {\n    if (\n      !ready ||\n      !isPresent ||\n      focusedOnOpen.current ||\n      !ctx.contentRef.current\n    )\n      return;\n    focusedOnOpen.current = true;\n    onOpenAutoFocus?.(ctx.contentRef.current);\n  }, [ready, isPresent, ctx.contentRef, onOpenAutoFocus]);\n  // `safeToRemove` is a new function on every render: AnimatePresence\n  // rebuilds its context each time its parent renders. Read it through a ref\n  // so a render during the exit (a consumer's state change, a list streaming\n  // in) does not restart the exit from where it got to - restarted every\n  // render, it would close in ever smaller steps and never report completion,\n  // leaving an inert, invisible panel mounted for good.\n  const safeToRemoveRef = useRef(safeToRemove);\n  useLayoutEffect(() => {\n    safeToRemoveRef.current = safeToRemove;\n  });\n  useEffect(() => {\n    if (!ready) {\n      if (!isPresent) safeToRemoveRef.current?.();\n      return;\n    }\n    const settle = () => {\n      if (!isPresent) safeToRemoveRef.current?.();\n    };\n    if (reduce) {\n      progress.jump(1);\n      const animation = animate(fade, isPresent ? 1 : 0, {\n        duration: 0.12,\n        onComplete: settle,\n      });\n      return () => animation.stop();\n    }\n    const animation = animate(progress, isPresent ? 1 : 0, {\n      ...(isPresent ? MORPH_ENTER : MORPH_EXIT),\n      onComplete: settle,\n    });\n    return () => animation.stop();\n  }, [fade, progress, ready, isPresent, reduce]);\n\n  // The wrapper stays `visibility: hidden` until the first measurement, and\n  // focus() inside a hidden subtree is silently ignored. So move focus in the\n  // commit that makes the panel visible, not when it mounts. A CSS transition\n  // on `visibility` can still hold the controls hidden for a moment after\n  // that commit (a reduced-motion reset that gives every element a short\n  // transition-duration does), so while focus rests on the panel or has not\n  // moved, each such transition that ends tries the candidates again, until\n  // the user presses a key or pointer. The effect runs once per open, so it\n  // reads the caller's props through refs: a new ref or callback passed\n  // mid-open must not tear down a pending retry.\n  const initialFocusRef = useRef(initialFocus);\n  const callerFocusesRef = useRef(onOpenAutoFocus !== undefined);\n  useLayoutEffect(() => {\n    initialFocusRef.current = initialFocus;\n    callerFocusesRef.current = onOpenAutoFocus !== undefined;\n  });\n  const { contentRef, takeFocusOnOpen } = ctx;\n  useLayoutEffect(() => {\n    if (!ready || !isPresent) return;\n    if (!takeFocusOnOpen() || callerFocusesRef.current) return;\n    const panel = contentRef.current;\n    const wrapper = panel?.parentElement;\n    if (!panel || !wrapper) return;\n    const from = document.activeElement;\n    const unmoved = () =>\n      document.activeElement === from || document.activeElement === panel;\n    // The selector also matches elements focus() refuses: a hidden input, a\n    // disabled button that carries a tabindex, anything under display: none.\n    // Keep the first candidate that takes focus, else hold it on the panel.\n    const focusFirst = () => {\n      const candidates = [\n        initialFocusRef.current?.current,\n        ...panel.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR),\n      ];\n      for (const candidate of candidates) {\n        if (!candidate) continue;\n        candidate.focus({ preventScroll: true });\n        if (unmoved()) continue;\n        // preventScroll keeps the page still, but it also stops the panel's\n        // own scroll area from bringing a row below the fold into view.\n        candidate.scrollIntoView?.({ block: \"nearest\" });\n        return true;\n      }\n      panel.focus({ preventScroll: true });\n      return false;\n    };\n    if (focusFirst()) return;\n    const retry = (event: TransitionEvent) => {\n      if (event.propertyName !== \"visibility\") return;\n      if (!unmoved() || focusFirst()) stop();\n    };\n    const stop = () => {\n      wrapper.removeEventListener(\"transitionend\", retry);\n      document.removeEventListener(\"keydown\", stop, true);\n      document.removeEventListener(\"pointerdown\", stop, true);\n    };\n    wrapper.addEventListener(\"transitionend\", retry);\n    document.addEventListener(\"keydown\", stop, true);\n    document.addEventListener(\"pointerdown\", stop, true);\n    return stop;\n  }, [ready, isPresent, contentRef, takeFocusOnOpen]);\n\n  return (\n    <motion.div\n      data-morph-popover-portal=\"\"\n      inert={!isPresent}\n      style={{\n        left,\n        top,\n        opacity: reduce ? fade : surfaceOpacity,\n        pointerEvents: isPresent ? \"auto\" : \"none\",\n        visibility: layout ? \"visible\" : \"hidden\",\n      }}\n      // A drop-shadow follows the clipped surface; box-shadow would be cut\n      // off by its own clip. Caller surface classes retain their old target.\n      className={cn(\n        \"fixed z-[9999]\",\n        shadow && \"[filter:drop-shadow(0_10px_18px_rgba(0,0,0,0.14))]\",\n      )}\n    >\n      <motion.div\n        ref={ctx.contentRef}\n        id={ctx.contentId}\n        role=\"dialog\"\n        aria-labelledby={ctx.triggerId}\n        tabIndex={-1}\n        style={{\n          clipPath: reduce ? undefined : clipPath,\n          borderRadius: radius,\n          maxHeight: layout ? availableHeight : undefined,\n          overflowX: \"hidden\",\n          overflowY: \"auto\",\n        }}\n        className={cn(\n          // The panel holds focus when nothing inside it can. An inset ring\n          // stays inside the clip that would cut off an outline.\n          \"border border-border bg-background outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring\",\n          className,\n        )}\n      >\n        {children}\n      </motion.div>\n    </motion.div>\n  );\n}\n"},{"path":"components/motion/select.tsx","type":"util","content":"\"use client\";\n\nimport { Check, ChevronDown } from \"lucide-react\";\nimport {\n  AnimatePresence,\n  animate,\n  type MotionValue,\n  motion,\n  useMotionValue,\n  useMotionValueEvent,\n  useReducedMotion,\n  useTransform,\n  type Variants,\n} from \"motion/react\";\nimport {\n  createContext,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { MENU_ITEM_CLASS, MenuItemHighlight } from \"@/components/motion/menu/menu-item-highlight\";\nimport { EASE_OUT } from \"@/lib/ease\";\nimport { type DismissReason, useDismiss } from \"@/lib/hooks/use-dismiss\";\nimport { type ListboxRow, useListbox } from \"@/lib/hooks/use-listbox\";\nimport { useSound } from \"@/lib/sound\";\nimport { closeSound } from \"@/lib/sounds/close\";\nimport { openSound } from \"@/lib/sounds/open\";\nimport { selectSound } from \"@/lib/sounds/select\";\nimport { cn } from \"@/lib/utils\";\n\n// One progress value drives the surface, gap, corners and chevron. This short\n// spring suits the full reveal distance; each reader clamps its small internal\n// overshoot, so all visible endpoints settle together. Rows share a short\n// reveal so long lists have no late entries.\nconst UNFOLD_SPRING = {\n  type: \"spring\",\n  visualDuration: 0.2,\n  bounce: 0.12,\n} as const;\n// Exits are faster than entrances: the panel folds back on a short ease.\nconst UNFOLD_EXIT = { duration: 0.15, ease: EASE_OUT } as const;\n// Opened or closed from the keyboard: no motion at all.\nconst INSTANT = { duration: 0 } as const;\n// The trigger's label rolls when the value changes: the old one rises out,\n// faster than the new one rises in, with a 2px blur that hides the overlap.\nconst LABEL_IN = { duration: 0.18, ease: EASE_OUT } as const;\nconst LABEL_OUT = { duration: 0.12, ease: EASE_OUT } as const;\n// The trigger is a pill (half its h-10 height). The panel is rounded-2xl, the\n// radius every floating list in the library uses.\nconst TRIGGER_RADIUS = 20;\nconst PANEL_RADIUS = 16;\n// How far the open panel sits from the trigger once it has pulled away.\nconst GAP = 8;\n// The surface starts as a thin lip flush against the trigger's edge.\nconst LIP = 8;\nconst lerp = (a: number, b: number, t: number) => a + (b - a) * t;\n\n// `custom` is the instant flag: rows of a list opened from the keyboard are\n// simply there, like the panel around them.\nconst ITEM_VARIANTS: Variants = {\n  // A shared short reveal keeps late rows in long, scrolled lists ready with\n  // the surface. Per-index staggering can delay visible rows by over a second.\n  hidden: (instant = false) => ({\n    opacity: 0,\n    y: -4,\n    transition: instant ? INSTANT : { duration: 0.08, ease: EASE_OUT },\n  }),\n  show: (instant = false) => ({\n    opacity: 1,\n    y: 0,\n    transition: instant ? INSTANT : { duration: 0.12, ease: EASE_OUT },\n  }),\n};\n\ntype Placement = \"bottom\" | \"top\";\n\ninterface SelectContextValue {\n  value: string | undefined;\n  open: boolean;\n  /** `instant` skips the unfold: the keyboard asked for it. */\n  setOpen: (open: boolean, quiet?: boolean, instant?: boolean) => void;\n  select: (value: string, instant?: boolean) => void;\n  register: (value: string, label: string, disabled: boolean) => void;\n  unregister: (value: string) => void;\n  labelFor: (value: string | undefined) => string | undefined;\n  rows: ListboxRow[];\n  /** Closes the panel; focus inside it returns to the trigger. */\n  close: (quiet?: boolean, instant?: boolean) => void;\n  /** Whether the latest open or close skips its animation. */\n  instant: boolean;\n  reduce: boolean;\n  progress: MotionValue<number>;\n  triggerId: string;\n  listId: string;\n  disabled: boolean;\n  placement: Placement;\n  setPlacement: (p: Placement) => void;\n}\n\nconst SelectContext = createContext<SelectContextValue | null>(null);\n// The active option (resolved during render by the content), whether its\n// highlight glides (after the pointer) or jumps (after a key), and how a\n// pointer resting on an option makes it the active one.\ninterface ActiveOption {\n  activeId: string | undefined;\n  glide: boolean;\n  setActive: (id: string) => void;\n}\nconst ActiveOptionContext = createContext<ActiveOption>({\n  activeId: undefined,\n  glide: true,\n  setActive: () => {},\n});\n\nfunction useSelectContext(component: string) {\n  const ctx = useContext(SelectContext);\n  if (!ctx) throw new Error(`${component} must be used within <Select>`);\n  return ctx;\n}\n\nexport interface SelectProps {\n  /** The selected value, for controlled use. */\n  value?: string;\n  /** The initial value when uncontrolled. */\n  defaultValue?: string;\n  /** Called with the new value when an option is picked. */\n  onValueChange?: (value: string) => void;\n  /**\n   * Controlled open state of the panel. A layout that stacks selects can hold\n   * this to keep exactly one panel open - the panel is absolutely positioned\n   * inside its field, so two open at once paint over each other's options.\n   */\n  open?: boolean;\n  /** Uncontrolled initial open state. Default false. */\n  defaultOpen?: boolean;\n  /**\n   * Fires whenever the panel opens or closes. The panel is absolutely\n   * positioned inside the field, so a layout that stacks selects has to know\n   * which one is open to paint it above its neighbours.\n   */\n  onOpenChange?: (open: boolean) => void;\n  /** Disables the trigger so the panel cannot open. Default: false */\n  disabled?: boolean;\n  /** Play open and close swishes and a select on a pick. Off by default; a `SoundProvider` can mute it app-wide. */\n  sound?: boolean;\n  /** Classes merged onto the root element. */\n  className?: string;\n  children: ReactNode;\n}\n\nexport function Select({\n  value,\n  defaultValue,\n  onValueChange,\n  open: openProp,\n  defaultOpen = false,\n  onOpenChange,\n  disabled = false,\n  sound = false,\n  className,\n  children,\n}: SelectProps) {\n  const reduce = useReducedMotion() ?? false;\n  const baseId = useId();\n  const rootRef = useRef<HTMLDivElement>(null);\n  const [internalOpen, setInternalOpen] = useState(defaultOpen);\n  const [internal, setInternal] = useState(defaultValue);\n  const [labels, setLabels] = useState<\n    Map<string, { label: string; disabled: boolean }>\n  >(new Map());\n  const [placement, setPlacement] = useState<Placement>(\"bottom\");\n  const [instant, setInstant] = useState(false);\n\n  const controlled = value !== undefined;\n  const current = controlled ? value : internal;\n  const openControlled = openProp !== undefined;\n  const open = openControlled ? openProp : internalOpen;\n  const progress = useMotionValue(open ? 1 : 0);\n\n  const playOpen = useSound(openSound, { enabled: sound });\n  const playClose = useSound(closeSound, { enabled: sound });\n  const playSelect = useSound(selectSound, { enabled: sound });\n\n  // `quiet` skips the close sweep when a pick already made its own sound.\n  const setOpen = useCallback(\n    (next: boolean, quiet = false, now = false) => {\n      if (next !== open) {\n        if (!quiet) {\n          if (next) playOpen();\n          else playClose();\n        }\n        setInstant(now);\n      }\n      if (!openControlled) setInternalOpen(next);\n      onOpenChange?.(next);\n    },\n    [onOpenChange, openControlled, open, playOpen, playClose],\n  );\n\n  // The panel turns inert as it closes, which would drop focus held inside it\n  // on the page body. Hand it back to the trigger before that happens.\n  const close = useCallback(\n    (quiet = false, now = false) => {\n      const trigger = document.getElementById(`${baseId}-trigger`);\n      if (\n        rootRef.current?.contains(document.activeElement) &&\n        document.activeElement !== trigger\n      )\n        trigger?.focus();\n      setOpen(false, quiet, now);\n    },\n    [baseId, setOpen],\n  );\n\n  const select = useCallback(\n    (next: string, now = false) => {\n      playSelect();\n      if (!controlled) setInternal(next);\n      onValueChange?.(next);\n      close(true, now);\n    },\n    [controlled, onValueChange, close, playSelect],\n  );\n\n  const register = useCallback((v: string, label: string, disabled: boolean) => {\n    setLabels((m) => {\n      const entry = m.get(v);\n      if (entry?.label === label && entry.disabled === disabled) return m;\n      return new Map(m).set(v, { label, disabled });\n    });\n  }, []);\n  const unregister = useCallback((v: string) => {\n    setLabels((m) => {\n      if (!m.has(v)) return m;\n      const next = new Map(m);\n      next.delete(v);\n      return next;\n    });\n  }, []);\n\n  // Reduced motion has no travel, so the progress only carries a short fade.\n  useEffect(() => {\n    const animation = animate(\n      progress,\n      open ? 1 : 0,\n      instant ? INSTANT : reduce ? { duration: 0.12 } : open ? UNFOLD_SPRING : UNFOLD_EXIT,\n    );\n    return () => animation.stop();\n  }, [open, progress, reduce, instant]);\n\n  // Escape hands focus back to the trigger and closes at once; an outside\n  // press leaves focus where the press put it and folds the panel away.\n  const dismiss = useCallback(\n    (reason: DismissReason) => (reason === \"escape\" ? close(false, true) : setOpen(false)),\n    [close, setOpen],\n  );\n  useDismiss(open, dismiss, rootRef);\n\n  const rows = useMemo(\n    () =>\n      Array.from(labels, ([id, entry]) => ({\n        id,\n        label: entry.label,\n        disabled: entry.disabled,\n      })),\n    [labels],\n  );\n\n  const ctx = useMemo<SelectContextValue>(\n    () => ({\n      value: current,\n      open,\n      setOpen,\n      select,\n      register,\n      unregister,\n      labelFor: (v) => (v === undefined ? undefined : labels.get(v)?.label),\n      rows,\n      close,\n      instant,\n      reduce,\n      progress,\n      triggerId: `${baseId}-trigger`,\n      listId: `${baseId}-list`,\n      disabled,\n      placement,\n      setPlacement,\n    }),\n    [\n      current,\n      open,\n      setOpen,\n      select,\n      register,\n      unregister,\n      labels,\n      rows,\n      close,\n      instant,\n      reduce,\n      progress,\n      baseId,\n      disabled,\n      placement,\n    ],\n  );\n\n  return (\n    <SelectContext.Provider value={ctx}>\n      <div ref={rootRef} className={cn(\"relative\", className)}>\n        {children}\n      </div>\n    </SelectContext.Provider>\n  );\n}\n\nexport interface SelectTriggerProps {\n  /** Classes merged onto the trigger button. */\n  className?: string;\n  children: ReactNode;\n}\n\nexport function SelectTrigger({ className, children }: SelectTriggerProps) {\n  const ctx = useSelectContext(\"SelectTrigger\");\n  const isTop = ctx.placement === \"top\";\n  // The edge facing the panel flattens while the panel is attached to it and\n  // rounds back as the panel pulls away - the two pinch apart - on the same\n  // curve the panel moves on. The far edge stays rounded.\n  const nearRadius = useTransform(\n    ctx.progress,\n    [0, 0.2, 0.4, 1],\n    [TRIGGER_RADIUS, 0, 0, TRIGGER_RADIUS],\n  );\n  const rotate = useTransform(ctx.progress, (p) =>\n    ctx.reduce ? (ctx.open ? 180 : 0) : Math.min(1, Math.max(0, p)) * 180,\n  );\n  return (\n    <motion.button\n      type=\"button\"\n      id={ctx.triggerId}\n      disabled={ctx.disabled}\n      aria-haspopup=\"listbox\"\n      aria-expanded={ctx.open}\n      aria-controls={ctx.listId}\n      // `detail` is 0 for a click the keyboard made (Enter, Space): no unfold.\n      onClick={(event) => ctx.setOpen(!ctx.open, false, event.detail === 0)}\n      onKeyDown={(event) => {\n        if (\n          !ctx.open &&\n          (event.key === \"ArrowDown\" || event.key === \"ArrowUp\")\n        ) {\n          event.preventDefault();\n          ctx.setOpen(true, false, true);\n        }\n      }}\n      style={{\n        borderTopLeftRadius: ctx.reduce || !isTop ? TRIGGER_RADIUS : nearRadius,\n        borderTopRightRadius: ctx.reduce || !isTop ? TRIGGER_RADIUS : nearRadius,\n        borderBottomLeftRadius: ctx.reduce || isTop ? TRIGGER_RADIUS : nearRadius,\n        borderBottomRightRadius: ctx.reduce || isTop ? TRIGGER_RADIUS : nearRadius,\n      }}\n      className={cn(\n        \"relative z-10 flex h-10 w-full items-center justify-between gap-2 border border-border bg-background px-4 text-sm text-foreground outline-none transition-colors\",\n        \"hover:border-(--color-border-strong) focus-visible:ring-2 focus-visible:ring-foreground/20\",\n        \"disabled:pointer-events-none disabled:opacity-50\",\n        className,\n      )}\n    >\n      {children}\n      <motion.span\n        aria-hidden\n        style={{ rotate }}\n        className=\"text-muted-foreground\"\n      >\n        <ChevronDown className=\"h-4 w-4\" />\n      </motion.span>\n    </motion.button>\n  );\n}\n\nexport interface SelectValueProps {\n  /** Text shown while nothing is selected. Default: \"Select\" */\n  placeholder?: string;\n  /** Classes merged onto the label wrapper. */\n  className?: string;\n}\n\nexport function SelectValue({ placeholder, className }: SelectValueProps) {\n  const ctx = useSelectContext(\"SelectValue\");\n  const label = ctx.labelFor(ctx.value);\n  const text = label ?? placeholder ?? \"Select\";\n  // A pick from the keyboard swaps the label at once; reduced motion keeps a\n  // short crossfade without the travel.\n  const still = ctx.instant || ctx.reduce;\n  const swap = ctx.instant ? INSTANT : ctx.reduce ? { duration: 0.12 } : LABEL_IN;\n  return (\n    // Both labels share one grid cell, so the outgoing one never takes space\n    // or moves the chevron, and both truncate the same way.\n    <span className={cn(\"grid min-w-0 flex-1 overflow-hidden text-left\", className)}>\n      <AnimatePresence initial={false}>\n        <motion.span\n          key={text}\n          initial={still ? { opacity: 0 } : { opacity: 0, y: \"70%\", filter: \"blur(2px)\" }}\n          animate={{ opacity: 1, y: \"0%\", filter: \"blur(0px)\" }}\n          exit={\n            still\n              ? { opacity: 0, transition: swap }\n              : { opacity: 0, y: \"-70%\", filter: \"blur(2px)\", transition: LABEL_OUT }\n          }\n          transition={swap}\n          className={cn(\n            \"col-start-1 row-start-1 block truncate\",\n            label ? \"text-foreground\" : \"text-muted-foreground\",\n          )}\n        >\n          {text}\n        </motion.span>\n      </AnimatePresence>\n    </span>\n  );\n}\n\nexport interface SelectContentProps {\n  /** Classes merged onto the options panel. */\n  className?: string;\n  children: ReactNode;\n}\n\nexport function SelectContent({ className, children }: SelectContentProps) {\n  const ctx = useSelectContext(\"SelectContent\");\n  const panelRef = useRef<HTMLDivElement>(null);\n  const [height, setHeight] = useState(0);\n  const { open, progress, reduce, setPlacement } = ctx;\n  const { activeId, onKeyDown, moveTo } = useListbox({\n    open,\n    rows: ctx.rows,\n    selected: ctx.value,\n    list: panelRef,\n  });\n  const [glide, setGlide] = useState(true);\n  const active = useMemo<ActiveOption>(\n    () => ({ activeId, glide, setActive: moveTo }),\n    [activeId, glide, moveTo],\n  );\n\n  // Keep descendants laid out while hidden: display:none resets nested\n  // scrollers in Chromium. Collapse only the hidden outer footprint after\n  // exit so it cannot extend page scrolling. Opening restores the full box\n  // before measurement or focus; neither layout change is animated.\n  const [exiting, setExiting] = useState(false);\n  const [wasOpen, setWasOpen] = useState(open);\n  if (open !== wasOpen) {\n    setWasOpen(open);\n    if (!open) setExiting(true);\n  }\n  const present = open || exiting;\n  useMotionValueEvent(progress, \"animationComplete\", () => {\n    if (progress.get() === 0) setExiting(false);\n  });\n\n  useLayoutEffect(() => {\n    const node = panelRef.current;\n    if (!node || !present) return;\n    const measure = () => setHeight(node.offsetHeight);\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(node);\n    return () => observer.disconnect();\n  }, [present]);\n\n  // On open, flip upward when there isn't room below and there's more above.\n  useLayoutEffect(() => {\n    if (!open) return;\n    const trigger = document.getElementById(ctx.triggerId);\n    const node = panelRef.current;\n    if (!trigger || !node) return;\n    const rect = trigger.getBoundingClientRect();\n    const h = node.offsetHeight;\n    const below = window.innerHeight - rect.bottom;\n    const above = rect.top;\n    setPlacement(below < h + 16 && above > below ? \"top\" : \"bottom\");\n  }, [open, ctx.triggerId, setPlacement]);\n\n  const isTop = ctx.placement === \"top\";\n\n  // Reveal a full-size panel from its near edge. No ancestor scales the list,\n  // so rows, borders and shadow keep their natural thickness. The clip and\n  // corner writes can paint; only the gap uses a transform. All read one\n  // progress value, with no animated layout properties.\n  const ready = height > 0 && !reduce;\n  const fromY = ready ? (isTop ? GAP : -GAP) : 0;\n  const detach = useTransform(progress, [0.4, 1], [0, 1]);\n  const y = useTransform(detach, (d) => lerp(fromY, 0, d));\n  const nearRadius = useTransform(detach, (d) => (ready ? PANEL_RADIUS * d : PANEL_RADIUS));\n  const borderRadius = useTransform(nearRadius, (near) =>\n    isTop\n      ? `${PANEL_RADIUS}px ${PANEL_RADIUS}px ${near}px ${near}px`\n      : `${near}px ${near}px ${PANEL_RADIUS}px ${PANEL_RADIUS}px`,\n  );\n  const clipPath = useTransform([progress, nearRadius], ([p, near]: number[]) => {\n    if (!ready) return \"none\";\n    // Clamp overshoot so the clip never extends into the trigger or exposes\n    // overflowing children. At rest remove it so the native shadow is whole.\n    const reveal = Math.min(1, Math.max(0, p));\n    if (reveal === 1) return \"none\";\n    const hidden = Math.max(0, (height - LIP) * (1 - reveal));\n    const inset = isTop ? `${hidden}px 0 0 0` : `0 0 ${hidden}px 0`;\n    const corners = isTop\n      ? `${PANEL_RADIUS}px ${PANEL_RADIUS}px ${near}px ${near}px`\n      : `${near}px ${near}px ${PANEL_RADIUS}px ${PANEL_RADIUS}px`;\n    return `inset(${inset} round ${corners})`;\n  });\n  // The surface materialises over its first frames rather than popping in as\n  // a lip; with reduced motion the fade is the whole entrance.\n  const opacity = useTransform(progress, reduce ? [0, 1] : [0, 0.12], [0, 1]);\n\n  return (\n    <motion.div\n      ref={panelRef}\n      id={ctx.listId}\n      role=\"listbox\"\n      aria-labelledby={ctx.triggerId}\n      aria-hidden={!open}\n      inert={!open}\n      onKeyDown={(event) => {\n        // Set before the key moves the active option, so its highlight jumps.\n        setGlide(false);\n        // Tab leaves the list from the trigger, so focus moves on to the\n        // control after the select rather than into the closing panel.\n        if (event.key === \"Tab\") ctx.close(false, true);\n        else onKeyDown(event);\n      }}\n      onPointerMove={(event) => {\n        if (event.pointerType !== \"touch\") setGlide(true);\n      }}\n      style={{\n        visibility: present ? undefined : \"hidden\",\n        maxHeight: present ? undefined : 0,\n        borderWidth: present ? undefined : 0,\n        y,\n        clipPath,\n        borderRadius,\n        opacity,\n        pointerEvents: open ? \"auto\" : \"none\",\n        marginTop: isTop ? 0 : GAP,\n        marginBottom: isTop ? GAP : 0,\n      }}\n      // flush against the trigger, then separates into its own rounded pill;\n      // sits above or below depending on available space\n      className={cn(\n        // The same soft shadow as the menus, so floating lists read as one family.\n        \"absolute left-0 right-0 z-20 overflow-hidden border border-border bg-background shadow-[0_8px_24px_-8px_rgb(0_0_0/0.16)]\",\n        isTop ? \"bottom-full\" : \"top-full\",\n        className,\n      )}\n    >\n      <ActiveOptionContext.Provider value={active}>\n        <motion.div\n          initial={false}\n          animate={open ? \"show\" : \"hidden\"}\n          className=\"p-2\"\n        >\n          {children}\n        </motion.div>\n      </ActiveOptionContext.Provider>\n    </motion.div>\n  );\n}\n\nexport interface SelectItemProps {\n  /** Value reported when this option is picked. */\n  value: string;\n  /** Prevents picking this option. Default: false */\n  disabled?: boolean;\n  /** Classes merged onto the option button. */\n  className?: string;\n  children: ReactNode;\n}\n\nexport function SelectItem({\n  value,\n  disabled = false,\n  className,\n  children,\n}: SelectItemProps) {\n  const ctx = useSelectContext(\"SelectItem\");\n  const { activeId, glide, setActive } = useContext(ActiveOptionContext);\n  const selected = ctx.value === value;\n  const active = activeId === value;\n  const label = typeof children === \"string\" ? children : value;\n\n  useLayoutEffect(() => {\n    ctx.register(value, label, disabled);\n  }, [ctx.register, value, label, disabled]);\n  useLayoutEffect(() => () => ctx.unregister(value), [ctx.unregister, value]);\n\n  return (\n    <motion.div custom={ctx.instant} variants={ctx.reduce ? undefined : ITEM_VARIANTS}>\n      <button\n        type=\"button\"\n        role=\"option\"\n        aria-selected={selected}\n        disabled={disabled}\n        // One tab stop: the active option, which focus follows while open.\n        tabIndex={active ? 0 : -1}\n        data-listbox-id={value}\n        // A resting pointer makes this the active option, so the highlight\n        // follows the mouse the same way it follows the arrow keys.\n        onPointerMove={(event) => {\n          if (event.pointerType !== \"touch\" && !disabled && !active) setActive(value);\n        }}\n        // Enter or Space on the option (`detail` 0) closes without folding.\n        onClick={(event) => ctx.select(value, event.detail === 0)}\n        className={cn(\n          MENU_ITEM_CLASS,\n          \"justify-between gap-2 text-foreground\",\n          \"disabled:pointer-events-none disabled:opacity-50\",\n          className,\n        )}\n      >\n        {/* One highlight for the whole list: it glides after the pointer and\n            jumps after a key. The selected option is marked by its check. */}\n        {active && !disabled ? (\n          <MenuItemHighlight\n            layoutId={`${ctx.listId}-highlight`}\n            reduce={ctx.reduce}\n            instant={!glide}\n          />\n        ) : null}\n        <span className=\"flex min-w-0 flex-1 items-center gap-2\">{children}</span>\n        {selected ? <Check aria-hidden=\"true\" className=\"h-3.5 w-3.5 shrink-0\" /> : null}\n      </button>\n    </motion.div>\n  );\n}\n"},{"path":"lib/sound.tsx","type":"util","content":"\"use client\";\n\nimport {\n  createContext,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useEffect,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n} from \"react\";\nimport {\n  registerSoundSettings,\n  retainAudioContext,\n  type SoundSettingsEntry,\n} from \"@/lib/audio-context\";\nimport type { PlayOptions, Sound } from \"@/lib/sounds/engine\";\n\nexport interface SoundSettings {\n  /** False mutes every beUI sound under the provider. */\n  enabled: boolean;\n  /** 0 to 1, scales every beUI sound. */\n  volume: number;\n}\n\nconst SoundContext = createContext<SoundSettings & { depth: number }>({\n  enabled: true,\n  volume: 1,\n  depth: 0,\n});\n\n/**\n * App-wide sound settings. `enabled={false}` mutes every beUI sound, from\n * component `sound` props and `useSound` to the games, Wheel Picker and\n * Bookshelf, and `volume` scales them all. Without a provider, sounds play at\n * full volume. A nested provider overrides the one around it.\n */\nexport function SoundProvider({\n  enabled = true,\n  volume = 1,\n  children,\n}: Partial<SoundSettings> & { children: ReactNode }) {\n  const depth = useContext(SoundContext).depth + 1;\n  const value = useMemo(() => ({ enabled, volume, depth }), [enabled, volume, depth]);\n\n  // Module-level as well (lib/audio-context.ts), so players outside React\n  // and `sound.play()` obey it too.\n  const entry = useRef<SoundSettingsEntry>({ depth, enabled, volume });\n  const registration = useRef<ReturnType<typeof registerSoundSettings> | null>(null);\n  useEffect(() => {\n    registration.current = registerSoundSettings(entry.current);\n    return () => {\n      registration.current?.release();\n      registration.current = null;\n    };\n  }, []);\n  useEffect(() => {\n    Object.assign(entry.current, { depth, enabled, volume });\n    registration.current?.update();\n  }, [depth, enabled, volume]);\n\n  return <SoundContext.Provider value={value}>{children}</SoundContext.Provider>;\n}\n\nexport function useSoundSettings(): SoundSettings {\n  return useContext(SoundContext);\n}\n\nexport interface UseSoundOptions {\n  /** False makes `play` do nothing, for a component's `sound` prop. */\n  enabled?: boolean;\n  /** 0 to 1 for this sound, on top of the provider volume. */\n  volume?: number;\n}\n\n/**\n * A stable `play()` for one sound. It does nothing while disabled or muted,\n * and keeps the shared audio context warm only while it can play.\n */\nexport function useSound(sound: Sound, { enabled = true, volume = 1 }: UseSoundOptions = {}) {\n  const settings = useSoundSettings();\n  const on = enabled && settings.enabled && settings.volume > 0 && volume > 0;\n  // Read by the stable callback, so a caller's effects don't re-run when\n  // the settings change.\n  const latest = useRef({ on, volume, sound });\n  useLayoutEffect(() => {\n    latest.current = { on, volume, sound };\n  });\n\n  useEffect(() => {\n    if (!on) return;\n    return retainAudioContext();\n  }, [on]);\n\n  return useCallback((options?: PlayOptions) => {\n    const current = latest.current;\n    if (!current.on) return;\n    current.sound.play({ ...options, volume: (options?.volume ?? 1) * current.volume });\n  }, []);\n}\n"},{"path":"lib/sounds/toggle.ts","type":"util","content":"import { defineSound } from \"./engine\";\n\n// A real switch clicks twice: a light pre-click as it starts to travel, then\n// the snap as it lands. On goes low to high and lands on a higher body; off\n// is the mirror, so the two are easy to tell apart.\n\n/** A two-stage snap rising into place, for switching something on. */\nexport const toggleOnSound = defineSound({\n  name: \"Toggle on\",\n  duration: 0.1,\n  room: 0.1,\n  build: (v) => {\n    v.click({ freq: 2000, q: 1.5, decay: 0.004, gain: 0.22 });\n    v.click({ freq: 3800, q: 2, at: 0.024, decay: 0.005, gain: 0.5 });\n    v.strike({ freq: 980, material: \"plastic\", bend: 1.05, at: 0.024, decay: 0.045, gain: 0.5 });\n    v.strike({ freq: 190, material: \"wood\", bend: 1.3, at: 0.024, decay: 0.03, gain: 0.35 });\n  },\n});\n\n/** The same snap falling into place, for switching something off. */\nexport const toggleOffSound = defineSound({\n  name: \"Toggle off\",\n  duration: 0.1,\n  room: 0.1,\n  build: (v) => {\n    v.click({ freq: 3800, q: 2, decay: 0.004, gain: 0.22 });\n    v.click({ freq: 2000, q: 1.5, at: 0.024, decay: 0.005, gain: 0.5 });\n    v.strike({ freq: 640, material: \"plastic\", bend: 1.05, at: 0.024, decay: 0.045, gain: 0.5 });\n    v.strike({ freq: 160, material: \"wood\", bend: 1.3, at: 0.024, decay: 0.03, gain: 0.35 });\n  },\n});\n"},{"path":"components/motion/tooltip/grace.ts","type":"util","content":"type Point = { x: number; y: number };\ntype Box = { left: number; top: number; right: number; bottom: number };\n\n/**\n * The corridor a pointer may cross between the trigger and the open tooltip\n * without closing it: the convex hull of where it left and the box it is\n * heading for. A fixed timeout either cuts a slow diagonal move short or keeps\n * the label alive after the pointer has plainly gone elsewhere; this follows\n * the path itself.\n */\nexport function graceArea(exit: Point, target: Box): Point[] {\n  // A few pixels either side of the exit point give the corridor some width at\n  // its narrow end, so a hand that drifts sideways while it moves stays inside.\n  const pad = 5;\n  return hull([\n    { x: exit.x - pad, y: exit.y - pad },\n    { x: exit.x + pad, y: exit.y - pad },\n    { x: exit.x - pad, y: exit.y + pad },\n    { x: exit.x + pad, y: exit.y + pad },\n    { x: target.left, y: target.top },\n    { x: target.right, y: target.top },\n    { x: target.right, y: target.bottom },\n    { x: target.left, y: target.bottom },\n  ]);\n}\n\nexport function inBox(point: Point, box: Box) {\n  return (\n    point.x >= box.left && point.x <= box.right && point.y >= box.top && point.y <= box.bottom\n  );\n}\n\nexport function inPolygon(point: Point, polygon: Point[]) {\n  let inside = false;\n  for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {\n    const a = polygon[i];\n    const b = polygon[j];\n    if (\n      a.y > point.y !== b.y > point.y &&\n      point.x < ((b.x - a.x) * (point.y - a.y)) / (b.y - a.y) + a.x\n    ) {\n      inside = !inside;\n    }\n  }\n  return inside;\n}\n\n// Monotone chain; the corridor is always convex, so a hull is all it needs.\nfunction hull(points: Point[]) {\n  const sorted = [...points].sort((a, b) => a.x - b.x || a.y - b.y);\n  const cross = (o: Point, a: Point, b: Point) =>\n    (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);\n  const lower: Point[] = [];\n  for (const p of sorted) {\n    while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], p) <= 0) {\n      lower.pop();\n    }\n    lower.push(p);\n  }\n  const upper: Point[] = [];\n  for (let i = sorted.length - 1; i >= 0; i--) {\n    const p = sorted[i];\n    while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], p) <= 0) {\n      upper.pop();\n    }\n    upper.push(p);\n  }\n  lower.pop();\n  upper.pop();\n  return lower.concat(upper);\n}\n\n/**\n * How the user last reached for the page. A focus that a mouse press caused is\n * not a request to read the label: the pointer is already on the control and\n * hovering showed it. A focus that followed a key - Tab, or a roving arrow key\n * moving focus in script - is the only way a keyboard user sees it at all.\n */\nlet modality: \"keyboard\" | \"pointer\" = \"keyboard\";\nlet listening = false;\n\nexport function watchModality() {\n  if (listening || typeof window === \"undefined\") return;\n  listening = true;\n  window.addEventListener(\"keydown\", () => (modality = \"keyboard\"), true);\n  window.addEventListener(\"pointerdown\", () => (modality = \"pointer\"), true);\n}\n\nexport function focusFromKeyboard() {\n  return modality === \"keyboard\";\n}\n"},{"path":"components/motion/tooltip/positioner.tsx","type":"util","content":"\"use client\";\n\nimport { useIsPresent } from \"motion/react\";\nimport { type CSSProperties, type ReactNode, type Ref, useCallback, useState } from \"react\";\nimport { type TooltipSide, useTooltipPosition } from \"./use-position\";\n\ntype PositionProps = Parameters<typeof useTooltipPosition>[0];\n\n/** Readiness lives with the mounted overlay, not a trigger ref's attach/detach cycle. */\nexport function TooltipPositioner({\n  children,\n  ...position\n}: Omit<PositionProps, \"open\" | \"onPosition\"> & {\n  children: (ready: boolean, present: boolean, side: TooltipSide) => ReactNode;\n}) {\n  const present = useIsPresent();\n  const [ready, setReady] = useState(false);\n  const [side, setSide] = useState<TooltipSide>(position.side);\n  const onPosition = useCallback((placed: TooltipSide) => {\n    setReady(true);\n    setSide(placed);\n  }, []);\n  useTooltipPosition({ ...position, open: present, onPosition });\n  return (\n    <span\n      ref={position.floatingRef}\n      inert={!present}\n      aria-hidden={!present || undefined}\n      className=\"pointer-events-none fixed left-0 top-0 z-[9999] w-max\"\n      style={{ visibility: \"hidden\", maxWidth: \"calc(100vw - 16px)\" }}\n    >\n      {children(ready, present, side)}\n    </span>\n  );\n}\n\n// Each arrow is a 12px box whose base sits on the surface's inner border edge,\n// so its fill covers the border beneath it and only the two outer edges stroke.\nconst ARROW: Record<TooltipSide, { path: string; style: CSSProperties }> = {\n  top: { path: \"M0 6L6 12L12 6\", style: { top: \"calc(100% - 6px)\" } },\n  bottom: { path: \"M0 6L6 0L12 6\", style: { bottom: \"calc(100% - 6px)\" } },\n  left: { path: \"M6 0L12 6L6 12\", style: { left: \"calc(100% - 6px)\" } },\n  right: { path: \"M6 0L0 6L6 12\", style: { right: \"calc(100% - 6px)\" } },\n};\n\nexport function TooltipArrow({ side, ref }: { side: TooltipSide; ref: Ref<SVGSVGElement> }) {\n  const { path, style } = ARROW[side];\n  return (\n    <svg\n      ref={ref}\n      aria-hidden=\"true\"\n      width=\"12\"\n      height=\"12\"\n      viewBox=\"0 0 12 12\"\n      className=\"pointer-events-none absolute overflow-visible\"\n      style={style}\n    >\n      {/* Redrawn to fit the surface's edge once placed (see arrowShape). */}\n      <path data-arrow-fill=\"\" d={`${path}Z`} style={{ fill: \"var(--tooltip-arrow-fill, transparent)\" }} />\n      <path\n        data-arrow-stroke=\"\"\n        d={path}\n        fill=\"none\"\n        strokeWidth=\"1\"\n        style={{ stroke: \"var(--tooltip-arrow-stroke, transparent)\" }}\n      />\n    </svg>\n  );\n}\n"},{"path":"components/motion/tooltip/use-position.ts","type":"util","content":"\"use client\";\n\nimport {\n  arrow as arrowMiddleware,\n  autoUpdate,\n  computePosition,\n  flip,\n  hide,\n  offset,\n  type Placement,\n  shift,\n  type VirtualElement,\n} from \"@floating-ui/dom\";\nimport { type RefObject, useCallback, useLayoutEffect, useMemo, useRef } from \"react\";\n\nexport type TooltipSide = \"top\" | \"right\" | \"bottom\" | \"left\";\nexport type TooltipAlign = \"start\" | \"center\" | \"end\";\nexport type TooltipPoint = {\n  /** Horizontal position; for `anchorPoint`, a 0 to 1 fraction of the anchor's width. */\n  x: number;\n  /** Vertical position; for `anchorPoint`, a 0 to 1 fraction of the anchor's height. */\n  y: number;\n};\nexport type TooltipAnchor = HTMLElement | SVGElement;\n\nconst ORIGIN: Record<TooltipSide, string> = {\n  top: \"center bottom\",\n  bottom: \"center top\",\n  left: \"right center\",\n  right: \"left center\",\n};\n\n/** `top` painted over `bottom`, as one opaque colour. Falls back to `top`. */\nfunction blend(top: string, bottom: string) {\n  const context = document.createElement(\"canvas\").getContext(\"2d\", { willReadFrequently: true });\n  if (!context) return top;\n  context.fillStyle = bottom;\n  context.fillRect(0, 0, 1, 1);\n  context.fillStyle = top;\n  context.fillRect(0, 0, 1, 1);\n  const [r, g, b, a] = context.getImageData(0, 0, 1, 1).data;\n  // A see-through background has nothing solid to blend onto.\n  return a === 255 ? `rgb(${r}, ${g}, ${b})` : top;\n}\n\n/** The arrow element's box, which the arrow middleware centres along the edge. */\nconst ARROW_SIZE = 12;\n/** How far the tip reaches past the border's inner edge. */\nconst ARROW_REACH = 6;\n\n/**\n * How far a rounded edge has curved in from its straight line at `position`\n * along an edge of `length`, with corners of `radius`. Zero on the straight\n * stretch between the corners.\n */\nfunction curveDepth(position: number, length: number, radius: number) {\n  const offset =\n    position < radius ? radius - position : position > length - radius ? position - (length - radius) : 0;\n  if (offset <= 0) return 0;\n  return radius - Math.sqrt(Math.max(radius * radius - offset * offset, 0));\n}\n\n/**\n * The arrow's two paths, in the surface's border-box coordinates. Each 45°\n * side runs from the tip until it meets the middle of the surface's border,\n * wherever that is: on a straight stretch, or partway round a pill's curved\n * end. The stroke covers only those two sides, so the border flows straight\n * into them. The fill closes a little inside the surface, hiding the stretch\n * of border the arrow sits on.\n */\nfunction arrowShape({\n  side,\n  center,\n  width,\n  height,\n  radius,\n  border,\n}: {\n  side: TooltipSide;\n  center: number;\n  width: number;\n  height: number;\n  radius: number;\n  border: number;\n}) {\n  const vertical = side === \"top\" || side === \"bottom\";\n  const length = vertical ? width : height;\n  // Work on one edge: `depth` runs inward from the edge's outer line, `along` runs down it.\n  const tip = { depth: border - ARROW_REACH, along: center };\n  // The border's centre line: the stroke meets it there, so the two line up.\n  const line = border / 2;\n  // Both sides follow the same rule, so an arrow a pixel off-centre stays symmetric.\n  const curved =\n    curveDepth(center - ARROW_SIZE / 2, length, radius) > 0 ||\n    curveDepth(center + ARROW_SIZE / 2, length, radius) > 0;\n  const meet = (direction: -1 | 1) => {\n    // On a straight stretch the 45° side meets the border directly.\n    if (!curved) {\n      for (let t = 0; t <= ARROW_SIZE; t += 0.05) {\n        const along = center + direction * t;\n        const depth = tip.depth + t;\n        if (depth >= line) return { depth, along };\n      }\n    }\n    // On a pill's round end a 45° side passes outside the curve, or meets it\n    // at a kink. Run the side tangent to the curve instead, so the border\n    // flows into it without a corner.\n    const curve = radius - line;\n    const centre = { depth: radius, along: direction < 0 ? radius : length - radius };\n    const dx = tip.depth - centre.depth;\n    const dy = tip.along - centre.along;\n    const distance = Math.hypot(dx, dy);\n    if (distance <= curve) return { depth: line, along: center + direction * ARROW_REACH };\n    const base = Math.atan2(dy, dx);\n    const spread = Math.acos(curve / distance);\n    const candidates = [base + spread, base - spread].map((angle) => ({\n      depth: centre.depth + curve * Math.cos(angle),\n      along: centre.along + curve * Math.sin(angle),\n    }));\n    // The tangent on this side of the tip.\n    return direction < 0\n      ? candidates[0].along < candidates[1].along\n        ? candidates[0]\n        : candidates[1]\n      : candidates[0].along > candidates[1].along\n        ? candidates[0]\n        : candidates[1];\n  };\n  const start = meet(-1);\n  const end = meet(1);\n  const inside = Math.max(start.depth, end.depth) + border + 1;\n  const point = ({ depth, along }: { depth: number; along: number }) => {\n    const [x, y] =\n      side === \"right\"\n        ? [depth, along]\n        : side === \"left\"\n          ? [width - depth, along]\n          : side === \"bottom\"\n            ? [along, depth]\n            : [along, height - depth];\n    return `${x.toFixed(2)} ${y.toFixed(2)}`;\n  };\n  return {\n    fill: `M${point(tip)}L${point(start)}L${point({ depth: inside, along: start.along })}L${point({ depth: inside, along: end.along })}L${point(end)}Z`,\n    stroke: `M${point(start)}L${point(tip)}L${point(end)}`,\n  };\n}\n\n/** Position is geometry, not animation. One write per frame, never a spring chasing a pointer. */\nexport function useTooltipPosition({\n  open,\n  anchor,\n  floatingRef,\n  arrowRef,\n  anchorPoint,\n  followCursor,\n  side,\n  align,\n  sideOffset,\n  onDismiss,\n  onPosition,\n  pointer,\n}: {\n  open: boolean;\n  anchor: TooltipAnchor | null;\n  floatingRef: RefObject<HTMLSpanElement | null>;\n  arrowRef?: RefObject<SVGSVGElement | null>;\n  anchorPoint?: TooltipPoint;\n  followCursor: boolean;\n  side: TooltipSide;\n  align: TooltipAlign;\n  sideOffset?: number;\n  onDismiss: () => void;\n  onPosition: (side: TooltipSide) => void;\n  pointer: ReturnType<typeof useTooltipPointer>;\n}) {\n  const { cursor, onMove } = pointer;\n  const preferred: Placement = align === \"center\" ? side : `${side}-${align}`;\n  const cursorSide = useRef<Placement | null>(null);\n  useLayoutEffect(() => {\n    cursorSide.current = open ? preferred : null;\n  }, [open, preferred]);\n  const frame = useRef<number | null>(null);\n  const version = useRef(0);\n  const update = useRef<() => void>(() => {});\n  const schedule = useCallback(() => {\n    // Invalidate older async calculations as soon as new geometry is requested.\n    version.current++;\n    if (frame.current !== null) return;\n    frame.current = requestAnimationFrame(() => {\n      frame.current = null;\n      update.current();\n    });\n  }, []);\n  useLayoutEffect(() => {\n    onMove.current = schedule;\n    return () => {\n      onMove.current = null;\n    };\n  }, [onMove, schedule]);\n  const pointX = anchorPoint?.x;\n  const pointY = anchorPoint?.y;\n\n  // Latest committed inputs are read without recreating observers for every period/content update.\n  useLayoutEffect(() => {\n    update.current = () => {\n      const floating = floatingRef.current;\n      if (!open || !anchor || !floating) return;\n      const revision = ++version.current;\n      const currentCursor = followCursor ? cursor.current : null;\n      const virtual = Boolean(currentCursor) || pointX !== undefined || pointY !== undefined;\n      const reference: Element | VirtualElement = virtual\n        ? {\n            contextElement: anchor,\n            getBoundingClientRect: () => {\n              const rect = anchor.getBoundingClientRect();\n              const x = currentCursor?.x ?? rect.left + rect.width * (pointX ?? 0.5);\n              const y = currentCursor?.y ?? rect.top + rect.height * (pointY ?? 0.5);\n              return { x, y, left: x, right: x, top: y, bottom: y, width: 0, height: 0 };\n            },\n          }\n        : anchor;\n      const arrowElement = arrowRef?.current ?? null;\n      void computePosition(reference, floating, {\n        strategy: \"fixed\",\n        placement: currentCursor ? (cursorSide.current ?? preferred) : preferred,\n        middleware: [\n          offset(sideOffset ?? (currentCursor ? 12 : 8)),\n          flip({ padding: 8 }),\n          shift({ padding: 8 }),\n          ...(arrowElement ? [arrowMiddleware({ element: arrowElement, padding: 10 })] : []),\n          // A label left floating over whatever scrolled into its trigger's place\n          // describes nothing there. Points inside a chart move with the chart.\n          ...(virtual ? [] : [hide({ strategy: \"referenceHidden\" })]),\n        ],\n      }).then(({ x, y, placement, middlewareData }) => {\n        if (version.current !== revision || !floating.isConnected) return;\n        // Hold the chosen side for this hover session. Crossing a flip threshold\n        // repeatedly must not bounce the surface above and below the pointer.\n        if (currentCursor) cursorSide.current = placement;\n        else cursorSide.current = null;\n        const placedSide = placement.split(\"-\")[0] as TooltipSide;\n        const dpr = window.devicePixelRatio || 1;\n        floating.style.transform = `translate3d(${Math.round(x * dpr) / dpr}px, ${Math.round(y * dpr) / dpr}px, 0)`;\n        floating.style.setProperty(\"--tooltip-origin\", ORIGIN[placedSide]);\n        // A box with no size has no clipped state to report, only a missing layout.\n        const box = anchor.getBoundingClientRect();\n        const clipped =\n          Boolean(middlewareData.hide?.referenceHidden) && (box.width > 0 || box.height > 0);\n        floating.style.visibility = clipped ? \"hidden\" : \"visible\";\n        floating.dataset.placement = placement;\n        const surface = arrowElement?.parentElement;\n        if (arrowElement && surface) {\n          // The middleware centres the 12px arrow box along the edge; its\n          // centre is where the tip points. The paths are drawn in the\n          // surface's border-box coordinates, so the svg sits at its corner.\n          const { x: ax, y: ay } = middlewareData.arrow ?? {};\n          const vertical = placedSide === \"top\" || placedSide === \"bottom\";\n          const width = surface.offsetWidth;\n          const height = surface.offsetHeight;\n          const along = (vertical ? ax : ay) ?? ((vertical ? width : height) - ARROW_SIZE) / 2;\n          const style = getComputedStyle(surface);\n          const shape = arrowShape({\n            side: placedSide,\n            center: along + ARROW_SIZE / 2,\n            width,\n            height,\n            // `rounded-full` resolves to a huge radius; the box clamps it to half its short side.\n            radius: Math.min(Number.parseFloat(style.borderTopLeftRadius) || 0, width / 2, height / 2),\n            border: surface.clientLeft,\n          });\n          Object.assign(arrowElement.style, {\n            left: `${-surface.clientLeft}px`,\n            top: `${-surface.clientTop}px`,\n            right: \"auto\",\n            bottom: \"auto\",\n          });\n          arrowElement.querySelector(\"[data-arrow-fill]\")?.setAttribute(\"d\", shape.fill);\n          arrowElement.querySelector(\"[data-arrow-stroke]\")?.setAttribute(\"d\", shape.stroke);\n          // Paint with whatever the surface resolved to, so a restyled tooltip\n          // keeps a matching arrow without a second set of classes. A\n          // see-through border is drawn over the surface's own background, so\n          // the stroke takes that blended colour: half of it sits over the\n          // page, and it overlaps the border where the two meet.\n          arrowElement.style.setProperty(\"--tooltip-arrow-fill\", style.backgroundColor);\n          arrowElement.style.setProperty(\n            \"--tooltip-arrow-stroke\",\n            blend(style.borderTopColor, style.backgroundColor),\n          );\n        }\n        onPosition(placedSide);\n      });\n    };\n    if (open) schedule();\n  }, [\n    open,\n    anchor,\n    floatingRef,\n    arrowRef,\n    followCursor,\n    pointX,\n    pointY,\n    preferred,\n    sideOffset,\n    schedule,\n    onPosition,\n    cursor,\n  ]);\n\n  useLayoutEffect(() => {\n    const floating = floatingRef.current;\n    if (!open || !anchor || !floating) return;\n    const stop = autoUpdate(anchor, floating, schedule);\n    const onScroll = () => {\n      // A stationary pointer no longer describes the same chart point after scrolling.\n      if (followCursor && cursor.current) onDismiss();\n    };\n    window.addEventListener(\"scroll\", onScroll, true);\n    return () => {\n      stop();\n      window.removeEventListener(\"scroll\", onScroll, true);\n      version.current++;\n      if (frame.current !== null) cancelAnimationFrame(frame.current);\n      frame.current = null;\n    };\n  }, [open, anchor, floatingRef, followCursor, onDismiss, schedule, cursor]);\n\n  useLayoutEffect(\n    () => () => {\n      version.current++;\n      if (frame.current !== null) cancelAnimationFrame(frame.current);\n    },\n    [],\n  );\n}\n\n/** Pointer lifetime belongs to the anchor, including the opening delay. */\nexport function useTooltipPointer(anchor: TooltipAnchor | null, followCursor: boolean) {\n  const cursor = useRef<TooltipPoint | null>(null);\n  const onMove = useRef<(() => void) | null>(null);\n  const pointerFocus = useRef(false);\n  useLayoutEffect(() => {\n    if (!anchor || !followCursor) return;\n    const point = (event: PointerEvent) => {\n      if (event.type === \"pointermove\" && event.pointerType === \"touch\" && !event.buttons) return;\n      cursor.current = { x: event.clientX, y: event.clientY };\n      if (event.type === \"pointerdown\") pointerFocus.current = true;\n      onMove.current?.();\n    };\n    const keyboard = () => {\n      cursor.current = null;\n      pointerFocus.current = false;\n      onMove.current?.();\n    };\n    const focus = () => {\n      if (!pointerFocus.current) cursor.current = null;\n      pointerFocus.current = false;\n      onMove.current?.();\n    };\n    const leave = () => {\n      cursor.current = null;\n    };\n    anchor.addEventListener(\"pointerenter\", point as EventListener, { passive: true });\n    anchor.addEventListener(\"pointermove\", point as EventListener, { passive: true });\n    anchor.addEventListener(\"pointerdown\", point as EventListener, { passive: true });\n    anchor.addEventListener(\"pointerleave\", leave);\n    anchor.addEventListener(\"pointercancel\", leave);\n    anchor.addEventListener(\"keydown\", keyboard);\n    anchor.addEventListener(\"focusin\", focus);\n    return () => {\n      cursor.current = null;\n      anchor.removeEventListener(\"pointerenter\", point as EventListener);\n      anchor.removeEventListener(\"pointermove\", point as EventListener);\n      anchor.removeEventListener(\"pointerdown\", point as EventListener);\n      anchor.removeEventListener(\"pointerleave\", leave);\n      anchor.removeEventListener(\"pointercancel\", leave);\n      anchor.removeEventListener(\"keydown\", keyboard);\n      anchor.removeEventListener(\"focusin\", focus);\n    };\n  }, [anchor, followCursor]);\n\n  return useMemo(() => ({ cursor, onMove }), []);\n}\n"},{"path":"components/motion/tooltip-surface.tsx","type":"util","content":"\"use client\";\n\nimport { motion, useReducedMotion, type Variants } from \"motion/react\";\nimport type { ComponentProps, ReactNode, Ref } from \"react\";\nimport { EASE_OUT } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\nconst ENTER = { duration: 0.18, ease: EASE_OUT };\nconst EXIT = { duration: 0.12, ease: EASE_OUT };\nconst INSTANT = { duration: 0 };\n\n/**\n * `custom` is the `instant` flag. An exiting surface reads it from its\n * `AnimatePresence`, so a tooltip replaced by a neighbour vanishes at once\n * even though it has already left the React tree.\n */\nconst variants = (reduce: boolean): Variants => ({\n  closed: (instant = false) => ({\n    opacity: 0,\n    scale: reduce ? 1 : 0.97,\n    transition: instant ? INSTANT : EXIT,\n  }),\n  open: (instant = false) => ({\n    opacity: 1,\n    scale: 1,\n    transition: instant ? INSTANT : ENTER,\n  }),\n});\n\n/** Presentation only: the unanimated parent owns measurement and positioning. */\nexport function TooltipSurface({\n  children,\n  className,\n  ref,\n  ready = true,\n  instant = false,\n  style,\n  ...props\n}: Omit<ComponentProps<typeof motion.span>, \"children\"> & {\n  children?: ReactNode;\n  /** Start the entrance only after the positioning layer has been measured. */\n  ready?: boolean;\n  /**\n   * Appear and disappear without animating: a label opened from the keyboard,\n   * or one of a row of tooltips the pointer is moving along.\n   */\n  instant?: boolean;\n  ref?: Ref<HTMLSpanElement>;\n}) {\n  const reduce = useReducedMotion() ?? false;\n  return (\n    <motion.span\n      ref={ref}\n      role=\"tooltip\"\n      custom={instant}\n      variants={variants(reduce)}\n      initial=\"closed\"\n      animate={ready ? \"open\" : \"closed\"}\n      exit=\"closed\"\n      style={{ transformOrigin: \"var(--tooltip-origin, center)\", ...style }}\n      className={cn(\n        \"block whitespace-nowrap rounded-full border border-border bg-background px-3 py-1 text-xs font-medium text-foreground shadow-[0_8px_24px_-8px_rgb(0_0_0/0.16)]\",\n        className,\n      )}\n      {...props}\n    >\n      {children}\n    </motion.span>\n  );\n}\n"},{"path":"lib/hooks/use-dismiss.ts","type":"util","content":"\"use client\";\n\nimport { type RefObject, useEffect, useLayoutEffect, useRef } from \"react\";\nimport {\n  inLayerAbove,\n  inOtherLayer,\n  type Layer,\n  openLayer,\n  ownsEscape,\n} from \"@/lib/layers\";\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\n/** What closed the overlay: Escape, a pointerdown outside it, or focus leaving it. */\nexport type DismissReason = \"escape\" | \"pointer\" | \"focus\";\n\nexport interface DismissOptions {\n  /** Default `\"pass-through\"`. */\n  behavior?: DismissBehavior;\n  /** Dismiss on Escape as well. Default true. */\n  escape?: boolean;\n  /** Dismiss when focus moves outside, as a combobox does on Tab. Default false. */\n  focusOutside?: boolean;\n  /**\n   * Dismiss on a pointerdown outside. Default true. Turn it off for an overlay\n   * whose own backdrop handles presses and only needs Escape and layering.\n   */\n  outsidePress?: boolean;\n  /** Return true for an outside target that should *not* dismiss. */\n  ignore?: (target: Element) => boolean;\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.\n *\n * Each open dismissal is a layer in `lib/layers.ts`, so only the innermost\n * open overlay answers Escape (a menu inside a drawer closes, the drawer\n * stays), and a drawer's focus trap leaves focus in a menu it portaled out.\n */\nexport function useDismiss(\n  open: boolean,\n  onDismiss: (reason: DismissReason) => void,\n  ref: RefObject<HTMLElement | SVGElement | null> | null,\n  {\n    behavior = \"pass-through\",\n    escape: dismissOnEscape = true,\n    focusOutside = false,\n    outsidePress = true,\n    ignore,\n  }: DismissOptions = {},\n) {\n  // Read through refs, so a callback rebuilt each render neither re-binds the\n  // listeners nor moves this layer to the top of the stack.\n  const dismissRef = useRef(onDismiss);\n  const ignoreRef = useRef(ignore);\n  useLayoutEffect(() => {\n    dismissRef.current = onDismiss;\n    ignoreRef.current = ignore;\n  });\n\n  useEffect(() => {\n    if (!open) return;\n    const inside = (target: Node) =>\n      Boolean(ref?.current?.contains(target)) ||\n      (target instanceof Element && Boolean(ignoreRef.current?.(target)));\n    const layer: Layer = { contains: inside, escape: dismissOnEscape };\n    const closeLayer = openLayer(layer);\n    const onKey = (event: KeyboardEvent) => {\n      if (!dismissOnEscape || event.key !== \"Escape\" || !ownsEscape(layer, event)) return;\n      event.preventDefault();\n      dismissRef.current(\"escape\");\n    };\n    const onPointer = (event: PointerEvent) => {\n      const target = event.target as Element | null;\n      if (!target || inside(target)) return;\n      // A press in an overlay opened on top of this one (a tooltip or menu\n      // portaled to the body) belongs to that overlay, not outside this one.\n      if (inLayerAbove(layer, target)) return;\n      // Outside this overlay, but inside another open one: 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\" && !inOtherLayer(layer, target, { traps: false })) {\n        consumeActivation(event);\n      }\n      dismissRef.current(\"pointer\");\n    };\n    const onFocus = (event: FocusEvent) => {\n      const target = event.target;\n      if (target instanceof Node && !inside(target)) dismissRef.current(\"focus\");\n    };\n    window.addEventListener(\"keydown\", onKey);\n    if (outsidePress) window.addEventListener(\"pointerdown\", onPointer, true);\n    if (focusOutside) window.addEventListener(\"focusin\", onFocus);\n    return () => {\n      closeLayer();\n      window.removeEventListener(\"keydown\", onKey);\n      window.removeEventListener(\"pointerdown\", onPointer, true);\n      window.removeEventListener(\"focusin\", onFocus);\n    };\n  }, [open, ref, behavior, dismissOnEscape, focusOutside, outsidePress]);\n}\n"},{"path":"lib/hooks/use-hover-gesture.ts","type":"util","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":"util","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/merge-refs.ts","type":"util","content":"import type { Ref } from \"react\";\n\n/** Points a callback or object ref at `value`. */\nexport function assignRef<T>(ref: Ref<T> | undefined, value: T | null) {\n  if (typeof ref === \"function\") ref(value);\n  else if (ref) ref.current = value;\n}\n\n/** One callback ref that sets every ref it is given. */\nexport function mergeRefs<T>(...refs: Array<Ref<T> | undefined>) {\n  return (node: T | null) => {\n    for (const ref of refs) assignRef(ref, node);\n  };\n}\n"},{"path":"components/motion/popover-position.ts","type":"util","content":"\"use client\";\n\nimport {\n  type MutableRefObject,\n  useCallback,\n  useLayoutEffect,\n  useState,\n} from \"react\";\n\nexport type PortalLayout = {\n  trigger: {\n    left: number;\n    top: number;\n    width: number;\n    height: number;\n  };\n  content: {\n    width: number;\n    height: number;\n  };\n};\n\nfunction sameLayout(a: PortalLayout | null, b: PortalLayout) {\n  return (\n    a?.trigger.left === b.trigger.left &&\n    a.trigger.top === b.trigger.top &&\n    a.trigger.width === b.trigger.width &&\n    a.trigger.height === b.trigger.height &&\n    a.content.width === b.content.width &&\n    a.content.height === b.content.height\n  );\n}\n\n/** Measures a trigger and portalled panel in viewport coordinates. */\nexport function usePopoverPortalPosition<\n  TriggerElement extends HTMLElement,\n  ContentElement extends HTMLElement,\n>(\n  triggerRef: MutableRefObject<TriggerElement | null>,\n  contentRef: MutableRefObject<ContentElement | null>,\n  active: boolean,\n) {\n  const [layout, setLayout] = useState<PortalLayout | null>(null);\n\n  const update = useCallback(() => {\n    const trigger = triggerRef.current;\n    const content = contentRef.current;\n    if (!trigger || !content) return;\n\n    const rect = trigger.getBoundingClientRect();\n    const next: PortalLayout = {\n      trigger: {\n        left: rect.left,\n        top: rect.top,\n        width: rect.width,\n        height: rect.height,\n      },\n      content: {\n        width: content.offsetWidth,\n        height: content.offsetHeight,\n      },\n    };\n    setLayout((current) => (sameLayout(current, next) ? current : next));\n  }, [contentRef, triggerRef]);\n\n  useLayoutEffect(() => {\n    update();\n    if (!active) return;\n\n    const trigger = triggerRef.current;\n    const content = contentRef.current;\n    const observer = new ResizeObserver(update);\n    if (trigger) observer.observe(trigger);\n    if (content) observer.observe(content);\n\n    window.addEventListener(\"scroll\", update, true);\n    window.addEventListener(\"resize\", update);\n    return () => {\n      observer.disconnect();\n      window.removeEventListener(\"scroll\", update, true);\n      window.removeEventListener(\"resize\", update);\n    };\n  }, [active, contentRef, triggerRef, update]);\n\n  return layout;\n}\n"},{"path":"lib/focusable.ts","type":"util","content":"/**\n * Elements that can usually take keyboard focus. The selector cannot see\n * everything focus() checks (an element under `display: none`, say), so a\n * caller that needs certainty tries focus() and checks where it landed.\n */\nexport const FOCUSABLE_SELECTOR = [\n  \"a[href]\",\n  \"button:not(:disabled)\",\n  \"input:not(:disabled):not([type='hidden'])\",\n  \"select:not(:disabled)\",\n  \"textarea:not(:disabled)\",\n  \"[tabindex]:not([tabindex='-1'])\",\n].join(\",\");\n\n/** Elements inside `container` that Tab can reach, in DOM order. */\nexport function focusablesIn(container: Element | null | undefined) {\n  return Array.from(\n    container?.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR) ?? [],\n  ).filter((element) => element.tabIndex >= 0 && !element.closest(\"[inert]\"));\n}\n\n/** Focuses the first tabbable element in `panel`, or the panel itself. */\nexport function focusFirstIn(panel: HTMLElement | null | undefined) {\n  (focusablesIn(panel)[0] ?? panel)?.focus({ preventScroll: true });\n}\n\n/**\n * Keeps a Tab keypress inside `panel`, wrapping from the last tabbable element\n * to the first and back. Give the panel `tabIndex={-1}` so it can hold focus\n * when it has nothing tabbable.\n */\nexport function cycleTab(event: KeyboardEvent, panel: HTMLElement | null) {\n  if (event.key !== \"Tab\" || !panel) return;\n  const elements = focusablesIn(panel);\n  const first = elements[0];\n  const last = elements[elements.length - 1];\n  const active = document.activeElement;\n  if (!first || !last) {\n    event.preventDefault();\n    panel.focus({ preventScroll: true });\n  } else if (event.shiftKey && (active === first || active === panel)) {\n    event.preventDefault();\n    last.focus();\n  } else if (!event.shiftKey && active === last) {\n    event.preventDefault();\n    first.focus();\n  }\n}\n"},{"path":"components/motion/menu/menu-item-highlight.tsx","type":"util","content":"\"use client\";\n\nimport { motion } from \"motion/react\";\nimport { SPRING_LAYOUT } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\n/** The row shape every menu item shares. Menus add their own gap and states. */\nexport const MENU_ITEM_CLASS =\n  \"relative isolate flex w-full select-none items-center rounded-lg px-3 py-1.5 text-left text-sm outline-none\";\n\nexport interface MenuItemHighlightProps {\n  /** Shared by every row of one panel, so the highlight glides between them. */\n  layoutId: string;\n  tone?: \"default\" | \"destructive\";\n  reduce: boolean;\n  /**\n   * Jump instead of gliding: the highlight was moved by the keyboard, where a\n   * spring only trails behind fast arrowing.\n   */\n  instant?: boolean;\n}\n\n/** The highlight behind the active row. Render it only inside the active row. */\nexport function MenuItemHighlight({\n  layoutId,\n  tone = \"default\",\n  reduce,\n  instant = false,\n}: MenuItemHighlightProps) {\n  return (\n    <motion.span\n      aria-hidden=\"true\"\n      layoutId={layoutId}\n      className={cn(\n        \"absolute inset-0 -z-10 rounded-lg\",\n        tone === \"destructive\" ? \"bg-destructive/10\" : \"bg-foreground/[0.07]\",\n      )}\n      transition={reduce || instant ? { duration: 0 } : SPRING_LAYOUT}\n    />\n  );\n}\n"},{"path":"lib/hooks/use-listbox.ts","type":"util","content":"\"use client\";\n\nimport {\n  type KeyboardEvent,\n  type RefObject,\n  useEffect,\n  useMemo,\n  useRef,\n} from \"react\";\nimport { useOnOpen } from \"@/lib/hooks/use-on-open\";\nimport { useRowCursor } from \"@/lib/hooks/use-row-cursor\";\n\nexport interface ListboxRow {\n  id: string;\n  label: string;\n  disabled?: boolean;\n}\n\n// How long typed characters keep building one typeahead query.\nconst TYPEAHEAD_MS = 500;\n\n/**\n * Keyboard model for a popup listbox whose options are focusable buttons.\n *\n * The active option is resolved during render through `useRowCursor`, so the\n * roving `tabIndex` and the next key press always agree with what is on\n * screen. Opening starts on the selected option, or the first enabled one.\n * Arrow keys, Home and End move between enabled options, and printable\n * characters jump to the next option whose label starts with what was typed.\n * DOM focus follows the active option while the list is open; each option\n * carries its id in `data-listbox-id` so the list can find it.\n */\nexport function useListbox({\n  open,\n  rows,\n  selected,\n  list,\n}: {\n  open: boolean;\n  rows: readonly ListboxRow[];\n  selected: string | undefined;\n  list: RefObject<HTMLElement | null>;\n}) {\n  const enabled = useMemo(() => rows.filter((row) => !row.disabled), [rows]);\n  const { activeIndex, moveTo, moveActive } = useRowCursor(enabled, \"\");\n  useOnOpen(open, () =>\n    moveTo(enabled.some((row) => row.id === selected) ? (selected ?? null) : null),\n  );\n  const activeId = enabled[activeIndex]?.id;\n  const typed = useRef({ text: \"\", at: 0 });\n  // A list rendered open does not take focus from the page on mount; focus\n  // follows only once it has been opened, or once focus is already inside.\n  const openedOnMount = useRef(open);\n  useEffect(() => {\n    if (!open) openedOnMount.current = false;\n  }, [open]);\n\n  useEffect(() => {\n    if (!open || activeId === undefined) return;\n    if (\n      openedOnMount.current &&\n      !list.current?.contains(document.activeElement)\n    )\n      return;\n    const option = Array.from(\n      list.current?.querySelectorAll<HTMLElement>(\"[data-listbox-id]\") ?? [],\n    ).find((element) => element.dataset.listboxId === activeId);\n    option?.focus({ preventScroll: false });\n  }, [open, activeId, list]);\n\n  const onKeyDown = (event: KeyboardEvent) => {\n    const { key } = event;\n    if (key === \"ArrowDown\" || key === \"ArrowUp\") {\n      event.preventDefault();\n      moveActive(key === \"ArrowDown\" ? 1 : -1);\n    } else if (key === \"Home\" || key === \"End\") {\n      event.preventDefault();\n      const row = key === \"Home\" ? enabled[0] : enabled[enabled.length - 1];\n      if (row) moveTo(row.id);\n    } else if (\n      key.length === 1 &&\n      key !== \" \" &&\n      !event.ctrlKey &&\n      !event.metaKey &&\n      !event.altKey\n    ) {\n      const now = Date.now();\n      const char = key.toLowerCase();\n      const text =\n        now - typed.current.at < TYPEAHEAD_MS ? typed.current.text + char : char;\n      typed.current = { text, at: now };\n      // A repeated single letter cycles through the options that start with it.\n      const from = text.length === 1 ? activeIndex + 1 : activeIndex;\n      for (let step = 0; step < enabled.length; step++) {\n        const row = enabled[(from + step) % enabled.length];\n        if (row.label.toLowerCase().startsWith(text)) {\n          moveTo(row.id);\n          break;\n        }\n      }\n    }\n  };\n\n  // `moveTo` lets a pointer resting on an option make it the active one, so a\n  // highlight drawn from `activeId` follows the mouse as well as the keys.\n  return { activeId, onKeyDown, moveTo };\n}\n"},{"path":"lib/sounds/close.ts","type":"util","content":"import { defineSound } from \"./engine\";\n\n/** The open whoosh falling and a little quicker, settling with a soft low tap, for things closing. */\nexport const closeSound = defineSound({\n  name: \"Close\",\n  duration: 0.16,\n  room: 0.18,\n  build: (v) => {\n    v.noise({ freq: 2600, to: 700, q: 1.2, attack: 0.012, decay: 0.09, gain: 0.7 });\n    v.click({ freq: 1400, q: 1.2, at: 0.05, decay: 0.006, gain: 0.2 });\n    v.strike({ freq: 260, material: \"wood\", bend: 1.2, at: 0.05, decay: 0.045, gain: 0.3 });\n  },\n});\n"},{"path":"lib/sounds/open.ts","type":"util","content":"import { defineSound } from \"./engine\";\n\n/** A soft rising whoosh that lands with a light glass touch, for menus, popovers and dialogs opening. */\nexport const openSound = defineSound({\n  name: \"Open\",\n  duration: 0.2,\n  room: 0.2,\n  build: (v) => {\n    v.noise({ freq: 600, to: 2600, q: 1.2, attack: 0.035, decay: 0.11, gain: 0.75 });\n    v.noise({ freq: 4500, to: 6000, q: 1, attack: 0.03, decay: 0.07, gain: 0.05 });\n    v.strike({ freq: 1320, material: \"glass\", at: 0.05, decay: 0.07, gain: 0.12 });\n  },\n});\n"},{"path":"lib/sounds/select.ts","type":"util","content":"import { defineSound } from \"./engine\";\n\n/** A crisp detent, like a dial clicking into a notch, for tabs, segmented controls and menu choices. */\nexport const selectSound = defineSound({\n  name: \"Select\",\n  duration: 0.05,\n  room: 0.08,\n  build: (v) => {\n    v.click({ freq: 4500, q: 2.5, decay: 0.003, gain: 0.45 });\n    v.strike({ freq: 1700, material: \"metal\", decay: 0.028, gain: 0.3 });\n    v.strike({ freq: 520, material: \"wood\", bend: 1.15, decay: 0.012, gain: 0.25 });\n  },\n});\n"},{"path":"lib/audio-context.ts","type":"util","content":"// One AudioContext for every synthesized sound on the page: the sounds\n// library (lib/sounds/), the WheelPicker tick (lib/tick-sound.ts), the casino\n// games (lib/game-sounds.ts) and Bookshelf (lib/book-sounds.ts). Browsers cap\n// concurrent contexts, and a page can show a date made of several WheelPickers\n// next to a game, so they all share this one. It is created on first use and\n// closed once every player is disposed.\n//\n// Every player connects to `audioOutput()` rather than the context's\n// destination, so the page-wide volume and mute from `SoundProvider`\n// (lib/sound.tsx) reach all of them in one place.\n\ntype AudioContextCtor = typeof AudioContext;\n\nlet context: AudioContext | null = null;\nlet master: GainNode | null = null;\nlet users = 0;\n\n/** Settings one mounted `SoundProvider` asks for. */\nexport interface SoundSettingsEntry {\n  /** Nesting depth: the deepest provider decides. */\n  depth: number;\n  enabled: boolean;\n  volume: number;\n}\n\n// Mounted providers in mount order. Module state, so `sound.play()` called\n// outside React obeys them too. The deepest provider wins; among equals, the\n// one mounted last. Effects run child first, so this can't be \"whoever ran\n// last\".\nconst providers = new Set<SoundSettingsEntry>();\nlet allowed = true;\nlet volume = 1;\n\nfunction applySettings() {\n  let chosen: SoundSettingsEntry | undefined;\n  for (const entry of providers) {\n    if (!chosen || entry.depth >= chosen.depth) chosen = entry;\n  }\n  allowed = chosen?.enabled ?? true;\n  volume = Math.min(1, Math.max(0, chosen?.volume ?? 1));\n  if (master) master.gain.value = volume;\n}\n\n/**\n * Registers a provider's settings; call `update` after changing the entry and\n * the returned release function when the provider unmounts.\n */\nexport function registerSoundSettings(entry: SoundSettingsEntry) {\n  providers.add(entry);\n  applySettings();\n  return {\n    update: applySettings,\n    release() {\n      providers.delete(entry);\n      applySettings();\n    },\n  };\n}\n\n/**\n * Registers a sound player. Call the returned function when the player is\n * disposed; the context closes after the last one.\n */\nexport function retainAudioContext() {\n  users++;\n  let released = false;\n  return () => {\n    if (released) return;\n    released = true;\n    users--;\n    if (users === 0 && context) {\n      void context.close();\n      context = null;\n      master = null;\n    }\n  };\n}\n\n/**\n * The shared context, created on first call and resumed if suspended. Null\n * during SSR, in browsers without Web Audio, and while sounds are muted or at\n * zero volume.\n */\nexport function getAudioContext(): AudioContext | null {\n  if (!allowed || volume <= 0) return null;\n  if (!context) {\n    if (typeof window === \"undefined\") return null;\n    const Ctor =\n      window.AudioContext ??\n      (window as unknown as { webkitAudioContext?: AudioContextCtor }).webkitAudioContext;\n    if (!Ctor) return null;\n    context = new Ctor();\n  }\n  // Browsers may refuse outside a user gesture. Players call this from\n  // pointer and key handlers first, so a later call finds it running.\n  if (context.state === \"suspended\") void context.resume().catch(() => undefined);\n  return context;\n}\n\n/** The node every player connects to: the page-wide volume, then the speakers. */\nexport function audioOutput(ctx: AudioContext): AudioNode {\n  if (master?.context !== ctx) {\n    master = ctx.createGain();\n    master.gain.value = volume;\n    master.connect(ctx.destination);\n  }\n  return master;\n}\n\nconst gains = new WeakMap<BaseAudioContext, Map<string, GainNode>>();\n\n/**\n * A player's own level, made once per context and routed into `audioOutput`.\n * Players keep their mix this way without rebuilding nodes on every play, and\n * a context closed and recreated gets fresh ones.\n */\nexport function playerGain(ctx: AudioContext, key: string, level: number): GainNode {\n  let byKey = gains.get(ctx);\n  if (!byKey) {\n    byKey = new Map();\n    gains.set(ctx, byKey);\n  }\n  let gain = byKey.get(key);\n  if (!gain) {\n    gain = ctx.createGain();\n    gain.gain.value = level;\n    gain.connect(audioOutput(ctx));\n    byKey.set(key, gain);\n  }\n  return gain;\n}\n"},{"path":"lib/sounds/engine.ts","type":"util","content":"import { audioOutput, getAudioContext } from \"@/lib/audio-context\";\n\n// Every beUI sound is a short recipe played with Web Audio the moment it is\n// asked for. Nothing is downloaded. Recipes are built the way a real tap\n// sounds: a contact click (a millisecond of filtered noise), a body that\n// rings at a few inharmonic partials of a material and settles in pitch, and\n// a little of a small room behind it.\n\n/** Options for one play of a sound. */\nexport interface PlayOptions {\n  /** 0 to 1, multiplied with the page-wide volume from `SoundProvider`. */\n  volume?: number;\n  /** Pitch multiplier; 1 is the designed pitch. */\n  pitch?: number;\n}\n\n/** Where a sound renders: the live context, or an offline one for drawing. */\nexport interface SoundTarget {\n  context: BaseAudioContext;\n  destination: AudioNode;\n  /** Start time on the context clock, in seconds. */\n  when: number;\n  volume: number;\n  pitch: number;\n}\n\n/** A plain oscillator with an attack, a decay and an optional glide. */\nexport interface ToneSpec {\n  type?: OscillatorType;\n  /** Start frequency in Hz. */\n  freq: number;\n  /** End frequency in Hz; glides from `freq` over `glide`. */\n  to?: number;\n  /** Glide time in seconds; defaults to the attack plus decay. */\n  glide?: number;\n  /** Starts this many times higher and settles to `freq` in about 15 ms, like a struck object. */\n  bend?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Fade-in time in seconds. */\n  attack?: number;\n  /** Time to fade to silence after the attack, in seconds. */\n  decay: number;\n  gain: number;\n}\n\n/** A burst of filtered white noise. */\nexport interface NoiseSpec {\n  filter?: BiquadFilterType;\n  /** Filter frequency in Hz. */\n  freq: number;\n  /** End filter frequency in Hz; sweeps from `freq` over the decay. */\n  to?: number;\n  q?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Fade-in time in seconds. */\n  attack?: number;\n  /** Time to fade to silence after the attack, in seconds. */\n  decay: number;\n  gain: number;\n}\n\n/** The contact of a tap: a few milliseconds of band-passed noise with an instant attack. */\nexport interface ClickSpec {\n  /** Band center in Hz: 1-2 kHz is a soft knock, 3-5 kHz a crisp click. */\n  freq: number;\n  /** Band width; higher is narrower and more tonal. */\n  q?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Time to fade to silence, in seconds. */\n  decay?: number;\n  gain: number;\n}\n\n/** How a material rings: partials as [frequency ratio, level], and how fast high ones die. */\nexport interface Material {\n  partials: readonly (readonly [ratio: number, level: number])[];\n  /** Higher partials decay in `decay / ratio ** damping`; wood is high, metal low. */\n  damping: number;\n}\n\n// Partial ratios follow the modes of small struck objects: a free bar for\n// wood and metal, a cup for glass, a tuned bar for the mallet.\nexport const MATERIALS = {\n  wood: { partials: [[1, 1], [2.76, 0.3], [5.4, 0.08]], damping: 1.3 },\n  plastic: { partials: [[1, 1], [2.43, 0.4], [4.86, 0.14]], damping: 0.9 },\n  glass: { partials: [[1, 1], [2.32, 0.42], [4.25, 0.2], [6.63, 0.08]], damping: 0.55 },\n  metal: { partials: [[1, 1], [2.76, 0.5], [5.4, 0.26], [8.93, 0.1]], damping: 0.4 },\n  mallet: { partials: [[1, 1], [3.99, 0.2], [9.14, 0.05]], damping: 0.8 },\n  bell: { partials: [[1, 1], [2.0, 0.34], [2.76, 0.2], [5.4, 0.07]], damping: 0.5 },\n} satisfies Record<string, Material>;\n\n/** A struck object: one partial per mode of its material, each with its own decay. */\nexport interface StrikeSpec {\n  /** Fundamental in Hz. */\n  freq: number;\n  /** A name from `MATERIALS` or your own partials. Default: \"plastic\". */\n  material?: keyof typeof MATERIALS | Material;\n  /** Starts this many times higher and settles in about 15 ms. Default: 1.01. */\n  bend?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Time for the fundamental to fade to silence, in seconds. */\n  decay: number;\n  gain: number;\n}\n\nexport interface Voice {\n  tone(spec: ToneSpec): void;\n  noise(spec: NoiseSpec): void;\n  click(spec: ClickSpec): void;\n  strike(spec: StrikeSpec): void;\n}\n\nexport interface Sound {\n  /** Display name, like \"Tap\". */\n  name: string;\n  /** Length in seconds; the room tail rings a little past it. */\n  duration: number;\n  /** Plays the sound now. Silent during SSR and while sounds are muted. */\n  play(options?: PlayOptions): void;\n  /** Schedules the sound on any context; `play` uses the live one. */\n  render(target: SoundTarget): void;\n}\n\nexport interface SoundRecipe {\n  /** Display name, like \"Tap\". */\n  name: string;\n  /** Length in seconds; the room tail rings a little past it. */\n  duration: number;\n  /** Random pitch spread per play (0.04 = ±4%), so repeats don't sound stamped. */\n  vary?: number;\n  /** How much of the small room the sound is played in, 0 (dry) to 1. Default: 0.12. */\n  room?: number;\n  /** Adds the sound's layers to the voice on each play. */\n  build: (voice: Voice) => void;\n}\n\n// Keeps a sum of voices well under clipping at volume 1.\nconst MASTER_GAIN = 0.16;\nconst SILENT = 0.0001;\n// Time a strike or bend takes to settle onto its pitch.\nconst SETTLE = 0.015;\n\nconst noiseBuffers = new WeakMap<BaseAudioContext, AudioBuffer>();\n\n/** One second of white noise per context, shared by every noise voice. */\nexport function noiseBuffer(context: BaseAudioContext) {\n  let buffer = noiseBuffers.get(context);\n  if (!buffer) {\n    buffer = context.createBuffer(1, context.sampleRate, context.sampleRate);\n    const data = buffer.getChannelData(0);\n    for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;\n    noiseBuffers.set(context, buffer);\n  }\n  return buffer;\n}\n\n// A small, soft room: 8 early reflections, then a diffuse tail that falls\n// 60 dB in 0.3 s and darkens as it fades, the way air and soft walls\n// absorb highs first. Generated once per context.\nconst ROOM_LENGTH = 0.3;\n// The convolver's equal-power normalization leaves the room about 15 dB\n// under the dry sound; this brings `room: 0.12` to a tail heard only as space.\nconst ROOM_GAIN = 6;\nconst roomBuffers = new WeakMap<BaseAudioContext, AudioBuffer>();\n\nfunction roomBuffer(context: BaseAudioContext) {\n  let buffer = roomBuffers.get(context);\n  if (!buffer) {\n    const rate = context.sampleRate;\n    const length = Math.ceil(ROOM_LENGTH * rate);\n    buffer = context.createBuffer(2, length, rate);\n    for (let channel = 0; channel < 2; channel++) {\n      const data = buffer.getChannelData(channel);\n      let smooth = 0;\n      for (let i = Math.floor(0.004 * rate); i < length; i++) {\n        const t = i / rate;\n        // One-pole low-pass whose cutoff closes over the tail.\n        const brightness = 0.7 * Math.exp(-t / 0.08) + 0.08;\n        smooth += brightness * (Math.random() * 2 - 1 - smooth);\n        data[i] = smooth * Math.exp(-t / 0.043);\n      }\n      for (let r = 0; r < 8; r++) {\n        const at = Math.floor((0.005 + Math.random() * 0.022) * rate);\n        data[at] += (Math.random() < 0.5 ? -1 : 1) * (0.5 - r * 0.05);\n      }\n    }\n    roomBuffers.set(context, buffer);\n  }\n  return buffer;\n}\n\n// One convolver per output node, shared by every play: building one is the\n// expensive part, sending to it is cheap.\nconst rooms = new WeakMap<AudioNode, ConvolverNode>();\n\nfunction roomFor(context: BaseAudioContext, destination: AudioNode) {\n  let room = rooms.get(destination);\n  if (!room) {\n    room = context.createConvolver();\n    room.buffer = roomBuffer(context);\n    room.connect(destination);\n    rooms.set(destination, room);\n  }\n  return room;\n}\n\n/** A linear attack to `peak`, then an exponential fall to silence. */\nfunction envelope(param: AudioParam, start: number, attack: number, decay: number, peak: number) {\n  param.setValueAtTime(0, start);\n  param.linearRampToValueAtTime(Math.max(peak, SILENT), start + attack);\n  param.exponentialRampToValueAtTime(SILENT, start + attack + decay);\n}\n\nfunction voiceFor(target: SoundTarget, output: AudioNode): Voice {\n  const { context, when, pitch } = target;\n  // Partials above this only add hiss on small speakers, or alias near Nyquist.\n  const ceiling = Math.min(12000, context.sampleRate * 0.45);\n\n  const tone: Voice[\"tone\"] = ({ type = \"sine\", freq, to, glide, bend, at = 0, attack = 0.002, decay, gain }) => {\n    const start = when + at;\n    const osc = context.createOscillator();\n    const amp = context.createGain();\n    osc.type = type;\n    const base = freq * pitch;\n    osc.frequency.setValueAtTime(base * (bend ?? 1), start);\n    if (bend !== undefined) osc.frequency.exponentialRampToValueAtTime(base, start + SETTLE);\n    if (to !== undefined) {\n      osc.frequency.exponentialRampToValueAtTime(to * pitch, start + Math.max(glide ?? attack + decay, SETTLE));\n    }\n    envelope(amp.gain, start, attack, decay, gain);\n    osc.connect(amp).connect(output);\n    osc.start(start);\n    osc.stop(start + attack + decay + 0.02);\n  };\n\n  const noise: Voice[\"noise\"] = ({ filter = \"bandpass\", freq, to, q = 1, at = 0, attack = 0.002, decay, gain }) => {\n    const start = when + at;\n    const source = context.createBufferSource();\n    const shape = context.createBiquadFilter();\n    const amp = context.createGain();\n    source.buffer = noiseBuffer(context);\n    shape.type = filter;\n    shape.Q.value = q;\n    shape.frequency.setValueAtTime(freq * pitch, start);\n    if (to !== undefined) {\n      shape.frequency.exponentialRampToValueAtTime(to * pitch, start + attack + decay);\n    }\n    envelope(amp.gain, start, attack, decay, gain);\n    source.connect(shape).connect(amp).connect(output);\n    // A random offset into the buffer keeps each burst a little different.\n    source.start(start, Math.random() * 0.5);\n    source.stop(start + attack + decay + 0.02);\n  };\n\n  return {\n    tone,\n    noise,\n    click({ freq, q = 2, at = 0, decay = 0.005, gain }) {\n      // A little spread on the band, so no two contacts are identical.\n      noise({ freq: freq * (0.94 + Math.random() * 0.12), q, at, attack: 0.0005, decay, gain });\n    },\n    strike({ freq, material = \"plastic\", bend = 1.01, at = 0, decay, gain }) {\n      const { partials, damping } = typeof material === \"string\" ? MATERIALS[material] : material;\n      for (const [ratio, level] of partials) {\n        if (freq * ratio * pitch * bend > ceiling) continue;\n        tone({\n          // Real objects are never perfectly tuned; a hair of detune per partial.\n          freq: freq * ratio * (1 + (Math.random() * 2 - 1) * 0.003),\n          bend,\n          at,\n          attack: 0.001,\n          decay: decay / ratio ** damping,\n          gain: gain * level,\n        });\n      }\n    },\n  };\n}\n\n/** Turns a recipe into a playable sound. */\nexport function defineSound({ name, duration, vary = 0, room = 0.12, build }: SoundRecipe): Sound {\n  const render = (target: SoundTarget) => {\n    const { context, destination } = target;\n    const output = context.createGain();\n    output.gain.value = MASTER_GAIN * target.volume;\n    output.connect(destination);\n    if (room > 0) {\n      const send = context.createGain();\n      send.gain.value = room * ROOM_GAIN;\n      output.connect(send).connect(roomFor(context, destination));\n    }\n    build(voiceFor(target, output));\n  };\n\n  return {\n    name,\n    duration,\n    render,\n    play({ volume = 1, pitch = 1 } = {}) {\n      const context = getAudioContext();\n      if (!context || volume <= 0) return;\n      const spread = vary ? 1 + (Math.random() * 2 - 1) * vary : 1;\n      render({\n        context,\n        // The page-wide volume is applied there.\n        destination: audioOutput(context),\n        when: context.currentTime + 0.005,\n        volume,\n        pitch: pitch * spread,\n      });\n    },\n  };\n}\n"},{"path":"lib/layers.ts","type":"util","content":"/**\n * Every open overlay on the page, innermost last: focus traps, modal scopes\n * and dismissable menus all register here. Overlays have no shared z-order to\n * consult, and a menu inside a drawer portals out of it, so this stack is how\n * they agree on who answers Escape and where focus may go.\n */\n\nexport interface Layer {\n  /** Whether `target` belongs to this layer (its panel, portals, trigger). */\n  contains: (target: Node) => boolean;\n  /** True for focus traps and modal scopes, which pull stray focus back. */\n  traps?: boolean;\n  /** False for a layer that ignores Escape, so the key reaches the one below. */\n  escape?: boolean;\n}\n\nconst stack: Layer[] = [];\n// The innermost layer when each Escape began, read before any handler runs,\n// so a layer that closes itself mid-event can't hand the key to the one below.\nconst escapeOwners = new WeakMap<Event, Layer | undefined>();\nlet listening = false;\n\nfunction innermostEscapeLayer() {\n  for (let index = stack.length - 1; index >= 0; index--) {\n    if (stack[index].escape !== false) return stack[index];\n  }\n  return undefined;\n}\n\nfunction recordEscapeOwner(event: KeyboardEvent) {\n  if (event.key === \"Escape\") escapeOwners.set(event, innermostEscapeLayer());\n}\n\n/** Registers an open layer. Call the returned function when it closes. */\nexport function openLayer(layer: Layer) {\n  if (!listening) {\n    document.addEventListener(\"keydown\", recordEscapeOwner, true);\n    listening = true;\n  }\n  stack.push(layer);\n  return () => {\n    const index = stack.indexOf(layer);\n    if (index !== -1) stack.splice(index, 1);\n  };\n}\n\n/** Whether this Escape is `layer`'s to answer: it was innermost when the key went down. */\nexport function ownsEscape(layer: Layer, event: KeyboardEvent) {\n  if (event.defaultPrevented) return false;\n  const owner = escapeOwners.has(event)\n    ? escapeOwners.get(event)\n    : innermostEscapeLayer();\n  return owner === layer;\n}\n\n/** Whether `target` sits in a layer opened on top of `layer`. */\nexport function inLayerAbove(layer: Layer, target: Node) {\n  const index = stack.indexOf(layer);\n  return stack.slice(index + 1).some((above) => above.contains(target));\n}\n\n/** Whether a focus trap is open on top of `layer`; stray focus is that one's to pull back. */\nexport function trapAbove(layer: Layer) {\n  const index = stack.indexOf(layer);\n  return stack.slice(index + 1).some((above) => above.traps);\n}\n\n/**\n * Whether `target` belongs to any open layer other than `layer`. Pass\n * `traps: false` to count only dismissable overlays, not the traps under them.\n */\nexport function inOtherLayer(layer: Layer, target: Node, { traps = true } = {}) {\n  return stack.some(\n    (other) => other !== layer && (traps || !other.traps) && other.contains(target),\n  );\n}\n"},{"path":"lib/touch.ts","type":"util","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"},{"path":"lib/hooks/use-on-open.ts","type":"util","content":"\"use client\";\n\nimport { useState } from \"react\";\n\n/**\n * Runs `start` during the render in which `open` becomes true.\n *\n * Opening a list starts a fresh session - an empty query, the highlight back at\n * the top - and that is a resolution, not a side effect: a passive effect runs\n * after the commit, so the new session would carry the last one's state for a\n * window in which a key press can land.\n *\n * `start` may only set state belonging to the calling component. Anything that\n * reaches outside it - a consumer's callback, a DOM write, moving focus - is a\n * side effect, and React rejects a callback that sets another component's state\n * during this one's render. Put those in an effect keyed to `open`.\n */\nexport function useOnOpen(open: boolean, start: () => void) {\n  const [wasOpen, setWasOpen] = useState(open);\n  if (open !== wasOpen) {\n    setWasOpen(open);\n    if (open) start();\n  }\n}\n"},{"path":"lib/hooks/use-row-cursor.ts","type":"util","content":"\"use client\";\n\nimport { useCallback, useLayoutEffect, useRef, useState } from \"react\";\n\n/**\n * Where the keyboard or the pointer last moved to: the row's id, stamped with\n * the query it was placed under.\n */\ntype RowCursor = { id: string; query: string };\n\n/** The cursor's row, or -1 once the query has moved on or the row has left. */\nfunction indexOfCursor(\n  rows: readonly { id: string }[],\n  query: string,\n  cursor: RowCursor | null,\n) {\n  if (cursor === null || cursor.query !== query) return -1;\n  return rows.findIndex((row) => row.id === cursor.id);\n}\n\n/**\n * The highlighted row of a list whose rows can change under it.\n *\n * Which row is highlighted is resolved during render, never in a passive\n * effect: a passive effect runs after the commit, so a list that had just\n * changed would carry an `aria-activedescendant` naming a row that has left it,\n * and a key pressed in that window would commit the wrong row or nothing at\n * all.\n *\n * The cursor holds the row's id, not its position. A position alone cannot tell\n * a list that shrank from one that swapped its rows for a different set of the\n * same length, and the second case is the one that silently hands Enter to a\n * row the user never chose. A cursor whose row has left the list returns the\n * highlight to the first row rather than to the nearest surviving one: the row\n * the user aimed at is gone, and the first row is where a new query already\n * puts the highlight.\n *\n * Pass the query the list is filtered by. The cursor is stamped with it and\n * dropped when it changes, so a caller cannot forget to clear it - including a\n * caller whose query arrives as a prop and so never runs its own handler. Rows\n * that come back under a query that has moved on cannot revive it either.\n * `moveTo(null)` is for deliberate resets, such as reopening the list.\n *\n * Both callbacks keep one identity for the life of the component, and read the\n * rows and the query through a ref to do it. A caller will put them in an\n * effect's dependencies - the exhaustive-deps rule makes it - and a `moveTo`\n * rebuilt on every keystroke would re-run that effect on every keystroke.\n */\nexport function useRowCursor(rows: readonly { id: string }[], query: string) {\n  const [cursor, setCursor] = useState<RowCursor | null>(null);\n  // Written after commit, not during render: a render React discards or has not\n  // finished still runs the component body, and an event handler that read this\n  // in that window would stamp the cursor with a query the committed tree does\n  // not have.\n  const latest = useRef({ rows, query });\n  useLayoutEffect(() => {\n    latest.current = { rows, query };\n  });\n\n  const cursorRow = indexOfCursor(rows, query, cursor);\n  // Cleared rather than ignored: React re-runs this render with the cursor\n  // already gone, so rows that come back cannot revive a highlight the user has\n  // stopped aiming at.\n  if (cursor !== null && cursorRow < 0) setCursor(null);\n\n  const moveTo = useCallback(\n    (id: string | null) =>\n      setCursor(id === null ? null : { id, query: latest.current.query }),\n    [],\n  );\n\n  const moveActive = useCallback((direction: 1 | -1) => {\n    const { rows: live, query: liveQuery } = latest.current;\n    const last = live.length - 1;\n    if (last < 0) return;\n    // Steps from the row the cursor is really on, inside the update, so that\n    // two keys landing in one batch move two rows rather than one.\n    setCursor((current) => {\n      const at = Math.max(indexOfCursor(live, liveQuery, current), 0);\n      const next = Math.min(Math.max(at + direction, 0), last);\n      return { id: live[next].id, query: liveQuery };\n    });\n  }, []);\n\n  return { activeIndex: cursorRow < 0 ? 0 : cursorRow, moveTo, moveActive };\n}\n"},{"path":"components/previews/blocks/availability-scheduler.preview.tsx","type":"preview","content":"\"use client\";\n\nimport { AvailabilityScheduler } from \"@/components/motion/availability-scheduler\";\n\nexport function AvailabilitySchedulerPreview() {\n  return (\n    <div className=\"flex w-full justify-center\">\n      <AvailabilityScheduler />\n    </div>\n  );\n}\n"}]}