{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "prediction",
  "type": "registry:ui",
  "title": "Prediction",
  "description": "\"Who will win?\" on a phone: the room calls an outcome before it happens, locks it in, and waits. Nobody sees how the room called it until the host settles it, so a call is the person's own read. Then the room's spread appears with the outcome marked, and…",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "games",
    "game"
  ],
  "dependencies": [
    "@base-ui/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/motion-token.json",
    "https://ds.interlace.tools/r/tally-bars.json",
    "https://ds.interlace.tools/r/use-reduced-motion.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/games/prediction.tsx",
      "target": "components/ui/games/prediction.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport { Radio } from '@base-ui/react/radio';\n\n// @interlace/prediction v1.1.0 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/prediction\n// What changed since: https://ds.interlace.tools/c/prediction#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — Prediction\n *\n * \"Who will win?\" on a phone: the room calls an outcome before it happens,\n * locks it in, and waits. Nobody sees how the room called it until the\n * host settles it, so a call is the person's own read. Then the room's\n * spread appears with the outcome marked, and the viewer learns whether\n * they called it, with the points `predictionPoints` gives (a rare right\n * call can pay more, with `reward=\"bold\"`).\n *\n * ## Anatomy\n *\n *   Prediction                     (div — data-slot=\"prediction\", data-state=choosing|locked|closed|settled)\n *     ├─ p                         (data-slot=\"prediction-question\": names the choices)\n *     ├─ RadioGroup                (data-slot=\"prediction-options\": while choosing)\n *     │   └─ Radio × n             (data-slot=\"prediction-option\")\n *     ├─ Button                    (data-slot=\"prediction-lock\": \"Lock it in\")\n *     ├─ p tabIndex=-1 aria-live   (data-slot=\"prediction-result\": locked, closed, called it or not)\n *     └─ TallyBars                 (data-slot=\"prediction-spread\": once settled, outcome marked)\n *\n * ## Motion\n *\n * Locking in presses the chosen option once (150ms). When the outcome\n * arrives the result rises into place (200ms, `ease-enter`) and the spread's\n * bars grow; a right call lifts a little further, so a win feels like one.\n * An outcome already set on mount (a reload) is drawn in place and takes\n * no focus. Under reduced motion everything is simply there.\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        | prediction / -question / -options / -option / -lock / -result / -spread |\n * | R7   | cn + ...rest              | `cn(…, className)` + `{...props}`                    |\n * | R8   | Enums, not booleans       | `reward`                                             |\n * | R9   | Controlled + uncontrolled | `value` / `defaultValue` / `onLock`                  |\n * | R14  | Declares min viewport     | `data-min-viewport` + exported const                 |\n * | R26  | A11y                      | a named radio group; outcome in words; result focused when it was ours to move |\n */\n\nimport { RadioGroup } from '@base-ui/react/radio-group';\nimport * as React from 'react';\n\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 { predictionPoints, type PredictionReward } from '@/components/ui/games/prediction-model';\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 PredictionChoice {\n  id: string;\n  label: string;\n}\n\ninterface PredictionLabels {\n  /** @default 'Lock it in' */\n  lock?: string;\n  /** After locking in. @default (pick) => `Locked in: ${pick}. Waiting for the result.` */\n  locked?: (pick: string) => string;\n  /** Calls are closed and this viewer made none. @default 'Calls are closed.' */\n  closed?: string;\n  /** A right call. @default (points) => `You called it. +${points} points.` */\n  called?: (points: string, outcome: string) => string;\n  /** A wrong call. @default (outcome) => `Not this time. It was ${outcome}.` */\n  missed?: (outcome: string, pick: string) => string;\n  /** The outcome, for a viewer who made no call. @default (outcome) => `It was ${outcome}.` */\n  outcome?: (outcome: string) => string;\n  /** Names the room's spread. @default 'How the room called it' */\n  spread?: string;\n  tally?: TallyBarsLabels;\n}\n\ntype PredictionProps = Omit<React.ComponentProps<'div'>, 'children' | 'defaultValue'> & {\n  question: React.ReactNode;\n  options: readonly PredictionChoice[];\n  /** The viewer's locked call, controlled. null while choosing. */\n  value?: string | null;\n  /** The viewer's locked call, uncontrolled. */\n  defaultValue?: string | null;\n  /** Called once, when the viewer locks in. */\n  onLock?: (id: string) => void;\n  /** No more calls; the viewer can no longer lock in. */\n  closed?: boolean;\n  /** The outcome, once the host settles it. Settling also closes calls. */\n  outcome?: string | null;\n  /** The room's calls per option id, shown once settled. */\n  counts?: Readonly<Record<string, number>>;\n  /** `counts` already hold this viewer's call. @default false */\n  countsIncludeOwn?: boolean;\n  /** Points for a right call. @default 500 */\n  points?: number;\n  /** `bold` pays a call few people made more. @default 'flat' */\n  reward?: PredictionReward;\n  locale?: string;\n  labels?: PredictionLabels;\n};\n\nfunction Prediction({\n  question,\n  options,\n  value: valueProp,\n  defaultValue = null,\n  onLock,\n  closed = false,\n  outcome = null,\n  counts,\n  countsIncludeOwn = false,\n  points = 500,\n  reward = 'flat',\n  locale,\n  labels,\n  className,\n  ...props\n}: PredictionProps) {\n  const reduced = useReducedMotion();\n  const nf = React.useMemo(() => new Intl.NumberFormat(locale), [locale]);\n  const ids = options.map((o) => o.id);\n  const nameOf = (id: string) => options.find((o) => o.id === id)?.label ?? id;\n  const [own, setOwn] = React.useState<string | null>(defaultValue);\n  const raw = valueProp === undefined ? own : valueProp;\n  const locked = raw !== null && ids.includes(raw) ? raw : null;\n  const [draft, setDraft] = React.useState<string | null>(null);\n  const settled = outcome !== null && ids.includes(outcome) ? outcome : null;\n  const state = settled !== null ? 'settled' : locked !== null ? 'locked' : closed ? 'closed' : 'choosing';\n  const questionId = React.useId();\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const resultRef = React.useRef<HTMLParagraphElement>(null);\n  // A controlled call stays unlocked until the room echoes it back; a second tap in between must not resend it.\n  const sent = React.useRef(false);\n\n  const room = tally(ids, counts, { vote: locked, countsIncludeVote: countsIncludeOwn });\n  const outcomeRow = room.rows.find((r) => r.id === settled);\n  const right = settled !== null && locked === settled;\n  const award = predictionPoints(outcomeRow?.share ?? 1, { points, reward });\n\n  // When the outcome lands: rise into place, and focus the sentence if focus was ours to move.\n  // An outcome already there on mount (a reload) is shown as it is: no motion, no focus move.\n  const shownOutcome = React.useRef(settled);\n  React.useEffect(() => {\n    if (settled === shownOutcome.current) return;\n    shownOutcome.current = settled;\n    if (settled === null) return;\n    const root = rootRef.current;\n    const active = document.activeElement;\n    if (!active || active === document.body || root?.contains(active)) resultRef.current?.focus();\n    const el = resultRef.current;\n    if (reduced || !el || typeof el.animate !== 'function') return;\n    el.animate(\n      [\n        { transform: `translateY(${right ? 12 : 8}px)`, opacity: 0 },\n        { transform: 'translateY(0)', opacity: 1 },\n      ],\n      { duration: 200, easing: motionEase(el, 'enter') },\n    );\n    // Once per outcome.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [settled]);\n\n  const lock = () => {\n    if (locked !== null || sent.current || draft === null || closed || settled !== null) return;\n    sent.current = true;\n    const chosen = rootRef.current?.querySelector<HTMLElement>(`[data-slot=\"prediction-option\"][data-checked]`);\n    if (!reduced && chosen && typeof chosen.animate === 'function') {\n      chosen.animate([{ transform: 'scale(1)' }, { transform: 'scale(0.96)' }, { transform: 'scale(1)' }], {\n        duration: 150,\n        easing: motionEase(chosen, 'move'),\n      });\n    }\n    if (valueProp === undefined) setOwn(draft);\n    onLock?.(draft);\n  };\n\n  const result =\n    state === 'settled'\n      ? right\n        ? (labels?.called ?? ((p: string) => `You called it. +${p} points.`))(\n            nf.format(award),\n            nameOf(settled as string),\n          )\n        : locked !== null\n          ? (labels?.missed ?? ((o: string) => `Not this time. It was ${o}.`))(\n              nameOf(settled as string),\n              nameOf(locked),\n            )\n          : (labels?.outcome ?? ((o: string) => `It was ${o}.`))(nameOf(settled as string))\n      : state === 'locked'\n        ? (labels?.locked ?? ((p: string) => `Locked in: ${p}. Waiting for the result.`))(nameOf(locked as string))\n        : state === 'closed'\n          ? (labels?.closed ?? 'Calls are closed.')\n          : '';\n\n  const optionLabels = Object.fromEntries(options.map((o) => [o.id, o.label]));\n\n  return (\n    <div\n      ref={rootRef}\n      data-slot=\"prediction\"\n      data-state={state}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('grid gap-4', className)}\n      {...props}\n    >\n      <p id={questionId} data-slot=\"prediction-question\" className=\"font-heading text-lg font-semibold text-balance\">\n        {question}\n      </p>\n\n      {state === 'choosing' ? (\n        <>\n          <RadioGroup\n            data-slot=\"prediction-options\"\n            aria-labelledby={questionId}\n            value={draft}\n            onValueChange={(v) => setDraft(v as string)}\n            className=\"grid gap-2\"\n          >\n            {options.map((o) => (\n              <Radio.Root\n                key={o.id}\n                value={o.id}\n                data-slot=\"prediction-option\"\n                className={cn(\n                  'bg-background text-foreground group flex min-h-12 items-center gap-3 rounded-lg border px-4 py-3 text-start text-base font-medium',\n                  'motion-safe:transition-colors motion-safe:duration-(--duration-fast) hover:bg-muted',\n                  'data-[checked]:border-primary data-[checked]:bg-primary/10',\n                  'focus-visible:outline-ring outline-offset-2 focus-visible:outline-2',\n                )}\n              >\n                <span\n                  aria-hidden\n                  className=\"border-input grid size-5 shrink-0 place-items-center rounded-full border-2 group-data-[checked]:border-primary\"\n                >\n                  <Radio.Indicator className=\"bg-primary size-2.5 rounded-full\" />\n                </span>\n                <span className=\"min-w-0\">{o.label}</span>\n              </Radio.Root>\n            ))}\n          </RadioGroup>\n          <Button\n            data-slot=\"prediction-lock\"\n            size=\"lg\"\n            className=\"justify-self-start\"\n            disabled={draft === null}\n            onClick={lock}\n          >\n            {labels?.lock ?? 'Lock it in'}\n          </Button>\n        </>\n      ) : null}\n\n      <p\n        ref={resultRef}\n        tabIndex={-1}\n        data-slot=\"prediction-result\"\n        data-right={right ? '' : undefined}\n        aria-live=\"polite\"\n        className={cn(\n          'focus-visible:outline-ring rounded-sm outline-offset-4 empty:hidden focus-visible:outline-2',\n          state === 'settled' ? 'text-base font-semibold' : 'text-muted-foreground text-sm',\n          right && 'text-primary',\n        )}\n      >\n        {result}\n      </p>\n\n      {state === 'settled' ? (\n        <section\n          data-slot=\"prediction-spread\"\n          aria-label={labels?.spread ?? 'How the room called it'}\n          className=\"grid gap-2\"\n        >\n          <p className=\"text-muted-foreground text-xs font-semibold tracking-wide uppercase\">\n            {labels?.spread ?? 'How the room called it'}\n          </p>\n          <TallyBars\n            rows={room.rows}\n            optionLabels={optionLabels}\n            marks={{ [settled as string]: 'correct' }}\n            animate={!reduced}\n            locale={locale}\n            labels={{ correct: 'Outcome', ...labels?.tally }}\n          />\n        </section>\n      ) : null}\n    </div>\n  );\n}\nPrediction.displayName = 'Prediction';\n\nexport { Prediction };\nexport type { PredictionProps, PredictionLabels, PredictionChoice };\n"
    },
    {
      "path": "registry/interlace-ui/games/prediction-model.ts",
      "target": "components/ui/games/prediction-model.ts",
      "type": "registry:ui",
      "content": "export type PredictionReward = 'flat' | 'bold';\n\nexport interface PredictionOptions {\n  /** Points for a right call. @default 500 */\n  points?: number;\n  /** `bold` pays a rare right call more. @default 'flat' */\n  reward?: PredictionReward;\n}\n\nexport interface PredictionResult {\n  /** Picks per option id, every option present. */\n  counts: Record<string, number>;\n  /** Valid picks. */\n  total: number;\n  /** The outcome, when it is one of the options; otherwise null and nobody scores. */\n  outcome: string | null;\n  /** People who called it, sorted. */\n  winners: string[];\n  /** Share of the room that called it, 0 to 1. */\n  share: number;\n  /** Points per person who made a valid pick: the points for a right call, 0 otherwise. */\n  points: Record<string, number>;\n}\n\n/** The most a right call can be worth before the bold bonus, so a prize that is not sane never overflows. */\nexport const MAX_PREDICTION_POINTS = 1_000_000;\n\n/** Points one right call earns, given the share of the room that made it. */\nexport function predictionPoints(share: number, options: PredictionOptions = {}): number {\n  const { points = 500, reward = 'flat' } = options;\n  const base = Number.isFinite(points) ? Math.min(Math.max(0, points), MAX_PREDICTION_POINTS) : 0;\n  if (reward === 'flat') return Math.round(base);\n  const s = Number.isFinite(share) ? Math.min(1, Math.max(0, share)) : 1;\n  return Math.round(base * (2 - s));\n}\n\nexport function settlePredictions(\n  picks: Readonly<Record<string, string>>,\n  optionIds: readonly string[],\n  outcome: string | null | undefined,\n  options: PredictionOptions = {},\n): PredictionResult {\n  const ids = Array.isArray(optionIds) ? optionIds.filter((id) => typeof id === 'string') : [];\n  const record = typeof picks === 'object' && picks !== null && !Array.isArray(picks) ? picks : {};\n  const known = new Set(ids);\n  const counts: Record<string, number> = Object.fromEntries(ids.map((id) => [id, 0]));\n  const valid = Object.entries(record).filter(([, pick]) => known.has(pick));\n  for (const [, pick] of valid) counts[pick] = (counts[pick] as number) + 1;\n  const total = valid.length;\n  const settled = known.has(outcome as string) ? (outcome as string) : null;\n  const winners = valid.filter(([, pick]) => pick === settled).map(([by]) => by);\n  winners.sort();\n  const share = total > 0 ? winners.length / total : 0;\n  const award = predictionPoints(share, options);\n  const points: Record<string, number> = Object.fromEntries(\n    valid.map(([by, pick]) => [by, pick === settled ? award : 0]),\n  );\n  return { counts, total, outcome: settled, winners, share, points };\n}\n\n/**\n * @interlace/ui — prediction-model\n *\n * \"Who will win?\": everyone calls an outcome before it happens (the next\n * round, a vote, a guess about the room itself), the host settles it, and\n * whoever called it scores. Calling it is about reading the room, so the\n * room's spread is shown only after the outcome.\n *\n * `settlePredictions` takes picks keyed by person, so a message delivered\n * twice, or late, changes nothing. A pick for an option that does not\n * exist is dropped. With `reward: 'bold'` a call few people made pays more\n * than one everybody made: up to twice the points for a call only you\n * made, the base points for one the whole room made.\n */\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.1.0",
    "since": "2.0.0"
  },
  "docs": "## @interlace/prediction\n\nInstalled to `components/ui/games/prediction.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/games/prediction';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/prediction\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
