Countdown
A fixed UTC deadline with rolling digits, a compact variant and a completion message.
pnpm dlx shadcn@latest add @haze/countdown---
import { cn } from "../../../lib/haze/utils";
type Unit = "days" | "hours" | "minutes" | "seconds";
interface Props {
target: Date | number | string;
label?: string;
completeLabel?: string;
units?: Unit[];
variant?: "display" | "compact";
class?: string;
}
const { target, label = "Time remaining", completeLabel = "Live now", units, variant = "display", class: className } = Astro.props;
const sizes: Record<Unit, number> = { days: 86400000, hours: 3600000, minutes: 60000, seconds: 1000 };
const order = Object.keys(sizes) as Unit[];
const requested = order.filter((unit) => units?.includes(unit));
const shown = requested.length ? requested : order;
const compact = variant === "compact";
const short: Record<Unit, string> = { days: "d", hours: "h", minutes: "m", seconds: "s" };
let timestamp = target instanceof Date ? target.getTime() : typeof target === "number" ? target : NaN;
if (typeof target === "string") {
const iso = target.trim();
if (/^\d{4}-\d{2}-\d{2}$/.test(iso)) timestamp = Date.parse(iso + "T00:00:00Z");
else if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?$/i.test(iso)) {
timestamp = Date.parse(/(?:Z|[+-]\d{2}:?\d{2})$/i.test(iso) ? iso : iso + "Z");
}
}
const deadline = new Date(timestamp);
const valid = Number.isFinite(deadline.getTime());
const formatted = valid ? new Intl.DateTimeFormat("en", {
year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", second: "2-digit", timeZone: "UTC", timeZoneName: "short",
}).format(deadline) : "";
---
<div data-haze-countdown data-deadline={valid ? deadline.getTime() : undefined} data-complete={completeLabel}
class={cn("grid min-w-0 gap-2.5", compact && "gap-1.5", className)}>
<p class="text-[0.8125rem]/5 font-medium tracking-[-0.01em] wrap-anywhere">{label}</p>
{valid ? (
<>
<div hidden data-clock role="timer" aria-label={label} aria-live="off"
class={cn("min-w-0 items-start [&[hidden]]:hidden", compact ? "flex flex-wrap gap-2 font-mono" : "grid grid-cols-2 gap-x-2 gap-y-3 sm:flex sm:flex-wrap")}>
{shown.map((unit) => (
<span aria-hidden="true" data-unit={unit} data-step={sizes[unit]} class={cn(compact ? "inline-flex items-baseline gap-0.5" : "grid min-w-fit grow justify-items-center gap-1.5")}>
<span data-digits class={cn("inline-flex min-w-0 justify-center font-mono font-medium tabular-nums",
compact ? "text-base/6" : "w-full min-w-[2.3ch] rounded-xl border border-border bg-card px-1 py-2 text-2xl/8 tracking-tight sm:text-3xl/9")}>00</span>
<span class={cn("text-xs/4 text-muted-foreground", !compact && "capitalize")}>{compact ? short[unit] : unit}</span>
</span>
))}
<span data-spoken class="sr-only"></span>
</div>
<span data-finish role="status" aria-atomic="true" class="text-[1.0625rem]/6 font-medium text-success empty:sr-only"></span>
<time datetime={deadline.toISOString()} class="font-mono text-xs/5 wrap-anywhere text-muted-foreground">{formatted}</time>
</>
) : <p class="text-[0.8125rem]/5 text-muted-foreground">Date unavailable</p>}
</div>
<script>
let timer: number | undefined;
const reduced = matchMedia("(prefers-reduced-motion: reduce)");
function showDigits(group: HTMLElement, text: string, animate: boolean) {
if (group.textContent === text && group.childElementCount) return;
if (group.childElementCount !== text.length) {
group.replaceChildren(...Array.from(text, () => document.createElement("span")));
}
Array.from(group.children).forEach((digit, index) => {
if (digit.textContent === text[index]) return;
digit.textContent = text[index];
if (animate && !reduced.matches && typeof digit.animate === "function") {
digit.animate([{ opacity: 0.45, translate: "0 0.2em" }, { opacity: 1, translate: "0 0" }], {
duration: 150, easing: getComputedStyle(group).getPropertyValue("--ease-snappy").trim() || "ease",
});
}
});
}
function update(root: HTMLElement, now: number) {
const clock = root.querySelector<HTMLElement>("[data-clock]");
const spoken = root.querySelector<HTMLElement>("[data-spoken]");
const finish = root.querySelector<HTMLElement>("[data-finish]");
if (!clock || !spoken || !finish) return Infinity;
const remaining = Number(root.dataset.deadline) - now;
if (remaining <= 0) {
clock.hidden = true;
if (!root.hasAttribute("data-finished")) {
finish.textContent = root.dataset.complete ?? "Live now";
root.setAttribute("data-finished", "");
}
root.setAttribute("data-enhanced", "");
return Infinity;
}
const groups = Array.from(clock.querySelectorAll<HTMLElement>("[data-unit]"));
const step = Number(groups[groups.length - 1].dataset.step);
let rest = Math.ceil(remaining / step) * step;
const words: string[] = [];
for (const group of groups) {
const size = Number(group.dataset.step);
const value = Math.floor(rest / size);
rest %= size;
const name = group.dataset.unit!;
const digits = group.querySelector<HTMLElement>("[data-digits]")!;
showDigits(digits, String(value).padStart(2, "0"), !clock.hidden);
if (value && (size !== 1000 || remaining < 60000 || !words.length)) {
words.push(value + " " + (value === 1 ? name.slice(0, -1) : name));
}
}
const description = words.join(", ");
if (spoken.textContent !== description) spoken.textContent = description;
clock.hidden = false;
root.setAttribute("data-enhanced", "");
return remaining % step || step;
}
function refresh() {
window.clearTimeout(timer);
const now = Date.now();
let next = Infinity;
document.querySelectorAll<HTMLElement>("[data-haze-countdown][data-deadline]").forEach((root) => {
next = Math.min(next, update(root, now));
});
if (!document.hidden && Number.isFinite(next)) timer = window.setTimeout(refresh, next + 5);
}
if (!document.documentElement.hasAttribute("data-haze-countdown-listener")) {
document.documentElement.setAttribute("data-haze-countdown-listener", "");
document.addEventListener("astro:page-load", refresh);
document.addEventListener("visibilitychange", refresh);
window.addEventListener("pageshow", refresh);
refresh();
}
</script>When to use
- A launch or event starts at the same instant for every viewer.
- An announcement changes state when registration closes.
When not to use
- Show a clock counting up or a duration with no known end.
- Use progress to track completed work.
Installation
Add the Haze registry to components.json once, then install Countdown with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/countdownnpx shadcn@latest add @haze/countdownyarn dlx shadcn@latest add @haze/countdownbunx --bun shadcn@latest add @haze/countdownFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| target* | Date | number | string | – | Deadline as a Date, epoch milliseconds or ISO date/time. A missing offset means UTC. |
| label | string | Time remaining | Visible name of the timer. |
| completeLabel | string | Live now | Replaces the clock at the deadline. |
| units | ('days' | 'hours' | 'minutes' | 'seconds')[] | – | Shown largest first. The largest selected unit includes omitted larger units. |
| variant | 'display' | 'compact' | display | Segmented digit tiles or a compact inline readout. |
| class | string | – | Classes applied to the timer wrapper. |
Accessibility
- A readable UTC deadline is available before the clock enhances.
- The timer exposes remaining time on demand and announces completion once. Only changed digits move when motion is enabled.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI component "Countdown" with `npx shadcn@latest add @haze/countdown`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import Countdown from "@/components/haze/ui/countdown.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: http://localhost:4329/ui/countdown.md
Customize with real content
Adapt the Haze countdown ui for our product. Replace the demo values of these props with our real content: target, label, completeLabel, units, variant, class. Keep the layout, the heading level rules and these accessibility details: A readable UTC deadline is available before the clock enhances. The timer exposes remaining time on demand and announces completion once. Only changed digits move when motion is enabled. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using countdown, check it fits: use it when a launch or event starts at the same instant for every viewer.; an announcement changes state when registration closes.. Avoid it when show a clock counting up or a duration with no known end.; use progress to track completed work.. Alternatives: @haze/progress, @haze/animated-number.
Dependencies
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.