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
23function resolveTimestampLocale(systemLocale: string | null | undefined): string | undefined {
24 const tag = systemLocale?.trim();
25 if (!tag) return undefined;
26
27 try {
28 // Reject structurally invalid tags; let ICU fall back for valid tags it lacks data for.
29 Intl.DateTimeFormat.supportedLocalesOf([tag]);
30 return tag;
31 } catch {
32 return undefined;
33 }
34}
35
36function readHostSystemLocale(): string | null {
37 if (typeof window === "undefined") return null;
38 return window.desktopBridge?.getSystemLocale() ?? null;
39}
40
41const timestampLocale = resolveTimestampLocale(readHostSystemLocale());
42
43const WEEKDAY_INDEXES = [0, 1, 2, 3, 4, 5, 6] as const;
44type WeekdayIndex = (typeof WEEKDAY_INDEXES)[number];
45
46type LocaleWithWeekInfo = Intl.Locale & {
47 readonly weekInfo?: { readonly firstDay: number };
48 getWeekInfo?: () => { readonly firstDay: number };
49};
50
51/**
52 * First weekday of a locale as a `Date#getDay` index (0 is Sunday), or
53 * `undefined` when the runtime has no week data, so callers keep their own
54 * default.
55 */
56function resolveWeekStartsOn(locale: string | undefined): WeekdayIndex | undefined {
57 try {
58 const resolved: LocaleWithWeekInfo = new Intl.Locale(
59 locale ?? Intl.DateTimeFormat().resolvedOptions().locale,
60 );
61 // Week info counts Monday as 1 and Sunday as 7.
62 const firstDay = resolved.getWeekInfo?.().firstDay ?? resolved.weekInfo?.firstDay;
63 return firstDay === undefined ? undefined : WEEKDAY_INDEXES[firstDay % 7];
64 } catch {
65 return undefined;
66 }
67}
68
69export const weekStartsOn = resolveWeekStartsOn(timestampLocale);
70
71// A formatter keeps the default zone it was built in, so default-zone formatters run in UTC
72// on the wall-clock time, which Date reads from the current zone.
73function wallClockAsUtc(date: Date): Date {
74 return new Date(date.getTime() - date.getTimezoneOffset() * 60_000);
75}
76
77const timestampFormatterCache = new Map<string, Intl.DateTimeFormat>();
78
79function getTimestampFormatter(
80 timestampFormat: TimestampFormat,
81 includeSeconds: boolean,
82 timeZone = "UTC",
83): Intl.DateTimeFormat {
84 const cacheKey = `${timestampFormat}:${includeSeconds ? "seconds" : "minutes"}:${timeZone}`;
85 const cachedFormatter = timestampFormatterCache.get(cacheKey);
86 if (cachedFormatter) {
87 return cachedFormatter;
88 }
89
90 const formatter = new Intl.DateTimeFormat(timestampLocale, {
91 ...getTimestampFormatOptions(timestampFormat, includeSeconds),
92 timeZone,
93 });
94 timestampFormatterCache.set(cacheKey, formatter);
95 return formatter;
96}
97
98function formatTime(date: Date, timestampFormat: TimestampFormat, timeZone?: string): string {
99 return timeZone
100 ? getTimestampFormatter(timestampFormat, false, timeZone).format(date)
101 : getTimestampFormatter(timestampFormat, false).format(wallClockAsUtc(date));
102}
103
104export function resolveHour12(timestampFormat: TimestampFormat): boolean {
105 return getTimestampFormatter(timestampFormat, false).resolvedOptions().hour12 ?? false;
106}
107
108export function parseTimestampDate(isoDate: string): Date | null {
109 const date = new Date(isoDate);
110 return Number.isNaN(date.getTime()) ? null : date;
111}
112
113// Deliberately not the host locale: the tooltip's ordinal suffix and
114// day-before-month order below are English, so a localized month alone would
115// read "4th Juni 2026".
116const monthNameFormatter = new Intl.DateTimeFormat("en-US", { month: "long", timeZone: "UTC" });
117
118function ordinalSuffix(day: number): string {
119 const lastTwo = day % 100;
120 if (lastTwo >= 11 && lastTwo <= 13) return "th";
121 switch (day % 10) {
122 case 1:
123 return "st";
124 case 2:
125 return "nd";
126 case 3:
127 return "rd";
128 default:
129 return "th";
130 }
131}
132
133export function formatChatTimestampTooltip(
134 isoDate: string,
135 timestampFormat: TimestampFormat,
136): string {
137 const date = parseTimestampDate(isoDate);
138 if (!date) return "";
139 const time = formatTime(date, timestampFormat);
140 const day = date.getDate();
141 const month = monthNameFormatter.format(wallClockAsUtc(date));
142 const year = date.getFullYear();
143 return `${time}, ${day}${ordinalSuffix(day)} ${month} ${year}`;
144}
145
146export function formatFullTimestamp(isoDate: string, timestampFormat: TimestampFormat): string {
147 return new Date(isoDate).toLocaleString(
148 undefined,
149 timestampFormat === "locale" ? undefined : { hour12: timestampFormat === "12-hour" },
150 );
151}
152
153export function formatShortTimestamp(isoDate: string, timestampFormat: TimestampFormat): string {
154 const date = parseTimestampDate(isoDate);
155 if (!date) return "";
156 return formatTime(date, timestampFormat);
157}
158
159const numericDateOptions: Intl.DateTimeFormatOptions = { month: "numeric", day: "numeric" };
160const numericDateWithYearOptions: Intl.DateTimeFormatOptions = {
161 ...numericDateOptions,
162 year: "numeric",
163};
164const numericDateFormatter = new Intl.DateTimeFormat(timestampLocale, {
165 ...numericDateOptions,
166 timeZone: "UTC",
167});
168const numericDateWithYearFormatter = new Intl.DateTimeFormat(timestampLocale, {
169 ...numericDateWithYearOptions,
170 timeZone: "UTC",
171});
172
173interface CalendarDay {
174 year: number;
175 /** Days since the epoch, so differences are whole days across DST shifts. */
176 index: number;
177}
178
179function calendarDay(date: Date, timeZone: string | undefined): CalendarDay {
180 if (!timeZone) {
181 const year = date.getFullYear();
182 return { year, index: Date.UTC(year, date.getMonth(), date.getDate()) / 86_400_000 };
183 }
184 const parts = new Intl.DateTimeFormat("en-US", {
185 timeZone,
186 year: "numeric",
187 month: "numeric",
188 day: "numeric",
189 }).formatToParts(date);
190 const part = (type: Intl.DateTimeFormatPartTypes) =>
191 Number(parts.find((entry) => entry.type === type)?.value);
192 const year = part("year");
193 return { year, index: Date.UTC(year, part("month") - 1, part("day")) / 86_400_000 };
194}
195
196function formatNumericDate(date: Date, sameYear: boolean, timeZone: string | undefined): string {
197 if (!timeZone) {
198 return (sameYear ? numericDateFormatter : numericDateWithYearFormatter).format(
199 wallClockAsUtc(date),
200 );
201 }
202 return new Intl.DateTimeFormat(timestampLocale, {
203 ...(sameYear ? numericDateOptions : numericDateWithYearOptions),
204 timeZone,
205 }).format(date);
206}
207
208export function formatDayAwareTimestamp(
209 isoDate: string,
210 timestampFormat: TimestampFormat,
211 nowMs: number = Date.now(),
212 timeZone?: string,
213): string {
214 const date = parseTimestampDate(isoDate);
215 if (!date) return "";
216 const time = formatTime(date, timestampFormat, timeZone);
217
218 const today = calendarDay(new Date(nowMs), timeZone);
219 const messageDay = calendarDay(date, timeZone);
220 const dayDiff = today.index - messageDay.index;
221
222 if (dayDiff <= 0) return time;
223 if (dayDiff === 1) return `yesterday at ${time}`;
224 return `${formatNumericDate(date, messageDay.year === today.year, timeZone)} ${time}`;
225}
226
227/** `timeZone` overrides the system's current zone. */
228export function formatUpcomingTimestamp(
229 isoDate: string,
230 timestampFormat: TimestampFormat,
231 nowMs: number = Date.now(),
232 timeZone?: string,
233): string {
234 const date = parseTimestampDate(isoDate);
235 if (!date) return "";
236 const time = formatTime(date, timestampFormat, timeZone);
237
238 const today = calendarDay(new Date(nowMs), timeZone);
239 const targetDay = calendarDay(date, timeZone);
240 const dayDiff = targetDay.index - today.index;
241
242 if (dayDiff < 0) return formatDayAwareTimestamp(isoDate, timestampFormat, nowMs, timeZone);
243 if (dayDiff === 0) return time;
244 if (dayDiff === 1) return `tomorrow at ${time}`;
245 return `${formatNumericDate(date, targetDay.year === today.year, timeZone)} ${time}`;
246}
247
248type RelativeTimeParts = { value: string; suffix: string | null };
249export type RelativeTimeState =
250 | { status: "missing" }
251 | { status: "invalid" }
252 | { status: "relative"; value: string; suffix: string | null };
253
254const MINUTE_MS = 60_000;
255const HOUR_MS = 3_600_000;
256const DAY_MS = 86_400_000;
257
258function relativeTimeUnitMs(elapsedMs: number): number {
259 if (elapsedMs < HOUR_MS) return MINUTE_MS;
260 if (elapsedMs < DAY_MS) return HOUR_MS;
261 return DAY_MS;
262}
263
264/** Elapsed time floored to formatRelativeTime precision; equal labels yield equal values. */
265export function relativeTimeElapsedMs(isoDate: string, nowMs: number = Date.now()): number | null {
266 const date = parseTimestampDate(isoDate);
267 if (!date) return null;
268 const elapsedMs = Math.max(0, nowMs - date.getTime());
269 const unitMs = relativeTimeUnitMs(elapsedMs);
270 return Math.floor(elapsedMs / unitMs) * unitMs;
271}
272
273export function msUntilRelativeTimeChange(
274 isoDate: string,
275 nowMs: number = Date.now(),
276): number | null {
277 const date = parseTimestampDate(isoDate);
278 if (!date) return null;
279 const elapsedMs = Math.max(0, nowMs - date.getTime());
280 const unitMs = relativeTimeUnitMs(elapsedMs);
281 const nextChangeMs = date.getTime() + (Math.floor(elapsedMs / unitMs) + 1) * unitMs;
282 // Delays above 2^31-1 fire immediately; cap safely and let callers reschedule.
283 return Math.min(nextChangeMs - nowMs, DAY_MS);
284}
285
286export function formatRelativeElapsed(elapsedMs: number): RelativeTimeParts {
287 const seconds = Math.floor(elapsedMs / 1000);
288 if (seconds < 60) return { value: "just now", suffix: null };
289 const minutes = Math.floor(seconds / 60);
290 if (minutes < 60) return { value: `${minutes}m`, suffix: "ago" };
291 const hours = Math.floor(minutes / 60);
292 if (hours < 24) return { value: `${hours}h`, suffix: "ago" };
293 const days = Math.floor(hours / 24);
294 return { value: `${days}d`, suffix: "ago" };
295}
296
297export function formatRelativeTime(
298 isoDate: string,
299 nowMs: number = Date.now(),
300): RelativeTimeParts | null {
301 const elapsedMs = relativeTimeElapsedMs(isoDate, nowMs);
302 return elapsedMs === null ? null : formatRelativeElapsed(elapsedMs);
303}
304
305export function formatRelativeTimeLabel(isoDate: string, nowMs: number = Date.now()) {
306 const relative = formatRelativeTime(isoDate, nowMs);
307 if (!relative) return "";
308 return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
309}
310
311export function formatElapsedDurationLabel(isoDate: string, nowMs: number = Date.now()): string {
312 const date = parseTimestampDate(isoDate);
313 if (!date) return "";
314 const diffMs = nowMs - date.getTime();
315 if (diffMs <= 0) return "just now";
316
317 const seconds = Math.floor(diffMs / 1000);
318 if (seconds < 5) return "just now";
319 if (seconds < 60) return `${seconds}s`;
320
321 const minutes = Math.floor(seconds / 60);
322 if (minutes < 60) return `${minutes}m`;
323
324 const hours = Math.floor(minutes / 60);
325 if (hours < 24) return `${hours}h`;
326
327 const days = Math.floor(hours / 24);
328 return `${days}d`;
329}
330
331/** Pass nowMs to match a parent-driven render tick. */
332export function formatExpiresInLabel(isoDate: string, nowMs: number = Date.now()): string {
333 const date = parseTimestampDate(isoDate);
334 if (!date) return "";
335 const diffMs = date.getTime() - nowMs;
336 if (diffMs <= 0) return "Expired";
337
338 const totalSeconds = Math.floor(diffMs / 1000);
339 if (totalSeconds < 5) return "Expires in a moment";
340 if (totalSeconds < 60) return `Expires in ${totalSeconds}s`;
341
342 if (totalSeconds < 3600) {
343 const minutes = Math.floor(totalSeconds / 60);
344 const seconds = totalSeconds % 60;
345 return seconds === 0 ? `Expires in ${minutes}m` : `Expires in ${minutes}m ${seconds}s`;
346 }
347
348 if (totalSeconds < 86_400) {
349 const hours = Math.floor(totalSeconds / 3600);
350 const rem = totalSeconds % 3600;
351 const minutes = Math.floor(rem / 60);
352 const seconds = rem % 60;
353 const parts = [`${hours}h`];
354 if (minutes > 0) parts.push(`${minutes}m`);
355 if (seconds > 0) parts.push(`${seconds}s`);
356 return `Expires in ${parts.join(" ")}`;
357 }
358
359 const days = Math.floor(totalSeconds / 86_400);
360 const remAfterDays = totalSeconds % 86_400;
361 if (remAfterDays === 0) return `Expires in ${days}d`;
362 const hours = Math.floor(remAfterDays / 3600);
363 const rem = remAfterDays % 3600;
364 const minutes = Math.floor(rem / 60);
365 const seconds = rem % 60;
366 const tail: string[] = [];
367 if (hours > 0) tail.push(`${hours}h`);
368 if (minutes > 0) tail.push(`${minutes}m`);
369 if (seconds > 0) tail.push(`${seconds}s`);
370 return tail.length > 0 ? `Expires in ${days}d ${tail.join(" ")}` : `Expires in ${days}d`;
371}