Open History to see the last commit
1import { type TimestampFormat } from "@t3tools/contracts/settings";
2import { msg } from "gt-react";
3
4import { DEFAULT_LOCALE } from "./i18n/locales";
5import { getActiveLocale, m, type MessageResolver } from "./i18n/messages";
6
7function getTimestampFormatOptions(
8 timestampFormat: TimestampFormat,
9 includeSeconds: boolean,
10): Intl.DateTimeFormatOptions {
11 const baseOptions: Intl.DateTimeFormatOptions = {
12 hour: "numeric",
13 minute: "2-digit",
14 ...(includeSeconds ? { second: "2-digit" } : {}),
15 };
16
17 if (timestampFormat === "locale") {
18 return baseOptions;
19 }
20
21 return {
22 ...baseOptions,
23 hour12: timestampFormat === "12-hour",
24 };
25}
26
27function resolveTimestampLocale(systemLocale: string | null | undefined): string | undefined {
28 const tag = systemLocale?.trim();
29 if (!tag) return undefined;
30
31 try {
32 // Reject structurally invalid tags; let ICU fall back for valid tags it lacks data for.
33 Intl.DateTimeFormat.supportedLocalesOf([tag]);
34 return tag;
35 } catch {
36 return undefined;
37 }
38}
39
40function readHostSystemLocale(): string | null {
41 if (typeof window === "undefined") return null;
42 return window.desktopBridge?.getSystemLocale() ?? null;
43}
44
45const timestampLocale = resolveTimestampLocale(readHostSystemLocale());
46
47const WEEKDAY_INDEXES = [0, 1, 2, 3, 4, 5, 6] as const;
48type WeekdayIndex = (typeof WEEKDAY_INDEXES)[number];
49
50type LocaleWithWeekInfo = Intl.Locale & {
51 readonly weekInfo?: { readonly firstDay: number };
52 getWeekInfo?: () => { readonly firstDay: number };
53};
54
55/**
56 * First weekday of a locale as a `Date#getDay` index (0 is Sunday), or
57 * `undefined` when the runtime has no week data, so callers keep their own
58 * default.
59 */
60function resolveWeekStartsOn(locale: string | undefined): WeekdayIndex | undefined {
61 try {
62 const resolved: LocaleWithWeekInfo = new Intl.Locale(
63 locale ?? Intl.DateTimeFormat().resolvedOptions().locale,
64 );
65 // Week info counts Monday as 1 and Sunday as 7.
66 const firstDay = resolved.getWeekInfo?.().firstDay ?? resolved.weekInfo?.firstDay;
67 return firstDay === undefined ? undefined : WEEKDAY_INDEXES[firstDay % 7];
68 } catch {
69 return undefined;
70 }
71}
72
73export const weekStartsOn = resolveWeekStartsOn(timestampLocale);
74
75// A formatter keeps the default zone it was built in, so default-zone formatters run in UTC
76// on the wall-clock time, which Date reads from the current zone.
77function wallClockAsUtc(date: Date): Date {
78 return new Date(date.getTime() - date.getTimezoneOffset() * 60_000);
79}
80
81const timestampFormatterCache = new Map<string, Intl.DateTimeFormat>();
82
83function getTimestampFormatter(
84 timestampFormat: TimestampFormat,
85 includeSeconds: boolean,
86 timeZone = "UTC",
87): Intl.DateTimeFormat {
88 const cacheKey = `${timestampFormat}:${includeSeconds ? "seconds" : "minutes"}:${timeZone}`;
89 const cachedFormatter = timestampFormatterCache.get(cacheKey);
90 if (cachedFormatter) {
91 return cachedFormatter;
92 }
93
94 const formatter = new Intl.DateTimeFormat(timestampLocale, {
95 ...getTimestampFormatOptions(timestampFormat, includeSeconds),
96 timeZone,
97 });
98 timestampFormatterCache.set(cacheKey, formatter);
99 return formatter;
100}
101
102function formatTime(date: Date, timestampFormat: TimestampFormat, timeZone?: string): string {
103 return timeZone
104 ? getTimestampFormatter(timestampFormat, false, timeZone).format(date)
105 : getTimestampFormatter(timestampFormat, false).format(wallClockAsUtc(date));
106}
107
108export function resolveHour12(timestampFormat: TimestampFormat): boolean {
109 return getTimestampFormatter(timestampFormat, false).resolvedOptions().hour12 ?? false;
110}
111
112export function parseTimestampDate(isoDate: string): Date | null {
113 const date = new Date(isoDate);
114 return Number.isNaN(date.getTime()) ? null : date;
115}
116
117// English keeps its ordinal day-before-month form; other UI languages use their own long date.
118const monthNameFormatter = new Intl.DateTimeFormat("en-US", { month: "long", timeZone: "UTC" });
119const longDateFormatterCache = new Map<string, Intl.DateTimeFormat>();
120
121function getLongDateFormatter(locale: string): Intl.DateTimeFormat {
122 let formatter = longDateFormatterCache.get(locale);
123 if (!formatter) {
124 formatter = new Intl.DateTimeFormat(locale, {
125 day: "numeric",
126 month: "long",
127 year: "numeric",
128 timeZone: "UTC",
129 });
130 longDateFormatterCache.set(locale, formatter);
131 }
132 return formatter;
133}
134
135function ordinalSuffix(day: number): string {
136 const lastTwo = day % 100;
137 if (lastTwo >= 11 && lastTwo <= 13) return "th";
138 switch (day % 10) {
139 case 1:
140 return "st";
141 case 2:
142 return "nd";
143 case 3:
144 return "rd";
145 default:
146 return "th";
147 }
148}
149
150export function formatChatTimestampTooltip(
151 isoDate: string,
152 timestampFormat: TimestampFormat,
153 resolve: MessageResolver = m,
154): string {
155 const date = parseTimestampDate(isoDate);
156 if (!date) return "";
157 const time = formatTime(date, timestampFormat);
158 const locale = getActiveLocale();
159 if (locale !== DEFAULT_LOCALE) {
160 const longDate = getLongDateFormatter(locale).format(wallClockAsUtc(date));
161 return resolve(
162 msg("{time}, {date}", { time, date: longDate, $context: "message time, then its date" }),
163 );
164 }
165 const day = date.getDate();
166 const month = monthNameFormatter.format(wallClockAsUtc(date));
167 const year = date.getFullYear();
168 return `${time}, ${day}${ordinalSuffix(day)} ${month} ${year}`;
169}
170
171export function formatFullTimestamp(isoDate: string, timestampFormat: TimestampFormat): string {
172 return new Date(isoDate).toLocaleString(
173 undefined,
174 timestampFormat === "locale" ? undefined : { hour12: timestampFormat === "12-hour" },
175 );
176}
177
178export function formatShortTimestamp(isoDate: string, timestampFormat: TimestampFormat): string {
179 const date = parseTimestampDate(isoDate);
180 if (!date) return "";
181 return formatTime(date, timestampFormat);
182}
183
184const dateTimeFormatterCache = new Map<TimestampFormat, Intl.DateTimeFormat>();
185
186export function formatDateTimeTimestamp(isoDate: string, timestampFormat: TimestampFormat): string {
187 const date = parseTimestampDate(isoDate);
188 if (!date) return "";
189 let formatter = dateTimeFormatterCache.get(timestampFormat);
190 if (!formatter) {
191 formatter = new Intl.DateTimeFormat(timestampLocale, {
192 dateStyle: "medium",
193 timeStyle: "short",
194 ...(timestampFormat === "locale" ? {} : { hour12: timestampFormat === "12-hour" }),
195 });
196 dateTimeFormatterCache.set(timestampFormat, formatter);
197 }
198 return formatter.format(date);
199}
200
201/** A wall-clock `H:MM` or `HH:MM` that names no date or zone, such as a daily schedule's time. */
202export function formatTimeOfDay(timeOfDay: string, timestampFormat: TimestampFormat): string {
203 const match = /^(\d{1,2}):(\d{2})$/.exec(timeOfDay);
204 if (!match) return timeOfDay;
205 // Default-zone formatters run in UTC, so the host zone cannot shift the wall time.
206 return getTimestampFormatter(timestampFormat, false).format(
207 Date.UTC(2000, 0, 1, Number(match[1]), Number(match[2])),
208 );
209}
210
211const numericDateOptions: Intl.DateTimeFormatOptions = { month: "numeric", day: "numeric" };
212const numericDateWithYearOptions: Intl.DateTimeFormatOptions = {
213 ...numericDateOptions,
214 year: "numeric",
215};
216const numericDateFormatter = new Intl.DateTimeFormat(timestampLocale, {
217 ...numericDateOptions,
218 timeZone: "UTC",
219});
220const numericDateWithYearFormatter = new Intl.DateTimeFormat(timestampLocale, {
221 ...numericDateWithYearOptions,
222 timeZone: "UTC",
223});
224
225interface CalendarDay {
226 year: number;
227 /** Days since the epoch, so differences are whole days across DST shifts. */
228 index: number;
229}
230
231function calendarDay(date: Date, timeZone: string | undefined): CalendarDay {
232 if (!timeZone) {
233 const year = date.getFullYear();
234 return { year, index: Date.UTC(year, date.getMonth(), date.getDate()) / 86_400_000 };
235 }
236 const parts = new Intl.DateTimeFormat("en-US", {
237 timeZone,
238 year: "numeric",
239 month: "numeric",
240 day: "numeric",
241 }).formatToParts(date);
242 const part = (type: Intl.DateTimeFormatPartTypes) =>
243 Number(parts.find((entry) => entry.type === type)?.value);
244 const year = part("year");
245 return { year, index: Date.UTC(year, part("month") - 1, part("day")) / 86_400_000 };
246}
247
248function formatNumericDate(date: Date, sameYear: boolean, timeZone: string | undefined): string {
249 if (!timeZone) {
250 return (sameYear ? numericDateFormatter : numericDateWithYearFormatter).format(
251 wallClockAsUtc(date),
252 );
253 }
254 return new Intl.DateTimeFormat(timestampLocale, {
255 ...(sameYear ? numericDateOptions : numericDateWithYearOptions),
256 timeZone,
257 }).format(date);
258}
259
260export function formatDayAwareTimestamp(
261 isoDate: string,
262 timestampFormat: TimestampFormat,
263 nowMs: number = Date.now(),
264 timeZone?: string,
265 resolve: MessageResolver = m,
266): string {
267 const date = parseTimestampDate(isoDate);
268 if (!date) return "";
269 const time = formatTime(date, timestampFormat, timeZone);
270
271 const today = calendarDay(new Date(nowMs), timeZone);
272 const messageDay = calendarDay(date, timeZone);
273 const dayDiff = today.index - messageDay.index;
274
275 if (dayDiff <= 0) return time;
276 if (dayDiff === 1) return resolve(msg("yesterday at {time}", { time }));
277 return `${formatNumericDate(date, messageDay.year === today.year, timeZone)} ${time}`;
278}
279
280/** `timeZone` overrides the system's current zone. */
281export function formatUpcomingTimestamp(
282 isoDate: string,
283 timestampFormat: TimestampFormat,
284 nowMs: number = Date.now(),
285 timeZone?: string,
286 resolve: MessageResolver = m,
287): string {
288 const date = parseTimestampDate(isoDate);
289 if (!date) return "";
290 const time = formatTime(date, timestampFormat, timeZone);
291
292 const today = calendarDay(new Date(nowMs), timeZone);
293 const targetDay = calendarDay(date, timeZone);
294 const dayDiff = targetDay.index - today.index;
295
296 if (dayDiff < 0) {
297 return formatDayAwareTimestamp(isoDate, timestampFormat, nowMs, timeZone, resolve);
298 }
299 if (dayDiff === 0) return time;
300 if (dayDiff === 1) return resolve(msg("tomorrow at {time}", { time }));
301 return `${formatNumericDate(date, targetDay.year === today.year, timeZone)} ${time}`;
302}
303
304/** `label` is the whole phrase ("5m ago"); `value` and `suffix` split it for styled layouts. */
305type RelativeTimeParts = { value: string; suffix: string | null; label: string };
306export type RelativeTimeState =
307 | { status: "missing" }
308 | { status: "invalid" }
309 | ({ status: "relative" } & RelativeTimeParts);
310
311const MINUTE_MS = 60_000;
312const HOUR_MS = 3_600_000;
313const DAY_MS = 86_400_000;
314
315function relativeTimeUnitMs(elapsedMs: number): number {
316 if (elapsedMs < HOUR_MS) return MINUTE_MS;
317 if (elapsedMs < DAY_MS) return HOUR_MS;
318 return DAY_MS;
319}
320
321/** Elapsed time floored to formatRelativeTime precision; equal labels yield equal values. */
322export function relativeTimeElapsedMs(isoDate: string, nowMs: number = Date.now()): number | null {
323 const date = parseTimestampDate(isoDate);
324 if (!date) return null;
325 const elapsedMs = Math.max(0, nowMs - date.getTime());
326 const unitMs = relativeTimeUnitMs(elapsedMs);
327 return Math.floor(elapsedMs / unitMs) * unitMs;
328}
329
330export function msUntilRelativeTimeChange(
331 isoDate: string,
332 nowMs: number = Date.now(),
333): number | null {
334 const date = parseTimestampDate(isoDate);
335 if (!date) return null;
336 const elapsedMs = Math.max(0, nowMs - date.getTime());
337 const unitMs = relativeTimeUnitMs(elapsedMs);
338 const nextChangeMs = date.getTime() + (Math.floor(elapsedMs / unitMs) + 1) * unitMs;
339 // Delays above 2^31-1 fire immediately; cap safely and let callers reschedule.
340 return Math.min(nextChangeMs - nowMs, DAY_MS);
341}
342
343const secondsLabel = (count: number, resolve: MessageResolver) =>
344 resolve(msg("{count}s", { count, $context: "seconds, abbreviated" }));
345const minutesLabel = (count: number, resolve: MessageResolver) =>
346 resolve(msg("{count}m", { count, $context: "minutes, abbreviated" }));
347const hoursLabel = (count: number, resolve: MessageResolver) =>
348 resolve(msg("{count}h", { count, $context: "hours, abbreviated" }));
349const daysLabel = (count: number, resolve: MessageResolver) =>
350 resolve(msg("{count}d", { count, $context: "days, abbreviated" }));
351
352function relativeElapsedLabel(elapsedMs: number, resolve: MessageResolver): string {
353 const seconds = Math.floor(elapsedMs / 1000);
354 if (seconds < 60) return resolve(msg("just now"));
355 const minutes = Math.floor(seconds / 60);
356 if (minutes < 60) return resolve(msg("{count}m ago", { count: minutes }));
357 const hours = Math.floor(minutes / 60);
358 if (hours < 24) return resolve(msg("{count}h ago", { count: hours }));
359 return resolve(msg("{count}d ago", { count: Math.floor(hours / 24) }));
360}
361
362export function formatRelativeElapsed(
363 elapsedMs: number,
364 resolve: MessageResolver = m,
365): RelativeTimeParts {
366 const label = relativeElapsedLabel(elapsedMs, resolve);
367 const seconds = Math.floor(elapsedMs / 1000);
368 if (seconds < 60) return { value: label, suffix: null, label };
369 const ago = resolve(msg("ago", { $context: "follows an elapsed time such as 5m" }));
370 const minutes = Math.floor(seconds / 60);
371 if (minutes < 60) return { value: minutesLabel(minutes, resolve), suffix: ago, label };
372 const hours = Math.floor(minutes / 60);
373 if (hours < 24) return { value: hoursLabel(hours, resolve), suffix: ago, label };
374 const days = Math.floor(hours / 24);
375 return { value: daysLabel(days, resolve), suffix: ago, label };
376}
377
378export function formatRelativeTime(
379 isoDate: string,
380 nowMs: number = Date.now(),
381 resolve: MessageResolver = m,
382): RelativeTimeParts | null {
383 const elapsedMs = relativeTimeElapsedMs(isoDate, nowMs);
384 return elapsedMs === null ? null : formatRelativeElapsed(elapsedMs, resolve);
385}
386
387export function formatRelativeTimeLabel(
388 isoDate: string,
389 nowMs: number = Date.now(),
390 resolve: MessageResolver = m,
391) {
392 const elapsedMs = relativeTimeElapsedMs(isoDate, nowMs);
393 return elapsedMs === null ? "" : relativeElapsedLabel(elapsedMs, resolve);
394}
395
396export function formatElapsedDurationLabel(
397 isoDate: string,
398 nowMs: number = Date.now(),
399 resolve: MessageResolver = m,
400): string {
401 const date = parseTimestampDate(isoDate);
402 if (!date) return "";
403 const diffMs = nowMs - date.getTime();
404 if (diffMs <= 0) return resolve(msg("just now"));
405
406 const seconds = Math.floor(diffMs / 1000);
407 if (seconds < 5) return resolve(msg("just now"));
408 if (seconds < 60) return secondsLabel(seconds, resolve);
409
410 const minutes = Math.floor(seconds / 60);
411 if (minutes < 60) return minutesLabel(minutes, resolve);
412
413 const hours = Math.floor(minutes / 60);
414 if (hours < 24) return hoursLabel(hours, resolve);
415
416 const days = Math.floor(hours / 24);
417 return daysLabel(days, resolve);
418}
419
420/** Pass nowMs to match a parent-driven render tick. */
421export function formatExpiresInLabel(
422 isoDate: string,
423 nowMs: number = Date.now(),
424 resolve: MessageResolver = m,
425): string {
426 const date = parseTimestampDate(isoDate);
427 if (!date) return "";
428 const diffMs = date.getTime() - nowMs;
429 if (diffMs <= 0) return resolve(msg("Expired"));
430
431 const totalSeconds = Math.floor(diffMs / 1000);
432 if (totalSeconds < 5) return resolve(msg("Expires in a moment"));
433 const expiresIn = (parts: string[]) =>
434 resolve(msg("Expires in {duration}", { duration: parts.join(" ") }));
435 if (totalSeconds < 60) return expiresIn([secondsLabel(totalSeconds, resolve)]);
436
437 if (totalSeconds < 3600) {
438 const minutes = Math.floor(totalSeconds / 60);
439 const seconds = totalSeconds % 60;
440 return seconds === 0
441 ? expiresIn([minutesLabel(minutes, resolve)])
442 : expiresIn([minutesLabel(minutes, resolve), secondsLabel(seconds, resolve)]);
443 }
444
445 if (totalSeconds < 86_400) {
446 const hours = Math.floor(totalSeconds / 3600);
447 const rem = totalSeconds % 3600;
448 const minutes = Math.floor(rem / 60);
449 const seconds = rem % 60;
450 const parts = [hoursLabel(hours, resolve)];
451 if (minutes > 0) parts.push(minutesLabel(minutes, resolve));
452 if (seconds > 0) parts.push(secondsLabel(seconds, resolve));
453 return expiresIn(parts);
454 }
455
456 const days = Math.floor(totalSeconds / 86_400);
457 const remAfterDays = totalSeconds % 86_400;
458 if (remAfterDays === 0) return expiresIn([daysLabel(days, resolve)]);
459 const hours = Math.floor(remAfterDays / 3600);
460 const rem = remAfterDays % 3600;
461 const minutes = Math.floor(rem / 60);
462 const seconds = rem % 60;
463 const parts = [daysLabel(days, resolve)];
464 if (hours > 0) parts.push(hoursLabel(hours, resolve));
465 if (minutes > 0) parts.push(minutesLabel(minutes, resolve));
466 if (seconds > 0) parts.push(secondsLabel(seconds, resolve));
467 return expiresIn(parts);
468}