{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "daily-puzzle",
  "type": "registry:ui",
  "title": "Daily Puzzle",
  "description": "The frame around a daily game: its name, today's number and date, how far through the rounds the player is, and, once they finish, a countdown to the next one. The game itself is the children, so any round (a CloserGame, a GuessReveal, your own) sits…",
  "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"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/games/daily-puzzle.tsx",
      "target": "components/ui/games/daily-puzzle.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/daily-puzzle v1.2.2 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/daily-puzzle\n// What changed since: https://ds.interlace.tools/c/daily-puzzle#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — DailyPuzzle\n *\n * The frame around a daily game: its name, today's number and date, how far\n * through the rounds the player is, and, once they finish, a countdown to the\n * next one. The game itself is the children, so any round (a CloserGame, a\n * GuessReveal, your own) sits inside the same shell.\n *\n * ## Anatomy\n *\n *   DailyPuzzle                    (section — data-slot=\"daily-puzzle\", data-state=playing|done, data-size, labelled by the title)\n *     ├─ header                    (data-slot=\"daily-puzzle-header\")\n *     │   ├─ h2                    (data-slot=\"daily-puzzle-title\")\n *     │   ├─ p                     (data-slot=\"daily-puzzle-meta\": \"No. 42 · Tuesday, November 24\")\n *     │   └─ div                   (data-slot=\"daily-puzzle-aside\": a compact Streak, a menu)\n *     ├─ div                       (data-slot=\"daily-puzzle-progress\": \"Round 2 of 3\" + marks)\n *     └─ div                       (data-slot=\"daily-puzzle-body\", keyed by round so each one arrives)\n *\n *   DailyPuzzleCountdown           (p — data-slot=\"daily-puzzle-countdown\": \"Next puzzle in 5 h 12 min\")\n *\n * ## Rounds\n *\n * `rounds` is how many there are and `round` the one in play (1-based).\n * The progress line is a polite live region, so moving on is announced.\n * When `done`, every mark fills and the line says so. Each new round's body\n * rises in once (150ms, `motion-safe:` only). The first round does not: it is\n * what the page opens on, often its largest paint, so it is there at first\n * paint and only the rounds after it arrive.\n *\n * ## The countdown\n *\n * The server cannot know the player's clock, so the server HTML says \"Next\n * puzzle at midnight\" (`labels.nextAtMidnight`) and the browser replaces it\n * with the time left, read in `timeZone`, ticking each minute (each second\n * in the last minute). At zero it calls `onNextDay`, so the page can load\n * the new puzzle.\n *\n * ## MIN_VIEWPORT — 320\n *\n * | Rule | Concept                   | Where in this file                                     |\n * | ---- | ------------------------- | ------------------------------------------------------ |\n * | R4   | Extends native el         | `React.ComponentProps<'section'>`                      |\n * | R6   | data-slot per part        | daily-puzzle / -header / -title / -meta / -aside / -progress / -body / -countdown |\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, border               |\n * | R26  | A11y                      | labelled section; progress in words, announced; real `<time>` |\n */\n\nimport { cn } from '@/lib/utils';\nimport { dayKey, dayKeyToDate, msUntilNextDay, type DayKey } from '@/components/ui/games/daily';\n\nexport const MIN_VIEWPORT = 320 as const;\n\ninterface DailyPuzzleLabels {\n  /** @default n => `No. ${n}` */\n  number?: (n: string) => string;\n  /** @default (round, rounds) => `Round ${round} of ${rounds}` */\n  progress?: (round: number, rounds: number) => string;\n  /** @default 'All done for today' */\n  done?: string;\n}\n\ntype DailyPuzzleProps = Omit<React.ComponentProps<'section'>, 'title'> & {\n  /** The game's name. Rendered as an h2; `headingLevel` changes the element only. */\n  title: React.ReactNode;\n  /** @default 2 */\n  headingLevel?: 1 | 2 | 3;\n  /**\n   * `default` sets the title at `text-h3`, for a puzzle inside a page. `page` sets it as\n   * Typography's `h1` does (`text-h1`), for a page whose content is the puzzle.\n   * Visual only: pair it with `headingLevel={1}`.\n   * @default 'default'\n   */\n  size?: 'default' | 'page';\n  /** Today's puzzle number (see `puzzleNumber`). */\n  number?: number;\n  /** Today's day key, shown as a date. */\n  day?: DayKey;\n  /** Rounds in today's puzzle. Leave out for a one-round game. */\n  rounds?: number;\n  /** The round in play, 1-based. @default 1 */\n  round?: number;\n  /** The player has finished today's puzzle. */\n  done?: boolean;\n  /** Beside the title: a compact Streak, a help button. */\n  aside?: React.ReactNode;\n  locale?: string;\n  labels?: DailyPuzzleLabels;\n};\n\nfunction DailyPuzzle({\n  title,\n  headingLevel = 2,\n  size = 'default',\n  number,\n  day,\n  rounds,\n  round = 1,\n  done = false,\n  aside,\n  locale,\n  labels,\n  className,\n  children,\n  ...props\n}: DailyPuzzleProps) {\n  const titleId = React.useId();\n  // The entry transition is for one round giving way to the next. On first paint the\n  // body is the page's content (often its LCP), so it must not start from opacity 0.\n  const [entered, setEntered] = React.useState(false);\n  React.useEffect(() => setEntered(true), []);\n  const Heading = `h${headingLevel}` as const;\n  const meta: string[] = [];\n  if (number !== undefined) {\n    const n = new Intl.NumberFormat(locale).format(number);\n    meta.push(labels?.number ? labels.number(n) : `No. ${n}`);\n  }\n  if (day) {\n    meta.push(\n      new Intl.DateTimeFormat(locale, { weekday: 'long', month: 'long', day: 'numeric', timeZone: 'UTC' }).format(\n        dayKeyToDate(day),\n      ),\n    );\n  }\n  const current = Math.min(Math.max(round, 1), rounds ?? 1);\n  const progress = done\n    ? (labels?.done ?? 'All done for today')\n    : (labels?.progress ?? ((r: number, of: number) => `Round ${r} of ${of}`))(current, rounds ?? 1);\n\n  return (\n    <section\n      data-slot=\"daily-puzzle\"\n      data-state={done ? 'done' : 'playing'}\n      data-size={size}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      aria-labelledby={titleId}\n      className={cn('grid gap-5', className)}\n      {...props}\n    >\n      <header data-slot=\"daily-puzzle-header\" className=\"flex flex-wrap items-start justify-between gap-x-4 gap-y-2\">\n        <div className=\"grid min-w-0 gap-1\">\n          <Heading\n            id={titleId}\n            data-slot=\"daily-puzzle-title\"\n            className={cn(\n              'font-heading text-balance',\n              size === 'page' ? 'text-h1 tracking-display font-bold' : 'text-h3 font-semibold',\n            )}\n          >\n            {title}\n          </Heading>\n          {meta.length ? (\n            <p data-slot=\"daily-puzzle-meta\" className=\"text-muted-foreground text-sm\">\n              {number !== undefined && day ? (\n                <>\n                  {meta[0]} <span aria-hidden>·</span> <time dateTime={day}>{meta[1]}</time>\n                </>\n              ) : day ? (\n                <time dateTime={day}>{meta[0]}</time>\n              ) : (\n                meta[0]\n              )}\n            </p>\n          ) : null}\n        </div>\n        {aside ? (\n          <div data-slot=\"daily-puzzle-aside\" className=\"flex shrink-0 items-center gap-2\">\n            {aside}\n          </div>\n        ) : null}\n      </header>\n\n      {rounds && rounds > 1 ? (\n        <div data-slot=\"daily-puzzle-progress\" className=\"flex flex-wrap items-center gap-3\">\n          <ol aria-hidden className=\"flex gap-1.5\">\n            {Array.from({ length: rounds }, (_, i) => {\n              const state = done || i + 1 < current ? 'done' : i + 1 === current ? 'current' : 'next';\n              return (\n                <li\n                  key={i}\n                  data-state={state}\n                  className={cn(\n                    'h-1.5 w-6 rounded-full',\n                    'motion-safe:transition-colors motion-safe:duration-(--duration-medium) motion-safe:ease-enter',\n                    state === 'done' && 'bg-primary',\n                    state === 'current' && 'bg-primary/40 ring-primary ring-1',\n                    state === 'next' && 'bg-input',\n                  )}\n                />\n              );\n            })}\n          </ol>\n          <p aria-live=\"polite\" className=\"text-muted-foreground text-sm font-medium\">\n            {progress}\n          </p>\n        </div>\n      ) : done ? (\n        <p data-slot=\"daily-puzzle-progress\" aria-live=\"polite\" className=\"text-muted-foreground text-sm font-medium\">\n          {progress}\n        </p>\n      ) : null}\n\n      <div\n        key={done ? 'done' : current}\n        data-slot=\"daily-puzzle-body\"\n        className={cn(\n          'motion-safe:transition-[translate,opacity] motion-safe:duration-(--duration-base) motion-safe:ease-enter',\n          entered && 'motion-safe:starting:translate-y-2 motion-safe:starting:opacity-0',\n        )}\n      >\n        {children}\n      </div>\n    </section>\n  );\n}\nDailyPuzzle.displayName = 'DailyPuzzle';\n\ninterface DailyPuzzleCountdownProps extends Omit<React.ComponentProps<'p'>, 'children'> {\n  /** IANA zone the next day starts in. @default the runtime's */\n  timeZone?: string;\n  /** Called once when the next day starts. */\n  onNextDay?: () => void;\n  locale?: string;\n  labels?: {\n    /** Server HTML, before the clock is known. @default 'Next puzzle at midnight' */\n    nextAtMidnight?: string;\n    /** @default time => `Next puzzle in ${time}` */\n    nextIn?: (time: string) => string;\n    /** @default 'A new puzzle is ready' */\n    ready?: string;\n  };\n}\n\n/** Time left in the locale's own short unit words, such as \"5 hr 12 min\", \"12 min\" or \"45 sec\" in en-US. */\nfunction formatLeft(ms: number, locale?: string) {\n  const unit = (u: 'hour' | 'minute' | 'second', n: number) =>\n    new Intl.NumberFormat(locale, { style: 'unit', unit: u, unitDisplay: 'short' }).format(n);\n  if (ms < 60_000) return unit('second', Math.max(0, Math.ceil(ms / 1000)));\n  const minutes = Math.ceil(ms / 60_000);\n  const h = Math.floor(minutes / 60);\n  const m = minutes % 60;\n  return h > 0 ? (m > 0 ? `${unit('hour', h)} ${unit('minute', m)}` : unit('hour', h)) : unit('minute', m);\n}\n\nfunction DailyPuzzleCountdown({ timeZone, onNextDay, locale, labels, className, ...props }: DailyPuzzleCountdownProps) {\n  const [left, setLeft] = React.useState<number | null>(null);\n  const onNextDayRef = React.useRef(onNextDay);\n  onNextDayRef.current = onNextDay;\n\n  React.useEffect(() => {\n    let timer: ReturnType<typeof setTimeout>;\n    const startDay = dayKey(Date.now(), timeZone);\n    const tick = () => {\n      const now = Date.now();\n      if (dayKey(now, timeZone) !== startDay) {\n        setLeft(0);\n        onNextDayRef.current?.();\n        return;\n      }\n      const ms = msUntilNextDay(now, timeZone);\n      setLeft(ms);\n      // Tick as each minute turns; every second in the last minute.\n      timer = setTimeout(tick, (ms <= 60_000 ? ms % 1000 : ms % 60_000) + 20);\n    };\n    tick();\n    return () => clearTimeout(timer);\n  }, [timeZone]);\n\n  const text =\n    left === null\n      ? (labels?.nextAtMidnight ?? 'Next puzzle at midnight')\n      : left === 0\n        ? (labels?.ready ?? 'A new puzzle is ready')\n        : (labels?.nextIn ?? ((t: string) => `Next puzzle in ${t}`))(formatLeft(left, locale));\n\n  return (\n    <p\n      data-slot=\"daily-puzzle-countdown\"\n      data-state={left === 0 ? 'ready' : 'waiting'}\n      className={cn('text-muted-foreground text-sm tabular-nums', className)}\n      {...props}\n    >\n      {/* The ticks stay quiet; only the day turning is announced. A live region\n          must exist before its text changes, so it is always rendered. */}\n      <span aria-hidden={left === 0 || undefined}>{text}</span>\n      <span data-slot=\"daily-puzzle-countdown-status\" aria-live=\"polite\" className=\"sr-only\">\n        {left === 0 ? text : ''}\n      </span>\n    </p>\n  );\n}\nDailyPuzzleCountdown.displayName = 'DailyPuzzleCountdown';\n\nexport { DailyPuzzle, DailyPuzzleCountdown, formatLeft };\nexport type { DailyPuzzleProps, DailyPuzzleLabels, DailyPuzzleCountdownProps };\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"
    }
  ],
  "meta": {
    "tier": "game",
    "client": true,
    "minViewport": 320,
    "loading": false,
    "version": "1.2.2",
    "since": "2.0.0"
  },
  "docs": "## @interlace/daily-puzzle\n\nInstalled to `components/ui/games/daily-puzzle.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/games/daily-puzzle';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/daily-puzzle\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
