diff --git a/README.md b/README.md index 0cb50fe..5827bd1 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,7 @@ So, a relative date phrase is used for up to a month and then the actual date is | :------------- | :--------------- | :------------------------------------------------------------------------------------------ | :------------------------------- | | `datetime` | `datetime` | `string` | - | | `format` | `format` | `'datetime'\|'relative'\|'duration'` | `'auto'` | +| `absoluteFormat` | `absolute-format` | `'compact'\|undefined` | `undefined` | | `date` | - | `Date \| null` | - | | `tense` | `tense` | `'auto'\|'past'\|'future'` | `'auto'` | | `precision` | `precision` | `'year'\|'month'\|'day'\|'hour'\|'minute'\|'second'` | `'second'` | @@ -188,6 +189,23 @@ Code that uses `format=micro` should consider migrating to `format=relative` (pe | Dec 15 2022 | 21 minutes ago | 21 minutes, 30 seconds | 21m | 21m 30s | | Dec 15 2022 | 37 seconds ago | 37 seconds | 1m | 37s | +##### absolute-format (`'compact'`, default: unset) + +Set `absolute-format="compact"` to shorten the visible text when the element displays an absolute timestamp. It applies to explicit `format="datetime"`, dates outside the applicable `threshold`, and absolute output selected by `data-prefers-absolute-time`. It does not force absolute output or change relative and duration text. + +```html + + Nov 2, 2026 + +``` + +- **Today** in the effective display time zone: a localized word for today and a 12-hour time, such as `today at 3:04 PM`. The element uses the locale's date/time connector when it can identify one safely. For Japanese and Chinese locale families, or when the connector is ambiguous, it joins the localized today and time with a space instead. +- **Any other calendar day**: an abbreviated month, numeric day, and full numeric year in the locale's order, such as `Nov 2, 2026`. The year is included even in the current year, and the time is omitted. + +Compact text never shows a time zone name. It honors `lang` and `time-zone` but overrides `prefix`, `format-style`, `second`, `minute`, `hour`, `weekday`, `day`, `month`, `year`, `time-zone-name`, and `hour-cycle` for visible absolute text only. It leaves `datetime`, full title formatting (including the usual `hour-cycle`), custom titles, and `no-title` unchanged. + +The `absoluteFormat` property reflects the attribute and is typed as `AbsoluteFormat | undefined`, where `AbsoluteFormat` is `'compact'`. Omit the attribute, remove it, or set `absoluteFormat` to `undefined` to use the existing presentation. Empty and unrecognized attribute values also use the existing presentation. + ##### tense (`'auto'|'past'|'future'`, default: `auto`) If `format` is `'datetime'` then this value will be ignored. diff --git a/src/relative-time-element.ts b/src/relative-time-element.ts index e7c9d47..2c0e44c 100644 --- a/src/relative-time-element.ts +++ b/src/relative-time-element.ts @@ -18,6 +18,7 @@ export type DeprecatedFormat = 'auto' | 'micro' | 'elapsed' export type ResolvedFormat = 'duration' | 'relative' | 'datetime' export type Format = DeprecatedFormat | ResolvedFormat export type FormatStyle = 'long' | 'short' | 'narrow' +export type AbsoluteFormat = 'compact' export type Tense = 'auto' | 'past' | 'future' const emptyDuration = new Duration() @@ -35,7 +36,10 @@ export class RelativeTimeUpdatedEvent extends Event { } } -function getUnitFactor(el: RelativeTimeElement): number { +// Compact text changes at the day boundary. Text from a threshold can also turn relative. +type CompactAbsolute = false | 'day' | 'threshold' + +function getUnitFactor(el: RelativeTimeElement, compactAbsolute: CompactAbsolute): number { const date = el.date if (!date) return Infinity const now = Date.now() @@ -53,8 +57,11 @@ function getUnitFactor(el: RelativeTimeElement): number { factor = 1000 } else if (ms < 60 * 60 * 1000) { factor = 60 * 1000 - } else { - // Day rounding follows the calendar, so labels like "yesterday" change at midnight + } + if (compactAbsolute === 'day' || (compactAbsolute && date.getTime() <= now)) { + factor = msUntilNextDay(now, el.timeZone) + } else if (compactAbsolute || ms >= 60 * 60 * 1000) { + // Calendar labels change at the day boundary, even for recent compact timestamps. factor = Math.min(factor, msUntilNextDay(now, el.timeZone)) } const threshold = getExplicitThreshold(el) @@ -86,6 +93,65 @@ function getExplicitThreshold(el: RelativeTimeElement): string | null { return threshold && isDuration(threshold) ? threshold : null } +function getAffixes(formatter: Intl.DateTimeFormat, date: Date): readonly [string, string] { + const parts = formatter.formatToParts(date) + const first = parts[0] + const last = parts[parts.length - 1] + return [first?.type === 'literal' ? first.value : '', last?.type === 'literal' ? last.value : ''] +} + +function stripAffixes(text: string, start: string, end: string): string | undefined { + if (text.startsWith(start) && text.endsWith(end) && start.length + end.length <= text.length) { + return text.slice(start.length, text.length - end.length) + } +} + +function formatCompactToday(date: Date, locale: string, timeZone: string | undefined): string { + const options = {timeZone, hourCycle: 'h12'} as const + const today = relativeTimeFormat(locale, {numeric: 'auto'}).format(0, 'day') + const time = dateTimeFormat(locale, {...options, hour: 'numeric', minute: '2-digit'}).format(date) + const fallback = `${today} ${time}` + const pattern = dateTimeFormat(locale, {...options, dateStyle: 'long', timeStyle: 'short'}) + if (/^(ja|zh|yue)(-|$)/.test(pattern.resolvedOptions().locale)) return fallback + + const parts = pattern.formatToParts(date) + if (parts.some(part => part.type === 'unknown')) return fallback + const fields = parts.flatMap(({type}, index) => + type === 'literal' ? [] : [{index, isTime: type === 'hour' || type === 'minute' || type === 'dayPeriod'}], + ) + if (!fields.length) return fallback + + // Find two contiguous groups of fields (date and time), in either order. + const timeFirst = fields[0].isTime + const boundary = fields.findIndex(field => field.isTime !== timeFirst) + if (boundary < 1 || fields.slice(boundary).some(field => field.isTime === timeFirst)) return fallback + + // Standalone fields can have their own affixes, e.g. the Korean day suffix "일". + // Remove only matching affixes, leaving the combined pattern's connector literals intact. + const dateAffixes = getAffixes(dateTimeFormat(locale, {...options, dateStyle: 'long'}), date) + const timeAffixes = getAffixes(dateTimeFormat(locale, {...options, timeStyle: 'short'}), date) + const [first, second] = timeFirst ? [timeAffixes, dateAffixes] : [dateAffixes, timeAffixes] + const literals = (start: number, end?: number) => + parts + .slice(start, end) + .map(part => part.value) + .join('') + const prefix = stripAffixes(literals(0, fields[0].index), '', first[0]) + const separator = stripAffixes(literals(fields[boundary - 1].index + 1, fields[boundary].index), first[1], second[0]) + const suffix = stripAffixes(literals(fields[fields.length - 1].index + 1), second[1], '') + // An unmatched letter or number attached to a field may be part of that field, not a connector. + if ( + prefix === undefined || + !separator || + suffix === undefined || + /^[\p{L}\p{M}\p{N}]|[\p{L}\p{M}\p{N}]$/u.test(separator) + ) { + return fallback + } + + return timeFirst ? `${prefix}${time}${separator}${today}${suffix}` : `${prefix}${today}${separator}${time}${suffix}` +} + // Determine whether the user has a 12 (vs. 24) hour cycle preference via the // browser's resolved DateTimeFormat options. The result is environment-constant, // so it is computed once and memoized. @@ -111,20 +177,21 @@ if (typeof window !== 'undefined' && typeof window.addEventListener === 'functio } const dateObserver = new (class { - elements: Set = new Set() + elements = new Map() time = Infinity updating = false - observe(element: RelativeTimeElement) { - this.elements.add(element) + observe(element: RelativeTimeElement, compactAbsolute: CompactAbsolute) { + this.elements.set(element, compactAbsolute) if (this.updating) return const date = element.date if (date) { - const ms = getUnitFactor(element) - const time = Date.now() + ms + const ms = getUnitFactor(element, compactAbsolute) + const delay = compactAbsolute ? Math.min(60 * 60 * 1000, ms) : ms + const time = Date.now() + delay if (time < this.time || this.time <= Date.now()) { clearTimeout(this.timer) - this.timer = setTimeout(() => this.update(), ms) + this.timer = setTimeout(() => this.update(), delay) this.time = time } } @@ -138,24 +205,31 @@ const dateObserver = new (class { timer: ReturnType = -1 as unknown as ReturnType update() { clearTimeout(this.timer) + this.time = Infinity if (!this.elements.size) return let nearestDistance = Infinity this.updating = true try { - for (const timeEl of this.elements) { - nearestDistance = Math.min(nearestDistance, getUnitFactor(timeEl)) + for (const timeEl of this.elements.keys()) { timeEl.update() + const compactAbsolute = this.elements.get(timeEl) + if (compactAbsolute !== undefined) + nearestDistance = Math.min(nearestDistance, getUnitFactor(timeEl, compactAbsolute)) } } finally { this.updating = false } - this.time = Math.min(60 * 60 * 1000, nearestDistance) - this.timer = setTimeout(() => this.update(), this.time) - this.time += Date.now() + if (!this.elements.size) return + const ms = Math.min(60 * 60 * 1000, nearestDistance) + this.timer = setTimeout(() => this.update(), ms) + this.time = Date.now() + ms } })() +/** + * @attr {'compact'} absolute-format + */ export class RelativeTimeElement extends HTMLElement implements Intl.DateTimeFormatOptions { static define(tag = 'relative-time', registry = customElements) { registry.define(tag, this) @@ -214,6 +288,7 @@ export class RelativeTimeElement extends HTMLElement implements Intl.DateTimeFor 'precision', 'format', 'format-style', + 'absolute-format', 'no-title', 'datetime', 'lang', @@ -349,8 +424,12 @@ export class RelativeTimeElement extends HTMLElement implements Intl.DateTimeFor return `${this.prefix} ${formatter.format(date)}`.trim() } - #isToday(date: Date, locale: string, timeZone: string | undefined): boolean { - const now = new Date() + #getCompactAbsoluteTimeFormat(date: Date, locale: string, timeZone: string | undefined, isToday: boolean): string { + if (isToday) return formatCompactToday(date, locale, timeZone) + return dateTimeFormat(locale, {timeZone, month: 'short', day: 'numeric', year: 'numeric'}).format(date) + } + + #isToday(date: Date, locale: string, timeZone: string | undefined, now = Date.now()): boolean { const formatter = dateTimeFormat(locale, { timeZone, year: 'numeric', @@ -623,6 +702,23 @@ export class RelativeTimeElement extends HTMLElement implements Intl.DateTimeFor this.setAttribute('format', value) } + /** + * Optional preset for resolved absolute text. Overrides display fields and the hour cycle, not the title. + * @attr absolute-format + * @reflect + */ + get absoluteFormat(): AbsoluteFormat | undefined { + if (this.getAttribute('absolute-format') === 'compact') return 'compact' + } + + set absoluteFormat(value: AbsoluteFormat | undefined) { + if (value === undefined) { + this.removeAttribute('absolute-format') + } else { + this.setAttribute('absolute-format', value) + } + } + get formatStyle(): FormatStyle { const formatStyle = this.getAttribute('format-style') if (formatStyle === 'long') return 'long' @@ -720,7 +816,12 @@ export class RelativeTimeElement extends HTMLElement implements Intl.DateTimeFor // Experimental: Enable absolute time if users prefers it, but never for `duration` format const displayUserPreferredAbsoluteTime = this.#shouldDisplayUserPreferredAbsoluteTime(format) - if (displayUserPreferredAbsoluteTime) { + const compactAbsolute = + this.absoluteFormat === 'compact' && (displayUserPreferredAbsoluteTime || format === 'datetime') + const compactToday = compactAbsolute && this.#isToday(date, locale, timeZone, now) + if (compactAbsolute) { + newText = this.#getCompactAbsoluteTimeFormat(date, locale, timeZone, compactToday) + } else if (displayUserPreferredAbsoluteTime) { newText = this.#getUserPreferredAbsoluteTimeFormat(date, locale, timeZone, hourCycle) } else { if (format === 'duration') { @@ -747,13 +848,23 @@ export class RelativeTimeElement extends HTMLElement implements Intl.DateTimeFor this.dispatchEvent(new RelativeTimeUpdatedEvent(oldText, newText, oldTitle, newTitle)) } - const shouldObserve = - (!displayUserPreferredAbsoluteTime && (format === 'relative' || format === 'duration')) || - (this.format === 'micro' && Boolean(this.#getExplicitThreshold()) && date.getTime() > now) || - (displayUserPreferredAbsoluteTime && - (this.#isToday(date, locale, timeZone) || this.#isCurrentYear(date, locale, timeZone))) + const isFuture = date.getTime() > now + const compactBoundary = + compactAbsolute && + !compactToday && + !isFuture && + this.#isToday(date, locale, timeZone, now + msUntilNextDay(now, timeZone)) + const shouldObserve = compactAbsolute + ? compactToday || isFuture || compactBoundary + : (!displayUserPreferredAbsoluteTime && (format === 'relative' || format === 'duration')) || + (this.format === 'micro' && Boolean(this.#getExplicitThreshold()) && isFuture) || + (displayUserPreferredAbsoluteTime && + (this.#isToday(date, locale, timeZone) || this.#isCurrentYear(date, locale, timeZone))) if (shouldObserve) { - dateObserver.observe(this) + dateObserver.observe( + this, + compactAbsolute && (displayUserPreferredAbsoluteTime || this.format === 'datetime' ? 'day' : 'threshold'), + ) } else { dateObserver.unobserve(this) } diff --git a/test/relative-time.js b/test/relative-time.js index 186a140..ae1818a 100644 --- a/test/relative-time.js +++ b/test/relative-time.js @@ -2483,6 +2483,392 @@ suite('relative-time', function () { }) }) + suite('[absolute-format="compact"]', function () { + const todayDateTime = '2026-11-03T15:04:00.000Z' + const yesterdayDateTime = '2026-11-02T15:04:00.000Z' + const reference = '2026-11-03T16:04:00.000Z' + const display = el => el.shadowRoot.textContent + + function render(attributes = {}, parent = fixture) { + const el = document.createElement('relative-time') + for (const [name, value] of Object.entries({ + lang: 'en-US', + 'time-zone': 'UTC', + datetime: todayDateTime, + format: 'datetime', + 'absolute-format': 'compact', + ...attributes, + })) { + if (value !== undefined) el.setAttribute(name, value) + } + parent.append(el) + return el + } + + teardown(() => { + document.documentElement.removeAttribute('data-prefers-absolute-time') + }) + + test('renders today with a time and other days with an unpadded date including the year', async () => { + freezeTime(new Date(reference)) + const el = render() + assert.equal(display(el), 'today at 3:04 PM') + el.datetime = yesterdayDateTime + await Promise.resolve() + assert.equal(display(el), 'Nov 2, 2026') + el.datetime = '2026-11-04T15:04:00.000Z' + await Promise.resolve() + assert.equal(display(el), 'Nov 4, 2026') + }) + + for (const preferenceTarget of ['documentElement', 'body']) { + test(`uses the same preset when ${preferenceTarget} prefers absolute time`, async () => { + freezeTime(new Date(reference)) + document[preferenceTarget].setAttribute('data-prefers-absolute-time', 'true') + const el = render({format: 'relative'}) + assert.equal(display(el), 'today at 3:04 PM') + el.datetime = yesterdayDateTime + await Promise.resolve() + assert.equal(display(el), 'Nov 2, 2026') + }) + } + + test('only applies the preset after resolving the relative threshold and tense', async () => { + freezeTime(new Date(reference)) + const el = render({format: 'relative'}) + assert.equal(display(el), '1 hour ago') + el.threshold = 'PT30M' + await Promise.resolve() + assert.equal(display(el), 'today at 3:04 PM') + el.tense = 'past' + await Promise.resolve() + assert.equal(display(el), '1 hour ago') + }) + + test('leaves duration and elapsed output unchanged even with the absolute preference', () => { + freezeTime(new Date(reference)) + document.body.setAttribute('data-prefers-absolute-time', 'true') + assert.equal(display(render({format: 'duration'})), '1 hour') + assert.equal(display(render({format: 'elapsed'})), '1h') + }) + + test('leaves micro duration and tense output unchanged unless it resolves to absolute', async () => { + freezeTime(new Date(reference)) + const el = render({format: 'micro'}) + assert.equal(display(el), '1h') + el.tense = 'past' + await Promise.resolve() + assert.equal(display(el), '1h ago') + document.body.setAttribute('data-prefers-absolute-time', 'true') + el.update() + assert.equal(display(el), 'today at 3:04 PM') + document.body.removeAttribute('data-prefers-absolute-time') + el.threshold = 'PT30M' + await Promise.resolve() + assert.equal(display(el), 'today at 3:04 PM') + }) + + test('updates when the property or attribute changes, and ignores empty and unknown values', async () => { + freezeTime(new Date(reference)) + const el = render({'absolute-format': undefined}) + const original = display(el) + assert.isUndefined(el.absoluteFormat) + assert.notEqual(original, 'today at 3:04 PM') + + for (const value of ['', 'unknown']) { + el.setAttribute('absolute-format', value) + await Promise.resolve() + assert.isUndefined(el.absoluteFormat) + assert.equal(display(el), original) + } + + el.absoluteFormat = 'compact' + await Promise.resolve() + assert.equal(el.getAttribute('absolute-format'), 'compact') + assert.equal(display(el), 'today at 3:04 PM') + el.removeAttribute('absolute-format') + await Promise.resolve() + assert.equal(display(el), original) + + el.setAttribute('absolute-format', 'compact') + await Promise.resolve() + assert.equal(el.absoluteFormat, 'compact') + assert.equal(display(el), 'today at 3:04 PM') + el.absoluteFormat = undefined + await Promise.resolve() + assert.isFalse(el.hasAttribute('absolute-format')) + assert.equal(display(el), original) + }) + + test('overrides display options and hour cycle without changing the datetime or full title', async () => { + freezeTime(new Date(reference)) + const parent = document.createElement('div') + parent.setAttribute('hour-cycle', 'h23') + fixture.append(parent) + const el = render( + { + 'absolute-format': undefined, + prefix: 'Uploaded:', + 'format-style': 'long', + weekday: 'long', + day: '2-digit', + month: 'long', + year: '2-digit', + hour: '2-digit', + minute: 'numeric', + second: 'numeric', + 'time-zone-name': 'long', + }, + parent, + ) + const original = display(el) + const title = el.getAttribute('title') + assert.match(original, /^Uploaded:.*November.*15:04:00/) + assert.match(title, /Nov 3, 2026, 15:04 UTC/) + el.absoluteFormat = 'compact' + await Promise.resolve() + assert.equal(display(el), 'today at 3:04 PM', 'overrides inherited hour cycle') + el.setAttribute('hour-cycle', 'h23') + await Promise.resolve() + assert.equal(display(el), 'today at 3:04 PM', 'overrides explicit hour cycle') + assert.equal(el.getAttribute('title'), title) + assert.equal(el.getAttribute('datetime'), todayDateTime) + + el.datetime = yesterdayDateTime + await Promise.resolve() + assert.equal(display(el), 'Nov 2, 2026') + el.datetime = todayDateTime + el.absoluteFormat = undefined + await Promise.resolve() + assert.equal(display(el), original) + assert.equal(el.getAttribute('title'), title) + }) + + test('preserves custom titles, no-title, and light DOM fallbacks for invalid dates', async () => { + freezeTime(new Date(reference)) + const custom = render({title: 'Custom timestamp'}) + const suppressed = render({'no-title': ''}) + const invalid = render({datetime: 'Invalid', 'no-title': ''}) + invalid.textContent = 'Server timestamp' + await Promise.resolve() + + assert.equal(display(custom), 'today at 3:04 PM') + assert.equal(custom.title, 'Custom timestamp') + assert.equal(display(suppressed), 'today at 3:04 PM') + assert.isFalse(suppressed.hasAttribute('title')) + assert.equal(display(invalid), 'Server timestamp') + assert.isFalse(invalid.hasAttribute('title')) + }) + + test('uses the inherited display time zone rather than the browser or UTC day', async () => { + freezeTime(new Date('2026-11-04T03:30:00.000Z')) + const parent = document.createElement('div') + parent.setAttribute('time-zone', 'America/New_York') + fixture.append(parent) + const el = render({'time-zone': undefined}, parent) + assert.equal(display(el), 'today at 10:04 AM') + el.setAttribute('time-zone', 'UTC') + await Promise.resolve() + assert.equal(display(el), 'Nov 3, 2026') + }) + + for (const [lang, separator, timePrefix] of [ + ['en-US', ' at '], + ['en-GB', ' at '], + ['de-DE', ' um '], + ['fr-FR', ' à '], + ['es-ES', ' a las '], + ['ca-ES', ', a les '], + ['ru-RU', ' в '], + ['vi-VN', ' ', 'lúc '], + ['ja-JP', ' '], + ['zh-CN', ' '], + ['zh-Hant-TW', ' '], + ['ko-KR', ' '], + ]) { + test(`uses the date/time pattern or a safe fallback for ${lang}`, () => { + freezeTime(new Date(reference)) + const today = new Intl.RelativeTimeFormat(lang, {numeric: 'auto'}).format(0, 'day') + const time = new Intl.DateTimeFormat(lang, { + timeZone: 'UTC', + hourCycle: 'h12', + hour: 'numeric', + minute: '2-digit', + }).format(new Date(todayDateTime)) + + assert.equal( + display(render({lang})), + timePrefix ? `${timePrefix}${time}${separator}${today}` : `${today}${separator}${time}`, + ) + }) + } + + test('preserves localized date order and digits', () => { + freezeTime(new Date(reference)) + assert.equal(display(render({lang: 'ar-EG-u-nu-arab', datetime: yesterdayDateTime})), '٢ نوفمبر ٢٠٢٦') + }) + + for (const { + reason, + before, + datetime, + timeZone, + after, + initialText, + updatedText, + attributes, + prefersAbsoluteTime, + hourly, + } of [ + { + reason: 'today (less than a minute old) to a date at midnight', + before: '2034-11-03T23:59:59.500Z', + datetime: '2034-11-03T23:59:30.000Z', + after: '2034-11-04T00:00:00.000Z', + initialText: 'today at 11:59 PM', + updatedText: 'Nov 3, 2034', + }, + { + reason: 'today (less than an hour old) to a date at midnight', + before: '2035-11-03T23:59:30.000Z', + datetime: '2035-11-03T23:45:00.000Z', + after: '2035-11-04T00:00:00.000Z', + initialText: 'today at 11:45 PM', + updatedText: 'Nov 3, 2035', + }, + { + reason: 'today to a date at midnight with hourly updates', + before: '2033-11-03T12:00:30.000Z', + datetime: '2033-11-03T12:00:00.000Z', + after: '2033-11-04T00:00:00.000Z', + initialText: 'today at 12:00 PM', + updatedText: 'Nov 3, 2033', + hourly: true, + }, + { + reason: 'today (more than an hour old) to a date at midnight', + before: '2036-11-03T23:59:30.000Z', + datetime: '2036-11-03T15:04:00.000Z', + after: '2036-11-04T00:00:00.000Z', + initialText: 'today at 3:04 PM', + updatedText: 'Nov 3, 2036', + }, + { + reason: 'a future date to today across New Year in the display zone', + before: '2037-01-01T04:59:30.000Z', + datetime: '2037-01-01T20:04:00.000Z', + timeZone: 'America/New_York', + after: '2037-01-01T05:00:00.000Z', + initialText: 'Jan 1, 2037', + updatedText: 'today at 3:04 PM', + }, + { + reason: 'a future date to today when a DST jump skips midnight', + before: '2025-03-30T00:30:00.000Z', + datetime: '2025-03-30T03:04:00.000Z', + timeZone: 'America/Nuuk', + after: '2025-03-30T01:00:00.000Z', + initialText: 'Mar 30, 2025', + updatedText: 'today at 2:04 AM', + }, + { + reason: 'a past date to today when Antarctica/Casey rolls back to the previous day', + before: '2010-03-04T14:30:00.000Z', + datetime: '2010-03-04T12:04:00.000Z', + timeZone: 'Antarctica/Casey', + after: '2010-03-04T15:00:00.000Z', + initialText: 'Mar 4, 2010', + updatedText: 'today at 11:04 PM', + }, + { + reason: 'compact absolute text back to micro duration at its threshold', + before: '2038-11-03T16:00:00.000Z', + datetime: '2038-11-03T16:01:02.000Z', + after: '2038-11-03T16:00:02.000Z', + initialText: 'today at 4:01 PM', + updatedText: '1m', + attributes: {format: 'micro', threshold: 'PT1M'}, + }, + { + reason: 'recent threshold-derived compact text to a date at midnight with hourly updates', + before: '2039-11-03T12:00:30.000Z', + datetime: '2039-11-03T12:00:00.000Z', + after: '2039-11-04T00:00:00.000Z', + initialText: 'today at 12:00 PM', + updatedText: 'Nov 3, 2039', + attributes: {format: 'relative', threshold: 'PT10S'}, + hourly: true, + }, + { + reason: 'a future datetime today to a date at midnight with hourly updates', + before: '2040-11-03T12:00:00.000Z', + datetime: '2040-11-03T12:00:30.000Z', + after: '2040-11-04T00:00:00.000Z', + initialText: 'today at 12:00 PM', + updatedText: 'Nov 3, 2040', + hourly: true, + }, + { + reason: 'a future preferred absolute time today to a date at midnight with hourly updates', + before: '2041-11-03T12:00:00.000Z', + datetime: '2041-11-03T12:30:00.000Z', + after: '2041-11-04T00:00:00.000Z', + initialText: 'today at 12:30 PM', + updatedText: 'Nov 3, 2041', + attributes: {format: 'relative'}, + prefersAbsoluteTime: true, + hourly: true, + }, + { + reason: 'threshold-derived compact text to relative text at its threshold', + before: '2042-11-03T12:00:00.000Z', + datetime: '2042-11-03T12:10:10.000Z', + after: '2042-11-03T12:01:00.000Z', + initialText: 'today at 12:10 PM', + updatedText: 'in 9 minutes', + attributes: {format: 'relative', threshold: 'PT10M'}, + }, + ]) { + test(`automatically updates ${reason}`, async () => { + freezeTime(new Date(before)) + if (prefersAbsoluteTime) document.documentElement.setAttribute('data-prefers-absolute-time', 'true') + const originalSetTimeout = window.setTimeout + let tick + let delay + globalThis.setTimeout = window.setTimeout = function (callback, ms) { + tick = callback + delay = ms + return 0 + } + try { + const el = render({datetime, 'time-zone': timeZone ?? 'UTC', ...attributes}) + await Promise.resolve() + assert.equal(display(el), initialText) + assert.isFunction(tick) + if (hourly) { + // Only the first delay comes from this element alone. Later ticks include other observed elements. + assert.equal(delay, 60 * 60 * 1000) + let now = Date.parse(before) + while (now < Date.parse(after)) { + const nextDelay = Math.min(60 * 60 * 1000, Date.parse(after) - now) + assert.isAtMost(delay, 60 * 60 * 1000) + now += nextDelay + Date.now = () => now + tick() + } + } else { + assert.equal(delay, Date.parse(after) - Date.parse(before)) + Date.now = () => Date.parse(after) + tick() + } + assert.equal(display(el), updatedText) + } finally { + globalThis.setTimeout = window.setTimeout = originalSetTimeout + } + }) + } + }) + suite('[aria-hidden]', async () => { test('[aria-hidden="true"] applies to shadow root', async () => { const now = new Date().toISOString()