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