{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "relief",
  "type": "registry:ui",
  "title": "Relief",
  "description": "Kinetic Typography Word Wall: matching words rise off the page as color-banded blocks. A take on the word cloud (tag cloud) and animated background (backdrop). Fits hero, integrations, features, 404 page and CTA sections.",
  "author": "KeyframeUI <https://keyframeui.com>",
  "categories": [
    "hero",
    "integrations",
    "features",
    "404-page",
    "cta",
    "word-cloud",
    "animated-background",
    "3d",
    "typography",
    "canvas",
    "interaction"
  ],
  "docs": "Live preview, examples and props: https://keyframeui.com/components/relief",
  "dependencies": [
    "clsx",
    "tailwind-merge"
  ],
  "registryDependencies": [
    "utils"
  ],
  "files": [
    {
      "path": "components/ui/relief.tsx",
      "type": "registry:ui",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\n/**\n * Keep:\n * - Height and color are one value: a word's stack is cut into one band per ink, low to high, and\n *   its face takes the ink of the band it reached. Never color a word apart from its height.\n * - One rAF loop paints one canvas. Flat words are drawn once into a still layer; a frame draws\n *   only the raised words, row by row from the top, one fill per ink per row plus cached text\n *   sprites. The loop sleeps when nothing moves, off screen and in a hidden tab.\n * - A change to `raise` travels out from `origin` as a ripple, and each word eases in and out from\n *   wherever it was, so a change mid-flight never snaps. The wave calms while words are raised.\n * - Restraint keeps it legible: a crest lifts only a seeded 40% of words, `raise` heights under\n *   0.12 stay flat, and words under a `data-relief-quiet` element stay flat and dim so the copy\n *   laid over the wall reads. Raise the few words that matter, not the whole list.\n * - Under reduced motion it draws one still frame: the wave held, raised words already up, no\n *   pointer mound.\n */\nconst TIMING = {\n  /** One crest of the wave passing a word, in seconds at speed 1. */\n  period: 5.6,\n  /** The wave's speed multiplier (the `speed` prop). */\n  speed: 1,\n  /** A word rising to its `raise` height or settling back, in seconds (the `duration` prop). */\n  duration: 0.75,\n  /** How fast a change to `raise` travels out from `origin`, in px/s (the `ripple` prop). */\n  ripple: 1500,\n  /** The wave calming while words are raised, and swelling back, in seconds. */\n  calm: 0.9,\n  /** The wave's center drifting round the wall, in seconds per loop. */\n  drift: 64,\n  /** The pointer's mound catching up with the pointer, in seconds (time constant). */\n  follow: 0.09,\n  /** The mound rising when the pointer arrives and settling when it leaves, in seconds (time constant). */\n  hover: 0.22,\n  /** The canvas fading in on its first frame. */\n  enter: { duration: 600, easing: \"cubic-bezier(0.22, 1, 0.36, 1)\" },\n  /** Where the wave is held under reduced motion, in seconds of wave time. */\n  still: 2.4,\n} as const;\n\n/* ─────────────────────────────────────────────────────────\n * RELIEF STORYBOARD\n *\n *  wall     rows of short uppercase words fill the box edge\n *           to edge, each row starting at a different offset\n *           so words run off both sides. Flat words are plain\n *           dim type; a small asterisk sits in some gaps\n *  rise     a word that rises leaves its place as a block:\n *           its face lifts by up to `depth` px and the stack\n *           under it shows one band per ink, lowest ink at\n *           the base. The face takes the ink of the band it\n *           reached, so height reads as color: navy low,\n *           ice in the middle, orange at the top\n *  wave     with nothing raised, a slow chevron wave rolls\n *           out from a center that drifts round the wall.\n *           A crest lifts only about 4 words in 10, each to\n *           its own height, so it reads as a ripple through\n *           the wall rather than a solid band\n *  raise    `raise` names words (by text or tag) or gives\n *           each a height. Every copy of a named word rises;\n *           the change travels out from `origin` at 1500px/s\n *           and each word eases over 0.75s from wherever it\n *           was. Meanwhile the wave calms flat over 0.9s\n *  pointer  a mouse or pen pushes up a soft mound under it\n *           (`reach` px), which settles when it leaves\n *  quiet    words under any `data-relief-quiet` element\n *           stay flat and dim, so a headline laid over the\n *           wall reads\n *  sleep    off screen, in a hidden tab, or once everything\n *           has settled with the wave off, nothing draws\n *  reduced  one still frame: the wave held mid-swell, raised\n *           words already up, no mound; changes jump\n * ───────────────────────────────────────────────────────── */\n\nconst RELIEF = {\n  /** Default inks, low to high: navy, electric blue, azure, sky, ice, peach, orange, red-orange. */\n  inks: [\"#1a2a7a\", \"#2340e8\", \"#3b78ff\", \"#8db6ff\", \"#eef3ff\", \"#ffcfa8\", \"#ff8a4c\", \"#ff4a1c\"],\n  chip: 1.5, // a word's block height, in ems\n  pad: 0.5, // space each side of a word inside its block, in ems\n  tracking: 0.04, // letter spacing, in ems\n  star: 0.22, // share of gaps that carry an asterisk\n  wave: {\n    length: 520, // px between crests\n    lean: 0.62, // how much the across distance counts against the down distance, for the chevron\n    floor: 0.5, // share of each crest that stays flat\n    reach: [0.3, 0.22], // how far the center drifts, as a share of the wall's width and height\n    share: 0.4, // share of words a crest lifts; the rest stay flat, so the wave reads as a ripple, not a slab\n    low: 0.45, // the lowest a lifted word goes at the crest, as a share of full height\n  },\n  mound: 0.78, // the pointer mound's height, as a share of `depth`\n  calmTo: 0, // the wave's height while words are raised\n  quiet: { pad: 16, fade: 72, dim: 0.06 }, // px round a quiet element, px it fades over, flat-word opacity under it\n  faceIn: 0.07, // the share of `depth` over which a rising face fades in from flat type\n  rest: 0.12, // a `raise` height under this stays flat, so no word rests half-faded\n  maxDpr: 2,\n  budget: 9, // ms a frame's drawing may take before the canvas drops resolution\n  textDark: \"#0a0b10\",\n  textLight: \"#ffffff\",\n} as const;\n\nconst REDUCED = \"(prefers-reduced-motion: reduce)\";\nconst subscribeReduced = (onChange: () => void) => {\n  const query = window.matchMedia(REDUCED);\n  query.addEventListener(\"change\", onChange);\n  return () => query.removeEventListener(\"change\", onChange);\n};\n\n/** Reduced motion from the media query, false on the server and in the hydration render. */\nfunction useReduced() {\n  return React.useSyncExternalStore(\n    subscribeReduced,\n    () => window.matchMedia(REDUCED).matches,\n    () => false,\n  );\n}\n\nconst clamp01 = (t: number) => Math.min(1, Math.max(0, t));\nconst easeInOut = (t: number) => (t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2);\nconst smooth = (t: number) => t * t * (3 - 2 * t);\n\n/** A seeded generator, so the same words always lay out the same wall. */\nfunction seeded(key: string) {\n  let h = 2166136261;\n  for (let i = 0; i < key.length; i++) h = Math.imul(h ^ key.charCodeAt(i), 16777619);\n  return () => {\n    h = (h + 0x6d2b79f5) | 0;\n    let t = Math.imul(h ^ (h >>> 15), 1 | h);\n    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n  };\n}\n\n/** sRGB channels of any CSS color, read back from a 1px canvas so every color syntax works. */\nfunction rgbOf(color: string): [number, number, number, number] {\n  const c = document.createElement(\"canvas\").getContext(\"2d\", { willReadFrequently: true });\n  if (!c) return [0, 0, 0, 0];\n  c.fillStyle = color;\n  c.fillRect(0, 0, 1, 1);\n  const [r, g, b, a] = c.getImageData(0, 0, 1, 1).data;\n  return [r, g, b, a];\n}\n\nfunction luminance(color: string) {\n  const [r, g, b] = rgbOf(color);\n  const lin = (v: number) => {\n    const s = v / 255;\n    return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;\n  };\n  return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);\n}\n\nconst contrast = (a: number, b: number) => (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);\n\n/** The first painted background at or above `el`: the seam drawn round raised words. */\nfunction groundColor(el: HTMLElement | null) {\n  for (let node = el; node; node = node.parentElement) {\n    const bg = getComputedStyle(node).backgroundColor;\n    if (bg && rgbOf(bg)[3] > 0) return bg;\n  }\n  return null;\n}\n\nexport type ReliefWord = string | { text: string; tags?: string[] };\n\n/** A word as `raise` sees it. */\nexport type ReliefEntry = { text: string; tags: string[] };\n\nexport type ReliefRaise =\n  | string\n  | string[]\n  | Record<string, number>\n  | ((word: ReliefEntry) => number)\n  | null;\n\ntype Options = {\n  depth: number;\n  fontSize: number;\n  gap: number;\n  reach: number;\n  tilt: number;\n  speed: number;\n  duration: number;\n  ripple: number;\n  wave: boolean;\n  pointer: boolean;\n  paused: boolean;\n  reduced: boolean;\n  inks: readonly string[];\n  seed: string;\n};\n\n/** Each word's height from `raise`, 0–1, by its index in the word list. */\nfunction targetsFor(entries: ReliefEntry[], raise: ReliefRaise | undefined) {\n  const out = new Float32Array(entries.length);\n  if (raise == null) return { values: out, any: false };\n  let fn: (word: ReliefEntry) => number;\n  if (typeof raise === \"function\") fn = raise;\n  else if (typeof raise === \"string\" || Array.isArray(raise)) {\n    const keys = new Set((typeof raise === \"string\" ? [raise] : raise).map((k) => k.toLowerCase()));\n    fn = (w) => (keys.has(w.text.toLowerCase()) || w.tags.some((t) => keys.has(t.toLowerCase())) ? 1 : 0);\n  } else {\n    const map = new Map(Object.entries(raise).map(([k, v]) => [k.toLowerCase(), v]));\n    fn = (w) => {\n      let v = map.get(w.text.toLowerCase()) ?? 0;\n      for (const t of w.tags) v = Math.max(v, map.get(t.toLowerCase()) ?? 0);\n      return v;\n    };\n  }\n  let any = false;\n  for (let i = 0; i < entries.length; i++) {\n    const v = clamp01(fn(entries[i]) || 0);\n    out[i] = v < RELIEF.rest ? 0 : v;\n    if (out[i] > 0) any = true;\n  }\n  return { values: out, any };\n}\n\nfunction createRelief() {\n  let root: HTMLElement | null = null;\n  let probe: HTMLElement | null = null; // a hidden span carrying `wordClassName`\n  let canvas: HTMLCanvasElement | null = null;\n  let ctx: CanvasRenderingContext2D | null = null;\n  let options: Options = {\n    depth: 24,\n    fontSize: 13,\n    gap: 6,\n    reach: 150,\n    tilt: 0,\n    speed: TIMING.speed,\n    duration: TIMING.duration,\n    ripple: TIMING.ripple,\n    wave: true,\n    pointer: true,\n    paused: false,\n    reduced: false,\n    inks: RELIEF.inks,\n    seed: \"relief\",\n  };\n\n  let entries: ReliefEntry[] = [];\n  let targets = new Float32Array(0);\n  let raised = false;\n  let origin: [number, number] = [0.5, 0.5];\n\n  // Colors and type, read from the root.\n  let flat = \"#71717a\";\n  let ground: string | null = null;\n  let font = \"sans-serif\";\n  let weight = \"600\";\n  let faceDark: boolean[] = [];\n\n  // The wall, rebuilt when the box, the words or the type change.\n  let width = 0;\n  let height = 0;\n  let dpr = 1;\n  let dprCap: number = RELIEF.maxDpr;\n  let chipH = 0;\n  let pitch = 0;\n  let fieldW = 0;\n  let fieldH = 0;\n  let cos = 1;\n  let sin = 0;\n  // One entry per word on the wall (struct of arrays: no objects to chase each frame).\n  let count = 0;\n  let cx = new Float32Array(0); // left edge, field space\n  let cy = new Float32Array(0); // top edge, field space\n  let cw = new Float32Array(0); // block width\n  let sx = new Float32Array(0); // center, box space (for ripples, quiet and the pointer)\n  let sy = new Float32Array(0);\n  let word = new Int32Array(0); // index into entries\n  let quiet = new Float32Array(0); // 0–1, how far under a quiet element\n  let swell = new Float32Array(0); // 0–1, how high the wave lifts this word (0 for most)\n  let from = new Float32Array(0); // raise animation: start value, end value, start time\n  let to = new Float32Array(0);\n  let start = new Float64Array(0);\n  let lift = new Float32Array(0); // this frame's height, 0–1\n  let rowStart = new Int32Array(0);\n  let rows = 0;\n  let stars: number[] = []; // x, y pairs in field space\n  let widths: number[] = []; // per entry, block width\n  let atlas: HTMLCanvasElement | null = null; // every word twice: dark text, then light text\n  let atlasX = new Float32Array(0);\n  let atlasY = new Float32Array(0);\n  let atlasRow = 0; // y offset of the light-text half\n  let still: HTMLCanvasElement | null = null; // the flat wall\n\n  // Time.\n  let raf = 0;\n  let last = 0;\n  let waveTime = 0;\n  let calm = { from: 0, to: 0, start: -Infinity }; // the wave's share: swells in on the first frame\n  let entered = false;\n  let inView = false;\n  let pageVisible = true;\n  let drawCost = 0;\n  let slowFrames = 0;\n\n  // The pointer's mound, in box space.\n  const mound = { x: 0, y: 0, tx: 0, ty: 0, s: 0, ts: 0 };\n\n  let quietEls: Element[] = [];\n  const cleanups: (() => void)[] = [];\n  const now = () => performance.now() / 1000;\n  const awake = () => inView && pageVisible;\n\n  function readStyle() {\n    if (!root || !probe) return;\n    const style = getComputedStyle(probe);\n    flat = style.color;\n    font = style.fontFamily || \"sans-serif\";\n    weight = style.fontWeight || \"600\";\n    ground = groundColor(root);\n    const dark = luminance(RELIEF.textDark);\n    const light = luminance(RELIEF.textLight);\n    faceDark = options.inks.map((ink) => {\n      const l = luminance(ink);\n      return contrast(l, dark) >= contrast(l, light);\n    });\n  }\n\n  function fontString() {\n    return `${weight} ${options.fontSize}px ${font}`;\n  }\n\n  /** Words measured once per type change; the wall is laid from these widths. */\n  function measure() {\n    const c = document.createElement(\"canvas\").getContext(\"2d\");\n    if (!c) return;\n    c.font = fontString();\n    if (\"letterSpacing\" in c) c.letterSpacing = `${options.fontSize * RELIEF.tracking}px`;\n    const pad = options.fontSize * RELIEF.pad;\n    widths = entries.map((e) => Math.ceil(c.measureText(e.text).width + pad * 2));\n  }\n\n  /** Every word drawn once with dark text and once with light, at the canvas's resolution. */\n  function buildAtlas() {\n    if (!entries.length) return;\n    atlas ??= document.createElement(\"canvas\");\n    const h = chipH;\n    const maxW = 2048;\n    let x = 0;\n    let y = 0;\n    atlasX = new Float32Array(entries.length);\n    atlasY = new Float32Array(entries.length);\n    for (let i = 0; i < entries.length; i++) {\n      if (x + widths[i] > maxW) {\n        x = 0;\n        y += h + 2;\n      }\n      atlasX[i] = x;\n      atlasY[i] = y;\n      x += widths[i] + 2;\n    }\n    atlasRow = y + h + 2;\n    atlas.width = Math.ceil(maxW * dpr);\n    atlas.height = Math.ceil(atlasRow * 2 * dpr);\n    const c = atlas.getContext(\"2d\");\n    if (!c) return;\n    c.setTransform(dpr, 0, 0, dpr, 0, 0);\n    c.font = fontString();\n    if (\"letterSpacing\" in c) c.letterSpacing = `${options.fontSize * RELIEF.tracking}px`;\n    c.textBaseline = \"alphabetic\";\n    c.textAlign = \"left\";\n    const cap = c.measureText(\"H\").actualBoundingBoxAscent || options.fontSize * 0.7;\n    const pad = options.fontSize * RELIEF.pad;\n    for (let half = 0; half < 2; half++) {\n      c.fillStyle = half === 0 ? RELIEF.textDark : RELIEF.textLight;\n      for (let i = 0; i < entries.length; i++) {\n        c.fillText(entries[i].text, atlasX[i] + pad, atlasY[i] + half * atlasRow + (h + cap) / 2);\n      }\n    }\n  }\n\n  /** Lays the wall over the (tilted) box and draws the flat layer. */\n  function layout() {\n    if (!root || !canvas) return;\n    const w = root.clientWidth;\n    const h = root.clientHeight;\n    if (!w || !h) return;\n    width = w;\n    height = h;\n    dpr = Math.min(window.devicePixelRatio || 1, dprCap);\n    canvas.width = Math.round(w * dpr);\n    canvas.height = Math.round(h * dpr);\n\n    const theta = (options.tilt * Math.PI) / 180;\n    cos = Math.cos(theta);\n    sin = Math.sin(theta);\n    fieldW = w * Math.abs(cos) + h * Math.abs(sin);\n    fieldH = w * Math.abs(sin) + h * Math.abs(cos);\n\n    chipH = Math.round(options.fontSize * RELIEF.chip);\n    pitch = chipH + options.gap;\n    measure();\n\n    const random = seeded(`${options.seed}:${entries.length}`);\n    const n = entries.length;\n    const lists: number[][] = [];\n    const starList: number[] = [];\n    if (n) {\n      // Rows from just above the top to below the bottom, so raised words never leave a bare edge.\n      const top = -pitch * 0.5;\n      const rowCount = Math.ceil((fieldH + options.depth + pitch) / pitch) + 1;\n      const order = Array.from({ length: n }, (_, i) => i);\n      const star = options.fontSize * 1.4;\n      for (let r = 0; r < rowCount; r++) {\n        // A fresh shuffle per row, so the same word doesn't stack in a column.\n        for (let i = n - 1; i > 0; i--) {\n          const j = Math.floor(random() * (i + 1));\n          [order[i], order[j]] = [order[j], order[i]];\n        }\n        const row: number[] = [];\n        let x = -random() * options.fontSize * 6;\n        let k = 0;\n        while (x < fieldW) {\n          const i = order[k++ % n];\n          row.push(i, x, top + r * pitch);\n          x += widths[i] + options.gap;\n          if (random() < RELIEF.star) {\n            starList.push(x + star / 2 - options.gap / 2, top + r * pitch + chipH / 2);\n            x += star;\n          }\n        }\n        lists.push(row);\n      }\n    }\n    rows = lists.length;\n    count = lists.reduce((sum, row) => sum + row.length / 3, 0);\n    cx = new Float32Array(count);\n    cy = new Float32Array(count);\n    cw = new Float32Array(count);\n    sx = new Float32Array(count);\n    sy = new Float32Array(count);\n    word = new Int32Array(count);\n    quiet = new Float32Array(count);\n    swell = new Float32Array(count);\n    const pickRandom = seeded(`${options.seed}:swell`);\n    for (let c = 0; c < count; c++) {\n      const r = pickRandom();\n      swell[c] = r < RELIEF.wave.share ? RELIEF.wave.low + (1 - RELIEF.wave.low) * (r / RELIEF.wave.share) : 0;\n    }\n    from = new Float32Array(count);\n    to = new Float32Array(count);\n    start = new Float64Array(count);\n    lift = new Float32Array(count);\n    rowStart = new Int32Array(rows + 1);\n    let k = 0;\n    lists.forEach((row, r) => {\n      rowStart[r] = k;\n      for (let j = 0; j < row.length; j += 3) {\n        const i = row[j];\n        word[k] = i;\n        cx[k] = row[j + 1];\n        cy[k] = row[j + 2];\n        cw[k] = widths[i];\n        const [x, y] = toBox(cx[k] + cw[k] / 2, cy[k] + chipH / 2);\n        sx[k] = x;\n        sy[k] = y;\n        k++;\n      }\n    });\n    rowStart[rows] = k;\n    stars = starList;\n    // A relayout puts words straight at the heights they had: no ripple, no snap back to flat.\n    // Before the first frame everything starts flat, so the entrance can ripple in.\n    for (let c = 0; c < count; c++) {\n      const v = entered ? (targets[word[c]] ?? 0) : 0;\n      from[c] = v;\n      to[c] = v;\n      start[c] = -Infinity;\n    }\n    readQuiet();\n    buildAtlas();\n    drawStill();\n    wake();\n  }\n\n  /** Field space (the tilted wall) to box space. */\n  function toBox(u: number, v: number): [number, number] {\n    const du = u - fieldW / 2;\n    const dv = v - fieldH / 2;\n    return [width / 2 + du * cos - dv * sin, height / 2 + du * sin + dv * cos];\n  }\n\n  function toField(x: number, y: number): [number, number] {\n    const dx = x - width / 2;\n    const dy = y - height / 2;\n    return [fieldW / 2 + dx * cos + dy * sin, fieldH / 2 - dx * sin + dy * cos];\n  }\n\n  function setTransform(c: CanvasRenderingContext2D) {\n    // screen = C + R·(u − F): in device px that's dpr·R·u + dpr·(C − R·F).\n    const tx = width / 2 - (fieldW / 2) * cos + (fieldH / 2) * sin;\n    const ty = height / 2 - (fieldW / 2) * sin - (fieldH / 2) * cos;\n    c.setTransform(dpr * cos, dpr * sin, -dpr * sin, dpr * cos, dpr * tx, dpr * ty);\n  }\n\n  /** How far each word sits under a `data-relief-quiet` element. */\n  function readQuiet() {\n    if (!root) return;\n    const box = root.getBoundingClientRect();\n    const rects = quietEls.map((el) => {\n      const r = el.getBoundingClientRect();\n      const p = RELIEF.quiet.pad;\n      return [r.left - box.left - p, r.top - box.top - p, r.right - box.left + p, r.bottom - box.top + p];\n    });\n    for (let c = 0; c < count; c++) {\n      let q = 0;\n      for (const [l, t, r, b] of rects) {\n        const dx = Math.max(l - sx[c], 0, sx[c] - r);\n        const dy = Math.max(t - sy[c], 0, sy[c] - b);\n        const d = Math.hypot(dx, dy * 1.6);\n        q = Math.max(q, 1 - smooth(clamp01(d / RELIEF.quiet.fade)));\n      }\n      quiet[c] = q;\n    }\n  }\n\n  function drawStill() {\n    if (!canvas) return;\n    still ??= document.createElement(\"canvas\");\n    still.width = canvas.width;\n    still.height = canvas.height;\n    const c = still.getContext(\"2d\");\n    if (!c) return;\n    c.clearRect(0, 0, still.width, still.height);\n    setTransform(c);\n    c.font = fontString();\n    if (\"letterSpacing\" in c) c.letterSpacing = `${options.fontSize * RELIEF.tracking}px`;\n    c.textBaseline = \"alphabetic\";\n    c.fillStyle = flat;\n    const cap = c.measureText(\"H\").actualBoundingBoxAscent || options.fontSize * 0.7;\n    const pad = options.fontSize * RELIEF.pad;\n    for (let k = 0; k < count; k++) {\n      c.globalAlpha = 1 - quiet[k] * (1 - RELIEF.quiet.dim);\n      c.fillText(entries[word[k]].text, cx[k] + pad, cy[k] + (chipH + cap) / 2);\n    }\n    // Asterisks in some gaps, drawn as strokes so no font has to carry the glyph.\n    c.globalAlpha = 0.55;\n    c.strokeStyle = flat;\n    c.lineWidth = Math.max(1, options.fontSize / 11);\n    c.lineCap = \"round\";\n    const arm = options.fontSize * 0.26;\n    c.beginPath();\n    for (let i = 0; i < stars.length; i += 2) {\n      for (let a = 0; a < 3; a++) {\n        const ang = (a * Math.PI) / 3 + Math.PI / 2;\n        const dx = Math.cos(ang) * arm;\n        const dy = Math.sin(ang) * arm;\n        c.moveTo(stars[i] - dx, stars[i + 1] - dy);\n        c.lineTo(stars[i] + dx, stars[i + 1] + dy);\n      }\n    }\n    c.stroke();\n    c.globalAlpha = 1;\n  }\n\n  /** Starts every word toward its `raise` height, rippling out from `origin`. */\n  function retarget(instant = false) {\n    const t = now();\n    const ox = origin[0] * width;\n    const oy = origin[1] * height;\n    const jump = instant || options.reduced;\n    for (let c = 0; c < count; c++) {\n      const v = targets[word[c]] ?? 0;\n      if (v === to[c] && !jump) continue;\n      from[c] = jump ? v : raiseAt(c, t);\n      to[c] = v;\n      start[c] = jump ? t - options.duration : t + Math.hypot(sx[c] - ox, sy[c] - oy) / Math.max(1, options.ripple);\n    }\n    const goal = options.wave && !raised ? 1 : RELIEF.calmTo;\n    if (goal !== calm.to || calm.start === -Infinity) {\n      const value = calmAt(t);\n      calm = { from: jump ? goal : value, to: goal, start: t };\n    }\n    wake();\n  }\n\n  function raiseAt(c: number, t: number) {\n    const p = clamp01((t - start[c]) / Math.max(0.01, options.duration));\n    return from[c] + (to[c] - from[c]) * easeInOut(p);\n  }\n\n  function calmAt(t: number) {\n    const p = clamp01((t - calm.start) / TIMING.calm);\n    return calm.from + (calm.to - calm.from) * easeInOut(p);\n  }\n\n  /** The wave at a word, 0–1. */\n  function waveAt(u: number, v: number, time: number) {\n    const W = RELIEF.wave;\n    const loop = (time / TIMING.drift) * Math.PI * 2;\n    const ou = fieldW / 2 + Math.sin(loop) * fieldW * W.reach[0];\n    const ov = fieldH / 2 + Math.sin(loop * 1.7 + 1.3) * fieldH * W.reach[1];\n    const d = Math.abs(u - ou) * W.lean + Math.abs(v - ov);\n    const s = 0.5 + 0.5 * Math.sin((d / W.length - time / TIMING.period) * Math.PI * 2);\n    const e = clamp01((s - W.floor) / (1 - W.floor));\n    return e * e * (3 - 2 * e);\n  }\n\n  function frame(stamp: number) {\n    raf = 0;\n    if (!ctx || !canvas || !still) return;\n    const t = stamp / 1000;\n    const dt = last ? Math.min(0.05, t - last) : 0;\n    last = t;\n    const T0 = performance.now();\n\n    if (!options.paused && !options.reduced) waveTime += dt * options.speed;\n    const wavePart = options.reduced ? (options.wave && !raised ? 1 : 0) : calmAt(t);\n    const waveClock = options.reduced ? TIMING.still : waveTime;\n\n    // The pointer's mound eases toward the pointer and in or out.\n    let moving = false;\n    if (options.pointer && !options.reduced) {\n      const kf = 1 - Math.exp(-dt / TIMING.follow);\n      const kh = 1 - Math.exp(-dt / TIMING.hover);\n      mound.x += (mound.tx - mound.x) * kf;\n      mound.y += (mound.ty - mound.y) * kf;\n      mound.s += (mound.ts - mound.s) * kh;\n      if (Math.abs(mound.ts - mound.s) < 0.002) mound.s = mound.ts;\n      moving = mound.s > 0.002 && (mound.s !== mound.ts || Math.hypot(mound.tx - mound.x, mound.ty - mound.y) > 0.3);\n    } else mound.s = 0;\n    const [mu, mv] = toField(mound.x, mound.y);\n    const reach = Math.max(1, options.reach);\n\n    let animating = moving || (wavePart > 0 && !options.paused && !options.reduced) || (!options.reduced && t - calm.start < TIMING.calm);\n    for (let c = 0; c < count; c++) {\n      let e = 0;\n      const p = (t - start[c]) / Math.max(0.01, options.duration);\n      if (p < 1 && !options.reduced) animating = true;\n      const r = options.reduced ? to[c] : raiseAt(c, t);\n      e = r;\n      const u = cx[c] + cw[c] / 2;\n      const v = cy[c] + chipH / 2;\n      if (wavePart > 0.001 && swell[c] > 0) e = Math.max(e, waveAt(u, v, waveClock) * wavePart * swell[c]);\n      if (mound.s > 0.001) {\n        const du = (u - mu) * 0.8;\n        const dv = v - mv;\n        const d2 = (du * du + dv * dv) / (reach * reach);\n        if (d2 < 1) e = Math.max(e, (1 - d2) * (1 - d2) * RELIEF.mound * mound.s);\n      }\n      lift[c] = e * (1 - quiet[c]);\n    }\n\n    draw();\n    const cost = performance.now() - T0;\n    drawCost = drawCost ? drawCost * 0.9 + cost * 0.1 : cost;\n    // A slow device gets a lighter canvas rather than dropped frames.\n    if (drawCost > RELIEF.budget && dpr > 1) {\n      if (++slowFrames > 45) {\n        slowFrames = 0;\n        drawCost = 0;\n        dprCap = Math.max(1, dpr - 0.5);\n        layout();\n        return;\n      }\n    } else slowFrames = 0;\n\n    if (animating && awake()) raf = requestAnimationFrame(frame);\n    else last = 0;\n  }\n\n  function draw() {\n    if (!ctx || !canvas || !still) return;\n    ctx.setTransform(1, 0, 0, 1, 0, 0);\n    ctx.globalAlpha = 1;\n    ctx.clearRect(0, 0, canvas.width, canvas.height);\n    ctx.drawImage(still, 0, 0);\n    setTransform(ctx);\n\n    const inks = options.inks;\n    const N = inks.length;\n    const depth = options.depth;\n    const band = depth / N;\n    const h = chipH;\n    const snap = options.tilt === 0 ? (y: number) => Math.round(y * dpr) / dpr : (y: number) => y;\n    const fadeBelow = RELIEF.faceIn;\n\n    for (let r = 0; r < rows; r++) {\n      const a = rowStart[r];\n      const b = rowStart[r + 1];\n      let any = false;\n      for (let c = a; c < b; c++) {\n        if (lift[c] > 0.004) {\n          any = true;\n          break;\n        }\n      }\n      if (!any) continue;\n\n      // A seam of the ground round each raised block, so neighbors of one ink stay apart.\n      if (ground) {\n        ctx.fillStyle = ground;\n        ctx.beginPath();\n        for (let c = a; c < b; c++) {\n          if (lift[c] <= 0.004) continue;\n          const L = snap(lift[c] * depth);\n          ctx.rect(cx[c] - 1, cy[c] - L - 1, cw[c] + 2, h + L + 2);\n        }\n        ctx.fill();\n      }\n\n      // One fill per ink: the bands of that ink, plus the faces that reached it.\n      for (let k = 0; k < N; k++) {\n        ctx.fillStyle = inks[k];\n        ctx.beginPath();\n        let filled = false;\n        const z0 = k * band;\n        for (let c = a; c < b; c++) {\n          const e = lift[c];\n          if (e <= 0.004) continue;\n          const L = snap(e * depth);\n          if (L > z0) {\n            const z1 = Math.min(L, (k + 1) * band);\n            ctx.rect(cx[c], cy[c] + h - z1, cw[c], z1 - z0);\n            filled = true;\n          }\n          if (e >= fadeBelow && Math.min(N - 1, Math.floor(L / band)) === k) {\n            ctx.rect(cx[c], cy[c] - L, cw[c], h);\n            filled = true;\n          }\n        }\n        if (filled) ctx.fill();\n      }\n\n      // Faces still fading in from flat type, one at a time (only the few at a crest's foot).\n      for (let c = a; c < b; c++) {\n        const e = lift[c];\n        if (e <= 0.004 || e >= fadeBelow) continue;\n        const L = snap(e * depth);\n        ctx.globalAlpha = e / fadeBelow;\n        ctx.fillStyle = inks[0];\n        ctx.fillRect(cx[c], cy[c] - L, cw[c], h);\n      }\n      ctx.globalAlpha = 1;\n\n      // Text, from the atlas.\n      if (atlas) {\n        for (let c = a; c < b; c++) {\n          const e = lift[c];\n          if (e <= 0.004) continue;\n          const L = snap(e * depth);\n          const k = Math.min(N - 1, Math.floor(L / band));\n          const i = word[c];\n          const ay = atlasY[i] + (faceDark[e < fadeBelow ? 0 : k] ? 0 : atlasRow);\n          ctx.globalAlpha = e < fadeBelow ? e / fadeBelow : 1;\n          ctx.drawImage(atlas, atlasX[i] * dpr, ay * dpr, cw[c] * dpr, h * dpr, cx[c], cy[c] - L, cw[c], h);\n        }\n        ctx.globalAlpha = 1;\n      }\n    }\n\n    if (!entered) {\n      entered = true;\n      if (options.reduced) canvas.style.opacity = \"1\";\n      else {\n        const anim = canvas.animate([{ opacity: 0 }, { opacity: 1 }], {\n          duration: TIMING.enter.duration,\n          easing: TIMING.enter.easing,\n        });\n        anim.onfinish = () => {\n          if (canvas) canvas.style.opacity = \"1\";\n        };\n        canvas.style.opacity = \"1\";\n      }\n      retarget();\n    }\n  }\n\n  function wake() {\n    if (raf || !ctx || !awake()) return;\n    raf = requestAnimationFrame(frame);\n  }\n\n  function setAwake() {\n    if (awake()) wake();\n    else {\n      cancelAnimationFrame(raf);\n      raf = 0;\n      last = 0;\n    }\n  }\n\n  return {\n    connect(el: { root: HTMLElement; canvas: HTMLCanvasElement; probe: HTMLElement }) {\n      root = el.root;\n      canvas = el.canvas;\n      probe = el.probe;\n      ctx = canvas.getContext(\"2d\");\n      pageVisible = document.visibilityState === \"visible\";\n      const findQuiet = () => {\n        quietEls = root ? Array.from(root.querySelectorAll(\"[data-relief-quiet]\")) : [];\n        quietObserver.disconnect();\n        quietEls.forEach((q) => quietObserver.observe(q));\n      };\n      const refresh = () => {\n        readStyle();\n        layout();\n      };\n\n      let pending = 0;\n      const schedule = () => {\n        if (pending) return;\n        pending = requestAnimationFrame(() => {\n          pending = 0;\n          layout();\n        });\n      };\n      const quietObserver = new ResizeObserver(() => {\n        if (!count) return;\n        readQuiet();\n        drawStill();\n        wake(); // one frame at least, so a settled wall follows the copy\n      });\n      findQuiet();\n      readStyle();\n      layout();\n\n      const resize = new ResizeObserver(schedule);\n      resize.observe(root);\n      const io = new IntersectionObserver(([entry]) => {\n        inView = entry.isIntersecting;\n        setAwake();\n      });\n      io.observe(root);\n      const visibility = () => {\n        pageVisible = document.visibilityState === \"visible\";\n        setAwake();\n      };\n      document.addEventListener(\"visibilitychange\", visibility);\n      // Only a change in which elements are quiet redraws; text updates inside them don't.\n      const children = new MutationObserver(() => {\n        const before = quietEls;\n        findQuiet();\n        if (before.length === quietEls.length && before.every((q, i) => q === quietEls[i])) return;\n        readQuiet();\n        drawStill();\n        wake();\n      });\n      children.observe(root, { childList: true, subtree: true });\n\n      // Type and color follow the theme: a scheme change or a class on <html> redraws.\n      const scheme = window.matchMedia(\"(prefers-color-scheme: dark)\");\n      scheme.addEventListener(\"change\", refresh);\n      const themeAttrs = new MutationObserver(refresh);\n      themeAttrs.observe(document.documentElement, { attributes: true, attributeFilter: [\"class\", \"data-theme\", \"style\"] });\n      let fontsGone = false;\n      document.fonts?.ready.then(() => {\n        if (!fontsGone) refresh();\n      });\n      const fontsLoaded = () => refresh();\n      document.fonts?.addEventListener(\"loadingdone\", fontsLoaded);\n\n      const move = (event: PointerEvent) => {\n        if (event.pointerType === \"touch\" || !root) return;\n        const box = root.getBoundingClientRect();\n        mound.tx = event.clientX - box.left;\n        mound.ty = event.clientY - box.top;\n        if (mound.ts === 0) {\n          mound.x = mound.tx;\n          mound.y = mound.ty;\n        }\n        mound.ts = 1;\n        wake();\n      };\n      const leave = () => {\n        mound.ts = 0;\n        wake();\n      };\n      root.addEventListener(\"pointermove\", move, { passive: true });\n      root.addEventListener(\"pointerleave\", leave, { passive: true });\n\n      cleanups.push(\n        () => resize.disconnect(),\n        () => io.disconnect(),\n        () => quietObserver.disconnect(),\n        () => children.disconnect(),\n        () => document.removeEventListener(\"visibilitychange\", visibility),\n        () => scheme.removeEventListener(\"change\", refresh),\n        () => themeAttrs.disconnect(),\n        () => {\n          fontsGone = true;\n          document.fonts?.removeEventListener(\"loadingdone\", fontsLoaded);\n        },\n        () => cancelAnimationFrame(pending),\n        () => el.root.removeEventListener(\"pointermove\", move),\n        () => el.root.removeEventListener(\"pointerleave\", leave),\n      );\n      return () => {\n        cancelAnimationFrame(raf);\n        raf = 0;\n        last = 0;\n        inView = false;\n        entered = false;\n        cleanups.splice(0).forEach((fn) => fn());\n        root = canvas = probe = null;\n        ctx = null;\n      };\n    },\n\n    setOptions(next: Options) {\n      const relayout =\n        next.depth !== options.depth ||\n        next.fontSize !== options.fontSize ||\n        next.gap !== options.gap ||\n        next.tilt !== options.tilt ||\n        next.seed !== options.seed;\n      const recolor = next.inks.join() !== options.inks.join();\n      const calmChange = next.wave !== options.wave || next.reduced !== options.reduced;\n      options = next;\n      if (recolor) readStyle();\n      if (relayout) layout();\n      if (calmChange && entered) retarget();\n      wake();\n    },\n\n    setWords(next: ReliefEntry[]) {\n      entries = next;\n      targets = new Float32Array(next.length);\n      to = new Float32Array(0);\n      layout();\n    },\n\n    setRaise(raise: ReliefRaise | undefined, at: [number, number]) {\n      const result = targetsFor(entries, raise);\n      targets = result.values;\n      raised = result.any;\n      origin = at;\n      if (entered) retarget();\n    },\n  };\n}\n\nexport interface ReliefProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"children\"> {\n  /** The words on the wall: strings, or `{ text, tags }` so `raise` can name a group. They repeat to fill the box. */\n  words: ReliefWord[];\n  /**\n   * What stands raised. A word or tag (or a list of them) raises every match to full height; a\n   * `{ word: height }` map or a function gives each word a height from 0 to 1. `null` lets the wave\n   * run.\n   */\n  raise?: ReliefRaise;\n  /** Where a change to `raise` ripples out from, as `[x, y]` fractions of the box. */\n  origin?: [number, number];\n  /** The ambient wave while nothing is raised. It calms flat while words are raised. */\n  wave?: boolean;\n  /** A mouse or pen pushes up a soft mound of words under it. */\n  pointer?: boolean;\n  /** Inks from low to high. A word's stack shows one band per ink and its face takes the ink it reached. */\n  inks?: string[];\n  /** How far a word at full height rises, in px. */\n  depth?: number;\n  /** Type size of the words, in px. */\n  fontSize?: number;\n  /** Space between words and between rows, in px. */\n  gap?: number;\n  /** Radius of the pointer's mound, in px. */\n  reach?: number;\n  /** Turns the whole wall, in degrees. It still fills the box. */\n  tilt?: number;\n  /** Speed of the wave, as a multiplier. */\n  speed?: number;\n  /** Seconds a word takes to rise to its new height or settle back. */\n  duration?: number;\n  /** How fast a change to `raise` travels across the wall, in px per second. */\n  ripple?: number;\n  /** Holds the wave where it is. Raised words and the pointer still move. */\n  paused?: boolean;\n  /** Changes the shuffle, for two walls of the same words that shouldn't match. */\n  seed?: string;\n  /**\n   * Classes for the flat words: their `text-*` color, font family and weight. Kept off the root so\n   * the content you lay over the wall doesn't inherit it.\n   */\n  wordClassName?: string;\n  /** What the wall shows, for screen readers. The raised words are read after it. */\n  label?: string;\n  /** Content laid over the wall. Mark the part that must read with `data-relief-quiet`. */\n  children?: React.ReactNode;\n  ref?: React.Ref<HTMLDivElement>;\n}\n\nconst DEFAULT_ORIGIN: [number, number] = [0.5, 0.5];\n\nexport function Relief({\n  words,\n  raise,\n  origin = DEFAULT_ORIGIN,\n  wave = true,\n  pointer = true,\n  inks = RELIEF.inks as unknown as string[],\n  depth = 24,\n  fontSize = 13,\n  gap = 6,\n  reach = 150,\n  tilt = 0,\n  speed = TIMING.speed,\n  duration = TIMING.duration,\n  ripple = TIMING.ripple,\n  paused = false,\n  seed = \"relief\",\n  wordClassName,\n  label,\n  className,\n  children,\n  ref,\n  ...props\n}: ReliefProps) {\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const setRoot = React.useCallback(\n    (node: HTMLDivElement | null) => {\n      rootRef.current = node;\n      if (typeof ref === \"function\") ref(node);\n      else if (ref) ref.current = node;\n    },\n    [ref],\n  );\n  const canvasRef = React.useRef<HTMLCanvasElement>(null);\n  const probeRef = React.useRef<HTMLSpanElement>(null);\n  const [relief] = React.useState(createRelief);\n  const reduced = useReduced();\n\n  const entries = React.useMemo<ReliefEntry[]>(() => {\n    const seen = new Set<string>();\n    const out: ReliefEntry[] = [];\n    for (const w of words) {\n      const e = typeof w === \"string\" ? { text: w, tags: [] } : { text: w.text, tags: w.tags ?? [] };\n      const text = e.text.trim().toUpperCase();\n      if (!text || seen.has(text)) continue;\n      seen.add(text);\n      out.push({ text, tags: e.tags });\n    }\n    return out;\n  }, [words]);\n\n  React.useLayoutEffect(() => {\n    const root = rootRef.current;\n    const canvas = canvasRef.current;\n    const probe = probeRef.current;\n    if (!root || !canvas || !probe) return;\n    return relief.connect({ root, canvas, probe });\n  }, [relief]);\n\n  const inkKey = inks.join(\"|\");\n  React.useEffect(() => {\n    relief.setOptions({\n      depth: Math.max(4, depth),\n      fontSize: Math.max(8, fontSize),\n      gap: Math.max(0, gap),\n      reach: Math.max(20, reach),\n      tilt,\n      speed: Math.max(0, speed),\n      duration: Math.max(0.05, duration),\n      ripple: Math.max(50, ripple),\n      wave,\n      pointer,\n      paused,\n      reduced,\n      inks: inkKey.split(\"|\").filter(Boolean),\n      seed,\n    });\n  }, [relief, depth, fontSize, gap, reach, tilt, speed, duration, ripple, wave, pointer, paused, reduced, inkKey, seed]);\n\n  React.useEffect(() => {\n    relief.setWords(entries);\n  }, [relief, entries]);\n\n  // A new function each render would restart every word, so only a change in result counts.\n  const raiseKey = React.useMemo(() => {\n    if (raise == null) return \"\";\n    if (typeof raise === \"function\") return entries.map((e) => clamp01(raise(e) || 0).toFixed(3)).join(\",\");\n    return JSON.stringify(raise);\n  }, [raise, entries]);\n  const raiseRef = React.useRef(raise);\n  React.useEffect(() => {\n    raiseRef.current = raise;\n  });\n  const [ox, oy] = origin;\n  React.useEffect(() => {\n    relief.setRaise(raiseRef.current, [ox, oy]);\n    // Words first: setWords runs before this on a change to both.\n  }, [relief, raiseKey, entries, ox, oy]);\n\n  let raisedText = \"\";\n  if (label && raise != null) {\n    const { values } = targetsFor(entries, raise);\n    raisedText = entries\n      .filter((_, i) => values[i] > 0)\n      .map((e) => e.text.toLowerCase())\n      .join(\", \");\n  }\n\n  return (\n    <div\n      ref={setRoot}\n      className={cn(\n        \"relative isolate overflow-hidden bg-white dark:bg-[#07080c]\",\n        className,\n      )}\n      {...props}\n    >\n      <canvas\n        ref={canvasRef}\n        aria-hidden\n        className=\"pointer-events-none absolute inset-0 -z-10 size-full\"\n        style={{ opacity: 0 }}\n      />\n      {/* The flat words' color and type, read by the canvas. The default applies only when no class is given. */}\n      <span\n        ref={probeRef}\n        aria-hidden\n        className={cn(\"hidden font-semibold\", wordClassName ?? \"text-zinc-300 dark:text-zinc-700\")}\n      />\n      {label ? (\n        <p className=\"sr-only\">\n          {label}\n          {raisedText ? `. Raised: ${raisedText}.` : \"\"}\n        </p>\n      ) : null}\n      {children}\n    </div>\n  );\n}\n"
    }
  ]
}