Open History to see the last commit
1import { type TimestampFormat } from "@t3tools/contracts/settings";
2
3function getTimestampFormatOptions(
4 timestampFormat: TimestampFormat,
5 includeSeconds: boolean,
6): Intl.DateTimeFormatOptions {
7 const baseOptions: Intl.DateTimeFormatOptions = {
8 hour: "numeric",
9 minute: "2-digit",
10 ...(includeSeconds ? { second: "2-digit" } : {}),
11 };
12
13 if (timestampFormat === "locale") {
14 return baseOptions;
15 }
16
17 return {
18 ...baseOptions,
19 hour12: timestampFormat === "12-hour",
20 };
21}
22
23export function resolveTimestampLocale(
24 systemLocale: string | null | undefined,
25): string | undefined {
26 const tag = systemLocale?.trim();
27 if (!tag) return undefined;
28
29 try {
30 // Every timestamp in the UI runs through this formatter, so a tag the host
31 // could not normalize falls back rather than throwing. Throws on a
32 // structurally invalid tag; a well-formed tag ICU has no data for resolves
33 // here and is left to ICU's own fallback.
34 Intl.DateTimeFormat.supportedLocalesOf([tag]);
35 return tag;
36 } catch {
37 return undefined;
38 }
39}
40
41function readHostSystemLocale(): string | null {
42 if (typeof window === "undefined") return null;
43 return window.desktopBridge?.getSystemLocale?.() ?? null;
44}
45
46const timestampLocale = resolveTimestampLocale(readHostSystemLocale());
47
48const WEEKDAY_INDEXES = [0, 1, 2, 3, 4, 5, 6] as const;
49type WeekdayIndex = (typeof WEEKDAY_INDEXES)[number];
50
51type LocaleWithWeekInfo = Intl.Locale & {
52 readonly weekInfo?: { readonly firstDay: number };
53 getWeekInfo?: () => { readonly firstDay: number };
54};
55
56/**
57 * First weekday of a locale as a `Date#getDay` index (0 is Sunday), or
58 * `undefined` when the runtime has no week data, so callers keep their own
59 * default.
60 */
61export function resolveWeekStartsOn(locale: string | undefined): WeekdayIndex | undefined {
62 try {
63 const resolved: LocaleWithWeekInfo = new Intl.Locale(
64 locale ?? Intl.DateTimeFormat().resolvedOptions().locale,
65 );
66 // Week info counts Monday as 1 and Sunday as 7.
67 const firstDay = resolved.getWeekInfo?.().firstDay ?? resolved.weekInfo?.firstDay;
68 return firstDay === undefined ? undefined : WEEKDAY_INDEXES[firstDay % 7];
69 } catch {
70 return undefined;
71 }
72}
73
74export const weekStartsOn = resolveWeekStartsOn(timestampLocale);
75
76const timestampFormatterCache = new Map<string, Intl.DateTimeFormat>();
77
78function getTimestampFormatter(
79 timestampFormat: TimestampFormat,
80 includeSeconds: boolean,
81): Intl.DateTimeFormat {
82 const cacheKey = `${timestampFormat}:${includeSeconds ? "seconds" : "minutes"}`;
83 const cachedFormatter = timestampFormatterCache.get(cacheKey);
84 if (cachedFormatter) {
85 return cachedFormatter;
86 }
87
88 const formatter = new Intl.DateTimeFormat(
89 timestampLocale,
90 getTimestampFormatOptions(timestampFormat, includeSeconds),
91 );
92 timestampFormatterCache.set(cacheKey, formatter);
93 return formatter;
94}
95
96export function resolveHour12(timestampFormat: TimestampFormat): boolean {
97 return getTimestampFormatter(timestampFormat, false).resolvedOptions().hour12 ?? false;
98}
99
100export function parseTimestampDate(isoDate: string): Date | null {
101 const date = new Date(isoDate);
102 return Number.isNaN(date.getTime()) ? null : date;
103}
104
105export function formatTimestamp(isoDate: string, timestampFormat: TimestampFormat): string {
106 const date = parseTimestampDate(isoDate);
107 if (!date) return "";
108 return getTimestampFormatter(timestampFormat, true).format(date);
109}
110
111// Deliberately not the host locale: the tooltip's ordinal suffix and
112// day-before-month order below are English, so a localized month alone would
113// read "4th Juni 2026".
114const monthNameFormatter = new Intl.DateTimeFormat("en-US", { month: "long" });
115
116function ordinalSuffix(day: number): string {
117 const lastTwo = day % 100;
118 if (lastTwo >= 11 && lastTwo <= 13) return "th";
119 switch (day % 10) {
120 case 1:
121 return "st";
122 case 2:
123 return "nd";
124 case 3:
125 return "rd";
126 default:
127 return "th";
128 }
129}
130
131export function formatChatTimestampTooltip(
132 isoDate: string,
133 timestampFormat: TimestampFormat,
134): string {
135 const date = parseTimestampDate(isoDate);
136 if (!date) return "";
137 const time = formatShortTimestamp(isoDate, timestampFormat);
138 const day = date.getDate();
139 const month = monthNameFormatter.format(date);
140 const year = date.getFullYear();
141 return `${time}, ${day}${ordinalSuffix(day)} ${month} ${year}`;
142}
143
144export function formatShortTimestamp(isoDate: string, timestampFormat: TimestampFormat): string {
145 const date = parseTimestampDate(isoDate);
146 if (!date) return "";
147 return getTimestampFormatter(timestampFormat, false).format(date);
148}
149
150const numericDateFormatter = new Intl.DateTimeFormat(timestampLocale, {
151 month: "numeric",
152 day: "numeric",
153});
154const numericDateWithYearFormatter = new Intl.DateTimeFormat(timestampLocale, {
155 month: "numeric",
156 day: "numeric",
157 year: "numeric",
158});
159
160export function formatDayAwareTimestamp(
161 isoDate: string,
162 timestampFormat: TimestampFormat,
163 nowMs: number = Date.now(),
164): string {
165 const date = parseTimestampDate(isoDate);
166 if (!date) return "";
167 const time = getTimestampFormatter(timestampFormat, false).format(date);
168
169 const now = new Date(nowMs);
170 const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
171 const startOfMessageDay = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
172 // Round so DST-shifted 23/25 hour days still count as whole days.
173 const dayDiff = Math.round((startOfToday - startOfMessageDay) / 86_400_000);
174
175 if (dayDiff <= 0) return time;
176 if (dayDiff === 1) return `yesterday at ${time}`;
177 const dateFormatter =
178 date.getFullYear() === now.getFullYear() ? numericDateFormatter : numericDateWithYearFormatter;
179 return `${dateFormatter.format(date)} ${time}`;
180}
181
182export function formatUpcomingTimestamp(
183 isoDate: string,
184 timestampFormat: TimestampFormat,
185 nowMs: number = Date.now(),
186): string {
187 const date = parseTimestampDate(isoDate);
188 if (!date) return "";
189 const time = getTimestampFormatter(timestampFormat, false).format(date);
190
191 const now = new Date(nowMs);
192 const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
193 const startOfTargetDay = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
194 const dayDiff = Math.round((startOfTargetDay - startOfToday) / 86_400_000);
195
196 if (dayDiff < 0) return formatDayAwareTimestamp(isoDate, timestampFormat, nowMs);
197 if (dayDiff === 0) return time;
198 if (dayDiff === 1) return `tomorrow at ${time}`;
199 const dateFormatter =
200 date.getFullYear() === now.getFullYear() ? numericDateFormatter : numericDateWithYearFormatter;
201 return `${dateFormatter.format(date)} ${time}`;
202}
203
204type RelativeTimeParts = { value: string; suffix: string | null };
205export type RelativeTimeState =
206 | { status: "missing" }
207 | { status: "invalid" }
208 | { status: "relative"; value: string; suffix: string | null };
209
210const MINUTE_MS = 60_000;
211const HOUR_MS = 3_600_000;
212const DAY_MS = 86_400_000;
213
214function relativeTimeUnitMs(elapsedMs: number): number {
215 if (elapsedMs < HOUR_MS) return MINUTE_MS;
216 if (elapsedMs < DAY_MS) return HOUR_MS;
217 return DAY_MS;
218}
219
220/**
221 * Elapsed time floored to the precision `formatRelativeTime` shows, so two
222 * instants with the same label return the same number.
223 */
224export function relativeTimeElapsedMs(isoDate: string, nowMs: number = Date.now()): number | null {
225 const date = parseTimestampDate(isoDate);
226 if (!date) return null;
227 const elapsedMs = Math.max(0, nowMs - date.getTime());
228 const unitMs = relativeTimeUnitMs(elapsedMs);
229 return Math.floor(elapsedMs / unitMs) * unitMs;
230}
231
232/** Milliseconds until the `formatRelativeTime` label for `isoDate` next changes. */
233export function msUntilRelativeTimeChange(
234 isoDate: string,
235 nowMs: number = Date.now(),
236): number | null {
237 const date = parseTimestampDate(isoDate);
238 if (!date) return null;
239 const elapsedMs = Math.max(0, nowMs - date.getTime());
240 const unitMs = relativeTimeUnitMs(elapsedMs);
241 const nextChangeMs = date.getTime() + (Math.floor(elapsedMs / unitMs) + 1) * unitMs;
242 // setTimeout fires at once past 2^31-1 ms, which would loop on a far-future
243 // timestamp. Waking early is harmless: the caller re-reads and re-schedules.
244 return Math.min(nextChangeMs - nowMs, DAY_MS);
245}
246
247export function formatRelativeElapsed(elapsedMs: number): RelativeTimeParts {
248 const seconds = Math.floor(elapsedMs / 1000);
249 if (seconds < 60) return { value: "just now", suffix: null };
250 const minutes = Math.floor(seconds / 60);
251 if (minutes < 60) return { value: `${minutes}m`, suffix: "ago" };
252 const hours = Math.floor(minutes / 60);
253 if (hours < 24) return { value: `${hours}h`, suffix: "ago" };
254 const days = Math.floor(hours / 24);
255 return { value: `${days}d`, suffix: "ago" };
256}
257
258export function formatRelativeTime(
259 isoDate: string,
260 nowMs: number = Date.now(),
261): RelativeTimeParts | null {
262 const elapsedMs = relativeTimeElapsedMs(isoDate, nowMs);
263 return elapsedMs === null ? null : formatRelativeElapsed(elapsedMs);
264}
265
266export function formatRelativeTimeLabel(isoDate: string, nowMs: number = Date.now()) {
267 const relative = formatRelativeTime(isoDate, nowMs);
268 if (!relative) return "";
269 return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
270}
271
272export function formatElapsedDurationLabel(isoDate: string, nowMs: number = Date.now()): string {
273 const date = parseTimestampDate(isoDate);
274 if (!date) return "";
275 const diffMs = nowMs - date.getTime();
276 if (diffMs <= 0) return "just now";
277
278 const seconds = Math.floor(diffMs / 1000);
279 if (seconds < 5) return "just now";
280 if (seconds < 60) return `${seconds}s`;
281
282 const minutes = Math.floor(seconds / 60);
283 if (minutes < 60) return `${minutes}m`;
284
285 const hours = Math.floor(minutes / 60);
286 if (hours < 24) return `${hours}h`;
287
288 const days = Math.floor(hours / 24);
289 return `${days}d`;
290}
291
292export function formatRelativeTimeUntil(isoDate: string): RelativeTimeParts | null {
293 const date = parseTimestampDate(isoDate);
294 if (!date) return null;
295 const diffMs = date.getTime() - Date.now();
296 if (diffMs <= 0) return { value: "Expired", suffix: null };
297 const seconds = Math.floor(diffMs / 1000);
298 if (seconds < 5) return { value: "Soon", suffix: null };
299 if (seconds < 60) return { value: `${seconds}s`, suffix: "left" };
300 const minutes = Math.floor(seconds / 60);
301 if (minutes < 60) return { value: `${minutes}m`, suffix: "left" };
302 const hours = Math.floor(minutes / 60);
303 if (hours < 24) return { value: `${hours}h`, suffix: "left" };
304 const days = Math.floor(hours / 24);
305 return { value: `${days}d`, suffix: "left" };
306}
307
308export function formatRelativeTimeUntilLabel(isoDate: string): string {
309 const relative = formatRelativeTimeUntil(isoDate);
310 if (!relative) return "";
311 return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
312}
313
314/**
315 * Pass `nowMs` when a parent tick drives re-renders so the diff matches that snapshot.
316 */
317export function formatExpiresInLabel(isoDate: string, nowMs: number = Date.now()): string {
318 const date = parseTimestampDate(isoDate);
319 if (!date) return "";
320 const diffMs = date.getTime() - nowMs;
321 if (diffMs <= 0) return "Expired";
322
323 const totalSeconds = Math.floor(diffMs / 1000);
324 if (totalSeconds < 5) return "Expires in a moment";
325 if (totalSeconds < 60) return `Expires in ${totalSeconds}s`;
326
327 if (totalSeconds < 3600) {
328 const minutes = Math.floor(totalSeconds / 60);
329 const seconds = totalSeconds % 60;
330 return seconds === 0 ? `Expires in ${minutes}m` : `Expires in ${minutes}m ${seconds}s`;
331 }
332
333 if (totalSeconds < 86_400) {
334 const hours = Math.floor(totalSeconds / 3600);
335 const rem = totalSeconds % 3600;
336 const minutes = Math.floor(rem / 60);
337 const seconds = rem % 60;
338 const parts = [`${hours}h`];
339 if (minutes > 0) parts.push(`${minutes}m`);
340 if (seconds > 0) parts.push(`${seconds}s`);
341 return `Expires in ${parts.join(" ")}`;
342 }
343
344 const days = Math.floor(totalSeconds / 86_400);
345 const remAfterDays = totalSeconds % 86_400;
346 if (remAfterDays === 0) return `Expires in ${days}d`;
347 const hours = Math.floor(remAfterDays / 3600);
348 const rem = remAfterDays % 3600;
349 const minutes = Math.floor(rem / 60);
350 const seconds = rem % 60;
351 const tail: string[] = [];
352 if (hours > 0) tail.push(`${hours}h`);
353 if (minutes > 0) tail.push(`${minutes}m`);
354 if (seconds > 0) tail.push(`${seconds}s`);
355 return tail.length > 0 ? `Expires in ${days}d ${tail.join(" ")}` : `Expires in ${days}d`;
356}