{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tally-bars",
  "type": "registry:ui",
  "title": "Tally Bars",
  "description": "How everyone answered, as one bar per option with its whole percent: the results of a poll, or the spread of answers after a quiz question. The viewer's own choice is named in words, and a quiz can mark the right option, so nothing depends on colour alone.",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "games",
    "game"
  ],
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "https://ds.interlace.tools/r/interlace-base.json",
    "https://ds.interlace.tools/r/cn.json",
    "https://ds.interlace.tools/r/motion-token.json",
    "https://ds.interlace.tools/r/use-reduced-motion.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/games/tally-bars.tsx",
      "target": "components/ui/games/tally-bars.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/tally-bars v1.0.1 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/tally-bars\n// What changed since: https://ds.interlace.tools/c/tally-bars#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — TallyBars\n *\n * How everyone answered, as one bar per option with its whole percent: the\n * results of a poll, or the spread of answers after a quiz question. The\n * viewer's own choice is named in words, and a quiz can mark the right\n * option, so nothing depends on colour alone.\n *\n * Feed it the rows from `tally()` in `games/tally-model` (percents that sum\n * to 100, the viewer's vote counted once), plus a label per option.\n *\n * ## Anatomy\n *\n *   TallyBars                     (div — data-slot=\"tally-bars\")\n *     ├─ ol                       (data-slot=\"tally-bars-list\")\n *     │   └─ li × n               (data-slot=\"tally-bars-row\", data-mine, data-leading, data-mark)\n *     │       ├─ span             (data-slot=\"tally-bars-label\": label + \"Your answer\" / mark words)\n *     │       ├─ span             (data-slot=\"tally-bars-percent\")\n *     │       └─ span aria-hidden (data-slot=\"tally-bars-track\" › data-slot=\"tally-bars-fill\")\n *     └─ p                        (data-slot=\"tally-bars-total\": \"1,204 votes\")\n *\n * ## Motion\n *\n * On mount each fill grows from the start of its track to its share (400ms,\n * `--ease-enter`), all at once, so the eye compares the ends rather than\n * following a sequence. The percents are in the HTML from the start. Under\n * reduced motion the bars are simply at their share. `animate={false}` draws\n * them in place, for a results view restored on reload.\n *\n * ## MIN_VIEWPORT — 320\n *\n * | Rule | Concept                   | Where in this file                                   |\n * | ---- | ------------------------- | ---------------------------------------------------- |\n * | R4   | Extends native el         | `React.ComponentProps<'div'>`                        |\n * | R6   | data-slot per part        | tally-bars / -list / -row / -label / -percent / -track / -fill / -total |\n * | R7   | cn + ...rest              | `cn(…, className)` + `{...props}`                    |\n * | R14  | Declares min viewport     | `data-min-viewport` + exported const                 |\n * | R19  | Tokens only               | primary, success, foreground, muted                  |\n * | R26  | A11y                      | a list read as text; bars hidden; marks in words     |\n */\n\nimport { Check, X } from 'lucide-react';\n\nimport { cn } from '@/lib/utils';\nimport { useReducedMotion } from '@/hooks/use-reduced-motion';\nimport { motionDuration, motionEase } from '@/lib/motion-token';\nimport type { TallyRow } from '@/components/ui/games/tally-model';\n\nexport const MIN_VIEWPORT = 320 as const;\n\n/** A quiz's verdict on one option. */\nexport type TallyMark = 'correct' | 'wrong';\n\ninterface TallyBarsLabels {\n  /** Beside the viewer's own option. @default 'Your answer' */\n  mine?: string;\n  /** Beside the right option. @default 'Right answer' */\n  correct?: string;\n  /** The total line. @default (n, formatted) => `${formatted} ${n === 1 ? 'vote' : 'votes'}` */\n  total?: (count: number, formatted: string) => string;\n}\n\ntype TallyBarsProps = Omit<React.ComponentProps<'div'>, 'children'> & {\n  rows: readonly TallyRow[];\n  /** The text for each option id. */\n  optionLabels: Readonly<Record<string, React.ReactNode>>;\n  /** Marks per option id, for a quiz. Only `correct` is drawn and named; `wrong` just stays plain. */\n  marks?: Readonly<Record<string, TallyMark>>;\n  /** Grow the bars on mount. @default true */\n  animate?: boolean;\n  /** Show the total line. @default true */\n  showTotal?: boolean;\n  locale?: string;\n  labels?: TallyBarsLabels;\n};\n\nconst TOTAL: NonNullable<TallyBarsLabels['total']> = (n, f) => `${f} ${n === 1 ? 'vote' : 'votes'}`;\n\nfunction TallyBars({\n  rows,\n  optionLabels,\n  marks,\n  animate = true,\n  showTotal = true,\n  locale,\n  labels,\n  className,\n  ...props\n}: TallyBarsProps) {\n  const reduced = useReducedMotion();\n  const listRef = React.useRef<HTMLOListElement>(null);\n  const nf = React.useMemo(() => new Intl.NumberFormat(locale), [locale]);\n  const pf = React.useMemo(() => new Intl.NumberFormat(locale, { style: 'percent' }), [locale]);\n  const total = rows.reduce((a, r) => a + r.count, 0);\n\n  // Grow every fill once, on mount, together.\n  React.useEffect(() => {\n    if (!animate || reduced) return;\n    const fills = listRef.current?.querySelectorAll<HTMLElement>('[data-slot=\"tally-bars-fill\"]');\n    fills?.forEach((fill) => {\n      if (typeof fill.animate !== 'function') return;\n      fill.animate([{ transform: 'scaleX(0)' }, { transform: 'scaleX(1)' }], {\n        duration: motionDuration(fill, 'slow'),\n        easing: motionEase(fill, 'enter'),\n      });\n    });\n    // Mount only: later count changes move the bars without a replay.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  return (\n    <div\n      data-slot=\"tally-bars\"\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('grid gap-3', className)}\n      {...props}\n    >\n      <ol ref={listRef} data-slot=\"tally-bars-list\" className=\"grid gap-3\">\n        {rows.map((row) => {\n          const mark = marks?.[row.id];\n          return (\n            <li\n              key={row.id}\n              data-slot=\"tally-bars-row\"\n              data-mine={row.mine ? '' : undefined}\n              data-leading={row.leading ? '' : undefined}\n              data-mark={mark}\n              className=\"grid grid-cols-[1fr_auto] items-baseline gap-x-3 gap-y-1.5\"\n            >\n              <span data-slot=\"tally-bars-label\" className={cn('min-w-0 text-sm', row.mine && 'font-semibold')}>\n                {optionLabels[row.id] ?? row.id}\n                {mark === 'correct' ? (\n                  <span className=\"text-success ms-2 inline-flex items-center gap-1 text-xs font-semibold whitespace-nowrap\">\n                    <Check aria-hidden className=\"size-3.5\" strokeWidth={3} />\n                    {labels?.correct ?? 'Right answer'}\n                  </span>\n                ) : null}\n                {row.mine ? (\n                  <span className=\"text-muted-foreground ms-2 inline-flex items-center gap-1 text-xs font-semibold whitespace-nowrap\">\n                    {mark === 'wrong' ? <X aria-hidden className=\"size-3.5\" strokeWidth={3} /> : null}\n                    {labels?.mine ?? 'Your answer'}\n                  </span>\n                ) : null}\n              </span>\n              <span data-slot=\"tally-bars-percent\" className=\"text-sm font-semibold tabular-nums\">\n                {pf.format(row.percent / 100)}\n              </span>\n              <span\n                aria-hidden\n                data-slot=\"tally-bars-track\"\n                className=\"bg-muted col-span-2 block h-2 overflow-hidden rounded-full\"\n              >\n                <span\n                  data-slot=\"tally-bars-fill\"\n                  className={cn(\n                    'block h-full origin-left rounded-full rtl:origin-right',\n                    mark === 'correct' ? 'bg-success' : row.mine ? 'bg-primary' : 'bg-foreground/35',\n                  )}\n                  style={{ width: `${row.percent}%` }}\n                />\n              </span>\n            </li>\n          );\n        })}\n      </ol>\n      {showTotal ? (\n        <p data-slot=\"tally-bars-total\" className=\"text-muted-foreground text-xs tabular-nums\">\n          {(labels?.total ?? TOTAL)(total, nf.format(total))}\n        </p>\n      ) : null}\n    </div>\n  );\n}\nTallyBars.displayName = 'TallyBars';\n\nexport { TallyBars };\nexport type { TallyBarsProps, TallyBarsLabels };\n"
    },
    {
      "path": "registry/interlace-ui/games/tally-model.ts",
      "target": "components/ui/games/tally-model.ts",
      "type": "registry:ui",
      "content": "export interface TallyRow {\n  id: string;\n  count: number;\n  /** count / total, 0–1. 0 when nobody has voted. */\n  share: number;\n  /** Whole percent; the rows sum to 100 when total > 0. */\n  percent: number;\n  /** The viewer's own choice. */\n  mine: boolean;\n  /** Has the highest count (ties all lead). False when nobody has voted. */\n  leading: boolean;\n}\n\nexport interface TallyOptions {\n  /** The viewer's choice, if any. */\n  vote?: string | null;\n  /** The counts already include the viewer's vote. @default false */\n  countsIncludeVote?: boolean;\n}\n\nexport interface Tally {\n  rows: TallyRow[];\n  total: number;\n}\n\n/** Largest count kept per option, so a hostile 1e308 can never push a total to Infinity. */\nconst MAX_COUNT = 1e12;\n\nconst clampCount = (n: number): number =>\n  Number.isFinite(n) ? Math.min(Math.max(Math.floor(n), 0), MAX_COUNT) : 0;\n\n/** Whole percents that sum to 100 (largest remainder). All 0 when the total is 0. */\nexport function wholePercents(input: readonly number[]): number[] {\n  const counts = input.map(clampCount);\n  const total = counts.reduce((a, b) => a + b, 0);\n  if (!(total > 0)) return counts.map(() => 0);\n  const exact = counts.map((c) => (c / total) * 100);\n  const out = exact.map(Math.floor);\n  let left = 100 - out.reduce((a, b) => a + b, 0);\n  const order = exact\n    .map((e, i) => ({ i, rest: e - Math.floor(e) }))\n    // Biggest remainder first; on a tie the earlier option wins, so the result is stable.\n    .sort((a, b) => b.rest - a.rest || a.i - b.i);\n  for (const { i } of order) {\n    if (left <= 0) break;\n    out[i] = (out[i] as number) + 1;\n    left -= 1;\n  }\n  return out;\n}\n\n/** The rows for `ids`, in that order. Unknown ids count 0; negative or non-finite counts count 0. */\nexport function tally(\n  ids: readonly string[],\n  counts: Readonly<Record<string, number>> = {},\n  options: TallyOptions = {},\n): Tally {\n  const { vote = null, countsIncludeVote = false } = options;\n  // A repeated id would be counted twice; an inherited count is not a vote.\n  ids = [...new Set(ids)];\n  const raw = ids.map((id) => {\n    const n = Object.prototype.hasOwnProperty.call(counts, id) ? (counts[id] as number) : 0;\n    const base = clampCount(n);\n    return id === vote && !countsIncludeVote ? base + 1 : base;\n  });\n  const total = raw.reduce((a, b) => a + b, 0);\n  const percents = wholePercents(raw);\n  const top = raw.reduce((a, b) => Math.max(a, b), -Infinity);\n  return {\n    total,\n    rows: ids.map((id, i) => ({\n      id,\n      count: raw[i] as number,\n      share: total > 0 ? (raw[i] as number) / total : 0,\n      percent: percents[i] as number,\n      mine: vote !== null && id === vote,\n      leading: (raw[i] as number) > 0 && raw[i] === top,\n    })),\n  };\n}\n\n/**\n * @interlace/ui — games/tally-model\n *\n * Counts per option turned into shares a reader can trust: whole percents\n * that add up to exactly 100, the viewer's own choice included once, and the\n * leading option named. Pure, so a server can return the same numbers the\n * client draws, and a poll and a quiz share one rule.\n *\n * ## Percents that add up\n *\n * Rounding each share on its own can give 33 + 33 + 33 = 99. The largest\n * remainder method hands the missing points to the options that lost the\n * most to rounding, so the column always sums to 100 (or to 0 when nobody\n * has voted).\n *\n * ## The viewer's vote\n *\n * A poll usually knows the tally from the server and the viewer's choice\n * from the tap that just happened. Pass the server counts with\n * `countsIncludeVote: false` (the default) and the viewer's vote is added\n * once, so the bars move the moment they tap. When the server's counts\n * already hold it (a reload), pass `countsIncludeVote: true`.\n */\n"
    }
  ],
  "meta": {
    "tier": "game",
    "client": true,
    "minViewport": 320,
    "loading": false,
    "version": "1.0.1",
    "since": "2.0.0"
  },
  "docs": "## @interlace/tally-bars\n\nInstalled to `components/ui/games/tally-bars.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/games/tally-bars';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/tally-bars\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
