# Relief: Kinetic Typography Word Wall for React

> A wall of words where height means something. The words you name (by text or tag) rise out of the page as blocks whose stacked bands run from navy to orange, so how high a word stands is also its color. A change ripples out from where it was asked for; with nothing raised a slow wave rolls across the wall, and the pointer pushes up a mound.

Kinetic Typography Word Wall for React: matching words rise off the page as color-banded blocks. Built with Tailwind CSS; install it with the shadcn CLI. It's a KeyframeUI component: the file lands in your project as source, yours to edit.

- Docs and live preview: https://keyframeui.com/components/relief
- Tags: Typography, Canvas, Interaction, 3D
- npm dependencies: clsx, tailwind-merge

## Installation

Register the @keyframeui registry in `components.json` once per project:

```json
{
  "registries": {
    "@keyframeui": "https://keyframeui.com/r/{name}.json"
  }
}
```

Then add the component. It lands in `components/ui/relief.tsx`, and the CLI also adds `lib/utils.ts` (the `cn` helper) and installs the npm dependencies:

```bash
npx shadcn@latest add @keyframeui/relief
```

Or install by URL, without registering the namespace:

```bash
npx shadcn@latest add https://keyframeui.com/r/relief.json
```

## Usage

The main demo shows typical usage.

### Integrations

An integrations wall: pick Data, Payments, Messaging or Dev and the tools of that kind rise out of the wall, rippling from the button you pressed. All lets the wave run.

Install this demo, with the component included:

```bash
npx shadcn@latest add @keyframeui/relief-demo
```

```tsx title="components/relief-demo.tsx"
"use client";

import * as React from "react";

import { Relief, type ReliefWord } from "@/components/ui/relief";

const GROUPS = [
  { id: "all", label: "All" },
  { id: "data", label: "Data" },
  { id: "payments", label: "Payments" },
  { id: "messaging", label: "Messaging" },
  { id: "dev", label: "Dev" },
] as const;

type Group = (typeof GROUPS)[number]["id"];

const TOOLS: Record<Exclude<Group, "all">, string[]> = {
  data: ["Warehouse", "Sheets", "Lake", "Tables", "Snapshots", "CSV", "Parquet", "Metrics", "Events", "Logs"],
  payments: ["Invoices", "Ledger", "Refunds", "Payouts", "Tax", "Cards", "Billing", "Wallets", "Receipts"],
  messaging: ["Email", "SMS", "Chat", "Push", "Inbox", "Voice", "Digest", "Alerts", "Threads"],
  dev: ["Webhooks", "API", "CLI", "SDK", "GraphQL", "Cron", "Queues", "Edge", "Secrets", "Git"],
};

const WORDS: ReliefWord[] = Object.entries(TOOLS).flatMap(([group, names]) =>
  names.map((text) => ({ text, tags: [group] })),
);

export function ReliefDemo() {
  const [group, setGroup] = React.useState<Group>("all");
  const [origin, setOrigin] = React.useState<[number, number]>([0.5, 0.5]);
  const wallRef = React.useRef<HTMLDivElement>(null);
  const count = group === "all" ? WORDS.length : TOOLS[group].length;

  function pick(next: Group, button: HTMLElement) {
    const wall = wallRef.current?.getBoundingClientRect();
    const box = button.getBoundingClientRect();
    if (wall) {
      // The rise ripples out from the button that asked for it.
      setOrigin([
        (box.left + box.width / 2 - wall.left) / wall.width,
        (box.top + box.height / 2 - wall.top) / wall.height,
      ]);
    }
    setGroup(next);
  }

  // Arrow keys move the pick round the group, as in any radio group.
  function onKeyDown(event: React.KeyboardEvent<HTMLDivElement>) {
    const step = event.key === "ArrowRight" || event.key === "ArrowDown" ? 1 : event.key === "ArrowLeft" || event.key === "ArrowUp" ? -1 : 0;
    if (!step) return;
    event.preventDefault();
    const i = GROUPS.findIndex((g) => g.id === group);
    const next = GROUPS[(i + step + GROUPS.length) % GROUPS.length];
    const button = event.currentTarget.querySelector<HTMLElement>(`[data-group="${next.id}"]`);
    if (button) {
      button.focus();
      pick(next.id, button);
    }
  }

  return (
    <Relief
      ref={wallRef}
      words={WORDS}
      raise={group === "all" ? null : group}
      origin={origin}
      label="Integrations wall"
      className="flex h-[30rem] w-full items-end p-4 sm:p-6"
    >
      <div
        data-relief-quiet
        className="w-full max-w-md rounded-2xl border border-zinc-200 bg-white p-5 shadow-[0_12px_40px_-12px_rgb(0_0_0/0.25)] dark:border-white/10 dark:bg-[#0d0f16]"
      >
        <p className="text-base font-semibold tracking-tight text-zinc-950 dark:text-white">
          Plugs into {count} tools
        </p>
        <p className="mt-1 text-sm font-normal text-zinc-600 dark:text-zinc-400">
          Pick a kind and watch what connects rise out of the wall.
        </p>
        <div role="radiogroup" aria-label="Kind of tool" onKeyDown={onKeyDown} className="mt-4 flex flex-wrap gap-1.5">
          {GROUPS.map((g) => {
            const on = g.id === group;
            return (
              <button
                key={g.id}
                type="button"
                role="radio"
                aria-checked={on}
                tabIndex={on ? 0 : -1}
                data-group={g.id}
                onClick={(event) => pick(g.id, event.currentTarget)}
                className={
                  on
                    ? "h-8 rounded-full bg-zinc-950 px-3.5 text-sm font-medium text-white transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#2340e8] dark:bg-white dark:text-zinc-950"
                    : "h-8 rounded-full border border-zinc-200 px-3.5 text-sm font-medium text-zinc-700 transition-colors hover:border-zinc-300 hover:bg-zinc-50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#2340e8] dark:border-white/10 dark:text-zinc-300 dark:hover:border-white/20 dark:hover:bg-white/5"
                }
              >
                {g.label}
              </button>
            );
          })}
        </div>
      </div>
    </Relief>
  );
}
```

## Examples

Finished sections built with Relief. Each one installs whole, with the component included.

### Help Center Search

A help center's topics as the wall. Type and every topic that matches rises, closer matches higher, with the count of articles beside the box.

Install this demo, with the component included:

```bash
npx shadcn@latest add @keyframeui/relief-search-demo
```

```tsx title="components/relief-search-demo.tsx"
"use client";

import * as React from "react";

import { Relief, type ReliefEntry, type ReliefWord } from "@/components/ui/relief";

// A help center's topics, each with the words people use for it.
const TOPICS: ReliefWord[] = [
  { text: "Billing", tags: ["payment", "card", "charge", "price"] },
  { text: "Refunds", tags: ["money back", "charge", "cancel"] },
  { text: "Invoices", tags: ["receipt", "billing", "tax"] },
  { text: "Receipts", tags: ["invoice", "billing"] },
  { text: "Tax", tags: ["vat", "invoice", "billing"] },
  { text: "Plans", tags: ["price", "upgrade", "billing"] },
  { text: "Trials", tags: ["free", "plans"] },
  { text: "Upgrade", tags: ["plans", "seats"] },
  { text: "Cancel", tags: ["refund", "delete", "plans"] },
  { text: "Login", tags: ["sign in", "password", "access"] },
  { text: "Password", tags: ["login", "reset", "sign in"] },
  { text: "Two-factor", tags: ["2fa", "login", "security", "code"] },
  { text: "SSO", tags: ["login", "saml", "security"] },
  { text: "Roles", tags: ["permissions", "team", "access"] },
  { text: "Teams", tags: ["invite", "members", "seats"] },
  { text: "Seats", tags: ["members", "billing", "team"] },
  { text: "Invite", tags: ["team", "members"] },
  { text: "Export", tags: ["download", "csv", "data"] },
  { text: "Import", tags: ["upload", "csv", "data"] },
  { text: "CSV", tags: ["export", "import", "data"] },
  { text: "Backups", tags: ["restore", "data"] },
  { text: "Restore", tags: ["backup", "undo", "data"] },
  { text: "API keys", tags: ["api", "token", "developer"] },
  { text: "Webhooks", tags: ["api", "events", "developer"] },
  { text: "Rate limits", tags: ["api", "429", "developer"] },
  { text: "Domains", tags: ["dns", "custom domain"] },
  { text: "DNS", tags: ["domain", "records"] },
  { text: "SSL", tags: ["https", "certificate", "domain"] },
  { text: "Status", tags: ["uptime", "outage", "down"] },
  { text: "Uptime", tags: ["status", "outage"] },
  { text: "Alerts", tags: ["notifications", "email"] },
  { text: "Email", tags: ["notifications", "alerts"] },
  { text: "Mobile", tags: ["app", "ios", "android"] },
  { text: "Offline", tags: ["sync", "mobile"] },
  { text: "Sync", tags: ["offline", "devices"] },
  { text: "Sharing", tags: ["links", "invite"] },
  { text: "Comments", tags: ["mentions", "notifications"] },
  { text: "Shortcuts", tags: ["keyboard", "hotkeys"] },
  { text: "Privacy", tags: ["gdpr", "data", "security"] },
  { text: "GDPR", tags: ["privacy", "data"] },
  { text: "Audit log", tags: ["security", "history"] },
  { text: "Delete account", tags: ["cancel", "privacy"] },
];

const SUGGESTIONS = ["billing", "login", "export", "api"];

/** How well a topic answers the query, 0–1: its name beats the words people use for it. */
function scorer(query: string) {
  const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
  return (word: ReliefEntry) => {
    if (!terms.length) return 0;
    const name = word.text.toLowerCase();
    let best = 0;
    for (const term of terms) {
      if (name.startsWith(term)) best = Math.max(best, 1);
      else if (name.includes(term)) best = Math.max(best, 0.8);
      else if (word.tags.some((tag) => tag.startsWith(term))) best = Math.max(best, 0.5);
    }
    return best;
  };
}

export function ReliefSearchDemo() {
  const [query, setQuery] = React.useState("");
  const [origin, setOrigin] = React.useState<[number, number]>([0.5, 0.5]);
  const wallRef = React.useRef<HTMLDivElement>(null);
  const boxRef = React.useRef<HTMLDivElement>(null);
  const score = React.useMemo(() => scorer(query), [query]);
  const matches = React.useMemo(
    () =>
      query.trim()
        ? TOPICS.map((t) => (typeof t === "string" ? { text: t, tags: [] } : { text: t.text, tags: t.tags ?? [] }))
            .filter((t) => score(t) > 0)
            .sort((a, b) => score(b) - score(a))
        : [],
    [query, score],
  );

  // Answers ripple out from the search box, wherever the layout put it.
  React.useLayoutEffect(() => {
    const wall = wallRef.current?.getBoundingClientRect();
    const box = boxRef.current?.getBoundingClientRect();
    if (!wall || !box) return;
    setOrigin([(box.left + box.width / 2 - wall.left) / wall.width, (box.top + 24 - wall.top) / wall.height]);
  }, []);

  return (
    <Relief
      ref={wallRef}
      words={TOPICS}
      raise={query.trim() ? score : null}
      origin={origin}
      inks={["#2a1260", "#4c1d95", "#6d28d9", "#a78bfa", "#f5f3ff", "#fbcfe8", "#ff5ca8", "#e0136f"]}
      label="Help center topics"
      className="flex h-[30rem] w-full items-center justify-center p-4"
    >
      <div
        ref={boxRef}
        data-relief-quiet
        className="w-full max-w-md rounded-2xl border border-zinc-200 bg-white p-2 shadow-[0_12px_40px_-12px_rgb(0_0_0/0.25)] dark:border-white/10 dark:bg-[#0d0f16]"
      >
        <label className="flex h-12 items-center gap-3 rounded-xl px-3 focus-within:bg-zinc-50 dark:focus-within:bg-white/5">
          <svg aria-hidden viewBox="0 0 20 20" className="size-5 shrink-0 text-zinc-400" fill="none" stroke="currentColor" strokeWidth="1.8">
            <circle cx="9" cy="9" r="6" />
            <path d="m13.5 13.5 3.5 3.5" strokeLinecap="round" />
          </svg>
          <span className="sr-only">Search the help center</span>
          <input
            value={query}
            onChange={(event) => setQuery(event.target.value)}
            placeholder="Search the help center"
            className="h-full min-w-0 flex-1 bg-transparent text-base font-normal text-zinc-950 placeholder:text-zinc-400 focus:outline-none dark:text-white dark:placeholder:text-zinc-500"
          />
          {query ? (
            <button
              type="button"
              onClick={() => setQuery("")}
              className="rounded-md px-2 py-1 text-xs font-medium text-zinc-500 hover:bg-zinc-100 hover:text-zinc-900 dark:hover:bg-white/10 dark:hover:text-white"
            >
              Clear
            </button>
          ) : null}
        </label>
        <div className="flex min-h-10 items-center gap-2 border-t border-zinc-100 px-3 pt-2 text-sm font-normal dark:border-white/5">
          {query.trim() ? (
            <p aria-live="polite" className="truncate text-zinc-600 dark:text-zinc-400">
              {matches.length ? (
                <>
                  <span className="font-medium text-[#e0136f] dark:text-[#ff5ca8]">
                    {matches.length} {matches.length === 1 ? "topic" : "topics"}
                  </span>{" "}
                  · {matches.slice(0, 3).map((m) => m.text).join(", ")}
                </>
              ) : (
                "No topic yet. Try fewer letters."
              )}
            </p>
          ) : (
            <>
              <span className="text-zinc-500">Try</span>
              {SUGGESTIONS.map((s) => (
                <button
                  key={s}
                  type="button"
                  onClick={() => setQuery(s)}
                  className="rounded-full border border-zinc-200 px-2.5 py-0.5 text-xs font-medium text-zinc-700 hover:border-zinc-300 hover:bg-zinc-50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#6d28d9] dark:border-white/10 dark:text-zinc-300 dark:hover:bg-white/5"
                >
                  {s}
                </button>
              ))}
            </>
          )}
        </div>
      </div>
    </Relief>
  );
}
```

### Live Topics

What customers are writing in about this hour: each topic's height is its share of tickets and moves as new ones arrive, read against a fewer-to-more scale.

Install this demo, with the component included:

```bash
npx shadcn@latest add @keyframeui/relief-volume-demo
```

```tsx title="components/relief-volume-demo.tsx"
"use client";

import * as React from "react";

import { Relief } from "@/components/ui/relief";

const INKS = ["#053b2a", "#00663a", "#00b25d", "#7ee2a8", "#f2fff7", "#fde68a", "#f59e0b", "#ff5a1f"];

// Tickets per hour a topic usually gets.
const BASE: Record<string, number> = {
  Refunds: 140, Login: 120, Shipping: 110, Password: 96, Invoices: 80, Delivery: 74, Returns: 70,
  Billing: 66, Tracking: 60, Discounts: 44, Sizes: 40, Exchange: 36, Damaged: 34, Address: 30,
  Gift: 26, Warranty: 22, Stock: 20, Payment: 52, Cancel: 48, Account: 28, Points: 16, Email: 18,
  Coupons: 24, Duties: 12, Pickup: 14, Reviews: 10,
};
const TOPICS = Object.keys(BASE);
const TICK = 2400;
/** Only the busiest few topics rise, so the wall says what's loud at a glance. */
const TOP = 5;

/** One step of a slow random walk, so topics drift up and down like a real queue. */
function step(prev: Record<string, number>, seed: number) {
  const next: Record<string, number> = {};
  TOPICS.forEach((topic, i) => {
    const wobble = Math.sin(seed * 1.7 + i * 2.3) * 0.22 + Math.sin(seed * 0.6 + i) * 0.12;
    next[topic] = Math.max(4, Math.round(BASE[topic] * (1 + wobble) * 0.6 + prev[topic] * 0.4));
  });
  // Now and then one topic spikes, the way an outage or a sale shows up first in the queue.
  if (seed % 5 === 3) next.Shipping = Math.round(BASE.Shipping * 1.9);
  if (seed % 7 === 5) next.Password = Math.round(BASE.Password * 1.8);
  return next;
}

export function ReliefVolumeDemo() {
  const [counts, setCounts] = React.useState(BASE);
  const rootRef = React.useRef<HTMLDivElement>(null);

  // New tickets arrive while the wall is on screen.
  React.useEffect(() => {
    const root = rootRef.current;
    if (!root) return;
    let timer = 0;
    let seed = 0;
    const io = new IntersectionObserver(([entry]) => {
      window.clearInterval(timer);
      if (entry.isIntersecting) {
        timer = window.setInterval(() => {
          seed += 1;
          setCounts((prev) => step(prev, seed));
        }, TICK);
      }
    });
    io.observe(root);
    return () => {
      io.disconnect();
      window.clearInterval(timer);
    };
  }, []);

  const max = Math.max(...Object.values(counts));
  const heights = React.useMemo(() => {
    const out: Record<string, number> = {};
    // The top few by tickets, each as high as its share of the busiest one; the rest stay flat type.
    const ranked = [...TOPICS].sort((a, b) => counts[b] - counts[a]).slice(0, TOP);
    for (const topic of ranked) out[topic] = Math.max(0.3, counts[topic] / max);
    return out;
  }, [counts, max]);
  const top = [...TOPICS].sort((a, b) => counts[b] - counts[a]).slice(0, TOP);
  const total = TOPICS.reduce((sum, t) => sum + counts[t], 0);

  return (
    <Relief
      ref={rootRef}
      words={TOPICS}
      raise={heights}
      inks={INKS}
      duration={1.1}
      origin={[0.5, 1]}
      label="Support topics by tickets this hour"
      className="flex h-[30rem] w-full items-end justify-end p-4 sm:p-6"
    >
      <div
        data-relief-quiet
        className="w-full max-w-xs rounded-2xl border border-zinc-200 bg-white p-5 shadow-[0_12px_40px_-12px_rgb(0_0_0/0.25)] dark:border-white/10 dark:bg-[#0d0f16]"
      >
        <div className="flex items-baseline justify-between gap-3">
          <p className="text-sm font-semibold tracking-tight text-zinc-950 dark:text-white">This hour</p>
          <p className="text-xs font-normal tabular-nums text-zinc-500">{total.toLocaleString("en-US")} tickets</p>
        </div>
        <ol className="mt-3 space-y-2">
          {top.map((topic, i) => (
            <li key={topic} className="flex items-center gap-3 text-sm font-normal">
              <span className="w-3 text-xs tabular-nums text-zinc-400">{i + 1}</span>
              <span className="flex-1 text-zinc-800 dark:text-zinc-200">{topic}</span>
              <span className="tabular-nums text-zinc-500">{counts[topic]}</span>
            </li>
          ))}
        </ol>
        <div className="mt-4 border-t border-zinc-100 pt-3 dark:border-white/5">
          <div aria-hidden className="flex h-1.5 overflow-hidden rounded-full">
            {INKS.map((ink) => (
              <span key={ink} className="flex-1" style={{ background: ink }} />
            ))}
          </div>
          <div className="mt-1.5 flex justify-between text-[11px] font-normal text-zinc-500">
            <span>Fewer</span>
            <span>Height and color: tickets per topic</span>
            <span>More</span>
          </div>
        </div>
      </div>
    </Relief>
  );
}
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `words` | `ReliefWord[]` |  | The words on the wall: strings, or `{ text, tags }` so `raise` can name a group. Shown uppercase, each once in the list; they repeat to fill the box. |
| `raise` | `string \| string[] \| Record<string, number> \| ((word: ReliefEntry) => number) \| null` |  | What stands raised. A word or tag, or a list of them, raises every match to full height; a `{ word: height }` map or a function gives each word a height from 0 to 1 (a search score, a count, a plan tier); heights under 0.12 stay flat. `null` lets the wave run. |
| `origin` | `[number, number]` | `[0.5, 0.5]` | Where a change to `raise` ripples out from, as fractions of the box. Point it at the control that asked for it. |
| `wave` | `boolean` | `true` | A slow chevron wave rolls across the wall while nothing is raised, and calms flat while words are. |
| `pointer` | `boolean` | `true` | A mouse or pen pushes up a soft mound of words under it. Touch doesn't, so a finger can scroll past. |
| `inks` | `string[]` |  | Inks from low to high, any CSS colors (8 by default, navy to red-orange). A stack shows one band per ink, and each face takes the ink it reached; its text turns dark or white, whichever reads better on it. |
| `depth` | `number` | `24` | How far a word at full height rises, in px. |
| `fontSize` | `number` | `13` | Type size of the words, in px. |
| `gap` | `number` | `6` | Space between words and between rows, in px. |
| `reach` | `number` | `150` | Radius of the pointer's mound, in px. |
| `tilt` | `number` | `0` | Turns the whole wall, in degrees. It still fills the box edge to edge. |
| `speed` | `number` | `1` | Speed of the wave, as a multiplier. |
| `duration` | `number` | `0.75` | Seconds a word takes to rise to a new height or settle back. It eases in and out from wherever it was. |
| `ripple` | `number` | `1500` | How fast a change to `raise` travels out from `origin`, in px per second. |
| `paused` | `boolean` | `false` | Holds the wave where it is. Raised words and the pointer still move. |
| `seed` | `string` | `"relief"` | Changes the shuffle, for two walls of the same words that shouldn't match. |
| `wordClassName` | `string` |  | Classes for the flat words: a `text-*` color, and the font family and weight they're set in. Default `text-zinc-300 dark:text-zinc-700`, semibold. Raised faces pick dark or white text themselves. |
| `label` | `string` |  | What the wall shows, for screen readers; the words standing raised are read after it. Without it the wall is decoration. |
| `children` | `React.ReactNode` |  | Content laid over the wall. Words under any element marked `data-relief-quiet` stay flat and dim, so a headline or a panel reads. |
| `className` | `string` |  | Classes for the root, which sizes the wall. Its background (default `bg-white`, `#07080c` at night) is the ground and the seam drawn round raised words. |

## What to keep

To adapt it, change its props first. When you do edit `components/ui/relief.tsx`, keep these, which make it feel and behave right:

- Height and color are one value: a word's stack is cut into one band per ink, low to high, and its face takes the ink of the band it reached. Never color a word apart from its height.
- One rAF loop paints one canvas. Flat words are drawn once into a still layer; a frame draws only the raised words, row by row from the top, one fill per ink per row plus cached text sprites. The loop sleeps when nothing moves, off screen and in a hidden tab.
- A change to `raise` travels out from `origin` as a ripple, and each word eases in and out from wherever it was, so a change mid-flight never snaps. The wave calms while words are raised.
- Restraint keeps it legible: a crest lifts only a seeded 40% of words, `raise` heights under 0.12 stay flat, and words under a `data-relief-quiet` element stay flat and dim so the copy laid over the wall reads. Raise the few words that matter, not the whole list.
- Under reduced motion it draws one still frame: the wave held, raised words already up, no pointer mound.

Its timing (durations, delays, springs and easings) is all in the `TIMING` block at the top of the file; the timing props default to it.

## Source

```tsx title="components/ui/relief.tsx"
"use client";

import * as React from "react";

import { cn } from "@/lib/utils";

/**
 * Keep:
 * - Height and color are one value: a word's stack is cut into one band per ink, low to high, and
 *   its face takes the ink of the band it reached. Never color a word apart from its height.
 * - One rAF loop paints one canvas. Flat words are drawn once into a still layer; a frame draws
 *   only the raised words, row by row from the top, one fill per ink per row plus cached text
 *   sprites. The loop sleeps when nothing moves, off screen and in a hidden tab.
 * - A change to `raise` travels out from `origin` as a ripple, and each word eases in and out from
 *   wherever it was, so a change mid-flight never snaps. The wave calms while words are raised.
 * - Restraint keeps it legible: a crest lifts only a seeded 40% of words, `raise` heights under
 *   0.12 stay flat, and words under a `data-relief-quiet` element stay flat and dim so the copy
 *   laid over the wall reads. Raise the few words that matter, not the whole list.
 * - Under reduced motion it draws one still frame: the wave held, raised words already up, no
 *   pointer mound.
 */
const TIMING = {
  /** One crest of the wave passing a word, in seconds at speed 1. */
  period: 5.6,
  /** The wave's speed multiplier (the `speed` prop). */
  speed: 1,
  /** A word rising to its `raise` height or settling back, in seconds (the `duration` prop). */
  duration: 0.75,
  /** How fast a change to `raise` travels out from `origin`, in px/s (the `ripple` prop). */
  ripple: 1500,
  /** The wave calming while words are raised, and swelling back, in seconds. */
  calm: 0.9,
  /** The wave's center drifting round the wall, in seconds per loop. */
  drift: 64,
  /** The pointer's mound catching up with the pointer, in seconds (time constant). */
  follow: 0.09,
  /** The mound rising when the pointer arrives and settling when it leaves, in seconds (time constant). */
  hover: 0.22,
  /** The canvas fading in on its first frame. */
  enter: { duration: 600, easing: "cubic-bezier(0.22, 1, 0.36, 1)" },
  /** Where the wave is held under reduced motion, in seconds of wave time. */
  still: 2.4,
} as const;

/* ─────────────────────────────────────────────────────────
 * RELIEF STORYBOARD
 *
 *  wall     rows of short uppercase words fill the box edge
 *           to edge, each row starting at a different offset
 *           so words run off both sides. Flat words are plain
 *           dim type; a small asterisk sits in some gaps
 *  rise     a word that rises leaves its place as a block:
 *           its face lifts by up to `depth` px and the stack
 *           under it shows one band per ink, lowest ink at
 *           the base. The face takes the ink of the band it
 *           reached, so height reads as color: navy low,
 *           ice in the middle, orange at the top
 *  wave     with nothing raised, a slow chevron wave rolls
 *           out from a center that drifts round the wall.
 *           A crest lifts only about 4 words in 10, each to
 *           its own height, so it reads as a ripple through
 *           the wall rather than a solid band
 *  raise    `raise` names words (by text or tag) or gives
 *           each a height. Every copy of a named word rises;
 *           the change travels out from `origin` at 1500px/s
 *           and each word eases over 0.75s from wherever it
 *           was. Meanwhile the wave calms flat over 0.9s
 *  pointer  a mouse or pen pushes up a soft mound under it
 *           (`reach` px), which settles when it leaves
 *  quiet    words under any `data-relief-quiet` element
 *           stay flat and dim, so a headline laid over the
 *           wall reads
 *  sleep    off screen, in a hidden tab, or once everything
 *           has settled with the wave off, nothing draws
 *  reduced  one still frame: the wave held mid-swell, raised
 *           words already up, no mound; changes jump
 * ───────────────────────────────────────────────────────── */

const RELIEF = {
  /** Default inks, low to high: navy, electric blue, azure, sky, ice, peach, orange, red-orange. */
  inks: ["#1a2a7a", "#2340e8", "#3b78ff", "#8db6ff", "#eef3ff", "#ffcfa8", "#ff8a4c", "#ff4a1c"],
  chip: 1.5, // a word's block height, in ems
  pad: 0.5, // space each side of a word inside its block, in ems
  tracking: 0.04, // letter spacing, in ems
  star: 0.22, // share of gaps that carry an asterisk
  wave: {
    length: 520, // px between crests
    lean: 0.62, // how much the across distance counts against the down distance, for the chevron
    floor: 0.5, // share of each crest that stays flat
    reach: [0.3, 0.22], // how far the center drifts, as a share of the wall's width and height
    share: 0.4, // share of words a crest lifts; the rest stay flat, so the wave reads as a ripple, not a slab
    low: 0.45, // the lowest a lifted word goes at the crest, as a share of full height
  },
  mound: 0.78, // the pointer mound's height, as a share of `depth`
  calmTo: 0, // the wave's height while words are raised
  quiet: { pad: 16, fade: 72, dim: 0.06 }, // px round a quiet element, px it fades over, flat-word opacity under it
  faceIn: 0.07, // the share of `depth` over which a rising face fades in from flat type
  rest: 0.12, // a `raise` height under this stays flat, so no word rests half-faded
  maxDpr: 2,
  budget: 9, // ms a frame's drawing may take before the canvas drops resolution
  textDark: "#0a0b10",
  textLight: "#ffffff",
} as const;

const REDUCED = "(prefers-reduced-motion: reduce)";
const subscribeReduced = (onChange: () => void) => {
  const query = window.matchMedia(REDUCED);
  query.addEventListener("change", onChange);
  return () => query.removeEventListener("change", onChange);
};

/** Reduced motion from the media query, false on the server and in the hydration render. */
function useReduced() {
  return React.useSyncExternalStore(
    subscribeReduced,
    () => window.matchMedia(REDUCED).matches,
    () => false,
  );
}

const clamp01 = (t: number) => Math.min(1, Math.max(0, t));
const easeInOut = (t: number) => (t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2);
const smooth = (t: number) => t * t * (3 - 2 * t);

/** A seeded generator, so the same words always lay out the same wall. */
function seeded(key: string) {
  let h = 2166136261;
  for (let i = 0; i < key.length; i++) h = Math.imul(h ^ key.charCodeAt(i), 16777619);
  return () => {
    h = (h + 0x6d2b79f5) | 0;
    let t = Math.imul(h ^ (h >>> 15), 1 | h);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

/** sRGB channels of any CSS color, read back from a 1px canvas so every color syntax works. */
function rgbOf(color: string): [number, number, number, number] {
  const c = document.createElement("canvas").getContext("2d", { willReadFrequently: true });
  if (!c) return [0, 0, 0, 0];
  c.fillStyle = color;
  c.fillRect(0, 0, 1, 1);
  const [r, g, b, a] = c.getImageData(0, 0, 1, 1).data;
  return [r, g, b, a];
}

function luminance(color: string) {
  const [r, g, b] = rgbOf(color);
  const lin = (v: number) => {
    const s = v / 255;
    return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
  };
  return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
}

const contrast = (a: number, b: number) => (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);

/** The first painted background at or above `el`: the seam drawn round raised words. */
function groundColor(el: HTMLElement | null) {
  for (let node = el; node; node = node.parentElement) {
    const bg = getComputedStyle(node).backgroundColor;
    if (bg && rgbOf(bg)[3] > 0) return bg;
  }
  return null;
}

export type ReliefWord = string | { text: string; tags?: string[] };

/** A word as `raise` sees it. */
export type ReliefEntry = { text: string; tags: string[] };

export type ReliefRaise =
  | string
  | string[]
  | Record<string, number>
  | ((word: ReliefEntry) => number)
  | null;

type Options = {
  depth: number;
  fontSize: number;
  gap: number;
  reach: number;
  tilt: number;
  speed: number;
  duration: number;
  ripple: number;
  wave: boolean;
  pointer: boolean;
  paused: boolean;
  reduced: boolean;
  inks: readonly string[];
  seed: string;
};

/** Each word's height from `raise`, 0–1, by its index in the word list. */
function targetsFor(entries: ReliefEntry[], raise: ReliefRaise | undefined) {
  const out = new Float32Array(entries.length);
  if (raise == null) return { values: out, any: false };
  let fn: (word: ReliefEntry) => number;
  if (typeof raise === "function") fn = raise;
  else if (typeof raise === "string" || Array.isArray(raise)) {
    const keys = new Set((typeof raise === "string" ? [raise] : raise).map((k) => k.toLowerCase()));
    fn = (w) => (keys.has(w.text.toLowerCase()) || w.tags.some((t) => keys.has(t.toLowerCase())) ? 1 : 0);
  } else {
    const map = new Map(Object.entries(raise).map(([k, v]) => [k.toLowerCase(), v]));
    fn = (w) => {
      let v = map.get(w.text.toLowerCase()) ?? 0;
      for (const t of w.tags) v = Math.max(v, map.get(t.toLowerCase()) ?? 0);
      return v;
    };
  }
  let any = false;
  for (let i = 0; i < entries.length; i++) {
    const v = clamp01(fn(entries[i]) || 0);
    out[i] = v < RELIEF.rest ? 0 : v;
    if (out[i] > 0) any = true;
  }
  return { values: out, any };
}

function createRelief() {
  let root: HTMLElement | null = null;
  let probe: HTMLElement | null = null; // a hidden span carrying `wordClassName`
  let canvas: HTMLCanvasElement | null = null;
  let ctx: CanvasRenderingContext2D | null = null;
  let options: Options = {
    depth: 24,
    fontSize: 13,
    gap: 6,
    reach: 150,
    tilt: 0,
    speed: TIMING.speed,
    duration: TIMING.duration,
    ripple: TIMING.ripple,
    wave: true,
    pointer: true,
    paused: false,
    reduced: false,
    inks: RELIEF.inks,
    seed: "relief",
  };

  let entries: ReliefEntry[] = [];
  let targets = new Float32Array(0);
  let raised = false;
  let origin: [number, number] = [0.5, 0.5];

  // Colors and type, read from the root.
  let flat = "#71717a";
  let ground: string | null = null;
  let font = "sans-serif";
  let weight = "600";
  let faceDark: boolean[] = [];

  // The wall, rebuilt when the box, the words or the type change.
  let width = 0;
  let height = 0;
  let dpr = 1;
  let dprCap: number = RELIEF.maxDpr;
  let chipH = 0;
  let pitch = 0;
  let fieldW = 0;
  let fieldH = 0;
  let cos = 1;
  let sin = 0;
  // One entry per word on the wall (struct of arrays: no objects to chase each frame).
  let count = 0;
  let cx = new Float32Array(0); // left edge, field space
  let cy = new Float32Array(0); // top edge, field space
  let cw = new Float32Array(0); // block width
  let sx = new Float32Array(0); // center, box space (for ripples, quiet and the pointer)
  let sy = new Float32Array(0);
  let word = new Int32Array(0); // index into entries
  let quiet = new Float32Array(0); // 0–1, how far under a quiet element
  let swell = new Float32Array(0); // 0–1, how high the wave lifts this word (0 for most)
  let from = new Float32Array(0); // raise animation: start value, end value, start time
  let to = new Float32Array(0);
  let start = new Float64Array(0);
  let lift = new Float32Array(0); // this frame's height, 0–1
  let rowStart = new Int32Array(0);
  let rows = 0;
  let stars: number[] = []; // x, y pairs in field space
  let widths: number[] = []; // per entry, block width
  let atlas: HTMLCanvasElement | null = null; // every word twice: dark text, then light text
  let atlasX = new Float32Array(0);
  let atlasY = new Float32Array(0);
  let atlasRow = 0; // y offset of the light-text half
  let still: HTMLCanvasElement | null = null; // the flat wall

  // Time.
  let raf = 0;
  let last = 0;
  let waveTime = 0;
  let calm = { from: 0, to: 0, start: -Infinity }; // the wave's share: swells in on the first frame
  let entered = false;
  let inView = false;
  let pageVisible = true;
  let drawCost = 0;
  let slowFrames = 0;

  // The pointer's mound, in box space.
  const mound = { x: 0, y: 0, tx: 0, ty: 0, s: 0, ts: 0 };

  let quietEls: Element[] = [];
  const cleanups: (() => void)[] = [];
  const now = () => performance.now() / 1000;
  const awake = () => inView && pageVisible;

  function readStyle() {
    if (!root || !probe) return;
    const style = getComputedStyle(probe);
    flat = style.color;
    font = style.fontFamily || "sans-serif";
    weight = style.fontWeight || "600";
    ground = groundColor(root);
    const dark = luminance(RELIEF.textDark);
    const light = luminance(RELIEF.textLight);
    faceDark = options.inks.map((ink) => {
      const l = luminance(ink);
      return contrast(l, dark) >= contrast(l, light);
    });
  }

  function fontString() {
    return `${weight} ${options.fontSize}px ${font}`;
  }

  /** Words measured once per type change; the wall is laid from these widths. */
  function measure() {
    const c = document.createElement("canvas").getContext("2d");
    if (!c) return;
    c.font = fontString();
    if ("letterSpacing" in c) c.letterSpacing = `${options.fontSize * RELIEF.tracking}px`;
    const pad = options.fontSize * RELIEF.pad;
    widths = entries.map((e) => Math.ceil(c.measureText(e.text).width + pad * 2));
  }

  /** Every word drawn once with dark text and once with light, at the canvas's resolution. */
  function buildAtlas() {
    if (!entries.length) return;
    atlas ??= document.createElement("canvas");
    const h = chipH;
    const maxW = 2048;
    let x = 0;
    let y = 0;
    atlasX = new Float32Array(entries.length);
    atlasY = new Float32Array(entries.length);
    for (let i = 0; i < entries.length; i++) {
      if (x + widths[i] > maxW) {
        x = 0;
        y += h + 2;
      }
      atlasX[i] = x;
      atlasY[i] = y;
      x += widths[i] + 2;
    }
    atlasRow = y + h + 2;
    atlas.width = Math.ceil(maxW * dpr);
    atlas.height = Math.ceil(atlasRow * 2 * dpr);
    const c = atlas.getContext("2d");
    if (!c) return;
    c.setTransform(dpr, 0, 0, dpr, 0, 0);
    c.font = fontString();
    if ("letterSpacing" in c) c.letterSpacing = `${options.fontSize * RELIEF.tracking}px`;
    c.textBaseline = "alphabetic";
    c.textAlign = "left";
    const cap = c.measureText("H").actualBoundingBoxAscent || options.fontSize * 0.7;
    const pad = options.fontSize * RELIEF.pad;
    for (let half = 0; half < 2; half++) {
      c.fillStyle = half === 0 ? RELIEF.textDark : RELIEF.textLight;
      for (let i = 0; i < entries.length; i++) {
        c.fillText(entries[i].text, atlasX[i] + pad, atlasY[i] + half * atlasRow + (h + cap) / 2);
      }
    }
  }

  /** Lays the wall over the (tilted) box and draws the flat layer. */
  function layout() {
    if (!root || !canvas) return;
    const w = root.clientWidth;
    const h = root.clientHeight;
    if (!w || !h) return;
    width = w;
    height = h;
    dpr = Math.min(window.devicePixelRatio || 1, dprCap);
    canvas.width = Math.round(w * dpr);
    canvas.height = Math.round(h * dpr);

    const theta = (options.tilt * Math.PI) / 180;
    cos = Math.cos(theta);
    sin = Math.sin(theta);
    fieldW = w * Math.abs(cos) + h * Math.abs(sin);
    fieldH = w * Math.abs(sin) + h * Math.abs(cos);

    chipH = Math.round(options.fontSize * RELIEF.chip);
    pitch = chipH + options.gap;
    measure();

    const random = seeded(`${options.seed}:${entries.length}`);
    const n = entries.length;
    const lists: number[][] = [];
    const starList: number[] = [];
    if (n) {
      // Rows from just above the top to below the bottom, so raised words never leave a bare edge.
      const top = -pitch * 0.5;
      const rowCount = Math.ceil((fieldH + options.depth + pitch) / pitch) + 1;
      const order = Array.from({ length: n }, (_, i) => i);
      const star = options.fontSize * 1.4;
      for (let r = 0; r < rowCount; r++) {
        // A fresh shuffle per row, so the same word doesn't stack in a column.
        for (let i = n - 1; i > 0; i--) {
          const j = Math.floor(random() * (i + 1));
          [order[i], order[j]] = [order[j], order[i]];
        }
        const row: number[] = [];
        let x = -random() * options.fontSize * 6;
        let k = 0;
        while (x < fieldW) {
          const i = order[k++ % n];
          row.push(i, x, top + r * pitch);
          x += widths[i] + options.gap;
          if (random() < RELIEF.star) {
            starList.push(x + star / 2 - options.gap / 2, top + r * pitch + chipH / 2);
            x += star;
          }
        }
        lists.push(row);
      }
    }
    rows = lists.length;
    count = lists.reduce((sum, row) => sum + row.length / 3, 0);
    cx = new Float32Array(count);
    cy = new Float32Array(count);
    cw = new Float32Array(count);
    sx = new Float32Array(count);
    sy = new Float32Array(count);
    word = new Int32Array(count);
    quiet = new Float32Array(count);
    swell = new Float32Array(count);
    const pickRandom = seeded(`${options.seed}:swell`);
    for (let c = 0; c < count; c++) {
      const r = pickRandom();
      swell[c] = r < RELIEF.wave.share ? RELIEF.wave.low + (1 - RELIEF.wave.low) * (r / RELIEF.wave.share) : 0;
    }
    from = new Float32Array(count);
    to = new Float32Array(count);
    start = new Float64Array(count);
    lift = new Float32Array(count);
    rowStart = new Int32Array(rows + 1);
    let k = 0;
    lists.forEach((row, r) => {
      rowStart[r] = k;
      for (let j = 0; j < row.length; j += 3) {
        const i = row[j];
        word[k] = i;
        cx[k] = row[j + 1];
        cy[k] = row[j + 2];
        cw[k] = widths[i];
        const [x, y] = toBox(cx[k] + cw[k] / 2, cy[k] + chipH / 2);
        sx[k] = x;
        sy[k] = y;
        k++;
      }
    });
    rowStart[rows] = k;
    stars = starList;
    // A relayout puts words straight at the heights they had: no ripple, no snap back to flat.
    // Before the first frame everything starts flat, so the entrance can ripple in.
    for (let c = 0; c < count; c++) {
      const v = entered ? (targets[word[c]] ?? 0) : 0;
      from[c] = v;
      to[c] = v;
      start[c] = -Infinity;
    }
    readQuiet();
    buildAtlas();
    drawStill();
    wake();
  }

  /** Field space (the tilted wall) to box space. */
  function toBox(u: number, v: number): [number, number] {
    const du = u - fieldW / 2;
    const dv = v - fieldH / 2;
    return [width / 2 + du * cos - dv * sin, height / 2 + du * sin + dv * cos];
  }

  function toField(x: number, y: number): [number, number] {
    const dx = x - width / 2;
    const dy = y - height / 2;
    return [fieldW / 2 + dx * cos + dy * sin, fieldH / 2 - dx * sin + dy * cos];
  }

  function setTransform(c: CanvasRenderingContext2D) {
    // screen = C + R·(u − F): in device px that's dpr·R·u + dpr·(C − R·F).
    const tx = width / 2 - (fieldW / 2) * cos + (fieldH / 2) * sin;
    const ty = height / 2 - (fieldW / 2) * sin - (fieldH / 2) * cos;
    c.setTransform(dpr * cos, dpr * sin, -dpr * sin, dpr * cos, dpr * tx, dpr * ty);
  }

  /** How far each word sits under a `data-relief-quiet` element. */
  function readQuiet() {
    if (!root) return;
    const box = root.getBoundingClientRect();
    const rects = quietEls.map((el) => {
      const r = el.getBoundingClientRect();
      const p = RELIEF.quiet.pad;
      return [r.left - box.left - p, r.top - box.top - p, r.right - box.left + p, r.bottom - box.top + p];
    });
    for (let c = 0; c < count; c++) {
      let q = 0;
      for (const [l, t, r, b] of rects) {
        const dx = Math.max(l - sx[c], 0, sx[c] - r);
        const dy = Math.max(t - sy[c], 0, sy[c] - b);
        const d = Math.hypot(dx, dy * 1.6);
        q = Math.max(q, 1 - smooth(clamp01(d / RELIEF.quiet.fade)));
      }
      quiet[c] = q;
    }
  }

  function drawStill() {
    if (!canvas) return;
    still ??= document.createElement("canvas");
    still.width = canvas.width;
    still.height = canvas.height;
    const c = still.getContext("2d");
    if (!c) return;
    c.clearRect(0, 0, still.width, still.height);
    setTransform(c);
    c.font = fontString();
    if ("letterSpacing" in c) c.letterSpacing = `${options.fontSize * RELIEF.tracking}px`;
    c.textBaseline = "alphabetic";
    c.fillStyle = flat;
    const cap = c.measureText("H").actualBoundingBoxAscent || options.fontSize * 0.7;
    const pad = options.fontSize * RELIEF.pad;
    for (let k = 0; k < count; k++) {
      c.globalAlpha = 1 - quiet[k] * (1 - RELIEF.quiet.dim);
      c.fillText(entries[word[k]].text, cx[k] + pad, cy[k] + (chipH + cap) / 2);
    }
    // Asterisks in some gaps, drawn as strokes so no font has to carry the glyph.
    c.globalAlpha = 0.55;
    c.strokeStyle = flat;
    c.lineWidth = Math.max(1, options.fontSize / 11);
    c.lineCap = "round";
    const arm = options.fontSize * 0.26;
    c.beginPath();
    for (let i = 0; i < stars.length; i += 2) {
      for (let a = 0; a < 3; a++) {
        const ang = (a * Math.PI) / 3 + Math.PI / 2;
        const dx = Math.cos(ang) * arm;
        const dy = Math.sin(ang) * arm;
        c.moveTo(stars[i] - dx, stars[i + 1] - dy);
        c.lineTo(stars[i] + dx, stars[i + 1] + dy);
      }
    }
    c.stroke();
    c.globalAlpha = 1;
  }

  /** Starts every word toward its `raise` height, rippling out from `origin`. */
  function retarget(instant = false) {
    const t = now();
    const ox = origin[0] * width;
    const oy = origin[1] * height;
    const jump = instant || options.reduced;
    for (let c = 0; c < count; c++) {
      const v = targets[word[c]] ?? 0;
      if (v === to[c] && !jump) continue;
      from[c] = jump ? v : raiseAt(c, t);
      to[c] = v;
      start[c] = jump ? t - options.duration : t + Math.hypot(sx[c] - ox, sy[c] - oy) / Math.max(1, options.ripple);
    }
    const goal = options.wave && !raised ? 1 : RELIEF.calmTo;
    if (goal !== calm.to || calm.start === -Infinity) {
      const value = calmAt(t);
      calm = { from: jump ? goal : value, to: goal, start: t };
    }
    wake();
  }

  function raiseAt(c: number, t: number) {
    const p = clamp01((t - start[c]) / Math.max(0.01, options.duration));
    return from[c] + (to[c] - from[c]) * easeInOut(p);
  }

  function calmAt(t: number) {
    const p = clamp01((t - calm.start) / TIMING.calm);
    return calm.from + (calm.to - calm.from) * easeInOut(p);
  }

  /** The wave at a word, 0–1. */
  function waveAt(u: number, v: number, time: number) {
    const W = RELIEF.wave;
    const loop = (time / TIMING.drift) * Math.PI * 2;
    const ou = fieldW / 2 + Math.sin(loop) * fieldW * W.reach[0];
    const ov = fieldH / 2 + Math.sin(loop * 1.7 + 1.3) * fieldH * W.reach[1];
    const d = Math.abs(u - ou) * W.lean + Math.abs(v - ov);
    const s = 0.5 + 0.5 * Math.sin((d / W.length - time / TIMING.period) * Math.PI * 2);
    const e = clamp01((s - W.floor) / (1 - W.floor));
    return e * e * (3 - 2 * e);
  }

  function frame(stamp: number) {
    raf = 0;
    if (!ctx || !canvas || !still) return;
    const t = stamp / 1000;
    const dt = last ? Math.min(0.05, t - last) : 0;
    last = t;
    const T0 = performance.now();

    if (!options.paused && !options.reduced) waveTime += dt * options.speed;
    const wavePart = options.reduced ? (options.wave && !raised ? 1 : 0) : calmAt(t);
    const waveClock = options.reduced ? TIMING.still : waveTime;

    // The pointer's mound eases toward the pointer and in or out.
    let moving = false;
    if (options.pointer && !options.reduced) {
      const kf = 1 - Math.exp(-dt / TIMING.follow);
      const kh = 1 - Math.exp(-dt / TIMING.hover);
      mound.x += (mound.tx - mound.x) * kf;
      mound.y += (mound.ty - mound.y) * kf;
      mound.s += (mound.ts - mound.s) * kh;
      if (Math.abs(mound.ts - mound.s) < 0.002) mound.s = mound.ts;
      moving = mound.s > 0.002 && (mound.s !== mound.ts || Math.hypot(mound.tx - mound.x, mound.ty - mound.y) > 0.3);
    } else mound.s = 0;
    const [mu, mv] = toField(mound.x, mound.y);
    const reach = Math.max(1, options.reach);

    let animating = moving || (wavePart > 0 && !options.paused && !options.reduced) || (!options.reduced && t - calm.start < TIMING.calm);
    for (let c = 0; c < count; c++) {
      let e = 0;
      const p = (t - start[c]) / Math.max(0.01, options.duration);
      if (p < 1 && !options.reduced) animating = true;
      const r = options.reduced ? to[c] : raiseAt(c, t);
      e = r;
      const u = cx[c] + cw[c] / 2;
      const v = cy[c] + chipH / 2;
      if (wavePart > 0.001 && swell[c] > 0) e = Math.max(e, waveAt(u, v, waveClock) * wavePart * swell[c]);
      if (mound.s > 0.001) {
        const du = (u - mu) * 0.8;
        const dv = v - mv;
        const d2 = (du * du + dv * dv) / (reach * reach);
        if (d2 < 1) e = Math.max(e, (1 - d2) * (1 - d2) * RELIEF.mound * mound.s);
      }
      lift[c] = e * (1 - quiet[c]);
    }

    draw();
    const cost = performance.now() - T0;
    drawCost = drawCost ? drawCost * 0.9 + cost * 0.1 : cost;
    // A slow device gets a lighter canvas rather than dropped frames.
    if (drawCost > RELIEF.budget && dpr > 1) {
      if (++slowFrames > 45) {
        slowFrames = 0;
        drawCost = 0;
        dprCap = Math.max(1, dpr - 0.5);
        layout();
        return;
      }
    } else slowFrames = 0;

    if (animating && awake()) raf = requestAnimationFrame(frame);
    else last = 0;
  }

  function draw() {
    if (!ctx || !canvas || !still) return;
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.globalAlpha = 1;
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(still, 0, 0);
    setTransform(ctx);

    const inks = options.inks;
    const N = inks.length;
    const depth = options.depth;
    const band = depth / N;
    const h = chipH;
    const snap = options.tilt === 0 ? (y: number) => Math.round(y * dpr) / dpr : (y: number) => y;
    const fadeBelow = RELIEF.faceIn;

    for (let r = 0; r < rows; r++) {
      const a = rowStart[r];
      const b = rowStart[r + 1];
      let any = false;
      for (let c = a; c < b; c++) {
        if (lift[c] > 0.004) {
          any = true;
          break;
        }
      }
      if (!any) continue;

      // A seam of the ground round each raised block, so neighbors of one ink stay apart.
      if (ground) {
        ctx.fillStyle = ground;
        ctx.beginPath();
        for (let c = a; c < b; c++) {
          if (lift[c] <= 0.004) continue;
          const L = snap(lift[c] * depth);
          ctx.rect(cx[c] - 1, cy[c] - L - 1, cw[c] + 2, h + L + 2);
        }
        ctx.fill();
      }

      // One fill per ink: the bands of that ink, plus the faces that reached it.
      for (let k = 0; k < N; k++) {
        ctx.fillStyle = inks[k];
        ctx.beginPath();
        let filled = false;
        const z0 = k * band;
        for (let c = a; c < b; c++) {
          const e = lift[c];
          if (e <= 0.004) continue;
          const L = snap(e * depth);
          if (L > z0) {
            const z1 = Math.min(L, (k + 1) * band);
            ctx.rect(cx[c], cy[c] + h - z1, cw[c], z1 - z0);
            filled = true;
          }
          if (e >= fadeBelow && Math.min(N - 1, Math.floor(L / band)) === k) {
            ctx.rect(cx[c], cy[c] - L, cw[c], h);
            filled = true;
          }
        }
        if (filled) ctx.fill();
      }

      // Faces still fading in from flat type, one at a time (only the few at a crest's foot).
      for (let c = a; c < b; c++) {
        const e = lift[c];
        if (e <= 0.004 || e >= fadeBelow) continue;
        const L = snap(e * depth);
        ctx.globalAlpha = e / fadeBelow;
        ctx.fillStyle = inks[0];
        ctx.fillRect(cx[c], cy[c] - L, cw[c], h);
      }
      ctx.globalAlpha = 1;

      // Text, from the atlas.
      if (atlas) {
        for (let c = a; c < b; c++) {
          const e = lift[c];
          if (e <= 0.004) continue;
          const L = snap(e * depth);
          const k = Math.min(N - 1, Math.floor(L / band));
          const i = word[c];
          const ay = atlasY[i] + (faceDark[e < fadeBelow ? 0 : k] ? 0 : atlasRow);
          ctx.globalAlpha = e < fadeBelow ? e / fadeBelow : 1;
          ctx.drawImage(atlas, atlasX[i] * dpr, ay * dpr, cw[c] * dpr, h * dpr, cx[c], cy[c] - L, cw[c], h);
        }
        ctx.globalAlpha = 1;
      }
    }

    if (!entered) {
      entered = true;
      if (options.reduced) canvas.style.opacity = "1";
      else {
        const anim = canvas.animate([{ opacity: 0 }, { opacity: 1 }], {
          duration: TIMING.enter.duration,
          easing: TIMING.enter.easing,
        });
        anim.onfinish = () => {
          if (canvas) canvas.style.opacity = "1";
        };
        canvas.style.opacity = "1";
      }
      retarget();
    }
  }

  function wake() {
    if (raf || !ctx || !awake()) return;
    raf = requestAnimationFrame(frame);
  }

  function setAwake() {
    if (awake()) wake();
    else {
      cancelAnimationFrame(raf);
      raf = 0;
      last = 0;
    }
  }

  return {
    connect(el: { root: HTMLElement; canvas: HTMLCanvasElement; probe: HTMLElement }) {
      root = el.root;
      canvas = el.canvas;
      probe = el.probe;
      ctx = canvas.getContext("2d");
      pageVisible = document.visibilityState === "visible";
      const findQuiet = () => {
        quietEls = root ? Array.from(root.querySelectorAll("[data-relief-quiet]")) : [];
        quietObserver.disconnect();
        quietEls.forEach((q) => quietObserver.observe(q));
      };
      const refresh = () => {
        readStyle();
        layout();
      };

      let pending = 0;
      const schedule = () => {
        if (pending) return;
        pending = requestAnimationFrame(() => {
          pending = 0;
          layout();
        });
      };
      const quietObserver = new ResizeObserver(() => {
        if (!count) return;
        readQuiet();
        drawStill();
        wake(); // one frame at least, so a settled wall follows the copy
      });
      findQuiet();
      readStyle();
      layout();

      const resize = new ResizeObserver(schedule);
      resize.observe(root);
      const io = new IntersectionObserver(([entry]) => {
        inView = entry.isIntersecting;
        setAwake();
      });
      io.observe(root);
      const visibility = () => {
        pageVisible = document.visibilityState === "visible";
        setAwake();
      };
      document.addEventListener("visibilitychange", visibility);
      // Only a change in which elements are quiet redraws; text updates inside them don't.
      const children = new MutationObserver(() => {
        const before = quietEls;
        findQuiet();
        if (before.length === quietEls.length && before.every((q, i) => q === quietEls[i])) return;
        readQuiet();
        drawStill();
        wake();
      });
      children.observe(root, { childList: true, subtree: true });

      // Type and color follow the theme: a scheme change or a class on <html> redraws.
      const scheme = window.matchMedia("(prefers-color-scheme: dark)");
      scheme.addEventListener("change", refresh);
      const themeAttrs = new MutationObserver(refresh);
      themeAttrs.observe(document.documentElement, { attributes: true, attributeFilter: ["class", "data-theme", "style"] });
      let fontsGone = false;
      document.fonts?.ready.then(() => {
        if (!fontsGone) refresh();
      });
      const fontsLoaded = () => refresh();
      document.fonts?.addEventListener("loadingdone", fontsLoaded);

      const move = (event: PointerEvent) => {
        if (event.pointerType === "touch" || !root) return;
        const box = root.getBoundingClientRect();
        mound.tx = event.clientX - box.left;
        mound.ty = event.clientY - box.top;
        if (mound.ts === 0) {
          mound.x = mound.tx;
          mound.y = mound.ty;
        }
        mound.ts = 1;
        wake();
      };
      const leave = () => {
        mound.ts = 0;
        wake();
      };
      root.addEventListener("pointermove", move, { passive: true });
      root.addEventListener("pointerleave", leave, { passive: true });

      cleanups.push(
        () => resize.disconnect(),
        () => io.disconnect(),
        () => quietObserver.disconnect(),
        () => children.disconnect(),
        () => document.removeEventListener("visibilitychange", visibility),
        () => scheme.removeEventListener("change", refresh),
        () => themeAttrs.disconnect(),
        () => {
          fontsGone = true;
          document.fonts?.removeEventListener("loadingdone", fontsLoaded);
        },
        () => cancelAnimationFrame(pending),
        () => el.root.removeEventListener("pointermove", move),
        () => el.root.removeEventListener("pointerleave", leave),
      );
      return () => {
        cancelAnimationFrame(raf);
        raf = 0;
        last = 0;
        inView = false;
        entered = false;
        cleanups.splice(0).forEach((fn) => fn());
        root = canvas = probe = null;
        ctx = null;
      };
    },

    setOptions(next: Options) {
      const relayout =
        next.depth !== options.depth ||
        next.fontSize !== options.fontSize ||
        next.gap !== options.gap ||
        next.tilt !== options.tilt ||
        next.seed !== options.seed;
      const recolor = next.inks.join() !== options.inks.join();
      const calmChange = next.wave !== options.wave || next.reduced !== options.reduced;
      options = next;
      if (recolor) readStyle();
      if (relayout) layout();
      if (calmChange && entered) retarget();
      wake();
    },

    setWords(next: ReliefEntry[]) {
      entries = next;
      targets = new Float32Array(next.length);
      to = new Float32Array(0);
      layout();
    },

    setRaise(raise: ReliefRaise | undefined, at: [number, number]) {
      const result = targetsFor(entries, raise);
      targets = result.values;
      raised = result.any;
      origin = at;
      if (entered) retarget();
    },
  };
}

export interface ReliefProps extends Omit<React.HTMLAttributes<HTMLDivElement>, "children"> {
  /** The words on the wall: strings, or `{ text, tags }` so `raise` can name a group. They repeat to fill the box. */
  words: ReliefWord[];
  /**
   * What stands raised. A word or tag (or a list of them) raises every match to full height; a
   * `{ word: height }` map or a function gives each word a height from 0 to 1. `null` lets the wave
   * run.
   */
  raise?: ReliefRaise;
  /** Where a change to `raise` ripples out from, as `[x, y]` fractions of the box. */
  origin?: [number, number];
  /** The ambient wave while nothing is raised. It calms flat while words are raised. */
  wave?: boolean;
  /** A mouse or pen pushes up a soft mound of words under it. */
  pointer?: boolean;
  /** Inks from low to high. A word's stack shows one band per ink and its face takes the ink it reached. */
  inks?: string[];
  /** How far a word at full height rises, in px. */
  depth?: number;
  /** Type size of the words, in px. */
  fontSize?: number;
  /** Space between words and between rows, in px. */
  gap?: number;
  /** Radius of the pointer's mound, in px. */
  reach?: number;
  /** Turns the whole wall, in degrees. It still fills the box. */
  tilt?: number;
  /** Speed of the wave, as a multiplier. */
  speed?: number;
  /** Seconds a word takes to rise to its new height or settle back. */
  duration?: number;
  /** How fast a change to `raise` travels across the wall, in px per second. */
  ripple?: number;
  /** Holds the wave where it is. Raised words and the pointer still move. */
  paused?: boolean;
  /** Changes the shuffle, for two walls of the same words that shouldn't match. */
  seed?: string;
  /**
   * Classes for the flat words: their `text-*` color, font family and weight. Kept off the root so
   * the content you lay over the wall doesn't inherit it.
   */
  wordClassName?: string;
  /** What the wall shows, for screen readers. The raised words are read after it. */
  label?: string;
  /** Content laid over the wall. Mark the part that must read with `data-relief-quiet`. */
  children?: React.ReactNode;
  ref?: React.Ref<HTMLDivElement>;
}

const DEFAULT_ORIGIN: [number, number] = [0.5, 0.5];

export function Relief({
  words,
  raise,
  origin = DEFAULT_ORIGIN,
  wave = true,
  pointer = true,
  inks = RELIEF.inks as unknown as string[],
  depth = 24,
  fontSize = 13,
  gap = 6,
  reach = 150,
  tilt = 0,
  speed = TIMING.speed,
  duration = TIMING.duration,
  ripple = TIMING.ripple,
  paused = false,
  seed = "relief",
  wordClassName,
  label,
  className,
  children,
  ref,
  ...props
}: ReliefProps) {
  const rootRef = React.useRef<HTMLDivElement>(null);
  const setRoot = React.useCallback(
    (node: HTMLDivElement | null) => {
      rootRef.current = node;
      if (typeof ref === "function") ref(node);
      else if (ref) ref.current = node;
    },
    [ref],
  );
  const canvasRef = React.useRef<HTMLCanvasElement>(null);
  const probeRef = React.useRef<HTMLSpanElement>(null);
  const [relief] = React.useState(createRelief);
  const reduced = useReduced();

  const entries = React.useMemo<ReliefEntry[]>(() => {
    const seen = new Set<string>();
    const out: ReliefEntry[] = [];
    for (const w of words) {
      const e = typeof w === "string" ? { text: w, tags: [] } : { text: w.text, tags: w.tags ?? [] };
      const text = e.text.trim().toUpperCase();
      if (!text || seen.has(text)) continue;
      seen.add(text);
      out.push({ text, tags: e.tags });
    }
    return out;
  }, [words]);

  React.useLayoutEffect(() => {
    const root = rootRef.current;
    const canvas = canvasRef.current;
    const probe = probeRef.current;
    if (!root || !canvas || !probe) return;
    return relief.connect({ root, canvas, probe });
  }, [relief]);

  const inkKey = inks.join("|");
  React.useEffect(() => {
    relief.setOptions({
      depth: Math.max(4, depth),
      fontSize: Math.max(8, fontSize),
      gap: Math.max(0, gap),
      reach: Math.max(20, reach),
      tilt,
      speed: Math.max(0, speed),
      duration: Math.max(0.05, duration),
      ripple: Math.max(50, ripple),
      wave,
      pointer,
      paused,
      reduced,
      inks: inkKey.split("|").filter(Boolean),
      seed,
    });
  }, [relief, depth, fontSize, gap, reach, tilt, speed, duration, ripple, wave, pointer, paused, reduced, inkKey, seed]);

  React.useEffect(() => {
    relief.setWords(entries);
  }, [relief, entries]);

  // A new function each render would restart every word, so only a change in result counts.
  const raiseKey = React.useMemo(() => {
    if (raise == null) return "";
    if (typeof raise === "function") return entries.map((e) => clamp01(raise(e) || 0).toFixed(3)).join(",");
    return JSON.stringify(raise);
  }, [raise, entries]);
  const raiseRef = React.useRef(raise);
  React.useEffect(() => {
    raiseRef.current = raise;
  });
  const [ox, oy] = origin;
  React.useEffect(() => {
    relief.setRaise(raiseRef.current, [ox, oy]);
    // Words first: setWords runs before this on a change to both.
  }, [relief, raiseKey, entries, ox, oy]);

  let raisedText = "";
  if (label && raise != null) {
    const { values } = targetsFor(entries, raise);
    raisedText = entries
      .filter((_, i) => values[i] > 0)
      .map((e) => e.text.toLowerCase())
      .join(", ");
  }

  return (
    <div
      ref={setRoot}
      className={cn(
        "relative isolate overflow-hidden bg-white dark:bg-[#07080c]",
        className,
      )}
      {...props}
    >
      <canvas
        ref={canvasRef}
        aria-hidden
        className="pointer-events-none absolute inset-0 -z-10 size-full"
        style={{ opacity: 0 }}
      />
      {/* The flat words' color and type, read by the canvas. The default applies only when no class is given. */}
      <span
        ref={probeRef}
        aria-hidden
        className={cn("hidden font-semibold", wordClassName ?? "text-zinc-300 dark:text-zinc-700")}
      />
      {label ? (
        <p className="sr-only">
          {label}
          {raisedText ? `. Raised: ${raisedText}.` : ""}
        </p>
      ) : null}
      {children}
    </div>
  );
}
```
