{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "glass-lens-carousel",
  "type": "registry:ui",
  "title": "Glass Lens Carousel",
  "description": "A looping image strip that is never drawn straight to screen: it renders to an offscreen texture, then a fullscreen pass samples it back through a thick optical element - drawing the picture inward, separating it into colour channels toward the perimeter, and adding a bright core, a modulated ring and an undulating edge. Scroll or drag to travel it; click a panel to bring it forward and enlarge it. Two WebGL2 passes, no 3D library.",
  "files": [
    {
      "path": "registry/crafterui/ui/glass-lens-carousel.tsx",
      "type": "registry:ui",
      "content": "\"use client\"\n\n// A continuous strip of work viewed through a thick optical element.\n//\n// The strip is unremarkable on its own: panels of equal height, each holding\n// its source aspect, cycling so there is no end to arrive at. The interest is\n// in the second stage. The strip is never rasterised to the display - it goes\n// to an offscreen texture, and a fullscreen triangle pair samples that texture\n// back through an optic that draws the image inward, separates it into colour\n// channels toward its perimeter, and adds a bright core, a modulated ring and a\n// perimeter that undulates as the strip travels behind it.\n//\n// Two stages, one canvas, no scene graph. Every term the optic needs is a\n// function of radial position, so it fits in a page of shader code.\nimport * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\n\nexport interface GlassLensItem {\n  /** Cover art. Cross-origin sources must send CORS headers. */\n  image: string\n  /** Shown while this panel is centred. */\n  title: string\n  /** The line under the title. */\n  caption?: string\n}\n\nexport interface GlassLensCarouselProps\n  extends Omit<React.ComponentPropsWithoutRef<\"section\">, \"children\"> {\n  items: GlassLensItem[]\n  /** Wordmark in the top-left. Omit to drop it. @default undefined */\n  brand?: string\n  /** Panel height, as a fraction of the stage. @default 0.62 */\n  panelHeight?: number\n  /** Space between panels, in px. @default 12 */\n  gap?: number\n  /** Panel corner radius, in px. @default 6 */\n  radius?: number\n  /** The lens ring and aura colour. @default \"#009dff\" */\n  tint?: string\n  /** Click a panel to centre and enlarge it. @default true */\n  focusable?: boolean\n  /** Label on the focused panel's dismiss control. @default \"Close\" */\n  closeLabel?: string\n  /** Extra classes on the root surface. @default undefined */\n  className?: string\n}\n\n/* Motion characteristics. The strip is deliberately weighty; a low convergence\n   rate is most of what makes the optic register as a physical thickness rather\n   than a filter applied over an ordinary carousel. */\nconst EASE = 0.09 // fraction of the remaining distance closed each frame\nconst SNAP_EASE = 0.05 // ... and once it is settling onto a panel\nconst DRAG_EASE = 0.24 // ... and while a finger or cursor is pulling it\nconst WHEEL = 1.4\nconst DRAG = 1.6\nconst FRICTION = 0.865 // flick decay after a drag release\nconst SNAP_IDLE = 120 // ms of quiet input before the row settles on a panel\nconst CLICK_SLOP = 6 // px of travel that still counts as a click\n\n/* Panels contract as travel speed rises, which suggests resistance acting on\n   something with mass. The threshold below is the per-frame speed at which the\n   full contraction is reached. */\nconst SHRINK_MAX = 60\nconst SHRINK_ATTACK = 0.25\nconst SHRINK_DECAY = 0.06\n\n/* Expanded view: the chosen panel enlarges and remains, the others withdraw\n   from the centre outward, and the optic dissolves as they leave. */\nconst FOCUS_EASE = 0.085\nconst FOCUS_STAGGER = 0.055\nconst FOCUS_DROP = 1.4 // how far a panel falls, in stage heights\nconst FOCUS_GROW = 0.18\n\n/* Introduction: panels rise into place from beneath at reduced size, beginning\n   with the pair nearest the centre. */\nconst ENTRY_SECONDS = 1.15\nconst ENTRY_STAGGER = 0.07\nconst ENTRY_START = 0.22 // height they start at, of their final height\n\n/** Interval, in frames, between palette reads. Resolving a token forces a style\n    recalculation, and the palette only changes when someone toggles the theme. */\nconst THEME_EVERY = 20\n\nconst clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v))\nconst lerp = (a: number, b: number, t: number) => a + (b - a) * t\n/** Fifth-order ease-out. The extended tail lets a movement settle rather than\n    terminate abruptly. */\nconst outQuint = (t: number) => 1 - Math.pow(1 - clamp(t, 0, 1), 5)\n\nconst PANEL_VERT = /* glsl */ `#version 300 es\nin vec2 aPos;\nuniform vec4 uRect;   // centre.xy, size.xy - px, origin at the stage centre\nuniform vec2 uRes;\nout vec2 vUv;\nout vec2 vLocal;      // px from the panel centre, for the corner cut\nvoid main() {\n  vUv = vec2(aPos.x, 1.0 - aPos.y);\n  vLocal = (aPos - 0.5) * uRect.zw;\n  gl_Position = vec4((uRect.xy + vLocal) / (uRes * 0.5), 0.0, 1.0);\n}`\n\nconst PANEL_FRAG = /* glsl */ `#version 300 es\nprecision highp float;\nin vec2 vUv;\nin vec2 vLocal;\nuniform sampler2D uTex;\nuniform vec4 uRect;\nuniform vec3 uBg;\nuniform float uFade;    // still loading -> the panel is only its own shadow\nuniform float uRadius;\nout vec4 fragColor;\n\nfloat sdRoundBox(vec2 p, vec2 b, float r) {\n  vec2 q = abs(p) - b + r;\n  return min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - r;\n}\n\nvoid main() {\n  // Corners are clipped rather than alpha-blended. The strip is opaque and the\n  // surface behind it is the identical colour, so there is nothing to blend.\n  float d = sdRoundBox(vLocal, uRect.zw * 0.5, min(uRadius, min(uRect.z, uRect.w) * 0.5));\n  if (d > 0.0) discard;\n  fragColor = vec4(mix(uBg, texture(uTex, vUv).rgb, uFade), 1.0);\n}`\n\nconst LENS_VERT = /* glsl */ `#version 300 es\nin vec2 aPos;\nout vec2 vUv;\nvoid main() {\n  vUv = aPos;\n  gl_Position = vec4(aPos * 2.0 - 1.0, 0.0, 1.0);\n}`\n\n/* The optic. A single elliptical region, rotated away from vertical and\n   extending past the frame vertically, so it presents as a diagonal band across\n   the view rather than a bubble within it. The normalised radius runs from 0 at\n   the centre to 1 at the boundary, and every term that follows - perimeter\n   undulation, channel separation, core, ring, boundary highlight - is a function\n   of that one quantity. Beyond the boundary the strip is passed through\n   unaltered, which is what gives the element a locatable edge.\n\n   A single scalar attenuates the entire effect, letting the introduction bring\n   it up and the expanded view take it away without a second code path. */\nconst LENS_FRAG = /* glsl */ `#version 300 es\nprecision highp float;\n#define SAMPLES 12\n\nin vec2 vUv;\nuniform sampler2D uTex;\nuniform float uAspect;\nuniform float uTime;\nuniform float uStrength;\nuniform vec3 uTint;\nout vec4 fragColor;\n\nconst float SIZE_X = 0.565;     // half-width, in screen-height units\nconst float SIZE_Y = 1.0;       // half-height - past the frame, so it never closes\nconst float ROTATION = 1.13446; // 65 degrees\nconst float DISPERSION = 11.0;\nconst float GLOW = 4.2;\nconst float WHITE_GLOW = 0.24;\nconst float NOVA_SIZE = 12.0;\nconst float RING = 6.0;\nconst float RING_RADIUS = 0.49;\nconst float RING_WIDTH = 0.014;\nconst float SHIMMER_FREQ = 12.0;\nconst float SHIMMER_SPEED = 3.5;\nconst float SHIMMER_DEPTH = 0.12;\nconst float RIM_START = 0.578;\nconst float RIM_TANGENTIAL = 0.6;\nconst float RIM_FREQ_1 = 2.0;\nconst float RIM_FREQ_2 = 1.0;\nconst float RIM_LINE = 1.4;\nconst float RIM_LINE_POS = 0.488;\nconst float RIM_LINE_WIDTH = 0.003;\n\nvoid main() {\n  vec3 base = texture(uTex, vUv).rgb;\n\n  // Converted to local coordinates, corrected for aspect, then rotated, so the\n  // region and all of its internal structure turn as one.\n  vec2 offset = vUv - 0.5;\n  vec2 p = vec2(offset.x * uAspect, offset.y);\n  float ca = cos(ROTATION), sa = sin(ROTATION);\n  p = mat2(ca, -sa, sa, ca) * p;\n\n  float nd = length(p / vec2(SIZE_X, SIZE_Y));\n  if (nd > 1.0 || uStrength < 0.001) {\n    fragColor = vec4(base, 1.0);\n    return;\n  }\n  float shape = clamp(nd, 0.0, 1.0);\n\n  vec2 radial = normalize(offset + 1e-6);\n  vec2 tangent = vec2(-radial.y, radial.x);\n  float angle = atan(p.y, p.x);\n\n  // Perimeter undulation, applied tangentially so the strip travels along the\n  // boundary rather than being displaced outward through it.\n  float rim = smoothstep(RIM_START, 1.0, nd);\n  float wave = sin(angle * RIM_FREQ_1) * 0.55 + sin(angle * RIM_FREQ_2) * 0.25;\n  vec2 baseUV = 0.5 + offset\n    + tangent * wave * rim * (SIZE_X + SIZE_Y) * 0.5 * RIM_TANGENTIAL * uStrength;\n\n  // Channel separation: a single run of taps along the radial direction, each\n  // weighted per channel and normalised afterwards, so the interior stays\n  // neutral and only the perimeter resolves into colour.\n  vec2 dispDir = offset * DISPERSION * 0.004 * smoothstep(0.55, 1.0, nd) * uStrength;\n  vec3 col = vec3(0.0);\n  vec3 weight = vec3(0.0);\n  for (int i = 0; i < SAMPLES; i++) {\n    float t = float(i) / float(SAMPLES - 1);\n    vec3 w = vec3(\n      exp(-pow((t - 0.0) / 0.38, 2.0)),\n      exp(-pow((t - 0.5) / 0.38, 2.0)),\n      exp(-pow((t - 1.0) / 0.38, 2.0))\n    );\n    col += texture(uTex, baseUV + dispDir * (t - 0.5)).rgb * w;\n    weight += w;\n  }\n  col /= max(weight, vec3(0.001));\n\n  // Slight darkening toward the interior - the only indication that the centre\n  // looks through more material than the boundary does.\n  col *= mix(0.91, 1.0, smoothstep(0.0, 0.38, shape));\n\n  float r2 = shape * shape * 0.25;\n  float gs = max(NOVA_SIZE * GLOW * 0.003, 0.004);\n  float nova = (exp(-r2 / gs) + exp(-r2 / (gs * 7.0)) * 0.18)\n             * WHITE_GLOW * (GLOW / 17.0) * 1.15;\n  col += vec3(nova * uStrength);\n\n  float dC = shape * 0.5;\n  float ring = exp(-pow((dC - RING_RADIUS) / RING_WIDTH, 2.0)) * RING * (GLOW / 17.0) * 1.8;\n  ring *= sin(angle * SHIMMER_FREQ + uTime * SHIMMER_SPEED) * SHIMMER_DEPTH + (1.0 - SHIMMER_DEPTH);\n  float aura = exp(-pow((dC - RING_RADIUS) / (RING_WIDTH * 6.0), 2.0)) * 0.28 * RING * (GLOW / 17.0);\n  col += uTint * (ring + aura) * uStrength;\n  col += vec3(exp(-pow((dC - RIM_LINE_POS) / RIM_LINE_WIDTH, 2.0)) * RIM_LINE * uStrength);\n\n  fragColor = vec4(mix(base, col, smoothstep(1.0, 0.93, nd)), 1.0);\n}`\n\nfunction build(gl: WebGL2RenderingContext, vert: string, frag: string) {\n  const program = gl.createProgram()\n  if (!program) return null\n  for (const [type, source] of [\n    [gl.VERTEX_SHADER, vert],\n    [gl.FRAGMENT_SHADER, frag],\n  ] as const) {\n    const shader = gl.createShader(type)\n    if (!shader) return null\n    gl.shaderSource(shader, source)\n    gl.compileShader(shader)\n    if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n      console.error(gl.getShaderInfoLog(shader))\n      return null\n    }\n    gl.attachShader(program, shader)\n    gl.deleteShader(shader)\n  }\n  gl.bindAttribLocation(program, 0, \"aPos\")\n  gl.linkProgram(program)\n  if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {\n    console.error(gl.getProgramInfoLog(program))\n    return null\n  }\n  return program\n}\n\n/** Cached uniform handles. getUniformLocation performs a string lookup on every\n    call, and this sits inside the per-frame path. */\nfunction uniforms(gl: WebGL2RenderingContext, program: WebGLProgram) {\n  const cache = new Map<string, WebGLUniformLocation | null>()\n  return (name: string) => {\n    let loc = cache.get(name)\n    if (loc === undefined) {\n      loc = gl.getUniformLocation(program, name)\n      cache.set(name, loc)\n    }\n    return loc\n  }\n}\n\n/** Resolves any CSS colour to 0-1 RGB by asking the browser instead of parsing\n    it. Theme tokens here are written in oklch, and naive comma-splitting of the\n    computed string yields a confidently incorrect near-black. */\nfunction colorReader() {\n  const probe = document.createElement(\"canvas\")\n  probe.width = probe.height = 1\n  const ctx = probe.getContext(\"2d\", { willReadFrequently: true })\n  return (css: string): [number, number, number] => {\n    if (!ctx) return [0, 0, 0]\n    ctx.fillStyle = \"#000\"\n    ctx.fillStyle = css // left at black if the browser cannot parse it\n    ctx.fillRect(0, 0, 1, 1)\n    const [r, g, b] = ctx.getImageData(0, 0, 1, 1).data\n    return [r / 255, g / 255, b / 255]\n  }\n}\n\ntype Panel = { texture: WebGLTexture | null; aspect: number; fade: number }\n\nexport function GlassLensCarousel({\n  items,\n  brand,\n  panelHeight = 0.62,\n  gap = 12,\n  radius = 6,\n  tint = \"#009dff\",\n  focusable = true,\n  closeLabel = \"Close\",\n  className,\n  ...props\n}: GlassLensCarouselProps) {\n  const canvasRef = React.useRef<HTMLCanvasElement>(null)\n  const [active, setActive] = React.useState(0)\n  const [focused, setFocused] = React.useState<number | null>(null)\n  const [reduced, setReduced] = React.useState(false)\n  const [supported, setSupported] = React.useState(true)\n\n  // The frame loop reads these. They are refs so that changing a label or a\n  // tint does not tear the loop down and drop the row back to its entry state.\n  const settings = React.useRef({ panelHeight, gap, radius, tint, focusable })\n  settings.current = { panelHeight, gap, radius, tint, focusable }\n  const focusRef = React.useRef<number | null>(null)\n  focusRef.current = focused\n  /** Populated by the render loop so keyboard input drives the same travel the\n      wheel does. */\n  const step = React.useRef<(by: number) => void>(() => {})\n\n  const count = items.length\n  // The loop owns the textures, so it rebuilds when the pictures change - and\n  // must not when only a caption does.\n  const sources = items.map((item) => item.image).join(\" \")\n\n  React.useEffect(() => {\n    const query = window.matchMedia(\"(prefers-reduced-motion: reduce)\")\n    const read = () => setReduced(query.matches)\n    read()\n    query.addEventListener(\"change\", read)\n    return () => query.removeEventListener(\"change\", read)\n  }, [])\n\n  React.useEffect(() => {\n    const canvas = canvasRef.current\n    if (!canvas || !count) return\n    const gl = canvas.getContext(\"webgl2\", { alpha: false, antialias: false })\n    if (!gl) {\n      setSupported(false)\n      return\n    }\n\n    const readColor = colorReader()\n    const panelProgram = build(gl, PANEL_VERT, PANEL_FRAG)\n    const lensProgram = build(gl, LENS_VERT, LENS_FRAG)\n    if (!panelProgram || !lensProgram) return\n    const panelU = uniforms(gl, panelProgram)\n    const lensU = uniforms(gl, lensProgram)\n\n    const quad = gl.createVertexArray()\n    gl.bindVertexArray(quad)\n    const buffer = gl.createBuffer()\n    gl.bindBuffer(gl.ARRAY_BUFFER, buffer)\n    gl.bufferData(\n      gl.ARRAY_BUFFER,\n      new Float32Array([0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1]),\n      gl.STATIC_DRAW\n    )\n    gl.enableVertexAttribArray(0)\n    gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0)\n\n    // The strip is rendered here at device resolution. Allocating this in CSS\n    // pixels and letting the optic magnify it is the difference between a clear\n    // element and a soft one.\n    const target = gl.createFramebuffer()\n    const rowTexture = gl.createTexture()\n    gl.bindTexture(gl.TEXTURE_2D, rowTexture)\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.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    gl.bindFramebuffer(gl.FRAMEBUFFER, target)\n    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, rowTexture, 0)\n    gl.bindFramebuffer(gl.FRAMEBUFFER, null)\n\n    const panels: Panel[] = items.map(() => ({ texture: null, aspect: 1.5, fade: 0 }))\n    const images = items.map((item, i) => {\n      const image = new Image()\n      image.crossOrigin = \"anonymous\"\n      image.decoding = \"async\"\n      image.onload = () => {\n        const texture = gl.createTexture()\n        gl.bindTexture(gl.TEXTURE_2D, texture)\n        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image)\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        gl.generateMipmap(gl.TEXTURE_2D)\n        panels[i].texture = texture\n        panels[i].aspect = image.naturalWidth / Math.max(image.naturalHeight, 1)\n      }\n      image.src = item.image\n      return image\n    })\n\n    // --- state ------------------------------------------------------------\n    let width = 0\n    let height = 0\n    let scroll = 0\n    let goal = 0\n    let velocity = 0\n    let energy = 0 // smoothed scroll activity, 0..1\n    let lastInput = 0\n    let snapped = true\n    let entry = 0\n    let focus = 0\n    let focusIndex = 0\n    let clock = 0\n    let previous = 0\n    let ticks = 0\n    let frame = 0\n    let background: [number, number, number] = [0, 0, 0]\n    let tintRgb: [number, number, number] = [0, 0.6, 1]\n\n    const widths = new Float32Array(count)\n    const centers = new Float32Array(count)\n    const screenX = new Float32Array(count)\n    let total = 1\n    let panelPx = 1\n\n    /** Each width derives from its own source aspect, so nothing is cropped. */\n    const measure = () => {\n      panelPx = height * settings.current.panelHeight\n      let x = 0\n      for (let i = 0; i < count; i++) {\n        widths[i] = panelPx * panels[i].aspect\n        centers[i] = x + widths[i] / 2\n        x += widths[i] + settings.current.gap\n      }\n      total = Math.max(x, 1)\n    }\n\n    /** Strip offset that places a given panel at centre, resolved along whichever\n        direction round the cycle is shorter, so settling never unwinds the whole\n        sequence. */\n    const centerFor = (i: number, from: number) =>\n      centers[i] + Math.round((from - centers[i]) / total) * total\n\n    const nearest = (from: number) => {\n      let best = 0\n      let bestGap = Infinity\n      for (let i = 0; i < count; i++) {\n        const distance = Math.abs(centerFor(i, from) - from)\n        if (distance < bestGap) {\n          bestGap = distance\n          best = i\n        }\n      }\n      return best\n    }\n\n    const resize = () => {\n      const w = canvas.clientWidth\n      const h = canvas.clientHeight\n      if (!w || !h) return\n      const dpr = Math.min(window.devicePixelRatio || 1, 2)\n      width = w\n      height = h\n      canvas.width = Math.round(w * dpr)\n      canvas.height = Math.round(h * dpr)\n      gl.bindTexture(gl.TEXTURE_2D, rowTexture)\n      gl.texImage2D(\n        gl.TEXTURE_2D, 0, gl.RGBA, canvas.width, canvas.height, 0,\n        gl.RGBA, gl.UNSIGNED_BYTE, null\n      )\n      measure()\n    }\n    resize()\n    const observer = new ResizeObserver(resize)\n    observer.observe(canvas)\n\n    // --- input ------------------------------------------------------------\n    const push = (delta: number) => {\n      goal += delta\n      lastInput = performance.now()\n      snapped = false\n    }\n    step.current = (by: number) => {\n      if (focusRef.current !== null) return\n      const from = nearest(goal)\n      const next = ((from + by) % count + count) % count\n      goal = centerFor(next, goal)\n      lastInput = performance.now()\n      snapped = true\n      velocity = 0\n    }\n\n    const onWheel = (event: WheelEvent) => {\n      if (focusRef.current !== null) return\n      const delta =\n        Math.abs(event.deltaX) > Math.abs(event.deltaY) ? event.deltaX : event.deltaY\n      event.preventDefault()\n      push(delta * WHEEL)\n      velocity = 0\n    }\n    canvas.addEventListener(\"wheel\", onWheel, { passive: false })\n\n    let dragFrom: number | null = null\n    let dragTravel = 0\n    let dragLast = 0\n    let dragStep = 0\n    let dragging = false\n\n    const onDown = (event: PointerEvent) => {\n      if (focusRef.current !== null) return\n      dragFrom = event.clientX\n      dragTravel = 0\n      dragStep = 0\n      dragging = true\n      dragLast = performance.now()\n      velocity = 0\n      canvas.setPointerCapture(event.pointerId)\n    }\n    const onMove = (event: PointerEvent) => {\n      if (dragFrom === null) return\n      // Touch input tracks one-to-one; pointer input carries the weighted rate.\n      const travel = dragFrom - event.clientX\n      dragStep = travel * (event.pointerType === \"touch\" ? 1 : DRAG)\n      dragTravel += Math.abs(travel)\n      dragFrom = event.clientX\n      dragLast = performance.now()\n      push(dragStep)\n    }\n    const onUp = (event: PointerEvent) => {\n      if (dragFrom === null) return\n      const slop = event.pointerType === \"touch\" ? 12 : CLICK_SLOP\n      const wasClick = dragTravel < slop\n      dragFrom = null\n      dragging = false\n      // A pointer at rest before release was positioning the strip rather than\n      // launching it, so momentum is granted only to movement still in progress.\n      if (!wasClick && performance.now() - dragLast < 90) velocity = dragStep\n      if (wasClick && settings.current.focusable) {\n        const hit = pick(event.clientX)\n        if (hit >= 0) {\n          goal = centerFor(hit, goal)\n          setFocused(hit)\n        }\n      }\n    }\n\n    /** Identifies the panel beneath a client x-coordinate. Positions are taken\n        from the frame currently on screen, so this queries what is displayed\n        rather than recomputing the layout. */\n    const pick = (clientX: number) => {\n      const x = clientX - canvas.getBoundingClientRect().left - width / 2\n      const scale = 1 - 0.25 * energy\n      for (let i = 0; i < count; i++) {\n        if (Math.abs(x - screenX[i]) <= (widths[i] * scale) / 2) return i\n      }\n      return -1\n    }\n\n    canvas.addEventListener(\"pointerdown\", onDown)\n    canvas.addEventListener(\"pointermove\", onMove)\n    canvas.addEventListener(\"pointerup\", onUp)\n    canvas.addEventListener(\"pointercancel\", onUp)\n\n    // --- frame ------------------------------------------------------------\n    const draw = (now: number) => {\n      frame = requestAnimationFrame(draw)\n      if (!width || !height) return\n      const dt = previous ? Math.min((now - previous) / 1000, 1 / 20) : 0\n      previous = now\n      clock += dt\n      measure()\n\n      if (ticks++ % THEME_EVERY === 0) {\n        background = readColor(getComputedStyle(canvas).backgroundColor)\n        tintRgb = readColor(settings.current.tint)\n      }\n\n      // Runs a single time on an independent clock, and only once there is\n      // artwork to show - the sequence is wasted on empty rectangles.\n      if (panels.some((panel) => panel.texture)) {\n        entry = reduced ? 1 : Math.min(1, entry + dt / ENTRY_SECONDS)\n      }\n\n      // The expanded view supersedes everything else: input is suspended, the\n      // chosen panel holds position and enlarges, the rest withdraw.\n      const wanted = focusRef.current\n      if (wanted !== null) focusIndex = wanted\n      const focusGoal = wanted === null ? 0 : 1\n      focus = reduced ? focusGoal : focus + (focusGoal - focus) * FOCUS_EASE\n      if (Math.abs(focus - focusGoal) < 0.002) focus = focusGoal\n\n      if (Math.abs(velocity) > 0.4) {\n        goal += velocity\n        velocity *= FRICTION\n        lastInput = now\n        snapped = false\n      } else velocity = 0\n\n      // Settling is triggered by elapsed quiet rather than by remaining\n      // distance. A slow scroll and a fast flick both fall silent identically,\n      // whereas any speed threshold would treat them differently.\n      if (!snapped && !dragging && now - lastInput > SNAP_IDLE && !velocity) {\n        goal = centerFor(nearest(goal), goal)\n        snapped = true\n      }\n\n      const before = scroll\n      const ease = dragging ? DRAG_EASE : snapped ? SNAP_EASE : EASE\n      scroll += (goal - scroll) * (reduced ? 1 : ease)\n      const speed = Math.abs(scroll - before)\n      const want = clamp(speed / SHRINK_MAX, 0, 1)\n      energy += (want - energy) * (want > energy ? SHRINK_ATTACK : SHRINK_DECAY)\n\n      const near = nearest(scroll)\n      setActive((prev) => (prev === near ? prev : near))\n\n      // --- pass one: the row, into a texture -----------------------------\n      gl.bindFramebuffer(gl.FRAMEBUFFER, target)\n      gl.viewport(0, 0, canvas.width, canvas.height)\n      gl.clearColor(background[0], background[1], background[2], 1)\n      gl.clear(gl.COLOR_BUFFER_BIT)\n      gl.useProgram(panelProgram)\n      gl.bindVertexArray(quad)\n      gl.uniform2f(panelU(\"uRes\"), width, height)\n      gl.uniform3fv(panelU(\"uBg\"), background)\n      gl.uniform1i(panelU(\"uTex\"), 0)\n      gl.uniform1f(panelU(\"uRadius\"), settings.current.radius)\n      gl.activeTexture(gl.TEXTURE0)\n\n      const shrink = 1 - 0.25 * energy\n      const half = width / 2\n      const copies = Math.ceil(width / total) + 2\n\n      for (let i = 0; i < count; i++) {\n        const panel = panels[i]\n        panel.fade = Math.min(1, panel.fade + (panel.texture ? dt * 5 : 0))\n        screenX[i] = Infinity\n\n        // Folded into a window centred on the stage, then stepped outward on\n        // both sides - the sequence has no terminus, so a panel can appear twice.\n        const x = (((centers[i] - scroll) % total) + total * 1.5) % total - total / 2\n        const rank = Math.abs(i - near)\n        const grow = outQuint(\n          clamp(entry * (1 + ENTRY_STAGGER * count) - rank * ENTRY_STAGGER, 0, 1)\n        )\n        const scale = lerp(ENTRY_START, 1, grow) * shrink\n        let w = widths[i] * scale\n        let h = panelPx * scale\n        let y = (1 - grow) * height * 0.55\n\n        if (focus > 0) {\n          if (i === focusIndex) {\n            w *= 1 + FOCUS_GROW * focus\n            h *= 1 + FOCUS_GROW * focus\n          } else {\n            // Offset from the centre outward: adjacent panels leave first, the\n            // extremes last.\n            const fall = outQuint(\n              clamp(\n                focus * (1 + FOCUS_STAGGER * count) -\n                  Math.abs(i - focusIndex) * FOCUS_STAGGER,\n                0,\n                1\n              )\n            )\n            y -= fall * height * FOCUS_DROP\n          }\n        }\n\n        for (let c = 0; c < copies; c++) {\n          const px = x + (c - Math.floor(copies / 2)) * total\n          if (px < -half - w || px > half + w) continue\n          if (Math.abs(px) < Math.abs(screenX[i])) screenX[i] = px\n          if (!panel.texture) continue\n          gl.bindTexture(gl.TEXTURE_2D, panel.texture)\n          gl.uniform4f(panelU(\"uRect\"), px, y, w, h)\n          gl.uniform1f(panelU(\"uFade\"), panel.fade)\n          gl.drawArrays(gl.TRIANGLES, 0, 6)\n        }\n      }\n\n      // --- pass two: read it back through the glass ----------------------\n      gl.bindFramebuffer(gl.FRAMEBUFFER, null)\n      gl.viewport(0, 0, canvas.width, canvas.height)\n      gl.useProgram(lensProgram)\n      gl.bindVertexArray(quad)\n      gl.activeTexture(gl.TEXTURE0)\n      gl.bindTexture(gl.TEXTURE_2D, rowTexture)\n      gl.uniform1i(lensU(\"uTex\"), 0)\n      gl.uniform1f(lensU(\"uAspect\"), width / height)\n      gl.uniform1f(lensU(\"uTime\"), reduced ? 0 : clock)\n      gl.uniform1f(lensU(\"uStrength\"), outQuint(entry) * (1 - focus))\n      gl.uniform3fv(lensU(\"uTint\"), tintRgb)\n      gl.drawArrays(gl.TRIANGLES, 0, 6)\n    }\n    frame = requestAnimationFrame(draw)\n\n    return () => {\n      cancelAnimationFrame(frame)\n      observer.disconnect()\n      canvas.removeEventListener(\"wheel\", onWheel)\n      canvas.removeEventListener(\"pointerdown\", onDown)\n      canvas.removeEventListener(\"pointermove\", onMove)\n      canvas.removeEventListener(\"pointerup\", onUp)\n      canvas.removeEventListener(\"pointercancel\", onUp)\n      for (const image of images) image.onload = null\n      for (const panel of panels) if (panel.texture) gl.deleteTexture(panel.texture)\n      gl.deleteTexture(rowTexture)\n      gl.deleteFramebuffer(target)\n      gl.deleteBuffer(buffer)\n      gl.deleteVertexArray(quad)\n      gl.deleteProgram(panelProgram)\n      gl.deleteProgram(lensProgram)\n    }\n    // `sources` stands in for `items` - see the note beside it.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [sources, count, reduced])\n\n  const item = items[active]\n  const open = focused !== null\n\n  // No WebGL2 - a blank rectangle is the one outcome worse than no effect. The\n  // row without its glass is still the row: a native snap scroller of the same\n  // pictures, in the same order.\n  if (!supported) {\n    return (\n      <section\n        aria-roledescription=\"carousel\"\n        aria-label={brand ?? \"Gallery\"}\n        className={cn(\"bg-background text-foreground relative h-full min-h-[24rem] w-full\", className)}\n        {...props}\n      >\n        <ul className=\"flex h-full snap-x snap-mandatory items-center gap-3 overflow-x-auto px-[5%]\">\n          {items.map((entry) => (\n            <li key={entry.image} className=\"h-[58%] shrink-0 snap-center\">\n              <img\n                src={entry.image}\n                alt={entry.title}\n                className=\"bg-muted h-full w-auto rounded-lg object-cover\"\n              />\n            </li>\n          ))}\n        </ul>\n      </section>\n    )\n  }\n\n  return (\n    <section\n      aria-roledescription=\"carousel\"\n      aria-label={brand ?? \"Gallery\"}\n      className={cn(\n        \"bg-background text-foreground relative h-full min-h-[24rem] w-full overflow-hidden select-none\",\n        className\n      )}\n      {...props}\n    >\n      <canvas\n        ref={canvasRef}\n        tabIndex={0}\n        role=\"listbox\"\n        aria-label={brand ?? \"Gallery\"}\n        aria-activedescendant={`glass-lens-${active}`}\n        className={cn(\n          \"bg-background focus-visible:outline-foreground absolute inset-0 h-full w-full touch-pan-y outline-none focus-visible:outline-2 focus-visible:-outline-offset-4\",\n          open ? \"cursor-default\" : \"cursor-grab active:cursor-grabbing\"\n        )}\n        onKeyDown={(event) => {\n          if (event.key === \"ArrowRight\") step.current(1)\n          else if (event.key === \"ArrowLeft\") step.current(-1)\n          else if (event.key === \"Escape\") setFocused(null)\n          else if (focusable && (event.key === \"Enter\" || event.key === \" \")) {\n            setFocused((prev) => (prev === null ? active : null))\n          } else return\n          event.preventDefault()\n        }}\n      />\n\n      {/* Everything visible is painted into the canvas, so assistive technology\n          and keyboard users receive this equivalent instead: the same entries in\n          the same sequence. */}\n      <ul className=\"sr-only\">\n        {items.map((entry, i) => (\n          <li key={entry.image} id={`glass-lens-${i}`} role=\"option\" aria-selected={i === active}>\n            {entry.title}\n            {entry.caption ? `. ${entry.caption}` : \"\"}\n          </li>\n        ))}\n      </ul>\n\n      {brand ? (\n        <div className=\"pointer-events-none absolute top-[6%] left-[5%] text-sm font-medium tracking-tight\">\n          {brand}\n        </div>\n      ) : null}\n\n      <div\n        className={cn(\n          \"pointer-events-none absolute bottom-[7%] left-[5%] max-w-[70%] transition-opacity duration-500\",\n          open ? \"opacity-0\" : \"opacity-100\"\n        )}\n      >\n        <div className=\"text-2xl leading-none font-medium tracking-tight\">{item?.title}</div>\n        {item?.caption ? (\n          <div className=\"text-muted-foreground mt-1.5 text-sm\">{item.caption}</div>\n        ) : null}\n      </div>\n\n      <div className=\"text-muted-foreground pointer-events-none absolute right-[5%] bottom-[7%] text-sm tabular-nums\">\n        {String(active + 1).padStart(2, \"0\")}\n        <span className=\"opacity-50\"> / {String(count).padStart(2, \"0\")}</span>\n      </div>\n\n      {focusable ? (\n        <button\n          type=\"button\"\n          onClick={() => setFocused(null)}\n          className={cn(\n            \"border-border bg-background/70 text-foreground focus-visible:outline-foreground absolute top-[6%] right-[5%] cursor-pointer rounded-full border px-3.5 py-1.5 text-xs backdrop-blur-sm transition outline-none focus-visible:outline-2 focus-visible:outline-offset-2\",\n            open ? \"opacity-100\" : \"pointer-events-none opacity-0\"\n          )}\n        >\n          {closeLabel}\n        </button>\n      ) : null}\n    </section>\n  )\n}\n"
    }
  ]
}
