An open source design system that's fully customizable and agent ready
TypeScript
feat(Timestamp): show one instant across several time zones on hover (#4188) (#4234)
AK4d9de2c18d1a
diff --git a/.changeset/timestamp-tooltip-timezones.md b/.changeset/timestamp-tooltip-timezones.mdnew file mode 100644index 0000000000..d887448c6c--- /dev/null+++ b/.changeset/timestamp-tooltip-timezones.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+'@astryxdesign/cli': patch+---++[feat] Timestamp: new `tooltipEntries` prop renders the hover tooltip across several time zones and/or formats at once — one line per entry, each with an optional `timezoneID` (IANA id; omit it or pass `'local'` for the viewer's zone), `format` (every non-relative `TimestampFormat` plus `'full'`), and `label`. The default is unchanged: with no entries the tooltip stays the single full absolute line in the viewer's zone. Configuring entries also attaches the tooltip to absolute formats, which previously had none — note that this gives those timestamps a tab stop and focus ring, as relative timestamps already have, so a column of them gains one tab stop per row. `hasTooltip={false}` still suppresses the tooltip, and an empty array counts as no configuration. Also corrects `isTimezoneShown`'s documentation, which claimed it applied to the `system_date_time` and `system_time` formats; it never has, and those formats stay machine-readable. (#4188)+@AKnassadiff --git a/apps/storybook/stories/Timestamp.stories.tsx b/apps/storybook/stories/Timestamp.stories.tsxindex be6ee081e4..9f0c124de0 100644--- a/apps/storybook/stories/Timestamp.stories.tsx+++ b/apps/storybook/stories/Timestamp.stories.tsx@@ -160,6 +160,80 @@ export const TimeFormat: Story = {},};+export const TooltipTimezones: Story = {+ name: 'Tooltip — multiple time zones',+ 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+ </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">+ Three labelled zones — the widest case the 300px tooltip holds+ </Text>+ <div>+ <Timestamp+ value="2026-02-19T17:00:00Z"+ format="date"+ tooltipEntries={[+ {+ timezoneID: 'America/New_York',+ format: 'date_time',+ label: 'New York',+ },+ {+ timezoneID: 'Europe/London',+ format: 'date_time',+ label: 'London',+ },+ {timezoneID: 'Asia/Tokyo', format: 'date_time', label: 'Tokyo'},+ ]}+ />+ </div>+ </div>+ <div>+ <Text type="supporting" color="secondary">+ One zone, two formats — friendly line plus a machine-precise line+ </Text>+ <div>+ <Timestamp+ value="2026-02-19T17:00:00Z"+ format="date_time"+ tooltipEntries={[+ {format: 'full'},+ {format: 'system_date_time', label: 'ISO'},+ ]}+ />+ </div>+ </div>+ <div>+ <Text type="supporting" color="secondary">+ UTC only — an audit log that never shows local time+ </Text>+ <div>+ <Timestamp+ value="2026-02-19T17:00:00Z"+ format="date_time"+ tooltipEntries={[{timezoneID: 'UTC', label: 'UTC'}]}+ />+ </div>+ </div>+ </div>+ ),+};+export const SystemFormats: Story = {render: () => (<div style={{display: 'flex', flexDirection: 'column', gap: '8px'}}>diff --git a/packages/cli/templates/blocks/components/Timestamp/TimestampTimezone.tsx b/packages/cli/templates/blocks/components/Timestamp/TimestampTimezone.tsxindex 4c85e8ed11..c29ce61b03 100644--- a/packages/cli/templates/blocks/components/Timestamp/TimestampTimezone.tsx+++ b/packages/cli/templates/blocks/components/Timestamp/TimestampTimezone.tsx@@ -16,17 +16,37 @@ export default function TimestampTimezone() {User-facing with timezone</Text><Stack direction="horizontal" gap={4} vAlign="center">- <Timestamp value={DATE} format="date_time" isTimezoneShown color="primary" />- <Timestamp value={DATE} format="time" isTimezoneShown color="primary" />+ <Timestamp+ value={DATE}+ format="date_time"+ isTimezoneShown+ color="primary"+ />+ <Timestamp+ value={DATE}+ format="time"+ isTimezoneShown+ color="primary"+ /></Stack></Stack><Stack direction="vertical" gap={1}><Text type="supporting" color="secondary">- System formats with timezone+ System formats stay machine-readable — never suffixed with a zone</Text><Stack direction="horizontal" gap={4} vAlign="center">- <Timestamp value={DATE} format="system_date_time" isTimezoneShown type="code" color="primary" />- <Timestamp value={DATE} format="system_time" isTimezoneShown type="code" color="primary" />+ <Timestamp+ value={DATE}+ format="system_date_time"+ type="code"+ color="primary"+ />+ <Timestamp+ value={DATE}+ format="system_time"+ type="code"+ color="primary"+ /></Stack></Stack></Stack>diff --git a/packages/cli/templates/blocks/components/Timestamp/TimestampTooltipTimezones.doc.mjs b/packages/cli/templates/blocks/components/Timestamp/TimestampTooltipTimezones.doc.mjsnew file mode 100644index 0000000000..3988f9a44e--- /dev/null+++ b/packages/cli/templates/blocks/components/Timestamp/TimestampTooltipTimezones.doc.mjs@@ -0,0 +1,14 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('../../../../../core/src/docs-types').TemplateDoc} */+export const doc = {+ type: 'block',+ exampleFor: 'Timestamp',+ name: 'Timestamp — Tooltip time zones',+ displayName: 'Timestamp — Tooltip time zones',+ description:+ 'Hover tooltips that show one instant across several time zones or formats. Use tooltipEntries when readers must compare zones, like an incident log carrying both the reader’s time and the event’s origin zone.',+ isReady: true,+ aspectRatio: 16 / 9,+ componentsUsed: ['Timestamp', 'Layout', 'Text'],+};diff --git a/packages/cli/templates/blocks/components/Timestamp/TimestampTooltipTimezones.tsx b/packages/cli/templates/blocks/components/Timestamp/TimestampTooltipTimezones.tsxnew file mode 100644index 0000000000..f4c44c2aac--- /dev/null+++ b/packages/cli/templates/blocks/components/Timestamp/TimestampTooltipTimezones.tsx@@ -0,0 +1,62 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import {Timestamp} from '@astryxdesign/core/Timestamp';+import {Stack} from '@astryxdesign/core/Layout';+import {Text} from '@astryxdesign/core/Text';++const DATE = '2026-02-19T17:00:00Z';++export default function TimestampTooltipTimezones() {+ return (+ <Stack direction="vertical" gap={4}>+ <Stack direction="vertical" gap={1}>+ <Text type="supporting" color="secondary">+ Local + UTC — hover to compare+ </Text>+ <Timestamp+ value={DATE}+ format="relative"+ color="primary"+ tooltipEntries={[+ {format: 'date_time', label: 'Local'},+ {timezoneID: 'UTC', format: 'date_time', label: 'UTC'},+ ]}+ />+ </Stack>+ <Stack direction="vertical" gap={1}>+ <Text type="supporting" color="secondary">+ Incident origin zone alongside the reader’s+ </Text>+ <Timestamp+ value={DATE}+ format="date_time"+ color="primary"+ tooltipEntries={[+ {format: 'date_time', label: 'Local'},+ {+ timezoneID: 'America/Los_Angeles',+ format: 'date_time',+ label: 'Origin',+ },+ ]}+ />+ </Stack>+ <Stack direction="vertical" gap={1}>+ <Text type="supporting" color="secondary">+ Friendly line plus a machine-precise line+ </Text>+ <Timestamp+ value={DATE}+ format="date_time"+ color="primary"+ tooltipEntries={[+ {format: 'full'},+ {format: 'system_date_time', label: 'ISO'},+ ]}+ />+ </Stack>+ </Stack>+ );+}diff --git a/packages/core/src/Timestamp/Timestamp.doc.mjs b/packages/core/src/Timestamp/Timestamp.doc.mjsindex 4a70273c67..81a659aa63 100644--- a/packages/core/src/Timestamp/Timestamp.doc.mjs+++ b/packages/core/src/Timestamp/Timestamp.doc.mjs@@ -45,11 +45,17 @@ export const docs = {'Whether to show a tooltip with the full date/time on hover when displaying relative time.',default: 'true',},+ {+ name: 'tooltipEntries',+ type: 'ReadonlyArray<{timezoneID?: string; format?: TimestampTooltipFormat; label?: string}>',+ 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.",+ },{name: 'isTimezoneShown',type: 'boolean',description:- 'Whether to append the timezone abbreviation. Applies to date_time, time, system_date_time, and system_time formats.',+ 'Whether to append the timezone abbreviation to the visible text. Applies to the date_time and time formats; system_* formats stay machine-readable and never carry one. Use tooltipEntries to control the tooltip’s time zones.',default: 'false',},{@@ -94,14 +100,19 @@ export const docs = {{guidance: true, description: 'Use the auto format in feeds and lists so recent items show "2 hours ago" and older items show the full date automatically.'},{guidance: true, description: 'Keep formatting consistent within the same list or table; mixing relative and absolute timestamps in the same column confuses scanning.'},{guidance: true, description: 'Enable isTimezoneShown when the audience spans multiple time zones, like a global team calendar or audit log.'},+ {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: 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 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.'},+ {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.'},],},};@@ -113,7 +124,10 @@ export const docsZh = {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',- isTimezoneShown: '\u662f\u5426\u9644\u52a0\u65f6\u533a\u7f29\u5199\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',+ 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',type: '\u6765\u81ea Text \u7684\u8bed\u4e49\u6587\u672c\u7c7b\u578b\u3002',size: '\u663e\u5f0f\u5b57\u4f53\u5927\u5c0f\u8986\u76d6\u3002',@@ -127,21 +141,26 @@ export const docsZh = {{guidance: true, description: 'Use the auto format in feeds and lists so recent items show "2 hours ago" and older items show the full date automatically.'},{guidance: true, description: 'Keep formatting consistent within the same list or table; mixing relative and absolute timestamps in the same column confuses scanning.'},{guidance: true, description: 'Enable isTimezoneShown when the audience spans multiple time zones, like a global team calendar or audit log.'},+ {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: 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 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.'},+ {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.'},],},};/** @type {import('../docs-types').TranslationDoc} */export const docsDense = {- description: 'formatted timestamp with relative/absolute/auto modes, live updates, timezone display',+ description: 'formatted timestamp with relative/absolute/auto modes, live updates, timezone display, multi-zone tooltip',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.',@@ -149,7 +168,9 @@ export const docsDense = {{guidance: true, description: 'Auto format in feeds and lists; recent shows relative, older shows date_time.'},{guidance: true, description: 'Consistent formatting within the same list or table column.'},{guidance: true, description: 'isTimezoneShown for multi-timezone audiences.'},+ {guidance: true, description: 'tooltipEntries to compare zones on hover; label each entry once more than one zone is shown.'},{guidance: true, description: 'isLive for dashboards so relative time stays current.'},+ {guidance: false, description: 'Don\'t use fixed-offset ids like "EST" for timezoneID; they skip DST. Use region ids like "America/New_York".'},{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.'},@@ -160,7 +181,10 @@ export const docsDense = {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)',- isTimezoneShown: 'append timezone abbreviation',+ 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",+ isTimezoneShown:+ 'append timezone abbreviation to visible text (date_time and time only)',isLive: 'live-update relative time',type: 'Text semantic type',size: 'font size override',diff --git a/packages/core/src/Timestamp/Timestamp.test.tsx b/packages/core/src/Timestamp/Timestamp.test.tsxindex f0c2997326..fb9002b8ce 100644--- a/packages/core/src/Timestamp/Timestamp.test.tsx+++ b/packages/core/src/Timestamp/Timestamp.test.tsx@@ -4,6 +4,7 @@ import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';import {render, screen, act, waitFor} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {Timestamp} from './Timestamp';+import {formatTooltipLines} from './tooltipEntries';describe('Timestamp', () => {beforeEach(() => {@@ -487,4 +488,374 @@ describe('Timestamp', () => {expect(label).not.toContain('ago');});});++ // --- 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';++ 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).+ vi.useRealTimers();+ HTMLElement.prototype.showPopover = vi.fn();+ HTMLElement.prototype.hidePopover = vi.fn();+ });++ afterEach(() => {+ HTMLElement.prototype.showPopover = originalShowPopover;+ HTMLElement.prototype.hidePopover = originalHidePopover;+ });++ it('leaves the default tooltip as a single unwrapped line', async () => {+ render(+ <Timestamp+ value={Date.now() / 1000 - 3600}+ format="relative"+ 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();++ const normalize = (s: string) => s.replace(/\s+/g, ' ');+ expect(normalize(layer.textContent ?? '')).toContain(+ normalize(screen.getByTestId('ts').getAttribute('aria-label') ?? '\0'),+ );+ });++ it('renders one tooltip line per configured entry', async () => {+ render(+ <Timestamp+ value={VALUE}+ format="relative"+ tooltipEntries={[+ {label: 'Local'},+ {timezoneID: 'UTC', label: 'UTC'},+ {timezoneID: 'Asia/Tokyo', label: 'Tokyo'},+ ]}+ />,+ );+ 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');+ });++ it('renders each entry in the time zone it names', async () => {+ render(+ <Timestamp+ value={VALUE}+ format="relative"+ tooltipEntries={[+ {timezoneID: 'UTC', format: 'system_date_time', label: 'UTC'},+ {+ timezoneID: 'Asia/Tokyo',+ format: 'system_date_time',+ label: 'Tokyo',+ },+ ]}+ />,+ );+ const layer = await screen.findByRole('tooltip', {hidden: true});+ const values = Array.from(layer.querySelectorAll('dd')).map(+ el => el.textContent,+ );+ // Machine formats are locale- and host-timezone-independent, so these+ // hold on any developer machine and on CI.+ 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 () => {+ render(+ <Timestamp+ value={VALUE}+ format="date_time"+ tooltipEntries={[{timezoneID: 'UTC', label: 'UTC'}]}+ 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');+ // ...and the anchor becomes keyboard-reachable, as it is for relative.+ expect(screen.getByTestId('ts')).toHaveAttribute('tabindex', '0');+ });++ it('treats an empty entry list exactly like no configuration', () => {+ render(+ <Timestamp+ value={VALUE}+ format="date_time"+ tooltipEntries={[]}+ 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.+ expect(screen.getByTestId('ts')).not.toHaveAttribute('tabindex');+ });++ it('still honors hasTooltip={false} when entries are configured', () => {+ render(+ <Timestamp+ value={VALUE}+ format="date_time"+ hasTooltip={false}+ tooltipEntries={[{timezoneID: 'UTC'}]}+ data-testid="ts"+ />,+ );+ expect(screen.getByTestId('ts')).not.toHaveAttribute('tabindex');+ });++ it('leaves the accessible name unchanged when entries are configured', async () => {+ const value = Date.now() / 1000 - 3600;+ const {unmount} = render(+ <Timestamp value={value} format="relative" data-testid="a" />,+ );+ const before = screen.getByTestId('a').getAttribute('aria-label');+ unmount();++ render(+ <Timestamp+ value={value}+ format="relative"+ tooltipEntries={[{timezoneID: 'UTC', label: 'UTC'}]}+ data-testid="b"+ />,+ );+ // 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.+ expect(screen.getByTestId('b').getAttribute('aria-label')).toBe(before);+ });++ it('does not add an accessible name to absolute formats with entries', () => {+ render(+ <Timestamp+ value={VALUE}+ format="date_time"+ tooltipEntries={[{timezoneID: 'UTC'}]}+ data-testid="ts"+ />,+ );+ expect(screen.getByTestId('ts').getAttribute('aria-label')).toBeNull();+ });++ it('renders nothing for an unparseable value even with entries', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ try {+ const {container} = render(+ <Timestamp+ value="not-a-date"+ 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.+ expect(container).toBeEmptyDOMElement();+ } finally {+ warn.mockRestore();+ }+ });++ it('shows configured entries when auto resolves to an absolute format', async () => {+ render(+ <Timestamp+ value={VALUE}+ format="auto"+ autoThreshold={0}+ tooltipEntries={[+ {timezoneID: 'UTC', format: 'system_date_time', label: 'UTC'},+ ]}+ data-testid="ts"+ />,+ );+ // 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');+ expect(screen.getByTestId('ts')).toHaveAttribute('tabindex', '0');+ });++ it('accepts a unix-seconds value alongside entries', async () => {+ render(+ <Timestamp+ value={Date.parse(VALUE) / 1000}+ format="relative"+ tooltipEntries={[+ {timezoneID: 'UTC', format: 'system_date_time', label: 'UTC'},+ ]}+ />,+ );+ const layer = await screen.findByRole('tooltip', {hidden: true});+ expect(layer.textContent).toContain('2026-02-19 17:00:00');+ });++ it('pairs exactly one label cell with one value cell per entry', async () => {+ render(+ <Timestamp+ value={VALUE}+ format="relative"+ tooltipEntries={[+ {timezoneID: 'UTC', label: 'UTC'},+ {timezoneID: 'Asia/Tokyo'},+ {timezoneID: 'Europe/London', label: 'London'},+ ]}+ />,+ );+ 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('');+ });++ it('gives the tab stop back when entries are removed', () => {+ const {rerender} = render(+ <Timestamp+ value={VALUE}+ format="date_time"+ tooltipEntries={[{timezoneID: 'UTC'}]}+ data-testid="ts"+ />,+ );+ 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.+ 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 {+ render(+ <Timestamp+ value={VALUE}+ format="relative"+ tooltipEntries={[+ {timezoneID: 'Not/AZone', format: 'system_date_time'},+ {timezoneID: 'UTC', format: 'system_date_time'},+ ]}+ />,+ );+ const layer = await screen.findByRole('tooltip', {hidden: true});+ const values = Array.from(layer.querySelectorAll('dd')).map(+ el => el.textContent,+ );+ expect(values).toHaveLength(2);+ expect(values[1]).toBe('2026-02-19 17:00:00');+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('Not/AZone'));+ } finally {+ warn.mockRestore();+ }+ });+ });++ describe('one formatter behind both surfaces', () => {+ // The rendered text and a tooltip line are two views of the same instant.+ // They are meant to come from one formatter parameterized by zone, not two+ // that happen to agree: a format added or reshaped on one surface and not+ // the other is a silent drift, invisible until someone compares them.+ // These assertions compare the two surfaces directly, so re-forking either+ // one fails here. Locale- and timezone-agnostic: nothing is pinned to a+ // literal, only the two paths to each other.+ const VALUE = '2026-02-19T17:00:00Z';++ const SHARED_FORMATS = [+ 'date',+ 'date_long',+ 'date_weekday',+ 'date_time',+ 'time',+ 'system_date',+ 'system_date_time',+ 'system_time',+ ] as const;++ it.each(SHARED_FORMATS)(+ 'renders %s identically as text and as a zone-less tooltip line',+ format => {+ render(+ <Timestamp+ value={VALUE}+ format={format}+ hasTooltip={false}+ data-testid="ts"+ />,+ );+ const [line] = formatTooltipLines(new Date(VALUE), [{format}]);+ expect(line.value).toBe(screen.getByTestId('ts').textContent);+ },+ );++ it('renders the full style identically as the aria-label and as a line', () => {+ // 'full' is the one member with no visible-text counterpart — it backs+ // the accessible name of a relative timestamp and the tooltip's default+ // line. Those two must not drift apart either.+ render(+ <Timestamp+ value={VALUE}+ format="relative"+ hasTooltip={false}+ data-testid="ts"+ />,+ );+ const [line] = formatTooltipLines(new Date(VALUE), [{format: 'full'}]);+ expect(line.value).toBe(+ screen.getByTestId('ts').getAttribute('aria-label'),+ );+ });+ });});diff --git a/packages/core/src/Timestamp/Timestamp.tsx b/packages/core/src/Timestamp/Timestamp.tsxindex 29a2ad7159..eac8c97096 100644--- a/packages/core/src/Timestamp/Timestamp.tsx+++ b/packages/core/src/Timestamp/Timestamp.tsx@@ -16,7 +16,7 @@* - /packages/cli/templates/blocks/components/Timestamp/ (showcase blocks)*/-import {useEffect, useRef, useState, lazy, Suspense} from 'react';+import {useEffect, useRef, useState, lazy, Suspense, Fragment} from 'react';import * as stylex from '@stylexjs/stylex';import {Text} from '../Text';import type {TextType, TextSize, TextColor, TextWeight} from '../theme/types';@@ -24,8 +24,10 @@ import {mergeProps, mergeRefs} from '../utils';import {useDevWarning} from '../hooks/useDevWarning';import type {BaseProps} from '../BaseProps';import {themeProps} from '../utils/themeProps';-import {colorVars} from '../theme/tokens.stylex';-import {SHARED_DATE_FORMAT_OPTIONS} from '../utils/plainDate';+import {colorVars, spacingVars} from '../theme/tokens.stylex';+import {formatInstant} from './formatInstant';+import {formatTooltipLines} from './tooltipEntries';+import type {TimestampTooltipEntry} from './tooltipEntries';const LazyXDSTooltip = lazy(async () =>import('../Tooltip/Tooltip').then(mod => ({default: mod.Tooltip})),@@ -78,8 +80,35 @@ export interface TimestampProps extends BaseProps<HTMLTimeElement> {*/hasTooltip?: boolean;/**- * Whether to append the timezone abbreviation after the timestamp.- * Applies to date_time, time, system_date_time, and system_time formats.+ * 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.+ *+ * 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.+ *+ * @default undefined — a single line with the full absolute time in the+ * viewer's own time zone+ * @example+ * ```+ * <Timestamp+ * value={savedAt}+ * tooltipEntries={[+ * {label: 'Your time'},+ * {timezoneID: 'UTC', label: 'UTC'},+ * ]}+ * />+ * ```+ */+ tooltipEntries?: ReadonlyArray<TimestampTooltipEntry>;+ /**+ * Whether to append the timezone abbreviation after the timestamp text.+ * Applies to the date_time and time formats. The system_* formats stay+ * machine-readable and never carry a timezone abbreviation.+ *+ * Affects the visible text only — use `tooltipEntries` to control the+ * tooltip's time zones.* @default false*/isTimezoneShown?: boolean;@@ -137,6 +166,31 @@ const styles = stylex.create({':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,+ },});// =============================================================================@@ -244,89 +298,6 @@ function getRelativeTimeString(date: Date, now: Date): string {return `${years} ${years === 1 ? 'year' : 'years'} ago`;}-function pad(n: number): string {- return String(n).padStart(2, '0');-}--function formatTimestamp(- date: Date,- format: Exclude<TimestampFormat, 'relative' | 'auto'>,- isTimezoneShown: boolean,-): string {- switch (format) {- case 'date':- return new Intl.DateTimeFormat(- undefined,- SHARED_DATE_FORMAT_OPTIONS.date,- ).format(date);-- case 'date_long':- return new Intl.DateTimeFormat(- undefined,- SHARED_DATE_FORMAT_OPTIONS.date_long,- ).format(date);-- case 'date_weekday':- return new Intl.DateTimeFormat(- undefined,- SHARED_DATE_FORMAT_OPTIONS.date_weekday,- ).format(date);-- case 'date_time':- return new Intl.DateTimeFormat(undefined, {- year: 'numeric',- month: 'short',- day: 'numeric',- hour: 'numeric',- minute: '2-digit',- ...(isTimezoneShown ? {timeZoneName: 'short'} : {}),- }).format(date);-- case 'time':- return new Intl.DateTimeFormat(undefined, {- hour: 'numeric',- minute: '2-digit',- ...(isTimezoneShown ? {timeZoneName: 'short'} : {}),- }).format(date);-- case 'system_date': {- const y = date.getFullYear();- const m = pad(date.getMonth() + 1);- const d = pad(date.getDate());- return `${y}-${m}-${d}`;- }-- case 'system_date_time': {- const y = date.getFullYear();- const m = pad(date.getMonth() + 1);- const d = pad(date.getDate());- const h = pad(date.getHours());- const min = pad(date.getMinutes());- const s = pad(date.getSeconds());- return `${y}-${m}-${d} ${h}:${min}:${s}`;- }-- case 'system_time': {- const h = pad(date.getHours());- const min = pad(date.getMinutes());- const s = pad(date.getSeconds());- return `${h}:${min}:${s}`;- }- }-}--function getFullAbsoluteString(date: Date): string {- return new Intl.DateTimeFormat(undefined, {- year: 'numeric',- month: 'long',- day: 'numeric',- hour: 'numeric',- minute: '2-digit',- second: '2-digit',- timeZoneName: 'short',- }).format(date);-}-/** Returns the interval (in ms) at which a relative timestamp should update. */function getLiveInterval(diffSeconds: number): number {const absDiff = Math.abs(diffSeconds);@@ -374,6 +345,7 @@ export function Timestamp({format = 'auto',autoThreshold = DEFAULT_AUTO_THRESHOLD,hasTooltip = true,+ tooltipEntries,isTimezoneShown = false,isLive = false,type = 'supporting',@@ -406,17 +378,18 @@ export function Timestamp({: 'date_time': format;- // Format the display text+ // Format the display text. No time zone is passed: the visible text always+ // reads in the viewer's own zone, and only the tooltip names others.const displayText = !isValidDate? '': effectiveFormat === 'relative'? getRelativeTimeString(date, now): isAbsoluteFormat(effectiveFormat)- ? formatTimestamp(date, effectiveFormat, isTimezoneShown)+ ? formatInstant(date, effectiveFormat, {isTimezoneShown}): '';// Full absolute text for tooltip and aria-label- const fullAbsoluteText = isValidDate ? getFullAbsoluteString(date) : '';+ const fullAbsoluteText = isValidDate ? formatInstant(date, 'full') : '';// Live updatesuseEffect(() => {@@ -443,7 +416,19 @@ export function Timestamp({return null;}- const showTooltip = hasTooltip && effectiveFormat === 'relative';+ // 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 =+ tooltipEntries !== undefined && tooltipEntries.length > 0+ ? 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.+ const showTooltip =+ hasTooltip && (effectiveFormat === 'relative' || entries !== undefined);const timestampProps = mergeProps(themeProps('timestamp', {format: effectiveFormat}),@@ -479,13 +464,31 @@ export function Timestamp({);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>+ );+return (<>{timeElement}<Suspense fallback={null}><LazyXDSTooltipanchorRef={timeRef}- content={fullAbsoluteText}+ content={tooltipContent}placement="above"/></Suspense>diff --git a/packages/core/src/Timestamp/formatInstant.ts b/packages/core/src/Timestamp/formatInstant.tsnew file mode 100644index 0000000000..7e9c9a755c--- /dev/null+++ b/packages/core/src/Timestamp/formatInstant.ts@@ -0,0 +1,218 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file formatInstant.ts+ * @input A Date, one absolute format name, and an optional time zone+ * @output That instant rendered as a string+ * @position Leaf shared by Timestamp's visible text and each of its tooltip+ * lines; owns every absolute format Timestamp can produce+ *+ * Timestamp renders the same instant on two surfaces — the visible text and,+ * on hover, one line per configured time zone. They differ only in which zone+ * they name and whether they carry a zone abbreviation, so they are one+ * formatter parameterized by zone rather than two switches that have to be+ * kept in step by hand. Adding a member to `TimestampFormat` now fails to+ * compile in exactly one place.+ *+ * Each caller keeps its own policy for the zone abbreviation: the visible text+ * takes it straight from the `isTimezoneShown` prop, a tooltip line derives it+ * from how many zones are on screen (see tooltipEntries.ts). Only the+ * rendering is shared, not the decision.+ *+ * Omitting `timeZone` means the viewer's own zone. That path hands `Intl` no+ * `timeZone` and keeps `system_*` on plain `Date` getters, so it produces+ * exactly what it produced before this module existed.+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/Timestamp/Timestamp.tsx+ * - /packages/core/src/Timestamp/tooltipEntries.ts+ * - /packages/core/src/Timestamp/Timestamp.test.tsx+ */++import {SHARED_DATE_FORMAT_OPTIONS, getTimeZoneParts} from '../utils/plainDate';+import type {TimestampFormat} from './Timestamp';++// =============================================================================+// Types+// =============================================================================++/**+ * Every format that names a fixed instant, plus `'full'` — the long absolute+ * style ("February 19, 2026 at 5:00:00 PM UTC") that backs a relative+ * timestamp's accessible name and the tooltip's default line.+ *+ * `'relative'` and `'auto'` are excluded: a relative phrase names no instant,+ * so a zone could not change what it says.+ */+export type InstantFormat =+ | Exclude<TimestampFormat, 'relative' | 'auto'>+ | 'full';++export interface FormatInstantOptions {+ /**+ * IANA time zone identifier. Omit for the viewer's own zone — which is what+ * `Intl` already does with no `timeZone`, so the omitted path never+ * constructs an explicit-zone formatter and cannot drift from the host+ * default.+ *+ * Must already be one the platform accepts. An identifier `Intl` does not+ * recognize throws a `RangeError` from its constructor, before any+ * formatting happens; deciding what to do about that belongs to whoever+ * took the identifier from a consumer, not here (tooltipEntries resolves+ * and warns in `resolveTimezoneID`, then passes only what survived).+ */+ timeZone?: string;+ /**+ * Whether to append the zone abbreviation. Honoured by `date_time` and+ * `time` only: `'full'` always carries one because that is the style, and+ * the `system_*` shapes never do — a trailing "PST" would break anything+ * parsing them, which is why `isTimezoneShown` has never applied to them.+ * @default false+ */+ isTimezoneShown?: boolean;+}++// =============================================================================+// Option bags+// =============================================================================++/** The long absolute style, with seconds and a zone name. */+const FULL_OPTIONS: Intl.DateTimeFormatOptions = {+ year: 'numeric',+ month: 'long',+ day: 'numeric',+ hour: 'numeric',+ minute: '2-digit',+ second: '2-digit',+ timeZoneName: 'short',+};++/** The time-of-day part, shared by `time` and `date_time`. */+const TIME_OPTIONS: Intl.DateTimeFormatOptions = {+ hour: 'numeric',+ minute: '2-digit',+};++/**+ * The date part here is spelled out rather than taken from+ * `SHARED_DATE_FORMAT_OPTIONS.date`. That bag is shared with DateInput, and+ * pointing `date_time` at it would mean a change made for date-only fields+ * silently reshaped every date-and-time reading too. The two agree today; they+ * are not the same decision.+ */+const DATE_TIME_OPTIONS: Intl.DateTimeFormatOptions = {+ year: 'numeric',+ month: 'short',+ day: 'numeric',+ ...TIME_OPTIONS,+};++// =============================================================================+// Formatting+// =============================================================================++function pad(n: number): string {+ return String(n).padStart(2, '0');+}++/** The fields a `system_*` string is assembled from. */+interface WallClock {+ year: number;+ month: number;+ day: number;+ hour: number;+ minute: number;+ second: number;+}++/**+ * Wall-clock fields for an instant: in the named zone, or — with no zone —+ * the viewer's own, read straight off the `Date`. The zone-less branch+ * deliberately stays on plain getters so the default rendering never gains a+ * dependency on `Intl` zone data it did not have before.+ *+ * The explicit return type is load-bearing: it is what forces the two branches+ * to keep producing the same shape.+ */+function getWallClock(date: Date, timeZone: string | undefined): WallClock {+ return timeZone === undefined+ ? {+ year: date.getFullYear(),+ month: date.getMonth() + 1,+ day: date.getDate(),+ hour: date.getHours(),+ minute: date.getMinutes(),+ second: date.getSeconds(),+ }+ : getTimeZoneParts(date.getTime(), timeZone);+}++/**+ * Renders one instant in one absolute format.+ *+ * Pure: the same arguments always produce the same string for a given host+ * locale (and, when no `timeZone` is given, host zone).+ */+export function formatInstant(+ date: Date,+ format: InstantFormat,+ {timeZone, isTimezoneShown = false}: FormatInstantOptions = {},+): string {+ const zone = timeZone === undefined ? {} : {timeZone};+ const zoneName = isTimezoneShown ? {timeZoneName: 'short' as const} : {};++ switch (format) {+ case 'full':+ return new Intl.DateTimeFormat(undefined, {+ ...FULL_OPTIONS,+ ...zone,+ }).format(date);++ case 'date':+ return new Intl.DateTimeFormat(undefined, {+ ...SHARED_DATE_FORMAT_OPTIONS.date,+ ...zone,+ }).format(date);++ case 'date_long':+ return new Intl.DateTimeFormat(undefined, {+ ...SHARED_DATE_FORMAT_OPTIONS.date_long,+ ...zone,+ }).format(date);++ case 'date_weekday':+ return new Intl.DateTimeFormat(undefined, {+ ...SHARED_DATE_FORMAT_OPTIONS.date_weekday,+ ...zone,+ }).format(date);++ case 'date_time':+ return new Intl.DateTimeFormat(undefined, {+ ...DATE_TIME_OPTIONS,+ ...zoneName,+ ...zone,+ }).format(date);++ case 'time':+ return new Intl.DateTimeFormat(undefined, {+ ...TIME_OPTIONS,+ ...zoneName,+ ...zone,+ }).format(date);++ case 'system_date': {+ const w = getWallClock(date, timeZone);+ return `${w.year}-${pad(w.month)}-${pad(w.day)}`;+ }++ case 'system_date_time': {+ const w = getWallClock(date, timeZone);+ return `${w.year}-${pad(w.month)}-${pad(w.day)} ${pad(w.hour)}:${pad(w.minute)}:${pad(w.second)}`;+ }++ case 'system_time': {+ const w = getWallClock(date, timeZone);+ return `${pad(w.hour)}:${pad(w.minute)}:${pad(w.second)}`;+ }+ }+}diff --git a/packages/core/src/Timestamp/index.ts b/packages/core/src/Timestamp/index.tsindex 6f42acf540..3bda667ffd 100644--- a/packages/core/src/Timestamp/index.ts+++ b/packages/core/src/Timestamp/index.ts@@ -13,3 +13,7 @@export {Timestamp} from './Timestamp';export type {TimestampProps, TimestampFormat} from './Timestamp';+export type {+ TimestampTooltipEntry,+ TimestampTooltipFormat,+} from './tooltipEntries';diff --git a/packages/core/src/Timestamp/tooltipEntries.test.ts b/packages/core/src/Timestamp/tooltipEntries.test.tsnew file mode 100644index 0000000000..f25555871f--- /dev/null+++ b/packages/core/src/Timestamp/tooltipEntries.test.ts@@ -0,0 +1,552 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file tooltipEntries.test.ts+ * @input formatTooltipLines and its entry types+ * @output Coverage for zone/format/label resolution of Timestamp tooltip lines+ * @position Unit tests for the pure tooltip-line formatter+ *+ * These tests must pass under ANY machine timezone. The repo pins TZ neither in+ * vitest.config.ts nor in CI, so a developer machine (e.g. America/New_York) and+ * CI (typically UTC) run the same assertions. Every exact-string expectation+ * therefore names an explicit zone and uses a `system_*` format, which is built+ * from numeric parts and is both timezone- and locale-independent. Assertions+ * about locale-formatted output stay structural.+ */++import {describe, it, expect, vi} from 'vitest';+import {SHARED_DATE_FORMAT_OPTIONS} from '../utils/plainDate';+import {formatTooltipLines} from './tooltipEntries';++/** 2026-02-19T17:00:00Z — chosen so several zones land on different dates. */+const INSTANT = new Date('2026-02-19T17:00:00Z');++const LOCAL_ZONE = Intl.DateTimeFormat().resolvedOptions().timeZone;++describe('formatTooltipLines', () => {+ // --- Explicit zones: exact, locale-free, TZ-agnostic ---++ it('renders system_date_time in an explicit zone', () => {+ const lines = formatTooltipLines(INSTANT, [+ {timezoneID: 'UTC', format: 'system_date_time'},+ ]);+ expect(lines).toHaveLength(1);+ expect(lines[0].value).toBe('2026-02-19 17:00:00');+ });++ it('crosses the date line for a zone that is a day ahead', () => {+ // 17:00Z is 02:00 the NEXT day in Tokyo. A naive local-getter+ // implementation would return the viewer's date here.+ const lines = formatTooltipLines(INSTANT, [+ {timezoneID: 'Asia/Tokyo', format: 'system_date_time'},+ ]);+ expect(lines[0].value).toBe('2026-02-20 02:00:00');+ });++ it('handles a half-hour offset zone', () => {+ const lines = formatTooltipLines(INSTANT, [+ {timezoneID: 'Asia/Kolkata', format: 'system_date_time'},+ ]);+ expect(lines[0].value).toBe('2026-02-19 22:30:00');+ });++ it('renders system_date and system_time in an explicit zone', () => {+ const lines = formatTooltipLines(INSTANT, [+ {timezoneID: 'America/Los_Angeles', format: 'system_date'},+ {timezoneID: 'America/Los_Angeles', format: 'system_time'},+ ]);+ expect(lines[0].value).toBe('2026-02-19');+ expect(lines[1].value).toBe('09:00:00');+ });++ it('honors the zone across a DST transition rather than a fixed offset', () => {+ // Los Angeles is UTC-8 in January and UTC-7 in July. A fixed-offset+ // implementation would get one of these wrong.+ const winter = formatTooltipLines(new Date('2026-01-15T20:00:00Z'), [+ {timezoneID: 'America/Los_Angeles', format: 'system_date_time'},+ ]);+ const summer = formatTooltipLines(new Date('2026-07-15T20:00:00Z'), [+ {timezoneID: 'America/Los_Angeles', format: 'system_date_time'},+ ]);+ expect(winter[0].value).toBe('2026-01-15 12:00:00');+ expect(summer[0].value).toBe('2026-07-15 13:00:00');+ });++ // --- The shared date vocabulary ---++ it.each(['date', 'date_long', 'date_weekday'] as const)(+ 'renders %s from the shared option bag, in the requested zone',+ format => {+ // These three members are owned by SHARED_DATE_FORMAT_OPTIONS so that+ // Timestamp's rendered text and DateInput's display path cannot drift.+ // A tooltip line must come from the same bag: rebuilding the expected+ // string from the shared constant here fails the moment this file+ // inlines its own options again. Locale-agnostic — both sides format+ // under whatever locale the machine has.+ for (const timezoneID of ['UTC', 'Asia/Tokyo']) {+ const [line] = formatTooltipLines(INSTANT, [{timezoneID, format}]);+ expect(line.value).toBe(+ new Intl.DateTimeFormat(undefined, {+ ...SHARED_DATE_FORMAT_OPTIONS[format],+ timeZone: timezoneID,+ }).format(INSTANT),+ );+ }++ // 17:00Z is already the next calendar day in Tokyo, so the two zones+ // must disagree — proof the zone reached Intl rather than being dropped.+ const [utc] = formatTooltipLines(INSTANT, [{timezoneID: 'UTC', format}]);+ const [tokyo] = formatTooltipLines(INSTANT, [+ {timezoneID: 'Asia/Tokyo', format},+ ]);+ expect(tokyo.value).not.toBe(utc.value);+ },+ );++ // --- Equivalence with the untouched local implementation ---++ it('matches the local-getter output character-for-character for the viewer zone', () => {+ // The existing formatTimestamp() builds system_* from date.getFullYear()/+ // getHours()/... Naming the viewer's own zone explicitly must produce the+ // identical string, or the two code paths have drifted.+ const pad = (n: number) => String(n).padStart(2, '0');+ const expected = `${INSTANT.getFullYear()}-${pad(INSTANT.getMonth() + 1)}-${pad(+ INSTANT.getDate(),+ )} ${pad(INSTANT.getHours())}:${pad(INSTANT.getMinutes())}:${pad(+ INSTANT.getSeconds(),+ )}`;++ const explicit = formatTooltipLines(INSTANT, [+ {timezoneID: LOCAL_ZONE, format: 'system_date_time'},+ ]);+ const implicit = formatTooltipLines(INSTANT, [+ {format: 'system_date_time'},+ ]);++ expect(explicit[0].value).toBe(expected);+ expect(implicit[0].value).toBe(expected);+ });++ // --- The 'local' sentinel ---++ it("treats timezoneID 'local' as an alias for the viewer's zone", () => {+ const omitted = formatTooltipLines(INSTANT, [{format: 'system_date_time'}]);+ const sentinel = formatTooltipLines(INSTANT, [+ {timezoneID: 'local', format: 'system_date_time'},+ ]);+ expect(sentinel[0].value).toBe(omitted[0].value);+ });++ it("does not treat 'local' as an IANA id to be looked up", () => {+ // 'local' is not a real zone; it must never reach Intl, which would throw.+ expect(() =>+ formatTooltipLines(INSTANT, [{timezoneID: 'local'}]),+ ).not.toThrow();+ });++ // --- Defaults ---++ it("defaults an entry's format to the full absolute style", () => {+ const [line] = formatTooltipLines(INSTANT, [{timezoneID: 'UTC'}]);+ // The full style carries date, time-with-seconds and a zone name.+ expect(line.value).toContain('2026');+ expect(line.value).toMatch(/\d{1,2}:00:00/);+ expect(line.value).toContain('UTC');+ });++ it('defaults an entry to the viewer zone when no timezoneID is given', () => {+ const [line] = formatTooltipLines(INSTANT, [{}]);+ expect(line.value).toContain('2026');+ expect(line.label).toBeUndefined();+ });++ // --- Labels ---++ it('passes a consumer label through verbatim', () => {+ const lines = formatTooltipLines(INSTANT, [+ {label: 'Your time'},+ {timezoneID: 'UTC', label: 'UTC'},+ ]);+ expect(lines[0].label).toBe('Your time');+ expect(lines[1].label).toBe('UTC');+ });++ it('never invents a label when none is supplied', () => {+ const lines = formatTooltipLines(INSTANT, [{}, {timezoneID: 'Asia/Tokyo'}]);+ expect(lines[0].label).toBeUndefined();+ expect(lines[1].label).toBeUndefined();+ });++ // --- Auto zone abbreviation (the disambiguation rule) ---++ it('appends a zone abbreviation to date_time lines when zones differ', () => {+ const lines = formatTooltipLines(INSTANT, [+ {format: 'date_time'},+ {timezoneID: 'UTC', format: 'date_time'},+ ]);+ // Two distinct zones were asked for, so each line must say which it is.+ expect(lines[1].value).toContain('UTC');+ });++ it('marks even the unnamed local line once a second zone is on screen', () => {+ // This is the case only the multiple-zones half of the rule can reach: the+ // first entry names nothing, so without that clause it would sit unmarked+ // beside a marked foreign line and read as though it were the foreign one.+ const alone = formatTooltipLines(INSTANT, [{format: 'date_time'}]);+ const beside = formatTooltipLines(INSTANT, [+ {format: 'date_time'},+ {timezoneID: 'UTC', format: 'date_time'},+ ]);+ expect(beside[0].value).not.toBe(alone[0].value);+ expect(beside[0].value.startsWith(alone[0].value)).toBe(true);+ });++ it('omits the zone abbreviation when one unnamed zone is shown twice', () => {+ // Same viewer zone rendered in two formats, neither of them steered by the+ // consumer — a zone marker here would be noise.+ const lines = formatTooltipLines(INSTANT, [+ {format: 'date_time'},+ {format: 'system_date_time'},+ ]);+ const localName = new Intl.DateTimeFormat(undefined, {+ timeZoneName: 'short',+ })+ .formatToParts(INSTANT)+ .find(part => part.type === 'timeZoneName')?.value;+ expect(lines[0].value).not.toContain(localName);+ });++ it('never appends a zone abbreviation to system_* lines', () => {+ const lines = formatTooltipLines(INSTANT, [+ {format: 'system_date_time'},+ {timezoneID: 'Asia/Tokyo', format: 'system_date_time'},+ ]);+ // Two distinct zones, but system_* output stays machine-clean.+ expect(lines[1].value).toBe('2026-02-20 02:00:00');+ });++ it('marks a single explicitly-named zone so it cannot be read as local', () => {+ // The tooltip is never read in isolation: it is the <time>'s+ // aria-describedby, and that element's accessible name is the LOCAL+ // absolute time. A lone foreign-zone line with no marker is therefore+ // announced right after a local time, with nothing to say it is not one.+ const zoneName = new Intl.DateTimeFormat(undefined, {+ timeZone: 'Asia/Tokyo',+ timeZoneName: 'short',+ })+ .formatToParts(INSTANT)+ .find(part => part.type === 'timeZoneName')?.value;++ const [line] = formatTooltipLines(INSTANT, [+ {timezoneID: 'Asia/Tokyo', format: 'date_time'},+ ]);+ expect(zoneName).toBeTruthy();+ expect(line.value).toContain(zoneName);+ });++ it('leaves an unnamed local line unmarked', () => {+ // The consumer never named a zone, so there is nothing to disambiguate+ // against — this must stay as bare as the visible text is by default.+ const [line] = formatTooltipLines(INSTANT, [{format: 'date_time'}]);+ const localName = new Intl.DateTimeFormat(undefined, {+ timeZoneName: 'short',+ })+ .formatToParts(INSTANT)+ .find(part => part.type === 'timeZoneName')?.value;+ expect(line.value).not.toContain(localName);+ });++ it('always carries a zone name on the full style, even for a single line', () => {+ const [line] = formatTooltipLines(INSTANT, [{timezoneID: 'UTC'}]);+ expect(line.value).toContain('UTC');+ });++ // --- Invalid zone handling ---++ it('falls back to the viewer zone instead of throwing on an invalid zone id', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ try {+ const lines = formatTooltipLines(INSTANT, [+ {timezoneID: 'Not/AZone', format: 'system_date_time'},+ ]);+ const local = formatTooltipLines(INSTANT, [{format: 'system_date_time'}]);+ expect(lines[0].value).toBe(local[0].value);+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('Not/AZone'));+ } finally {+ warn.mockRestore();+ }+ });++ it('warns once per unknown zone, however many times it is used', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ try {+ // The same bad id twice in one call, then again on a re-render. A live+ // timestamp re-renders every second, so one typo must not turn into an+ // unbounded stream of identical console warnings.+ formatTooltipLines(INSTANT, [+ {timezoneID: 'Bad/RepeatedZone'},+ {timezoneID: 'Bad/RepeatedZone'},+ ]);+ formatTooltipLines(INSTANT, [{timezoneID: 'Bad/RepeatedZone'}]);+ expect(warn).toHaveBeenCalledTimes(1);+ } finally {+ warn.mockRestore();+ }+ });++ it('falls back for an empty or whitespace-only zone id', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ try {+ const local = formatTooltipLines(INSTANT, [{format: 'system_date_time'}]);+ // Intl rejects both of these, so they must take the same degraded path+ // as any other unknown identifier rather than reaching the formatter.+ for (const timezoneID of ['', ' ']) {+ const lines = formatTooltipLines(INSTANT, [+ {timezoneID, format: 'system_date_time'},+ ]);+ expect(lines[0].value).toBe(local[0].value);+ }+ expect(warn).toHaveBeenCalledTimes(2);+ } finally {+ warn.mockRestore();+ }+ });++ it('rejects a zone id padded with whitespace rather than trimming it', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ try {+ const local = formatTooltipLines(INSTANT, [{format: 'system_date_time'}]);+ // ' UTC ' is not a valid identifier. Silently trimming would be a guess+ // about intent; degrading to the viewer's zone with a warning is not.+ const padded = formatTooltipLines(INSTANT, [+ {timezoneID: ' UTC ', format: 'system_date_time'},+ ]);+ expect(padded[0].value).toBe(local[0].value);+ expect(warn).toHaveBeenCalledWith(expect.stringContaining(' UTC '));+ } finally {+ warn.mockRestore();+ }+ });++ it('accepts a legacy link id and resolves it to the modern zone', () => {+ // Intl accepts the old US/* names; they must not be mistaken for junk.+ const legacy = formatTooltipLines(INSTANT, [+ {timezoneID: 'US/Pacific', format: 'system_date_time'},+ ]);+ expect(legacy[0].value).toBe('2026-02-19 09:00:00');+ });++ it('treats a fixed-offset id like EST as fixed, not as US Eastern', () => {+ // Intl ACCEPTS 'EST', so no warning fires — but it is a fixed UTC-5 zone+ // that never observes daylight saving. A consumer who writes 'EST' meaning+ // "US Eastern" is silently an hour out for half the year. Pinned here so+ // the trap is visible in the tests, and steered against in the docs.+ const summer = new Date('2026-07-19T17:00:00Z');+ const fixed = formatTooltipLines(summer, [+ {timezoneID: 'EST', format: 'system_date_time'},+ ]);+ const region = formatTooltipLines(summer, [+ {timezoneID: 'America/New_York', format: 'system_date_time'},+ ]);+ expect(fixed[0].value).toBe('2026-07-19 12:00:00');+ expect(region[0].value).toBe('2026-07-19 13:00:00');+ });++ it('keeps the remaining lines intact when one entry has a bad zone', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ try {+ const lines = formatTooltipLines(INSTANT, [+ {timezoneID: 'Not/AZone', format: 'system_date_time'},+ {timezoneID: 'UTC', format: 'system_date_time'},+ ]);+ expect(lines).toHaveLength(2);+ expect(lines[1].value).toBe('2026-02-19 17:00:00');+ } finally {+ warn.mockRestore();+ }+ });++ // --- Wall-clock edges ---++ it('renders midnight as 00, never 24', () => {+ // The parts are read under hourCycle 'h23'. Under 'h24' the same instant+ // comes back as hour 24 and every midnight timestamp renders wrong.+ const lines = formatTooltipLines(new Date('2026-02-19T00:00:00Z'), [+ {timezoneID: 'UTC', format: 'system_date_time'},+ ]);+ expect(lines[0].value).toBe('2026-02-19 00:00:00');+ });++ it('rolls midnight into the next day for a zone that is ahead', () => {+ // 15:00Z is exactly 00:00 the following day in Tokyo — midnight and a+ // date rollover in the same assertion.+ const lines = formatTooltipLines(new Date('2026-02-19T15:00:00Z'), [+ {timezoneID: 'Asia/Tokyo', format: 'system_date_time'},+ ]);+ expect(lines[0].value).toBe('2026-02-20 00:00:00');+ });++ it('handles a 45-minute offset zone', () => {+ // Nepal is UTC+5:45. Anything that assumes whole- or half-hour offsets+ // gets this wrong.+ const lines = formatTooltipLines(INSTANT, [+ {timezoneID: 'Asia/Kathmandu', format: 'system_date_time'},+ ]);+ expect(lines[0].value).toBe('2026-02-19 22:45:00');+ });++ it('spans the full range either side of the date line', () => {+ // +14 and -11 are the extremes in use; the same instant is 25 hours and+ // two calendar days apart between them.+ const lines = formatTooltipLines(INSTANT, [+ {timezoneID: 'Pacific/Kiritimati', format: 'system_date_time'},+ {timezoneID: 'Pacific/Niue', format: 'system_date_time'},+ ]);+ expect(lines.map(l => l.value)).toEqual([+ '2026-02-20 07:00:00',+ '2026-02-19 06:00:00',+ ]);+ });++ it('carries the year across a new-year boundary', () => {+ const lines = formatTooltipLines(new Date('2025-12-31T23:30:00Z'), [+ {timezoneID: 'Asia/Tokyo', format: 'system_date_time'},+ ]);+ expect(lines[0].value).toBe('2026-01-01 08:30:00');+ });++ it('renders a leap day', () => {+ const lines = formatTooltipLines(new Date('2028-02-29T12:00:00Z'), [+ {timezoneID: 'UTC', format: 'system_date'},+ ]);+ expect(lines[0].value).toBe('2028-02-29');+ });++ it('renders both halves of a repeated DST hour identically', () => {+ // On the fall-back date, 01:30 local happens twice. Mapping an instant to+ // a wall clock is many-to-one, so both instants legitimately render the+ // same machine string — which is exactly why system_* output is not+ // sufficient on its own to identify an instant. Pinned so nobody "fixes"+ // it into a fake distinction.+ const beforeShift = formatTooltipLines(new Date('2026-11-01T05:30:00Z'), [+ {timezoneID: 'America/New_York', format: 'system_date_time'},+ ]);+ const afterShift = formatTooltipLines(new Date('2026-11-01T06:30:00Z'), [+ {timezoneID: 'America/New_York', format: 'system_date_time'},+ ]);+ expect(beforeShift[0].value).toBe('2026-11-01 01:30:00');+ expect(afterShift[0].value).toBe('2026-11-01 01:30:00');+ });++ // --- Distinct-zone counting drives the abbreviation rule ---++ it('counts a zone that fell back to local as the local zone', () => {+ // The bad entry degrades to the viewer's zone, so the tooltip is really+ // showing ONE zone and must not start labelling lines as if it showed two.+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ try {+ const single = formatTooltipLines(INSTANT, [{format: 'date_time'}]);+ const withBad = formatTooltipLines(INSTANT, [+ {format: 'date_time'},+ {timezoneID: 'Bad/CountingZone', format: 'date_time'},+ ]);+ expect(withBad[0].value).toBe(single[0].value);+ expect(withBad[1].value).toBe(single[0].value);+ } finally {+ warn.mockRestore();+ }+ });++ it('renders two alias spellings of one zone identically to a single one', () => {+ // 'UTC' and 'GMT' are aliases, so the distinctness key counts them as two+ // zones. That can never show, because a line whose zone the consumer named+ // is marked whether or not a second zone is present — all three renderings+ // below must agree. If the marker rule ever narrows back to "more than one+ // zone", this pair would start disagreeing with the single entry and read+ // as two lines that need telling apart while being character-identical.+ const pair = formatTooltipLines(INSTANT, [+ {timezoneID: 'UTC', format: 'date_time'},+ {timezoneID: 'GMT', format: 'date_time'},+ ]);+ const solo = formatTooltipLines(INSTANT, [+ {timezoneID: 'UTC', format: 'date_time'},+ ]);+ expect(pair[0].value).toBe(solo[0].value);+ expect(pair[1].value).toBe(solo[0].value);+ });++ it('renders the same zone spelled in different casing identically', () => {+ // Zone ids are case-insensitive per ECMA-402, and the distinctness key+ // lowercases to match, so neither line can drift from the other.+ const lines = formatTooltipLines(INSTANT, [+ {timezoneID: 'UTC', format: 'date_time'},+ {timezoneID: 'utc', format: 'date_time'},+ ]);+ expect(lines[0].value).toBe(lines[1].value);+ });++ it("counts an omitted zone and 'local' as one zone", () => {+ const single = formatTooltipLines(INSTANT, [{format: 'date_time'}]);+ const both = formatTooltipLines(INSTANT, [+ {format: 'date_time'},+ {timezoneID: 'local', format: 'date_time'},+ ]);+ expect(both[0].value).toBe(single[0].value);+ expect(both[1].value).toBe(single[0].value);+ });++ // --- Entry shape ---++ it('treats an explicitly undefined format as absent', () => {+ const explicit = formatTooltipLines(INSTANT, [+ {timezoneID: 'UTC', format: undefined},+ ]);+ const omitted = formatTooltipLines(INSTANT, [{timezoneID: 'UTC'}]);+ expect(explicit[0].value).toBe(omitted[0].value);+ });++ it('keeps an empty-string label rather than dropping it', () => {+ // '' is a deliberate "this line has no label" that still occupies the+ // label column; only an omitted label is truly absent.+ const [line] = formatTooltipLines(INSTANT, [{label: ''}]);+ expect(line.label).toBe('');+ });++ // --- Ordering and arity ---++ it('preserves entry order', () => {+ const lines = formatTooltipLines(INSTANT, [+ {timezoneID: 'Asia/Tokyo', format: 'system_date', label: 'Tokyo'},+ {timezoneID: 'UTC', format: 'system_date', label: 'UTC'},+ {timezoneID: 'America/Los_Angeles', format: 'system_date', label: 'LA'},+ ]);+ expect(lines.map(l => l.label)).toEqual(['Tokyo', 'UTC', 'LA']);+ expect(lines.map(l => l.value)).toEqual([+ '2026-02-20',+ '2026-02-19',+ '2026-02-19',+ ]);+ });++ it('returns one line per entry, including duplicates', () => {+ const lines = formatTooltipLines(INSTANT, [+ {timezoneID: 'UTC'},+ {timezoneID: 'UTC'},+ ]);+ expect(lines).toHaveLength(2);+ expect(lines[0].value).toBe(lines[1].value);+ });++ it('returns an empty array for no entries', () => {+ expect(formatTooltipLines(INSTANT, [])).toEqual([]);+ });++ // --- Zone ids are case-insensitive per ECMA-402 ---++ it('accepts a lowercase IANA id', () => {+ const lines = formatTooltipLines(INSTANT, [+ {timezoneID: 'asia/tokyo', format: 'system_date_time'},+ ]);+ expect(lines[0].value).toBe('2026-02-20 02:00:00');+ });+});diff --git a/packages/core/src/Timestamp/tooltipEntries.ts b/packages/core/src/Timestamp/tooltipEntries.tsnew file mode 100644index 0000000000..df5549915a--- /dev/null+++ b/packages/core/src/Timestamp/tooltipEntries.ts@@ -0,0 +1,210 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file tooltipEntries.ts+ * @input A Date and the consumer's tooltip entry list+ * @output Pure formatting of one tooltip line per entry, plus the entry types+ * @position Leaf module; owns which zone each tooltip line names and whether+ * it needs a zone abbreviation, then defers to formatInstant to render it+ *+ * This module holds only the decisions a tooltip makes that the visible text+ * does not: resolving `timezoneID` (including the `'local'` alias and the+ * fallback for an unknown identifier), and deciding which lines need a zone+ * abbreviation to be told apart. The formatting itself is formatInstant's,+ * shared with the rendered text, so the two surfaces cannot drift.+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/Timestamp/Timestamp.tsx+ * - /packages/core/src/Timestamp/formatInstant.ts+ * - /packages/core/src/Timestamp/tooltipEntries.test.ts+ * - /packages/core/src/Timestamp/Timestamp.doc.mjs+ * - /packages/core/src/Timestamp/index.ts+ */++import {devWarn} from '../utils/devWarning';+import {formatInstant} from './formatInstant';+import type {InstantFormat} from './formatInstant';++// =============================================================================+// Types+// =============================================================================++/**+ * Formats available to a tooltip line.+ *+ * Every `TimestampFormat` that names a fixed instant, plus `'full'` — the long+ * absolute style the tooltip has always shown ("February 19, 2026 at 5:00:00 PM+ * UTC"). `'relative'` and `'auto'` are excluded: a relative phrase ignores any+ * zone, which would make `timezoneID` silently inert on that line.+ *+ * `'full'` lives only in this vocabulary, never in `TimestampFormat` — nothing+ * asked for it as a visible display format, and keeping it out means new+ * members added to `TimestampFormat` become valid tooltip formats for free.+ *+ * The public spelling of {@link InstantFormat}: consumers reading Timestamp's+ * props should not have to know the name of its internal formatter.+ */+export type TimestampTooltipFormat = InstantFormat;++/** One line of the Timestamp tooltip. */+export interface TimestampTooltipEntry {+ /**+ * IANA time zone identifier, e.g. `'UTC'`, `'America/Los_Angeles'`.+ * Omit it — or pass `'local'` — for the viewer's own zone.+ *+ * Prefer region identifiers. Fixed-offset abbreviations such as `'EST'` are+ * accepted by the platform but never observe daylight saving, so they read+ * an hour wrong for half the year — `'America/New_York'` is what people+ * usually mean by "Eastern".+ *+ * An identifier the platform does not recognize falls back to the viewer's+ * zone with a console warning rather than throwing.+ */+ timezoneID?: string;+ /**+ * How this line renders the instant.+ * @default 'full'+ */+ format?: TimestampTooltipFormat;+ /**+ * Text shown beside the time, e.g. `'Local'`, `'UTC'`, `'Pacific'`.+ * Supplied already translated; Timestamp never invents or localizes labels.+ */+ label?: string;+}++/** A rendered tooltip line. */+export interface TimestampTooltipLine {+ label?: string;+ value: string;+}++// =============================================================================+// Zone resolution+// =============================================================================++/** Spelling that means "the viewer's own zone" without naming it. */+const LOCAL_ZONE_ALIAS = 'local';++/**+ * Zone identifiers already reported as unknown.+ *+ * Resolution runs once per entry on every render, so without this a single+ * typo on a live timestamp would emit the same warning every tick, forever.+ * One report per bad identifier is enough to act on.+ */+const warnedTimezoneIDs = new Set<string>();++/**+ * Resolves an entry's zone to something safe to hand to `Intl`.+ *+ * Returns `undefined` for the viewer's own zone, which is also what `Intl`+ * treats as "use the host zone" — so the local path never constructs a+ * formatter with an explicit `timeZone` and cannot drift from today's output.+ */+function resolveTimezoneID(timezoneID: string | undefined): string | undefined {+ if (+ timezoneID === undefined ||+ timezoneID.toLowerCase() === LOCAL_ZONE_ALIAS+ ) {+ return undefined;+ }++ // An unrecognized identifier makes every Intl.DateTimeFormat constructor+ // throw a RangeError. Rendering a timestamp must never take down the tree —+ // degrade to the viewer's zone and say so, mirroring how an unparseable+ // `value` is handled in Timestamp.tsx.+ try {+ new Intl.DateTimeFormat(undefined, {timeZone: timezoneID});+ } catch {+ if (!warnedTimezoneIDs.has(timezoneID)) {+ warnedTimezoneIDs.add(timezoneID);+ devWarn(+ 'Timestamp',+ `unknown time zone ${JSON.stringify(timezoneID)} in tooltipEntries. Falling back to the viewer's time zone.`,+ );+ }+ return undefined;+ }++ return timezoneID;+}++/**+ * A stable key for "which zone did the consumer ask for", used to decide+ * whether the tooltip needs zone abbreviations to disambiguate its lines.+ *+ * Deliberately keyed on the *requested* zone, not on the resolved offset: a+ * consumer who asks for two zones gets both labelled even when the viewer+ * happens to be sitting in one of them, so the rendering does not change shape+ * depending on where the reader is. That also keeps this testable under any+ * machine timezone.+ */+function zoneKey(resolved: string | undefined): string {+ return resolved === undefined ? LOCAL_ZONE_ALIAS : resolved.toLowerCase();+}++// =============================================================================+// Zone marking+// =============================================================================++/**+ * Whether a format should carry a zone abbreviation.+ *+ * `'full'` always has one (that is the style). `system_*` never does — those+ * are machine shapes and a trailing "PST" would break anything parsing them,+ * which is also why `isTimezoneShown` has never applied to them.+ *+ * The two human formats that can carry one do so when either the reader has+ * to tell several lines apart, or the line shows a zone the consumer named+ * explicitly. That second case matters even for a lone entry: the tooltip is+ * the `<time>` element's `aria-describedby`, and that element's accessible+ * name is the absolute time in the *viewer's* zone — so an unmarked foreign+ * time is announced directly after a local one with nothing to distinguish+ * them. A line the consumer did not steer stays unmarked, matching how the+ * visible text reads with `isTimezoneShown` off.+ */+function shouldShowZoneName(+ format: TimestampTooltipFormat,+ hasMultipleZones: boolean,+ isNamedZone: boolean,+): boolean {+ if (format === 'full') {+ return true;+ }+ if (format === 'date_time' || format === 'time') {+ return hasMultipleZones || isNamedZone;+ }+ return false;+}++/**+ * Renders one tooltip line per entry, in the order given.+ *+ * Pure: the same `date` and `entries` always produce the same lines for a given+ * host zone and locale.+ */+export function formatTooltipLines(+ date: Date,+ entries: ReadonlyArray<TimestampTooltipEntry>,+): ReadonlyArray<TimestampTooltipLine> {+ const resolved = entries.map(entry => resolveTimezoneID(entry.timezoneID));+ const hasMultipleZones = new Set(resolved.map(zoneKey)).size > 1;++ return entries.map((entry, index) => {+ const format = entry.format ?? 'full';+ const timeZone = resolved[index];++ return {+ ...(entry.label === undefined ? {} : {label: entry.label}),+ value: formatInstant(date, format, {+ timeZone,+ isTimezoneShown: shouldShowZoneName(+ format,+ hasMultipleZones,+ timeZone !== undefined,+ ),+ }),+ };+ });+}diff --git a/packages/core/src/utils/plainDate.ts b/packages/core/src/utils/plainDate.tsindex ab369c0ca7..acdece6372 100644--- a/packages/core/src/utils/plainDate.ts+++ b/packages/core/src/utils/plainDate.ts@@ -88,7 +88,16 @@ export function plainDateAddDays(pd: PlainDate, n: number): PlainDate {return plainDateFromDate(d);}-function getTimeZoneParts(+/**+ * The wall-clock fields an instant reads as in a given zone.+ *+ * A fixed `'en-US'` locale with `hourCycle: 'h23'` keeps the parts numeric and+ * stable whatever locale the viewer has, so callers can assemble machine+ * shapes (`YYYY-MM-DD`, `HH:mm:ss`) from them. Exported for Timestamp, whose+ * `system_*` formats are built from these fields rather than through `Intl`+ * formatting.+ */+export function getTimeZoneParts(instant: number,timezoneID: string,): {