Countdown
A deadline chip that reads “2d 4h left”. The server renders the end date in UTC inside <time dateTime>; after hydration it counts down on a shared clock, turns urgent near the end and shows local time on hover.
Preview
Submissions close
Voting ends
Seconds precision
Already over
Install
npx shadcn@latest add @dxbh-ui/countdown
Add the @dxbh-ui registry to components.json once:
{
"registries": {
"@dxbh-ui": "https://ui.dxbh.dev/r/{name}.json"
}
}Usage
"use client";
import { useState } from "react";
import { Countdown } from "@/components/ui/countdown/countdown";
export default function CountdownDemo() {
const [ends] = useState(() => {
const now = Date.now();
return {
week: now + 9 * 86_400_000,
day: now + 30 * 3_600_000 + 12 * 60_000,
soon: now + 4 * 60_000 + 30_000,
past: now - 3_600_000,
};
});
return (
<div className="flex flex-col items-start gap-3 text-sm">
<div className="flex items-center gap-3"><Countdown to={ends.week} /><span className="text-muted-foreground">Submissions close</span></div>
<div className="flex items-center gap-3"><Countdown to={ends.day} /><span className="text-muted-foreground">Voting ends</span></div>
<div className="flex items-center gap-3"><Countdown to={ends.soon} precision="second" /><span className="text-muted-foreground">Seconds precision</span></div>
<div className="flex items-center gap-3"><Countdown to={ends.past} /><span className="text-muted-foreground">Already over</span></div>
</div>
);
}Props
| Prop | Type | Default |
|---|---|---|
to*When it ends. | Date | string | number | — |
precisionHow often it ticks. | "minute" | "second" | "minute" |
urgentWithinMs left below which the chip turns urgent (48h). | number | 172800000 |
endedLabelShown once the time has passed. | string | "Ended" |
formatReplace the remaining-time text. | (msLeft: number) => string | — |
onEndCalled once when it reaches zero while mounted. | () => void | — |
hideIconHide the clock icon. | boolean | false |
Polish
- Ticks on the shared, boundary-aligned useNow clock: every countdown on the page changes on the same frame from one timer.
- tabular-nums so the digits never shift the chip's width. Ticks change text only; nothing animates per tick.
- Server and hydration render the UTC end date in <time dateTime>, then swap to time left, with no hydration mismatch.
- Urgency pairs the --negative colour with the text itself, so meaning never depends on colour alone.
- Minute precision rounds up so the last minute reads “1m left”, never “0m left”; opt into seconds with precision="second".
- Product-specific warning colours replaced with the shadcn palette and dxbh-ui status tokens; onEnd and format hooks added.
Source
"use client";
import { useEffect, useRef, type HTMLAttributes } from "react";
import { Clock } from "lucide-react";
import { cn } from "@/lib/utils";
import { useNow } from "@/hooks/use-now";
import { formatLocal, formatUtc, toDate, type TimeValue } from "@/components/ui/local-time/local-time";
const MINUTE = 60_000;
const HOUR = 60 * MINUTE;
const DAY = 24 * HOUR;
/** "3d left", "1d 4h left", "2h 5m left", "4m left", "12s left" (seconds precision only). */
export function formatRemaining(ms: number, precision: "minute" | "second" = "minute"): string {
const d = Math.floor(ms / DAY);
const h = Math.floor((ms % DAY) / HOUR);
const m = Math.floor((ms % HOUR) / MINUTE);
const s = Math.floor((ms % MINUTE) / 1000);
if (d >= 2) return `${d}d left`;
if (d === 1) return `1d ${h}h left`;
if (h >= 1) return `${h}h ${m}m left`;
if (precision === "second") return m >= 1 ? `${m}m ${s}s left` : `${Math.max(s, 1)}s left`;
// Round up so the last minute reads "1m left", never "0m left".
return `${Math.max(Math.ceil(ms / MINUTE), 1)}m left`;
}
export type CountdownProps = Omit<HTMLAttributes<HTMLTimeElement>, "children"> & {
/** When it ends: a Date, an ISO string or epoch ms. */
to: TimeValue;
/** Tick every minute (default) or every second. */
precision?: "minute" | "second";
/** Below this many ms left the chip turns urgent. Default 48 hours. */
urgentWithin?: number;
/** Shown once the time has passed. */
endedLabel?: string;
/** Replace the remaining-time text. */
format?: (msLeft: number) => string;
/** Called once when the countdown reaches zero while mounted. */
onEnd?: () => void;
/** Hide the clock icon. */
hideIcon?: boolean;
};
/**
* A deadline chip. The server renders the end date in UTC inside a
* `<time dateTime>`; after hydration it reads "9d left" from a shared clock
* and changes text without animating each tick.
*/
export function Countdown({
to,
precision = "minute",
urgentWithin = 48 * HOUR,
endedLabel = "Ended",
format,
onEnd,
hideIcon = false,
className,
title,
...props
}: CountdownProps) {
const end = toDate(to);
const now = useNow(precision === "second" ? 1000 : MINUTE);
const left = now === null ? null : end.getTime() - now;
const ended = left !== null && left <= 0;
const urgent = left !== null && !ended && left < urgentWithin;
const utc = formatUtc(end);
// Fire onEnd only for a countdown that was running when it reached zero.
const wasRunning = useRef(false);
const onEndRef = useRef(onEnd);
useEffect(() => {
onEndRef.current = onEnd;
});
useEffect(() => {
if (left === null) return;
if (!ended) wasRunning.current = true;
else if (wasRunning.current) {
wasRunning.current = false;
onEndRef.current?.();
}
}, [left, ended]);
const text = left === null ? `Ends ${utc}` : ended ? endedLabel : (format ?? ((ms) => formatRemaining(ms, precision)))(left);
return (
<time
dateTime={end.toISOString()}
title={title ?? (now === null ? utc : `${formatLocal(end, "datetime", undefined, { dateStyle: "medium", timeStyle: "short" })} (${utc})`)}
data-state={left === null ? "pending" : ended ? "ended" : urgent ? "urgent" : "running"}
className={cn(
"inline-flex h-6 items-center gap-1.5 rounded-full border px-2.5 text-xs leading-none font-medium whitespace-nowrap tabular-nums",
ended ? "text-muted-foreground" : urgent ? "border-negative/30 text-negative" : "text-foreground",
className,
)}
{...props}
>
{hideIcon ? null : <Clock aria-hidden="true" className="size-3.5 shrink-0" />}
{text}
{left === null || ended ? null : <span className="sr-only">{`, ends ${utc}`}</span>}
</time>
);
}Extracted from koryaku/src/components/challenge/countdown.tsx at 92a2356.