{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "countdown",
  "type": "registry:ui",
  "title": "Countdown",
  "description": "The time left until a moment, as text that counts down (\"4 min 12 s\"), announced to screen-reader users only at the moments the project lists.",
  "categories": [
    "ui"
  ],
  "dependencies": [],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/announce",
    "@rivier-ui/cn"
  ],
  "files": [
    {
      "path": "registry/ui/countdown.tsx",
      "type": "registry:ui",
      "target": "components/ui/countdown.tsx",
      "content": "\"use client\";\n/**\n * @name countdown\n * @category ui\n * @description The time left until a moment, as text that counts down (\"4 min 12 s\"), announced to screen-reader users only at the moments the project lists.\n * @when Something the person holds for a limited time: a reserved seat, a price that is kept, a code that expires, a session about to end. Say what happens at the end and offer a way to get more time beside it. Not for decoration or pressure: a countdown that restarts or means nothing is a dark pattern. For progress through a known amount of work use progress.\n * @example\n * <p>\n *   Your seats are held for{\" \"}\n *   <Countdown\n *     to={hold.expiresAt}\n *     locale=\"en\"\n *     thresholds={[300, 60]}\n *     announceAt={(_, left) => `${left} left to finish booking`}\n *     onExpire={release}\n *     expiredLabel=\"no longer: the hold has ended\"\n *   />\n * </p>\n */\nimport { useEffect, useMemo, useRef, useSyncExternalStore, type ComponentProps, type ReactNode } from \"react\";\nimport { announce } from \"@/lib/announce\";\nimport { cn } from \"@/lib/cn\";\n\n/* One clock for every countdown on the page: it ticks once a second while anything listens and the tab is visible. */\nconst listeners = new Set<() => void>();\nlet nowSeconds = 0;\nlet timer: number | undefined;\n\nconst read = (): number => Math.floor(Date.now() / 1000);\n\nfunction tick(): void {\n  const next = read();\n  if (next === nowSeconds) return;\n  nowSeconds = next;\n  for (const listener of listeners) listener();\n}\n\nfunction run(): void {\n  window.clearInterval(timer);\n  timer = undefined;\n  if (listeners.size === 0 || document.visibilityState === \"hidden\") return;\n  tick();\n  // Four checks a second, so that the shown second never lags the real one by more than a quarter.\n  timer = window.setInterval(tick, 250);\n}\n\nfunction subscribe(listener: () => void): () => void {\n  if (listeners.size === 0) document.addEventListener(\"visibilitychange\", run);\n  listeners.add(listener);\n  run();\n  return () => {\n    listeners.delete(listener);\n    if (listeners.size === 0) document.removeEventListener(\"visibilitychange\", run);\n    run();\n  };\n}\n\nfunction snapshot(): number {\n  if (nowSeconds === 0) nowSeconds = read();\n  return nowSeconds;\n}\n\n/** The server does not know when the page will be looked at. */\nconst serverSnapshot = (): null => null;\n\nexport type CountdownParts = { hours: number; minutes: number; seconds: number; total: number };\n\nexport type CountdownProps = Omit<ComponentProps<\"span\">, \"children\"> & {\n  /** The moment it counts down to: a Date, a timestamp in milliseconds, or an ISO string. */\n  to: Date | number | string;\n  /** The locale the units are written in (\"4 min 12 s\", \"4 Min. 12 Sek.\"). Default: the runtime's. */\n  locale?: string;\n  /** Seconds left at which to speak, for example [300, 60]. Nothing is announced between them. */\n  thresholds?: number[];\n  /** The sentence said at a threshold, from the seconds left and the time as text. Default: the time as text. */\n  announceAt?: (secondsLeft: number, text: string) => string;\n  /** Called once when the time runs out (also when it had already run out as the page loaded). */\n  onExpire?: () => void;\n  /** Shown, and said, once the time has run out. */\n  expiredLabel?: string;\n  /** Writes the time yourself (\"04:12\"). */\n  format?: (parts: CountdownParts) => string;\n  /** Shown on the server and until the page is live, in place of a time nobody can know yet. Keep it about as wide as a time. */\n  fallback?: ReactNode;\n};\n\n/**\n * A timer (`role=\"timer\"`): screen readers can read it on demand but are not interrupted every second.\n * Figures are tabular and the seconds keep two digits while there are minutes, so the text around it does\n * not move as it counts. It stops ticking while the tab is hidden and is right again the moment it returns,\n * because it is worked out from the clock, not counted.\n */\nexport function Countdown({ to, locale, thresholds, announceAt, onExpire, expiredLabel = \"Time is up\", format, fallback = \"–\", className, ...props }: CountdownProps) {\n  const now = useSyncExternalStore(subscribe, snapshot, serverSnapshot);\n  const target = Math.floor(new Date(to).getTime() / 1000);\n  const left = now === null || Number.isNaN(target) ? null : Math.max(0, target - now);\n\n  const units = useMemo(() => {\n    const unit = (name: \"hour\" | \"minute\" | \"second\", pad: boolean): Intl.NumberFormat =>\n      new Intl.NumberFormat(locale, { style: \"unit\", unit: name, unitDisplay: \"short\", minimumIntegerDigits: pad ? 2 : 1 });\n    return { hour: unit(\"hour\", false), minute: unit(\"minute\", false), minutePadded: unit(\"minute\", true), second: unit(\"second\", false), secondPadded: unit(\"second\", true) };\n  }, [locale]);\n\n  let text: string | null = null;\n  if (left !== null && left > 0) {\n    const parts: CountdownParts = { hours: Math.floor(left / 3600), minutes: Math.floor((left % 3600) / 60), seconds: left % 60, total: left };\n    if (format) text = format(parts);\n    else if (parts.hours > 0) text = `${units.hour.format(parts.hours)} ${units.minutePadded.format(parts.minutes)} ${units.secondPadded.format(parts.seconds)}`;\n    else if (parts.minutes > 0) text = `${units.minute.format(parts.minutes)} ${units.secondPadded.format(parts.seconds)}`;\n    else text = units.second.format(parts.seconds);\n  }\n\n  // What the effects below need at the moment they run, without running again when it changes.\n  const latest = useRef({ thresholds, announceAt, onExpire, expiredLabel, text });\n  useEffect(() => {\n    latest.current = { thresholds, announceAt, onExpire, expiredLabel, text };\n  });\n  const previous = useRef<number | null>(null);\n  const expired = useRef(false);\n  useEffect(() => {\n    if (left === null) return;\n    const before = previous.current;\n    previous.current = left;\n    const current = latest.current;\n    if (left === 0) {\n      if (expired.current) return;\n      expired.current = true;\n      // Said only when the person saw it run out, not for a page that loads after the end.\n      if (before !== null) announce(current.expiredLabel);\n      current.onExpire?.();\n      return;\n    }\n    expired.current = false;\n    if (before === null || current.text === null) return;\n    // A threshold is crossed when the last tick was above it and this one is at or below it (a hidden tab can skip seconds).\n    const crossed = (current.thresholds ?? []).filter((threshold) => before > threshold && left <= threshold);\n    if (crossed.length > 0) announce(current.announceAt ? current.announceAt(left, current.text) : current.text);\n  }, [left]);\n\n  return (\n    <span\n      role=\"timer\"\n      data-slot=\"countdown\"\n      data-state={left === null ? \"pending\" : left === 0 ? \"expired\" : \"running\"}\n      className={cn(\"inline-block whitespace-nowrap tabular-nums\", className)}\n      {...props}\n    >\n      {left === null ? fallback : left === 0 ? expiredLabel : text}\n    </span>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "ui",
    "when": "Something the person holds for a limited time: a reserved seat, a price that is kept, a code that expires, a session about to end. Say what happens at the end and offer a way to get more time beside it. Not for decoration or pressure: a countdown that restarts or means nothing is a dark pattern. For progress through a known amount of work use progress.",
    "example": "<p>\n  Your seats are held for{\" \"}\n  <Countdown\n    to={hold.expiresAt}\n    locale=\"en\"\n    thresholds={[300, 60]}\n    announceAt={(_, left) => `${left} left to finish booking`}\n    onExpire={release}\n    expiredLabel=\"no longer: the hold has ended\"\n  />\n</p>",
    "client": true
  }
}
