{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tally",
  "type": "registry:ui",
  "title": "Tally",
  "description": "Animated Dot Chart: every dot is a unit, and the dots that moved fly between clusters. A take on the chart (graph). Fits stats, app UI and about sections.",
  "author": "KeyframeUI <https://keyframeui.com>",
  "categories": [
    "stats",
    "app-ui",
    "about",
    "chart",
    "particle-effect",
    "data",
    "canvas"
  ],
  "docs": "Live preview, examples and props: https://keyframeui.com/components/tally",
  "dependencies": [
    "clsx",
    "tailwind-merge"
  ],
  "registryDependencies": [
    "utils"
  ],
  "files": [
    {
      "path": "components/ui/tally.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 was to its slot),\n *   so it lands exactly, a new update starts from where each dot is, and the loop stops once nothing\n *   moves.\n * - A cluster fills its hex spiral from the middle out, so it grows and shrinks at its rim and stays\n *   round; a shrinking cluster hands its outermost dots to the nearest growing cluster first.\n * - Dots keep their identity and `per` stays fixed once picked: a unit that moved between categories\n *   flies between clusters and is never swapped for a new dot. Only a change in the total brings dots\n *   in from the edge or sends them out through it.\n * - Each cluster draws in its item's color, read from a swatch beside its label, and a dot crossing\n *   to another cluster shades from the old color to the new one as it flies.\n * - Under reduced motion nothing flies: the chart crossfades to the new numbers and counts jump.\n */\nconst TIMING = {\n  /** Dots gathering along the edge before the first one leaves, on the way in, in seconds. */\n  gather: 0.45,\n  /** A dot's flight, in seconds (the `duration` prop): in from the edge, or across to another cluster. Each varies ±25%. */\n  flight: 1.1,\n  /** Seconds between the first launch and the last on the way in (the `stagger` prop). */\n  spread: 0.9,\n  /** Seconds between the first launch and the last when the numbers change. */\n  moveSpread: 0.5,\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.55,\n  /** A dot sliding to a new place in its own cluster when the chart relays out, in seconds. */\n  shift: 0.6,\n  /** Clusters other than the pointed one dimming, in seconds. */\n  dim: 0.2,\n  /** The labels dimming with them. */\n  labelDim: \"duration-200\",\n  /** A label under a `free` cluster sliding as the cluster grows or shrinks. */\n  labelSlide: \"transform 0.6s cubic-bezier(0.65, 0, 0.35, 1)\",\n  /** Under reduced motion, the crossfade that replaces every flight, in seconds. */\n  fade: 0.3,\n} as const;\n\n/* ─────────────────────────────────────────────────────────\n * TALLY STORYBOARD\n *\n *  rest     one round cluster per category, every dot a\n *           fixed amount (`per`), packed on a hex lattice\n *           from the middle out; units you mark `hollow`\n *           (failed, refunded) are rings among the dots.\n *           Labels sit under the clusters with exact counts\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 behind the cluster it's bound for\n *  flight   0.45s in they leave over 0.9s, each bowing in on\n *           a cubic for about 1.1s and growing from 62% to\n *           full size; its trail is its own path, lagging 55%\n *           of the flight, reeling in once it lands\n *  move     new numbers: each shrinking cluster gives its\n *           outermost dots to the nearest growing one, which\n *           takes them at its rim. They fly across on bowed\n *           curves, launched over 0.5s. Counts step as dots\n *           leave and land, and read exact when it's over\n *  total    a bigger total brings the extra dots in from the\n *           edge; a smaller one sends dots out through it\n *  relay    when clusters no longer fit (one grew past its\n *           room), the whole lattice tightens and dots slide\n *           to their new places in 0.6s\n *  point    the pointer over a cluster or its label dims the\n *           others to 22% in 0.2s; a tap does the same on touch\n *  resize   the layout is laid again and snaps; nothing replays\n *  sleep    off screen or in a hidden tab nothing draws;\n *           flights finish on time while hidden\n *  reduced  no flights: the chart crossfades to the new numbers\n *           in 0.3s and counts jump\n * ───────────────────────────────────────────────────────── */\n\nconst TALLY = {\n  targetDots: 600, // dots in all, when `per` is picked for you\n  headroom: 1.6, // area a cluster can grow into at full dot size, as a multiple of its first size\n  minCell: 132, // px, narrowest column in a row before clusters wrap onto another row\n  labelBand: 46, // px under each row of clusters for its labels\n  legendBand: 28, // px above the clusters for the legend\n  margin: 8, // px between a cluster and the edge of its room\n  labelGap: 8, // px between a `free` cluster and its label\n  rings: 44, // hex rings in the spiral a cluster fills\n  rim: 0.55, // pitch, noise on the spiral order, so a rim fills unevenly instead of as a perfect hexagon\n  jitter: 1.6, // rad, spread of a dot's start around the line from the middle through its cluster\n  band: 3, // rows deep the edge band can stack\n  swirl: [0.1, 0.32], // sideways bow of a long flight, share of its length\n  swirlShort: [0.04, 0.14], // and of a short slide\n  launch: 0.3, // share of its length a flight heads straight out 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,\n  dim: 0.22, // opacity of the clusters you're not pointing at\n  tints: 8, // color steps a dot crossing between clusters shades through\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 where it was 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 a cluster always marks the same dots hollow. */\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  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  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\n/* ── Spiral ───────────────────────────────────────────── */\n// The order a cluster fills its lattice: hex points sorted by distance from the middle, with a\n// little fixed noise so the rim grows unevenly. In pitch units; built once.\n\nlet spiralXY: Float32Array | null = null;\nlet spiralReach: Float32Array | null = null; // farthest point among the first i + 1, for fitting\n\nfunction spiral() {\n  if (spiralXY && spiralReach) return { xy: spiralXY, reach: spiralReach };\n  const K = TALLY.rings;\n  const pts: [number, number, number, number][] = [];\n  for (let q = -K; q <= K; q++) {\n    for (let r = Math.max(-K, -q - K); r <= Math.min(K, -q + K); r++) {\n      const x = q + r / 2;\n      const y = (r * Math.sqrt(3)) / 2;\n      const d = Math.hypot(x, y);\n      const noise = (Math.imul((q * 73856093) ^ (r * 19349663), 2654435761) >>> 0) / 4294967296;\n      pts.push([x, y, d, d + noise * TALLY.rim]);\n    }\n  }\n  pts.sort((a, b) => a[3] - b[3]);\n  spiralXY = new Float32Array(pts.length * 2);\n  spiralReach = new Float32Array(pts.length);\n  let far = 0;\n  pts.forEach(([x, y, d], i) => {\n    spiralXY![i * 2] = x;\n    spiralXY![i * 2 + 1] = y;\n    far = Math.max(far, d);\n    spiralReach![i] = far;\n  });\n  return { xy: spiralXY, reach: spiralReach };\n}\n\n/** How many dots fit within `radius` pitches of the middle, dot edges included. */\nfunction capacity(radius: number) {\n  const { reach } = spiral();\n  let lo = 0;\n  let hi = reach.length;\n  while (lo < hi) {\n    const mid = (lo + hi) >> 1;\n    if (reach[mid] + 0.5 <= radius) lo = mid + 1;\n    else hi = mid;\n  }\n  return lo;\n}\n\n/** The smallest of 1, 2, 2.5, 5 × 10^k at or above `x`, so the legend reads cleanly. */\nfunction niceUp(x: number) {\n  if (!(x > 0)) return 1;\n  const k = Math.pow(10, Math.floor(Math.log10(x)));\n  for (const m of [1, 2, 2.5, 5, 10]) if (m * k >= x * 0.9999) return m * k;\n  return 10 * k;\n}\n\n/** Item colors when an item doesn't set one, by position: vivid on white and on zinc-950 alike. */\nconst PALETTE = [\n  \"text-[#ff5a1f] dark:text-[#ff7a45]\", // hot orange\n  \"text-[#7c3aed] dark:text-[#a78bfa]\", // electric violet\n  \"text-[#00b25d] dark:text-[#34d399]\", // vivid green\n  \"text-[#ff2d87] dark:text-[#ff5ca8]\", // hot pink\n  \"text-[#2f45e8] dark:text-[#8b98ff]\", // electric blue\n  \"text-[#f59e0b] dark:text-[#fbbf24]\", // amber\n] as const;\n\ntype RGB = [number, number, number];\nlet parser: CanvasRenderingContext2D | null = null;\n\n/** Any CSS color as RGB, read back from a 1px canvas so oklch and friends work too. */\nfunction rgbOf(css: string): RGB {\n  parser ??= document.createElement(\"canvas\").getContext(\"2d\", { willReadFrequently: true });\n  if (!parser) return [47, 69, 232];\n  parser.clearRect(0, 0, 1, 1);\n  parser.fillStyle = \"#2f45e8\";\n  parser.fillStyle = css;\n  parser.fillRect(0, 0, 1, 1);\n  const [r, g, b] = parser.getImageData(0, 0, 1, 1).data;\n  return [r, g, b];\n}\n\nexport interface TallyItem {\n  /** Stable id. The same id keeps its cluster, its dots and its place across updates. */\n  id: string;\n  /** Shown under the cluster. */\n  label: string;\n  /** The amount; the cluster holds `value / per` dots, rounded. */\n  value: number;\n  /** How much of `value` is drawn as hollow rings instead of solid dots, like failed requests. */\n  hollow?: number;\n  /** For `layout=\"free\"`: where the cluster sits across the box, 0–1. */\n  x?: number;\n  /** For `layout=\"free\"`: where it sits down the box, 0–1. */\n  y?: number;\n  /** A `text-*` color for this cluster's dots and its label's swatch. Without it, the next color of the built-in palette. */\n  dotClassName?: string;\n}\n\ntype Layout = \"row\" | \"free\";\n\ntype Options = {\n  per: number | undefined;\n  layout: Layout;\n  legend: boolean;\n  dotSize: number;\n  gap: number;\n  trails: boolean;\n  flight: number;\n  spread: number;\n  trail: number;\n  reduced: boolean;\n};\n\ntype Cluster = {\n  id: string;\n  item: TallyItem;\n  n: number; // dots it holds once settled\n  h: number; // of which hollow\n  cx: number;\n  cy: number;\n  room: number; // px, the radius it may fill\n  reach: number; // px, the radius it does fill once settled\n  dots: Dot[]; // in spiral order: dots[i] rests on spiral point i\n  keys: Float32Array | null; // per spiral point, which ones turn hollow first\n  hollow: Uint8Array;\n  alpha: number;\n  alphaFrom: number;\n  alphaTo: number;\n  alphaT0: number;\n  rgb: RGB; // its color\n  css: string;\n};\n\ntype Dot = {\n  home: Cluster | null; // the cluster it belongs to; null while it leaves the box\n  from: Cluster | null; // a cluster it left that still counts it until it launches\n  index: number;\n  x: number; // where it rests: its slot, or the point past the edge it leaves for\n  y: number;\n  c: Float64Array | null; // its flight, while it has one\n  appear: number;\n  t0: number;\n  dur: number;\n  landed: boolean; // flight over; the trail may still be reeling in\n  stay: boolean; // sliding inside its own cluster, so it still counts there\n  intro: boolean; // flying in with the entrance; counts already show it\n  tint: Cluster | null; // the cluster whose color it shades from while it flies\n  kind: number; // for a dot leaving the box\n};\n\nconst SOLID = 2;\nconst HOLLOW = 1;\n\ntype TallySnapshot = {\n  /** Units per dot, once picked. */\n  per: number | null;\n  /** Each label's anchor (x, top) and width, in px, once laid out. */\n  labels: Record<string, [number, number, number]> | null;\n  /** Each cluster's count while dots are moving; null when every count is exact. */\n  counts: Record<string, number> | null;\n  /** The cluster the pointer is on. */\n  active: string | null;\n  layout: Layout;\n};\n\nconst SERVER_SNAPSHOT: TallySnapshot = { per: null, labels: null, counts: null, active: null, layout: \"row\" };\n\nfunction createTally() {\n  let root: HTMLElement | null = null;\n  let canvas: HTMLCanvasElement | null = null;\n  let ctx: CanvasRenderingContext2D | null = null;\n  let options: Options = {\n    per: undefined,\n    layout: \"row\",\n    legend: true,\n    dotSize: 6,\n    gap: 1.5,\n    trails: true,\n    flight: TIMING.flight,\n    spread: TIMING.spread,\n    trail: TIMING.trail,\n    reduced: false,\n  };\n  let onSettle: (() => void) | null = null;\n\n  let width = 0;\n  let height = 0;\n  let dpr = 1;\n  let pitch = 7.5;\n  let radius = 3;\n  let per: number | null = null;\n  let items: TallyItem[] = [];\n  let signature = \"\";\n  let clusters: Cluster[] = [];\n  let flying: Dot[] = [];\n  let counting = false;\n\n  let cache: HTMLCanvasElement | null = null;\n  let cacheDirty = true;\n  let prev: HTMLCanvasElement | null = null;\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 active: string | null = null;\n  const random = seeded(\"tally\");\n  const point = new Float64Array(2);\n  const cleanups: (() => void)[] = [];\n\n  let snapshot: TallySnapshot = { ...SERVER_SNAPSHOT };\n  const listeners = new Set<() => void>();\n  const publish = (patch: Partial<TallySnapshot>) => {\n    snapshot = { ...snapshot, ...patch };\n    listeners.forEach((fn) => fn());\n  };\n\n  const now = () => performance.now() / 1000;\n  const awake = () => inView && pageVisible;\n  const vary = (dur: number, by = 0.25) => dur * (1 - by + random() * by * 2);\n\n  /** Each cluster's color, from the swatch beside its label. */\n  function readTints() {\n    for (const c of clusters) {\n      const swatch = root?.querySelector<HTMLElement>(`[data-tally-swatch=\"${CSS.escape(c.id)}\"]`);\n      if (!swatch) continue;\n      c.rgb = rgbOf(getComputedStyle(swatch).color);\n      c.css = `rgb(${c.rgb.join(\", \")})`;\n    }\n    cacheDirty = true;\n  }\n\n  function readColors() {\n    readTints();\n    draw();\n  }\n\n  /** A dot's color `mix` of the way from one cluster's color to another's, in a few steps so dots batch. */\n  function tint(from: Cluster, to: Cluster, mix: number) {\n    if (from === to || mix >= 1) return to.css;\n    if (mix <= 0) return from.css;\n    const k = Math.round(mix * TALLY.tints) / TALLY.tints;\n    const a = from.rgb;\n    const b = to.rgb;\n    return `rgb(${Math.round(a[0] + (b[0] - a[0]) * k)}, ${Math.round(a[1] + (b[1] - a[1]) * k)}, ${Math.round(a[2] + (b[2] - a[2]) * k)})`;\n  }\n\n  function newCluster(item: TallyItem): Cluster {\n    return {\n      id: item.id,\n      item,\n      n: 0,\n      h: 0,\n      cx: width / 2,\n      cy: height / 2,\n      room: 0,\n      reach: 0,\n      dots: [],\n      keys: null,\n      hollow: new Uint8Array(0),\n      alpha: 1,\n      alphaFrom: 1,\n      alphaTo: 1,\n      alphaT0: -1,\n      rgb: [47, 69, 232],\n      css: \"rgb(47, 69, 232)\",\n    };\n  }\n\n  /** Each cluster's middle and the room it has, from the layout. */\n  function rooms() {\n    const N = clusters.length;\n    if (!N || !width || !height) return;\n    const top = options.legend ? TALLY.legendBand : 0;\n    const labels: Record<string, [number, number, number]> = {};\n    if (options.layout === \"row\") {\n      let cols = Math.max(1, Math.min(N, Math.floor(width / TALLY.minCell)));\n      const rows = Math.ceil(N / cols);\n      cols = Math.ceil(N / rows);\n      const cellW = width / cols;\n      const cellH = (height - top) / rows;\n      const areaH = Math.max(0, cellH - TALLY.labelBand);\n      clusters.forEach((c, k) => {\n        const row = Math.floor(k / cols);\n        const col = k % cols;\n        const inRow = Math.min(cols, N - row * cols);\n        const x0 = ((cols - inRow) * cellW) / 2 + col * cellW;\n        const y0 = top + row * cellH;\n        c.cx = x0 + cellW / 2;\n        c.cy = y0 + areaH / 2;\n        c.room = Math.max(0, Math.min(cellW, areaH) / 2 - TALLY.margin);\n        labels[c.id] = [c.cx, y0 + areaH + 2, cellW - 8];\n      });\n    } else {\n      const areaH = Math.max(0, height - top - TALLY.labelBand);\n      clusters.forEach((c, k) => {\n        c.cx = clamp01(c.item.x ?? (k + 0.5) / N) * width;\n        c.cy = top + clamp01(c.item.y ?? 0.5) * areaH;\n      });\n      clusters.forEach((c) => {\n        let room = Math.min(c.cx, width - c.cx, c.cy - top + TALLY.margin, top + areaH - c.cy + TALLY.margin);\n        for (const o of clusters) if (o !== c) room = Math.min(room, Math.hypot(o.cx - c.cx, o.cy - c.cy) / 2);\n        c.room = Math.max(0, room - TALLY.margin);\n      });\n    }\n    return labels;\n  }\n\n  /** Picks units per dot once: about `targetDots` in all, with room for each cluster to grow. */\n  function pickPer() {\n    if (options.per && options.per > 0) {\n      per = options.per;\n      return;\n    }\n    if (per !== null) return;\n    const base = options.dotSize + options.gap;\n    let total = 0;\n    let need = 0;\n    for (const c of clusters) {\n      const v = Math.max(0, c.item.value);\n      total += v;\n      const cap = capacity(c.room / base);\n      if (v > 0) need = Math.max(need, cap > 0 ? (v * TALLY.headroom) / cap : Infinity);\n    }\n    if (!total) return;\n    per = niceUp(Math.max(total / TALLY.targetDots, Number.isFinite(need) ? need : total));\n  }\n\n  /** The pitch every cluster fits at, and each cluster's settled radius and label. */\n  function fit(labels: Record<string, [number, number, number]>) {\n    const { reach } = spiral();\n    const base = Math.max(1, options.dotSize + options.gap);\n    pitch = base;\n    for (const c of clusters) if (c.n > 0) pitch = Math.min(pitch, c.room / (reach[c.n - 1] + 0.5));\n    pitch = Math.max(1.5, pitch);\n    radius = (options.dotSize / 2) * (pitch / base);\n    for (const c of clusters) {\n      c.reach = c.n > 0 ? (reach[c.n - 1] + 0.5) * pitch : 0;\n      if (options.layout === \"free\") labels[c.id] = [c.cx, c.cy + c.reach + TALLY.labelGap, Math.max(96, c.reach * 2 + 32)];\n    }\n    publish({ labels, per, layout: options.layout });\n  }\n\n  function counts() {\n    if (!per) return;\n    const max = spiral().reach.length;\n    for (const c of clusters) {\n      c.n = Math.min(max, Math.max(0, Math.round(c.item.value / per)));\n      c.h = Math.min(c.n, Math.max(0, Math.round((c.item.hollow ?? 0) / per)));\n      if (!c.keys) {\n        const r = seeded(`tally:${c.id}`);\n        c.keys = Float32Array.from({ length: max }, () => r());\n      }\n      // The h points with the lowest keys among the first n are hollow.\n      const keys = c.keys;\n      const order = Array.from({ length: c.n }, (_, i) => i).sort((a, b) => keys[a] - keys[b]);\n      c.hollow = new Uint8Array(c.n);\n      for (let i = 0; i < c.h; i++) c.hollow[order[i]] = 1;\n    }\n  }\n\n  function slot(c: Cluster, i: number): [number, number] {\n    const { xy } = spiral();\n    return [c.cx + xy[i * 2] * pitch, c.cy + xy[i * 2 + 1] * pitch];\n  }\n\n  /** Where a dot is at time t. */\n  function where(d: Dot, t: number) {\n    if (d.c && t < d.t0 + d.dur) at(d.c, t <= d.t0 ? 0 : ease((t - d.t0) / d.dur), point);\n    else {\n      point[0] = d.x;\n      point[1] = d.y;\n    }\n    return point;\n  }\n\n  /**\n   * The point on the plot's edge at `angle` from its middle, `inset` px in (negative: past it).\n   * The plot leaves out the legend above and, in a row, the labels below, so dots never wait on\n   * top of text.\n   */\n  function edgeAt(angle: number, inset: number, plot = true): [number, number] {\n    const top = plot && options.legend ? TALLY.legendBand : 0;\n    const bottom = height - (plot && options.layout === \"row\" ? TALLY.labelBand : 0);\n    const mx = width / 2;\n    const my = (top + bottom) / 2;\n    const ux = Math.cos(angle);\n    const uy = Math.sin(angle);\n    const hw = width / 2 - inset;\n    const hh = Math.max(0, (bottom - top) / 2 - inset);\n    const t = Math.min(ux ? hw / Math.abs(ux) : Infinity, uy ? hh / Math.abs(uy) : Infinity);\n    return [mx + ux * t, my + uy * t];\n  }\n\n  /** The angle from the plot's middle to (x, y). */\n  function angleTo(x: number, y: number) {\n    const top = options.legend ? TALLY.legendBand : 0;\n    const bottom = height - (options.layout === \"row\" ? TALLY.labelBand : 0);\n    return Math.atan2(y - (top + bottom) / 2, x - width / 2);\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 a 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 * TALLY.launch + nx,\n      y0 + uy * d * TALLY.launch + ny,\n      x3 - ux * d * TALLY.land + nx * 0.35,\n      y3 - uy * d * TALLY.land + ny * 0.35,\n      x3,\n      y3,\n    );\n  }\n\n  function fly(d: Dot, x: number, y: number, bow: readonly [number, number], t0: number, dur: number, appear: number) {\n    const [sx, sy] = where(d, Math.max(appear, now()));\n    d.c = curve(sx, sy, x, y, bow);\n    d.x = x;\n    d.y = y;\n    d.t0 = t0;\n    d.dur = dur;\n    d.appear = appear;\n    d.landed = false;\n    if (!flying.includes(d)) flying.push(d);\n  }\n\n  /** Every cluster holds exactly its dots, each resting on its slot. Nothing flies. */\n  function snap() {\n    for (const c of clusters) {\n      if (c.dots.length > c.n) c.dots.length = c.n;\n      while (c.dots.length < c.n) c.dots.push(blank(c, c.dots.length));\n      c.dots.forEach((d, i) => {\n        const [x, y] = slot(c, i);\n        Object.assign(d, { home: c, from: null, index: i, x, y, c: null, landed: true, stay: false, intro: false, tint: c });\n      });\n    }\n    flying = [];\n    counting = false;\n    cacheDirty = true;\n    if (snapshot.counts) publish({ counts: null });\n  }\n\n  function blank(c: Cluster, index: number): Dot {\n    const [x, y] = slot(c, index);\n    return { home: c, from: null, index, x, y, c: null, appear: 0, t0: 0, dur: 0, landed: true, stay: false, intro: false, tint: c, kind: SOLID };\n  }\n\n  /** A dot for `c` coming in from the edge behind it. */\n  function arrive(c: Cluster, t0: number, dur: number, appear: number) {\n    const index = c.dots.length;\n    const d = blank(c, index);\n    const angle = angleTo(c.cx, c.cy) + (random() - 0.5) * TALLY.jitter;\n    const [ex, ey] = edgeAt(angle, radius + Math.floor(random() * TALLY.band) * pitch * 0.9);\n    d.x = ex;\n    d.y = ey;\n    c.dots.push(d);\n    const [x, y] = slot(c, index);\n    d.c = null;\n    fly(d, x, y, TALLY.swirl, t0, dur, appear);\n  }\n\n  function play() {\n    played = true;\n    snap();\n    if (!clusters.some((c) => c.n)) return;\n    if (options.reduced) {\n      crossfade(false);\n      return;\n    }\n    const t = now();\n    for (const c of clusters) {\n      const n = c.n;\n      c.dots = [];\n      for (let i = 0; i < n; i++) {\n        const t0 = t + TIMING.gather + random() * options.spread;\n        arrive(c, t0, vary(options.flight), Math.max(t + random() * TIMING.gather, t0 - TIMING.lead * (0.3 + random() * 0.7)));\n        c.dots[c.dots.length - 1].intro = true;\n      }\n    }\n    settling = true;\n    wake();\n  }\n\n  /** New numbers, a new layout or new items: move what moved, from where it is now. */\n  function apply(removed: Cluster[]) {\n    if (!width || !height) return;\n    const labels = rooms() ?? {};\n    pickPer();\n    if (!per) {\n      publish({ labels, per: null, layout: options.layout });\n      return;\n    }\n    counts();\n    fit(labels);\n    if (!played) {\n      snap();\n      draw();\n      return;\n    }\n    if (options.reduced) {\n      keepCopy();\n      snap();\n      crossfade(true);\n      return;\n    }\n    const t = now();\n    // What each shrinking or removed cluster gives up: its outermost dots first.\n    const pool: { from: Cluster; dots: Dot[] }[] = [];\n    for (const c of clusters) if (c.dots.length > c.n) pool.push({ from: c, dots: c.dots.splice(c.n).reverse() });\n    for (const c of removed) pool.push({ from: c, dots: c.dots.splice(0).reverse() });\n    const needs = clusters.filter((c) => c.dots.length < c.n);\n    const pairs: [number, { from: Cluster; dots: Dot[] }, Cluster][] = [];\n    for (const p of pool) for (const c of needs) pairs.push([Math.hypot(p.from.cx - c.cx, p.from.cy - c.cy), p, c]);\n    pairs.sort((a, b) => a[0] - b[0]);\n    const counted = (d: Dot) => !d.c || d.landed || d.stay || d.intro;\n    let moved = 0;\n    for (const [, p, c] of pairs) {\n      while (p.dots.length && c.dots.length < c.n) {\n        const d = p.dots.shift()!;\n        if (counted(d)) d.from = p.from;\n        d.tint = p.from;\n        d.home = c;\n        d.index = c.dots.length;\n        d.stay = false;\n        d.intro = false;\n        c.dots.push(d);\n        const [x, y] = slot(c, d.index);\n        fly(d, x, y, TALLY.swirl, t + random() * TIMING.moveSpread, vary(options.flight), t);\n        moved++;\n      }\n    }\n    // A bigger total comes in from the edge; a smaller one leaves through it.\n    for (const c of needs) {\n      while (c.dots.length < c.n) {\n        arrive(c, t + TIMING.lead * 0.5 + random() * TIMING.moveSpread, vary(options.flight), t + random() * TIMING.lead * 0.5);\n        moved++;\n      }\n    }\n    for (const p of pool) {\n      for (const d of p.dots) {\n        const [x, y] = where(d, t);\n        if (counted(d)) d.from = p.from;\n        d.kind = p.from.hollow[d.index] ? HOLLOW : SOLID;\n        d.tint = p.from;\n        d.home = null;\n        d.stay = false;\n        d.intro = false;\n        const angle = angleTo(x, y) + (random() - 0.5) * TALLY.jitter * 0.4;\n        const [ex, ey] = edgeAt(angle, -radius * 3, false);\n        fly(d, ex, ey, TALLY.swirlShort, t + random() * TIMING.moveSpread, vary(options.flight), t);\n        moved++;\n      }\n    }\n    // Dots whose slot moved (a new layout, a tighter lattice) slide to it.\n    for (const c of clusters) {\n      c.dots.forEach((d, i) => {\n        d.index = i;\n        const [x, y] = slot(c, i);\n        if (Math.abs(d.x - x) < 0.01 && Math.abs(d.y - y) < 0.01) return;\n        const resting = !d.c || d.landed;\n        d.stay = resting || d.stay;\n        if (resting) d.tint = c;\n        fly(d, x, y, TALLY.swirlShort, resting ? t : Math.max(t, d.t0), resting ? vary(TIMING.shift, 0.15) : vary(options.flight), t);\n      });\n    }\n    cacheDirty = true;\n    counting = moved > 0;\n    settling = true;\n    wake();\n  }\n\n  function keepCopy() {\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 setActive(id: string | null) {\n    if (id === active) return;\n    active = id;\n    const t = now();\n    for (const c of clusters) {\n      c.alphaFrom = alphaOf(c, t);\n      c.alphaTo = id === null || c.id === id ? 1 : TALLY.dim;\n      c.alphaT0 = t;\n    }\n    publish({ active: id });\n    wake();\n  }\n\n  function alphaOf(c: Cluster, t: number) {\n    if (c.alphaT0 < 0) return c.alphaTo;\n    const u = options.reduced ? 1 : clamp01((t - c.alphaT0) / TIMING.dim);\n    c.alpha = c.alphaFrom + (c.alphaTo - c.alphaFrom) * ease(u);\n    if (u >= 1) c.alphaT0 = -1;\n    return c.alpha;\n  }\n\n  function drawCache(t: number) {\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    // Nothing shows before the entrance: the dots arrive with it.\n    if (!played) return;\n    c.setTransform(dpr, 0, 0, dpr, 0, 0);\n    c.lineWidth = TALLY.ring;\n    const r = radius;\n    const rr = Math.max(0.5, r - TALLY.ring / 2);\n    for (const cl of clusters) {\n      const fill = new Path2D();\n      const rings = new Path2D();\n      cl.dots.forEach((d, i) => {\n        if (d.c && !d.landed) return;\n        if (cl.hollow[i]) {\n          rings.moveTo(d.x + rr, d.y);\n          rings.arc(d.x, d.y, rr, 0, Math.PI * 2);\n        } else {\n          fill.moveTo(d.x + r, d.y);\n          fill.arc(d.x, d.y, r, 0, Math.PI * 2);\n        }\n      });\n      c.globalAlpha = alphaOf(cl, t);\n      c.fillStyle = cl.css;\n      c.strokeStyle = cl.css;\n      c.fill(fill);\n      c.stroke(rings);\n    }\n    c.globalAlpha = 1;\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    for (const d of flying) {\n      if (!d.landed && t >= d.t0 + d.dur) {\n        d.landed = true;\n        d.stay = false;\n        d.intro = false;\n        d.from = null;\n        if (d.home) cacheDirty = true;\n      }\n    }\n    flying = flying.filter((d) => {\n      if (t < d.t0 + d.dur * (1 + span)) return true;\n      d.c = null;\n      return false;\n    });\n    let tweening = false;\n    for (const c of clusters) {\n      if (c.alphaT0 >= 0) {\n        tweening = true;\n        cacheDirty = true;\n      }\n    }\n\n    ctx.setTransform(1, 0, 0, 1, 0, 0);\n    ctx.clearRect(0, 0, canvas.width, canvas.height);\n    if (cacheDirty) drawCache(t);\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    // Moving dots and their trails, batched by color and by the opacity of the cluster they're bound for.\n    type Group = { css: string; alpha: number; fill: Path2D; rings: Path2D; trail: Path2D; traced: boolean };\n    const groups = new Map<string, Group>();\n    for (const d of flying) {\n      if (t < d.appear || !d.c) continue;\n      const u = (t - d.t0) / d.dur;\n      const head = u <= 0 ? 0 : u >= 1 ? 1 : ease(u);\n      const to = d.home ?? d.tint;\n      const from = d.tint ?? to;\n      const css = from && to ? tint(from, to, head) : \"currentColor\";\n      const alpha = d.home ? Math.round(alphaOf(d.home, t) * 20) / 20 : 1;\n      const key = `${css}|${alpha}`;\n      let g = groups.get(key);\n      if (!g) groups.set(key, (g = { css, alpha, fill: new Path2D(), rings: new Path2D(), trail: new Path2D(), traced: false }));\n      if (span > 0 && u > 0) {\n        const tail = ease(clamp01(u - span));\n        if (head - tail > 0.001) {\n          addPiece(g.trail, d.c, tail, head);\n          g.traced = true;\n        }\n      }\n      if (d.landed) continue;\n      at(d.c, head, point);\n      const grow = u <= 0 ? clamp01((t - d.appear) / TIMING.pop) : 1;\n      const leaving = !d.home;\n      const scale = d.stay ? 1 : leaving ? 1 - (1 - TALLY.flightSize) * head : u <= 0 ? 1 : TALLY.flightSize + (1 - TALLY.flightSize) * head;\n      const r = radius * scale * grow;\n      if (r < 0.3) continue;\n      const hollow = d.home ? d.home.hollow[d.index] : d.kind === HOLLOW;\n      if (hollow) {\n        const rr = Math.max(0.4, r - TALLY.ring / 2);\n        g.rings.moveTo(point[0] + rr, point[1]);\n        g.rings.arc(point[0], point[1], rr, 0, Math.PI * 2);\n      } else {\n        g.fill.moveTo(point[0] + r, point[1]);\n        g.fill.arc(point[0], point[1], r, 0, Math.PI * 2);\n      }\n    }\n    for (const g of groups.values()) {\n      ctx.fillStyle = g.css;\n      ctx.strokeStyle = g.css;\n      if (g.traced) {\n        ctx.globalAlpha = TALLY.trailAlpha * g.alpha;\n        ctx.lineWidth = TALLY.trailWidth;\n        ctx.stroke(g.trail);\n      }\n      ctx.globalAlpha = g.alpha;\n      ctx.lineWidth = TALLY.ring;\n      ctx.fill(g.fill);\n      ctx.stroke(g.rings);\n    }\n    ctx.globalAlpha = 1;\n\n    if (counting) writeCounts(t);\n\n    const moving = flying.some((d) => !d.landed);\n    if (settling && !moving && !fading) {\n      settling = false;\n      onSettle?.();\n    }\n    // Called outside the loop too (a color change), so never start a second loop.\n    if (!raf && (flying.length || fading || tweening) && awake()) raf = requestAnimationFrame(frame);\n  }\n\n  /** Counts while dots move: a dot counts where it rests, and where it left until it launches. */\n  function writeCounts(t: number) {\n    if (!per) return;\n    let busy = false;\n    const n: Record<string, number> = {};\n    for (const c of clusters) {\n      let k = 0;\n      for (const d of c.dots) {\n        if (!d.c || d.landed || d.stay || d.intro) k++;\n        else busy = true;\n      }\n      n[c.id] = k;\n    }\n    for (const d of flying) {\n      if (d.from && !d.landed && t < d.t0 && d.from.id in n) n[d.from.id]++;\n      if (!d.landed) busy = true;\n    }\n    if (!busy) {\n      counting = false;\n      publish({ counts: null });\n      return;\n    }\n    const next: Record<string, number> = {};\n    let changed = !snapshot.counts;\n    for (const c of clusters) {\n      next[c.id] = n[c.id] * per;\n      if (!changed && snapshot.counts?.[c.id] !== next[c.id]) changed = true;\n    }\n    if (changed) publish({ counts: next });\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, TALLY.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    relay();\n  }\n\n  /** Lays everything out again and snaps to it; an entrance that hasn't played waits. */\n  function relay() {\n    if (!width || !height) return;\n    const labels = rooms() ?? {};\n    pickPer();\n    if (per) {\n      counts();\n      fit(labels);\n    } else publish({ labels, per: null, layout: options.layout });\n    prev = null;\n    fadeT0 = -1;\n    // A resize mid-flight snaps to the settled chart, and still reports it as settled.\n    const interrupted = played && settling;\n    settling = false;\n    snap();\n    draw();\n    if (interrupted) onSettle?.();\n    if (!played && awake()) play();\n  }\n\n  function setAwake() {\n    if (awake()) {\n      if (!played && width && per) play();\n      wake();\n    } else {\n      cancelAnimationFrame(raf);\n      raf = 0;\n    }\n  }\n\n  /** The cluster under (x, y), if any. */\n  function hit(x: number, y: number) {\n    let best: Cluster | null = null;\n    let bestD = Infinity;\n    for (const c of clusters) {\n      if (!c.n) continue;\n      const d = Math.hypot(x - c.cx, y - c.cy);\n      if (d <= c.reach + pitch * 1.5 && d < bestD) {\n        best = c;\n        bestD = d;\n      }\n    }\n    return best?.id ?? null;\n  }\n\n  return {\n    connect(el: { root: HTMLElement; canvas: HTMLCanvasElement }) {\n      root = el.root;\n      canvas = el.canvas;\n      ctx = canvas.getContext(\"2d\");\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\n      cleanups.push(\n        () => resize.disconnect(),\n        () => io.disconnect(),\n        () => document.removeEventListener(\"visibilitychange\", visibility),\n        () => scheme.removeEventListener(\"change\", readColors),\n        () => themeAttrs.disconnect(),\n      );\n      return () => {\n        cancelAnimationFrame(raf);\n        raf = 0;\n        flying = [];\n        inView = false;\n        cleanups.splice(0).forEach((fn) => fn());\n        root = canvas = null;\n        ctx = null;\n      };\n    },\n\n    setOptions(next: Options) {\n      const relayout =\n        next.dotSize !== options.dotSize || next.gap !== options.gap || next.legend !== options.legend || next.reduced !== options.reduced;\n      const reshape = next.layout !== options.layout || next.per !== options.per;\n      if (next.per !== options.per) per = null;\n      options = next;\n      if (relayout) relay();\n      else if (reshape) apply([]);\n    },\n\n    setItems(next: TallyItem[]) {\n      const sig = next.map((i) => `${i.id}\\u0001${i.value}\\u0001${i.hollow ?? 0}\\u0001${i.x ?? \"\"}\\u0001${i.y ?? \"\"}\\u0001${i.label}`).join(\"\\u0002\");\n      if (sig === signature) return;\n      signature = sig;\n      items = next;\n      const old = new Map(clusters.map((c) => [c.id, c]));\n      clusters = items.map((item) => {\n        const c = old.get(item.id) ?? newCluster(item);\n        old.delete(item.id);\n        c.item = item;\n        if (active && c.id !== active) c.alpha = c.alphaTo = TALLY.dim;\n        return c;\n      });\n      if (active && !clusters.some((c) => c.id === active)) setActive(null);\n      readTints();\n      apply([...old.values()]);\n      if (!played && awake() && per) play();\n    },\n\n    point(x: number | null, y = 0) {\n      setActive(x === null ? null : hit(x, y));\n    },\n\n    toggle(x: number, y: number) {\n      const id = hit(x, y);\n      setActive(id === active ? null : id);\n    },\n\n    activate(id: string | null) {\n      setActive(id);\n    },\n\n    setOnSettle(fn: (() => void) | null) {\n      onSettle = fn;\n    },\n\n    subscribe(fn: () => void) {\n      listeners.add(fn);\n      return () => {\n        listeners.delete(fn);\n      };\n    },\n\n    getSnapshot: () => snapshot,\n  };\n}\n\ntype Engine = ReturnType<typeof createTally>;\n\nconst NUMBER = new Intl.NumberFormat(\"en-US\", { maximumFractionDigits: 1 });\nconst formatNumber = (value: number) => NUMBER.format(value);\nconst getServerSnapshot = () => SERVER_SNAPSHOT;\n\nexport interface TallyProps extends React.HTMLAttributes<HTMLDivElement> {\n  /** The categories, in order: `{ id, label, value, hollow?, x?, y? }`. Change a value and the dots that moved fly between clusters. */\n  items: TallyItem[];\n  /** How much one dot stands for. Picked for you on first layout (about 600 dots in all, rounded to 1, 2, 2.5 or 5 × 10ⁿ), then kept, so a dot means the same thing after every update. */\n  per?: number;\n  /** `row` puts clusters side by side under one baseline of labels, wrapping onto more rows in a narrow box; `free` puts each one at its item's `x` and `y`, like places on a map. */\n  layout?: Layout;\n  /** Diameter of a dot, in px. Clusters that would outgrow their room shrink every dot together instead. */\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 once it lands. */\n  trails?: boolean;\n  /** Seconds a dot takes to fly: in from the edge, or across to another cluster. Each varies by a quarter either way. */\n  duration?: number;\n  /** Seconds between the first dot leaving the edge and the last, on the way in. */\n  stagger?: number;\n  /** How far a trail lags behind its dot, as a share of the flight. */\n  trailLength?: number;\n  /** Formats the counts under the clusters and in the legend. */\n  format?: (value: number) => string;\n  /** What a unit is called (\"jobs\", \"votes\"), for the legend and screen readers. */\n  unit?: string;\n  /** What a hollow ring means (\"retried\"). Adds it to the legend. */\n  hollowLabel?: string;\n  /** Show the legend above the clusters: what one dot is worth, and what a ring means. */\n  legend?: boolean;\n  /** Names the chart for screen readers. */\n  label?: string;\n  /** One `text-*` color for every cluster, for a one-color chart. Items' own `dotClassName` still win; without either, each cluster takes the next palette color. The canvas reads it, so `dark:` variants work. */\n  dotClassName?: string;\n  /** Classes for each label under a cluster (its color, mostly). */\n  labelClassName?: string;\n  /** Called each time every dot has landed: after the entrance and after each update. */\n  onSettle?: () => void;\n}\n\nexport function Tally({\n  items,\n  per,\n  layout = \"row\",\n  dotSize = 6,\n  gap = 1.5,\n  trails = true,\n  duration = TIMING.flight,\n  stagger = TIMING.spread,\n  trailLength = TIMING.trail,\n  format = formatNumber,\n  unit,\n  hollowLabel,\n  legend = true,\n  label,\n  dotClassName,\n  labelClassName,\n  onSettle,\n  className,\n  children,\n  onPointerMove,\n  onPointerDown,\n  onPointerLeave,\n  ...props\n}: TallyProps) {\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const canvasRef = React.useRef<HTMLCanvasElement>(null);\n  const [engine] = React.useState<Engine>(createTally);\n  const reduced = useReduced();\n  const snap = React.useSyncExternalStore(engine.subscribe, engine.getSnapshot, getServerSnapshot);\n\n  React.useLayoutEffect(() => {\n    const root = rootRef.current;\n    const canvas = canvasRef.current;\n    if (!root || !canvas) return;\n    return engine.connect({ root, canvas });\n  }, [engine]);\n\n  React.useEffect(() => {\n    engine.setOptions({\n      per: per && per > 0 ? per : undefined,\n      layout,\n      legend,\n      dotSize: Math.max(1.5, dotSize),\n      gap: Math.max(0, gap),\n      trails,\n      flight: Math.max(0.1, duration),\n      spread: Math.max(0, stagger),\n      trail: clamp01(trailLength),\n      reduced,\n    });\n  }, [engine, per, layout, legend, dotSize, gap, trails, duration, stagger, trailLength, reduced]);\n\n  React.useEffect(() => {\n    engine.setItems(items);\n  }, [engine, items]);\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 local = (event: React.PointerEvent<HTMLDivElement>) => {\n    const box = event.currentTarget.getBoundingClientRect();\n    return [event.clientX - box.left, event.clientY - box.top] as const;\n  };\n\n  const unitText = unit ? ` ${unit}` : \"\";\n  return (\n    <div\n      ref={rootRef}\n      className={cn(\"relative isolate\", className)}\n      onPointerMove={(event) => {\n        onPointerMove?.(event);\n        // Over a label, the label's own handlers decide.\n        if ((event.target as HTMLElement).closest(\"[data-tally-label]\")) return;\n        if (event.pointerType === \"mouse\") engine.point(...local(event));\n      }}\n      onPointerDown={(event) => {\n        onPointerDown?.(event);\n        if (event.pointerType !== \"mouse\") engine.toggle(...local(event));\n      }}\n      onPointerLeave={(event) => {\n        onPointerLeave?.(event);\n        if (event.pointerType === \"mouse\") engine.point(null);\n      }}\n      {...props}\n    >\n      <canvas ref={canvasRef} aria-hidden className=\"pointer-events-none absolute inset-0 -z-10 size-full\" />\n\n      {legend && snap.per !== null && (\n        <div aria-hidden className=\"absolute top-0 left-0 flex items-center gap-4 font-mono text-[11px] leading-5 text-zinc-500 dark:text-zinc-400\">\n          <span className=\"flex items-center gap-1.5\">\n            <span className={cn(\"size-1.5 rounded-full bg-current\", dotClassName)} />\n            {`= ${format(snap.per)}${unitText}`}\n          </span>\n          {hollowLabel && (\n            <span className=\"flex items-center gap-1.5\">\n              <span className={cn(\"size-1.5 rounded-full border border-current\", dotClassName)} />\n              {hollowLabel}\n            </span>\n          )}\n        </div>\n      )}\n\n      {items.map((item, k) => {\n        // The item's own color, then the chart's, then the palette. The canvas reads it from the swatch.\n        const tone = item.dotClassName ?? dotClassName ?? PALETTE[k % PALETTE.length];\n        const anchor = snap.labels?.[item.id];\n        const count = snap.counts?.[item.id];\n        const style: React.CSSProperties = anchor\n          ? {\n              left: 0,\n              top: 0,\n              width: anchor[2],\n              transform: `translate(${anchor[0] - anchor[2] / 2}px, ${anchor[1]}px)`,\n              transition: snap.layout === \"free\" && !reduced ? TIMING.labelSlide : undefined,\n            }\n          : { left: `${((k + 0.5) / items.length) * 100}%`, top: `calc(100% - ${TALLY.labelBand - 2}px)`, transform: \"translateX(-50%)\" };\n        return (\n          <div\n            key={item.id}\n            aria-hidden\n            data-tally-label=\"\"\n            onPointerEnter={(event) => event.pointerType === \"mouse\" && engine.activate(item.id)}\n            onPointerLeave={(event) => event.pointerType === \"mouse\" && engine.activate(null)}\n            data-dim={snap.active !== null && snap.active !== item.id}\n            className={cn(\n              `absolute flex flex-col items-center px-1 text-center transition-opacity ${TIMING.labelDim} data-[dim=true]:opacity-35`,\n              \"text-zinc-950 dark:text-white\",\n              labelClassName,\n            )}\n            style={style}\n          >\n            <span className=\"flex max-w-full items-center gap-1.5\">\n              <span data-tally-swatch={item.id} className={cn(\"size-2 shrink-0 bg-current\", tone)} />\n              <span className=\"truncate font-mono text-[11px] leading-4 tracking-wide uppercase opacity-60\">{item.label}</span>\n            </span>\n            <span className=\"text-[15px] leading-6 font-medium tabular-nums\">{format(count ?? item.value)}</span>\n          </div>\n        );\n      })}\n\n      <ul aria-label={label} aria-live=\"polite\" className=\"sr-only\">\n        {items.map((item) => (\n          <li key={item.id}>\n            {`${item.label}: ${format(item.value)}${unitText}`}\n            {item.hollow ? `, ${format(item.hollow)} ${hollowLabel ?? \"hollow\"}` : \"\"}\n          </li>\n        ))}\n      </ul>\n      {children}\n    </div>\n  );\n}\n"
    }
  ]
}