{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "picture-orbit",
  "title": "Picture Orbit",
  "description": "Picture cards that rise past a still title as you scroll, each along an oval around it, on three depth layers that drift and lean away from the pointer, drawn in one call and idle when still. Raw WebGL 2, no dependencies.",
  "files": [
    {
      "path": "registry/mewo/ui/picture-orbit.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { cn } from \"@/lib/utils\"\n\nexport interface PictureOrbitImage {\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 PictureOrbitProps extends React.ComponentProps<\"div\"> {\n  /** The pictures on the cards; each depth layer cycles through them in its own order (up to 100). */\n  images?: PictureOrbitImage[]\n  /** Held still in the middle while the cards travel around it. */\n  children?: React.ReactNode\n  /** View heights of scroll it stays pinned for, the cards rising all the while at their own pace. */\n  length?: number\n  /** How far the cards lean away from the pointer, the nearer ones more: 0 holds them still. */\n  lean?: number\n  /** The cards' slow idle drift. Off, nothing moves while the reader neither scrolls nor moves the pointer. */\n  float?: boolean\n  /** Called with a picture's index in `images` when its card is clicked. */\n  onPick?: (index: number) => void\n  /** Override the device pixel ratio, which is capped at 2. */\n  dpr?: number\n}\n\ntype Settings = Required<Pick<PictureOrbitProps, \"images\" | \"length\" | \"lean\" | \"float\">> & Pick<PictureOrbitProps, \"onPick\" | \"dpr\">\ntype World = \"wide\" | \"narrow\"\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: PictureOrbitImage[] = CATS.map(([id, aspect]) => ({ src: `https://cataas.com/cat/${id}?type=small`, aspect }))\n\n// where the field is when the stage pins (in its own scroll units: view heights at the layers' speeds)\nconst START = 17.9\nconst LENGTH = 4.6\n// cards further than this from the middle (box heights, past their own half-height) are off the stage\nconst REACH = 0.7\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 field: three depth layers (near pictures, mid\n// pictures, pale far cards) spread evenly (Poisson-disc, no two in a layer overlapping) over `span` × `period`,\n// which wraps vertically, rising at their own parallax `speed` (box heights per view height of scroll). Each card\n// rides an oval around the middle: its half-width is the card's distance out (`arc`, at least the layer's `clear`)\n// × `out`, its half-height r0·(arc/a0)^p, never under r0, so the inner cards bow the most and every card draws in\n// towards the top and bottom. Cards are drawn at `size` of their base size.\ntype Layer = { speed: number; h: [number, number]; gap: number; cls: 0 | 1; depth: number; clear: number }\ntype Field = { span: number; period: number; layers: Layer[]; oval: { r0: number; a0: number; p: number; out: number; size: number } }\nconst FIELD: Record<World, Field> = {\n  wide: {\n    span: 3.2, period: 3.0,\n    oval: { r0: 0.72, a0: 0.5, p: 1.55, out: 1.5, size: 0.8 },\n    layers: [\n      { speed: 0.708, h: [0.19, 0.27], gap: 0.42, cls: 0, depth: 1, clear: 0.3 },\n      { speed: 0.637, h: [0.15, 0.21], gap: 0.36, cls: 0, depth: 0.7, clear: 0.26 },\n      { speed: 0.566, h: [0.13, 0.2], gap: 0.32, cls: 1, depth: 0.45, clear: 0 },\n    ],\n  },\n  narrow: {\n    span: 1.5, period: 2.6,\n    oval: { r0: 0.7, a0: 0.27, p: 2.7, out: 1.5, size: 0.8 },\n    layers: [\n      { speed: 0.986, h: [0.15, 0.21], gap: 0.36, cls: 0, depth: 1, clear: 0 },\n      { speed: 0.867, h: [0.12, 0.18], gap: 0.31, cls: 0, depth: 0.7, clear: 0 },\n      { speed: 0.789, h: [0.11, 0.16], gap: 0.28, cls: 1, depth: 0.45, clear: 0 },\n    ],\n  },\n}\n// how the field is seeded: cards are drawn at `size`, and on a wide box the pictures keep their inner edge `column`\n// from the centre and out of a headline's band above it (half-width x, half-height h plus the card's, rising from y0\n// by `rise` per step of its layer's speed until `until`)\nconst SEED = { size: 0.75, 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 wrap = (y: number, p: number) => (((y % p) + p) % p) - p / 2\nconst pushIn = (v: number) => Math.exp(-0.16 * (1 - clamp01(v)) ** 2)\nconst PUSH = pushIn(0)\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 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 OrbitCard = {\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  /** its oval's half-width before `out` */\n  arc: number\n}\n\nfunction clearOfText(world: World, ly: Layer, x0: number, y0: number, w: number, h: number) {\n  if (world !== \"wide\" || ly.cls !== 0) return true\n  const F = FIELD[world]\n  const H = SEED.hero\n  if (Math.abs(x0) * PUSH - w / 2 < SEED.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 buildOrbit(world: World, pictures: number[]): OrbitCard[] {\n  const F = FIELD[world]\n  const r = rng(world === \"wide\" ? 21 : 23)\n  const cards: OrbitCard[] = []\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 * SEED.size, h * SEED.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      // the pictures' distances out are mapped back onto the range they had before the text clearance, from the\n      // layer's `clear` to the field's edge\n      const R = F.span / 2\n      const w = h * aspect\n      const inner = world === \"wide\" && ly.cls === 0 ? (SEED.column + (w * SEED.size) / 2) / PUSH : ly.clear\n      const arc = ly.clear + ((Math.abs(x0) - inner) * (R - ly.clear)) / Math.max(1e-6, R - inner)\n      cards.push({ cls: ly.cls, aspect, img, layer: li, x0, y0, w, h, phase: r() * Math.PI * 2, arc })\n    }\n  }\n  return cards\n}\n\n/** A card at scroll position v: [x, y, w, h] into out. float (0 to 1) scales its idle drift; lean is the pointer's\n * pull. */\nexport function orbitAt(world: World, c: OrbitCard, v: number, time: number, float: number, leanX: number, leanY: number, out: number[]) {\n  const F = FIELD[world]\n  const ly = F.layers[c.layer]!\n  const A = F.oval\n  const fx = Math.sin(time * 0.4 + c.phase) * 0.004 * float - leanX * 0.022 * ly.depth\n  const fy = Math.cos(time * 0.33 + c.phase * 1.3) * 0.006 * float - leanY * 0.022 * ly.depth\n  const y = wrap(c.y0 - ly.speed * v, F.period)\n  const ry = A.r0 * Math.max(1, (c.arc / A.a0) ** A.p)\n  out[0] = Math.sign(c.x0) * c.arc * A.out * Math.sqrt(Math.max(0, 1 - (y / ry) ** 2)) + fx\n  out[1] = y + fy\n  out[2] = c.w * A.size\n  out[3] = c.h * A.size\n  return out\n}\n\n/** The nearest ancestor that scrolls vertically, or null when the page itself does. */\nfunction scrollParent(node: HTMLElement): HTMLElement | null {\n  for (let el = node.parentElement; el && el !== document.body && el !== document.documentElement; el = el.parentElement) {\n    const { overflowY } = getComputedStyle(el)\n    if (overflowY === \"auto\" || overflowY === \"scroll\") return el\n  }\n  return null\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\nconst TITLE = (\n  <p className=\"grid w-max text-start font-heading text-[length:5.25cqw] leading-[0.98] font-normal tracking-[-0.03em] text-foreground @max-[900px]:text-[length:min(10.27cqw,46.2px)]\">\n    <span className=\"whitespace-nowrap\">\n      <em className=\"text-[0.8em] italic\">the </em>Land\n    </span>\n    {/* the second line steps in by 2.1em, so the two lines always overlap a little */}\n    <span className=\"ps-[2.1em] whitespace-nowrap\">\n      <em className=\"text-[0.8em] italic\">of the </em>Rivers\n    </span>\n  </p>\n)\n\n/**\n * Picture cards that rise past a still middle as the reader scrolls, each along an oval around it, so they bow out\n * around the text there and draw in towards the top and bottom: three depth layers at their own speeds, drifting\n * slowly and leaning away from the pointer. Pins to its nearest scroll container, or to the page. One WebGL 2 draw\n * call from one atlas; it draws only while something moves, and never off screen.\n */\nexport function PictureOrbit({\n  images = PICTURES,\n  children = TITLE,\n  length = LENGTH,\n  lean = 1,\n  float = true,\n  onPick,\n  dpr,\n  className,\n  style,\n  ...props\n}: PictureOrbitProps) {\n  const stageRef = React.useRef<HTMLDivElement>(null)\n  const settings: Settings = { images, length, lean, float, onPick, dpr }\n  const settingsRef = React.useRef(settings)\n  const wakeRef = React.useRef<(() => void) | null>(null)\n\n  React.useEffect(() => {\n    const stage = stageRef.current\n    // The root's ref stays the consumer's, so the root is reached through the stage.\n    const root = stage?.parentElement\n    if (!stage || !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    stage.prepend(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 boxes: [number, number, number, number][] = []\n    let mipsDirty = true\n    let loads: HTMLImageElement[] = []\n    const buildAtlas = (pictures: PictureOrbitImage[]) => {\n      for (const img of loads) img.onload = img.onerror = null\n      loads = []\n      const 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    stage.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 scroller = scrollParent(root)\n    const reduced = window.matchMedia?.(\"(prefers-reduced-motion: reduce)\").matches ?? false\n    const fields: Partial<Record<World, OrbitCard[]>> = {}\n    let shownImages: PictureOrbitImage[] | 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 raf = 0\n    let last = 0\n    let visible = true\n    let drawnAt = Number.NaN\n    // the field's own clock for its drift\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 fieldFor = (world: World, pictures: PictureOrbitImage[]) => {\n      const cards = fields[world] ?? buildOrbit(world, pictures.map((p) => p.aspect))\n      fields[world] = cards\n      if (data.length < cards.length * STRIDE) {\n        data = new Float32Array(cards.length * STRIDE)\n        hits = new Float32Array(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 cards\n    }\n\n    // view heights scrolled since the stage pinned (negative before)\n    const pinned = () => {\n      const viewport = scroller ? scroller.clientHeight : window.innerHeight\n      const top = root.getBoundingClientRect().top - (scroller ? scroller.getBoundingClientRect().top : 0)\n      return -top / Math.max(1, viewport)\n    }\n\n    const draw = (v: number) => {\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 fields.wide\n          delete fields.narrow\n          buildAtlas(pictures)\n        }\n      }\n      const world: World = width < 900 ? \"narrow\" : \"wide\"\n      const cards = fieldFor(world, pictures)\n      if (mipsDirty) {\n        gl.bindTexture(gl.TEXTURE_2D, texture)\n        gl.generateMipmap(gl.TEXTURE_2D)\n        mipsDirty = false\n      }\n      const drift = s.float && !reduced ? 1 : 0\n      const lx = reduced ? 0 : leaned[0] * s.lean\n      const ly = reduced ? 0 : leaned[1] * s.lean\n      const ox = width / 2\n      const oy = height / 2\n      let n = 0\n      hitCount = 0\n      // far layers first\n      for (let layer = 2; layer >= 0; layer--)\n        for (const c of cards) {\n          if (c.layer !== layer) continue\n          orbitAt(world, c, v, clock, drift, lx, ly, out)\n          // only what can show\n          if (Math.abs(out[1]) - out[3] / 2 > REACH) continue\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] = 1\n          n++\n          if (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 reader scrolls, the cards drift, or they 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      let moving = false\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 (s.lean !== 0 && !reduced) moving = true\n      if (s.float && !reduced) {\n        clock += dt\n        moving = true\n      }\n      // the cards rise at the field's own pace, from just before the stage pins to just after it lets go\n      const v = START + Math.min(Math.max(pinned(), -1), Math.max(0, s.length) + 1)\n      if (moving || v !== drawnAt || mipsDirty) {\n        drawnAt = v\n        draw(v)\n      }\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      // Inside a scroll container the stage pins to that container, not the window.\n      if (scroller) root.style.setProperty(\"--mewo-viewport\", `${scroller.clientHeight}px`)\n      width = Math.max(1, stage.clientWidth)\n      height = Math.max(1, stage.clientHeight)\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      drawnAt = Number.NaN\n      wake()\n    }\n    const pick = (clientX: number, clientY: number) => {\n      const r = stage.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 stage (held at its edges outside it): the cards lean away from it\n    const onPointer = (e: PointerEvent) => {\n      if (!visible) return\n      const r = stage.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 (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(stage)\n    if (scroller) resizeObserver.observe(scroller)\n    const intersection = new IntersectionObserver(\n      (entries) => {\n        visible = entries.some((entry) => entry.isIntersecting)\n        if (visible) wake()\n      },\n      // against the window, not the scroll box: the box's own clip still counts, and so does the box leaving the page\n      { root: null }\n    )\n    intersection.observe(stage)\n    const themeObserver = new MutationObserver(() => {\n      readTheme()\n      drawnAt = Number.NaN\n      wake()\n    })\n    themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: [\"class\", \"style\", \"data-theme\"] })\n    const target = scroller ?? window\n    target.addEventListener(\"scroll\", wake, { passive: true })\n    document.addEventListener(\"visibilitychange\", onVisibility)\n    window.addEventListener(\"pointermove\", onPointer, { passive: true })\n    canvas.addEventListener(\"click\", onClick)\n    readTheme()\n    resize()\n    wakeRef.current = () => {\n      drawnAt = Number.NaN\n      wake()\n    }\n\n    return () => {\n      cancelAnimationFrame(raf)\n      raf = -1\n      wakeRef.current = null\n      for (const img of loads) img.onload = img.onerror = null\n      resizeObserver.disconnect()\n      intersection.disconnect()\n      themeObserver.disconnect()\n      target.removeEventListener(\"scroll\", wake)\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      data-slot=\"picture-orbit\"\n      className={cn(\"relative h-[calc(var(--mewo-viewport,100vh)*var(--mewo-length))]\", className)}\n      style={{ \"--mewo-length\": Math.max(0, length) + 1, ...style } as React.CSSProperties}\n      {...props}\n    >\n      <div ref={stageRef} data-slot=\"picture-orbit-stage\" className=\"sticky top-0 h-[var(--mewo-viewport,100vh)] w-full overflow-hidden [container-type:size]\">\n        {children != null && (\n          <div data-slot=\"picture-orbit-content\" className=\"pointer-events-none absolute inset-0 z-[1] grid place-items-center p-6 text-center\">\n            {children}\n          </div>\n        )}\n      </div>\n    </div>\n  )\n}\n",
      "type": "registry:ui"
    }
  ],
  "meta": {
    "added": "2026-10-27"
  },
  "categories": [
    "background",
    "scroll"
  ],
  "type": "registry:ui"
}