{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "prism-carousel",
  "title": "Prism Carousel",
  "description": "A coverflow of rounded images that sweeps a band of spectrum and colour into each new one and splits into a spectrum while it moves, with drag, wheel, keys, autoplay and captions. Raw WebGL 2, no dependencies.",
  "files": [
    {
      "path": "registry/mewo/ui/prism-carousel.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { cn } from \"@/lib/utils\"\n\nexport interface PrismCarouselItem {\n  /** Image URL. It is drawn with WebGL, so the server must allow cross-origin use (CORS). */\n  src: string\n  /** Image description for screen readers. */\n  alt: string\n  /** First caption line while the image is active. */\n  title?: string\n  /** Second caption line while the image is active. */\n  subtitle?: string\n  /** Opened when the active image is clicked or Enter is pressed. */\n  href?: string\n}\n\n/** What `controlsRef` receives. */\nexport interface PrismCarouselControls {\n  /** Moves to the next image. */\n  next(): void\n  /** Moves to the previous image. */\n  previous(): void\n  /** Moves to the image at `index`, the short way round when looping. */\n  goTo(index: number): void\n}\n\nexport interface PrismCarouselProps extends Omit<React.ComponentProps<\"div\">, \"onSelect\" | \"draggable\"> {\n  /** Images to show, in order. They must allow cross-origin loading. */\n  items?: PrismCarouselItem[]\n  /** Index of the image shown first. */\n  startIndex?: number\n  /** Width divided by height of the active image. Neighbours are narrower crops of their images. */\n  aspect?: number\n  /** Height of the active image as a fraction of the space above the caption. */\n  size?: number\n  /** Height of the neighbouring images relative to the active one. */\n  neighborScale?: number\n  /** Space between images in pixels. */\n  gap?: number\n  /** Corner radius of the active image in pixels. Neighbours scale it with their height. */\n  radius?: number\n  /** Colour of the images that are not active, from 0 (monochrome) to 1 (full colour). */\n  saturation?: number\n  /** How much the images away from the centre darken. */\n  dim?: number\n  /** Strength of the band of spectrum that sweeps across each new image. 0 turns the colour on without a sweep. */\n  sweep?: number\n  /** Seconds the sweep takes to cross an image. */\n  sweepDuration?: number\n  /** How strongly images split into a spectrum while the carousel moves. 0 keeps them sharp. */\n  dispersion?: number\n  /** Advance to the next image every `interval` seconds. Holds off screen and for reduced-motion users. */\n  autoplay?: boolean\n  /** Seconds between autoplay steps. */\n  interval?: number\n  /** Wrap around at the ends. */\n  loop?: boolean\n  /** Show the title and subtitle of the active image. */\n  captions?: boolean\n  /** Show previous and next buttons with a counter. */\n  controls?: boolean\n  /** Drag or swipe sideways to move between images, with inertia and snapping. */\n  draggable?: boolean\n  /** Scroll to move between images, one image per notch. */\n  wheel?: boolean\n  /** Pause autoplay while the pointer is over the carousel. Hovering a neighbour also lets some colour in. */\n  pauseOnHover?: boolean\n  /** Background of the component, any CSS colour. Caption and controls turn near-black or near-white to suit it. */\n  backgroundColor?: string\n  /** Stops autoplay. Reduced-motion users also get no sweep or dispersion. */\n  paused?: boolean\n  /** Most device pixels per CSS pixel the canvas uses. It is never more than 2. */\n  dpr?: number\n  /** Receives `next()`, `previous()` and `goTo(index)` to move the carousel from outside. */\n  controlsRef?: React.Ref<PrismCarouselControls>\n  /** Called when a different image becomes active. */\n  onIndexChange?: (index: number) => void\n  /** Called when the active image is clicked or Enter is pressed. */\n  onSelect?: (item: PrismCarouselItem, index: number) => void\n  /** Rendered on top of the carousel, after the caption. */\n  children?: React.ReactNode\n}\n\nexport const DEFAULT_ITEMS: PrismCarouselItem[] = [\n  [\"Harbour Light\", \"Morning on the water\"],\n  [\"Paper Moon\", \"A quiet night in the city\"],\n  [\"Salt Road\", \"Across the flats at noon\"],\n  [\"Green Hour\", \"Rain on the hills\"],\n  [\"Low Tide\", \"The sea pulls back\"],\n  [\"Night Orchard\", \"Lanterns between the trees\"],\n  [\"Copper Field\", \"Late sun on the grass\"],\n  [\"Blue Hollow\", \"Cold air before dawn\"],\n].map(([title, subtitle], index) => ({\n  src: `https://cataas.com/cat/${[\"AZo9zQWvZFvOBdGF\", \"OcCyCN1wBhrCZAvP\", \"1DrcyohjhwcNaRIz\", \"4CGBn8ySN95C7cG6\", \"5ieh9ATqpWGGSpdH\", \"9BbLV02Aj1E3pJfV\", \"9pbDi3QZsDUt40ha\", \"AYKSorXzeDn2lVD7\"][index]}`,\n  alt: `Placeholder photograph for ${title}`,\n  title,\n  subtitle,\n}))\n\nconst DEFAULT_LABEL = \"Prism carousel. Scroll, drag or use the arrow keys to move between images.\"\n\n// Motion. Springs are in rad/s with a damping ratio.\n// Navigation and the settle after a drag share one spring.\nconst POSITION_SPRING = { omega: 10, zeta: 0.94 }\n// The image that stops being active drains its colour on this spring, starting this many ms later.\nconst COLOUR_OUT_SPRING = { omega: 7.55, zeta: 0.9 }\nconst COLOUR_OUT_DELAY = 75\n// Hover colour on a neighbour, critically damped: quicker in than out. The shader lets 60% of it through.\nconst HOVER_IN = 14\nconst HOVER_OUT = 9.5\n// The colour edge of a sweep, as a share of the image width, when it starts and once `sweepDuration` has\n// passed. It runs on to 1.25 so the band leaves the image before the sweep ends. 10 means no sweep.\nconst SWEEP_FROM = -0.27\nconst SWEEP_TO = 1\nconst SWEEP_DONE = 1.25\nconst NO_SWEEP = 10\n// Seconds of motion smeared into the spectrum per unit of `dispersion`, and the most it may spread\n// as a share of an image's width.\nconst DISPERSION_TIME = 0.0056\nconst DISPERSION_MAX = 0.35\n// Pixels a press travels before it becomes a drag.\nconst DRAG_THRESHOLD = 4\n// Past either end without `loop`, a drag moves the row this much per pixel.\nconst OVERDRAG = 0.35\n// Release speed is read over this many ms of pointer samples.\nconst VELOCITY_WINDOW = 100\n// Seconds of release velocity projected forward to choose where a drag lands.\nconst RELEASE_LOOKAHEAD = 0.23\n// Wheel delta per image. A step is taken once half of one has built up, at most two per event, and\n// a pause this long in ms drops a partial step.\nconst WHEEL_STEP = 100\nconst WHEEL_MAX_STEPS = 2\nconst WHEEL_RESET = 250\n// The caption swaps when a move crosses its midpoint, then fades in on an ease-out-quint.\nconst CAPTION_FADE = 470\nconst CAPTION_DELAY = 16\nconst CAPTION_EASE = \"cubic-bezier(0.22, 1, 0.36, 1)\"\n// Shortest autoplay interval, in seconds.\nconst MIN_INTERVAL = 0.5\n// The first step after idling covers about a frame and a half (ms), so a move starts the moment it is asked for.\nconst HEAD_START = 25\n// dt is clamped so a hitch or a tab switch does not jump the springs.\nconst MAX_DT = 0.05\n// Springs are integrated in fixed substeps so a slow frame does not change their shape.\nconst SUBSTEP = 1 / 240\n\n// Layout.\n// Pixels between the active image and the caption block.\nconst CAPTION_GAP = 16.15\n// Pixels the caption block reserves beyond its own height.\nconst CAPTION_SLACK = 8.3\n// The caption block's height before it has been measured.\nconst CAPTION_BLOCK = 84\n// The active image never comes closer than this to the top.\nconst TOP_MARGIN = 45\n// Width over height of the first neighbour, whatever the active aspect.\nconst NEIGHBOR_ASPECT = 0.72\n// On a narrow container the active image is at most this share of the width, bending down past NARROW_FROM px.\nconst NARROW_WIDTH = 0.84\nconst NARROW_FROM = 400\nconst NARROW_BEND = 0.00076\n// |offset| where the outermost images start to fade out.\nconst EDGE_FADE_START = 2.82\n\n// Width between the active (|o| = 0) and first-neighbour (|o| = 1) sizes, as a 0..1 blend at |o| = 0, 0.05, ... 1.\n// The shape depends on how much wider the active image is than a neighbour (ratio rho = Wa / Wn).\nconst T_RHO_HIGH = { rho: 3.157, t: [1, 0.9955, 0.9819, 0.9587, 0.9253, 0.8821, 0.8285, 0.7671, 0.7006, 0.6341, 0.5677, 0.5012, 0.4347, 0.3684, 0.3038, 0.2413, 0.184, 0.1304, 0.0817, 0.0386, 0] }\nconst T_RHO_LOW = { rho: 1.576, t: [1, 0.9977, 0.9856, 0.9645, 0.935, 0.8922, 0.8492, 0.7874, 0.7322, 0.6723, 0.6101, 0.5496, 0.4901, 0.4272, 0.3622, 0.3061, 0.2427, 0.1829, 0.122, 0.0612, 0] }\n// Width beyond the first neighbour relative to it, at |o| = 1, 1.05, ... 2.9 (roughly a third per slot).\nconst R = [1, 0.9218, 0.852, 0.7898, 0.7345, 0.6879, 0.6503, 0.6205, 0.5976, 0.5734, 0.5479, 0.5243, 0.5001, 0.476, 0.4526, 0.4297, 0.4059, 0.3857, 0.3674, 0.3478, 0.3318, 0.316, 0.3004, 0.2848, 0.2719, 0.2579, 0.2462, 0.2356, 0.2234, 0.2138, 0.2043, 0.193, 0.1831, 0.173, 0.1621, 0.1525, 0.1432, 0.1338, 0.1247]\n// Opacity of the outermost images at |o| = 2.82, 2.84, ... 3.42.\nconst FADE = [1, 0.992, 0.98, 0.969, 0.953, 0.939, 0.916, 0.894, 0.869, 0.843, 0.817, 0.788, 0.759, 0.718, 0.69, 0.653, 0.621, 0.576, 0.533, 0.498, 0.465, 0.429, 0.394, 0.352, 0.31, 0.278, 0.245, 0.217, 0.159, 0.094, 0]\n\nconst clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value))\nconst wrap = (i: number, n: number) => ((i % n) + n) % n\nconst pad2 = (n: number) => String(n).padStart(2, \"0\")\n\nconst table = (t: number[], x: number, step: number, x0 = 0) => {\n  const f = (x - x0) / step\n  if (f <= 0) return t[0]\n  if (f >= t.length - 1) return t[t.length - 1]\n  const i = Math.floor(f)\n  return t[i] + (t[i + 1] - t[i]) * (f - i)\n}\n\nconst smoothstep = (x: number) => {\n  const t = clamp(x, 0, 1)\n  return t * t * (3 - 2 * t)\n}\n\ntype LayoutSettings = { aspect: number; size: number; neighborScale: number; gap: number }\n\ntype Metrics = {\n  W: number\n  H: number\n  /** Vertical centre of the images. */\n  cy: number\n  /** Active image height and width. */\n  Ha: number\n  Wa: number\n  /** First neighbour height and width. */\n  Hn: number\n  Wn: number\n  rho: number\n  gap: number\n  /** Pixels of drag per image: the width of an image half a slot from the centre, plus the gap. */\n  D: number\n  /** Top of the caption block. */\n  captionY: number\n}\n\ntype Box = {\n  /** Item index. */\n  index: number\n  /** Offset from the centre, in images. */\n  o: number\n  x: number\n  y: number\n  w: number\n  h: number\n  alpha: number\n  bright: number\n}\n\n/** Image sizes for a container of W × H CSS pixels whose caption block is `captionBlock` pixels tall. */\nexport function computeMetrics(W: number, H: number, captionBlock: number, s: LayoutSettings): Metrics {\n  const S = Math.max(1, H - (captionBlock > 0 ? captionBlock + CAPTION_SLACK : CAPTION_SLACK))\n  const vertical = Math.min(s.size * S, S - 2 * TOP_MARGIN)\n  const wCap = NARROW_WIDTH * W - NARROW_BEND * Math.max(0, W - NARROW_FROM) ** 2\n  const Ha = Math.max(8, Math.min(vertical, wCap / s.aspect))\n  const Wa = s.aspect * Ha\n  const Hn = s.neighborScale * Ha\n  const Wn = NEIGHBOR_ASPECT * Hn\n  const m: Metrics = { W, H, cy: S / 2, Ha, Wa, Hn, Wn, rho: Wa / Math.max(1e-3, Wn), gap: s.gap, D: 1, captionY: S / 2 + Ha / 2 + CAPTION_GAP }\n  m.D = imageWidth(0.5, m) + s.gap\n  return m\n}\n\n/** Width of an image `o` slots from the centre. */\nexport function imageWidth(o: number, m: Metrics) {\n  const a = Math.abs(o)\n  if (a <= 1) {\n    const k = (m.rho - T_RHO_HIGH.rho) / (T_RHO_LOW.rho - T_RHO_HIGH.rho)\n    const t = table(T_RHO_HIGH.t, a, 0.05) + (table(T_RHO_LOW.t, a, 0.05) - table(T_RHO_HIGH.t, a, 0.05)) * k\n    return m.Wn + (m.Wa - m.Wn) * clamp(t, 0, 1)\n  }\n  const r = a <= 2.9 ? table(R, a, 0.05, 1) : R[R.length - 1] * Math.pow(3, -(a - 2.9))\n  return m.Wn * r\n}\n\n/** Height of an image `o` slots from the centre. */\nexport const imageHeight = (o: number, m: Metrics) => m.Hn + (m.Ha - m.Hn) * (1 - smoothstep(Math.abs(o)))\n\n/** Opacity of an image `o` slots from the centre: only the outermost fade. */\nexport const imageOpacity = (o: number) => table(FADE, Math.abs(o), 0.02, EDGE_FADE_START)\n\n/** Brightness of an image `o` slots from the centre. */\nexport const imageBrightness = (o: number, dim: number) => 1 - dim * smoothstep(Math.abs(o))\n\n/** Every visible image for scroll position `p` (a continuous index), packed outwards from the centre line. */\nexport function layoutImages(p: number, count: number, loop: boolean, m: Metrics, dim: number): Box[] {\n  if (!count) return []\n  const k = Math.floor(p)\n  const f = p - k\n  const slots: { j: number; index: number; o: number; w: number; h: number }[] = []\n  for (let j = -4; j <= 5; j++) {\n    const raw = k + j\n    if (!loop && (raw < 0 || raw >= count)) continue\n    const o = j - f\n    if (Math.abs(o) > 3.45) continue\n    slots.push({ j, index: wrap(raw, count), o, w: imageWidth(o, m), h: imageHeight(o, m) })\n  }\n  const byJ = new Map(slots.map((s) => [s.j, s]))\n  const centres = new Map<number, number>()\n  // The centre line sits at fraction f between the centres of slot 0 and slot 1.\n  const w0 = byJ.get(0)?.w ?? imageWidth(-f, m)\n  const w1 = byJ.get(1)?.w ?? imageWidth(1 - f, m)\n  const c0 = m.W / 2 - f * (w0 / 2 + m.gap + w1 / 2)\n  centres.set(0, c0)\n  let c = c0\n  let prevW = w0\n  for (let j = 1; j <= 5; j++) {\n    const w = byJ.get(j)?.w ?? imageWidth(j - f, m)\n    c += prevW / 2 + m.gap + w / 2\n    centres.set(j, c)\n    prevW = w\n  }\n  c = c0\n  prevW = w0\n  for (let j = -1; j >= -4; j--) {\n    const w = byJ.get(j)?.w ?? imageWidth(j - f, m)\n    c -= prevW / 2 + m.gap + w / 2\n    centres.set(j, c)\n    prevW = w\n  }\n  return slots\n    .map((s) => ({ index: s.index, o: s.o, x: centres.get(s.j)! - s.w / 2, y: m.cy - s.h / 2, w: s.w, h: s.h, alpha: imageOpacity(s.o), bright: imageBrightness(s.o, dim) }))\n    .filter((b) => b.alpha > 0.001 && b.w > 0.2 && b.x < m.W && b.x + b.w > 0)\n}\n\ntype Spring = { x: number; v: number }\n\n/** Advances a damped spring toward `target` by `dt` seconds. */\nfunction stepSpring(s: Spring, target: number, omega: number, zeta: number, dt: number) {\n  for (let t = 0; t < dt - 1e-9; t += SUBSTEP) {\n    const h = Math.min(SUBSTEP, dt - t)\n    s.v += (omega * omega * (target - s.x) - 2 * zeta * omega * s.v) * h\n    s.x += s.v * h\n  }\n}\n\n/** Where the colour edge of a sweep that began at `start` (ms) is at `now`. */\nconst sweepEdge = (now: number, start: number, duration: number) =>\n  SWEEP_FROM + (SWEEP_TO - SWEEP_FROM) * ((now - start) / (Math.max(0.05, duration) * 1000))\n\n// One rounded, cover-cropped quad per visible image, with the grey/colour mix, the spectrum sweep and the\n// motion dispersion done per pixel.\nconst VERTEX = `#version 300 es\nin vec2 aPos;\nuniform vec4 uRect;   // x, y, w, h in device px (top-left origin)\nuniform vec2 uRes;\nout vec2 vLocal;\nvoid main() {\n  vLocal = aPos;\n  vec2 px = uRect.xy + aPos * uRect.zw;\n  vec2 clip = px / uRes * 2.0 - 1.0;\n  gl_Position = vec4(clip.x, -clip.y, 0.0, 1.0);\n}`\n\nconst FRAGMENT = `#version 300 es\nprecision highp float;\nin vec2 vLocal;\nuniform sampler2D uTex;\nuniform float uHasTex;\nuniform vec2 uSize;     // quad size incl. 1px padding, device px\nuniform vec2 uBox;      // image size, device px\nuniform float uRadius;  // device px\nuniform vec4 uCrop;     // uv offset xy, uv scale zw (cover crop)\nuniform float uAlpha;\nuniform float uBright;\nuniform float uSat;     // colour of inactive images, 0..1\nuniform float uColour;  // colour owned by this image (fades out after it stops being active)\nuniform float uHover;   // hover colour, 0..1\nuniform float uReveal;  // sweep: position of the colour edge across the image (0..1), large when done\nuniform float uSweep;   // sweep band strength\nuniform float uDisp;    // dispersion spread, as a share of the rect width\nout vec4 outColor;\n\nfloat sdRound(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}\nfloat g(float x, float mu, float s) { float d = (x - mu) / s; return exp(-0.5 * d * d); }\n// spectral weights across the dispersion taps: red leads, violet trails\nvec3 spectrum(float t) {\n  return vec3(g(t, 0.85, 0.22) + 0.25 * g(t, 0.05, 0.12), g(t, 0.5, 0.2), g(t, 0.12, 0.2)) + 0.04;\n}\nvec3 tex(vec2 local) { return texture(uTex, uCrop.xy + local * uCrop.zw).rgb; }\n\nvoid main() {\n  vec2 px = vLocal * uSize;\n  float d = sdRound(px - uSize * 0.5, uBox * 0.5, uRadius);\n  float cover = clamp(0.5 - d, 0.0, 1.0);\n  if (cover <= 0.0) discard;\n\n  vec3 col;\n  if (uHasTex < 0.5) {\n    col = vec3(0.16);\n  } else if (uDisp > 0.0004) {\n    vec3 acc = vec3(0.0), wsum = vec3(0.0);\n    for (int k = 0; k < 9; k++) {\n      float t = float(k) / 8.0;\n      vec3 w = spectrum(t);\n      acc += tex(vLocal + vec2((t - 0.5) * uDisp, 0.0)) * w;\n      wsum += w;\n    }\n    col = acc / wsum;\n  } else {\n    col = tex(vLocal);\n  }\n\n  float luma = dot(col, vec3(0.2126, 0.7152, 0.0722));\n  float dd = vLocal.x - uReveal;\n  float owned = uColour * (1.0 - smoothstep(-0.08, 0.10, dd));\n  float amount = max(owned, uHover * 0.6);\n  amount = uSat + (1.0 - uSat) * amount;\n  vec3 c = mix(vec3(luma), col, amount);\n  if (uSweep > 0.0) {\n    vec3 tint = vec3(\n      0.12 * g(dd, -0.13, 0.04) - 0.38 * g(dd, -0.03, 0.035) + 0.23 * g(dd, 0.09, 0.045),\n      0.88 * g(dd, 0.02, 0.06),\n      0.75 * g(dd, -0.035, 0.045));\n    c += uSweep * tint * luma;\n  }\n  c = clamp(c * uBright, 0.0, 1.0);\n  float a = uAlpha * cover;\n  outColor = vec4(c * a, a);\n}`\n\nconst UNIFORMS = [\"uRect\", \"uRes\", \"uTex\", \"uHasTex\", \"uSize\", \"uBox\", \"uRadius\", \"uCrop\", \"uAlpha\", \"uBright\", \"uSat\", \"uColour\", \"uHover\", \"uReveal\", \"uSweep\", \"uDisp\"] as const\n\ntype DrawItem = {\n  /** Texture key: the item index. */\n  key: number\n  /** CSS pixels. */\n  x: number\n  y: number\n  w: number\n  h: number\n  radius: number\n  alpha: number\n  bright: number\n  sat: number\n  colour: number\n  hover: number\n  reveal: number\n  sweep: number\n  disp: number\n}\n\nconst compile = (gl: WebGL2RenderingContext, type: number, source: string) => {\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)) return shader\n  gl.deleteShader(shader)\n  return null\n}\n\nfunction createRenderer(gl: WebGL2RenderingContext, canvas: HTMLCanvasElement) {\n  const vertex = compile(gl, gl.VERTEX_SHADER, VERTEX)\n  const fragment = compile(gl, gl.FRAGMENT_SHADER, FRAGMENT)\n  const program = gl.createProgram()\n  if (!vertex || !fragment || !program) return null\n  gl.attachShader(program, vertex)\n  gl.attachShader(program, fragment)\n  gl.linkProgram(program)\n  gl.deleteShader(vertex)\n  gl.deleteShader(fragment)\n  const vao = gl.createVertexArray()\n  const buffer = gl.createBuffer()\n  const blank = gl.createTexture()\n  if (!gl.getProgramParameter(program, gl.LINK_STATUS) || !vao || !buffer || !blank) {\n    gl.deleteVertexArray(vao)\n    gl.deleteBuffer(buffer)\n    gl.deleteTexture(blank)\n    gl.deleteProgram(program)\n    return null\n  }\n  const u = Object.fromEntries(UNIFORMS.map((name) => [name, gl.getUniformLocation(program, name)])) as Record<(typeof UNIFORMS)[number], WebGLUniformLocation | null>\n  gl.bindVertexArray(vao)\n  gl.bindBuffer(gl.ARRAY_BUFFER, buffer)\n  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]), gl.STATIC_DRAW)\n  const position = gl.getAttribLocation(program, \"aPos\")\n  gl.enableVertexAttribArray(position)\n  gl.vertexAttribPointer(position, 2, gl.FLOAT, false, 0, 0)\n  gl.bindVertexArray(null)\n  const textures = new Map<number, { texture: WebGLTexture; w: number; h: number }>()\n  gl.bindTexture(gl.TEXTURE_2D, blank)\n  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([40, 40, 40, 255]))\n  let dpr = 1\n\n  return {\n    setSize(w: number, h: number, ratio: number) {\n      dpr = ratio\n      const width = Math.max(1, Math.round(w * ratio))\n      const height = Math.max(1, Math.round(h * ratio))\n      // Assigning the same size would clear the canvas.\n      if (canvas.width !== width || canvas.height !== height) {\n        canvas.width = width\n        canvas.height = height\n      }\n    },\n    upload(key: number, image: HTMLImageElement) {\n      const old = textures.get(key)\n      if (old) gl.deleteTexture(old.texture)\n      const texture = gl.createTexture()\n      if (!texture) return\n      gl.bindTexture(gl.TEXTURE_2D, texture)\n      gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false)\n      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image)\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      textures.set(key, { texture, w: image.naturalWidth, h: image.naturalHeight })\n    },\n    clearTextures() {\n      textures.forEach((t) => gl.deleteTexture(t.texture))\n      textures.clear()\n    },\n    draw(items: DrawItem[]) {\n      gl.viewport(0, 0, canvas.width, canvas.height)\n      gl.clearColor(0, 0, 0, 0)\n      gl.clear(gl.COLOR_BUFFER_BIT)\n      gl.enable(gl.BLEND)\n      gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)\n      gl.useProgram(program)\n      gl.bindVertexArray(vao)\n      gl.uniform2f(u.uRes, canvas.width, canvas.height)\n      gl.uniform1i(u.uTex, 0)\n      gl.activeTexture(gl.TEXTURE0)\n      for (const it of items) {\n        const t = textures.get(it.key)\n        const w = it.w * dpr\n        const h = it.h * dpr\n        // The quad is padded by a pixel so the anti-aliased edge is not clipped.\n        gl.uniform4f(u.uRect, it.x * dpr - 1, it.y * dpr - 1, w + 2, h + 2)\n        gl.uniform2f(u.uSize, w + 2, h + 2)\n        gl.uniform2f(u.uBox, w, h)\n        gl.uniform1f(u.uRadius, Math.min(it.radius * dpr, Math.min(w, h) / 2))\n        let cx = 0\n        let cy = 0\n        let sx = 1\n        let sy = 1\n        if (t) {\n          const ta = t.w / t.h\n          const ra = w / h\n          if (ra > ta) sy = ta / ra\n          else sx = ra / ta\n          // The extra pixel of padding on each side.\n          const px = sx / w\n          const py = sy / h\n          cx = (1 - sx) / 2 - px\n          cy = (1 - sy) / 2 - py\n          sx += 2 * px\n          sy += 2 * py\n        }\n        gl.uniform4f(u.uCrop, cx, cy, sx, sy)\n        gl.bindTexture(gl.TEXTURE_2D, t ? t.texture : blank)\n        gl.uniform1f(u.uHasTex, t ? 1 : 0)\n        gl.uniform1f(u.uAlpha, it.alpha)\n        gl.uniform1f(u.uBright, it.bright)\n        gl.uniform1f(u.uSat, it.sat)\n        gl.uniform1f(u.uColour, it.colour)\n        gl.uniform1f(u.uHover, it.hover)\n        gl.uniform1f(u.uReveal, it.reveal)\n        gl.uniform1f(u.uSweep, it.sweep)\n        gl.uniform1f(u.uDisp, it.disp)\n        gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)\n      }\n      gl.bindVertexArray(null)\n    },\n    dispose() {\n      textures.forEach((t) => gl.deleteTexture(t.texture))\n      textures.clear()\n      gl.deleteTexture(blank)\n      gl.deleteBuffer(buffer)\n      gl.deleteVertexArray(vao)\n      gl.deleteProgram(program)\n    },\n  }\n}\n\n// Caption and controls turn near-black or near-white against `backgroundColor`. A 2D canvas parses the colour,\n// so names, hsl() and oklch() all work; one probe serves every instance and each colour is parsed once.\nconst textColours = new Map<string, string | undefined>()\nlet colourProbe: CanvasRenderingContext2D | null = null\n\nfunction textColourFor(bg: string) {\n  if (!bg || bg === \"transparent\" || typeof document === \"undefined\") return undefined\n  if (textColours.has(bg)) return textColours.get(bg)\n  colourProbe ??= document.createElement(\"canvas\").getContext(\"2d\")\n  if (!colourProbe) return undefined\n  colourProbe.fillStyle = \"#000\"\n  colourProbe.fillStyle = bg\n  const value = String(colourProbe.fillStyle)\n  const hex = value.match(/^#([0-9a-f]{6})$/i)\n  let r = 0\n  let g = 0\n  let b = 0\n  let a = 1\n  if (hex) {\n    const n = parseInt(hex[1], 16)\n    r = n >> 16\n    g = (n >> 8) & 255\n    b = n & 255\n  } else {\n    const parts = value.match(/[\\d.]+/g)?.map(Number) ?? [0, 0, 0, 0]\n    r = parts[0]\n    g = parts[1]\n    b = parts[2]\n    a = parts[3] ?? 1\n  }\n  const lum = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255\n  const colour = a < 0.2 ? undefined : lum > 0.55 ? \"rgb(10, 10, 10)\" : \"rgb(250, 250, 250)\"\n  textColours.set(bg, colour)\n  return colour\n}\n\nconst REDUCED_MOTION = \"(prefers-reduced-motion: reduce)\"\nconst subscribeReducedMotion = (onChange: () => void) => {\n  const query = window.matchMedia?.(REDUCED_MOTION)\n  query?.addEventListener?.(\"change\", onChange)\n  return () => query?.removeEventListener?.(\"change\", onChange)\n}\nconst prefersReducedMotion = () => window.matchMedia?.(REDUCED_MOTION).matches ?? false\nconst subscribeNothing = () => () => {}\n\nfunction selectItem(items: PrismCarouselItem[], index: number, onSelect?: (item: PrismCarouselItem, index: number) => void) {\n  const item = items[index]\n  if (!item) return\n  onSelect?.(item, index)\n  if (item.href) window.location.assign(item.href)\n}\n\ntype Settings = {\n  items: PrismCarouselItem[]\n  count: number\n  start: number\n  aspect: number\n  size: number\n  neighborScale: number\n  gap: number\n  radius: number\n  saturation: number\n  dim: number\n  sweep: number\n  sweepDuration: number\n  dispersion: number\n  autoplay: boolean\n  interval: number\n  loop: boolean\n  captions: boolean\n  controls: boolean\n  draggable: boolean\n  wheel: boolean\n  pauseOnHover: boolean\n  paused: boolean\n  dpr: number\n  reduced: boolean\n  hovering: boolean\n  onIndexChange?: (index: number) => void\n  onSelect?: (item: PrismCarouselItem, index: number) => void\n}\n\ntype ImageFx = {\n  colour: Spring\n  colourTarget: number\n  /** Time (ms) the colour spring may start: the delay before a colour drains. */\n  colourFrom: number\n  sweepStart: number | null\n  hover: Spring\n}\n\n// Where the carousel is and what each image is doing. It outlives the WebGL setup, so a Strict Mode remount\n// in development picks up where it was.\ntype Engine = {\n  pos: Spring\n  target: number\n  owner: number\n  pendingSnap: number\n  display: number\n  fx: Map<number, ImageFx>\n  hovered: number\n  drag: null | { id: number; x0: number; p0: number; active: boolean; samples: [number, number][] }\n  wheelAcc: number\n  wheelAt: number\n  images: Map<string, HTMLImageElement>\n}\n\nconst createEngine = (start: number): Engine => ({\n  pos: { x: start, v: 0 },\n  target: start,\n  owner: start,\n  pendingSnap: -1,\n  display: start,\n  fx: new Map(),\n  hovered: -1,\n  drag: null,\n  wheelAcc: 0,\n  wheelAt: 0,\n  images: new Map(),\n})\n\nconst fxOf = (e: Engine, i: number) => {\n  let f = e.fx.get(i)\n  if (!f) {\n    f = { colour: { x: 0, v: 0 }, colourTarget: 0, colourFrom: 0, sweepStart: null, hover: { x: 0, v: 0 } }\n    e.fx.set(i, f)\n  }\n  return f\n}\n\nfunction Chevron({ direction }: { direction: \"left\" | \"right\" }) {\n  return (\n    <svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">\n      <polyline points={direction === \"left\" ? \"15 18 9 12 15 6\" : \"9 18 15 12 9 6\"} />\n    </svg>\n  )\n}\n\nexport function PrismCarousel({\n  items = DEFAULT_ITEMS,\n  startIndex = 0,\n  aspect = 1.5,\n  size = 0.62,\n  neighborScale = 0.66,\n  gap = 14,\n  radius = 18,\n  saturation = 0,\n  dim = 0.2,\n  sweep = 1,\n  sweepDuration = 1.1,\n  dispersion = 1,\n  autoplay = true,\n  interval = 4.5,\n  loop = true,\n  captions = true,\n  controls = true,\n  draggable = true,\n  wheel = true,\n  pauseOnHover = true,\n  backgroundColor = \"transparent\",\n  paused = false,\n  dpr = 2,\n  controlsRef,\n  onIndexChange,\n  onSelect,\n  className,\n  style,\n  children,\n  onKeyDown,\n  onPointerEnter,\n  onPointerLeave,\n  ...props\n}: PrismCarouselProps) {\n  const count = items.length\n  const start = count ? clamp(Math.round(startIndex), 0, count - 1) : 0\n  const [display, setDisplay] = React.useState(start)\n  const [hovering, setHovering] = React.useState(false)\n  const reduced = React.useSyncExternalStore(subscribeReducedMotion, prefersReducedMotion, () => false)\n  // Parsed on the client only: the server has no canvas, and hydration then re-renders with the colour.\n  const fg = React.useSyncExternalStore(subscribeNothing, () => textColourFor(backgroundColor), () => undefined)\n\n  const surfaceRef = React.useRef<HTMLDivElement>(null)\n  const captionRef = React.useRef<HTMLDivElement>(null)\n  const titlesRef = React.useRef<HTMLDivElement>(null)\n  const engineRef = React.useRef<Engine | null>(null)\n  const syncRef = React.useRef<(() => void) | null>(null)\n  const apiRef = React.useRef<{ navigate: (delta: number) => void; goTo: (index: number) => void } | null>(null)\n  const settings: Settings = {\n    items,\n    count,\n    start,\n    aspect,\n    size,\n    neighborScale,\n    gap,\n    radius,\n    saturation,\n    dim,\n    sweep,\n    sweepDuration,\n    dispersion,\n    autoplay,\n    interval,\n    loop,\n    captions,\n    controls,\n    draggable,\n    wheel,\n    pauseOnHover,\n    paused,\n    dpr,\n    reduced,\n    hovering,\n    onIndexChange,\n    onSelect,\n  }\n  const settingsRef = React.useRef(settings)\n\n  // This effect runs exactly once. A prop change reaches it through settingsRef and sync(), never by\n  // tearing the context down.\n  React.useEffect(() => {\n    const surface = surfaceRef.current\n    // The root's ref stays the consumer's, so the root is reached through the surface.\n    const root = surface?.parentElement\n    if (!surface || !root) return\n    const e = (engineRef.current ??= createEngine(settingsRef.current.start))\n\n    // The canvas is made here, not in JSX: React Strict Mode runs this effect twice in development, and a\n    // context lost by the first cleanup would come straight back from getContext() on the same element.\n    const canvas = document.createElement(\"canvas\")\n    canvas.className = \"absolute inset-0 block h-full w-full\"\n    canvas.setAttribute(\"aria-hidden\", \"true\")\n    const gl = canvas.getContext(\"webgl2\", { alpha: true, premultipliedAlpha: true, antialias: false, depth: false, stencil: false })\n    // Without WebGL 2 (jsdom, GPU-less CI, an old browser) no images draw, but the caption, controls,\n    // keyboard and autoplay still work and nothing throws.\n    const renderer = gl ? createRenderer(gl, canvas) : null\n    if (renderer) surface.appendChild(canvas)\n\n    let raf = 0\n    let last = 0\n    let visible = true\n    let disposed = false\n    let autoplayTimer = 0\n    let width = 0\n    let height = 0\n    let captionBlock = CAPTION_BLOCK\n    let metrics: Metrics | null = null\n    let boxes: Box[] = []\n    let loadedItems: PrismCarouselItem[] | null = null\n    let loads = 0\n    let watchedCaption: HTMLElement | null = null\n    let dprKey = settingsRef.current.dpr\n    let layoutKey = \"\"\n    let autoplayKey = \"\"\n\n    const layoutKeyOf = (s: Settings) => [s.aspect, s.size, s.neighborScale, s.gap, s.radius, s.saturation, s.dim, s.sweep, s.dispersion, s.loop, s.count, s.captions, s.controls].join()\n    const autoplayKeyOf = (s: Settings) => [s.autoplay, s.paused, s.interval, s.pauseOnHover, s.hovering, s.loop, s.count, s.reduced].join()\n\n    const measureCaption = () => {\n      const el = captionRef.current\n      return el && el.offsetHeight > 0 ? el.offsetHeight : 0\n    }\n\n    const layout = () => {\n      metrics = computeMetrics(width, height, captionBlock, settingsRef.current)\n      root.style.setProperty(\"--prism-caption-y\", `${metrics.captionY}px`)\n    }\n\n    const draw = (now: number) => {\n      const s = settingsRef.current\n      if (!renderer || !metrics || !s.count) return\n      const m = metrics\n      boxes = layoutImages(e.pos.x, s.count, s.loop, m, s.dim)\n      const speedPx = Math.abs(e.pos.v) * m.D\n      const spread = s.reduced ? 0 : s.dispersion * DISPERSION_TIME * speedPx\n      renderer.draw(\n        boxes.map((b) => {\n          const f = fxOf(e, b.index)\n          let reveal = NO_SWEEP\n          let sweepStrength = 0\n          if (f.sweepStart !== null) {\n            reveal = sweepEdge(now, f.sweepStart, s.sweepDuration)\n            sweepStrength = s.sweep * f.colour.x\n          }\n          return {\n            key: b.index,\n            x: b.x,\n            y: b.y,\n            w: b.w,\n            h: b.h,\n            radius: s.radius * (b.h / m.Ha),\n            alpha: b.alpha,\n            bright: b.bright,\n            sat: s.saturation,\n            colour: f.colour.x,\n            hover: f.hover.x,\n            reveal,\n            sweep: sweepStrength,\n            disp: Math.min(DISPERSION_MAX, spread / Math.max(1, b.w)),\n          }\n        })\n      )\n    }\n\n    const setDisplayIndex = (i: number) => {\n      if (i === e.display) return\n      e.display = i\n      setDisplay(i)\n      settingsRef.current.onIndexChange?.(i)\n    }\n\n    const frame = (now: number) => {\n      raf = 0\n      // Never schedule while off screen; the IntersectionObserver wakes the loop again.\n      if (!visible) return\n      const s = settingsRef.current\n      const dt = clamp((now - last) / 1000, 0, MAX_DT)\n      last = now\n      let moving = false\n      if (!e.drag?.active) {\n        stepSpring(e.pos, e.target, POSITION_SPRING.omega, POSITION_SPRING.zeta, dt)\n        if (Math.abs(e.pos.x - e.target) < 1e-4 && Math.abs(e.pos.v) < 1e-3) {\n          e.pos.x = e.target\n          e.pos.v = 0\n        } else moving = true\n      } else moving = true\n      const shown = s.count ? wrap(Math.round(e.pos.x), s.count) : 0\n      if (e.pendingSnap === shown) {\n        const f = fxOf(e, shown)\n        f.colour.x = 1\n        f.colour.v = 0\n        e.pendingSnap = -1\n      }\n      for (const [i, f] of e.fx) {\n        if (now >= f.colourFrom) stepSpring(f.colour, f.colourTarget, COLOUR_OUT_SPRING.omega, COLOUR_OUT_SPRING.zeta, dt)\n        if (Math.abs(f.colour.x - f.colourTarget) > 1e-3 || Math.abs(f.colour.v) > 1e-3) moving = true\n        else {\n          f.colour.x = f.colourTarget\n          f.colour.v = 0\n        }\n        const hoverTarget = e.hovered === i && i !== e.owner ? 1 : 0\n        stepSpring(f.hover, hoverTarget, hoverTarget ? HOVER_IN : HOVER_OUT, 1, dt)\n        if (Math.abs(f.hover.x - hoverTarget) > 1e-3) moving = true\n        else {\n          f.hover.x = hoverTarget\n          f.hover.v = 0\n        }\n        if (f.sweepStart !== null) {\n          if (sweepEdge(now, f.sweepStart, s.sweepDuration) > SWEEP_DONE) f.sweepStart = null\n          else moving = true\n        }\n      }\n      setDisplayIndex(shown)\n      draw(now)\n      // The loop keeps going only while something moves: the position, a colour, a hover, a sweep or a drag.\n      if (moving) raf = requestAnimationFrame(frame)\n    }\n\n    const wake = () => {\n      if (raf || !visible || document.hidden) return\n      last = performance.now() - HEAD_START\n      raf = requestAnimationFrame(frame)\n    }\n\n    // The colour passes from the image that was active to the one that will be.\n    const handOff = (to: number, now: number) => {\n      const s = settingsRef.current\n      if (to === e.owner) return\n      const old = fxOf(e, e.owner)\n      old.colourTarget = 0\n      old.colourFrom = now + COLOUR_OUT_DELAY\n      const f = fxOf(e, to)\n      f.colourTarget = 1\n      f.colourFrom = 0\n      f.colour.v = 0\n      if (s.sweep > 0 && !s.reduced) {\n        f.colour.x = 1\n        f.sweepStart = now\n        e.pendingSnap = -1\n      } else {\n        // Without a sweep the colour snaps on as the move crosses its midpoint.\n        f.colour.x = 0\n        f.sweepStart = null\n        e.pendingSnap = to\n      }\n      e.owner = to\n    }\n\n    // One step per interval. The timer restarts after every move, and holds while paused, hovered, off\n    // screen, in a hidden tab and for reduced-motion users.\n    const scheduleAutoplay = () => {\n      window.clearTimeout(autoplayTimer)\n      const s = settingsRef.current\n      const held = s.paused || !s.autoplay || (s.pauseOnHover && s.hovering) || s.reduced || document.hidden || !visible || s.count < 2\n      if (held) return\n      if (!s.loop && e.target >= s.count - 1) return\n      autoplayTimer = window.setTimeout(() => navigate(1), Math.max(MIN_INTERVAL, s.interval) * 1000)\n    }\n\n    const navigate = (delta: number) => {\n      const s = settingsRef.current\n      if (!s.count || !delta || e.drag?.active) return\n      const next = s.loop ? e.target + delta : clamp(e.target + delta, 0, s.count - 1)\n      if (next === e.target) return\n      e.target = next\n      handOff(wrap(next, s.count), performance.now())\n      wake()\n      scheduleAutoplay()\n    }\n\n    const goTo = (index: number) => {\n      const s = settingsRef.current\n      if (!s.count) return\n      const i = wrap(Math.round(index), s.count)\n      let delta = i - wrap(e.target, s.count)\n      if (s.loop && Math.abs(delta) > s.count / 2) delta -= Math.sign(delta) * s.count\n      navigate(delta)\n    }\n\n    const load = (list: PrismCarouselItem[]) => {\n      loadedItems = list\n      const generation = ++loads\n      if (!renderer) return\n      renderer.clearTextures()\n      list.forEach((item, i) => {\n        const done = (image: HTMLImageElement) => {\n          if (disposed || generation !== loads) return\n          renderer.upload(i, image)\n          // The first image sweeps in once it has loaded.\n          if (i === e.owner) {\n            const f = fxOf(e, i)\n            if (f.colourTarget === 0 && f.sweepStart === null) {\n              const s = settingsRef.current\n              f.colourTarget = 1\n              f.colour.x = 1\n              f.colour.v = 0\n              if (s.sweep > 0 && !s.reduced) f.sweepStart = performance.now()\n            }\n          }\n          wake()\n        }\n        const cached = e.images.get(item.src)\n        if (cached?.complete && cached.naturalWidth) return done(cached)\n        const image = cached ?? new Image()\n        if (!cached) {\n          image.crossOrigin = \"anonymous\"\n          image.decoding = \"async\"\n          image.src = item.src\n          e.images.set(item.src, image)\n        }\n        image.addEventListener(\"load\", () => done(image), { once: true })\n        image.addEventListener(\"error\", () => console.warn(`PrismCarousel: couldn't load ${item.src} (it must allow cross-origin use)`), { once: true })\n      })\n    }\n\n    const resizeObserver = new ResizeObserver(() => resize())\n\n    const watchCaption = () => {\n      const el = captionRef.current\n      if (el === watchedCaption) return\n      if (watchedCaption) resizeObserver.unobserve(watchedCaption)\n      if (el) resizeObserver.observe(el)\n      watchedCaption = el\n    }\n\n    const resize = () => {\n      const rect = root.getBoundingClientRect()\n      width = rect.width\n      height = rect.height\n      captionBlock = measureCaption()\n      // At most 2 device pixels per CSS pixel, and never more than `dpr`.\n      renderer?.setSize(rect.width, rect.height, Math.min(window.devicePixelRatio || 1, 2, Math.max(0.5, settingsRef.current.dpr)))\n      layout()\n      draw(performance.now())\n    }\n\n    // Called after every render with the new props in settingsRef. Each change does only what it needs.\n    const sync = () => {\n      const s = settingsRef.current\n      if (s.items !== loadedItems) load(s.items)\n      if (s.dpr !== dprKey) {\n        dprKey = s.dpr\n        resize()\n      }\n      const nextLayout = layoutKeyOf(s)\n      if (nextLayout !== layoutKey) {\n        layoutKey = nextLayout\n        if (s.count) {\n          if (e.target > s.count - 1 && !s.loop) e.target = s.count - 1\n          watchCaption()\n          captionBlock = measureCaption()\n          layout()\n          draw(performance.now())\n          wake()\n        }\n      }\n      const nextAutoplay = autoplayKeyOf(s)\n      if (nextAutoplay !== autoplayKey) {\n        autoplayKey = nextAutoplay\n        scheduleAutoplay()\n      }\n    }\n\n    const hit = (clientX: number, clientY: number) => {\n      const r = surface.getBoundingClientRect()\n      const x = clientX - r.left\n      const y = clientY - r.top\n      return boxes.find((b) => x >= b.x && x <= b.x + b.w && y >= b.y && y <= b.y + b.h) ?? null\n    }\n\n    // Pointer: drag with inertia, click a neighbour to go to it, hover a neighbour for some colour.\n    const onPointerDown = (event: PointerEvent) => {\n      if (event.pointerType === \"mouse\" && event.button !== 0) return\n      e.drag = { id: event.pointerId, x0: event.clientX, p0: e.pos.x, active: false, samples: [[performance.now(), event.clientX]] }\n    }\n\n    const onPointerMove = (event: PointerEvent) => {\n      const d = e.drag\n      if (!d || d.id !== event.pointerId) {\n        if (event.pointerType === \"mouse\" && !d) {\n          const b = hit(event.clientX, event.clientY)\n          const index = b && Math.abs(b.o) > 0.5 ? b.index : -1\n          if (index !== e.hovered) {\n            e.hovered = index\n            wake()\n          }\n          surface.style.cursor = b ? \"pointer\" : \"\"\n        }\n        return\n      }\n      const s = settingsRef.current\n      if (!d.active) {\n        if (!s.draggable || Math.abs(event.clientX - d.x0) < DRAG_THRESHOLD) return\n        d.active = true\n        d.x0 = event.clientX\n        try {\n          surface.setPointerCapture(event.pointerId)\n        } catch {\n          // The pointer was already released.\n        }\n        surface.style.cursor = \"grabbing\"\n      }\n      const m = metrics\n      if (!m) return\n      // One pixel of drag is one pixel of travel at w(½) + gap per image.\n      let p = d.p0 - (event.clientX - d.x0) / m.D\n      if (!s.loop) {\n        const lo = 0\n        const hi = s.count - 1\n        if (p < lo) p = lo - (lo - p) * OVERDRAG\n        if (p > hi) p = hi + (p - hi) * OVERDRAG\n      }\n      const now = performance.now()\n      d.samples.push([now, event.clientX])\n      while (d.samples.length > 2 && now - d.samples[0][0] > VELOCITY_WINDOW) d.samples.shift()\n      const [t0, x0] = d.samples[0]\n      e.pos.v = now - t0 > 0 ? ((-(event.clientX - x0) / (now - t0)) * 1000) / m.D : 0\n      e.pos.x = p\n      e.target = Math.round(p)\n      wake()\n    }\n\n    const onPointerUp = (event: PointerEvent) => {\n      const d = e.drag\n      if (!d || d.id !== event.pointerId) return\n      e.drag = null\n      surface.style.cursor = \"\"\n      const s = settingsRef.current\n      if (!d.active) {\n        // A click: select the active image, or go to the neighbour that was clicked.\n        const b = hit(event.clientX, event.clientY)\n        if (!b) return\n        if (Math.abs(b.o) < 0.5) selectItem(s.items, b.index, s.onSelect)\n        else navigate(Math.round(b.o))\n        return\n      }\n      const now = performance.now()\n      const recent = d.samples.filter(([t]) => now - t < VELOCITY_WINDOW)\n      let v = 0\n      if (recent.length >= 2 && metrics) {\n        const [ta, xa] = recent[0]\n        const [tb, xb] = recent[recent.length - 1]\n        if (tb > ta) v = ((-(xb - xa) / (tb - ta)) * 1000) / metrics.D\n      }\n      e.pos.v = v\n      let target = Math.round(e.pos.x + v * RELEASE_LOOKAHEAD)\n      if (!s.loop) target = clamp(target, 0, s.count - 1)\n      e.target = target\n      handOff(wrap(target, s.count), now)\n      wake()\n      scheduleAutoplay()\n    }\n\n    const onPointerLeave = () => {\n      if (e.hovered === -1) return\n      e.hovered = -1\n      wake()\n    }\n\n    const onWheel = (event: WheelEvent) => {\n      if (!settingsRef.current.wheel) return\n      event.preventDefault()\n      const unit = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? height || 400 : 1\n      const delta = (Math.abs(event.deltaX) > Math.abs(event.deltaY) ? event.deltaX : event.deltaY) * unit\n      const now = performance.now()\n      if (now - e.wheelAt > WHEEL_RESET) e.wheelAcc = 0\n      e.wheelAt = now\n      e.wheelAcc += delta\n      const steps = Math.sign(e.wheelAcc) * Math.min(WHEEL_MAX_STEPS, Math.round(Math.abs(e.wheelAcc) / WHEEL_STEP))\n      if (steps) {\n        e.wheelAcc -= steps * WHEEL_STEP\n        navigate(steps)\n      }\n    }\n\n    const onVisibility = () => {\n      wake()\n      scheduleAutoplay()\n    }\n\n    // Off screen the loop stops where it is and autoplay holds; both carry on when the carousel is back.\n    const intersection = new IntersectionObserver((entries) => {\n      const was = visible\n      visible = entries.some((entry) => entry.isIntersecting)\n      if (visible === was) return\n      if (visible) wake()\n      scheduleAutoplay()\n    })\n\n    resizeObserver.observe(root)\n    watchCaption()\n    intersection.observe(root)\n    document.addEventListener(\"visibilitychange\", onVisibility)\n    surface.addEventListener(\"pointerdown\", onPointerDown, { passive: true })\n    surface.addEventListener(\"pointermove\", onPointerMove, { passive: true })\n    surface.addEventListener(\"pointerup\", onPointerUp, { passive: true })\n    surface.addEventListener(\"pointercancel\", onPointerUp, { passive: true })\n    surface.addEventListener(\"pointerleave\", onPointerLeave, { passive: true })\n    // Not passive: the wheel moves the carousel instead of the page while it is enabled.\n    surface.addEventListener(\"wheel\", onWheel, { passive: false })\n\n    resize()\n    load(settingsRef.current.items)\n    layoutKey = layoutKeyOf(settingsRef.current)\n    autoplayKey = autoplayKeyOf(settingsRef.current)\n    scheduleAutoplay()\n    syncRef.current = sync\n    apiRef.current = { navigate, goTo }\n\n    // Release everything, then the context, then the element.\n    return () => {\n      disposed = true\n      cancelAnimationFrame(raf)\n      window.clearTimeout(autoplayTimer)\n      e.drag = null\n      syncRef.current = null\n      apiRef.current = null\n      resizeObserver.disconnect()\n      intersection.disconnect()\n      document.removeEventListener(\"visibilitychange\", onVisibility)\n      surface.removeEventListener(\"pointerdown\", onPointerDown)\n      surface.removeEventListener(\"pointermove\", onPointerMove)\n      surface.removeEventListener(\"pointerup\", onPointerUp)\n      surface.removeEventListener(\"pointercancel\", onPointerUp)\n      surface.removeEventListener(\"pointerleave\", onPointerLeave)\n      surface.removeEventListener(\"wheel\", onWheel)\n      surface.style.cursor = \"\"\n      renderer?.dispose()\n      gl?.getExtension(\"WEBGL_lose_context\")?.loseContext()\n      canvas.remove()\n    }\n  }, [])\n\n  // Props reach the loop through a ref written here, after the setup effect, never during render. It is a\n  // layout effect so a change of layout (captions toggled, a new size) is measured and drawn before paint.\n  React.useLayoutEffect(() => {\n    settingsRef.current = settings\n    syncRef.current?.()\n  })\n\n  // The caption swaps when a move crosses its midpoint, then fades in.\n  const shownCaption = React.useRef(start)\n  React.useLayoutEffect(() => {\n    if (shownCaption.current === display) return\n    shownCaption.current = display\n    if (reduced) return\n    titlesRef.current?.animate?.([{ opacity: 0 }, { opacity: 1 }], { duration: CAPTION_FADE, delay: CAPTION_DELAY, easing: CAPTION_EASE, fill: \"backwards\" })\n  }, [display, reduced])\n\n  React.useImperativeHandle(\n    controlsRef,\n    () => ({\n      next: () => apiRef.current?.navigate(1),\n      previous: () => apiRef.current?.navigate(-1),\n      goTo: (index: number) => apiRef.current?.goTo(index),\n    }),\n    []\n  )\n\n  const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    onKeyDown?.(event)\n    if (event.defaultPrevented || event.target !== event.currentTarget) return\n    if (event.key === \"ArrowRight\") {\n      event.preventDefault()\n      apiRef.current?.navigate(1)\n    } else if (event.key === \"ArrowLeft\") {\n      event.preventDefault()\n      apiRef.current?.navigate(-1)\n    } else if (event.key === \"Enter\") selectItem(items, display, onSelect)\n  }\n\n  const item = items[display]\n\n  return (\n    <div\n      data-slot=\"prism-carousel\"\n      role=\"region\"\n      aria-roledescription=\"carousel\"\n      aria-label={DEFAULT_LABEL}\n      tabIndex={0}\n      className={cn(\"relative h-full min-h-105 w-full overflow-hidden text-foreground outline-none focus-visible:inset-ring-2 focus-visible:inset-ring-current/35\", className)}\n      style={{ backgroundColor, color: fg, ...style }}\n      onKeyDown={handleKeyDown}\n      onPointerEnter={(event) => {\n        onPointerEnter?.(event)\n        if (event.pointerType === \"mouse\") setHovering(true)\n      }}\n      onPointerLeave={(event) => {\n        onPointerLeave?.(event)\n        if (event.pointerType === \"mouse\") setHovering(false)\n      }}\n      {...props}\n    >\n      <div ref={surfaceRef} data-slot=\"prism-carousel-surface\" className=\"absolute inset-0 touch-pan-y select-none\" />\n      <ul className=\"sr-only\">\n        {items.map((it, i) => (\n          <li key={i}>{it.title ? `${it.title}: ${it.alt}` : it.alt}</li>\n        ))}\n      </ul>\n      {(captions || controls) && (\n        <div ref={captionRef} data-slot=\"prism-carousel-caption\" className=\"pointer-events-none absolute inset-x-0 top-[var(--prism-caption-y,82%)] flex flex-col items-center gap-3\">\n          {captions && (\n            <div ref={titlesRef} className=\"flex flex-col items-center gap-0.5 text-center\" aria-live={autoplay && !paused && !hovering && !reduced ? \"off\" : \"polite\"}>\n              {item?.title && <span className=\"text-[15px] leading-[1.35] font-semibold\">{item.title}</span>}\n              {item?.subtitle && <span className=\"text-[13px] leading-[1.35] opacity-60\">{item.subtitle}</span>}\n            </div>\n          )}\n          {controls && (\n            <div data-slot=\"prism-carousel-controls\" className=\"pointer-events-auto flex items-center gap-3.5 text-[12px] tabular-nums\">\n              <button\n                type=\"button\"\n                aria-label=\"Previous\"\n                onClick={() => apiRef.current?.navigate(-1)}\n                className=\"grid size-8 cursor-pointer place-items-center rounded-full bg-current/10 transition-[background-color] duration-160 ease-[ease] hover:bg-current/18 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-current\"\n              >\n                <Chevron direction=\"left\" />\n              </button>\n              <span className=\"min-w-13 text-center opacity-60\">\n                {pad2(display + 1)} / {pad2(count)}\n              </span>\n              <button\n                type=\"button\"\n                aria-label=\"Next\"\n                onClick={() => apiRef.current?.navigate(1)}\n                className=\"grid size-8 cursor-pointer place-items-center rounded-full bg-current/10 transition-[background-color] duration-160 ease-[ease] hover:bg-current/18 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-current\"\n              >\n                <Chevron direction=\"right\" />\n              </button>\n            </div>\n          )}\n        </div>\n      )}\n      {children}\n    </div>\n  )\n}\n",
      "type": "registry:ui"
    }
  ],
  "meta": {
    "added": "2026-10-28"
  },
  "categories": [
    "card"
  ],
  "type": "registry:ui"
}