{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "order-game",
  "type": "registry:ui",
  "title": "Order Game",
  "description": "Put a handful of items in order: events from earliest to latest, places from smallest to largest. The player drags rows by their handle, or moves them with the arrow keys or the up and down buttons, then locks in. The rows then glide into the right order…",
  "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/motion-token.json",
    "https://ds.interlace.tools/r/use-reduced-motion.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/games/order-game.tsx",
      "target": "components/ui/games/order-game.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/order-game v1.2.0 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/order-game\n// What changed since: https://ds.interlace.tools/c/order-game#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — OrderGame\n *\n * Put a handful of items in order: events from earliest to latest, places\n * from smallest to largest. The player drags rows by their handle, or moves\n * them with the arrow keys or the up and down buttons, then locks in. The\n * rows then glide into the right order, each one showing its value and\n * whether the player had it in the right place. Dealing and scoring live in\n * `order-model.ts` and are exported, so a server deals and scores the same\n * round.\n *\n * ## Anatomy\n *\n *   OrderGame                        (div — data-slot=\"order-game\", data-state=ordering|revealed)\n *     ├─ p                           (data-slot=\"order-game-question\", id ← the list's label)\n *     ├─ span                        (data-slot=\"order-game-end\": the first end, e.g. \"Earliest\")\n *     ├─ ol                          (data-slot=\"order-game-list\")\n *     │   └─ li × n                  (data-slot=\"order-game-item\", data-dragging, data-place=right|wrong)\n *     │       ├─ button              (data-slot=\"order-game-handle\": drag, or arrow keys)\n *     │       ├─ span                (label, then the value after the reveal)\n *     │       └─ Button × 2          (data-slot=\"order-game-move\": up / down)\n *     ├─ span                        (data-slot=\"order-game-end\": the last end, e.g. \"Latest\")\n *     ├─ form                        (data-slot=\"order-game-form\": Lock in)\n *     ├─ p tabIndex=-1 aria-live     (data-slot=\"order-game-result\")\n *     ├─ span sr-only aria-live      (data-slot=\"order-game-announce\": \"Moved X to place 2 of 5\")\n *     └─ div                         (data-slot=\"order-game-explanation\": opens on reveal)\n *\n * ## Moving without dragging\n *\n * Dragging is never the only way (WCAG 2.5.7). Every row has up and down\n * buttons, and its handle moves it with the arrow keys (Home and End send it\n * to either end). Each move is announced with the item's new place.\n *\n * ## Controlled or not\n *\n * `items` come in the right order; the round starts from `dealOrder(…,\n * seed)`, so every player gets the same deal. `result` / `defaultResult`\n * restore a locked-in round as the revealed state. `onSubmit` fires once,\n * with the scored result.\n *\n * ## Motion\n *\n * A dragged row follows the pointer; the others make room by sliding\n * (150ms, `--ease-move`). On the reveal every row travels to its right\n * place (400ms). Rows are moved with transforms measured before and after\n * the change, so layout never jumps. Under reduced motion rows are simply\n * in their new places; a dragged row still follows the pointer, since that\n * is the player's own hand.\n *\n * ## MIN_VIEWPORT — 320\n *\n * | Rule | Concept                   | Where in this file                                    |\n * | ---- | ------------------------- | ----------------------------------------------------- |\n * | R4   | Extends native el         | `React.ComponentProps<'div'>`                         |\n * | R6   | data-slot per part        | order-game / -question / -end / -list / -item / -handle / -move / -form / -result / -announce / -explanation |\n * | R7   | cn + ...rest              | `cn(…, className)` + `{...props}`                     |\n * | R9   | Controlled + uncontrolled | `result` / `defaultResult` / `onSubmit`               |\n * | R14  | Declares min viewport     | `data-min-viewport` + exported const                  |\n * | R26  | A11y                      | buttons and keys for every move; moves announced; places in words |\n */\n\nimport { ArrowDown, ArrowUp, Check, GripVertical, X } from 'lucide-react';\n\nimport { cn } from '@/lib/utils';\nimport { useReducedMotion } from '@/hooks/use-reduced-motion';\nimport { motionDuration, motionEase } from '@/lib/motion-token';\nimport { Button } from '@/components/ui/button';\nimport { dealOrder, moveItem, scoreOrder, type OrderResult, type OrderScoreOptions } from '@/components/ui/games/order-model';\n\nexport const MIN_VIEWPORT = 320 as const;\n\ninterface OrderItem {\n  id: string;\n  label: React.ReactNode;\n  /** Plain text for announcements, when `label` is not a string. */\n  text?: string;\n  /** Shown after the reveal: the value the order is by (a year, a size). */\n  value?: React.ReactNode;\n}\n\ninterface OrderGameLabels {\n  /** The lock-in button. @default 'Lock in' */\n  submit?: string;\n  /** The handle's name. @default (item) => `Reorder ${item}` */\n  handle?: (item: string) => string;\n  /** How to use the handle. @default 'Drag, or use the arrow keys.' */\n  handleHint?: string;\n  /** @default (item) => `Move ${item} up` */\n  up?: (item: string) => string;\n  /** @default (item) => `Move ${item} down` */\n  down?: (item: string) => string;\n  /** Announced after a move. @default (item, place, total) => `${item}, place ${place} of ${total}` */\n  moved?: (item: string, place: number, total: number) => string;\n  /** After the reveal, on a row in the right place. @default 'Right place' */\n  right?: string;\n  /** After the reveal, on a row that was elsewhere. @default (place) => `You had it ${ordinal(place)}` */\n  had?: (place: number) => string;\n  /** The result sentence. */\n  result?: (r: { inPlace: number; total: number; points: number; perfect: boolean }) => string;\n}\n\ntype OrderGameProps = Omit<React.ComponentProps<'div'>, 'children' | 'onSubmit'> & {\n  question: React.ReactNode;\n  /** The items, in the RIGHT order. The round is dealt from them. */\n  items: readonly OrderItem[];\n  /** Seeds the deal, so every player starts from the same order. @default the ids joined */\n  seed?: number | string;\n  /** Words at the two ends of the list, e.g. `['Earliest', 'Latest']`. */\n  ends?: readonly [React.ReactNode, React.ReactNode];\n  /** The scored round, controlled. null for none yet. */\n  result?: OrderResult | null;\n  /** The scored round, uncontrolled. */\n  defaultResult?: OrderResult | null;\n  /** Called once, on lock-in. */\n  onSubmit?: (result: OrderResult) => void;\n  /** Shown after the reveal. */\n  explanation?: React.ReactNode;\n  score?: OrderScoreOptions;\n  labels?: OrderGameLabels;\n};\n\nconst RESULT: NonNullable<OrderGameLabels['result']> = ({ inPlace, total, points, perfect }) =>\n  perfect ? `All ${total} in the right place. ${points} points.` : `${inPlace} of ${total} in the right place. ${points} points.`;\n\nconst textOf = (i: OrderItem) =>\n  i.text ?? (typeof i.label === 'string' || typeof i.label === 'number' ? String(i.label) : i.id);\n\n/** Measure each row's top, keyed by id, to animate from after the order changes. */\nfunction useFlip(listRef: React.RefObject<HTMLOListElement | null>, order: readonly string[], reduced: boolean) {\n  const before = React.useRef<Map<string, number> | null>(null);\n  const duration = React.useRef(150);\n  const skip = React.useRef<string | null>(null);\n\n  const capture = React.useCallback(\n    (ms = 150, skipId: string | null = null) => {\n      const list = listRef.current;\n      if (!list) return;\n      duration.current = ms;\n      skip.current = skipId;\n      before.current = new Map(\n        Array.from(list.querySelectorAll<HTMLElement>('[data-slot=\"order-game-item\"]')).map((el) => [\n          el.dataset.id as string,\n          el.getBoundingClientRect().top,\n        ]),\n      );\n    },\n    [listRef],\n  );\n\n  React.useLayoutEffect(() => {\n    const prev = before.current;\n    before.current = null;\n    const list = listRef.current;\n    if (!prev || !list || reduced) return;\n    list.querySelectorAll<HTMLElement>('[data-slot=\"order-game-item\"]').forEach((el) => {\n      const id = el.dataset.id as string;\n      if (id === skip.current) return;\n      const from = prev.get(id);\n      if (from === undefined || typeof el.animate !== 'function') return;\n      const dy = from - el.getBoundingClientRect().top;\n      if (Math.abs(dy) < 1) return;\n      el.animate([{ transform: `translateY(${dy}px)` }, { transform: 'none' }], {\n        duration: duration.current,\n        easing: motionEase(el, 'move'),\n      });\n    });\n  }, [order, listRef, reduced]);\n\n  return capture;\n}\n\nconst ORDINAL = (n: number) => {\n  const s = ['th', 'st', 'nd', 'rd'];\n  const v = n % 100;\n  return `${n}${s[(v - 20) % 10] ?? s[v] ?? s[0]}`;\n};\n\nfunction OrderGame({\n  question,\n  items,\n  seed,\n  ends,\n  result: resultProp,\n  defaultResult = null,\n  onSubmit,\n  explanation,\n  score,\n  labels,\n  className,\n  ...props\n}: OrderGameProps) {\n  const correct = React.useMemo(() => items.map((i) => i.id), [items]);\n  const byId = React.useMemo(() => new Map(items.map((i) => [i.id, i])), [items]);\n  const [draft, setDraft] = React.useState<string[]>(() => dealOrder(correct, seed ?? correct.join('|')));\n  const [uncontrolled, setUncontrolled] = React.useState<OrderResult | null>(defaultResult);\n  const result = resultProp === undefined ? uncontrolled : resultProp;\n  const revealed = result !== null && result !== undefined;\n  const order = revealed ? result.correct : draft;\n  const reduced = useReducedMotion();\n  const listRef = React.useRef<HTMLOListElement>(null);\n  const resultRef = React.useRef<HTMLParagraphElement>(null);\n  const formRef = React.useRef<HTMLFormElement>(null);\n  const [announce, setAnnounce] = React.useState('');\n  const [dragging, setDragging] = React.useState<string | null>(null);\n  const drag = React.useRef<{ id: string; startY: number; startTop: number; pointer: number; top: number } | null>(null);\n  const sent = React.useRef(revealed);\n  const moveFocus = React.useRef(false);\n  const focusAfter = React.useRef<{ id: string; slot: string } | null>(null);\n  const questionId = React.useId();\n  const hintId = React.useId();\n  const explanationId = React.useId();\n  const capture = useFlip(listRef, order, reduced);\n  const rowOf = (id: string) =>\n    Array.from(listRef.current?.querySelectorAll<HTMLElement>('[data-slot=\"order-game-item\"]') ?? []).find(\n      (el) => el.dataset.id === id,\n    );\n\n  React.useEffect(() => {\n    if (!revealed) sent.current = false;\n  }, [revealed]);\n\n  const words = {\n    handle: labels?.handle ?? ((t: string) => `Reorder ${t}`),\n    up: labels?.up ?? ((t: string) => `Move ${t} up`),\n    down: labels?.down ?? ((t: string) => `Move ${t} down`),\n    moved: labels?.moved ?? ((t: string, p: number, n: number) => `${t}, place ${p} of ${n}`),\n    had: labels?.had ?? ((p: number) => `You had it ${ORDINAL(p)}`),\n  };\n\n  const move = (id: string, to: number, slot?: string) => {\n    if (revealed) return;\n    const from = draft.indexOf(id);\n    const target = Math.min(draft.length - 1, Math.max(0, to));\n    if (from < 0 || from === target) return;\n    capture(150);\n    setDraft(moveItem(draft, from, target));\n    if (slot) focusAfter.current = { id, slot };\n    const item = byId.get(id);\n    if (item) setAnnounce(words.moved(textOf(item), target + 1, draft.length));\n  };\n\n  // Keep focus on the control that moved a row: React re-orders the nodes, and a\n  // button that reaches an end is disabled, so focus is put back where it belongs.\n  React.useEffect(() => {\n    const f = focusAfter.current;\n    focusAfter.current = null;\n    if (!f) return;\n    const row = rowOf(f.id);\n    let el = row?.querySelector<HTMLButtonElement>(`[data-control=\"${f.slot}\"]`);\n    if (el?.disabled) el = row?.querySelector<HTMLButtonElement>('[data-control=\"handle\"]');\n    if (el && document.activeElement !== el) el.focus();\n  }, [draft]);\n\n  React.useEffect(() => {\n    if (!revealed || !moveFocus.current) return;\n    moveFocus.current = false;\n    resultRef.current?.focus();\n  }, [revealed]);\n\n  const submit = () => {\n    if (revealed || sent.current) return;\n    sent.current = true;\n    moveFocus.current = !!formRef.current?.contains(document.activeElement);\n    const scored = scoreOrder(draft, correct, score);\n    capture(400);\n    if (resultProp === undefined) setUncontrolled(scored);\n    onSubmit?.(scored);\n  };\n\n  // ── Dragging: the row follows the pointer; others make room as it crosses their middles.\n  const onPointerDown = (id: string) => (e: React.PointerEvent<HTMLButtonElement>) => {\n    if (revealed || e.button > 0) return;\n    const row = (e.currentTarget as HTMLElement).closest<HTMLElement>('[data-slot=\"order-game-item\"]');\n    if (!row) return;\n    e.preventDefault();\n    e.currentTarget.setPointerCapture?.(e.pointerId);\n    drag.current = { id, startY: e.clientY, startTop: row.offsetTop, pointer: e.pointerId, top: row.offsetTop };\n    setDragging(id);\n  };\n\n  const onPointerMove = (e: React.PointerEvent<HTMLButtonElement>) => {\n    const d = drag.current;\n    const list = listRef.current;\n    if (!d || !list || e.pointerId !== d.pointer) return;\n    const rows = Array.from(list.querySelectorAll<HTMLElement>('[data-slot=\"order-game-item\"]'));\n    const row = rows.find((r) => r.dataset.id === d.id);\n    if (!row) return;\n    const top = d.startTop + (e.clientY - d.startY);\n    const centre = top + row.offsetHeight / 2;\n    // The slot whose middle the dragged row's centre has passed.\n    let target = 0;\n    for (const other of rows) {\n      if (other === row) continue;\n      if (centre > other.offsetTop + other.offsetHeight / 2) target += 1;\n    }\n    d.top = top;\n    const from = draft.indexOf(d.id);\n    if (target !== from) {\n      // The row's new slot is laid out first; the layout effect below then places it under the pointer.\n      capture(150, d.id);\n      setDraft(moveItem(draft, from, target));\n    } else {\n      row.style.transform = `translateY(${top - row.offsetTop}px)`;\n    }\n  };\n\n  // Keep a dragged row under the pointer after the list re-orders (offsetTop ignores transforms).\n  React.useLayoutEffect(() => {\n    const d = drag.current;\n    if (!d) return;\n    const row = rowOf(d.id);\n    if (row) row.style.transform = `translateY(${d.top - row.offsetTop}px)`;\n  }, [draft]);\n\n  const endDrag = (e: React.PointerEvent<HTMLButtonElement>) => {\n    const d = drag.current;\n    if (!d || e.pointerId !== d.pointer) return;\n    drag.current = null;\n    setDragging(null);\n    const row = rowOf(d.id);\n    if (!row) return;\n    const current = row.style.transform;\n    row.style.transform = '';\n    if (!reduced && current && typeof row.animate === 'function') {\n      row.animate([{ transform: current }, { transform: 'none' }], { duration: motionDuration(row, 'base'), easing: motionEase(row, 'enter') });\n    }\n    const item = byId.get(d.id);\n    if (item) setAnnounce(words.moved(textOf(item), draft.indexOf(d.id) + 1, draft.length));\n  };\n\n  const onHandleKey = (id: string) => (e: React.KeyboardEvent<HTMLButtonElement>) => {\n    const at = draft.indexOf(id);\n    const to =\n      e.key === 'ArrowUp' ? at - 1 : e.key === 'ArrowDown' ? at + 1 : e.key === 'Home' ? 0 : e.key === 'End' ? draft.length - 1 : null;\n    if (to === null) return;\n    e.preventDefault();\n    move(id, to, 'handle');\n  };\n\n  const placeHad = (id: string) => (revealed ? result.order.indexOf(id) + 1 : 0);\n\n  return (\n    <div\n      data-slot=\"order-game\"\n      data-state={revealed ? 'revealed' : 'ordering'}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('grid gap-3', className)}\n      {...props}\n    >\n      <p id={questionId} data-slot=\"order-game-question\" className=\"font-heading text-lg font-semibold text-balance\">\n        {question}\n      </p>\n      <span id={hintId} className=\"sr-only\">\n        {labels?.handleHint ?? 'Drag, or use the arrow keys.'}\n      </span>\n\n      {ends ? (\n        <span data-slot=\"order-game-end\" className=\"text-muted-foreground text-xs font-semibold\">\n          {ends[0]}\n        </span>\n      ) : null}\n\n      <ol ref={listRef} aria-labelledby={questionId} data-slot=\"order-game-list\" className=\"grid gap-2\">\n        {order.map((id, index) => {\n          const item = byId.get(id);\n          if (!item) return null;\n          const t = textOf(item);\n          const had = placeHad(id);\n          const right = revealed && had === index + 1;\n          return (\n            <li\n              key={id}\n              data-id={id}\n              data-slot=\"order-game-item\"\n              data-dragging={dragging === id ? '' : undefined}\n              data-place={revealed ? (right ? 'right' : 'wrong') : undefined}\n              className={cn(\n                'bg-card text-card-foreground relative flex min-h-12 items-center gap-2 rounded-lg border py-1.5 ps-1.5 pe-1.5',\n                dragging === id && 'border-primary z-raised shadow-lg',\n                revealed && (right ? 'border-success' : 'border-border'),\n              )}\n            >\n              {!revealed ? (\n                <button\n                  type=\"button\"\n                  data-slot=\"order-game-handle\"\n                  data-control=\"handle\"\n                  aria-label={words.handle(t)}\n                  aria-describedby={hintId}\n                  onPointerDown={onPointerDown(id)}\n                  onPointerMove={onPointerMove}\n                  onPointerUp={endDrag}\n                  onPointerCancel={endDrag}\n                  onKeyDown={onHandleKey(id)}\n                  className={cn(\n                    'text-muted-foreground hover:text-foreground grid size-11 shrink-0 touch-none place-items-center rounded-md',\n                    'focus-visible:outline-ring outline-offset-2 focus-visible:outline-2',\n                    dragging === id ? 'cursor-grabbing' : 'cursor-grab',\n                  )}\n                >\n                  <GripVertical aria-hidden className=\"size-5\" />\n                </button>\n              ) : (\n                <span\n                  aria-hidden\n                  className={cn(\n                    'grid size-11 shrink-0 place-items-center',\n                    right ? 'text-success' : 'text-muted-foreground',\n                  )}\n                >\n                  {right ? <Check className=\"size-5\" strokeWidth={3} /> : <X className=\"size-5\" strokeWidth={2.5} />}\n                </span>\n              )}\n\n              <span className=\"min-w-0 flex-1 py-1\">\n                <span className=\"block font-medium\">{item.label}</span>\n                {revealed ? (\n                  <span className=\"text-muted-foreground flex flex-wrap gap-x-3 text-sm\">\n                    {item.value !== undefined ? <span className=\"text-foreground font-semibold tabular-nums\">{item.value}</span> : null}\n                    <span className={cn(right && 'text-success font-semibold')}>\n                      {right ? (labels?.right ?? 'Right place') : words.had(had)}\n                    </span>\n                  </span>\n                ) : null}\n              </span>\n\n              {!revealed ? (\n                <span className=\"flex shrink-0 gap-1\">\n                  <Button\n                    type=\"button\"\n                    variant=\"ghost\"\n                    size=\"icon\"\n                    data-slot=\"order-game-move\"\n                    data-control=\"up\"\n                    aria-label={words.up(t)}\n                    disabled={index === 0}\n                    onClick={() => move(id, index - 1, 'up')}\n                  >\n                    <ArrowUp aria-hidden />\n                  </Button>\n                  <Button\n                    type=\"button\"\n                    variant=\"ghost\"\n                    size=\"icon\"\n                    data-slot=\"order-game-move\"\n                    data-control=\"down\"\n                    aria-label={words.down(t)}\n                    disabled={index === order.length - 1}\n                    onClick={() => move(id, index + 1, 'down')}\n                  >\n                    <ArrowDown aria-hidden />\n                  </Button>\n                </span>\n              ) : null}\n            </li>\n          );\n        })}\n      </ol>\n\n      {ends ? (\n        <span data-slot=\"order-game-end\" className=\"text-muted-foreground text-xs font-semibold\">\n          {ends[1]}\n        </span>\n      ) : null}\n\n      {!revealed ? (\n        <form\n          ref={formRef}\n          data-slot=\"order-game-form\"\n          className=\"flex justify-end pt-1\"\n          onSubmit={(e) => {\n            e.preventDefault();\n            submit();\n          }}\n        >\n          <Button type=\"submit\">{labels?.submit ?? 'Lock in'}</Button>\n        </form>\n      ) : null}\n\n      <p\n        ref={resultRef}\n        tabIndex={-1}\n        data-slot=\"order-game-result\"\n        aria-live=\"polite\"\n        aria-describedby={revealed && explanation ? explanationId : undefined}\n        className=\"focus-visible:outline-ring rounded-sm text-sm font-semibold outline-offset-4 empty:hidden focus-visible:outline-2\"\n      >\n        {revealed\n          ? (labels?.result ?? RESULT)({\n              inPlace: result.inPlace,\n              total: result.order.length,\n              points: result.points,\n              perfect: result.perfect,\n            })\n          : ''}\n      </p>\n\n      <span data-slot=\"order-game-announce\" aria-live=\"assertive\" className=\"sr-only\">\n        {announce}\n      </span>\n\n      {explanation ? (\n        <div\n          data-slot=\"order-game-explanation\"\n          className={cn(\n            'grid',\n            'motion-safe:transition-[grid-template-rows,opacity] motion-safe:duration-(--duration-medium) motion-safe:ease-enter',\n            revealed ? 'grid-rows-[1fr] opacity-100' : 'grid-rows-[0fr] opacity-0',\n          )}\n          inert={revealed ? undefined : true}\n        >\n          <div id={explanationId} className=\"text-muted-foreground -m-1 min-h-0 overflow-hidden p-1 text-sm leading-relaxed\">\n            {explanation}\n          </div>\n        </div>\n      ) : null}\n    </div>\n  );\n}\nOrderGame.displayName = 'OrderGame';\n\nexport { OrderGame };\nexport type { OrderGameProps, OrderItem, OrderGameLabels };\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"
    }
  ],
  "meta": {
    "tier": "game",
    "client": true,
    "minViewport": 320,
    "loading": false,
    "version": "1.2.0",
    "since": "2.0.0"
  },
  "docs": "## @interlace/order-game\n\nInstalled to `components/ui/games/order-game.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/games/order-game';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/order-game\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
