# Swarm: Particle Text Animation for React

> Your word or logo, set in dots that come in from the edge of the box. They gather along the frame, bow inward on hairline trails and lock into a honeycomb, most of them solid and a few left as hollow rings. Raise `fill` and solid dots fly in onto the rings, like a progress bar in your mark's shape; give it a new word and the same dots reroute to it.

Particle Text Animation for React: dots fly in on hairline trails and pack into your word or logo. 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/swarm
- Tags: Text, Canvas, Hero
- 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/swarm.tsx`, and the CLI also adds `lib/utils.ts` (the `cn` helper) and installs the npm dependencies:

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

Or install by URL, without registering the namespace:

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

## Usage

The main demo shows typical usage.

### Product Tabs

Three product names on tabs; each one reroutes the same dots into the next word.

Install this demo, with the component included:

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

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

import * as React from "react";

import { Swarm } from "@/components/ui/swarm";

// Each product has its own pair of colors; the dots blend from the first to the second across the stage.
const PRODUCTS = [
  {
    id: "ingest",
    word: "ingest",
    line: "Pulls events from forty sources into one stream.",
    from: "text-[#ff5a1f] dark:text-[#ff7a45]",
    to: "text-[#ff2d87] dark:text-[#ff5ca8]",
    swatch: "bg-[#ff5a1f] dark:bg-[#ff7a45]",
  },
  {
    id: "route",
    word: "route",
    line: "Hands every event to whichever model is free.",
    from: "text-[#7c3aed] dark:text-[#a78bfa]",
    to: "text-[#00a3ff] dark:text-[#38bdf8]",
    swatch: "bg-[#7c3aed] dark:bg-[#a78bfa]",
  },
  {
    id: "serve",
    word: "serve",
    line: "Answers from the nearest of nine regions.",
    from: "text-[#00b25d] dark:text-[#34d399]",
    to: "text-[#f59e0b] dark:text-[#fbbf24]",
    swatch: "bg-[#00b25d] dark:bg-[#34d399]",
  },
];

// Seconds a settled word holds before the next one, until the visitor picks one.
const HOLD = 2.4;

export function SwarmDemo() {
  const [index, setIndex] = React.useState(0);
  const [picked, setPicked] = React.useState(false);
  const timer = React.useRef(0);
  const tabs = React.useRef<(HTMLButtonElement | null)[]>([]);
  const product = PRODUCTS[index];

  React.useEffect(() => () => window.clearTimeout(timer.current), []);

  // Once every dot has landed, wait a beat and move on, unless the visitor has taken over.
  const onSettle = React.useCallback(() => {
    window.clearTimeout(timer.current);
    if (picked || window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    timer.current = window.setTimeout(() => setIndex((i) => (i + 1) % PRODUCTS.length), HOLD * 1000);
  }, [picked]);

  const pick = (i: number) => {
    window.clearTimeout(timer.current);
    setPicked(true);
    setIndex(i);
  };

  const onKeyDown = (event: React.KeyboardEvent) => {
    const step = event.key === "ArrowRight" ? 1 : event.key === "ArrowLeft" ? -1 : 0;
    if (!step) return;
    event.preventDefault();
    const next = (index + step + PRODUCTS.length) % PRODUCTS.length;
    pick(next);
    tabs.current[next]?.focus();
  };

  return (
    <div className="w-full max-w-3xl overflow-hidden rounded-2xl border border-zinc-950/10 bg-white text-zinc-950 dark:border-white/10 dark:bg-zinc-950 dark:text-white">
      <div className="flex items-center justify-between gap-4 px-5 py-3.5 font-mono text-[11px] tracking-wide text-zinc-500 uppercase dark:text-zinc-400">
        <span className="flex items-center gap-2 text-zinc-950 dark:text-white">
          <span aria-hidden className={`size-2 transition-colors duration-300 ${product.swatch}`} />
          Kestrel
        </span>
        <span aria-hidden>[ 0{index + 1} / 0{PRODUCTS.length} ]</span>
      </div>

      <Swarm
        id="swarm-demo-panel"
        role="tabpanel"
        aria-labelledby={`swarm-demo-tab-${product.id}`}
        text={product.word}
        label={product.word}
        dotClassName={product.from}
        gradientClassName={product.to}
        onSettle={onSettle}
        className="aspect-[4/3] border-y border-zinc-950/10 bg-zinc-100/70 sm:aspect-[16/8] dark:border-white/10 dark:bg-white/[0.03]"
      >
        {/* Registration marks: two corner ticks and two squares, the way a proof sheet is marked. */}
        <span aria-hidden className="absolute top-3 left-3 size-3 border-t border-l border-zinc-400 dark:border-zinc-600" />
        <span aria-hidden className="absolute right-3 bottom-3 size-3 border-r border-b border-zinc-400 dark:border-zinc-600" />
        <span aria-hidden className="absolute top-[18%] right-[9%] size-2 border border-zinc-400 dark:border-zinc-600" />
        <span aria-hidden className={`absolute bottom-[16%] left-[8%] size-2 transition-colors duration-300 ${product.swatch}`} />
      </Swarm>

      <div className="flex flex-col gap-4 px-5 py-4 sm:flex-row sm:items-center sm:justify-between">
        <p aria-live="polite" className="font-mono text-xs leading-relaxed text-zinc-600 dark:text-zinc-400">
          {product.line}
        </p>
        <div role="tablist" aria-label="Kestrel products" onKeyDown={onKeyDown} className="flex shrink-0 gap-1">
          {PRODUCTS.map((p, i) => (
            <button
              key={p.id}
              ref={(el) => {
                tabs.current[i] = el;
              }}
              id={`swarm-demo-tab-${p.id}`}
              type="button"
              role="tab"
              aria-selected={i === index}
              aria-controls="swarm-demo-panel"
              tabIndex={i === index ? 0 : -1}
              onClick={() => pick(i)}
              className="flex items-center gap-1.5 rounded-full px-3.5 py-1.5 font-mono text-xs text-zinc-500 transition-colors hover:text-zinc-950 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-zinc-950 aria-selected:bg-zinc-950 aria-selected:text-white dark:text-zinc-400 dark:hover:text-white dark:focus-visible:outline-white dark:aria-selected:bg-white dark:aria-selected:text-zinc-950"
            >
              <span aria-hidden className={`size-1.5 rounded-full ${p.swatch}`} />
              {p.word}
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}
```

## Examples

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

### Preloader

A workspace loading: the brand mark starts as hollow rings and fills with solid dots as the load reports progress.

Install this demo, with the component included:

```bash
npx shadcn@latest add @keyframeui/swarm-loader-demo
```

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

import * as React from "react";

import { Swarm } from "@/components/ui/swarm";

// Perihel's mark: an orbit broken at the top right, with its planet in the gap.
const MARK =
  "M22.625 9.153A11 11 0 1 1 14.847 1.375L13.812 5.239A7 7 0 1 0 18.761 10.188Z" +
  "M18.364 3.036A2.6 2.6 0 1 1 18.364 8.236A2.6 2.6 0 1 1 18.364 3.036Z";

// What loading reports, as the share done, and how long each step takes in ms.
const STEPS: [number, number][] = [
  [0.06, 500],
  [0.19, 420],
  [0.33, 640],
  [0.41, 300],
  [0.58, 520],
  [0.66, 380],
  [0.83, 600],
  [0.92, 360],
  [1, 480],
];

export function SwarmLoaderDemo() {
  const [progress, setProgress] = React.useState(0);
  const [ready, setReady] = React.useState(false);
  const [run, setRun] = React.useState(0);

  // Walk the steps; a new run starts over from nothing.
  React.useEffect(() => {
    const timers: number[] = [];
    let at = 700;
    for (const [share, ms] of STEPS) {
      at += ms;
      timers.push(window.setTimeout(() => setProgress(share), at));
    }
    return () => timers.forEach(window.clearTimeout);
  }, [run]);

  const onSettle = React.useCallback(() => {
    if (progress >= 1) setReady(true);
  }, [progress]);

  const again = () => {
    setReady(false);
    setProgress(0);
    setRun((r) => r + 1);
  };

  const percent = Math.round(progress * 100);

  return (
    <div className="w-full max-w-md overflow-hidden rounded-2xl border border-zinc-950/10 bg-white text-zinc-950 dark:border-white/10 dark:bg-zinc-950 dark:text-white">
      <Swarm
        path={MARK}
        viewBox="0 0 24 24"
        fill={progress}
        dotSize={5}
        gap={1.5}
        label="Perihel"
        dotClassName="text-[#ff2d87] dark:text-[#ff5ca8]"
        gradientClassName="text-[#ff8a00] dark:text-[#ffa53d]"
        ringClassName="text-zinc-300 dark:text-zinc-700"
        onSettle={onSettle}
        className="aspect-square bg-zinc-100/70 dark:bg-white/[0.03]"
      />
      <div className="flex items-center justify-between gap-4 border-t border-zinc-950/10 px-5 py-4 dark:border-white/10">
        <div className="min-w-0">
          <p className="text-sm font-medium tracking-tight">{ready ? "Your workspace is ready" : "Opening your workspace"}</p>
          <p className="mt-0.5 font-mono text-[11px] text-zinc-500 uppercase dark:text-zinc-400">
            {ready ? "3 boards · 41 cards synced" : "Syncing boards and cards"}
          </p>
        </div>
        {ready ? (
          <button
            type="button"
            onClick={again}
            className="shrink-0 rounded-full bg-zinc-950 px-3.5 py-1.5 font-mono text-xs text-white transition-colors hover:bg-zinc-800 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#e0136f] dark:bg-white dark:text-zinc-950 dark:hover:bg-zinc-200 dark:focus-visible:outline-[#ff5ca8]"
          >
            Load again
          </button>
        ) : (
          <span
            role="progressbar"
            aria-label="Loading"
            aria-valuemin={0}
            aria-valuemax={100}
            aria-valuenow={percent}
            className="shrink-0 font-mono text-sm text-[#e0136f] tabular-nums dark:text-[#ff5ca8]"
          >
            {String(percent).padStart(2, "0")}%
          </span>
        )}
      </div>
    </div>
  );
}
```

### 404 Page

A not-found page whose number is two-thirds solid; the hollow rings are the part that never arrived, and late dots keep drifting in.

Install this demo, with the component included:

```bash
npx shadcn@latest add @keyframeui/swarm-404-demo
```

```tsx title="components/swarm-404-demo.tsx"
import { Swarm } from "@/components/ui/swarm";

export function Swarm404Demo() {
  return (
    <div className="w-full max-w-3xl overflow-hidden rounded-2xl border border-zinc-950/10 bg-white text-zinc-950 dark:border-white/10 dark:bg-zinc-950 dark:text-white">
      {/* Most of the number made it; the hollow rings are the parts that didn't, and late dots keep drifting in. */}
      <Swarm
        text="404"
        fill={0.68}
        dotSize={7}
        gap={2}
        label="404"
        dotClassName="text-[#7c3aed] dark:text-[#a78bfa]"
        gradientClassName="text-[#ff2d87] dark:text-[#ff5ca8]"
        className="aspect-[4/3] bg-zinc-100/70 sm:aspect-[2/1] dark:bg-white/[0.03]"
      />
      <div className="flex flex-col gap-5 border-t border-zinc-950/10 px-6 py-6 sm:flex-row sm:items-end sm:justify-between dark:border-white/10">
        <div>
          <h2 className="text-xl font-semibold tracking-tight text-balance">Part of this page never arrived.</h2>
          <p className="mt-2 max-w-sm text-sm leading-relaxed text-zinc-600 dark:text-zinc-400">
            The link may be old, or the page moved when we reorganised the docs. Everything else is where you left it.
          </p>
        </div>
        <div className="flex shrink-0 gap-2">
          <a
            href="#"
            className="rounded-full bg-zinc-950 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-zinc-800 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#7c3aed] dark:bg-white dark:text-zinc-950 dark:hover:bg-zinc-200 dark:focus-visible:outline-[#a78bfa]"
          >
            Back to docs
          </a>
          <a
            href="#"
            className="rounded-full border border-zinc-950/10 px-4 py-2 text-sm font-medium text-zinc-700 transition-colors hover:bg-zinc-950/5 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#7c3aed] dark:border-white/15 dark:text-zinc-300 dark:hover:bg-white/10 dark:focus-visible:outline-[#a78bfa]"
          >
            Report link
          </a>
        </div>
      </div>
    </div>
  );
}
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `text` | `string` |  | A word or short line for the dots to form. Use `\n` for a second line. Set in `textFont` at weight 800 and fitted inside the box. |
| `textFont` | `string` | `"ui-sans-serif, system-ui, sans-serif"` | Font family `text` is set in before it's turned into dots. It's measured again once your web fonts load. |
| `path` | `string` |  | An SVG path (`d`) for the dots to form, such as your logo mark, read against `viewBox`. Used when there's no `text`; with neither, the dots form a disc. |
| `viewBox` | `string` | `"0 0 24 24"` | The coordinate box `path` is drawn in, like an SVG's `viewBox`. |
| `fill` | `number` | `0.9` | Share of the mark that's solid, from 0 to 1; the rest are hollow rings, in a fixed random order. Raise it and solid dots fly in from the edge onto the rings, lower it and they fly out and leave their rings: a progress bar in the shape of your mark. `1` for a solid mark. |
| `dotSize` | `number` | `6` | Diameter of a landed dot, in px. The lattice adjusts to the box: past about 4,200 dots it widens, dots included, so it stays smooth, and under about 900 it tightens (down to half this size) so a word in a phone-sized box still reads. |
| `gap` | `number` | `1.5` | Space between neighbouring dots, in px. |
| `trails` | `boolean` | `true` | Draw each dot's path behind it as a hairline that reels in once it lands. |
| `drift` | `boolean` | `true` | Once settled, keep a few late dots coming in from the corners on long trails, so the mark never sits dead still. Off under reduced motion. |
| `duration` | `number` | `1.15` | Seconds a dot takes to fly from the edge to its slot on the way in. Each one varies by a quarter either way. |
| `stagger` | `number` | `0.9` | Seconds between the first dot leaving the edge and the last, on the way in. |
| `trailLength` | `number` | `0.6` | How far a trail lags behind its dot, as a share of the flight, from 0 (no trail) to 1 (the whole path so far). |
| `label` | `string` |  | Describes the mark for screen readers. Defaults to `text`; without either, the swarm is decorative and hidden from them. |
| `dotClassName` | `string` | `"text-[#2f45e8] dark:text-[#8b98ff]"` | A `text-*` color for the dots, rings and trails. The canvas reads it, so `dark:` variants work. |
| `gradientClassName` | `string` |  | A second `text-*` color. Dots, rings and trails blend from `dotClassName` at the top left to this at the bottom right, by where each one is, so a dot changes color as it crosses the box. One gradient for the whole canvas, so it costs nothing extra. |
| `ringClassName` | `string` |  | A `text-*` color for the hollow rings alone, so what's still to come reads apart from what's solid, like a muted gray under a bright fill. Without it, rings take the dots' color. |
| `canvasClassName` | `string` |  | Classes for the canvas. It fills the box by default and the mark is fitted inside it, so position it to set the mark in one part of the box. |
| `onSettle` | `() => void` |  | Called each time every dot has landed: after the entrance, a new mark or a new `fill`. Use it to reveal the page behind a preloader or move to the next word. |
| `children` | `React.ReactNode` |  | Content drawn over the dots. |
| `className` | `string` |  | Classes for the box. Give it a size: the mark is fitted inside it, about 9% in from each edge. |

## What to keep

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

- Every dot's position is a closed-form function of time (a cubic from where it starts to its slot), so landings are exact, a change mid-flight starts from where the dot is, and the loop stops once nothing moves.
- Dots land on a hex lattice inside the mark and never overlap there. Settled dots are drawn once into an offscreen canvas and blitted; moving dots, rings and trails are one path each, painted with one color or one canvas-wide gradient, so a dot takes the color of the spot it's in.
- A trail is the dot's own curve drawn from a point that lags behind it, so it reels in when the dot lands. Never a fading smear: the canvas is transparent over your background.
- New dots come in from the box's edge, behind their slot as seen from the middle; dots that leave go back out the same way. Nothing appears out of thin air mid-box.
- Under reduced motion nothing travels: the mark crossfades in place and drift is off.

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/swarm.tsx"
"use client";

import * as React from "react";

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

/**
 * Keep:
 * - Every dot's position is a closed-form function of time (a cubic from where it starts to its
 *   slot), so landings are exact, a change mid-flight starts from where the dot is, and the loop
 *   stops once nothing moves.
 * - Dots land on a hex lattice inside the mark and never overlap there. Settled dots are drawn once
 *   into an offscreen canvas and blitted; moving dots, rings and trails are one path each, painted
 *   with one color or one canvas-wide gradient, so a dot takes the color of the spot it's in.
 * - A trail is the dot's own curve drawn from a point that lags behind it, so it reels in when the
 *   dot lands. Never a fading smear: the canvas is transparent over your background.
 * - New dots come in from the box's edge, behind their slot as seen from the middle; dots that
 *   leave go back out the same way. Nothing appears out of thin air mid-box.
 * - Under reduced motion nothing travels: the mark crossfades in place and drift is off.
 */
const TIMING = {
  /** Dots gathering along the edge before the first one leaves, in seconds. */
  gather: 0.45,
  /** A dot's flight from the edge to its slot, in seconds (the `duration` prop). Each one varies ±25%. */
  flight: 1.15,
  /** Seconds between the first launch and the last (the `stagger` prop). */
  spread: 0.9,
  /** Longest a dot waits on the edge before it leaves, in seconds. */
  lead: 0.4,
  /** A waiting dot growing in on the edge, in seconds. */
  pop: 0.18,
  /** Share of its flight time a trail lags behind its dot (the `trailLength` prop). */
  trail: 0.6,
  /** A new mark: each dot's flight and the spread of launches, in seconds. */
  reroute: { flight: 1.05, spread: 0.4 },
  /**
   * `fill` changing: each dot's flight, and the spread of launches in seconds, which grows by
   * `step` per square root of the dots that change, up to `spread`.
   */
  refill: { flight: 0.95, spread: 0.6, step: 0.04 },
  /** Drift at rest: seconds between late dots (randomized ±40%), and a late dot's flight in seconds. */
  drift: { every: 0.45, flight: 2.6 },
  /** Under reduced motion, the crossfade that replaces every flight, in seconds. */
  fade: 0.3,
} as const;

/* ─────────────────────────────────────────────────────────
 * SWARM STORYBOARD
 *
 *  rest     before it's seen, an empty box. Settled, your mark
 *           (a word, an SVG path, or a disc) set in dots on a
 *           hex lattice, most solid, a few hollow rings
 *  gather   the first time a quarter of it scrolls into view,
 *           dots pop onto the box's edge, up to three deep,
 *           each one roughly behind the slot it's bound for
 *  flight   0.45s in they start leaving, spread over 0.9s:
 *           each one bows in along a cubic for about 1.15s,
 *           easing out of the edge and into its slot, growing
 *           from 62% to full size on the way. Its trail is its
 *           own path, lagging 60% of the flight behind, so a
 *           burst reads as hairlines converging on the mark
 *  land     a dot locks onto its slot exactly; the trail
 *           behind it reels in over the next 0.7s
 *  drift    settled, a late dot leaves a corner every ~0.45s
 *           and takes 2.6s to merge into a solid slot, so a
 *           few long hairlines are always coming in
 *  fill     `fill` is the solid share; the rest are hollow
 *           rings, in a fixed random order. Raise it and solid
 *           dots fly in from the edge onto the rings; lower it
 *           and solid dots fly out, leaving their rings behind
 *  reroute  a new mark: dots already in the box fly to the new
 *           slots (left to right, column by column, so letters
 *           trade with their neighbours), extras leave through
 *           the edge, and missing ones come in from it. 1.05s
 *           flights spread over 0.4s; a change mid-flight
 *           starts from where each dot is
 *  resize   the lattice is laid again and the mark snaps to
 *           its settled state; nothing replays
 *  sleep    off screen or in a hidden tab nothing draws and
 *           drift stops; flights finish on time while hidden
 *  reduced  no flights and no drift: the mark crossfades in
 *           over 0.3s, and a new mark or fill crossfades too
 * ───────────────────────────────────────────────────────── */

const SWARM = {
  pad: 0.09, // share of the box kept clear around the mark
  maxDots: 4200, // past this many slots the lattice widens, dots and all
  minDots: 900, // under this many the lattice tightens, so a mark in a small box still reads
  minShrink: 0.5, // but dots never get smaller than this share of `dotSize`
  sample: 0.5, // mask samples per CSS px
  band: 3, // rows deep the edge band can stack
  jitter: 0.7, // rad, spread of a dot's start around the line from the middle through its slot
  swirl: [0.1, 0.34], // sideways bow of an edge flight, share of its length
  swirlShort: [0.04, 0.16], // and of a flight inside the box (reroute, leaving)
  launch: 0.3, // share of its length a flight heads straight in before it bends
  land: 0.22, // share of its length a flight comes straight in at the end
  flightSize: 0.62, // a dot's size mid-flight, share of its landed size
  ring: 1, // px, stroke of a hollow ring
  trailWidth: 0.6, // px
  trailAlpha: 0.32, // opacity of the hairline trails
  corner: 0.32, // rad, spread of a late dot's start around its corner
  maxDpr: 2,
} 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) => (t < 0 ? 0 : t > 1 ? 1 : t);
/** In-out cubic: a dot eases off the edge and settles into its slot without a snap. */
const ease = (u: number) => (u < 0.5 ? 4 * u * u * u : 1 - (-2 * u + 2) ** 3 / 2);

/** A seeded generator, so the same mark always fills in the same order. */
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;
  };
}

/** Point on the cubic `c` (x0 y0 x1 y1 x2 y2 x3 y3) at parameter t, written into `out`. */
function at(c: Float64Array, t: number, out: Float64Array) {
  const m = 1 - t;
  const a = m * m * m;
  const b = 3 * m * m * t;
  const d = 3 * m * t * t;
  const e = t * t * t;
  out[0] = a * c[0] + b * c[2] + d * c[4] + e * c[6];
  out[1] = a * c[1] + b * c[3] + d * c[5] + e * c[7];
}

/** Adds the piece of cubic `c` between parameters a and b to `path` (de Casteljau, twice). */
function addPiece(path: Path2D, c: Float64Array, a: number, b: number) {
  const lerp = (p: number, q: number, t: number) => p + (q - p) * t;
  // Left part of the curve, up to b.
  const q0x = lerp(c[0], c[2], b), q0y = lerp(c[1], c[3], b);
  const q1x = lerp(c[2], c[4], b), q1y = lerp(c[3], c[5], b);
  const q2x = lerp(c[4], c[6], b), q2y = lerp(c[5], c[7], b);
  const r0x = lerp(q0x, q1x, b), r0y = lerp(q0y, q1y, b);
  const r1x = lerp(q1x, q2x, b), r1y = lerp(q1y, q2y, b);
  const sx = lerp(r0x, r1x, b), sy = lerp(r0y, r1y, b);
  // Right part of that, from a.
  const t = b > 0 ? a / b : 0;
  const u0x = lerp(c[0], q0x, t), u0y = lerp(c[1], q0y, t);
  const u1x = lerp(q0x, r0x, t), u1y = lerp(q0y, r0y, t);
  const u2x = lerp(r0x, sx, t), u2y = lerp(r0y, sy, t);
  const v0x = lerp(u0x, u1x, t), v0y = lerp(u0y, u1y, t);
  const v1x = lerp(u1x, u2x, t), v1y = lerp(u1y, u2y, t);
  path.moveTo(lerp(v0x, v1x, t), lerp(v0y, v1y, t));
  path.bezierCurveTo(v1x, v1y, u2x, u2y, sx, sy);
}

type Source =
  | { kind: "disc" }
  | { kind: "text"; text: string; font: string }
  | { kind: "path"; d: string; box: [number, number, number, number] };

function keyOf(s: Source) {
  return s.kind === "disc" ? "disc" : s.kind === "text" ? `text:${s.font}:${s.text}` : `path:${s.box.join(",")}:${s.d}`;
}

type Options = {
  fill: number;
  dotSize: number;
  gap: number;
  trails: boolean;
  drift: boolean;
  flight: number;
  spread: number;
  trail: number;
  reduced: boolean;
};

const EMPTY = 0;
const HOLLOW = 1;
const SOLID = 2;

const LAND = 0; // flies to a slot and takes it
const LEAVE = 1; // flies out through the edge and is gone
const STRAY = 2; // a late dot that merges into a solid slot

type Dot = {
  slot: number;
  kind: number; // HOLLOW or SOLID
  role: number;
  c: Float64Array; // its curve
  appear: number; // s, when it shows (on the edge, for one coming in)
  t0: number; // s, launch
  dur: number; // s, flight
};

function createSwarm() {
  let root: HTMLElement | null = null;
  let canvas: HTMLCanvasElement | null = null;
  let ctx: CanvasRenderingContext2D | null = null;
  let probes: { dot: HTMLElement; to: HTMLElement; ring: HTMLElement } | null = null;
  let tones = { gradient: false, ring: false };
  let color = "currentColor";
  let colorTo: string | null = null; // the far end of the blend, with `gradientClassName`
  let ringColor: string | null = null; // hollow rings in a color of their own, with `ringClassName`
  let options: Options = {
    fill: 0.9,
    dotSize: 6,
    gap: 1.5,
    trails: true,
    drift: true,
    flight: TIMING.flight,
    spread: TIMING.spread,
    trail: TIMING.trail,
    reduced: false,
  };
  let source: Source = { kind: "disc" };
  let onSettle: (() => void) | null = null;

  let width = 0;
  let height = 0;
  let dpr = 1;

  // The lattice: slot positions, the order they turn solid in, and what each holds now.
  let xs = new Float32Array(0);
  let ys = new Float32Array(0);
  let rank = new Int32Array(0);
  let state = new Uint8Array(0);
  let inbound = new Uint8Array(0); // a LAND dot is on its way to this slot
  let count = 0;
  let solid = 0; // slots that are solid once settled
  let radius = 3; // px, a landed dot
  let pitch = 7.5; // px between neighbouring slots

  let dots: Dot[] = [];
  let cache: HTMLCanvasElement | null = null; // settled slots, blitted every frame
  let cacheDirty = true;
  let prev: HTMLCanvasElement | null = null; // what the mark looked like before a reduced crossfade
  let fadeT0 = -1;

  let raf = 0;
  let inView = false;
  let pageVisible = true;
  let played = false;
  let settling = false;
  let relayPending = false; // web fonts arrived mid-flight: lay the text again once it settles
  let driftTimer = 0;
  let random = seeded("swarm");
  const point = new Float64Array(2);
  const cleanups: (() => void)[] = [];

  const now = () => performance.now() / 1000;
  const awake = () => inView && pageVisible;

  function readColors() {
    if (!probes) return;
    color = getComputedStyle(probes.dot).color;
    colorTo = tones.gradient ? getComputedStyle(probes.to).color : null;
    ringColor = tones.ring ? getComputedStyle(probes.ring).color : null;
    cacheDirty = true;
    draw();
  }

  /**
   * The dots' paint for a context: one color, or a blend from the top left corner to the bottom
   * right one, in CSS px, so every dot takes the color of the spot it's in.
   */
  function paint(c: CanvasRenderingContext2D) {
    if (!colorTo) return color;
    const g = c.createLinearGradient(0, 0, width, height);
    g.addColorStop(0, color);
    g.addColorStop(1, colorTo);
    return g;
  }

  /** The mark drawn white on a small canvas, read back as alpha. */
  function mask() {
    const k = SWARM.sample;
    const w = Math.max(1, Math.round(width * k));
    const h = Math.max(1, Math.round(height * k));
    const c = document.createElement("canvas");
    c.width = w;
    c.height = h;
    const s = c.getContext("2d", { willReadFrequently: true });
    if (!s) return null;
    const innerW = width * (1 - SWARM.pad * 2);
    const innerH = height * (1 - SWARM.pad * 2);
    s.fillStyle = "#fff";
    if (source.kind === "disc") {
      s.setTransform(k, 0, 0, k, 0, 0);
      s.beginPath();
      s.arc(width / 2, height / 2, Math.min(innerW, innerH) / 2, 0, Math.PI * 2);
      s.fill();
    } else if (source.kind === "text") {
      const lines = source.text.split("\n");
      const base = 100;
      s.font = `800 ${base}px ${source.font}`;
      const metrics = lines.map((line) => s.measureText(line));
      const ascent = Math.max(...metrics.map((m) => m.actualBoundingBoxAscent));
      const descent = Math.max(...metrics.map((m) => m.actualBoundingBoxDescent));
      const lineHeight = (ascent + descent) * 1.08;
      const textW = Math.max(...metrics.map((m) => m.actualBoundingBoxLeft + m.actualBoundingBoxRight));
      const textH = ascent + descent + lineHeight * (lines.length - 1);
      const scale = Math.min(innerW / textW, innerH / textH);
      const ox = (width - textW * scale) / 2;
      const oy = (height - textH * scale) / 2;
      s.setTransform(k * scale, 0, 0, k * scale, k * ox, k * oy);
      s.textBaseline = "alphabetic";
      lines.forEach((line, i) => {
        const m = metrics[i];
        const lineW = m.actualBoundingBoxLeft + m.actualBoundingBoxRight;
        s.fillText(line, (textW - lineW) / 2 + m.actualBoundingBoxLeft, ascent + i * lineHeight);
      });
    } else {
      const [minX, minY, bw, bh] = source.box;
      const scale = Math.min(innerW / bw, innerH / bh);
      const ox = (width - bw * scale) / 2 - minX * scale;
      const oy = (height - bh * scale) / 2 - minY * scale;
      s.setTransform(k * scale, 0, 0, k * scale, k * ox, k * oy);
      s.fill(new Path2D(source.d));
    }
    return { data: s.getImageData(0, 0, w, h).data, w, h };
  }

  /** Lays the hex lattice over the mark: one slot wherever a lattice point falls inside it. */
  function buildSlots() {
    count = 0;
    if (!width || !height) return;
    const m = mask();
    if (!m) return;
    const k = SWARM.sample;
    let covered = 0;
    for (let i = 3; i < m.data.length; i += 4) if (m.data[i] > 127) covered++;
    const area = covered / (k * k);
    const base = Math.max(1, options.dotSize + options.gap);
    const rowFactor = Math.sqrt(3) / 2;
    const estimate = area / (base * base * rowFactor);
    // Too many slots for the box: widen the whole lattice, dots included, so the look holds. Too
    // few to read (a word in a phone-sized box): tighten it the same way, down to half size.
    const grow =
      estimate > SWARM.maxDots
        ? Math.sqrt(estimate / SWARM.maxDots)
        : estimate < SWARM.minDots
          ? Math.max(SWARM.minShrink, Math.sqrt(estimate / SWARM.minDots))
          : 1;
    pitch = base * grow;
    radius = (options.dotSize / 2) * grow;
    const rowH = pitch * rowFactor;
    const px: number[] = [];
    const py: number[] = [];
    const rows = Math.ceil(height / 2 / rowH);
    const cols = Math.ceil(width / 2 / pitch) + 1;
    for (let r = -rows; r <= rows; r++) {
      const y = height / 2 + r * rowH;
      const off = r & 1 ? pitch / 2 : 0;
      for (let c = -cols; c <= cols; c++) {
        const x = width / 2 + c * pitch + off;
        const mx = Math.round(x * k);
        const my = Math.round(y * k);
        if (mx < 0 || my < 0 || mx >= m.w || my >= m.h) continue;
        if (m.data[(my * m.w + mx) * 4 + 3] > 127) {
          px.push(x);
          py.push(y);
        }
      }
    }
    count = px.length;
    xs = Float32Array.from(px);
    ys = Float32Array.from(py);
    // A fixed random order per mark, so the same fill always shows the same rings.
    random = seeded(`${keyOf(source)}:${count}`);
    const order = Array.from({ length: count }, (_, i) => i);
    for (let i = count - 1; i > 0; i--) {
      const j = Math.floor(random() * (i + 1));
      [order[i], order[j]] = [order[j], order[i]];
    }
    rank = new Int32Array(count);
    order.forEach((slot, i) => (rank[slot] = i));
    state = new Uint8Array(count);
    inbound = new Uint8Array(count);
    solid = Math.round(clamp01(options.fill) * count);
  }

  /** Where a dot bound for (x, y) waits on the edge: out from the middle past its slot, `inset` px in. */
  function edgeFrom(x: number, y: number, inset: number, spread: number) {
    const angle = Math.atan2(y - height / 2, x - width / 2) + (random() - 0.5) * spread;
    return edgeAt(angle, inset);
  }

  function edgeAt(angle: number, inset: number): [number, number] {
    const ux = Math.cos(angle);
    const uy = Math.sin(angle);
    const hw = width / 2 - inset;
    const hh = height / 2 - inset;
    const t = Math.min(ux ? hw / Math.abs(ux) : Infinity, uy ? hh / Math.abs(uy) : Infinity);
    return [width / 2 + ux * t, height / 2 + uy * t];
  }

  /** A cubic from (x0, y0) to (x3, y3): straight out, a sideways bow, straight in. */
  function curve(x0: number, y0: number, x3: number, y3: number, bowRange: readonly [number, number]) {
    const dx = x3 - x0;
    const dy = y3 - y0;
    const d = Math.hypot(dx, dy) || 1;
    const ux = dx / d;
    const uy = dy / d;
    const bow = d * (bowRange[0] + random() * (bowRange[1] - bowRange[0]));
    // Every dot bows the same way, so the burst turns like one swirl instead of crossing itself.
    const nx = -uy * bow;
    const ny = ux * bow;
    return Float64Array.of(
      x0,
      y0,
      x0 + ux * d * SWARM.launch + nx,
      y0 + uy * d * SWARM.launch + ny,
      x3 - ux * d * SWARM.land + nx * 0.35,
      y3 - uy * d * SWARM.land + ny * 0.35,
      x3,
      y3,
    );
  }

  /** A dot coming in from the edge to `slot`. */
  function arrive(slot: number, kind: number, t0: number, dur: number, appear: number) {
    const inset = radius + Math.floor(random() * SWARM.band) * pitch * 0.9;
    const [x, y] = edgeFrom(xs[slot], ys[slot], inset, SWARM.jitter);
    inbound[slot] = 1;
    dots.push({ slot, kind, role: LAND, c: curve(x, y, xs[slot], ys[slot], SWARM.swirl), appear, t0, dur });
  }

  /** A dot at (x, y) leaving through the edge behind it. */
  function leave(x: number, y: number, kind: number, t0: number, dur: number, appear: number) {
    const angle = Math.atan2(y - height / 2, x - width / 2) + (random() - 0.5) * SWARM.jitter * 0.5;
    const [ex, ey] = edgeAt(angle, -radius * 3);
    dots.push({ slot: -1, kind, role: LEAVE, c: curve(x, y, ex, ey, SWARM.swirlShort), appear, t0, dur });
  }

  const vary = (dur: number, by = 0.25) => dur * (1 - by + random() * by * 2);
  const settledKind = (slot: number) => (rank[slot] < solid ? SOLID : HOLLOW);

  function settleAll() {
    for (let s = 0; s < count; s++) state[s] = settledKind(s);
    inbound.fill(0);
    dots = dots.filter((d) => d.role === LEAVE && !options.reduced);
    cacheDirty = true;
  }

  /** Keeps a copy of the canvas so a reduced-motion change can crossfade from it. */
  function snapshot() {
    if (!canvas || !cache) return;
    prev ??= document.createElement("canvas");
    prev.width = canvas.width;
    prev.height = canvas.height;
    prev.getContext("2d")?.drawImage(cache, 0, 0);
  }

  function crossfade(withPrev: boolean) {
    if (!withPrev) prev = null;
    fadeT0 = now();
    settling = true;
    wake();
  }

  function play() {
    played = true;
    dots = [];
    state.fill(EMPTY);
    inbound.fill(0);
    cacheDirty = true;
    if (!count) return;
    if (options.reduced) {
      settleAll();
      crossfade(false);
      return;
    }
    const t = now();
    for (let s = 0; s < count; s++) {
      const t0 = t + TIMING.gather + random() * options.spread;
      const appear = Math.max(t + random() * TIMING.gather, t0 - TIMING.lead * (0.3 + random() * 0.7));
      arrive(s, settledKind(s), t0, vary(options.flight), appear);
    }
    settling = true;
    wake();
  }

  function reroute() {
    const t = now();
    // Everything in the box now: settled slots, and dots on their way to one.
    const ox: number[] = [];
    const oy: number[] = [];
    const ok: number[] = [];
    for (let s = 0; s < count; s++) {
      if (state[s] !== EMPTY && !inbound[s]) {
        ox.push(xs[s]);
        oy.push(ys[s]);
        ok.push(state[s]);
      }
    }
    for (const d of dots) {
      if (d.role !== LAND || t < d.appear) continue;
      at(d.c, ease(clamp01((t - d.t0) / d.dur)), point);
      ox.push(point[0]);
      oy.push(point[1]);
      ok.push(d.kind);
    }
    if (options.reduced) snapshot();
    dots = dots.filter((d) => d.role === LEAVE);
    buildSlots();
    cacheDirty = true;
    if (options.reduced) {
      settleAll();
      crossfade(true);
      return;
    }

    // Match old dots to new slots in reading order: split both into the same number of columns
    // by x, then sort each column by y, so a letter trades with the letter where it lands.
    const columns = Math.max(1, Math.round(Math.sqrt(Math.min(ox.length, count)) / 2));
    const order = (n: number, x: (i: number) => number, y: (i: number) => number) => {
      const byX = Array.from({ length: n }, (_, i) => i).sort((a, b) => x(a) - x(b));
      const out: number[] = [];
      for (let c = 0; c < columns; c++) {
        const part = byX.slice(Math.floor((c * n) / columns), Math.floor(((c + 1) * n) / columns));
        part.sort((a, b) => y(a) - y(b));
        out.push(...part);
      }
      return out;
    };
    const olds = order(ox.length, (i) => ox[i], (i) => oy[i]);
    const news = order(count, (i) => xs[i], (i) => ys[i]);
    const N = olds.length;
    const M = news.length;
    const taken = new Uint8Array(M);
    const spread = TIMING.reroute.spread;
    if (N >= M) {
      const used = new Uint8Array(N);
      for (let j = 0; j < M; j++) {
        const i = Math.min(N - 1, Math.floor((j * N) / M));
        used[i] = 1;
        flyTo(ox[olds[i]], oy[olds[i]], news[j], t + random() * spread);
        taken[j] = 1;
      }
      for (let i = 0; i < N; i++) {
        if (used[i]) continue;
        leave(ox[olds[i]], oy[olds[i]], ok[olds[i]], t + random() * spread, vary(TIMING.reroute.flight), t);
      }
    } else {
      for (let i = 0; i < N; i++) {
        const j = Math.min(M - 1, Math.floor((i * M) / N));
        flyTo(ox[olds[i]], oy[olds[i]], news[j], t + random() * spread);
        taken[j] = 1;
      }
      for (let j = 0; j < M; j++) {
        if (taken[j]) continue;
        const t0 = t + TIMING.lead * 0.5 + random() * spread;
        arrive(news[j], settledKind(news[j]), t0, vary(TIMING.reroute.flight), t + random() * TIMING.lead * 0.5);
      }
    }
    settling = true;
    wake();
  }

  /** A dot already in the box flying from (x, y) to `slot`, taking the slot's kind on the way. */
  function flyTo(x: number, y: number, slot: number, t0: number) {
    inbound[slot] = 1;
    dots.push({
      slot,
      kind: settledKind(slot),
      role: LAND,
      c: curve(x, y, xs[slot], ys[slot], SWARM.swirlShort),
      appear: Math.min(t0, now()),
      t0,
      dur: vary(TIMING.reroute.flight),
    });
  }

  function refill(next: number) {
    if (next === solid) return;
    if (!played || !count) {
      solid = next;
      return;
    }
    const t = now();
    if (options.reduced) {
      snapshot();
      solid = next;
      settleAll();
      crossfade(true);
      return;
    }
    solid = next;
    // Dots still on their way just change what they'll be when they land.
    for (const d of dots) if (d.role === LAND) d.kind = settledKind(d.slot);
    const grow: number[] = [];
    const shrink: number[] = [];
    for (let s = 0; s < count; s++) {
      if (inbound[s]) continue;
      const want = settledKind(s);
      if (state[s] === HOLLOW && want === SOLID) grow.push(s);
      else if (state[s] === SOLID && want === HOLLOW) shrink.push(s);
    }
    // Fill in the fixed order, spread wider when more change, up to the cap.
    grow.sort((a, b) => rank[a] - rank[b]);
    const spread = Math.min(TIMING.refill.spread, TIMING.refill.step * Math.sqrt(grow.length + shrink.length));
    grow.forEach((s, i) => {
      const t0 = t + TIMING.lead * 0.5 + (grow.length > 1 ? i / (grow.length - 1) : 0) * spread;
      arrive(s, SOLID, t0, vary(TIMING.refill.flight), t + (i / Math.max(1, grow.length)) * spread);
    });
    for (const s of shrink) {
      state[s] = HOLLOW;
      leave(xs[s], ys[s], SOLID, t + random() * spread, vary(TIMING.refill.flight), t);
    }
    cacheDirty = true;
    settling = true;
    wake();
  }

  /** A late dot from a corner, merging into a solid slot. */
  function stray() {
    if (!solid || !count) return;
    let slot = -1;
    for (let tries = 0; tries < 12 && slot < 0; tries++) {
      const s = Math.floor(random() * count);
      if (state[s] === SOLID && !inbound[s]) slot = s;
    }
    if (slot < 0) return;
    const corner = Math.floor(random() * 4);
    const cornerAngle = Math.atan2((corner & 1 ? 1 : -1) * height, (corner & 2 ? 1 : -1) * width);
    const [x, y] = edgeAt(cornerAngle + (random() - 0.5) * SWARM.corner * 2, radius);
    const t = now();
    dots.push({
      slot,
      kind: SOLID,
      role: STRAY,
      c: curve(x, y, xs[slot], ys[slot], SWARM.swirl),
      appear: t,
      t0: t + TIMING.pop,
      dur: vary(TIMING.drift.flight, 0.2),
    });
    wake();
  }

  function scheduleDrift() {
    window.clearTimeout(driftTimer);
    driftTimer = 0;
    if (!options.drift || options.reduced || !played || settling || !awake() || !solid) return;
    driftTimer = window.setTimeout(
      () => {
        driftTimer = 0;
        stray();
        scheduleDrift();
      },
      TIMING.drift.every * (0.6 + random() * 0.8) * 1000,
    );
  }

  function drawCache() {
    cacheDirty = false;
    if (!canvas) return;
    cache ??= document.createElement("canvas");
    if (cache.width !== canvas.width || cache.height !== canvas.height) {
      cache.width = canvas.width;
      cache.height = canvas.height;
    }
    const c = cache.getContext("2d");
    if (!c) return;
    c.setTransform(1, 0, 0, 1, 0, 0);
    c.clearRect(0, 0, cache.width, cache.height);
    c.setTransform(dpr, 0, 0, dpr, 0, 0);
    const fill = new Path2D();
    const rings = new Path2D();
    const r = radius;
    const rr = Math.max(0.5, r - SWARM.ring / 2);
    for (let s = 0; s < count; s++) {
      // A slot whose dot is still flying in shows nothing, or its ring while a solid dot comes to fill it.
      const v = state[s];
      if (v === SOLID) {
        fill.moveTo(xs[s] + r, ys[s]);
        fill.arc(xs[s], ys[s], r, 0, Math.PI * 2);
      } else if (v === HOLLOW) {
        rings.moveTo(xs[s] + rr, ys[s]);
        rings.arc(xs[s], ys[s], rr, 0, Math.PI * 2);
      }
    }
    const style = paint(c);
    c.fillStyle = style;
    c.strokeStyle = ringColor ?? style;
    c.lineWidth = SWARM.ring;
    c.fill(fill);
    c.stroke(rings);
  }

  function frame() {
    raf = 0;
    draw();
  }

  function draw() {
    if (!ctx || !canvas) return;
    const t = now();
    const span = options.trails ? options.trail : 0;

    // Landings first, so a dot that lands this frame is already in the settled layer.
    let landing = 0;
    for (const d of dots) {
      if (d.role !== LAND) continue;
      if (t >= d.t0 + d.dur) {
        if (inbound[d.slot]) {
          state[d.slot] = d.kind;
          inbound[d.slot] = 0;
          cacheDirty = true;
        }
      } else landing++;
    }
    dots = dots.filter((d) => t < d.t0 + d.dur * (1 + span));

    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    if (cacheDirty) drawCache();
    let fading = false;
    if (cache) {
      if (fadeT0 >= 0) {
        const a = clamp01((t - fadeT0) / TIMING.fade);
        if (prev) {
          ctx.globalAlpha = 1 - a;
          ctx.drawImage(prev, 0, 0);
        }
        ctx.globalAlpha = a;
        ctx.drawImage(cache, 0, 0);
        ctx.globalAlpha = 1;
        if (a >= 1) {
          fadeT0 = -1;
          prev = null;
        } else fading = true;
      } else ctx.drawImage(cache, 0, 0);
    }

    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    const trail = new Path2D();
    const fill = new Path2D();
    const rings = new Path2D();
    let traced = false;
    for (const d of dots) {
      if (t < d.appear) continue;
      const u = (t - d.t0) / d.dur;
      const head = u <= 0 ? 0 : u >= 1 ? 1 : ease(u);
      if (span > 0 && u > 0) {
        const tail = ease(clamp01(u - span));
        if (head - tail > 0.001) {
          addPiece(trail, d.c, tail, head);
          traced = true;
        }
      }
      // Landed and merged dots live in the settled layer; only their trail is still reeling in.
      if (u >= 1 && d.role !== LEAVE) continue;
      at(d.c, head, point);
      const grow = u <= 0 ? clamp01((t - d.appear) / TIMING.pop) : 1;
      const scale =
        d.role === LEAVE
          ? 1 - (1 - SWARM.flightSize) * head
          : u <= 0
            ? 1
            : SWARM.flightSize + (1 - SWARM.flightSize) * head;
      const r = radius * scale * grow;
      if (r < 0.3) continue;
      if (d.kind === SOLID) {
        fill.moveTo(point[0] + r, point[1]);
        fill.arc(point[0], point[1], r, 0, Math.PI * 2);
      } else {
        const rr = Math.max(0.4, r - SWARM.ring / 2);
        rings.moveTo(point[0] + rr, point[1]);
        rings.arc(point[0], point[1], rr, 0, Math.PI * 2);
      }
    }
    const style = paint(ctx);
    ctx.strokeStyle = style;
    ctx.fillStyle = style;
    if (traced) {
      ctx.globalAlpha = SWARM.trailAlpha;
      ctx.lineWidth = SWARM.trailWidth;
      ctx.stroke(trail);
      ctx.globalAlpha = 1;
    }
    ctx.fill(fill);
    ctx.strokeStyle = ringColor ?? style;
    ctx.lineWidth = SWARM.ring;
    ctx.stroke(rings);

    if (settling && !landing && !fading && !dots.some((d) => d.role === LEAVE)) {
      settling = false;
      if (relayPending) {
        relayPending = false;
        reroute(); // settles again, and reports then
        return;
      }
      onSettle?.();
      scheduleDrift();
    }
    // Called outside the loop too (a color change), so never start a second loop.
    if (!raf && (dots.length || fading) && awake()) raf = requestAnimationFrame(frame);
  }

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

  function layout() {
    if (!root || !canvas) return;
    const w = root.clientWidth;
    const h = root.clientHeight;
    const nextDpr = Math.min(window.devicePixelRatio || 1, SWARM.maxDpr);
    if (w === width && h === height && nextDpr === dpr) return;
    width = w;
    height = h;
    dpr = nextDpr;
    canvas.width = Math.max(1, Math.round(w * dpr));
    canvas.height = Math.max(1, Math.round(h * dpr));
    rebuild();
  }

  /** Lays the lattice again and snaps to the settled mark; an entrance that hasn't played waits. */
  function rebuild() {
    // A resize mid-flight snaps to the settled mark, and still reports it as settled.
    const interrupted = played && settling;
    buildSlots();
    dots = [];
    prev = null;
    fadeT0 = -1;
    relayPending = false;
    if (played) {
      settleAll();
      settling = false;
    }
    cacheDirty = true;
    draw();
    if (interrupted) onSettle?.();
    if (!played && awake()) play();
    scheduleDrift();
  }

  function setAwake() {
    if (awake()) {
      if (!played && width) play();
      wake();
      scheduleDrift();
    } else {
      cancelAnimationFrame(raf);
      raf = 0;
      window.clearTimeout(driftTimer);
      driftTimer = 0;
      dots = dots.filter((d) => d.role !== STRAY);
    }
  }

  return {
    connect(el: { root: HTMLElement; canvas: HTMLCanvasElement; dot: HTMLElement; to: HTMLElement; ring: HTMLElement }) {
      root = el.root;
      canvas = el.canvas;
      ctx = canvas.getContext("2d");
      probes = { dot: el.dot, to: el.to, ring: el.ring };
      width = 0;
      pageVisible = document.visibilityState === "visible";
      readColors();
      layout();

      const resize = new ResizeObserver(() => layout());
      resize.observe(root);
      const io = new IntersectionObserver(
        ([entry]) => {
          inView = entry.isIntersecting;
          setAwake();
        },
        { threshold: 0.25 },
      );
      io.observe(root);
      const visibility = () => {
        pageVisible = document.visibilityState === "visible";
        setAwake();
      };
      document.addEventListener("visibilitychange", visibility);
      const scheme = window.matchMedia("(prefers-color-scheme: dark)");
      scheme.addEventListener("change", readColors);
      const themeAttrs = new MutationObserver(readColors);
      themeAttrs.observe(document.documentElement, { attributes: true, attributeFilter: ["class", "data-theme", "style"] });
      // Text is measured in its real font once it has loaded.
      let alive = true;
      document.fonts?.ready.then(() => {
        if (!alive || source.kind !== "text") return;
        // Before the entrance, lay it again quietly; during one, after it lands; after it, fly there.
        if (!played) rebuild();
        else if (settling) relayPending = true;
        else reroute();
      });

      cleanups.push(
        () => resize.disconnect(),
        () => io.disconnect(),
        () => document.removeEventListener("visibilitychange", visibility),
        () => scheme.removeEventListener("change", readColors),
        () => themeAttrs.disconnect(),
        () => (alive = false),
      );
      return () => {
        cancelAnimationFrame(raf);
        raf = 0;
        window.clearTimeout(driftTimer);
        driftTimer = 0;
        dots = [];
        inView = false;
        cleanups.splice(0).forEach((fn) => fn());
        root = canvas = null;
        probes = null;
        ctx = null;
      };
    },

    setOptions(next: Options) {
      const relay = next.dotSize !== options.dotSize || next.gap !== options.gap;
      const reducedChanged = next.reduced !== options.reduced;
      const fillChanged = next.fill !== options.fill;
      options = next;
      if (relay) {
        if (width) rebuild();
        return;
      }
      if (reducedChanged && played) {
        const interrupted = settling;
        settleAll();
        dots = [];
        settling = false;
        draw();
        if (interrupted) onSettle?.();
      }
      if (fillChanged) refill(Math.round(clamp01(next.fill) * count));
      scheduleDrift();
    },

    setSource(next: Source) {
      if (keyOf(next) === keyOf(source)) return;
      source = next;
      relayPending = false;
      if (!width) return;
      if (played) reroute();
      else rebuild();
    },

    /** Reads the colors again, after the probes' classes change. */
    setTones(next: { gradient: boolean; ring: boolean }) {
      tones = next;
      readColors();
    },

    setOnSettle(fn: (() => void) | null) {
      onSettle = fn;
    },
  };
}

type Engine = ReturnType<typeof createSwarm>;

function parseViewBox(viewBox: string): [number, number, number, number] {
  const n = viewBox.split(/[\s,]+/).map(Number);
  return n.length === 4 && n.every(Number.isFinite) && n[2] > 0 && n[3] > 0 ? [n[0], n[1], n[2], n[3]] : [0, 0, 24, 24];
}

export interface SwarmProps extends React.HTMLAttributes<HTMLDivElement> {
  /** A word or short line for the dots to form. Use `\n` for a second line. */
  text?: string;
  /** Font family `text` is set in, at weight 800, before it's turned into dots. */
  textFont?: string;
  /** An SVG path (`d`) for the dots to form, such as your logo mark. Read against `viewBox`. */
  path?: string;
  /** The coordinate box `path` is drawn in, like an SVG's `viewBox`. */
  viewBox?: string;
  /** Share of the mark that's solid, from 0 to 1; the rest are hollow rings. Raise it and solid dots fly in onto the rings, like a progress bar in the shape of your mark. */
  fill?: number;
  /** Diameter of a landed dot, in px. */
  dotSize?: number;
  /** Space between neighbouring dots, in px. */
  gap?: number;
  /** Draw each dot's path behind it as a hairline that reels in when it lands. */
  trails?: boolean;
  /** Once settled, keep a few late dots coming in from the corners on long trails. */
  drift?: boolean;
  /** Seconds a dot takes to fly from the edge to its slot. Each one varies by a quarter either way. */
  duration?: number;
  /** Seconds between the first dot leaving the edge and the last. */
  stagger?: number;
  /** How far a trail lags behind its dot, as a share of the flight. */
  trailLength?: number;
  /** Describes the mark for screen readers. Defaults to `text`; without either, the swarm is decorative. */
  label?: string;
  /** A `text-*` color for the dots and trails. The canvas reads it, so `dark:` variants work. */
  dotClassName?: string;
  /** A second `text-*` color. Dots, rings and trails blend from `dotClassName` at the top left to this at the bottom right, by where each one is, so a dot changes color as it crosses the box. */
  gradientClassName?: string;
  /** A `text-*` color for the hollow rings alone, so what's still to come reads apart from what's solid. Without it, rings take the dots' color. */
  ringClassName?: string;
  /** Classes for the canvas. It fills the box by default; the mark is fitted inside it. */
  canvasClassName?: string;
  /** Called each time every dot has landed: after the entrance, a new mark or a new `fill`. */
  onSettle?: () => void;
}

export function Swarm({
  text,
  textFont = "ui-sans-serif, system-ui, sans-serif",
  path,
  viewBox = "0 0 24 24",
  fill = 0.9,
  dotSize = 6,
  gap = 1.5,
  trails = true,
  drift = true,
  duration = TIMING.flight,
  stagger = TIMING.spread,
  trailLength = TIMING.trail,
  label,
  dotClassName,
  gradientClassName,
  ringClassName,
  canvasClassName,
  onSettle,
  className,
  children,
  ...props
}: SwarmProps) {
  const rootRef = React.useRef<HTMLDivElement>(null);
  const canvasRef = React.useRef<HTMLCanvasElement>(null);
  const dotRef = React.useRef<HTMLSpanElement>(null);
  const toRef = React.useRef<HTMLSpanElement>(null);
  const ringRef = React.useRef<HTMLSpanElement>(null);
  const [engine] = React.useState<Engine>(createSwarm);
  const reduced = useReduced();

  React.useLayoutEffect(() => {
    const root = rootRef.current;
    const canvas = canvasRef.current;
    const dot = dotRef.current;
    const to = toRef.current;
    const ring = ringRef.current;
    if (!root || !canvas || !dot || !to || !ring) return;
    return engine.connect({ root, canvas, dot, to, ring });
  }, [engine]);

  React.useEffect(() => {
    engine.setOptions({
      fill: clamp01(fill),
      dotSize: Math.max(1.5, dotSize),
      gap: Math.max(0, gap),
      trails,
      drift,
      flight: Math.max(0.1, duration),
      spread: Math.max(0, stagger),
      trail: clamp01(trailLength),
      reduced,
    });
  }, [engine, fill, dotSize, gap, trails, drift, duration, stagger, trailLength, reduced]);

  React.useEffect(() => {
    if (text) engine.setSource({ kind: "text", text, font: textFont });
    else if (path) engine.setSource({ kind: "path", d: path, box: parseViewBox(viewBox) });
    else engine.setSource({ kind: "disc" });
  }, [engine, text, textFont, path, viewBox]);

  // The probes' classes are already on the page by the time this runs, so the colors read fresh.
  const gradient = !!gradientClassName;
  const ring = !!ringClassName;
  React.useEffect(() => {
    engine.setTones({ gradient, ring });
  }, [engine, gradient, ring, dotClassName, gradientClassName, ringClassName]);

  const onSettleRef = React.useRef(onSettle);
  React.useEffect(() => {
    onSettleRef.current = onSettle;
  });
  React.useEffect(() => {
    engine.setOnSettle(() => onSettleRef.current?.());
    return () => engine.setOnSettle(null);
  }, [engine]);

  const name = label ?? text;
  return (
    <div ref={rootRef} className={cn("relative isolate", className)} {...props}>
      <canvas
        ref={canvasRef}
        role={name ? "img" : undefined}
        aria-label={name}
        aria-hidden={name ? undefined : true}
        className={cn("pointer-events-none absolute inset-0 -z-10 size-full", canvasClassName)}
      />
      {/* The probes the canvas reads its colors from. The default applies only when no class is given, so a `dark:` default can't win over yours. */}
      <span ref={dotRef} aria-hidden className={cn("hidden", dotClassName ?? "text-[#2f45e8] dark:text-[#8b98ff]")} />
      <span ref={toRef} aria-hidden className={cn("hidden", gradientClassName)} />
      <span ref={ringRef} aria-hidden className={cn("hidden", ringClassName)} />
      {children}
    </div>
  );
}
```
