{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "wave-ribbon",
  "title": "Wave ribbon",
  "description": "Pictures on a long ribbon that undulates gently in depth; neighbours recede into fog in the theme's background, and a fast drag deepens the wave a little. WebGL, with a CSS 3D fallback.",
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "utils"
  ],
  "files": [
    {
      "path": "registry/manniche/wave-ribbon/wave-ribbon.tsx",
      "content": "import { ChevronLeft, ChevronRight } from 'lucide-react'\nimport {\n  useCallback,\n  useId,\n  useLayoutEffect,\n  useRef,\n  useState,\n  type HTMLAttributes,\n  type KeyboardEvent,\n  type MouseEvent,\n  type PointerEvent,\n} from 'react'\nimport { useCarouselEngine } from '@/registry/manniche/hooks/use-carousel-engine'\nimport { glAtlas, glProgram, useGlStage, type GlAtlas, type GlImage, type GlSceneContext, type Rgb } from '@/registry/manniche/hooks/use-gl-stage'\nimport { cn } from '@/lib/utils'\n\nexport type WaveRibbonProps = Omit<HTMLAttributes<HTMLDivElement>, 'onChange'> & {\n  /** The pictures, each with alt text. Pictures from another origin must send CORS headers to be drawn into WebGL. */\n  images: GlImage[]\n  /** Read by screen readers, e.g. “Landscapes”. */\n  label: string\n  /** Controlled: the picture at the front. */\n  index?: number\n  /** The picture at the front at first, when uncontrolled. */\n  defaultIndex?: number\n  /** Called when the ribbon heads for a new picture: on release, a key, a button or a click. */\n  onIndexChange?: (index: number) => void\n  /** Wrap round from the last picture to the first. Needs three pictures or more. */\n  loop?: boolean\n  /** Picture width over height. */\n  aspect?: number\n  /** How deep the wave runs; 0 lays the pictures out in a flat row. */\n  amplitude?: number\n  /** How much the pictures away from the front fade into the page, 0–1. */\n  fog?: number\n  /** A very slow drift in the wave while the ribbon is at rest. Off under reduced motion and off screen. */\n  animate?: boolean\n  /** Show the previous and next buttons and the position rule. */\n  controls?: boolean\n  /** The words on the buttons and for screen readers, to translate them, e.g. `{ picture: 'Bild', of: 'von' }`. */\n  labels?: Partial<Record<'previous' | 'next' | 'picture' | 'of', string>>\n}\n\nconst EN = { previous: 'Previous picture', next: 'Next picture', picture: 'Picture', of: 'of' }\nconst TYPING = 'input, textarea, select, [contenteditable=\"\"], [contenteditable=\"true\"]'\n\n// The scene, in world units of one picture width.\nconst GAP = 0.09 // between pictures, along the ribbon\nconst FOV = (24 * Math.PI) / 180 // vertical field of view: long, so the wave reads calm rather than wide-angle\nconst DEPTH = 0.42 // how far the wave dips back, at amplitude 1\nconst LIFT = 0.06 // how far it dips down as it goes back\nconst WAVE = 3.9 // one wavelength, crest to crest\nconst RECEDE = 0.28 // how far the ribbon falls back towards its ends, per RECEDE_LEN of length\nconst RECEDE_LEN = 1.6\nconst RADIUS = 14 // px, the corner radius of the picture at the front\nconst SEG = 28 // columns per picture, so it bends smoothly\nconst PAD = 0.03 // world units of quad around each picture, room for its smoothed edge\nconst FOG_START = 1 // distance along the ribbon where the fog begins\nconst FOG_DEPTH = 0.35 // how fast the fog thickens with depth\nconst FLUTTER = 0.3 // how much deeper the wave runs at full speed\n\nconst clamp = (v: number, a: number, b: number) => Math.min(b, Math.max(a, v))\nconst smooth = (a: number, b: number, v: number) => {\n  const t = clamp((v - a) / (b - a), 0, 1)\n  return t * t * (3 - 2 * t)\n}\n\n/** The wave: depth `a` with wavenumber `k`, a dip of `h` with wavenumber `ky`, a drifting phase `ph`, and a fall\n *  back of `r` per `rl` towards the ends. */\ntype Wave = { a: number; k: number; h: number; ky: number; ph: number; r: number; rl: number }\n\n// The ribbon's centre line, as height and depth over x. The crest sits at x = 0, facing the camera.\nconst waveY = (w: Wave, x: number) => w.h * (Math.cos(w.ky * x + w.ph) - Math.cos(w.ph))\nconst waveZ = (w: Wave, x: number) => w.a * (Math.cos(w.k * x) - 1) - w.r * (Math.hypot(1, x / w.rl) - 1)\nconst slopeY = (w: Wave, x: number) => -w.h * w.ky * Math.sin(w.ky * x + w.ph)\nconst slopeZ = (w: Wave, x: number) => -w.a * w.k * Math.sin(w.k * x) - (w.r * x) / (w.rl * w.rl * Math.hypot(1, x / w.rl))\n// How far x moves per unit of distance along the ribbon.\nconst dxds = (w: Wave, x: number) => 1 / Math.sqrt(1 + slopeY(w, x) ** 2 + slopeZ(w, x) ** 2)\n// Walk `s` along the ribbon from x, in midpoint steps. The vertex shader takes the same steps across a picture.\nfunction walk(w: Wave, x: number, s: number, steps: number) {\n  const h = s / steps\n  for (let i = 0; i < steps; i++) x += h * dxds(w, x + 0.5 * h * dxds(w, x))\n  return x\n}\nconst arcToX = (w: Wave, s: number) => walk(w, 0, s, Math.max(1, Math.ceil(Math.abs(s) / 0.2)))\n\n/** The camera and sizes for a stage, in world units of one picture width. */\ntype Rig = {\n  width: number\n  height: number\n  half: [number, number]\n  spacing: number\n  fx: number\n  fy: number\n  shift: number\n  dist: number\n  camY: number\n  /** Pixels per world unit at the front. */\n  ppu: number\n  radius: number\n  /** Distance along the ribbon where a picture's outer edge reaches the side of the frame. */\n  end: number\n  /** Pixels at each side of the frame over which the ribbon dissolves into the page. */\n  band: number\n  wave: Wave\n}\n\nfunction rigFor(width: number, height: number, aspect: number, amplitude: number, n: number, loop: boolean): Rig {\n  const half: [number, number] = [0.5, 0.5 / aspect]\n  const ratio = width / height\n  const f = 1 / Math.tan(FOV / 2)\n  // The front picture takes a set share of the height, and at most under a third of the width.\n  const share = 0.72\n  const dist = Math.max((half[1] * f) / share, (half[0] * f) / (ratio * 0.3))\n  const camY = half[1] * 0.42\n  const k = (2 * Math.PI) / WAVE\n  const wave: Wave = { a: DEPTH * amplitude, k, h: LIFT * amplitude, ky: k * 0.5, ph: 0, r: RECEDE * amplitude, rl: RECEDE_LEN }\n  const rig: Rig = {\n    width,\n    height,\n    half,\n    spacing: 1 + GAP,\n    fx: f / ratio,\n    fy: f,\n    shift: (f * camY) / dist,\n    dist,\n    camY,\n    ppu: (height / 2) * (f / dist),\n    radius: 0,\n    end: 0,\n    band: clamp(width * 0.13, 48, 200),\n    wave,\n  }\n  rig.radius = Math.min(RADIUS / rig.ppu, 0.16)\n  // Walk out along the ribbon until a picture's outer edge reaches the side of the frame.\n  let s = 0.5\n  while (s < 9) {\n    const x = arcToX(wave, s + 0.5)\n    const [px] = project(rig, x, waveY(wave, x), waveZ(wave, x))\n    if (px > width) break\n    s += 0.05\n  }\n  rig.end = loop ? Math.min(s, (n / 2) * rig.spacing - 0.4) : s\n  return rig\n}\n\n// A world point to stage pixels, and its distance from the camera.\nfunction project(r: Rig, x: number, y: number, z: number): [number, number, number] {\n  const w = r.dist - z\n  const nx = (r.fx * x) / w\n  const ny = (r.fy * (y - r.camY)) / w + r.shift\n  return [((nx + 1) / 2) * r.width, ((1 - ny) / 2) * r.height, w]\n}\n\n// How much a point at distance `s` along the ribbon and depth `z` mixes into the page.\nfunction fogAt(r: Rig, fog: number, s: number, z: number) {\n  const fs = smooth(FOG_START, r.end + 0.5, Math.abs(s))\n  const fz = 1 - Math.exp(z * FOG_DEPTH)\n  return fog * (1 - (1 - fs) * (1 - fz))\n}\n\n// How visible the ribbon is at a horizontal point on the stage: it dissolves into the page at both sides.\nconst edgeAt = (r: Rig, px: number) => smooth(0, r.band, Math.min(px, r.width - px))\n\ntype Card = { i: number; s: number; x: number; w: number; alpha: number }\n\n// The pictures in view for a position, farthest first.\nfunction lay(r: Rig, wave: Wave, p: number, n: number, loop: boolean): Card[] {\n  const out: Card[] = []\n  for (let i = 0; i < n; i++) {\n    let d = i - p\n    if (loop) d = ((((d + n / 2) % n) + n) % n) - n / 2\n    const s = d * r.spacing\n    if (Math.abs(s) > r.end + 1.05) continue\n    // Near the seam of a loop a picture is about to jump to the other end, so it is gone first.\n    const seam = loop ? clamp((n / 2 - Math.abs(d)) / 0.75, 0, 1) : 1\n    if (seam <= 0) continue\n    const x = arcToX(wave, s)\n    out.push({ i, s, x, w: r.dist - waveZ(wave, x), alpha: seam })\n  }\n  return out.sort((a, b) => b.w - a.w)\n}\n\nconst VERTEX = `\nattribute vec2 aP;\nuniform vec2 uHalf;\nuniform float uPad;\nuniform float uXc;\nuniform float uSc;\nuniform vec4 uWave;\nuniform float uPh;\nuniform vec2 uRec;\nuniform vec4 uCam;\nuniform vec3 uCam2;\nuniform float uViewH;\nvarying vec2 vLocal;\nvarying float vS;\nvarying float vZ;\nvarying vec3 vN;\nvarying float vAA;\nvec2 slope(float x){float e=sqrt(1.+x*x/(uRec.y*uRec.y));return vec2(-uWave.z*uWave.w*sin(uWave.w*x+uPh),-uWave.x*uWave.y*sin(uWave.y*x)-uRec.x*x/(uRec.y*uRec.y*e));}\nfloat dxds(float x){vec2 d=slope(x);return inversesqrt(1.+dot(d,d));}\nvoid main(){\n  vec2 p=aP*(uHalf+uPad);\n  // Walk from the picture's centre along the ribbon, the same midpoint steps as on the CPU.\n  float h=p.x*.5;\n  float x=uXc;\n  x+=h*dxds(x+.5*h*dxds(x));\n  x+=h*dxds(x+.5*h*dxds(x));\n  vec2 d=slope(x);\n  float y=uWave.z*(cos(uWave.w*x+uPh)-cos(uPh))+p.y;\n  float z=uWave.x*(cos(uWave.y*x)-1.)-uRec.x*(sqrt(1.+x*x/(uRec.y*uRec.y))-1.);\n  vN=normalize(vec3(-d.y,0.,1.));\n  vLocal=p;\n  vS=uSc+p.x;\n  vZ=z;\n  vec3 v=vec3(x,y-uCam2.x,z-uCam.w);\n  float w=-v.z;\n  float n=uCam2.y;\n  float f=uCam2.z;\n  gl_Position=vec4(uCam.x*v.x,uCam.y*v.y+uCam.z*w,(f+n)/(f-n)*w-2.*f*n/(f-n),w);\n  // World units per device pixel here, for the edge when derivatives are missing.\n  vAA=w/(uCam.y*uViewH*.5);\n}`\n\nconst FRAGMENT = `\nprecision mediump float;\nuniform sampler2D uTex;\nuniform vec4 uRect;\nuniform vec2 uBox;\nuniform float uRadius;\nuniform float uHair;\nuniform vec3 uBg;\nuniform vec3 uFg;\nuniform vec4 uFog;\nuniform vec2 uEdge;\nuniform float uAlpha;\nuniform vec3 uLight;\nvarying vec2 vLocal;\nvarying float vS;\nvarying float vZ;\nvarying vec3 vN;\nvarying float vAA;\nvoid main(){\n  vec2 q=abs(vLocal)-uBox+uRadius;\n  float d=length(max(q,0.))+min(max(q.x,q.y),0.)-uRadius;\n#ifdef DERIV\n  float aa=max(fwidth(d),1e-4);\n#else\n  float aa=vAA;\n#endif\n  float a=clamp(.5-d/aa,0.,1.)*uAlpha;\n  // The ribbon dissolves into the page at both sides of the frame.\n  a*=smoothstep(0.,uEdge.y,min(gl_FragCoord.x,uEdge.x-gl_FragCoord.x));\n  if(a<.002)discard;\n  vec2 uv=clamp(vLocal/(2.*uBox)+.5,0.,1.);\n  vec3 c=texture2D(uTex,mix(uRect.xy,uRect.zw,vec2(uv.x,1.-uv.y))).rgb;\n  // Lit softly from the upper left and front, so the bend reads.\n  float lam=max(dot(normalize(vN),uLight),0.);\n  c*=mix(.84,1.02,lam);\n  // A hairline just inside the edge.\n  float line=clamp((d+aa*uHair)/aa+.5,0.,1.);\n  c=mix(c,uFg,line*.13);\n  float fs=smoothstep(uFog.x,uFog.y,abs(vS));\n  float fz=1.-exp(vZ*uFog.z);\n  c=mix(c,uBg,uFog.w*(1.-(1.-fs)*(1.-fz)));\n  gl_FragColor=vec4(c*a,a);\n}`\n\n/**\n * A gallery on a long ribbon in 3D. The ribbon runs from left to right and undulates gently in depth: the picture\n * at the front faces you on the crest, and its neighbours bend along the wave as it falls away, fading into the page\n * at both ends. Dragging travels along the ribbon: the pictures slide along the curve while the wave stays where it\n * is, and speed briefly deepens it, so the ribbon flutters and then settles. Drag or swipe with momentum, use a\n * trackpad, the arrow keys, the buttons, or click a picture to bring it to the front. The pictures are drawn with\n * WebGL as finely divided quads that the vertex shader bends onto the ribbon. Under reduced motion every move jumps\n * and the ribbon holds still. Without WebGL, or if the GPU drops the context, the same pictures stand flat on the\n * same wave in CSS 3D.\n */\nexport function WaveRibbon({\n  images,\n  label,\n  index,\n  defaultIndex,\n  onIndexChange,\n  loop = false,\n  aspect = 4 / 5,\n  amplitude = 1,\n  fog = 0.6,\n  animate = false,\n  controls = true,\n  labels = {},\n  className,\n  onKeyDown,\n  ...rest\n}: WaveRibbonProps) {\n  const t = { ...EN, ...labels }\n  const n = images.length\n  const wraps = loop && n > 2\n  const id = useId()\n\n  const stage = useRef<HTMLDivElement | null>(null)\n  const cards = useRef<(HTMLDivElement | null)[]>([])\n  const ticks = useRef<(HTMLSpanElement | null)[]>([])\n  const [width, setWidth] = useState(0)\n  const height = width ? Math.round(clamp(width * 0.3, 300, 480)) : 0\n  const rig = width ? rigFor(width, height, aspect, amplitude, n, wraps) : null\n\n  // What the frame loop and the scene read, so neither needs React to render.\n  const live = useRef({ rig, n, wraps, fog, pos: 0, vel: 0, wave: rig?.wave ?? null, ready: false })\n  useLayoutEffect(() => {\n    Object.assign(live.current, { rig, n, wraps, fog })\n  })\n  const source = useRef({ images, aspect })\n  useLayoutEffect(() => {\n    source.current = { images, aspect }\n  })\n\n  const build = useCallback(({ gl, ready, redraw, fail, colors: initial, signal }: GlSceneContext) => {\n    const deriv = !!gl.getExtension('OES_standard_derivatives')\n    const prog = glProgram(gl, VERTEX, (deriv ? '#extension GL_OES_standard_derivatives : enable\\n#define DERIV\\n' : '') + FRAGMENT)\n    if (!prog) return null\n    const u = (name: string) => gl.getUniformLocation(prog, name)\n    const U = {\n      half: u('uHalf'),\n      box: u('uBox'),\n      pad: u('uPad'),\n      xc: u('uXc'),\n      sc: u('uSc'),\n      wave: u('uWave'),\n      ph: u('uPh'),\n      rec: u('uRec'),\n      cam: u('uCam'),\n      cam2: u('uCam2'),\n      viewH: u('uViewH'),\n      tex: u('uTex'),\n      rect: u('uRect'),\n      radius: u('uRadius'),\n      hair: u('uHair'),\n      bg: u('uBg'),\n      fg: u('uFg'),\n      fog: u('uFog'),\n      edge: u('uEdge'),\n      alpha: u('uAlpha'),\n      light: u('uLight'),\n    }\n    // One strip of columns from the left edge to the right, two rows: the ribbon only bends sideways.\n    const verts = new Float32Array((SEG + 1) * 4)\n    for (let i = 0; i <= SEG; i++) verts.set([-1 + (2 * i) / SEG, 1, -1 + (2 * i) / SEG, -1], i * 4)\n    const buf = gl.createBuffer()\n    gl.bindBuffer(gl.ARRAY_BUFFER, buf)\n    gl.bufferData(gl.ARRAY_BUFFER, verts, gl.STATIC_DRAW)\n    const aP = gl.getAttribLocation(prog, 'aP')\n\n    let atlas: GlAtlas | null = null\n    let colors: Rgb[] = initial\n    let viewH = 1\n    let dpr = 1\n    // The flutter: how much deeper the wave runs now, eased towards the speed without overshoot.\n    let flutter = 0\n    let last = 0\n    let settle = 0\n    const L = Math.hypot(-0.5, 0.32, 1)\n\n    const { images: pics, aspect: ratio } = source.current\n    glAtlas(gl, pics, { aspect: ratio, cell: 768, empty: colors[2], signal }).then((a) => {\n      if (signal.aborted) return\n      if (!a) return fail()\n      atlas = a\n      ready()\n    })\n\n    const draw = (time: number) => {\n      const st = live.current\n      const r = st.rig\n      gl.clearColor(0, 0, 0, 0)\n      gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)\n      if (!r || !atlas) return\n\n      const now = performance.now()\n      const dt = last ? Math.min(0.05, (now - last) / 1000) : 0.016\n      last = now\n      const want = FLUTTER * Math.tanh(Math.abs(st.vel) / 7)\n      // Quick to deepen, slow to relax: a first-order ease, so it never swings past.\n      flutter += (want - flutter) * (1 - Math.exp(-dt / (want > flutter ? 0.09 : 0.42)))\n      if (flutter < 0.0008 && !want) flutter = 0\n      cancelAnimationFrame(settle)\n      if (flutter > 0 && !want) settle = requestAnimationFrame(() => redraw())\n\n      // At rest the phase is 0; with the ambient drift it sways slowly round it.\n      const ph = 0.55 * Math.sin((time - 4) * 0.13)\n      const wave: Wave = { ...r.wave, a: r.wave.a * (1 + flutter), h: r.wave.h * (1 + flutter * 0.6), ph }\n      st.wave = wave\n      const list = lay(r, wave, st.pos, st.n, st.wraps)\n\n      gl.useProgram(prog)\n      gl.enable(gl.DEPTH_TEST)\n      gl.depthFunc(gl.LEQUAL)\n      gl.enable(gl.BLEND)\n      gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)\n      gl.bindBuffer(gl.ARRAY_BUFFER, buf)\n      gl.enableVertexAttribArray(aP)\n      gl.vertexAttribPointer(aP, 2, gl.FLOAT, false, 0, 0)\n      gl.activeTexture(gl.TEXTURE0)\n      gl.bindTexture(gl.TEXTURE_2D, atlas.texture)\n      gl.uniform1i(U.tex, 0)\n      gl.uniform2f(U.half, r.half[0], r.half[1])\n      gl.uniform2f(U.box, r.half[0], r.half[1])\n      gl.uniform1f(U.pad, PAD)\n      gl.uniform4f(U.wave, wave.a, wave.k, wave.h, wave.ky)\n      gl.uniform1f(U.ph, wave.ph)\n      gl.uniform2f(U.rec, wave.r, wave.rl)\n      gl.uniform4f(U.cam, r.fx, r.fy, r.shift, r.dist)\n      gl.uniform3f(U.cam2, r.camY, 0.3, r.dist + 12)\n      gl.uniform1f(U.viewH, viewH)\n      gl.uniform1f(U.radius, r.radius)\n      gl.uniform1f(U.hair, dpr)\n      gl.uniform3f(U.bg, ...colors[0])\n      gl.uniform3f(U.fg, ...colors[1])\n      gl.uniform4f(U.fog, FOG_START, r.end + 0.5, FOG_DEPTH, st.fog)\n      gl.uniform2f(U.edge, gl.drawingBufferWidth, r.band * dpr)\n      gl.uniform3f(U.light, -0.5 / L, 0.32 / L, 1 / L)\n      for (const c of list) {\n        const rect = atlas.rects[c.i]\n        if (!rect) continue\n        gl.uniform1f(U.xc, c.x)\n        gl.uniform1f(U.sc, c.s)\n        gl.uniform4f(U.rect, rect[0], rect[1], rect[2], rect[3])\n        gl.uniform1f(U.alpha, c.alpha)\n        gl.drawArrays(gl.TRIANGLE_STRIP, 0, (SEG + 1) * 2)\n      }\n    }\n\n    return {\n      draw,\n      resize: (_w: number, h: number, ratio: number) => {\n        viewH = h\n        dpr = ratio\n      },\n      theme: (c: Rgb[]) => {\n        colors = c\n      },\n      dispose: () => {\n        cancelAnimationFrame(settle)\n        gl.deleteBuffer(buf)\n        gl.deleteProgram(prog)\n        if (atlas) gl.deleteTexture(atlas.texture)\n      },\n    }\n  }, [])\n\n  const key = `${images.map((im) => im.src).join('\\n')}|${aspect}`\n  const gl = useGlStage(stage, build, key, {\n    animate,\n    maxDpr: 2,\n    colors: ['var(--background)', 'var(--foreground)', 'var(--muted)'],\n    className: 'pointer-events-none absolute inset-0 size-full opacity-0 transition-opacity duration-300 ease-out-quint data-ready:opacity-100 motion-reduce:transition-none',\n  })\n  const ready = gl.status === 'ready'\n\n  // The flat cards in CSS 3D, for when WebGL is not drawing: the same wave, the same camera.\n  const paint = useCallback(() => {\n    const st = live.current\n    const r = st.rig\n    if (!r || st.ready) return\n    const p = st.pos\n    const shown = new Set<number>()\n    for (const c of lay(r, r.wave, p, st.n, st.wraps)) {\n      const el = cards.current[c.i]\n      if (!el) continue\n      shown.add(c.i)\n      const z = waveZ(r.wave, c.x)\n      const mix = fogAt(r, st.fog, c.s, z)\n      const turn = Math.atan(-slopeZ(r.wave, c.x))\n      el.style.visibility = 'visible'\n      el.style.transform =\n        `translate3d(${(c.x * r.ppu).toFixed(2)}px, ${(-waveY(r.wave, c.x) * r.ppu).toFixed(2)}px, ${(z * r.ppu).toFixed(2)}px)` +\n        ` rotateY(${turn.toFixed(4)}rad)`\n      el.style.opacity = c.alpha.toFixed(3)\n      el.style.zIndex = String(1000 - Math.round(c.w * 50))\n      const veil = el.lastElementChild as HTMLElement\n      veil.style.opacity = mix.toFixed(3)\n    }\n    cards.current.forEach((el, i) => {\n      if (el && !shown.has(i)) el.style.visibility = 'hidden'\n    })\n  }, [])\n\n  const rule = useCallback((p: number) => {\n    const { n: count, wraps: w } = live.current\n    const at = w ? (((p % count) + count) % count) / count : (Math.min(Math.max(p, 0), count - 1) / Math.max(count - 1, 1)) * (1 - 1 / count)\n    ticks.current.forEach((el, k) => {\n      if (el) el.style.transform = `translateX(${((at - k) * 100).toFixed(3)}cqw)`\n    })\n  }, [])\n\n  const { redraw } = gl\n  const onFrame = useCallback(\n    (p: number, v: number) => {\n      live.current.pos = p\n      live.current.vel = v\n      redraw()\n      paint()\n      rule(p)\n    },\n    [redraw, paint, rule],\n  )\n\n  const engine = useCarouselEngine({\n    count: n,\n    loop: wraps,\n    index,\n    defaultIndex,\n    onIndexChange,\n    step: rig ? rig.spacing * rig.ppu : 300,\n    onFrame,\n  })\n  const current = engine.index\n\n  // The stage only exists while there are pictures, so watch it again when the first ones arrive.\n  const empty = !n\n  useLayoutEffect(() => {\n    const el = stage.current\n    if (!el) return\n    const ro = new ResizeObserver(([e]) => setWidth(Math.round(e.contentRect.width)))\n    ro.observe(el)\n    return () => ro.disconnect()\n  }, [empty])\n\n  // A new size, shape or set of pictures, or WebGL taking over or dropping out: draw the current frame again.\n  const { draw } = engine\n  useLayoutEffect(() => {\n    live.current.ready = ready\n    draw()\n  }, [draw, ready, width, aspect, amplitude, fog, n, wraps])\n\n  // The picture under a point on the stage, from the same maths the shader runs; the nearest wins.\n  const hit = (e: MouseEvent<HTMLElement> | PointerEvent<HTMLElement>) => {\n    const st = live.current\n    const r = st.rig\n    const wave = st.wave ?? r?.wave\n    const el = stage.current\n    if (!r || !wave || !el) return null\n    const box = el.getBoundingClientRect()\n    const px = e.clientX - box.left\n    const py = e.clientY - box.top\n    let best: number | null = null\n    for (const c of lay(r, wave, st.pos, st.n, st.wraps)) {\n      if (c.alpha * edgeAt(r, project(r, c.x, waveY(wave, c.x), waveZ(wave, c.x))[0]) < 0.3) continue\n      const outline: [number, number][] = []\n      for (const side of [1, -1]) {\n        for (let j = 0; j <= 8; j++) {\n          const ds = (side > 0 ? -0.5 + j / 8 : 0.5 - j / 8) * 2 * r.half[0]\n          const x = walk(wave, c.x, ds, 2)\n          const [sx, sy] = project(r, x, waveY(wave, x) + side * r.half[1], waveZ(wave, x))\n          outline.push([sx, sy])\n        }\n      }\n      let inside = false\n      for (let a = 0, b = outline.length - 1; a < outline.length; b = a++) {\n        const [xa, ya] = outline[a]\n        const [xb, yb] = outline[b]\n        if (ya > py !== yb > py && px < ((xb - xa) * (py - ya)) / (yb - ya) + xa) inside = !inside\n      }\n      // Drawn farthest first, so the last hit is the one in front.\n      if (inside) best = c.i\n    }\n    return best\n  }\n\n  const onClick = (e: MouseEvent<HTMLDivElement>) => {\n    if (!ready || e.defaultPrevented) return\n    const i = hit(e)\n    if (i !== null && i !== current) engine.go(i)\n  }\n\n  // A pointer over a picture away from the front shows that it can be clicked.\n  const onPointerMove = (e: PointerEvent<HTMLDivElement>) => {\n    engine.bind.onPointerMove(e)\n    const el = e.currentTarget\n    if (!ready || e.pointerType !== 'mouse' || 'dragging' in el.dataset) {\n      el.style.cursor = ''\n      return\n    }\n    const i = hit(e)\n    el.style.cursor = i !== null && i !== current ? 'pointer' : ''\n  }\n\n  const keys = (e: KeyboardEvent<HTMLDivElement>) => {\n    onKeyDown?.(e)\n    if (e.defaultPrevented || (e.target as HTMLElement).closest(TYPING)) return\n    if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') engine.move(e.key === 'ArrowRight' ? 1 : -1)\n    else if (e.key === 'Home') engine.go(0)\n    else if (e.key === 'End') engine.go(n - 1)\n    else return\n    e.preventDefault()\n  }\n\n  if (!n) return null\n\n  const atStart = !wraps && current === 0\n  const atEnd = !wraps && current === n - 1\n  const button =\n    'grid size-11 shrink-0 cursor-pointer place-items-center rounded-full bg-muted text-foreground [-webkit-tap-highlight-color:transparent] hover:bg-[color-mix(in_oklab,var(--foreground)_8%,var(--muted))] ' +\n    'transition-[opacity,transform] duration-150 ease-out-quint active:scale-[0.96] aria-disabled:cursor-default aria-disabled:opacity-35 aria-disabled:active:scale-100 motion-reduce:transition-none ' +\n    'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring'\n\n  return (\n    <div onKeyDown={keys} className={cn('w-full', className)} {...rest}>\n      <div\n        {...engine.bind}\n        ref={(el) => {\n          stage.current = el\n          engine.bind.ref(el)\n        }}\n        onPointerMove={onPointerMove}\n        onClick={onClick}\n        id={id}\n        role=\"group\"\n        aria-roledescription=\"carousel\"\n        aria-label={label}\n        tabIndex={0}\n        style={{ height: height || 300 }}\n        className={cn(\n          'relative isolate w-full touch-pan-y overflow-hidden rounded-[calc(var(--radius)*2+2px)] select-none [-webkit-tap-highlight-color:transparent]',\n          'cursor-grab data-dragging:cursor-grabbing',\n          'focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-ring',\n        )}\n      >\n        {/* The pictures for screen readers, and the picture itself until WebGL draws or when it cannot. */}\n        <div\n          style={\n            rig\n              ? {\n                  perspective: rig.dist * rig.ppu,\n                  perspectiveOrigin: `50% ${(((1 - rig.shift) / 2) * 100).toFixed(2)}%`,\n                  maskImage: `linear-gradient(to right, transparent, #000 ${rig.band}px, #000 calc(100% - ${rig.band}px), transparent)`,\n                }\n              : undefined\n          }\n          className={cn(\n            'absolute inset-0 transition-opacity duration-300 ease-out-quint motion-reduce:transition-none',\n            ready && 'pointer-events-none opacity-0',\n          )}\n        >\n          {rig &&\n            images.map((im, i) => {\n              const on = i === current\n              return (\n                <div\n                  key={i}\n                  ref={(el) => {\n                    cards.current[i] = el\n                  }}\n                  role=\"group\"\n                  aria-roledescription=\"slide\"\n                  aria-label={`${t.picture} ${i + 1} ${t.of} ${n}`}\n                  aria-hidden={!on}\n                  onClick={on || ready ? undefined : () => engine.go(i)}\n                  style={{\n                    width: rig.half[0] * 2 * rig.ppu,\n                    height: rig.half[1] * 2 * rig.ppu,\n                    marginLeft: -rig.half[0] * rig.ppu,\n                    marginTop: -rig.half[1] * rig.ppu,\n                  }}\n                  className={cn('absolute top-1/2 left-1/2 overflow-hidden rounded-[calc(var(--radius)+2px)] bg-muted', !on && 'invisible cursor-pointer')}\n                >\n                  <img\n                    inert={!on}\n                    src={im.src}\n                    alt={im.alt}\n                    draggable={false}\n                    decoding=\"async\"\n                    className=\"size-full object-cover [-webkit-user-drag:none]\"\n                  />\n                  <span aria-hidden className=\"pointer-events-none absolute inset-0 rounded-[inherit] shadow-[inset_0_0_0_1px_color-mix(in_oklab,var(--foreground)_9%,transparent)]\" />\n                  <span aria-hidden className=\"pointer-events-none absolute inset-0 bg-background opacity-0\" />\n                </div>\n              )\n            })}\n        </div>\n      </div>\n\n      {controls && n > 1 ? (\n        <div className=\"mx-auto mt-4 flex max-w-sm items-center gap-3\">\n          {/* aria-disabled, not disabled: a button that has focus keeps it when it reaches the end. */}\n          <button type=\"button\" aria-label={t.previous} aria-controls={id} aria-disabled={atStart} onClick={() => atStart || engine.move(-1)} className={button}>\n            <ChevronLeft className=\"size-[18px]\" strokeWidth={2} aria-hidden />\n          </button>\n          <div className=\"flex min-w-0 flex-1 flex-col gap-2\">\n            {/* A hairline rule with a primary tick, one picture's share of it long, that follows the position. In a\n                loop a second tick trails one rule-length behind, so the tick slides off one end and on at the other. */}\n            <div aria-hidden className=\"@container relative h-1 overflow-hidden rounded-full bg-muted\">\n              {(wraps ? [0, 1] : [0]).map((k) => (\n                <span\n                  key={k}\n                  ref={(el) => {\n                    ticks.current[k] = el\n                  }}\n                  style={{ width: `${100 / n}%` }}\n                  className=\"absolute inset-y-0 left-0 block rounded-full bg-primary\"\n                />\n              ))}\n            </div>\n            <p className=\"flex justify-between font-mono text-[11px] leading-none font-medium tracking-[0.04em] text-muted-foreground tabular-nums\">\n              <span aria-hidden>{String(current + 1).padStart(2, '0')}</span>\n              <span aria-hidden>{String(n).padStart(2, '0')}</span>\n            </p>\n          </div>\n          <button type=\"button\" aria-label={t.next} aria-controls={id} aria-disabled={atEnd} onClick={() => atEnd || engine.move(1)} className={button}>\n            <ChevronRight className=\"size-[18px]\" strokeWidth={2} aria-hidden />\n          </button>\n        </div>\n      ) : null}\n      <p aria-live=\"polite\" className=\"sr-only\">\n        {`${t.picture} ${current + 1} ${t.of} ${n}`}\n      </p>\n    </div>\n  )\n}\n",
      "type": "registry:component"
    },
    {
      "path": "registry/manniche/hooks/use-carousel-engine.ts",
      "content": "import { useEffect, useLayoutEffect, useState, type MouseEvent, type PointerEvent } from 'react'\nimport { useReducedMotion } from '@/registry/manniche/hooks/use-reduced-motion'\n\nexport type CarouselEngineOptions = {\n  /** How many slides there are. */\n  count: number\n  /** Wrap around from the last slide to the first. */\n  loop?: boolean\n  /** Controlled: the current slide. The carousel shows it, and goes back to it if `onIndexChange` does not update it. */\n  index?: number\n  /** The slide shown first, when uncontrolled. */\n  defaultIndex?: number\n  /** Called when the carousel heads for a new slide: on release, a key or a button, not when the glide ends. */\n  onIndexChange?: (index: number) => void\n  /** The drag direction. `x` also takes sideways wheel and trackpad swipes. */\n  axis?: 'x' | 'y'\n  /** Pixels of drag that move the carousel one slide. Negative turns the drag round, e.g. pull down for the next slide. */\n  step: number\n  /** Come to rest on a whole slide. Off, a fling glides to a stop anywhere. */\n  snap?: boolean\n  /** Draws a frame: the position in slides (fractional while moving) and the speed in slides per second. */\n  onFrame: (position: number, velocity: number) => void\n}\n\nexport type CarouselEngine = {\n  /** The slide the carousel is on or heading to. */\n  index: number\n  /** Go to a slide. In a loop it takes the short way round. */\n  go: (index: number) => void\n  /** Move by a number of slides from where the carousel is heading. */\n  move: (by: number) => void\n  /** Draw the current frame again, e.g. after a resize. */\n  draw: () => void\n  /** Spread on the element that takes the drag. */\n  bind: {\n    ref: (el: HTMLElement | null) => void\n    onPointerDown: (e: PointerEvent<HTMLElement>) => void\n    onPointerMove: (e: PointerEvent<HTMLElement>) => void\n    onPointerUp: (e: PointerEvent<HTMLElement>) => void\n    onPointerCancel: (e: PointerEvent<HTMLElement>) => void\n    onClickCapture: (e: MouseEvent<HTMLElement>) => void\n  }\n}\n\ntype Settings = Required<Pick<CarouselEngineOptions, 'loop' | 'axis' | 'snap' | 'step' | 'onFrame'>> &\n  Pick<CarouselEngineOptions, 'onIndexChange'> & { n: number; reduce: boolean }\n\nconst SLOP = 6 // px before a press becomes a drag\nconst THROW = 0.32 // s: how far a fling carries, as speed × this\nconst SAMPLE = 90 // ms of pointer history used for the release speed\nconst mod = (v: number, n: number) => ((v % n) + n) % n\nconst clamp = (v: number, a: number, b: number) => Math.min(b, Math.max(a, v))\n// Pixels per slide, kept away from zero but with its sign.\nconst per = (step: number) => (step < 0 ? -1 : 1) * Math.max(Math.abs(step), 1)\n// Past an end the carousel gives less and less, and never more than one slide.\nconst rubber = (over: number) => 1 - 1 / (over * 0.55 + 1)\n\n/**\n * The motion behind the carousels: one position, in slides, that drag, fling, wheel, keys and buttons all move.\n * It runs a frame loop only while something moves and hands each frame to `onFrame`, which writes transforms\n * straight to the DOM, so React renders only when the slide changes. Glides use ease-out-quint: 300 ms for a\n * step, and after a fling a duration that starts at the finger's speed. Under reduced motion every move jumps.\n */\nexport function useCarouselEngine(options: CarouselEngineOptions): CarouselEngine {\n  const { count, loop = false, index, defaultIndex = 0, axis = 'x', snap = true, step, onFrame, onIndexChange } = options\n  const n = Math.max(count, 1)\n  const reduce = useReducedMotion()\n  const [current, setCurrent] = useState(() => clamp(index ?? defaultIndex, 0, n - 1))\n  const [m] = useState(() => machine(current, setCurrent))\n  const [surface, setSurface] = useState<HTMLElement | null>(null)\n\n  // The latest options, for the handlers and the frame loop, which outlive a render.\n  useLayoutEffect(() => {\n    m.configure({ n, loop, axis, snap, step, onFrame, onIndexChange, reduce })\n  })\n\n  // A new count, or a loop turned on or off, puts the carousel back on a slide it has.\n  useEffect(() => m.reseat(), [n, loop, m])\n  // Controlled: follow the index from outside, and go back to it when a move was not taken up. Neither calls\n  // onIndexChange, as the parent already knows.\n  const controlled = index !== undefined\n  const target = clamp(index ?? 0, 0, n - 1)\n  useEffect(() => {\n    if (controlled && target !== m.committed) m.go(target, false)\n  })\n\n  useEffect(() => (surface && axis === 'x' ? m.listenWheel(surface) : undefined), [surface, axis, m])\n  useEffect(() => m.stop, [m])\n\n  return { index: controlled ? target : current, go: m.go, move: m.move, draw: m.draw, bind: { ref: setSurface, ...m.handlers } }\n}\n\ntype Tween = { from: number; to: number; start: number; dur: number }\ntype Drag = { id: number; x: number; y: number; p0: number; active: boolean; samples: [number, number][]; resume: number | null }\n\n// The state and behaviour, made once per carousel and kept for its lifetime.\nfunction machine(start: number, setCurrent: (i: number) => void) {\n  let want = start // where a drag or the wheel puts the carousel\n  let drawn = start // the position on screen\n  let velocity = 0\n  let tween: Tween | null = null\n  let drag: Drag | null = null\n  let raf = 0\n  let last = 0\n  let swallowClick = false\n  let wheelTimer = 0\n\n  const m = {\n    set: null as Settings | null,\n    committed: start,\n    configure: (settings: Settings) => {\n      m.set = settings\n    },\n    go,\n    move,\n    reseat,\n    draw,\n    stop,\n    listenWheel,\n    handlers: {\n      onPointerDown,\n      onPointerMove,\n      onPointerUp: (e: PointerEvent<HTMLElement>) => release(e, false),\n      onPointerCancel: (e: PointerEvent<HTMLElement>) => release(e, true),\n      onClickCapture,\n    },\n  }\n\n  function draw() {\n    m.set?.onFrame(drawn, velocity)\n  }\n\n  function tick(now: number) {\n    raf = 0\n    const o = m.set\n    if (!o) return\n    let p = want\n    if (tween) {\n      const u = clamp((now - tween.start) / tween.dur, 0, 1)\n      p = tween.from + (tween.to - tween.from) * (1 - (1 - u) ** 5)\n      if (u >= 1) tween = null\n    }\n    const dt = Math.max(now - last, 1) / 1000\n    last = now\n    // Smoothed over about 60 ms, so a layout can lean into the speed without jitter.\n    velocity = o.reduce ? 0 : velocity + ((p - drawn) / dt - velocity) * (1 - Math.exp(-dt / 0.06))\n    drawn = p\n    const moving = tween || drag?.active || Math.abs(velocity) > 0.01\n    if (!moving) velocity = 0\n    o.onFrame(p, velocity)\n    if (moving) raf = requestAnimationFrame(tick)\n  }\n\n  function run() {\n    if (raf) return\n    last = performance.now()\n    raf = requestAnimationFrame(tick)\n  }\n\n  function commit(to: number, notify = true) {\n    const o = m.set\n    if (!o) return\n    const i = mod(Math.round(to), o.n)\n    if (i === m.committed) return\n    m.committed = i\n    setCurrent(i)\n    if (notify) o.onIndexChange?.(i)\n  }\n\n  // Glide to a position. With a release speed (slides/s) in the same direction, the glide starts at that speed.\n  function glide(to: number, speed = 0) {\n    want = to\n    const dist = to - drawn\n    if (m.set?.reduce || Math.abs(dist) < 1e-4) tween = null\n    else {\n      const dur = speed && Math.sign(speed) === Math.sign(dist) ? clamp(((5 * Math.abs(dist)) / Math.abs(speed)) * 1000, 220, 900) : 300\n      tween = { from: drawn, to, start: performance.now(), dur }\n    }\n    run()\n  }\n\n  function go(i: number, notify = true) {\n    const o = m.set\n    if (!o || mod(i, o.n) === m.committed) return\n    let to: number\n    if (o.loop) {\n      const at = Math.round(tween?.to ?? want)\n      to = at + mod(i - at + o.n / 2, o.n) - o.n / 2\n      // An even count puts the far slide exactly half way round: go forwards.\n      if (to < at && mod(i - at, o.n) === o.n / 2) to = at + o.n / 2\n    } else to = clamp(i, 0, o.n - 1)\n    glide(to)\n    commit(to, notify)\n  }\n\n  // After the count or the loop changes: jump to the current slide, or the last one if it is gone. A position\n  // wound past the ends of a loop means nothing in the new count, so it is unwound too.\n  function reseat() {\n    const o = m.set\n    if (!o) return\n    const i = clamp(m.committed, 0, o.n - 1)\n    if (want === i && drawn === i && !tween) return\n    tween = null\n    velocity = 0\n    want = drawn = i\n    commit(i)\n    draw()\n  }\n\n  function move(by: number) {\n    const o = m.set\n    if (!o) return\n    let to = Math.round(tween?.to ?? want) + by\n    if (!o.loop) to = clamp(to, 0, o.n - 1)\n    glide(to)\n    commit(to)\n  }\n\n  function stop() {\n    cancelAnimationFrame(raf)\n    clearTimeout(wheelTimer)\n    raf = 0\n    tween = null\n    drag = null\n    velocity = 0\n    // Land where it was heading, so a remount starts settled.\n    drawn = want\n  }\n\n  // Where a position lands once the ends of a carousel that does not loop push back.\n  function give(raw: number) {\n    const o = m.set!\n    if (o.loop) return raw\n    if (raw < 0) return -rubber(-raw)\n    if (raw > o.n - 1) return o.n - 1 + rubber(raw - (o.n - 1))\n    return raw\n  }\n\n  function settle(speed: number, from: number) {\n    const o = m.set!\n    let to = drawn + speed * THROW\n    if (o.snap) {\n      to = Math.round(to)\n      // A quick flick always moves at least one slide.\n      if (Math.abs(speed) > 0.8 && to === Math.round(from)) to += Math.sign(speed)\n    }\n    if (!o.loop) to = clamp(to, 0, o.n - 1)\n    glide(to, speed)\n    commit(to)\n  }\n\n  function onPointerDown(e: PointerEvent<HTMLElement>) {\n    swallowClick = false\n    // A press that left the carousel before it became a drag never got its pointerup.\n    if (drag && !drag.active) drop(drag)\n    if (!e.isPrimary || e.button !== 0 || drag || !m.set || m.set.n < 2) return\n    const resume = tween ? tween.to : null\n    // Catch a moving carousel where it is.\n    if (tween) {\n      tween = null\n      want = drawn\n    }\n    drag = { id: e.pointerId, x: e.clientX, y: e.clientY, p0: drawn, active: false, samples: [[e.timeStamp, drawn]], resume }\n  }\n\n  function onPointerMove(e: PointerEvent<HTMLElement>) {\n    const d = drag\n    const o = m.set\n    if (!d || !o || e.pointerId !== d.id) return\n    // The mouse came back with its button up, so it was let go outside the carousel.\n    if (!d.active && !(e.buttons & 1)) return drop(d)\n    const dx = e.clientX - d.x\n    const dy = e.clientY - d.y\n    const along = o.axis === 'x' ? dx : dy\n    const across = o.axis === 'x' ? dy : dx\n    if (!d.active) {\n      if (Math.abs(along) < SLOP && Math.abs(across) < SLOP) return\n      // Moving across the carousel: leave it to the page.\n      if (Math.abs(across) >= Math.abs(along)) return drop(d)\n      d.active = true\n      // Count from here, so the slop does not make the slides jump.\n      if (o.axis === 'x') d.x += Math.sign(dx) * SLOP\n      else d.y += Math.sign(dy) * SLOP\n      e.currentTarget.setPointerCapture(e.pointerId)\n      e.currentTarget.dataset.dragging = ''\n    }\n    const p = give(d.p0 - (o.axis === 'x' ? e.clientX - d.x : e.clientY - d.y) / per(o.step))\n    want = p\n    d.samples.push([e.timeStamp, p])\n    while (d.samples.length > 2 && e.timeStamp - d.samples[0][0] > SAMPLE) d.samples.shift()\n    run()\n  }\n\n  function release(e: PointerEvent<HTMLElement>, cancelled: boolean) {\n    const d = drag\n    if (!d || e.pointerId !== d.id) return\n    delete e.currentTarget.dataset.dragging\n    if (!d.active) return drop(d)\n    drag = null\n    swallowClick = true\n    let speed = 0\n    const [t0, p0] = d.samples[0]\n    const [t1, p1] = d.samples[d.samples.length - 1]\n    // A finger that stopped before letting go throws nothing.\n    if (!cancelled && t1 > t0 && e.timeStamp - t1 < 60) speed = ((p1 - p0) / (t1 - t0)) * 1000\n    settle(speed, d.p0)\n  }\n\n  // Let go of a press that never became a drag, and finish any glide it caught.\n  function drop(d: Drag) {\n    drag = null\n    if (d.resume !== null) glide(d.resume)\n  }\n\n  // A drag ends with a click on whatever was under the pointer; that click is not meant.\n  function onClickCapture(e: MouseEvent<HTMLElement>) {\n    if (!swallowClick) return\n    swallowClick = false\n    e.preventDefault()\n    e.stopPropagation()\n  }\n\n  // Sideways wheel and trackpad swipes. A vertical wheel is left to the page.\n  function listenWheel(el: HTMLElement) {\n    let base: number | null = null\n    const onWheel = (e: WheelEvent) => {\n      const o = m.set\n      const dx = e.deltaX || (e.shiftKey ? e.deltaY : 0)\n      if (!o || o.n < 2 || Math.abs(dx) <= Math.abs(e.shiftKey ? 0 : e.deltaY)) return\n      e.preventDefault()\n      if (drag?.active) return\n      tween = null\n      base = (base ?? drawn) + (dx * (e.deltaMode === 1 ? 16 : 1)) / per(o.step)\n      if (!o.loop) base = clamp(base, -1.5, o.n + 0.5)\n      want = give(base)\n      run()\n      clearTimeout(wheelTimer)\n      wheelTimer = window.setTimeout(() => {\n        base = null\n        settle(0, drawn)\n      }, 140)\n    }\n    el.addEventListener('wheel', onWheel, { passive: false })\n    return () => {\n      el.removeEventListener('wheel', onWheel)\n      clearTimeout(wheelTimer)\n    }\n  }\n\n  return m\n}\n",
      "type": "registry:hook"
    },
    {
      "path": "registry/manniche/hooks/use-gl-stage.ts",
      "content": "import { useCallback, useEffect, useLayoutEffect, useRef, useState, type RefObject } from 'react'\nimport { useReducedMotion } from '@/registry/manniche/hooks/use-reduced-motion'\n\n/** A picture for a WebGL carousel. The alt text is what screen readers read; the canvas itself is hidden from them. */\nexport type GlImage = { src: string; alt: string }\n\nexport type Rgb = [number, number, number]\n\nexport type GlSceneContext = {\n  gl: WebGLRenderingContext\n  canvas: HTMLCanvasElement\n  /** Call once the scene has what it needs for its first frame, e.g. after its pictures load. The canvas fades in. */\n  ready: () => void\n  /** Draw again, e.g. once a texture has loaded. */\n  redraw: () => void\n  /** Call when the scene cannot run after all, e.g. its pictures could not be uploaded. The stage reports `failed`. */\n  fail: () => void\n  /** The theme's colours when the scene is built, in the order of `colors`, e.g. for a texture's empty cells. */\n  colors: Rgb[]\n  /** Set when the stage is torn down, so work that finishes later can stop. */\n  signal: AbortSignal\n}\n\nexport type GlScene = {\n  /** Draws a frame. `time` is in seconds; it only moves while the stage animates on its own and stands still under reduced motion. */\n  draw: (time: number) => void\n  /** The canvas has a new size in device pixels. The viewport is already set. */\n  resize?: (width: number, height: number, dpr: number) => void\n  /** The theme's colours, in the order of `colors`, as 0–1 RGB. Called before the first frame and on every theme change. */\n  theme?: (colors: Rgb[]) => void\n  /** Frees what the scene made. The context is released right after. */\n  dispose?: () => void\n}\n\nexport type GlStageOptions = {\n  /** Upper bound on device pixels per CSS pixel. */\n  maxDpr?: number\n  /** Upper bound on the canvas's device pixels; past it the canvas renders smaller and the browser scales it up. */\n  maxPixels?: number\n  /** A frame loop of its own while on screen, for motion that does not come from the carousel. Off under reduced motion. */\n  animate?: boolean\n  /** CSS colours the scene needs, e.g. `var(--background)`. Read from the host, so they follow the theme. */\n  colors?: string[]\n  /** Classes for the canvas, which goes first in the host. */\n  className?: string\n  /** Context attributes on top of the defaults (no antialias, low power). */\n  attributes?: WebGLContextAttributes\n}\n\nexport type GlStage = {\n  /** `pending` until the scene is ready, `ready` once it has drawn, `failed` without WebGL or after the GPU drops the context. */\n  status: 'pending' | 'ready' | 'failed'\n  /** Draw a frame now, e.g. from a carousel's `onFrame`. Does nothing before the scene exists. */\n  redraw: () => void\n}\n\n// Seconds of animation that a still frame shows under reduced motion, so it is not the plain first frame.\nconst STILL = 4\n\n/**\n * Runs a WebGL scene in a canvas inside `host`: a fresh canvas each run, sized to the host with a cap on pixels,\n * the theme's colours read live, its own frame loop only while on screen, and the context released on teardown or\n * failure, so a page never holds more than it uses. `build` makes the scene; it runs again when `key` changes, so put\n * everything the scene is built from in it, e.g. the pictures' addresses. Return null from `build` when the scene cannot\n * run, and the stage reports `failed`.\n */\nexport function useGlStage(\n  host: RefObject<HTMLElement | null>,\n  build: (ctx: GlSceneContext) => GlScene | null,\n  key: string,\n  { maxDpr = 2, maxPixels = 2_400_000, animate = false, colors = [], className = '', attributes }: GlStageOptions = {},\n): GlStage {\n  const reduce = useReducedMotion()\n  const [status, setStatus] = useState<GlStage['status']>('pending')\n  // The live scene's draw, for redraw(); null between runs.\n  const live = useRef<(() => void) | null>(null)\n  const palette = colors.join('|')\n  const attrs = JSON.stringify(attributes ?? {})\n  // The latest build, so a new function each render does not rebuild the scene; `key` does.\n  const make = useRef(build)\n  useLayoutEffect(() => {\n    make.current = build\n  })\n\n  useEffect(() => {\n    const wrap = host.current\n    if (!wrap) return\n    const abort = new AbortController()\n    // Reported after the effect, and only while this run is the live one.\n    const report = (s: GlStage['status']) => queueMicrotask(() => abort.signal.aborted || setStatus(s))\n    report('pending')\n    // A fresh canvas per run: a canvas whose context was lost cannot hand out a new one.\n    const el = document.createElement('canvas')\n    el.setAttribute('aria-hidden', 'true')\n    el.className = className\n    wrap.prepend(el)\n\n    const options: WebGLContextAttributes = { antialias: false, alpha: true, premultipliedAlpha: true, powerPreference: 'low-power', ...JSON.parse(attrs) }\n    const gl = el.getContext('webgl', options)\n    if (!gl) {\n      el.remove()\n      report('failed')\n      return () => abort.abort()\n    }\n\n    let scene: GlScene | null = null\n    let dead = false\n    let shown = false\n    let clock = STILL\n    let raf = 0\n    let last = 0\n    let visible = false\n    const looping = animate && !reduce\n\n    const frame = () => {\n      if (!dead && scene) scene.draw(clock)\n    }\n    let released = false\n    const release = () => {\n      if (released) return\n      released = true\n      dead = true\n      live.current = null\n      cancelAnimationFrame(raf)\n      abort.abort()\n      try {\n        scene?.dispose?.()\n      } catch {\n        // The context may already be gone; there is nothing left to free.\n      }\n      gl.getExtension('WEBGL_lose_context')?.loseContext()\n      el.remove()\n    }\n\n    // The theme's colours, read through a 1 px canvas so any CSS colour (oklch, color-mix, var) comes out as RGB.\n    const probe = document.createElement('canvas').getContext('2d', { willReadFrequently: true })\n    const wanted = palette ? palette.split('|') : []\n    const read = () => {\n      const style = getComputedStyle(wrap)\n      return wanted.map((c): Rgb => {\n        const value = c.startsWith('var(') ? style.getPropertyValue(c.slice(4, -1).split(',')[0].trim()).trim() || '#808080' : c\n        if (!probe) return [0.5, 0.5, 0.5]\n        probe.clearRect(0, 0, 1, 1)\n        probe.fillStyle = '#808080'\n        probe.fillStyle = value\n        probe.fillRect(0, 0, 1, 1)\n        const [r, g, b] = probe.getImageData(0, 0, 1, 1).data\n        return [r / 255, g / 255, b / 255]\n      })\n    }\n\n    const ctx: GlSceneContext = {\n      gl,\n      canvas: el,\n      signal: abort.signal,\n      colors: read(),\n      fail: () => {\n        if (dead) return\n        release()\n        queueMicrotask(() => setStatus('failed'))\n      },\n      redraw: () => {\n        // A running loop draws on its next frame anyway.\n        if (!(looping && visible)) frame()\n      },\n      ready: () => {\n        if (dead || shown) return\n        shown = true\n        frame()\n        // Wait a frame so the canvas fades in instead of popping.\n        requestAnimationFrame(() => {\n          if (dead) return\n          el.dataset.ready = ''\n          report('ready')\n        })\n      },\n    }\n\n    try {\n      scene = make.current(ctx)\n    } catch {\n      scene = null\n    }\n    // Free the context straight away, so a scene that cannot run does not hold one of the page's few.\n    if (!scene) {\n      release()\n      queueMicrotask(() => setStatus('failed'))\n      return\n    }\n    live.current = ctx.redraw\n\n    const theme = () => {\n      if (dead || !scene?.theme || !wanted.length) return\n      scene.theme(read())\n      ctx.redraw()\n    }\n    theme()\n    // The theme changes through a class or inline variables on <html>, or the system's colour scheme.\n    const mo = new MutationObserver(theme)\n    mo.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'style', 'data-theme'] })\n    const scheme = window.matchMedia('(prefers-color-scheme: dark)')\n    scheme.addEventListener('change', theme)\n\n    const resize = () => {\n      if (dead) return\n      const w = el.clientWidth\n      const h = el.clientHeight\n      let dpr = Math.min(maxDpr, window.devicePixelRatio || 1)\n      if (w * h * dpr * dpr > maxPixels) dpr = Math.sqrt(maxPixels / Math.max(1, w * h))\n      el.width = Math.max(1, Math.round(w * dpr))\n      el.height = Math.max(1, Math.round(h * dpr))\n      gl.viewport(0, 0, el.width, el.height)\n      scene?.resize?.(el.width, el.height, dpr)\n      frame()\n    }\n    const ro = new ResizeObserver(resize)\n    ro.observe(el)\n    resize()\n\n    const loop = (now: number) => {\n      // Cap the step so a stalled tab does not jump the motion ahead.\n      clock += Math.min(50, now - (last || now)) / 1000\n      last = now\n      frame()\n      raf = requestAnimationFrame(loop)\n    }\n    // Only animate while on screen.\n    const io = new IntersectionObserver(([entry]) => {\n      if (dead || !looping || entry.isIntersecting === visible) return\n      visible = entry.isIntersecting\n      last = 0\n      if (visible) raf = requestAnimationFrame(loop)\n      else cancelAnimationFrame(raf)\n    })\n    io.observe(el)\n\n    // If the GPU drops the context, the component shows its fallback again.\n    const lost = (e: Event) => {\n      e.preventDefault()\n      dead = true\n      live.current = null\n      cancelAnimationFrame(raf)\n      delete el.dataset.ready\n      report('failed')\n    }\n    el.addEventListener('webglcontextlost', lost)\n\n    return () => {\n      ro.disconnect()\n      io.disconnect()\n      mo.disconnect()\n      scheme.removeEventListener('change', theme)\n      el.removeEventListener('webglcontextlost', lost)\n      release()\n    }\n  }, [host, key, reduce, animate, maxDpr, maxPixels, palette, className, attrs])\n\n  const redraw = useCallback(() => live.current?.(), [])\n  return { status, redraw }\n}\n\n/**\n * Compiles and links a program, or returns null so the caller can fall back; the reason goes to the console unless the\n * context was lost. A uniform used in both shaders must have the same precision in each, or linking fails.\n */\nexport function glProgram(gl: WebGLRenderingContext, vertex: string, fragment: string) {\n  const program = gl.createProgram()\n  if (!program) return null\n  const log: string[] = []\n  for (const [type, src] of [\n    [gl.VERTEX_SHADER, vertex],\n    [gl.FRAGMENT_SHADER, fragment],\n  ] as const) {\n    const s = gl.createShader(type)\n    if (!s) {\n      gl.deleteProgram(program)\n      return null\n    }\n    gl.shaderSource(s, src)\n    gl.compileShader(s)\n    if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) log.push(gl.getShaderInfoLog(s) ?? '')\n    gl.attachShader(program, s)\n    // Flagged for deletion; it lives until the program goes.\n    gl.deleteShader(s)\n  }\n  gl.linkProgram(program)\n  if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {\n    if (!gl.isContextLost()) console.warn('WebGL program failed:', log.join('\\n') || gl.getProgramInfoLog(program))\n    gl.deleteProgram(program)\n    return null\n  }\n  return program\n}\n\nexport type GlAtlas = {\n  /** The texture, power-of-two sized, with mipmaps. */\n  texture: WebGLTexture\n  /** Each picture's corner in the atlas as [u0, v0, u1, v1], with v growing downwards (the texture is not flipped). */\n  rects: [number, number, number, number][]\n  /** False for a picture that did not load; its cell shows `empty` instead. */\n  loaded: boolean[]\n  /** A cell's width and height in texels, without its gutter. */\n  cell: [number, number]\n  /** The texture's width and height in texels. */\n  size: [number, number]\n}\n\nconst pow2 = (v: number) => 2 ** Math.ceil(Math.log2(Math.max(1, v)))\n\nfunction load(src: string, signal: AbortSignal) {\n  return new Promise<HTMLImageElement | null>((resolve) => {\n    const img = new Image()\n    // A picture from another origin must send CORS headers to be drawn into WebGL; without them it shows as empty.\n    if (!/^(data|blob):/.test(src)) img.crossOrigin = 'anonymous'\n    img.decoding = 'async'\n    img.onload = () => resolve(img)\n    img.onerror = () => resolve(null)\n    signal.addEventListener('abort', () => resolve(null), { once: true })\n    img.src = src\n  })\n}\n\nexport type GlAtlasOptions = {\n  /** The pictures' width over height; each is cropped from the middle to fill a cell of this shape. */\n  aspect: number\n  /** The longer side of a cell in texels, at most. Cells shrink to keep the texture within `limit`. */\n  cell?: number\n  /** The texture's largest side in texels. A 2048 atlas with mipmaps takes about 22 MB of GPU memory, a 4096 one four times that. */\n  limit?: number\n  /** The colour of a cell whose picture did not load. */\n  empty?: Rgb\n  signal: AbortSignal\n}\n\n/**\n * Loads pictures and paints them, cropped to fill a cell of `aspect` (width over height), into one texture. Each cell\n * has a gutter of its own edge pixels, so mipmaps and filtering never bleed one picture into the next. Resolves to\n * null if the stage was torn down meanwhile, or if the pictures could not be uploaded.\n */\nexport async function glAtlas(\n  gl: WebGLRenderingContext,\n  images: GlImage[],\n  { aspect, cell = 1024, limit = 2048, empty = [0.5, 0.5, 0.5], signal }: GlAtlasOptions,\n): Promise<GlAtlas | null> {\n  const n = Math.max(images.length, 1)\n  const cols = Math.ceil(Math.sqrt(n * aspect) / aspect) || 1\n  const rows = Math.ceil(n / cols)\n  const gutter = 4\n  // The largest cell in the picture's shape that fits the grid within the limit; the limit is a power of two, so the\n  // texture never rounds up past it.\n  const max = Math.min(pow2(limit), gl.getParameter(gl.MAX_TEXTURE_SIZE) as number)\n  const w = aspect >= 1 ? 1 : aspect\n  const h = aspect >= 1 ? 1 / aspect : 1\n  const size = Math.max(16, Math.floor(Math.min(cell, (max / cols - gutter * 2) / w, (max / rows - gutter * 2) / h)))\n  const cw = Math.max(1, Math.floor(size * w))\n  const ch = Math.max(1, Math.floor(size * h))\n  const W = pow2((cw + gutter * 2) * cols)\n  const H = pow2((ch + gutter * 2) * rows)\n\n  const pictures = await Promise.all(images.map((im) => load(im.src, signal)))\n  if (signal.aborted) return null\n\n  const canvas = document.createElement('canvas')\n  canvas.width = W\n  canvas.height = H\n  const c = canvas.getContext('2d')\n  if (!c) return null\n  c.imageSmoothingQuality = 'high'\n  const fill = `rgb(${empty.map((v) => Math.round(v * 255)).join(' ')})`\n  const rects: GlAtlas['rects'] = []\n  const loaded: boolean[] = []\n\n  pictures.forEach((img, i) => {\n    const x = (i % cols) * (cw + gutter * 2) + gutter\n    const y = Math.floor(i / cols) * (ch + gutter * 2) + gutter\n    rects.push([x / W, y / H, (x + cw) / W, (y + ch) / H])\n    const ok = !!img && img.naturalWidth > 0\n    loaded.push(ok)\n    if (!ok) {\n      c.fillStyle = fill\n      c.fillRect(x - gutter, y - gutter, cw + gutter * 2, ch + gutter * 2)\n      return\n    }\n    // Crop to fill the cell, from the middle.\n    const k = Math.max(cw / img.naturalWidth, ch / img.naturalHeight)\n    const sw = cw / k\n    const sh = ch / k\n    const sx = (img.naturalWidth - sw) / 2\n    const sy = (img.naturalHeight - sh) / 2\n    c.drawImage(img, sx, sy, sw, sh, x, y, cw, ch)\n    // The gutter repeats the cell's outermost pixels.\n    c.drawImage(canvas, x, y, cw, 1, x, y - gutter, cw, gutter)\n    c.drawImage(canvas, x, y + ch - 1, cw, 1, x, y + ch, cw, gutter)\n    c.drawImage(canvas, x, y - gutter, 1, ch + gutter * 2, x - gutter, y - gutter, gutter, ch + gutter * 2)\n    c.drawImage(canvas, x + cw - 1, y - gutter, 1, ch + gutter * 2, x + cw, y - gutter, gutter, ch + gutter * 2)\n  })\n\n  const texture = gl.createTexture()\n  if (!texture || gl.isContextLost()) return null\n  gl.bindTexture(gl.TEXTURE_2D, texture)\n  gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true)\n  try {\n    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, canvas)\n  } catch {\n    // A picture tainted the canvas; nothing can be uploaded.\n    gl.deleteTexture(texture)\n    return null\n  }\n  gl.generateMipmap(gl.TEXTURE_2D)\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR)\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)\n  const aniso = gl.getExtension('EXT_texture_filter_anisotropic')\n  if (aniso) gl.texParameterf(gl.TEXTURE_2D, aniso.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(8, gl.getParameter(aniso.MAX_TEXTURE_MAX_ANISOTROPY_EXT)))\n  return { texture, rects, loaded, cell: [cw, ch], size: [W, H] }\n}\n",
      "type": "registry:hook"
    },
    {
      "path": "registry/manniche/hooks/use-reduced-motion.ts",
      "content": "import { useSyncExternalStore } from 'react'\n\nconst QUERY = '(prefers-reduced-motion: reduce)'\n\nfunction subscribe(onChange: () => void) {\n  const mq = window.matchMedia(QUERY)\n  mq.addEventListener('change', onChange)\n  return () => mq.removeEventListener('change', onChange)\n}\n\n/** True when the visitor has asked the system for less motion. */\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(QUERY).matches,\n    () => false,\n  )\n}\n",
      "type": "registry:hook"
    }
  ],
  "categories": [
    "widgets"
  ],
  "type": "registry:component"
}