{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "milestones",
  "type": "registry:ui",
  "title": "Milestones",
  "description": "The marks along a path a player is on (a 3, 7 and 30-day streak; levels 5, 10 and 20): the ones reached, the next one with how far is left, and a few beyond. It shows where the player is going, not a wall of locked trophies, so only a window around 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/cn.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/games/milestones.tsx",
      "target": "components/ui/games/milestones.tsx",
      "type": "registry:ui",
      "content": "import * as React from 'react';\n\n// @interlace/milestones v1.1.0 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/milestones\n// What changed since: https://ds.interlace.tools/c/milestones#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — Milestones\n *\n * The marks along a path a player is on (a 3, 7 and 30-day streak; levels\n * 5, 10 and 20): the ones reached, the next one with how far is left, and\n * a few beyond. It shows where the player is going, not a wall of locked\n * trophies, so only a window around the next mark is drawn.\n *\n * ## Anatomy\n *\n *   Milestones                     (div — data-slot=\"milestones\")\n *     ├─ ol                        (data-slot=\"milestones-list\", labelled)\n *     │   └─ li × n                (data-slot=\"milestone\", data-state=reached|next|ahead)\n *     │       ├─ span aria-hidden  (data-slot=\"milestone-mark\": the step, an award when reached)\n *     │       └─ span              (data-slot=\"milestone-label\")\n *     └─ p                         (data-slot=\"milestones-next\": \"3 more days to 7 days\")\n *\n * ## Never colour alone\n *\n * Reached is a filled mark with an award icon, next a ring in the accent\n * with a dot, ahead a dashed ring. Each item also says its state in words\n * for assistive tech.\n *\n * ## Motion\n *\n * The latest reached mark scales in once (CSS `@starting-style`,\n * `motion-safe:` only). Renders on the server.\n *\n * ## MIN_VIEWPORT — 320\n *\n * Five marks fit a 288px column; the row wraps beyond that.\n *\n * | Rule | Concept                   | Where in this file                                   |\n * | ---- | ------------------------- | ---------------------------------------------------- |\n * | R4   | Extends native el         | `React.ComponentProps<'div'>`                        |\n * | R6   | data-slot per part        | milestones / -list / milestone / -mark / -label / -next |\n * | R7   | cn + ...rest              | `cn(…, className)` + `{...props}`                    |\n * | R14  | Declares min viewport     | `data-min-viewport` + exported const                 |\n * | R19  | Tokens only               | primary, input, muted-foreground                     |\n * | R26  | A11y                      | labelled list; every state in words                  |\n */\n\nimport { Award } from 'lucide-react';\n\nimport { cn } from '@/lib/utils';\nimport { nextMilestone } from '@/components/ui/games/progress-model';\n\nexport const MIN_VIEWPORT = 320 as const;\n\nexport type MilestoneState = 'reached' | 'next' | 'ahead';\n\ninterface MilestonesLabels {\n  /** Names the list. @default 'Milestones' */\n  list?: string;\n  /** One step, as words: \"7 days\". @default n => n */\n  step?: (step: number, formatted: string) => string;\n  /** The line under the list. @default (left, step) => `${left} more to ${step}` */\n  next?: (left: string, step: string) => string;\n  /** When every step is reached. @default 'Every milestone reached.' */\n  done?: string;\n  /** Each state, read after the step. */\n  state?: Partial<Record<MilestoneState, string>>;\n}\n\ntype MilestonesProps = Omit<React.ComponentProps<'div'>, 'children'> & {\n  /** Where the player is: a streak length, a level. */\n  value: number;\n  /** The steps, any order. */\n  steps: readonly number[];\n  /** How many reached steps to keep in view. @default 2 */\n  behind?: number;\n  /** How many steps to show in all. @default 5 */\n  show?: number;\n  /** BCP 47 locale for the numbers. */\n  locale?: string;\n  labels?: MilestonesLabels;\n};\n\nconst STATE: Record<MilestoneState, string> = { reached: 'reached', next: 'next', ahead: 'ahead' };\n\nconst MARK =\n  'grid size-10 shrink-0 place-items-center rounded-full text-sm font-semibold tabular-nums [&_svg]:size-4';\n\n/** The window of steps to draw: a few reached, the next, and some ahead. */\nexport function milestoneWindow(value: number, steps: readonly number[], behind = 2, show = 5): number[] {\n  const sorted = [...new Set(steps)].sort((a, b) => a - b);\n  const firstAhead = sorted.findIndex((s) => s > value);\n  const pivot = firstAhead === -1 ? sorted.length : firstAhead;\n  const count = Math.max(1, show);\n  let start = Math.max(0, pivot - Math.max(0, behind));\n  start = Math.max(0, Math.min(start, sorted.length - count));\n  return sorted.slice(start, start + count);\n}\n\nfunction Milestones({\n  value,\n  steps,\n  behind = 2,\n  show = 5,\n  locale,\n  labels,\n  className,\n  ...props\n}: MilestonesProps) {\n  const nf = new Intl.NumberFormat(locale);\n  const shown = milestoneWindow(value, steps, behind, show);\n  const next = nextMilestone(value, steps);\n  const lastReached = [...shown].reverse().find((s) => s <= value);\n  const word = (s: number) => (labels?.step ?? ((_n: number, f: string) => f))(s, nf.format(s));\n\n  return (\n    <div\n      data-slot=\"milestones\"\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('grid gap-3', className)}\n      {...props}\n    >\n      <ol\n        data-slot=\"milestones-list\"\n        aria-label={labels?.list ?? 'Milestones'}\n        className=\"flex flex-wrap gap-x-3 gap-y-2\"\n      >\n        {shown.map((s) => {\n          const state: MilestoneState = s <= value ? 'reached' : s === next ? 'next' : 'ahead';\n          return (\n            <li\n              key={s}\n              data-slot=\"milestone\"\n              data-state={state}\n              aria-current={state === 'next' ? 'step' : undefined}\n              className=\"grid w-14 justify-items-center gap-1 text-center\"\n            >\n              <span\n                aria-hidden\n                data-slot=\"milestone-mark\"\n                className={cn(\n                  MARK,\n                  state === 'reached' && 'bg-primary text-primary-foreground',\n                  state === 'next' && 'border-primary text-foreground border-2',\n                  state === 'ahead' && 'border-input text-muted-foreground border-2 border-dashed',\n                  s === lastReached &&\n                    'motion-safe:transition-[scale,opacity] motion-safe:duration-(--duration-medium) motion-safe:ease-enter motion-safe:starting:scale-75 motion-safe:starting:opacity-0',\n                )}\n              >\n                {state === 'reached' ? <Award /> : nf.format(s)}\n              </span>\n              <span\n                data-slot=\"milestone-label\"\n                className={cn('text-xs leading-tight', state === 'ahead' ? 'text-muted-foreground' : 'font-medium')}\n              >\n                {word(s)}\n                <span className=\"sr-only\">: {labels?.state?.[state] ?? STATE[state]}</span>\n              </span>\n            </li>\n          );\n        })}\n      </ol>\n      <p data-slot=\"milestones-next\" dir=\"auto\" className=\"text-muted-foreground text-sm tabular-nums\">\n        {next === undefined\n          ? (labels?.done ?? 'Every milestone reached.')\n          : (labels?.next ?? ((l: string, s: string) => `${l} more to ${s}`))(nf.format(next - value), word(next))}\n      </p>\n    </div>\n  );\n}\nMilestones.displayName = 'Milestones';\n\nexport { Milestones };\nexport type { MilestonesProps, MilestonesLabels };\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/progress-model.ts",
      "target": "components/ui/games/progress-model.ts",
      "type": "registry:ui",
      "content": "import { isDayKey, type DayKey } from '@/components/ui/games/daily';\n\n/**\n * @interlace/ui — games/progress-model\n *\n * The numbers behind a sense of progress: experience points (XP) and the\n * level they add up to, a daily goal, and milestones worth marking. Pure:\n * give it what the player earned and on which day; it returns where they\n * stand. A game decides what earns XP; this file only adds it up, so a\n * server can check the same numbers a screen shows.\n *\n * ## XP rewards showing up\n *\n * A game that pays for \"right\" teaches people to say they were right. Give\n * XP for finishing things, and keep honest self-ratings out of it.\n *\n * ## Levels\n *\n * Level 1 starts at 0 XP. Each level costs `first + step × (level − 1)` XP\n * to finish (100, 150, 200… by default), so early levels come quickly and\n * later ones stay within reach.\n *\n * ## Daily goal\n *\n * The XP a player means to earn each day. `goalOn` says how far today is;\n * `goalDays` lists the days the goal was met, which `summarizeStreak` can\n * turn into a goal streak.\n *\n * ## Milestones\n *\n * A milestone is a value worth marking (a 7-day streak, level 5).\n * `milestonesCrossed` returns the ones a change passed, so a screen\n * celebrates each once, at the moment it happens, and never on a reload.\n */\n\n/** XP earned on one day. Several entries for the same day add up. */\nexport interface XpEntry {\n  day: DayKey;\n  xp: number;\n}\n\nexport interface LevelCurve {\n  /** XP to finish level 1. @default 100 */\n  first: number;\n  /** Extra XP each later level costs. @default 50 */\n  step: number;\n}\n\nexport const DEFAULT_LEVEL_CURVE: LevelCurve = { first: 100, step: 50 };\n\nexport interface Level {\n  /** 1-based. */\n  level: number;\n  /** XP earned inside this level. */\n  into: number;\n  /** XP this level takes to finish. */\n  span: number;\n  /** `into / span`, 0 to 1. */\n  progress: number;\n  /** XP still needed for the next level. */\n  toNext: number;\n  /** All XP, the input. */\n  total: number;\n}\n\nconst clean = (xp: number) => (Number.isFinite(xp) && xp > 0 ? xp : 0);\n\nfunction curveOf(curve?: Partial<LevelCurve>): LevelCurve {\n  const first = clean(curve?.first ?? DEFAULT_LEVEL_CURVE.first) || DEFAULT_LEVEL_CURVE.first;\n  const step = clean(curve?.step ?? DEFAULT_LEVEL_CURVE.step);\n  return { first, step };\n}\n\n/** XP to finish `level` (1-based) on this curve. */\nexport function levelSpan(level: number, curve?: Partial<LevelCurve>): number {\n  const c = curveOf(curve);\n  return c.first + c.step * (Math.max(1, Math.floor(level)) - 1);\n}\n\n/** The level a total of XP reaches, and how far into it. */\nexport function levelFor(totalXp: number, curve?: Partial<LevelCurve>): Level {\n  const total = clean(totalXp);\n  let level = 1;\n  let left = total;\n  let span = levelSpan(1, curve);\n  while (left >= span) {\n    left -= span;\n    level += 1;\n    span = levelSpan(level, curve);\n  }\n  return { level, into: left, span, progress: left / span, toNext: span - left, total };\n}\n\n/** Every valid entry's XP, added up. */\nexport function totalXp(entries: Iterable<XpEntry>): number {\n  let sum = 0;\n  for (const e of entries) if (isDayKey(e.day)) sum += clean(e.xp);\n  return sum;\n}\n\n/** XP earned on one day. */\nexport function xpOn(entries: Iterable<XpEntry>, day: DayKey): number {\n  let sum = 0;\n  for (const e of entries) if (e.day === day) sum += clean(e.xp);\n  return sum;\n}\n\nexport interface GoalProgress {\n  earned: number;\n  goal: number;\n  met: boolean;\n  /** 0 to 1, capped at 1. */\n  progress: number;\n  /** XP still needed today; 0 once met. */\n  left: number;\n}\n\n/** How far a day is toward the goal. A goal of 0 or less counts as met. */\nexport function goalOn(entries: Iterable<XpEntry>, day: DayKey, goal: number): GoalProgress {\n  const earned = xpOn(entries, day);\n  const g = clean(goal);\n  if (g === 0) return { earned, goal: 0, met: true, progress: 1, left: 0 };\n  return { earned, goal: g, met: earned >= g, progress: Math.min(1, earned / g), left: Math.max(0, g - earned) };\n}\n\n/** The days the goal was met, sorted. Feed them to `summarizeStreak` for a goal streak. */\nexport function goalDays(entries: Iterable<XpEntry>, goal: number): DayKey[] {\n  const byDay = new Map<DayKey, number>();\n  for (const e of entries) if (isDayKey(e.day)) byDay.set(e.day, (byDay.get(e.day) ?? 0) + clean(e.xp));\n  const g = clean(goal);\n  return [...byDay].filter(([, xp]) => xp > 0 && xp >= g).map(([day]) => day).sort();\n}\n\n/** Streak lengths worth marking. */\nexport const DEFAULT_STREAK_MILESTONES: readonly number[] = [3, 7, 14, 30, 50, 100, 200, 365];\n\n/** The milestones a change from `before` to `after` passed, smallest first. */\nexport function milestonesCrossed(before: number, after: number, steps: readonly number[]): number[] {\n  return [...steps].filter((s) => s > before && s <= after).sort((a, b) => a - b);\n}\n\n/** The first milestone above `value`, or undefined past the last. */\nexport function nextMilestone(value: number, steps: readonly number[]): number | undefined {\n  return [...steps].sort((a, b) => a - b).find((s) => s > value);\n}\n\n/** The highest milestone reached, or undefined before the first. */\nexport function lastMilestone(value: number, steps: readonly number[]): number | undefined {\n  return [...steps].sort((a, b) => b - a).find((s) => s <= value);\n}\n\nexport interface XpGain {\n  before: Level;\n  after: Level;\n  gained: number;\n  /** Levels finished by this gain (0 most of the time). */\n  levelsUp: number;\n}\n\n/** What one gain did: the level before and after, and how many levels it finished. */\nexport function gainXp(totalBefore: number, gained: number, curve?: Partial<LevelCurve>): XpGain {\n  const before = levelFor(totalBefore, curve);\n  const g = clean(gained);\n  const after = levelFor(before.total + g, curve);\n  return { before, after, gained: g, levelsUp: after.level - before.level };\n}\n"
    }
  ],
  "meta": {
    "tier": "game",
    "client": false,
    "minViewport": 320,
    "loading": false,
    "version": "1.1.0",
    "since": "2.0.0"
  },
  "docs": "## @interlace/milestones\n\nInstalled to `components/ui/games/milestones.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/games/milestones';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/milestones\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
