{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "dot-vote",
  "type": "registry:ui",
  "title": "Dot Vote",
  "description": "After a brainstorm, the room chooses: each person spreads a few dots across the ideas (two on one idea means \"this one, really\"), sends them, and watches the ideas rank themselves as everyone's dots come in. It pairs with `TextWall` or `QuestionBoard` for…",
  "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/button.json",
    "https://ds.interlace.tools/r/cn.json",
    "https://ds.interlace.tools/r/flip-group.json",
    "https://ds.interlace.tools/r/motion-token.json",
    "https://ds.interlace.tools/r/use-reduced-motion.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/games/dot-vote.tsx",
      "target": "components/ui/games/dot-vote.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/dot-vote v1.0.0 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/dot-vote\n// What changed since: https://ds.interlace.tools/c/dot-vote#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — DotVote\n *\n * After a brainstorm, the room chooses: each person spreads a few dots\n * across the ideas (two on one idea means \"this one, really\"), sends them,\n * and watches the ideas rank themselves as everyone's dots come in. It\n * pairs with `TextWall` or `QuestionBoard` for the brainstorm before it.\n *\n * ## Anatomy\n *\n *   DotVote                        (div — data-slot=\"dot-vote\", data-state=voting|sent)\n *     ├─ p                         (data-slot=\"dot-vote-question\")\n *     ├─ ul                        (data-slot=\"dot-vote-ideas\": while voting)\n *     │   └─ li × n                (data-slot=\"dot-vote-idea\": text, pips, − and + with names)\n *     ├─ div                       (data-slot=\"dot-vote-footer\": dots left, announced; Send)\n *     ├─ p tabIndex=-1 aria-live   (data-slot=\"dot-vote-result\": after sending)\n *     └─ ol                        (FlipGroup — data-slot=\"dot-vote-results\": most dots first)\n *         └─ li × n                (data-slot=\"dot-vote-row\": rank, text, bar, dots, yours)\n *\n * ## Motion\n *\n * A dot fills its pip with a small pop (`--duration-fast`). Once sent, the\n * bars grow to their share (400ms, `ease-enter`) and, as more dots arrive,\n * ideas glide to their new rank (FlipGroup, 400ms). Under reduced motion\n * everything is simply in place.\n *\n * ## MIN_VIEWPORT — 320\n *\n * | Rule | Concept                   | Where in this file                                   |\n * | ---- | ------------------------- | ---------------------------------------------------- |\n * | R4   | Extends native el         | `div` props                                          |\n * | R6   | data-slot per part        | dot-vote / -question / -ideas / -idea / -footer / -result / -results / -row |\n * | R7   | cn + ...rest              | `cn(…, className)` + `{...props}`                    |\n * | R9   | Controlled + uncontrolled | `value` / `defaultValue` / `onSend`                  |\n * | R14  | Declares min viewport     | `data-min-viewport` + exported const                 |\n * | R26  | A11y                      | each button names its idea; dots in words; dots left announced; result focused |\n */\n\nimport { Minus, Plus } from 'lucide-react';\n\nimport { FlipGroup } from '@/components/ui/effects/flip-group';\nimport { cn } from '@/lib/utils';\nimport { motionEase } from '@/lib/motion-token';\nimport { useReducedMotion } from '@/hooks/use-reduced-motion';\nimport { Button } from '@/components/ui/button';\nimport { cleanBallot, dotsLeft, tallyDots, type DotBallot } from '@/components/ui/games/dot-vote-model';\n\nexport const MIN_VIEWPORT = 320 as const;\n\ninterface DotIdea {\n  id: string;\n  text: string;\n}\n\ninterface DotVoteLabels {\n  /** @default 'Send my dots' */\n  send?: string;\n  /** @default (n) => `${n} dots left` */\n  left?: (n: number, formatted: string) => string;\n  /** @default (idea) => `Add a dot to ${idea}` */\n  add?: (idea: string) => string;\n  /** @default (idea) => `Take a dot from ${idea}` */\n  remove?: (idea: string) => string;\n  /** A count of dots, in words. @default (n) => `${n} dots` */\n  count?: (n: number, formatted: string) => string;\n  /** Beside the viewer's own dots in the results. @default (n) => `Yours: ${n}` */\n  mine?: (n: number, formatted: string) => string;\n  /** After sending. @default (voters) => `Sent. ${voters} people have voted so far.` */\n  result?: (voters: number, formatted: string) => string;\n}\n\ntype DotVoteProps = Omit<React.ComponentProps<'div'>, 'children' | 'defaultValue'> & {\n  question: React.ReactNode;\n  ideas: readonly DotIdea[];\n  /** Dots each person has. @default 3 */\n  dots?: number;\n  /** Most dots on one idea. @default dots */\n  maxPerIdea?: number;\n  /** The viewer's sent dots, controlled. null while voting. */\n  value?: DotBallot | null;\n  /** The viewer's sent dots, uncontrolled. */\n  defaultValue?: DotBallot | null;\n  /** Called once, when the viewer sends, with a valid ballot. */\n  onSend?: (ballot: Record<string, number>) => void;\n  /** Everyone's ballots, keyed by person; shown once the viewer has sent. */\n  ballots?: Readonly<Record<string, DotBallot>>;\n  /** `ballots` already hold this viewer's dots. @default false */\n  ballotsIncludeOwn?: boolean;\n  locale?: string;\n  labels?: DotVoteLabels;\n};\n\nconst plural = (word: string) => (n: number, f: string) => `${f} ${n === 1 ? word : `${word}s`}`;\n\nfunction DotVote({\n  question,\n  ideas,\n  dots = 3,\n  maxPerIdea,\n  value: valueProp,\n  defaultValue = null,\n  onSend,\n  ballots = {},\n  ballotsIncludeOwn = false,\n  locale,\n  labels,\n  className,\n  ...props\n}: DotVoteProps) {\n  const reduced = useReducedMotion();\n  const nf = React.useMemo(() => new Intl.NumberFormat(locale), [locale]);\n  const rules = { dots, maxPerIdea };\n  const ids = ideas.map((i) => i.id);\n  const [own, setOwn] = React.useState<DotBallot | null>(defaultValue);\n  const sent = valueProp === undefined ? own : valueProp;\n  const [draft, setDraft] = React.useState<Record<string, number>>({});\n  const [sentHere, setSentHere] = React.useState(false);\n  const questionId = React.useId();\n  const resultRef = React.useRef<HTMLParagraphElement>(null);\n  const listRef = React.useRef<HTMLDivElement>(null);\n\n  const left = dotsLeft(draft, rules);\n  const cap = Math.min(dots, maxPerIdea ?? dots);\n  const mine = sent ? cleanBallot(sent, ids, rules) : null;\n  const room = tallyDots(mine && !ballotsIncludeOwn ? { ...ballots, 'you': mine } : ballots, ids, rules);\n  const top = Math.max(1, ...room.rows.map((r) => r.dots));\n  const textOf = (id: string) => ideas.find((i) => i.id === id)?.text ?? id;\n  const countWords = labels?.count ?? plural('dot');\n\n  React.useEffect(() => {\n    if (!sentHere) return;\n    resultRef.current?.focus();\n    if (reduced) return;\n    listRef.current?.querySelectorAll<HTMLElement>('[data-slot=\"dot-vote-fill\"]').forEach((bar) => {\n      if (typeof bar.animate !== 'function') return;\n      bar.animate([{ transform: 'scaleX(0)' }, { transform: 'scaleX(1)' }], {\n        duration: 400,\n        easing: motionEase(bar, 'enter'),\n      });\n    });\n    // Once, when this viewer's dots land.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [sentHere]);\n\n  const change = (id: string, by: 1 | -1) =>\n    setDraft((d) => cleanBallot({ ...d, [id]: Math.max(0, (d[id] ?? 0) + by) }, ids, rules));\n\n  const send = () => {\n    if (sent) return;\n    const ballot = cleanBallot(draft, ids, rules);\n    if (Object.keys(ballot).length === 0) return;\n    setSentHere(true);\n    if (valueProp === undefined) setOwn(ballot);\n    onSend?.(ballot);\n  };\n\n  return (\n    <div\n      data-slot=\"dot-vote\"\n      data-state={sent ? 'sent' : 'voting'}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('grid gap-4', className)}\n      {...props}\n    >\n      <p id={questionId} data-slot=\"dot-vote-question\" className=\"font-heading text-lg font-semibold text-balance\">\n        {question}\n      </p>\n\n      {sent ? null : (\n        <>\n          <ul data-slot=\"dot-vote-ideas\" aria-labelledby={questionId} className=\"grid gap-2\">\n            {ideas.map((idea) => {\n              const n = draft[idea.id] ?? 0;\n              return (\n                <li\n                  key={idea.id}\n                  data-slot=\"dot-vote-idea\"\n                  data-dots={n}\n                  className={cn(\n                    'flex items-center gap-3 rounded-lg border px-3 py-2',\n                    'motion-safe:transition-colors motion-safe:duration-(--duration-fast)',\n                    n > 0 ? 'border-primary bg-primary/5' : 'bg-background',\n                  )}\n                >\n                  <span className=\"min-w-0 flex-1 text-base text-pretty\">{idea.text}</span>\n                  <span aria-hidden className=\"flex gap-1\">\n                    {Array.from({ length: cap }, (_, i) => (\n                      <span\n                        key={`pip-${i}`}\n                        data-filled={i < n ? '' : undefined}\n                        className={cn(\n                          'size-2.5 rounded-full border',\n                          'motion-safe:transition-[transform,background-color] motion-safe:duration-(--duration-fast) motion-safe:ease-enter',\n                          i < n ? 'bg-primary border-primary scale-110' : 'border-muted-foreground/50 scale-100',\n                        )}\n                      />\n                    ))}\n                  </span>\n                  <span className=\"sr-only\">{countWords(n, nf.format(n))}</span>\n                  <span className=\"flex gap-1\">\n                    <Button\n                      type=\"button\"\n                      variant=\"outline\"\n                      size=\"icon\"\n                      aria-label={(labels?.remove ?? ((t: string) => `Take a dot from ${t}`))(idea.text)}\n                      disabled={n === 0}\n                      onClick={() => change(idea.id, -1)}\n                    >\n                      <Minus aria-hidden />\n                    </Button>\n                    <Button\n                      type=\"button\"\n                      variant=\"outline\"\n                      size=\"icon\"\n                      aria-label={(labels?.add ?? ((t: string) => `Add a dot to ${t}`))(idea.text)}\n                      disabled={left === 0 || n >= cap}\n                      onClick={() => change(idea.id, 1)}\n                    >\n                      <Plus aria-hidden />\n                    </Button>\n                  </span>\n                </li>\n              );\n            })}\n          </ul>\n          <div data-slot=\"dot-vote-footer\" className=\"flex flex-wrap items-center justify-between gap-3\">\n            <p aria-live=\"polite\" className=\"text-muted-foreground text-sm tabular-nums\">\n              {(labels?.left ?? ((n: number, f: string) => `${f} ${n === 1 ? 'dot' : 'dots'} left`))(\n                left,\n                nf.format(left),\n              )}\n            </p>\n            <Button data-slot=\"dot-vote-send\" size=\"lg\" disabled={left === dots} onClick={send}>\n              {labels?.send ?? 'Send my dots'}\n            </Button>\n          </div>\n        </>\n      )}\n\n      <p\n        ref={resultRef}\n        tabIndex={-1}\n        data-slot=\"dot-vote-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        {sent\n          ? (\n              labels?.result ??\n              ((v: number, f: string) => `Sent. ${f} ${v === 1 ? 'person has' : 'people have'} voted so far.`)\n            )(room.voters, nf.format(room.voters))\n          : ''}\n      </p>\n\n      {sent ? (\n        <div ref={listRef}>\n          <FlipGroup render={<ol />} data-slot=\"dot-vote-results\" className=\"grid gap-2\">\n            {room.rows.map((row) => {\n              const yours = mine?.[row.id] ?? 0;\n              return (\n                <li\n                  key={row.id}\n                  data-slot=\"dot-vote-row\"\n                  data-flip-id={row.id}\n                  data-mine={yours > 0 ? '' : undefined}\n                  className=\"grid grid-cols-[1.5rem_1fr_auto] items-baseline gap-x-3 gap-y-1\"\n                >\n                  <span className=\"text-muted-foreground text-sm font-semibold tabular-nums\">\n                    {row.rank > 0 ? nf.format(row.rank) : ''}\n                  </span>\n                  <span className={cn('min-w-0 text-base text-pretty', yours > 0 && 'font-semibold')}>\n                    {textOf(row.id)}\n                    {yours > 0 ? (\n                      <span className=\"text-primary ms-2 text-xs font-medium\">\n                        {(labels?.mine ?? ((_: number, f: string) => `Yours: ${f}`))(yours, nf.format(yours))}\n                      </span>\n                    ) : null}\n                  </span>\n                  <span className=\"text-sm tabular-nums\">{countWords(row.dots, nf.format(row.dots))}</span>\n                  <span aria-hidden className=\"bg-muted col-start-2 col-end-4 block h-2 overflow-hidden rounded-full\">\n                    <span\n                      data-slot=\"dot-vote-fill\"\n                      className={cn(\n                        'block h-full origin-left rounded-full rtl:origin-right',\n                        'motion-safe:transition-transform motion-safe:duration-(--duration-slow) motion-safe:ease-move',\n                        yours > 0 ? 'bg-primary' : 'bg-foreground/35',\n                      )}\n                      style={{ transform: `scaleX(${row.dots / top})` }}\n                    />\n                  </span>\n                </li>\n              );\n            })}\n          </FlipGroup>\n        </div>\n      ) : null}\n    </div>\n  );\n}\nDotVote.displayName = 'DotVote';\n\nexport { DotVote };\nexport type { DotVoteProps, DotVoteLabels, DotIdea };\n"
    },
    {
      "path": "registry/interlace-ui/games/dot-vote-model.ts",
      "target": "components/ui/games/dot-vote-model.ts",
      "type": "registry:ui",
      "content": "export type DotBallot = Readonly<Record<string, number>>;\n\nexport interface DotRules {\n  /** Dots each person has. @default 3 */\n  dots?: number;\n  /** Most dots on one idea. @default dots */\n  maxPerIdea?: number;\n}\n\nexport interface DotRow {\n  id: string;\n  dots: number;\n  /** People who put at least one dot here. */\n  people: number;\n  /** 1 for the most dots; ideas on the same count share a rank. 0 for none. */\n  rank: number;\n}\n\nexport interface DotTally {\n  /** Most dots first; ties in the ideas' order. */\n  rows: DotRow[];\n  /** All dots placed. */\n  total: number;\n  /** People who placed at least one dot. */\n  voters: number;\n}\n\nfunction whole(n: unknown, fallback: number): number {\n  return Number.isFinite(n) && (n as number) >= 0 ? Math.floor(n as number) : fallback;\n}\n\nfunction limits(rules: DotRules): { dots: number; cap: number } {\n  const dots = whole(rules.dots, 3);\n  const cap = Math.min(dots, whole(rules.maxPerIdea, dots));\n  return { dots, cap };\n}\n\n/** Dots still to place. */\nexport function dotsLeft(ballot: DotBallot, rules: DotRules = {}): number {\n  const { dots } = limits(rules);\n  const used = Object.values(ballot).reduce((a, n) => a + whole(n, 0), 0);\n  return Math.max(0, dots - used);\n}\n\n/** One person's dots made valid, in the ideas' order. */\nexport function cleanBallot(\n  ballot: DotBallot,\n  ideaIds: readonly string[],\n  rules: DotRules = {},\n): Record<string, number> {\n  const { dots, cap } = limits(rules);\n  const out: Record<string, number> = {};\n  let left = dots;\n  for (const id of new Set(ideaIds)) {\n    const own = Object.prototype.hasOwnProperty.call(ballot, id) ? ballot[id] : 0;\n    const n = Math.min(cap, whole(own, 0), left);\n    if (n > 0) {\n      // defineProperty: a plain `out['__proto__'] = n` would be swallowed.\n      Object.defineProperty(out, id, { value: n, enumerable: true, writable: true, configurable: true });\n      left -= n;\n    }\n  }\n  return out;\n}\n\nexport function tallyDots(\n  ballots: Readonly<Record<string, DotBallot>>,\n  ideaIds: readonly string[],\n  rules: DotRules = {},\n): DotTally {\n  const dots = new Map(ideaIds.map((id) => [id, 0]));\n  const people = new Map(ideaIds.map((id) => [id, 0]));\n  let voters = 0;\n  for (const ballot of Object.values(ballots)) {\n    const clean = cleanBallot(ballot ?? {}, ideaIds, rules);\n    const ids = Object.keys(clean);\n    if (ids.length > 0) voters += 1;\n    for (const id of ids) {\n      dots.set(id, (dots.get(id) as number) + (clean[id] as number));\n      people.set(id, (people.get(id) as number) + 1);\n    }\n  }\n  const rows = [...new Set(ideaIds)]\n    .map((id) => ({ id, dots: dots.get(id) as number, people: people.get(id) as number, rank: 0 }))\n    // Array sort is stable, so ties keep the ideas' own order.\n    .sort((a, b) => b.dots - a.dots);\n  let rank = 0;\n  rows.forEach((row, i) => {\n    if (row.dots === 0) return;\n    if (i === 0 || row.dots !== (rows[i - 1] as DotRow).dots) rank = i + 1;\n    row.rank = rank;\n  });\n  return { rows, total: rows.reduce((a, r) => a + r.dots, 0), voters };\n}\n\n/**\n * @interlace/ui — dot-vote-model\n *\n * Brainstorm, then choose: everyone spreads a few dots across the ideas on\n * the wall, and the ideas with the most dots rise. A dot vote shows how\n * strongly people feel as well as what they chose, because a person can put\n * two dots on one idea.\n *\n * `cleanBallot` makes one person's dots valid: unknown ideas dropped, whole\n * non-negative counts, at most `maxPerIdea` on one idea and `dots` in all\n * (dots past the limit are dropped from the ideas listed last; an idea listed\n * twice counts once). `tallyDots`\n * takes ballots keyed by person, so a ballot sent twice counts once and the\n * latest ballot a person sends replaces the earlier one. Ties keep the\n * ideas' own order, so every screen ranks them the same way.\n */\n"
    }
  ],
  "meta": {
    "tier": "game",
    "client": true,
    "minViewport": 320,
    "loading": false,
    "version": "1.0.0",
    "since": "2.0.0"
  },
  "docs": "## @interlace/dot-vote\n\nInstalled to `components/ui/games/dot-vote.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/games/dot-vote';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/dot-vote\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
