All components plainsurfacesmmdlg
Timer
Countdown and stopwatch with a large tabular readout and start, pause, resume and reset controls.
05
00
1234567891011121314151617181920212223242526import { Timer } from "#components/ui/ui-sdk/timer.tsx";import { indigoPalette } from "@stylexblocks/ui/themes/palettes.ts";
export function Example() { return ( // UI SDK has no timer primitive: Root runs a requestAnimationFrame // clock; Area is role="timer" and completion is announced once. // render / children functions receive the timer API as state <Timer.Root countdown startMs={5 * 60 * 1000} variant="plain" size="md" palette={indigoPalette}> <Timer.Area> <Timer.Item type="minutes" /> <Timer.Separator>:</Timer.Separator> <Timer.Item type="seconds" /> </Timer.Area> <Timer.Control> <Timer.ActionTrigger action="start">Start</Timer.ActionTrigger> <Timer.ActionTrigger action="pause">Pause</Timer.ActionTrigger> <Timer.ActionTrigger action="resume">Resume</Timer.ActionTrigger> <Timer.ActionTrigger action="reset">Reset</Timer.ActionTrigger> </Timer.Control> </Timer.Root> );}
// stopwatch: <Timer.Root startMs={0}> (add targetMs to stop at a limit)// completion: <Timer.Root onComplete={() => ...} completeLabel="Time's up">Variants
05
00
05
00
Sizes
05
00
05
00
05
00
Stopwatch
Without countdown the timer counts up from startMs; a 10ms interval drives the milliseconds item. Restart zeroes it and keeps running.
00
00
000
Completion
The readout is role="timer", so screen readers stay quiet while it ticks; a polite live region announces once when the countdown reaches zero.
00
10
Install
1npx stylexblocks add timerSource
components/ui/ui-sdk/timer.tsx
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502import * as stylex from "@stylexjs/stylex";import { createContext, useContext, useEffect, useMemo, useRef, useState } from "react";import { mergeProps, renderElement, type PartProps } from "@ui-sdk/react/primitive";import { createSlotRecipeContext } from "#lib/ui-sdk/create-slot-recipe-context.tsx";import { defineSlotRecipe } from "#lib/recipe-props.ts";import { colorPalette } from '@stylexblocks/ui/color-palette.stylex.ts'import { durations } from '@stylexblocks/ui/tokens/durations.stylex.ts'import { fontSizes } from '@stylexblocks/ui/tokens/font-sizes.stylex.ts'import { fontWeights } from '@stylexblocks/ui/tokens/font-weights.stylex.ts'import { letterSpacings } from '@stylexblocks/ui/tokens/letter-spacings.stylex.ts'import { lineHeights } from '@stylexblocks/ui/tokens/line-heights.stylex.ts'import { semanticColors } from '@stylexblocks/ui/semantic-tokens/colors.stylex.ts'import { semanticRadii } from '@stylexblocks/ui/semantic-tokens/radii.stylex.ts'import { semanticShadows } from '@stylexblocks/ui/semantic-tokens/shadows.stylex.ts'import { sizes } from '@stylexblocks/ui/tokens/sizes.stylex.ts'import { spacing } from '@stylexblocks/ui/tokens/spacing.stylex.ts'
const timerRoot = stylex.create({ base: { display: 'inline-flex', flexDirection: 'column', alignItems: 'center', gap: spacing._4, color: semanticColors.fg, },})
const timerRootSizes = stylex.create({ sm: { '--timer-font-size': fontSizes._2xl, '--timer-item-px': spacing._1_5, '--timer-item-py': spacing._1, '--timer-trigger-height': sizes.controlXs, '--timer-trigger-px': spacing._2, '--timer-trigger-font-size': fontSizes.xs, }, md: { '--timer-font-size': fontSizes._4xl, '--timer-item-px': spacing._2, '--timer-item-py': spacing._1, '--timer-trigger-height': sizes.controlSm, '--timer-trigger-px': spacing._2_5, '--timer-trigger-font-size': fontSizes.sm, }, lg: { '--timer-font-size': fontSizes._6xl, '--timer-item-px': spacing._3, '--timer-item-py': spacing._1_5, '--timer-trigger-height': sizes.controlMd, '--timer-trigger-px': spacing._3, '--timer-trigger-font-size': fontSizes.sm, },})
/** The time readout: one big line of tabular numerals. */const timerArea = stylex.create({ base: { display: 'flex', alignItems: 'center', gap: spacing._1, fontSize: 'var(--timer-font-size)', lineHeight: 1, fontWeight: fontWeights.semibold, letterSpacing: letterSpacings.tight, fontVariantNumeric: 'tabular-nums', },})
const timerItem = stylex.create({ base: { minWidth: '2ch', textAlign: 'center', fontVariantNumeric: 'tabular-nums', },})
const timerItemVariants = stylex.create({ plain: {}, surface: { paddingInline: 'var(--timer-item-px)', paddingBlock: 'var(--timer-item-py)', borderRadius: semanticRadii.panel, backgroundColor: colorPalette.subtle, color: colorPalette.fg, boxShadow: `inset 0 0 0 1px ${colorPalette.border}`, },})
const timerSeparator = stylex.create({ base: { color: semanticColors.fgSubtle, fontWeight: fontWeights.medium, userSelect: 'none', },})
const timerControl = stylex.create({ base: { display: 'flex', alignItems: 'center', gap: spacing._2, },})
/** Start / pause / resume / reset buttons, styled like a `surface` Button. */const timerActionTrigger = stylex.create({ base: { display: { default: 'inline-flex', ':is([hidden])': 'none', }, alignItems: 'center', justifyContent: 'center', gap: spacing._1_5, appearance: 'none', flexShrink: 0, userSelect: 'none', whiteSpace: 'nowrap', height: 'var(--timer-trigger-height)', minWidth: 'var(--timer-trigger-height)', paddingInline: 'var(--timer-trigger-px)', borderRadius: semanticRadii.control, fontFamily: 'inherit', fontSize: 'var(--timer-trigger-font-size)', lineHeight: lineHeights.sm, fontWeight: fontWeights.medium, color: colorPalette.fg, backgroundColor: { default: semanticColors.bg, ':hover': colorPalette.muted, }, borderWidth: '1px', borderStyle: 'solid', borderColor: { default: `color-mix(in oklch, ${colorPalette.emphasized} 90%, transparent)`, ':hover': colorPalette.emphasized, }, boxShadow: semanticShadows.xs, cursor: { default: 'pointer', ':is(:disabled, [disabled], [data-disabled])': 'not-allowed', }, opacity: { default: null, ':is(:disabled, [disabled], [data-disabled])': 0.5, }, transitionProperty: 'background-color, border-color, color, box-shadow', transitionDuration: durations.moderate, outlineWidth: { default: null, ':focus-visible': '1px', }, outlineOffset: { default: null, ':focus-visible': '2px', }, outlineStyle: { default: 'none', ':focus-visible': 'solid', }, outlineColor: { default: null, ':focus-visible': colorPalette.focusRing, }, },})
export type TimerSize = keyof typeof timerRootSizes
export type TimerVariant = keyof typeof timerItemVariants
const timerRecipe = defineSlotRecipe({ slots: { root: { styles: timerRoot, sizes: timerRootSizes }, area: { styles: timerArea }, item: { styles: timerItem, variants: timerItemVariants }, separator: { styles: timerSeparator }, control: { styles: timerControl }, actionTrigger: { styles: timerActionTrigger }, }, defaultVariants: { size: "md", variant: "plain" },});
const chrome = stylex.create({ srOnly: { position: "absolute", width: "1px", height: "1px", padding: 0, margin: "-1px", overflow: "hidden", clip: "rect(0, 0, 0, 0)", whiteSpace: "nowrap", borderWidth: 0, },});
export interface Time<T = number> { days: T; hours: T; minutes: T; seconds: T; milliseconds: T;}
export type TimePart = keyof Time;export type TimerAction = "start" | "pause" | "resume" | "reset" | "restart";
export interface TimerTickDetails { value: number; time: Time; formattedTime: Time<string>;}
function msToTime(ms: number): Time { const t = Math.max(0, ms); return { days: Math.floor(t / 86_400_000), hours: Math.floor(t / 3_600_000) % 24, minutes: Math.floor(t / 60_000) % 60, seconds: Math.floor(t / 1000) % 60, milliseconds: t % 1000, };}
const pad = (n: number, size = 2) => String(n).padStart(size, "0");
function formatTime(time: Time): Time<string> { return { days: pad(time.days), hours: pad(time.hours), minutes: pad(time.minutes), seconds: pad(time.seconds), milliseconds: pad(time.milliseconds, 3), };}
export interface TimerApi { running: boolean; paused: boolean; /** Current value in milliseconds. */ value: number; time: Time; formattedTime: Time<string>; /** 0–1 progress from `startMs` toward `targetMs`. */ progressPercent: number; start: () => void; pause: () => void; resume: () => void; reset: () => void; restart: () => void;}
const TimerContext = createContext<TimerApi | null>(null);
function useTimer() { const ctx = useContext(TimerContext); if (!ctx) throw new Error("Timer parts must be rendered inside <Timer.Root>"); return ctx;}
export type TimerRootOwnProps = { /** Count down from `startMs` to `targetMs` (default 0) instead of up. */ countdown?: boolean; /** Starting value in milliseconds. */ startMs?: number; /** Value at which the timer completes (required for a stopwatch to stop). */ targetMs?: number; /** Start running on mount. */ autoStart?: boolean; /** Tick granularity in milliseconds. */ interval?: number; onTick?: (details: TimerTickDetails) => void; onComplete?: () => void; /** Announced to screen readers when the timer reaches its target. */ completeLabel?: string;};
type Status = "idle" | "running" | "paused";
function RootNode({ render, countdown = false, startMs = 0, targetMs, autoStart = false, interval = 1000, onTick, onComplete, completeLabel = "Timer complete", children, ...rest}: PartProps<"div", TimerApi> & TimerRootOwnProps) { const [status, setStatus] = useState<Status>(autoStart ? "running" : "idle"); const [currentMs, setCurrentMs] = useState(startMs); const [announcement, setAnnouncement] = useState(""); // bumped by reset/restart so a running clock re-anchors its origin const [epoch, setEpoch] = useState(0); const target = targetMs ?? (countdown ? 0 : undefined);
const valueRef = useRef(currentMs); valueRef.current = currentMs; const callbacks = useRef({ onTick, onComplete, completeLabel }); callbacks.current = { onTick, onComplete, completeLabel };
// requestAnimationFrame clock: whole intervals are accounted against a // fixed origin, so a throttled background tab catches up on return. useEffect(() => { if (status !== "running") return; let origin = performance.now(); let frame = requestAnimationFrame(function loop(now) { const steps = Math.floor((now - origin) / interval); if (steps > 0) { origin += steps * interval; const sign = countdown ? -1 : 1; let next = valueRef.current + sign * steps * interval; if (target != null) next = countdown ? Math.max(next, target) : Math.min(next, target); valueRef.current = next; setCurrentMs(next); const time = msToTime(next); callbacks.current.onTick?.({ value: next, time, formattedTime: formatTime(time) }); if (target != null && (countdown ? next <= target : next >= target)) { setStatus("idle"); setAnnouncement(callbacks.current.completeLabel); callbacks.current.onComplete?.(); return; } } frame = requestAnimationFrame(loop); }); return () => cancelAnimationFrame(frame); }, [status, epoch, interval, countdown, target]);
const api = useMemo<TimerApi>(() => { const time = msToTime(currentMs); const range = (target ?? 0) - startMs; const progress = range === 0 ? 0 : (currentMs - startMs) / range; const run = () => { setAnnouncement(""); setStatus("running"); }; return { running: status === "running", paused: status === "paused", value: currentMs, time, formattedTime: formatTime(time), progressPercent: Math.min(Math.max(progress, 0), 1), start: () => { if (status === "idle") run(); }, pause: () => { if (status === "running") setStatus("paused"); }, resume: () => { if (status === "paused") run(); }, reset: () => { valueRef.current = startMs; setCurrentMs(startMs); setEpoch((e) => e + 1); if (status === "paused") setStatus("idle"); }, restart: () => { valueRef.current = startMs; setCurrentMs(startMs); setEpoch((e) => e + 1); run(); }, }; }, [status, currentMs, startMs, target]);
const element = renderElement( "div", mergeProps( { "data-state": status, children: ( <> {typeof children === "function" ? children(api) : children} <span role="status" aria-live="polite" {...stylex.props(chrome.srOnly)}> {announcement} </span> </> ), }, rest, ), render, api, ); return <TimerContext.Provider value={api}>{element}</TimerContext.Provider>;}
function AreaNode({ render, ...rest }: PartProps<"div", TimerApi>) { const api = useTimer(); const { days, hours, minutes, seconds } = api.formattedTime; return renderElement( "div", mergeProps( { // role="timer" is implicitly aria-live="off": no per-tick chatter role: "timer", "aria-atomic": true, "aria-label": `${Number(days)} days ${hours}:${minutes}:${seconds}`, }, rest, ), render, api, );}
function ItemNode({ render, type, ...rest}: PartProps<"div", TimerApi> & { type: TimePart }) { const api = useTimer(); return renderElement( "div", mergeProps( { "data-type": type, style: { "--value": api.time[type] } as React.CSSProperties, children: api.formattedTime[type], }, rest, ), render, api, );}
function SeparatorNode({ render, ...rest }: PartProps<"div">) { return renderElement("div", mergeProps({ "aria-hidden": true }, rest), render);}
function ActionTriggerNode({ render, action, ...rest}: PartProps<"button", TimerApi> & { action: TimerAction }) { const api = useTimer(); const idle = !api.running && !api.paused; const hidden = { start: !idle, pause: !api.running, resume: !api.paused, reset: idle, restart: false, }[action]; return renderElement( "button", mergeProps( { type: "button" as const, hidden, "data-action": action, onClick: (event: React.MouseEvent) => { if (!event.defaultPrevented) api[action](); }, }, rest, ), render, api, );}
/** Render-prop access to the timer API, like Ark's `Timer.Context`. */function TimerContextConsumer({ children }: { children: (api: TimerApi) => React.ReactNode }) { return <>{children(useTimer())}</>;}
const { withProvider, withContext } = createSlotRecipeContext(timerRecipe);
/** * Timer — a countdown or stopwatch. UI SDK ships no timer primitive, so * Root runs the clock itself (requestAnimationFrame, whole `interval` * ticks) with start / pause / resume / reset / restart, counting down from * `startMs` with `countdown` or up toward an optional `targetMs`. * `<Timer.Root variant size>` resolves the recipe once; every part inherits * it through context. Area is `role="timer"` (silent while running); a * polite live region announces completion once. ActionTriggers hide when * their action doesn't apply. Composition per part via `render`, whose * function form (and Root's `children` function) receives the timer API. */export const Timer = { Root: withProvider(RootNode, "root", "TimerRoot"), Area: withContext(AreaNode, "area", "TimerArea"), Item: withContext(ItemNode, "item", "TimerItem"), Separator: withContext(SeparatorNode, "separator", "TimerSeparator"), Control: withContext("div", "control", "TimerControl"), ActionTrigger: withContext(ActionTriggerNode, "actionTrigger", "TimerActionTrigger"), Context: TimerContextConsumer,};
export type TimerRootProps = React.ComponentProps<typeof Timer.Root>;export type TimerItemProps = React.ComponentProps<typeof Timer.Item>;export type TimerActionTriggerProps = React.ComponentProps<typeof Timer.ActionTrigger>;