{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "standings",
  "type": "registry:ui",
  "title": "Standings",
  "description": "The board between rounds of a live game: who is where now, and how they got there. Each player's points from this round pop up beside their name, their total counts up from where it was, and then the rows glide to their new places, with the places gained…",
  "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/cn.json",
    "https://ds.interlace.tools/r/count-up.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/standings.tsx",
      "target": "components/ui/games/standings.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/standings v1.1.1 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/standings\n// What changed since: https://ds.interlace.tools/c/standings#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — Standings\n *\n * The board between rounds of a live game: who is where now, and how they\n * got there. Each player's points from this round pop up beside their name,\n * their total counts up from where it was, and then the rows glide to their\n * new places, with the places gained said in words. It is the moment a room\n * looks up at the big screen, so the change is the content: a board that\n * jumped would hide who overtook whom.\n *\n * ## Anatomy\n *\n *   Standings                       (section — data-slot=\"standings\", data-phase=before|after)\n *     ├─ h2/p?                      (data-slot=\"standings-caption\", when `showCaption`)\n *     └─ ol (FlipGroup)             (data-slot=\"standings-list\")\n *         └─ li × n                 (data-slot=\"standings-row\", data-flip-id, data-rank, data-current, data-moved)\n *             ├─ span               (data-slot=\"standings-rank\")\n *             ├─ span               (data-slot=\"standings-name\", with a \"You\" tag on the viewer's row)\n *             │   under it: span?   (data-slot=\"standings-gained\": \"+990\", this round)\n *             │         and span?   (data-slot=\"standings-moved\": \"▲ 2\", places gained)\n *             └─ span               (data-slot=\"standings-score\", CountUp)\n *\n * ## Content first\n *\n * The list is an ordered list in the final order once the glide starts, and\n * every figure is text: rank, name, points this round, places gained and\n * the total, read as one sentence per row. The moving digits are hidden from\n * assistive tech (CountUp keeps one stable label). Ranking is\n * `rankEntries` from leaderboard-model, so ties share a place everywhere.\n *\n * ## Motion\n *\n * Three beats, each one a thing the eye can follow: the round's points pop\n * in (scale only, so the text is never faint; 40ms apart a row), the totals\n * count up (`countMs`, 900ms), then the rows glide to their new places (FlipGroup,\n * transform only, 520ms) and a row that climbed shows its arrow. Under\n * reduced motion, or with `animate={false}`, the board is simply in its new\n * order with every figure in place.\n *\n * ## MIN_VIEWPORT — 320\n *\n * Names wrap onto a second line (never an ellipsis) before the figures move.\n *\n * | Rule | Concept                   | Where in this file                               |\n * | ---- | ------------------------- | ------------------------------------------------ |\n * | R4   | Extends native el         | `React.ComponentProps<'section'>`                |\n * | R6   | data-slot per part        | standings / -list / -row / -rank / -name / …     |\n * | R7   | cn + ...rest              | `cn(…, className)` + `{...props}`                |\n * | R14  | Declares min viewport     | `data-min-viewport` + exported const             |\n * | R19  | Tokens only               | primary, success, muted, border                  |\n * | R26  | A11y                      | ordered list, figures in words, stable labels    |\n */\n\nimport { CountUp } from '@/components/ui/effects/count-up';\nimport { FlipGroup } from '@/components/ui/effects/flip-group';\nimport { cn } from '@/lib/utils';\nimport { useReducedMotion } from '@/hooks/use-reduced-motion';\nimport { motionEase } from '@/lib/motion-token';\nimport { rankEntries, type RankedEntry } from '@/components/ui/games/leaderboard-model';\n\nexport const MIN_VIEWPORT = 320 as const;\n\nexport interface StandingsEntry {\n  id: string;\n  name: string;\n  /** The total after this round. */\n  score: number;\n  /** Points won this round, already in `score`. 0 or missing: none. */\n  gained?: number;\n}\n\nexport interface StandingsLabels {\n  /** @default 'You' */\n  you?: string;\n  /** Read for a row's points this round. @default (n) => `${n} points this round` */\n  gained?: (formatted: string) => string;\n  /** Read for places gained. @default (n) => n === 1 ? 'up 1 place' : `up ${n} places` */\n  up?: (n: number) => string;\n  /** Read for places lost. @default (n) => n === 1 ? 'down 1 place' : `down ${n} places` */\n  down?: (n: number) => string;\n  /** Read before the total. @default 'total' */\n  total?: string;\n}\n\ntype StandingsProps = Omit<React.ComponentProps<'section'>, 'children'> & {\n  entries: readonly StandingsEntry[];\n  /** Names the board. */\n  caption: React.ReactNode;\n  /** Show the caption, or keep it for assistive tech only. @default true */\n  showCaption?: boolean;\n  /** The viewing player's id: their row is marked and always shown. */\n  currentId?: string;\n  /** The most rows shown, plus the viewer's own if it falls below. @default 8 */\n  limit?: number;\n  /** Play the three beats. @default true */\n  animate?: boolean;\n  /** How long the totals count, in ms; the glide follows. @default 900 */\n  countMs?: number;\n  locale?: string;\n  labels?: StandingsLabels;\n};\n\n\n/** The rows to show: the top `limit` by the new ranking, plus the viewer's own. */\nfunction pick(now: RankedEntry[], limit: number, currentId?: string): Set<string> {\n  const ids = new Set(now.slice(0, limit).map((e) => e.id));\n  if (currentId && now.some((e) => e.id === currentId)) ids.add(currentId);\n  return ids;\n}\n\nfunction Standings({\n  entries,\n  caption,\n  showCaption = true,\n  currentId,\n  limit = 8,\n  animate = true,\n  countMs = 900,\n  locale,\n  labels,\n  className,\n  ...props\n}: StandingsProps) {\n  const reduced = useReducedMotion();\n  const play = animate && !reduced;\n  const captionId = React.useId();\n  const rootRef = React.useRef<HTMLElement>(null);\n\n  const gainedOf = React.useMemo(() => new Map(entries.map((e) => [e.id, Math.max(0, e.gained ?? 0)])), [entries]);\n  const now = React.useMemo(() => rankEntries(entries.map(({ id, name, score }) => ({ id, name, score }))), [entries]);\n  const before = React.useMemo(\n    () =>\n      rankEntries(\n        entries.map(({ id, name, score, gained }) => ({ id, name, score: score - Math.max(0, gained ?? 0) })),\n      ),\n    [entries],\n  );\n  const shown = React.useMemo(() => pick(now, limit, currentId), [now, limit, currentId]);\n  const beforeRank = React.useMemo(() => new Map(before.map((e) => [e.id, e.rank])), [before]);\n  // Before anyone scored, everyone was level: a climb or a drop would mean nothing.\n  const firstRound = before.every((e) => e.score === 0);\n\n  // A new round's figures start the beats again.\n  const roundKey = entries.map((e) => `${e.id}:${e.score}`).join('|');\n  const [phase, setPhase] = React.useState<'before' | 'after'>(play ? 'before' : 'after');\n  React.useEffect(() => {\n    if (!play) {\n      setPhase('after');\n      return;\n    }\n    setPhase('before');\n    const list = rootRef.current;\n    // Beat one: the round's points pop in, a row at a time.\n    list?.querySelectorAll<HTMLElement>('[data-slot=\"standings-gained\"]').forEach((chip, i) => {\n      if (typeof chip.animate === 'function')\n        chip.animate(\n          [{ transform: 'scale(0.4)' }, { transform: 'scale(1.12)', offset: 0.6 }, { transform: 'scale(1)' }],\n          { duration: 420, delay: i * 40, easing: motionEase(chip, 'enter'), fill: 'backwards' },\n        );\n    });\n    // Beat three, once the totals have counted: the glide.\n    const t = setTimeout(() => setPhase('after'), countMs);\n    return () => clearTimeout(t);\n  }, [roundKey, play, countMs]);\n\n  const nf = React.useMemo(() => new Intl.NumberFormat(locale), [locale]);\n  const order = (phase === 'before' ? before : now).filter((e) => shown.has(e.id));\n  const nowRank = new Map(now.map((e) => [e.id, e]));\n  const you = labels?.you ?? 'You';\n  const words = {\n    gained: labels?.gained ?? ((n: string) => `${n} points this round`),\n    up: labels?.up ?? ((n: number) => (n === 1 ? 'up 1 place' : `up ${n} places`)),\n    down: labels?.down ?? ((n: number) => (n === 1 ? 'down 1 place' : `down ${n} places`)),\n    total: labels?.total ?? 'total',\n  };\n\n  return (\n    <section\n      ref={rootRef}\n      data-slot=\"standings\"\n      data-phase={phase}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      aria-labelledby={captionId}\n      className={cn('grid gap-3', className)}\n      {...props}\n    >\n      <p\n        id={captionId}\n        data-slot=\"standings-caption\"\n        className={cn('font-heading text-lg font-semibold', !showCaption && 'sr-only')}\n      >\n        {caption}\n      </p>\n      <FlipGroup duration={520} render={<ol data-slot=\"standings-list\" className=\"grid gap-2\" />}>\n        {order.map((shownEntry) => {\n          const final = nowRank.get(shownEntry.id)!;\n          const rank = phase === 'before' ? shownEntry.rank : final.rank;\n          const tied = phase === 'before' ? shownEntry.tied : final.tied;\n          const gained = gainedOf.get(final.id) ?? 0;\n          const moved = (beforeRank.get(final.id) ?? final.rank) - final.rank;\n          const current = final.id === currentId;\n          const showMoved = phase === 'after' && moved !== 0 && !firstRound;\n          return (\n            <li\n              key={final.id}\n              data-flip-id={final.id}\n              data-slot=\"standings-row\"\n              data-rank={final.rank}\n              data-current={current ? '' : undefined}\n              data-moved={moved > 0 ? 'up' : moved < 0 ? 'down' : undefined}\n              className={cn(\n                'border-border bg-card text-card-foreground flex items-center gap-3 rounded-lg border px-3 py-2.5',\n                current && 'border-primary bg-primary/8',\n              )}\n            >\n              <span\n                data-slot=\"standings-rank\"\n                className={cn(\n                  'grid size-8 shrink-0 place-items-center rounded-md text-sm font-semibold tabular-nums',\n                  rank <= 3 ? 'bg-primary text-primary-foreground' : 'bg-muted text-foreground',\n                )}\n              >\n                {tied ? `=${rank}` : rank}\n              </span>\n              <span className=\"grid min-w-0 flex-1 gap-0.5\">\n                <span data-slot=\"standings-name\" className=\"flex min-w-0 items-center gap-2\">\n                  <span data-slot=\"standings-name-text\" className={cn('min-w-0 wrap-anywhere', current && 'font-semibold')}>\n                    {final.name}\n                  </span>\n                  {current ? (\n                    <span className=\"border-primary text-primary shrink-0 rounded-full border px-2 text-xs leading-5 font-semibold\">\n                      {you}\n                    </span>\n                  ) : null}\n                </span>\n                {gained > 0 || showMoved ? (\n                  <span className=\"flex flex-wrap items-center gap-x-2 text-sm\">\n                    {gained > 0 ? (\n                      <span\n                        data-slot=\"standings-gained\"\n                        className=\"text-success inline-block font-semibold tabular-nums\"\n                      >\n                        <span aria-hidden>+{nf.format(gained)}</span>\n                        <span className=\"sr-only\">, {words.gained(nf.format(gained))}</span>\n                      </span>\n                    ) : null}\n                    {showMoved ? (\n                      <span\n                        data-slot=\"standings-moved\"\n                        className={cn(\n                          'font-semibold tabular-nums',\n                          moved > 0 ? 'text-success' : 'text-muted-foreground',\n                        )}\n                      >\n                        <span aria-hidden>\n                          {moved > 0 ? '▲' : '▼'} {Math.abs(moved)}\n                        </span>\n                        <span className=\"sr-only\">, {moved > 0 ? words.up(moved) : words.down(-moved)}</span>\n                      </span>\n                    ) : null}\n                  </span>\n                ) : null}\n              </span>\n              <span data-slot=\"standings-score\" className=\"shrink-0 text-end font-semibold tabular-nums\">\n                <span className=\"sr-only\">, {words.total} </span>\n                {play ? (\n                  <CountUp\n                    key={`${final.id}:${final.score}`}\n                    value={final.score}\n                    from={final.score - gained}\n                    duration={countMs}\n                    format={{ maximumFractionDigits: 0 }}\n                    start=\"mount\"\n                    locale={locale}\n                  />\n                ) : (\n                  nf.format(final.score)\n                )}\n              </span>\n            </li>\n          );\n        })}\n      </FlipGroup>\n    </section>\n  );\n}\n\nStandings.displayName = 'Standings';\n\nexport { Standings };\nexport type { StandingsProps };\n"
    },
    {
      "path": "registry/interlace-ui/games/leaderboard-model.ts",
      "target": "components/ui/games/leaderboard-model.ts",
      "type": "registry:ui",
      "content": "export interface LeaderboardEntry {\n  /** Stable id: a player or a group. */\n  id: string;\n  /** What the board shows. */\n  name: string;\n  score: number;\n  /** Breaks ties on score: lower first (time taken, say). Equal or missing values share a rank. */\n  tiebreak?: number;\n}\n\nexport interface RankedEntry extends LeaderboardEntry {\n  /** 1-based; ties share a rank and the next rank skips (1, 2, 2, 4). */\n  rank: number;\n  /** True when another entry has the same rank. */\n  tied: boolean;\n}\n\nexport interface RankOptions {\n  /** `desc` when a higher score wins. @default 'desc' */\n  order?: 'desc' | 'asc';\n  /** Below this many entries the board is hidden. @default 1 */\n  minPlayers?: number;\n  /** Rows to show from the top. @default all */\n  limit?: number;\n  /** The viewing player's id: their row is kept even outside `limit`. */\n  currentId?: string;\n}\n\nexport interface RankedBoard {\n  /** False while fewer than `minPlayers` have played. */\n  visible: boolean;\n  /** Entries counted. */\n  players: number;\n  /** The top rows, within `limit`. Empty while hidden. */\n  top: RankedEntry[];\n  /** The viewing player's row when it falls outside `top`. */\n  current?: RankedEntry;\n}\n\n/** Rank every entry. */\nexport function rankEntries(entries: readonly LeaderboardEntry[], order: 'desc' | 'asc' = 'desc'): RankedEntry[] {\n  const sign = order === 'desc' ? -1 : 1;\n  // An id counts once: a repeated message must not add a row, and the latest report wins.\n  const sorted = [...new Map(entries.map((e) => [e.id, e])).values()]\n    .sort(\n      (a, b) =>\n        sign * (a.score - b.score) || (a.tiebreak ?? Infinity) - (b.tiebreak ?? Infinity) || a.name.localeCompare(b.name),\n    );\n  const same = (a: LeaderboardEntry, b: LeaderboardEntry) => a.score === b.score && (a.tiebreak ?? null) === (b.tiebreak ?? null);\n  const ranked: RankedEntry[] = [];\n  sorted.forEach((entry, i) => {\n    const prev = sorted[i - 1];\n    const rank = prev && same(prev, entry) ? (ranked[i - 1] as RankedEntry).rank : i + 1;\n    ranked.push({ ...entry, rank, tied: false });\n  });\n  for (let i = 0; i < ranked.length; i++) {\n    const r = ranked[i] as RankedEntry;\n    r.tied = ranked[i - 1]?.rank === r.rank || ranked[i + 1]?.rank === r.rank;\n  }\n  return ranked;\n}\n\n/** The board as a page shows it: hidden below the minimum, top rows, and the viewer's own row. */\nexport function buildBoard(entries: readonly LeaderboardEntry[], options: RankOptions = {}): RankedBoard {\n  const { order = 'desc', minPlayers = 1, limit, currentId } = options;\n  const ranked = rankEntries(entries, order);\n  const players = ranked.length;\n  if (players < Math.max(1, minPlayers)) return { visible: false, players, top: [] };\n  const top = limit === undefined ? ranked : ranked.slice(0, limit);\n  const mine = currentId === undefined ? undefined : ranked.find((e) => e.id === currentId);\n  const current = mine && !top.includes(mine) ? mine : undefined;\n  return { visible: true, players, top, current };\n}\n\n/**\n * @interlace/ui — games/leaderboard-model\n *\n * Ranking for a group's board: ties share a rank (1, 2, 2, 4), the board\n * stays hidden until enough people have played, and the player's own row is\n * found even when it falls outside the top rows. Pure, so the server that\n * stores scores ranks them the same way.\n *\n * ## Why a minimum\n *\n * A board of two people tells each of them exactly what the other scored.\n * `minPlayers` keeps a small group's scores private until there are enough\n * of them to stand in a crowd.\n */\n"
    }
  ],
  "meta": {
    "tier": "game",
    "client": true,
    "minViewport": 320,
    "loading": false,
    "version": "1.1.1",
    "since": "2.0.0"
  },
  "docs": "## @interlace/standings\n\nInstalled to `components/ui/games/standings.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/games/standings';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/standings\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
