{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "poll",
  "type": "registry:ui",
  "title": "Poll",
  "description": "One question, one tap. The options are plain buttons; tapping one casts the vote, and the options turn into the results in place, with the bars growing to everyone's shares and the viewer's choice named. There is no submit step, because a poll that asks…",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "games",
    "game"
  ],
  "dependencies": [],
  "registryDependencies": [
    "https://ds.interlace.tools/r/interlace-base.json",
    "https://ds.interlace.tools/r/button.json",
    "https://ds.interlace.tools/r/cn.json",
    "https://ds.interlace.tools/r/tally-bars.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/games/poll.tsx",
      "target": "components/ui/games/poll.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/poll v1.0.0 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/poll\n// What changed since: https://ds.interlace.tools/c/poll#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — Poll\n *\n * One question, one tap. The options are plain buttons; tapping one casts\n * the vote, and the options turn into the results in place, with the bars\n * growing to everyone's shares and the viewer's choice named. There is no\n * submit step, because a poll that asks twice gets half the answers.\n *\n * ## Anatomy\n *\n *   Poll                           (div — data-slot=\"poll\", data-state=open|voted)\n *     ├─ p                         (data-slot=\"poll-question\", id ← the option group's label)\n *     ├─ div role=\"group\"          (data-slot=\"poll-options\": one Button per option, before the vote)\n *     ├─ TallyBars                 (after the vote, when at least `minVotes` are in)\n *     ├─ p tabIndex=-1 aria-live   (data-slot=\"poll-result\": the result in one sentence)\n *     └─ div                       (data-slot=\"poll-footer\": optional, e.g. \"Closes Friday\")\n *\n * ## Data\n *\n * `counts` are the votes per option id from your store. Leave out the\n * viewer's own vote (`countsIncludeVote={false}`, the default) and the poll\n * adds it, so the results are right the moment they tap; pass `true` when\n * the counts came back from the server with it. `vote` / `defaultVote` hold\n * the viewer's choice, so a page that remembers it opens on the results.\n * `onVote` fires once, with the option id.\n *\n * Small polls give voters away. `minVotes` keeps the shares hidden until\n * that many votes are in, and says so.\n *\n * ## Motion\n *\n * The bars grow from zero to their shares on the vote (TallyBars, 400ms).\n * Under reduced motion they are simply there. Restoring a stored vote\n * draws them in place.\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        | poll / -question / -options / -result / -footer      |\n * | R7   | cn + ...rest              | `cn(…, className)` + `{...props}`                    |\n * | R9   | Controlled + uncontrolled | `vote` / `defaultVote` / `onVote`                    |\n * | R14  | Declares min viewport     | `data-min-viewport` + exported const                 |\n * | R26  | A11y                      | labelled group of buttons; result announced and focused |\n */\n\nimport { cn } from '@/lib/utils';\nimport { Button } from '@/components/ui/button';\nimport { TallyBars, type TallyBarsLabels } from '@/components/ui/games/tally-bars';\nimport { tally } from '@/components/ui/games/tally-model';\n\nexport const MIN_VIEWPORT = 320 as const;\n\ninterface PollOption {\n  id: string;\n  label: React.ReactNode;\n  /** Plain text for the result sentence, when `label` is not a string. */\n  text?: string;\n}\n\ninterface PollLabels extends TallyBarsLabels {\n  /** After the vote. @default ({ option, percent, total }) => `You chose ${option}, with ${percent} of ${total}.` */\n  result?: (r: { option: string; percent: string; total: string; count: number }) => string;\n  /** While fewer than `minVotes` are in. @default (min) => `Thanks. The results show once ${min} people have voted.` */\n  pending?: (min: number) => string;\n}\n\ntype PollProps = Omit<React.ComponentProps<'div'>, 'children' | 'onChange'> & {\n  question: React.ReactNode;\n  options: readonly PollOption[];\n  /** Votes per option id from your store. */\n  counts?: Readonly<Record<string, number>>;\n  /** `counts` already include this viewer's vote. @default false */\n  countsIncludeVote?: boolean;\n  /** The viewer's choice, controlled. null for none yet. */\n  vote?: string | null;\n  /** The viewer's choice, uncontrolled. */\n  defaultVote?: string | null;\n  /** Called once, when the viewer taps an option. */\n  onVote?: (optionId: string) => void;\n  /** Hide the shares until this many votes are in. @default 1 */\n  minVotes?: number;\n  /** Under the results: when the poll closes, what it is for. */\n  footer?: React.ReactNode;\n  locale?: string;\n  labels?: PollLabels;\n};\n\nconst RESULT: NonNullable<PollLabels['result']> = ({ option, percent, total }) =>\n  `You chose ${option}, with ${percent} of ${total}.`;\nconst PENDING: NonNullable<PollLabels['pending']> = (min) =>\n  `Thanks. The results show once ${min} people have voted.`;\n\nconst textOf = (o: PollOption) => o.text ?? (typeof o.label === 'string' || typeof o.label === 'number' ? String(o.label) : o.id);\n\nfunction Poll({\n  question,\n  options,\n  counts,\n  countsIncludeVote = false,\n  vote: voteProp,\n  defaultVote = null,\n  onVote,\n  minVotes = 1,\n  footer,\n  locale,\n  labels,\n  className,\n  ...props\n}: PollProps) {\n  const [uncontrolled, setUncontrolled] = React.useState<string | null>(defaultVote);\n  const vote = voteProp === undefined ? uncontrolled : voteProp;\n  const voted = vote !== null && vote !== undefined && options.some((o) => o.id === vote);\n  const questionId = React.useId();\n  const resultRef = React.useRef<HTMLParagraphElement>(null);\n  const groupRef = React.useRef<HTMLDivElement>(null);\n  const sent = React.useRef(voted);\n  const moveFocus = React.useRef(false);\n  // Bars grow only for a vote cast here, not for one restored on load.\n  const [castHere, setCastHere] = React.useState(false);\n\n  const ids = options.map((o) => o.id);\n  const { rows, total } = tally(ids, counts, { vote: voted ? vote : null, countsIncludeVote });\n  const shown = voted && total >= minVotes;\n  const nf = React.useMemo(() => new Intl.NumberFormat(locale), [locale]);\n  const pf = React.useMemo(() => new Intl.NumberFormat(locale, { style: 'percent' }), [locale]);\n\n  React.useEffect(() => {\n    if (!voted) sent.current = false;\n  }, [voted]);\n\n  React.useEffect(() => {\n    if (!voted || !moveFocus.current) return;\n    moveFocus.current = false;\n    resultRef.current?.focus();\n  }, [voted]);\n\n  const cast = (id: string) => {\n    if (voted || sent.current) return;\n    sent.current = true;\n    // The buttons go away: if focus was on one, the result takes it.\n    moveFocus.current = !!groupRef.current?.contains(document.activeElement);\n    setCastHere(true);\n    if (voteProp === undefined) setUncontrolled(id);\n    onVote?.(id);\n  };\n\n  const mine = rows.find((r) => r.mine);\n  const chosen = options.find((o) => o.id === vote);\n  const totalText = (labels?.total ?? ((n: number, f: string) => `${f} ${n === 1 ? 'vote' : 'votes'}`))(total, nf.format(total));\n\n  return (\n    <div\n      data-slot=\"poll\"\n      data-state={voted ? 'voted' : 'open'}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('grid gap-4', className)}\n      {...props}\n    >\n      <p id={questionId} data-slot=\"poll-question\" className=\"font-heading text-lg font-semibold text-balance\">\n        {question}\n      </p>\n\n      {!voted ? (\n        <div ref={groupRef} role=\"group\" aria-labelledby={questionId} data-slot=\"poll-options\" className=\"grid gap-2\">\n          {options.map((o) => (\n            <Button\n              key={o.id}\n              type=\"button\"\n              variant=\"outline\"\n              size=\"lg\"\n              className=\"h-auto min-h-11 justify-start py-2.5 text-start whitespace-normal\"\n              onClick={() => cast(o.id)}\n            >\n              {o.label}\n            </Button>\n          ))}\n        </div>\n      ) : shown ? (\n        <TallyBars\n          rows={rows}\n          optionLabels={Object.fromEntries(options.map((o) => [o.id, o.label]))}\n          animate={castHere}\n          locale={locale}\n          labels={labels}\n        />\n      ) : null}\n\n      <p\n        ref={resultRef}\n        tabIndex={-1}\n        data-slot=\"poll-result\"\n        aria-live=\"polite\"\n        className=\"focus-visible:outline-ring rounded-sm text-sm outline-offset-4 empty:hidden focus-visible:outline-2\"\n      >\n        {voted && chosen && mine\n          ? shown\n            ? (labels?.result ?? RESULT)({\n                option: textOf(chosen),\n                percent: pf.format(mine.percent / 100),\n                total: totalText,\n                count: total,\n              })\n            : (labels?.pending ?? PENDING)(minVotes)\n          : ''}\n      </p>\n\n      {footer ? (\n        <div data-slot=\"poll-footer\" className=\"text-muted-foreground text-xs\">\n          {footer}\n        </div>\n      ) : null}\n    </div>\n  );\n}\nPoll.displayName = 'Poll';\n\nexport { Poll };\nexport type { PollProps, PollOption, PollLabels };\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.0",
    "since": "2.0.0"
  },
  "docs": "## @interlace/poll\n\nInstalled to `components/ui/games/poll.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/games/poll';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/poll\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
