{"slug":"animated-toast-stack","name":"Animated Toast Stack","description":"Toasts in one morphing island: a pill that springs into a card, opens into a list on hover, and swipes away.","category":"motion","source_url":"https://beui.dev/r/animated-toast-stack/raw","detail_url":"https://beui.dev/r/animated-toast-stack","raw_url":"https://beui.dev/r/animated-toast-stack/raw","page_url":"https://beui.dev/components/motion/animated-toast-stack","markdown_url":"https://beui.dev/components/motion/animated-toast-stack.md","published_at":"2026-06-05","updated_at":"2026-11-28","dependencies":["@floating-ui/dom","clsx","lucide-react","motion","react","react-dom","tailwind-merge"],"internal":["./animated-toast-stack/toast-body","./animated-toast-stack/types","./animated-toast-stack/use-animated-toast-stack","./animated-toast-stack/use-content-size","./engine","./tooltip/grace","./tooltip/positioner","./tooltip/use-position","./types","./use-position","@/components/motion/animated-toast-stack","@/components/motion/tooltip","@/components/motion/tooltip-surface","@/lib/audio-context","@/lib/ease","@/lib/hooks/use-dismiss","@/lib/hooks/use-hover-gesture","@/lib/hooks/use-tap-gesture","@/lib/i18n","@/lib/layers","@/lib/merge-refs","@/lib/sound","@/lib/sounds/engine","@/lib/sounds/notify","@/lib/touch","@/lib/utils"],"install_slugs":["animated-toast-stack"],"requires_theme":true,"props":[{"displayName":"AnimatedToastStack","props":[{"name":"toasts","type":"AnimatedToast[]","required":true,"defaultValue":null,"description":"Toasts to show, oldest first. Usually the `toasts` from `useAnimatedToastStack`."},{"name":"onDismiss","type":"((id: string) => void)","required":false,"defaultValue":null,"description":"Called with the toast id on close or swipe. Swipe and close work only when set."},{"name":"position","type":"\"top-left\" | \"top-center\" | \"top-right\" | \"bottom-left\" | \"bottom-center\" | \"bottom-right\"","required":false,"defaultValue":"bottom-right","description":"Screen corner or edge the stack anchors to. Default: \"bottom-right\""},{"name":"placement","type":"\"fixed\" | \"static\" | \"absolute\"","required":false,"defaultValue":null,"description":"How the stack is positioned. Overrides `fixed` when set."},{"name":"fixed","type":"boolean","required":false,"defaultValue":"false","description":"Shorthand for `placement=\"fixed\"`. Default: false"},{"name":"portal","type":"boolean","required":false,"defaultValue":null,"description":"Render into a portal. Defaults to true when the placement is fixed."},{"name":"portalRoot","type":"Element | null","required":false,"defaultValue":null,"description":"Element to portal into. Defaults to `document.body`."},{"name":"maxVisible","type":"number","required":false,"defaultValue":"4","description":"How many toasts the open island lists. Default 4."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."},{"name":"classNames","type":"ToastClassNames","required":false,"defaultValue":null,"description":"Classes for each inner part, keyed by slot."},{"name":"icons","type":"Partial<Record<ToastStatus, ReactNode>>","required":false,"defaultValue":null,"description":"Icons per status, used in place of the built-in ones."},{"name":"renderToast","type":"((toast: AnimatedToast) => ReactNode)","required":false,"defaultValue":null,"description":"Renders a toast's whole body in place of the built-in layout."},{"name":"labels","type":"Partial<{ dismiss: string; region: string; more: string; }>","required":false,"defaultValue":null,"description":"Override any built-in string."},{"name":"sound","type":"boolean","required":false,"defaultValue":"false","description":"Play a two-note chime when a new toast arrives. Off by default; a\n`SoundProvider` can mute it app-wide."},{"name":"onPause","type":"(() => void)","required":false,"defaultValue":null,"description":"Called when the island opens (hover, focus or a tap). Pass the hook's\n`pause` so toasts don't run out while someone is reading them."},{"name":"onResume","type":"(() => void)","required":false,"defaultValue":null,"description":"Called when it closes again. Pass the hook's `resume`."}]},{"displayName":"useAnimatedToastStack","props":[{"name":"initialToasts","type":"ToastInput[]","required":false,"defaultValue":"[]","description":"Toasts in the stack on first render."},{"name":"defaultDuration","type":"number","required":false,"defaultValue":"4200","description":"Time before a toast without its own `duration` closes, in ms. Default: 4200"},{"name":"limit","type":"number","required":false,"defaultValue":null,"description":"Most toasts kept. Older ones drop off when a new one arrives."}]}],"types":[{"name":"AnimatedToast","file":"components/motion/animated-toast-stack/types.ts","fields":[{"name":"id","type":"string","required":true,"description":"Unique key, used to update or dismiss the toast."},{"name":"title","type":"ReactNode","required":true,"description":"Main line, shown in the closed island and the open list."},{"name":"description","type":"ReactNode","required":false,"description":"Muted second line, up to 2 lines, hidden in the closed island."},{"name":"status","type":"ToastStatus","required":false,"description":"Sets the icon and its colour; `loading` spins the icon. Default: `neutral`"},{"name":"icon","type":"ReactNode","required":false,"description":"Icon in the leading chip, used when the stack's `icons` has none for the status."},{"name":"action","type":"AnimatedToastAction","required":false,"description":"Optional button shown under the description."},{"name":"duration","type":"number","required":false,"description":"Time before the toast closes, in ms; 0 keeps it open. Default: the stack's `defaultDuration`"},{"name":"dismissible","type":"boolean","required":false,"description":"Set to false to hide the close button. Default: true"},{"name":"createdAt","type":"number","required":false,"description":"When the countdown started, in ms since epoch. Set by the stack."}]},{"name":"ToastClassNames","file":"components/motion/animated-toast-stack/types.ts","fields":[{"name":"root","type":"string","required":false,"description":"The anchored layer the island sits in."},{"name":"item","type":"string","required":false,"description":"One row of the open list."},{"name":"surface","type":"string","required":false,"description":"The island itself."},{"name":"iconWrap","type":"string","required":false,"description":"The round chip around the status icon."},{"name":"content","type":"string","required":false,"description":"The column holding the title, description and action."},{"name":"title","type":"string","required":false,"description":"The title text."},{"name":"description","type":"string","required":false,"description":"The description text."},{"name":"action","type":"string","required":false,"description":"The action button."},{"name":"close","type":"string","required":false,"description":"The close button."},{"name":"progress","type":"string","required":false,"description":"Not applied yet; the toast has no progress bar."}]},{"name":"AnimatedToastAction","file":"components/motion/animated-toast-stack/types.ts","fields":[{"name":"label","type":"ReactNode","required":true,"description":"Text of the action button under the description."},{"name":"onClick","type":"(toast: AnimatedToast) => void","required":true,"description":"Fires when the action button is pressed, with the toast it belongs to."}]}],"files":[{"path":"components/motion/animated-toast-stack.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/motion/animated-toast-stack\n\nimport { AnimatePresence, motion, type PanInfo, useReducedMotion } from \"motion/react\";\nimport { type ReactNode, type Ref, useEffect, useLayoutEffect, useRef, useState } from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { EASE_OUT } from \"@/lib/ease\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { useSound } from \"@/lib/sound\";\nimport { notifySound } from \"@/lib/sounds/notify\";\nimport { cn } from \"@/lib/utils\";\nimport { ToastBody } from \"./animated-toast-stack/toast-body\";\nimport type {\n  AnimatedToast,\n  ToastClassNames,\n  ToastPosition,\n  ToastStatus,\n} from \"./animated-toast-stack/types\";\nimport { useContentSize } from \"./animated-toast-stack/use-content-size\";\n\nexport type {\n  AnimatedToast,\n  AnimatedToastAction,\n  ToastClassNames,\n  ToastInput,\n  ToastPosition,\n  ToastStatus,\n  UseAnimatedToastStackOptions,\n} from \"./animated-toast-stack/types\";\nexport { useAnimatedToastStack } from \"./animated-toast-stack/use-animated-toast-stack\";\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const animatedToastStackMessages = {\n  dismiss: \"Dismiss toast\",\n  region: \"Notifications\",\n  more: \"{count} more\",\n};\n\nexport type AnimatedToastStackMessages = typeof animatedToastStackMessages;\n\nexport interface AnimatedToastStackProps {\n  /** Toasts to show, oldest first. Usually the `toasts` from `useAnimatedToastStack`. */\n  toasts: AnimatedToast[];\n  /** Called with the toast id on close or swipe. Swipe and close work only when set. */\n  onDismiss?: (id: string) => void;\n  /** Screen corner or edge the stack anchors to. Default: \"bottom-right\" */\n  position?: ToastPosition;\n  /** How the stack is positioned. Overrides `fixed` when set. */\n  placement?: \"static\" | \"fixed\" | \"absolute\";\n  /** Shorthand for `placement=\"fixed\"`. Default: false */\n  fixed?: boolean;\n  /** Render into a portal. Defaults to true when the placement is fixed. */\n  portal?: boolean;\n  /** Element to portal into. Defaults to `document.body`. */\n  portalRoot?: Element | null;\n  /** How many toasts the open island lists. Default 4. */\n  maxVisible?: number;\n  /** Classes merged onto the root element. */\n  className?: string;\n  /** Classes for each inner part, keyed by slot. */\n  classNames?: ToastClassNames;\n  /** Icons per status, used in place of the built-in ones. */\n  icons?: Partial<Record<ToastStatus, ReactNode>>;\n  /** Renders a toast's whole body in place of the built-in layout. */\n  renderToast?: (toast: AnimatedToast) => ReactNode;\n  /** Override any built-in string. */\n  labels?: Partial<AnimatedToastStackMessages>;\n  /**\n   * Play a two-note chime when a new toast arrives. Off by default; a\n   * `SoundProvider` can mute it app-wide.\n   */\n  sound?: boolean;\n  /**\n   * Called when the island opens (hover, focus or a tap). Pass the hook's\n   * `pause` so toasts don't run out while someone is reading them.\n   */\n  onPause?: () => void;\n  /** Called when it closes again. Pass the hook's `resume`. */\n  onResume?: () => void;\n}\n\n// The island blooms out of a dot this size and folds back into one.\nconst DOT = 40;\n// One radius, never animated: the browser clamps it to half the height, so\n// the dot, the pill and the card all fall out of the size spring.\nconst RADIUS = 20;\n// The card and the open list share one width, so swapping between them only\n// moves the height.\nconst CARD = \"w-[22rem] max-w-[calc(100vw-2rem)]\";\n// Closing waits a beat, so a shell resizing under the pointer never flaps.\nconst COLLAPSE_DELAY = 120;\n// The island's size spring. Less bounce than SPRING_MORPH: a toast resizes\n// often, and an overshooting height reads as a wobble. Local because only this\n// shell morphs between so many sizes.\nconst ISLAND_SPRING = { type: \"spring\", duration: 0.45, bounce: 0.08 } as const;\nconst FOLD = { duration: 0.25, ease: EASE_OUT } as const;\nconst FADE = { duration: 0.12, ease: EASE_OUT } as const;\n// New content blooms in once the shell is most of the way open, instead of\n// riding the whole spring, so it is never seen half clipped.\nconst CONTENT_IN = {\n  default: ISLAND_SPRING,\n  opacity: { duration: 0.18, delay: 0.05, ease: EASE_OUT },\n  filter: { duration: 0.22, delay: 0.05, ease: EASE_OUT },\n} as const;\n// Overlaps the incoming fade, so a swap is a crossfade and never a blank blink.\nconst CONTENT_OUT = { duration: 0.1, ease: EASE_OUT } as const;\n// A swipe this far (px) or this fast (px/s) dismisses.\nconst SWIPE_DISTANCE = 72;\nconst SWIPE_SPEED = 520;\n\nconst POSITION_CLASS: Record<ToastPosition, string> = {\n  \"top-left\": \"left-4 top-4 justify-start\",\n  \"top-center\": \"left-1/2 top-4 -translate-x-1/2 justify-center\",\n  \"top-right\": \"right-4 top-4 justify-end\",\n  \"bottom-left\": \"bottom-6 left-4 justify-start\",\n  \"bottom-center\": \"bottom-6 left-1/2 -translate-x-1/2 justify-center\",\n  \"bottom-right\": \"bottom-6 right-4 justify-end\",\n};\n\n// Content pins to the corner the island grows from: it holds still while the\n// shell opens around it, and the outgoing and incoming content share that\n// corner, so neither jumps when the other changes the size.\nconst PIN_CLASS: Record<ToastPosition, string> = {\n  \"top-left\": \"items-start justify-start\",\n  \"top-center\": \"items-start justify-center\",\n  \"top-right\": \"items-start justify-end\",\n  \"bottom-left\": \"items-end justify-start\",\n  \"bottom-center\": \"items-end justify-center\",\n  \"bottom-right\": \"items-end justify-end\",\n};\n\nconst swiped = (info: PanInfo) =>\n  Math.abs(info.offset.x) > SWIPE_DISTANCE || Math.abs(info.velocity.x) > SWIPE_SPEED;\n\nexport function AnimatedToastStack({\n  toasts,\n  onDismiss,\n  position = \"bottom-right\",\n  placement,\n  fixed = false,\n  portal,\n  portalRoot,\n  maxVisible = 4,\n  className,\n  classNames,\n  icons,\n  renderToast,\n  labels,\n  sound = false,\n  onPause,\n  onResume,\n}: AnimatedToastStackProps) {\n  const t = useMessages(\"animatedToastStack\", animatedToastStackMessages, labels);\n  const [portalTarget, setPortalTarget] = useState<Element | null>(null);\n  const play = useSound(notifySound, { enabled: sound });\n  // Toasts present on the first render are already on screen, so only ids\n  // that arrive later chime, once per batch.\n  const seen = useRef<Set<string> | null>(null);\n  useEffect(() => {\n    const ids = toasts.map((toast) => toast.id);\n    if (seen.current && ids.some((id) => !seen.current?.has(id))) play();\n    seen.current = new Set(ids);\n  }, [toasts, play]);\n  const visible = toasts.slice(-maxVisible);\n  const resolvedPlacement = placement ?? (fixed ? \"fixed\" : \"static\");\n  const shouldPortal = portal ?? resolvedPlacement === \"fixed\";\n\n  useEffect(() => {\n    setPortalTarget(shouldPortal ? (portalRoot ?? document.body) : null);\n  }, [portalRoot, shouldPortal]);\n\n  const layer = (\n    <div\n      className={cn(\n        \"pointer-events-none flex\",\n        // Above dialogs and menus (z-[100]), so a toast fired from one shows;\n        // below tooltips and popovers (z-[9999]).\n        resolvedPlacement === \"fixed\" && \"fixed z-[200]\",\n        resolvedPlacement === \"absolute\" && \"absolute z-20\",\n        resolvedPlacement !== \"static\" && cn(CARD, POSITION_CLASS[position]),\n        classNames?.root,\n        className,\n      )}\n    >\n      {/* One island cannot announce each toast, so a hidden live region does:\n          every new toast, and every change to one, is read out politely. */}\n      <div className=\"sr-only\" aria-live=\"polite\" aria-atomic=\"false\">\n        {toasts.map((toast) => (\n          <p key={toast.id}>\n            {toast.title}\n            {toast.description ? \". \" : null}\n            {toast.description}\n          </p>\n        ))}\n      </div>\n      <AnimatePresence>\n        {visible.length > 0 ? (\n          <Island\n            key=\"island\"\n            toasts={visible}\n            position={position}\n            onDismiss={onDismiss}\n            classNames={classNames}\n            icons={icons}\n            renderToast={renderToast}\n            labels={{ dismiss: t(\"dismiss\"), region: t(\"region\"), more: (count) => t(\"more\", { count }) }}\n            onPause={onPause}\n            onResume={onResume}\n          />\n        ) : null}\n      </AnimatePresence>\n    </div>\n  );\n\n  if (shouldPortal && !portalTarget) return null;\n  if (shouldPortal && portalTarget) return createPortal(layer, portalTarget);\n  return layer;\n}\n\nfunction Island({\n  toasts,\n  position,\n  onDismiss,\n  classNames,\n  icons,\n  renderToast,\n  labels,\n  onPause,\n  onResume,\n}: {\n  toasts: AnimatedToast[];\n  position: ToastPosition;\n  onDismiss?: (id: string) => void;\n  classNames?: ToastClassNames;\n  icons?: Partial<Record<ToastStatus, ReactNode>>;\n  renderToast?: (toast: AnimatedToast) => ReactNode;\n  labels: { dismiss: string; region: string; more: (count: number) => string };\n  onPause?: () => void;\n  onResume?: () => void;\n}) {\n  const reduce = useReducedMotion() ?? false;\n  const [sizer, size] = useContentSize<HTMLDivElement>();\n  const shellRef = useRef<HTMLElement>(null);\n  const newest = toasts[toasts.length - 1];\n  const others = toasts.length - 1;\n  const fromBottom = position.startsWith(\"bottom\");\n  const edge = fromBottom ? 1 : -1;\n  const compact = !newest.description && !newest.action && !renderToast;\n  const canSwipe = newest.dismissible !== false && Boolean(onDismiss);\n\n  // The island opens into the full list while it is hovered or focused, or\n  // after a tap on a touch screen, and holds every countdown while open.\n  const [hovered, setHovered] = useState(false);\n  const [focused, setFocused] = useState(false);\n  const [tapped, setTapped] = useState(false);\n  const open = hovered || focused || tapped;\n  const collapseTimer = useRef<number | null>(null);\n  // Set when a swipe throws away the last toast: the island leaves that way.\n  const [flung, setFlung] = useState<-1 | 0 | 1>(0);\n\n  const latest = useRef({ onPause, onResume });\n  useLayoutEffect(() => {\n    latest.current = { onPause, onResume };\n  });\n  useEffect(() => {\n    if (open) latest.current.onPause?.();\n    else latest.current.onResume?.();\n  }, [open]);\n  useEffect(\n    () => () => {\n      if (collapseTimer.current) window.clearTimeout(collapseTimer.current);\n      latest.current.onResume?.();\n    },\n    [],\n  );\n\n  // A tap anywhere else closes what a tap opened.\n  useEffect(() => {\n    if (!tapped) return;\n    const onDown = (event: PointerEvent) => {\n      if (!shellRef.current?.contains(event.target as Node)) setTapped(false);\n    };\n    document.addEventListener(\"pointerdown\", onDown);\n    return () => document.removeEventListener(\"pointerdown\", onDown);\n  }, [tapped]);\n\n  const ordered = fromBottom ? toasts : [...toasts].reverse();\n  const rowTransition = reduce ? FADE : CONTENT_IN;\n  const shellTransition = reduce\n    ? { width: { duration: 0 }, height: { duration: 0 }, default: { duration: 0.15, ease: EASE_OUT } }\n    : {\n        default: ISLAND_SPRING,\n        opacity: { duration: 0.18, ease: EASE_OUT },\n        filter: { duration: 0.24, ease: EASE_OUT },\n      };\n  // Outgoing content holds the corner it was pinned to while it fades.\n  const anchorX = position.endsWith(\"right\") ? \"right\" : \"left\";\n  const anchorY = fromBottom ? \"bottom\" : \"top\";\n  const origin = `${anchorY} ${position.endsWith(\"center\") ? \"center\" : anchorX}`;\n\n  return (\n    <motion.section\n      ref={shellRef}\n      aria-label={labels.region}\n      // Reachable from the keyboard even as a pill with nothing to press.\n      tabIndex={0}\n      initial={reduce ? { opacity: 0 } : { opacity: 0, width: DOT, height: DOT, y: 16 * edge, filter: \"blur(6px)\" }}\n      animate={{\n        opacity: 1,\n        x: 0,\n        y: 0,\n        filter: \"blur(0px)\",\n        ...(size ? { width: size.width, height: size.height } : {}),\n      }}\n      // Folds back into the dot, or flies off the way it was swiped.\n      exit={\n        reduce\n          ? { opacity: 0, transition: FADE }\n          : flung\n            ? { opacity: 0, x: flung * 160, filter: \"blur(4px)\", transition: FOLD }\n            : { opacity: 0, width: DOT, height: DOT, y: 10 * edge, filter: \"blur(6px)\", transition: FOLD }\n      }\n      transition={shellTransition}\n      drag={!open && canSwipe ? \"x\" : false}\n      dragConstraints={{ left: 0, right: 0 }}\n      dragElastic={0.2}\n      onDragEnd={(_, info) => {\n        if (!canSwipe || !swiped(info)) return;\n        if (toasts.length === 1) setFlung(info.offset.x < 0 ? -1 : 1);\n        onDismiss?.(newest.id);\n      }}\n      onTap={(event) => {\n        const pointer = (event as PointerEvent).pointerType;\n        if (pointer !== \"touch\" && pointer !== \"pen\") return;\n        // A tap on a toast's own button (close, action) is that button's.\n        const target = event.target instanceof Element ? event.target : null;\n        if (target?.closest(\"button\")) return;\n        setTapped((current) => !current);\n      }}\n      onPointerEnter={(event) => {\n        if (event.pointerType === \"touch\") return;\n        if (collapseTimer.current) window.clearTimeout(collapseTimer.current);\n        setHovered(true);\n      }}\n      onPointerLeave={(event) => {\n        if (event.pointerType === \"touch\") return;\n        if (collapseTimer.current) window.clearTimeout(collapseTimer.current);\n        collapseTimer.current = window.setTimeout(() => setHovered(false), COLLAPSE_DELAY);\n      }}\n      onFocus={() => setFocused(true)}\n      onBlur={(event) => {\n        if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setFocused(false);\n      }}\n      onKeyDown={(event) => {\n        if (event.key !== \"Escape\") return;\n        setHovered(false);\n        setTapped(false);\n        (document.activeElement as HTMLElement | null)?.blur();\n      }}\n      style={{ borderRadius: RADIUS }}\n      className={cn(\n        // A ring, not a border: the shell's box stays exactly the content's\n        // size, so leaving content is pinned where it was drawn.\n        \"pointer-events-auto relative flex touch-pan-y overflow-hidden bg-card text-foreground shadow-[0_8px_24px_-8px_rgb(0_0_0/0.16)] ring-1 ring-border outline-none\",\n        \"focus-visible:ring-2 focus-visible:ring-ring\",\n        PIN_CLASS[position],\n        classNames?.surface,\n      )}\n    >\n      {/* w-max keeps this at the natural size of what is shown; the shell\n          springs its real width and height toward it. */}\n      <div ref={sizer} className=\"w-max shrink-0\">\n        <AnimatePresence mode=\"popLayout\" initial={false} anchorX={anchorX} anchorY={anchorY}>\n          {open || !compact ? (\n            // The card and the open list are one stack: the newest toast's row\n            // stays mounted while the others fade in around it, so opening\n            // never redraws the text that is already on screen.\n            <Slot key=\"stack\" fromBottom={fromBottom} origin={origin} reduce={reduce} className={CARD}>\n              <ol className=\"relative divide-y divide-border\">\n                <AnimatePresence initial={false} mode=\"popLayout\" anchorY={anchorY}>\n                  {(open ? ordered : [newest]).map((toast) => (\n                    <Row\n                      key={toast.id}\n                      toast={toast}\n                      others={open ? 0 : others}\n                      swipe={open}\n                      onDismiss={onDismiss}\n                      classNames={classNames}\n                      icons={icons}\n                      renderToast={renderToast}\n                      labels={labels}\n                      reduce={reduce}\n                      transition={rowTransition}\n                    />\n                  ))}\n                </AnimatePresence>\n              </ol>\n            </Slot>\n          ) : (\n            <Slot key={`${newest.id}-pill`} fromBottom={fromBottom} origin={origin} reduce={reduce}>\n              <ToastBody\n                toast={newest}\n                compact\n                others={others}\n                onDismiss={onDismiss}\n                dismissLabel={labels.dismiss}\n                moreLabel={labels.more(others)}\n                classNames={classNames}\n                icons={icons}\n                renderToast={renderToast}\n                reduce={reduce}\n              />\n            </Slot>\n          )}\n        </AnimatePresence>\n      </div>\n    </motion.section>\n  );\n}\n\n/** What the island shows: it unfurls out of the edge and is sucked back into it. */\nfunction Slot({\n  ref,\n  fromBottom,\n  origin,\n  reduce,\n  className,\n  children,\n}: {\n  // popLayout measures and pins the outgoing slot through this ref.\n  ref?: Ref<HTMLDivElement>;\n  fromBottom: boolean;\n  origin: string;\n  reduce: boolean;\n  className?: string;\n  children: ReactNode;\n}) {\n  return (\n    <motion.div\n      ref={ref}\n      initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.97, y: fromBottom ? 4 : -4, filter: \"blur(4px)\" }}\n      animate={reduce ? { opacity: 1 } : { opacity: 1, scale: 1, y: 0, filter: \"blur(0px)\" }}\n      // Out fast and blur-free, before the resizing shell can clip it.\n      exit={reduce ? { opacity: 0, transition: FADE } : { opacity: 0, scale: 0.97, transition: CONTENT_OUT }}\n      transition={reduce ? FADE : CONTENT_IN}\n      style={{ transformOrigin: origin }}\n      className={className}\n    >\n      {children}\n    </motion.div>\n  );\n}\n\n/** One toast in the open island: its own close, and a swipe of its own. */\nfunction Row({\n  ref,\n  toast,\n  others,\n  swipe,\n  onDismiss,\n  classNames,\n  icons,\n  renderToast,\n  labels,\n  reduce,\n  transition,\n}: {\n  // popLayout pins a leaving row through this ref while the others close up.\n  ref?: Ref<HTMLLIElement>;\n  toast: AnimatedToast;\n  // The collapsed card counts the toasts waiting behind it.\n  others: number;\n  // Rows swipe on their own only in the open list; the collapsed island swipes whole.\n  swipe: boolean;\n  onDismiss?: (id: string) => void;\n  classNames?: ToastClassNames;\n  icons?: Partial<Record<ToastStatus, ReactNode>>;\n  renderToast?: (toast: AnimatedToast) => ReactNode;\n  labels: { dismiss: string; more: (count: number) => string };\n  reduce: boolean;\n  transition: object;\n}) {\n  const [flung, setFlung] = useState<-1 | 0 | 1>(0);\n  const canSwipe = swipe && toast.dismissible !== false && Boolean(onDismiss);\n  return (\n    <motion.li\n      ref={ref}\n      layout=\"position\"\n      initial={reduce ? { opacity: 0 } : { opacity: 0, y: 6 }}\n      animate={{ opacity: 1, x: 0, y: 0 }}\n      exit={\n        reduce || !flung\n          ? { opacity: 0, transition: FADE }\n          : { opacity: 0, x: flung * 160, transition: FOLD }\n      }\n      transition={transition}\n      drag={canSwipe ? \"x\" : false}\n      dragConstraints={{ left: 0, right: 0 }}\n      dragElastic={0.2}\n      onDragEnd={(_, info) => {\n        if (!canSwipe || !swiped(info)) return;\n        setFlung(info.offset.x < 0 ? -1 : 1);\n        onDismiss?.(toast.id);\n      }}\n      className={cn(\"relative bg-card\", classNames?.item)}\n    >\n      <ToastBody\n        toast={toast}\n        others={others}\n        onDismiss={onDismiss}\n        dismissLabel={labels.dismiss}\n        moreLabel={labels.more(others)}\n        classNames={classNames}\n        icons={icons}\n        renderToast={renderToast}\n        reduce={reduce}\n      />\n    </motion.li>\n  );\n}\n"},{"path":"components/motion/animated-toast-stack/toast-body.tsx","type":"util","content":"\"use client\";\n\nimport {\n  AlertCircle,\n  Bell,\n  Check,\n  Info,\n  LoaderCircle,\n  type LucideIcon,\n  X,\n} from \"lucide-react\";\nimport { AnimatePresence, motion } from \"motion/react\";\nimport type { ReactNode } from \"react\";\nimport { Tooltip } from \"@/components/motion/tooltip\";\nimport { EASE_OUT } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\nimport type { AnimatedToast, ToastClassNames, ToastStatus } from \"./types\";\n\nconst STATUS_ICON: Record<ToastStatus, LucideIcon> = {\n  neutral: Bell,\n  info: Info,\n  loading: LoaderCircle,\n  success: Check,\n  error: AlertCircle,\n};\n\n// The chip stays neutral; only the icon carries the status colour.\nconst STATUS_COLOR: Record<ToastStatus, string> = {\n  neutral: \"text-muted-foreground\",\n  info: \"text-primary\",\n  loading: \"text-primary\",\n  success: \"text-emerald-600 dark:text-emerald-400\",\n  error: \"text-destructive\",\n};\n\n// A status change (loading to success) morphs the icon and text in place.\nconst SWAP = { duration: 0.24, ease: EASE_OUT } as const;\n\nfunction Swap({\n  id,\n  reduce,\n  className = \"block min-w-0\",\n  children,\n}: {\n  id: string;\n  reduce: boolean;\n  className?: string;\n  children: ReactNode;\n}) {\n  return (\n    <AnimatePresence mode=\"popLayout\" initial={false}>\n      <motion.span\n        key={id}\n        initial={reduce ? { opacity: 0 } : { opacity: 0, y: 6, filter: \"blur(4px)\" }}\n        animate={reduce ? { opacity: 1 } : { opacity: 1, y: 0, filter: \"blur(0px)\" }}\n        exit={reduce ? { opacity: 0 } : { opacity: 0, y: -6, filter: \"blur(4px)\" }}\n        transition={SWAP}\n        className={className}\n      >\n        {children}\n      </motion.span>\n    </AnimatePresence>\n  );\n}\n\nexport interface ToastBodyProps {\n  toast: AnimatedToast;\n  /** The one-line pill: icon, title and a count of the others. No details. */\n  compact?: boolean;\n  /** How many other toasts are waiting, shown as +N. */\n  others?: number;\n  onDismiss?: (id: string) => void;\n  dismissLabel: string;\n  moreLabel: string;\n  classNames?: ToastClassNames;\n  icons?: Partial<Record<ToastStatus, ReactNode>>;\n  renderToast?: (toast: AnimatedToast) => ReactNode;\n  reduce: boolean;\n}\n\n/** One toast's content: the pill, the card, or a row of the open list. */\nexport function ToastBody({\n  toast,\n  compact = false,\n  others = 0,\n  onDismiss,\n  dismissLabel,\n  moreLabel,\n  classNames,\n  icons,\n  renderToast,\n  reduce,\n}: ToastBodyProps) {\n  if (renderToast) return <>{renderToast(toast)}</>;\n\n  const status = toast.status ?? \"neutral\";\n  const Icon = STATUS_ICON[status];\n  const icon = icons?.[status] ?? toast.icon ?? <Icon className=\"h-3.5 w-3.5\" />;\n  const canDismiss = toast.dismissible !== false && Boolean(onDismiss);\n  const details = !compact && Boolean(toast.description || toast.action);\n\n  const chip = (\n    <span\n      className={cn(\n        // A foreground tint, not bg-muted: muted is the card colour in dark mode.\n        \"relative inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-foreground/[0.06]\",\n        STATUS_COLOR[status],\n        details && \"mt-0.5\",\n        classNames?.iconWrap,\n      )}\n    >\n      {/* A flex box, not a block: a block lines the icon up on the text\n          baseline, which leaves it off centre in the chip. */}\n      <Swap id={status} reduce={reduce} className=\"flex items-center justify-center\">\n        <span className={cn(\"flex\", status === \"loading\" && \"animate-spin\")}>{icon}</span>\n      </Swap>\n    </span>\n  );\n\n  const count =\n    others > 0 ? (\n      <span className=\"inline-flex h-5 shrink-0 items-center rounded-full bg-foreground/[0.06] px-1.5 text-[11px] font-medium tabular-nums text-muted-foreground\">\n        <span aria-hidden=\"true\">+{others}</span>\n        <span className=\"sr-only\">{moreLabel}</span>\n      </span>\n    ) : null;\n\n  if (compact) {\n    return (\n      <div className=\"flex h-10 items-center gap-2 pr-3 pl-1.5\">\n        {chip}\n        <span className={cn(\"relative max-w-[15rem] truncate text-sm font-medium text-foreground\", classNames?.title)}>\n          <Swap id={`${status}-${String(toast.title)}`} reduce={reduce}>\n            {toast.title}\n          </Swap>\n        </span>\n        {count}\n      </div>\n    );\n  }\n\n  return (\n    <div className={cn(\"flex gap-3 p-3\", details ? \"items-start\" : \"items-center\")}>\n      {chip}\n      <div className={cn(\"relative min-w-0 flex-1\", classNames?.content)}>\n        {/* The count rides the title line, so the description keeps the full\n            width and wraps the same whether the island is open or not. */}\n        <div className=\"relative flex min-w-0 items-center gap-1.5\">\n          <Swap id={`${status}-${String(toast.title)}`} reduce={reduce}>\n            <span className={cn(\"block truncate text-sm font-medium leading-5 text-foreground\", classNames?.title)}>\n              {toast.title}\n            </span>\n          </Swap>\n          {count}\n        </div>\n        {toast.description ? (\n          <div className=\"relative\">\n            <Swap id={`${status}-${String(toast.description)}`} reduce={reduce}>\n              <span\n                className={cn(\n                  \"mt-0.5 line-clamp-2 block text-xs leading-4 text-muted-foreground\",\n                  classNames?.description,\n                )}\n              >\n                {toast.description}\n              </span>\n            </Swap>\n          </div>\n        ) : null}\n        {toast.action ? (\n          <button\n            type=\"button\"\n            onClick={() => toast.action?.onClick(toast)}\n            className={cn(\n              \"mt-2 inline-flex h-7 items-center rounded-full bg-foreground/[0.06] px-3 text-xs font-medium text-foreground transition-colors hover:bg-foreground/[0.1]\",\n              classNames?.action,\n            )}\n          >\n            {toast.action.label}\n          </button>\n        ) : null}\n      </div>\n      {canDismiss ? (\n        <Tooltip content={dismissLabel} side=\"top\">\n          <button\n            type=\"button\"\n            onClick={() => onDismiss?.(toast.id)}\n            aria-label={dismissLabel}\n            className={cn(\n              \"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-foreground/[0.06] hover:text-foreground\",\n              classNames?.close,\n            )}\n          >\n            <X aria-hidden=\"true\" className=\"h-3.5 w-3.5\" />\n          </button>\n        </Tooltip>\n      ) : null}\n    </div>\n  );\n}\n"},{"path":"components/motion/animated-toast-stack/types.ts","type":"util","content":"import type { ReactNode } from \"react\";\n\nexport type ToastStatus = \"neutral\" | \"info\" | \"loading\" | \"success\" | \"error\";\nexport type ToastPosition =\n  | \"top-left\"\n  | \"top-center\"\n  | \"top-right\"\n  | \"bottom-left\"\n  | \"bottom-center\"\n  | \"bottom-right\";\n\nexport type AnimatedToastAction = {\n  /** Text of the action button under the description. */\n  label: ReactNode;\n  /** Fires when the action button is pressed, with the toast it belongs to. */\n  onClick: (toast: AnimatedToast) => void;\n};\n\nexport type AnimatedToast = {\n  /** Unique key, used to update or dismiss the toast. */\n  id: string;\n  /** Main line, shown in the closed island and the open list. */\n  title: ReactNode;\n  /** Muted second line, up to 2 lines, hidden in the closed island. */\n  description?: ReactNode;\n  /** Sets the icon and its colour; `loading` spins the icon. Default: `neutral` */\n  status?: ToastStatus;\n  /** Icon in the leading chip, used when the stack's `icons` has none for the status. */\n  icon?: ReactNode;\n  /** Optional button shown under the description. */\n  action?: AnimatedToastAction;\n  /** Time before the toast closes, in ms; 0 keeps it open. Default: the stack's `defaultDuration` */\n  duration?: number;\n  /** Set to false to hide the close button. Default: true */\n  dismissible?: boolean;\n  /** When the countdown started, in ms since epoch. Set by the stack. */\n  createdAt?: number;\n};\n\nexport type ToastInput = Omit<AnimatedToast, \"id\" | \"createdAt\"> & {\n  id?: string;\n};\n\nexport type ToastClassNames = {\n  /** The anchored layer the island sits in. */\n  root?: string;\n  /** One row of the open list. */\n  item?: string;\n  /** The island itself. */\n  surface?: string;\n  /** The round chip around the status icon. */\n  iconWrap?: string;\n  /** The column holding the title, description and action. */\n  content?: string;\n  /** The title text. */\n  title?: string;\n  /** The description text. */\n  description?: string;\n  /** The action button. */\n  action?: string;\n  /** The close button. */\n  close?: string;\n  /** Not applied yet; the toast has no progress bar. */\n  progress?: string;\n};\n\nexport interface UseAnimatedToastStackOptions {\n  /** Toasts in the stack on first render. */\n  initialToasts?: ToastInput[];\n  /** Time before a toast without its own `duration` closes, in ms. Default: 4200 */\n  defaultDuration?: number;\n  /** Most toasts kept. Older ones drop off when a new one arrives. */\n  limit?: number;\n}\n"},{"path":"components/motion/animated-toast-stack/use-animated-toast-stack.ts","type":"util","content":"\"use client\";\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport type { AnimatedToast, ToastInput, UseAnimatedToastStackOptions } from \"./types\";\n\nlet idSeed = 0;\n\nfunction createToast(input: ToastInput, defaultDuration: number): AnimatedToast {\n  return {\n    duration: defaultDuration,\n    dismissible: true,\n    ...input,\n    id: input.id ?? `toast-${Date.now()}-${idSeed++}`,\n    createdAt: Date.now(),\n  };\n}\n\ntype ToastTimer = {\n  /** createdAt and duration: a change restarts the countdown. */\n  signature: string;\n  /** Time left when not running. */\n  remaining: number;\n  /** When it fires, while running. */\n  deadline: number;\n  timer: number | null;\n};\n\nexport function useAnimatedToastStack({\n  initialToasts = [],\n  defaultDuration = 4200,\n  limit,\n}: UseAnimatedToastStackOptions = {}) {\n  const toastTimers = useRef<Map<string, ToastTimer>>(new Map());\n  // Countdowns stop while the stack is hovered or focused, and while the tab\n  // is hidden, so a toast never runs out while someone is reading it or away.\n  const hold = useRef({ hovered: false, hidden: false });\n  const [toasts, setToasts] = useState<AnimatedToast[]>(() =>\n    initialToasts.map((toast) => createToast(toast, defaultDuration)),\n  );\n\n  const dismissToast = useCallback((id: string) => {\n    setToasts((current) => current.filter((toast) => toast.id !== id));\n  }, []);\n\n  const clearToasts = useCallback(() => {\n    setToasts([]);\n  }, []);\n\n  const showToast = useCallback(\n    (input: ToastInput) => {\n      const toast = createToast(input, defaultDuration);\n      setToasts((current) => {\n        const next = [...current, toast];\n        return typeof limit === \"number\" ? next.slice(-limit) : next;\n      });\n      return toast.id;\n    },\n    [defaultDuration, limit],\n  );\n\n  const updateToast = useCallback((id: string, patch: Partial<ToastInput>) => {\n    setToasts((current) =>\n      current.map((toast) =>\n        toast.id === id\n          ? {\n              ...toast,\n              ...patch,\n              id,\n              createdAt: patch.duration === undefined ? toast.createdAt : Date.now(),\n            }\n          : toast,\n      ),\n    );\n  }, []);\n\n  const run = useCallback(\n    (id: string, entry: ToastTimer) => {\n      entry.deadline = Date.now() + entry.remaining;\n      entry.timer = window.setTimeout(() => {\n        toastTimers.current.delete(id);\n        dismissToast(id);\n      }, entry.remaining);\n    },\n    [dismissToast],\n  );\n\n  const stopAll = useCallback(() => {\n    toastTimers.current.forEach((entry) => {\n      if (entry.timer === null) return;\n      window.clearTimeout(entry.timer);\n      entry.timer = null;\n      entry.remaining = Math.max(entry.deadline - Date.now(), 0);\n    });\n  }, []);\n\n  const startAll = useCallback(() => {\n    if (hold.current.hovered || hold.current.hidden) return;\n    toastTimers.current.forEach((entry, id) => {\n      if (entry.timer === null) run(id, entry);\n    });\n  }, [run]);\n\n  useEffect(() => {\n    const activeIds = new Set(toasts.map((toast) => toast.id));\n\n    toastTimers.current.forEach((entry, id) => {\n      if (!activeIds.has(id)) {\n        if (entry.timer !== null) window.clearTimeout(entry.timer);\n        toastTimers.current.delete(id);\n      }\n    });\n\n    toasts.forEach((toast) => {\n      const duration = toast.duration ?? defaultDuration;\n      const existing = toastTimers.current.get(toast.id);\n\n      if (duration <= 0) {\n        if (existing) {\n          if (existing.timer !== null) window.clearTimeout(existing.timer);\n          toastTimers.current.delete(toast.id);\n        }\n        return;\n      }\n\n      const createdAt = toast.createdAt ?? Date.now();\n      const signature = `${createdAt}:${duration}`;\n\n      if (existing?.signature === signature) {\n        return;\n      }\n\n      if (existing?.timer != null) {\n        window.clearTimeout(existing.timer);\n      }\n\n      const entry: ToastTimer = {\n        signature,\n        remaining: Math.max(duration - (Date.now() - createdAt), 0),\n        deadline: 0,\n        timer: null,\n      };\n      toastTimers.current.set(toast.id, entry);\n      // A toast that arrives while the stack is held waits its full time.\n      if (!hold.current.hovered && !hold.current.hidden) run(toast.id, entry);\n    });\n  }, [defaultDuration, run, toasts]);\n\n  useEffect(() => {\n    const onVisibility = () => {\n      hold.current.hidden = document.hidden;\n      if (document.hidden) stopAll();\n      else startAll();\n    };\n    hold.current.hidden = document.hidden;\n    document.addEventListener(\"visibilitychange\", onVisibility);\n    return () => document.removeEventListener(\"visibilitychange\", onVisibility);\n  }, [stopAll, startAll]);\n\n  useEffect(() => {\n    const timers = toastTimers.current;\n\n    return () => {\n      timers.forEach((entry) => {\n        if (entry.timer !== null) window.clearTimeout(entry.timer);\n      });\n      timers.clear();\n    };\n  }, []);\n\n  /** Stop every countdown, e.g. while the stack is open. Pass to the stack's `onPause`. */\n  const pause = useCallback(() => {\n    hold.current.hovered = true;\n    stopAll();\n  }, [stopAll]);\n\n  /** Restart them with the time each had left. Pass to the stack's `onResume`. */\n  const resume = useCallback(() => {\n    hold.current.hovered = false;\n    startAll();\n  }, [startAll]);\n\n  return useMemo(\n    () => ({\n      toasts,\n      showToast,\n      updateToast,\n      dismissToast,\n      clearToasts,\n      setToasts,\n      pause,\n      resume,\n    }),\n    [clearToasts, dismissToast, showToast, toasts, updateToast, pause, resume],\n  );\n}\n"},{"path":"components/motion/animated-toast-stack/use-content-size.ts","type":"util","content":"\"use client\";\n\nimport { useLayoutEffect, useRef, useState } from \"react\";\n\n/**\n * The natural size of whatever the island shows, so the shell can spring its\n * real width and height to it (no scale, so text never stretches). Measured\n * once before paint, then on every resize as content swaps.\n */\nexport function useContentSize<T extends HTMLElement>() {\n  const ref = useRef<T | null>(null);\n  const [size, setSize] = useState<{ width: number; height: number } | null>(null);\n\n  useLayoutEffect(() => {\n    const element = ref.current;\n    if (!element) return;\n    const measure = () => {\n      const next = { width: element.offsetWidth, height: element.offsetHeight };\n      setSize((current) =>\n        current?.width === next.width && current.height === next.height ? current : next,\n      );\n    };\n    measure();\n    if (typeof ResizeObserver === \"undefined\") return;\n    const observer = new ResizeObserver(measure);\n    observer.observe(element);\n    return () => observer.disconnect();\n  }, []);\n\n  return [ref, size] as const;\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":"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/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/notify.ts","type":"util","content":"import { defineSound } from \"./engine\";\n\n/** A small struck bell with a slow shimmer, for a new message or toast. */\nexport const notifySound = defineSound({\n  name: \"Notify\",\n  duration: 0.55,\n  room: 0.3,\n  build: (v) => {\n    v.click({ freq: 5000, q: 1.5, decay: 0.003, gain: 0.16 });\n    v.strike({ freq: 1568, material: \"bell\", bend: 1.004, decay: 0.48, gain: 0.42 });\n    // A twin 5 Hz sharp beats against it: the shimmer of a real bell.\n    v.tone({ freq: 1573, decay: 0.45, gain: 0.2 });\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/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/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":"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":"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":"components/previews/motion/animated-toast-stack.preview.tsx","type":"preview","content":"\"use client\";\n\nimport { Check, LoaderCircle, Megaphone, X } from \"lucide-react\";\nimport { useState } from \"react\";\nimport {\n  AnimatedToastStack,\n  type ToastInput,\n  type ToastPosition,\n  useAnimatedToastStack,\n} from \"@/components/motion/animated-toast-stack\";\nimport { cn } from \"@/lib/utils\";\n\nconst POSITIONS: ToastPosition[] = [\n  \"top-left\",\n  \"top-center\",\n  \"top-right\",\n  \"bottom-left\",\n  \"bottom-center\",\n  \"bottom-right\",\n];\n\nconst EXAMPLES: Array<ToastInput & { label: string }> = [\n  {\n    label: \"Title only\",\n    status: \"success\",\n    title: \"Saved\",\n    duration: 0,\n  },\n  {\n    label: \"Promise\",\n    status: \"loading\",\n    title: \"Publishing component\",\n    description: \"Bundling source, preview, and registry metadata.\",\n    duration: 0,\n  },\n  {\n    label: \"Success\",\n    status: \"success\",\n    title: \"Component published\",\n    description: \"Registry endpoint and raw source are available.\",\n  },\n  {\n    label: \"Error\",\n    status: \"error\",\n    title: \"Snapshot failed\",\n    description: \"Retry after the browser target settles.\",\n  },\n];\n\nexport function AnimatedToastStackPreview() {\n  const [position, setPosition] = useState<ToastPosition>(\"bottom-right\");\n  const {\n    toasts,\n    showToast,\n    updateToast,\n    dismissToast,\n    clearToasts,\n    pause,\n    resume,\n  } = useAnimatedToastStack({\n    defaultDuration: 3600,\n    limit: 5,\n  });\n\n  const openToast = (input: ToastInput) => {\n    const id = showToast(input);\n    if (input.status === \"loading\") {\n      window.setTimeout(() => {\n        updateToast(id, {\n          status: \"success\",\n          title: \"Publish complete\",\n          description: \"Toast updated in-place from loading to success.\",\n          duration: 3200,\n        });\n      }, 1800);\n    }\n  };\n\n  const moveStack = (nextPosition: ToastPosition) => {\n    setPosition(nextPosition);\n    showToast({\n      status: \"info\",\n      title: \"Position changed\",\n      description: `New toasts open from ${nextPosition}.`,\n    });\n  };\n\n  return (\n    <div className=\"flex min-h-72 w-full flex-col items-center justify-center gap-6\">\n      <AnimatedToastStack\n        sound\n        toasts={toasts}\n        onDismiss={dismissToast}\n        onPause={pause}\n        onResume={resume}\n        position={position}\n        placement=\"fixed\"\n        maxVisible={4}\n        icons={{\n          neutral: <Megaphone className=\"h-3.5 w-3.5\" />,\n        }}\n      />\n\n      <div className=\"flex flex-col items-center gap-2 text-center\">\n        <p className=\"text-sm font-medium text-foreground\">Open a real toast</p>\n        <p className=\"max-w-sm text-xs leading-5 text-muted-foreground\">\n          Toasts render fixed on the screen. Change position to open a toast from that edge.\n        </p>\n      </div>\n\n      <div className=\"flex flex-wrap items-center justify-center gap-2\">\n        {EXAMPLES.map((example) => {\n          return (\n            <button\n              key={example.label}\n              type=\"button\"\n              onClick={() => openToast(example)}\n              className=\"inline-flex h-9 items-center gap-2 rounded-full border border-border bg-card px-4 text-xs font-medium text-foreground transition-colors press hover:border-(--color-border-strong)\"\n            >\n              {example.status === \"loading\" ? (\n                <LoaderCircle className=\"h-3.5 w-3.5\" />\n              ) : example.status === \"success\" ? (\n                <Check className=\"h-3.5 w-3.5\" />\n              ) : (\n                <X className=\"h-3.5 w-3.5\" />\n              )}\n              {example.label}\n            </button>\n          );\n        })}\n        <button\n          type=\"button\"\n          onClick={clearToasts}\n          className=\"inline-flex h-9 items-center rounded-full px-4 text-xs font-medium text-muted-foreground press hover:bg-foreground/[0.06] hover:text-foreground\"\n        >\n          Clear\n        </button>\n      </div>\n\n      <div className=\"flex flex-wrap items-center justify-center gap-1.5\">\n        {POSITIONS.map((positionOption) => (\n          <button\n            key={positionOption}\n            type=\"button\"\n            onClick={() => moveStack(positionOption)}\n            className={cn(\n              \"rounded-full px-2.5 py-1 text-[11px] font-medium transition-colors press\",\n              position === positionOption\n                ? \"bg-primary text-primary-foreground\"\n                : \"bg-foreground/[0.04] text-muted-foreground hover:bg-foreground/[0.08] hover:text-foreground\",\n            )}\n          >\n            {positionOption}\n          </button>\n        ))}\n      </div>\n    </div>\n  );\n}\n"}]}