{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "points-split",
  "type": "registry:ui",
  "title": "Points Split",
  "description": "Spend a budget of points across options. `PointsSplit` is a phone: each option has a minus and a plus, a bar shows how much of the budget sits on it, and a counter says what is left; Send unlocks when the budget is spent. `PointsTotals` is the screen: the…",
  "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"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/games/points-split.tsx",
      "target": "components/ui/games/points-split.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport { Minus, Plus } from 'lucide-react';\n\n// @interlace/points-split v1.0.0 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/points-split\n// What changed since: https://ds.interlace.tools/c/points-split#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — PointsSplit and PointsTotals\n *\n * Spend a budget of points across options. `PointsSplit` is a phone: each\n * option has a minus and a plus, a bar shows how much of the budget sits\n * on it, and a counter says what is left; Send unlocks when the budget is\n * spent. `PointsTotals` is the screen: the room's points per option, most\n * first, gliding as the order changes.\n *\n * ## Anatomy\n *\n *   PointsSplit                     (fieldset — data-slot=\"points-split\", data-state=choosing|sent)\n *     ├─ legend                     (data-slot=\"points-split-question\")\n *     ├─ p aria-live                (data-slot=\"points-split-left\": \"40 points left\")\n *     ├─ ul > li × n                (data-slot=\"points-split-option\": name, bar, −, value, +)\n *     └─ Button                     (data-slot=\"points-split-send\")\n *   PointsTotals                    (FlipGroup ol — data-slot=\"points-totals\")\n *     └─ li × n                     (name, bar, points, share; read as one line each)\n *\n * ## Motion\n *\n * Bars grow and shrink with each tap (transform, 150ms). On the screen, rows\n * glide to their new rank (FlipGroup). Under reduced motion they just change.\n *\n * ## MIN_VIEWPORT — 320\n *\n * | Rule | Concept                   | Where in this file                                   |\n * | ---- | ------------------------- | ---------------------------------------------------- |\n * | R4   | Extends native el         | `fieldset` / `ol` props                              |\n * | R6   | data-slot per part        | points-split / -question / -left / -option / -send; points-totals |\n * | R7   | cn + ...rest              | `cn(…, className)` + `{...props}`                    |\n * | R9   | Controlled + uncontrolled | `value` / `defaultValue` / `onChange` / `onSend`     |\n * | R14  | Declares min viewport     | `data-min-viewport` + exported const                 |\n * | R26  | A11y                      | buttons named per option; the left count announced; value as text |\n */\n\nimport * as React from 'react';\n\nimport { FlipGroup } from '@/components/ui/effects/flip-group';\nimport { cn } from '@/lib/utils';\nimport { Button } from '@/components/ui/button';\nimport { checkSplit, nudge, spentOf, type PointsRules, type PointsTotal, type Split } from '@/components/ui/games/points-model';\n\nexport const MIN_VIEWPORT = 320 as const;\n\ninterface PointsOption {\n  id: string;\n  label: string;\n}\n\ninterface PointsSplitLabels {\n  /** @default (n) => `${n} points left` */\n  left?: (left: string) => string;\n  /** @default (label, step) => `Add ${step} points to ${label}` */\n  add?: (label: string, step: string) => string;\n  /** @default (label, step) => `Take ${step} points from ${label}` */\n  remove?: (label: string, step: string) => string;\n  /** @default 'Send' */\n  send?: string;\n  /** @default 'Sent. Thank you.' */\n  sent?: string;\n}\n\ntype PointsSplitProps = Omit<React.ComponentProps<'fieldset'>, 'children' | 'defaultValue' | 'onChange'> &\n  PointsRules & {\n    question: React.ReactNode;\n    options: readonly PointsOption[];\n    /** The split while choosing, controlled. */\n    value?: Split;\n    defaultValue?: Split;\n    onChange?: (split: Split) => void;\n    /** Called once with a valid split. */\n    onSend?: (split: Split) => void;\n    /** Shown after sending, instead of the controls. */\n    sent?: boolean;\n    locale?: string;\n    labels?: PointsSplitLabels;\n  };\n\nfunction PointsSplit({\n  question,\n  options,\n  budget = 100,\n  step = 10,\n  partial = false,\n  value: valueProp,\n  defaultValue = {},\n  onChange,\n  onSend,\n  sent: sentProp,\n  locale,\n  labels,\n  className,\n  disabled,\n  ...props\n}: PointsSplitProps) {\n  const [own, setOwn] = React.useState<Split>(defaultValue);\n  const split = valueProp ?? own;\n  const [sentHere, setSentHere] = React.useState(false);\n  const sent = sentProp ?? sentHere;\n  const nf = React.useMemo(() => new Intl.NumberFormat(locale), [locale]);\n  const rules = { budget, step, partial };\n  const left = budget - spentOf(split);\n  const ids = options.map((o) => o.id);\n  const valid = checkSplit(split, ids, rules).ok;\n\n  const set = (next: Split) => {\n    if (valueProp === undefined) setOwn(next);\n    onChange?.(next);\n  };\n  const send = () => {\n    if (!valid || sent) return;\n    setSentHere(true);\n    onSend?.(split);\n  };\n\n  return (\n    <fieldset\n      data-slot=\"points-split\"\n      data-state={sent ? 'sent' : 'choosing'}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      disabled={disabled || sent}\n      className={cn('grid min-w-0 gap-4', className)}\n      {...props}\n    >\n      <legend data-slot=\"points-split-question\" className=\"font-heading mb-1 text-lg font-semibold text-balance\">\n        {question}\n      </legend>\n      <p\n        data-slot=\"points-split-left\"\n        aria-live=\"polite\"\n        className={cn('text-sm font-medium tabular-nums', left === 0 ? 'text-muted-foreground' : 'text-foreground')}\n      >\n        {sent\n          ? (labels?.sent ?? 'Sent. Thank you.')\n          : (labels?.left ?? ((n: string) => `${n} points left`))(nf.format(left))}\n      </p>\n      <ul className=\"grid gap-3\">\n        {options.map((o) => {\n          const n = split[o.id] ?? 0;\n          const stepText = nf.format(step);\n          return (\n            <li key={o.id} data-slot=\"points-split-option\" className=\"grid gap-1.5\">\n              <div className=\"flex items-center gap-3\">\n                <span className=\"min-w-0 flex-1 text-sm font-medium\">{o.label}</span>\n                <Button\n                  size=\"icon-sm\"\n                  variant=\"outline\"\n                  aria-label={(labels?.remove ?? ((l: string, s: string) => `Take ${s} points from ${l}`))(\n                    o.label,\n                    stepText,\n                  )}\n                  disabled={n === 0}\n                  onClick={() => set(nudge(split, o.id, -step, rules))}\n                >\n                  <Minus aria-hidden />\n                </Button>\n                <span className=\"w-10 text-center text-sm font-semibold tabular-nums\">{nf.format(n)}</span>\n                <Button\n                  size=\"icon-sm\"\n                  variant=\"outline\"\n                  aria-label={(labels?.add ?? ((l: string, s: string) => `Add ${s} points to ${l}`))(o.label, stepText)}\n                  disabled={left < step}\n                  onClick={() => set(nudge(split, o.id, step, rules))}\n                >\n                  <Plus aria-hidden />\n                </Button>\n              </div>\n              <span aria-hidden className=\"bg-muted block h-1.5 overflow-hidden rounded-full\">\n                <span\n                  className=\"bg-primary block h-full origin-left rounded-full motion-safe:transition-transform motion-safe:duration-(--duration-base) motion-safe:ease-move rtl:origin-right\"\n                  style={{ transform: `scaleX(${budget > 0 ? n / budget : 0})` }}\n                />\n              </span>\n            </li>\n          );\n        })}\n      </ul>\n      {!sent ? (\n        <Button data-slot=\"points-split-send\" size=\"lg\" className=\"justify-self-start\" disabled={!valid} onClick={send}>\n          {labels?.send ?? 'Send'}\n        </Button>\n      ) : null}\n    </fieldset>\n  );\n}\nPointsSplit.displayName = 'PointsSplit';\n\n// --- PointsTotals (screen) -------------------------------------------------------\n\ninterface PointsTotalsLabels {\n  /** One row, read whole. @default (r) => `${r.label}: ${r.points} points, ${r.share}` */\n  row?: (r: { label: string; points: string; share: string }) => string;\n}\n\ntype PointsTotalsProps = Omit<React.ComponentProps<'div'>, 'children'> & {\n  /** From `totalPoints`. */\n  totals: readonly PointsTotal[];\n  options: readonly PointsOption[];\n  /** `stage` for a shared screen. @default 'default' */\n  size?: 'default' | 'stage';\n  locale?: string;\n  labels?: PointsTotalsLabels;\n};\n\nfunction PointsTotals({ totals, options, size = 'default', locale, labels, className, ...props }: PointsTotalsProps) {\n  const nf = React.useMemo(() => new Intl.NumberFormat(locale), [locale]);\n  const pct = React.useMemo(() => new Intl.NumberFormat(locale, { style: 'percent' }), [locale]);\n  const names = new Map(options.map((o) => [o.id, o.label]));\n  const top = Math.max(...totals.map((t) => t.share), Number.EPSILON);\n  const stage = size === 'stage';\n  return (\n    <FlipGroup\n      render={<ol />}\n      data-slot=\"points-totals\"\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('grid gap-3', className)}\n      {...props}\n    >\n      {totals.map((t) => {\n        const label = names.get(t.id) ?? t.id;\n        const points = nf.format(t.points);\n        const share = pct.format(t.share);\n        return (\n          <li key={t.id} data-flip-id={t.id} className=\"grid gap-1\">\n            <span className=\"sr-only\">\n              {(labels?.row ?? ((r) => `${r.label}: ${r.points} points, ${r.share}`))({ label, points, share })}\n            </span>\n            <div aria-hidden className={cn('flex items-baseline gap-3', stage ? 'text-lg' : 'text-sm')}>\n              <span className=\"min-w-0 flex-1 font-medium\">{label}</span>\n              <span className=\"font-semibold tabular-nums\">{points}</span>\n              <span className=\"text-muted-foreground w-12 text-end tabular-nums\">{share}</span>\n            </div>\n            <span aria-hidden className={cn('bg-muted block overflow-hidden rounded-full', stage ? 'h-3' : 'h-2')}>\n              <span\n                className=\"bg-primary block h-full origin-left rounded-full motion-safe:transition-transform motion-safe:duration-(--duration-slow) motion-safe:ease-move rtl:origin-right\"\n                style={{ transform: `scaleX(${t.share / top})` }}\n              />\n            </span>\n          </li>\n        );\n      })}\n    </FlipGroup>\n  );\n}\nPointsTotals.displayName = 'PointsTotals';\n\nexport { PointsSplit, PointsTotals };\nexport type { PointsSplitProps, PointsSplitLabels, PointsTotalsProps, PointsTotalsLabels, PointsOption };\n"
    },
    {
      "path": "registry/interlace-ui/games/points-model.ts",
      "target": "components/ui/games/points-model.ts",
      "type": "registry:ui",
      "content": "export interface PointsRules {\n  /** @default 100 */\n  budget?: number;\n  /** Points move in steps of this size. @default 10 */\n  step?: number;\n  /** Allow sending before the whole budget is spent. @default false */\n  partial?: boolean;\n}\n\nexport type Split = Readonly<Record<string, number>>;\n\nexport type SplitRefusal = 'unknown-option' | 'not-a-step' | 'negative' | 'over-budget' | 'under-budget';\n\nfunction isSplit(split: unknown): split is Split {\n  return typeof split === 'object' && split !== null && !Array.isArray(split);\n}\n\n/** A host rule that is not a usable number falls back to its default. */\nfunction rule(value: number | undefined, fallback: number, min: number): number {\n  return Number.isFinite(value) && (value as number) >= min ? (value as number) : fallback;\n}\n\nfunction rulesOf(rules: PointsRules): { budget: number; step: number; partial: boolean } {\n  const { budget, step, partial = false } = rules;\n  return { budget: rule(budget, 100, 0), step: rule(step, 10, Number.MIN_VALUE), partial };\n}\n\n/** Adds up the real amounts; anything that is not a finite number counts as nothing. */\nexport function spentOf(split: Split): number {\n  if (!isSplit(split)) return 0;\n  let spent = 0;\n  for (const n of Object.values(split)) if (Number.isFinite(n)) spent += n as number;\n  return spent;\n}\n\nexport function checkSplit(\n  split: Split,\n  options: readonly string[],\n  rules: PointsRules = {},\n): { ok: true } | { ok: false; reason: SplitRefusal } {\n  if (!isSplit(split)) return { ok: false, reason: 'unknown-option' };\n  const { budget, step, partial } = rulesOf(rules);\n  const known = new Set(Array.isArray(options) ? options : undefined);\n  for (const [id, n] of Object.entries(split)) {\n    if (!known.has(id)) return { ok: false, reason: 'unknown-option' };\n    if (!Number.isFinite(n) || (n as number) < 0) return { ok: false, reason: 'negative' };\n    if ((n as number) % step !== 0) return { ok: false, reason: 'not-a-step' };\n  }\n  const spent = spentOf(split);\n  if (spent > budget) return { ok: false, reason: 'over-budget' };\n  if (!partial && spent < budget) return { ok: false, reason: 'under-budget' };\n  return { ok: true };\n}\n\nexport interface PointsTotal {\n  id: string;\n  points: number;\n  /** 0 to 1 of all points the room spent. */\n  share: number;\n  /** People who put anything on this option. */\n  backers: number;\n}\n\n/**\n * Room totals, most points first (ties keep the options' order). `splits`\n * maps each person to their split; pass the latest per person.\n */\nexport function totalPoints(\n  splits: Readonly<Record<string, Split>>,\n  options: readonly string[],\n  rules: PointsRules = {},\n): { totals: PointsTotal[]; people: number } {\n  const ids = [...new Set(Array.isArray(options) ? options : [])];\n  const sum = new Map(ids.map((id) => [id, { points: 0, backers: 0 }]));\n  let people = 0;\n  for (const split of isSplit(splits) ? Object.values(splits) : []) {\n    if (!checkSplit(split, options, rules).ok) continue;\n    people++;\n    for (const [id, n] of Object.entries(split)) {\n      const row = sum.get(id) as { points: number; backers: number };\n      row.points += n;\n      if (n > 0) row.backers++;\n    }\n  }\n  const all = [...sum.values()].reduce((a, r) => a + r.points, 0);\n  const totals = ids\n    .map((id, i) => ({ id, i, ...(sum.get(id) as { points: number; backers: number }) }))\n    .sort((a, b) => b.points - a.points || a.i - b.i)\n    .map(({ id, points, backers }) => ({ id, points, backers, share: all > 0 ? points / all : 0 }));\n  return { totals, people };\n}\n\n/** Moves `delta` points onto (or off) one option, kept within the budget and above zero. */\nexport function nudge(split: Split, id: string, delta: number, rules: PointsRules = {}): Split {\n  const base: Split = isSplit(split) ? split : {};\n  if (!Number.isFinite(delta)) return base;\n  const { budget } = rulesOf(rules);\n  const current = base[id] ?? 0;\n  const room = budget - spentOf(base);\n  const next = Math.max(0, current + Math.min(delta, room));\n  return { ...base, [id]: next };\n}\n\n/**\n * @interlace/ui — points-model\n *\n * Spend a budget of points across options: \"you have 100 points, put them\n * where you want more time\". It shows strength of preference, which a\n * one-choice poll hides, and nobody can vote for everything.\n *\n * `checkSplit` says whether one person's split is valid: known options,\n * whole steps, nothing negative, the whole budget spent (or no more than it,\n * with `partial`). `totalPoints` adds the room's valid splits per option and\n * ranks them; invalid splits are left out, so a bad message cannot skew the\n * room, and each person counts once (the last split they sent).\n */\n"
    }
  ],
  "meta": {
    "tier": "game",
    "client": true,
    "minViewport": 320,
    "loading": false,
    "version": "1.0.0",
    "since": "2.0.0"
  },
  "docs": "## @interlace/points-split\n\nInstalled to `components/ui/games/points-split.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/games/points-split';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/points-split\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
