{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "streak",
  "type": "registry:ui",
  "title": "Streak",
  "description": "A player's run of days: the count, a line on where today stands, and a strip of recent days, each marked played, rested, missed or still open. Rest days come from a `RestRule` (weekdays and dates that never break a run), so a habit does not punish a day…",
  "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/streak.tsx",
      "target": "components/ui/games/streak.tsx",
      "type": "registry:ui",
      "content": "import * as React from 'react';\n\n// @interlace/streak v1.2.0 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/streak\n// What changed since: https://ds.interlace.tools/c/streak#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — Streak\n *\n * A player's run of days: the count, a line on where today stands, and a\n * strip of recent days, each marked played, rested, missed or still open.\n * Rest days come from a `RestRule` (weekdays and dates that never break a\n * run), so a habit does not punish a day off. `protection` lets a player\n * earn shields that cover a missed day (see `streak-model.ts`). The arithmetic lives in\n * `streak-model.ts` and is exported, so a server can store and check the\n * same numbers this shows.\n *\n * ## Anatomy\n *\n *   Streak                         (div — data-slot=\"streak\", data-status=played|pending|resting|none)\n *     ├─ p                         (data-slot=\"streak-count\": the number and its unit)\n *     ├─ p                         (data-slot=\"streak-status\": where today stands)\n *     ├─ ol                        (data-slot=\"streak-days\", labelled)\n *     │   └─ li × length           (data-slot=\"streak-day\", data-state=played|rest|missed|open|future)\n *     ├─ p                         (data-slot=\"streak-best\")\n *     └─ p                         (data-slot=\"streak-shields\": shields held, or days to the next one — with `protection`)\n *\n *   variant=\"compact\" renders one inline chip (data-slot=\"streak\") with the\n *   count and a full sentence for assistive tech, for a header or a toolbar.\n *\n * ## Never colour alone\n *\n * A played day is a filled mark with a check, a rest day a dashed ring with\n * a moon, a shielded day a tinted mark with a shield, a missed day an empty\n * ring, today an open ring with a dot. Each\n * day also carries its full date and state as text for screen readers.\n *\n * ## Motion\n *\n * Today's check scales in once when it first appears (CSS `@starting-style`,\n * 250ms, `motion-safe:` only). Nothing else moves.\n *\n * ## Server first\n *\n * No hooks, no state: it renders on the server. Pass `today` (a day key in\n * the player's time zone) when the server's clock is not the player's; the\n * fallback reads the clock in `timeZone`.\n *\n * ## MIN_VIEWPORT — 320\n *\n * Seven 28px marks with their gaps fit a 288px column; they grow to 32px\n * from `xs`.\n *\n * | Rule | Concept                   | Where in this file                                    |\n * | ---- | ------------------------- | ----------------------------------------------------- |\n * | R4   | Extends native el         | `React.ComponentProps<'div'>`                         |\n * | R6   | data-slot per part        | streak / -count / -status / -days / -day / -best      |\n * | R7   | cn + ...rest              | `cn(…, className)` + `{...props}`                     |\n * | R14  | Declares min viewport     | `data-min-viewport` + exported const                  |\n * | R19  | Tokens only               | primary, muted-foreground, input, ring                |\n * | R26  | A11y                      | labelled list; every day as text; status as a sentence |\n */\n\nimport { Check, Flame, Moon, Shield, ShieldCheck } from 'lucide-react';\n\nimport { cn } from '@/lib/utils';\nimport { dayKey, dayKeyToDate, type DayKey } from '@/components/ui/games/daily';\nimport {\n  streakDays,\n  summarizeStreak,\n  type Protection,\n  type RestRule,\n  type StreakDayState,\n  type StreakStatus,\n} from '@/components/ui/games/streak-model';\n\nexport const MIN_VIEWPORT = 320 as const;\n\ninterface StreakLabels {\n  /** After the number. @default 'day streak' */\n  unit?: string;\n  /** One sentence per status. */\n  status?: Partial<Record<StreakStatus, string>>;\n  /** The best run. @default n => `Best: ${n} days` */\n  best?: (best: number) => string;\n  /** Names the strip for assistive tech. @default 'Recent days' */\n  days?: string;\n  /** Each day's state, read after its date. */\n  state?: Partial<Record<StreakDayState, string>>;\n  /** Shields held. @default n => `${n} streak shield(s) ready` */\n  shields?: (held: number) => string;\n  /** Days to the next shield, when none is held. @default n => `${n} more day(s) earns a streak shield` */\n  nextShield?: (days: number) => string;\n}\n\ntype StreakProps = Omit<React.ComponentProps<'div'>, 'children'> & {\n  /** Every day the player played, as day keys. Order and duplicates do not matter. */\n  played: readonly DayKey[];\n  /** Today, in the player's time zone. @default dayKey(new Date(), timeZone) */\n  today?: DayKey;\n  /** IANA time zone for the fallback `today`. */\n  timeZone?: string;\n  /** Days that never break a run. */\n  rest?: RestRule;\n  /** Shields a player earns to cover a missed day. */\n  protection?: Protection;\n  /** Days in the strip, ending today. @default 7 */\n  length?: number;\n  /** Days after today to show as still to come. @default 0 */\n  after?: number;\n  /** `full` shows the strip; `compact` is one inline chip. @default 'full' */\n  variant?: 'full' | 'compact';\n  /** Show the best run under the strip. @default true */\n  showBest?: boolean;\n  /** BCP 47 locale for numbers and day names. @default the runtime's */\n  locale?: string;\n  labels?: StreakLabels;\n};\n\nconst STATUS: Record<StreakStatus, string> = {\n  played: 'Played today. See you tomorrow.',\n  pending: 'Play today to keep your streak.',\n  resting: 'Rest day. Your streak is safe.',\n  none: 'Play today to start a streak.',\n};\n\nconst STATE: Record<StreakDayState, string> = {\n  played: 'played',\n  rest: 'rest day',\n  shielded: 'missed, covered by a shield',\n  missed: 'missed',\n  open: 'not played yet',\n  future: 'still to come',\n};\n\nconst MARK =\n  'relative grid size-7 xs:size-8 shrink-0 place-items-center rounded-full [&_svg]:size-3.5 xs:[&_svg]:size-4';\n\nfunction DayMark({ state, today }: { state: StreakDayState; today: boolean }) {\n  switch (state) {\n    case 'played':\n      return (\n        <span className={cn(MARK, 'bg-primary text-primary-foreground')}>\n          <Check\n            aria-hidden\n            strokeWidth={3}\n            className={cn(\n              today &&\n                'motion-safe:transition-[scale,opacity] motion-safe:duration-(--duration-medium) motion-safe:ease-enter motion-safe:starting:scale-50 motion-safe:starting:opacity-0',\n            )}\n          />\n        </span>\n      );\n    case 'rest':\n      return (\n        <span className={cn(MARK, 'border-muted-foreground text-muted-foreground border-2 border-dashed')}>\n          <Moon aria-hidden />\n        </span>\n      );\n    case 'shielded':\n      return (\n        <span className={cn(MARK, 'bg-primary/15 text-primary')}>\n          <ShieldCheck aria-hidden />\n        </span>\n      );\n    case 'open':\n      return (\n        <span className={cn(MARK, 'border-primary border-2')}>\n          <span aria-hidden className=\"bg-primary size-1.5 rounded-full\" />\n        </span>\n      );\n    case 'future':\n      return <span className={cn(MARK, 'border-input border border-dashed')} />;\n    case 'missed':\n    default:\n      return <span className={cn(MARK, 'border-input border-2')} />;\n  }\n}\n\nfunction Streak({\n  played,\n  today: todayProp,\n  timeZone,\n  rest,\n  protection,\n  length = 7,\n  after = 0,\n  variant = 'full',\n  showBest = true,\n  locale,\n  labels,\n  className,\n  ...props\n}: StreakProps) {\n  const today = todayProp ?? dayKey(new Date(), timeZone);\n  const summary = summarizeStreak(played, today, rest, protection);\n  const unit = labels?.unit ?? 'day streak';\n  const status = labels?.status?.[summary.status] ?? STATUS[summary.status];\n  const nf = new Intl.NumberFormat(locale);\n  const count = nf.format(summary.current);\n\n  if (variant === 'compact') {\n    return (\n      <div\n        data-slot=\"streak\"\n        data-variant=\"compact\"\n        data-status={summary.status}\n        data-min-viewport={String(MIN_VIEWPORT)}\n        className={cn(\n          'border-border bg-card text-card-foreground inline-flex min-h-8 items-center gap-1.5 rounded-full border px-3 text-sm font-semibold tabular-nums',\n          className,\n        )}\n        {...props}\n      >\n        <Flame\n          aria-hidden\n          className={cn('size-4', summary.status === 'played' ? 'text-primary' : 'text-muted-foreground')}\n        />\n        <span aria-hidden>{count}</span>\n        <span className=\"sr-only\">\n          {count} {unit}. {status}\n        </span>\n      </div>\n    );\n  }\n\n  const days = streakDays(played, today, { length, after, rest, protection });\n  const short = new Intl.DateTimeFormat(locale, { weekday: 'narrow', timeZone: 'UTC' });\n  const long = new Intl.DateTimeFormat(locale, {\n    weekday: 'long',\n    month: 'long',\n    day: 'numeric',\n    timeZone: 'UTC',\n  });\n  const best = labels?.best ?? ((n: number) => `Best: ${new Intl.NumberFormat(locale).format(n)} ${n === 1 ? 'day' : 'days'}`);\n\n  return (\n    <div\n      data-slot=\"streak\"\n      data-variant=\"full\"\n      data-status={summary.status}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('grid gap-3', className)}\n      {...props}\n    >\n      <p data-slot=\"streak-count\" className=\"flex items-baseline gap-2\">\n        <span className=\"font-heading text-section leading-none font-semibold tabular-nums\">{count}</span>\n        <span className=\"text-muted-foreground text-sm font-medium\">{unit}</span>\n      </p>\n      <p data-slot=\"streak-status\" className=\"text-sm\">\n        {status}\n      </p>\n      <ol\n        data-slot=\"streak-days\"\n        aria-label={labels?.days ?? 'Recent days'}\n        className=\"xs:gap-2 flex flex-wrap gap-1.5\"\n      >\n        {days.map((d) => (\n          <li\n            key={d.day}\n            data-slot=\"streak-day\"\n            data-state={d.state}\n            data-today={d.today ? '' : undefined}\n            aria-current={d.today ? 'date' : undefined}\n            className=\"grid justify-items-center gap-1\"\n          >\n            <span\n              aria-hidden\n              className={cn(\n                'text-xs leading-none',\n                d.today ? 'text-foreground font-semibold' : 'text-muted-foreground',\n              )}\n            >\n              {short.format(dayKeyToDate(d.day))}\n            </span>\n            <DayMark state={d.state} today={d.today} />\n            <span className=\"sr-only\">\n              {long.format(dayKeyToDate(d.day))}: {labels?.state?.[d.state] ?? STATE[d.state]}\n            </span>\n          </li>\n        ))}\n      </ol>\n      {showBest && summary.best > 0 ? (\n        <p data-slot=\"streak-best\" className=\"text-muted-foreground text-sm\">\n          {best(summary.best)}\n        </p>\n      ) : null}\n      {protection && (summary.shields > 0 || summary.nextShieldIn !== null) ? (\n        <p data-slot=\"streak-shields\" className=\"text-muted-foreground flex items-center gap-1.5 text-sm\">\n          <Shield aria-hidden className={cn('size-4 shrink-0', summary.shields > 0 && 'text-primary')} />\n          {summary.shields > 0\n            ? (labels?.shields ??\n                ((n: number) => `${nf.format(n)} streak ${n === 1 ? 'shield' : 'shields'} ready`))(summary.shields)\n            : (labels?.nextShield ??\n                ((n: number) => `${nf.format(n)} more ${n === 1 ? 'day earns' : 'days earn'} a streak shield`))(\n                summary.nextShieldIn!,\n              )}\n        </p>\n      ) : null}\n    </div>\n  );\n}\nStreak.displayName = 'Streak';\n\nexport { Streak };\nexport type { StreakProps, StreakLabels };\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/streak-model.ts",
      "target": "components/ui/games/streak-model.ts",
      "type": "registry:ui",
      "content": "import { addDays, daysBetween, isDayKey, weekdayOf, type DayKey } from '@/components/ui/games/daily';\n\n/**\n * @interlace/ui — games/streak-model\n *\n * How long a player's run of days is, with rest days. Pure: give it the days\n * a player played and today's key; it returns the current run, the best run\n * and what each recent day was.\n *\n * ## Rest days\n *\n * A habit that punishes a day off teaches people to quit. `RestRule` names\n * days that never break a run: weekdays (`weekdays: [6]` rests every\n * Saturday) and dates (`dates: ['2026-12-25']`). A rest day the player skips\n * is passed over: the run neither grows nor ends. A rest day the player\n * plays anyway counts like any other day.\n *\n * ## Today is open\n *\n * Not having played yet today never ends a run; the day is still going. The\n * run ends only when a whole working day passes without a game. `status`\n * says which of these states the player is in, so a component can say\n * \"play today to keep it\" without working that out again.\n *\n * ## Shields\n *\n * `Protection` lets a player earn their way past a missed day. Every\n * `every` days played in a run earns one shield, up to `max` held. A\n * missed working day with a shield in hand spends it: the day is\n * `shielded`, and the run carries on (it does not grow). Shields are worked\n * out from the played days alone, never stored, so every device and a\n * server reach the same count. Shields outlive a broken run: what was\n * earned stays earned.\n */\n\nexport interface RestRule {\n  /** Weekdays that never break a run: 0 Sunday to 6 Saturday. */\n  weekdays?: readonly number[];\n  /** Single dates that never break a run, as day keys. */\n  dates?: readonly DayKey[];\n}\n\n/**\n * - `played`: played today.\n * - `pending`: a run is alive and today still needs a game.\n * - `resting`: today is a rest day and has no game; the run is safe.\n * - `none`: no run to keep.\n */\nexport type StreakStatus = 'played' | 'pending' | 'resting' | 'none';\n\n/** What one day was: played, rested, missed, today with no game yet, or not yet come. */\nexport type StreakDayState = 'played' | 'rest' | 'shielded' | 'missed' | 'open' | 'future';\n\n/** How a player earns protection for a missed day. */\nexport interface Protection {\n  /** Days played in a run that earn one shield. */\n  every: number;\n  /** Shields a player can hold at once. */\n  max: number;\n}\n\nexport interface StreakDay {\n  day: DayKey;\n  state: StreakDayState;\n  /** True for today's key. */\n  today: boolean;\n}\n\nexport interface StreakSummary {\n  /** Days played in the run that is still alive (0 when there is none). */\n  current: number;\n  /** The longest run on record, today's included. */\n  best: number;\n  status: StreakStatus;\n  /** Total distinct days played up to today. */\n  total: number;\n  /** Shields held now (0 without `Protection`). */\n  shields: number;\n  /** Missed days a shield has covered, ever. */\n  shieldsUsed: number;\n  /** Days still to play in this run to earn the next shield; null when none can be earned. */\n  nextShieldIn: number | null;\n}\n\n/** True when the rule makes `day` a rest day. */\nexport function isRestDay(day: DayKey, rest?: RestRule): boolean {\n  if (!rest) return false;\n  if (rest.dates?.includes(day)) return true;\n  return rest.weekdays?.includes(weekdayOf(day)) ?? false;\n}\n\nfunction playedSet(played: Iterable<DayKey>, today: DayKey): Set<DayKey> {\n  const set = new Set<DayKey>();\n  for (const day of played) {\n    // A malformed key or a day after today (another device's clock) is ignored.\n    if (isDayKey(day) && day <= today) set.add(day);\n  }\n  return set;\n}\n\ninterface Walk {\n  run: number;\n  best: number;\n  shields: number;\n  shieldsUsed: number;\n  /** Days earned toward the next shield in the current run. */\n  toward: number;\n  shieldedDays: Set<DayKey>;\n}\n\nfunction validProtection(p?: Protection): Protection | undefined {\n  if (!p || !(p.every >= 1) || !(p.max >= 1)) return undefined;\n  return { every: Math.floor(p.every), max: Math.floor(p.max) };\n}\n\n// One pass from the first game to today. A missed working day spends a\n// shield or resets the run; today never does, because it is still open.\nfunction walk(days: Set<DayKey>, today: DayKey, rest?: RestRule, protection?: Protection): Walk {\n  const out: Walk = { run: 0, best: 0, shields: 0, shieldsUsed: 0, toward: 0, shieldedDays: new Set() };\n  if (days.size === 0) return out;\n  const p = validProtection(protection);\n  const first = [...days].sort()[0] as DayKey;\n  const span = daysBetween(first, today);\n  for (let i = 0; i <= span; i++) {\n    const day = addDays(first, i);\n    if (days.has(day)) {\n      out.run += 1;\n      if (p) {\n        out.toward += 1;\n        if (out.toward >= p.every) {\n          out.toward = 0;\n          out.shields = Math.min(p.max, out.shields + 1);\n        }\n      }\n    } else if (day !== today && !isRestDay(day, rest)) {\n      if (out.shields > 0 && out.run > 0) {\n        out.shields -= 1;\n        out.shieldsUsed += 1;\n        out.shieldedDays.add(day);\n      } else {\n        out.run = 0;\n        out.toward = 0;\n      }\n    }\n    out.best = Math.max(out.best, out.run);\n  }\n  return out;\n}\n\n/** The player's current and best run, and where today stands. */\nexport function summarizeStreak(\n  played: Iterable<DayKey>,\n  today: DayKey,\n  rest?: RestRule,\n  protection?: Protection,\n): StreakSummary {\n  const days = playedSet(played, today);\n  const p = validProtection(protection);\n  const w = walk(days, today, rest, p);\n  const nextShieldIn = p && w.shields < p.max ? p.every - w.toward : null;\n  const base = { shields: w.shields, shieldsUsed: w.shieldsUsed, nextShieldIn };\n  if (days.size === 0) {\n    return { current: 0, best: 0, status: isRestDay(today, rest) ? 'resting' : 'none', total: 0, ...base };\n  }\n  const run = w.run;\n  const playedToday = days.has(today);\n  const status: StreakStatus = playedToday\n    ? 'played'\n    : isRestDay(today, rest)\n      ? run > 0\n        ? 'resting'\n        : 'none'\n      : run > 0\n        ? 'pending'\n        : 'none';\n  return { current: run, best: w.best, status, total: days.size, ...base };\n}\n\n/**\n * The last `length` days ending today, oldest first, each with its state.\n * Pass `after` to also show days after today as `future` (a full week strip\n * that ends on Saturday, say).\n */\nexport function streakDays(\n  played: Iterable<DayKey>,\n  today: DayKey,\n  options: { length?: number; after?: number; rest?: RestRule; protection?: Protection } = {},\n): StreakDay[] {\n  const { length = 7, after = 0, rest, protection } = options;\n  const days = playedSet(played, today);\n  const { shieldedDays } = walk(days, today, rest, protection);\n  const out: StreakDay[] = [];\n  for (let i = -(length - 1); i <= after; i++) {\n    const day = addDays(today, i);\n    const state: StreakDayState =\n      i > 0\n        ? 'future'\n        : days.has(day)\n          ? 'played'\n          : isRestDay(day, rest)\n            ? 'rest'\n            : shieldedDays.has(day)\n              ? 'shielded'\n              : i === 0\n              ? 'open'\n              : 'missed';\n    out.push({ day, state, today: i === 0 });\n  }\n  return out;\n}\n"
    }
  ],
  "meta": {
    "tier": "game",
    "client": false,
    "minViewport": 320,
    "loading": false,
    "version": "1.2.0",
    "since": "2.0.0"
  },
  "docs": "## @interlace/streak\n\nInstalled to `components/ui/games/streak.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/games/streak';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/streak\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
