{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"reaction-picker","type":"registry:component","title":"Reaction Picker","description":"A reaction button whose tray grows out of it in colour; the one you pick arcs onto the button, which catches it with a burst as the count rolls.","author":"Saurabh <saurabh10102@gmail.com>","dependencies":["clsx","lucide-react","motion","tailwind-merge"],"registryDependencies":["https://beui.dev/r/theme.json"],"docs":"Reaction Picker: usage, props and types at https://beui.dev/micro-interactions/reaction-picker.md It uses beUI's theme tokens, added with this install.","files":[{"path":"components/motion/reaction-picker.tsx","type":"registry:component","target":"@components/motion/reaction-picker.tsx","content":"\"use client\";\n// beui.dev/micro-interactions/reaction-picker\n\nimport { Flame, Heart, Laugh, PartyPopper, SmilePlus, ThumbsUp } from \"lucide-react\";\nimport {\n  AnimatePresence,\n  animate,\n  motion,\n  useMotionTemplate,\n  useMotionValue,\n  useReducedMotion,\n  useSpring,\n  useTransform,\n  useVelocity,\n} from \"motion/react\";\nimport { type KeyboardEvent, type ReactNode, useEffect, useRef, useState } from \"react\";\nimport { DigitSwap } from \"@/components/motion/digit-swap\";\nimport { EASE_IN, EASE_IN_OUT, EASE_OUT, SPRING_PANEL, SPRING_PRESS } from \"@/lib/ease\";\nimport { useDismiss } from \"@/lib/hooks/use-dismiss\";\nimport { useHoverCapable } from \"@/lib/hooks/use-hover-capable\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { PresenceGate } from \"@/lib/presence-gate\";\nimport { useSound } from \"@/lib/sound\";\nimport { closeSound } from \"@/lib/sounds/close\";\nimport { openSound } from \"@/lib/sounds/open\";\nimport { selectSound } from \"@/lib/sounds/select\";\nimport { cn } from \"@/lib/utils\";\n\nexport const reactionPickerMessages = {\n  react: \"Add reaction\",\n  reacted: \"Reacted with {reaction}\",\n  reactions: \"Reactions\",\n  like: \"Like\",\n  love: \"Love\",\n  haha: \"Haha\",\n  fire: \"Fire\",\n  party: \"Party\",\n};\n\nexport type ReactionPickerMessages = typeof reactionPickerMessages;\n\nexport type Reaction = {\n  /** Unique key, used as the picker's value. */\n  id: string;\n  /** Name shown above the reaction on hover and used as its accessible name. */\n  label: string;\n  /** Icon or emoji in the tray, which flies to the trigger once picked. */\n  icon: ReactNode;\n  /** Text colour class for the icon, e.g. \"text-rose-500\". */\n  color?: string;\n  /** Classes for the button once this reaction is picked. */\n  tint?: string;\n};\n\nexport interface ReactionPickerProps {\n  /** The choices, in order. Defaults to like, love, haha, fire and party. */\n  reactions?: Reaction[];\n  /** The viewer's reaction id, or null for none. */\n  value?: string | null;\n  /** The initial reaction id when uncontrolled. Default: null */\n  defaultValue?: string | null;\n  /** Called with the picked reaction id, or null when the same one is picked again. */\n  onValueChange?: (value: string | null) => void;\n  /** Reactions from everyone else. The viewer's own is added on top. */\n  count?: number;\n  /** Override any built-in string, e.g. for translation. */\n  labels?: Partial<ReactionPickerMessages>;\n  /** Play open and close swishes for the tray and a select on a pick. Off by default; a `SoundProvider` can mute it app-wide. */\n  sound?: boolean;\n  /** Classes merged onto the root element. */\n  className?: string;\n}\n\n// Each reaction rises into the tray a beat after the one before it.\nconst STAGGER = 0.035;\nconst RISE = 12;\n// Looser than SPRING_SWAP on purpose: each icon lands with a small settle.\nconst SPRING_RISE = { type: \"spring\", stiffness: 520, damping: 22, mass: 0.6 } as const;\n// The hovered reaction lifts and grows quickly, and settles back as quickly.\nconst SPRING_HOVER = { type: \"spring\", stiffness: 600, damping: 26, mass: 0.5 } as const;\nconst OUT = { duration: 0.14, ease: EASE_OUT } as const;\n// The flight: across evenly, up slowing into the peak and down speeding out\n// of it, so it traces one smooth arc instead of stalling at the top.\nconst FLIGHT_SECONDS = 0.46;\nconst LIFT_SCALE = 1.25;\n// It lands a touch large and the button's icon settles from there.\nconst LAND_SCALE = 1.15;\n// The tray morphs out of the button: a pill clip that springs open from a\n// circle the tray's height over the icon. Near critical, so it never snaps\n// past open.\nconst SPRING_REVEAL = { type: \"spring\", stiffness: 340, damping: 32, mass: 0.8 } as const;\nconst TRAY_HEIGHT = 46;\n// The hover blob glides between reactions, stretching with its speed.\nconst SPRING_BLOB = { stiffness: 520, damping: 34, mass: 0.6 } as const;\n// One reaction slot: a 36px button plus the 2px gap.\nconst SLOT = 38;\n// The catch: the icon lands squashed and wobbles back to shape.\nconst SPRING_JELLY = { type: \"spring\", stiffness: 620, damping: 14, mass: 0.6 } as const;\nconst SQUASH = { scaleX: 1.3, scaleY: 0.78 } as const;\n\n// Sparks from the button when it catches a reaction, alternating near and far.\nconst SPARKS = Array.from({ length: 8 }, (_, index) => {\n  const angle = (index / 8) * Math.PI * 2;\n  const far = index % 2 === 0;\n  return { id: index, x: Math.cos(angle) * (far ? 18 : 13), y: Math.sin(angle) * (far ? 18 : 13), far };\n});\n\ntype Point = { x: number; y: number };\n/** A reaction in the air, and what the button showed before it was picked. */\ntype Flight = { id: number; reaction: Reaction; previous: Reaction | null; from: Point; to: Point; scale: number };\n\n/** The centre of an element, relative to an origin rect. */\nfunction centre(el: Element | null | undefined, origin: DOMRect): Point | null {\n  if (!el) return null;\n  const rect = el.getBoundingClientRect();\n  return { x: rect.left + rect.width / 2 - origin.left, y: rect.top + rect.height / 2 - origin.top };\n}\n\n/**\n * A reaction button. Pressing it grows a tray out of the button with each\n * reaction rising in turn; hovering one lifts it and shows its name. The one\n * you pick arcs down onto the button, which catches it with a pop and a burst\n * in the reaction's colour as the count rolls. Picking it again takes it back.\n */\nexport function ReactionPicker({\n  reactions: reactionsProp,\n  value: valueProp,\n  defaultValue = null,\n  onValueChange,\n  count = 0,\n  labels,\n  sound = false,\n  className,\n}: ReactionPickerProps) {\n  const t = useMessages(\"ReactionPicker\", reactionPickerMessages, labels);\n  const playOpen = useSound(openSound, { enabled: sound });\n  const playClose = useSound(closeSound, { enabled: sound });\n  const playPick = useSound(selectSound, { enabled: sound });\n  const reduce = Boolean(useReducedMotion());\n  const canHover = useHoverCapable();\n  const [internal, setInternal] = useState<string | null>(defaultValue);\n  const value = valueProp === undefined ? internal : valueProp;\n  const [open, setOpen] = useState(false);\n  const [active, setActive] = useState<string | null>(null);\n  const [flight, setFlight] = useState<Flight | null>(null);\n  // Counts catches, so each landing replays the pop and the sparks.\n  const [catches, setCatches] = useState(0);\n\n  const reactions: Reaction[] = reactionsProp ?? [\n    {\n      id: \"like\",\n      label: t(\"like\"),\n      icon: <ThumbsUp className=\"size-5\" />,\n      color: \"text-sky-500\",\n      tint: \"border-sky-500/30 bg-sky-500/10 text-sky-600 dark:text-sky-400\",\n    },\n    {\n      id: \"love\",\n      label: t(\"love\"),\n      icon: <Heart className=\"size-5\" />,\n      color: \"text-rose-500\",\n      tint: \"border-rose-500/30 bg-rose-500/10 text-rose-600 dark:text-rose-400\",\n    },\n    {\n      id: \"haha\",\n      label: t(\"haha\"),\n      icon: <Laugh className=\"size-5\" />,\n      color: \"text-amber-500\",\n      tint: \"border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400\",\n    },\n    {\n      id: \"fire\",\n      label: t(\"fire\"),\n      icon: <Flame className=\"size-5\" />,\n      color: \"text-orange-500\",\n      tint: \"border-orange-500/30 bg-orange-500/10 text-orange-600 dark:text-orange-400\",\n    },\n    {\n      id: \"party\",\n      label: t(\"party\"),\n      icon: <PartyPopper className=\"size-5\" />,\n      color: \"text-emerald-500\",\n      tint: \"border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400\",\n    },\n  ];\n  const chosen = reactions.find((reaction) => reaction.id === value) ?? null;\n  // While a reaction is in the air, the button still shows what it had, so\n  // nothing changes on it until the catch.\n  const shown = flight ? flight.previous : chosen;\n\n  const rootRef = useRef<HTMLDivElement>(null);\n  const triggerRef = useRef<HTMLButtonElement>(null);\n  const iconRef = useRef<HTMLSpanElement>(null);\n  const optionRefs = useRef<(HTMLButtonElement | null)[]>([]);\n  const optionIconRefs = useRef<(HTMLSpanElement | null)[]>([]);\n\n  // The tray's reveal: 1 is a circle over the icon, 0 is fully open. It\n  // springs open on open and morphs back into the circle as the tray leaves,\n  // so it is already closed when the next tray mounts and never flashes open\n  // for a frame (motion writes a reset value only on its next frame).\n  const reveal = useMotionValue(reduce ? 0 : 1);\n  const trayClip = useMotionTemplate`inset(0 calc((100% - ${TRAY_HEIGHT}px) * ${reveal}) 0 0 round 999px)`;\n  useEffect(() => {\n    if (reduce) {\n      reveal.jump(0);\n      return;\n    }\n    const controls = open ? animate(reveal, 0, SPRING_REVEAL) : animate(reveal, 1, OUT);\n    return () => controls.stop();\n  }, [open, reduce, reveal]);\n\n  // The hover blob: springs between slots and stretches with its speed.\n  const blobX = useSpring(0, SPRING_BLOB);\n  const blobSpeed = useVelocity(blobX);\n  const blobScaleX = useTransform(blobSpeed, (speed) => 1 + Math.min(Math.abs(speed) / 2200, 0.45));\n  const blobScaleY = useTransform(blobScaleX, (stretch) => 1 - (stretch - 1) * 0.35);\n  const activeIndex = reactions.findIndex((reaction) => reaction.id === active);\n  // Move the blob with the hover: it appears in place, then glides.\n  const hover = (id: string) => {\n    const index = reactions.findIndex((reaction) => reaction.id === id);\n    if (active === null || reduce) blobX.jump(index * SLOT);\n    else blobX.set(index * SLOT);\n    setActive(id);\n  };\n\n  // Close and hand focus back to the button when it was inside the tray.\n  const close = () => {\n    if (rootRef.current?.contains(document.activeElement)) triggerRef.current?.focus();\n    setOpen(false);\n    setActive(null);\n  };\n  // Closing without a pick; a pick closes quietly behind its own sound.\n  const dismiss = () => {\n    playClose();\n    close();\n  };\n  useDismiss(open, dismiss, rootRef);\n\n  // Opening by keyboard moves focus to the current reaction, or the first.\n  const focusOnOpen = useRef(false);\n  const startIndex = Math.max(0, reactions.findIndex((reaction) => reaction.id === value));\n  useEffect(() => {\n    if (!open || !focusOnOpen.current) return;\n    focusOnOpen.current = false;\n    optionRefs.current[startIndex]?.focus();\n  }, [open, startIndex]);\n\n  const pick = (reaction: Reaction, index: number) => {\n    const next = reaction.id === value ? null : reaction.id;\n    playPick({ pitch: next ? 1.1 : 0.85 });\n    // Measure both ends now, from the event, while the tray is still open:\n    // the icon itself, so a lifted one leaves from where it is drawn.\n    const root = rootRef.current?.getBoundingClientRect();\n    const source = optionIconRefs.current[index];\n    const from = root && centre(source, root);\n    const to = root && centre(iconRef.current, root);\n    if (next && from && to && !reduce) {\n      const scale = active === reaction.id ? LIFT_SCALE : 1;\n      setFlight({ id: Date.now(), reaction, previous: chosen, from, to, scale });\n      // The flying copy takes over from here; hide the original so it does\n      // not shrink away inside the closing tray beside it.\n      if (source) source.style.visibility = \"hidden\";\n    } else if (next) setCatches((value) => value + 1);\n    if (valueProp === undefined) setInternal(next);\n    onValueChange?.(next);\n    close();\n  };\n\n  const onTrayKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n    const index = optionRefs.current.indexOf(document.activeElement as HTMLButtonElement);\n    const step = event.key === \"ArrowRight\" ? 1 : event.key === \"ArrowLeft\" ? -1 : 0;\n    if (!step || index === -1) return;\n    event.preventDefault();\n    optionRefs.current[(index + step + reactions.length) % reactions.length]?.focus();\n  };\n\n  const total = count + (value ? 1 : 0);\n\n  return (\n    <div ref={rootRef} className={cn(\"relative inline-flex\", className)}>\n      <motion.button\n        ref={triggerRef}\n        type=\"button\"\n        aria-haspopup=\"true\"\n        aria-expanded={open}\n        aria-label={chosen ? t(\"reacted\", { reaction: chosen.label }) : t(\"react\")}\n        whileTap={reduce ? undefined : { scale: 0.94 }}\n        transition={SPRING_PRESS}\n        onClick={() => {\n          if (open) return dismiss();\n          playOpen();\n          setOpen(true);\n        }}\n        onKeyDown={(event) => {\n          if (event.key === \"Enter\" || event.key === \" \" || event.key === \"ArrowUp\") focusOnOpen.current = true;\n          if (event.key === \"ArrowUp\" && !open) {\n            event.preventDefault();\n            playOpen();\n            setOpen(true);\n          }\n        }}\n        className={cn(\n          \"relative inline-flex h-9 items-center gap-1.5 rounded-full border pr-3.5 pl-2.5 text-sm font-medium tabular-nums transition-colors duration-200\",\n          \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50\",\n          shown?.tint ?? \"border-border text-muted-foreground hover:bg-muted/60 hover:text-foreground\",\n        )}\n      >\n        <span ref={iconRef} aria-hidden=\"true\" className=\"relative inline-flex size-5 items-center justify-center\">\n          {/* The catch: sparks in the reaction's colour from where it lands. */}\n          {catches > 0 && !reduce && chosen ? (\n            <span key={catches} className={cn(\"pointer-events-none absolute inset-0\", chosen.color)}>\n              {SPARKS.map((spark) => (\n                <motion.span\n                  key={spark.id}\n                  className={cn(\"absolute top-1/2 left-1/2 rounded-full bg-current\", spark.far ? \"size-1\" : \"size-[3px]\")}\n                  style={{ translate: \"-50% -50%\" }}\n                  initial={{ opacity: 0, x: 0, y: 0 }}\n                  animate={{ opacity: [0, 1, 0], x: spark.x, y: spark.y }}\n                  transition={{ duration: 0.5, ease: EASE_OUT, delay: spark.far ? 0 : 0.04 }}\n                />\n              ))}\n            </span>\n          ) : null}\n          <AnimatePresence initial={false} mode=\"popLayout\">\n            <motion.span\n              key={`${shown?.id ?? \"none\"}-${shown ? catches : 0}`}\n              className=\"inline-flex\"\n              // A caught reaction takes over from the flying copy at its size\n              // and settles; the smiley comes back from above.\n              initial={\n                reduce\n                  ? { opacity: 0 }\n                  : shown\n                    ? { opacity: 1, scaleX: LAND_SCALE * SQUASH.scaleX, scaleY: LAND_SCALE * SQUASH.scaleY, y: 0 }\n                    : { opacity: 0, scaleX: 0.5, scaleY: 0.5, y: -6 }\n              }\n              animate={{ opacity: 1, scaleX: 1, scaleY: 1, y: 0 }}\n              exit={\n                reduce\n                  ? { opacity: 0, transition: OUT }\n                  : { opacity: 0, y: 6, scaleX: 0.8, scaleY: 0.8, transition: OUT }\n              }\n              // A caught reaction wobbles back from the squash; the smiley just settles.\n              transition={shown ? SPRING_JELLY : SPRING_PRESS}\n            >\n              {shown ? shown.icon : <SmilePlus className=\"size-5\" />}\n            </motion.span>\n          </AnimatePresence>\n        </span>\n        {total > 0 ? <DigitSwap value={total} direction={value ? \"up\" : \"down\"} /> : null}\n      </motion.button>\n\n      <AnimatePresence>\n        {open ? (\n          <PresenceGate>\n            {({ gate }) => (\n              <motion.div\n                role=\"group\"\n                aria-label={t(\"reactions\")}\n                onKeyDown={onTrayKeyDown}\n                onPointerLeave={() => setActive(null)}\n                // Rises out of the button's icon and sinks back into it: 20px in\n                // (padding plus half the icon), 26px below the tray (gap plus half the button).\n                style={{ transformOrigin: \"20px calc(100% + 26px)\", clipPath: trayClip, ...gate.style }}\n                inert={gate.inert}\n                className=\"absolute bottom-full left-0 z-20 mb-2 flex items-center gap-0.5 rounded-full border border-border bg-background p-1\"\n                initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.85, y: 8 }}\n                animate={{ opacity: 1, scale: 1, y: 0 }}\n                exit={reduce ? { opacity: 0, transition: OUT } : { opacity: 0, scale: 0.85, y: 6, transition: OUT }}\n                transition={{ ...SPRING_PANEL, opacity: { duration: 0.12, ease: EASE_OUT } }}\n              >\n                {/* The hover blob, gliding under whichever reaction is lifted. */}\n                <motion.span\n                  aria-hidden=\"true\"\n                  className=\"pointer-events-none absolute top-1 left-1 size-9 rounded-full bg-muted\"\n                  style={{ x: blobX, scaleX: blobScaleX, scaleY: blobScaleY }}\n                  initial={false}\n                  animate={{ opacity: active ? 1 : 0 }}\n                  transition={{ duration: 0.14, ease: EASE_OUT }}\n                />\n                {reactions.map((reaction, index) => {\n                  const lifted = active === reaction.id && !reduce;\n                  // The reactions either side lean in a little, like a dock.\n                  const near = !reduce && activeIndex !== -1 && Math.abs(index - activeIndex) === 1;\n                  return (\n                    <motion.button\n                      key={reaction.id}\n                      ref={(node) => {\n                        optionRefs.current[index] = node;\n                      }}\n                      type=\"button\"\n                      aria-label={reaction.label}\n                      aria-pressed={reaction.id === value}\n                      tabIndex={index === startIndex ? 0 : -1}\n                      onClick={() => pick(reaction, index)}\n                      onPointerEnter={() => canHover && hover(reaction.id)}\n                      onFocus={() => hover(reaction.id)}\n                      onBlur={() => setActive((current) => (current === reaction.id ? null : current))}\n                      className={cn(\n                        \"relative inline-flex size-9 items-center justify-center rounded-full transition-colors\",\n                        \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50\",\n                        reaction.color,\n                        reaction.id === value && \"bg-muted\",\n                      )}\n                      initial={{ opacity: 0, y: reduce ? 0 : RISE }}\n                      animate={{ opacity: 1, y: 0 }}\n                      transition={{\n                        opacity: { duration: 0.12, ease: EASE_OUT, delay: reduce ? 0 : index * STAGGER },\n                        y: { ...SPRING_RISE, delay: reduce ? 0 : index * STAGGER },\n                      }}\n                    >\n                      {/* Only the icon lifts and grows, so the name chip stays crisp. */}\n                      <motion.span\n                        ref={(node) => {\n                          optionIconRefs.current[index] = node;\n                        }}\n                        className=\"inline-flex\"\n                        initial={false}\n                        animate={{ y: lifted ? -6 : near ? -2 : 0, scale: lifted ? LIFT_SCALE : near ? 1.08 : 1 }}\n                        transition={SPRING_HOVER}\n                      >\n                        {reaction.icon}\n                      </motion.span>\n                      {/* The name rides above the lifted reaction. */}\n                      <AnimatePresence>\n                        {lifted ? (\n                          <motion.span\n                            aria-hidden=\"true\"\n                            className=\"pointer-events-none absolute bottom-full left-1/2 mb-2.5 rounded-full border border-border bg-background px-2 py-0.5 text-[11px] font-medium whitespace-nowrap text-foreground\"\n                            style={{ translate: \"-50% 0\" }}\n                            initial={{ opacity: 0, y: 4 }}\n                            animate={{ opacity: 1, y: 0 }}\n                            exit={{ opacity: 0, y: 4, transition: OUT }}\n                            transition={SPRING_HOVER}\n                          >\n                            {reaction.label}\n                          </motion.span>\n                        ) : null}\n                      </AnimatePresence>\n                    </motion.button>\n                  );\n                })}\n              </motion.div>\n            )}\n          </PresenceGate>\n        ) : null}\n      </AnimatePresence>\n\n      {/* The picked reaction in the air: across on one curve, up then down on another. */}\n      {flight ? (\n        <motion.span\n          key={flight.id}\n          aria-hidden=\"true\"\n          className={cn(\"pointer-events-none absolute top-0 left-0 z-30 inline-flex\", flight.reaction.color)}\n          style={{ translate: \"-50% -50%\" }}\n          initial={{ x: flight.from.x, y: flight.from.y, scale: flight.scale }}\n          animate={{\n            x: flight.to.x,\n            y: [flight.from.y, Math.min(flight.from.y, flight.to.y) - 18, flight.to.y],\n            scale: [flight.scale, 1.4, LAND_SCALE],\n            // It tips back on the way up and levels out to land.\n            rotate: [0, -12, 0],\n          }}\n          transition={{\n            x: { duration: FLIGHT_SECONDS, ease: EASE_IN_OUT },\n            y: { duration: FLIGHT_SECONDS, ease: [EASE_OUT, EASE_IN], times: [0, 0.4, 1] },\n            scale: { duration: FLIGHT_SECONDS, ease: [EASE_OUT, EASE_IN], times: [0, 0.4, 1] },\n            rotate: { duration: FLIGHT_SECONDS, ease: [EASE_OUT, EASE_IN_OUT], times: [0, 0.4, 1] },\n          }}\n          onAnimationComplete={() => {\n            setFlight(null);\n            setCatches((value) => value + 1);\n          }}\n        >\n          {flight.reaction.icon}\n        </motion.span>\n      ) : null}\n    </div>\n  );\n}\n"},{"path":"components/motion/digit-swap.tsx","type":"registry:component","target":"@components/motion/digit-swap.tsx","content":"\"use client\";\n// beui.dev/micro-interactions/reaction-picker\n\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { EASE_OUT } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\nexport type DigitSwapDirection = \"up\" | \"down\";\n\nexport interface DigitSwapProps {\n  /** Numeric or masked value rendered in fixed character slots. */\n  value: string | number;\n  /** Replays every glyph when the value itself contains unchanged characters. */\n  animationKey?: string | number;\n  /** Direction the next glyph enters from. */\n  direction?: DigitSwapDirection;\n  /** Per-glyph transition duration in seconds. */\n  duration?: number;\n  /** Delay in seconds between neighboring glyphs. */\n  stagger?: number;\n  /** Number of final characters that receive `suffixClassName`. */\n  suffixLength?: number;\n  /** Classes merged onto the root element. */\n  className?: string;\n  /** Classes merged onto every animated character. */\n  glyphClassName?: string;\n  /** Classes added to the last `suffixLength` characters. */\n  suffixClassName?: string;\n}\n\ntype GlyphMotionContext = {\n  direction: DigitSwapDirection;\n  reduceMotion: boolean;\n};\n\nconst GLYPH_VARIANTS = {\n  enter: ({ direction, reduceMotion }: GlyphMotionContext) => ({\n    opacity: 0,\n    transform: reduceMotion\n      ? \"none\"\n      : `translateY(${direction === \"up\" ? \"45%\" : \"-45%\"})`,\n  }),\n  visible: {\n    opacity: 1,\n    transform: \"translateY(0%)\",\n  },\n  exit: ({ direction, reduceMotion }: GlyphMotionContext) => ({\n    opacity: 0,\n    transform: reduceMotion\n      ? \"none\"\n      : `translateY(${direction === \"up\" ? \"-45%\" : \"45%\"})`,\n  }),\n};\n\n/**\n * Fixed-slot digits and mask glyphs that roll when their value changes.\n *\n * Each slot holds an invisible in-flow copy of its character, so the slot has\n * a real text baseline (it lines up with neighbouring text) and punctuation\n * keeps its natural width. Digits use a fixed 1ch slot so rolls never jitter.\n * Slots clip with `clip-path`, which, unlike `overflow: hidden`, leaves the\n * baseline alone.\n */\nexport function DigitSwap({\n  value,\n  animationKey,\n  direction = \"up\",\n  duration = 0.18,\n  stagger = 0.006,\n  suffixLength = 0,\n  className,\n  glyphClassName,\n  suffixClassName,\n}: DigitSwapProps) {\n  const reduceMotion = useReducedMotion() ?? false;\n  const text = String(value);\n  const suffixStart = Math.max(0, text.length - Math.max(0, suffixLength));\n  const motionContext: GlyphMotionContext = { direction, reduceMotion };\n  const glyphs = Array.from(text, (character, position) => ({\n    character,\n    id: `glyph-${position}`,\n    position,\n  }));\n\n  return (\n    <span\n      data-slot=\"digit-swap\"\n      data-direction={direction}\n      className={cn(\"inline-flex items-baseline whitespace-nowrap\", className)}\n    >\n      <span className=\"sr-only\">{text}</span>\n      <span aria-hidden=\"true\" className=\"inline-flex items-baseline\">\n        {glyphs.map(({ character, id, position }) => {\n          if (character === \" \") {\n            return <span key={id} className=\"inline-block w-[0.7ch]\" />;\n          }\n\n          const glyphKey =\n            animationKey === undefined\n              ? `${id}-${character}`\n              : `${id}-${character}-${animationKey}`;\n\n          return (\n            <span\n              key={id}\n              data-slot=\"digit-swap-glyph\"\n              className={cn(\n                \"relative inline-block h-[1.1em] shrink-0 leading-[1.1em] [clip-path:inset(0)]\",\n                /\\d/.test(character) && \"w-[1ch] text-center\",\n              )}\n            >\n              <span className=\"invisible\">{character}</span>\n              <AnimatePresence initial={false} custom={motionContext}>\n                <motion.span\n                  key={glyphKey}\n                  custom={motionContext}\n                  variants={GLYPH_VARIANTS}\n                  initial=\"enter\"\n                  animate=\"visible\"\n                  exit=\"exit\"\n                  transition={{\n                    duration: reduceMotion ? Math.min(duration, 0.12) : duration,\n                    delay: reduceMotion ? 0 : position * stagger,\n                    ease: EASE_OUT,\n                  }}\n                  className={cn(\n                    \"absolute inset-0 flex items-center justify-center leading-none\",\n                    glyphClassName,\n                    position >= suffixStart ? suffixClassName : undefined,\n                  )}\n                >\n                  {character}\n                </motion.span>\n              </AnimatePresence>\n            </span>\n          );\n        })}\n      </span>\n    </span>\n  );\n}\n"},{"path":"lib/ease.ts","type":"registry:lib","target":"@lib/ease.ts","content":"// Shared motion tokens. Easing curves mirror the CSS custom properties in\n// globals.css; springs are the canonical physics used across components.\n// Strong custom variants — defaults like `ease-in`/`ease-out` feel weak.\n\nexport const EASE_OUT = [0.16, 1, 0.3, 1] as const;\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/hooks/use-dismiss.ts","type":"registry:hook","target":"@lib/hooks/use-dismiss.ts","content":"\"use client\";\n\nimport { type RefObject, useEffect, useLayoutEffect, useRef } from \"react\";\nimport { inOtherLayer, type Layer, openLayer, ownsEscape } 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      // 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-capable.ts","type":"registry:hook","target":"@lib/hooks/use-hover-capable.ts","content":"\"use client\";\n\nimport { useEffect, useState } from \"react\";\n\n/**\n * Returns true only on devices that have a true hover (mouse / trackpad).\n * Touch devices fire phantom `:hover` on tap that sticks until tap-elsewhere\n * — gate hover-only effects (scale lifts, magnetic pulls) behind this.\n */\nexport function useHoverCapable() {\n  const [canHover, setCanHover] = useState(false);\n\n  useEffect(() => {\n    if (typeof window === \"undefined\" || !window.matchMedia) return;\n    const mq = window.matchMedia(\"(hover: hover) and (pointer: fine)\");\n    const update = () => setCanHover(mq.matches);\n    update();\n    mq.addEventListener?.(\"change\", update);\n    return () => mq.removeEventListener?.(\"change\", update);\n  }, []);\n\n  return canHover;\n}\n"},{"path":"lib/i18n.tsx","type":"registry:lib","target":"@lib/i18n.tsx","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/presence-gate.tsx","type":"registry:lib","target":"@lib/presence-gate.tsx","content":"\"use client\";\n\nimport { useIsPresent } from \"motion/react\";\nimport type { ReactNode } from \"react\";\n\nexport interface PresenceGateRenderProps {\n  /**\n   * False from the render that starts the exit animation onward. An overlay\n   * kept in the tree by `AnimatePresence` is still the topmost thing on the\n   * page, so anything it decides from `open` alone stays true for the whole\n   * exit — this is the boolean that already knows the overlay is leaving.\n   */\n  isPresent: boolean;\n  /**\n   * Spread onto every layer that takes pointer events while the overlay is\n   * open. Interaction releases in the same commit that starts the exit while\n   * the visual exit keeps playing: pointer events stop landing, and `inert`\n   * drops the subtree from focus order, from tab order and from the\n   * accessibility tree — an exiting dialog is not a dialog you can still type\n   * into. A layer that never takes pointer events (a wrapper that only centres\n   * the panel) takes `inert={!isPresent}` alone, so its own\n   * `pointer-events-none` is not overwritten.\n   */\n  gate: {\n    inert: boolean;\n    style: { pointerEvents: \"auto\" | \"none\" };\n  };\n}\n\nexport interface PresenceGateProps {\n  children: (props: PresenceGateRenderProps) => ReactNode;\n}\n\n/**\n * Reads the presence of the subtree it renders and hands it down.\n *\n * `useIsPresent` only answers inside the `AnimatePresence` subtree, and the\n * components that own an overlay render the `AnimatePresence` themselves, so\n * the boolean has to be read one component further down: this is that\n * component, and the render prop is how it reaches the layers.\n */\nexport function PresenceGate({ children }: PresenceGateProps) {\n  const isPresent = useIsPresent();\n\n  return children({\n    isPresent,\n    gate: {\n      inert: !isPresent,\n      style: { pointerEvents: isPresent ? \"auto\" : \"none\" },\n    },\n  });\n}\n"},{"path":"lib/sound.tsx","type":"registry:lib","target":"@lib/sound.tsx","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/close.ts","type":"registry:lib","target":"@lib/sounds/close.ts","content":"import { defineSound } from \"./engine\";\n\n/** The open whoosh falling and a little quicker, settling with a soft low tap, for things closing. */\nexport const closeSound = defineSound({\n  name: \"Close\",\n  duration: 0.16,\n  room: 0.18,\n  build: (v) => {\n    v.noise({ freq: 2600, to: 700, q: 1.2, attack: 0.012, decay: 0.09, gain: 0.7 });\n    v.click({ freq: 1400, q: 1.2, at: 0.05, decay: 0.006, gain: 0.2 });\n    v.strike({ freq: 260, material: \"wood\", bend: 1.2, at: 0.05, decay: 0.045, gain: 0.3 });\n  },\n});\n"},{"path":"lib/sounds/open.ts","type":"registry:lib","target":"@lib/sounds/open.ts","content":"import { defineSound } from \"./engine\";\n\n/** A soft rising whoosh that lands with a light glass touch, for menus, popovers and dialogs opening. */\nexport const openSound = defineSound({\n  name: \"Open\",\n  duration: 0.2,\n  room: 0.2,\n  build: (v) => {\n    v.noise({ freq: 600, to: 2600, q: 1.2, attack: 0.035, decay: 0.11, gain: 0.75 });\n    v.noise({ freq: 4500, to: 6000, q: 1, attack: 0.03, decay: 0.07, gain: 0.05 });\n    v.strike({ freq: 1320, material: \"glass\", at: 0.05, decay: 0.07, gain: 0.12 });\n  },\n});\n"},{"path":"lib/sounds/select.ts","type":"registry:lib","target":"@lib/sounds/select.ts","content":"import { defineSound } from \"./engine\";\n\n/** A crisp detent, like a dial clicking into a notch, for tabs, segmented controls and menu choices. */\nexport const selectSound = defineSound({\n  name: \"Select\",\n  duration: 0.05,\n  room: 0.08,\n  build: (v) => {\n    v.click({ freq: 4500, q: 2.5, decay: 0.003, gain: 0.45 });\n    v.strike({ freq: 1700, material: \"metal\", decay: 0.028, gain: 0.3 });\n    v.strike({ freq: 520, material: \"wood\", bend: 1.15, decay: 0.012, gain: 0.25 });\n  },\n});\n"},{"path":"lib/utils.ts","type":"registry:lib","target":"@lib/utils.ts","content":"import { clsx, type ClassValue } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs))\n}\n"},{"path":"lib/layers.ts","type":"registry:lib","target":"@lib/layers.ts","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/audio-context.ts","type":"registry:lib","target":"@lib/audio-context.ts","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":"registry:lib","target":"@lib/sounds/engine.ts","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"}]}