{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"bookshelf","type":"registry:component","title":"Bookshelf","description":"A shelf of book spines. Click one and it slides out and turns in 3D to show its cover while the others make room. Arrow keys browse, Escape puts it back, and reduced motion swaps the turn for a fade.","author":"Saurabh <saurabh10102@gmail.com>","dependencies":["clsx","motion","tailwind-merge"],"registryDependencies":[],"files":[{"path":"components/motion/bookshelf.tsx","type":"registry:component","target":"@components/motion/bookshelf.tsx","content":"\"use client\";\n// beui.dev/components/motion/bookshelf\n\nimport {\n  animate,\n  type MotionValue,\n  motion,\n  type Transition,\n  useMotionValue,\n  useReducedMotion,\n  useSpring,\n  useTransform,\n} from \"motion/react\";\nimport {\n  type KeyboardEvent,\n  type PointerEvent as ReactPointerEvent,\n  useCallback,\n  useEffect,\n  useLayoutEffect,\n  useRef,\n  useState,\n  type WheelEvent as ReactWheelEvent,\n} from \"react\";\nimport { type BookSounds, createBookSounds } from \"@/lib/book-sounds\";\nimport { EASE_OUT, SPRING_MOUSE } from \"@/lib/ease\";\nimport { useHoverCapable } from \"@/lib/hooks/use-hover-capable\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { capturePointer, releasePointer, TOUCH_GESTURE_CLASS } from \"@/lib/touch\";\nimport { cn } from \"@/lib/utils\";\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const bookshelfMessages = {\n  label: \"Bookshelf\",\n  book: \"{title}\",\n  bookWithAuthor: \"{title} by {author}\",\n};\n\nexport type BookshelfMessages = typeof bookshelfMessages;\n\nexport type BookshelfBook = {\n  id: string;\n  title: string;\n  author?: string;\n  /** Cloth color of the spine and cover. Any CSS color. */\n  color: string;\n  /** Text color on the spine and cover. Defaults to black or white, picked\n   * from `color` when it is a hex value, else white. */\n  textColor?: string;\n  /** Front cover image. Without one, the cover is typeset from the title and author. */\n  coverImage?: string;\n  /** Spine width in px. */\n  thickness?: number;\n};\n\nexport interface BookshelfProps {\n  books: BookshelfBook[];\n  /** Id of the open book, or null. Pass to control the shelf. */\n  value?: string | null;\n  defaultValue?: string | null;\n  onValueChange?: (id: string | null) => void;\n  /** Book height in px. */\n  height?: number;\n  /** Cover width as a fraction of the height. */\n  coverRatio?: number;\n  /** Space between closed books in px. */\n  gap?: number;\n  /** Extra space on each side of the open book in px. */\n  openGap?: number;\n  /** Tilt the open cover toward the mouse. Mouse only, off with reduced motion. */\n  tilt?: boolean;\n  /** Play a slide as a book comes out or goes back, and a soft tap as the\n   * mouse runs along the spines. Default false. */\n  sound?: boolean;\n  /** Override any built-in string. */\n  labels?: Partial<BookshelfMessages>;\n  className?: string;\n}\n\n// A book turning in 3D reads as a physical object, so it gets a little more\n// time than a UI transition. EASE_OUT front-loads most of each move.\n// Opening pulls the book forward first and turns it a beat later; closing\n// turns it back first and pushes it in a beat later, so the exit mirrors the\n// entry.\nconst PULL = { duration: 0.42, ease: EASE_OUT };\nconst TURN = { duration: 0.5, ease: EASE_OUT };\nconst LAG = 0.08;\nconst INSTANT = { duration: 0 };\nconst FADE = { duration: 0.2, ease: EASE_OUT };\n\nconst DEFAULT_THICKNESS = 40;\nconst PERSPECTIVE = 1600;\n// How far the open book comes toward the viewer, past the spines.\nconst PULL_DEPTH = 40;\n// Hover: a finger hooks the top of the spine, lifts it and tips it out a little.\nconst HOVER_LIFT = 8;\nconst HOVER_DEPTH = 10;\nconst HOVER_TIP = 5;\n// Largest cursor tilt of the open cover, in degrees.\nconst MAX_TILT = 6;\n// Shade at the far end of a turn: a face turned side-on to the viewer.\nconst SIDE_SHADE = 0.5;\n// A drag starts after this many px sideways, so a tap stays a tap.\nconst DRAG_SLOP = 6;\n// How far a released drag keeps gliding: velocity (px/s) times this.\nconst FLING = 0.22;\n// Past either end, the row follows the finger at this fraction.\nconst RUBBER = 0.3;\n\nfunction readableText(color: string) {\n  const hex = color.trim().match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i)?.[1];\n  if (!hex) return \"#ffffff\";\n  const full =\n    hex.length === 3\n      ? hex\n          .split(\"\")\n          .map((c) => c + c)\n          .join(\"\")\n      : hex;\n  const [r, g, b] = [0, 2, 4].map(\n    (i) => Number.parseInt(full.slice(i, i + 2), 16) / 255,\n  );\n  const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;\n  return luminance > 0.55 ? \"#1c1917\" : \"#fafaf9\";\n}\n\ntype Layout = { slots: number[]; width: number };\n\nfunction layoutShelf(\n  books: BookshelfBook[],\n  openIndex: number,\n  cover: number,\n  gap: number,\n  openGap: number,\n): Layout {\n  const slots: number[] = [];\n  let x = 0;\n  books.forEach((book, i) => {\n    const open = i === openIndex;\n    if (i > 0) x += open || i - 1 === openIndex ? openGap : gap;\n    slots.push(x);\n    x += open ? cover : (book.thickness ?? DEFAULT_THICKNESS);\n  });\n  return { slots, width: x };\n}\n\n// The focus outline is drawn on the book's faces, so it follows the 3D book\n// rather than the flat hit button that holds focus.\nconst FOCUS_RING =\n  \"group-has-[button:focus-visible]:outline-2 group-has-[button:focus-visible]:outline-offset-2 group-has-[button:focus-visible]:outline-ring\";\n\nfunction clamp(value: number, min: number, max: number) {\n  return Math.min(max, Math.max(min, value));\n}\n\nexport function Bookshelf({\n  books,\n  value,\n  defaultValue = null,\n  onValueChange,\n  height = 300,\n  coverRatio = 0.68,\n  gap = 3,\n  openGap = 16,\n  tilt = true,\n  sound = false,\n  labels,\n  className,\n}: BookshelfProps) {\n  const t = useMessages(\"bookshelf\", bookshelfMessages, labels);\n  const reduce = useReducedMotion() ?? false;\n  const canHover = useHoverCapable();\n\n  // Created on first use, so a silent shelf never touches Web Audio.\n  const soundsRef = useRef<BookSounds | null>(null);\n  const sounds = useCallback(() => {\n    if (!sound) return null;\n    soundsRef.current ??= createBookSounds();\n    return soundsRef.current;\n  }, [sound]);\n  useEffect(\n    () => () => {\n      soundsRef.current?.dispose();\n      soundsRef.current = null;\n    },\n    [],\n  );\n\n  const [uncontrolled, setUncontrolled] = useState<string | null>(defaultValue);\n  const openId = value !== undefined ? value : uncontrolled;\n  const openIndex = books.findIndex((b) => b.id === openId);\n\n  // The book that just closed keeps painting above its neighbours until it\n  // is back on the shelf, so it never slips under them mid-turn.\n  const [closingId, setClosingId] = useState<string | null>(null);\n\n  const setOpen = useCallback(\n    (id: string | null) => {\n      if (id === openId) return;\n      setClosingId(openId);\n      if (value === undefined) setUncontrolled(id);\n      onValueChange?.(id);\n      // A switch plays only the new book's slide; two at once is noise.\n      if (id === null) sounds()?.push();\n      else sounds()?.pull();\n    },\n    [openId, value, onValueChange, sounds],\n  );\n\n  const cover = Math.round(height * coverRatio);\n  const closed = layoutShelf(books, -1, cover, gap, openGap);\n  const shelf = layoutShelf(books, openIndex, cover, gap, openGap);\n\n  // Fit the closed shelf to the container; an open book that no longer fits\n  // pans the row so it stays in view.\n  const frameRef = useRef<HTMLDivElement>(null);\n  const [frameWidth, setFrameWidth] = useState(0);\n  useLayoutEffect(() => {\n    const el = frameRef.current;\n    if (!el) return;\n    setFrameWidth(el.clientWidth);\n    const ro = new ResizeObserver(([entry]) =>\n      setFrameWidth(entry.contentRect.width),\n    );\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, []);\n  const fit = frameWidth ? Math.min(1, frameWidth / closed.width) : 1;\n  const visible = frameWidth ? frameWidth / fit : shelf.width;\n  // Static per width, so the fade doesn't pop in and out as books open.\n  const canOverflow =\n    frameWidth > 0 && closed.width + cover + 2 * openGap > visible;\n  const overflowing = openIndex >= 0 && shelf.width > visible;\n\n  let rowX = -shelf.width / 2;\n  if (overflowing) {\n    const center = shelf.slots[openIndex] + cover / 2;\n    rowX = clamp(-center, visible / 2 - shelf.width, -visible / 2);\n  }\n\n  // Swipe (or scroll sideways) to see books cut off by the edges. The pan\n  // rides on top of the automatic centring and resets when a book opens.\n  const pan = useMotionValue(0);\n  const panMin = overflowing ? visible / 2 - shelf.width - rowX : 0;\n  const panMax = overflowing ? -visible / 2 - rowX : 0;\n  const panRange = useRef({ min: panMin, max: panMax, fit });\n  panRange.current = { min: panMin, max: panMax, fit };\n\n  useEffect(() => {\n    // Re-centre on every open, close or switch; the row's own move runs on\n    // the same timing, so the two read as one.\n    void openId;\n    if (pan.get() === 0) return;\n    const controls = animate(pan, 0, reduce ? INSTANT : TURN);\n    return () => controls.stop();\n  }, [openId, pan, reduce]);\n\n  const drag = useRef<{\n    id: number;\n    x: number;\n    y: number;\n    pan: number;\n    dragging: boolean;\n    lastX: number;\n    lastT: number;\n    vx: number;\n  } | null>(null);\n  const swallowClick = useRef(false);\n\n  const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>) => {\n    swallowClick.current = false;\n    // Browsers only start audio from a gesture; unlock it on the first press.\n    sounds()?.prepare();\n    if (!overflowing) return;\n    pan.stop();\n    drag.current = {\n      id: e.pointerId,\n      x: e.clientX,\n      y: e.clientY,\n      pan: pan.get(),\n      dragging: false,\n      lastX: e.clientX,\n      lastT: performance.now(),\n      vx: 0,\n    };\n  };\n\n  const onPointerMove = (e: ReactPointerEvent<HTMLDivElement>) => {\n    const d = drag.current;\n    if (!d || d.id !== e.pointerId) return;\n    const dx = e.clientX - d.x;\n    if (!d.dragging) {\n      if (Math.abs(dx) < DRAG_SLOP || Math.abs(dx) < Math.abs(e.clientY - d.y)) {\n        return;\n      }\n      d.dragging = true;\n      capturePointer(e.currentTarget, e.pointerId);\n    }\n    const { min, max, fit: scale } = panRange.current;\n    const raw = d.pan + dx / scale;\n    const over = raw > max ? raw - max : raw < min ? raw - min : 0;\n    pan.set(raw - over + over * RUBBER);\n    const now = performance.now();\n    const dt = now - d.lastT;\n    if (dt > 0) d.vx = ((e.clientX - d.lastX) / dt) * 1000;\n    d.lastX = e.clientX;\n    d.lastT = now;\n  };\n\n  const onPointerUp = (e: ReactPointerEvent<HTMLDivElement>) => {\n    const d = drag.current;\n    if (!d || d.id !== e.pointerId) return;\n    drag.current = null;\n    if (!d.dragging) return;\n    releasePointer(e.currentTarget, e.pointerId);\n    swallowClick.current = true;\n    const { min, max, fit: scale } = panRange.current;\n    const target = clamp(pan.get() + (d.vx * FLING) / scale, min, max);\n    if (reduce) pan.set(target);\n    else animate(pan, target, TURN);\n  };\n\n  const onWheel = (e: ReactWheelEvent<HTMLDivElement>) => {\n    if (!overflowing || Math.abs(e.deltaX) <= Math.abs(e.deltaY)) return;\n    pan.stop();\n    const { min, max, fit: scale } = panRange.current;\n    pan.set(clamp(pan.get() - e.deltaX / scale, min, max));\n  };\n\n  const buttonsRef = useRef<(HTMLButtonElement | null)[]>([]);\n  const onKeyDown = (e: KeyboardEvent<HTMLUListElement>) => {\n    const index = buttonsRef.current.indexOf(e.target as HTMLButtonElement);\n    if (index < 0) return;\n    let next = index;\n    if (e.key === \"ArrowRight\" || e.key === \"ArrowDown\") next = index + 1;\n    else if (e.key === \"ArrowLeft\" || e.key === \"ArrowUp\") next = index - 1;\n    else if (e.key === \"Home\") next = 0;\n    else if (e.key === \"End\") next = books.length - 1;\n    else if (e.key === \"Escape\" && openId !== null) {\n      e.preventDefault();\n      setOpen(null);\n      return;\n    } else return;\n    e.preventDefault();\n    next = clamp(next, 0, books.length - 1);\n    buttonsRef.current[next]?.focus();\n    // Browsing with a book open keeps one open, like pulling the next one out.\n    if (openId !== null) setOpen(books[next].id);\n  };\n\n  const [hoverId, setHoverId] = useState<string | null>(null);\n  // Neighbours make room as the open book turns, so they share its lag.\n  const slide = reduce\n    ? INSTANT\n    : { ...TURN, delay: openIndex >= 0 ? LAG : 0 };\n\n  return (\n    <div\n      ref={frameRef}\n      onPointerDown={onPointerDown}\n      onPointerMove={onPointerMove}\n      onPointerUp={onPointerUp}\n      onPointerCancel={onPointerUp}\n      onWheel={onWheel}\n      onClickCapture={(e) => {\n        // A swipe that ends on a book must not open it.\n        if (!swallowClick.current) return;\n        swallowClick.current = false;\n        e.preventDefault();\n        e.stopPropagation();\n      }}\n      className={cn(\n        \"relative w-full touch-pan-y [clip-path:inset(0)]\",\n        TOUCH_GESTURE_CLASS,\n        // Books cut by the edge fade out, so the row reads as continuing.\n        canOverflow &&\n          \"[mask-image:linear-gradient(90deg,transparent,#000_28px,#000_calc(100%-28px),transparent)]\",\n        className,\n      )}\n      // Room above and below for the open book coming forward and its shadow.\n      style={{ height: (height + 64) * fit }}\n    >\n      <div\n        className=\"absolute top-1/2 left-1/2\"\n        style={{\n          width: 0,\n          height,\n          marginTop: -height / 2,\n          transform: `scale(${fit})`,\n        }}\n      >\n        {/* Flat on purpose: each book is its own 3D scene, painted in z-index\n            order, so an open book always sits in front of its neighbours.\n            The vanishing point is the centre of the frame. */}\n        <ul\n          aria-label={t(\"label\")}\n          onKeyDown={onKeyDown}\n          className=\"absolute top-0 left-0 m-0 w-0 list-none p-0\"\n          style={{\n            height,\n            perspective: PERSPECTIVE,\n            perspectiveOrigin: \"0 50%\",\n          }}\n        >\n          {books.map((book, i) => (\n            <Book\n              key={book.id}\n              book={book}\n              name={\n                book.author\n                  ? t(\"bookWithAuthor\", { title: book.title, author: book.author })\n                  : t(\"book\", { title: book.title })\n              }\n              x={rowX + shelf.slots[i]}\n              slide={slide}\n              pan={pan}\n              open={i === openIndex}\n              closing={book.id === closingId}\n              hovered={canHover && hoverId === book.id}\n              tilt={tilt && canHover}\n              reduce={reduce}\n              height={height}\n              cover={cover}\n              buttonRef={(el) => {\n                buttonsRef.current[i] = el;\n              }}\n              onToggle={() => setOpen(i === openIndex ? null : book.id)}\n              onHover={(over) => {\n                setHoverId((id) => (over ? book.id : id === book.id ? null : id));\n                if (over && i !== openIndex) sounds()?.tap();\n              }}\n              onSettled={() =>\n                setClosingId((id) => (id === book.id ? null : id))\n              }\n            />\n          ))}\n        </ul>\n      </div>\n    </div>\n  );\n}\n\nfunction Book({\n  book,\n  name,\n  x,\n  slide,\n  pan,\n  open,\n  closing,\n  hovered,\n  tilt,\n  reduce,\n  height,\n  cover,\n  buttonRef,\n  onToggle,\n  onHover,\n  onSettled,\n}: {\n  book: BookshelfBook;\n  name: string;\n  x: number;\n  slide: Transition;\n  pan: MotionValue<number>;\n  open: boolean;\n  closing: boolean;\n  hovered: boolean;\n  tilt: boolean;\n  reduce: boolean;\n  height: number;\n  cover: number;\n  buttonRef: (el: HTMLButtonElement | null) => void;\n  onToggle: () => void;\n  onHover: (over: boolean) => void;\n  onSettled: () => void;\n}) {\n  const thickness = book.thickness ?? DEFAULT_THICKNESS;\n  const text = book.textColor ?? readableText(book.color);\n  const turned = open && !reduce;\n  const lifted = hovered && !open && !reduce;\n  // Offset that keeps the turned book's cover inside its slot and level with\n  // the spines: the box turns around its middle, then shifts by this much.\n  const turn = (cover - thickness) / 2;\n\n  // Each face darkens as it turns side-on to the viewer and lights up as it\n  // comes round to face them, tied to the angle so it stays in step when a\n  // turn is interrupted.\n  const angle = useMotionValue(turned ? -90 : 0);\n  const coverShade = useTransform(angle, [-90, 0], [0, SIDE_SHADE]);\n  const spineShade = useTransform(angle, [-90, 0], [SIDE_SHADE, 0]);\n\n  // Paint order follows the turn. While the cover is more than half turned\n  // toward the viewer the book is in front of its neighbours, so it paints\n  // over them (the open book over a closing one). Once it is side-on again,\n  // its cover runs back into the shelf; books left of centre show that side\n  // face, and it must stay behind the next spine instead of painting across\n  // it.\n  const frontZ = useTransform(angle, (a) => (a < -45 ? 3 : 1));\n  const backZ = useTransform(angle, (a) => (a < -45 ? 2 : 1));\n  // Reduced motion never turns: the flat open cover simply sits on top.\n  const zIndex = reduce ? (open ? 3 : 1) : open ? frontZ : closing ? backZ : 1;\n\n  const tiltX = useSpring(0, SPRING_MOUSE);\n  const tiltY = useSpring(0, SPRING_MOUSE);\n  const canTilt = tilt && turned;\n  useEffect(() => {\n    if (canTilt) return;\n    tiltX.set(0);\n    tiltY.set(0);\n  }, [canTilt, tiltX, tiltY]);\n\n  const onPointerMove = (e: ReactPointerEvent<HTMLButtonElement>) => {\n    if (!canTilt || e.pointerType !== \"mouse\") return;\n    // The hit button lies flat over the open cover, so its box is the cover's.\n    const rect = e.currentTarget.getBoundingClientRect();\n    if (!rect.width) return;\n    const px = clamp((e.clientX - rect.left) / rect.width, 0, 1);\n    const py = clamp((e.clientY - rect.top) / rect.height, 0, 1);\n    tiltY.set((px - 0.5) * 2 * MAX_TILT);\n    tiltX.set((0.5 - py) * 2 * MAX_TILT);\n  };\n\n  return (\n    <motion.li\n      className=\"group absolute top-0 left-0 [transform-style:preserve-3d]\"\n      style={{ width: thickness, height, zIndex }}\n      initial={false}\n      animate={{ x }}\n      transition={slide}\n    >\n      <motion.span\n        className=\"absolute inset-0 block [transform-style:preserve-3d]\"\n        style={{ x: pan }}\n      >\n        {/* The book is picture only. A browser hit-tests a 3D-turned cover\n            only inside its parent's box, which is the spine's, so the open\n            cover would ignore most clicks. A flat button over the book's\n            footprint (spine closed, cover open) takes the input instead. */}\n        <span\n          aria-hidden\n          className=\"pointer-events-none absolute inset-0 block [transform-style:preserve-3d]\"\n        >\n          {/* Pull: off the shelf toward the viewer, or a lift and tip on hover. */}\n          <motion.span\n            className=\"absolute top-0 left-0 block [transform-style:preserve-3d]\"\n            style={{\n              width: thickness,\n              height,\n              // Tips on the front-bottom edge, like a book hooked by its top.\n              transformOrigin: \"50% 100% 0\",\n            }}\n            initial={false}\n            animate={{\n              y: lifted ? -HOVER_LIFT : 0,\n              z: turned ? PULL_DEPTH : lifted ? HOVER_DEPTH : 0,\n              rotateX: lifted ? -HOVER_TIP : 0,\n            }}\n            transition={\n              reduce ? INSTANT : { ...PULL, delay: closing && !open ? LAG : 0 }\n            }\n            onAnimationComplete={() => {\n              if (closing && !open) onSettled();\n            }}\n          >\n            <Shadow open={open} cover={cover} height={height} reduce={reduce} />\n            {/* Tilt: the open cover leans toward the mouse. */}\n            <motion.span\n              className=\"absolute top-0 left-0 block [transform-style:preserve-3d]\"\n              style={{\n                width: thickness,\n                height,\n                rotateX: tiltX,\n                rotateY: tiltY,\n                transformOrigin: `${cover / 2}px 50% 0`,\n              }}\n            >\n              {/* Turn: spine to cover, around the middle of the book. */}\n              <motion.span\n                className=\"absolute top-0 left-0 block [transform-style:preserve-3d]\"\n                style={{\n                  width: thickness,\n                  height,\n                  transformOrigin: `${thickness / 2}px 50% ${-cover / 2}px`,\n                }}\n                initial={false}\n                animate={{\n                  x: turned ? turn : 0,\n                  z: turned ? turn : 0,\n                  rotateY: turned ? -90 : 0,\n                }}\n                transition={reduce ? INSTANT : { ...TURN, delay: open ? LAG : 0 }}\n                onUpdate={(latest) => {\n                  const value = Number.parseFloat(String(latest.rotateY));\n                  if (!Number.isNaN(value)) angle.set(value);\n                }}\n              >\n                <Spine\n                  book={book}\n                  text={text}\n                  thickness={thickness}\n                  height={height}\n                  hidden={open && reduce}\n                  shade={reduce ? null : spineShade}\n                />\n                <Cover\n                  book={book}\n                  text={text}\n                  thickness={thickness}\n                  width={cover}\n                  height={height}\n                  reduce={reduce}\n                  open={open}\n                  shade={reduce ? null : coverShade}\n                />\n              </motion.span>\n            </motion.span>\n          </motion.span>\n        </span>\n        <button\n          ref={buttonRef}\n          type=\"button\"\n          aria-label={name}\n          aria-pressed={open}\n          onClick={onToggle}\n          onPointerEnter={(e) => {\n            if (e.pointerType === \"mouse\") onHover(true);\n          }}\n          onPointerLeave={() => {\n            onHover(false);\n            tiltX.set(0);\n            tiltY.set(0);\n          }}\n          onPointerMove={onPointerMove}\n          className=\"absolute top-0 left-0 cursor-pointer border-0 bg-transparent p-0 outline-none\"\n          style={{ width: open ? cover : thickness, height }}\n        />\n      </motion.span>\n    </motion.li>\n  );\n}\n\nfunction Shadow({\n  open,\n  cover,\n  height,\n  reduce,\n}: {\n  open: boolean;\n  cover: number;\n  height: number;\n  reduce: boolean;\n}) {\n  // A soft pool under the open book that spreads as it comes off the shelf.\n  // It sits where the turned cover lands, and paints first so the book\n  // covers its top edge.\n  return (\n    <motion.span\n      className=\"pointer-events-none absolute left-0 block bg-[radial-gradient(closest-side,rgba(0,0,0,0.42),rgba(0,0,0,0))]\"\n      // A hair behind the cover's plane, so the two never fight for depth.\n      style={{ top: height - 12, width: cover, height: 28, z: -2 }}\n      initial={false}\n      animate={{ opacity: open ? 1 : 0, scaleX: open || reduce ? 1 : 0.6 }}\n      transition={reduce ? FADE : PULL}\n    />\n  );\n}\n\nfunction Shade({ opacity }: { opacity: MotionValue<number> | null }) {\n  if (!opacity) return null;\n  return (\n    <motion.span\n      className=\"pointer-events-none absolute inset-0 bg-black\"\n      style={{ opacity }}\n    />\n  );\n}\n\nfunction Spine({\n  book,\n  text,\n  thickness,\n  height,\n  hidden,\n  shade,\n}: {\n  book: BookshelfBook;\n  text: string;\n  thickness: number;\n  height: number;\n  hidden: boolean;\n  shade: MotionValue<number> | null;\n}) {\n  return (\n    <motion.span\n      className={cn(\n        \"absolute top-0 left-0 flex flex-col items-center overflow-hidden rounded-[2px] py-3 [backface-visibility:hidden]\",\n        FOCUS_RING,\n      )}\n      style={{ width: thickness, height, backgroundColor: book.color, color: text }}\n      initial={false}\n      animate={{ opacity: hidden ? 0 : 1 }}\n      transition={FADE}\n    >\n      {/* Rounded cloth: a dark rim on each edge and a soft highlight. */}\n      <span className=\"pointer-events-none absolute inset-0 bg-[linear-gradient(90deg,rgba(0,0,0,0.28),rgba(255,255,255,0.14)_28%,rgba(255,255,255,0)_55%,rgba(0,0,0,0.22))]\" />\n      <span className=\"pointer-events-none absolute inset-x-0 top-2 h-px bg-current opacity-30\" />\n      <span className=\"pointer-events-none absolute inset-x-0 bottom-2 h-px bg-current opacity-30\" />\n      {book.author ? (\n        <span className=\"relative max-h-[30%] min-h-0 overflow-hidden text-ellipsis whitespace-nowrap font-sans text-[9px] uppercase tracking-[0.14em] opacity-75 [writing-mode:vertical-rl]\">\n          {book.author}\n        </span>\n      ) : null}\n      <span className=\"relative mt-3 min-h-0 flex-1 overflow-hidden text-ellipsis whitespace-nowrap font-serif text-[13px] leading-none [writing-mode:vertical-rl]\">\n        {book.title}\n      </span>\n      <Shade opacity={shade} />\n    </motion.span>\n  );\n}\n\nfunction Cover({\n  book,\n  text,\n  thickness,\n  width,\n  height,\n  reduce,\n  open,\n  shade,\n}: {\n  book: BookshelfBook;\n  text: string;\n  thickness: number;\n  width: number;\n  height: number;\n  reduce: boolean;\n  open: boolean;\n  shade: MotionValue<number> | null;\n}) {\n  // Closed, the cover runs back from the spine's right edge into the shelf,\n  // facing right: books left of centre show it, books right of centre hide\n  // its back face. With reduced motion the book never turns: the cover lies\n  // flat and fades in over the spine instead.\n  const flat = reduce;\n  return (\n    <motion.span\n      className={cn(\n        \"absolute top-0 left-0 flex flex-col justify-between overflow-hidden rounded-r-[3px] rounded-l-[2px] p-5 text-left [backface-visibility:hidden]\",\n        FOCUS_RING,\n      )}\n      style={{\n        width,\n        height,\n        backgroundColor: book.color,\n        color: text,\n        transformOrigin: \"0 50%\",\n        transform: flat ? \"none\" : `translateX(${thickness}px) rotateY(90deg)`,\n      }}\n      initial={false}\n      animate={{ opacity: flat && !open ? 0 : 1 }}\n      transition={FADE}\n    >\n      {book.coverImage ? (\n        <img\n          src={book.coverImage}\n          alt=\"\"\n          draggable={false}\n          className=\"absolute inset-0 h-full w-full object-cover\"\n        />\n      ) : (\n        <>\n          <span className=\"relative line-clamp-4 font-serif text-xl leading-tight\">\n            {book.title}\n          </span>\n          {book.author ? (\n            <span className=\"relative font-sans text-[10px] uppercase tracking-[0.14em] opacity-75\">\n              {book.author}\n            </span>\n          ) : null}\n        </>\n      )}\n      {/* Hinge: the board folds into the spine a few px in from the edge. */}\n      <span className=\"pointer-events-none absolute inset-0 bg-[linear-gradient(90deg,rgba(0,0,0,0.35),rgba(255,255,255,0.1)_3%,rgba(0,0,0,0.12)_5%,rgba(0,0,0,0)_9%)]\" />\n      <Shade opacity={shade} />\n    </motion.span>\n  );\n}\n"},{"path":"lib/book-sounds.ts","type":"registry:lib","target":"@lib/book-sounds.ts","content":"// Synthesized bookshelf feedback, built from noise and a sine at runtime so\n// there are no audio files to ship:\n// - pull: a finger catches the spine, the book drags out against its\n//   neighbours with a grainy cloth-on-wood friction, and the board lands\n//   face-on with a soft papery thump;\n// - push: the same friction going back in, then a woody tock as it seats;\n// - tap: a dry tick as a finger runs along the spines.\n// Every sound is noise shaped by a filter and an envelope; pitched tones only\n// add a short, low body under a thump, never a melody, so nothing reads as\n// a synth.\n\nimport { getAudioContext, retainAudioContext } from \"@/lib/audio-context\";\n\nconst MASTER_GAIN = 0.2;\n// Running the pointer quickly along the spines riffles them, but not faster\n// than this, so a fast sweep stays a texture instead of a buzz.\nconst MIN_TAP_GAP = 0.045; // seconds\n// When the animation reaches the moment each sound marks. The book pulls\n// most of the way out and its cover comes round by about here...\nconst LAND_AT = 0.2;\n// ...and on the way back the push, which starts a beat after the turn,\n// seats the book about here.\nconst SEAT_AT = 0.22;\n\ntype Output = { master: GainNode; white: AudioBuffer; friction: AudioBuffer };\n\n// The context is shared page-wide (lib/audio-context.ts). The master gain and\n// the noise buffers belong to it, so they are rebuilt if it was closed and\n// recreated.\nlet output: Output | null = null;\n\nfunction whiteNoise(ctx: AudioContext, seconds: number) {\n  const length = Math.ceil(ctx.sampleRate * seconds);\n  const buffer = ctx.createBuffer(1, length, ctx.sampleRate);\n  const data = buffer.getChannelData(0);\n  for (let i = 0; i < length; i++) data[i] = Math.random() * 2 - 1;\n  return buffer;\n}\n\n/**\n * Noise with a stick-slip grain: its loudness wanders every few\n * milliseconds, with the odd louder catch, the way cloth judders across\n * wood. Filtered, it reads as friction rather than air.\n */\nfunction frictionNoise(ctx: AudioContext, seconds: number) {\n  const length = Math.ceil(ctx.sampleRate * seconds);\n  const buffer = ctx.createBuffer(1, length, ctx.sampleRate);\n  const data = buffer.getChannelData(0);\n  const grain = Math.max(1, Math.round(ctx.sampleRate * 0.003));\n  let target = 0.6;\n  let amp = 0.6;\n  for (let i = 0; i < length; i++) {\n    if (i % grain === 0) {\n      target = Math.random() < 0.06 ? 1.5 : 0.3 + Math.random() * 0.7;\n    }\n    amp += (target - amp) * 0.02;\n    data[i] = (Math.random() * 2 - 1) * amp;\n  }\n  return buffer;\n}\n\nfunction ensureOutput() {\n  const ctx = getAudioContext();\n  if (!ctx) return null;\n  if (output?.master.context !== ctx) {\n    const master = ctx.createGain();\n    master.gain.value = MASTER_GAIN;\n    master.connect(ctx.destination);\n    output = {\n      master,\n      white: whiteNoise(ctx, 0.5),\n      friction: frictionNoise(ctx, 0.6),\n    };\n  }\n  return { ctx, ...output };\n}\n\n/**\n * Filtered noise that rises over `attack` and then tails off over about\n * `decay`. The tail is a natural decay toward silence rather than a ramp to\n * a fixed floor: a ramp to near-zero falls ~80dB and is gone by its first\n * third, so a slide would sound like a click.\n */\nfunction burst(\n  ctx: AudioContext,\n  out: Output,\n  buffer: AudioBuffer,\n  at: number,\n  {\n    type,\n    frequency,\n    to,\n    q = 0.8,\n    attack,\n    decay,\n    gain,\n  }: {\n    type: BiquadFilterType;\n    frequency: number;\n    /** Sweep the filter to this frequency over the sound. */\n    to?: number;\n    q?: number;\n    attack: number;\n    decay: number;\n    gain: number;\n  },\n) {\n  const peakAt = at + attack;\n  // Three time constants of decay is about -26dB, where the sound reads as\n  // over; it keeps running to ~-42dB so the tail never cuts off.\n  const end = peakAt + decay * 1.6;\n  const source = ctx.createBufferSource();\n  source.buffer = buffer;\n  const filter = ctx.createBiquadFilter();\n  filter.type = type;\n  filter.Q.value = q;\n  filter.frequency.setValueAtTime(frequency, at);\n  if (to) filter.frequency.exponentialRampToValueAtTime(to, peakAt + decay);\n  const env = ctx.createGain();\n  env.gain.setValueAtTime(0, at);\n  env.gain.linearRampToValueAtTime(gain, peakAt);\n  env.gain.setTargetAtTime(0, peakAt, decay / 3);\n  source.connect(filter).connect(env).connect(out.master);\n  // A random start in the buffer, so repeats never sound identical.\n  const offset = Math.random() * Math.max(0, buffer.duration - (end - at) - 0.01);\n  source.start(at, offset);\n  source.stop(end + 0.02);\n  source.onended = () => env.disconnect();\n}\n\n/** A short low sine under a thump: the hollow of a board or a shelf. */\nfunction body(\n  ctx: AudioContext,\n  out: Output,\n  at: number,\n  { frequency, decay, gain }: { frequency: number; decay: number; gain: number },\n) {\n  const osc = ctx.createOscillator();\n  const env = ctx.createGain();\n  osc.type = \"sine\";\n  osc.frequency.setValueAtTime(frequency, at);\n  // Settles a touch flat, like a struck panel, without the drum-like drop.\n  osc.frequency.exponentialRampToValueAtTime(frequency * 0.88, at + decay);\n  env.gain.setValueAtTime(0.0001, at);\n  env.gain.exponentialRampToValueAtTime(gain, at + 0.003);\n  env.gain.exponentialRampToValueAtTime(0.0001, at + decay);\n  osc.connect(env).connect(out.master);\n  osc.start(at);\n  osc.stop(at + decay + 0.02);\n  osc.onended = () => env.disconnect();\n}\n\nexport interface BookSounds {\n  /** Unlock audio; call from a click, tap or key handler. */\n  prepare: () => void;\n  /** A book sliding off the shelf and turning to face the viewer. */\n  pull: () => void;\n  /** A book sliding back in and seating. */\n  push: () => void;\n  /** A finger catching a spine. */\n  tap: () => void;\n  dispose: () => void;\n}\n\n/**\n * Lazily-initialized bookshelf sounds on the page's shared AudioContext.\n * Nothing is created until the first call. Safe during SSR and without Web\n * Audio: every call becomes a silent no-op.\n */\nexport function createBookSounds(): BookSounds {\n  const release = retainAudioContext();\n  let disposed = false;\n  let lastTap = Number.NEGATIVE_INFINITY;\n  const live = () => (disposed ? null : ensureOutput());\n\n  return {\n    prepare() {\n      live();\n    },\n    pull() {\n      const out = live();\n      if (!out) return;\n      const { ctx } = out;\n      const now = ctx.currentTime;\n      // The finger catches the spine: a tiny dry tick.\n      burst(ctx, out, out.white, now, {\n        type: \"highpass\",\n        frequency: 3200,\n        attack: 0.001,\n        decay: 0.012,\n        gain: 0.3,\n      });\n      // Out it drags, brightening as it frees from its neighbours.\n      burst(ctx, out, out.friction, now + 0.008, {\n        type: \"bandpass\",\n        frequency: 850,\n        to: 2000,\n        q: 0.7,\n        attack: 0.05,\n        decay: 0.17,\n        gain: 0.75,\n      });\n      // The board comes round and lands face-on: soft, papery, a little hollow.\n      burst(ctx, out, out.white, now + LAND_AT, {\n        type: \"lowpass\",\n        frequency: 1100,\n        q: 0.5,\n        attack: 0.002,\n        decay: 0.06,\n        gain: 0.45,\n      });\n      body(ctx, out, now + LAND_AT, { frequency: 190, decay: 0.07, gain: 0.22 });\n    },\n    push() {\n      const out = live();\n      if (!out) return;\n      const { ctx } = out;\n      const now = ctx.currentTime;\n      // Back in it drags, darkening as it slides between its neighbours.\n      burst(ctx, out, out.friction, now, {\n        type: \"bandpass\",\n        frequency: 1800,\n        to: 750,\n        q: 0.7,\n        attack: 0.04,\n        decay: 0.17,\n        gain: 0.65,\n      });\n      // It seats with a woody tock: the contact click, the thump of the\n      // board on the shelf, and the shelf's low hollow under it.\n      burst(ctx, out, out.white, now + SEAT_AT, {\n        type: \"highpass\",\n        frequency: 2200,\n        attack: 0.001,\n        decay: 0.01,\n        gain: 0.35,\n      });\n      burst(ctx, out, out.white, now + SEAT_AT, {\n        type: \"lowpass\",\n        frequency: 600,\n        q: 0.6,\n        attack: 0.002,\n        decay: 0.08,\n        gain: 0.75,\n      });\n      body(ctx, out, now + SEAT_AT, { frequency: 115, decay: 0.09, gain: 0.4 });\n    },\n    tap() {\n      const out = live();\n      if (!out) return;\n      const { ctx } = out;\n      const now = ctx.currentTime;\n      if (now - lastTap < MIN_TAP_GAP) return;\n      lastTap = now;\n      // Barely there, and a little different each time, like real spines.\n      burst(ctx, out, out.friction, now, {\n        type: \"bandpass\",\n        frequency: 2600 + Math.random() * 900,\n        to: 1800,\n        attack: 0.004,\n        decay: 0.04,\n        gain: 0.3,\n      });\n    },\n    dispose() {\n      if (disposed) return;\n      disposed = true;\n      release();\n    },\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"},{"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/touch.ts","type":"registry:lib","target":"@lib/touch.ts","content":"// Shared touch primitives. iOS and iPadOS run their own gestures on top of the\n// page — the long-press selection callout and the selection it drags in with\n// it — and they win: once the platform claims a touch it cancels ours\n// mid-gesture, so a press-and-hold or a drag simply dies. Surfaces that own\n// their gesture have to opt out.\n//\n// What the two classes below cover, precisely:\n// - `-webkit-touch-callout: none` stops iOS's long-press callout. WebKit-only:\n//   it is not a property other engines have, so it is inert everywhere else.\n// - `user-select: none` stops the long-press selection on every engine,\n//   Android included, and stops a drag from painting a selection under the\n//   cursor. It is inherited, so it reaches every descendant — which is why the\n//   two classes differ only in whether they apply it unconditionally.\n// What neither covers:\n// - Chrome for Android's long-press menu on a link or an image. No CSS\n//   suppresses it; a gesture surface that wraps one needs its own\n//   `onContextMenu` with `preventDefault()`.\n// - The native drag of an `<img>` or `<a>` descendant. `-webkit-user-drag` is\n//   not inherited and plain divs and buttons are not drag sources, so setting\n//   it on the surface does nothing — the child itself needs `draggable={false}`.\n\n/**\n * Classes for a surface that *is* the control: a thumb, a drum, a stage, a\n * handle, a hold button. Selection is suppressed on every input, because a\n * drag that highlights the control's own label is wrong on a mouse too.\n * Compose with `touch-none` when the surface also owns the scroll axis — leave\n * it off when the page must still scroll from there.\n */\nexport const TOUCH_GESTURE_CLASS = \"select-none [-webkit-touch-callout:none]\";\n\n/**\n * The same opt-out for a gesture surface that wraps content the consumer owns:\n * a scroller, a context-menu trigger, a sheet header, a list row. Selection is\n * suppressed only where the platform runs its own press gestures — a coarse\n * pointer — so a mouse user can still select and copy that content. If the\n * gesture itself would paint a selection under the cursor, add `select-none`\n * for the duration of the gesture rather than reaching for\n * `TOUCH_GESTURE_CLASS`.\n *\n * `pointer: coarse` describes the *primary* pointer and nothing else, so a\n * hybrid machine reads it wrong in both directions: a tablet with a mouse\n * plugged in keeps touch as primary and loses mouse selection, and a laptop\n * with a touchscreen keeps the mouse as primary and leaves selection live\n * under a finger. No media query can answer per interaction — the query is\n * about the device, and the question is about the gesture in progress. The\n * default stays here because it is right on the machines that are one thing or\n * the other, and losing a selection is a nuisance; where the miss costs a\n * *gesture* instead, the surface pairs it with `holdSelection` on the press.\n */\nexport const TOUCH_GESTURE_CONTENT_CLASS =\n  \"[-webkit-touch-callout:none] pointer-coarse:select-none\";\n\n/**\n * Suppress selection on `element` for as long as a gesture is running on it,\n * whatever the primary pointer of the machine happens to be. Returns the\n * release. Inline, so it wins over the class above and is gone again the\n * moment the gesture ends.\n *\n * For the press gestures a native selection would otherwise steal — a\n * long-press that opens a menu. Elsewhere prefer the classes: a surface that\n * takes selection away for the whole session is a surface whose text nobody\n * can copy.\n */\nexport function holdSelection(element: HTMLElement) {\n  element.style.setProperty(\"user-select\", \"none\");\n  element.style.setProperty(\"-webkit-user-select\", \"none\");\n  return () => {\n    element.style.removeProperty(\"user-select\");\n    element.style.removeProperty(\"-webkit-user-select\");\n  };\n}\n\n/**\n * Pointer capture, best effort. WebKit throws `NotFoundError` when the pointer\n * is already gone by the time the handler runs — routine on iOS, where the\n * system can claim the touch first — and an uncaught throw takes the rest of\n * the handler, the gesture included, down with it. Touch pointers carry\n * implicit capture anyway, so losing it is never fatal.\n */\nexport function capturePointer(element: Element, pointerId: number) {\n  try {\n    element.setPointerCapture(pointerId);\n  } catch {\n    // Pointer is no longer active — implicit capture still applies on touch.\n  }\n}\n\n/** Release a capture taken with `capturePointer`, ignoring a stale pointer. */\nexport function releasePointer(element: Element, pointerId: number) {\n  try {\n    if (element.hasPointerCapture(pointerId)) {\n      element.releasePointerCapture(pointerId);\n    }\n  } catch {\n    // Capture was already dropped by the browser.\n  }\n}\n\n/**\n * Whether this event came from a pointer that is *hovering*: not a touch, and\n * not currently pressed. Which input the user is holding right now is not\n * something a device capability can answer — a touchscreen laptop hovers and\n * taps, and iPadOS reports a fine hovering pointer for a finger — so both\n * paths stay live and each handler branches on the event it was given.\n *\n * A pen resting on the glass is making contact, not hovering: `buttons` is the\n * tell, and it sends a pen tap down the same route a finger takes.\n *\n * This answers what an *enter* asks. A leave is the other half of a pair and\n * has to be read against the enter that started it — `useHoverGesture` in\n * `lib/hooks/use-hover-gesture` does that, and hover surfaces should use it\n * rather than asking this question twice.\n */\nexport const isHoveringPointer = (event: {\n  pointerType: string;\n  buttons: number;\n}) => event.pointerType !== \"touch\" && event.buttons === 0;\n"},{"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/audio-context.ts","type":"registry:lib","target":"@lib/audio-context.ts","content":"// One AudioContext for every synthesized sound on the page (lib/tick-sound.ts,\n// lib/game-sounds.ts). Browsers cap concurrent contexts, and a page can show a\n// date made of several WheelPickers next to a game, so they all share this\n// one. It is created on first use and closed once every player is disposed.\n\ntype AudioContextCtor = typeof AudioContext;\n\nlet context: AudioContext | null = null;\nlet users = 0;\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    }\n  };\n}\n\n/**\n * The shared context, created on first call and resumed if suspended. Null\n * during SSR and in browsers without Web Audio.\n */\nexport function getAudioContext(): AudioContext | 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"}]}