{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "lens-strip",
  "title": "Lens strip",
  "description": "A strip of pictures sliding behind a fixed lens of thick glass that magnifies the one in it, bends it at the bevelled rim with faint colour fringes, and smears it a little while moving. WebGL, with a DOM fallback.",
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "utils"
  ],
  "files": [
    {
      "path": "registry/manniche/lens-strip/lens-strip.tsx",
      "content": "import { ChevronLeft, ChevronRight } from 'lucide-react'\nimport { useCallback, useId, useLayoutEffect, useMemo, useRef, useState, type HTMLAttributes, type KeyboardEvent } from 'react'\nimport { useCarouselEngine } from '@/registry/manniche/hooks/use-carousel-engine'\nimport { glAtlas, glProgram, useGlStage, type GlAtlas, type GlImage, type GlScene, type GlSceneContext, type Rgb } from '@/registry/manniche/hooks/use-gl-stage'\nimport { useReducedMotion } from '@/registry/manniche/hooks/use-reduced-motion'\nimport { cn } from '@/lib/utils'\n\n/*\n * A strip of pictures that slides behind a fixed lens of thick, clear glass. Through the lens the strip is magnified,\n * so the picture at rest fills it; near the rim a bevel bends the image inwards and splits it into faint colour\n * fringes, as real glass does. While the strip moves, its speed adds a little more dispersion and a slight sideways\n * smear inside the lens, and both settle back to clean glass as it comes to rest.\n *\n * One fragment shader draws the whole stage: each pixel maps to a point on the strip, and from there to the picture in\n * a texture atlas. Outside the lens that point is the pixel itself; inside it, the point is magnified about the lens's\n * centre and pushed along the bevel's slope, separately for red, green and blue. The engine drives the position, and\n * a frame is drawn only while something moves.\n *\n * Under reduced motion every move jumps and the lens shows one still, clean frame. Without WebGL, or when the GPU drops\n * the context, the pictures themselves are the carousel: the same strip in the DOM, with the picture in the middle\n * raised to the lens's size. They are always there for screen readers.\n */\n\n/** A picture in the strip. `title` is shown under the lens. */\nexport type LensStripImage = GlImage & { title?: string }\n\nexport type LensStripProps = Omit<HTMLAttributes<HTMLDivElement>, 'onChange'> & {\n  /** The pictures, in order. Pictures from another origin must send CORS headers, or they show as empty cards. */\n  images: LensStripImage[]\n  /** Read by screen readers, e.g. “Landscapes”. */\n  label: string\n  /** Controlled: the picture in the lens. */\n  index?: number\n  /** The picture in the lens at first, when uncontrolled. */\n  defaultIndex?: number\n  /** Called when the strip 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. */\n  loop?: boolean\n  /** Picture width over height. The lens takes the same shape. */\n  aspect?: number\n  /** How much larger the strip looks through the lens. */\n  magnify?: number\n  /** How strongly the glass splits light into colour at its rim, from 0 (none) to 1. */\n  dispersion?: number\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\"]'\nconst COLORS = ['var(--background)', 'var(--foreground)']\nconst CANVAS = '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// Parts of the stage's width over which the strip fades out at each side.\nconst FADE = 0.16\n// How far the bevel bends the view at the rim, as a part of its width, and how much of that the picture covers: the\n// rest shows the picture's own edge curving away, which is what makes the glass read as thick.\nconst BEND = 1\nconst COVER = 0.45\n\nconst clamp = (v: number, a: number, b: number) => Math.min(b, Math.max(a, v))\nconst mod = (v: number, n: number) => ((v % n) + n) % n\nconst pad = (v: number) => String(v).padStart(2, '0')\n\ntype Geometry = {\n  width: number\n  height: number\n  /** A card in the strip, in CSS px. */\n  cardW: number\n  cardH: number\n  cardR: number\n  pitch: number\n  /** The lens, in CSS px. */\n  lensW: number\n  lensH: number\n  lensR: number\n  bevel: number\n  /** How far the view bends at the rim, in lens px. */\n  bend: number\n  /** Card to lens scale. */\n  magnify: number\n}\n\n// Everything is sized from the lens: most of the stage's height, in the pictures' shape. The cards are the lens over\n// `magnify`, plus most of the bevel's bend, so the picture at rest fills the lens almost to its rim.\nfunction measure(width: number, aspect: number, magnify: number): Geometry {\n  // 16:7 on wide screens; taller on narrow ones, so the lens keeps a useful size.\n  const height = Math.round(Math.max((width * 7) / 16, Math.min(width * 0.72, 380)))\n  let lensH = height * 0.76\n  let lensW = lensH * aspect\n  if (lensW > width * 0.5) {\n    lensW = width * 0.5\n    lensH = lensW / aspect\n  }\n  const short = Math.min(lensW, lensH)\n  const bevel = short * 0.2\n  const bend = bevel * BEND\n  const cardW = (lensW + bend * COVER * 2) / magnify\n  const cardH = cardW / aspect\n  return {\n    width,\n    height,\n    cardW,\n    cardH,\n    cardR: clamp(cardW * 0.07, 8, 14),\n    pitch: cardW + Math.max(8, cardW * 0.075),\n    lensW,\n    lensH,\n    lensR: Math.max(bevel, short * 0.11),\n    bevel,\n    bend,\n    magnify,\n  }\n}\n\nconst VERTEX = `attribute vec2 a;void main(){gl_Position=vec4(a,0.,1.);}`\n\n// All lengths are CSS px from the stage's centre, with y going down like the atlas.\nconst FRAGMENT = `#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\nuniform sampler2D uTex;\nuniform vec3 uView;  // half width, half height, device px per CSS px\nuniform vec4 uLens;  // half width, half height, corner radius, bevel width\nuniform vec4 uCard;  // half width, half height, corner radius, pitch\nuniform vec4 uStrip; // position, count, loops (0 or 1), magnify\nuniform vec4 uGlass; // bend at the rim, dispersion, sideways colour split, smear\nuniform vec4 uCell;  // the first cell's corner and size in the atlas\nuniform vec3 uGrid;  // step from cell to cell, columns\nuniform vec3 uBody;  // the glass's own colour\nuniform vec4 uShade; // shadow, rim line, dark inner edge, side fade\n\nfloat box(vec2 p, vec2 b, float r) {\n  vec2 q = abs(p) - b + r;\n  return length(max(q, 0.)) + min(max(q.x, q.y), 0.) - r;\n}\n\n// The strip at a point: the card there as premultiplied colour, or nothing in a gap. aa is a device pixel in strip px.\nvec4 strip(vec2 s, float aa) {\n  float u = s.x / uCard.w + uStrip.x;\n  float i = floor(u + .5);\n  vec2 l = vec2((u - i) * uCard.w, s.y);\n  float a = clamp(.5 - box(l, uCard.xy, uCard.z) / aa, 0., 1.);\n  float k = i;\n  if (uStrip.z > .5) k = mod(i, uStrip.y);\n  else a *= step(-.5, i) * step(i, uStrip.y - .5);\n  k = floor(k + .5);\n  float row = floor((k + .5) / uGrid.z);\n  vec2 f = clamp(l / (2. * uCard.xy) + .5, 0., 1.);\n  return texture2D(uTex, uCell.xy + vec2(k - row * uGrid.z, row) * uGrid.xy + f * uCell.zw) * a;\n}\n\n// The strip seen through the glass at a lens point, laid over the glass's own colour, smeared sideways while moving.\nvec3 seen(vec2 c, float aa) {\n  vec4 s = strip(c, aa);\n  if (abs(uGlass.w) > .01) s = s * .5 + (strip(c - vec2(uGlass.w, 0.), aa) + strip(c + vec2(uGlass.w, 0.), aa)) * .25;\n  return s.rgb + uBody * (1. - s.a);\n}\n\nvoid main() {\n  float px = 1. / uView.z;\n  vec2 p = vec2(gl_FragCoord.x * px - uView.x, uView.y - gl_FragCoord.y * px);\n  float d = box(p, uLens.xy, uLens.z);\n\n  // Outside the lens: the plain strip, fading out towards the sides, under the lens's soft shadow.\n  vec4 o = vec4(0.);\n  if (d > -px) {\n    o = strip(p, px) * smoothstep(0., uShade.w, uView.x - abs(p.x));\n    float sh = box(p - vec2(0., uLens.w * .3), uLens.xy, uLens.z);\n    float shadow = uShade.x * (1. - smoothstep(-uLens.w * .4, uLens.w * 1.2, sh));\n    o = o * (1. - shadow) + vec4(0., 0., 0., shadow);\n    if (d > px) {\n      gl_FragColor = o;\n      return;\n    }\n  }\n\n  // Inside: t runs from 0 at the rim to 1 where the flat top starts; the bevel's slope falls smoothly to nothing.\n  float t = clamp(-d / uLens.w, 0., 1.);\n  float slope = (1. - t) * (1. - t) * (1. - t);\n  vec2 q = abs(p) - uLens.xy + uLens.z;\n  vec2 n = sign(p) * normalize(max(q, 0.) + .001);\n  // The slope bends the view outwards, so the image curves in at the rim; blue bends more than red.\n  vec2 bend = n * uGlass.x * slope;\n  float aa = px / uStrip.w;\n  vec2 side = vec2(uGlass.z, 0.);\n  vec3 c = vec3(\n    seen((p + bend * (1. - uGlass.y) - side) / uStrip.w, aa).r,\n    seen((p + bend) / uStrip.w, aa).g,\n    seen((p + bend * (1. + uGlass.y) + side) / uStrip.w, aa).b\n  );\n\n  // Light from the top left: a fine bright line along that part of the rim, a soft dark edge inside the opposite one.\n  vec2 light = vec2(-.48, -.88);\n  float lit = max(dot(n, light), 0.);\n  float away = max(dot(n, -light), 0.);\n  float rim = -d;\n  c *= 1. - uShade.z * away * slope;\n  c = mix(c, vec3(1.), .1 * lit * slope);\n  c *= 1. - uShade.y * (1. - smoothstep(0., 1.2, rim));\n  float line = (1. - smoothstep(.55, 1.5, rim)) * smoothstep(.0, .35, rim + .2);\n  c = mix(c, vec3(1.), line * (.12 + .7 * lit * lit));\n\n  gl_FragColor = mix(o, vec4(c, 1.), clamp(.5 - d / px, 0., 1.));\n}`\n\n/**\n * A strip of pictures that slides behind a fixed glass lens. The lens magnifies the picture in it, bends the image\n * at its bevelled rim with faint colour fringes, and smears it a little while the strip moves. Drag or swipe with\n * momentum, use a trackpad, the arrow keys, the buttons, or click a picture to bring it into the lens. The picture's\n * title and a counter sit under the lens. Uses one WebGL context; without WebGL the strip is drawn in the DOM.\n */\nexport function LensStrip({\n  images,\n  label,\n  index,\n  defaultIndex,\n  onIndexChange,\n  loop = true,\n  aspect = 4 / 5,\n  magnify = 1.6,\n  dispersion = 0.5,\n  labels = {},\n  className,\n  onKeyDown,\n  ...rest\n}: LensStripProps) {\n  const t = { ...EN, ...labels }\n  const n = images.length\n  const wraps = loop && n > 2\n  const id = useId()\n  const reduce = useReducedMotion()\n\n  const stage = useRef<HTMLDivElement | null>(null)\n  const cards = useRef<(HTMLDivElement | null)[]>([])\n  const title = useRef<HTMLSpanElement | null>(null)\n  const [width, setWidth] = useState(0)\n  const geo = useMemo(() => (width ? measure(width, aspect, Math.max(1, magnify)) : null), [width, aspect, magnify])\n\n  // What the frame loop and the shader read, kept out of React so a frame never renders.\n  const live = useRef({ geo, position: 0, velocity: 0, dispersion, wraps, n })\n  useLayoutEffect(() => {\n    Object.assign(live.current, { geo, dispersion, wraps, n })\n  })\n  // The picture nearest the lens, which the caption shows; it changes mid-drag, not only when the strip settles.\n  const [near, setNear] = useState<number | null>(null)\n  const nearRef = useRef<number | null>(null)\n\n  const key = `${aspect}|${images.map((im) => im.src).join('\\n')}`\n\n  const build = (ctx: GlSceneContext): GlScene | null => buildScene(ctx, images, aspect, live.current)\n  const gl = useGlStage(stage, build, key, { colors: COLORS, className: CANVAS })\n  const { redraw } = gl\n  const drawn = gl.status === 'ready'\n\n  const paint = useCallback(\n    (p: number, velocity: number) => {\n      const s = live.current\n      s.position = p\n      s.velocity = velocity\n      redraw()\n      const g = s.geo\n      if (!g) return\n      // The DOM strip: the same cards in the same places, the one in the lens raised to the lens's size. It is the\n      // picture when WebGL is missing, and what clicks land on when it is not.\n      const raise = g.magnify\n      const reach = g.width / 2 + g.pitch\n      for (let i = 0; i < s.n; i++) {\n        const el = cards.current[i]\n        if (!el) continue\n        let d = i - p\n        if (s.wraps) d = mod(d + s.n / 2, s.n) - s.n / 2\n        const x = d * g.pitch\n        if (Math.abs(x) > reach) {\n          el.style.visibility = 'hidden'\n          continue\n        }\n        const k = Math.max(0, 1 - Math.abs(d))\n        const lift = k * k * (3 - 2 * k)\n        el.style.visibility = 'visible'\n        el.style.transform = `translate3d(${x.toFixed(2)}px, 0, 0) scale(${(1 + (raise - 1) * lift).toFixed(4)})`\n        el.style.zIndex = String(Math.round(lift * 100) + 1)\n      }\n      // Without wrapping, the strip can be pulled past an end; the caption stays on the end picture.\n      const r = s.wraps ? mod(Math.round(p), Math.max(s.n, 1)) : clamp(Math.round(p), 0, Math.max(s.n - 1, 0))\n      if (r !== nearRef.current) {\n        nearRef.current = r\n        setNear(r)\n      }\n    },\n    [redraw],\n  )\n\n  const engine = useCarouselEngine({ count: n, loop: wraps, index, defaultIndex, onIndexChange, step: geo?.pitch ?? 200, onFrame: paint })\n  const current = engine.index\n  const shown = near ?? current\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 or set of pictures: draw the current frame again.\n  const { draw } = engine\n  useLayoutEffect(() => {\n    draw()\n  }, [draw, paint, geo, n, wraps, dispersion])\n\n  // The caption's title eases in when it changes.\n  const first = useRef(true)\n  useLayoutEffect(() => {\n    if (first.current || reduce) {\n      first.current = false\n      return\n    }\n    title.current?.animate([{ opacity: 0, transform: 'translateY(3px)' }, { opacity: 1, transform: 'none' }], { duration: 220, easing: 'cubic-bezier(0.23, 1, 0.32, 1)' })\n  }, [shown, reduce])\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 caption = images[shown]?.title\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\n      role=\"group\"\n      aria-roledescription=\"carousel\"\n      aria-label={label}\n      tabIndex={0}\n      onKeyDown={keys}\n      className={cn('group/lens w-full outline-none', className)}\n      {...rest}\n    >\n      <div\n        {...engine.bind}\n        ref={(el) => {\n          stage.current = el\n          engine.bind.ref(el)\n        }}\n        id={id}\n        style={{ height: geo?.height ?? 320 }}\n        className={cn(\n          'relative w-full touch-pan-y overflow-x-clip rounded-[calc(var(--radius)*2+2px)] select-none [-webkit-tap-highlight-color:transparent]',\n          n > 1 && 'cursor-grab data-dragging:cursor-grabbing',\n          'group-focus-visible/lens:outline-2 group-focus-visible/lens:outline-offset-4 group-focus-visible/lens:outline-ring',\n        )}\n      >\n        <div\n          className={cn(\n            'absolute inset-0 transition-opacity duration-300 ease-out-quint motion-reduce:transition-none',\n            '[mask-image:linear-gradient(to_right,transparent,#000_16%,#000_84%,transparent)]',\n            drawn && 'opacity-0',\n          )}\n        >\n          {geo &&\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 ? undefined : () => engine.go(i)}\n                  style={{ width: geo.cardW, height: geo.cardH, marginLeft: -geo.cardW / 2, marginTop: -geo.cardH / 2, borderRadius: geo.cardR }}\n                  className={cn(\n                    'absolute top-1/2 left-1/2 overflow-hidden bg-muted will-change-transform',\n                    'shadow-[0_1px_2px_rgb(0_0_0/0.06),0_14px_28px_-16px_rgb(0_0_0/0.4)]',\n                    !on && 'invisible cursor-pointer',\n                  )}\n                >\n                  <div inert={!on} className=\"absolute inset-0\">\n                    <img src={im.src} alt={im.alt} draggable={false} decoding=\"async\" className=\"size-full object-cover [-webkit-user-drag:none]\" />\n                  </div>\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                </div>\n              )\n            })}\n        </div>\n      </div>\n\n      <div className=\"mx-auto mt-3 flex w-full max-w-xs items-center justify-between gap-3\">\n        {n > 1 ? (\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        ) : null}\n        <p aria-hidden className=\"flex min-w-0 flex-1 flex-col items-center gap-1.5 text-center\">\n          {caption ? (\n            <span ref={title} className=\"max-w-full truncate text-[14px] leading-none font-medium tracking-[-0.01em] text-foreground\">\n              {caption}\n            </span>\n          ) : null}\n          <span className=\"font-mono text-[11px] leading-none font-medium tracking-[0.04em] text-muted-foreground tabular-nums\">\n            {pad(shown + 1)} / {pad(n)}\n          </span>\n        </p>\n        {n > 1 ? (\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        ) : null}\n      </div>\n      <p aria-live=\"polite\" className=\"sr-only\">\n        {`${images[current]?.title ? `${images[current].title}, ` : ''}${t.picture} ${current + 1} ${t.of} ${n}`}\n      </p>\n    </div>\n  )\n}\n\ntype Live = { geo: Geometry | null; position: number; velocity: number; dispersion: number; wraps: boolean; n: number }\n\nfunction buildScene({ gl, ready, fail, signal }: GlSceneContext, images: GlImage[], aspect: number, live: Live): GlScene | null {\n  const program = glProgram(gl, VERTEX, FRAGMENT)\n  if (!program) return null\n  gl.useProgram(program)\n  // One triangle that covers the whole canvas.\n  const buffer = gl.createBuffer()\n  gl.bindBuffer(gl.ARRAY_BUFFER, buffer)\n  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW)\n  const at = gl.getAttribLocation(program, 'a')\n  gl.enableVertexAttribArray(at)\n  gl.vertexAttribPointer(at, 2, gl.FLOAT, false, 0, 0)\n  const u = (name: string) => gl.getUniformLocation(program, name)\n  const uView = u('uView')\n  const uLens = u('uLens')\n  const uCard = u('uCard')\n  const uStrip = u('uStrip')\n  const uGlass = u('uGlass')\n  const uCell = u('uCell')\n  const uGrid = u('uGrid')\n  const uBody = u('uBody')\n  const uShade = u('uShade')\n  gl.uniform1i(u('uTex'), 0)\n\n  let atlas: GlAtlas | null = null\n  let size = [1, 1, 1]\n  let body: Rgb = [0.5, 0.5, 0.5]\n  let dark = false\n\n  glAtlas(gl, images, { aspect, signal }).then((a) => {\n    if (signal.aborted) return\n    if (!a) return fail()\n    atlas = a\n    // The grid of cells, read back from the corners glAtlas reports.\n    const [u0, v0, u1, v1] = a.rects[0]\n    const cols = Math.max(1, a.rects.filter((r) => r[1] === v0).length)\n    const su = a.rects[1] && cols > 1 ? a.rects[1][0] - u0 : 1\n    const sv = a.rects[cols] ? a.rects[cols][1] - v0 : 1\n    gl.activeTexture(gl.TEXTURE0)\n    gl.bindTexture(gl.TEXTURE_2D, a.texture)\n    gl.uniform4f(uCell, u0, v0, u1 - u0, v1 - v0)\n    gl.uniform3f(uGrid, su, sv, cols)\n    ready()\n  })\n\n  return {\n    resize: (w, h, dpr) => {\n      size = [w / dpr / 2, h / dpr / 2, dpr]\n    },\n    theme: ([bg, fg]) => {\n      dark = 0.2126 * bg[0] + 0.7152 * bg[1] + 0.0722 * bg[2] < 0.5\n      // The glass's own colour: the background, a breath towards the foreground.\n      body = [0, 1, 2].map((i) => bg[i] + (fg[i] - bg[i]) * 0.035) as Rgb\n    },\n    draw: () => {\n      const g = live.geo\n      if (!atlas || !g) return\n      const n = Math.max(live.n, 1)\n      const position = live.wraps ? mod(live.position, n) : live.position\n      // The speed in CSS px per second, eased into 0–1: more colour and a slight smear while the strip moves.\n      const speed = Math.abs(live.velocity) * g.pitch\n      const motion = 1 - Math.exp(-speed / 1800)\n      const disp = clamp(live.dispersion, 0, 1)\n      gl.uniform3f(uView, size[0], size[1], size[2])\n      gl.uniform4f(uLens, g.lensW / 2, g.lensH / 2, g.lensR, g.bevel)\n      gl.uniform4f(uCard, g.cardW / 2, g.cardH / 2, g.cardR, g.pitch)\n      gl.uniform4f(uStrip, position, n, live.wraps ? 1 : 0, g.magnify)\n      gl.uniform4f(\n        uGlass,\n        g.bend,\n        disp * 0.06 + motion * 0.2 * (0.4 + disp),\n        Math.sign(live.velocity) * motion * 1.1 * (0.4 + disp),\n        Math.sign(live.velocity) * motion * 3.2,\n      )\n      gl.uniform3f(uBody, body[0], body[1], body[2])\n      gl.uniform4f(uShade, dark ? 0.3 : 0.07, dark ? 0.28 : 0.14, dark ? 0.32 : 0.2, g.width * FADE)\n      gl.drawArrays(gl.TRIANGLES, 0, 3)\n    },\n    dispose: () => {\n      if (atlas) gl.deleteTexture(atlas.texture)\n      gl.deleteBuffer(buffer)\n      gl.deleteProgram(program)\n    },\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"
}