{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "picture-wave",
  "title": "Picture Wave",
  "description": "Picture cards fly in as a wave between two words, hold, then burst into a floating field that leans away from the pointer, drawn in one call and idle when still. Raw WebGL 2, no dependencies.",
  "files": [
    {
      "path": "registry/mewo/ui/picture-wave.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { cn } from \"@/lib/utils\"\n\nexport type PictureWaveState = \"wave\" | \"field\"\nexport type PictureWaveOrientation = \"auto\" | \"horizontal\" | \"vertical\"\n\nexport interface PictureWaveImage {\n  /** The picture's URL, served with CORS. */\n  src: string\n  /** Its width ÷ height. A card takes these proportions between 0.6 and 1.7 and crops the picture beyond them. */\n  aspect: number\n}\n\nexport interface PictureWaveControls {\n  /** Flies the wave in again from nothing. */\n  replay: () => void\n}\n\nexport interface PictureWaveProps extends Omit<React.ComponentProps<\"div\">, \"children\"> {\n  /** The pictures on the cards; each depth layer of the field cycles through them in its own order (up to 100). */\n  images?: PictureWaveImage[]\n  /** The two words riding the wave's ends; an empty list leaves them out. */\n  words?: string[]\n  /** `\"wave\"`: the cards fly in and hold one period of a sine between the words. `\"field\"`: the wave then bursts\n   * into a field over the whole box that floats and leans away from the pointer. Back to `\"wave\"`, it gathers again. */\n  state?: PictureWaveState\n  /** The wave's long axis. `\"auto\"` lays it across, and stands it up in a box narrower than 900px, as on a phone. */\n  orientation?: PictureWaveOrientation\n  /** How far the field's cards lean away from the pointer, the nearer ones more: 0 holds them still. */\n  lean?: number\n  /** The field's slow idle drift. Off, nothing moves once the cards settle and the pointer rests. */\n  float?: boolean\n  /** Called with a picture's index in `images` when its card in the field is clicked. */\n  onPick?: (index: number) => void\n  /** `replay()`, to fly the wave in again. */\n  controlsRef?: React.Ref<PictureWaveControls>\n  /** Override the device pixel ratio, which is capped at 2. */\n  dpr?: number\n}\n\ntype Settings = Required<Pick<PictureWaveProps, \"images\" | \"state\" | \"orientation\" | \"lean\" | \"float\">> & Pick<PictureWaveProps, \"onPick\" | \"dpr\">\ntype World = \"horizontal\" | \"vertical\"\ntype Keys = readonly (readonly [number, number])[]\n\n// the default pictures: placeholder cats, each a fixed one from cataas.com at its small size, with its proportions\n// (width ÷ height), which seed the field's layout\nconst CATS: [id: string, aspect: number][] = [\n  [\"9KJtZfvlNhq7KbAm\", 1.502], [\"eM4t8b4yK9eu2hPm\", 0.558], [\"h4QKV0SMYKgSqHKV\", 1.667], [\"qEUtU3MgNTamybTm\", 0.562],\n  [\"RGUEWaEBQfkVW8zJ\", 0.812], [\"YqxwxAM4KsP47qTE\", 0.747], [\"3OI0zHkZS3RCb8xa\", 0.785], [\"0F0IKAPOdWiE755P\", 0.562],\n  [\"0mstmOIucwiN80jb\", 1.35], [\"1bJraW0IwSPm3MVd\", 0.75], [\"1N2AH31jiY6N9TYc\", 0.559], [\"2AjkEyDta2fk44NE\", 0.75],\n  [\"2Bb8z8bR1w5EFHhz\", 0.562], [\"2eXYJhGolHqOAKaM\", 0.883], [\"2xsQpqvspMC4OjXs\", 0.562], [\"3zM2HCQRdiZHB3Oo\", 0.562],\n  [\"4cnQObJyASFknf5L\", 0.451], [\"5enhMoq1fey3akP5\", 0.75], [\"7b6yOergmSkMZH7w\", 1.778], [\"7d7EPnouLU1Vwkdc\", 1.003],\n  [\"7VVdI0PDAwo0GLeJ\", 0.562], [\"89ddp91tTolLtlPz\", 0.45], [\"9hrU6WQjC4dn75hm\", 0.642], [\"A8f9fzuNUo7m54Jn\", 0.563],\n  [\"aKJD8Z7P8bQ8FDZ8\", 1.923], [\"BcBdLFp6n00qaTAm\", 0.752], [\"blCoC4jk99A5ChEC\", 0.747], [\"bOakL3BtHlryCLW3\", 0.75],\n  [\"3xajd1BkJ3RbfSkx\", 0.667], [\"GILRuBVxMjB0htly\", 0.75], [\"BuhnkqtpZqAxfsqQ\", 0.562], [\"iTmHMagWzAFn7fWM\", 0.748],\n  [\"mJ75VJU1htTphntH\", 0.75], [\"mrPYfaRfJqUmxHN0\", 0.75], [\"nxxtDWRE2dbpfM4D\", 0.75], [\"OZMYTHi2vMfUZEz0\", 1.782],\n  [\"ToFVsijtJWykEzKp\", 0.753], [\"VCV7NVM2hPvTPCc2\", 1.333], [\"xAeSjzULC9p4K8dz\", 0.75], [\"7xrDGcZqKEL4VTAM\", 0.6],\n  [\"G2gU9xo3HUvi70LL\", 0.75], [\"i17rOOhMY9XBvrUr\", 0.75], [\"NuCbxqOj92foqkh4\", 0.748], [\"S7LsxaFfwWhOZ6ir\", 0.751],\n  [\"TTY9yyybuIJMHYWs\", 0.75], [\"um3WTSJgjcOYucjo\", 0.562], [\"UPOwrNmxZARXkZuV\", 0.75], [\"VGIZrxdpLB3domok\", 0.75],\n  [\"yDesNhidQSPbzLAz\", 0.752], [\"YxFaRBNhBAMi1vBP\", 0.998], [\"5n4MTAC6ld0bVeCe\", 1.778], [\"AZo9zQWvZFvOBdGF\", 1.734],\n  [\"dBaJIho0PvGiwVsm\", 0.752], [\"JazIRPFqDYCXNJaA\", 1.176], [\"ngfJ6lSzEdJQ9GO8\", 1.013], [\"OcCyCN1wBhrCZAvP\", 1.333],\n  [\"7kM2cnX1djCXn0ut\", 1.333], [\"BswnFbCjndW2X9oO\", 0.932], [\"EMgyHa7PjTe3j9SE\", 0.75], [\"IN8bFy4SO9xHp4ib\", 0.75],\n  [\"YHCa57fmqzJfBODT\", 0.8], [\"1CF7xZmlX0t8QpgP\", 1.504], [\"1DrcyohjhwcNaRIz\", 1.333], [\"1KeQpy7eHqi0SFmc\", 0.75],\n  [\"1ntkA1kLWffNS2xN\", 1.778], [\"1si02A2ZNdeNH3yo\", 0.802], [\"1wpap8yckt96vOoU\", 1.027], [\"1Y3dpssxcbHPEkfO\", 0.75],\n  [\"22tTAaFI1Q33YBGO\", 1.778], [\"28ZtVybuyptnWzTM\", 0.75], [\"2lnVocnpd25cUka7\", 0.906], [\"2lo2luOySDGPFCng\", 0.75],\n]\nexport const PICTURES: PictureWaveImage[] = CATS.map(([id, aspect]) => ({ src: `https://cataas.com/cat/${id}?type=small`, aspect }))\nconst WORDS = [\"Between\", \"Rivers\"]\n\n// The sequence, in seconds from the first card: the wave grows in about its centre, holds (where \"wave\" rests),\n// the words dim and go, the cards burst into the field and land at TIME.field.\nconst TIME = { wordsOn: 0.14, wave: 1.88, wordsDim: 1.96, wordsOff: 2.18, field: 3.83 }\n// the wave's scale against time\nconst GROW: Keys = [[0, 0], [0.087, 0.05], [0.22, 0.124], [0.353, 0.273], [0.474, 0.471], [0.6, 0.703], [0.724, 0.843], [0.858, 0.942], [0.99, 0.983], [1.13, 1]]\n// the field's drift and lean ease in over SETTLE_IN once it lands, and out over SETTLE_OUT before it gathers again\nconst SETTLE_IN = 1.5\nconst SETTLE_OUT = 0.5\n// the pointer is followed with this time constant (s)\nconst LEAN_EASE = 0.35\nconst PIXEL_BUDGET = 4.5e6\nconst CELL = 256\nconst GROUND = [217, 212, 203] as const\n\n// Every length is in heights of the box from its centre, y down. The wave: y = A sin(2π (x + span) / period + phase)\n// along its long axis, from −span to span about its centre; gap runs from each end to the inner edge of its word.\ntype Ribbon = { axis: 0 | 1; centre: [number, number]; span: number; period: number; amp: number; phase: number; cardH: number; gap: [number, number] }\nconst RIBBON: Record<World, Ribbon> = {\n  horizontal: { axis: 0, centre: [0.1235, 0.002], span: 0.4035, period: 0.756, amp: -0.154, phase: -0.17, cardH: 0.105, gap: [0.053, 0.042] },\n  vertical: { axis: 1, centre: [-0.001, -0.0085], span: 0.2695, period: 0.506, amp: -0.076, phase: -0.18, cardH: 0.075, gap: [0.02, 0.026] },\n}\n// The burst: each card leaves its place in the wave for its place in the field, passing towards the viewer on the\n// way (it grows and moves out from the centre by `push` at mid-flight, and rises by `drop`). `order`: which cards\n// leave first (0 the start end, 1 the far end, 2 both ends, 3 the middle), over `spread` seconds; `ghost`: when the\n// field's other cards fade in.\ntype Burst = { size: number; start: number; dur: number; spread: number; order: number; push: number; drop: number; power: number; ghost: [number, number] }\nconst BURST: Record<World, Burst> = {\n  horizontal: { size: 0.93, start: 2.018, dur: 1.347, spread: 0.452, order: 1, push: 1.096, drop: -0.3, power: 1.89, ghost: [2.85, 3.2] },\n  vertical: { size: 0.9, start: 1.951, dur: 1.12, spread: 0.402, order: 3, push: 1.724, drop: -0.255, power: 1.613, ghost: [2.73, 3.18] },\n}\n// The field: three depth layers (near pictures, mid pictures, pale far cards) spread evenly (Poisson-disc, no two in\n// a layer overlapping) over `span` × `period`, which wraps vertically; the layers' parallax speeds shape the band the\n// pictures keep clear of above the centre. Cards are drawn at `size` of their base size.\ntype Layer = { speed: number; h: [number, number]; gap: number; cls: 0 | 1; depth: number }\ntype Field = { span: number; period: number; size: number; layers: Layer[] }\nconst FIELD: Record<World, Field> = {\n  horizontal: {\n    span: 3.2, period: 3.0, size: 0.75,\n    layers: [\n      { speed: 0.708, h: [0.19, 0.27], gap: 0.42, cls: 0, depth: 1 },\n      { speed: 0.637, h: [0.15, 0.21], gap: 0.36, cls: 0, depth: 0.7 },\n      { speed: 0.566, h: [0.13, 0.2], gap: 0.32, cls: 1, depth: 0.45 },\n    ],\n  },\n  vertical: {\n    span: 1.5, period: 2.6, size: 0.75,\n    layers: [\n      { speed: 0.986, h: [0.15, 0.21], gap: 0.36, cls: 0, depth: 1 },\n      { speed: 0.867, h: [0.12, 0.18], gap: 0.31, cls: 0, depth: 0.7 },\n      { speed: 0.789, h: [0.11, 0.16], gap: 0.28, cls: 1, depth: 0.45 },\n    ],\n  },\n}\n// Across, pictures keep their inner edge `column` from the centre and out of a headline's box above the centre\n// (half-width x, half-height h plus the card's, rising from y0 by `rise` per step of its layer's speed until\n// `until`), so a title over the field stays clear. Pale cards may pass behind; standing up, the text fills the width.\nconst CLEAR = { column: 0.34, hero: { x: 0.52, h: 0.18, y0: -0.095, rise: 0.749, until: 0.95 } }\n\nconst clamp01 = (x: number) => Math.min(1, Math.max(0, x))\nconst easeInOut = (x: number, p: number) => (x < 0.5 ? (2 * x) ** p / 2 : 1 - (2 - 2 * x) ** p / 2)\nconst wrap = (y: number, p: number) => (((y % p) + p) % p) - p / 2\n// the field's offsets from the centre, pulled in a little, and less as the headline's box rises\nconst pushIn = (v: number) => Math.exp(-0.16 * (1 - clamp01(v)) ** 2)\nconst PUSH = pushIn(0)\n// cards in the middle of the wave sit further back than its ends (smaller, drawn behind)\nconst deckDepth = (u: number) => 0.65 + 0.35 * Math.abs(2 * u - 1)\nconst deckAspect = (a: number) => Math.min(1.5, Math.max(0.6, a))\nconst delayOf = (order: number, u: number) => [u, 1 - u, 1 - Math.abs(2 * u - 1), Math.abs(2 * u - 1)][order]!\n\nconst rng = (seed: number) => () => {\n  seed = (seed + 0x6d2b79f5) | 0\n  let t = Math.imul(seed ^ (seed >>> 15), 1 | seed)\n  t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t\n  return ((t ^ (t >>> 14)) >>> 0) / 4294967296\n}\n\n/** A keyframed value at k, linear between keys and held past either end. */\nexport function valueAt(keys: Keys, k: number) {\n  if (k <= keys[0]![0]) return keys[0]![1]\n  for (let i = 1; i < keys.length; i++) {\n    const [b, vb] = keys[i]!\n    if (k <= b) {\n      const [a, va] = keys[i - 1]!\n      return va + ((vb - va) * (k - a)) / (b - a)\n    }\n  }\n  return keys[keys.length - 1]![1]\n}\n\n/** The wave's scale at time t: 0 before the first card, 1 once it has arrived. */\nexport const waveScale = (t: number) => valueAt(GROW, t)\n\n/** The words' look at time t: hidden, shown, or dimmed just before the burst. */\nexport function wordsAt(t: number): \"off\" | \"on\" | \"dim\" {\n  if (t >= TIME.wordsOn && t < TIME.wordsDim) return \"on\"\n  return t >= TIME.wordsDim && t < TIME.wordsOff ? \"dim\" : \"off\"\n}\n\n/** A picture card's proportions: its picture's, between 0.6 and 1.7. */\nexport const pictureAspect = (a: number) => Math.min(1.7, Math.max(0.6, a))\n\nexport type FieldCard = {\n  /** 0 a picture, 1 a pale card */\n  cls: 0 | 1\n  aspect: number\n  /** the picture it shows (an index into the pictures), or −1 */\n  img: number\n  layer: number\n  x0: number\n  y0: number\n  w: number\n  h: number\n  phase: number\n  /** where it rests in the field: x, y, w, h */\n  at0: [number, number, number, number]\n}\n\nfunction clearOfText(world: World, ly: Layer, x0: number, y0: number, w: number, h: number) {\n  if (world !== \"horizontal\" || ly.cls !== 0) return true\n  const F = FIELD[world]\n  const H = CLEAR.hero\n  if (Math.abs(x0) * PUSH - w / 2 < CLEAR.column) return false\n  for (let v = 0; v <= H.until + 1e-6; v += 0.05) {\n    const g = pushIn(v)\n    if (Math.abs(x0) * g - w / 2 >= H.x) continue\n    const y = wrap(y0 - ly.speed * v, F.period) * g\n    if (Math.abs(y - (H.y0 - H.rise * v)) < h / 2 + H.h) return false\n  }\n  return true\n}\n\n/** The field's cards for a world, seeded, from the pictures' proportions. */\nexport function buildField(world: World, seed: number, pictures: number[]): FieldCard[] {\n  const F = FIELD[world]\n  const r = rng(seed)\n  const cards: FieldCard[] = []\n  for (const [li, ly] of F.layers.entries()) {\n    // darts on a torus in y (the layer wraps); each draws its size first, so the text test sees the card's edges\n    const pts: [number, number, number, number, number][] = []\n    const order = pictures.map((_, i) => i)\n    for (let i = order.length - 1; i > 0; i--) {\n      const j = Math.floor(r() * (i + 1))\n      ;[order[i], order[j]] = [order[j]!, order[i]!]\n    }\n    for (let tries = 0; tries < 6000; tries++) {\n      const x = (r() - 0.5) * F.span\n      const y = r() * F.period\n      const h = ly.h[0] + r() * (ly.h[1] - ly.h[0])\n      const img = ly.cls === 0 && order.length ? order[pts.length % order.length]! : -1\n      const aspect = img >= 0 ? pictureAspect(pictures[img]!) : 0.75 + r() * 0.5\n      if (!clearOfText(world, ly, x, y, h * aspect * F.size, h * F.size)) continue\n      let ok = true\n      for (const [px, py] of pts) {\n        const dy = Math.min(Math.abs(py - y), F.period - Math.abs(py - y))\n        if (Math.hypot(px - x, dy) < ly.gap) {\n          ok = false\n          break\n        }\n      }\n      if (ok) pts.push([x, y, h, aspect, img])\n    }\n    for (const [x0, y0, h, aspect, img] of pts) {\n      const w = h * aspect\n      const card: FieldCard = { cls: ly.cls, aspect, img, layer: li, x0, y0, w, h, phase: r() * Math.PI * 2, at0: [0, 0, 0, 0] }\n      const at = [0, 0, 0, 0]\n      fieldAt(world, card, 0, 0, 0, 0, at)\n      card.at0 = [at[0]!, at[1]!, at[2]!, at[3]!]\n      cards.push(card)\n    }\n  }\n  return cards\n}\n\n// a card in the field: [x, y, w, h] into out. float (0 to 1) scales its idle drift; lean is the pointer's pull\nfunction fieldAt(world: World, c: FieldCard, time: number, float: number, leanX: number, leanY: number, out: number[]) {\n  const F = FIELD[world]\n  const depth = F.layers[c.layer]!.depth\n  const fx = Math.sin(time * 0.4 + c.phase) * 0.004 * float - leanX * 0.022 * depth\n  const fy = Math.cos(time * 0.33 + c.phase * 1.3) * 0.006 * float - leanY * 0.022 * depth\n  out[0] = c.x0 * PUSH + fx\n  out[1] = wrap(c.y0, F.period) * PUSH + fy\n  out[2] = c.w * F.size\n  out[3] = c.h * F.size\n  return out\n}\n\n/** The point u (0 to 1) along the wave at full size, from its centre: [x, y] into out. */\nexport function wavePoint(world: World, u: number, out: number[]) {\n  const R = RIBBON[world]\n  const a = -R.span + 2 * R.span * u\n  const across = R.amp * Math.sin((2 * Math.PI * (a + R.span)) / R.period + R.phase)\n  out[R.axis] = a\n  out[1 - R.axis] = across\n  return out\n}\n\nconst point = [0, 0]\n// a card of the wave at time t, u along it, the wave at scale s: [x, y, w, h] into out; false while hidden\nfunction burstAt(world: World, t: number, u: number, s: number, c: FieldCard, out: number[]) {\n  if (t < 0 || s <= 0.001) return false\n  const P = BURST[world]\n  const R = RIBBON[world]\n  const h0 = R.cardH * P.size * deckDepth(u) * s\n  const w0 = h0 * deckAspect(c.aspect)\n  wavePoint(world, u, point)\n  const ax = R.centre[0] + point[0]! * s\n  const ay = R.centre[1] + point[1]! * s\n  const p = clamp01((t - P.start - P.spread * delayOf(P.order, u)) / P.dur)\n  if (p <= 0) {\n    out[0] = ax\n    out[1] = ay\n    out[2] = w0\n    out[3] = h0\n    return true\n  }\n  const e = easeInOut(p, P.power)\n  const arc = Math.sin(Math.PI * e)\n  const [fx, fy, fw, fh] = c.at0\n  const m = 1 + P.push * arc\n  out[0] = (ax + (fx - ax) * e) * m\n  out[1] = (ay + (fy - ay) * e) * m + P.drop * arc\n  out[2] = (w0 + (fw - w0) * e) * m\n  out[3] = (h0 + (fh - h0) * e) * m\n  return true\n}\n\ntype Scene = { cards: FieldCard[]; slot: Int32Array; deck: number; order: number[] }\n\n// the wave: the pictures resting near the middle band, in order along its long axis; draw order: far layers first,\n// and in the wave its middle behind its ends\nfunction buildScene(world: World, pictures: number[]): Scene {\n  const cards = buildField(world, world === \"horizontal\" ? 21 : 23, pictures)\n  const axis = RIBBON[world].axis\n  const deck = cards\n    .map((c, i) => [i, c.at0[axis]] as const)\n    .filter(([i]) => cards[i]!.cls === 0 && Math.abs(cards[i]!.at0[1]) < 1.3)\n    .sort((a, b) => a[1] - b[1])\n    .map(([i]) => i)\n  const slot = new Int32Array(cards.length).fill(-1)\n  deck.forEach((i, k) => (slot[i] = k))\n  const rank = (i: number) => (2 - cards[i]!.layer) * 10 + (slot[i]! < 0 ? 0 : Math.abs((2 * slot[i]!) / Math.max(1, deck.length - 1) - 1))\n  const order = cards.map((_, i) => i).sort((a, b) => rank(a) - rank(b))\n  return { cards, slot, deck: deck.length, order }\n}\n\nconst VERTEX = `#version 300 es\nin vec4 aBox;\nin vec4 aUv;\nin vec2 aStyle;\nuniform vec2 uView;\nout vec2 vUv;\nout vec2 vStyle;\nvoid main() {\n  vec2 q = vec2(float(gl_VertexID & 1), float((gl_VertexID >> 1) & 1));\n  vUv = aUv.xy + q * aUv.zw;\n  vStyle = aStyle;\n  vec2 p = aBox.xy + (q - 0.5) * aBox.zw;\n  gl_Position = vec4(p.x / uView.x * 2.0 - 1.0, 1.0 - p.y / uView.y * 2.0, 0.0, 1.0);\n}`\n\n// kind 0 samples the atlas, kind 1 is a pale card in the theme's colour\nconst FRAGMENT = `#version 300 es\nprecision mediump float;\nuniform sampler2D uMap;\nuniform vec3 uPale;\nin vec2 vUv;\nin vec2 vStyle;\nout vec4 outColor;\nvoid main() {\n  vec4 tex = texture(uMap, vUv);\n  vec4 c = vStyle.x < 0.5 ? tex : vec4(uPale, 1.0);\n  float a = c.a * vStyle.y;\n  if (a < 0.003) discard;\n  outColor = vec4(c.rgb * a, a);\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 setRef<T>(ref: React.Ref<T> | undefined, value: T) {\n  if (typeof ref === \"function\") ref(value)\n  else if (ref) ref.current = value\n}\n\nconst WORD =\n  \"absolute top-0 left-0 whitespace-nowrap text-foreground/40 opacity-0 transition-[opacity,color] duration-450 ease-[ease] data-[state=dim]:text-foreground/30 data-[state=dim]:opacity-100 data-[state=dim]:duration-250 data-[state=on]:text-foreground data-[state=on]:opacity-100 motion-reduce:transition-none\"\n\n/**\n * Picture cards fly in as one period of a sine between two words, hold, then burst into a field spread over the\n * whole box: three depth layers that drift slowly and lean away from the pointer, the nearer ones more. One WebGL 2\n * draw call from one atlas; it stops drawing once nothing moves, and never draws off screen. Fills its parent.\n */\nexport function PictureWave({\n  images = PICTURES,\n  words = WORDS,\n  state = \"field\",\n  orientation = \"auto\",\n  lean = 1,\n  float = true,\n  onPick,\n  controlsRef,\n  dpr,\n  className,\n  ref,\n  ...props\n}: PictureWaveProps) {\n  const rootRef = React.useRef<HTMLDivElement>(null)\n  const wordsRef = React.useRef<HTMLParagraphElement>(null)\n  const wordARef = React.useRef<HTMLSpanElement>(null)\n  const wordBRef = React.useRef<HTMLSpanElement>(null)\n  const settings: Settings = { images, state, orientation, lean, float, onPick, dpr }\n  const settingsRef = React.useRef(settings)\n  const wakeRef = React.useRef<(() => void) | null>(null)\n  const replayRef = React.useRef<(() => void) | null>(null)\n\n  React.useImperativeHandle(controlsRef, () => ({ replay: () => replayRef.current?.() }), [])\n\n  React.useEffect(() => {\n    const root = rootRef.current\n    if (!root) return\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: true, depth: false, stencil: false })\n    if (!gl) return\n    root.appendChild(canvas)\n\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\n    gl.attachShader(program, vertex)\n    gl.attachShader(program, fragment)\n    gl.linkProgram(program)\n    gl.deleteShader(vertex)\n    gl.deleteShader(fragment)\n    if (!gl.getProgramParameter(program, gl.LINK_STATUS)) return\n    const uView = gl.getUniformLocation(program, \"uView\")\n    const uPale = gl.getUniformLocation(program, \"uPale\")\n    const uMap = gl.getUniformLocation(program, \"uMap\")\n\n    // one instance buffer: box (centre x, y and size in pixels), atlas rectangle, style (kind, alpha)\n    const STRIDE = 10\n    const vao = gl.createVertexArray()\n    const buffer = gl.createBuffer()\n    gl.bindVertexArray(vao)\n    gl.bindBuffer(gl.ARRAY_BUFFER, buffer)\n    const attrib = (name: string, size: number, offset: number) => {\n      const loc = gl.getAttribLocation(program, name)\n      if (loc < 0) return\n      gl.enableVertexAttribArray(loc)\n      gl.vertexAttribPointer(loc, size, gl.FLOAT, false, STRIDE * 4, offset * 4)\n      gl.vertexAttribDivisor(loc, 1)\n    }\n    attrib(\"aBox\", 4, 0)\n    attrib(\"aUv\", 4, 4)\n    attrib(\"aStyle\", 2, 8)\n    gl.bindVertexArray(null)\n\n    // The atlas: one square cell per picture, the card's box centred in it at the card's proportions. Each picture\n    // is cropped to fill that box, and the rest of its cell holds the same picture stretched, so the small mipmap\n    // levels don't blend a neighbour into the card's edges. A quiet ground shows until a picture arrives; each one\n    // goes up into its own cell, and the mipmaps are rebuilt at most once a frame.\n    const texture = gl.createTexture()\n    const anisotropy = gl.getExtension(\"EXT_texture_filter_anisotropic\")\n    let grid = 1\n    let boxes: [number, number, number, number][] = []\n    let mipsDirty = true\n    let loads: HTMLImageElement[] = []\n    const buildAtlas = (pictures: PictureWaveImage[]) => {\n      for (const img of loads) img.onload = img.onerror = null\n      loads = []\n      grid = Math.max(1, Math.ceil(Math.sqrt(pictures.length)))\n      const size = grid * CELL\n      gl.bindTexture(gl.TEXTURE_2D, texture)\n      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null)\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      if (anisotropy) gl.texParameterf(gl.TEXTURE_2D, anisotropy.TEXTURE_MAX_ANISOTROPY_EXT, 4)\n      const fbo = gl.createFramebuffer()\n      gl.bindFramebuffer(gl.FRAMEBUFFER, fbo)\n      gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0)\n      gl.clearColor(GROUND[0] / 255, GROUND[1] / 255, GROUND[2] / 255, 1)\n      gl.clear(gl.COLOR_BUFFER_BIT)\n      gl.bindFramebuffer(gl.FRAMEBUFFER, null)\n      gl.deleteFramebuffer(fbo)\n      mipsDirty = true\n      boxes = pictures.map((p, i) => {\n        const a = pictureAspect(p.aspect)\n        const w = a >= 1 ? CELL - 2 : Math.round((CELL - 2) * a)\n        const h = a >= 1 ? Math.round((CELL - 2) / a) : CELL - 2\n        const col = i % grid\n        const row = Math.floor(i / grid)\n        const x = (CELL - w) / 2\n        const y = (CELL - h) / 2\n        const img = new Image()\n        img.crossOrigin = \"anonymous\"\n        img.decoding = \"async\"\n        img.onload = () => {\n          const iw = img.naturalWidth\n          const ih = img.naturalHeight\n          if (!iw || !ih) return\n          const cell = document.createElement(\"canvas\")\n          cell.width = cell.height = CELL\n          const g = cell.getContext(\"2d\")\n          if (!g) return\n          g.fillStyle = `rgb(${GROUND.join(\",\")})`\n          g.fillRect(0, 0, CELL, CELL)\n          g.drawImage(img, 0, 0, CELL, CELL)\n          const s = Math.max(w / iw, h / ih)\n          g.drawImage(img, (iw - w / s) / 2, (ih - h / s) / 2, w / s, h / s, x, y, w, h)\n          gl.bindTexture(gl.TEXTURE_2D, texture)\n          gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false)\n          gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false)\n          try {\n            gl.texSubImage2D(gl.TEXTURE_2D, 0, col * CELL, row * CELL, gl.RGBA, gl.UNSIGNED_BYTE, cell)\n          } catch {\n            // a picture served without CORS can't go up: its card keeps the ground\n            return\n          }\n          mipsDirty = true\n          wake()\n        }\n        img.src = p.src\n        loads.push(img)\n        // UVs: v counts from the top (no flip)\n        return [(col * CELL + x) / size, (row * CELL + y) / size, w / size, h / size]\n      })\n    }\n\n    // the pale cards take a whisper of the ink over the page colour, read through a probe so they follow the theme\n    const probe = document.createElement(\"span\")\n    probe.style.cssText = \"position:absolute;width:0;height:0;overflow:hidden;visibility:hidden\"\n    root.appendChild(probe)\n    const swatch = document.createElement(\"canvas\").getContext(\"2d\", { willReadFrequently: true })\n    let pale: [number, number, number] = [246 / 255, 246 / 255, 245 / 255]\n    const readTheme = () => {\n      probe.style.color = \"color-mix(in srgb, var(--foreground, #000) 4%, var(--background, #fff))\"\n      const value = getComputedStyle(probe).color\n      if (!swatch || !value) return\n      swatch.clearRect(0, 0, 1, 1)\n      swatch.fillStyle = value\n      swatch.fillRect(0, 0, 1, 1)\n      const [r, g, b] = swatch.getImageData(0, 0, 1, 1).data\n      pale = [r! / 255, g! / 255, b! / 255]\n    }\n\n    const reduced = window.matchMedia?.(\"(prefers-reduced-motion: reduce)\").matches ?? false\n    const scenes: Partial<Record<World, Scene>> = {}\n    let shownImages: PictureWaveImage[] | null = null\n    let imagesKey = \"\\u0000\"\n    let data = new Float32Array(0)\n    let hits = new Float32Array(0)\n    let hitCount = 0\n    let width = 1\n    let height = 1\n    let rtl = false\n    let shownWorld: World | null = null\n    let wordWidths: [number, number] | null = null\n    let shownWords = \"\"\n    let raf = 0\n    let last = 0\n    let visible = true\n    // the sequence's clock (s), how far the field has settled (0 to 1), the field's own clock for its drift\n    let t = 0\n    let settle = 0\n    let clock = 0\n    const mouse: [number, number] = [0, 0]\n    const leaned: [number, number] = [0, 0]\n    const out: [number, number, number, number] = [0, 0, 0, 0]\n\n    const sceneFor = (world: World, pictures: PictureWaveImage[]) => {\n      const scene = scenes[world] ?? buildScene(world, pictures.map((p) => p.aspect))\n      scenes[world] = scene\n      if (data.length < scene.cards.length * STRIDE) {\n        data = new Float32Array(scene.cards.length * STRIDE)\n        hits = new Float32Array(scene.cards.length * 5)\n        // the GPU buffer is sized once per layout; each frame writes only what it draws\n        gl.bindBuffer(gl.ARRAY_BUFFER, buffer)\n        gl.bufferData(gl.ARRAY_BUFFER, data.byteLength, gl.DYNAMIC_DRAW)\n      }\n      return scene\n    }\n\n    // the words ride just outside the wave's two ends, a little air from the cards; across, when one is too long\n    // for its side, both are set a little smaller from their inner edges, never closer to the cards\n    const placeWords = (world: World) => {\n      const first = wordARef.current\n      const second = wordBRef.current\n      if (!first) return\n      const key = `${first.textContent}\\u0001${second?.textContent ?? \"\"}`\n      if (!wordWidths || key !== shownWords) {\n        shownWords = key\n        wordWidths = [first.offsetWidth, second?.offsetWidth ?? 0]\n      }\n      const R = RIBBON[world]\n      const s = waveScale(t)\n      const k = R.axis\n      const start = R.centre[k] - R.span * s - R.gap[0]\n      const end = R.centre[k] + R.span * s + R.gap[1]\n      const cross = R.centre[1 - k]!\n      const gap = 0.045 * height\n      const state = wordsAt(t)\n      for (const el of [first, second]) if (el && el.dataset.state !== state) el.dataset.state = state\n      if (k === 0) {\n        // the first word opens the line: on the left, or on the right when the text runs right to left\n        const [left, right, lw, rw] = rtl ? [second, first, wordWidths[1], wordWidths[0]] : [first, second, wordWidths[0], wordWidths[1]]\n        const edge = 6.5 * 0.00625 * width\n        const l = width / 2 + start * height - gap\n        const r = width / 2 + end * height + gap\n        const y = height / 2 + cross * height\n        const fit = (room: number, w: number) => (w ? Math.min(1, Math.max(0.55, room / w)) : 1)\n        const sc = Math.min(fit(l - edge, lw), fit(width - edge - r, rw))\n        if (left) {\n          left.style.transformOrigin = \"100% 50%\"\n          left.style.transform = `translate(${l}px, ${y}px) translate(-100%, -50%) scale(${sc})`\n        }\n        if (right) {\n          right.style.transformOrigin = \"0 50%\"\n          right.style.transform = `translate(${r}px, ${y}px) translate(0, -50%) scale(${sc})`\n        }\n      } else {\n        const x = width / 2 + cross * height\n        first.style.transformOrigin = \"\"\n        first.style.transform = `translate(${x}px, ${height / 2 + start * height - gap}px) translate(-50%, -100%)`\n        if (second) {\n          second.style.transformOrigin = \"\"\n          second.style.transform = `translate(${x}px, ${height / 2 + end * height + gap}px) translate(-50%, 0)`\n        }\n      }\n    }\n\n    const draw = () => {\n      const s = settingsRef.current\n      const pictures = s.images.slice(0, 100)\n      if (s.images !== shownImages) {\n        // a new list with the same pictures (written inline by the consumer) keeps the atlas and the layout\n        shownImages = s.images\n        const key = pictures.map((p) => `${p.src}\\u0002${p.aspect}`).join(\"\\u0001\")\n        if (key !== imagesKey) {\n          imagesKey = key\n          delete scenes.horizontal\n          delete scenes.vertical\n          buildAtlas(pictures)\n        }\n      }\n      const world: World = s.orientation === \"auto\" ? (width < 900 ? \"vertical\" : \"horizontal\") : s.orientation\n      const line = wordsRef.current\n      if (world !== shownWorld || (line && line.dataset.world !== world)) {\n        shownWorld = world\n        if (line) line.dataset.world = world\n        wordWidths = null\n      }\n      const scene = sceneFor(world, pictures)\n      if (mipsDirty) {\n        gl.bindTexture(gl.TEXTURE_2D, texture)\n        gl.generateMipmap(gl.TEXTURE_2D)\n        mipsDirty = false\n      }\n      if (t < TIME.field) placeWords(world)\n      else if (wordARef.current?.dataset.state !== \"off\") placeWords(world)\n\n      const P = BURST[world]\n      const ghost = clamp01((t - P.ghost[0]) / (P.ghost[1] - P.ghost[0]))\n      const scale = waveScale(t)\n      const inField = t >= TIME.field\n      const drift = s.float && !reduced ? settle : 0\n      const lx = leaned[0] * s.lean * settle\n      const ly = leaned[1] * s.lean * settle\n      const ox = width / 2\n      const oy = height / 2\n      let n = 0\n      hitCount = 0\n      for (const i of scene.order) {\n        const c = scene.cards[i]!\n        let alpha = 1\n        if (!inField) {\n          const k = scene.slot[i]!\n          if (k < 0) {\n            // the field's other cards fade in as the burst lands\n            alpha = ghost\n            if (alpha <= 0.002) continue\n            fieldAt(world, c, clock, 0, 0, 0, out)\n          } else if (!burstAt(world, t, scene.deck > 1 ? k / (scene.deck - 1) : 0.5, scale, c, out)) continue\n        } else fieldAt(world, c, clock, drift, lx, ly, out)\n        const picture = c.cls === 0 && c.img >= 0 && c.img < boxes.length\n        const box = picture ? boxes[c.img]! : null\n        const o = n * STRIDE\n        const w = out[2] * height\n        const h = out[3] * height\n        const x = ox + out[0] * height\n        const y = oy + out[1] * height\n        data[o] = x\n        data[o + 1] = y\n        data[o + 2] = w\n        data[o + 3] = h\n        data[o + 4] = box ? box[0] : 0\n        data[o + 5] = box ? box[1] : 0\n        data[o + 6] = box ? box[2] : 0\n        data[o + 7] = box ? box[3] : 0\n        data[o + 8] = box ? 0 : 1\n        data[o + 9] = alpha\n        n++\n        if (inField && picture) {\n          const q = hitCount * 5\n          hits[q] = c.img\n          hits[q + 1] = x - w / 2\n          hits[q + 2] = y - h / 2\n          hits[q + 3] = x + w / 2\n          hits[q + 4] = y + h / 2\n          hitCount++\n        }\n      }\n\n      gl.viewport(0, 0, canvas.width, canvas.height)\n      gl.clearColor(0, 0, 0, 0)\n      gl.clear(gl.COLOR_BUFFER_BIT)\n      if (!n) return\n      gl.useProgram(program)\n      gl.bindVertexArray(vao)\n      gl.bindBuffer(gl.ARRAY_BUFFER, buffer)\n      gl.bufferSubData(gl.ARRAY_BUFFER, 0, data, 0, n * STRIDE)\n      gl.activeTexture(gl.TEXTURE0)\n      gl.bindTexture(gl.TEXTURE_2D, texture)\n      gl.uniform1i(uMap, 0)\n      gl.uniform2f(uView, width, height)\n      gl.uniform3f(uPale, pale[0], pale[1], pale[2])\n      gl.enable(gl.BLEND)\n      gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)\n      gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, n)\n      gl.bindVertexArray(null)\n    }\n\n    // the loop runs while the sequence plays, the field settles or drifts, or the cards still follow the pointer\n    const frame = (now: number) => {\n      raf = 0\n      if (!visible || document.hidden) {\n        last = 0\n        return\n      }\n      const dt = last ? Math.min(0.05, Math.max(1 / 240, (now - last) / 1000)) : 1 / 60\n      const s = settingsRef.current\n      const target = s.state === \"wave\" ? TIME.wave : TIME.field\n      let moving = false\n      if (reduced) {\n        t = target\n        settle = 0\n      } else if (t < target) {\n        t = Math.min(target, t + dt)\n        moving = true\n      } else if (t > target) {\n        // leaving the field: its drift and lean ease out first, then the cards gather back into the wave\n        if (settle > 0) settle = Math.max(0, settle - dt / SETTLE_OUT)\n        else t = Math.max(target, t - dt)\n        moving = true\n      } else if (t >= TIME.field && settle < 1) {\n        settle = Math.min(1, settle + dt / SETTLE_IN)\n        moving = true\n      }\n      const k = reduced ? 0 : 1 - Math.exp(-dt / LEAN_EASE)\n      leaned[0] += (mouse[0] - leaned[0]) * k\n      leaned[1] += (mouse[1] - leaned[1]) * k\n      // within a few hundredths of a pixel of the pointer, the lean lands and the loop may stop\n      if (Math.abs(mouse[0] - leaned[0]) + Math.abs(mouse[1] - leaned[1]) < 2e-3) {\n        leaned[0] = mouse[0]\n        leaned[1] = mouse[1]\n      } else if (settle > 0 && s.lean !== 0) moving = true\n      if (settle > 0 && s.float && !reduced) {\n        clock += dt\n        moving = true\n      }\n      draw()\n      last = moving ? now : 0\n      if (moving) wake()\n    }\n    const wake = () => {\n      if (!raf && visible && !document.hidden) raf = requestAnimationFrame(frame)\n    }\n\n    const resize = () => {\n      const s = settingsRef.current\n      width = Math.max(1, root.clientWidth)\n      height = Math.max(1, root.clientHeight)\n      rtl = getComputedStyle(root).direction === \"rtl\"\n      wordWidths = null\n      const ratio = Math.min(s.dpr || window.devicePixelRatio || 1, 2, Math.sqrt(PIXEL_BUDGET / (width * height)))\n      canvas.width = Math.max(1, Math.round(width * ratio))\n      canvas.height = Math.max(1, Math.round(height * ratio))\n      wake()\n    }\n    const pick = (clientX: number, clientY: number) => {\n      const r = root.getBoundingClientRect()\n      const x = clientX - r.left\n      const y = clientY - r.top\n      for (let k = hitCount - 1; k >= 0; k--) {\n        const q = k * 5\n        if (x >= hits[q + 1]! && x <= hits[q + 3]! && y >= hits[q + 2]! && y <= hits[q + 4]!) return hits[q]!\n      }\n      return -1\n    }\n    // the pointer, −1 to 1 across the box (held at its edges outside it): the field's cards lean away from it\n    const onPointer = (e: PointerEvent) => {\n      const r = root.getBoundingClientRect()\n      mouse[0] = Math.min(1, Math.max(-1, ((e.clientX - r.left) / Math.max(1, r.width)) * 2 - 1))\n      mouse[1] = Math.min(1, Math.max(-1, ((e.clientY - r.top) / Math.max(1, r.height)) * 2 - 1))\n      const inside = e.clientX >= r.left && e.clientX <= r.right && e.clientY >= r.top && e.clientY <= r.bottom\n      const cursor = inside && settingsRef.current.onPick && pick(e.clientX, e.clientY) >= 0 ? \"pointer\" : \"\"\n      if (canvas.style.cursor !== cursor) canvas.style.cursor = cursor\n      if (settle > 0 && settingsRef.current.lean !== 0) wake()\n    }\n    const onClick = (e: MouseEvent) => {\n      const i = pick(e.clientX, e.clientY)\n      if (i >= 0) settingsRef.current.onPick?.(i)\n    }\n    const onVisibility = () => wake()\n    const resizeObserver = new ResizeObserver(resize)\n    resizeObserver.observe(root)\n    const intersection = new IntersectionObserver((entries) => {\n      visible = entries.some((entry) => entry.isIntersecting)\n      if (visible) wake()\n    })\n    intersection.observe(root)\n    const themeObserver = new MutationObserver(() => {\n      readTheme()\n      wake()\n    })\n    themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: [\"class\", \"style\", \"data-theme\"] })\n    document.addEventListener(\"visibilitychange\", onVisibility)\n    window.addEventListener(\"pointermove\", onPointer, { passive: true })\n    canvas.addEventListener(\"click\", onClick)\n    document.fonts?.ready.then(() => {\n      wordWidths = null\n      wake()\n    })\n    readTheme()\n    resize()\n    wakeRef.current = () => {\n      wordWidths = null\n      wake()\n    }\n    replayRef.current = () => {\n      t = 0\n      settle = 0\n      wake()\n    }\n\n    return () => {\n      cancelAnimationFrame(raf)\n      raf = -1\n      wakeRef.current = null\n      replayRef.current = null\n      for (const img of loads) img.onload = img.onerror = null\n      resizeObserver.disconnect()\n      intersection.disconnect()\n      themeObserver.disconnect()\n      document.removeEventListener(\"visibilitychange\", onVisibility)\n      window.removeEventListener(\"pointermove\", onPointer)\n      canvas.removeEventListener(\"click\", onClick)\n      gl.deleteBuffer(buffer)\n      gl.deleteVertexArray(vao)\n      gl.deleteTexture(texture)\n      gl.deleteProgram(program)\n      gl.getExtension(\"WEBGL_lose_context\")?.loseContext()\n      canvas.remove()\n      probe.remove()\n    }\n  }, [])\n\n  // props reach the loop through refs written here, never in render; a change only wakes it\n  React.useEffect(() => {\n    settingsRef.current = settings\n    wakeRef.current?.()\n  })\n\n  return (\n    <div\n      ref={(el: HTMLDivElement | null) => {\n        rootRef.current = el\n        setRef(ref, el)\n      }}\n      data-slot=\"picture-wave\"\n      className={cn(\"relative h-full w-full overflow-hidden [container-type:size]\", className)}\n      {...props}\n    >\n      {words.length > 0 && (\n        <p\n          ref={wordsRef}\n          aria-hidden=\"true\"\n          className=\"pointer-events-none absolute inset-0 z-[1] m-0 font-heading text-[length:5cqw] leading-none tracking-[-0.03em] data-[world=vertical]:text-[length:min(10.667cqw,48px)]\"\n        >\n          <span ref={wordARef} className={WORD}>\n            {words[0]}\n          </span>\n          {words[1] && (\n            <span ref={wordBRef} className={WORD}>\n              {words[1]}\n            </span>\n          )}\n        </p>\n      )}\n    </div>\n  )\n}\n",
      "type": "registry:ui"
    }
  ],
  "meta": {
    "added": "2026-10-27"
  },
  "categories": [
    "background",
    "hero"
  ],
  "type": "registry:ui"
}