From da5144fe8313362a5283ea1935a49939dc887fd9 Mon Sep 17 00:00:00 2001 From: tay1orjones <3360588+tay1orjones@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:02:25 +0000 Subject: [PATCH 1/8] Initial plan From d78caadac0e96621ff2f71cafe67cf61643c7872 Mon Sep 17 00:00:00 2001 From: tay1orjones <3360588+tay1orjones@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:10:35 +0000 Subject: [PATCH 2/8] feat: add the compact absolute-time preset Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- src/relative-time-element.ts | 135 ++++++++++++--- test/relative-time.js | 311 +++++++++++++++++++++++++++++++++++ 2 files changed, 425 insertions(+), 21 deletions(-) diff --git a/src/relative-time-element.ts b/src/relative-time-element.ts index e7c9d47..2483fc8 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,7 @@ export class RelativeTimeUpdatedEvent extends Event { } } -function getUnitFactor(el: RelativeTimeElement): number { +function getUnitFactor(el: RelativeTimeElement, compactAbsolute: boolean): number { const date = el.date if (!date) return Infinity const now = Date.now() @@ -53,8 +54,9 @@ 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 || 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 +88,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,16 +172,16 @@ 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: boolean) { + this.elements.set(element, compactAbsolute) if (this.updating) return const date = element.date if (date) { - const ms = getUnitFactor(element) + const ms = getUnitFactor(element, compactAbsolute) const time = Date.now() + ms if (time < this.time || this.time <= Date.now()) { clearTimeout(this.timer) @@ -138,24 +199,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 - Optional preset for visible absolute text only. + */ export class RelativeTimeElement extends HTMLElement implements Intl.DateTimeFormatOptions { static define(tag = 'relative-time', registry = customElements) { registry.define(tag, this) @@ -214,6 +282,7 @@ export class RelativeTimeElement extends HTMLElement implements Intl.DateTimeFor 'precision', 'format', 'format-style', + 'absolute-format', 'no-title', 'datetime', 'lang', @@ -349,8 +418,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 +696,19 @@ export class RelativeTimeElement extends HTMLElement implements Intl.DateTimeFor this.setAttribute('format', value) } + /** Preset for resolved absolute text. Overrides display fields and the hour cycle, not the title. */ + 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 +806,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 +838,15 @@ 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 shouldObserve = compactAbsolute + ? compactToday || isFuture + : (!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) } else { dateObserver.unobserve(this) } diff --git a/test/relative-time.js b/test/relative-time.js index 186a140..1fd1dfc 100644 --- a/test/relative-time.js +++ b/test/relative-time.js @@ -2483,6 +2483,317 @@ 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)) + const lang = 'ar-EG-u-nu-arab' + const localized = new Intl.DateTimeFormat(lang, { + timeZone: 'UTC', + day: 'numeric', + month: 'short', + year: 'numeric', + }).format(new Date(yesterdayDateTime)) + assert.equal(display(render({lang, datetime: yesterdayDateTime})), localized) + }) + + for (const {reason, before, datetime, timeZone, after, initialText, updatedText, attributes} 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 (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: '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'}, + }, + ]) { + test(`automatically updates ${reason}`, async () => { + freezeTime(new Date(before)) + 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) + 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() From 2d5502b110c5ad2ce4e9af2668e43dd3a316c4bc Mon Sep 17 00:00:00 2001 From: tay1orjones <3360588+tay1orjones@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:12:49 +0000 Subject: [PATCH 3/8] docs: document compact absolute-time precedence Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- README.md | 18 ++++++++++++++++++ src/relative-time-element.ts | 8 ++++++-- 2 files changed, 24 insertions(+), 2 deletions(-) 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 2483fc8..a2c5306 100644 --- a/src/relative-time-element.ts +++ b/src/relative-time-element.ts @@ -222,7 +222,7 @@ const dateObserver = new (class { })() /** - * @attr {'compact'} absolute-format - Optional preset for visible absolute text only. + * @attr {'compact'} absolute-format */ export class RelativeTimeElement extends HTMLElement implements Intl.DateTimeFormatOptions { static define(tag = 'relative-time', registry = customElements) { @@ -696,7 +696,11 @@ export class RelativeTimeElement extends HTMLElement implements Intl.DateTimeFor this.setAttribute('format', value) } - /** Preset for resolved absolute text. Overrides display fields and the hour cycle, not the title. */ + /** + * 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' } From 84ab6dc47882f5e487a46059a13b340076c33e06 Mon Sep 17 00:00:00 2001 From: tay1orjones <3360588+tay1orjones@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:37:40 +0000 Subject: [PATCH 4/8] fix: correct compact absolute rollover scheduling Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- src/relative-time-element.ts | 11 +++++++++-- test/relative-time.js | 17 +++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/relative-time-element.ts b/src/relative-time-element.ts index a2c5306..5b344ab 100644 --- a/src/relative-time-element.ts +++ b/src/relative-time-element.ts @@ -55,7 +55,9 @@ function getUnitFactor(el: RelativeTimeElement, compactAbsolute: boolean): numbe } else if (ms < 60 * 60 * 1000) { factor = 60 * 1000 } - if (compactAbsolute || ms >= 60 * 60 * 1000) { + if (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)) } @@ -843,8 +845,13 @@ export class RelativeTimeElement extends HTMLElement implements Intl.DateTimeFor } const isFuture = date.getTime() > now + const compactBoundary = + compactAbsolute && + !compactToday && + !isFuture && + this.#isToday(date, locale, timeZone, now + msUntilNextDay(now, timeZone)) const shouldObserve = compactAbsolute - ? compactToday || isFuture + ? compactToday || isFuture || compactBoundary : (!displayUserPreferredAbsoluteTime && (format === 'relative' || format === 'duration')) || (this.format === 'micro' && Boolean(this.#getExplicitThreshold()) && isFuture) || (displayUserPreferredAbsoluteTime && diff --git a/test/relative-time.js b/test/relative-time.js index 1fd1dfc..8105a5d 100644 --- a/test/relative-time.js +++ b/test/relative-time.js @@ -2732,6 +2732,14 @@ suite('relative-time', function () { initialText: 'today at 11:45 PM', updatedText: 'Nov 3, 2035', }, + { + reason: 'today (less than a minute old) to a date at midnight without a fine-grained tick', + 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', + }, { reason: 'today (more than an hour old) to a date at midnight', before: '2036-11-03T23:59:30.000Z', @@ -2758,6 +2766,15 @@ suite('relative-time', function () { 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', From adfbb14caacd38914cfd5c52dac2c7a3996ac9ea Mon Sep 17 00:00:00 2001 From: tay1orjones <3360588+tay1orjones@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:03:15 +0000 Subject: [PATCH 5/8] fix: cap initial compact observer timer Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- src/relative-time-element.ts | 5 +++-- test/relative-time.js | 22 +++++++++++++++++----- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/src/relative-time-element.ts b/src/relative-time-element.ts index 5b344ab..98788db 100644 --- a/src/relative-time-element.ts +++ b/src/relative-time-element.ts @@ -184,10 +184,11 @@ const dateObserver = new (class { const date = element.date if (date) { const ms = getUnitFactor(element, compactAbsolute) - const time = Date.now() + ms + 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 } } diff --git a/test/relative-time.js b/test/relative-time.js index 8105a5d..4cefb72 100644 --- a/test/relative-time.js +++ b/test/relative-time.js @@ -2715,7 +2715,7 @@ suite('relative-time', function () { assert.equal(display(render({lang, datetime: yesterdayDateTime})), localized) }) - for (const {reason, before, datetime, timeZone, after, initialText, updatedText, attributes} of [ + for (const {reason, before, datetime, timeZone, after, initialText, updatedText, attributes, hourly} of [ { reason: 'today (less than a minute old) to a date at midnight', before: '2034-11-03T23:59:59.500Z', @@ -2733,12 +2733,13 @@ suite('relative-time', function () { updatedText: 'Nov 3, 2035', }, { - reason: 'today (less than a minute old) to a date at midnight without a fine-grained tick', + 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', @@ -2800,9 +2801,20 @@ suite('relative-time', function () { await Promise.resolve() assert.equal(display(el), initialText) assert.isFunction(tick) - assert.equal(delay, Date.parse(after) - Date.parse(before)) - Date.now = () => Date.parse(after) - tick() + if (hourly) { + 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 From 98035107f8451aabaf9214538d8ed30d90c5068d Mon Sep 17 00:00:00 2001 From: Taylor Jones Date: Fri, 20 Nov 2026 09:27:37 -0600 Subject: [PATCH 6/8] test: assert the first compact hourly delay The hourly rollover case used `assert.isAtMost`, so a 1 s delay passed. Removing the recent-past `msUntilNextDay` branch in `getUnitFactor` did not fail any test. Assert the first delay from `observe()`, which comes only from the new element. Later delays also include other elements in the shared observer, so the loop keeps `isAtMost`. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- test/relative-time.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/relative-time.js b/test/relative-time.js index 4cefb72..4466073 100644 --- a/test/relative-time.js +++ b/test/relative-time.js @@ -2802,6 +2802,8 @@ suite('relative-time', function () { 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) From afa3f15651facb3dc73a09259f09d613b4fa328f Mon Sep 17 00:00:00 2001 From: Taylor Jones Date: Fri, 20 Nov 2026 09:29:22 -0600 Subject: [PATCH 7/8] fix: skip fine-grained ticks for compact datetime text A future compact timestamp ticked every 60 s in its last hour and every 1 s in its last minute. With explicit `format="datetime"` or the absolute-time preference, the compact text only changes at midnight, so those ticks did no work. The observer now records why compact text is observed: - `day`: explicit `format="datetime"` or the preference. Schedule the next tick at the next day boundary (still capped at one hour). - `threshold`: compact text from a threshold. It can turn relative before midnight, so keep the existing cadence (fine ticks, capped by the next day boundary, plus the `micro` threshold time). Past compact text still waits for the next day boundary. The `format="datetime"` hourly case now takes the `day` path, so add a threshold-derived recent-past case to keep coverage of that branch. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/relative-time-element.ts | 16 +++++++---- test/relative-time.js | 53 +++++++++++++++++++++++++++++++++++- 2 files changed, 63 insertions(+), 6 deletions(-) diff --git a/src/relative-time-element.ts b/src/relative-time-element.ts index 98788db..2c0e44c 100644 --- a/src/relative-time-element.ts +++ b/src/relative-time-element.ts @@ -36,7 +36,10 @@ export class RelativeTimeUpdatedEvent extends Event { } } -function getUnitFactor(el: RelativeTimeElement, compactAbsolute: boolean): 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() @@ -55,7 +58,7 @@ function getUnitFactor(el: RelativeTimeElement, compactAbsolute: boolean): numbe } else if (ms < 60 * 60 * 1000) { factor = 60 * 1000 } - if (compactAbsolute && date.getTime() <= now) { + 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. @@ -174,11 +177,11 @@ if (typeof window !== 'undefined' && typeof window.addEventListener === 'functio } const dateObserver = new (class { - elements = new Map() + elements = new Map() time = Infinity updating = false - observe(element: RelativeTimeElement, compactAbsolute: boolean) { + observe(element: RelativeTimeElement, compactAbsolute: CompactAbsolute) { this.elements.set(element, compactAbsolute) if (this.updating) return const date = element.date @@ -858,7 +861,10 @@ export class RelativeTimeElement extends HTMLElement implements Intl.DateTimeFor (displayUserPreferredAbsoluteTime && (this.#isToday(date, locale, timeZone) || this.#isCurrentYear(date, locale, timeZone))) if (shouldObserve) { - dateObserver.observe(this, compactAbsolute) + 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 4466073..4f83d6b 100644 --- a/test/relative-time.js +++ b/test/relative-time.js @@ -2715,7 +2715,18 @@ suite('relative-time', function () { assert.equal(display(render({lang, datetime: yesterdayDateTime})), localized) }) - for (const {reason, before, datetime, timeZone, after, initialText, updatedText, attributes, hourly} of [ + 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', @@ -2785,9 +2796,49 @@ suite('relative-time', function () { 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 From 28a3589896dad16d429119cf94712b18b60c498d Mon Sep 17 00:00:00 2001 From: Taylor Jones Date: Fri, 20 Nov 2026 09:29:59 -0600 Subject: [PATCH 8/8] test: assert literal Arabic digits The digits test built its expected value with the same `Intl` call as the element, so it also passed with ASCII digits. Assert the literal `ar-EG-u-nu-arab` output instead. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- test/relative-time.js | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/test/relative-time.js b/test/relative-time.js index 4f83d6b..ae1818a 100644 --- a/test/relative-time.js +++ b/test/relative-time.js @@ -2705,14 +2705,7 @@ suite('relative-time', function () { test('preserves localized date order and digits', () => { freezeTime(new Date(reference)) - const lang = 'ar-EG-u-nu-arab' - const localized = new Intl.DateTimeFormat(lang, { - timeZone: 'UTC', - day: 'numeric', - month: 'short', - year: 'numeric', - }).format(new Date(yesterdayDateTime)) - assert.equal(display(render({lang, datetime: yesterdayDateTime})), localized) + assert.equal(display(render({lang: 'ar-EG-u-nu-arab', datetime: yesterdayDateTime})), '٢ نوفمبر ٢٠٢٦') }) for (const {