Skip to content

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

TypeScript

feat(timestamp): add an opt-in copyable multi-timezone hover card (#4582)

freddymeta18d98f4eb7a7
diff --git a/.changeset/timestamp-copyable-hover-card.md b/.changeset/timestamp-copyable-hover-card.md
new file mode 100644
index 0000000000..65c52a2956
--- /dev/null
+++ b/.changeset/timestamp-copyable-hover-card.md
@@ -0,0 +1,11 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Timestamp: the hover surface is now a single copyable hover card for every timestamp that shows one. Relative timestamps and `tooltipEntries`-configured timestamps share one card, replacing the old read-only tooltip; the default single row carries the full absolute time and is itself copyable.
+
+Each `tooltipEntries` row opts into a copy button via `isCopyable` (default `false`) — so a card can mix human-readable, read-only rows with a copyable machine value (e.g. show local and UTC for reading, but only let readers grab the `system_date_time` value). Copyable rows render their copy button in a dedicated trailing action column so the buttons align down one column regardless of value width; that column is only reserved when some row is copyable, so a fully read-only card carries no trailing gutter. The card's labels use the `supporting` text role (the secondary, quieter register that is Timestamp's own default) and values the `body` role.
+
+This is a behavior and visual change for relative timestamps — hovering now reveals a copyable card instead of a plain tooltip.
+
+@freddymeta
diff --git a/apps/storybook/stories/Timestamp.stories.tsx b/apps/storybook/stories/Timestamp.stories.tsx
index 2f5844f39a..7c5f8e26e0 100644
--- a/apps/storybook/stories/Timestamp.stories.tsx
+++ b/apps/storybook/stories/Timestamp.stories.tsx
@@ -80,7 +80,7 @@ const meta: Meta<typeof Timestamp> = {
},
hasTooltip: {
control: 'boolean',
- description: 'Show tooltip on hover',
+ description: 'Show copyable hover card on hover',
},
isTimezoneShown: {
control: 'boolean',
@@ -188,12 +188,13 @@ export const TimeFormat: Story = {
};
export const TooltipTimezones: Story = {
- name: 'Tooltip — multiple time zones',
+ name: 'Hover card — configuration examples',
render: () => (
<div style={{display: 'flex', flexDirection: 'column', gap: '32px'}}>
<div>
<Text type="supporting" color="secondary">
- Local + UTC, default format — hover or tab to the timestamp
+ Local + UTC, default format — hover or tab to the timestamp, then copy
+ any row
</Text>
<div>
<Timestamp
@@ -208,7 +209,7 @@ export const TooltipTimezones: Story = {
</div>
<div>
<Text type="supporting" color="secondary">
- Three labelled zones — the widest case the 300px tooltip holds
+ Three labelled zones — the widest case the card holds
</Text>
<div>
<Timestamp
@@ -261,6 +262,112 @@ export const TooltipTimezones: Story = {
),
};
+export const CopyableHoverCard: Story = {
+ name: 'Copyable hover card',
+ render: () => (
+ <div style={{display: 'flex', flexDirection: 'column', gap: '32px'}}>
+ <div>
+ <Text type="supporting" color="secondary">
+ Local, UTC, another zone, and Unix seconds — hover or tab, then copy
+ any row
+ </Text>
+ <div>
+ <Timestamp
+ value="2026-02-19T17:00:00Z"
+ format="relative"
+ tooltipEntries={[
+ {label: 'Local'},
+ {timezoneID: 'UTC', label: 'UTC'},
+ {
+ timezoneID: 'Asia/Tokyo',
+ format: 'date_time',
+ label: 'Tokyo',
+ },
+ {
+ timezoneID: 'UTC',
+ format: 'system_date_time',
+ label: 'ISO (UTC)',
+ },
+ ]}
+ />
+ </div>
+ </div>
+ <div>
+ <Text type="supporting" color="secondary">
+ A single UTC entry — one copyable row, on an absolute format that has
+ no hover card of its own
+ </Text>
+ <div>
+ <Timestamp
+ value="2026-02-19T17:00:00Z"
+ format="date_time"
+ tooltipEntries={[{timezoneID: 'UTC', label: 'UTC'}]}
+ />
+ </div>
+ </div>
+ </div>
+ ),
+};
+
+export const PerEntryCopyable: Story = {
+ name: 'Per-entry copyable',
+ render: () => (
+ <div style={{display: 'flex', flexDirection: 'column', gap: '32px'}}>
+ <div>
+ <Text type="supporting" color="secondary">
+ Mixed: human-readable rows are read-only; only the machine value opts
+ into a copy button
+ </Text>
+ <div>
+ <Timestamp
+ value="2026-02-19T17:00:00Z"
+ format="relative"
+ tooltipEntries={[
+ {label: 'Local'},
+ {timezoneID: 'UTC', label: 'UTC'},
+ {
+ timezoneID: 'UTC',
+ format: 'system_date_time',
+ label: 'ISO (UTC)',
+ isCopyable: true,
+ },
+ ]}
+ />
+ </div>
+ </div>
+ <div>
+ <Text type="supporting" color="secondary">
+ Fully read-only card — no row opts in, so there is no copy button and
+ no trailing action column
+ </Text>
+ <div>
+ <Timestamp
+ value="2026-02-19T17:00:00Z"
+ format="relative"
+ tooltipEntries={[
+ {label: 'Local'},
+ {timezoneID: 'UTC', label: 'UTC'},
+ ]}
+ />
+ </div>
+ </div>
+ <div>
+ <Text type="supporting" color="secondary">
+ Single read-only row with no label — the value sits flush at the
+ leading edge
+ </Text>
+ <div>
+ <Timestamp
+ value="2026-02-19T17:00:00Z"
+ format="relative"
+ tooltipEntries={[{}]}
+ />
+ </div>
+ </div>
+ </div>
+ ),
+};
+
export const SystemFormats: Story = {
render: () => (
<div style={{display: 'flex', flexDirection: 'column', gap: '8px'}}>
diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json
index 6c01fc789b..04d47bcdf3 100644
--- a/packages/core/locales/en.json
+++ b/packages/core/locales/en.json
@@ -923,6 +923,18 @@
"defaultMessage": "Clear {label}",
"description": "Screen-reader-only label on the X that clears the value from a TimeInput. Example: `Clear Start time`."
},
+ "@astryx.timestamp.copyValue": {
+ "defaultMessage": "Copy {value}",
+ "description": "Aria label on a Timestamp copyable-hover-card row's copy button, in its default state. `value` is the formatted instant that row shows (e.g. `Copy February 19, 2026 at 5:00:00 PM UTC`). Imperative verb. Pairs with `timestamp.copied` (post-click state)."
+ },
+ "@astryx.timestamp.copied": {
+ "defaultMessage": "Copied",
+ "description": "Aria label on a Timestamp copy button for ~1.5s after a successful copy, and the text announced to a polite live region. Past-participle (\"has been copied\"); pairs with `timestamp.copyValue`."
+ },
+ "@astryx.timestamp.detailsLabel": {
+ "defaultMessage": "Timestamp details",
+ "description": "Accessible name for the Timestamp copyable hover card popup, which lists the instant in the configured time zones/formats with a copy button per row."
+ },
"@astryx.token.remove": {
"defaultMessage": "Remove {label}",
"description": "Screen-reader-only label on the \"×\" on an individual Token/chip. Example: `Remove John Smith`, `Remove Active`. Imperative verb."
diff --git a/packages/core/src/Timestamp/Timestamp.doc.mjs b/packages/core/src/Timestamp/Timestamp.doc.mjs
index 7b4c3f803a..b71882405a 100644
--- a/packages/core/src/Timestamp/Timestamp.doc.mjs
+++ b/packages/core/src/Timestamp/Timestamp.doc.mjs
@@ -42,14 +42,14 @@ export const docs = {
name: 'hasTooltip',
type: 'boolean',
description:
- 'Whether to show a tooltip with the full date/time on hover when displaying relative time.',
+ '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.',
default: 'true',
},
{
name: 'tooltipEntries',
- type: 'ReadonlyArray<{timezoneID?: string; format?: TimestampTooltipFormat; label?: string}>',
+ type: 'ReadonlyArray<{timezoneID?: string; format?: TimestampTooltipFormat; label?: string; isCopyable?: boolean}>',
description:
- "Lines to show in the hover tooltip, so one instant can be read in several time zones and/or formats at once. Each entry is one line, in the order given. Omit timezoneID (or pass 'local') for the viewer's own zone; format defaults to the full absolute style and also accepts 'full' alongside every non-relative TimestampFormat. Configuring entries also attaches the tooltip to absolute formats, which otherwise have none.",
+ "Lines to show on hover, so one instant can be read — and optionally copied — in several time zones and/or formats at once. Each entry is one line, in the order given. Omit timezoneID (or pass 'local') for the viewer's own zone; format defaults to the full absolute style and also accepts 'full' alongside every non-relative TimestampFormat. Rows are read-only unless they set isCopyable (default false); copyable rows show a copy button in a dedicated trailing action column so buttons align, and the column is only present when some row is copyable. With no entries the card shows a single default row with the full absolute time, which is copyable. Configuring entries also attaches the surface to absolute formats, which otherwise have none.",
},
{
name: 'isTimezoneShown',
@@ -91,6 +91,7 @@ export const docs = {
theming: {
targets: [
{className: 'astryx-timestamp', visualProps: ['type', 'color', 'format']},
+ {className: 'astryx-timestamp-copy-button'},
],
},
usage: {
@@ -103,16 +104,18 @@ export const docs = {
{guidance: true, description: 'Use tooltipEntries when readers must compare zones, such as an incident log where the reader\'s time and the event\'s origin zone both matter.'},
{guidance: true, description: 'Label every entry once a tooltip shows more than one zone; a bare abbreviation is not always recognizable (Tokyo renders as "GMT+9", not "JST").'},
{guidance: true, description: 'Use isLive for active dashboards or real-time feeds so the relative time stays accurate without a page refresh.'},
+ {guidance: true, description: 'Reach for tooltipEntries when readers need to grab an exact value — an incident log or deploy record where someone pastes the UTC time or Unix seconds elsewhere; configuring entries turns the hover into copy-to-clipboard rows.'},
{guidance: false, description: 'Don\'t display raw Unix timestamps or ISO strings to users; always pass them through Timestamp to get a human-readable format.'},
{guidance: false, description: 'Avoid system_date or system_time formats in user-facing UI; they are meant for developer tools, logs, and machine-readable contexts.'},
- {guidance: false, description: 'Don\'t disable the tooltip on relative timestamps; users expect to hover for the full date when they see "3 hours ago".'},
- {guidance: false, description: 'Don\'t stack many zones into one tooltip; it is capped at 300px wide and long labelled lines wrap. Two or three entries read well.'},
+ {guidance: false, description: 'Don\'t disable the hover card on relative timestamps; users expect to hover for the full date when they see "3 hours ago".'},
+ {guidance: false, description: 'Don\'t stack many zones into one card; it is capped at 300px wide and long labelled lines wrap. Two or three entries read well.'},
{guidance: false, description: 'Don\'t pass a fixed-offset abbreviation like "EST" as timezoneID; it is a valid identifier but never observes daylight saving, so it reads an hour wrong for half the year. Use the region id, "America/New_York".'},
],
anatomy: [
{name: 'Formatted text', required: true, description: 'The rendered date, time, or relative label like "2 hours ago" or "Mar 21, 2025".'},
- {name: 'Tooltip', required: false, description: 'A hover card showing the full absolute date and time when the display is relative, or the lines configured via tooltipEntries.'},
- {name: 'Tooltip entry', required: false, description: 'One line of the tooltip: an optional label beside the instant rendered in one time zone and format.'},
+ {name: 'Hover card', required: false, description: 'A copyable hover card showing the full absolute date and time when the display is relative, or the rows configured via tooltipEntries. Its default single row carries the full absolute time.'},
+ {name: 'Hover card row', required: false, description: 'One row of the card: an optional label beside the instant rendered in one time zone and format. Rows opt into a copy button via isCopyable.'},
+ {name: 'Copy button', required: true, description: 'Per-row copy-to-clipboard button in the hover card; copies that row\'s formatted value.'},
],
},
};
@@ -123,9 +126,9 @@ export const docsZh = {
value: '\u8981\u663e\u793a\u7684\u65e5\u671f/\u65f6\u95f4\u3002\u63a5\u53d7 Unix \u65f6\u95f4\u6233\uff08\u79d2\uff09\u6216 ISO 8601 \u5b57\u7b26\u4e32\u3002',
format: "\u663e\u793a\u683c\u5f0f\u3002'relative' \u663e\u793a '2\u5c0f\u65f6\u524d'\uff0c'date' \u663e\u793a\u65e5\u671f\uff0c'date_long' \u663e\u793a\u957f\u6708\u4efd\u65e5\u671f\uff0c'date_weekday' \u663e\u793a\u661f\u671f+\u65e5\u671f\uff0c'auto' \u6839\u636e\u65f6\u95f4\u8fdc\u8fd1\u81ea\u52a8\u5207\u6362\u3002",
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\u5de5\u5177\u63d0\u793a\uff08\u76f8\u5bf9\u65f6\u95f4\u6a21\u5f0f\uff09\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',
tooltipEntries:
- '\u5de5\u5177\u63d0\u793a\u4e2d\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\uff08\u6216\u4f20\u5165 \'local\'\uff09\u8868\u793a\u67e5\u770b\u8005\u672c\u5730\u65f6\u533a\u3002\u914d\u7f6e\u540e\uff0c\u7edd\u5bf9\u65f6\u95f4\u683c\u5f0f\u4e5f\u4f1a\u663e\u793a\u5de5\u5177\u63d0\u793a\u3002',
+ '\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\uff08\u6216\u4f20\u5165 \'local\'\uff09\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:
'\u662f\u5426\u5728\u53ef\u89c1\u6587\u672c\u540e\u9644\u52a0\u65f6\u533a\u7f29\u5199\uff08\u4ec5 date_time \u548c time\uff1bsystem_* \u683c\u5f0f\u4e0d\u9644\u52a0\uff09\u3002',
isLive: '\u76f8\u5bf9\u65f6\u95f4\u662f\u5426\u5b9e\u65f6\u66f4\u65b0\u3002',
@@ -144,23 +147,25 @@ export const docsZh = {
{guidance: true, description: 'Use tooltipEntries when readers must compare zones, such as an incident log where the reader\'s time and the event\'s origin zone both matter.'},
{guidance: true, description: 'Label every entry once a tooltip shows more than one zone; a bare abbreviation is not always recognizable (Tokyo renders as "GMT+9", not "JST").'},
{guidance: true, description: 'Use isLive for active dashboards or real-time feeds so the relative time stays accurate without a page refresh.'},
+ {guidance: true, description: 'Reach for tooltipEntries when readers need to grab an exact value — an incident log or deploy record where someone pastes the UTC time or Unix seconds elsewhere; configuring entries turns the hover into copy-to-clipboard rows.'},
{guidance: false, description: 'Don\'t display raw Unix timestamps or ISO strings to users; always pass them through Timestamp to get a human-readable format.'},
{guidance: false, description: 'Avoid system_date or system_time formats in user-facing UI; they are meant for developer tools, logs, and machine-readable contexts.'},
- {guidance: false, description: 'Don\'t disable the tooltip on relative timestamps; users expect to hover for the full date when they see "3 hours ago".'},
- {guidance: false, description: 'Don\'t stack many zones into one tooltip; it is capped at 300px wide and long labelled lines wrap. Two or three entries read well.'},
+ {guidance: false, description: 'Don\'t disable the hover card on relative timestamps; users expect to hover for the full date when they see "3 hours ago".'},
+ {guidance: false, description: 'Don\'t stack many zones into one card; it is capped at 300px wide and long labelled lines wrap. Two or three entries read well.'},
{guidance: false, description: 'Don\'t pass a fixed-offset abbreviation like "EST" as timezoneID; it is a valid identifier but never observes daylight saving, so it reads an hour wrong for half the year. Use the region id, "America/New_York".'},
],
anatomy: [
{name: 'Formatted text', required: true, description: 'The rendered date, time, or relative label like "2 hours ago" or "Mar 21, 2025".'},
- {name: 'Tooltip', required: false, description: 'A hover card showing the full absolute date and time when the display is relative, or the lines configured via tooltipEntries.'},
- {name: 'Tooltip entry', required: false, description: 'One line of the tooltip: an optional label beside the instant rendered in one time zone and format.'},
+ {name: 'Hover card', required: false, description: 'A copyable hover card showing the full absolute date and time when the display is relative, or the rows configured via tooltipEntries. Its default single row carries the full absolute time.'},
+ {name: 'Hover card row', required: false, description: 'One row of the card: an optional label beside the instant rendered in one time zone and format. Rows opt into a copy button via isCopyable.'},
+ {name: 'Copy button', required: true, description: 'Per-row copy-to-clipboard button in the hover card; copies that row\'s formatted value.'},
],
},
};
/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */
export const docsDense = {
- description: 'formatted timestamp with relative/absolute/auto modes, live updates, timezone display, multi-zone tooltip',
+ description: 'formatted timestamp with relative/absolute/auto modes, live updates, timezone display, and a copyable multi-zone hover card (default single full-time row, customized via tooltipEntries)',
usage: {
description:
'Timestamp formats a date or time into readable text. Use for creation dates, update times, or schedules; relative for recency, absolute for precision, auto to switch automatically.',
@@ -173,8 +178,8 @@ export const docsDense = {
{guidance: true, description: 'isLive for dashboards so relative time stays current.'},
{guidance: false, description: 'Don\'t show raw Unix timestamps or ISO strings; always use Timestamp.'},
{guidance: false, description: 'Avoid system_* formats in user-facing UI; those are for dev tools and logs.'},
- {guidance: false, description: 'Don\'t disable tooltip on relative timestamps; users expect the full date on hover.'},
- {guidance: false, description: 'Don\'t stack many zones in one tooltip; it caps at 300px and long labels wrap. Two or three read well.'},
+ {guidance: false, description: 'Don\'t disable the hover card on relative timestamps; users expect the full date on hover.'},
+ {guidance: false, description: 'Don\'t stack many zones in one card; it caps at 300px and long labels wrap. Two or three read well.'},
{guidance: false, description: 'Don\'t use fixed-offset ids like "EST" for timezoneID; they skip DST. Use region ids like "America/New_York".'},
],
},
@@ -182,9 +187,9 @@ export const docsDense = {
value: 'date/time as unix seconds or ISO string',
format: "display mode: 'relative', 'auto', 'date', 'date_long', 'date_weekday', 'date_time', 'time', 'system_date', 'system_date_time', 'system_time'",
autoThreshold: 'seconds threshold for auto relative\u2192date_time switch',
- hasTooltip: 'show full time tooltip on hover (relative mode)',
+ hasTooltip: 'show copyable full-time hover card on hover (relative mode, or any format with tooltipEntries)',
tooltipEntries:
- "tooltip lines across zones/formats: [{timezoneID?, format?, label?}]; timezoneID omitted or 'local' = viewer zone, format defaults to 'full'; also enables the tooltip on absolute formats",
+ "hover rows across zones/formats: [{timezoneID?, format?, label?}]; timezoneID omitted or 'local' = 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:
'append timezone abbreviation to visible text (date_time and time only)',
isLive: 'live-update relative time',
diff --git a/packages/core/src/Timestamp/Timestamp.test.tsx b/packages/core/src/Timestamp/Timestamp.test.tsx
index 3867c1b409..33bb91dfb9 100644
--- a/packages/core/src/Timestamp/Timestamp.test.tsx
+++ b/packages/core/src/Timestamp/Timestamp.test.tsx
@@ -1,12 +1,30 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
-import {render, screen, act, waitFor} from '@testing-library/react';
+import {
+ describe,
+ it,
+ expect,
+ vi,
+ beforeAll,
+ beforeEach,
+ afterEach,
+} from 'vitest';
+import {render, screen, act, waitFor, fireEvent} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {Timestamp} from './Timestamp';
import {formatTooltipLines} from './tooltipEntries';
+import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
+import {InternationalizationProvider} from '../i18n';
describe('Timestamp', () => {
+ // The hover card is loaded lazily (React.lazy + Suspense), so its chunk
+ // resolves asynchronously the first time a card renders. Warm the module
+ // cache once up front so findByRole('dialog') never races the cold import's
+ // resolution against its default 1s timeout.
+ beforeAll(async () => {
+ await import('./TimestampHoverCard');
+ });
+
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-03-25T12:00:00Z'));
@@ -504,17 +522,17 @@ describe('Timestamp', () => {
}
});
- // --- Tooltip keyboard reachability (WCAG 1.4.13 / 2.1.1) ---
+ // --- Hover card keyboard reachability (WCAG 1.4.13 / 2.1.1) ---
- describe('tooltip keyboard reachability', () => {
+ describe('hover card keyboard reachability', () => {
const originalMatches = HTMLElement.prototype.matches;
const originalShowPopover = HTMLElement.prototype.showPopover;
const originalHidePopover = HTMLElement.prototype.hidePopover;
beforeEach(() => {
- // The tooltip is lazy-loaded via a dynamic import; real timers let the
- // import promise and RTL's waitFor resolve naturally (the outer
- // beforeEach installs fake timers, which would stall them).
+ // The card content renders inline in a (mocked) popover; real timers let
+ // RTL's findBy* and the async paths resolve (the outer beforeEach
+ // installs fake timers, which would stall them).
vi.useRealTimers();
// Mock the Popover API, which jsdom does not implement.
@@ -522,7 +540,7 @@ describe('Timestamp', () => {
HTMLElement.prototype.hidePopover = vi.fn();
// jsdom does not derive :focus-visible from keyboard focus for a <time>
- // element; treat the focused element as focus-visible so the tooltip's
+ // element; treat the focused element as focus-visible so the card's
// keyboard-focus path can be exercised.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(HTMLElement.prototype as any).matches = function (
@@ -542,7 +560,7 @@ describe('Timestamp', () => {
HTMLElement.prototype.hidePopover = originalHidePopover;
});
- it('makes the <time> element focusable while the tooltip is attached', () => {
+ it('makes the <time> element focusable while the hover card is attached', () => {
render(
<Timestamp
value={Date.now() / 1000 - 3600}
@@ -553,7 +571,7 @@ describe('Timestamp', () => {
expect(screen.getByTestId('ts')).toHaveAttribute('tabindex', '0');
});
- it('shows the tooltip when the timestamp receives keyboard focus', async () => {
+ it('shows the hover card when the timestamp receives keyboard focus', async () => {
const user = userEvent.setup();
render(
<Timestamp
@@ -564,13 +582,13 @@ describe('Timestamp', () => {
);
const el = screen.getByTestId('ts');
- // Wait for the lazy-loaded tooltip layer to mount and confirm it
- // carries the full absolute time (same string as the aria-label).
+ // The card layer mounts inline and carries the full absolute time (the
+ // same string as the aria-label) as its single default copyable row.
// Compare with normalized whitespace: Intl output can contain narrow
// no-break spaces that jest-dom's matcher normalization would break on.
- const layer = await screen.findByRole('tooltip', {hidden: true});
+ const card = await screen.findByRole('dialog', {hidden: true});
const normalize = (s: string) => s.replace(/\s+/g, ' ');
- expect(normalize(layer.textContent ?? '')).toContain(
+ expect(normalize(card.textContent ?? '')).toContain(
normalize(el.getAttribute('aria-label') ?? '\0'),
);
@@ -582,7 +600,7 @@ describe('Timestamp', () => {
});
});
- it('does not add a tab stop when the tooltip is disabled', () => {
+ it('does not add a tab stop when the hover card is disabled', () => {
render(
<Timestamp
value={Date.now() / 1000 - 3600}
@@ -594,7 +612,7 @@ describe('Timestamp', () => {
expect(screen.getByTestId('ts')).not.toHaveAttribute('tabindex');
});
- it('does not add a tab stop for absolute formats (no tooltip)', () => {
+ it('does not add a tab stop for absolute formats (no hover card)', () => {
render(
<Timestamp
value="2026-02-19T17:00:00Z"
@@ -605,7 +623,7 @@ describe('Timestamp', () => {
expect(screen.getByTestId('ts')).not.toHaveAttribute('tabindex');
});
- it('keeps the full absolute aria-label while the tooltip is attached', () => {
+ it('keeps the full absolute aria-label while the hover card is attached', () => {
render(
<Timestamp
value={Date.now() / 1000 - 3600}
@@ -620,30 +638,33 @@ describe('Timestamp', () => {
});
});
- // --- Multi-zone / multi-format tooltip entries ---
-
- describe('tooltipEntries', () => {
- // A fixed instant that lands on a different calendar day in Tokyo, so a
- // zone-blind implementation is visible in the output.
- const VALUE = '2026-02-19T17:00:00Z';
+ // --- Default hover card (no tooltipEntries) ---
+ describe('default hover card (no tooltipEntries)', () => {
const originalShowPopover = HTMLElement.prototype.showPopover;
const originalHidePopover = HTMLElement.prototype.hidePopover;
beforeEach(() => {
- // The tooltip is lazy-loaded; real timers let the dynamic import and
- // RTL's findBy* resolve (the outer beforeEach installs fake timers).
+ // The card content renders inline in a (mocked) popover; real timers let
+ // RTL's findBy* and the async clipboard write resolve (the outer
+ // beforeEach installs fake timers).
vi.useRealTimers();
HTMLElement.prototype.showPopover = vi.fn();
HTMLElement.prototype.hidePopover = vi.fn();
+ // jsdom does not implement the async Clipboard API.
+ Object.defineProperty(navigator, 'clipboard', {
+ value: {writeText: vi.fn().mockResolvedValue(undefined)},
+ configurable: true,
+ });
});
afterEach(() => {
HTMLElement.prototype.showPopover = originalShowPopover;
HTMLElement.prototype.hidePopover = originalHidePopover;
+ __resetLiveRegionsForTest();
});
- it('leaves the default tooltip as a single unwrapped line', async () => {
+ it('renders the unified copyable card with a single default absolute row', async () => {
render(
<Timestamp
value={Date.now() / 1000 - 3600}
@@ -651,18 +672,91 @@ describe('Timestamp', () => {
data-testid="ts"
/>,
);
- const layer = await screen.findByRole('tooltip', {hidden: true});
- // No entries configured — the tooltip content stays the bare string it
- // has always been, with no list wrapper introduced around it.
- expect(layer.querySelector('dl')).toBeNull();
+ // With no entries the hover surface is still the copyable card — one
+ // surface, one styling — never the old read-only tooltip.
+ expect(
+ screen.queryByRole('tooltip', {hidden: true}),
+ ).not.toBeInTheDocument();
+ const card = await screen.findByRole('dialog', {hidden: true});
+ // The default card is the named details card, exactly as the configured
+ // one is.
+ expect(card).toHaveAttribute('aria-label', 'Timestamp details');
+ // Exactly one row, carrying the full absolute time (the same string as
+ // the aria-label) with its own copy button.
+ expect(card.querySelectorAll('dd')).toHaveLength(1);
+ expect(card.querySelectorAll('button')).toHaveLength(1);
const normalize = (s: string) => s.replace(/\s+/g, ' ');
- expect(normalize(layer.textContent ?? '')).toContain(
+ expect(normalize(card.textContent ?? '')).toContain(
normalize(screen.getByTestId('ts').getAttribute('aria-label') ?? '\0'),
);
});
- it('renders one tooltip line per configured entry', async () => {
+ it("copies the default absolute row's value", async () => {
+ render(<Timestamp value={Date.now() / 1000 - 3600} format="relative" />);
+ const card = await screen.findByRole('dialog', {hidden: true});
+ const rowValue = card.querySelector('dd')?.textContent ?? '';
+ expect(rowValue).toBeTruthy();
+ fireEvent.click(card.querySelector('button')!);
+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith(rowValue);
+ // Let the async copy resolve and flip the button into its copied state
+ // so the state update settles inside act().
+ await waitFor(() => {
+ expect(
+ screen.getByRole('button', {name: 'Copied', hidden: true}),
+ ).toBeInTheDocument();
+ });
+ });
+ });
+
+ // --- Multi-zone / multi-format copyable hover card (tooltipEntries) ---
+
+ describe('tooltipEntries copyable hover card', () => {
+ // A fixed instant that lands on a different calendar day in Tokyo, so a
+ // zone-blind implementation is visible in the output.
+ const VALUE = '2026-02-19T17:00:00Z';
+
+ const originalShowPopover = HTMLElement.prototype.showPopover;
+ const originalHidePopover = HTMLElement.prototype.hidePopover;
+
+ beforeEach(() => {
+ // The card content renders inline in a (mocked) popover, so its rows are
+ // in the DOM without opening it. Real timers so RTL's findBy* and the
+ // async clipboard write resolve (the outer beforeEach installs fake ones).
+ vi.useRealTimers();
+ HTMLElement.prototype.showPopover = vi.fn();
+ HTMLElement.prototype.hidePopover = vi.fn();
+ // jsdom does not implement the async Clipboard API.
+ Object.defineProperty(navigator, 'clipboard', {
+ value: {writeText: vi.fn().mockResolvedValue(undefined)},
+ configurable: true,
+ });
+ });
+
+ afterEach(() => {
+ HTMLElement.prototype.showPopover = originalShowPopover;
+ HTMLElement.prototype.hidePopover = originalHidePopover;
+ __resetLiveRegionsForTest();
+ });
+
+ it('presents configured entries as a named card, not a read-only tooltip', async () => {
+ render(
+ <Timestamp
+ value={VALUE}
+ format="relative"
+ tooltipEntries={[{label: 'Local'}, {timezoneID: 'UTC', label: 'UTC'}]}
+ />,
+ );
+ // Entries present — the surface is the interactive card, never the
+ // lightweight read-only tooltip.
+ expect(
+ screen.queryByRole('tooltip', {hidden: true}),
+ ).not.toBeInTheDocument();
+ const card = await screen.findByRole('dialog', {hidden: true});
+ expect(card).toHaveAttribute('aria-label', 'Timestamp details');
+ });
+
+ it('renders one row per configured entry, read-only by default', async () => {
render(
<Timestamp
value={VALUE}
@@ -674,11 +768,37 @@ describe('Timestamp', () => {
]}
/>,
);
- const layer = await screen.findByRole('tooltip', {hidden: true});
- expect(layer.querySelectorAll('dd')).toHaveLength(3);
- expect(layer.textContent).toContain('Local');
- expect(layer.textContent).toContain('UTC');
- expect(layer.textContent).toContain('Tokyo');
+ const card = await screen.findByRole('dialog', {hidden: true});
+ expect(card.querySelectorAll('dd')).toHaveLength(3);
+ // Entries are read-only unless they opt in, so no copy buttons and no
+ // trailing action column are rendered.
+ expect(card.querySelectorAll('button')).toHaveLength(0);
+ expect(card.textContent).toContain('Local');
+ expect(card.textContent).toContain('UTC');
+ expect(card.textContent).toContain('Tokyo');
+ });
+
+ it('renders a copy button only on rows that opt into isCopyable', async () => {
+ render(
+ <Timestamp
+ value={VALUE}
+ format="relative"
+ tooltipEntries={[
+ {label: 'Local'},
+ {timezoneID: 'UTC', label: 'UTC'},
+ {
+ timezoneID: 'UTC',
+ format: 'system_date_time',
+ label: 'ISO',
+ isCopyable: true,
+ },
+ ]}
+ />,
+ );
+ const card = await screen.findByRole('dialog', {hidden: true});
+ // Three rows, but only the opted-in row carries a copy button.
+ expect(card.querySelectorAll('dd')).toHaveLength(3);
+ expect(card.querySelectorAll('button')).toHaveLength(1);
});
it('renders each entry in the time zone it names', async () => {
@@ -696,8 +816,8 @@ describe('Timestamp', () => {
]}
/>,
);
- const layer = await screen.findByRole('tooltip', {hidden: true});
- const values = Array.from(layer.querySelectorAll('dd')).map(
+ const card = await screen.findByRole('dialog', {hidden: true});
+ const values = Array.from(card.querySelectorAll('dd')).map(
el => el.textContent,
);
// Machine formats are locale- and host-timezone-independent, so these
@@ -705,7 +825,62 @@ describe('Timestamp', () => {
expect(values).toEqual(['2026-02-19 17:00:00', '2026-02-20 02:00:00']);
});
- it('shows a tooltip for absolute formats once entries are configured', async () => {
+ it("copies an opted-in row's value and flips the button to the copied state", async () => {
+ render(
+ <Timestamp
+ value={VALUE}
+ format="relative"
+ tooltipEntries={[
+ {
+ label: 'ISO',
+ format: 'system_date_time',
+ timezoneID: 'UTC',
+ isCopyable: true,
+ },
+ ]}
+ />,
+ );
+ const card = await screen.findByRole('dialog', {hidden: true});
+ const [rowValue] = Array.from(card.querySelectorAll('dd')).map(
+ el => el.textContent ?? '',
+ );
+ const copyButton = card.querySelectorAll('button')[0];
+
+ fireEvent.click(copyButton);
+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith(rowValue);
+
+ // The button announces and flips its icon/label to the copied state.
+ await waitFor(() => {
+ expect(
+ screen.getByRole('button', {name: 'Copied', hidden: true}),
+ ).toBeInTheDocument();
+ });
+ });
+
+ it('announces the copy to a polite live region through the i18n catalog', async () => {
+ render(
+ <InternationalizationProvider
+ locale="fr"
+ overrides={{fr: {'@astryx.timestamp.copied': 'Copié'}}}>
+ <Timestamp
+ value={VALUE}
+ format="relative"
+ tooltipEntries={[
+ {timezoneID: 'UTC', label: 'UTC', isCopyable: true},
+ ]}
+ />
+ </InternationalizationProvider>,
+ );
+ const card = await screen.findByRole('dialog', {hidden: true});
+ fireEvent.click(card.querySelector('button')!);
+ await waitFor(() => {
+ expect(
+ document.querySelector('[data-astryx-live-region="polite"]'),
+ ).toHaveTextContent('Copié');
+ });
+ });
+
+ it('shows the card for absolute formats once entries are configured', async () => {
render(
<Timestamp
value={VALUE}
@@ -714,10 +889,10 @@ describe('Timestamp', () => {
data-testid="ts"
/>,
);
- // Without entries an absolute format has no tooltip at all; configuring
- // entries must not be silently ignored.
- const layer = await screen.findByRole('tooltip', {hidden: true});
- expect(layer.textContent).toContain('UTC');
+ // Without entries an absolute format has no hover surface at all;
+ // configuring entries must not be silently ignored.
+ const card = await screen.findByRole('dialog', {hidden: true});
+ expect(card.textContent).toContain('UTC');
// ...and the anchor becomes keyboard-reachable, as it is for relative.
expect(screen.getByTestId('ts')).toHaveAttribute('tabindex', '0');
});
@@ -731,25 +906,33 @@ describe('Timestamp', () => {
data-testid="ts"
/>,
);
- // `hasTooltip` stays the only on/off switch — an empty array is not a
- // second way to spell "off", and it must not widen the gate either.
+ // An empty array is not a way to configure the card — with no lines to
+ // show, an absolute format stays surface-less (no tab stop, no card).
expect(screen.getByTestId('ts')).not.toHaveAttribute('tabindex');
+ expect(screen.queryByRole('dialog', {hidden: true})).toBeNull();
});
- it('still honors hasTooltip={false} when entries are configured', () => {
+ it('stays inert when hasTooltip is false even with entries configured', () => {
render(
<Timestamp
value={VALUE}
- format="date_time"
+ format="relative"
hasTooltip={false}
- tooltipEntries={[{timezoneID: 'UTC'}]}
+ tooltipEntries={[{timezoneID: 'UTC', label: 'UTC'}]}
data-testid="ts"
/>,
);
+ // hasTooltip stays the on/off switch: false suppresses the surface even
+ // when entries would otherwise upgrade it to the card.
+ expect(screen.queryByRole('dialog', {hidden: true})).toBeNull();
+ expect(screen.queryByRole('tooltip', {hidden: true})).toBeNull();
expect(screen.getByTestId('ts')).not.toHaveAttribute('tabindex');
+ expect(
+ screen.getByTestId('ts').getAttribute('aria-describedby'),
+ ).toBeNull();
});
- it('leaves the accessible name unchanged when entries are configured', async () => {
+ it('leaves the accessible name unchanged when entries are configured', () => {
const value = Date.now() / 1000 - 3600;
const {unmount} = render(
<Timestamp value={value} format="relative" data-testid="a" />,
@@ -766,8 +949,8 @@ describe('Timestamp', () => {
/>,
);
// The accessible name stays the canonical absolute time in the viewer's
- // own zone; the extra zones reach assistive tech through the tooltip's
- // aria-describedby, not by being stuffed into the name.
+ // own zone; the extra zones reach assistive tech through the card, not
+ // by being stuffed into the name.
expect(screen.getByTestId('b').getAttribute('aria-label')).toBe(before);
});
@@ -792,8 +975,8 @@ describe('Timestamp', () => {
tooltipEntries={[{timezoneID: 'UTC', label: 'UTC'}]}
/>,
);
- // The invalid-value bail-out runs before any tooltip work, so there is
- // no half-rendered tooltip anchored to nothing.
+ // The invalid-value bail-out runs before any hover-surface work, so
+ // there is no half-rendered card anchored to nothing.
expect(container).toBeEmptyDOMElement();
} finally {
warn.mockRestore();
@@ -813,8 +996,8 @@ describe('Timestamp', () => {
/>,
);
// autoThreshold={0} forces the absolute branch regardless of the clock.
- const layer = await screen.findByRole('tooltip', {hidden: true});
- expect(layer.textContent).toContain('2026-02-19 17:00:00');
+ const card = await screen.findByRole('dialog', {hidden: true});
+ expect(card.textContent).toContain('2026-02-19 17:00:00');
expect(screen.getByTestId('ts')).toHaveAttribute('tabindex', '0');
});
@@ -828,8 +1011,8 @@ describe('Timestamp', () => {
]}
/>,
);
- const layer = await screen.findByRole('tooltip', {hidden: true});
- expect(layer.textContent).toContain('2026-02-19 17:00:00');
+ const card = await screen.findByRole('dialog', {hidden: true});
+ expect(card.textContent).toContain('2026-02-19 17:00:00');
});
it('pairs exactly one label cell with one value cell per entry', async () => {
@@ -844,12 +1027,12 @@ describe('Timestamp', () => {
]}
/>,
);
- const layer = await screen.findByRole('tooltip', {hidden: true});
- // An unlabeled entry still emits its label cell, so the two-column grid
- // stays aligned and the <dl> stays valid markup.
- expect(layer.querySelectorAll('dt')).toHaveLength(3);
- expect(layer.querySelectorAll('dd')).toHaveLength(3);
- expect(layer.querySelectorAll('dt')[1].textContent).toBe('');
+ const card = await screen.findByRole('dialog', {hidden: true});
+ // An unlabeled entry still emits its label cell, so the grid stays
+ // aligned and the <dl> stays valid markup.
+ expect(card.querySelectorAll('dt')).toHaveLength(3);
+ expect(card.querySelectorAll('dd')).toHaveLength(3);
+ expect(card.querySelectorAll('dt')[1].textContent).toBe('');
});
it('gives the tab stop back when entries are removed', () => {
@@ -864,50 +1047,11 @@ describe('Timestamp', () => {
expect(screen.getByTestId('ts')).toHaveAttribute('tabindex', '0');
rerender(<Timestamp value={VALUE} format="date_time" data-testid="ts" />);
- // The widened gate is driven purely by entry presence, so dropping the
- // prop must also drop the tab stop rather than stranding one.
+ // The surface is driven purely by entry presence, so dropping the prop
+ // must also drop the tab stop rather than stranding one.
expect(screen.getByTestId('ts')).not.toHaveAttribute('tabindex');
});
- it('describes an absolute-format timestamp with its tooltip', async () => {
- render(
- <Timestamp
- value={VALUE}
- format="date_time"
- tooltipEntries={[{timezoneID: 'UTC', label: 'UTC'}]}
- data-testid="ts"
- />,
- );
- const layer = await screen.findByRole('tooltip', {hidden: true});
- const el = screen.getByTestId('ts');
- // An absolute format carries no aria-label, so aria-describedby is the
- // only route the configured zones have to assistive tech.
- expect(el.getAttribute('aria-label')).toBeNull();
- await waitFor(() => {
- expect(el.getAttribute('aria-describedby')).toBe(layer.id);
- });
- expect(layer.id).toBeTruthy();
- });
-
- it('leaves no tooltip and no description when hasTooltip is false', () => {
- render(
- <Timestamp
- value={VALUE}
- format="relative"
- hasTooltip={false}
- tooltipEntries={[{timezoneID: 'UTC', label: 'UTC'}]}
- data-testid="ts"
- />,
- );
- expect(
- screen.queryByRole('tooltip', {hidden: true}),
- ).not.toBeInTheDocument();
- // No orphaned reference pointing at a tooltip that was never rendered.
- expect(
- screen.getByTestId('ts').getAttribute('aria-describedby'),
- ).toBeNull();
- });
-
it('does not crash on an unknown time zone', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
try {
@@ -921,8 +1065,8 @@ describe('Timestamp', () => {
]}
/>,
);
- const layer = await screen.findByRole('tooltip', {hidden: true});
- const values = Array.from(layer.querySelectorAll('dd')).map(
+ const card = await screen.findByRole('dialog', {hidden: true});
+ const values = Array.from(card.querySelectorAll('dd')).map(
el => el.textContent,
);
expect(values).toHaveLength(2);
diff --git a/packages/core/src/Timestamp/Timestamp.tsx b/packages/core/src/Timestamp/Timestamp.tsx
index d65f0783de..27c38688f0 100644
--- a/packages/core/src/Timestamp/Timestamp.tsx
+++ b/packages/core/src/Timestamp/Timestamp.tsx
@@ -16,22 +16,26 @@
* - /packages/cli/assets/templates/blocks/components/Timestamp/ (showcase blocks)
*/
-import {useEffect, useRef, useState, lazy, Suspense, Fragment} from 'react';
+import {lazy, Suspense, useEffect, useRef, useState} from 'react';
import * as stylex from '@stylexjs/stylex';
import {Text} from '../Text';
import type {TextType, TextSize, TextColor, TextWeight} from '../theme/types';
import {mergeProps, mergeRefs} from '../utils';
import {useDevWarning} from '../hooks/useDevWarning';
+import {useTranslator} from '../i18n';
import type {BaseProps} from '../BaseProps';
import {themeProps} from '../utils/themeProps';
-import {colorVars, spacingVars} from '../theme/tokens.stylex';
import {formatInstant} from './formatInstant';
import {formatTooltipLines} from './tooltipEntries';
-import type {TimestampTooltipEntry} from './tooltipEntries';
+import type {
+ TimestampTooltipEntry,
+ TimestampTooltipLine,
+} from './tooltipEntries';
-const LazyXDSTooltip = lazy(async () =>
- import('../Tooltip/Tooltip').then(mod => ({default: mod.Tooltip})),
-);
+// Load the overlay lazily so a card-less Timestamp — the default — never
+// bundles HoverCard or the copy affordance's Icon/IconButton. Mirrors the code
+// split the read-only Tooltip path used before it.
+const LazyTimestampHoverCard = lazy(async () => import('./TimestampHoverCard'));
// =============================================================================
// Types
@@ -79,21 +83,29 @@ export interface TimestampProps extends BaseProps<HTMLTimeElement> {
*/
autoThreshold?: number;
/**
- * Whether to show a tooltip with the full date/time on hover.
+ * Whether to show a hover card with the full date/time on hover. The card
+ * is copyable — its default single row carries the full absolute time — and
+ * `tooltipEntries` customizes its rows.
* @default true
*/
hasTooltip?: boolean;
/**
- * Lines to show in the hover tooltip, so one instant can be read in several
- * time zones and/or formats at once. Each entry is one line, rendered in the
- * order given, with an optional label.
+ * Lines to show on hover, so one instant can be read — and optionally
+ * copied — in several time zones and/or formats at once. Each entry is one
+ * line, rendered in the order given, with an optional label.
*
- * Configuring entries also attaches the tooltip to absolute formats, which
- * otherwise have no tooltip at all. `hasTooltip={false}` still suppresses it,
- * and an empty array is treated as no configuration.
+ * Rows are read-only unless they set `isCopyable` (default `false`). A
+ * copyable row shows a copy button in a dedicated trailing action column so
+ * the buttons align across rows; that column is only present when some row
+ * is copyable. With no entries the card shows a single default row with the
+ * full absolute time in the viewer's own zone, which is copyable.
*
- * @default undefined — a single line with the full absolute time in the
- * viewer's own time zone
+ * Configuring entries also attaches the surface to absolute formats, which
+ * otherwise have no hover card at all. `hasTooltip={false}` still suppresses
+ * it, and an empty array is treated as no configuration.
+ *
+ * @default undefined — a single default row with the full absolute time in
+ * the viewer's own time zone
* @example
* ```
* <Timestamp
@@ -101,6 +113,7 @@ export interface TimestampProps extends BaseProps<HTMLTimeElement> {
* tooltipEntries={[
* {label: 'Your time'},
* {timezoneID: 'UTC', label: 'UTC'},
+ * {timezoneID: 'UTC', format: 'system_date_time', label: 'ISO', isCopyable: true},
* ]}
* />
* ```
@@ -158,43 +171,6 @@ const styles = stylex.create({
color: 'inherit',
fontWeight: 'inherit',
},
- // Visible focus ring for the tooltip tab stop, matching the repo-wide
- // focus-visible outline treatment (see Token, Thumbnail).
- focusable: {
- outline: {
- default: null,
- ':focus-visible': `2px solid ${colorVars['--color-accent']}`,
- },
- outlineOffset: {
- default: '0',
- ':focus-visible': '2px',
- },
- },
- // Label/value pairs for a multi-entry tooltip. The label column is sized to
- // its content, so when no entry carries a label it collapses to zero width
- // and the values sit exactly where a plain list of lines would.
- tooltipLines: {
- display: 'grid',
- gridTemplateColumns: 'auto 1fr',
- rowGap: spacingVars['--spacing-0-5'],
- marginBlock: 0,
- marginInline: 0,
- },
- tooltipLabel: {
- marginBlock: 0,
- marginInline: 0,
- // Only a label that actually has text earns the gutter, keeping the
- // unlabeled case flush.
- paddingInlineEnd: {
- default: 0,
- ':not(:empty)': spacingVars['--spacing-2'],
- },
- },
- tooltipValue: {
- marginBlock: 0,
- // <dd> carries a 40px inline start margin from the UA stylesheet.
- marginInline: 0,
- },
});
// =============================================================================
@@ -410,8 +386,8 @@ function isRelativeFormat(
*
* Renders a semantic `<time>` element with an ISO 8601 `datetime` attribute,
* styled via Text. Supports relative ("2 hours ago"), multiple absolute
- * formats, and auto formatting. Optionally shows a tooltip with the full
- * absolute time and can update live.
+ * formats, and auto formatting. Optionally shows a hover card with the full
+ * absolute time (copyable) and can update live.
*
* @example
* ```
@@ -439,6 +415,7 @@ export function Timestamp({
ref,
'data-testid': testId,
}: TimestampProps) {
+ const t = useTranslator();
const timeRef = useRef<HTMLTimeElement>(null);
const [now, setNow] = useState(() => new Date());
@@ -506,13 +483,22 @@ export function Timestamp({
? tooltipEntries
: undefined;
- // Absolute formats have never carried a tooltip. Leaving that gate closed
- // when a consumer has explicitly configured tooltip lines would let `format`
- // silently suppress another prop's output, so entry presence opens it too.
- // With no entries this reduces to the original condition exactly.
+ // Absolute formats have never carried a hover surface. Leaving that gate
+ // closed when a consumer has explicitly configured tooltip lines would let
+ // `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);
+ // 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
+ // the same copyable card — the default line is a one-row card carrying the
+ // full absolute time, itself copyable, just like a configured entry.
+ const lines: ReadonlyArray<TimestampTooltipLine> =
+ entries === undefined
+ ? [{value: fullAbsoluteText, isCopyable: true}]
+ : formatTooltipLines(date, entries);
+
const timestampProps = mergeProps(
themeProps('timestamp', {format: effectiveFormat}),
{className, style},
@@ -532,50 +518,42 @@ export function Timestamp({
aria-label={
isRelativeFormat(effectiveFormat) ? fullAbsoluteText : undefined
}
- // The absolute-time tooltip is anchored here with the default 'auto'
- // focus trigger, which only activates on focusable anchors. A bare
- // <time> is not focusable, so without a tab stop sighted keyboard
- // users could never reveal the tooltip (WCAG 1.4.13 / 2.1.1). Only
- // add the tab stop while a tooltip is actually attached — no
- // gratuitous tab stops otherwise.
+ // 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.
tabIndex={showTooltip ? 0 : undefined}
data-testid={testId}
- {...stylex.props(styles.time, showTooltip && styles.focusable)}>
+ {...stylex.props(styles.time)}>
{displayText}
</time>
</Text>
);
if (showTooltip) {
- // Built inside the branch so a timestamp without a tooltip allocates none
- // of it. With no entries the content stays the bare string it has always
- // been — no wrapper element is introduced around the default line.
- const tooltipContent =
- entries === undefined ? (
- fullAbsoluteText
- ) : (
- <dl {...stylex.props(styles.tooltipLines)}>
- {formatTooltipLines(date, entries).map((line, index) => (
- // eslint-disable-next-line @eslint-react/no-array-index-key -- tooltip lines are fixed positional slots and two entries may legitimately be identical
- <Fragment key={index}>
- <dt {...stylex.props(styles.tooltipLabel)}>{line.label ?? ''}</dt>
- <dd {...stylex.props(styles.tooltipValue)}>{line.value}</dd>
- </Fragment>
- ))}
- </dl>
- );
-
+ // 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 (
- <>
- {timeElement}
- <Suspense fallback={null}>
- <LazyXDSTooltip
- anchorRef={timeRef}
- content={tooltipContent}
- placement="above"
- />
- </Suspense>
- </>
+ <Suspense fallback={timeElement}>
+ <LazyTimestampHoverCard
+ lines={lines}
+ label={t('@astryx.timestamp.detailsLabel')}>
+ {timeElement}
+ </LazyTimestampHoverCard>
+ </Suspense>
);
}
diff --git a/packages/core/src/Timestamp/TimestampHoverCard.tsx b/packages/core/src/Timestamp/TimestampHoverCard.tsx
new file mode 100644
index 0000000000..7134b6645b
--- /dev/null
+++ b/packages/core/src/Timestamp/TimestampHoverCard.tsx
@@ -0,0 +1,277 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file TimestampHoverCard.tsx
+ * @input Uses React, HoverCard, IconButton, Icon, 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
+ * default, card-less Timestamp never bundles this chunk.
+ *
+ * Layout: a semantic `<dl>` laid out as a grid. Labelled cards use three
+ * columns — label, value, and a trailing action column for copy buttons —
+ * so the buttons align down a single column no matter how wide each value
+ * is. The action column is only added when at least one row is copyable, so
+ * a fully read-only card carries no dangling gutter. Label-less cards drop
+ * the label column and stack to whatever columns remain.
+ *
+ * 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.doc.mjs (theming.targets)
+ * - /packages/core/src/Timestamp/Timestamp.test.tsx
+ */
+
+import type {ReactNode} from 'react';
+import {useCallback, useEffect, useRef, useState} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {HoverCard} from '../HoverCard';
+import {IconButton} from '../IconButton';
+import {Icon} from '../Icon';
+import {useAnnounce} from '../hooks/useAnnounce';
+import {useTranslator} from '../i18n';
+import {themeProps} from '../utils/themeProps';
+import {
+ colorVars,
+ spacingVars,
+ typeScaleVars,
+ fontWeightVars,
+} from '../theme/tokens.stylex';
+import type {TimestampTooltipLine} from './tooltipEntries';
+
+const styles = stylex.create({
+ // The card is a definition list laid out as a grid so cells align into
+ // columns across rows. `gridTemplateColumns` is set per-card (below) to add
+ // or drop the label and action columns; the row/column gaps live here.
+ dl: {
+ display: 'grid',
+ alignItems: 'center',
+ columnGap: spacingVars['--spacing-4'],
+ rowGap: spacingVars['--spacing-2'],
+ margin: 0,
+ padding: 0,
+ },
+ // Each row spans the full grid so its cells land in the shared columns.
+ // `display: contents` lets the <dt>/<dd> participate directly in the grid.
+ row: {
+ display: 'contents',
+ },
+ // Label: the design system's `supporting` role — secondary colour, the
+ // supporting size/leading, normal weight. This matches Timestamp's own
+ // default `type` ('supporting'), so the card's labels read at the same
+ // register as the component itself.
+ label: {
+ color: colorVars['--color-text-secondary'],
+ fontSize: typeScaleVars['--text-supporting-size'],
+ lineHeight: typeScaleVars['--text-supporting-leading'],
+ fontWeight: fontWeightVars['--font-weight-normal'],
+ margin: 0,
+ padding: 0,
+ whiteSpace: 'nowrap',
+ },
+ // Value: the `body` role — primary colour, body size/leading, normal weight.
+ value: {
+ color: colorVars['--color-text-primary'],
+ fontSize: typeScaleVars['--text-body-size'],
+ lineHeight: typeScaleVars['--text-body-leading'],
+ fontWeight: fontWeightVars['--font-weight-normal'],
+ margin: 0,
+ padding: 0,
+ whiteSpace: 'nowrap',
+ },
+ // The trailing action cell holds the copy button (or nothing, on a
+ // read-only row). It lives in its own grid column so buttons align.
+ action: {
+ display: 'flex',
+ justifyContent: 'flex-end',
+ alignItems: 'center',
+ },
+});
+
+// Grid templates, selected per-card by which columns are present.
+// - hasAnyLabel + hasAnyCopyable → label | value | action
+// - hasAnyLabel only → label | value
+// - hasAnyCopyable only → value | action
+// - neither → value
+const gridTemplates = stylex.create({
+ labelValueAction: {gridTemplateColumns: 'auto 1fr auto'},
+ labelValue: {gridTemplateColumns: 'auto 1fr'},
+ valueAction: {gridTemplateColumns: '1fr auto'},
+ value: {gridTemplateColumns: '1fr'},
+});
+
+/** How long the copied checkmark stays before reverting to the copy icon. */
+const COPY_FEEDBACK_MS = 1500;
+
+/**
+ * The per-row copy affordance: a compact ghost `IconButton` that writes the
+ * row's value to the clipboard, flips `copy` → `check` for a moment, and
+ * announces the copy to a polite live region (a swapped aria-label alone
+ * isn't reliably announced). A clipboard rejection is a silent no-op.
+ *
+ * Kept as its own component so its state/timer/effect only exist for rows that
+ * actually opt into copying — read-only rows render no button and carry none
+ * of this machinery.
+ */
+function CopyButton({value}: {value: string}) {
+ const t = useTranslator();
+ const announce = useAnnounce();
+ const [copied, setCopied] = useState(false);
+ const resetTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ useEffect(() => {
+ return () => {
+ if (resetTimerRef.current != null) {
+ clearTimeout(resetTimerRef.current);
+ }
+ };
+ }, []);
+
+ const handleCopy = useCallback(async () => {
+ try {
+ await navigator.clipboard.writeText(value);
+ setCopied(true);
+ announce(t('@astryx.timestamp.copied'));
+ // Restart the reset timer on every copy so a rapid re-copy isn't
+ // reverted early by the previous click's timer.
+ if (resetTimerRef.current != null) {
+ clearTimeout(resetTimerRef.current);
+ }
+ resetTimerRef.current = setTimeout(() => {
+ resetTimerRef.current = null;
+ setCopied(false);
+ }, COPY_FEEDBACK_MS);
+ } catch {
+ // Clipboard failures leave the copied state unchanged.
+ }
+ }, [value, announce, t]);
+
+ return (
+ <IconButton
+ variant="ghost"
+ size="sm"
+ icon={<Icon icon={copied ? 'check' : 'copy'} size="sm" color="inherit" />}
+ label={
+ copied
+ ? t('@astryx.timestamp.copied')
+ : t('@astryx.timestamp.copyValue', {value})
+ }
+ onClick={() => {
+ void handleCopy();
+ }}
+ {...themeProps('timestamp-copy-button')}
+ />
+ );
+}
+
+/**
+ * One row of the hover card: an optional label, the formatted instant, and —
+ * when the card reserves an action column — a trailing action cell holding the
+ * copy button (for a copyable row) or nothing (for a read-only row, so the
+ * columns stay aligned). Pure presentation: the copy state lives in
+ * {@link CopyButton}, which only copyable rows render.
+ */
+function EntryRow({
+ line,
+ hasLabelColumn,
+ hasActionColumn,
+}: {
+ line: TimestampTooltipLine;
+ hasLabelColumn: boolean;
+ hasActionColumn: boolean;
+}) {
+ return (
+ <div {...stylex.props(styles.row)}>
+ {hasLabelColumn && (
+ <dt {...stylex.props(styles.label)}>{line.label ?? ''}</dt>
+ )}
+ <dd {...stylex.props(styles.value)}>{line.value}</dd>
+ {hasActionColumn && (
+ <div {...stylex.props(styles.action)}>
+ {line.isCopyable && <CopyButton value={line.value} />}
+ </div>
+ )}
+ </div>
+ );
+}
+
+export interface TimestampHoverCardProps {
+ /** The rows to render, each a labelled instant, optionally copyable. */
+ lines: ReadonlyArray<TimestampTooltipLine>;
+ /** Accessible name for the card. */
+ label: string;
+ /** The anchor the card is attached to (the `<time>` element). */
+ children: ReactNode;
+}
+
+function gridTemplateFor(
+ hasLabelColumn: boolean,
+ hasActionColumn: boolean,
+): stylex.StyleXStyles {
+ if (hasLabelColumn && hasActionColumn) {
+ return gridTemplates.labelValueAction;
+ }
+ if (hasLabelColumn) {
+ return gridTemplates.labelValue;
+ }
+ if (hasActionColumn) {
+ return gridTemplates.valueAction;
+ }
+ return gridTemplates.value;
+}
+
+/**
+ * The copyable hover card for Timestamp. Renders a semantic `<dl>` as a grid:
+ * an optional label column, the value, and — when any row is copyable — a
+ * trailing action column carrying that row's copy button, so buttons align
+ * down one column. With a single default line this is a one-row card carrying
+ * the full absolute time, copyable. Opens on hover and on keyboard focus (the
+ * anchor's tab stop), with a dashed-underline affordance signalling it is
+ * interactive.
+ */
+export default function TimestampHoverCard({
+ lines,
+ label,
+ children,
+}: TimestampHoverCardProps): ReactNode {
+ // 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
+ // has no trailing gutter.
+ const hasLabelColumn = lines.some(
+ line => line.label != null && line.label !== '',
+ );
+ const hasActionColumn = lines.some(line => line.isCopyable);
+
+ const cardContent = (
+ <dl
+ {...stylex.props(
+ styles.dl,
+ gridTemplateFor(hasLabelColumn, hasActionColumn),
+ )}>
+ {lines.map((line, index) => (
+ <EntryRow
+ // eslint-disable-next-line @eslint-react/no-array-index-key -- rows are fixed positional slots and two entries may legitimately be identical
+ key={index}
+ line={line}
+ hasLabelColumn={hasLabelColumn}
+ hasActionColumn={hasActionColumn}
+ />
+ ))}
+ </dl>
+ );
+
+ return (
+ <HoverCard
+ content={cardContent}
+ placement="above"
+ focusTrigger="always"
+ hasHoverIndication
+ label={label}>
+ {children}
+ </HoverCard>
+ );
+}
+
+TimestampHoverCard.displayName = 'TimestampHoverCard';
diff --git a/packages/core/src/Timestamp/tooltipEntries.test.ts b/packages/core/src/Timestamp/tooltipEntries.test.ts
index f25555871f..a5f52d56dd 100644
--- a/packages/core/src/Timestamp/tooltipEntries.test.ts
+++ b/packages/core/src/Timestamp/tooltipEntries.test.ts
@@ -512,6 +512,15 @@ describe('formatTooltipLines', () => {
expect(line.label).toBe('');
});
+ it('marks lines read-only by default and copyable only when opted in', () => {
+ const lines = formatTooltipLines(INSTANT, [
+ {label: 'Local'},
+ {label: 'ISO', format: 'system_date_time', isCopyable: true},
+ {label: 'Off', isCopyable: false},
+ ]);
+ expect(lines.map(l => l.isCopyable)).toEqual([false, true, false]);
+ });
+
// --- Ordering and arity ---
it('preserves entry order', () => {
diff --git a/packages/core/src/Timestamp/tooltipEntries.ts b/packages/core/src/Timestamp/tooltipEntries.ts
index 4129830fa2..1e739d856a 100644
--- a/packages/core/src/Timestamp/tooltipEntries.ts
+++ b/packages/core/src/Timestamp/tooltipEntries.ts
@@ -72,12 +72,26 @@ export interface TimestampTooltipEntry {
* Supplied already translated; Timestamp never invents or localizes labels.
*/
label?: string;
+ /**
+ * Whether this row shows a copy-to-clipboard button, rendered in a dedicated
+ * trailing action column so the buttons line up across rows regardless of
+ * each value's width. The action column is only reserved when at least one
+ * row is copyable, so a fully read-only card has no trailing gutter.
+ *
+ * Defaults to `false` — rows are read-only unless opted in. Set `true` for a
+ * row whose value is worth pasting elsewhere, such as a machine-readable
+ * `system_date_time` value shown beside human-readable zones that only need
+ * to be read.
+ * @default false
+ */
+ isCopyable?: boolean;
}
/** A rendered tooltip line. */
export interface TimestampTooltipLine {
label?: string;
value: string;
+ isCopyable: boolean;
}
// =============================================================================
@@ -198,6 +212,7 @@ export function formatTooltipLines(
return {
...(entry.label === undefined ? {} : {label: entry.label}),
+ isCopyable: entry.isCopyable ?? false,
value: formatInstant(date, format, {
timeZone,
isTimezoneShown: shouldShowZoneName(