Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/relative-time-compact-absolute.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@primer/react': minor
---

RelativeTime: Add `absoluteFormat="compact"` to shorten absolute timestamps without changing when they appear.
6 changes: 3 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion packages/react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@
},
"dependencies": {
"@github/mini-throttle": "^2.1.1",
"@github/relative-time-element": "^5.0.0",
"@github/relative-time-element": "^5.4.0",
"@lit-labs/react": "1.2.1",
"@oddbird/popover-polyfill": "^0.7.3",
"@primer/behaviors": "^1.10.3",
Expand Down
9 changes: 9 additions & 0 deletions packages/react/src/RelativeTime/RelativeTime.docs.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
},
{
"id": "components-relativetime-features--count-down-timer"
},
{
"id": "components-relativetime-features--compact-absolute-format"
}
],
"importPath": "@primer/react",
Expand All @@ -38,6 +41,12 @@
"defaultValue": "'auto'",
"description": "The format with which to display the time"
},
{
"name": "absoluteFormat",
"type": "'compact'",
"defaultValue": "undefined",
"description": "Controls presentation when absolute output is selected. `compact` shows localized today with 12-hour time, or a localized date with its year and no time. It omits the visible time zone and overrides `prefix`, `formatStyle`, and individual date/time display fields. Locale and display time zone still apply. It does not force absolute output or change the full timestamp title. Omitting the prop preserves existing behavior."
},
{
"name": "tense",
"type": "'auto' | 'past' | 'future'",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,4 +149,26 @@ export const CountDownTimer: StoryFn = args => {
CountDownTimer.args = {date: new Date('2038-01-19T03:14:08Z'), format: 'elapsed', day: '', month: ''}
CountDownTimer.argTypes = {date: {control: false}, format: {control: false}}

export const CompactAbsoluteFormat: StoryFn = () => {
const today = new Date()

return (
<dl>
<dt>Compact today</dt>
<dd>
<RelativeTime date={today} format="datetime" absoluteFormat="compact" />
</dd>
<dt>Compact on another day</dt>
<dd>
<RelativeTime datetime="2020-01-01T00:00:00Z" format="datetime" absoluteFormat="compact" />
</dd>
<dt>Standard absolute time today</dt>
<dd>
<RelativeTime date={today} format="datetime" hour="numeric" minute="2-digit" timeZoneName="short" />
</dd>
</dl>
)
}
CompactAbsoluteFormat.parameters = {controls: {disable: true}}

export default meta
161 changes: 128 additions & 33 deletions packages/react/src/RelativeTime/RelativeTime.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {hydrateRoot, type Root} from 'react-dom/client'
import {renderToString} from 'react-dom/server'
import {describe, expect, it, vi} from 'vitest'
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'
import RelativeTime from '.'
import {act, render} from '@testing-library/react'
import {implementsClassName} from '../utils/testing'
Expand Down Expand Up @@ -31,47 +31,54 @@ describe('RelativeTime', () => {
expect(container.textContent).toEqual('Mar 7, 2024')
})

it('renders children if passed', () => {
it.each([undefined, 'compact'] as const)('renders children if passed (absoluteFormat: %s)', absoluteFormat => {
const date = new Date('2024-03-07T12:22:48.123Z')
const {container} = render(<RelativeTime date={date}>server rendered date</RelativeTime>)
const {container} = render(
<RelativeTime date={date} absoluteFormat={absoluteFormat}>
server rendered date
</RelativeTime>,
)
expect(container.textContent).toEqual('server rendered date')
})

it('hydrates the fallback without errors when server and client time zones differ', async () => {
const date = new Date('2024-03-07T00:30:00.000Z')
const relativeTime = <RelativeTime date={date} />
const toLocaleDateStringSpy = vi.spyOn(Date.prototype, 'toLocaleDateString').mockReturnValue('Mar 7, 2024')
const container = document.createElement('div')
container.innerHTML = renderToString(relativeTime)
document.body.appendChild(container)
it.each([undefined, 'compact'] as const)(
'hydrates the fallback without errors when server and client time zones differ (absoluteFormat: %s)',
async absoluteFormat => {
const date = new Date('2024-03-07T00:30:00.000Z')
const relativeTime = <RelativeTime date={date} absoluteFormat={absoluteFormat} />
const toLocaleDateStringSpy = vi.spyOn(Date.prototype, 'toLocaleDateString').mockReturnValue('Mar 7, 2024')
const container = document.createElement('div')
container.innerHTML = renderToString(relativeTime)
document.body.appendChild(container)

toLocaleDateStringSpy.mockImplementation((_locales, options) =>
options?.timeZone === 'UTC' ? 'Mar 7, 2024' : 'Mar 6, 2024',
)
toLocaleDateStringSpy.mockImplementation((_locales, options) =>
options?.timeZone === 'UTC' ? 'Mar 7, 2024' : 'Mar 6, 2024',
)

const recoverableErrors: unknown[] = []
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
let root: Root | undefined
const recoverableErrors: unknown[] = []
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
let root: Root | undefined

try {
expect(container.firstChild).toHaveTextContent('Mar 7, 2024')
try {
expect(container.firstChild).toHaveTextContent('Mar 7, 2024')

await act(async () => {
root = hydrateRoot(container, relativeTime, {
onRecoverableError: error => recoverableErrors.push(error),
await act(async () => {
root = hydrateRoot(container, relativeTime, {
onRecoverableError: error => recoverableErrors.push(error),
})
})
})

expect(recoverableErrors).toEqual([])
expect(consoleErrorSpy).not.toHaveBeenCalled()
expect(container.firstChild).toHaveTextContent('Mar 7, 2024')
} finally {
toLocaleDateStringSpy.mockRestore()
consoleErrorSpy.mockRestore()
await act(async () => root?.unmount())
container.remove()
}
})

expect(recoverableErrors).toEqual([])
expect(consoleErrorSpy).not.toHaveBeenCalled()
expect(container.firstChild).toHaveTextContent('Mar 7, 2024')
} finally {
toLocaleDateStringSpy.mockRestore()
consoleErrorSpy.mockRestore()
await act(async () => root?.unmount())
container.remove()
}
},
)

it('does not render no-title attribute by default', () => {
const date = new Date('2024-03-07T12:22:48.123Z')
Expand All @@ -84,4 +91,92 @@ describe('RelativeTime', () => {
const {container} = render(<RelativeTime date={date} noTitle={true} />)
expect(container.firstChild).toHaveAttribute('no-title')
})

describe('compact absolute output', () => {
const date = new Date('2026-11-03T15:04:00.000Z')

beforeEach(() => {
vi.useFakeTimers({toFake: ['Date']})
vi.setSystemTime(new Date('2026-11-03T16:04:00.000Z'))
})

afterEach(() => {
vi.useRealTimers()
})

it('updates and restores absolute text without changing the datetime or full title', async () => {
const props = {
date,
format: 'datetime',
lang: 'en-US',
'time-zone': 'UTC',
'hour-cycle': 'h23',
prefix: 'Uploaded:',
hour: 'numeric',
minute: '2-digit',
timeZoneName: 'short',
} as const
const {container, rerender} = render(<RelativeTime {...props} />)
const element = container.querySelector('relative-time')
const displayedText = () => element?.shadowRoot?.textContent

await expect.poll(displayedText).toContain('Uploaded:')
const standardText = displayedText()
const fullTitle = element?.getAttribute('title')
expect(fullTitle).toContain('15:04 UTC')

rerender(<RelativeTime {...props} absoluteFormat="compact" />)
await expect.poll(displayedText).toBe('today at 3:04 PM')
expect(element).toHaveAttribute('datetime', date.toISOString())
expect(element).toHaveAttribute('title', fullTitle)

rerender(<RelativeTime {...props} />)
await expect.poll(displayedText).toBe(standardText)
})

it.each([
{name: 'a custom title', title: 'Uploaded earlier', noTitle: false},
{name: 'noTitle', title: undefined, noTitle: true},
])('renders a compact non-today datetime with $name when absolute time is preferred', async ({title, noTitle}) => {
const datetime = '2026-11-02T15:04:00.000Z'
const preference = 'data-prefers-absolute-time'
const previousPreference = document.body.getAttribute(preference)
document.body.setAttribute(preference, 'true')

try {
const {container} = render(
<RelativeTime
datetime={datetime}
format="relative"
lang="en-US"
time-zone="UTC"
absoluteFormat="compact"
title={title}
noTitle={noTitle}
/>,
)
const element = container.querySelector('relative-time')

await expect.poll(() => element?.shadowRoot?.textContent).toBe('Nov 2, 2026')
expect(element).toHaveAttribute('datetime', datetime)
expect(element?.getAttribute('title')).toBe(title ?? null)
} finally {
if (previousPreference === null) document.body.removeAttribute(preference)
else document.body.setAttribute(preference, previousPreference)
}
})

it.each([
{format: 'relative', text: '1 hour ago'},
{format: 'duration', text: '1 hour'},
{format: 'micro', text: '1h'},
] as const)('does not force absolute output in $format mode', async ({format, text}) => {
const {container} = render(
<RelativeTime date={date} format={format} lang="en-US" time-zone="UTC" absoluteFormat="compact" />,
)
const element = container.querySelector('relative-time')

await expect.poll(() => element?.shadowRoot?.textContent).toBe(text)
})
})
})
10 changes: 8 additions & 2 deletions packages/react/src/RelativeTime/RelativeTime.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,16 @@ const localeOptions: Intl.DateTimeFormatOptions = {
year: 'numeric',
timeZone: 'UTC',
} satisfies Intl.DateTimeFormatOptions
function RelativeTime({date, datetime, children, noTitle, ...props}: RelativeTimeProps) {
function RelativeTime({date, datetime, children, noTitle, absoluteFormat, ...props}: RelativeTimeProps) {
if (datetime) date = new Date(datetime)
return (
<RelativeTimeComponent {...props} date={date} no-title={noTitle ? '' : undefined} data-component="RelativeTime">
<RelativeTimeComponent
{...props}
date={date}
absoluteFormat={absoluteFormat}
no-title={noTitle ? '' : undefined}
data-component="RelativeTime"
>
{children || date?.toLocaleDateString('en', localeOptions) || ''}
</RelativeTimeComponent>
)
Expand Down
Loading