An open source design system that's fully customizable and agent ready
TypeScript
timestamp (#885)
Andrey Godere519b1ccf59b
diff --git a/apps/storybook/stories/Timestamp.stories.tsx b/apps/storybook/stories/Timestamp.stories.tsxnew file mode 100644index 0000000000..e8a2790f18--- /dev/null+++ b/apps/storybook/stories/Timestamp.stories.tsx@@ -0,0 +1,330 @@+import type {Meta, StoryObj} from '@storybook/react';+import {XDSTimestamp} from '@xds/core/Timestamp';+import {XDSText} from '@xds/core/Text';++const meta: Meta<typeof XDSTimestamp> = {+ title: 'Core/XDSTimestamp',+ component: XDSTimestamp,+ tags: ['autodocs'],+ argTypes: {+ format: {+ control: 'select',+ options: [+ 'relative',+ 'auto',+ 'date',+ 'date_time',+ 'time',+ 'system_date',+ 'system_date_time',+ 'system_time',+ ],+ description: 'Display format',+ },+ type: {+ control: 'select',+ options: [+ 'body',+ 'large',+ 'label',+ 'supporting',+ 'code',+ 'display-1',+ 'display-2',+ 'display-3',+ ],+ description: 'Semantic text type (from XDSText)',+ },+ size: {+ control: 'select',+ options: [+ '4xs',+ '3xs',+ '2xs',+ 'xsm',+ 'sm',+ 'base',+ 'lg',+ 'xl',+ '2xl',+ '3xl',+ '4xl',+ ],+ description: 'Font size override',+ },+ color: {+ control: 'select',+ options: [+ 'primary',+ 'secondary',+ 'disabled',+ 'placeholder',+ 'active',+ 'inherit',+ ],+ description: 'Text color',+ },+ weight: {+ control: 'select',+ options: ['normal', 'medium', 'semibold', 'bold'],+ description: 'Font weight',+ },+ isLive: {+ control: 'boolean',+ description: 'Live-update relative time',+ },+ hasTooltip: {+ control: 'boolean',+ description: 'Show tooltip on hover',+ },+ isTimezoneShown: {+ control: 'boolean',+ description: 'Append timezone abbreviation',+ },+ },+};++export default meta;+type Story = StoryObj<typeof XDSTimestamp>;++export const Default: Story = {+ args: {+ value: '2026-03-25T12:00:00Z',+ },+};++export const RelativeFormat: Story = {+ render: () => (+ <div+ style={{+ display: 'flex',+ flexDirection: 'column',+ gap: '8px',+ alignItems: 'flex-start',+ }}>+ <XDSTimestamp value={Date.now() / 1000 - 5} format="relative" />+ <XDSTimestamp value={Date.now() / 1000 - 120} format="relative" />+ <XDSTimestamp value={Date.now() / 1000 - 3600} format="relative" />+ <XDSTimestamp value={Date.now() / 1000 - 86400} format="relative" />+ <XDSTimestamp value={Date.now() / 1000 - 259200} format="relative" />+ <XDSTimestamp value={Date.now() / 1000 - 90 * 86400} format="relative" />+ <XDSTimestamp value={Date.now() / 1000 - 730 * 86400} format="relative" />+ </div>+ ),+};++export const DateFormat: Story = {+ args: {+ value: '2026-02-19T17:00:00Z',+ format: 'date',+ },+};++export const DateTimeFormat: Story = {+ args: {+ value: '2026-02-19T17:00:00Z',+ format: 'date_time',+ },+};++export const DateTimeWithTimezone: Story = {+ args: {+ value: '2026-02-19T17:00:00Z',+ format: 'date_time',+ isTimezoneShown: true,+ },+};++export const TimeFormat: Story = {+ args: {+ value: '2026-02-19T17:00:00Z',+ format: 'time',+ },+};++export const SystemFormats: Story = {+ render: () => (+ <div style={{display: 'flex', flexDirection: 'column', gap: '8px'}}>+ <div>+ <XDSText type="label" color="secondary">+ system_date:{' '}+ </XDSText>+ <XDSTimestamp+ value="2026-02-19T17:00:00Z"+ format="system_date"+ type="code"+ />+ </div>+ <div>+ <XDSText type="label" color="secondary">+ system_date_time:{' '}+ </XDSText>+ <XDSTimestamp+ value="2026-02-19T17:00:00Z"+ format="system_date_time"+ type="code"+ />+ </div>+ <div>+ <XDSText type="label" color="secondary">+ system_time:{' '}+ </XDSText>+ <XDSTimestamp+ value="2026-02-19T17:00:00Z"+ format="system_time"+ type="code"+ />+ </div>+ </div>+ ),+};++export const AllFormats: Story = {+ render: () => {+ const date = '2026-02-19T17:00:00Z';+ return (+ <div style={{display: 'flex', flexDirection: 'column', gap: '8px'}}>+ <div>+ <XDSText type="label" color="secondary">+ relative:{' '}+ </XDSText>+ <XDSTimestamp value={Date.now() / 1000 - 3600} format="relative" />+ </div>+ <div>+ <XDSText type="label" color="secondary">+ date:{' '}+ </XDSText>+ <XDSTimestamp value={date} format="date" />+ </div>+ <div>+ <XDSText type="label" color="secondary">+ date_time:{' '}+ </XDSText>+ <XDSTimestamp value={date} format="date_time" />+ </div>+ <div>+ <XDSText type="label" color="secondary">+ time:{' '}+ </XDSText>+ <XDSTimestamp value={date} format="time" />+ </div>+ <div>+ <XDSText type="label" color="secondary">+ system_date:{' '}+ </XDSText>+ <XDSTimestamp value={date} format="system_date" type="code" />+ </div>+ <div>+ <XDSText type="label" color="secondary">+ system_date_time:{' '}+ </XDSText>+ <XDSTimestamp value={date} format="system_date_time" type="code" />+ </div>+ <div>+ <XDSText type="label" color="secondary">+ system_time:{' '}+ </XDSText>+ <XDSTimestamp value={date} format="system_time" type="code" />+ </div>+ </div>+ );+ },+};++export const LiveUpdating: Story = {+ args: {+ value: Date.now() / 1000 - 5,+ format: 'relative',+ isLive: true,+ },+};++export const TextTypes: Story = {+ render: () => (+ <div style={{display: 'flex', flexDirection: 'column', gap: '8px'}}>+ <XDSTimestamp+ value="2026-02-19T17:00:00Z"+ format="date_time"+ type="supporting"+ />+ <XDSTimestamp+ value="2026-02-19T17:00:00Z"+ format="date_time"+ type="body"+ />+ <XDSTimestamp+ value="2026-02-19T17:00:00Z"+ format="date_time"+ type="large"+ />+ <XDSTimestamp+ value="2026-02-19T17:00:00Z"+ format="date_time"+ type="label"+ weight="semibold"+ />+ </div>+ ),+};++export const Colors: Story = {+ render: () => (+ <div style={{display: 'flex', flexDirection: 'column', gap: '8px'}}>+ <XDSTimestamp+ value="2026-02-19T17:00:00Z"+ format="date_time"+ color="primary"+ />+ <XDSTimestamp+ value="2026-02-19T17:00:00Z"+ format="date_time"+ color="secondary"+ />+ <XDSTimestamp+ value="2026-02-19T17:00:00Z"+ format="date_time"+ color="disabled"+ />+ <XDSTimestamp+ value="2026-02-19T17:00:00Z"+ format="date_time"+ color="active"+ />+ </div>+ ),+};++export const AutoFormat: Story = {+ render: () => (+ <div style={{display: 'flex', flexDirection: 'column', gap: '8px'}}>+ <div>+ <XDSText type="label" color="secondary">+ Recent (relative):{' '}+ </XDSText>+ <XDSTimestamp value={Date.now() / 1000 - 3600} format="auto" />+ </div>+ <div>+ <XDSText type="label" color="secondary">+ Old (date_time):{' '}+ </XDSText>+ <XDSTimestamp value="2025-01-01T12:00:00Z" format="auto" />+ </div>+ </div>+ ),+};++export const FutureDates: Story = {+ render: () => (+ <div+ style={{+ display: 'flex',+ flexDirection: 'column',+ gap: '8px',+ alignItems: 'flex-start',+ }}>+ <XDSTimestamp value={Date.now() / 1000 + 60} format="relative" />+ <XDSTimestamp value={Date.now() / 1000 + 3600} format="relative" />+ <XDSTimestamp value={Date.now() / 1000 + 86400} format="relative" />+ </div>+ ),+};diff --git a/packages/core/package.json b/packages/core/package.jsonindex 43505ab914..6c1920f47a 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -352,6 +352,12 @@"import": "./dist/TimeInput/index.mjs","require": "./dist/TimeInput/index.js"},+ "./Timestamp": {+ "source": "./src/Timestamp/index.ts",+ "types": "./dist/Timestamp/index.d.ts",+ "import": "./dist/Timestamp/index.mjs",+ "require": "./dist/Timestamp/index.js"+ },"./Token": {"source": "./src/Token/index.ts","types": "./dist/Token/index.d.ts",diff --git a/packages/core/src/Timestamp/Timestamp.doc.mjs b/packages/core/src/Timestamp/Timestamp.doc.mjsnew file mode 100644index 0000000000..c791d759df--- /dev/null+++ b/packages/core/src/Timestamp/Timestamp.doc.mjs@@ -0,0 +1,138 @@+/** @type {import('../docs-types').ComponentDoc} */++export const docs = {+ name: 'Timestamp',+ description:+ 'Displays a formatted timestamp as human-readable text with optional tooltip and live updates. Renders via XDSText for consistent typography.',+ props: [+ {+ name: 'value',+ type: 'string | number',+ description:+ 'The date/time to display. Accepts Unix timestamps (seconds) or ISO 8601 strings.',+ required: true,+ },+ {+ name: 'format',+ type: "'relative' | 'auto' | 'date' | 'date_time' | 'time' | 'system_date' | 'system_date_time' | 'system_time'",+ description:+ "Display format. 'relative' shows '2 hours ago', 'date' shows 'Mar 21, 2025', 'date_time' shows 'Mar 21, 2025, 2:51 PM', 'time' shows '2:51 PM', 'system_*' variants use ISO-style formatting, 'auto' switches from relative to date_time based on recency.",+ default: "'auto'",+ },+ {+ name: 'autoThreshold',+ type: 'number',+ description:+ "Threshold in seconds for 'auto' format to switch from relative to date_time.",+ default: '604800',+ },+ {+ name: 'hasTooltip',+ type: 'boolean',+ description:+ 'Whether to show a tooltip with the full date/time on hover when displaying relative time.',+ default: 'true',+ },+ {+ name: 'isTimezoneShown',+ type: 'boolean',+ description:+ 'Whether to append the timezone abbreviation. Applies to date_time, time, system_date_time, and system_time formats.',+ default: 'false',+ },+ {+ name: 'isLive',+ type: 'boolean',+ description:+ 'Whether the relative time should update live (e.g. "2 min ago" → "3 min ago").',+ default: 'false',+ },+ {+ name: 'type',+ type: 'XDSTextType',+ description: 'Semantic text type from XDSText. Determines size, weight, and line-height.',+ default: "'supporting'",+ },+ {+ name: 'size',+ type: 'XDSTextSize',+ description: 'Explicit font size override. Overrides the size from type.',+ },+ {+ name: 'color',+ type: 'XDSTextColor',+ description: 'Text color.',+ default: "'secondary'",+ },+ {+ name: 'weight',+ type: 'XDSTextWeight',+ description: 'Font weight override.',+ },+ ],+ features: [+ "Formats: 'relative', 'date', 'date_time', 'time', 'system_date', 'system_date_time', 'system_time', 'auto'",+ 'Live updates: opt-in timer that adjusts frequency based on age',+ 'Tooltip: shows full date/time on hover for relative timestamps',+ 'Semantic HTML: renders <time> with ISO 8601 datetime attribute',+ 'Typography: delegates to XDSText for consistent sizing and color',+ "System formats: ISO-style dates/times for databases and logs",+ ],+ examples: [+ {+ label: 'Auto format (default)',+ code: '<XDSTimestamp value="2026-03-25T12:00:00Z" />',+ },+ {+ label: 'Relative format',+ code: '<XDSTimestamp value={Date.now() / 1000 - 3600} format="relative" />',+ },+ {+ label: 'Date only',+ code: '<XDSTimestamp value="2026-02-19T17:00:00Z" format="date" />',+ },+ {+ label: 'Date and time',+ code: '<XDSTimestamp value="2026-02-19T17:00:00Z" format="date_time" />',+ },+ {+ label: 'Time only',+ code: '<XDSTimestamp value="2026-02-19T17:00:00Z" format="time" />',+ },+ {+ label: 'System date/time',+ code: '<XDSTimestamp value="2026-02-19T17:00:00Z" format="system_date_time" type="code" />',+ },+ {+ label: 'Live updating',+ code: '<XDSTimestamp value={Date.now() / 1000 - 120} format="relative" isLive />',+ },+ ],+ theming: {+ targets: [+ {className: 'xds-timestamp', visualProps: ['type', 'color']},+ ],+ },+ accessibility: [+ 'Renders as <time datetime="..."> with ISO 8601 datetime attribute for machines.',+ 'Sets aria-label with full absolute time when displaying relative format.',+ 'Tooltip is keyboard accessible via focus.',+ ],+};++/** @type {import('../docs-types').TranslationDoc} */+export const docsDense = {+ description: 'formatted timestamp display with relative/absolute/auto modes via XDSText',+ propDescriptions: {+ value: 'date/time as unix seconds or ISO string',+ format: "display mode: 'relative', 'auto', 'date', 'date_time', 'time', 'system_date', 'system_date_time', 'system_time'",+ autoThreshold: 'seconds threshold for auto relative→date_time switch',+ hasTooltip: 'show full time tooltip on hover (relative mode)',+ isTimezoneShown: 'append timezone abbreviation',+ isLive: 'live-update relative time',+ type: 'XDSText semantic type',+ size: 'font size override',+ color: 'text color',+ weight: 'font weight override',+ },+};diff --git a/packages/core/src/Timestamp/XDSTimestamp.test.tsx b/packages/core/src/Timestamp/XDSTimestamp.test.tsxnew file mode 100644index 0000000000..f16bf43cb0--- /dev/null+++ b/packages/core/src/Timestamp/XDSTimestamp.test.tsx@@ -0,0 +1,265 @@+import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';+import {render, screen, act} from '@testing-library/react';+import {XDSTimestamp} from './XDSTimestamp';++describe('XDSTimestamp', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-03-25T12:00:00Z'));+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('renders a <time> element with ISO datetime attribute', () => {+ render(+ <XDSTimestamp+ value="2026-03-25T10:00:00Z"+ format="date_time"+ data-testid="ts"+ />,+ );+ const el = screen.getByTestId('ts');+ expect(el.tagName).toBe('TIME');+ expect(el.getAttribute('datetime')).toBe('2026-03-25T10:00:00.000Z');+ });++ it('renders relative format for recent times', () => {+ const twoHoursAgo = Date.now() / 1000 - 7200;+ render(<XDSTimestamp value={twoHoursAgo} format="relative" />);+ expect(screen.getByText('2 hours ago')).toBeInTheDocument();+ });++ it('renders "just now" for very recent times', () => {+ const fiveSecondsAgo = Date.now() / 1000 - 5;+ render(<XDSTimestamp value={fiveSecondsAgo} format="relative" />);+ expect(screen.getByText('just now')).toBeInTheDocument();+ });++ it('renders "yesterday" for times ~1 day ago', () => {+ const yesterday = Date.now() / 1000 - 100000;+ render(<XDSTimestamp value={yesterday} format="relative" />);+ expect(screen.getByText('yesterday')).toBeInTheDocument();+ });++ // --- Standard display formats ---++ it('renders date format', () => {+ render(+ <XDSTimestamp+ value="2026-02-19T17:00:00Z"+ format="date"+ data-testid="ts"+ />,+ );+ const el = screen.getByTestId('ts');+ expect(el.textContent).toContain('2026');+ // Should not contain time+ expect(el.textContent).not.toContain(':');+ });++ it('renders date_time format', () => {+ render(+ <XDSTimestamp+ value="2026-02-19T17:00:00Z"+ format="date_time"+ data-testid="ts"+ />,+ );+ const el = screen.getByTestId('ts');+ expect(el.textContent).toContain('2026');+ // Should contain a colon for the time portion+ expect(el.textContent).toContain(':');+ });++ it('renders time format', () => {+ render(+ <XDSTimestamp+ value="2026-02-19T17:00:00Z"+ format="time"+ data-testid="ts"+ />,+ );+ const el = screen.getByTestId('ts');+ // Should contain time but not year+ expect(el.textContent).toContain(':');+ expect(el.textContent).not.toContain('2026');+ });++ // --- System formats ---++ it('renders system_date format', () => {+ render(+ <XDSTimestamp+ value="2026-02-19T17:00:00Z"+ format="system_date"+ data-testid="ts"+ />,+ );+ const el = screen.getByTestId('ts');+ expect(el.textContent).toMatch(/2026-02-\d{2}/);+ });++ it('renders system_date_time format', () => {+ render(+ <XDSTimestamp+ value="2026-02-19T17:00:00Z"+ format="system_date_time"+ data-testid="ts"+ />,+ );+ const el = screen.getByTestId('ts');+ expect(el.textContent).toMatch(/2026-02-\d{2} \d{2}:\d{2}:\d{2}/);+ });++ it('renders system_time format', () => {+ render(+ <XDSTimestamp+ value="2026-02-19T17:00:00Z"+ format="system_time"+ data-testid="ts"+ />,+ );+ const el = screen.getByTestId('ts');+ expect(el.textContent).toMatch(/\d{2}:\d{2}:\d{2}/);+ });++ // --- Auto format ---++ it('auto format uses relative for recent times', () => {+ const oneHourAgo = Date.now() / 1000 - 3600;+ render(<XDSTimestamp value={oneHourAgo} format="auto" />);+ expect(screen.getByText('1 hour ago')).toBeInTheDocument();+ });++ it('auto format uses date_time for old times', () => {+ const oldDate = '2026-01-01T12:00:00Z';+ render(<XDSTimestamp value={oldDate} format="auto" data-testid="ts" />);+ const el = screen.getByTestId('ts');+ expect(el.textContent).toContain('2026');+ expect(el.textContent).not.toContain('ago');+ });++ // --- Accessibility ---++ it('sets aria-label with full absolute time in relative mode', () => {+ const oneHourAgo = Date.now() / 1000 - 3600;+ render(+ <XDSTimestamp+ value={oneHourAgo}+ format="relative"+ hasTooltip={false}+ data-testid="ts"+ />,+ );+ const el = screen.getByTestId('ts');+ expect(el.getAttribute('aria-label')).toBeTruthy();+ expect(el.getAttribute('aria-label')).toContain('2026');+ });++ it('does not set aria-label in non-relative mode', () => {+ render(+ <XDSTimestamp+ value="2026-02-19T17:00:00Z"+ format="date_time"+ data-testid="ts"+ />,+ );+ const el = screen.getByTestId('ts');+ expect(el.getAttribute('aria-label')).toBeNull();+ });++ // --- Input handling ---++ it('accepts Unix timestamp in seconds', () => {+ render(<XDSTimestamp value={1740000000} format="date" data-testid="ts" />);+ const el = screen.getByTestId('ts');+ expect(el.getAttribute('datetime')).toBeTruthy();+ });++ it('accepts ISO string', () => {+ render(+ <XDSTimestamp+ value="2026-03-25T10:00:00Z"+ format="date_time"+ data-testid="ts"+ />,+ );+ const el = screen.getByTestId('ts');+ expect(el.getAttribute('datetime')).toBe('2026-03-25T10:00:00.000Z');+ });++ // --- Live updates ---++ it('live updates relative time', () => {+ const now = Date.now() / 1000;+ render(<XDSTimestamp value={now - 5} format="relative" isLive />);+ expect(screen.getByText('just now')).toBeInTheDocument();++ act(() => {+ vi.advanceTimersByTime(30_000);+ });+ expect(screen.getByText('35 seconds ago')).toBeInTheDocument();+ });++ // --- Ref ---++ it('forwards ref', () => {+ const ref = {current: null as HTMLTimeElement | null};+ render(+ <XDSTimestamp+ ref={ref}+ value="2026-03-25T10:00:00Z"+ format="date_time"+ />,+ );+ expect(ref.current).toBeInstanceOf(HTMLTimeElement);+ });++ // --- Test ID ---++ it('spreads data-testid', () => {+ render(+ <XDSTimestamp+ value="2026-03-25T10:00:00Z"+ format="date_time"+ data-testid="my-timestamp"+ />,+ );+ expect(screen.getByTestId('my-timestamp')).toBeInTheDocument();+ });++ // --- Future dates ---++ it('handles future dates in relative mode', () => {+ const oneHourFromNow = Date.now() / 1000 + 3600;+ render(<XDSTimestamp value={oneHourFromNow} format="relative" />);+ expect(screen.getByText('in 1 hour')).toBeInTheDocument();+ });++ // --- Long-ago relative ---++ it('renders months ago for dates older than 30 days', () => {+ const threeMonthsAgo = Date.now() / 1000 - 90 * 86400;+ render(<XDSTimestamp value={threeMonthsAgo} format="relative" />);+ expect(screen.getByText('3 months ago')).toBeInTheDocument();+ });++ it('renders years ago for dates older than 365 days', () => {+ const twoYearsAgo = Date.now() / 1000 - 730 * 86400;+ render(<XDSTimestamp value={twoYearsAgo} format="relative" />);+ expect(screen.getByText('2 years ago')).toBeInTheDocument();+ });++ // --- Auto threshold ---++ it('respects custom autoThreshold', () => {+ const twoHoursAgo = Date.now() / 1000 - 7200;+ render(+ <XDSTimestamp value={twoHoursAgo} format="auto" autoThreshold={3600} />,+ );+ const el = screen.getByRole('time');+ expect(el.textContent).not.toContain('ago');+ });+});diff --git a/packages/core/src/Timestamp/XDSTimestamp.tsx b/packages/core/src/Timestamp/XDSTimestamp.tsxnew file mode 100644index 0000000000..deb31c1713--- /dev/null+++ b/packages/core/src/Timestamp/XDSTimestamp.tsx@@ -0,0 +1,425 @@+'use client';++/**+ * @file XDSTimestamp.tsx+ * @input Uses React, Intl.DateTimeFormat, XDSText+ * @output Exports XDSTimestamp component and related types+ * @position Core implementation; renders formatted timestamps+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/Timestamp/Timestamp.doc.mjs+ * - /packages/core/src/Timestamp/XDSTimestamp.test.tsx+ * - /packages/core/src/Timestamp/index.ts+ * - /apps/storybook/stories/Timestamp.stories.tsx+ */++import {useEffect, useRef, useState, lazy, Suspense} from 'react';+import * as stylex from '@stylexjs/stylex';+import {XDSText} from '../Text';+import type {+ XDSTextType,+ XDSTextSize,+ XDSTextColor,+ XDSTextWeight,+} from '../theme/types';+import {xdsClassName, mergeProps} from '../utils';+import type {StyleXStyles} from '@stylexjs/stylex';++const LazyXDSTooltip = lazy(() =>+ import('../Tooltip/XDSTooltip').then(mod => ({default: mod.XDSTooltip})),+);++// =============================================================================+// Types+// =============================================================================++export type XDSTimestampFormat =+ | 'relative'+ | 'auto'+ | 'date'+ | 'date_time'+ | 'time'+ | 'system_date'+ | 'system_date_time'+ | 'system_time';++export interface XDSTimestampProps {+ /** Ref forwarded to the root element. */+ ref?: React.Ref<HTMLTimeElement>;+ /** The date/time to display. Accepts Unix timestamps (seconds) or ISO 8601 strings. */+ value: string | number;+ /**+ * Display format.+ * - `'relative'`: "2 hours ago", "yesterday", "just now"+ * - `'auto'`: Relative for recent times, `date_time` for older+ * - `'date'`: "Mar 21, 2025"+ * - `'date_time'`: "Mar 21, 2025, 2:51 PM"+ * - `'time'`: "2:51 PM"+ * - `'system_date'`: "2025-03-21"+ * - `'system_date_time'`: "2025-03-21 14:51:53"+ * - `'system_time'`: "14:51:53"+ * @default 'auto'+ */+ format?: XDSTimestampFormat;+ /**+ * Threshold in seconds for 'auto' format to switch from relative to date_time.+ * @default 604800 (7 days)+ */+ autoThreshold?: number;+ /**+ * Whether to show a tooltip with the full date/time on hover.+ * @default true+ */+ hasTooltip?: boolean;+ /**+ * Whether to append the timezone abbreviation after the timestamp.+ * Applies to date_time, time, system_date_time, and system_time formats.+ * @default false+ */+ isTimezoneShown?: boolean;+ /**+ * Whether the relative time should update live.+ * @default false+ */+ isLive?: boolean;+ /**+ * Semantic text type. Determines size, weight, and line-height from theme.+ * @default 'supporting'+ */+ type?: XDSTextType;+ /**+ * Explicit font size override. Overrides the size from `type`.+ */+ size?: XDSTextSize;+ /**+ * Text color.+ * @default 'secondary'+ */+ color?: XDSTextColor;+ /**+ * Font weight override.+ */+ weight?: XDSTextWeight;+ /**+ * StyleX styles created via `stylex.create()`.+ */+ xstyle?: StyleXStyles;+ /**+ * CSS class name(s) appended to the root element.+ */+ className?: string;+ /**+ * Inline styles to apply to the root element.+ */+ style?: React.CSSProperties;+ /** Test ID for testing frameworks. */+ 'data-testid'?: string;+}++// =============================================================================+// Styles+// =============================================================================++const styles = stylex.create({+ time: {+ display: 'inline',+ fontFamily: 'inherit',+ fontStyle: 'normal',+ // Reset <time> element defaults+ fontSize: 'inherit',+ lineHeight: 'inherit',+ color: 'inherit',+ fontWeight: 'inherit',+ },+});++// =============================================================================+// Formatting utilities+// =============================================================================++const SECOND = 1;+const MINUTE = 60;+const HOUR = 3600;+const DAY = 86400;+const WEEK = 7 * DAY;+const MONTH = 30 * DAY;+const YEAR = 365 * DAY;++/** Default auto threshold: 7 days in seconds */+const DEFAULT_AUTO_THRESHOLD = 7 * DAY;++function parseValue(value: string | number): Date {+ if (typeof value === 'number') {+ // Heuristic: if the number is less than 1e12, treat as seconds; otherwise ms.+ // Unix timestamps in seconds are < 1e12 until ~2286.+ return new Date(value < 1e12 ? value * 1000 : value);+ }+ return new Date(value);+}++function getRelativeTimeString(date: Date, now: Date): string {+ const diffSeconds = Math.round((now.getTime() - date.getTime()) / 1000);++ if (diffSeconds < 0) {+ // Future dates+ const absDiff = Math.abs(diffSeconds);+ if (absDiff < MINUTE) return 'in a few seconds';+ if (absDiff < HOUR) {+ const mins = Math.round(absDiff / MINUTE);+ return `in ${mins} ${mins === 1 ? 'minute' : 'minutes'}`;+ }+ if (absDiff < DAY) {+ const hours = Math.round(absDiff / HOUR);+ return `in ${hours} ${hours === 1 ? 'hour' : 'hours'}`;+ }+ if (absDiff < MONTH) {+ const days = Math.round(absDiff / DAY);+ return `in ${days} ${days === 1 ? 'day' : 'days'}`;+ }+ if (absDiff < YEAR) {+ const months = Math.round(absDiff / MONTH);+ return `in ${months} ${months === 1 ? 'month' : 'months'}`;+ }+ const years = Math.round(absDiff / YEAR);+ return `in ${years} ${years === 1 ? 'year' : 'years'}`;+ }++ if (diffSeconds < 10) return 'just now';+ if (diffSeconds < MINUTE) return `${diffSeconds} seconds ago`;+ if (diffSeconds < HOUR) {+ const mins = Math.round(diffSeconds / MINUTE);+ return `${mins} ${mins === 1 ? 'minute' : 'minutes'} ago`;+ }+ if (diffSeconds < DAY) {+ const hours = Math.round(diffSeconds / HOUR);+ return `${hours} ${hours === 1 ? 'hour' : 'hours'} ago`;+ }+ if (diffSeconds < 2 * DAY) return 'yesterday';+ if (diffSeconds < MONTH) {+ const days = Math.round(diffSeconds / DAY);+ return `${days} days ago`;+ }+ if (diffSeconds < YEAR) {+ const months = Math.round(diffSeconds / MONTH);+ return `${months} ${months === 1 ? 'month' : 'months'} ago`;+ }+ const years = Math.round(diffSeconds / YEAR);+ return `${years} ${years === 1 ? 'year' : 'years'} ago`;+}++function pad(n: number): string {+ return String(n).padStart(2, '0');+}++function formatTimestamp(+ date: Date,+ format: Exclude<XDSTimestampFormat, 'relative' | 'auto'>,+ isTimezoneShown: boolean,+): string {+ switch (format) {+ case 'date':+ return new Intl.DateTimeFormat(undefined, {+ year: 'numeric',+ month: 'short',+ day: 'numeric',+ }).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);+ if (absDiff < MINUTE) return 1000; // every second+ if (absDiff < HOUR) return 30_000; // every 30s+ if (absDiff < DAY) return 60_000; // every minute+ return 300_000; // every 5 minutes+}++/** Whether a format is non-relative (i.e. shows a fixed date/time). */+function isAbsoluteFormat(+ format: XDSTimestampFormat,+): format is Exclude<XDSTimestampFormat, 'relative' | 'auto'> {+ return format !== 'relative' && format !== 'auto';+}++// =============================================================================+// Component+// =============================================================================++/**+ * Displays a formatted timestamp as human-readable text.+ *+ * Renders a semantic `<time>` element with an ISO 8601 `datetime` attribute,+ * styled via XDSText. Supports relative ("2 hours ago"), multiple absolute+ * formats, and auto formatting. Optionally shows a tooltip with the full+ * absolute time and can update live.+ *+ * @example+ * ```+ * <XDSTimestamp value="2026-02-19T17:00:00Z" />+ * <XDSTimestamp value={1740000000} format="date" />+ * <XDSTimestamp value={date} format="auto" isLive />+ * <XDSTimestamp value={event.timestamp} format="system_date_time" />+ * ```+ */+export function XDSTimestamp({+ value,+ format = 'auto',+ autoThreshold = DEFAULT_AUTO_THRESHOLD,+ hasTooltip = true,+ isTimezoneShown = false,+ isLive = false,+ type = 'supporting',+ size,+ color = 'secondary',+ weight,+ xstyle,+ className,+ style,+ ref,+ 'data-testid': testId,+}: XDSTimestampProps) {+ const timeRef = useRef<HTMLTimeElement>(null);+ const [now, setNow] = useState(() => new Date());++ const date = parseValue(value);+ const isoString = date.toISOString();++ // Determine effective format+ const diffSeconds = Math.round((now.getTime() - date.getTime()) / 1000);+ const effectiveFormat: XDSTimestampFormat =+ format === 'auto'+ ? Math.abs(diffSeconds) <= autoThreshold+ ? 'relative'+ : 'date_time'+ : format;++ // Format the display text+ const displayText =+ effectiveFormat === 'relative'+ ? getRelativeTimeString(date, now)+ : isAbsoluteFormat(effectiveFormat)+ ? formatTimestamp(date, effectiveFormat, isTimezoneShown)+ : '';++ // Full absolute text for tooltip and aria-label+ const fullAbsoluteText = getFullAbsoluteString(date);++ // Live updates+ useEffect(() => {+ if (!isLive || effectiveFormat !== 'relative') return;++ const interval = getLiveInterval(diffSeconds);+ const timer = setInterval(() => {+ setNow(new Date());+ }, interval);++ return () => clearInterval(timer);+ }, [isLive, effectiveFormat, diffSeconds]);++ // Tooltip needs the ref+ const combinedRef = (el: HTMLTimeElement | null) => {+ (timeRef as React.MutableRefObject<HTMLTimeElement | null>).current = el;+ if (typeof ref === 'function') {+ ref(el);+ } else if (ref) {+ (ref as React.MutableRefObject<HTMLTimeElement | null>).current = el;+ }+ };++ const showTooltip = hasTooltip && effectiveFormat === 'relative';++ const timeElement = (+ <XDSText+ type={type}+ size={size}+ color={color}+ weight={weight}+ xstyle={xstyle}+ className={className}+ style={style}>+ <time+ ref={combinedRef}+ dateTime={isoString}+ aria-label={+ effectiveFormat === 'relative' ? fullAbsoluteText : undefined+ }+ data-testid={testId}+ {...stylex.props(styles.time)}>+ {displayText}+ </time>+ </XDSText>+ );++ if (showTooltip) {+ return (+ <>+ {timeElement}+ <Suspense fallback={null}>+ <LazyXDSTooltip+ anchorRef={timeRef}+ content={fullAbsoluteText}+ placement="above"+ />+ </Suspense>+ </>+ );+ }++ return timeElement;+}++XDSTimestamp.displayName = 'XDSTimestamp';diff --git a/packages/core/src/Timestamp/index.ts b/packages/core/src/Timestamp/index.tsnew file mode 100644index 0000000000..c3b8fdd956--- /dev/null+++ b/packages/core/src/Timestamp/index.ts@@ -0,0 +1,13 @@+'use client';++/**+ * @file index.ts+ * @input Timestamp component+ * @output Exports all Timestamp module public API+ * @position Entry point for Timestamp module+ *+ * SYNC: When adding new Timestamp files, update exports here+ */++export {XDSTimestamp} from './XDSTimestamp';+export type {XDSTimestampProps, XDSTimestampFormat} from './XDSTimestamp';diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 60c74d50a1..42e3147803 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -100,6 +100,9 @@ export * from './StatusDot';// Spinner loading indicatorexport * from './Spinner';+// Timestamp display+export * from './Timestamp';+// Overflow listexport * from './OverflowList';