Open History to see the last commit
1import { useEffect, useState, type ReactNode } from "react";
2
3import { cn } from "~/lib/utils";
4
5/**
6 * Live countdown text that re-renders only this span each second (the same
7 * self-ticking pattern as the sidebar Working duration), so a static reset
8 * time can read as "resets in 14m" without repainting the banner's parents.
9 */
10export function UsageLimitCountdown({
11 resetsAt,
12 prefix = "resets in",
13 className,
14}: {
15 resetsAt: string;
16 prefix?: string | null;
17 className?: string;
18}) {
19 const targetMs = Date.parse(resetsAt);
20 const [, setTick] = useState(0);
21 useEffect(() => {
22 if (Number.isNaN(targetMs)) return;
23 const id = window.setInterval(() => setTick((tick) => tick + 1), 1_000);
24 return () => window.clearInterval(id);
25 }, [targetMs]);
26 if (Number.isNaN(targetMs)) return null;
27
28 const remaining = targetMs - Date.now();
29 let label: ReactNode;
30 if (remaining <= 0) {
31 // A passed window can't take the "in <time>" shape — "resets in ready
32 // soon"-style concatenations read as broken English — so the preposition
33 // collapses ("resets now", "tokens return now"). A null prefix still
34 // renders the bare value.
35 label = prefix === null ? "now" : `${prefix.replace(/\sin$/, "")} now`;
36 } else {
37 const totalMinutes = Math.ceil(remaining / 60_000);
38 label =
39 totalMinutes < 60
40 ? `${totalMinutes}m`
41 : `${Math.floor(totalMinutes / 60)}h ${totalMinutes % 60}m`;
42 }
43 return (
44 <span className={cn("tabular-nums", className)}>
45 {prefix === null || remaining <= 0 ? label : `${prefix} ${label}`}
46 </span>
47 );
48}