Skip to content

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

TypeScript

fix(Timestamp): attach popup semantics to the focusable time (#6298)

Jiun Shinb207e607abcf
diff --git a/.changeset/timestamp-focusable-popup-trigger.md b/.changeset/timestamp-focusable-popup-trigger.md
new file mode 100644
index 0000000000..da9d4684d5
--- /dev/null
+++ b/.changeset/timestamp-focusable-popup-trigger.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Timestamp exposes its details popup on the focusable time element.
+@jiunshinn
diff --git a/apps/storybook/stories/Timestamp.stories.tsx b/apps/storybook/stories/Timestamp.stories.tsx
index c2e87f2634..54fa293488 100644
--- a/apps/storybook/stories/Timestamp.stories.tsx
+++ b/apps/storybook/stories/Timestamp.stories.tsx
@@ -1,5 +1,12 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
+/**
+ * @file Timestamp.stories.tsx
+ * @input Uses Timestamp, Text, and the Storybook theme decorator
+ * @output Stories for timestamp formats, sequential keyboard access and lazy details
+ * @position Storybook examples for Timestamp
+ */
+
import type {Meta, StoryObj} from '@storybook/react';
import {Timestamp} from '@astryxdesign/core/Timestamp';
import {InternationalizationProvider} from '@astryxdesign/core/i18n';
@@ -81,7 +88,7 @@ const meta: Meta<typeof Timestamp> = {
},
hasTooltip: {
control: 'boolean',
- description: 'Show copyable hover card on hover',
+ description: 'Show copyable details on hover or keyboard focus',
},
isTimezoneShown: {
control: 'boolean',
@@ -100,6 +107,14 @@ export const Default: Story = {
};
export const RelativeFormat: Story = {
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'Tab to a timestamp to reveal its details dialog. The focused time exposes the popup relationship. Tab into the copy button; Escape dismisses its tooltip, then the card, returning focus to the timestamp.',
+ },
+ },
+ },
render: () => (
<div
style={{
diff --git a/docs/specs/components/Timestamp/Timestamp.spec.md b/docs/specs/components/Timestamp/Timestamp.spec.md
index f4fede9f0d..8ff3a50d0d 100644
--- a/docs/specs/components/Timestamp/Timestamp.spec.md
+++ b/docs/specs/components/Timestamp/Timestamp.spec.md
@@ -39,15 +39,15 @@ system_specs: [spec:AST-009, spec:AST-013/FR12, spec:AST-085, spec:AST-111/FR18]
## Contract at a glance
-| Area | Contract |
-| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| Public contract | A `time` element for a `value` (Unix seconds, milliseconds, or ISO 8601) in one of twelve `format`s, with optional live updates, time-zone suffix, and a copyable hover card. |
-| Behavior | Relative output carries the full absolute date as its default accessible name; relative output, or configured `tooltipEntries`, attach a keyboard-reachable hover card of copyable rows. |
-| End-user impact | Readers see compact or exact times in their locale; screen-reader users hear the full date and time zone; keyboard users can open and copy the exact time. |
-| Builder impact | Optional: set `calendar` on the `InternationalizationProvider` to write dates in another calendar. Optional: map the hover card's copy glyph through the `timestamp-copy` icon slot (FR10). |
-| Compatibility/readiness | No prop or default changes; FR10 adds the opt-in `timestamp-copy` theme slot, which is current and awaits implementation. Without a provider calendar the output is unchanged; under one, date-bearing formats change calendar, and calendars that need `Temporal` fall back to Gregorian where it is missing (the `spec:AST-013` FR12 exception). A provider locale with a `-u-ca-` keyword keeps Gregorian dates (`spec:AST-111` DEC-2); set the provider's `calendar` to choose one. Two implementation gaps are listed under Current-state impact. |
-| Review checks | Reject a relative timestamp without the full absolute name when the caller names nothing, a hover card without a tab stop, a change that makes more server markup depend on the server's zone, or a crash on an unparseable value. |
-| Governing rules | `architecture:internationalization/INV4,INV8,INV10`; `spec:AST-111/FR18`; `spec:AST-013` FR12; `architecture:react-component-runtime/INV1,INV3,INV5`; `architecture:public-component-api/INV5,INV6,INV8`; `architecture:icon-resolution-and-component-slots/INV2,INV4–INV8`. |
+| Area | Contract |
+| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Public contract | A `time` element for a `value` (Unix seconds, milliseconds, or ISO 8601) in one of twelve `format`s, with optional live updates, time-zone suffix, and a copyable hover card. |
+| Behavior | Relative output carries the full absolute date as its default accessible name; relative output, or configured `tooltipEntries`, attach a keyboard-reachable hover card of copyable rows. |
+| End-user impact | Readers see compact or exact times in their locale; screen-reader users hear the full date and time zone; keyboard users can open and copy the exact time. |
+| Builder impact | Optional: set `calendar` on the `InternationalizationProvider` to write dates in another calendar. Optional: map the hover card's copy glyph through the `timestamp-copy` icon slot (FR10). |
+| Compatibility/readiness | No prop or default changes; FR10 adds the opt-in `timestamp-copy` theme slot, which is current and awaits implementation. Without a provider calendar the output is unchanged; under one, date-bearing formats change calendar, and calendars that need `Temporal` fall back to Gregorian where it is missing (the `spec:AST-013` FR12 exception). A provider locale with a `-u-ca-` keyword keeps Gregorian dates (`spec:AST-111` DEC-2); set the provider's `calendar` to choose one. One implementation gap is listed under Current-state impact. |
+| Review checks | Reject a relative timestamp without the full absolute name when the caller names nothing, a hover card without a tab stop, a change that makes more server markup depend on the server's zone, or a crash on an unparseable value. |
+| Governing rules | `architecture:internationalization/INV4,INV8,INV10`; `spec:AST-111/FR18`; `spec:AST-013` FR12; `architecture:react-component-runtime/INV1,INV3,INV5`; `architecture:public-component-api/INV5,INV6,INV8`; `architecture:icon-resolution-and-component-slots/INV2,INV4–INV8`. |
This table is a review projection; the body below is authoritative.
@@ -76,11 +76,6 @@ Consumer migration instructions belong in consumer docs and release notes.
## Current-state impact
-- **Focus lost when the card attaches (FR6, AR3).** While the card module
- loads, a fallback `time` with the tab stop renders; when the card attaches it
- replaces that element, so keyboard focus placed on it falls to the page body
- and no card opens, where `spec:AST-085` FR4 keeps focus on a control that
- stays available.
- **Absolute formats depend on the server's zone (FR3).** An absolute format
other than `unix_seconds` renders in the host's time zone unless the caller
passes `timezoneID`, so without it the same instant reads "Mar 25" from a
@@ -126,7 +121,7 @@ Consumer migration instructions belong in consumer docs and release notes.
| FR3 | Server markup does not depend on the server's time zone and hydrates without a mismatch. A format that needs the clock renders `date_time` in UTC and the Gregorian calendar with the zone shown until the client can read the clock; the client then shows the resolved format without committing the UTC placeholder. A calendar that needs `Temporal` hydrates without a mismatch only when the server and the browser resolve it the same way (the `spec:AST-013` FR12 exception). Implementation gap: absolute formats other than `unix_seconds` render in the host's time zone unless the caller passes `timezoneID`, so without it their server markup depends on the server's zone and hydrating it in another zone produces a text mismatch (Current-state impact). | Current source and tests |
| FR4 | With `isLive` and relative output, the clock refreshes every second under a minute old, every 30 seconds under an hour, every minute under a day, and every five minutes beyond; the timer is cleared on unmount or when the inputs change. Locale changes update the output live. | Current source and tests |
| FR5 | Relative output is named by the full absolute date and the long time-zone name unless a caller names the element; absolute output adds no name. A caller's explicit `aria-label` reaches the element (`architecture:public-component-api` INV5). | Current source and tests |
-| FR6 | When `hasTooltip` is true and the output is relative or `tooltipEntries` is non-empty, a lazily loaded HoverCard named "Timestamp details" attaches above the timestamp, opening on hover and on keyboard focus; the `time` element gains `tabIndex={0}`. Otherwise no card renders and no tab stop is added. Focus placed on the timestamp stays there when the card attaches (`spec:AST-085` FR4). Implementation gap: while the card module loads, a fallback `time` with the tab stop renders, and attaching the card replaces it, so focus placed on it falls to the page body and no card opens (Current-state impact). | Current source and tests |
+| FR6 | When `hasTooltip` is true and the output is relative or `tooltipEntries` is non-empty, a lazily loaded HoverCard named "Timestamp details" attaches above the timestamp, opening on hover and on keyboard focus; the `time` element gains `tabIndex={0}`. Otherwise no card renders and no tab stop is added. Focus placed on the timestamp stays there when the card attaches (`spec:AST-085` FR4). | Current source and tests |
| FR7 | The card is a description list in a grid: an optional label column (present when any row has a label), the value column, and a trailing action column (present when any row is copyable). Without entries it has one copyable row with the full absolute time in the viewer's zone. Each configured entry is one row in the given order, rendered in its own time zone and format, read-only unless `isCopyable`. An entry without its own `timezoneID` renders in the Timestamp's `timezoneID` when one is set, else the viewer's zone. An unknown time zone does not crash. A description list holds only name-value groups (WCAG 2.2 1.3.1). Each row is a name-value group; a row without a label is named by its time zone's long name, which is visually hidden. A copy button sits inside its row's value. | Current source and tests |
| FR8 | A copy button is a small ghost IconButton on the `timestamp-copy-button` target, named "Copy {value}" with a "Copy" tooltip; activating it writes the row's value to the clipboard, switches to the copied glyph (`check` unless a theme maps `timestamp-copy`, FR10) and the "Copied" name and tooltip for 1.5 seconds, and announces "Copied" politely. A clipboard rejection does nothing. | Current source and tests |
| FR9 | `ref`, `data-testid`, and other supported DOM, ARIA, data, and event props reach the `time` element; `xstyle`, `className`, and `style` reach the Text wrapper. A caller `aria-labelledby` names the element in place of FR5's name. A caller's explicit `tabIndex` reaches the element (`architecture:public-component-api` INV5). | Current source and tests |
@@ -174,11 +169,12 @@ Consumer migration instructions belong in consumer docs and release notes.
- **AR2 — Full name for relative output.** Relative output is named by the full
absolute date with the spelled-out time zone (WCAG 2.2 3.1.4).
- **AR3 — Keyboard-reachable card.** While a card is attached the timestamp is
- a tab stop and the card opens on focus; the trigger carries no
- `aria-expanded`. Without a card there is no tab stop. Implementation gap:
- focus placed on the timestamp before the card module loads is lost when the
- card attaches (FR6). The popup relationship sits on the Text wrapper rather
- than the focused `time` and is not contracted.
+ a tab stop and the card opens on focus. Without a card there is no tab stop.
+ The focusable `time` is the card's anchor and keeps focus while the card
+ loads and attaches. While the card is open, the `time` names it through
+ `aria-controls`; it carries no `aria-haspopup` or `aria-expanded`, which the
+ time role does not support. Hover and focus on the `time` open the card;
+ empty layout space around it does not.
- **AR4 — Copy feedback.** Copy buttons are named with their value, and a copy
is announced politely.
@@ -250,19 +246,19 @@ Consumer migration instructions belong in consumer docs and release notes.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- |
-| FR1, FR2 | `Timestamp.test.tsx` format, auto, locale, calendar-system, and invalid-value tests; `tooltipEntries.test.ts` calendar tests; stable visual baseline `core-timestamp--default` | Every format; thresholds; locales; `persian`, `hebrew`, and `buddhist` under English and native locales, with and without `Temporal`; `iso8601`; `chinese` where `Intl` and `Temporal` disagree; unparseable values; default | A wrong phrase, a crossed tier, a non-Gregorian year without a provider calendar, a date-bearing format that ignores the provider calendar or names another day than `component:Calendar`, a changed `system_*` or `time` output, a missing `time` element or `datetime`, a crash, or a missing development warning for an unparseable value fails; a changed default type or color comes back changed for review. Gap: no test asserts the `timestamp` target or its format reflection. | `audit:Timestamp/behavior` |
-| FR3 | `Timestamp.test.tsx` server-rendering suite and "hydrates a clock format rendered on a server without Temporal" | Server zones; hydration | Zone-dependent markup, a hydration mismatch, or a committed placeholder fails. Gap: no test covers an absolute format rendered on a server in another zone. | `audit:Timestamp/behavior` |
-| FR4, PR1 | `Timestamp.test.tsx` live-update and locale tests | Live relative output; locale change | A missing refresh or a stale locale fails. Gap: the per-tier refresh intervals and the timer cleanup on unmount or input change have no automated check. | `audit:Timestamp/behavior` |
-| FR5, AR2 | `Timestamp.test.tsx` naming tests | Relative, absolute, time-zone spelling | A missing or short-zone name, or a name on absolute output, fails. A caller `aria-label` replaced on relative output fails. | `audit:Timestamp/a11y` |
-| FR6, AR3 | `Timestamp.test.tsx` keyboard-reachability suite | Relative, absolute, disabled, entries removed | A missing tab stop, `aria-expanded` on the trigger, or a stray tab stop fails. The aria-expanded test also pins `aria-haspopup` on the Text wrapper, which is current behavior, not contract. Gap: no test covers focus on the timestamp while the card module loads, or `aria-controls`. | `audit:Timestamp/a11y` |
-| FR7, FR8, AR4 | `Timestamp.test.tsx` hover-card suites, including "keeps a copyable labelled card a valid description list" and the default card's hidden zone name; `tooltipEntries.test.ts`; `useClipboard.test.tsx` | Default row, entries, copyable rows, unknown zone | A wrong row count or order, an unpaired label, a copy button on a read-only row, a wrong copied value, a missing copied state, or a missing announcement fails. Gap: no check runs the `definition-list` structure rule on the open card; the grid columns and the 1.5-second reset have no automated check; `useClipboard.test.tsx` covers the clipboard-rejection no-op. | `audit:Timestamp/behavior` |
-| FR9 | `Timestamp.test.tsx` ref, test-id, and pass-through tests | Ref, test id, caller props | A ref, test id, or caller prop missing from the `time` element fails. A caller `tabIndex` replaced while a card is attached fails. Gap: no test asserts that `xstyle`, `className`, and `style` reach the Text wrapper, or covers a caller `aria-labelledby`. | `audit:Timestamp/behavior` |
-| FR10 | `Timestamp.test.tsx` copy icon slot suite; the slot inventory test | No entry, a slot function in both states, `null`, a size request | The glyph ignores the slot or its state, `null` removes the button, its name, or its copy action, a size request resizes the button, or the consumer docs do not list the slot. | `audit:Timestamp/theming` |
-| Theming anatomy map | `scripts/check-knowledge.mjs` | Consumer anatomy, targets, HoverCard delegate | Missing, extra, or stale mappings fail repository validation. | `audit:Timestamp/theming` |
-| AR1 | `Timestamp.test.tsx` `datetime` tests | `date_time`; `date` | A missing or wrong ISO `datetime` on `date_time`, or a missing one on `date`, fails. Gap: no test asserts the exact `datetime` on relative or other absolute formats. | `audit:Timestamp/a11y` |
-| AR2, AR4 | Accessibility-tree evidence (`spec:AST-009` FR3) | Relative output; copy buttons | Gap: no accessibility-tree check proves the computed name of relative output or the copy-button names; the unit tests query the DOM. | `audit:Timestamp/a11y` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- |
+| FR1, FR2 | `Timestamp.test.tsx` format, auto, locale, calendar-system, and invalid-value tests; `tooltipEntries.test.ts` calendar tests; stable visual baseline `core-timestamp--default` | Every format; thresholds; locales; `persian`, `hebrew`, and `buddhist` under English and native locales, with and without `Temporal`; `iso8601`; `chinese` where `Intl` and `Temporal` disagree; unparseable values; default | A wrong phrase, a crossed tier, a non-Gregorian year without a provider calendar, a date-bearing format that ignores the provider calendar or names another day than `component:Calendar`, a changed `system_*` or `time` output, a missing `time` element or `datetime`, a crash, or a missing development warning for an unparseable value fails; a changed default type or color comes back changed for review. Gap: no test asserts the `timestamp` target or its format reflection. | `audit:Timestamp/behavior` |
+| FR3 | `Timestamp.test.tsx` server-rendering suite and "hydrates a clock format rendered on a server without Temporal" | Server zones; hydration | Zone-dependent markup, a hydration mismatch, or a committed placeholder fails. Gap: no test covers an absolute format rendered on a server in another zone. | `audit:Timestamp/behavior` |
+| FR4, PR1 | `Timestamp.test.tsx` live-update and locale tests | Live relative output; locale change | A missing refresh or a stale locale fails. Gap: the per-tier refresh intervals and the timer cleanup on unmount or input change have no automated check. | `audit:Timestamp/behavior` |
+| FR5, AR2 | `Timestamp.test.tsx` naming tests | Relative, absolute, time-zone spelling | A missing or short-zone name, or a name on absolute output, fails. A caller `aria-label` replaced on relative output fails. | `audit:Timestamp/a11y` |
+| FR6, AR3 | `Timestamp.test.tsx` keyboard-reachability suite; `Timestamp.a11y.browser.spec.ts` (Chromium and WebKit): focus stays on the `time` across the lazy attach, `aria-controls` names the open card, and axe passes | Relative, absolute, disabled, entries removed | A missing tab stop, `aria-expanded` on the trigger, or a stray tab stop fails. | `audit:Timestamp/a11y` |
+| FR7, FR8, AR4 | `Timestamp.test.tsx` hover-card suites, including "keeps a copyable labelled card a valid description list" and the default card's hidden zone name; `tooltipEntries.test.ts`; `useClipboard.test.tsx` | Default row, entries, copyable rows, unknown zone | A wrong row count or order, an unpaired label, a copy button on a read-only row, a wrong copied value, a missing copied state, or a missing announcement fails. Gap: no check runs the `definition-list` structure rule on the open card; the grid columns and the 1.5-second reset have no automated check; `useClipboard.test.tsx` covers the clipboard-rejection no-op. | `audit:Timestamp/behavior` |
+| FR9 | `Timestamp.test.tsx` ref, test-id, and pass-through tests | Ref, test id, caller props | A ref, test id, or caller prop missing from the `time` element fails. A caller `tabIndex` replaced while a card is attached fails. Gap: no test asserts that `xstyle`, `className`, and `style` reach the Text wrapper, or covers a caller `aria-labelledby`. | `audit:Timestamp/behavior` |
+| FR10 | `Timestamp.test.tsx` copy icon slot suite; the slot inventory test | No entry, a slot function in both states, `null`, a size request | The glyph ignores the slot or its state, `null` removes the button, its name, or its copy action, a size request resizes the button, or the consumer docs do not list the slot. | `audit:Timestamp/theming` |
+| Theming anatomy map | `scripts/check-knowledge.mjs` | Consumer anatomy, targets, HoverCard delegate | Missing, extra, or stale mappings fail repository validation. | `audit:Timestamp/theming` |
+| AR1 | `Timestamp.test.tsx` `datetime` tests | `date_time`; `date` | A missing or wrong ISO `datetime` on `date_time`, or a missing one on `date`, fails. Gap: no test asserts the exact `datetime` on relative or other absolute formats. | `audit:Timestamp/a11y` |
+| AR2, AR4 | Accessibility-tree evidence (`spec:AST-009` FR3) | Relative output; copy buttons | Gap: no accessibility-tree check proves the computed name of relative output or the copy-button names; the unit tests query the DOM. | `audit:Timestamp/a11y` |
## Decision log
diff --git a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json
index 14096788fd..0510a54723 100644
--- a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json
+++ b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json
@@ -1084,13 +1084,6 @@
"FR8",
"spec:AST-086"
],
- "packages/core/src/Timestamp/Timestamp.tsx": [
- "FR5",
- "FR9",
- "component:Timestamp",
- "component:Timestamp",
- "spec quote"
- ],
"packages/core/src/Toast/Toast.tsx": ["FR3"],
"packages/core/src/Toast/ToastViewport.tsx": [
"FR10",
diff --git a/packages/core/src/HoverCard/HoverCard.tsx b/packages/core/src/HoverCard/HoverCard.tsx
index d06a2bdd33..dc125890f8 100644
--- a/packages/core/src/HoverCard/HoverCard.tsx
+++ b/packages/core/src/HoverCard/HoverCard.tsx
@@ -41,6 +41,7 @@ export type {
HoverCardFocusTrigger,
HoverCardTouchTrigger,
} from './useHoverCard';
+import {mergeIds} from './mergeIds';
// `aria-haspopup` and `aria-controls` are global, so any trigger may carry
// them. `aria-expanded` is not. This is the ARIA 1.2 "Supported States and
@@ -259,14 +260,6 @@ function isTextOnly(children: ReactNode): boolean {
return hasText;
}
-/**
- * Utility to merge ARIA ID strings
- */
-function mergeIds(...ids: (string | undefined | null)[]): string | undefined {
- const filtered = ids.filter(Boolean);
- return filtered.length > 0 ? filtered.join(' ') : undefined;
-}
-
/**
* HoverCard component for displaying interactive content on hover/focus.
*
diff --git a/packages/core/src/HoverCard/mergeIds.ts b/packages/core/src/HoverCard/mergeIds.ts
new file mode 100644
index 0000000000..3b0c8934e0
--- /dev/null
+++ b/packages/core/src/HoverCard/mergeIds.ts
@@ -0,0 +1,16 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file mergeIds.ts
+ * @input ARIA id-reference strings, some of which may be missing
+ * @output One space-separated id-reference string, or undefined when empty
+ * @position Shared by HoverCard and Timestamp's card for `aria-controls` and
+ * `aria-describedby`
+ */
+
+export function mergeIds(
+ ...ids: (string | undefined | null)[]
+): string | undefined {
+ const filtered = ids.filter(Boolean);
+ return filtered.length > 0 ? filtered.join(' ') : undefined;
+}
diff --git a/packages/core/src/Timestamp/Timestamp.a11y.browser.spec.ts b/packages/core/src/Timestamp/Timestamp.a11y.browser.spec.ts
new file mode 100644
index 0000000000..ff2981a51c
--- /dev/null
+++ b/packages/core/src/Timestamp/Timestamp.a11y.browser.spec.ts
@@ -0,0 +1,130 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @pr-a11y scope core/Timestamp
+
+/**
+ * @file Timestamp.a11y.browser.spec.ts
+ * @input Built Storybook, keyboard navigation in Chromium and WebKit, and a
+ * delayed card chunk
+ * @output Proof of sequential copy access and focus preservation on cold loads
+ * @position Browser regressions for Timestamp's lazy details attachment
+ */
+
+import AxeBuilder from '@axe-core/playwright';
+import {expect, test} from '@astryxdesign/a11y-spec/playwright';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+let storybook: StaticServer;
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+test.afterAll(async () => storybook?.close());
+
+for (const moveAway of [false, true]) {
+ test(`cold card attachment ${moveAway ? 'respects newer focus' : 'preserves focus and opens details'}`, async ({
+ page,
+ }) => {
+ let release!: () => void;
+ const heldChunk = new Promise<void>(resolve => {
+ release = resolve;
+ });
+ let intercepted = false;
+ await page.route(/TimestampHoverCard[^/]*\.js(?:\?.*)?$/, async route => {
+ intercepted = true;
+ await heldChunk;
+ await route.continue();
+ });
+ try {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-timestamp--relative-format&viewMode=story`,
+ );
+ const times = page.locator('#storybook-root time');
+ await expect(times).toHaveCount(7);
+ await expect.poll(() => intercepted).toBe(true);
+ await page.keyboard.press('Tab');
+ await expect(times.first()).toBeFocused();
+ const original = await times.first().elementHandle();
+ if (original === null) {
+ throw new Error('Expected the first timestamp');
+ }
+ if (moveAway) {
+ await page.keyboard.press('Tab');
+ await expect(times.nth(1)).toBeFocused();
+ }
+ release();
+ const activeTime = times.nth(moveAway ? 1 : 0);
+ await expect(activeTime).toBeFocused();
+ await expect(activeTime).toHaveAttribute('aria-controls', /.+/);
+ // The card has attached, and the time the reader focused survived it.
+ expect(await original.evaluate(node => node.isConnected)).toBe(true);
+ if (moveAway) {
+ await expect(times.first()).not.toHaveAttribute('aria-controls');
+ }
+ const cardId = await activeTime.getAttribute('aria-controls');
+ const card = page.locator(`[id="${cardId}"]`);
+ await expect(card).toBeVisible();
+ await expect(activeTime).not.toHaveAttribute('aria-expanded');
+ await page.keyboard.press('Tab');
+ await expect(card.getByRole('button', {name: /^Copy /})).toBeFocused();
+ await page.keyboard.press('Shift+Tab');
+ await expect(activeTime).toBeFocused();
+ // The copy button's own tooltip dismisses independently of the card.
+ await expect(page.getByRole('tooltip')).not.toBeVisible();
+ await page.keyboard.press('Escape');
+ await expect(card).not.toBeVisible();
+ await expect(activeTime).toBeFocused();
+ } finally {
+ release();
+ }
+ });
+}
+
+test('each timestamp owns the next copy-button tab stop', async ({page}) => {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-timestamp--relative-format&viewMode=story`,
+ );
+ const times = page.locator('#storybook-root time');
+ await expect(times).toHaveCount(7);
+ await page.keyboard.press('Tab');
+ for (let index = 0; index < 2; index++) {
+ await expect(times.nth(index)).toBeFocused();
+ await expect(times.nth(index)).toHaveAttribute('aria-controls', /.+/);
+ const id = await times.nth(index).getAttribute('aria-controls');
+ await page.keyboard.press('Tab');
+ await expect(
+ page.locator(`[id="${id}"]`).getByRole('button', {name: /^Copy /}),
+ ).toBeFocused();
+ await page.keyboard.press('Tab');
+ }
+ await expect(times.nth(2)).toBeFocused();
+});
+
+test('an open card passes axe, and the time carries no unsupported popup attribute', async ({
+ page,
+}) => {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-timestamp--relative-format&viewMode=story`,
+ );
+ await expect(page.locator('#storybook-root time')).toHaveCount(7);
+ const time = page.locator('#storybook-root time').first();
+ await page.keyboard.press('Tab');
+ await expect(time).toBeFocused();
+ await expect(time).toHaveAttribute('aria-controls', /.+/);
+ await expect(time).not.toHaveAttribute('aria-haspopup');
+ await expect(time).not.toHaveAttribute('aria-expanded');
+ // A story is a page fragment with no landmarks or heading.
+ const results = await new AxeBuilder({page})
+ .disableRules(['landmark-one-main', 'page-has-heading-one', 'region'])
+ .analyze();
+ expect(
+ results.violations.map(
+ violation =>
+ `${violation.id}: ${violation.nodes.map(node => node.target.join(' ')).join(', ')}`,
+ ),
+ ).toEqual([]);
+});
diff --git a/packages/core/src/Timestamp/Timestamp.doc.mjs b/packages/core/src/Timestamp/Timestamp.doc.mjs
index 6c3c184a37..d453b413d7 100644
--- a/packages/core/src/Timestamp/Timestamp.doc.mjs
+++ b/packages/core/src/Timestamp/Timestamp.doc.mjs
@@ -1,5 +1,12 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
+/**
+ * @file Timestamp.doc.mjs
+ * @input Timestamp public props, theming targets, and usage patterns
+ * @output Consumer documentation for formatted times and hover/keyboard details
+ * @position Timestamp documentation consumed by the CLI and doc site
+ */
+
/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */
export const docs = {
@@ -58,7 +65,7 @@ export const docs = {
name: 'hasTooltip',
type: 'boolean',
description:
- 'Whether to show a copyable hover card with the full date/time on hover. Applies to relative timestamps and to any format once tooltipEntries is configured.',
+ 'Whether to show a copyable hover card with the full date/time on hover or keyboard focus. Applies to relative timestamps and to any format once tooltipEntries is configured.',
default: 'true',
},
{
@@ -113,7 +120,7 @@ export const docs = {
componentIcons: [
{
slot: 'timestamp-copy',
- description: "The copy button icon on a hover card row.",
+ description: 'The copy button icon on a hover card row.',
fallback: '`copy`; `check` while copied',
state: [
{
@@ -237,7 +244,7 @@ export const docsZh = {
autoThreshold:
'auto \u683c\u5f0f\u4ece\u76f8\u5bf9\u65f6\u95f4\u5207\u6362\u5230 date_time \u7684\u9608\u503c\u79d2\u6570\u3002',
hasTooltip:
- '\u60ac\u505c\u65f6\u662f\u5426\u663e\u793a\u5305\u542b\u5b8c\u6574\u65e5\u671f/\u65f6\u95f4\u7684\u53ef\u590d\u5236\u60ac\u505c\u5361\u7247\uff08\u76f8\u5bf9\u65f6\u95f4\u6a21\u5f0f\uff0c\u6216\u914d\u7f6e tooltipEntries \u7684\u4efb\u610f\u683c\u5f0f\uff09\u3002',
+ '\u60ac\u505c\u6216\u952e\u76d8\u805a\u7126\u65f6\u662f\u5426\u663e\u793a\u5305\u542b\u5b8c\u6574\u65e5\u671f/\u65f6\u95f4\u7684\u53ef\u590d\u5236\u60ac\u505c\u5361\u7247\uff08\u76f8\u5bf9\u65f6\u95f4\u6a21\u5f0f\uff0c\u6216\u914d\u7f6e tooltipEntries \u7684\u4efb\u610f\u683c\u5f0f\uff09\u3002',
tooltipEntries:
"\u60ac\u505c\u65f6\u8981\u663e\u793a\u7684\u884c\uff0c\u7528\u4e8e\u540c\u65f6\u5c55\u793a\u591a\u4e2a\u65f6\u533a\u548c/\u6216\u591a\u79cd\u683c\u5f0f\u3002\u6bcf\u9879\u4e3a\u4e00\u884c\uff0c\u6309\u987a\u5e8f\u6e32\u67d3\uff1b\u7701\u7565 timezoneID \u8868\u793a\u6cbf\u7528 Timestamp \u7684 timezoneID\uff08\u672a\u8bbe\u7f6e\u65f6\u4e3a\u67e5\u770b\u8005\u672c\u5730\u65f6\u533a\uff09\uff0c\u4f20\u5165 'local' \u5219\u59cb\u7ec8\u8868\u793a\u67e5\u770b\u8005\u672c\u5730\u65f6\u533a\u3002\u60ac\u505c\u9762\u677f\u59cb\u7ec8\u662f\u53ef\u9010\u884c\u590d\u5236\u5230\u526a\u8d34\u677f\u7684\u4ea4\u4e92\u5f0f\u5361\u7247\uff0c\u8fd9\u4e9b\u914d\u7f6e\u9879\u81ea\u5b9a\u4e49\u5176\u884c\uff1b\u672a\u914d\u7f6e\u65f6\u5361\u7247\u663e\u793a\u4e00\u884c\u9ed8\u8ba4\u7684\u5b8c\u6574\u7edd\u5bf9\u65f6\u95f4\u3002\u914d\u7f6e\u540e\u7edd\u5bf9\u65f6\u95f4\u683c\u5f0f\u4e5f\u4f1a\u56e0\u6b64\u83b7\u5f97\u60ac\u505c\u9762\u677f\u3002",
isTimezoneShown:
@@ -422,7 +429,7 @@ export const docsDense = {
"display mode: 'relative' (locale-native long wording), 'relative_short' (locale-native narrow wording), 'auto', 'date', 'date_long', 'date_weekday', 'date_time', 'time', 'system_date', 'system_date_time', 'system_time', 'unix_seconds'; date-bearing formats use the provider calendar, system_* and time do not",
autoThreshold: 'seconds threshold for auto relative\u2192date_time switch',
hasTooltip:
- 'show copyable full-time hover card on hover (relative mode, or any format with tooltipEntries)',
+ 'show copyable full-time hover card on hover or keyboard focus (relative mode, or any format with tooltipEntries)',
tooltipEntries:
"hover rows across zones/formats: [{timezoneID?, format?, label?}]; an entry without timezoneID follows the Timestamp timezoneID when set, else the viewer zone ('local' always means the viewer zone), format defaults to 'full'; the hover surface is always a copy-to-clipboard card, these customize its rows (default: a single full-time row), and configuring entries enables the card on absolute formats",
isTimezoneShown:
diff --git a/packages/core/src/Timestamp/Timestamp.test.tsx b/packages/core/src/Timestamp/Timestamp.test.tsx
index 66617cb216..2fb5a0e4b9 100644
--- a/packages/core/src/Timestamp/Timestamp.test.tsx
+++ b/packages/core/src/Timestamp/Timestamp.test.tsx
@@ -1,5 +1,12 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
+/**
+ * @file Timestamp.test.tsx
+ * @input Uses Timestamp, Testing Library, and mocked browser APIs
+ * @output Regression coverage for formatting and the focusable details trigger
+ * @position Colocated Timestamp behavior and accessibility tests
+ */
+
import 'temporal-polyfill/full/global';
import {
describe,
@@ -43,12 +50,7 @@ async function openTimestampHoverCard(): Promise<HTMLElement> {
if (timestamp == null) {
throw new Error('Expected Timestamp to render a <time> element');
}
- const trigger = timestamp.parentElement;
- if (trigger == null) {
- throw new Error('Expected Timestamp to render a hover-card trigger');
- }
-
- fireEvent.mouseEnter(trigger);
+ await userEvent.hover(timestamp);
await waitFor(() => {
expect(HTMLElement.prototype.showPopover).toHaveBeenCalled();
});
@@ -770,9 +772,15 @@ describe('Timestamp', () => {
// installs fake timers, which would stall them).
vi.useRealTimers();
- // Mock the Popover API, which jsdom does not implement.
- HTMLElement.prototype.showPopover = vi.fn();
- HTMLElement.prototype.hidePopover = vi.fn();
+ // Match HoverCard's Popover API mock so dismissal can observe which
+ // layer is actually open, including the copy button's nested tooltip.
+ const openPopovers = new WeakSet<HTMLElement>();
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ openPopovers.add(this);
+ });
+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
+ openPopovers.delete(this);
+ });
// jsdom does not derive :focus-visible from keyboard focus for a <time>
// element; treat the focused element as focus-visible so the card's
@@ -781,6 +789,9 @@ describe('Timestamp', () => {
(HTMLElement.prototype as any).matches = function (
selector: string,
): boolean {
+ if (selector === ':popover-open') {
+ return openPopovers.has(this);
+ }
if (selector === ':focus-visible') {
return this === document.activeElement;
}
@@ -820,23 +831,39 @@ describe('Timestamp', () => {
expect(screen.getByTestId('ts')).toHaveAttribute('tabindex', '0');
});
- it('does not put aria-expanded on the role-less hover-card trigger', async () => {
- render(
- <Timestamp
- value={Date.now() / 1000 - 3600}
- format="relative"
- data-testid="ts"
- />,
- );
- const trigger = screen.getByTestId('ts').parentElement;
- // The trigger is Text's <span>, which has no role, so aria-expanded is
- // invalid on it (axe aria-allowed-attr, critical). aria-haspopup is
- // global and still advertises the dialog.
- await waitFor(() => {
- expect(trigger).toHaveAttribute('aria-haspopup', 'dialog');
- });
- expect(trigger).not.toHaveAttribute('aria-expanded');
- });
+ it.each([
+ ['relative', {format: 'relative'}],
+ ['relative_short', {format: 'relative_short'}],
+ ['auto', {format: 'auto'}],
+ ['configured absolute', {format: 'date_time', tooltipEntries: [{}]}],
+ ] as const)(
+ 'names the %s details card from the tab stop only while it is open',
+ async (_, props) => {
+ render(
+ <Timestamp
+ value={Date.now() / 1000 - 3600}
+ {...props}
+ data-testid="ts"
+ />,
+ );
+ const trigger = screen.getByTestId('ts');
+ expect(trigger).toHaveAttribute('tabindex', '0');
+ expect(trigger).not.toHaveAttribute('aria-controls');
+ act(() => trigger.focus());
+ const card = await screen.findByRole('dialog', {hidden: true});
+ await waitFor(() => {
+ expect(trigger).toHaveAttribute('aria-controls', card.id);
+ });
+ // The time role supports neither aria-haspopup nor aria-expanded, and
+ // the time keeps its own role.
+ expect(trigger).not.toHaveAttribute('aria-haspopup');
+ expect(trigger).not.toHaveAttribute('aria-expanded');
+ expect(trigger).not.toHaveAttribute('role');
+ expect(trigger.closest('.astryx-timestamp')).not.toHaveAttribute(
+ 'aria-haspopup',
+ );
+ },
+ );
it('shows the hover card when the timestamp receives keyboard focus', async () => {
const user = userEvent.setup();
@@ -875,6 +902,144 @@ describe('Timestamp', () => {
});
const card = screen.getByRole('dialog', {hidden: true});
expect(normalize(card.textContent ?? '')).toContain(normalize(expected));
+ expect(el).toHaveAttribute('aria-controls', card.id);
+ expect(el).not.toHaveAttribute('aria-expanded');
+
+ // Move into the card before dismissing it: focus must return to the
+ // same semantic timestamp that exposed the popup relationship.
+ const copy = screen.getByRole('button', {name: /^Copy /, hidden: true});
+ act(() => copy.focus());
+ expect(copy).toHaveFocus();
+ // The copy button's own tooltip is the topmost layer on focus.
+ if (screen.queryByRole('tooltip', {hidden: true})) {
+ await user.keyboard('{Escape}');
+ }
+ await user.keyboard('{Escape}');
+ await waitFor(() => {
+ expect(el).not.toHaveAttribute('aria-controls');
+ });
+ expect(el).toHaveFocus();
+ expect(el).not.toHaveAttribute('aria-haspopup');
+ });
+
+ it('keeps the ref, caller props, and text styling when a card is attached', async () => {
+ const ref = {current: null as HTMLTimeElement | null};
+ const onFocus = vi.fn();
+ const {rerender} = render(
+ <Timestamp
+ ref={ref}
+ value="2026-02-19T17:00:00Z"
+ format="date_time"
+ tooltipEntries={[{}]}
+ aria-label="Published"
+ aria-controls="related-content"
+ id="published-at"
+ data-source="cms"
+ onFocus={onFocus}
+ type="body"
+ color="primary"
+ weight="bold"
+ className="custom-timestamp"
+ style={{marginInlineStart: 12}}
+ data-testid="ts"
+ />,
+ );
+ const time = screen.getByTestId('ts');
+ expect(ref.current).toBe(time);
+ expect(time).toHaveAttribute('aria-label', 'Published');
+ expect(time).toHaveAttribute('id', 'published-at');
+ expect(time).toHaveAttribute('data-source', 'cms');
+ const text = time.closest('.astryx-timestamp');
+ expect(text).toHaveClass('astryx-text', 'custom-timestamp');
+ expect(text).toHaveAttribute('data-type', 'body');
+ expect(text).toHaveAttribute('data-color', 'primary');
+ expect(text).toHaveStyle({marginInlineStart: '12px'});
+
+ act(() => time.focus());
+ const card = await screen.findByRole('dialog', {hidden: true});
+ await waitFor(() => {
+ expect(time).toHaveAttribute(
+ 'aria-controls',
+ `related-content ${card.id}`,
+ );
+ });
+ expect(onFocus).toHaveBeenCalledOnce();
+
+ rerender(
+ <Timestamp
+ ref={ref}
+ value="2026-02-19T17:00:00Z"
+ format="date_time"
+ tooltipEntries={[{}]}
+ hasTooltip={false}
+ aria-controls="related-content"
+ data-testid="ts"
+ />,
+ );
+ expect(ref.current).toBe(screen.getByTestId('ts'));
+ expect(ref.current).not.toHaveAttribute('tabindex');
+ expect(ref.current).not.toHaveAttribute('aria-haspopup');
+ expect(ref.current).toHaveAttribute('aria-controls', 'related-content');
+ expect(
+ screen.queryByRole('dialog', {hidden: true}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('keeps a caller aria-controls changed while the card is open', async () => {
+ const props = {
+ value: '2026-02-19T17:00:00Z',
+ format: 'date_time',
+ tooltipEntries: [{}],
+ 'data-testid': 'ts',
+ } as const;
+ const {rerender} = render(<Timestamp {...props} aria-controls="first" />);
+ const time = screen.getByTestId('ts');
+ act(() => time.focus());
+ const card = await screen.findByRole('dialog', {hidden: true});
+ await waitFor(() => {
+ expect(time).toHaveAttribute('aria-controls', `first ${card.id}`);
+ });
+
+ rerender(<Timestamp {...props} aria-controls="second" />);
+ await waitFor(() => {
+ expect(time).toHaveAttribute('aria-controls', `second ${card.id}`);
+ });
+
+ act(() => time.blur());
+ await waitFor(() => {
+ expect(time).toHaveAttribute('aria-controls', 'second');
+ });
+ });
+
+ it('names no card after an open card is removed and a new one attaches', async () => {
+ const view = (hasTooltip: boolean) => (
+ <>
+ <Timestamp
+ value="2026-02-19T17:00:00Z"
+ format="date_time"
+ tooltipEntries={[{}]}
+ hasTooltip={hasTooltip}
+ data-testid="ts"
+ />
+ <button type="button">Elsewhere</button>
+ </>
+ );
+ const {rerender} = render(view(true));
+ const time = screen.getByTestId('ts');
+ act(() => time.focus());
+ const card = await screen.findByRole('dialog', {hidden: true});
+ await waitFor(() => {
+ expect(time).toHaveAttribute('aria-controls', card.id);
+ });
+
+ // The open card unmounts without a hide. Focus then moves on, and a new
+ // card attaches closed.
+ rerender(view(false));
+ act(() => screen.getByRole('button', {name: 'Elsewhere'}).focus());
+ rerender(view(true));
+ await act(async () => {});
+ expect(time).toHaveAttribute('tabindex', '0');
+ expect(time).not.toHaveAttribute('aria-controls');
});
it('keeps the default hover-card row in the viewer zone with timezoneID set', async () => {
diff --git a/packages/core/src/Timestamp/Timestamp.tsx b/packages/core/src/Timestamp/Timestamp.tsx
index 9f0f16f5a7..97aea75582 100644
--- a/packages/core/src/Timestamp/Timestamp.tsx
+++ b/packages/core/src/Timestamp/Timestamp.tsx
@@ -4,9 +4,10 @@
/**
* @file Timestamp.tsx
- * @input Uses React, Text, provider locale and calendar, and Timestamp formatters
+ * @input Uses React, Text, lazy TimestampHoverCard, provider locale and
+ * calendar, and Timestamp formatters
* @output Exports Timestamp component and related types
- * @position Core implementation; renders formatted timestamps
+ * @position Core implementation; a stable time node anchors lazily attached details
*
* SYNC: When modified, update these files to stay in sync:
* - /packages/core/src/Timestamp/formatRelativeTime.ts
@@ -34,6 +35,7 @@ import {useLocale} from '../i18n/useLocale';
import {useCalendarSystem} from '../i18n/useCalendarSystem';
import type {BaseProps} from '../BaseProps';
import {themeProps} from '../utils/themeProps';
+import {mergeIds} from '../HoverCard/mergeIds';
import {formatInstant, formatZoneName} from './formatInstant';
import {formatRelativeTime} from './formatRelativeTime';
import {formatTooltipLines, resolveTimezoneID} from './tooltipEntries';
@@ -115,7 +117,7 @@ export interface TimestampProps extends BaseProps<HTMLTimeElement> {
*/
autoThreshold?: number;
/**
- * Whether to show a hover card with the full date/time on hover. The card
+ * Whether to show a card with the full date/time on hover or keyboard focus. The card
* is copyable — its default single row carries the full absolute time — and
* `tooltipEntries` customizes its rows.
* @default true
@@ -329,6 +331,8 @@ export function Timestamp({
canReadClockOnClient,
canReadClockOnServer,
);
+ // The open card's id, which the card reports as it shows and hides.
+ const [openCardId, setOpenCardId] = useState<string | null>(null);
const [now, setNow] = useState<Date | null>(() =>
needsClock && canReadClock ? new Date() : null,
);
@@ -422,11 +426,6 @@ export function Timestamp({
!isValidDate,
);
- // Placed after all hooks so the hook order stays stable across renders.
- if (!isValidDate) {
- return null;
- }
-
// An empty array is not a second way to spell "off" — `hasTooltip` stays the
// only on/off axis — so normalize it away before anything reads it.
const entries =
@@ -439,7 +438,20 @@ export function Timestamp({
// `format` silently suppress another prop's output, so entry presence opens
// it too. With no entries this reduces to the original condition exactly.
const showTooltip =
- hasTooltip && (isRelativeFormat(effectiveFormat) || entries !== undefined);
+ isValidDate &&
+ hasTooltip &&
+ (isRelativeFormat(effectiveFormat) || entries !== undefined);
+
+ // A card that unmounts while open never reports its hide. Without a card,
+ // forget its id, so the time names no element that is gone.
+ if (!showTooltip && openCardId !== null) {
+ setOpenCardId(null);
+ }
+
+ // Placed after all hooks so the hook order stays stable across renders.
+ if (!isValidDate) {
+ return null;
+ }
// The rows the hover card renders: the configured entries, or the single
// default absolute line shown when none are set. Either way the surface is
@@ -462,68 +474,59 @@ export function Timestamp({
);
const timeElement = (
- <Text
- type={type}
- size={size}
- color={color}
- weight={weight}
- xstyle={xstyle}
- {...timestampProps}>
- <time
- ref={mergedTimeRef}
- dateTime={isoString}
- data-testid={testId}
- {...stylex.props(styles.time)}
- {...rest}
- // `ariaLabelText` is '' only for an invalid date, which bails out
- // before rendering — but keep the guard local: an empty aria-label
- // must be omitted entirely (not rendered as aria-label="") so AT
- // falls back to reading the visible <time> content.
- // A caller's own name wins (`component:Timestamp` FR5).
- {...(isRelativeFormat(effectiveFormat) &&
- ariaLabelText !== '' &&
- rest['aria-label'] == null
- ? {'aria-label': ariaLabelText}
- : {})}
- // The hover card is anchored here with focusTrigger="always", which
- // attaches focus listeners but does not itself make the anchor
- // focusable. A bare <time> is not focusable, so without a tab stop
- // sighted keyboard users could never reveal the card (WCAG 1.4.13 /
- // 2.1.1). Add the tab stop only while a card is actually attached — no
- // gratuitous tab stops otherwise. The card carries its own
- // dashed-underline hover indication as the affordance, so the anchor
- // needs no separate focus outline.
- // A caller's own tabIndex wins (`component:Timestamp` FR9).
- {...(showTooltip && rest.tabIndex == null ? {tabIndex: 0} : {})}>
- {displayText}
- </time>
- </Text>
+ <time
+ ref={mergedTimeRef}
+ dateTime={isoString}
+ data-testid={testId}
+ {...stylex.props(styles.time)}
+ {...rest}
+ // `ariaLabelText` is '' only for an invalid date, which bails out
+ // before rendering — but keep the guard local: an empty aria-label
+ // must be omitted entirely (not rendered as aria-label="") so AT
+ // falls back to reading the visible <time> content.
+ // A caller's own name wins.
+ {...(isRelativeFormat(effectiveFormat) &&
+ ariaLabelText !== '' &&
+ rest['aria-label'] == null
+ ? {'aria-label': ariaLabelText}
+ : {})}
+ // A bare <time> cannot take focus. Add the tab stop only while a card
+ // is attached, so keyboard users can open it. A caller's tabIndex wins.
+ {...(showTooltip && rest.tabIndex == null ? {tabIndex: 0} : {})}
+ // The time names the open card; a caller's own ids stay first. The time
+ // role supports neither aria-haspopup nor aria-expanded.
+ {...(showTooltip && openCardId != null
+ ? {'aria-controls': mergeIds(rest['aria-controls'], openCardId)}
+ : {})}>
+ {displayText}
+ </time>
);
- if (showTooltip) {
- // One surface for every timestamp that shows one: the copyable hover card,
- // loaded lazily so the default card-less path never bundles it. Each line
- // becomes a labelled row with its own copy button. With no configured
- // entries this is a single row carrying the full absolute time, itself
- // copyable — so hovering a relative timestamp reveals the full time and
- // lets the reader copy it. Opens on hover and on keyboard focus (the
- // <time> tab stop above), with the dashed-underline affordance signalling
- // it is interactive.
- //
- // While the chunk loads the bare <time> stays visible (the Suspense
- // fallback), so nothing disappears — the card simply attaches once ready.
- return (
- <Suspense fallback={timeElement}>
- <LazyTimestampHoverCard
- lines={lines}
- label={t('@astryx.timestamp.detailsLabel')}>
- {timeElement}
- </LazyTimestampHoverCard>
- </Suspense>
- );
- }
-
- return timeElement;
+ // Keep the focusable node outside Suspense. Attaching the lazy overlay must
+ // not replace a timestamp the reader focused while its chunk was loading.
+ return (
+ <>
+ <Text
+ type={type}
+ size={size}
+ color={color}
+ weight={weight}
+ xstyle={xstyle}
+ {...timestampProps}>
+ {timeElement}
+ </Text>
+ {showTooltip && (
+ <Suspense fallback={null}>
+ <LazyTimestampHoverCard
+ lines={lines}
+ label={t('@astryx.timestamp.detailsLabel')}
+ triggerRef={timeRef}
+ onCardOpenChange={setOpenCardId}
+ />
+ </Suspense>
+ )}
+ </>
+ );
}
Timestamp.displayName = 'Timestamp';
diff --git a/packages/core/src/Timestamp/TimestampHoverCard.tsx b/packages/core/src/Timestamp/TimestampHoverCard.tsx
index 5ba867c881..bce42f61dc 100644
--- a/packages/core/src/Timestamp/TimestampHoverCard.tsx
+++ b/packages/core/src/Timestamp/TimestampHoverCard.tsx
@@ -4,8 +4,8 @@
/**
* @file TimestampHoverCard.tsx
- * @input Uses React, HoverCard, IconButton, the theme's `timestamp-copy` icon
- * slot, formatted lines
+ * @input Uses React, useHoverCard, a stable time ref, IconButton, the theme's
+ * `timestamp-copy` icon slot, formatted lines
* @output Default-exports the lazily-loaded copyable hover card for Timestamp
* @position Split out of Timestamp so the overlay (HoverCard) and the copy
* affordance's Icon/IconButton load only when a card is actually shown — the
@@ -21,15 +21,16 @@
* is visually hidden. A card with no labels drops the label column.
*
* SYNC: When modified, update these files to stay in sync:
- * - /packages/core/src/Timestamp/Timestamp.tsx (the lazy() + Suspense wrapper)
+ * - /packages/core/src/Timestamp/Timestamp.tsx (the persistent trigger and lazy attachment)
* - /packages/core/src/Timestamp/Timestamp.doc.mjs (theming.targets)
* - /packages/core/src/Timestamp/Timestamp.test.tsx
*/
-import type {ReactNode} from 'react';
-import {useCallback} from 'react';
+import type {ReactNode, RefObject} from 'react';
+import {useCallback, useRef} from 'react';
import * as stylex from '@stylexjs/stylex';
-import {HoverCard} from '../HoverCard/HoverCard';
+import {useHoverCard} from '../HoverCard/useHoverCard';
+import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
import {IconButton} from '../IconButton/IconButton';
import {ComponentIcon} from '../Icon/ComponentIcon';
import {useClipboard} from '../hooks/useClipboard';
@@ -226,8 +227,13 @@ export interface TimestampHoverCardProps {
lines: ReadonlyArray<TimestampTooltipLine>;
/** Accessible name for the card. */
label: string;
- /** The anchor the card is attached to (the `<time>` element). */
- children: ReactNode;
+ /** Persistent anchor, rendered outside the lazy boundary. */
+ triggerRef: RefObject<HTMLTimeElement | null>;
+ /**
+ * Reports the open card's id when it shows, and null when it hides, so the
+ * time can name it through `aria-controls`.
+ */
+ onCardOpenChange: (cardId: string | null) => void;
}
function gridTemplateFor(
@@ -258,8 +264,51 @@ function gridTemplateFor(
export default function TimestampHoverCard({
lines,
label,
- children,
+ triggerRef,
+ onCardOpenChange,
}: TimestampHoverCardProps): ReactNode {
+ const cardIdRef = useRef<string | null>(null);
+ const handleShow = useCallback(() => {
+ onCardOpenChange(cardIdRef.current);
+ }, [onCardOpenChange]);
+ const handleHide = useCallback(() => {
+ onCardOpenChange(null);
+ }, [onCardOpenChange]);
+ const {positionRef, interactionRef, id, show, renderHoverCard} = useHoverCard(
+ {
+ placement: 'above',
+ focusTrigger: 'always',
+ label,
+ onShow: handleShow,
+ onHide: handleHide,
+ },
+ );
+
+ const didAttachRef = useRef(false);
+ // Syncs the hover card's anchor and listeners with the <time> that
+ // Timestamp renders outside this lazy module.
+ useIsomorphicLayoutEffect(() => {
+ const trigger = triggerRef.current;
+ if (!trigger) {
+ return;
+ }
+ cardIdRef.current = id;
+ positionRef(trigger);
+ interactionRef(trigger);
+ // Focus can reach the time before this module loads. Open the card only
+ // if the time still has focus.
+ if (!didAttachRef.current) {
+ didAttachRef.current = true;
+ if (trigger.ownerDocument.activeElement === trigger) {
+ show();
+ }
+ }
+ return () => {
+ positionRef(null);
+ interactionRef(null);
+ };
+ }, [triggerRef, positionRef, interactionRef, show, id]);
+
// A label column is only reserved when some row is labelled; otherwise the
// value sits flush at the card's leading edge. An action column is only
// reserved when some row is copyable (option B), so a fully read-only card
@@ -287,16 +336,7 @@ export default function TimestampHoverCard({
</dl>
);
- return (
- <HoverCard
- content={cardContent}
- placement="above"
- focusTrigger="always"
- hasHoverIndication
- label={label}>
- {children}
- </HoverCard>
- );
+ return renderHoverCard(cardContent);
}
TimestampHoverCard.displayName = 'TimestampHoverCard';