Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(Timer): add non-rendering elapsed time (#6438)

Cindy Zhang1d940e032cab
diff --git a/.changeset/add-non-rendering-timer.md b/.changeset/add-non-rendering-timer.md
new file mode 100644
index 0000000000..35acb17d81
--- /dev/null
+++ b/.changeset/add-non-rendering-timer.md
@@ -0,0 +1,11 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Add Timer for standardized elapsed durations without React tick renders.
+
+Use `Timer` for active-operation elapsed time. It starts from mount by default,
+accepts an earlier Unix-millisecond `startTime`, offers `elapsed` and `clock`
+formats with adaptive cadence, and matches Timestamp typography props.
+
+@cixzhang
diff --git a/apps/docsite/scripts/generate-data.mjs b/apps/docsite/scripts/generate-data.mjs
index 870ea0ab11..dcfbae8fd2 100644
--- a/apps/docsite/scripts/generate-data.mjs
+++ b/apps/docsite/scripts/generate-data.mjs
@@ -411,6 +411,7 @@ function generatePackageRegistry() {
description: raw.description || '',
packagePath: dir,
canaryOnly,
+ packageExports: raw.exports ?? null,
peerDependencies: raw.peerDependencies ?? {},
hasReadme,
hasChangelog,
@@ -421,6 +422,9 @@ function generatePackageRegistry() {
.filter(Boolean)
.sort((a, b) => a.name.localeCompare(b.name));
+ const publicPackages = packages.map(
+ ({packageExports: _packageExports, ...pkg}) => pkg,
+ );
const content = `// Auto-generated by scripts/generate-data.mjs — do not edit
export interface PackageMeta {
@@ -437,7 +441,7 @@ export interface PackageMeta {
changelog: string | null;
}
-export const packages: PackageMeta[] = ${JSON.stringify(packages, null, 2)};
+export const packages: PackageMeta[] = ${JSON.stringify(publicPackages, null, 2)};
`;
writeRegistry('packageRegistry.ts', content);
return packages;
diff --git a/apps/docsite/scripts/generate-shadcn-registry.mjs b/apps/docsite/scripts/generate-shadcn-registry.mjs
index 5431377e72..5d27705f88 100644
--- a/apps/docsite/scripts/generate-shadcn-registry.mjs
+++ b/apps/docsite/scripts/generate-shadcn-registry.mjs
@@ -61,6 +61,27 @@ function packageNameFromSpecifier(specifier) {
return specifier.split('/')[0];
}
+function packageExportsSpecifier(pkg, specifier) {
+ const packageExports = pkg.packageExports;
+ if (packageExports == null) return true;
+
+ const subpath = specifier.slice(pkg.name.length);
+ const exportKey = subpath ? `.${subpath}` : '.';
+ if (typeof packageExports === 'string' || Array.isArray(packageExports)) {
+ return exportKey === '.';
+ }
+ if (Object.hasOwn(packageExports, exportKey)) return true;
+
+ return Object.keys(packageExports).some(key => {
+ const wildcardIndex = key.indexOf('*');
+ if (wildcardIndex === -1) return false;
+ return (
+ exportKey.startsWith(key.slice(0, wildcardIndex)) &&
+ exportKey.endsWith(key.slice(wildcardIndex + 1))
+ );
+ });
+}
+
function readImportSpecifiers(source, fileName) {
const sourceFile = ts.createSourceFile(
fileName,
@@ -566,9 +587,21 @@ export function buildShadcnRegistry({
),
)
.sort((a, b) => a.name.localeCompare(b.name));
+ const packageCatalog = new Map(packages.map(pkg => [pkg.name, pkg]));
const blockItems = [];
let skippedUnpublishedBlocks = 0;
for (const block of blocks) {
+ const unpublishedComponentImport = readImportSpecifiers(
+ block.source,
+ `${block.dirName}.tsx`,
+ ).find(specifier => {
+ const pkg = packageCatalog.get(packageNameFromSpecifier(specifier));
+ return pkg != null && !packageExportsSpecifier(pkg, specifier);
+ });
+ if (unpublishedComponentImport) {
+ skippedUnpublishedBlocks++;
+ continue;
+ }
try {
blockItems.push(
blockItem(
diff --git a/apps/storybook/stories/Timer.stories.tsx b/apps/storybook/stories/Timer.stories.tsx
new file mode 100644
index 0000000000..8ba371069c
--- /dev/null
+++ b/apps/storybook/stories/Timer.stories.tsx
@@ -0,0 +1,92 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {useState} from 'react';
+import type {Meta, StoryObj} from '@storybook/react';
+import {Timer} from '@astryxdesign/core/Timer';
+import {Stack} from '@astryxdesign/core/Layout';
+import {Text} from '@astryxdesign/core/Text';
+
+const meta: Meta<typeof Timer> = {
+ title: 'Core/Timer',
+ component: Timer,
+ tags: ['autodocs'],
+ argTypes: {
+ startTime: {
+ control: 'number',
+ description: 'Operation start as Unix milliseconds',
+ },
+ format: {
+ control: 'select',
+ options: ['elapsed', 'clock'],
+ description: 'Standard elapsed or stopwatch representation',
+ },
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof Timer>;
+
+function FormatsStory() {
+ const [startedAt] = useState(() => Date.now() - 3_753_000);
+ return (
+ <Stack direction="vertical" gap={3}>
+ <Stack direction="horizontal" gap={2} vAlign="center">
+ <Text type="supporting" color="secondary">
+ Elapsed
+ </Text>
+ <Timer startTime={startedAt} type="body" color="primary" />
+ </Stack>
+ <Stack direction="horizontal" gap={2} vAlign="center">
+ <Text type="supporting" color="secondary">
+ Clock
+ </Text>
+ <Timer
+ format="clock"
+ startTime={startedAt}
+ type="body"
+ color="primary"
+ />
+ </Stack>
+ </Stack>
+ );
+}
+
+function EarlierStartStory() {
+ const [startedAt] = useState(() => Date.now() - 65_000);
+ return <Timer startTime={startedAt} />;
+}
+
+function TypographyStory() {
+ const [startedAt] = useState(() => Date.now() - 128_000);
+ return (
+ <Timer
+ startTime={startedAt}
+ type="body"
+ size="lg"
+ color="primary"
+ weight="semibold"
+ />
+ );
+}
+
+export const Default: Story = {};
+
+export const Formats: Story = {
+ render: () => <FormatsStory />,
+};
+
+export const WaitingMessage: Story = {
+ render: () => (
+ <Text type="body" color="primary">
+ Processing for <Timer type="inherit" color="inherit" />
+ </Text>
+ ),
+};
+
+export const EarlierStart: Story = {
+ render: () => <EarlierStartStory />,
+};
+
+export const Typography: Story = {
+ render: () => <TypographyStory />,
+};
diff --git a/internal/shadcn-registry/generate-shadcn-registry.test.mjs b/internal/shadcn-registry/generate-shadcn-registry.test.mjs
index cdfe5ccdd4..21a4d1f9d3 100644
--- a/internal/shadcn-registry/generate-shadcn-registry.test.mjs
+++ b/internal/shadcn-registry/generate-shadcn-registry.test.mjs
@@ -61,8 +61,19 @@ const SHADCN_ENTRY = createRequire(
).resolve('shadcn');
const packages = [
- {name: '@astryxdesign/cli', version: '0.6.0'},
- {name: '@astryxdesign/core', version: '0.5.2'},
+ {
+ name: '@astryxdesign/cli',
+ version: '0.6.0',
+ packageExports: {'.': './dist/index.js', './api': './dist/api.js'},
+ },
+ {
+ name: '@astryxdesign/core',
+ version: '0.5.2',
+ packageExports: {
+ '.': './dist/index.js',
+ './Button': './dist/Button/index.js',
+ },
+ },
];
function fixture(overrides = {}) {
@@ -282,6 +293,27 @@ describe('buildShadcnRegistry', () => {
]);
});
+ it('skips blocks whose component import is not published', () => {
+ const input = fixture();
+ input.blocks.push({
+ ...input.blocks[0],
+ dirName: 'TimerShowcase',
+ name: 'Timer',
+ displayName: 'Timer',
+ exampleFor: 'Timer',
+ source:
+ "import {Timer} from '@astryxdesign/core/Timer';\n" +
+ 'export default function TimerShowcase() { return <Timer />; }\n',
+ });
+
+ const {items, counts} = buildShadcnRegistry(input);
+
+ expect(items.map(item => item.name)).not.toContain(
+ 'showcase-timer-default',
+ );
+ expect(counts.skippedUnpublishedBlocks).toBe(1);
+ });
+
it('writes canonical nested paths and compatibility aliases', () => {
const outDir = mkdtempSync(path.join(tmpdir(), 'astryx-shadcn-routes-'));
try {
diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json
index 4e4ae7f03c..e00f21b441 100644
--- a/internal/shadcn-registry/routes.lock.json
+++ b/internal/shadcn-registry/routes.lock.json
@@ -1001,6 +1001,11 @@
"path": "components/time-input",
"aliases": []
},
+ {
+ "name": "component-timer",
+ "path": "components/timer",
+ "aliases": []
+ },
{
"name": "component-timestamp",
"path": "components/timestamp",
@@ -3155,6 +3160,21 @@
"path": "examples/time-input/states",
"aliases": []
},
+ {
+ "name": "example-timer-formats",
+ "path": "examples/timer/formats",
+ "aliases": []
+ },
+ {
+ "name": "example-timer-inline",
+ "path": "examples/timer/inline",
+ "aliases": []
+ },
+ {
+ "name": "example-timer-typography",
+ "path": "examples/timer/typography",
+ "aliases": []
+ },
{
"name": "example-timestamp-auto",
"path": "examples/timestamp/auto",
@@ -4530,6 +4550,11 @@
"path": "showcases/time-input/default",
"aliases": []
},
+ {
+ "name": "showcase-timer-default",
+ "path": "showcases/timer/default",
+ "aliases": []
+ },
{
"name": "showcase-timestamp-default",
"path": "showcases/timestamp/default",
diff --git a/packages/cli/assets/templates/blocks/components/Timer/TimerFormats.doc.mjs b/packages/cli/assets/templates/blocks/components/Timer/TimerFormats.doc.mjs
new file mode 100644
index 0000000000..513c05b32e
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Timer/TimerFormats.doc.mjs
@@ -0,0 +1,14 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
+export const doc = {
+ type: 'block',
+ exampleFor: 'Timer',
+ name: 'Timer — Formats',
+ displayName: 'Timer — Formats',
+ description:
+ 'Elapsed compact units and stopwatch clock notation shown from the same start time.',
+ isReady: true,
+ aspectRatio: 16 / 9,
+ componentsUsed: ['Timer', 'Layout', 'Text'],
+};
diff --git a/packages/cli/assets/templates/blocks/components/Timer/TimerFormats.tsx b/packages/cli/assets/templates/blocks/components/Timer/TimerFormats.tsx
new file mode 100644
index 0000000000..6b928d6d8e
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Timer/TimerFormats.tsx
@@ -0,0 +1,34 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import {useState} from 'react';
+import {Timer} from '@astryxdesign/core/Timer';
+import {Stack} from '@astryxdesign/core/Layout';
+import {Text} from '@astryxdesign/core/Text';
+
+export default function TimerFormats() {
+ const [startedAt] = useState(() => Date.now() - 3_753_000);
+
+ return (
+ <Stack direction="vertical" gap={3}>
+ <Stack direction="horizontal" gap={3} vAlign="center">
+ <Text type="supporting" color="secondary">
+ Elapsed
+ </Text>
+ <Timer startTime={startedAt} type="body" color="primary" />
+ </Stack>
+ <Stack direction="horizontal" gap={3} vAlign="center">
+ <Text type="supporting" color="secondary">
+ Clock
+ </Text>
+ <Timer
+ format="clock"
+ startTime={startedAt}
+ type="body"
+ color="primary"
+ />
+ </Stack>
+ </Stack>
+ );
+}
diff --git a/packages/cli/assets/templates/blocks/components/Timer/TimerInline.doc.mjs b/packages/cli/assets/templates/blocks/components/Timer/TimerInline.doc.mjs
new file mode 100644
index 0000000000..e0b9f0e45e
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Timer/TimerInline.doc.mjs
@@ -0,0 +1,14 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
+export const doc = {
+ type: 'block',
+ exampleFor: 'Timer',
+ name: 'Timer — Inline',
+ displayName: 'Timer — Inline',
+ description:
+ 'A Timer composed into status copy while inheriting the surrounding typography.',
+ isReady: true,
+ aspectRatio: 16 / 9,
+ componentsUsed: ['Timer', 'Text'],
+};
diff --git a/packages/cli/assets/templates/blocks/components/Timer/TimerInline.tsx b/packages/cli/assets/templates/blocks/components/Timer/TimerInline.tsx
new file mode 100644
index 0000000000..cdb29e8518
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Timer/TimerInline.tsx
@@ -0,0 +1,14 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import {Timer} from '@astryxdesign/core/Timer';
+import {Text} from '@astryxdesign/core/Text';
+
+export default function TimerInline() {
+ return (
+ <Text type="body" color="primary">
+ Processing for <Timer type="inherit" color="inherit" />
+ </Text>
+ );
+}
diff --git a/packages/cli/assets/templates/blocks/components/Timer/TimerShowcase.doc.mjs b/packages/cli/assets/templates/blocks/components/Timer/TimerShowcase.doc.mjs
new file mode 100644
index 0000000000..b8d97a9838
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Timer/TimerShowcase.doc.mjs
@@ -0,0 +1,13 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
+export const doc = {
+ type: 'block',
+ exampleFor: 'Timer',
+ name: 'Timer',
+ displayName: 'Timer',
+ isReady: true,
+ aspectRatio: 16 / 9,
+ isShowcase: true,
+ componentsUsed: ['Timer', 'Layout', 'Text'],
+};
diff --git a/packages/cli/assets/templates/blocks/components/Timer/TimerShowcase.tsx b/packages/cli/assets/templates/blocks/components/Timer/TimerShowcase.tsx
new file mode 100644
index 0000000000..88c6684d17
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Timer/TimerShowcase.tsx
@@ -0,0 +1,47 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import {useState} from 'react';
+import {Timer} from '@astryxdesign/core/Timer';
+import {Stack} from '@astryxdesign/core/Layout';
+import {Text} from '@astryxdesign/core/Text';
+
+export default function TimerShowcase() {
+ const [startedAt] = useState(() => Date.now() - 3_753_000);
+
+ return (
+ <Stack direction="vertical" gap={4}>
+ <Text type="large" color="primary" weight="semibold">
+ Processing
+ </Text>
+ <Stack direction="horizontal" gap={6} vAlign="center">
+ <Stack direction="vertical" gap={1}>
+ <Text type="supporting" color="secondary">
+ Elapsed
+ </Text>
+ <Timer
+ startTime={startedAt}
+ type="body"
+ size="xl"
+ color="primary"
+ weight="semibold"
+ />
+ </Stack>
+ <Stack direction="vertical" gap={1}>
+ <Text type="supporting" color="secondary">
+ Clock
+ </Text>
+ <Timer
+ format="clock"
+ startTime={startedAt}
+ type="body"
+ size="xl"
+ color="primary"
+ weight="semibold"
+ />
+ </Stack>
+ </Stack>
+ </Stack>
+ );
+}
diff --git a/packages/cli/assets/templates/blocks/components/Timer/TimerTypography.doc.mjs b/packages/cli/assets/templates/blocks/components/Timer/TimerTypography.doc.mjs
new file mode 100644
index 0000000000..ac54ea06d2
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Timer/TimerTypography.doc.mjs
@@ -0,0 +1,14 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
+export const doc = {
+ type: 'block',
+ exampleFor: 'Timer',
+ name: 'Timer — Typography',
+ displayName: 'Timer — Typography',
+ description:
+ 'Timer using its Timestamp-matched default typography and an emphasized override.',
+ isReady: true,
+ aspectRatio: 16 / 9,
+ componentsUsed: ['Timer', 'Layout', 'Text'],
+};
diff --git a/packages/cli/assets/templates/blocks/components/Timer/TimerTypography.tsx b/packages/cli/assets/templates/blocks/components/Timer/TimerTypography.tsx
new file mode 100644
index 0000000000..9e4f6a656d
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Timer/TimerTypography.tsx
@@ -0,0 +1,31 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import {useState} from 'react';
+import {Timer} from '@astryxdesign/core/Timer';
+import {Stack} from '@astryxdesign/core/Layout';
+import {Text} from '@astryxdesign/core/Text';
+
+export default function TimerTypography() {
+ const [startedAt] = useState(() => Date.now() - 128_000);
+
+ return (
+ <Stack direction="vertical" gap={3}>
+ <Text type="supporting" color="secondary">
+ Default
+ </Text>
+ <Timer startTime={startedAt} />
+ <Text type="supporting" color="secondary">
+ Emphasized
+ </Text>
+ <Timer
+ startTime={startedAt}
+ type="body"
+ size="xl"
+ color="primary"
+ weight="semibold"
+ />
+ </Stack>
+ );
+}
diff --git a/packages/core/package.json b/packages/core/package.json
index e4778b3d63..4a7b823b6c 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -539,6 +539,11 @@
"types": "./dist/TimeInput/index.d.ts",
"default": "./dist/TimeInput/index.js"
},
+ "./Timer": {
+ "source": "./src/Timer/index.ts",
+ "types": "./dist/Timer/index.d.ts",
+ "default": "./dist/Timer/index.js"
+ },
"./Timestamp": {
"source": "./src/Timestamp/index.ts",
"types": "./dist/Timestamp/index.d.ts",
diff --git a/packages/core/src/Timer/Timer.doc.mjs b/packages/core/src/Timer/Timer.doc.mjs
new file mode 100644
index 0000000000..049813da1f
--- /dev/null
+++ b/packages/core/src/Timer/Timer.doc.mjs
@@ -0,0 +1,183 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').ComponentAnatomyElement[]} */
+const anatomy = [
+ {
+ name: 'Elapsed time',
+ required: true,
+ description:
+ 'Semantic time element containing a standardized elapsed duration.',
+ },
+];
+
+/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */
+export const docs = {
+ name: 'Timer',
+ displayName: 'Timer',
+ category: 'Content',
+ keywords: [
+ 'timer',
+ 'elapsed',
+ 'duration',
+ 'seconds',
+ 'minutes',
+ 'hours',
+ 'stopwatch',
+ 'waiting',
+ 'loading',
+ 'processing',
+ ],
+ props: [
+ {
+ name: 'startTime',
+ type: 'number',
+ description:
+ "Unix time in milliseconds when the measured operation began. Omit it to start from this Timer's mount.",
+ },
+ {
+ name: 'format',
+ type: "'elapsed' | 'clock'",
+ description:
+ 'Standard duration representation. Elapsed uses compact units and drops seconds after one hour; clock uses m:ss or h:mm:ss.',
+ default: "'elapsed'",
+ },
+ {
+ name: 'type',
+ type: "'body' | 'large' | 'label' | 'supporting' | 'code' | 'display-1' | 'display-2' | 'display-3' | 'inherit'",
+ description:
+ 'Semantic text type. Uses the same typography behavior as Timestamp.',
+ default: "'supporting'",
+ },
+ {
+ name: 'size',
+ type: "'4xs' | '3xs' | '2xs' | 'xsm' | 'sm' | 'base' | 'lg' | 'xl' | '2xl' | '3xl' | '4xl'",
+ description: 'Explicit font size override. Overrides the size from type.',
+ },
+ {
+ name: 'color',
+ type: "'primary' | 'secondary' | 'disabled' | 'placeholder' | 'accent' | 'inherit'",
+ description: 'Text color.',
+ default: "'secondary'",
+ },
+ {
+ name: 'weight',
+ type: "'normal' | 'medium' | 'semibold' | 'bold'",
+ description: 'Font weight override.',
+ },
+ {
+ name: 'xstyle',
+ type: 'StyleXStyles',
+ description:
+ 'StyleX styles for the Text wrapper. Must be a stylex.create() value.',
+ },
+ {
+ name: 'className',
+ type: 'string',
+ description:
+ 'CSS class name for the Text wrapper. Prefer xstyle for styling.',
+ },
+ {
+ name: 'style',
+ type: 'CSSProperties',
+ description:
+ 'Inline styles for the Text wrapper. Prefer xstyle for styling.',
+ },
+ ],
+ examples: [
+ {
+ label: 'Elapsed duration',
+ code: '<Timer />',
+ },
+ {
+ label: 'Stopwatch clock',
+ code: '<Timer format="clock" />',
+ },
+ {
+ label: 'Operation that started before mount',
+ code: '<Timer startTime={operationStartedAt} />',
+ },
+ {
+ label: 'Match surrounding text',
+ code: `<Text>
+ Processing for <Timer type="inherit" color="inherit" />
+</Text>`,
+ },
+ {
+ label: 'Prominent elapsed time',
+ code: '<Timer type="body" size="lg" color="primary" weight="semibold" />',
+ },
+ ],
+ theming: {
+ targets: [{className: 'astryx-timer'}],
+ },
+ usage: {
+ anatomy,
+ description:
+ 'Displays a standardized elapsed duration for active work without scheduling a React render on every tick. Elapsed format updates by second below one hour and by minute after one hour; clock format remains second-precise.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Use elapsed for compact duration text that may span seconds, minutes, or hours.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Use clock for stopwatch-like surfaces where seconds remain meaningful after an hour.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Pass startTime when the operation began before Timer mounted so the display reflects the complete wait.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Do not use Timer for dates, time zones, or relative calendar language; use Timestamp instead.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Do not add aria-live unless hearing an announcement every tick is appropriate for the specific task.',
+ },
+ ],
+ },
+};
+
+/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */
+export const docsDense = {
+ description:
+ 'Standardized elapsed or stopwatch duration with clock-derived, non-rendering DOM updates.',
+ propDescriptions: {
+ startTime:
+ "operation start as Unix milliseconds; omit to count from Timer's mount",
+ format: 'elapsed compact units or clock stopwatch notation',
+ type: 'semantic text type; defaults to supporting like Timestamp',
+ size: 'explicit font size override',
+ color: 'text color; defaults to secondary like Timestamp',
+ weight: 'font weight override',
+ xstyle: 'StyleX styles for the Text wrapper',
+ className: 'CSS class for the Text wrapper',
+ style: 'inline styles for the Text wrapper',
+ },
+ usage: {
+ anatomy,
+ description:
+ 'Use for active-operation elapsed time when periodic React renders would add avoidable work.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Use elapsed for compact durations and clock for stopwatch UI.',
+ },
+ {
+ guidance: true,
+ description: 'Pass startTime for work that began before mount.',
+ },
+ {
+ guidance: false,
+ description: 'Use Timestamp for dates and relative calendar language.',
+ },
+ ],
+ },
+};
diff --git a/packages/core/src/Timer/Timer.spec.md b/packages/core/src/Timer/Timer.spec.md
new file mode 100644
index 0000000000..a52d290b7b
--- /dev/null
+++ b/packages/core/src/Timer/Timer.spec.md
@@ -0,0 +1,215 @@
+---
+schema_version: 3
+template_version: 5
+kind: component
+id: component:Timer
+authority: current
+archive_reason: null
+superseded_by: null
+approved_by: cixzhang
+approved_at: 2026-09-22
+owners: [cixzhang]
+review_triggers: [public-api, behavior, theming, accessibility, react-runtime]
+verified_by:
+ [
+ packages/core/src/Timer/Timer.test.tsx,
+ packages/core/src/theme/themingTargets.test.ts,
+ scripts/check-knowledge.mjs,
+ ]
+modules: []
+families: []
+design_specs: []
+architecture:
+ [
+ architecture:public-component-api,
+ architecture:component-theming-surface,
+ architecture:react-component-runtime,
+ ]
+contributing: []
+system_specs:
+ [
+ spec:AST-002/DEC-1,
+ spec:AST-037/DEC-1,
+ spec:AST-037/DEC-2,
+ spec:AST-037/DEC-3,
+ ]
+---
+
+# Timer component contract
+
+## Contract at a glance
+
+| Area | Contract |
+| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Public contract | `Timer`, `TimerProps`, `TimerFormat`, optional `startTime` Unix milliseconds, `elapsed` or `clock` format, Timestamp-equivalent `type`, `size`, `color`, and `weight`, `<time>` ref, and `BaseProps<HTMLTimeElement>`. |
+| Behavior | One semantic duration uses a standardized seconds-to-hours ladder and updates its owned DOM node without React tick renders; elapsed output drops to minute cadence after one hour. |
+| End-user impact | People watching active work see a stable, consistent duration without unnecessary timer work competing with the surrounding interface. |
+| Builder impact | Zero-config starts on mount with Timestamp's supporting typography; callers choose only an earlier origin, standard format, or standard typography override. |
+| Compatibility/readiness | Additive first release implementing current `spec:AST-037`; no existing API or behavior changes. |
+| Review checks | Reject custom formatters/cadence, state-driven ticks, callback-count drift, post-hour elapsed second wakes, typography divergence from Timestamp, leaked resources, negative output, lost passthrough/ref behavior, unsolicited live announcements, or extra anatomy/targets. |
+| Governing rules | `spec:AST-037`; `architecture:public-component-api`; `architecture:react-component-runtime`; `architecture:component-theming-surface`. |
+
+This table is a review projection; the body below is authoritative.
+
+## Intent
+
+Timer is the stable Core projection of `spec:AST-037`. It presents a standardized
+elapsed duration for active work while keeping clock ticks outside React's render
+lifecycle. Its typography surface and defaults match Timestamp so the two temporal
+content components behave consistently.
+
+## Compatibility and migration
+
+- Released default preserved: `not yet released`
+- Compatibility class: additive component and type exports
+- Controlled/uncontrolled behavior: not applicable
+- Migration decision: `spec:AST-037/DEC-1`, `spec:AST-037/DEC-2`, and
+ `spec:AST-037/DEC-3`
+
+Consumer migration instructions belong in consumer docs and release notes.
+
+## Ownership boundary
+
+**Owns**
+
+- Elapsed calculation from mount or a finite caller origin.
+- The `elapsed` and `clock` representation ladders and their visible precision.
+- One `<time>` element, its visible value, synchronized ISO duration, and timer
+ resource lifecycle.
+- Avoiding React update commits for clock ticks.
+- Timestamp-equivalent `type`, `size`, `color`, and `weight` behavior.
+- The `timer` theming target on the Text wrapper.
+
+**Does not own / non-goals**
+
+- Loading indicators, waiting copy, status, or visibility — product composition.
+- Dates, relative calendar language, time zones, or absolute instants — Timestamp.
+- Pause, resume, countdown, deadlines, alarms, laps, sub-second precision, custom
+ formatters, or caller-controlled scheduling cadence.
+- Automatic live-region announcements.
+
+Countdown is deferred to a later contract. The standard formatting and scheduling
+helpers remain direction-independent so that extension does not require replacing
+the current format API.
+
+## Public concepts
+
+| Concept | Closed values or states | Meaning | Availability | Default | Owner | Stability | Invalid-value behavior |
+| --------------- | ----------------------------------------- | ---------------------------------------------------- | ------------ | ------------------------------------------------------------------------------ | ----------------- | --------- | ---------------------------------------------------------- |
+| Elapsed origin | Mount time or finite `startTime` | Unix-millisecond origin for elapsed duration | Always | Mount time | `component:Timer` | Stable | Non-finite values fall back to mount time |
+| Duration format | `elapsed`, `clock` | Compact units or stopwatch notation | Always | `elapsed` | `component:Timer` | Stable | Types reject other values; runtime falls back to `elapsed` |
+| Typography | `type`, `size`, `color`, `weight` | Same Text-backed surface and resolution as Timestamp | Always | Timestamp defaults: supporting type, secondary color, type-derived size/weight | Timestamp/Text | Stable | Existing Text type behavior |
+| Time surface | `<time>` with visible text and `dateTime` | Semantic elapsed duration and time-element props/ref | Always | Selected format's zero value and `PT0S` before client synchronization | `component:Timer` | Stable | Timer-owned `dateTime` wins |
+
+## Behavioral and layout contract
+
+| ID | Candidate invariant | Basis | Draft review state |
+| ---- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- | ------------------ |
+| FR1 | Timer MUST render one `<time>` element with selected-format text and matching non-negative ISO 8601 duration. | `spec:AST-037` FR1, FR3, FR5 | Settled |
+| FR2 | Omitted or non-finite `startTime` MUST use the mount origin; a finite value MUST use that caller origin. | `spec:AST-037` FR2 | Settled |
+| FR3 | Ticks MUST recompute from the clock and origin, directly update the owned node, and produce zero React update commits. | `spec:AST-037` FR3–FR4 | Settled |
+| FR4 | Prop changes MUST take effect without remounting or duplicate resources; every setup MUST clean up its resource. | `spec:AST-037` FR6–FR7 | Settled |
+| FR5 | `type`, `size`, `color`, `weight`, `xstyle`, `className`, and `style` MUST resolve on the Text wrapper exactly as Timestamp does; other admitted DOM, data, ARIA, and event props and the ref MUST reach `<time>`. | `spec:AST-037` FR8 | Settled |
+| FR6 | Timer MUST NOT add live-region semantics by default. | `spec:AST-037` FR9 | Settled |
+| FR7 | The Text wrapper MUST carry exactly the `timer` target for this component. | `spec:AST-037` FR10 | Settled |
+| FR8 | Initial markup MUST use the selected format's zero value and `PT0S` without exposing a clock read in rendered markup. | `spec:AST-037` FR11 | Settled |
+| FR9 | `elapsed` and `clock` MUST update on second boundaries below one hour; `elapsed` MUST update on minute boundaries at or above one hour while `clock` remains second-precise. A future origin MUST schedule toward its first visible change rather than waking each second at zero. | `spec:AST-037` FR12 | Settled |
+| FR10 | Timer SHOULD skip DOM writes while the represented text and duration are unchanged. | `spec:AST-037` FR13 | Settled |
+
+### Allowed variation
+
+- **AV1 — Scheduling mechanism.** The private browser scheduling mechanism may
+ change while format-aware cadence, clock derivation, no-render ticks, and
+ complete cleanup remain true.
+- **AV2 — Composition.** Callers may use the supported typography and styling
+ inputs without changing timing behavior.
+
+### Representative states
+
+| State | Required invariant | Allowed variation |
+| ---------------- | -------------------------------------------------------------- | --------------------------------------- |
+| Initial elapsed | `0s` and `PT0S` on one `<time>` | Root props and styling |
+| Initial clock | `0:00` and `PT0S` on one `<time>` | Root props and styling |
+| Seconds/minutes | `34s`, `2m 08s`, `0:34`, or `2:08` with whole-second semantics | Finite elapsed value |
+| Hour-scale | `1h 02m` at minute cadence or `1:02:33` at second cadence | Format |
+| Delayed callback | Catch up to clock without accumulated drift | Delay length |
+| Prop update | New origin or format applies on the same `<time>` | Parent render cause |
+| Replay/unmount | Each acquired resource is released | Development replay count |
+| Typography | Timestamp defaults or explicit Text-family overrides | Supported type, size, color, and weight |
+
+### Transformation and precedence order
+
+- **ORD1 — Resolve → calculate → clamp → floor to visible precision → format →
+ write → schedule next visible boundary.** Apply the pipeline from `spec:AST-037`
+ to visible text and machine-readable duration.
+- **ORD2 — Timestamp styling split.** Typography, `xstyle`, `className`, `style`,
+ and the `timer` target compose on the Text wrapper. Time-element props and the ref
+ compose on `<time>`; Timer owns `dateTime`.
+
+### Performance and resources
+
+- **PR1 — No tick renders.** Advancing time produces zero React update commits.
+- **PR2 — One resource.** Each mounted Timer owns at most one active timer resource,
+ and each setup cleanup releases its resource.
+- **PR3 — Visible cadence.** Elapsed output at or above one hour does not wake for
+ hidden second changes; clock output remains second-precise.
+- **PR4 — Bounded writes.** Unchanged represented text and duration are not rewritten.
+
+## Accessibility contract
+
+- **AR1 — Semantic duration.** The `<time>` element exposes the current non-negative
+ ISO 8601 duration at the same precision as its visible output.
+- **AR2 — Quiet by default.** No role or `aria-live` value is added automatically;
+ deliberate caller ARIA passes through.
+- **AR3 — Perceivable text.** The formatted duration remains real text content.
+
+## Design relationships
+
+| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |
+| ---------------- | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------ | -------------- | ----------------------- |
+| Elapsed time | One stable inline duration with Timestamp-equivalent supporting typography by default and standard Text overrides. | `spec:AST-037/DEC-1`, `spec:AST-037/DEC-3` | Supporting | FR1, FR3, FR5, AR1, AR3 |
+
+### Theming anatomy
+
+<!-- anatomy-theming:v1 -->
+
+```json
+{
+ "Elapsed time": {"target": "timer"}
+}
+```
+
+## Family and system relationships
+
+- Timer and Timestamp are temporal Text-family content components: Timer owns
+ durations; Timestamp owns instants. Their typography API and defaults match.
+- `spec:AST-037` owns the public behavior, API, accessibility, performance, and
+ first-Core-admission decisions projected here.
+- `architecture:public-component-api` owns exports, BaseProps, styling, ref, and
+ caller-choice rules.
+- `architecture:react-component-runtime` owns Effect and resource lifecycle.
+- `architecture:component-theming-surface` owns target qualification.
+
+## Verification map
+
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| --------------------------- | -------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------- |
+| FR1–FR4, FR8–FR10, AR1, AR3 | `Timer.test.tsx` controlled-clock tests | Initial formats, origin variants including future scheduling, delayed callback, format change, second/minute/hour boundaries | State ticks, callback accumulation, wrong ladder/padding, negative values, needless pre-origin wakes, stale semantics, wrong cadence, or clock-derived initial markup fail | `audit:Timer/behavior` |
+| FR3, PR1 | React Profiler commit-count test | Several ticks | A state-based implementation adds update commits and fails | `audit:Timer/performance` |
+| FR4, PR2 | Resource spies under rerender, StrictMode, and unmount | Setup, dependency change, replay, cleanup | Duplicate or leaked resources fail counts | `audit:Timer/resources` |
+| FR5 | Public import, Timestamp-default typography, overrides, BaseProps, and ref tests | Default and explicit typography, ref, event, ARIA, class, style | Missing export, styling divergence, or dropped input fails | `audit:Timer/api` |
+| FR6, AR2 | Accessibility attribute tests | Default and deliberate caller ARIA | Unsolicited live semantics or dropped ARIA fails | `audit:Timer/accessibility` |
+| FR7 | `themingTargets.test.ts` and `scripts/check-knowledge.mjs` | One wrapper target | Missing, extra, or misplaced target fails | `audit:Timer/theming` |
+
+## Decision log
+
+No additional decision. This component projects `spec:AST-037` without widening it.
+
+## Open questions
+
+None.
+
+## Content boundary
+
+This file does not duplicate consumer examples, implementation code, private
+scheduling mechanics, measurements, or system rules. It links to their owners.
diff --git a/packages/core/src/Timer/Timer.test.tsx b/packages/core/src/Timer/Timer.test.tsx
new file mode 100644
index 0000000000..cc9783e222
--- /dev/null
+++ b/packages/core/src/Timer/Timer.test.tsx
@@ -0,0 +1,302 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Timer.test.tsx
+ * @input Uses React Testing Library, fake clocks, React Profiler, and Timer
+ * @output Verifies formats, adaptive cadence, render isolation, typography, resources, semantics, and passthrough
+ */
+
+import {Profiler, StrictMode, createRef} from 'react';
+import {renderToString} from 'react-dom/server';
+import {act, fireEvent, render, screen} from '@testing-library/react';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {Timer} from './Timer';
+
+describe('Timer', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-09-22T00:00:00Z'));
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ });
+
+ it('renders deterministic zero-duration markup for each standard format', () => {
+ const {rerender} = render(<Timer data-testid="timer" />);
+ const timer = screen.getByTestId('timer');
+
+ expect(timer.tagName).toBe('TIME');
+ expect(timer).toHaveTextContent('0s');
+ expect(timer).toHaveAttribute('datetime', 'PT0S');
+
+ rerender(<Timer format="clock" data-testid="timer" />);
+ expect(timer).toHaveTextContent('0:00');
+ expect(timer).toHaveAttribute('datetime', 'PT0S');
+ });
+
+ it('keeps server markup independent of the clock', () => {
+ const firstMarkup = renderToString(<Timer startTime={0} />);
+ const firstClockMarkup = renderToString(
+ <Timer startTime={0} format="clock" />,
+ );
+
+ vi.setSystemTime(new Date('2030-01-01T00:00:00Z'));
+ const secondMarkup = renderToString(<Timer startTime={0} />);
+ const secondClockMarkup = renderToString(
+ <Timer startTime={0} format="clock" />,
+ );
+
+ expect(firstMarkup).toBe(secondMarkup);
+ expect(firstMarkup).toContain('dateTime="PT0S"');
+ expect(firstMarkup).toContain('>0s</time>');
+ expect(firstClockMarkup).toBe(secondClockMarkup);
+ expect(firstClockMarkup).toContain('>0:00</time>');
+ });
+
+ it('derives elapsed time from the clock without accumulating callback count', () => {
+ let scheduledTick: (() => void) | undefined;
+ vi.spyOn(globalThis, 'setTimeout').mockImplementation(callback => {
+ scheduledTick = callback as () => void;
+ return 1 as unknown as ReturnType<typeof setTimeout>;
+ });
+
+ render(<Timer data-testid="timer" />);
+
+ vi.setSystemTime(new Date('2026-09-22T00:00:08.750Z'));
+ act(() => {
+ scheduledTick?.();
+ });
+
+ const timer = screen.getByTestId('timer');
+ expect(timer).toHaveTextContent('8s');
+ expect(timer).toHaveAttribute('datetime', 'PT8S');
+ });
+
+ it('formats elapsed durations across seconds, minutes, and hours', () => {
+ const now = Date.now();
+ const {rerender} = render(
+ <Timer startTime={now - 34_000} data-testid="timer" />,
+ );
+ const timer = screen.getByTestId('timer');
+ expect(timer).toHaveTextContent('34s');
+ expect(timer).toHaveAttribute('datetime', 'PT34S');
+
+ rerender(<Timer startTime={now - 128_000} data-testid="timer" />);
+ expect(timer).toHaveTextContent('2m 08s');
+ expect(timer).toHaveAttribute('datetime', 'PT128S');
+
+ rerender(<Timer startTime={now - 3_753_000} data-testid="timer" />);
+ expect(timer).toHaveTextContent('1h 02m');
+ expect(timer).toHaveAttribute('datetime', 'PT3720S');
+ });
+
+ it('formats clock durations across minutes and hours', () => {
+ const now = Date.now();
+ const {rerender} = render(
+ <Timer format="clock" startTime={now - 128_000} data-testid="timer" />,
+ );
+ const timer = screen.getByTestId('timer');
+ expect(timer).toHaveTextContent('2:08');
+ expect(timer).toHaveAttribute('datetime', 'PT128S');
+
+ rerender(
+ <Timer format="clock" startTime={now - 3_753_000} data-testid="timer" />,
+ );
+ expect(timer).toHaveTextContent('1:02:33');
+ expect(timer).toHaveAttribute('datetime', 'PT3753S');
+ });
+
+ it('uses second cadence until elapsed format reaches an hour, then minute cadence', () => {
+ const setTimeoutSpy = vi.spyOn(globalThis, 'setTimeout');
+ const startTime = Date.now() - 3_599_000;
+ render(<Timer startTime={startTime} data-testid="timer" />);
+ const timer = screen.getByTestId('timer');
+
+ expect(timer).toHaveTextContent('59m 59s');
+ expect(setTimeoutSpy).toHaveBeenLastCalledWith(expect.any(Function), 1000);
+
+ act(() => {
+ vi.advanceTimersByTime(1000);
+ });
+ expect(timer).toHaveTextContent('1h 00m');
+ expect(timer).toHaveAttribute('datetime', 'PT3600S');
+ expect(setTimeoutSpy).toHaveBeenLastCalledWith(
+ expect.any(Function),
+ 60_000,
+ );
+ });
+
+ it('keeps clock format on second cadence after an hour', () => {
+ const setTimeoutSpy = vi.spyOn(globalThis, 'setTimeout');
+ render(
+ <Timer
+ format="clock"
+ startTime={Date.now() - 3_723_000}
+ data-testid="timer"
+ />,
+ );
+
+ expect(screen.getByTestId('timer')).toHaveTextContent('1:02:03');
+ expect(setTimeoutSpy).toHaveBeenLastCalledWith(expect.any(Function), 1000);
+ });
+
+ it('counts from a finite caller-provided start time', () => {
+ const now = Date.now();
+ render(<Timer startTime={now - 12_400} data-testid="timer" />);
+
+ expect(screen.getByTestId('timer')).toHaveTextContent('12s');
+ expect(screen.getByTestId('timer')).toHaveAttribute('datetime', 'PT12S');
+ });
+
+ it('returns to the original mount origin when startTime is removed', () => {
+ const mountedAt = Date.now();
+ const {rerender} = render(
+ <Timer startTime={mountedAt - 10_000} data-testid="timer" />,
+ );
+
+ act(() => {
+ vi.advanceTimersByTime(2000);
+ });
+ rerender(<Timer data-testid="timer" />);
+
+ expect(screen.getByTestId('timer')).toHaveTextContent('2s');
+ expect(screen.getByTestId('timer')).toHaveAttribute('datetime', 'PT2S');
+ });
+
+ it('falls back to mount time for a non-finite start time', () => {
+ render(<Timer startTime={Number.NaN} data-testid="timer" />);
+
+ act(() => {
+ vi.advanceTimersByTime(2000);
+ });
+
+ expect(screen.getByTestId('timer')).toHaveTextContent('2s');
+ });
+
+ it('clamps a future origin to zero and schedules its first visible change directly', () => {
+ const setTimeoutSpy = vi.spyOn(globalThis, 'setTimeout');
+ render(<Timer startTime={Date.now() + 5000} data-testid="timer" />);
+
+ expect(screen.getByTestId('timer')).toHaveTextContent('0s');
+ expect(screen.getByTestId('timer')).toHaveAttribute('datetime', 'PT0S');
+ expect(setTimeoutSpy).toHaveBeenLastCalledWith(expect.any(Function), 6000);
+
+ act(() => {
+ vi.advanceTimersByTime(6000);
+ });
+
+ expect(screen.getByTestId('timer')).toHaveTextContent('1s');
+ expect(screen.getByTestId('timer')).toHaveAttribute('datetime', 'PT1S');
+ });
+
+ it('updates format without remounting or losing current elapsed time', () => {
+ const now = Date.now();
+ const {rerender} = render(
+ <Timer startTime={now - 3_723_000} data-testid="timer" />,
+ );
+ const timer = screen.getByTestId('timer');
+ expect(timer).toHaveTextContent('1h 02m');
+ expect(timer).toHaveAttribute('datetime', 'PT3720S');
+
+ rerender(
+ <Timer format="clock" startTime={now - 3_723_000} data-testid="timer" />,
+ );
+ expect(screen.getByTestId('timer')).toBe(timer);
+ expect(timer).toHaveTextContent('1:02:03');
+ expect(timer).toHaveAttribute('datetime', 'PT3723S');
+ });
+
+ it('does not schedule React update commits as time advances', () => {
+ const onRender = vi.fn();
+ render(
+ <Profiler id="timer" onRender={onRender}>
+ <Timer />
+ </Profiler>,
+ );
+ expect(onRender).toHaveBeenCalledTimes(1);
+
+ act(() => {
+ vi.advanceTimersByTime(5000);
+ });
+
+ expect(onRender).toHaveBeenCalledTimes(1);
+ });
+
+ it('owns one timer resource and cleans up under StrictMode replay', () => {
+ const setTimeoutSpy = vi.spyOn(window, 'setTimeout');
+ const clearTimeoutSpy = vi.spyOn(window, 'clearTimeout');
+ const {unmount} = render(
+ <StrictMode>
+ <Timer />
+ </StrictMode>,
+ );
+
+ expect(setTimeoutSpy).toHaveBeenCalledTimes(2);
+ expect(clearTimeoutSpy).toHaveBeenCalledTimes(1);
+
+ unmount();
+ expect(clearTimeoutSpy).toHaveBeenCalledTimes(2);
+ });
+
+ it('matches Timestamp typography defaults and accepts overrides', () => {
+ const {rerender} = render(<Timer data-testid="timer" />);
+ const timer = screen.getByTestId('timer');
+ const text = timer.parentElement;
+
+ expect(text).toHaveClass('astryx-text');
+ expect(text).toHaveClass('astryx-timer');
+ expect(text).toHaveAttribute('data-type', 'supporting');
+ expect(text).toHaveAttribute('data-color', 'secondary');
+
+ rerender(
+ <Timer
+ type="body"
+ size="lg"
+ color="primary"
+ weight="bold"
+ data-testid="timer"
+ />,
+ );
+ expect(text).toHaveAttribute('data-type', 'body');
+ expect(text).toHaveAttribute('data-size', 'lg');
+ expect(text).toHaveAttribute('data-color', 'primary');
+ });
+
+ it('forwards its time ref and preserves Timestamp-style root styling and time props', () => {
+ const ref = createRef<HTMLTimeElement>();
+ const onClick = vi.fn();
+ render(
+ <Timer
+ ref={ref}
+ id="elapsed"
+ className="custom-class"
+ style={{color: 'rgb(1, 2, 3)'}}
+ aria-live="polite"
+ onClick={onClick}
+ data-testid="timer"
+ />,
+ );
+
+ const timer = screen.getByTestId('timer');
+ const text = timer.parentElement;
+ expect(ref.current).toBe(timer);
+ expect(timer).toHaveAttribute('id', 'elapsed');
+ expect(text).toHaveClass('astryx-timer');
+ expect(text).toHaveClass('custom-class');
+ expect(text).toHaveStyle({color: 'rgb(1, 2, 3)'});
+ expect(timer).toHaveAttribute('aria-live', 'polite');
+
+ fireEvent.click(timer);
+ expect(onClick).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not add live-region semantics by default', () => {
+ render(<Timer data-testid="timer" />);
+ const timer = screen.getByTestId('timer');
+
+ expect(timer).not.toHaveAttribute('aria-live');
+ expect(timer).not.toHaveAttribute('role');
+ });
+});
diff --git a/packages/core/src/Timer/Timer.tsx b/packages/core/src/Timer/Timer.tsx
new file mode 100644
index 0000000000..e89a8af6de
--- /dev/null
+++ b/packages/core/src/Timer/Timer.tsx
@@ -0,0 +1,258 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file Timer.tsx
+ * @input Uses an optional start time, standardized format, Timestamp typography, BaseProps, and React ref
+ * @output Exports Timer, TimerProps, and TimerFormat with non-rendering elapsed-time updates
+ * @position Core content primitive for elapsed duration in active operations
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/Timer/Timer.spec.md
+ * - /packages/core/src/Timer/Timer.doc.mjs
+ * - /packages/core/src/Timer/Timer.test.tsx
+ * - /packages/core/src/Timer/index.ts
+ * - /apps/storybook/stories/Timer.stories.tsx
+ * - /packages/cli/assets/templates/blocks/components/Timer/
+ */
+
+import {useEffect, useRef, useState} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import type {BaseProps} from '../BaseProps';
+import {useMergedRefs} from '../hooks/useMergedRefs';
+import {Text} from '../Text';
+import type {TextColor, TextSize, TextType, TextWeight} from '../theme/types';
+import {mergeProps} from '../utils';
+import {themeProps} from '../utils/themeProps';
+
+const ONE_SECOND_MS = 1000;
+const ONE_MINUTE_MS = 60 * ONE_SECOND_MS;
+const ONE_HOUR_SECONDS = 60 * 60;
+const MAX_TIMEOUT_MS = 2_147_483_647;
+
+const styles = stylex.create({
+ time: {
+ color: 'inherit',
+ display: 'inline',
+ fontFamily: 'inherit',
+ fontSize: 'inherit',
+ fontStyle: 'normal',
+ fontVariantNumeric: 'tabular-nums',
+ fontWeight: 'inherit',
+ lineHeight: 'inherit',
+ },
+});
+
+export type TimerFormat = 'elapsed' | 'clock';
+
+type TimerPresentation = {
+ dateTime: string;
+ text: string;
+};
+
+function pad(value: number): string {
+ return String(value).padStart(2, '0');
+}
+
+function resolveFormat(format: TimerFormat): TimerFormat {
+ return format === 'clock' ? 'clock' : 'elapsed';
+}
+
+function getElapsedMilliseconds(now: number, startTime: number): number {
+ return Math.max(0, now - startTime);
+}
+
+function getPresentation(
+ elapsedMilliseconds: number,
+ format: TimerFormat,
+): TimerPresentation {
+ const elapsedSeconds = Math.floor(elapsedMilliseconds / ONE_SECOND_MS);
+
+ if (format === 'clock') {
+ const hours = Math.floor(elapsedSeconds / ONE_HOUR_SECONDS);
+ const minutes = Math.floor((elapsedSeconds % ONE_HOUR_SECONDS) / 60);
+ const seconds = elapsedSeconds % 60;
+ return {
+ dateTime: `PT${elapsedSeconds}S`,
+ text:
+ hours > 0
+ ? `${String(hours)}:${pad(minutes)}:${pad(seconds)}`
+ : `${String(minutes)}:${pad(seconds)}`,
+ };
+ }
+
+ if (elapsedSeconds < 60) {
+ return {
+ dateTime: `PT${elapsedSeconds}S`,
+ text: `${String(elapsedSeconds)}s`,
+ };
+ }
+
+ const totalMinutes = Math.floor(elapsedSeconds / 60);
+ if (totalMinutes < 60) {
+ return {
+ dateTime: `PT${elapsedSeconds}S`,
+ text: `${String(totalMinutes)}m ${pad(elapsedSeconds % 60)}s`,
+ };
+ }
+
+ const representedSeconds = totalMinutes * 60;
+ return {
+ dateTime: `PT${representedSeconds}S`,
+ text: `${String(Math.floor(totalMinutes / 60))}h ${pad(totalMinutes % 60)}m`,
+ };
+}
+
+function getMillisecondsUntilNextChange(
+ now: number,
+ startTime: number,
+ elapsedMilliseconds: number,
+ format: TimerFormat,
+): number {
+ if (now < startTime) {
+ return Math.min(startTime - now + ONE_SECOND_MS, MAX_TIMEOUT_MS);
+ }
+
+ const precision =
+ format === 'elapsed' &&
+ elapsedMilliseconds >= ONE_HOUR_SECONDS * ONE_SECOND_MS
+ ? ONE_MINUTE_MS
+ : ONE_SECOND_MS;
+ return precision - (elapsedMilliseconds % precision);
+}
+
+export interface TimerProps extends Omit<
+ BaseProps<HTMLTimeElement>,
+ 'dateTime'
+> {
+ /** Ref forwarded to the rendered `<time>` element. */
+ ref?: React.Ref<HTMLTimeElement>;
+ /**
+ * Unix time in milliseconds when the measured operation began. Omit it to
+ * start counting from this Timer's mount.
+ */
+ startTime?: number;
+ /**
+ * Standard duration representation.
+ * @default 'elapsed'
+ */
+ format?: TimerFormat;
+ /**
+ * Semantic text type. Matches Timestamp typography behavior.
+ * @default 'supporting'
+ */
+ type?: TextType;
+ /** Explicit font size override. Overrides the size from `type`. */
+ size?: TextSize;
+ /**
+ * Text color.
+ * @default 'secondary'
+ */
+ color?: TextColor;
+ /** Font weight override. */
+ weight?: TextWeight;
+}
+
+/**
+ * Displays a standardized elapsed duration without scheduling React tick renders.
+ *
+ * Timer writes changing text and its ISO 8601 duration directly to the owned
+ * `<time>` node. Use `elapsed` for compact duration text or `clock` for a
+ * stopwatch-like reading.
+ *
+ * @example
+ * ```
+ * <Timer />
+ * <Timer format="clock" />
+ * ```
+ */
+export function Timer({
+ startTime,
+ format = 'elapsed',
+ type = 'supporting',
+ size,
+ color = 'secondary',
+ weight,
+ ref,
+ xstyle,
+ className,
+ style,
+ ...rest
+}: TimerProps) {
+ const [mountTime] = useState(() => Date.now());
+ const timerRef = useRef<HTMLTimeElement>(null);
+ const mergedRef = useMergedRefs(ref, timerRef);
+ const resolvedFormat = resolveFormat(format);
+ const initialPresentation = getPresentation(0, resolvedFormat);
+
+ useEffect(() => {
+ const resolvedStartTime =
+ startTime !== undefined && Number.isFinite(startTime)
+ ? startTime
+ : mountTime;
+ let timeoutID: ReturnType<typeof setTimeout> | undefined;
+ let previousDateTime: string | undefined;
+ let previousText: string | undefined;
+
+ const tick = () => {
+ const now = Date.now();
+ const elapsedMilliseconds = getElapsedMilliseconds(
+ now,
+ resolvedStartTime,
+ );
+ const presentation = getPresentation(elapsedMilliseconds, resolvedFormat);
+ const node = timerRef.current;
+
+ if (node != null) {
+ if (presentation.text !== previousText) {
+ node.textContent = presentation.text;
+ previousText = presentation.text;
+ }
+ if (presentation.dateTime !== previousDateTime) {
+ node.dateTime = presentation.dateTime;
+ previousDateTime = presentation.dateTime;
+ }
+ }
+
+ timeoutID = setTimeout(
+ tick,
+ getMillisecondsUntilNextChange(
+ now,
+ resolvedStartTime,
+ elapsedMilliseconds,
+ resolvedFormat,
+ ),
+ );
+ };
+
+ tick();
+ return () => {
+ if (timeoutID !== undefined) {
+ clearTimeout(timeoutID);
+ }
+ };
+ }, [mountTime, resolvedFormat, startTime]);
+
+ const timerProps = mergeProps(themeProps('timer'), {className, style});
+
+ return (
+ <Text
+ type={type}
+ size={size}
+ color={color}
+ weight={weight}
+ xstyle={xstyle}
+ {...timerProps}>
+ <time
+ {...rest}
+ ref={mergedRef}
+ dateTime="PT0S"
+ {...stylex.props(styles.time)}>
+ {initialPresentation.text}
+ </time>
+ </Text>
+ );
+}
+
+Timer.displayName = 'Timer';
diff --git a/packages/core/src/Timer/index.ts b/packages/core/src/Timer/index.ts
new file mode 100644
index 0000000000..3f49a38f7b
--- /dev/null
+++ b/packages/core/src/Timer/index.ts
@@ -0,0 +1,11 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file index.ts
+ * @input Imports Timer, TimerProps, and TimerFormat
+ * @output Public Timer component barrel
+ * @position Component subpath entry point for @astryxdesign/core/Timer
+ */
+
+export {Timer} from './Timer';
+export type {TimerFormat, TimerProps} from './Timer';
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index bd78d506a0..cda2903001 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -161,6 +161,9 @@ export * from './Spinner';
// Timestamp display
export * from './Timestamp';
+// Elapsed timer display
+export * from './Timer';
+
// Overlay
export * from './Overlay';
export * from './Outline';