{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "album-rail",
  "title": "Album Rail",
  "description": "A fanned rail of album sleeves that turn away in 3D, with a record that slides out and spins on play, a tick ruler, swipe, wheel and arrow keys. No dependencies.",
  "files": [
    {
      "path": "registry/mewo/ui/album-rail.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { cn } from \"@/lib/utils\"\n\nexport interface AlbumRailItem {\n  /** Album title, shown in the caption. */\n  title: string\n  /** Artist, shown under the title. */\n  artist: string\n  /** Image URL for the sleeve. Also printed on the record's centre label. */\n  cover: string\n  /** Tint for the play button. Picked from the cover when left out. */\n  color?: string\n}\n\nexport interface AlbumRailProps extends Omit<React.ComponentProps<\"div\">, \"children\" | \"onChange\"> {\n  /** Albums, in order. */\n  albums?: AlbumRailItem[]\n  /** Index of the sleeve shown first. */\n  initialIndex?: number\n  /** Largest sleeve edge in pixels. Shrinks to fit narrow containers. */\n  size?: number\n  /** How many sleeves stay visible on each side of the front one. */\n  visible?: number\n  /** Y rotation of the side sleeves, in degrees. */\n  turn?: number\n  /** Extra in-plane tilt per step away from the front, in degrees: the \"hand of cards\" look. */\n  fan?: number\n  /** Wrap around at the ends. Needs three albums or more. */\n  loop?: boolean\n  /** Advance every this many milliseconds while nothing is playing. `false` turns it off. */\n  autoplay?: number | false\n  /** Hold autoplay while a mouse is over the rail. */\n  pauseOnHover?: boolean\n  /** Show the title and artist under the front sleeve. */\n  showCaption?: boolean\n  /** Show the previous, tick ruler, play and next bar under the caption. */\n  showControls?: boolean\n  /** Play button tint when the cover colour can't be read (a cross-origin image served without CORS, say). */\n  accent?: string\n  /** Called with the front album's index and the album whenever it changes. */\n  onChange?: (index: number, album: AlbumRailItem) => void\n  /** Called when a record starts or stops playing, with the front album's index and the album. */\n  onPlayChange?: (playing: boolean, index: number, album: AlbumRailItem) => void\n}\n\nexport const DEFAULT_ALBUMS: AlbumRailItem[] = [\n  [\"Paper Lanterns\", \"Juniper Hale\"],\n  [\"Neon Orchard\", \"The Glass Foxes\"],\n  [\"Quiet Engines\", \"Ottilie Marsh\"],\n  [\"Salt & Static\", \"Tin Harbour\"],\n  [\"Midnight Atlas\", \"Remy Okafor\"],\n  [\"Soft Machinery\", \"Velour Club\"],\n  [\"Golden Hour Drive\", \"Cassia Moon\"],\n  [\"Northbound Lines\", \"Pine & Ash\"],\n  [\"Echoes in Blue\", \"Theo Laurent\"],\n  [\"Wild Signal\", \"Kite Season\"],\n].map(([title, artist], index) => ({ title, artist, cover: `https://cataas.com/cat/${[\"JazIRPFqDYCXNJaA\", \"ngfJ6lSzEdJQ9GO8\", \"1wpap8yckt96vOoU\", \"2wfWxhA4oS7bGUFW\", \"2XYz3V6PILrrvZn6\", \"43hNBvUK9fAKsHv3\", \"4v9FDCzfJ9WkSn2V\", \"5RbMoA2duqnmB8ez\", \"98qvAp6CYXZMLztN\", \"SXLh7Co7iYYEVVgi\"][index]}` }))\n\n// Fan geometry, in units of the sleeve edge. The first neighbour's centre sits SPREAD from the front one's,\n// the second sits STACK further out, and every gap after that is DECAY times the one before.\nconst SPREAD = 0.51\nconst STACK = 0.22\nconst DECAY = 0.88\n// Side sleeves sink a little, so their bottoms roughly line up with the front one's.\nconst LIFT_NEAR = 0.03\nconst LIFT_FAR = 0.065\n// The first step away shrinks a sleeve by SHRINK_NEAR; further steps approach SHRINK_FAR more, by SHRINK_DECAY a step.\nconst SHRINK_NEAR = 0.16\nconst SHRINK_FAR = 0.36\nconst SHRINK_DECAY = 0.62\n// Steps past the first tilt by this share of `fan` each.\nconst FAN_FAR = 0.6\n// Sleeves darken as they move away from the front: this much for the first step, this much per further step, at most SHADE_MAX.\nconst SHADE_NEAR = 0.22\nconst SHADE_FAR = 0.1\nconst SHADE_MAX = 0.6\n// The front sleeve stacks on top, and every tenth of a step away sits one layer lower.\nconst Z_FRONT = 1000\nconst Z_STEPS = 10\n// While a record plays the front sleeve slides PLAY_SHIFT to the left, its record slides RECORD_OUT out to the right,\n// and the neighbours on either side move PLAY_SPREAD outwards to make room.\nconst PLAY_SHIFT = 0.29\nconst PLAY_SPREAD = 0.25\nconst RECORD_OUT = 0.53\n\n// Durations of the ease-in-out moves, in milliseconds.\nconst RAIL_MS = 750\nconst RELEASE_MS = 550\nconst PLAY_OPEN_MS = 480\nconst PLAY_CLOSE_MS = 220\n// A retargeted move carries the speed it had, up to this many times the speed of a plain ease from rest.\nconst MAX_CARRY = 3\n// Each frame advances the moves by the time since the last one, held between these, so a hitch or a tab switch does not jump.\nconst MIN_FRAME_MS = 1000 / 240\nconst MAX_FRAME_MS = 50\n\n// Dragging the sleeves moves the rail one album per DRAG_UNIT of the sleeve edge; the ruler moves one per tick.\nconst DRAG_UNIT = 0.55\n// A press becomes a drag once it has moved this many pixels.\nconst DRAG_THRESHOLD = 6\n// Past the ends of a rail that does not loop, the rail follows the pointer at this share of its travel.\nconst RUBBER_BAND = 0.3\n// Pointer positions kept to measure the release speed, and how far back in milliseconds they count.\nconst DRAG_SAMPLES = 6\nconst FLING_WINDOW = 100\n// On release the rail coasts for FLING_MS at the drag's speed, then snaps: at most FLING_MAX albums on,\n// starting at no more than FLING_SPEED albums a second.\nconst FLING_MS = 160\nconst FLING_MAX = 3\nconst FLING_SPEED = 20\n// Sideways wheel or trackpad travel steps once it passes WHEEL_STEP pixels, at most once per WHEEL_GAP milliseconds,\n// and WHEEL_IDLE milliseconds of rest start the count again.\nconst WHEEL_STEP = 40\nconst WHEEL_GAP = 260\nconst WHEEL_IDLE = 160\n\n// The ruler: one tick per album, TICK_GAP pixels apart, TICKS_PER_SIDE either side of the play button.\nconst TICK_GAP = 18\nconst TICKS_PER_SIDE = 8\n// Ticks fade out within TICK_HOLE pixels of the play button, over TICK_HOLE_FADE pixels,\n// and over the last TICK_EDGE_FADE gaps at either end of the ruler.\nconst TICK_HOLE = 27\nconst TICK_HOLE_FADE = 9\nconst TICK_EDGE_FADE = 3\nconst TICK_OPACITY = 0.4\n\n// The sleeve edge is at most this share of the rail's width, so narrow containers shrink it.\nconst FIT = 0.42\n// Covers are read at this size to pick the play button's tint.\nconst SAMPLE_SIZE = 16\n// Every pixel counts a little; saturated ones count with the square of their saturation, and much less when dark.\nconst BASE_WEIGHT = 0.05\nconst DARK_LEVEL = 40\nconst DARK_WEIGHT = 0.2\n\nconst REDUCED_MOTION = \"(prefers-reduced-motion: reduce)\"\n\nconst mod = (value: number, count: number) => ((value % count) + count) % count\nconst clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value))\n\n/** Steps from the front to sleeve `index` while the rail is at `position`; on a looping rail, the short way round. */\nexport function railOffset(index: number, position: number, count: number, wrap: boolean) {\n  const offset = index - position\n  return wrap ? mod(offset + count / 2, count) - count / 2 : offset\n}\n\n/** The rail position that brings `index` to the front from `base`: the short way round on a loop, held in range otherwise. */\nexport function railTarget(index: number, base: number, count: number, wrap: boolean) {\n  if (!wrap) return clamp(index, 0, count - 1)\n  let delta = mod(index - base, count)\n  if (delta > count / 2) delta -= count\n  return base + delta\n}\n\n/**\n * How a sleeve sits `offset` steps from the front. `x`, `y` and `shift` (the extra x while a record plays) are in units\n * of the sleeve edge, `record` is the share of RECORD_OUT its record slides out, and the angles are in degrees.\n */\nexport function sleevePose(offset: number, span: number, turn: number, fan: number) {\n  const dist = Math.abs(offset)\n  const side = Math.sign(offset)\n  // The first step away from the front is wide, later ones tuck in tighter and tighter.\n  const near = Math.min(dist, 1)\n  const far = Math.max(dist - 1, 0)\n  return {\n    x: side * (SPREAD * near + (STACK * (1 - DECAY ** far)) / (1 - DECAY)),\n    y: LIFT_NEAR * near + LIFT_FAR * far,\n    shift: side > 0 ? -PLAY_SHIFT + (PLAY_SHIFT + PLAY_SPREAD) * near : -PLAY_SHIFT + (PLAY_SHIFT - PLAY_SPREAD) * near,\n    scale: 1 - SHRINK_NEAR * near - SHRINK_FAR * (1 - SHRINK_DECAY ** far),\n    rotateY: side * near * turn,\n    rotateZ: side * fan * (near + FAN_FAR * far),\n    // Sleeves past `span` fade out over half a step.\n    opacity: clamp(span + 0.5 - dist, 0, 1),\n    shade: Math.min(near * SHADE_NEAR + far * SHADE_FAR, SHADE_MAX),\n    // Only the front sleeve's record comes out.\n    record: Math.max(0, 1 - dist * 2),\n    zIndex: Z_FRONT - Math.round(dist * Z_STEPS),\n  }\n}\n\n/** Where ruler tick `k` sits, in pixels from the ruler's centre, and how strongly it shows, while the rail is at `position`. */\nexport function tickPose(k: number, position: number, half: number) {\n  const x = (k - TICKS_PER_SIDE - (position - Math.floor(position))) * TICK_GAP\n  const ax = Math.abs(x)\n  const fade = clamp((half - ax) / (TICK_GAP * TICK_EDGE_FADE), 0, 1) * clamp((ax - TICK_HOLE) / TICK_HOLE_FADE, 0, 1)\n  return { x, opacity: fade * TICK_OPACITY }\n}\n\n/**\n * Where a released drag settles: the rail coasts on at the release `velocity` (pixels per millisecond, `unit` pixels per\n * album) for a moment, then snaps to an album, at most FLING_MAX away and inside the list unless it loops.\n */\nexport function flingTarget(position: number, velocity: number, unit: number, count: number, wrap: boolean) {\n  const projected = position - (velocity * FLING_MS) / unit\n  const target = clamp(Math.round(projected), Math.round(position) - FLING_MAX, Math.round(position) + FLING_MAX)\n  return wrap ? target : clamp(target, 0, count - 1)\n}\n\n/** The vivid average colour of RGBA pixel data: saturated pixels weigh the most. Null when there are no pixels. */\nexport function coverColor(pixels: ArrayLike<number>) {\n  let r = 0, g = 0, b = 0, w = 0\n  for (let i = 0; i + 3 < pixels.length; i += 4) {\n    const max = Math.max(pixels[i], pixels[i + 1], pixels[i + 2])\n    const min = Math.min(pixels[i], pixels[i + 1], pixels[i + 2])\n    const saturation = max ? (max - min) / max : 0\n    const weight = BASE_WEIGHT + saturation * saturation * (max > DARK_LEVEL ? 1 : DARK_WEIGHT)\n    r += pixels[i] * weight\n    g += pixels[i + 1] * weight\n    b += pixels[i + 2] * weight\n    w += weight\n  }\n  return w ? `rgb(${Math.round(r / w)}, ${Math.round(g / w)}, ${Math.round(b / w)})` : null\n}\n\n/**\n * A cubic Hermite tween: it eases in and out (smoothstep) from rest, and when it is retargeted mid-flight it starts from\n * its current velocity, so rapid clicks and drag releases never jerk. Times are in milliseconds.\n */\nexport interface Tween {\n  from: number\n  to: number\n  tangent: number\n  start: number\n  dur: number\n  pos: number\n  /** Units per second. */\n  vel: number\n  active: boolean\n}\n\nexport const createTween = (value: number): Tween => ({ from: value, to: value, tangent: 0, start: 0, dur: 1, pos: value, vel: 0, active: false })\n\n/** Moves a tween to time `now`. Returns whether it is still running. */\nexport function sampleTween(tw: Tween, now: number) {\n  if (!tw.active) return false\n  const t = clamp((now - tw.start) / tw.dur, 0, 1)\n  const t2 = t * t\n  const t3 = t2 * t\n  const d = tw.to - tw.from\n  tw.pos = tw.from + d * (3 * t2 - 2 * t3) + tw.tangent * (t3 - 2 * t2 + t)\n  tw.vel = (d * (6 * t - 6 * t2) + tw.tangent * (3 * t2 - 4 * t + 1)) / (tw.dur / 1000)\n  if (t >= 1) {\n    tw.pos = tw.to\n    tw.vel = 0\n    tw.active = false\n  }\n  return tw.active\n}\n\n/** Sends a tween to `to` over `dur` milliseconds from time `now`, carrying its current speed. A `dur` of 0 jumps there. */\nexport function retargetTween(tw: Tween, to: number, dur: number, now: number) {\n  sampleTween(tw, now)\n  if (dur <= 0) {\n    Object.assign(tw, { from: to, to, pos: to, vel: 0, active: false })\n    return\n  }\n  const d = to - tw.pos\n  // Carry the current speed in, but never so much that it overshoots or starts backwards.\n  const tangent = d ? clamp((tw.vel * dur) / 1000 / d, 0, MAX_CARRY) * d : 0\n  Object.assign(tw, { from: tw.pos, to, tangent, start: now, dur, vel: d ? tw.vel : 0, active: d !== 0 })\n}\n\n// Each cover is read once per page, however many rails show it, through one shared hidden canvas.\nconst covers = new Map<string, Promise<string | null>>()\nlet sampler: CanvasRenderingContext2D | null | undefined\n\nfunction readCover(src: string) {\n  let pending = covers.get(src)\n  if (!pending) {\n    pending = new Promise<string | null>((resolve) => {\n      const image = new Image()\n      // Reading pixels needs the image served with CORS headers. Without them the play button keeps the accent.\n      image.crossOrigin = \"anonymous\"\n      image.onload = () => {\n        try {\n          if (sampler === undefined) {\n            const canvas = document.createElement(\"canvas\")\n            canvas.width = canvas.height = SAMPLE_SIZE\n            sampler = canvas.getContext(\"2d\", { willReadFrequently: true })\n          }\n          if (!sampler) return resolve(null)\n          sampler.clearRect(0, 0, SAMPLE_SIZE, SAMPLE_SIZE)\n          sampler.drawImage(image, 0, 0, SAMPLE_SIZE, SAMPLE_SIZE)\n          resolve(coverColor(sampler.getImageData(0, 0, SAMPLE_SIZE, SAMPLE_SIZE).data))\n        } catch {\n          resolve(null) // A tainted canvas: the cover came without CORS headers after all.\n        }\n      }\n      image.onerror = () => resolve(null)\n      image.src = src\n    })\n    covers.set(src, pending)\n  }\n  return pending\n}\n\n/** The play button's tint: the album's own colour, else its cover's, else `fallback`. The last cover's colour stays while the next one loads. */\nfunction useCoverColor(src: string | undefined, preset: string | undefined, fallback: string) {\n  const [read, setRead] = React.useState<string | null>(null)\n  React.useEffect(() => {\n    if (preset || !src) return\n    let alive = true\n    readCover(src).then((color) => {\n      if (alive) setRead(color)\n    })\n    return () => {\n      alive = false\n    }\n  }, [src, preset])\n  if (preset) return preset\n  return (src && read) || fallback\n}\n\nconst subscribeReducedMotion = (onChange: () => void) => {\n  const query = window.matchMedia?.(REDUCED_MOTION)\n  query?.addEventListener(\"change\", onChange)\n  return () => query?.removeEventListener(\"change\", onChange)\n}\nconst prefersReducedMotion = () => window.matchMedia?.(REDUCED_MOTION).matches ?? false\nconst subscribeVisibility = (onChange: () => void) => {\n  document.addEventListener(\"visibilitychange\", onChange)\n  return () => document.removeEventListener(\"visibilitychange\", onChange)\n}\nconst pageHidden = () => document.hidden\nconst onServer = () => false\n\nconst NAV_BUTTON =\n  \"grid size-[32px] flex-none cursor-pointer place-items-center rounded-full border-0 bg-transparent p-0 text-inherit opacity-55 transition-[opacity,background-color] duration-200 ease-[ease] hover:bg-foreground/6 hover:opacity-100\"\nconst NAV_ICON = \"size-[14px] fill-none stroke-current [stroke-width:1.6] [stroke-linecap:round] [stroke-linejoin:round]\"\n\nexport function AlbumRail({\n  albums = DEFAULT_ALBUMS,\n  initialIndex = 0,\n  size = 280,\n  visible = 3,\n  turn = 22,\n  fan = 6,\n  loop = true,\n  autoplay = 4000,\n  pauseOnHover = true,\n  showCaption = true,\n  showControls = true,\n  accent = \"#b19eef\",\n  onChange,\n  onPlayChange,\n  className,\n  style,\n  onKeyDown,\n  onPointerEnter,\n  onPointerLeave,\n  onFocus,\n  onBlur,\n  ...props\n}: AlbumRailProps) {\n  const count = albums.length\n  const hasAlbums = count > 0\n  // With fewer than three sleeves a wrapped rail would visibly teleport, so it stays linear.\n  const wrap = loop && count >= 3\n  const span = wrap ? clamp(visible, 0, Math.floor((count - 1) / 2)) : Math.max(0, visible)\n  const start = count ? mod(Math.round(initialIndex), count) : 0\n\n  // The root's ref stays the consumer's, so the root is reached through the stage.\n  const stageRef = React.useRef<HTMLDivElement>(null)\n  const rulerRef = React.useRef<HTMLDivElement>(null)\n  const cards = React.useRef<(HTMLDivElement | null)[]>([])\n  const records = React.useRef<(HTMLDivElement | null)[]>([])\n  const shades = React.useRef<(HTMLSpanElement | null)[]>([])\n  const sleeves = React.useRef<(HTMLButtonElement | null)[]>([])\n  const ticks = React.useRef<(HTMLSpanElement | null)[]>([])\n\n  const [active, setActive] = React.useState(start)\n  const [playing, setPlaying] = React.useState(false)\n  const [edge, setEdge] = React.useState(size)\n  const [hovered, setHovered] = React.useState(false)\n  const [focused, setFocused] = React.useState(false)\n  const [dragging, setDragging] = React.useState(false)\n  const [offscreen, setOffscreen] = React.useState(false)\n  const hidden = React.useSyncExternalStore(subscribeVisibility, pageHidden, onServer)\n  const reduced = React.useSyncExternalStore(subscribeReducedMotion, prefersReducedMotion, onServer)\n  // Bumped on every navigation so the autoplay timer restarts right away,\n  // not only once the rail has moved far enough to change the front sleeve.\n  const [navCount, setNavCount] = React.useState(0)\n\n  // Motion lives outside React: every frame positions the sleeves directly, and React only re-renders when the front\n  // sleeve or the play state changes. `clock` is the moves' own time, advanced by clamped frame steps.\n  const motion = React.useRef({\n    rail: createTween(start),\n    play: createTween(0),\n    raf: 0,\n    clock: 0,\n    last: 0,\n    visible: true,\n    // Stacking and visibility are written only when they change, not every frame.\n    written: new WeakMap<HTMLElement, { zIndex: number; shown: boolean }>(),\n  })\n  const activeRef = React.useRef(start)\n  const playingRef = React.useRef(false)\n  // Half the ruler's width, until it is measured.\n  const rulerHalf = React.useRef(150)\n  const cfg = React.useRef({ count, edge, span, turn, fan, wrap, reduced })\n  const handlers = React.useRef({ albums, onChange, onPlayChange })\n\n  // Props reach the motion code through these refs, written after render and before the layout effects below read them.\n  React.useLayoutEffect(() => {\n    cfg.current = { count, edge, span, turn, fan, wrap, reduced }\n    handlers.current = { albums, onChange, onPlayChange }\n  })\n\n  const layout = React.useCallback(() => {\n    const { count, edge: S, span, turn, fan, wrap } = cfg.current\n    const m = motion.current\n    const pos = m.rail.pos\n    const p = m.play.pos\n\n    for (let i = 0; i < count; i++) {\n      const card = cards.current[i]\n      if (!card) continue\n      const pose = sleevePose(railOffset(i, pos, count, wrap), span, turn, fan)\n      card.style.transform =\n        `translate3d(${((pose.x + pose.shift * p) * S).toFixed(2)}px,${(pose.y * S).toFixed(2)}px,0) ` +\n        `rotateZ(${pose.rotateZ.toFixed(2)}deg) rotateY(${pose.rotateY.toFixed(2)}deg) scale(${pose.scale.toFixed(4)})`\n      card.style.opacity = pose.opacity.toFixed(3)\n\n      const shown = pose.opacity > 0\n      const last = m.written.get(card)\n      if (!last || last.zIndex !== pose.zIndex || last.shown !== shown) {\n        if (last?.zIndex !== pose.zIndex) card.style.zIndex = String(pose.zIndex)\n        if (last?.shown !== shown) card.style.visibility = shown ? \"visible\" : \"hidden\"\n        m.written.set(card, { zIndex: pose.zIndex, shown })\n      }\n\n      const shade = shades.current[i]\n      if (shade) shade.style.opacity = pose.shade.toFixed(3)\n      const record = records.current[i]\n      if (record) record.style.transform = `translateX(${(p * RECORD_OUT * S * pose.record).toFixed(2)}px)`\n    }\n\n    // Ruler ticks scroll with the rail, one tick per album.\n    ticks.current.forEach((tick, k) => {\n      if (!tick) return\n      const { x, opacity } = tickPose(k, pos, rulerHalf.current)\n      tick.style.transform = `translateX(${x.toFixed(2)}px)`\n      tick.style.opacity = opacity.toFixed(3)\n    })\n  }, [])\n\n  const sync = React.useCallback(() => {\n    const { count } = cfg.current\n    if (!count) return\n    const nearest = mod(Math.round(motion.current.rail.pos), count)\n    if (nearest === activeRef.current) return\n    activeRef.current = nearest\n    setActive(nearest)\n    handlers.current.onChange?.(nearest, handlers.current.albums[nearest])\n  }, [])\n\n  const stop = React.useCallback(() => {\n    cancelAnimationFrame(motion.current.raf)\n    motion.current.raf = 0\n  }, [])\n\n  const kick = React.useCallback(() => {\n    const m = motion.current\n    // Off screen and in a hidden tab nothing is scheduled; the move waits where it is.\n    if (m.raf || !m.visible || document.hidden) return\n    const frame = (now: number) => {\n      m.raf = 0\n      if (!m.visible || document.hidden) return\n      m.clock += clamp(now - m.last, MIN_FRAME_MS, MAX_FRAME_MS)\n      m.last = now\n      const railMoving = sampleTween(m.rail, m.clock)\n      const playMoving = sampleTween(m.play, m.clock)\n      // The loop ends as soon as both moves have landed; a rail at rest costs nothing.\n      if (railMoving || playMoving) m.raf = requestAnimationFrame(frame)\n      layout()\n      sync()\n    }\n    m.last = performance.now()\n    m.raf = requestAnimationFrame(frame)\n  }, [layout, sync])\n\n  /** Carries on with a move that was waiting off screen or in a hidden tab. */\n  const resume = React.useCallback(() => {\n    const m = motion.current\n    if (m.rail.active || m.play.active) kick()\n  }, [kick])\n\n  /** Starts a move, or jumps straight there when the user prefers reduced motion. */\n  const animate = React.useCallback(\n    (tw: Tween, to: number, dur: number) => {\n      const m = motion.current\n      const now = m.raf ? m.clock + clamp(performance.now() - m.last, 0, MAX_FRAME_MS) : m.clock\n      retargetTween(tw, to, cfg.current.reduced ? 0 : dur, now)\n      if (tw.active) return kick()\n      layout()\n      sync()\n    },\n    [kick, layout, sync]\n  )\n\n  const setPlay = React.useCallback(\n    (on: boolean) => {\n      if (playingRef.current === on) return\n      playingRef.current = on\n      setPlaying(on)\n      animate(motion.current.play, on ? 1 : 0, on ? PLAY_OPEN_MS : PLAY_CLOSE_MS)\n      const index = activeRef.current\n      handlers.current.onPlayChange?.(on, index, handlers.current.albums[index])\n    },\n    [animate]\n  )\n\n  const moveTo = React.useCallback(\n    (target: number, dur = RAIL_MS) => {\n      setPlay(false)\n      setNavCount((n) => n + 1)\n      animate(motion.current.rail, target, dur)\n    },\n    [animate, setPlay]\n  )\n\n  const go = React.useCallback(\n    (index: number) => {\n      const { count, wrap } = cfg.current\n      if (!count) return\n      moveTo(railTarget(index, Math.round(motion.current.rail.to), count, wrap))\n    },\n    [moveTo]\n  )\n\n  const step = React.useCallback(\n    (dir: number) => {\n      const { count, wrap } = cfg.current\n      const next = Math.round(motion.current.rail.to) + dir\n      moveTo(wrap ? next : clamp(next, 0, count - 1))\n    },\n    [moveTo]\n  )\n\n  // Re-anchor when the album list or looping changes, so positions stay in range.\n  React.useLayoutEffect(() => {\n    if (!count) return\n    stop()\n    const rail = motion.current.rail\n    Object.assign(rail, createTween(mod(Math.round(rail.to), count)))\n    layout()\n    sync()\n  }, [count, wrap, layout, stop, sync])\n\n  React.useLayoutEffect(() => {\n    layout()\n  }, [edge, span, turn, fan, showControls, layout])\n\n  // Fit the sleeve, and the ruler's fade, to the container.\n  React.useLayoutEffect(() => {\n    const root = stageRef.current?.parentElement\n    if (!root) return\n    const measure = () => {\n      setEdge(Math.round(Math.min(size, root.clientWidth * FIT)))\n      if (rulerRef.current) rulerHalf.current = rulerRef.current.clientWidth / 2\n      layout()\n    }\n    measure()\n    const observer = new ResizeObserver(measure)\n    observer.observe(root)\n    return () => observer.disconnect()\n  }, [size, showControls, hasAlbums, layout])\n\n  // Off screen the rail does no work: autoplay holds and a move waits, and both carry on when it is back in view\n  // or the tab is shown again.\n  React.useEffect(() => {\n    const root = stageRef.current?.parentElement\n    if (!root) return\n    const m = motion.current\n    const observer = new IntersectionObserver((entries) => {\n      const entry = entries[entries.length - 1]\n      m.visible = entry.isIntersecting\n      setOffscreen(!entry.isIntersecting)\n      resume()\n    })\n    observer.observe(root)\n    document.addEventListener(\"visibilitychange\", resume)\n    return () => {\n      observer.disconnect()\n      document.removeEventListener(\"visibilitychange\", resume)\n      m.visible = true\n    }\n  }, [hasAlbums, resume])\n\n  React.useEffect(() => stop, [stop])\n\n  // Autoplay waits while a record is playing, and restarts its timer on every move, so manual navigation never gets\n  // followed by an instant jump. Reduced motion turns it off.\n  const paused = playing || (pauseOnHover && hovered) || focused || dragging || hidden || offscreen || reduced\n  React.useEffect(() => {\n    if (!autoplay || paused || count < 2) return\n    const id = window.setTimeout(() => {\n      if (!cfg.current.wrap && activeRef.current >= count - 1) go(0)\n      else step(1)\n    }, autoplay)\n    return () => window.clearTimeout(id)\n  }, [navCount, active, autoplay, paused, count, go, step])\n\n  // Keep keyboard focus on the front sleeve as the rail moves.\n  React.useEffect(() => {\n    const root = stageRef.current?.parentElement\n    const el = document.activeElement\n    const target = sleeves.current[active]\n    if (root && target && el instanceof HTMLElement && el !== target && root.contains(el) && el.dataset.slot === \"album-rail-sleeve\") {\n      target.focus({ preventScroll: true })\n    }\n  }, [active])\n\n  // Horizontal wheel or trackpad swipe. Vertical scrolling is left to the page.\n  React.useEffect(() => {\n    const root = stageRef.current?.parentElement\n    if (!root) return\n    let acc = 0\n    let lastStep = 0\n    let idle = 0\n    const onWheel = (e: WheelEvent) => {\n      const horizontal = Math.abs(e.deltaX) > Math.abs(e.deltaY)\n      const delta = horizontal ? e.deltaX : e.shiftKey ? e.deltaY : 0\n      if (!delta) return\n      e.preventDefault()\n      acc += delta\n      window.clearTimeout(idle)\n      idle = window.setTimeout(() => (acc = 0), WHEEL_IDLE)\n      if (Math.abs(acc) > WHEEL_STEP && e.timeStamp - lastStep > WHEEL_GAP) {\n        step(Math.sign(acc))\n        acc = 0\n        lastStep = e.timeStamp\n      }\n    }\n    root.addEventListener(\"wheel\", onWheel, { passive: false })\n    return () => {\n      root.removeEventListener(\"wheel\", onWheel)\n      window.clearTimeout(idle)\n    }\n  }, [hasAlbums, step])\n\n  // Dragging the sleeves or scrubbing the ruler. Move and up listen on window, so a drag keeps working when the\n  // pointer leaves the rail; they only write the rail's position and wake the frame loop, which draws it.\n  const drag = React.useRef({\n    id: -1,\n    kind: \"rail\" as \"rail\" | \"ruler\",\n    x: 0,\n    from: 0,\n    moved: false,\n    samples: [] as { x: number; t: number }[],\n  })\n  const suppressClick = React.useRef(false)\n\n  React.useEffect(() => {\n    const unitPx = () => (drag.current.kind === \"ruler\" ? TICK_GAP : cfg.current.edge * DRAG_UNIT)\n\n    const onMove = (e: PointerEvent) => {\n      const d = drag.current\n      if (d.id !== e.pointerId) return\n      if (!d.moved) {\n        if (Math.abs(e.clientX - d.x) < DRAG_THRESHOLD) return\n        d.moved = true\n        d.x = e.clientX\n        d.from = motion.current.rail.pos\n        motion.current.rail.active = false\n        setPlay(false)\n        setDragging(true)\n      }\n      const { count, wrap } = cfg.current\n      let pos = d.from - (e.clientX - d.x) / unitPx()\n      if (!wrap) {\n        // Rubber band past the ends.\n        if (pos < 0) pos *= RUBBER_BAND\n        else if (pos > count - 1) pos = count - 1 + (pos - (count - 1)) * RUBBER_BAND\n      }\n      const rail = motion.current.rail\n      rail.pos = rail.to = pos\n      rail.vel = 0\n      d.samples.push({ x: e.clientX, t: e.timeStamp })\n      if (d.samples.length > DRAG_SAMPLES) d.samples.shift()\n      kick()\n    }\n\n    const onUp = (e: PointerEvent) => {\n      const d = drag.current\n      if (d.id !== e.pointerId) return\n      d.id = -1\n\n      if (!d.moved) {\n        // A tap on the ruler jumps to the tapped tick.\n        const ruler = rulerRef.current\n        if (d.kind === \"ruler\" && ruler && e.type === \"pointerup\") {\n          const r = ruler.getBoundingClientRect()\n          const ticksAway = Math.round((e.clientX - (r.left + r.width / 2)) / TICK_GAP)\n          if (ticksAway) step(ticksAway)\n        }\n        return\n      }\n\n      setDragging(false)\n      suppressClick.current = true\n\n      const recent = d.samples.filter((s) => e.timeStamp - s.t < FLING_WINDOW)\n      let velocity = 0 // pixels per millisecond\n      if (recent.length > 1) {\n        const a = recent[0]\n        const b = recent[recent.length - 1]\n        velocity = (b.x - a.x) / Math.max(b.t - a.t, 1)\n      }\n      const { count, wrap } = cfg.current\n      const unit = unitPx()\n      const rail = motion.current.rail\n      const target = flingTarget(rail.pos, velocity, unit, count, wrap)\n      rail.vel = clamp((-velocity * 1000) / unit, -FLING_SPEED, FLING_SPEED)\n      moveTo(target, RELEASE_MS)\n    }\n\n    window.addEventListener(\"pointermove\", onMove, { passive: true })\n    window.addEventListener(\"pointerup\", onUp, { passive: true })\n    window.addEventListener(\"pointercancel\", onUp, { passive: true })\n    return () => {\n      window.removeEventListener(\"pointermove\", onMove)\n      window.removeEventListener(\"pointerup\", onUp)\n      window.removeEventListener(\"pointercancel\", onUp)\n    }\n  }, [kick, moveTo, setPlay, step])\n\n  const startDrag = (e: React.PointerEvent, kind: \"rail\" | \"ruler\") => {\n    suppressClick.current = false\n    if (e.button !== 0 || count < 2) return\n    drag.current = {\n      id: e.pointerId,\n      kind,\n      x: e.clientX,\n      from: motion.current.rail.pos,\n      moved: false,\n      samples: [{ x: e.clientX, t: e.timeStamp }],\n    }\n  }\n\n  const onSleeveClick = (index: number) => {\n    if (suppressClick.current) {\n      suppressClick.current = false\n      return\n    }\n    if (index === activeRef.current) setPlay(!playingRef.current)\n    else go(index)\n  }\n\n  const handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {\n    onKeyDown?.(e)\n    if (e.defaultPrevented) return\n    if (e.key === \"ArrowRight\") step(1)\n    else if (e.key === \"ArrowLeft\") step(-1)\n    else if (e.key === \"Home\") go(0)\n    else if (e.key === \"End\") go(count - 1)\n    else return\n    e.preventDefault()\n  }\n\n  // Only keyboard focus holds autoplay; a mouse click that happens to focus a sleeve should not.\n  const handleFocus = (e: React.FocusEvent<HTMLDivElement>) => {\n    onFocus?.(e)\n    if (e.target instanceof HTMLElement && e.target.matches(\":focus-visible\")) setFocused(true)\n  }\n  const handleBlur = (e: React.FocusEvent<HTMLDivElement>) => {\n    onBlur?.(e)\n    if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setFocused(false)\n  }\n\n  const current = albums[active] ?? albums[0]\n  const tint = useCoverColor(current?.cover, current?.color, accent)\n\n  if (!count) return null\n  const autoplaying = Boolean(autoplay) && !paused && count > 1\n\n  return (\n    <div\n      data-slot=\"album-rail\"\n      role=\"region\"\n      aria-roledescription=\"carousel\"\n      aria-label=\"Albums\"\n      className={cn(\"relative w-full text-foreground select-none [-webkit-tap-highlight-color:transparent]\", className)}\n      style={{ ...style, \"--rail-size\": `${edge}px`, \"--rail-accent\": tint } as React.CSSProperties}\n      onKeyDown={handleKeyDown}\n      onPointerEnter={(e) => {\n        onPointerEnter?.(e)\n        if (e.pointerType === \"mouse\") setHovered(true)\n      }}\n      onPointerLeave={(e) => {\n        onPointerLeave?.(e)\n        setHovered(false)\n      }}\n      onFocus={handleFocus}\n      onBlur={handleBlur}\n      {...props}\n    >\n      <div\n        ref={stageRef}\n        className={cn(\n          \"relative h-[calc(var(--rail-size)*1.3)] touch-pan-y overflow-hidden [perspective:calc(var(--rail-size)*4.5)]\",\n          dragging ? \"cursor-grabbing\" : \"cursor-grab\"\n        )}\n        onPointerDown={(e) => startDrag(e, \"rail\")}\n      >\n        {albums.map((album, i) => {\n          const isActive = i === active\n          return (\n            <div\n              key={i}\n              ref={(el) => {\n                cards.current[i] = el\n              }}\n              data-slot=\"album-rail-card\"\n              className=\"group/card absolute top-1/2 left-1/2 mt-[calc(var(--rail-size)/-2)] ml-[calc(var(--rail-size)/-2)] size-(--rail-size) will-change-[transform,opacity]\"\n            >\n              <div\n                ref={(el) => {\n                  records.current[i] = el\n                }}\n                aria-hidden=\"true\"\n                className=\"absolute inset-[3%] z-0 will-change-transform\"\n              >\n                {/* Hover peek: the front record shows a sliver until it is played. */}\n                <div\n                  className={cn(\n                    \"size-full transition-transform duration-550 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none\",\n                    isActive && !playing && \"group-hover/card:[transform:translateX(9%)]\"\n                  )}\n                >\n                  {/* The light reflection on top stays put while the label spins underneath it. */}\n                  <div className=\"relative size-full overflow-hidden rounded-full bg-[#131116] shadow-[0_calc(var(--rail-size)*0.04)_calc(var(--rail-size)*0.1)_calc(var(--rail-size)*-0.02)_rgba(0,0,0,0.7),inset_0_0_0_1px_rgba(255,255,255,0.08)] after:pointer-events-none after:absolute after:inset-0 after:rounded-full after:[background:conic-gradient(from_25deg,transparent_0deg,rgba(255,255,255,0.12)_28deg,transparent_64deg,transparent_180deg,rgba(255,255,255,0.08)_212deg,transparent_248deg)]\">\n                    {/* The grooves are rings around the centre, so they hold still and only the label turns:\n                        a layered background never sits on a transformed element. */}\n                    <div className=\"absolute inset-0 rounded-full [background:radial-gradient(circle_closest-side,transparent_41%,rgba(255,255,255,0.07)_41.6%,transparent_42.6%),radial-gradient(circle_closest-side,transparent_58%,rgba(255,255,255,0.06)_58.6%,transparent_59.6%),radial-gradient(circle_closest-side,transparent_75%,rgba(255,255,255,0.06)_75.6%,transparent_76.6%),radial-gradient(circle_closest-side,transparent_95%,rgba(255,255,255,0.1)_96%,transparent_98%),repeating-radial-gradient(circle_closest-side,rgba(255,255,255,0.025)_0_1px,transparent_1px_3px)]\">\n                      <div\n                        className={cn(\n                          \"absolute inset-0\",\n                          isActive && playing\n                            ? \"motion-safe:animate-[mewo-album-rail-spin_2.4s_linear_infinite]\"\n                            : \"motion-safe:animate-[mewo-album-rail-spin_2.4s_linear_infinite_paused]\"\n                        )}\n                      >\n                        <span\n                          className=\"absolute top-1/2 left-1/2 size-[34%] -translate-1/2 rounded-full bg-cover bg-center shadow-[0_0_0_2px_rgba(0,0,0,0.5)] after:absolute after:top-1/2 after:left-1/2 after:size-[9%] after:-translate-1/2 after:rounded-full after:bg-[#050505]\"\n                          style={{ backgroundImage: `url(${JSON.stringify(album.cover)})` }}\n                        />\n                      </div>\n                    </div>\n                  </div>\n                </div>\n              </div>\n\n              <button\n                ref={(el) => {\n                  sleeves.current[i] = el\n                }}\n                type=\"button\"\n                data-slot=\"album-rail-sleeve\"\n                tabIndex={isActive ? 0 : -1}\n                aria-label={isActive ? `${playing ? \"Pause\" : \"Play\"} ${album.title} by ${album.artist}` : `${album.title} by ${album.artist}`}\n                aria-current={isActive ? \"true\" : undefined}\n                onClick={() => onSleeveClick(i)}\n                className=\"absolute inset-0 z-1 m-0 block cursor-[inherit] overflow-hidden rounded-[calc(var(--rail-size)*0.05)] border-0 bg-muted p-0 text-inherit shadow-[0_calc(var(--rail-size)*0.07)_calc(var(--rail-size)*0.14)_calc(var(--rail-size)*-0.03)_rgba(0,0,0,0.6)] [font:inherit] outline-none focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-ring after:pointer-events-none after:absolute after:inset-0 after:rounded-[inherit] after:shadow-[inset_0_0_0_1px_rgba(255,255,255,0.08)]\"\n              >\n                <img className=\"pointer-events-none block size-full object-cover [-webkit-user-drag:none]\" src={album.cover} alt=\"\" draggable={false} decoding=\"async\" />\n                <span className=\"pointer-events-none absolute inset-0 [background:linear-gradient(125deg,rgba(255,255,255,0.1)_0%,rgba(255,255,255,0)_36%)]\" />\n                {/* Darkens sleeves as they move away from the front; the frame loop sets its opacity. */}\n                <span\n                  ref={(el) => {\n                    shades.current[i] = el\n                  }}\n                  className=\"pointer-events-none absolute inset-0 bg-black opacity-0\"\n                />\n              </button>\n            </div>\n          )\n        })}\n      </div>\n\n      {showCaption && (\n        <div className=\"mt-[calc(var(--rail-size)*-0.02)] min-h-[3.4em] text-center\" aria-live={autoplaying ? \"off\" : \"polite\"} aria-atomic=\"true\">\n          <div key={active} className=\"motion-safe:animate-[mewo-album-rail-caption_0.5s_cubic-bezier(0.22,1,0.36,1)_both]\">\n            <p className=\"m-0 text-[1.05rem] font-semibold tracking-[-0.01em]\">{current.title}</p>\n            <p className=\"mt-[0.3em] mb-0 text-[0.875rem] opacity-55\">{current.artist}</p>\n          </div>\n        </div>\n      )}\n\n      {showControls && (\n        <div className=\"mt-[18px] flex items-center justify-center gap-[10px]\">\n          <button type=\"button\" aria-label=\"Previous album\" onClick={() => step(-1)} className={NAV_BUTTON}>\n            <svg viewBox=\"0 0 16 16\" aria-hidden=\"true\" className={NAV_ICON}>\n              <path d=\"M10 3.5 5.5 8l4.5 4.5\" />\n            </svg>\n          </button>\n\n          <div\n            ref={rulerRef}\n            role=\"slider\"\n            tabIndex={0}\n            aria-label=\"Choose album\"\n            aria-valuemin={1}\n            aria-valuemax={count}\n            aria-valuenow={active + 1}\n            aria-valuetext={`${current.title} by ${current.artist}`}\n            className=\"relative h-[38px] w-[min(306px,calc(100%_-_96px))] flex-none cursor-ew-resize touch-none rounded-[19px] outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n            onPointerDown={(e) => {\n              if (!(e.target as Element).closest('[data-slot=\"album-rail-play\"]')) startDrag(e, \"ruler\")\n            }}\n          >\n            {Array.from({ length: TICKS_PER_SIDE * 2 + 2 }, (_, k) => (\n              <span\n                key={k}\n                ref={(el) => {\n                  ticks.current[k] = el\n                }}\n                className=\"pointer-events-none absolute top-1/2 left-1/2 mt-[-4.5px] ml-[-0.75px] h-[9px] w-[1.5px] rounded-[1px] bg-current opacity-0 will-change-[transform,opacity]\"\n              />\n            ))}\n            {/* Tinted with the front cover's colour. */}\n            <button\n              type=\"button\"\n              data-slot=\"album-rail-play\"\n              aria-label={playing ? \"Pause\" : `Play ${current.title}`}\n              aria-pressed={playing}\n              onClick={() => setPlay(!playingRef.current)}\n              className=\"absolute top-1/2 left-1/2 mt-[-19px] ml-[-19px] grid size-[38px] cursor-pointer place-items-center rounded-full border-0 bg-[color-mix(in_srgb,var(--rail-accent)_30%,transparent)] p-0 text-[color-mix(in_srgb,var(--rail-accent)_70%,var(--color-foreground))] outline-none [transition:background-color_0.6s,color_0.6s,transform_0.2s_cubic-bezier(0.22,1,0.36,1)] hover:[transform:scale(1.06)] focus-visible:outline-2 focus-visible:outline-offset-3 focus-visible:outline-ring active:[transform:scale(0.94)]\"\n            >\n              {playing ? (\n                <svg viewBox=\"0 0 16 16\" aria-hidden=\"true\" className=\"size-[14px] fill-current\">\n                  <rect x=\"4\" y=\"3.5\" width=\"2.6\" height=\"9\" rx=\"0.8\" />\n                  <rect x=\"9.4\" y=\"3.5\" width=\"2.6\" height=\"9\" rx=\"0.8\" />\n                </svg>\n              ) : (\n                <svg viewBox=\"0 0 16 16\" aria-hidden=\"true\" className=\"size-[14px] fill-current\">\n                  <path d=\"M5.5 3.6v8.8a.6.6 0 0 0 .9.5l7-4.4a.6.6 0 0 0 0-1L6.4 3.1a.6.6 0 0 0-.9.5Z\" />\n                </svg>\n              )}\n            </button>\n          </div>\n\n          <button type=\"button\" aria-label=\"Next album\" onClick={() => step(1)} className={NAV_BUTTON}>\n            <svg viewBox=\"0 0 16 16\" aria-hidden=\"true\" className={NAV_ICON}>\n              <path d=\"M6 3.5 10.5 8 6 12.5\" />\n            </svg>\n          </button>\n        </div>\n      )}\n    </div>\n  )\n}\n",
      "type": "registry:ui"
    }
  ],
  "css": {
    "@keyframes mewo-album-rail-spin": {
      "to": {
        "transform": "rotate(360deg)"
      }
    },
    "@keyframes mewo-album-rail-caption": {
      "from": {
        "opacity": "0",
        "transform": "translateY(6px)",
        "filter": "blur(4px)"
      },
      "to": {
        "opacity": "1",
        "transform": "none",
        "filter": "none"
      }
    }
  },
  "meta": {
    "added": "2026-10-24"
  },
  "categories": [
    "card"
  ],
  "type": "registry:ui"
}