{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "swarm",
  "type": "registry:ui",
  "title": "Swarm",
  "description": "Particle Text Animation: dots fly in on hairline trails and pack into your word or logo. A take on the particle effect (particles) and text animation (text effect). Fits hero, about, preloader and 404 page sections.",
  "author": "KeyframeUI <https://keyframeui.com>",
  "categories": [
    "hero",
    "about",
    "preloader",
    "404-page",
    "particle-effect",
    "text-animation",
    "text",
    "canvas"
  ],
  "docs": "Live preview, examples and props: https://keyframeui.com/components/swarm",
  "dependencies": [
    "clsx",
    "tailwind-merge"
  ],
  "registryDependencies": [
    "utils"
  ],
  "files": [
    {
      "path": "components/ui/swarm.tsx",
      "type": "registry:ui",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\n/**\n * Keep:\n * - Every dot's position is a closed-form function of time (a cubic from where it starts to its\n *   slot), so landings are exact, a change mid-flight starts from where the dot is, and the loop\n *   stops once nothing moves.\n * - Dots land on a hex lattice inside the mark and never overlap there. Settled dots are drawn once\n *   into an offscreen canvas and blitted; moving dots, rings and trails are one path each, painted\n *   with one color or one canvas-wide gradient, so a dot takes the color of the spot it's in.\n * - A trail is the dot's own curve drawn from a point that lags behind it, so it reels in when the\n *   dot lands. Never a fading smear: the canvas is transparent over your background.\n * - New dots come in from the box's edge, behind their slot as seen from the middle; dots that\n *   leave go back out the same way. Nothing appears out of thin air mid-box.\n * - Under reduced motion nothing travels: the mark crossfades in place and drift is off.\n */\nconst TIMING = {\n  /** Dots gathering along the edge before the first one leaves, in seconds. */\n  gather: 0.45,\n  /** A dot's flight from the edge to its slot, in seconds (the `duration` prop). Each one varies ±25%. */\n  flight: 1.15,\n  /** Seconds between the first launch and the last (the `stagger` prop). */\n  spread: 0.9,\n  /** Longest a dot waits on the edge before it leaves, in seconds. */\n  lead: 0.4,\n  /** A waiting dot growing in on the edge, in seconds. */\n  pop: 0.18,\n  /** Share of its flight time a trail lags behind its dot (the `trailLength` prop). */\n  trail: 0.6,\n  /** A new mark: each dot's flight and the spread of launches, in seconds. */\n  reroute: { flight: 1.05, spread: 0.4 },\n  /**\n   * `fill` changing: each dot's flight, and the spread of launches in seconds, which grows by\n   * `step` per square root of the dots that change, up to `spread`.\n   */\n  refill: { flight: 0.95, spread: 0.6, step: 0.04 },\n  /** Drift at rest: seconds between late dots (randomized ±40%), and a late dot's flight in seconds. */\n  drift: { every: 0.45, flight: 2.6 },\n  /** Under reduced motion, the crossfade that replaces every flight, in seconds. */\n  fade: 0.3,\n} as const;\n\n/* ─────────────────────────────────────────────────────────\n * SWARM STORYBOARD\n *\n *  rest     before it's seen, an empty box. Settled, your mark\n *           (a word, an SVG path, or a disc) set in dots on a\n *           hex lattice, most solid, a few hollow rings\n *  gather   the first time a quarter of it scrolls into view,\n *           dots pop onto the box's edge, up to three deep,\n *           each one roughly behind the slot it's bound for\n *  flight   0.45s in they start leaving, spread over 0.9s:\n *           each one bows in along a cubic for about 1.15s,\n *           easing out of the edge and into its slot, growing\n *           from 62% to full size on the way. Its trail is its\n *           own path, lagging 60% of the flight behind, so a\n *           burst reads as hairlines converging on the mark\n *  land     a dot locks onto its slot exactly; the trail\n *           behind it reels in over the next 0.7s\n *  drift    settled, a late dot leaves a corner every ~0.45s\n *           and takes 2.6s to merge into a solid slot, so a\n *           few long hairlines are always coming in\n *  fill     `fill` is the solid share; the rest are hollow\n *           rings, in a fixed random order. Raise it and solid\n *           dots fly in from the edge onto the rings; lower it\n *           and solid dots fly out, leaving their rings behind\n *  reroute  a new mark: dots already in the box fly to the new\n *           slots (left to right, column by column, so letters\n *           trade with their neighbours), extras leave through\n *           the edge, and missing ones come in from it. 1.05s\n *           flights spread over 0.4s; a change mid-flight\n *           starts from where each dot is\n *  resize   the lattice is laid again and the mark snaps to\n *           its settled state; nothing replays\n *  sleep    off screen or in a hidden tab nothing draws and\n *           drift stops; flights finish on time while hidden\n *  reduced  no flights and no drift: the mark crossfades in\n *           over 0.3s, and a new mark or fill crossfades too\n * ───────────────────────────────────────────────────────── */\n\nconst SWARM = {\n  pad: 0.09, // share of the box kept clear around the mark\n  maxDots: 4200, // past this many slots the lattice widens, dots and all\n  minDots: 900, // under this many the lattice tightens, so a mark in a small box still reads\n  minShrink: 0.5, // but dots never get smaller than this share of `dotSize`\n  sample: 0.5, // mask samples per CSS px\n  band: 3, // rows deep the edge band can stack\n  jitter: 0.7, // rad, spread of a dot's start around the line from the middle through its slot\n  swirl: [0.1, 0.34], // sideways bow of an edge flight, share of its length\n  swirlShort: [0.04, 0.16], // and of a flight inside the box (reroute, leaving)\n  launch: 0.3, // share of its length a flight heads straight in before it bends\n  land: 0.22, // share of its length a flight comes straight in at the end\n  flightSize: 0.62, // a dot's size mid-flight, share of its landed size\n  ring: 1, // px, stroke of a hollow ring\n  trailWidth: 0.6, // px\n  trailAlpha: 0.32, // opacity of the hairline trails\n  corner: 0.32, // rad, spread of a late dot's start around its corner\n  maxDpr: 2,\n} as const;\n\nconst REDUCED = \"(prefers-reduced-motion: reduce)\";\nconst subscribeReduced = (onChange: () => void) => {\n  const query = window.matchMedia(REDUCED);\n  query.addEventListener(\"change\", onChange);\n  return () => query.removeEventListener(\"change\", onChange);\n};\n\n/** Reduced motion from the media query, false on the server and in the hydration render. */\nfunction useReduced() {\n  return React.useSyncExternalStore(\n    subscribeReduced,\n    () => window.matchMedia(REDUCED).matches,\n    () => false,\n  );\n}\n\nconst clamp01 = (t: number) => (t < 0 ? 0 : t > 1 ? 1 : t);\n/** In-out cubic: a dot eases off the edge and settles into its slot without a snap. */\nconst ease = (u: number) => (u < 0.5 ? 4 * u * u * u : 1 - (-2 * u + 2) ** 3 / 2);\n\n/** A seeded generator, so the same mark always fills in the same order. */\nfunction seeded(key: string) {\n  let h = 2166136261;\n  for (let i = 0; i < key.length; i++) h = Math.imul(h ^ key.charCodeAt(i), 16777619);\n  return () => {\n    h = (h + 0x6d2b79f5) | 0;\n    let t = Math.imul(h ^ (h >>> 15), 1 | h);\n    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n  };\n}\n\n/** Point on the cubic `c` (x0 y0 x1 y1 x2 y2 x3 y3) at parameter t, written into `out`. */\nfunction at(c: Float64Array, t: number, out: Float64Array) {\n  const m = 1 - t;\n  const a = m * m * m;\n  const b = 3 * m * m * t;\n  const d = 3 * m * t * t;\n  const e = t * t * t;\n  out[0] = a * c[0] + b * c[2] + d * c[4] + e * c[6];\n  out[1] = a * c[1] + b * c[3] + d * c[5] + e * c[7];\n}\n\n/** Adds the piece of cubic `c` between parameters a and b to `path` (de Casteljau, twice). */\nfunction addPiece(path: Path2D, c: Float64Array, a: number, b: number) {\n  const lerp = (p: number, q: number, t: number) => p + (q - p) * t;\n  // Left part of the curve, up to b.\n  const q0x = lerp(c[0], c[2], b), q0y = lerp(c[1], c[3], b);\n  const q1x = lerp(c[2], c[4], b), q1y = lerp(c[3], c[5], b);\n  const q2x = lerp(c[4], c[6], b), q2y = lerp(c[5], c[7], b);\n  const r0x = lerp(q0x, q1x, b), r0y = lerp(q0y, q1y, b);\n  const r1x = lerp(q1x, q2x, b), r1y = lerp(q1y, q2y, b);\n  const sx = lerp(r0x, r1x, b), sy = lerp(r0y, r1y, b);\n  // Right part of that, from a.\n  const t = b > 0 ? a / b : 0;\n  const u0x = lerp(c[0], q0x, t), u0y = lerp(c[1], q0y, t);\n  const u1x = lerp(q0x, r0x, t), u1y = lerp(q0y, r0y, t);\n  const u2x = lerp(r0x, sx, t), u2y = lerp(r0y, sy, t);\n  const v0x = lerp(u0x, u1x, t), v0y = lerp(u0y, u1y, t);\n  const v1x = lerp(u1x, u2x, t), v1y = lerp(u1y, u2y, t);\n  path.moveTo(lerp(v0x, v1x, t), lerp(v0y, v1y, t));\n  path.bezierCurveTo(v1x, v1y, u2x, u2y, sx, sy);\n}\n\ntype Source =\n  | { kind: \"disc\" }\n  | { kind: \"text\"; text: string; font: string }\n  | { kind: \"path\"; d: string; box: [number, number, number, number] };\n\nfunction keyOf(s: Source) {\n  return s.kind === \"disc\" ? \"disc\" : s.kind === \"text\" ? `text:${s.font}:${s.text}` : `path:${s.box.join(\",\")}:${s.d}`;\n}\n\ntype Options = {\n  fill: number;\n  dotSize: number;\n  gap: number;\n  trails: boolean;\n  drift: boolean;\n  flight: number;\n  spread: number;\n  trail: number;\n  reduced: boolean;\n};\n\nconst EMPTY = 0;\nconst HOLLOW = 1;\nconst SOLID = 2;\n\nconst LAND = 0; // flies to a slot and takes it\nconst LEAVE = 1; // flies out through the edge and is gone\nconst STRAY = 2; // a late dot that merges into a solid slot\n\ntype Dot = {\n  slot: number;\n  kind: number; // HOLLOW or SOLID\n  role: number;\n  c: Float64Array; // its curve\n  appear: number; // s, when it shows (on the edge, for one coming in)\n  t0: number; // s, launch\n  dur: number; // s, flight\n};\n\nfunction createSwarm() {\n  let root: HTMLElement | null = null;\n  let canvas: HTMLCanvasElement | null = null;\n  let ctx: CanvasRenderingContext2D | null = null;\n  let probes: { dot: HTMLElement; to: HTMLElement; ring: HTMLElement } | null = null;\n  let tones = { gradient: false, ring: false };\n  let color = \"currentColor\";\n  let colorTo: string | null = null; // the far end of the blend, with `gradientClassName`\n  let ringColor: string | null = null; // hollow rings in a color of their own, with `ringClassName`\n  let options: Options = {\n    fill: 0.9,\n    dotSize: 6,\n    gap: 1.5,\n    trails: true,\n    drift: true,\n    flight: TIMING.flight,\n    spread: TIMING.spread,\n    trail: TIMING.trail,\n    reduced: false,\n  };\n  let source: Source = { kind: \"disc\" };\n  let onSettle: (() => void) | null = null;\n\n  let width = 0;\n  let height = 0;\n  let dpr = 1;\n\n  // The lattice: slot positions, the order they turn solid in, and what each holds now.\n  let xs = new Float32Array(0);\n  let ys = new Float32Array(0);\n  let rank = new Int32Array(0);\n  let state = new Uint8Array(0);\n  let inbound = new Uint8Array(0); // a LAND dot is on its way to this slot\n  let count = 0;\n  let solid = 0; // slots that are solid once settled\n  let radius = 3; // px, a landed dot\n  let pitch = 7.5; // px between neighbouring slots\n\n  let dots: Dot[] = [];\n  let cache: HTMLCanvasElement | null = null; // settled slots, blitted every frame\n  let cacheDirty = true;\n  let prev: HTMLCanvasElement | null = null; // what the mark looked like before a reduced crossfade\n  let fadeT0 = -1;\n\n  let raf = 0;\n  let inView = false;\n  let pageVisible = true;\n  let played = false;\n  let settling = false;\n  let relayPending = false; // web fonts arrived mid-flight: lay the text again once it settles\n  let driftTimer = 0;\n  let random = seeded(\"swarm\");\n  const point = new Float64Array(2);\n  const cleanups: (() => void)[] = [];\n\n  const now = () => performance.now() / 1000;\n  const awake = () => inView && pageVisible;\n\n  function readColors() {\n    if (!probes) return;\n    color = getComputedStyle(probes.dot).color;\n    colorTo = tones.gradient ? getComputedStyle(probes.to).color : null;\n    ringColor = tones.ring ? getComputedStyle(probes.ring).color : null;\n    cacheDirty = true;\n    draw();\n  }\n\n  /**\n   * The dots' paint for a context: one color, or a blend from the top left corner to the bottom\n   * right one, in CSS px, so every dot takes the color of the spot it's in.\n   */\n  function paint(c: CanvasRenderingContext2D) {\n    if (!colorTo) return color;\n    const g = c.createLinearGradient(0, 0, width, height);\n    g.addColorStop(0, color);\n    g.addColorStop(1, colorTo);\n    return g;\n  }\n\n  /** The mark drawn white on a small canvas, read back as alpha. */\n  function mask() {\n    const k = SWARM.sample;\n    const w = Math.max(1, Math.round(width * k));\n    const h = Math.max(1, Math.round(height * k));\n    const c = document.createElement(\"canvas\");\n    c.width = w;\n    c.height = h;\n    const s = c.getContext(\"2d\", { willReadFrequently: true });\n    if (!s) return null;\n    const innerW = width * (1 - SWARM.pad * 2);\n    const innerH = height * (1 - SWARM.pad * 2);\n    s.fillStyle = \"#fff\";\n    if (source.kind === \"disc\") {\n      s.setTransform(k, 0, 0, k, 0, 0);\n      s.beginPath();\n      s.arc(width / 2, height / 2, Math.min(innerW, innerH) / 2, 0, Math.PI * 2);\n      s.fill();\n    } else if (source.kind === \"text\") {\n      const lines = source.text.split(\"\\n\");\n      const base = 100;\n      s.font = `800 ${base}px ${source.font}`;\n      const metrics = lines.map((line) => s.measureText(line));\n      const ascent = Math.max(...metrics.map((m) => m.actualBoundingBoxAscent));\n      const descent = Math.max(...metrics.map((m) => m.actualBoundingBoxDescent));\n      const lineHeight = (ascent + descent) * 1.08;\n      const textW = Math.max(...metrics.map((m) => m.actualBoundingBoxLeft + m.actualBoundingBoxRight));\n      const textH = ascent + descent + lineHeight * (lines.length - 1);\n      const scale = Math.min(innerW / textW, innerH / textH);\n      const ox = (width - textW * scale) / 2;\n      const oy = (height - textH * scale) / 2;\n      s.setTransform(k * scale, 0, 0, k * scale, k * ox, k * oy);\n      s.textBaseline = \"alphabetic\";\n      lines.forEach((line, i) => {\n        const m = metrics[i];\n        const lineW = m.actualBoundingBoxLeft + m.actualBoundingBoxRight;\n        s.fillText(line, (textW - lineW) / 2 + m.actualBoundingBoxLeft, ascent + i * lineHeight);\n      });\n    } else {\n      const [minX, minY, bw, bh] = source.box;\n      const scale = Math.min(innerW / bw, innerH / bh);\n      const ox = (width - bw * scale) / 2 - minX * scale;\n      const oy = (height - bh * scale) / 2 - minY * scale;\n      s.setTransform(k * scale, 0, 0, k * scale, k * ox, k * oy);\n      s.fill(new Path2D(source.d));\n    }\n    return { data: s.getImageData(0, 0, w, h).data, w, h };\n  }\n\n  /** Lays the hex lattice over the mark: one slot wherever a lattice point falls inside it. */\n  function buildSlots() {\n    count = 0;\n    if (!width || !height) return;\n    const m = mask();\n    if (!m) return;\n    const k = SWARM.sample;\n    let covered = 0;\n    for (let i = 3; i < m.data.length; i += 4) if (m.data[i] > 127) covered++;\n    const area = covered / (k * k);\n    const base = Math.max(1, options.dotSize + options.gap);\n    const rowFactor = Math.sqrt(3) / 2;\n    const estimate = area / (base * base * rowFactor);\n    // Too many slots for the box: widen the whole lattice, dots included, so the look holds. Too\n    // few to read (a word in a phone-sized box): tighten it the same way, down to half size.\n    const grow =\n      estimate > SWARM.maxDots\n        ? Math.sqrt(estimate / SWARM.maxDots)\n        : estimate < SWARM.minDots\n          ? Math.max(SWARM.minShrink, Math.sqrt(estimate / SWARM.minDots))\n          : 1;\n    pitch = base * grow;\n    radius = (options.dotSize / 2) * grow;\n    const rowH = pitch * rowFactor;\n    const px: number[] = [];\n    const py: number[] = [];\n    const rows = Math.ceil(height / 2 / rowH);\n    const cols = Math.ceil(width / 2 / pitch) + 1;\n    for (let r = -rows; r <= rows; r++) {\n      const y = height / 2 + r * rowH;\n      const off = r & 1 ? pitch / 2 : 0;\n      for (let c = -cols; c <= cols; c++) {\n        const x = width / 2 + c * pitch + off;\n        const mx = Math.round(x * k);\n        const my = Math.round(y * k);\n        if (mx < 0 || my < 0 || mx >= m.w || my >= m.h) continue;\n        if (m.data[(my * m.w + mx) * 4 + 3] > 127) {\n          px.push(x);\n          py.push(y);\n        }\n      }\n    }\n    count = px.length;\n    xs = Float32Array.from(px);\n    ys = Float32Array.from(py);\n    // A fixed random order per mark, so the same fill always shows the same rings.\n    random = seeded(`${keyOf(source)}:${count}`);\n    const order = Array.from({ length: count }, (_, i) => i);\n    for (let i = count - 1; i > 0; i--) {\n      const j = Math.floor(random() * (i + 1));\n      [order[i], order[j]] = [order[j], order[i]];\n    }\n    rank = new Int32Array(count);\n    order.forEach((slot, i) => (rank[slot] = i));\n    state = new Uint8Array(count);\n    inbound = new Uint8Array(count);\n    solid = Math.round(clamp01(options.fill) * count);\n  }\n\n  /** Where a dot bound for (x, y) waits on the edge: out from the middle past its slot, `inset` px in. */\n  function edgeFrom(x: number, y: number, inset: number, spread: number) {\n    const angle = Math.atan2(y - height / 2, x - width / 2) + (random() - 0.5) * spread;\n    return edgeAt(angle, inset);\n  }\n\n  function edgeAt(angle: number, inset: number): [number, number] {\n    const ux = Math.cos(angle);\n    const uy = Math.sin(angle);\n    const hw = width / 2 - inset;\n    const hh = height / 2 - inset;\n    const t = Math.min(ux ? hw / Math.abs(ux) : Infinity, uy ? hh / Math.abs(uy) : Infinity);\n    return [width / 2 + ux * t, height / 2 + uy * t];\n  }\n\n  /** A cubic from (x0, y0) to (x3, y3): straight out, a sideways bow, straight in. */\n  function curve(x0: number, y0: number, x3: number, y3: number, bowRange: readonly [number, number]) {\n    const dx = x3 - x0;\n    const dy = y3 - y0;\n    const d = Math.hypot(dx, dy) || 1;\n    const ux = dx / d;\n    const uy = dy / d;\n    const bow = d * (bowRange[0] + random() * (bowRange[1] - bowRange[0]));\n    // Every dot bows the same way, so the burst turns like one swirl instead of crossing itself.\n    const nx = -uy * bow;\n    const ny = ux * bow;\n    return Float64Array.of(\n      x0,\n      y0,\n      x0 + ux * d * SWARM.launch + nx,\n      y0 + uy * d * SWARM.launch + ny,\n      x3 - ux * d * SWARM.land + nx * 0.35,\n      y3 - uy * d * SWARM.land + ny * 0.35,\n      x3,\n      y3,\n    );\n  }\n\n  /** A dot coming in from the edge to `slot`. */\n  function arrive(slot: number, kind: number, t0: number, dur: number, appear: number) {\n    const inset = radius + Math.floor(random() * SWARM.band) * pitch * 0.9;\n    const [x, y] = edgeFrom(xs[slot], ys[slot], inset, SWARM.jitter);\n    inbound[slot] = 1;\n    dots.push({ slot, kind, role: LAND, c: curve(x, y, xs[slot], ys[slot], SWARM.swirl), appear, t0, dur });\n  }\n\n  /** A dot at (x, y) leaving through the edge behind it. */\n  function leave(x: number, y: number, kind: number, t0: number, dur: number, appear: number) {\n    const angle = Math.atan2(y - height / 2, x - width / 2) + (random() - 0.5) * SWARM.jitter * 0.5;\n    const [ex, ey] = edgeAt(angle, -radius * 3);\n    dots.push({ slot: -1, kind, role: LEAVE, c: curve(x, y, ex, ey, SWARM.swirlShort), appear, t0, dur });\n  }\n\n  const vary = (dur: number, by = 0.25) => dur * (1 - by + random() * by * 2);\n  const settledKind = (slot: number) => (rank[slot] < solid ? SOLID : HOLLOW);\n\n  function settleAll() {\n    for (let s = 0; s < count; s++) state[s] = settledKind(s);\n    inbound.fill(0);\n    dots = dots.filter((d) => d.role === LEAVE && !options.reduced);\n    cacheDirty = true;\n  }\n\n  /** Keeps a copy of the canvas so a reduced-motion change can crossfade from it. */\n  function snapshot() {\n    if (!canvas || !cache) return;\n    prev ??= document.createElement(\"canvas\");\n    prev.width = canvas.width;\n    prev.height = canvas.height;\n    prev.getContext(\"2d\")?.drawImage(cache, 0, 0);\n  }\n\n  function crossfade(withPrev: boolean) {\n    if (!withPrev) prev = null;\n    fadeT0 = now();\n    settling = true;\n    wake();\n  }\n\n  function play() {\n    played = true;\n    dots = [];\n    state.fill(EMPTY);\n    inbound.fill(0);\n    cacheDirty = true;\n    if (!count) return;\n    if (options.reduced) {\n      settleAll();\n      crossfade(false);\n      return;\n    }\n    const t = now();\n    for (let s = 0; s < count; s++) {\n      const t0 = t + TIMING.gather + random() * options.spread;\n      const appear = Math.max(t + random() * TIMING.gather, t0 - TIMING.lead * (0.3 + random() * 0.7));\n      arrive(s, settledKind(s), t0, vary(options.flight), appear);\n    }\n    settling = true;\n    wake();\n  }\n\n  function reroute() {\n    const t = now();\n    // Everything in the box now: settled slots, and dots on their way to one.\n    const ox: number[] = [];\n    const oy: number[] = [];\n    const ok: number[] = [];\n    for (let s = 0; s < count; s++) {\n      if (state[s] !== EMPTY && !inbound[s]) {\n        ox.push(xs[s]);\n        oy.push(ys[s]);\n        ok.push(state[s]);\n      }\n    }\n    for (const d of dots) {\n      if (d.role !== LAND || t < d.appear) continue;\n      at(d.c, ease(clamp01((t - d.t0) / d.dur)), point);\n      ox.push(point[0]);\n      oy.push(point[1]);\n      ok.push(d.kind);\n    }\n    if (options.reduced) snapshot();\n    dots = dots.filter((d) => d.role === LEAVE);\n    buildSlots();\n    cacheDirty = true;\n    if (options.reduced) {\n      settleAll();\n      crossfade(true);\n      return;\n    }\n\n    // Match old dots to new slots in reading order: split both into the same number of columns\n    // by x, then sort each column by y, so a letter trades with the letter where it lands.\n    const columns = Math.max(1, Math.round(Math.sqrt(Math.min(ox.length, count)) / 2));\n    const order = (n: number, x: (i: number) => number, y: (i: number) => number) => {\n      const byX = Array.from({ length: n }, (_, i) => i).sort((a, b) => x(a) - x(b));\n      const out: number[] = [];\n      for (let c = 0; c < columns; c++) {\n        const part = byX.slice(Math.floor((c * n) / columns), Math.floor(((c + 1) * n) / columns));\n        part.sort((a, b) => y(a) - y(b));\n        out.push(...part);\n      }\n      return out;\n    };\n    const olds = order(ox.length, (i) => ox[i], (i) => oy[i]);\n    const news = order(count, (i) => xs[i], (i) => ys[i]);\n    const N = olds.length;\n    const M = news.length;\n    const taken = new Uint8Array(M);\n    const spread = TIMING.reroute.spread;\n    if (N >= M) {\n      const used = new Uint8Array(N);\n      for (let j = 0; j < M; j++) {\n        const i = Math.min(N - 1, Math.floor((j * N) / M));\n        used[i] = 1;\n        flyTo(ox[olds[i]], oy[olds[i]], news[j], t + random() * spread);\n        taken[j] = 1;\n      }\n      for (let i = 0; i < N; i++) {\n        if (used[i]) continue;\n        leave(ox[olds[i]], oy[olds[i]], ok[olds[i]], t + random() * spread, vary(TIMING.reroute.flight), t);\n      }\n    } else {\n      for (let i = 0; i < N; i++) {\n        const j = Math.min(M - 1, Math.floor((i * M) / N));\n        flyTo(ox[olds[i]], oy[olds[i]], news[j], t + random() * spread);\n        taken[j] = 1;\n      }\n      for (let j = 0; j < M; j++) {\n        if (taken[j]) continue;\n        const t0 = t + TIMING.lead * 0.5 + random() * spread;\n        arrive(news[j], settledKind(news[j]), t0, vary(TIMING.reroute.flight), t + random() * TIMING.lead * 0.5);\n      }\n    }\n    settling = true;\n    wake();\n  }\n\n  /** A dot already in the box flying from (x, y) to `slot`, taking the slot's kind on the way. */\n  function flyTo(x: number, y: number, slot: number, t0: number) {\n    inbound[slot] = 1;\n    dots.push({\n      slot,\n      kind: settledKind(slot),\n      role: LAND,\n      c: curve(x, y, xs[slot], ys[slot], SWARM.swirlShort),\n      appear: Math.min(t0, now()),\n      t0,\n      dur: vary(TIMING.reroute.flight),\n    });\n  }\n\n  function refill(next: number) {\n    if (next === solid) return;\n    if (!played || !count) {\n      solid = next;\n      return;\n    }\n    const t = now();\n    if (options.reduced) {\n      snapshot();\n      solid = next;\n      settleAll();\n      crossfade(true);\n      return;\n    }\n    solid = next;\n    // Dots still on their way just change what they'll be when they land.\n    for (const d of dots) if (d.role === LAND) d.kind = settledKind(d.slot);\n    const grow: number[] = [];\n    const shrink: number[] = [];\n    for (let s = 0; s < count; s++) {\n      if (inbound[s]) continue;\n      const want = settledKind(s);\n      if (state[s] === HOLLOW && want === SOLID) grow.push(s);\n      else if (state[s] === SOLID && want === HOLLOW) shrink.push(s);\n    }\n    // Fill in the fixed order, spread wider when more change, up to the cap.\n    grow.sort((a, b) => rank[a] - rank[b]);\n    const spread = Math.min(TIMING.refill.spread, TIMING.refill.step * Math.sqrt(grow.length + shrink.length));\n    grow.forEach((s, i) => {\n      const t0 = t + TIMING.lead * 0.5 + (grow.length > 1 ? i / (grow.length - 1) : 0) * spread;\n      arrive(s, SOLID, t0, vary(TIMING.refill.flight), t + (i / Math.max(1, grow.length)) * spread);\n    });\n    for (const s of shrink) {\n      state[s] = HOLLOW;\n      leave(xs[s], ys[s], SOLID, t + random() * spread, vary(TIMING.refill.flight), t);\n    }\n    cacheDirty = true;\n    settling = true;\n    wake();\n  }\n\n  /** A late dot from a corner, merging into a solid slot. */\n  function stray() {\n    if (!solid || !count) return;\n    let slot = -1;\n    for (let tries = 0; tries < 12 && slot < 0; tries++) {\n      const s = Math.floor(random() * count);\n      if (state[s] === SOLID && !inbound[s]) slot = s;\n    }\n    if (slot < 0) return;\n    const corner = Math.floor(random() * 4);\n    const cornerAngle = Math.atan2((corner & 1 ? 1 : -1) * height, (corner & 2 ? 1 : -1) * width);\n    const [x, y] = edgeAt(cornerAngle + (random() - 0.5) * SWARM.corner * 2, radius);\n    const t = now();\n    dots.push({\n      slot,\n      kind: SOLID,\n      role: STRAY,\n      c: curve(x, y, xs[slot], ys[slot], SWARM.swirl),\n      appear: t,\n      t0: t + TIMING.pop,\n      dur: vary(TIMING.drift.flight, 0.2),\n    });\n    wake();\n  }\n\n  function scheduleDrift() {\n    window.clearTimeout(driftTimer);\n    driftTimer = 0;\n    if (!options.drift || options.reduced || !played || settling || !awake() || !solid) return;\n    driftTimer = window.setTimeout(\n      () => {\n        driftTimer = 0;\n        stray();\n        scheduleDrift();\n      },\n      TIMING.drift.every * (0.6 + random() * 0.8) * 1000,\n    );\n  }\n\n  function drawCache() {\n    cacheDirty = false;\n    if (!canvas) return;\n    cache ??= document.createElement(\"canvas\");\n    if (cache.width !== canvas.width || cache.height !== canvas.height) {\n      cache.width = canvas.width;\n      cache.height = canvas.height;\n    }\n    const c = cache.getContext(\"2d\");\n    if (!c) return;\n    c.setTransform(1, 0, 0, 1, 0, 0);\n    c.clearRect(0, 0, cache.width, cache.height);\n    c.setTransform(dpr, 0, 0, dpr, 0, 0);\n    const fill = new Path2D();\n    const rings = new Path2D();\n    const r = radius;\n    const rr = Math.max(0.5, r - SWARM.ring / 2);\n    for (let s = 0; s < count; s++) {\n      // A slot whose dot is still flying in shows nothing, or its ring while a solid dot comes to fill it.\n      const v = state[s];\n      if (v === SOLID) {\n        fill.moveTo(xs[s] + r, ys[s]);\n        fill.arc(xs[s], ys[s], r, 0, Math.PI * 2);\n      } else if (v === HOLLOW) {\n        rings.moveTo(xs[s] + rr, ys[s]);\n        rings.arc(xs[s], ys[s], rr, 0, Math.PI * 2);\n      }\n    }\n    const style = paint(c);\n    c.fillStyle = style;\n    c.strokeStyle = ringColor ?? style;\n    c.lineWidth = SWARM.ring;\n    c.fill(fill);\n    c.stroke(rings);\n  }\n\n  function frame() {\n    raf = 0;\n    draw();\n  }\n\n  function draw() {\n    if (!ctx || !canvas) return;\n    const t = now();\n    const span = options.trails ? options.trail : 0;\n\n    // Landings first, so a dot that lands this frame is already in the settled layer.\n    let landing = 0;\n    for (const d of dots) {\n      if (d.role !== LAND) continue;\n      if (t >= d.t0 + d.dur) {\n        if (inbound[d.slot]) {\n          state[d.slot] = d.kind;\n          inbound[d.slot] = 0;\n          cacheDirty = true;\n        }\n      } else landing++;\n    }\n    dots = dots.filter((d) => t < d.t0 + d.dur * (1 + span));\n\n    ctx.setTransform(1, 0, 0, 1, 0, 0);\n    ctx.clearRect(0, 0, canvas.width, canvas.height);\n    if (cacheDirty) drawCache();\n    let fading = false;\n    if (cache) {\n      if (fadeT0 >= 0) {\n        const a = clamp01((t - fadeT0) / TIMING.fade);\n        if (prev) {\n          ctx.globalAlpha = 1 - a;\n          ctx.drawImage(prev, 0, 0);\n        }\n        ctx.globalAlpha = a;\n        ctx.drawImage(cache, 0, 0);\n        ctx.globalAlpha = 1;\n        if (a >= 1) {\n          fadeT0 = -1;\n          prev = null;\n        } else fading = true;\n      } else ctx.drawImage(cache, 0, 0);\n    }\n\n    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n    const trail = new Path2D();\n    const fill = new Path2D();\n    const rings = new Path2D();\n    let traced = false;\n    for (const d of dots) {\n      if (t < d.appear) continue;\n      const u = (t - d.t0) / d.dur;\n      const head = u <= 0 ? 0 : u >= 1 ? 1 : ease(u);\n      if (span > 0 && u > 0) {\n        const tail = ease(clamp01(u - span));\n        if (head - tail > 0.001) {\n          addPiece(trail, d.c, tail, head);\n          traced = true;\n        }\n      }\n      // Landed and merged dots live in the settled layer; only their trail is still reeling in.\n      if (u >= 1 && d.role !== LEAVE) continue;\n      at(d.c, head, point);\n      const grow = u <= 0 ? clamp01((t - d.appear) / TIMING.pop) : 1;\n      const scale =\n        d.role === LEAVE\n          ? 1 - (1 - SWARM.flightSize) * head\n          : u <= 0\n            ? 1\n            : SWARM.flightSize + (1 - SWARM.flightSize) * head;\n      const r = radius * scale * grow;\n      if (r < 0.3) continue;\n      if (d.kind === SOLID) {\n        fill.moveTo(point[0] + r, point[1]);\n        fill.arc(point[0], point[1], r, 0, Math.PI * 2);\n      } else {\n        const rr = Math.max(0.4, r - SWARM.ring / 2);\n        rings.moveTo(point[0] + rr, point[1]);\n        rings.arc(point[0], point[1], rr, 0, Math.PI * 2);\n      }\n    }\n    const style = paint(ctx);\n    ctx.strokeStyle = style;\n    ctx.fillStyle = style;\n    if (traced) {\n      ctx.globalAlpha = SWARM.trailAlpha;\n      ctx.lineWidth = SWARM.trailWidth;\n      ctx.stroke(trail);\n      ctx.globalAlpha = 1;\n    }\n    ctx.fill(fill);\n    ctx.strokeStyle = ringColor ?? style;\n    ctx.lineWidth = SWARM.ring;\n    ctx.stroke(rings);\n\n    if (settling && !landing && !fading && !dots.some((d) => d.role === LEAVE)) {\n      settling = false;\n      if (relayPending) {\n        relayPending = false;\n        reroute(); // settles again, and reports then\n        return;\n      }\n      onSettle?.();\n      scheduleDrift();\n    }\n    // Called outside the loop too (a color change), so never start a second loop.\n    if (!raf && (dots.length || fading) && awake()) raf = requestAnimationFrame(frame);\n  }\n\n  function wake() {\n    if (raf || !awake() || !ctx) return;\n    raf = requestAnimationFrame(frame);\n  }\n\n  function layout() {\n    if (!root || !canvas) return;\n    const w = root.clientWidth;\n    const h = root.clientHeight;\n    const nextDpr = Math.min(window.devicePixelRatio || 1, SWARM.maxDpr);\n    if (w === width && h === height && nextDpr === dpr) return;\n    width = w;\n    height = h;\n    dpr = nextDpr;\n    canvas.width = Math.max(1, Math.round(w * dpr));\n    canvas.height = Math.max(1, Math.round(h * dpr));\n    rebuild();\n  }\n\n  /** Lays the lattice again and snaps to the settled mark; an entrance that hasn't played waits. */\n  function rebuild() {\n    // A resize mid-flight snaps to the settled mark, and still reports it as settled.\n    const interrupted = played && settling;\n    buildSlots();\n    dots = [];\n    prev = null;\n    fadeT0 = -1;\n    relayPending = false;\n    if (played) {\n      settleAll();\n      settling = false;\n    }\n    cacheDirty = true;\n    draw();\n    if (interrupted) onSettle?.();\n    if (!played && awake()) play();\n    scheduleDrift();\n  }\n\n  function setAwake() {\n    if (awake()) {\n      if (!played && width) play();\n      wake();\n      scheduleDrift();\n    } else {\n      cancelAnimationFrame(raf);\n      raf = 0;\n      window.clearTimeout(driftTimer);\n      driftTimer = 0;\n      dots = dots.filter((d) => d.role !== STRAY);\n    }\n  }\n\n  return {\n    connect(el: { root: HTMLElement; canvas: HTMLCanvasElement; dot: HTMLElement; to: HTMLElement; ring: HTMLElement }) {\n      root = el.root;\n      canvas = el.canvas;\n      ctx = canvas.getContext(\"2d\");\n      probes = { dot: el.dot, to: el.to, ring: el.ring };\n      width = 0;\n      pageVisible = document.visibilityState === \"visible\";\n      readColors();\n      layout();\n\n      const resize = new ResizeObserver(() => layout());\n      resize.observe(root);\n      const io = new IntersectionObserver(\n        ([entry]) => {\n          inView = entry.isIntersecting;\n          setAwake();\n        },\n        { threshold: 0.25 },\n      );\n      io.observe(root);\n      const visibility = () => {\n        pageVisible = document.visibilityState === \"visible\";\n        setAwake();\n      };\n      document.addEventListener(\"visibilitychange\", visibility);\n      const scheme = window.matchMedia(\"(prefers-color-scheme: dark)\");\n      scheme.addEventListener(\"change\", readColors);\n      const themeAttrs = new MutationObserver(readColors);\n      themeAttrs.observe(document.documentElement, { attributes: true, attributeFilter: [\"class\", \"data-theme\", \"style\"] });\n      // Text is measured in its real font once it has loaded.\n      let alive = true;\n      document.fonts?.ready.then(() => {\n        if (!alive || source.kind !== \"text\") return;\n        // Before the entrance, lay it again quietly; during one, after it lands; after it, fly there.\n        if (!played) rebuild();\n        else if (settling) relayPending = true;\n        else reroute();\n      });\n\n      cleanups.push(\n        () => resize.disconnect(),\n        () => io.disconnect(),\n        () => document.removeEventListener(\"visibilitychange\", visibility),\n        () => scheme.removeEventListener(\"change\", readColors),\n        () => themeAttrs.disconnect(),\n        () => (alive = false),\n      );\n      return () => {\n        cancelAnimationFrame(raf);\n        raf = 0;\n        window.clearTimeout(driftTimer);\n        driftTimer = 0;\n        dots = [];\n        inView = false;\n        cleanups.splice(0).forEach((fn) => fn());\n        root = canvas = null;\n        probes = null;\n        ctx = null;\n      };\n    },\n\n    setOptions(next: Options) {\n      const relay = next.dotSize !== options.dotSize || next.gap !== options.gap;\n      const reducedChanged = next.reduced !== options.reduced;\n      const fillChanged = next.fill !== options.fill;\n      options = next;\n      if (relay) {\n        if (width) rebuild();\n        return;\n      }\n      if (reducedChanged && played) {\n        const interrupted = settling;\n        settleAll();\n        dots = [];\n        settling = false;\n        draw();\n        if (interrupted) onSettle?.();\n      }\n      if (fillChanged) refill(Math.round(clamp01(next.fill) * count));\n      scheduleDrift();\n    },\n\n    setSource(next: Source) {\n      if (keyOf(next) === keyOf(source)) return;\n      source = next;\n      relayPending = false;\n      if (!width) return;\n      if (played) reroute();\n      else rebuild();\n    },\n\n    /** Reads the colors again, after the probes' classes change. */\n    setTones(next: { gradient: boolean; ring: boolean }) {\n      tones = next;\n      readColors();\n    },\n\n    setOnSettle(fn: (() => void) | null) {\n      onSettle = fn;\n    },\n  };\n}\n\ntype Engine = ReturnType<typeof createSwarm>;\n\nfunction parseViewBox(viewBox: string): [number, number, number, number] {\n  const n = viewBox.split(/[\\s,]+/).map(Number);\n  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];\n}\n\nexport interface SwarmProps extends React.HTMLAttributes<HTMLDivElement> {\n  /** A word or short line for the dots to form. Use `\\n` for a second line. */\n  text?: string;\n  /** Font family `text` is set in, at weight 800, before it's turned into dots. */\n  textFont?: string;\n  /** An SVG path (`d`) for the dots to form, such as your logo mark. Read against `viewBox`. */\n  path?: string;\n  /** The coordinate box `path` is drawn in, like an SVG's `viewBox`. */\n  viewBox?: string;\n  /** 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. */\n  fill?: number;\n  /** Diameter of a landed dot, in px. */\n  dotSize?: number;\n  /** Space between neighbouring dots, in px. */\n  gap?: number;\n  /** Draw each dot's path behind it as a hairline that reels in when it lands. */\n  trails?: boolean;\n  /** Once settled, keep a few late dots coming in from the corners on long trails. */\n  drift?: boolean;\n  /** Seconds a dot takes to fly from the edge to its slot. Each one varies by a quarter either way. */\n  duration?: number;\n  /** Seconds between the first dot leaving the edge and the last. */\n  stagger?: number;\n  /** How far a trail lags behind its dot, as a share of the flight. */\n  trailLength?: number;\n  /** Describes the mark for screen readers. Defaults to `text`; without either, the swarm is decorative. */\n  label?: string;\n  /** A `text-*` color for the dots and trails. The canvas reads it, so `dark:` variants work. */\n  dotClassName?: string;\n  /** 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. */\n  gradientClassName?: string;\n  /** 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. */\n  ringClassName?: string;\n  /** Classes for the canvas. It fills the box by default; the mark is fitted inside it. */\n  canvasClassName?: string;\n  /** Called each time every dot has landed: after the entrance, a new mark or a new `fill`. */\n  onSettle?: () => void;\n}\n\nexport function Swarm({\n  text,\n  textFont = \"ui-sans-serif, system-ui, sans-serif\",\n  path,\n  viewBox = \"0 0 24 24\",\n  fill = 0.9,\n  dotSize = 6,\n  gap = 1.5,\n  trails = true,\n  drift = true,\n  duration = TIMING.flight,\n  stagger = TIMING.spread,\n  trailLength = TIMING.trail,\n  label,\n  dotClassName,\n  gradientClassName,\n  ringClassName,\n  canvasClassName,\n  onSettle,\n  className,\n  children,\n  ...props\n}: SwarmProps) {\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const canvasRef = React.useRef<HTMLCanvasElement>(null);\n  const dotRef = React.useRef<HTMLSpanElement>(null);\n  const toRef = React.useRef<HTMLSpanElement>(null);\n  const ringRef = React.useRef<HTMLSpanElement>(null);\n  const [engine] = React.useState<Engine>(createSwarm);\n  const reduced = useReduced();\n\n  React.useLayoutEffect(() => {\n    const root = rootRef.current;\n    const canvas = canvasRef.current;\n    const dot = dotRef.current;\n    const to = toRef.current;\n    const ring = ringRef.current;\n    if (!root || !canvas || !dot || !to || !ring) return;\n    return engine.connect({ root, canvas, dot, to, ring });\n  }, [engine]);\n\n  React.useEffect(() => {\n    engine.setOptions({\n      fill: clamp01(fill),\n      dotSize: Math.max(1.5, dotSize),\n      gap: Math.max(0, gap),\n      trails,\n      drift,\n      flight: Math.max(0.1, duration),\n      spread: Math.max(0, stagger),\n      trail: clamp01(trailLength),\n      reduced,\n    });\n  }, [engine, fill, dotSize, gap, trails, drift, duration, stagger, trailLength, reduced]);\n\n  React.useEffect(() => {\n    if (text) engine.setSource({ kind: \"text\", text, font: textFont });\n    else if (path) engine.setSource({ kind: \"path\", d: path, box: parseViewBox(viewBox) });\n    else engine.setSource({ kind: \"disc\" });\n  }, [engine, text, textFont, path, viewBox]);\n\n  // The probes' classes are already on the page by the time this runs, so the colors read fresh.\n  const gradient = !!gradientClassName;\n  const ring = !!ringClassName;\n  React.useEffect(() => {\n    engine.setTones({ gradient, ring });\n  }, [engine, gradient, ring, dotClassName, gradientClassName, ringClassName]);\n\n  const onSettleRef = React.useRef(onSettle);\n  React.useEffect(() => {\n    onSettleRef.current = onSettle;\n  });\n  React.useEffect(() => {\n    engine.setOnSettle(() => onSettleRef.current?.());\n    return () => engine.setOnSettle(null);\n  }, [engine]);\n\n  const name = label ?? text;\n  return (\n    <div ref={rootRef} className={cn(\"relative isolate\", className)} {...props}>\n      <canvas\n        ref={canvasRef}\n        role={name ? \"img\" : undefined}\n        aria-label={name}\n        aria-hidden={name ? undefined : true}\n        className={cn(\"pointer-events-none absolute inset-0 -z-10 size-full\", canvasClassName)}\n      />\n      {/* 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. */}\n      <span ref={dotRef} aria-hidden className={cn(\"hidden\", dotClassName ?? \"text-[#2f45e8] dark:text-[#8b98ff]\")} />\n      <span ref={toRef} aria-hidden className={cn(\"hidden\", gradientClassName)} />\n      <span ref={ringRef} aria-hidden className={cn(\"hidden\", ringClassName)} />\n      {children}\n    </div>\n  );\n}\n"
    }
  ]
}