{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "ranking",
  "type": "registry:ui",
  "title": "Ranking",
  "description": "A room ranks the same items by preference. `RankChoices` is a phone: the items in a seeded starting order (so nobody's first item is favoured by where it was printed), moved with up and down buttons or the arrow keys on each row's handle, then sent.…",
  "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/ranking.tsx",
      "target": "components/ui/games/ranking.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport { ArrowDown, ArrowUp, ChevronsUpDown } from 'lucide-react';\n\n// @interlace/ranking v1.2.0 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/ranking\n// What changed since: https://ds.interlace.tools/c/ranking#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — RankChoices and RankResults\n *\n * A room ranks the same items by preference. `RankChoices` is a phone: the\n * items in a seeded starting order (so nobody's first item is favoured by\n * where it was printed), moved with up and down buttons or the arrow keys\n * on each row's handle, then sent. `RankResults` is the screen: the room's\n * order with each item's average place and first-place count, gliding as\n * answers arrive. For a round with a right order, use `OrderGame`.\n *\n * ## Anatomy\n *\n *   RankChoices                    (div — data-slot=\"rank-choices\", data-state=ranking|sent)\n *     ├─ p                         (data-slot=\"rank-choices-question\", labels the list)\n *     ├─ ol (FlipGroup)            (data-slot=\"rank-choices-list\")\n *     │   └─ li × n                (place, handle button (arrow keys), label, up / down)\n *     ├─ Button                    (data-slot=\"rank-choices-send\")\n *     └─ span sr-only aria-live    (data-slot=\"rank-choices-announce\": \"Music, now 2 of 4\")\n *   RankResults                    (FlipGroup ol — data-slot=\"rank-results\")\n *     └─ li × n                    (place, label, bar, average place; read as one line)\n *\n * ## Motion\n *\n * A moved row and its neighbour glide (FlipGroup, 250ms); room rows glide\n * to their new places as answers arrive. Under reduced motion they jump.\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        | rank-choices / -question / -list / -send / -announce; rank-results |\n * | R7   | cn + ...rest              | `cn(…, className)` + `{...props}`                    |\n * | R9   | Controlled + uncontrolled | `order` / `defaultOrder` / `onOrderChange` / `onSend` |\n * | R14  | Declares min viewport     | `data-min-viewport` + exported const                 |\n * | R26  | A11y                      | moves by button or key, each announced; results read as one line per row |\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 { seededShuffle } from '@/components/ui/games/daily';\nimport { moveItem } from '@/components/ui/games/order-model';\nimport type { RankedItem } from '@/components/ui/games/ranking-model';\n\nexport const MIN_VIEWPORT = 320 as const;\n\ninterface RankOption {\n  id: string;\n  label: string;\n}\n\ninterface RankChoicesLabels {\n  /** @default (label) => `Move ${label} up` */\n  up?: (label: string) => string;\n  /** @default (label) => `Move ${label} down` */\n  down?: (label: string) => string;\n  /** The handle's name. @default (label, place, total) => `${label}, ${place} of ${total}. Use the arrow keys to move it.` */\n  handle?: (label: string, place: number, total: number) => string;\n  /** Announced after a move. @default (label, place, total) => `${label}, now ${place} of ${total}` */\n  moved?: (label: string, place: number, total: number) => string;\n  /** @default 'Send my order' */\n  send?: string;\n  /** @default 'Sent. Thank you.' */\n  sent?: string;\n}\n\ntype RankChoicesProps = Omit<React.ComponentProps<'div'>, 'children'> & {\n  question: React.ReactNode;\n  options: readonly RankOption[];\n  /** Seeds the starting order. @default the ids joined */\n  seed?: number | string;\n  order?: readonly string[];\n  defaultOrder?: readonly string[];\n  onOrderChange?: (order: string[]) => void;\n  /** Called once, with the order. */\n  onSend?: (order: string[]) => void;\n  /** Shown as sent, from the parent. */\n  sent?: boolean;\n  labels?: RankChoicesLabels;\n};\n\nfunction RankChoices({\n  question,\n  options,\n  seed,\n  order: orderProp,\n  defaultOrder,\n  onOrderChange,\n  onSend,\n  sent: sentProp,\n  labels,\n  className,\n  ...props\n}: RankChoicesProps) {\n  const ids = options.map((o) => o.id);\n  const [own, setOwn] = React.useState<readonly string[]>(\n    () => defaultOrder ?? seededShuffle(ids, seed ?? ids.join('|')),\n  );\n  const order = orderProp ?? own;\n  const [sentHere, setSentHere] = React.useState(false);\n  const sent = sentProp ?? sentHere;\n  const [announce, setAnnounce] = React.useState('');\n  const questionId = React.useId();\n  const names = new Map(options.map((o) => [o.id, o.label]));\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const total = order.length;\n\n  const move = (from: number, to: number, focusHandle: boolean) => {\n    if (sent || to < 0 || to >= total || from === to) return;\n    const next = moveItem(order, from, to);\n    const id = order[from] as string;\n    if (orderProp === undefined) setOwn(next);\n    onOrderChange?.(next);\n    setAnnounce(\n      (labels?.moved ?? ((l: string, p: number, t: number) => `${l}, now ${p} of ${t}`))(\n        names.get(id) ?? id,\n        to + 1,\n        total,\n      ),\n    );\n    if (focusHandle) {\n      // Keep focus on the moved row's handle after the DOM reorders.\n      queueMicrotask(() =>\n        [...(rootRef.current?.querySelectorAll<HTMLElement>('[data-handle]') ?? [])]\n          .find((el) => el.dataset.handle === id)\n          ?.focus(),\n      );\n    }\n  };\n\n  const onKey = (e: React.KeyboardEvent, i: number) => {\n    const to =\n      e.key === 'ArrowUp'\n        ? i - 1\n        : e.key === 'ArrowDown'\n          ? i + 1\n          : e.key === 'Home'\n            ? 0\n            : e.key === 'End'\n              ? total - 1\n              : null;\n    if (to === null) return;\n    e.preventDefault();\n    move(i, to, true);\n  };\n\n  return (\n    <div\n      ref={rootRef}\n      data-slot=\"rank-choices\"\n      data-state={sent ? 'sent' : 'ranking'}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('grid gap-4', className)}\n      {...props}\n    >\n      <p id={questionId} data-slot=\"rank-choices-question\" className=\"font-heading text-lg font-semibold text-balance\">\n        {question}\n      </p>\n      <FlipGroup\n        render={<ol />}\n        duration={250}\n        aria-labelledby={questionId}\n        data-slot=\"rank-choices-list\"\n        className=\"grid gap-2\"\n      >\n        {order.map((id, i) => {\n          const label = names.get(id) ?? id;\n          return (\n            <li key={id} data-flip-id={id} className=\"bg-card flex items-center gap-2 rounded-lg border p-2 ps-3\">\n              <span aria-hidden className=\"text-muted-foreground w-5 text-sm font-semibold tabular-nums\">\n                {i + 1}\n              </span>\n              <button\n                type=\"button\"\n                data-handle={id}\n                disabled={sent}\n                aria-label={(\n                  labels?.handle ??\n                  ((l: string, p: number, t: number) => `${l}, ${p} of ${t}. Use the arrow keys to move it.`)\n                )(label, i + 1, total)}\n                onKeyDown={(e) => onKey(e, i)}\n                className=\"text-muted-foreground focus-visible:outline-ring grid size-8 place-items-center rounded-md outline-offset-2 focus-visible:outline-2 disabled:opacity-50\"\n              >\n                <ChevronsUpDown aria-hidden className=\"size-4\" />\n              </button>\n              <span className=\"min-w-0 flex-1 text-sm font-medium\">{label}</span>\n              <Button\n                size=\"icon-sm\"\n                variant=\"ghost\"\n                aria-label={(labels?.up ?? ((l: string) => `Move ${l} up`))(label)}\n                disabled={sent || i === 0}\n                onClick={() => move(i, i - 1, false)}\n              >\n                <ArrowUp aria-hidden />\n              </Button>\n              <Button\n                size=\"icon-sm\"\n                variant=\"ghost\"\n                aria-label={(labels?.down ?? ((l: string) => `Move ${l} down`))(label)}\n                disabled={sent || i === total - 1}\n                onClick={() => move(i, i + 1, false)}\n              >\n                <ArrowDown aria-hidden />\n              </Button>\n            </li>\n          );\n        })}\n      </FlipGroup>\n      {sent ? (\n        <p className=\"text-muted-foreground text-sm\">{labels?.sent ?? 'Sent. Thank you.'}</p>\n      ) : (\n        <Button\n          data-slot=\"rank-choices-send\"\n          size=\"lg\"\n          className=\"justify-self-start\"\n          onClick={() => {\n            setSentHere(true);\n            onSend?.([...order]);\n          }}\n        >\n          {labels?.send ?? 'Send my order'}\n        </Button>\n      )}\n      <span data-slot=\"rank-choices-announce\" aria-live=\"polite\" className=\"sr-only\">\n        {announce}\n      </span>\n    </div>\n  );\n}\nRankChoices.displayName = 'RankChoices';\n\n// --- RankResults (screen) --------------------------------------------------------\n\ninterface RankResultsLabels {\n  /** One row, read whole; `mean` is null while nobody has ranked. @default English: 'Music: place 1, average place 1.8, first for 4 people' */\n  row?: (r: { place: number; label: string; mean: string | null; firsts: string }) => string;\n  /** The visible average. @default (mean) => `avg ${mean}` */\n  mean?: (mean: string) => string;\n}\n\ntype RankResultsProps = Omit<React.ComponentProps<'div'>, 'children'> & {\n  /** From `tallyRankings`. */\n  items: readonly RankedItem[];\n  options: readonly RankOption[];\n  /** `stage` for a shared screen. @default 'default' */\n  size?: 'default' | 'stage';\n  locale?: string;\n  labels?: RankResultsLabels;\n};\n\nfunction RankResults({ items, options, size = 'default', locale, labels, className, ...props }: RankResultsProps) {\n  const one = React.useMemo(() => new Intl.NumberFormat(locale, { maximumFractionDigits: 1 }), [locale]);\n  const nf = React.useMemo(() => new Intl.NumberFormat(locale), [locale]);\n  const names = new Map(options.map((o) => [o.id, o.label]));\n  const top = Math.max(...items.map((r) => r.points), 1);\n  const stage = size === 'stage';\n  return (\n    <FlipGroup\n      render={<ol />}\n      data-slot=\"rank-results\"\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('grid gap-3', className)}\n      {...props}\n    >\n      {items.map((r, i) => {\n        const label = names.get(r.id) ?? r.id;\n        const mean = r.meanPlace === null ? null : one.format(r.meanPlace);\n        const firsts = nf.format(r.firsts);\n        return (\n          <li key={r.id} data-flip-id={r.id} className=\"grid gap-1\">\n            <span className=\"sr-only\">\n              {(\n                labels?.row ??\n                ((x) =>\n                  `${x.label}: place ${x.place}${x.mean === null ? '' : `, average place ${x.mean}`}, first for ${x.firsts} ${x.firsts === '1' ? 'person' : 'people'}`)\n              )({ place: i + 1, label, mean, firsts })}\n            </span>\n            <div aria-hidden className={cn('flex items-baseline gap-3', stage ? 'text-lg' : 'text-sm')}>\n              <span className=\"text-muted-foreground w-5 font-semibold tabular-nums\">{i + 1}</span>\n              <span className=\"min-w-0 flex-1 font-medium\">{label}</span>\n              {mean === null ? null : (\n                <span className=\"text-muted-foreground tabular-nums\">\n                  {(labels?.mean ?? ((m: string) => `avg ${m}`))(mean)}\n                </span>\n              )}\n            </div>\n            <span aria-hidden className={cn('bg-muted ms-8 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(${r.points / top})` }}\n              />\n            </span>\n          </li>\n        );\n      })}\n    </FlipGroup>\n  );\n}\nRankResults.displayName = 'RankResults';\n\nexport { RankChoices, RankResults };\nexport type { RankChoicesProps, RankChoicesLabels, RankResultsProps, RankResultsLabels, RankOption };\n"
    },
    {
      "path": "registry/interlace-ui/games/daily.ts",
      "target": "components/ui/games/daily.ts",
      "type": "registry:ui",
      "content": "export type DayKey = string;\n\nconst DAY_MS = 86_400_000;\nconst KEY_RE = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\n/**\n * The calendar day `date` falls on in `timeZone` (an IANA name such as\n * `\"Europe/Paris\"`). Without a time zone, the runtime's own is used, which on\n * a server is usually UTC: pass the player's zone when the page renders on\n * one.\n */\nexport function dayKey(date: Date | number = Date.now(), timeZone?: string): DayKey {\n  const parts = new Intl.DateTimeFormat('en-US', {\n    timeZone,\n    year: 'numeric',\n    month: '2-digit',\n    day: '2-digit',\n  }).formatToParts(typeof date === 'number' ? new Date(date) : date);\n  const part = Object.fromEntries(parts.map((p) => [p.type, p.value]));\n  return `${part.year}-${part.month}-${part.day}`;\n}\n\n/** True when `value` is a well-formed day key for a real date. */\nexport function isDayKey(value: unknown): value is DayKey {\n  if (typeof value !== 'string') return false;\n  const m = KEY_RE.exec(value);\n  if (!m) return false;\n  const d = new Date(Date.UTC(+m[1], +m[2] - 1, +m[3]));\n  return d.getUTCFullYear() === +m[1] && d.getUTCMonth() === +m[2] - 1 && d.getUTCDate() === +m[3];\n}\n\nfunction toUtc(key: DayKey): number {\n  const m = KEY_RE.exec(key);\n  if (!m) throw new RangeError(`Not a day key: \"${key}\" (expected YYYY-MM-DD)`);\n  return Date.UTC(+m[1], +m[2] - 1, +m[3]);\n}\n\n/** Midnight UTC of the day, as a Date: the safe way to format a key with Intl. */\nexport function dayKeyToDate(key: DayKey): Date {\n  return new Date(toUtc(key));\n}\n\n/** The key `days` after `key` (negative goes back). */\nexport function addDays(key: DayKey, days: number): DayKey {\n  return new Date(toUtc(key) + days * DAY_MS).toISOString().slice(0, 10);\n}\n\n/** Whole days from `from` to `to`; negative when `to` is earlier. */\nexport function daysBetween(from: DayKey, to: DayKey): number {\n  return Math.round((toUtc(to) - toUtc(from)) / DAY_MS);\n}\n\n/** Day of the week, 0 for Sunday to 6 for Saturday, as `Date.getDay` counts. */\nexport function weekdayOf(key: DayKey): number {\n  return new Date(toUtc(key)).getUTCDay();\n}\n\n/**\n * The puzzle's number: 1 on `firstDay`, 2 the day after. Before `firstDay`\n * it is 0 or less, which a caller should treat as \"not started\".\n */\nexport function puzzleNumber(key: DayKey, firstDay: DayKey): number {\n  return daysBetween(firstDay, key) + 1;\n}\n\n/** FNV-1a, 32-bit: a small, stable string hash for seeds. */\nexport function hashString(value: string): number {\n  let h = 0x811c9dc5;\n  for (let i = 0; i < value.length; i++) {\n    h ^= value.charCodeAt(i);\n    h = Math.imul(h, 0x01000193);\n  }\n  return h >>> 0;\n}\n\n/**\n * A seeded generator of numbers in [0, 1) (mulberry32). Good enough to deal\n * puzzles and shuffle answers the same way everywhere; not for anything\n * secret.\n */\nexport function seededRandom(seed: number | string): () => number {\n  let a = typeof seed === 'string' ? hashString(seed) : seed >>> 0;\n  return () => {\n    a = (a + 0x6d2b79f5) >>> 0;\n    let t = a;\n    t = Math.imul(t ^ (t >>> 15), t | 1);\n    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);\n    return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;\n  };\n}\n\n/** A copy of `items` in a seeded order (Fisher–Yates). */\nexport function seededShuffle<T>(items: readonly T[], seed: number | string): T[] {\n  const out = items.slice();\n  const random = seededRandom(seed);\n  for (let i = out.length - 1; i > 0; i--) {\n    const j = Math.floor(random() * (i + 1));\n    [out[i], out[j]] = [out[j] as T, out[i] as T];\n  }\n  return out;\n}\n\nexport interface DailyIndexOptions {\n  /** The day puzzle 1 ran. */\n  firstDay: DayKey;\n  /** `sequence` walks the pool in order; `shuffle` deals it in a seeded order per cycle. @default 'sequence' */\n  order?: 'sequence' | 'shuffle';\n  /** Changes the shuffled order. @default 'daily' */\n  seed?: string;\n}\n\n/**\n * Which item of a pool of `size` the day gets, or -1 for an empty pool or a\n * day before `firstDay`.\n */\nexport function dailyIndex(key: DayKey, size: number, options: DailyIndexOptions): number {\n  const n = puzzleNumber(key, options.firstDay);\n  if (size <= 0 || n < 1) return -1;\n  const position = (n - 1) % size;\n  if ((options.order ?? 'sequence') === 'sequence') return position;\n  const cycle = Math.floor((n - 1) / size);\n  const order = seededShuffle(\n    Array.from({ length: size }, (_, i) => i),\n    `${options.seed ?? 'daily'}:${cycle}`,\n  );\n  return order[position] as number;\n}\n\n/** The day's item from `pool`, or undefined when there is none. */\nexport function dailyItem<T>(pool: readonly T[], key: DayKey, options: DailyIndexOptions): T | undefined {\n  const i = dailyIndex(key, pool.length, options);\n  return i < 0 ? undefined : pool[i];\n}\n\n/**\n * Milliseconds until the next day starts in `timeZone`. On a day that a\n * clock change makes 23 or 25 hours long the answer can be off by that hour,\n * which is fine for a countdown and is why it is not used to pick puzzles.\n */\nexport function msUntilNextDay(now: Date | number = Date.now(), timeZone?: string): number {\n  const date = typeof now === 'number' ? new Date(now) : now;\n  const parts = new Intl.DateTimeFormat('en-US', {\n    timeZone,\n    hour: '2-digit',\n    minute: '2-digit',\n    second: '2-digit',\n    hourCycle: 'h23',\n  }).formatToParts(date);\n  const part = Object.fromEntries(parts.map((p) => [p.type, Number(p.value)]));\n  const elapsed =\n    ((part.hour! * 60 + part.minute!) * 60 + part.second!) * 1000 + date.getMilliseconds();\n  return DAY_MS - elapsed;\n}\n\n/**\n * @interlace/ui — games/daily\n *\n * The calendar under a daily game: which day it is for a player, which\n * puzzle that day gets, its number, and how long until the next one. Pure\n * functions, no React, no storage. Every component in `games/` builds on\n * these, and a server can call them too, so the puzzle a page renders and\n * the one a score is checked against come from the same arithmetic.\n *\n * ## Day keys\n *\n * A day is an ISO date string, `\"2026-11-24\"`, read in a time zone. Keys\n * sort as strings, survive JSON and storage unchanged, and compare without\n * a Date. Arithmetic on them runs in UTC, where every day has 24 hours, so\n * daylight-saving changes never skip or repeat a day.\n *\n * ## The puzzle of the day\n *\n * `dailyIndex` maps a day to an item in a pool. `order: 'sequence'` walks\n * the pool in order and starts again at the end. `order: 'shuffle'` deals\n * the pool in a seeded order that changes every cycle, and never repeats an\n * item inside a cycle. Both are deterministic: the same day, pool size and\n * seed give the same item on every device.\n */\n\n/** An ISO calendar date, `YYYY-MM-DD`. */\n"
    },
    {
      "path": "registry/interlace-ui/games/order-model.ts",
      "target": "components/ui/games/order-model.ts",
      "type": "registry:ui",
      "content": "import { seededShuffle } from '@/components/ui/games/daily';\n\n/**\n * @interlace/ui — games/order-model\n *\n * Dealing and scoring for a put-them-in-order round: dates on a timeline,\n * sizes, rankings. Pure, so a server deals and scores the same round and a\n * share card can draw one mark per place without saying the answer.\n *\n * ## Two measures\n *\n * - `inPlace`: how many items sit exactly where they belong. Easy to say\n *   (\"3 of 5 in the right place\") and what the marks show.\n * - `pairs`: the share of all pairs the player put in the right relative\n *   order (1 − normalised Kendall distance). It is fairer than `inPlace`:\n *   one item dragged from the top to the bottom shifts every other item by\n *   one and zeroes `inPlace`, yet most pairs are still right. Points follow\n *   `pairs`.\n */\n\nexport interface OrderScoreOptions {\n  /** Points for a perfect order. @default 100 */\n  maxPoints?: number;\n}\n\nexport interface OrderResult {\n  /** The player's order, as ids. */\n  order: string[];\n  /** The right order, as ids. */\n  correct: string[];\n  /** One flag per place in the player's order: is that item in its right place? */\n  places: boolean[];\n  /** Items in their right place. */\n  inPlace: number;\n  /** Share of pairs in the right relative order, 0–1. */\n  pairs: number;\n  points: number;\n  perfect: boolean;\n}\n\n// ponytail: the pair score is O(n^2); 500 items is 125k pairs, far past any real round.\nconst MAX_ITEMS = 500;\n\nfunction assertSameItems(order: readonly string[], correct: readonly string[]) {\n  if (!Array.isArray(order) || !Array.isArray(correct)) throw new RangeError('order and correct must be arrays');\n  if (order.length > MAX_ITEMS || correct.length > MAX_ITEMS) throw new RangeError(`at most ${MAX_ITEMS} items`);\n  const a = [...order].sort();\n  const b = [...correct].sort();\n  if (new Set(correct).size !== correct.length) throw new RangeError('ids must be unique');\n  if (a.length !== b.length || a.some((id, i) => id !== b[i])) {\n    throw new RangeError('order must hold exactly the same ids as correct');\n  }\n}\n\n/** Score the player's order against the right one. */\nexport function scoreOrder(order: readonly string[], correct: readonly string[], options: OrderScoreOptions = {}): OrderResult {\n  assertSameItems(order, correct);\n  const maxPoints = Number.isFinite(options.maxPoints) ? (options.maxPoints as number) : 100;\n  const rank = new Map(correct.map((id, i) => [id, i]));\n  const places = order.map((id, i) => rank.get(id) === i);\n  const n = order.length;\n  let good = 0;\n  let all = 0;\n  for (let i = 0; i < n; i++) {\n    for (let j = i + 1; j < n; j++) {\n      all += 1;\n      if ((rank.get(order[i] as string) as number) < (rank.get(order[j] as string) as number)) good += 1;\n    }\n  }\n  const pairs = all === 0 ? 1 : good / all;\n  const inPlace = places.filter(Boolean).length;\n  return {\n    order: [...order],\n    correct: [...correct],\n    places,\n    inPlace,\n    pairs,\n    points: Math.round(maxPoints * pairs),\n    perfect: inPlace === n,\n  };\n}\n\n/**\n * A starting order for the round: seeded, so every player gets the same deal\n * on the same day, and never already solved (a round of two or more items\n * always starts with at least one item out of place).\n */\nexport function dealOrder(correct: readonly string[], seed: number | string): string[] {\n  if (!Array.isArray(correct)) return [];\n  if (correct.length < 2) return [...correct];\n  const out = seededShuffle(correct, seed);\n  if (out.every((id, i) => id === correct[i])) out.push(out.shift() as string);\n  return out;\n}\n\n/** `order` with the item at `from` moved to `to` (both clamped). */\nexport function moveItem<T>(order: readonly T[], from: number, to: number): T[] {\n  const out = order.slice();\n  if (Number.isNaN(from) || Number.isNaN(to)) return out;\n  if (from < 0 || from >= out.length) return out;\n  const target = Math.min(out.length - 1, Math.max(0, to));\n  const [item] = out.splice(from, 1);\n  out.splice(target, 0, item as T);\n  return out;\n}\n"
    },
    {
      "path": "registry/interlace-ui/games/ranking-model.ts",
      "target": "components/ui/games/ranking-model.ts",
      "type": "registry:ui",
      "content": "import { scoreOrder } from '@/components/ui/games/order-model';\n\n/**\n * @interlace/ui — ranking-model\n *\n * A room ranks the same items by preference (\"what would you want to see\n * first?\"), with no right answer. `tallyRankings` turns everyone's order\n * into the room's: each item gets points by place (a Borda count: last\n * place 0, first place n − 1), its average place, and how many put it\n * first. `roomAgreement` says how much people agree with the room's order,\n * from 0 (the opposite) to 1 (the same), as the share of pairs in the same\n * order (see `scoreOrder` in `order-model`).\n *\n * A ranking that is not exactly the items, once each, is left out, so a bad\n * message cannot skew the room; each person counts once.\n */\n\nexport interface RankedItem {\n  id: string;\n  /** Borda points, summed over people. */\n  points: number;\n  /** Average place, 1 for first; null while nobody has ranked. */\n  meanPlace: number | null;\n  /** People who put it first. */\n  firsts: number;\n}\n\n/** True when `order` holds every item exactly once. */\nexport function isFullRanking(order: readonly string[], items: readonly string[]): boolean {\n  // A string or array-like is not a ranking: only a real array counts.\n  if (!Array.isArray(order)) return false;\n  const ids = [...new Set(items)];\n  if (order.length !== ids.length) return false;\n  const set = new Set(order);\n  return ids.every((id) => set.has(id));\n}\n\n/**\n * The room's order, most preferred first. Ties go to more first places,\n * then to the items' given order. `meanPlace` is null while nobody has ranked.\n */\nexport function tallyRankings(\n  rankings: Readonly<Record<string, readonly string[]>>,\n  listed: readonly string[],\n): { items: RankedItem[]; people: number } {\n  // An id listed twice is one item: counting it twice would drop every ranking.\n  const items = [...new Set(listed)];\n  const n = items.length;\n  const rows = new Map(items.map((id, i) => [id, { id, i, points: 0, places: 0, firsts: 0 }]));\n  let people = 0;\n  for (const order of Object.values(rankings)) {\n    if (!isFullRanking(order, items)) continue;\n    people++;\n    order.forEach((id, place) => {\n      const row = rows.get(id) as { points: number; places: number; firsts: number };\n      row.points += n - 1 - place;\n      row.places += place + 1;\n      if (place === 0) row.firsts++;\n    });\n  }\n  const ranked = [...rows.values()]\n    .sort((a, b) => b.points - a.points || b.firsts - a.firsts || a.i - b.i)\n    .map(({ id, points, places, firsts }) => ({\n      id,\n      points,\n      firsts,\n      meanPlace: people === 0 ? null : places / people,\n    }));\n  return { items: ranked, people };\n}\n\n/** How much the room agrees with its own order, 0 to 1; null with nobody. */\nexport function roomAgreement(\n  rankings: Readonly<Record<string, readonly string[]>>,\n  items: readonly string[],\n): number | null {\n  const valid = Object.values(rankings).filter((o) => isFullRanking(o, items));\n  if (valid.length === 0) return null;\n  const room = tallyRankings(rankings, items).items.map((r) => r.id);\n  return valid.reduce((sum, o) => sum + scoreOrder(o, room).pairs, 0) / valid.length;\n}\n"
    }
  ],
  "meta": {
    "tier": "game",
    "client": true,
    "minViewport": 320,
    "loading": false,
    "version": "1.2.0",
    "since": "2.0.0"
  },
  "docs": "## @interlace/ranking\n\nInstalled to `components/ui/games/ranking.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/games/ranking';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/ranking\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
