# Aurora light

Soft light for an element's moment, in our glass colors: the glim crosses a card when work arrives, the rim blooms out of what you pressed and holds while the agent works, the ring pops for a moment that matters.

Tier: free. Type: component. Category: feedback. Tags: agent, motion.

## Install

```bash
npx shadcn@latest add https://pixilui.com/r/aurora-light.json
```

One-time setup: add the registry to `components.json`:

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

Files: `components/pixilui/aurora-light.tsx`.

## Preview

Live preview: https://pixilui.com/components/aurora-light

Knobs:

- `effect`: `glim`, `ring`, `rim`
- `tone`: `color`, `single`, `grey`

Signature: The refund card pops and a muted ring in our glass colors flows through it from the top as $0.00 blurs into $42.00.

Styles: `lively` (default), `quiet`, set with `data-style` on <html>. The item reads the style through the foundation; it needs no prop. Standalone files: lively https://pixilui.com/r/standalone/aurora-light.tsx, quiet https://pixilui.com/r/standalone/aurora-light.quiet.tsx.

## Code

`components/pixilui/aurora-light.tsx`

```tsx
"use client";

/*
  Aurora light and the relay engine under it (agent motion family 1, flow along a path, and Aurora light; both locked 2 Dec
  2026, "yes, lock flow in Aurora"; the full-strength failure light red only since 4 Dec). A port of the locked relay.js,
  line for line: the clock, the tracks, the relays, the arrivals and the held light, drawn on canvas. Every colour and
  shared timing is a locked token in foundation.css section 8 (--pixilui-relay-*, --pixilui-aurora-*), read here as the
  lock reads relay.css; the drawing (gradient stops, sprite sizes, alphas) stays in the script, as in the lock. The lock
  wins over the token rule for this renderer, as it does for the activity mark: the canvas is painted with colour strings
  it builds itself.

  What the library adds to the lock, none of it visible on the reference pages:
  - the look (data-look), the strength (data-aurora) and the theme are read from the nearest ancestor that sets them, so
    one page can show both looks (the lock reads the look and theme from <html>; a page that sets them there draws the same);
  - the clock starts on first use (no window at import) and its frame loop rests while nothing is moving;
  - the canvases' classes take the library's names (relayClasses).

  The engine (relay) is shared: Handoff flow (Pro) draws its tracks and arrivals with it, Toast lands its money moved and
  failure moments with it, and AuroraLight below is its element face (the glim, the rim and the ring).
*/

import { forwardRef, useEffect, useImperativeHandle, useRef, type ComponentPropsWithoutRef } from "react";
import { cn } from "./lib/utils";
import { prefersReducedMotion } from "./lib/motion/reduced-motion";

/** The meanings a handoff or an arrival can carry (each is one palette). */
export type RelayFamily = "think" | "find" | "make" | "code" | "wait" | "done" | "fail" | "holo" | "idle";
/** Where an arrival enters an element. */
export type RelaySide = "left" | "right" | "top" | "bottom";
/** The two looks: Cells (the activity mark's cells) and Aurora (soft light). */
export type RelayLook = "cells" | "aurora";
/** Aurora's two strengths: soft for a flow, full for an element that is the moment itself. */
export type RelayStrength = "soft" | "full";
/** Color, Single (one hue per meaning) or Grey (silver light, failures stay red). */
export type RelayTone = "color" | "single" | "grey";

type Pt = [number, number];
type RGB = number[];
type Ctx = CanvasRenderingContext2D;

/** The canvases' classes (the library's names; the comparison gives the lock's back). */
export const relayClasses = { layer: "pixilui-relay-layer", light: "pixilui-relay-glimm" };
/** The tokens' prefix (the comparison reads the library's, which the reference page aliases). */
const P_ = "--pixilui-";

const TAU = Math.PI * 2;
const clamp = (v: number, a = 0, b = 1) => Math.max(a, Math.min(b, v));
const ss = (a: number, b: number, x: number) => { const t = clamp((x - a) / (b - a)); return t * t * (3 - 2 * t); };
const bez = (p1x: number, p1y: number, p2x: number, p2y: number) => (x: number) => {
  if (x <= 0) return 0; if (x >= 1) return 1;
  let t = x; for (let i = 0; i < 10; i++) { const cx = 3 * p1x * t * (1 - t) ** 2 + 3 * p2x * t * t * (1 - t) + t ** 3 - x, d = 3 * p1x * (1 - t) ** 2 + 6 * (p2x - p1x) * t * (1 - t) + 3 * (1 - p2x) * t * t; if (Math.abs(cx) < 1e-6 || !d) break; t = clamp(t - cx / d); }
  return 3 * p1y * t * (1 - t) ** 2 + 3 * p2y * t * t * (1 - t) + t ** 3;
};
// the named values (foundation.css section 8, the lock's relay.css), read where the engine is working (a one-file build
// scopes its tokens to `[data-pixilui]`; the library's foundation sets them on :root, which every element inherits) // brand-allow
let scope: Element | null = null;
const at = (el?: Element | null) => { if (el && el.isConnected) scope = el; };
const css = (n: string) => getComputedStyle(scope && scope.isConnected ? scope : document.documentElement).getPropertyValue((n.startsWith(P_) ? n : n.replace(/^--/, P_))).trim();
const ms = (n: string) => { const v = css(n); return (v.endsWith("ms") ? parseFloat(v) : v.endsWith("s") ? parseFloat(v) * 1000 : parseFloat(v)) || 0; };
// a curve token; without the foundation (no tokens at all) the browser's plain ease, so nothing throws
const curveTok = (n: string) => css(n) || "ease";
const sec = (n: string) => ms(n) / 1000;
const curveCache = new Map<string, (x: number) => number>();
const curveOf = (n: string) => {
  let c = curveCache.get(n);
  if (!c) { const m = css(n).match(/cubic-bezier\(([^)]+)\)/); const [a, b, d, e] = (m ? m[1]! : ".25,.1,.25,1").split(",").map(Number) as [number, number, number, number]; c = bez(a, b, d, e); curveCache.set(n, c); }
  return c;
};
// the relay leaves the port slowly, cruises and lands with a slight overshoot (measured on Flo's pulse)
const relayEase = (x: number) => curveOf("--pixilui-relay-curve")(x);
// the wave rushes in from the port and settles as it clears the far edge
const waveEase = (x: number) => curveOf("--pixilui-relay-wave-curve")(x);
/** Reduced motion: the OS setting, or data-reduced="true" on <html> (a page's own switch). */
const reduced = () => document.documentElement.dataset.reduced === "true" || prefersReducedMotion();

// -------------------------------------------------------------------------------------------------------------------
// the clock: every relay, wave, count and story step reads it, so Pause and Slow hold everything together

type Timer = { at: number; fn: () => void };
/** The shared clock: t in seconds, scale (Slow), paused (Pause). */
export const relayClock = { t: 0, scale: 1, paused: false };
const timers: Timer[] = [];
const ticks = new Set<(t: number) => void>();
let last = 0;
let running = false;
let started = false;
function frame(ts: number) {
  const dt = Math.min(.05, Math.max(0, (ts - last) / 1000)); last = ts;
  if (!relayClock.paused) relayClock.t += dt * relayClock.scale;
  timers.sort((a, b) => a.at - b.at);
  while (timers.length && timers[0]!.at <= relayClock.t) timers.shift()!.fn();
  for (const f of ticks) f(relayClock.t);
  syncHeld();
  // the loop rests while nothing is moving or waiting (the lock's page always has something drawing)
  if (!ticks.size && !timers.length && !held.size) { running = false; return; }
  requestAnimationFrame(frame);
}
/** Starts the shared clock (any call into the engine does this). */
export function relayStart() {
  if (typeof window === "undefined") return;
  if (!started) {
    started = true;
    new MutationObserver(() => { for (const k in cache) delete cache[k]; for (const k in pcache) delete pcache[k]; curveCache.clear(); }).observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme", "style", "class"] });
  }
  if (running) return;
  running = true; last = performance.now();
  requestAnimationFrame(frame);
}
/** Resolves after s seconds of the shared clock. */
export const relayWait = (s: number) => { relayStart(); return new Promise<void>((r) => timers.push({ at: relayClock.t + s, fn: r })); };
/** Calls f with the clock's time every frame until the returned function is called. */
export const relayOnTick = (f: (t: number) => void) => { relayStart(); ticks.add(f); return () => { ticks.delete(f); }; };

// -------------------------------------------------------------------------------------------------------------------
// tones per family and theme come from the locked activity mark (--pixilui-activity-mark-<family>-light|dark, five tones)

const themeOf = (el?: Element | null): Element => (el && el.closest && el.closest(".dark, .light, [data-theme]")) || document.documentElement;
/** Whether an element draws dark (the nearest .dark or data-theme, as the foundation's dark tokens follow). */
const dark = (el?: Element | null) => { const t = themeOf(el); return t.classList.contains("dark") || t.getAttribute("data-theme") === "dark"; };
const cache: Record<string, RGB[]> = {}, pcache: Record<string, RGB[]> = {};
/** The activity mark's five tones for a family, for an element's theme and tone (Grey turns every family but fail grey). */
export function relayTones(fam: RelayFamily, el?: Element | null): RGB[] {
  const grey = el && el.closest && el.closest('[data-flow-tone="grey"]');
  const f = grey && fam !== "fail" ? "idle" : fam, th = dark(el) ? "dark" : "light", key = f + th;
  if (cache[key]) return cache[key]!;
  const root = getComputedStyle(el && el.isConnected ? el : scope && scope.isConnected ? scope : document.documentElement);
  const v = root.getPropertyValue(`--pixilui-activity-mark-${f}-${th}`).trim().split(/[\s,]+/).filter(Boolean);
  const list = (v.length === 5 ? v : root.getPropertyValue(`--pixilui-activity-mark-idle-${th}`).trim().split(/[\s,]+/)).map((h) => { const x = h.replace("#", ""); return [0, 2, 4].map((i) => parseInt(x.slice(i, i + 2), 16)); });
  // without the foundation there are no tones: a grey ramp, so the engine still draws and never throws
  return (cache[key] = list.length === 5 && list.every((c) => c.every((n) => Number.isFinite(n))) ? list : GREY);
}
const GREY: RGB[] = [[232, 232, 236], [205, 205, 212], [170, 170, 180], [130, 130, 142], [95, 95, 106]];
const mixRGB = (a: RGB, b: RGB, p: number) => a.map((v, i) => Math.round(v + (b[i]! - v) * p));
const rgba = (c: RGB, a = 1) => `rgba(${c[0]},${c[1]},${c[2]},${a})`; // check-registry-ignore: the locked renderer paints a canvas
// tone at a fractional index 0..4
const toneAt = (T: RGB[], x: number) => { const i = clamp(Math.floor(x), 0, 3), f = clamp(x - i); return mixRGB(T[i]!, T[i + 1]!, f); };

// -------------------------------------------------------------------------------------------------------------------
// paths: an elbow between two ports, as a polyline with round corners, sampled every `pitch` px into cells

const PITCH = 3.4;
type Geo = { L: number; cells: { s: number; p: Pt }[]; at: (s: number) => Pt; key?: string };
function elbow(a: Pt, b: Pt, kind: string, r: number): Pt[] {
  const [x1, y1] = a, [x2, y2] = b;
  if (kind === "h" || (kind === "hvh" && Math.abs(y2 - y1) < 1) || (kind === "vhv" && Math.abs(x2 - x1) < 1)) return [[x1, y1], [x2, y2]];
  if (kind === "hvh") { const xm = Math.round((x1 + x2) / 2); return rounded([[x1, y1], [xm, y1], [xm, y2], [x2, y2]], r); } // across, down or up, across
  if (kind === "vh") return rounded([[x1, y1], [x1, y2], [x2, y2]], r); // down, then across into a side
  const ym = Math.round((y1 + y2) / 2); return rounded([[x1, y1], [x1, ym], [x2, ym], [x2, y2]], r); // down, across, down
}
// a polyline through the points with every inside corner rounded (a quadratic through the corner)
function rounded(P: Pt[], r: number): Pt[] {
  const out: Pt[] = [P[0]!];
  for (let i = 1; i < P.length - 1; i++) {
    const prev = P[i - 1]!, c = P[i]!, next = P[i + 1]!;
    const d1: Pt = [c[0] - prev[0], c[1] - prev[1]], d2: Pt = [next[0] - c[0], next[1] - c[1]];
    const l1 = Math.hypot(...d1), l2 = Math.hypot(...d2);
    if (l1 < .01 || l2 < .01) { out.push(c); continue; }
    const u1 = [d1[0] / l1, d1[1] / l1] as Pt, u2 = [d2[0] / l2, d2[1] / l2] as Pt;
    const rr = Math.min(r, l1 / 2, l2 / 2), s = [c[0] - u1[0] * rr, c[1] - u1[1] * rr] as Pt, e = [c[0] + u2[0] * rr, c[1] + u2[1] * rr] as Pt;
    for (let k = 0; k <= 12; k++) { const t = k / 12, m = 1 - t; out.push([m * m * s[0] + 2 * m * t * c[0] + t * t * e[0], m * m * s[1] + 2 * m * t * c[1] + t * t * e[1]]); }
  }
  out.push(P[P.length - 1]!);
  return out;
}
function sample(pts: Pt[]): Geo {
  const segs: [number, number, Pt, Pt][] = []; let L = 0;
  for (let i = 1; i < pts.length; i++) { const l = Math.hypot(pts[i]![0] - pts[i - 1]![0], pts[i]![1] - pts[i - 1]![1]); segs.push([L, l, pts[i - 1]!, pts[i]!]); L += l; }
  const at = (s: number): Pt => { for (const [s0, l, a, b] of segs) if (s <= s0 + l || b === pts[pts.length - 1]) { const t = l ? clamp((s - s0) / l) : 0; return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]; } return pts[pts.length - 1]!; };
  const cells: { s: number; p: Pt }[] = [];
  const n = Math.max(1, Math.round(L / PITCH));
  for (let i = 0; i <= n; i++) { const s = L * i / n; cells.push({ s, p: at(s) }); }
  return { L, cells, at };
}

// -------------------------------------------------------------------------------------------------------------------
// a layer: one canvas over a stage, drawing every track on it every frame

/** A track's options: its ends or its route, in stage px (read every frame, so layout changes follow). */
export type RelayTrackOptions = {
  /** A route of its own, as points (its corners are rounded; in Aurora a four-point route becomes one soft S). */
  path?: () => Pt[];
  /** Or two ends, joined by an elbow of `kind`. */
  ends?: () => [Pt, Pt];
  fam?: RelayFamily;
  /** The elbow: h, hvh (across, down, across; default), vh, vhv. */
  kind?: "h" | "hvh" | "vh" | "vhv";
  /** Corner radius of the elbow (8). */
  r?: number;
  /** 0 at rest (grey), 1 in use. */
  level?: number;
  /** How much of the track is drawn, 0 to 1 (1). */
  build?: number;
  /** false hides both ports; [start, end] picks them. */
  ports?: false | [boolean, boolean];
};
/** A handoff along a track. */
export type RelaySendOptions = { fam?: RelayFamily; dur?: number; back?: boolean; len?: number; small?: boolean; keepLevel?: boolean; speed?: number };
type Relay = { t0: number; dur: number; fam: RelayFamily; back: boolean; len: number; small: boolean };
/** One track: a wire between two ports. */
export type RelayTrack = {
  fam: RelayFamily; level: number; build: number; relays: Relay[];
  /** Change its family, level (it eases over .35s) or build. */
  set(p?: { fam?: RelayFamily; level?: number; build?: number }): RelayTrack;
  /** Draws the track on from its start (the trace). */
  drawOn(dur?: number): Promise<void>;
  /** A slow swell runs along it while its receiver works. */
  breathe(on: boolean): RelayTrack;
  /** A handoff: resolves when it lands on the far port. */
  send(p?: RelaySendOptions): Promise<void>;
};
/** A stage's layer of tracks. */
export type RelayLayer = { el: HTMLCanvasElement; tracks: RelayTrack[]; track(o: RelayTrackOptions): RelayTrack; clear(): void; destroy(): void };

/** One canvas under a stage's elements (the stage is positioned), drawing its tracks every frame. */
export function relayLayer(stage: HTMLElement): RelayLayer {
  at(stage);
  const cv = document.createElement("canvas"); cv.className = relayClasses.layer; cv.setAttribute("aria-hidden", "true");
  stage.prepend(cv);
  const ctx = cv.getContext("2d"), tracks: (RelayTrack & { draw: (ctx: Ctx, t: number, glow: HTMLCanvasElement) => void })[] = [];
  let W = 0, H = 0, dpr = 1;
  function size() {
    const r = stage.getBoundingClientRect(); dpr = Math.min(3, devicePixelRatio || 1); W = r.width; H = r.height;
    cv.width = Math.round(W * dpr); cv.height = Math.round(H * dpr); cv.style.width = W + "px"; cv.style.height = H + "px";
  }
  // (no ResizeObserver where there is no layout, as in a test DOM)
  const ro = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(size); ro?.observe(stage); size();
  const glow = sprite();
  const off = relayOnTick((t) => {
    if (!ctx) return;
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, W, H);
    for (const tr of tracks) tr.draw(ctx, t, glow);
  });
  return {
    el: cv, tracks,
    track(o) { const t = makeTrack(o, stage); tracks.push(t); return t; },
    clear() { tracks.length = 0; },
    destroy() { off(); ro?.disconnect(); cv.remove(); tracks.length = 0; },
  };
}
// a soft round light for dark mode, rendered once (never a canvas filter per frame)
function sprite() {
  const c = document.createElement("canvas"), s = 64; c.width = c.height = s;
  const g = c.getContext("2d");
  if (!g) return c;
  const gr = g.createRadialGradient(s / 2, s / 2, 0, s / 2, s / 2, s / 2);
  gr.addColorStop(0, "rgba(255,255,255,.9)"); gr.addColorStop(.25, "rgba(255,255,255,.35)"); gr.addColorStop(1, "rgba(255,255,255,0)"); // check-registry-ignore: the locked renderer paints a canvas
  g.fillStyle = gr; g.fillRect(0, 0, s, s); return c;
}

// -------------------------------------------------------------------------------------------------------------------
// a track: cells along an elbow; relays and a breathing swell light them

type TrackState = RelayTrack & {
  kind: string; r: number; lv: number; lvFrom: number; lvAt: number; breath: boolean; breathAt: number; ring: [number, number];
  g: Geo | null; stage: HTMLElement; ports?: false | [boolean, boolean]; drawAt?: [number, number] | null; landAt?: number;
  geo(): Geo; draw(ctx: Ctx, t: number, glow: HTMLCanvasElement): void;
};
function makeTrack(o: RelayTrackOptions, stage: HTMLElement): TrackState {
  const tr: TrackState = {
    fam: o.fam || "idle", kind: o.kind || "hvh", r: o.r ?? 8, level: o.level ?? 0, lv: o.level ?? 0, lvFrom: o.level ?? 0, lvAt: -1,
    build: o.build ?? 1, relays: [], breath: false, breathAt: 0, ring: [0, 0], g: null, stage, ports: o.ports,
    geo() {
      let pts: Pt[];
      if (o.path) pts = o.path(); else { const [a, b] = o.ends!(); pts = [a, b]; }
      const A = look(stage) === "aurora", key = pts.map((p) => p.map((v) => v.toFixed(1)).join(",")).join(";") + tr.kind + A;
      if (!tr.g || tr.g.key !== key) { tr.g = sample(o.path ? (A ? curve(pts) : rounded(pts, tr.r)) : elbow(pts[0]!, pts[1]!, tr.kind, tr.r)); tr.g.key = key; }
      return tr.g;
    },
    set(p = {}) {
      if (p.fam) tr.fam = p.fam;
      if (p.level != null && p.level !== tr.level) { tr.lvFrom = tr.lv; tr.level = p.level; tr.lvAt = relayClock.t; }
      if (p.build != null) tr.build = p.build;
      return tr;
    },
    // draw the track on from its start over `dur` (the trace)
    drawOn(dur = sec("--pixilui-relay-draw")) { const t0 = relayClock.t; tr.build = 0; tr.drawAt = [t0, dur]; return relayWait(dur); },
    breathe(on) { if (on && !tr.breath) tr.breathAt = relayClock.t; tr.breath = on; return tr; },
    send(p = {}) {
      const g = tr.geo(), fam = p.fam || tr.fam;
      if (reduced()) { tr.set({ level: 1 }); return Promise.resolve(); }
      relayStart();
      const dur = p.dur ?? (sec("--pixilui-relay-run") + g.L / +css("--pixilui-relay-px-per-s")) * (p.speed ? 1 / p.speed : 1);
      const r: Relay = { t0: relayClock.t, dur, fam, back: !!p.back, len: p.len ?? 26, small: !!p.small };
      tr.relays.push(r);
      tr.ring[r.back ? 1 : 0] = relayClock.t; // the port it leaves from releases
      // it lands when its head reaches the far port (the eased head passes the end at ~86% of the run)
      return new Promise<void>((res) => timers.push({ at: relayClock.t + dur * .8, fn: () => { tr.ring[r.back ? 0 : 1] = relayClock.t; tr.landAt = relayClock.t; if (!p.keepLevel) tr.set({ level: 1, fam: tr.fam }); res(); } }));
    },
    draw(ctx, t, glow) {
      const g = tr.geo(), D = dark(tr.stage), T = relayTones(tr.fam, tr.stage), G = relayTones("idle", tr.stage);
      if (tr.drawAt) { tr.build = clamp((t - tr.drawAt[0]) / tr.drawAt[1]); if (tr.build >= 1) tr.drawAt = null; }
      const lv = tr.lvAt < 0 ? tr.level : tr.lvFrom + (tr.level - tr.lvFrom) * ss(0, 1, (t - tr.lvAt) / .35);
      tr.lv = lv;
      tr.relays = tr.relays.filter((r) => t - r.t0 < r.dur + .05);
      if (look(tr.stage) === "aurora") {
        // comets: the head runs on past the far port until the tail is in, so it squeezes into the card
        return drawAurora(tr, ctx, t, g, lv, tr.relays.map((r) => {
          const u = (t - r.t0) / r.dur, len = (r.small ? 34 : 74) * K(tr.stage).len;
          return { u, head: -4 + (g.L + len + 4) * relayEase(clamp(u)), len, P: pal(r.fam, tr.stage), I: clamp(u / .06) * (r.small ? .8 : 1), back: r.back };
        }));
      }
      // relays alive now, each with its head (px along the track) and family tones
      const live: { hv: number; sig: number; back: boolean; fade: number; T: RGB[]; small: boolean }[] = [];
      for (const r of tr.relays) {
        const u = (t - r.t0) / r.dur, sigT = r.len, over = r.len * 1.6;
        const head = -6 + (g.L + over + 6) * relayEase(clamp(u));
        // the run grows out of the port with its tail held there, and squeezes into the far port as its tail catches up
        const hv = Math.min(g.L, head), tail = Math.max(0, head - sigT * 2.2), squeeze = clamp((hv - tail) / (sigT * 2.2));
        const fade = head > g.L ? clamp(squeeze / .3) : clamp(u / .08);
        live.push({ hv: r.back ? g.L - hv : hv, sig: Math.max(4, sigT * squeeze), back: r.back, fade, T: relayTones(r.fam, tr.stage), small: r.small });
      }
      const bp = 2.4, bAge = tr.breath && !reduced() ? ((t - tr.breathAt) % bp) / 1.3 : 9; // a swell runs the track in 1.3 s, then rests
      const bHead = (bAge <= 1) ? -20 + (g.L + 40) * ss(0, 1, bAge) : -999;
      const reach = g.L * tr.build;
      const sz = 2.3;
      for (const c of g.cells) {
        if (c.s > reach + .01) break;
        let I = 0, TT = T;
        for (const L of live) {
          const d = L.back ? c.s - L.hv : L.hv - c.s; // distance behind the head
          const k = d < 0 ? Math.exp(-((d / 2.6) ** 2)) : Math.exp(-((d / L.sig) ** 2) * .9);
          const v = k * L.fade * (L.small ? .8 : 1);
          if (v > I) { I = v; TT = L.T; }
        }
        if (bHead > -999) I = Math.max(I, .28 * Math.exp(-(((bHead - c.s) / 16) ** 2)));
        // the cell's resting tone: palest at rest, one step up in use; the draw-on front fades in
        const edge = tr.build < 1 ? ss(0, 1, (reach - c.s) / 18) : 1;
        // at rest a track is grey; work passing along it gives it its family's color (one step up while in use)
        const rest = D ? .5 + .7 * lv : .22 + 1 * lv;
        let col = mixRGB(toneAt(G, D ? .6 : .3), toneAt(T, rest), lv), size = sz;
        if (I > .01) { col = mixRGB(col, toneAt(TT, D ? 3.2 + .8 * I : 1.6 + 2.4 * I), clamp(I * 1.15)); size = sz + 1.5 * I; }
        const a = edge * (D ? .9 : 1);
        ctx.fillStyle = rgba(col, a); // check-registry-ignore: the locked renderer paints a canvas
        const h = size / 2;
        ctx.beginPath(); ctx.roundRect(c.p[0] - h, c.p[1] - h, size, size, size * .28); ctx.fill();
        if (D && I > .25) { ctx.globalCompositeOperation = "lighter"; ctx.globalAlpha = .55 * I; const gs = 16 + 10 * I; ctx.drawImage(glow, c.p[0] - gs / 2, c.p[1] - gs / 2, gs, gs); ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over"; }
      }
      // ports: small rings at both ends; the one a relay leaves from (or lands on) releases
      if (tr.build > .02) for (const [i, p] of [[0, g.cells[0]!.p], [1, g.cells[g.cells.length - 1]!.p]] as [0 | 1, Pt][]) {
        if (i === 1 && tr.build < .98) continue;
        if (o.ports === false || (o.ports && !o.ports[i])) continue;
        const age = t - tr.ring[i], pulse = age >= 0 && age < .5 ? Math.sin(Math.PI * clamp(age / .5)) : 0;
        const r = 3.2 + 1.6 * pulse;
        ctx.lineWidth = 1.4; ctx.strokeStyle = rgba(toneAt(T, (D ? 1.2 : 1.2) + .9 * lv + 1.4 * pulse)); // check-registry-ignore: the locked renderer paints a canvas
        ctx.fillStyle = D ? "#121214" : "#fff"; // check-registry-ignore: the locked renderer paints a canvas
        ctx.beginPath(); ctx.arc(p[0], p[1], r, 0, TAU); ctx.fill(); ctx.stroke();
      }
    },
  };
  return tr;
}

// -------------------------------------------------------------------------------------------------------------------
// the glimm: a dithered wave in the receiver's family enters the card at the port, crosses it with a soft wavy front
// (dense deep cells at the front thinning into a pale tint behind) and carries the card's changes as it passes them

/** A change that fires as the light reaches an element (or a fraction `at` of the way across). */
export type RelaySwap = { el?: Element | null; at?: number; run?: () => void };
/** An arrival on an element. */
export type RelayArriveOptions = {
  fam?: RelayFamily;
  /** The edge it enters from (left). */
  from?: RelaySide;
  /** Where along that edge, px (the middle). */
  at?: number;
  /** Changes, fired in order as the light reaches each. */
  swaps?: RelaySwap[];
  dur?: number;
  /** Force a look for this arrival. */
  look?: RelayLook;
  /** Force a strength (soft or full) for this arrival. */
  strength?: RelayStrength | number;
  /** Full strength: false for the rim (no ring, no pop). */
  ring?: boolean;
  /** Full strength: the point it flows out of, in element px (what was pressed), and that thing's radius. */
  point?: Pt;
  pointR?: number;
  /** Full strength: hand over to the held glass light partway through (a working element). */
  hold?: boolean;
  /** Full strength: false for no pop, or its depth (1). */
  pop?: false | number;
  band?: number; pitch?: number; bow?: number; res?: number; margin?: number; fade?: number;
};
type Swap = RelaySwap & { done: boolean; d?: number; q?: number };
const BAYER = [0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5].map((v) => (v + .5) / 16);
const famOf = new WeakMap<Element, RelayFamily>();
/**
 * An arrival: light lands on an element and crosses it, firing its swaps as it passes them. In Cells a dithered wave; in
 * Aurora soft the glim; at full strength the ring (or, with ring: false, the rim). Resolves once the light has crossed.
 */
export function relayArrive(card: HTMLElement, o: RelayArriveOptions = {}): Promise<void> {
  at(card);
  const fam = o.fam || "think", from = o.from || "left", dur = o.dur ?? sec("--pixilui-relay-cells-wave");
  const swaps: Swap[] = (o.swaps || []).map((s) => ({ ...s, done: false }));
  famOf.set(card, fam);
  if (reduced()) { swaps.forEach((s) => s.run?.()); return Promise.resolve(); }
  relayStart();
  if (look(card) === "aurora" || o.look === "aurora") return (o.strength === "full" || (o.strength !== "soft" && strong(card))) ? arrive(card, o) : glim(card, o);
  const cv = document.createElement("canvas"); cv.className = relayClasses.light; cv.setAttribute("aria-hidden", "true");
  card.prepend(cv);
  const ctx = cv.getContext("2d")!;
  const r = card.getBoundingClientRect(), dpr = Math.min(3, devicePixelRatio || 1), W = r.width, H = r.height;
  cv.width = Math.round(W * dpr); cv.height = Math.round(H * dpr); cv.style.width = W + "px"; cv.style.height = H + "px";
  const horiz = from === "left" || from === "right";
  const span = horiz ? W : H, across = horiz ? H : W;
  // the entry point along the entry edge (px), the port
  const entry = o.at != null ? o.at : across / 2;
  const B = o.band ?? 58, P = o.pitch ?? 3, cell = P - .9;
  const t0 = relayClock.t;
  // each swap fires when the front reaches its element's center
  for (const s of swaps) {
    if (s.el) { const e = s.el.getBoundingClientRect(), cx = e.left + e.width / 2 - r.left, cy = e.top + e.height / 2 - r.top;
      const d = from === "left" ? cx : from === "right" ? W - cx : from === "top" ? cy : H - cy, q = horiz ? cy : cx;
      s.d = d; s.q = q; } else { s.d = (s.at ?? .5) * span; s.q = entry; }
  }
  let crossed = false;
  return new Promise<void>((res) => {
    const off = relayOnTick((t) => {
      const T = relayTones(fam, card), D = dark(card), u = (t - t0) / dur, tau = t - t0;
      const F = -B * .3 + (span + B * 1.3) * waveEase(clamp(u));
      const rest = clamp((t - t0 - dur * .8) / .6); // the faint tint it leaves, fading
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, W, H);
      const front = (q: number) => F - .38 * Math.abs(q - entry) + 6 * Math.sin(TAU * q / 118 + 2.1 * tau) + 3 * Math.sin(TAU * q / 47 - 3.3 * tau);
      // the soft tint behind the front: one smooth layer per row, so the cells sit on color, not on white
      const tintA = (D ? .2 : .42) * (1 - rest);
      if (tintA > .002) {
        for (let q = 0; q < across; q += P) {
          const f = front(q + P / 2), x0 = Math.max(0, f - B * 2.4), x1 = Math.min(span, f);
          if (x1 <= x0) continue;
          const g = horiz ? ctx.createLinearGradient(from === "left" ? x0 : W - x0, 0, from === "left" ? x1 : W - x1, 0) : ctx.createLinearGradient(0, from === "top" ? x0 : H - x0, 0, from === "top" ? x1 : H - x1);
          g.addColorStop(0, rgba(T[D ? 1 : 0]!, 0)); g.addColorStop(.55, rgba(T[D ? 1 : 0]!, tintA)); g.addColorStop(1, rgba(T[D ? 2 : 1]!, Math.min(1, tintA * 1.5))); // check-registry-ignore: the locked renderer paints a canvas
          ctx.fillStyle = g;
          if (horiz) ctx.fillRect(from === "left" ? x0 : W - x1, q, x1 - x0, P); else ctx.fillRect(q, from === "top" ? x0 : H - x1, P, x1 - x0);
        }
      }
      // the dithered front: a cell is lit where the wave is stronger than its threshold in the 4 x 4 Bayer matrix
      if (u < 1.02) for (let qi = 0, q = P / 2; q < across; qi++, q += P) {
        const f = front(q);
        for (let di = 0, d = P / 2; d < span; di++, d += P) {
          const behind = f - d; if (behind < 0) break;
          if (behind > B) continue;
          const k = behind / B, I = (behind < 5 ? 1.2 : Math.pow(1 - k, 1.25)) * (1 - ss(.86, 1.02, u)); // a crisp leading row, thinning behind
          const th = BAYER[(qi & 3) * 4 + (di & 3)]!;
          if (I <= th) continue;
          const col = D ? toneAt(T, 2.2 + 1.8 * (1 - k)) : toneAt(T, 1 + 3 * (1 - k));
          ctx.fillStyle = rgba(col, D ? .85 : .9); // check-registry-ignore: the locked renderer paints a canvas
          const x = horiz ? (from === "left" ? d : W - d) : q, y = horiz ? q : (from === "top" ? d : H - d), h = cell / 2;
          ctx.fillRect(x - h, y - h, cell, cell);
        }
      }
      for (const s of swaps) if (!s.done && front(s.q!) >= s.d!) { s.done = true; s.run?.(); }
      // it resolves once the front has crossed (the story moves on); the tint it leaves keeps fading on its own
      if (u >= 1 && !crossed) { crossed = true; swaps.forEach((s) => { if (!s.done) { s.done = true; s.run?.(); } }); res(); }
      if (u >= 1 && rest >= 1) { off(); cv.remove(); }
    });
  });
}

// -------------------------------------------------------------------------------------------------------------------
// Aurora, the second look (2 Dec): soft light. A comet of stacked soft lights runs the wire; where it lands the glim (soft)
// or the ring and the rim (full) cross the element. Pastel and additive in dark, vivid and soft in light. Every light is a
// stamped sprite or a stroke, never a canvas filter.

/** The look an element draws in: the nearest data-look (the lock sets it on <html>), else Cells. */
const look = (el?: Element | null): RelayLook => (((el && el.closest && el.closest("[data-look]")) || document.documentElement) as HTMLElement).dataset.look === "aurora" ? "aurora" : "cells";
// two strengths: soft for a page where the work is the subject (the flow), full for an element that is the moment itself
const strong = (el?: Element | null) => (((el && el.closest && el.closest("[data-aurora]")) || document.documentElement) as HTMLElement).dataset.aurora === "full";
type Strength = { halo: number; haloA: number; core: number; flare: number; wireGlow: number; wire: number; breath: number; port: number; len: number; held: number };
const SOFT: Strength = { halo: .62, haloA: .72, core: .7, flare: .6, wireGlow: .45, wire: .62, breath: 0, port: .6, len: .62, held: .36 };
const FULL: Strength = { halo: 1, haloA: 1, core: 1, flare: 1, wireGlow: 1, wire: 1, breath: 1, port: 1, len: 1, held: 1 };
const K = (el?: Element | null) => strong(el) ? FULL : SOFT;
// the soft palettes: --pixilui-aurora-<family>-dark|light, from the head of the light to its tail
const FAMS: RelayFamily[] = ["think", "find", "make", "code", "wait", "done", "fail", "holo", "idle"];
const hex = (h: string) => { const x = h.replace("#", ""); return [0, 2, 4].map((i) => parseInt(x.slice(i, i + 2), 16)); };
// full strength wears our glass colors (--pixilui-aurora-glass-<family>-dark|light): the person avatars' jewel hues plus teal,
// mint and sky, so it reads as PixilUI, not as anyone's pastel neon
const list = (n: string) => { const l = css(n).split(/[\s,]+/).filter(Boolean).map(hex); return l.length >= 2 && l.every((c) => c.every((v) => Number.isFinite(v))) ? l : GREY.slice(1, 4); };
function pal(fam: RelayFamily, el?: Element | null): RGB[] {
  // Single: one hue per meaning, the activity mark's own family tones (head bright, tail deeper)
  const single = el && el.closest && el.closest('[data-flow-tone="single"]');
  if (single) { const T = relayTones(fam === "holo" ? "think" : fam, el), key = "s" + fam + (dark(el) ? "d" : "l"); return pcache[key] || (pcache[key] = dark(el) ? [T[4]!, T[3]!, T[2]!] : [T[3]!, T[2]!, T[1]!]); }
  const grey = el && el.closest && el.closest('[data-flow-tone="grey"]');
  const f = grey && fam !== "fail" ? "idle" : (FAMS.includes(fam) ? fam : "think"), th = dark(el) ? "dark" : "light";
  if (f !== "idle" && strong(el)) { const key = "g" + f + th; return pcache[key] || (pcache[key] = list(`--pixilui-aurora-glass-${f}-${th}`)); }
  const key = f + th;
  return pcache[key] || (pcache[key] = list(`--pixilui-aurora-${f}-${th}`));
}
const palAt = (P: RGB[], x: number) => { const n = P.length - 1, v = clamp(x) * n, i = Math.min(n - 1, Math.floor(v)); return mixRGB(P[i]!, P[i + 1]!, v - i); };
const WHITE = [255, 255, 255];
// a soft round light in one color, rendered once per color
const sprites = new Map<string, HTMLCanvasElement>();
function glowOf(c: RGB) {
  const q = c.map((v) => Math.min(255, Math.round(v / 12) * 12)), k = q.join(",");
  let s = sprites.get(k); if (s) return s;
  s = document.createElement("canvas"); const n = 64; s.width = s.height = n;
  const g = s.getContext("2d")!, gr = g.createRadialGradient(n / 2, n / 2, 0, n / 2, n / 2, n / 2);
  gr.addColorStop(0, rgba(q, 1)); gr.addColorStop(.2, rgba(q, .6)); gr.addColorStop(.5, rgba(q, .16)); gr.addColorStop(1, rgba(q, 0)); // check-registry-ignore: the locked renderer paints a canvas
  g.fillStyle = gr; g.fillRect(0, 0, n, n); sprites.set(k, s); return s;
}
const stamp = (ctx: Ctx, c: RGB, x: number, y: number, size: number, a: number) => { if (a <= .003) return; ctx.globalAlpha = Math.min(1, a); ctx.drawImage(glowOf(c), x - size / 2, y - size / 2, size, size); };
// the hue runs around a point and turns slowly: the holographic ring and rim
function conic(ctx: Ctx, P: RGB[], rot: number, x: number, y: number) {
  if (!ctx.createConicGradient) { const g = ctx.createLinearGradient(x - 200, y, x + 200, y); P.forEach((c, i) => g.addColorStop(i / (P.length - 1), rgba(c))); return g; } // check-registry-ignore: the locked renderer paints a canvas
  const g = ctx.createConicGradient(rot, x, y), loop = [...P, ...P.slice(0, -1).reverse()];
  loop.forEach((c, i) => g.addColorStop(i / (loop.length - 1), rgba(c))); // check-registry-ignore: the locked renderer paints a canvas
  return g;
}
// across, then up or down, then across: one soft S between the ports (Charles's wires); anything else gets wide corners
function curve(P: Pt[]): Pt[] {
  if (P.length === 4 && Math.abs(P[0]![1] - P[1]![1]) < .5 && Math.abs(P[1]![0] - P[2]![0]) < .5 && Math.abs(P[2]![1] - P[3]![1]) < .5 && P[3]![0] - P[0]![0] > 8) {
    const a = P[0]!, b = P[3]!, k = (b[0] - a[0]) * .55, out: Pt[] = [];
    for (let i = 0; i <= 48; i++) { const t = i / 48, m = 1 - t; out.push([m ** 3 * a[0] + 3 * m * m * t * (a[0] + k) + 3 * m * t * t * (b[0] - k) + t ** 3 * b[0], m ** 3 * a[1] + 3 * m * m * t * a[1] + 3 * m * t * t * b[1] + t ** 3 * b[1]]); }
    return out;
  }
  return rounded(P, 18);
}
// a comet: soft lights stamped along it (bigger and whiter toward the head), a thin hot core, a flare at the head.
// head and len in px along the track; it is clipped to the track, so it grows out of one port and squeezes into the other
function comet(ctx: Ctx, g: Geo, head: number, len: number, P: RGB[], I0: number, back: boolean, D: boolean, k: Strength = SOFT) {
  const L = g.L, s0 = Math.max(0, head - len), s1 = Math.min(L, head);
  if (s1 - s0 < .5 || I0 <= .01) return;
  const at = (s: number) => g.at(back ? L - s : s);
  ctx.globalCompositeOperation = D ? "lighter" : "source-over";
  for (let s = s0; s <= s1; s += 1.6) {
    const u = (s - (head - len)) / len, I = Math.pow(clamp(u), 1.6) * I0;
    if (I < .02) continue;
    const p = at(s);
    stamp(ctx, palAt(P, 1 - u), p[0], p[1], (9 + 17 * I) * k.halo, (D ? .3 : .26) * I * k.haloA);
  }
  ctx.lineCap = "round";
  let prev = at(Math.max(s0, head - len * .6));
  for (let s = Math.max(s0, head - len * .6) + 1.6; s <= s1 + .01; s += 1.6) {
    const u = clamp((s - (head - len * .6)) / (len * .6)), p = at(Math.min(s, s1));
    ctx.globalAlpha = (D ? .85 : .9) * u * I0;
    ctx.strokeStyle = rgba(D ? mixRGB(palAt(P, 1 - u), WHITE, .35 + .5 * u) : palAt(P, .6 * (1 - u))); // check-registry-ignore: the locked renderer paints a canvas
    ctx.lineWidth = (.6 + 1.5 * u) * k.core;
    ctx.beginPath(); ctx.moveTo(prev[0], prev[1]); ctx.lineTo(p[0], p[1]); ctx.stroke(); prev = p;
  }
  if (head <= L + len * .2) { const hp = at(s1); stamp(ctx, D ? mixRGB(P[0]!, WHITE, .55) : P[0]!, hp[0], hp[1], 20 * k.flare, (D ? .8 : .55) * I0 * (.4 + .6 * k.flare)); }
  ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over";
}
// the track in Aurora: a quiet grey line that takes one burst of color as light passes and fades back to grey, comets, and
// ports that flare as light leaves or lands (in full, a soft comet runs it now and then while its receiver works)
type Live = { u: number; head: number; len: number; P: RGB[]; I: number; back: boolean };
function drawAurora(tr: TrackState, ctx: Ctx, t: number, g: Geo, lv: number, live: Live[]) {
  const D = dark(tr.stage), P = pal(tr.fam, tr.stage), reach = g.L * tr.build;
  void lv;
  if (reach < .5) return;
  const sub = () => {
    ctx.beginPath(); ctx.moveTo(g.cells[0]!.p[0], g.cells[0]!.p[1]);
    for (const c of g.cells) { if (c.s > reach) { const p = g.at(reach); ctx.lineTo(p[0], p[1]); break; } ctx.lineTo(c.p[0], c.p[1]); }
  };
  ctx.lineCap = "round"; ctx.lineJoin = "round";
  sub(); ctx.lineWidth = 1.25; ctx.strokeStyle = D ? "rgba(255,255,255,.12)" : "rgba(30,28,48,.12)"; ctx.stroke(); // check-registry-ignore: the locked renderer paints a canvas
  // the burst: rises while a comet runs, then fades back to grey within a second of it landing
  let f = 0;
  for (const r of live) f = Math.max(f, ss(.1, .7, r.u));
  if (tr.landAt != null) f = Math.max(f, 1 - ss(0, 1, t - tr.landAt));
  if (f > .01) {
    const a = g.cells[0]!.p, b = g.at(g.L), gr = ctx.createLinearGradient(a[0], a[1], b[0], b[1]);
    P.forEach((c, i) => gr.addColorStop(i / (P.length - 1), rgba(c))); // check-registry-ignore: the locked renderer paints a canvas
    ctx.strokeStyle = gr; ctx.globalCompositeOperation = D ? "lighter" : "source-over";
    sub(); ctx.globalAlpha = (D ? .09 : .08) * f * K(tr.stage).wireGlow; ctx.lineWidth = 8; ctx.stroke();
    ctx.globalAlpha = (D ? .5 : .55) * f * K(tr.stage).wire; ctx.lineWidth = 1.5; ctx.stroke();
    ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over";
  }
  const k = K(tr.stage);
  for (const r of live) comet(ctx, g, r.head, r.len, r.P, r.I, r.back, D, k);
  if (tr.breath && !reduced() && k.breath > 0) {
    const ph = ((t - tr.breathAt) % 2.6) / 1.5;
    if (ph <= 1) comet(ctx, g, -10 + (g.L + 56) * ss(0, 1, ph), 46 * k.len, P, .42 * k.breath * Math.sin(Math.PI * clamp(ph)), false, D, k);
  }
  if (tr.build > .02) for (const [i, p] of [[0, g.cells[0]!.p], [1, g.cells[g.cells.length - 1]!.p]] as [0 | 1, Pt][]) {
    if (i === 1 && tr.build < .98) continue;
    if (tr.ports === false || (tr.ports && !tr.ports[i])) continue;
    const age = t - tr.ring[i], fl = age >= 0 && age < .6 ? Math.sin(Math.PI * clamp(age / .6)) : 0;
    ctx.globalCompositeOperation = D ? "lighter" : "source-over";
    if (fl > .01) stamp(ctx, D ? mixRGB(P[0]!, WHITE, .4) : P[0]!, p[0], p[1], (22 + 14 * fl) * k.port, (D ? .7 : .45) * fl * k.port);
    ctx.globalCompositeOperation = "source-over"; ctx.globalAlpha = 1;
    ctx.fillStyle = D ? "rgba(255,255,255,.24)" : "rgba(30,28,48,.22)"; // check-registry-ignore: the locked renderer paints a canvas
    ctx.beginPath(); ctx.arc(p[0], p[1], 2.4 + .8 * fl, 0, TAU); ctx.fill();
  }
}

// a card's rounded rect as a closed loop sampled into points, clockwise from the end of the top-left corner
function loopOf(W: number, H: number, r: number, inset: number) {
  const x0 = inset, y0 = inset, x1 = W - inset, y1 = H - inset, R = Math.max(0, r - inset), pts: Pt[] = [[x0 + R, y0], [x1 - R, y0]];
  const arc = (cx: number, cy: number, a0: number) => { for (let k = 1; k <= 8; k++) { const a = a0 + Math.PI / 2 * k / 8; pts.push([cx + R * Math.cos(a), cy + R * Math.sin(a)]); } };
  arc(x1 - R, y0 + R, -Math.PI / 2); pts.push([x1, y1 - R]); arc(x1 - R, y1 - R, 0); pts.push([x0 + R, y1]); arc(x0 + R, y1 - R, Math.PI / 2); pts.push([x0, y0 + R]); arc(x0 + R, y0 + R, Math.PI);
  return sample(pts);
}
// the light on a card's rim: a wide colored glow inside the card, a haze outside it and a thin near-white line on top, the
// hue turning around the card. The glow is one soft mask per card, blurred once (a shadow, never a per-frame filter) and
// tinted once per palette; a frame only cuts it to the lit stretch and draws it. Soft light lives in 1x buffers.
function buffer(w: number, h: number) { const b = document.createElement("canvas"); b.width = Math.max(1, Math.round(w)); b.height = Math.max(1, Math.round(h)); return b; }
type MaskKind = "soft" | "inner" | "glass" | "rim";
// kinds: 'soft' (the glim's edges: haze and deep inner glow, no line) and 'inner' (the full rim: the light lives inside the
// surface, falling off over about 12 px from a crisp 1 px pastel edge, with only a trace outside, so it reads as lit glass)
function glowMask(W: number, H: number, rr: number, M: number, kind: MaskKind) {
  const m = buffer(W + 2 * M, H + 2 * M), g = m.getContext("2d")!, FAR = 30000;
  const shape = () => { g.beginPath(); g.roundRect(M - FAR, M, W, H, rr); }; // drawn far off the canvas; only its shadow lands
  g.shadowOffsetX = FAR; g.strokeStyle = "#fff"; // check-registry-ignore: the locked renderer paints a canvas
  if (kind === "inner" || kind === "glass") {
    g.save(); g.beginPath(); g.roundRect(M, M, W, H, rr); g.clip();
    g.shadowColor = "rgba(255,255,255,.62)"; g.shadowBlur = 18; g.lineWidth = 8; shape(); g.stroke(); // the inner glow // check-registry-ignore: the locked renderer paints a canvas
    g.shadowColor = "rgba(255,255,255,.5)"; g.shadowBlur = 5; g.lineWidth = 3; shape(); g.stroke(); // close to the edge // check-registry-ignore: the locked renderer paints a canvas
    g.restore();
    g.shadowColor = "rgba(255,255,255,.1)"; g.shadowBlur = 6; g.lineWidth = 1.5; shape(); g.stroke(); // a trace outside // check-registry-ignore: the locked renderer paints a canvas
    g.shadowColor = "transparent"; g.shadowOffsetX = 0; g.strokeStyle = "rgba(255,255,255,.95)"; g.lineWidth = 1; // check-registry-ignore: the locked renderer paints a canvas
    g.beginPath(); g.roundRect(M + .5, M + .5, W - 1, H - 1, Math.max(0, rr - .5)); g.stroke(); // the edge
    if (kind === "glass") {
      g.globalCompositeOperation = "destination-in";
      const v = g.createLinearGradient(0, M, 0, M + H); v.addColorStop(0, "rgba(0,0,0,.4)"); v.addColorStop(.45, "rgba(0,0,0,.62)"); v.addColorStop(1, "rgba(0,0,0,1)"); // check-registry-ignore: the locked renderer paints a canvas
      g.fillStyle = v; g.fillRect(0, 0, m.width, m.height); g.globalCompositeOperation = "source-over";
    }
    return m;
  }
  const soft = kind === "soft";
  g.shadowColor = soft ? "rgba(255,255,255,.4)" : "rgba(255,255,255,.5)"; g.shadowBlur = soft ? 20 : 16; g.lineWidth = 3; shape(); g.stroke(); // haze, both sides // check-registry-ignore: the locked renderer paints a canvas
  if (!soft) { g.shadowColor = "rgba(255,255,255,.75)"; g.shadowBlur = 5; g.lineWidth = 1.5; shape(); g.stroke(); } // close glow // check-registry-ignore: the locked renderer paints a canvas
  g.save(); g.beginPath(); g.roundRect(M, M, W, H, rr); g.clip();
  g.shadowColor = "rgba(255,255,255,.55)"; g.shadowBlur = 26; g.lineWidth = 12; shape(); g.stroke(); // the deep inner glow // check-registry-ignore: the locked renderer paints a canvas
  g.restore();
  return m;
}
// a flat soft dot for cutting the glow to a stretch of rim with soft ends
let dot: HTMLCanvasElement | undefined;
function softDot() {
  if (dot) return dot;
  dot = buffer(64, 64); const g = dot.getContext("2d")!, gr = g.createRadialGradient(32, 32, 0, 32, 32, 32);
  gr.addColorStop(0, "#fff"); gr.addColorStop(.5, "rgba(255,255,255,.95)"); gr.addColorStop(1, "rgba(255,255,255,0)"); // check-registry-ignore: the locked renderer paints a canvas
  g.fillStyle = gr; g.fillRect(0, 0, 64, 64); return dot;
}
type CardCanvas = {
  cv: HTMLCanvasElement; ctx: Ctx; r: DOMRect; dpr: number; W: number; H: number; M: number; rr: number; loop: Geo; n: number;
  unsub: (() => void) | null; stop(): void; off?: HTMLCanvasElement; offx?: Ctx; rev?: HTMLCanvasElement; revx?: Ctx;
  arc(i: number, k: number): (x: Ctx) => void; all(x: Ctx): void; inside(): void; glassImg?: HTMLCanvasElement; glassKey?: string;
};
// the card's glow in a palette with its hue turned to rot, made once and shared by every canvas of the same card size
const masks = new Map<string, HTMLCanvasElement>(), tints = new Map<string, HTMLCanvasElement>();
function tinted(c: CardCanvas, P: RGB[], rot: number, kind: MaskKind | true = "soft") {
  if (kind === true) kind = "soft";
  const mk = [c.W, c.H, c.rr, c.M].map((v) => Math.round(v)).join("x") + kind, key = mk + P.map((q) => q.join(",")).join(";") + rot.toFixed(2);
  if (tints.has(key)) return tints.get(key)!;
  if (!masks.has(mk)) { if (masks.size > 24) masks.clear(); masks.set(mk, glowMask(Math.round(c.W), Math.round(c.H), c.rr, c.M, kind)); }
  const mask = masks.get(mk)!, b = buffer(mask.width, mask.height), g = b.getContext("2d")!;
  g.drawImage(mask, 0, 0); g.globalCompositeOperation = "source-in"; g.fillStyle = conic(g, P, rot, c.M + Math.round(c.W) / 2, c.M + Math.round(c.H) / 2); g.fillRect(0, 0, b.width, b.height);
  if (tints.size > 48) tints.clear();
  tints.set(key, b); return b;
}
// draw the rim. stretch: null for the whole rim, or [i, k] for k cells either side of cell i. drift (0..1) blends the glow
// between two turns of its hue, so the color drifts without re-tinting. line: the thin bright line on top
type Stretch = null | [number, number] | { cells: number[] };
function rim(c: CardCanvas, stretch: Stretch, P: RGB[], rot: number, I: number, D: boolean, line = false, drift = 0, kind: MaskKind = "inner") {
  if (I <= .005) return;
  const { ctx, W, H, M, loop, n } = c;
  ctx.globalCompositeOperation = D ? "lighter" : "source-over";
  const k = I * (D ? 1 : .9), A = tinted(c, P, 0, kind), B = drift > .002 ? tinted(c, P, Math.PI, kind) : null;
  if (!stretch) {
    ctx.globalAlpha = Math.min(1, k * (1 - drift)); ctx.drawImage(A, -M, -M, W + 2 * M, H + 2 * M);
    if (B) { ctx.globalAlpha = Math.min(1, k * drift); ctx.drawImage(B, -M, -M, W + 2 * M, H + 2 * M); }
  } else {
    if (!c.off) { c.off = buffer(A.width, A.height); c.offx = c.off.getContext("2d")!; c.rev = buffer(A.width, A.height); c.revx = c.rev.getContext("2d")!; }
    const v = c.revx!, o = c.offx!, sz = 2 * M + 14;
    v.globalCompositeOperation = "source-over"; v.clearRect(0, 0, c.rev!.width, c.rev!.height);
    // soft dots along the stretch, so its ends fade instead of cutting the glow off
    if ("cells" in stretch) { for (const j of stretch.cells) { const p = loop.cells[j]!.p; v.drawImage(softDot(), M + p[0] - sz / 2, M + p[1] - sz / 2, sz, sz); } }
    else {
      const [i, kk] = stretch;
      for (let j = -kk; j <= kk; j += 3) { const p = loop.cells[((i + j) % n + n) % n]!.p; v.drawImage(softDot(), M + p[0] - sz / 2, M + p[1] - sz / 2, sz, sz); }
      { const p = loop.cells[((i + kk) % n + n) % n]!.p; v.drawImage(softDot(), M + p[0] - sz / 2, M + p[1] - sz / 2, sz, sz); }
    }
    o.globalCompositeOperation = "source-over"; o.clearRect(0, 0, c.off.width, c.off.height); o.drawImage(A, 0, 0);
    o.globalCompositeOperation = "destination-in"; o.drawImage(c.rev!, 0, 0);
    ctx.globalAlpha = Math.min(1, k); ctx.drawImage(c.off, -M, -M, W + 2 * M, H + 2 * M);
  }
  if (line) {
    ctx.strokeStyle = conic(ctx, D ? P.map((q) => mixRGB(q, WHITE, .55)) : P, rot, W / 2, H / 2);
    ctx.lineWidth = D ? 1.4 : 1.3; ctx.lineCap = "round"; ctx.lineJoin = "round"; ctx.globalAlpha = Math.min(1, (D ? .9 : .85) * I);
    (stretch && !("cells" in stretch) ? c.arc(stretch[0], stretch[1]) : c.all)(ctx); ctx.stroke();
  }
  ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over";
}
type Stoppable = { stop(): void };
const auroraLive = new Set<Stoppable>(); // every Aurora canvas and its tick, so a reset can stop them all
function cardCanvas(card: HTMLElement, M: number, res?: number): CardCanvas {
  const cv = document.createElement("canvas"); cv.className = relayClasses.light; cv.setAttribute("aria-hidden", "true");
  const r = card.getBoundingClientRect(), dpr = res ?? Math.min(2, devicePixelRatio || 1), W = r.width, H = r.height;
  cv.width = Math.round((W + 2 * M) * dpr); cv.height = Math.round((H + 2 * M) * dpr);
  Object.assign(cv.style, { width: W + 2 * M + "px", height: H + 2 * M + "px", left: -M + "px", top: -M + "px", zIndex: -1 });
  card.prepend(cv);
  const rr = parseFloat(getComputedStyle(card).borderTopLeftRadius) || 12, loop = loopOf(W, H, rr, .75), n = loop.cells.length - 1;
  const c: CardCanvas = {
    cv, ctx: cv.getContext("2d")!, r, dpr, W, H, M, rr, loop, n, unsub: null, stop() { c.unsub?.(); cv.remove(); auroraLive.delete(c); },
    // a stretch of the rim, k cells either side of cell i (wrapping), and the whole rim
    arc: (i, k) => (x) => { x.beginPath(); for (let j = -k; j <= k; j++) { const p = loop.cells[((i + j) % n + n) % n]!.p; if (j === -k) x.moveTo(p[0], p[1]); else x.lineTo(p[0], p[1]); } },
    all: (x) => { x.beginPath(); loop.cells.forEach((q, i) => { if (i) x.lineTo(q.p[0], q.p[1]); else x.moveTo(q.p[0], q.p[1]); }); x.closePath(); },
    inside: () => { c.ctx.beginPath(); c.ctx.roundRect(0, 0, W, H, rr); },
  };
  auroraLive.add(c); return c;
}

// the soft arrival (the flow), after Flo's glim and the Glimm washes: a broad, blurred band in the receiver's colors enters at
// the port's edge with a curved front (its middle leads, like a wave), sways gently as it flows, carries its hues along with
// it and a second hue drifting across it, and crosses the whole card to the far edge, fading as it goes so it vanishes. The
// card's edges only take a blurred glow where it passes; nothing is drawn as a line. The changes run as its peak passes them
const glimEase = (x: number) => curveOf("--pixilui-relay-glim-curve")(x); // holds at the entry edge a moment, then flows through the card
function glim(card: HTMLElement, o: RelayArriveOptions): Promise<void> {
  const fam = o.fam || "think", from = o.from || "left", dur = o.dur ?? sec("--pixilui-relay-glim"), M = 30, S = typeof o.strength === "number" ? o.strength : 1;
  const swaps: Swap[] = (o.swaps || []).map((s) => ({ ...s, done: false }));
  const c = cardCanvas(card, M, o.res), { ctx, r, dpr, W, H } = c;
  const horiz = from === "left" || from === "right", span = horiz ? W : H, across = horiz ? H : W;
  const B = o.band ?? clamp(span * .46, 60, 120);
  const dir = ({ left: [1, 0], right: [-1, 0], top: [0, 1], bottom: [0, -1] } as Record<RelaySide, Pt>)[from], perp: Pt = [-dir[1], dir[0]];
  const E: Pt = from === "left" ? [0, o.at ?? H / 2] : from === "right" ? [W, o.at ?? H / 2] : from === "top" ? [o.at ?? W / 2, 0] : [o.at ?? W / 2, H];
  // the band is a soft ring around a point behind the entry edge: the further back, the flatter its bow
  const back = o.bow ?? Math.max(48, across * .55), C0: Pt = [E[0] - dir[0] * back, E[1] - dir[1] * back];
  for (const s of swaps) {
    if (s.el) { const e = s.el.getBoundingClientRect(); s.d = Math.hypot(e.left + e.width / 2 - r.left - C0[0], e.top + e.height / 2 - r.top - C0[1]); }
    else s.d = back + (s.at ?? .5) * span;
  }
  if (!c.off) { c.off = buffer(W + 2 * M, H + 2 * M); c.offx = c.off.getContext("2d")!; }
  const gb = buffer(W, H), g = gb.getContext("2d")!, mb = buffer(W, H), mg = mb.getContext("2d")!, ph = Math.random() * TAU;
  const t0 = relayClock.t;
  let crossed = false;
  return new Promise<void>((res) => {
    c.unsub = relayOnTick((t) => {
      const D = dark(card), P = pal(fam, card), u = (t - t0) / dur, tau = t - t0;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, W + 2 * M, H + 2 * M); ctx.translate(M, M);
      // the front's distance from the bow's centre, and the band's strength: full at once, fading steadily as it crosses
      const F = (back - B * .45) + (span + B * 1.3) * glimEase(clamp(u)), A = S * ss(0, .06, u) * (1 - ss(.15, 1, u));
      // the bow sways a little as it flows
      const sway = Math.sin(tau * 3.1 + ph) * across * .12, Cw: Pt = [C0[0] + perp[0] * sway, C0[1] + perp[1] * sway];
      if (A > .003) {
        g.setTransform(1, 0, 0, 1, 0, 0); g.globalCompositeOperation = "source-over"; g.globalAlpha = 1; g.clearRect(0, 0, W, H);
        // the colors: they run along the way the band travels (tail to head), so the hues move with it
        const p0: Pt = [C0[0] + dir[0] * (F - B * 1.3), C0[1] + dir[1] * (F - B * 1.3)], p1: Pt = [C0[0] + dir[0] * (F + B * .5), C0[1] + dir[1] * (F + B * .5)];
        const lin = g.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
        P.forEach((_q, i) => lin.addColorStop(i / (P.length - 1), rgba(P[P.length - 1 - i]!))); // check-registry-ignore: the locked renderer paints a canvas
        g.fillStyle = lin; g.fillRect(0, 0, W, H);
        // a second hue drifting across the band, so it flows instead of reading as one flat stripe
        const drift = Math.sin(tau * 2.3 + ph * 1.7) * across * .38, bc: Pt = [C0[0] + dir[0] * (F - B * .4) + perp[0] * drift, C0[1] + dir[1] * (F - B * .4) + perp[1] * drift];
        const blob = g.createRadialGradient(bc[0], bc[1], 0, bc[0], bc[1], B * 1.1);
        blob.addColorStop(0, rgba(palAt(P, .5), .75)); blob.addColorStop(1, rgba(palAt(P, .5), 0)); // check-registry-ignore: the locked renderer paints a canvas
        g.fillStyle = blob; g.fillRect(0, 0, W, H);
        // the band itself: two bowed, soft rings from points a little apart, swaying out of phase, so its front is a living
        // wave rather than one arc; soft on both sides, its tail longer than its leading edge
        mg.setTransform(1, 0, 0, 1, 0, 0); mg.globalCompositeOperation = "source-over"; mg.globalAlpha = 1; mg.clearRect(0, 0, W, H);
        for (const [k, sp, lag] of [[1, 1, 0], [-1, 1.37, 1.9]] as [number, number, number][]) {
          const off = across * (.2 + .08 * Math.sin(tau * 2.6 * sp + ph + lag)), cx = Cw[0] + perp[0] * off * k, cy = Cw[1] + perp[1] * off * k;
          const Fr = F + B * .14 * Math.sin(tau * 3.4 * sp + ph * 1.3 + lag);
          const rg = mg.createRadialGradient(cx, cy, Math.max(0, Fr - B * 1.3), cx, cy, Fr + B * .42);
          rg.addColorStop(0, "rgba(0,0,0,0)"); rg.addColorStop(.3, "rgba(0,0,0,.3)"); rg.addColorStop(.58, "rgba(0,0,0,.8)"); rg.addColorStop(.68, "rgba(0,0,0,1)"); // check-registry-ignore: the locked renderer paints a canvas
          rg.addColorStop(.79, "rgba(0,0,0,.55)"); rg.addColorStop(.9, "rgba(0,0,0,.14)"); rg.addColorStop(1, "rgba(0,0,0,0)"); // check-registry-ignore: the locked renderer paints a canvas
          mg.globalAlpha = .62; mg.globalCompositeOperation = "lighter"; mg.fillStyle = rg; mg.fillRect(0, 0, W, H);
        }
        g.globalCompositeOperation = "destination-in"; g.drawImage(mb, 0, 0);
        ctx.save(); c.inside(); ctx.clip(); ctx.globalCompositeOperation = D ? "lighter" : "source-over"; ctx.globalAlpha = Math.min(1, (D ? .42 : .34) * A);
        ctx.drawImage(gb, 0, 0, W, H); ctx.restore(); ctx.globalAlpha = 1;
        // the edges glow softly where the band is: the card's soft glow, cut to the band
        const o2 = c.offx!, tint = tinted(c, P, t0 * .3, true);
        o2.globalCompositeOperation = "source-over"; o2.clearRect(0, 0, c.off!.width, c.off!.height); o2.drawImage(tint, 0, 0);
        const m2 = o2.createRadialGradient(M + Cw[0], M + Cw[1], Math.max(0, F - B * 1.4), M + Cw[0], M + Cw[1], F + B * .55);
        m2.addColorStop(0, "rgba(0,0,0,0)"); m2.addColorStop(.7, "rgba(0,0,0,1)"); m2.addColorStop(1, "rgba(0,0,0,0)"); // check-registry-ignore: the locked renderer paints a canvas
        o2.globalCompositeOperation = "destination-in"; o2.fillStyle = m2; o2.fillRect(0, 0, c.off!.width, c.off!.height);
        ctx.globalCompositeOperation = D ? "lighter" : "source-over"; ctx.globalAlpha = Math.min(1, (D ? .5 : .42) * A);
        ctx.drawImage(c.off!, -M, -M, W + 2 * M, H + 2 * M); ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over";
      }
      // the spot where the light came in: soft, early, gone before the band is halfway
      const fl = S * ss(0, .05, u) * (1 - ss(.08, .45, u));
      if (fl > .01) { ctx.globalCompositeOperation = D ? "lighter" : "source-over"; stamp(ctx, D ? mixRGB(P[0]!, WHITE, .4) : P[0]!, E[0], E[1], 46, (D ? .42 : .28) * fl); ctx.globalCompositeOperation = "source-over"; ctx.globalAlpha = 1; }
      for (const s of swaps) if (!s.done && F - B * .2 >= s.d!) { s.done = true; s.run?.(); }
      if (u >= .72 && !crossed) { crossed = true; swaps.forEach((s) => { if (!s.done) { s.done = true; s.run?.(); } }); res(); }
      if (u >= 1.02) c.stop();
    });
  });
}
// a pop, measured on the glowing recording's success: the element squashes wide as the light lands, stretches back, settles
// in about 0.6 s, with a brief red and blue split on its text. Tactile, never a wobble that lasts
/** The ring's springy pop on an element (k scales it). */
export function relayPop(el: HTMLElement | null | undefined, k = 1) {
  if (!el || reduced()) return;
  const sq = (x: number, y: number) => `scale(${(1 + (x - 1) * k).toFixed(4)}, ${(1 + (y - 1) * k).toFixed(4)})`, split = (a: number) => a ? `${-1.2 * k}px 0 rgba(255,70,120,${(.5 * a).toFixed(2)}), ${1.2 * k}px 0 rgba(70,150,255,${(.5 * a).toFixed(2)})` : "0 0 transparent"; // check-registry-ignore: the locked pop's split, as the lock writes it
  el.animate([
    { transform: "none", textShadow: split(0) },
    { transform: sq(1.034, .972), textShadow: split(1), offset: .18 },
    { transform: sq(.986, 1.022), textShadow: split(.45), offset: .38 },
    { transform: sq(1.008, .995), textShadow: split(.1), offset: .6 },
    { transform: sq(.998, 1.002), textShadow: split(0), offset: .8 },
    { transform: "none", textShadow: split(0) },
  ], { duration: ms("--pixilui-relay-pop") / relayClock.scale, easing: curveTok("--pixilui-relay-spring-curve") });
}
/** A press with a spring: in, a little past rest, back. */
export function relayPress(el: HTMLElement | null | undefined) {
  if (!el || reduced()) return;
  el.animate([{ transform: "scale(1)" }, { transform: "scale(.9)", offset: .16 }, { transform: "scale(1.07)", offset: .48 }, { transform: "scale(.985)", offset: .74 }, { transform: "scale(1)" }], { duration: ms("--pixilui-relay-press") / relayClock.scale, easing: curveTok("--pixilui-relay-spring-curve") });
}
const muted = (P: RGB[], D: boolean) => P.map((q) => { const l = (q[0]! + q[1]! + q[2]!) / 3; return mixRGB(mixRGB(q, [l, l, l], .32), [0, 0, 0], D ? .12 : 0); });
// our glass light, built like the locked glass coin and the toggles' candy glass, in layers that blend into each other:
// a soft drop below in the light's own color, light pooled low inside, the inner rim (strongest low and at the sides), a
// lens of light across the upper face and the top edge lit
function glassLight(c: CardCanvas, P: RGB[], rot: number, I: number, D: boolean, drift = 0) {
  if (I <= .005) return;
  const { ctx, W, H, rr } = c, comp = D ? "lighter" : "source-over", mid = palAt(P, .5);
  // the drop: the light's own color under the element, soft and close
  ctx.save(); ctx.globalCompositeOperation = comp; ctx.translate(W / 2, H + Math.min(H, 60) * .12); ctx.scale(1, Math.min(.45, (Math.min(H, 80) * .5) / (W * .5)));
  const dg = ctx.createRadialGradient(0, 0, 0, 0, 0, W * .5);
  dg.addColorStop(0, rgba(mid, (D ? .16 : .05) * I)); dg.addColorStop(.6, rgba(mid, (D ? .05 : .015) * I)); dg.addColorStop(1, rgba(mid, 0)); // check-registry-ignore: the locked renderer paints a canvas
  ctx.fillStyle = dg; ctx.fillRect(-W, -W, W * 2, W * 2); ctx.restore();
  // inside the glass
  ctx.save(); c.inside(); ctx.clip(); ctx.globalCompositeOperation = comp;
  const ph = Math.min(H * .75, 76), pg = ctx.createLinearGradient(0, H, 0, H - ph);
  pg.addColorStop(0, rgba(P[1]!, (D ? .26 : .1) * I)); pg.addColorStop(.45, rgba(palAt(P, .8), (D ? .09 : .035) * I)); pg.addColorStop(1, rgba(P[P.length - 1]!, 0)); // check-registry-ignore: the locked renderer paints a canvas
  ctx.fillStyle = pg; ctx.fillRect(0, 0, W, H);
  if (D) {
    // the lens: light across the upper face, fading slowly like light on a glass dome
    ctx.save(); ctx.translate(W / 2, -H * .08); ctx.scale(1, Math.min(1, (H * .62) / (W * .55)));
    const lg = ctx.createRadialGradient(0, 0, 0, 0, 0, W * .55);
    lg.addColorStop(0, `rgba(255,255,255,${.1 * I})`); lg.addColorStop(.45, `rgba(255,255,255,${.04 * I})`); lg.addColorStop(1, "rgba(255,255,255,0)"); // check-registry-ignore: the locked renderer paints a canvas
    ctx.fillStyle = lg; ctx.fillRect(-W, -W, W * 2, W * 2); ctx.restore();
    // the top edge, lit: brightest in the middle, gone at the corners
    const tg = ctx.createLinearGradient(rr, 0, W - rr, 0);
    tg.addColorStop(0, "rgba(255,255,255,0)"); tg.addColorStop(.5, `rgba(255,255,255,${.42 * I})`); tg.addColorStop(1, "rgba(255,255,255,0)"); // check-registry-ignore: the locked renderer paints a canvas
    ctx.fillStyle = tg; ctx.fillRect(rr * .6, .5, W - rr * 1.2, 1);
  }
  ctx.restore();
  rim(c, null, P, rot, I, D, false, drift, "glass");
}
// the glass light drawn once per element, palette and theme, so a frame only fades it in (the layers are many gradients)
function glassCached(c: CardCanvas, P: RGB[], D: boolean) {
  const key = P.map((x) => x.join(",")).join(";") + D;
  if (c.glassKey === key) return c.glassImg!;
  const b = c.glassImg || buffer(c.cv.width, c.cv.height), g = b.getContext("2d")!;
  g.setTransform(1, 0, 0, 1, 0, 0); g.clearRect(0, 0, b.width, b.height); g.setTransform(c.dpr, 0, 0, c.dpr, c.M * c.dpr, c.M * c.dpr);
  const real = c.ctx; c.ctx = g; glassLight(c, P, 0, 1, D); c.ctx = real;
  c.glassImg = b; c.glassKey = key; return b;
}
function glassFade(c: CardCanvas, P: RGB[], I: number, D: boolean) {
  if (I <= .005) return;
  const img = glassCached(c, P, D), { ctx } = c;
  ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalCompositeOperation = D ? "lighter" : "source-over"; ctx.globalAlpha = Math.min(1, I);
  ctx.drawImage(img, 0, 0); ctx.restore();
}
// the full arrival: two soft, uneven rings in muted tones of our glass colors flow out from where it lands, kept inside
// the element. With a ring (a moment that matters) the element gives a springy pop and its glass light rises and fades.
// Without (ring: false): it flows out of what was pressed (point, pointR), and with hold the working element's glass
// light takes over partway through, as the only layer of it
const bloomEase = (x: number) => curveOf("--pixilui-relay-bloom-curve")(x); // out of what was pressed: it blooms round it a moment, then flows away
function arrive(card: HTMLElement, o: RelayArriveOptions): Promise<void> {
  const fam = o.fam || "think", from = o.from || "left", ringOn = o.ring !== false, dur = o.dur ?? sec(ringOn ? "--pixilui-relay-ring" : "--pixilui-relay-rim"), M = o.margin ?? 30;
  const swaps: Swap[] = (o.swaps || []).map((s) => ({ ...s, done: false }));
  const c = cardCanvas(card, M, o.res), { ctx, r, dpr, W, H } = c;
  const E: Pt = o.point || (from === "left" ? [0, o.at ?? H / 2] : from === "right" ? [W, o.at ?? H / 2] : from === "top" ? [o.at ?? W / 2, 0] : [o.at ?? W / 2, H]);
  const B = o.band ?? Math.max(60, Math.min(W, H) * .75), pr = o.pointR ?? (o.point ? 16 : 0);
  const Rmax = Math.max(...([[0, 0], [W, 0], [0, H], [W, H]] as Pt[]).map((p) => Math.hypot(p[0] - E[0], p[1] - E[1])));
  for (const s of swaps) {
    if (s.el) { const e = s.el.getBoundingClientRect(); s.d = Math.hypot(e.left + e.width / 2 - r.left - E[0], e.top + e.height / 2 - r.top - E[1]); }
    else s.d = (s.at ?? .5) * Rmax;
  }
  const t0 = relayClock.t, fade = o.fade ?? sec(ringOn ? "--pixilui-relay-ring-fade" : "--pixilui-relay-rim-fade"), S = typeof o.strength === "number" ? o.strength : 1, ph = Math.random() * TAU;
  // the ring's colors around where it lands, made once per palette; a frame masks them with two uneven, blurred rings
  const q = W * H > 150000 ? .5 : 1; // a big element's ring is drawn at half size: it is all soft light
  let ringCol: HTMLCanvasElement | null = null, ringKey = "";
  const rb = buffer(W * q, H * q), rg = rb.getContext("2d")!, mb = buffer(W * q, H * q), mg = mb.getContext("2d")!;
  const ringOf = (P: RGB[], D: boolean) => {
    const key = P.map((x) => x.join(",")).join(";") + D;
    if (ringKey !== key) { ringKey = key; ringCol = buffer(W * q, H * q); const g = ringCol.getContext("2d")!; g.scale(q, q); g.beginPath(); g.roundRect(0, 0, W, H, c.rr); g.clip(); g.fillStyle = conic(g, muted(P, D), t0 * .35, E[0], E[1]); g.fillRect(0, 0, W, H); }
    return ringCol!;
  };
  let crossed = false, popped = false, handed = false;
  const r0 = pr * .9; // the wave starts at the edge of what was pressed
  return new Promise<void>((res) => {
    c.unsub = relayOnTick((t) => {
      const D = dark(card), P = pal(fam, card), u = (t - t0) / dur, tau = t - t0, comp = D ? "lighter" : "source-over";
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, W + 2 * M, H + 2 * M); ctx.translate(M, M);
      // the wave: two soft, uneven rings from points a little apart, flowing out from where it lands (the edge of what was
      // pressed, for the composer), in muted tones of our glass colors, kept inside the element
      const R = r0 + (Rmax + B * .6 - r0) * (ringOn ? waveEase : bloomEase)(clamp(u / .85));
      if (ringOn && o.pop !== false && !popped && u >= .03) { popped = true; relayPop(card, o.pop ?? 1); }
      const A = S * ss(0, ringOn ? .08 : .04, u) * (1 - ss(.5, .95, u));
      if (A > .003) {
        mg.setTransform(q, 0, 0, q, 0, 0); mg.globalCompositeOperation = "source-over"; mg.globalAlpha = 1; mg.clearRect(0, 0, W, H);
        for (const [k, sp, lag] of [[1, 1, 0], [-1, 1.3, 2.1]] as [number, number, number][]) {
          const off = B * (.16 + .08 * Math.sin(tau * 1.6 * sp + ph + lag)), a = ph + k * 1.7, cx = E[0] + Math.cos(a) * off, cy = E[1] + Math.sin(a) * off;
          const Rr = R + B * .12 * Math.sin(tau * 2 * sp + lag);
          const gr = mg.createRadialGradient(cx, cy, Math.max(0, Rr - B), cx, cy, Rr + B * .35);
          gr.addColorStop(0, "rgba(0,0,0,0)"); gr.addColorStop(.32, "rgba(0,0,0,.35)"); gr.addColorStop(.58, "rgba(0,0,0,.9)"); gr.addColorStop(.72, "rgba(0,0,0,.9)"); gr.addColorStop(.88, "rgba(0,0,0,.3)"); gr.addColorStop(1, "rgba(0,0,0,0)"); // check-registry-ignore: the locked renderer paints a canvas
          mg.globalAlpha = .6; mg.globalCompositeOperation = "lighter"; mg.fillStyle = gr; mg.fillRect(0, 0, W, H);
        }
        rg.setTransform(1, 0, 0, 1, 0, 0); rg.globalCompositeOperation = "source-over"; rg.clearRect(0, 0, rb.width, rb.height); rg.drawImage(ringOf(P, D), 0, 0);
        rg.globalCompositeOperation = "destination-in"; rg.drawImage(mb, 0, 0);
        ctx.globalCompositeOperation = comp; ctx.globalAlpha = Math.min(1, (D ? .7 : .45) * A);
        ctx.drawImage(rb, 0, 0, W, H); ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over";
      }
      // then the glass light: for a working element the hold takes over partway through, so there is only ever one layer of
      // it (one smooth rise, no second fade); otherwise the arrival's own glass rises, holds a moment and fades
      if (o.hold) { if (!handed && u >= .35) { handed = true; relayHold(card, true, fam); } }
      else glassFade(c, P, S * ss(.32, .72, u) * (1 - clamp((t - t0 - dur) / fade)) * (D ? .85 : .62), D);
      for (const s of swaps) if (!s.done && R - B * .35 >= s.d!) { s.done = true; s.run?.(); }
      if (u >= .7 && !crossed) { crossed = true; swaps.forEach((s) => { if (!s.done) { s.done = true; s.run?.(); } }); res(); }
      if (t - t0 > dur + fade + .05) c.stop();
    });
  });
}
// a working card keeps a slow light on its rim. It is drawn once into two still layers at two turns of its hue and the
// compositor cross-fades them, so a held rim costs nothing per frame; the drift follows the shared clock (Pause, Slow)
type Held = { on: boolean; card: HTMLElement; wrap: HTMLDivElement; a: CardCanvas; b: CardCanvas; fam: RelayFamily; fade?: Animation; drift?: Animation; anims?: Animation[]; stop(): void };
const held = new Map<HTMLElement, Held>();
function drawHeld(h: Held) {
  const D = dark(h.card), P = pal(h.fam, h.card);
  [h.a, h.b].forEach((c, turn) => {
    const { ctx, dpr, W, H, M } = c;
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, W + 2 * M, H + 2 * M); ctx.translate(M, M);
    // soft (the flow): only a blurred tint at the edge, no line
    if (strong(h.card)) glassLight(c, P, turn ? Math.PI : 0, D ? .95 : .66, D, turn);
    else rim(c, null, P, turn ? Math.PI : 0, D ? .2 : .17, D, false, turn, "soft");
  });
}
/**
 * A working element keeps a slow light (in Aurora only): soft, a faint tint at its edge; full, the glass light (a lit top
 * edge, a lens, pooled light and a soft drop). Turning it off fades it out.
 */
export function relayHold(card: HTMLElement, on: boolean, fam?: RelayFamily) {
  at(card);
  let h = held.get(card);
  const fadeTo = (to: number, d: number) => { const hh = h!; hh.fade?.cancel(); const fromO = +getComputedStyle(hh.wrap).opacity; hh.wrap.style.opacity = String(to);
    hh.fade = hh.wrap.animate([{ opacity: fromO }, { opacity: to }], { duration: d / relayClock.scale, easing: curveTok("--pixilui-relay-hold-curve") }); return hh.fade; };
  if (!on) {
    if (h && h.on) { h.on = false; const hh = h; fadeTo(0, ms("--pixilui-relay-hold-out")).onfinish = () => { if (!hh.on) hh.stop(); }; }
    return;
  }
  if (look(card) !== "aurora" || reduced()) return;
  if (h) { if (!h.on) { h.on = true; fadeTo(1, ms("--pixilui-relay-hold-again")); } return; }
  relayStart();
  const wrap = document.createElement("div"); wrap.className = relayClasses.light; wrap.setAttribute("aria-hidden", "true");
  Object.assign(wrap.style, { position: "absolute", inset: "0", width: "auto", height: "auto", opacity: 0, zIndex: -1 });
  const a = cardCanvas(card, 30), b = cardCanvas(card, 30);
  auroraLive.delete(a); auroraLive.delete(b);
  wrap.append(a.cv, b.cv); card.prepend(wrap);
  const nh: Held = { on: true, card, wrap, a, b, fam: fam || famOf.get(card) || "think",
    stop() { (nh.anims || [nh.drift!]).forEach((x) => x.cancel()); nh.fade?.cancel(); wrap.remove(); held.delete(card); auroraLive.delete(nh); } };
  h = nh;
  held.set(card, nh); auroraLive.add(nh);
  drawHeld(nh);
  nh.drift = b.cv.animate([{ opacity: 0 }, { opacity: 1 }], { duration: ms("--pixilui-relay-drift"), iterations: Infinity, direction: "alternate", easing: "ease-in-out", delay: -Math.random() * ms("--pixilui-relay-drift") }); // check-registry-ignore: the locked renderer paints a canvas (and its drift curve is the lock's)
  nh.drift.playbackRate = relayClock.scale; if (relayClock.paused) nh.drift.pause();
  nh.anims = [nh.drift];
  fadeTo(1, ms("--pixilui-relay-hold-in"));
}
// the held rims' drift follows Pause and Slow
let heldPaused: boolean | null = null, heldScale: number | null = null;
function syncHeld() {
  if (relayClock.paused === heldPaused && relayClock.scale === heldScale) return;
  heldPaused = relayClock.paused; heldScale = relayClock.scale;
  for (const h of held.values()) for (const x of h.anims || [h.drift!]) { x.playbackRate = heldScale; if (heldPaused) x.pause(); else x.play(); }
}
/** Redraws the held lights after a theme or tone switch. */
export function relayRefresh() { for (const h of held.values()) drawHeld(h); }
/** Clears every Aurora light on the page (a replay, a look switch). */
export function relayReset() { [...auroraLive].forEach((c) => c.stop()); held.clear(); }

// -------------------------------------------------------------------------------------------------------------------
// words that change under the wave: the locked blur swap (out --dur-exit with --blur-in, in --dur-move from --blur-swap, rising)

/** The locked blur swap, on the shared clock (Slow slows it). */
export function relaySwapText(el: HTMLElement | null | undefined, text: string) {
  if (!el || el.textContent === text) return;
  if (reduced()) { el.textContent = text; return; }
  const out = el.animate([{ opacity: 1, filter: "blur(0)" }, { opacity: 0, filter: `blur(${css("--pixilui-blur-in")})` }], { duration: ms("--pixilui-dur-exit") / relayClock.scale, easing: curveTok("--pixilui-relay-swap-out-curve"), fill: "forwards" });
  out.onfinish = () => { el.textContent = text; out.cancel();
    el.animate([{ opacity: 0, filter: `blur(${css("--pixilui-blur-swap")})`, transform: `translateY(${css("--pixilui-relay-swap-rise")})` }, { opacity: 1, filter: "blur(0)", transform: "none" }], { duration: ms("--pixilui-dur-move") / relayClock.scale, easing: curveTok("--pixilui-relay-swap-in-curve") }); };
}
/** A number that counts on the shared clock, then lands. */
export function relayCount(el: HTMLElement, from: number, to: number, fmt: (v: number) => string = (v) => v.toFixed(0), dur = sec("--pixilui-relay-count")): Promise<void> {
  if (reduced()) { el.textContent = fmt(to); return Promise.resolve(); }
  const t0 = relayClock.t, e = curveOf("--pixilui-relay-count-curve");
  return new Promise<void>((res) => { const off = relayOnTick((t) => { const u = clamp((t - t0) / dur); el.textContent = fmt(from + (to - from) * e(u)); if (u >= 1) { off(); res(); } }); });
}

/**
 * The engine in one object, under the lock's names (Relay.glimm is relayArrive): for code that drives a page the way the
 * locked pages do.
 */
export const relay = {
  clock: relayClock, wait: relayWait, onTick: relayOnTick, layer: relayLayer, glimm: relayArrive, hold: relayHold, reset: relayReset, refresh: relayRefresh,
  pop: relayPop, press: relayPress, look: (el?: Element | null) => look(el), swapText: relaySwapText, count: relayCount, tones: relayTones,
  reduced: () => reduced(), ease: { relay: relayEase, wave: waveEase }, start: relayStart,
};

// -------------------------------------------------------------------------------------------------------------------
// Aurora light: the engine's element face

/** glim (soft, when work arrives), rim (full, while it works) or ring (full, when it lands). */
export type AuroraLightEffect = "glim" | "rim" | "ring";

/** One play of an effect. */
export type AuroraLightPlayOptions = {
  /** The meaning (its palette). */
  fam?: RelayFamily;
  /** glim and ring: the edge it enters from (glim left, ring top). */
  from?: RelaySide;
  /** Where along that edge, px. */
  at?: number;
  /** rim: what was pressed, inside the element; the light flows out of its edge (else from the element's middle). */
  pressed?: Element | null;
  /** Changes fired as the light reaches each element. */
  swaps?: RelaySwap[];
};

/**
 * Lights an element once, the way the locked Aurora page does. glim: the soft glim from an edge. ring: a springy pop and a
 * muted ring from where it lands, then the glass light rises and fades. rim: the light flows out of what was pressed and the
 * element keeps its glass light until relayHold(el, false). The element is the light's host: positioned and its own
 * stacking context (AuroraLight does this for you).
 */
export function auroraLight(el: HTMLElement, effect: AuroraLightEffect, o: AuroraLightPlayOptions = {}): Promise<void> {
  if (effect === "glim") return relayArrive(el, { fam: o.fam, from: o.from ?? "left", at: o.at, swaps: o.swaps, look: "aurora", strength: "soft" });
  if (effect === "ring") return relayArrive(el, { fam: o.fam ?? "done", from: o.from ?? "top", at: o.at, swaps: o.swaps, look: "aurora", strength: "full" });
  const box = el.getBoundingClientRect();
  let point: Pt | undefined, pointR: number | undefined;
  if (o.pressed) {
    const b = o.pressed.getBoundingClientRect();
    point = [b.left - box.left + b.width / 2, b.top - box.top + b.height / 2];
    pointR = b.width / 2;
    relayPress(o.pressed as HTMLElement);
  }
  return relayArrive(el, { fam: o.fam ?? "think", from: o.from ?? "left", at: o.at, point, pointR, ring: false, hold: true, swaps: o.swaps, look: "aurora", strength: "full" });
}

export type AuroraLightHandle = {
  /** Plays the effect once (the rim keeps its light until working is false or stop()). */
  play(o?: AuroraLightPlayOptions): Promise<void>;
  /** Fades the held light out. */
  stop(): void;
  /** The springy pop alone. */
  pop(): void;
  element: HTMLDivElement | null;
};

export type AuroraLightProps = ComponentPropsWithoutRef<"div"> & {
  /** glim (soft, when work arrives), rim (full, while it works) or ring (full, when it lands). */
  effect?: AuroraLightEffect;
  /** The meaning, which picks the palette: think, find, make, code, wait, done, fail, holo, idle. */
  fam?: RelayFamily;
  /** Color (full strength wears the glass colors), Single (one hue per meaning) or Grey (silver; failures stay red). */
  tone?: RelayTone;
  /** Change it (a count, an id) to play the effect again; plays on mount when set. */
  playKey?: string | number;
  /** rim: whether the element is working (keeps the glass light; false fades it out). */
  working?: boolean;
  /** glim and ring: the edge the light enters from. */
  from?: RelaySide;
  /** Fires once the light has crossed (the moment the changes under it are done). */
  onCrossed?: () => void;
};

/**
 * Wraps an element in Aurora light: the glim, the rim or the ring, in Color, Single or Grey. The wrapper is the light's
 * host (positioned, its own stacking context, its content above the light); the light is canvas, hidden from assistive
 * technology, and takes no pointer.
 */
export const AuroraLight = forwardRef<AuroraLightHandle, AuroraLightProps>(function AuroraLight(
  { effect = "glim", fam, tone = "color", playKey, working, from, onCrossed, className, children, ...rest },
  ref,
) {
  const host = useRef<HTMLDivElement>(null);
  const crossed = useRef(onCrossed);
  useEffect(() => { crossed.current = onCrossed; }, [onCrossed]);
  const play = (o: AuroraLightPlayOptions = {}) => {
    const el = host.current;
    if (!el) return Promise.resolve();
    return auroraLight(el, effect, { fam, from, ...o }).then(() => crossed.current?.());
  };
  useImperativeHandle(ref, () => ({
    play,
    stop: () => { if (host.current) relayHold(host.current, false); },
    pop: () => relayPop(host.current),
    get element() { return host.current; },
  }));
  useEffect(() => {
    if (playKey === undefined) return;
    void play();
    // plays when the key changes
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [playKey]);
  useEffect(() => {
    const el = host.current;
    if (!el || effect !== "rim" || working === undefined) return;
    relayHold(el, working, fam);
  }, [working, effect, fam]);
  useEffect(() => { relayRefresh(); }, [tone]);
  useEffect(() => () => { if (host.current) relayHold(host.current, false); }, []);
  return (
    <div
      ref={host}
      data-look="aurora"
      data-aurora={effect === "glim" ? "soft" : "full"}
      data-flow-tone={tone}
      className={cn("pixilui-relay-host relative isolate [&>:not(.pixilui-relay-glimm)]:relative [&>:not(.pixilui-relay-glimm)]:z-[1]", className)}
      {...rest}
    >
      {children}
    </div>
  );
});
```

## Usage

When to use:

- Glim (soft): work arriving where the content is the subject, such as an agent card taking a task, a row finishing or a figure updating.
- Rim (full): the element the person is acting on while the agent works, such as the composer after Send or the one agent they are watching.
- Ring (full): one moment per screen that deserves it, such as money moved, a deploy live or a plan upgraded.
- Tone: Color for AI moments, Single for a product with one brand color (one hue per meaning), Grey for neutral screens (failures stay red).

When not to use:

- Work moving between cards along a wire: use Handoff flow (the same engine, with tracks).
- Loading or progress: use the text shimmer, the agent status or a meter. The light marks a moment, never a wait.
- Every element on a screen: one ring per screen, and the glim only where something really changed.

```tsx
import { useEffect, useRef, useState } from "react";
import { AgentStatus, type AgentStatusState } from "@/components/pixilui/agent-status";
import { AuroraLight, relaySwapText, relayWait, type AuroraLightEffect, type AuroraLightHandle, type RelayFamily } from "@/components/pixilui/aurora-light";

// The first option of each knob is the demo's default; the docs preview starts there.
export const knobs = {
  effect: ["glim", "ring", "rim"],
  tone: ["color", "single", "grey"],
} as const;

type Beat = { fam: RelayFamily; status: AgentStatusState; words: string };
// the locked page's cards: an agent taking work (glim), a refund landing (ring), a writer at work (rim)
const RUNS: Record<AuroraLightEffect, { title: string; meta: string; start: Beat; beats: Beat[] }> = {
  glim: {
    title: "Researcher", meta: "Looks things up", start: { fam: "find", status: "queued", words: "Waiting for work" },
    beats: [{ fam: "find", status: "running", words: "Searching the docs" }, { fam: "done", status: "done", words: "Found 3 sources" }, { fam: "wait", status: "waiting", words: "Needs your approval" }, { fam: "fail", status: "failed", words: "Search timed out" }],
  },
  ring: { title: "Refund", meta: "Stripe · to Lena Ortiz", start: { fam: "done", status: "queued", words: "$0.00" }, beats: [{ fam: "done", status: "done", words: "$42.00" }] },
  rim: { title: "Writer", meta: "Drafts replies", start: { fam: "make", status: "queued", words: "Waiting for work" }, beats: [{ fam: "make", status: "running", words: "Drafting the reply" }] },
};

/** One card from the locked Aurora page, lit by the chosen effect at the page's pace: its status and words change as the light reaches them. */
export default function AuroraLightDemo({ effect = "glim", tone = "color" }: KnobValues<typeof knobs>) {
  const light = useRef<AuroraLightHandle>(null);
  const words = useRef<HTMLSpanElement>(null);
  const badge = useRef<HTMLSpanElement>(null);
  const run = RUNS[effect];
  const [status, setStatus] = useState<AgentStatusState>(run.start.status);
  useEffect(() => {
    let live = true;
    const handle = light.current;
    (async () => {
      while (live) {
        setStatus(run.start.status);
        if (words.current) words.current.textContent = run.start.words;
        for (const b of run.beats) {
          await relayWait(effect === "ring" ? 1.4 : 1.2);
          if (!live) return;
          await light.current?.play({ fam: b.fam, swaps: [{ el: badge.current, run: () => live && setStatus(b.status) }, { el: words.current, run: () => relaySwapText(words.current, b.words) }] });
        }
        if (effect === "rim") {
          // the writer works under its held glass light, then finishes
          await relayWait(3.2);
          if (!live) return;
          light.current?.stop();
          setStatus("done");
          relaySwapText(words.current, "Reply sent");
        }
        await relayWait(effect === "glim" ? 1.6 : 2.6);
      }
    })();
    return () => { live = false; handle?.stop(); };
  }, [effect, run]);
  return (
    <div className="flex w-full max-w-md justify-center rounded-panel bg-surface p-10 elevation-raised">
      <AuroraLight key={effect} ref={light} effect={effect} tone={tone} className="grid w-full max-w-72 gap-3 rounded-control p-3.5" style={{ background: "var(--pixilui-surface-muted)" }}>
        <div className="grid min-w-0">
          <b className="truncate type-label font-medium text-foreground">{run.title}</b>
          <span className="truncate type-caption text-muted">{run.meta}</span>
        </div>
        <div className="flex min-h-6 items-center justify-between gap-2.5">
          <span ref={words} className={effect === "ring" ? "truncate type-subheading font-medium text-foreground tabular-nums" : "truncate type-caption text-secondary"} />
          <span ref={badge}>
            <AgentStatus state={status} size="sm" />
          </span>
        </div>
      </AuroraLight>
    </div>
  );
}
```

## Examples

None.

## API

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `effect` | `"glim" \| "rim" \| "ring"` | `"glim"` | glim (soft, when work arrives), rim (full, while it works) or ring (full, when it lands). |
| `fam` | `"think" \| "find" \| "make" \| "code" \| "wait" \| "done" \| "fail" \| "holo" \| "idle"` |  | The meaning, which picks the palette: think, find, make, code, wait, done, fail, holo, idle. |
| `tone` | `"color" \| "single" \| "grey"` | `"color"` | Color (full strength wears the glass colors), Single (one hue per meaning) or Grey (silver; failures stay red). |
| `playKey` | `string \| number` |  | Change it (a count, an id) to play the effect again; plays on mount when set. |
| `working` | `boolean` |  | rim: whether the element is working (keeps the glass light; false fades it out). |
| `from` | `"left" \| "right" \| "top" \| "bottom"` |  | glim and ring: the edge the light enters from. |
| `onCrossed` | `() => void` |  | Fires once the light has crossed (the moment the changes under it are done). |

Also accepts every native `<div>` attribute, and a ref to it.

## Keyboard

- `Tab`: Never takes focus: the light is not interactive and the wrapped element keeps its own controls.

## Accessibility

- The light is canvas, aria-hidden and takes no pointer: the element's own words and status carry the change.
- Changes fired by swaps are real DOM changes, so assistive technology hears the new status and words.
- Reduced motion (the OS setting, or data-reduced on <html>): no light; the changes run at once.

## Motion

- Glim: a blurred band with a curved, two-lobed front crosses in 1250ms on cubic-bezier(.5, .05, .3, 1), holding at the entry edge a moment, fading as it goes.
- Ring: a 620ms springy pop as a muted ring grows over 2400ms, then the glass light rises, holds and fades over 1600ms.
- Rim: the wave blooms out of what was pressed over 2000ms and the glass light takes over at a third (900ms rise, 600ms out); it drifts in hue every 6400ms while it holds.
- Every light runs on one shared clock with Handoff flow, so pausing or slowing it holds them all.

## Responsive

- Any element size: the light is measured from the element when it plays; an element over 150,000 square px draws its ring at half resolution.

## Performance

- Soft light is stamped sprites and gradients in 1x buffers, never a per-frame canvas filter; a held rim is two still layers the compositor cross-fades.

## Notes for AI

- <AuroraLight effect="ring" ref={light}>...card...</AuroraLight> then light.current.play({ fam: "done", swaps: [{ el: statusEl, run: () => setStatus("done") }] }). Or playKey={n} to replay on change.
- Rim: play({ pressed: sendButton }) flows the light out of the button and holds the glass light; working={false} or stop() fades it.
- auroraLight(el, "glim" | "rim" | "ring", options) lights any positioned element with isolation: isolate, without the wrapper.
- Families pick the palette: think, find, make, code, wait, done, fail, holo, idle. The full failure light is red only (--pixilui-aurora-glass-fail-*).
- Every color and timing is a token: --pixilui-aurora-<family>-light|dark (soft), --pixilui-aurora-glass-<family>-light|dark (full), --pixilui-relay-* (timings).
- The engine is exported too (relayArrive, relayHold, relayLayer, relayClock, relaySwapText, relayCount, relay): Handoff flow and Toast run on it.

## Related

- [Handoff flow](https://pixilui.com/components/handoff-flow/markdown): Work moving between agents and tools: a handoff runs along the wire between two cards and lands as light that crosses the receiver, changing it as it passes. Cells or Aurora, in Color, Single or Grey.
- [Toast](https://pixilui.com/components/toast/markdown): Brief news at the corner on the locked float: a delete that waits while its red rim runs out, the agent asking one question, a run that stopped, money moved, and the everyday note, done, info, warning, error and save, in a stack that fans out.
- [Text shimmer](https://pixilui.com/components/text-shimmer/markdown): A band of light that sweeps through live words at an even pace, in grey or in the blue, violet and pink glint, while the words keep their own color.
