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 parseTimestampDate(isoDate: string): Date | null {
97 const date = new Date(isoDate);
98 return Number.isNaN(date.getTime()) ? null : date;
99}
100
101export function formatTimestamp(isoDate: string, timestampFormat: TimestampFormat): string {
102 const date = parseTimestampDate(isoDate);
103 if (!date) return "";
104 return getTimestampFormatter(timestampFormat, true).format(date);
105}
106
107// Deliberately not the host locale: the tooltip's ordinal suffix and
108// day-before-month order below are English, so a localized month alone would
109// read "4th Juni 2026".
110const monthNameFormatter = new Intl.DateTimeFormat("en-US", { month: "long" });
111
112function ordinalSuffix(day: number): string {
113 const lastTwo = day % 100;
114 if (lastTwo >= 11 && lastTwo <= 13) return "th";
115 switch (day % 10) {
116 case 1:
117 return "st";
118 case 2:
119 return "nd";
120 case 3:
121 return "rd";
122 default:
123 return "th";
124 }
125}
126
127export function formatChatTimestampTooltip(
128 isoDate: string,
129 timestampFormat: TimestampFormat,
130): string {
131 const date = parseTimestampDate(isoDate);
132 if (!date) return "";
133 const time = formatShortTimestamp(isoDate, timestampFormat);
134 const day = date.getDate();
135 const month = monthNameFormatter.format(date);
136 const year = date.getFullYear();
137 return `${time}, ${day}${ordinalSuffix(day)} ${month} ${year}`;
138}
139
140export function formatShortTimestamp(isoDate: string, timestampFormat: TimestampFormat): string {
141 const date = parseTimestampDate(isoDate);
142 if (!date) return "";
143 return getTimestampFormatter(timestampFormat, false).format(date);
144}
145
146const numericDateFormatter = new Intl.DateTimeFormat(timestampLocale, {
147 month: "numeric",
148 day: "numeric",
149});
150const numericDateWithYearFormatter = new Intl.DateTimeFormat(timestampLocale, {
151 month: "numeric",
152 day: "numeric",
153 year: "numeric",
154});
155
156export function formatDayAwareTimestamp(
157 isoDate: string,
158 timestampFormat: TimestampFormat,
159 nowMs: number = Date.now(),
160): string {
161 const date = parseTimestampDate(isoDate);
162 if (!date) return "";
163 const time = getTimestampFormatter(timestampFormat, false).format(date);
164
165 const now = new Date(nowMs);
166 const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
167 const startOfMessageDay = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
168 // Round so DST-shifted 23/25 hour days still count as whole days.
169 const dayDiff = Math.round((startOfToday - startOfMessageDay) / 86_400_000);
170
171 if (dayDiff <= 0) return time;
172 if (dayDiff === 1) return `yesterday at ${time}`;
173 const dateFormatter =
174 date.getFullYear() === now.getFullYear() ? numericDateFormatter : numericDateWithYearFormatter;
175 return `${dateFormatter.format(date)} ${time}`;
176}
177
178export function formatUpcomingTimestamp(
179 isoDate: string,
180 timestampFormat: TimestampFormat,
181 nowMs: number = Date.now(),
182): string {
183 const date = parseTimestampDate(isoDate);
184 if (!date) return "";
185 const time = getTimestampFormatter(timestampFormat, false).format(date);
186
187 const now = new Date(nowMs);
188 const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
189 const startOfTargetDay = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
190 const dayDiff = Math.round((startOfTargetDay - startOfToday) / 86_400_000);
191
192 if (dayDiff < 0) return formatDayAwareTimestamp(isoDate, timestampFormat, nowMs);
193 if (dayDiff === 0) return time;
194 if (dayDiff === 1) return `tomorrow at ${time}`;
195 const dateFormatter =
196 date.getFullYear() === now.getFullYear() ? numericDateFormatter : numericDateWithYearFormatter;
197 return `${dateFormatter.format(date)} ${time}`;
198}
199
200type RelativeTimeParts = { value: string; suffix: string | null };
201export type RelativeTimeState =
202 | { status: "missing" }
203 | { status: "invalid" }
204 | { status: "relative"; value: string; suffix: string | null };
205
206const MINUTE_MS = 60_000;
207const HOUR_MS = 3_600_000;
208const DAY_MS = 86_400_000;
209
210function relativeTimeUnitMs(elapsedMs: number): number {
211 if (elapsedMs < HOUR_MS) return MINUTE_MS;
212 if (elapsedMs < DAY_MS) return HOUR_MS;
213 return DAY_MS;
214}
215
216/**
217 * Elapsed time floored to the precision `formatRelativeTime` shows, so two
218 * instants with the same label return the same number.
219 */
220export function relativeTimeElapsedMs(isoDate: string, nowMs: number = Date.now()): number | null {
221 const date = parseTimestampDate(isoDate);
222 if (!date) return null;
223 const elapsedMs = Math.max(0, nowMs - date.getTime());
224 const unitMs = relativeTimeUnitMs(elapsedMs);
225 return Math.floor(elapsedMs / unitMs) * unitMs;
226}
227
228/** Milliseconds until the `formatRelativeTime` label for `isoDate` next changes. */
229export function msUntilRelativeTimeChange(
230 isoDate: string,
231 nowMs: number = Date.now(),
232): number | null {
233 const date = parseTimestampDate(isoDate);
234 if (!date) return null;
235 const elapsedMs = Math.max(0, nowMs - date.getTime());
236 const unitMs = relativeTimeUnitMs(elapsedMs);
237 const nextChangeMs = date.getTime() + (Math.floor(elapsedMs / unitMs) + 1) * unitMs;
238 // setTimeout fires at once past 2^31-1 ms, which would loop on a far-future
239 // timestamp. Waking early is harmless: the caller re-reads and re-schedules.
240 return Math.min(nextChangeMs - nowMs, DAY_MS);
241}
242
243export function formatRelativeElapsed(elapsedMs: number): RelativeTimeParts {
244 const seconds = Math.floor(elapsedMs / 1000);
245 if (seconds < 60) return { value: "just now", suffix: null };
246 const minutes = Math.floor(seconds / 60);
247 if (minutes < 60) return { value: `${minutes}m`, suffix: "ago" };
248 const hours = Math.floor(minutes / 60);
249 if (hours < 24) return { value: `${hours}h`, suffix: "ago" };
250 const days = Math.floor(hours / 24);
251 return { value: `${days}d`, suffix: "ago" };
252}
253
254export function formatRelativeTime(
255 isoDate: string,
256 nowMs: number = Date.now(),
257): RelativeTimeParts | null {
258 const elapsedMs = relativeTimeElapsedMs(isoDate, nowMs);
259 return elapsedMs === null ? null : formatRelativeElapsed(elapsedMs);
260}
261
262export function formatRelativeTimeLabel(isoDate: string, nowMs: number = Date.now()) {
263 const relative = formatRelativeTime(isoDate, nowMs);
264 if (!relative) return "";
265 return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
266}
267
268export function formatElapsedDurationLabel(isoDate: string, nowMs: number = Date.now()): string {
269 const date = parseTimestampDate(isoDate);
270 if (!date) return "";
271 const diffMs = nowMs - date.getTime();
272 if (diffMs <= 0) return "just now";
273
274 const seconds = Math.floor(diffMs / 1000);
275 if (seconds < 5) return "just now";
276 if (seconds < 60) return `${seconds}s`;
277
278 const minutes = Math.floor(seconds / 60);
279 if (minutes < 60) return `${minutes}m`;
280
281 const hours = Math.floor(minutes / 60);
282 if (hours < 24) return `${hours}h`;
283
284 const days = Math.floor(hours / 24);
285 return `${days}d`;
286}
287
288export function formatRelativeTimeUntil(isoDate: string): RelativeTimeParts | null {
289 const date = parseTimestampDate(isoDate);
290 if (!date) return null;
291 const diffMs = date.getTime() - Date.now();
292 if (diffMs <= 0) return { value: "Expired", suffix: null };
293 const seconds = Math.floor(diffMs / 1000);
294 if (seconds < 5) return { value: "Soon", suffix: null };
295 if (seconds < 60) return { value: `${seconds}s`, suffix: "left" };
296 const minutes = Math.floor(seconds / 60);
297 if (minutes < 60) return { value: `${minutes}m`, suffix: "left" };
298 const hours = Math.floor(minutes / 60);
299 if (hours < 24) return { value: `${hours}h`, suffix: "left" };
300 const days = Math.floor(hours / 24);
301 return { value: `${days}d`, suffix: "left" };
302}
303
304export function formatRelativeTimeUntilLabel(isoDate: string): string {
305 const relative = formatRelativeTimeUntil(isoDate);
306 if (!relative) return "";
307 return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
308}
309
310/**
311 * Pass `nowMs` when a parent tick drives re-renders so the diff matches that snapshot.
312 */
313export function formatExpiresInLabel(isoDate: string, nowMs: number = Date.now()): string {
314 const date = parseTimestampDate(isoDate);
315 if (!date) return "";
316 const diffMs = date.getTime() - nowMs;
317 if (diffMs <= 0) return "Expired";
318
319 const totalSeconds = Math.floor(diffMs / 1000);
320 if (totalSeconds < 5) return "Expires in a moment";
321 if (totalSeconds < 60) return `Expires in ${totalSeconds}s`;
322
323 if (totalSeconds < 3600) {
324 const minutes = Math.floor(totalSeconds / 60);
325 const seconds = totalSeconds % 60;
326 return seconds === 0 ? `Expires in ${minutes}m` : `Expires in ${minutes}m ${seconds}s`;
327 }
328
329 if (totalSeconds < 86_400) {
330 const hours = Math.floor(totalSeconds / 3600);
331 const rem = totalSeconds % 3600;
332 const minutes = Math.floor(rem / 60);
333 const seconds = rem % 60;
334 const parts = [`${hours}h`];
335 if (minutes > 0) parts.push(`${minutes}m`);
336 if (seconds > 0) parts.push(`${seconds}s`);
337 return `Expires in ${parts.join(" ")}`;
338 }
339
340 const days = Math.floor(totalSeconds / 86_400);
341 const remAfterDays = totalSeconds % 86_400;
342 if (remAfterDays === 0) return `Expires in ${days}d`;
343 const hours = Math.floor(remAfterDays / 3600);
344 const rem = remAfterDays % 3600;
345 const minutes = Math.floor(rem / 60);
346 const seconds = rem % 60;
347 const tail: string[] = [];
348 if (hours > 0) tail.push(`${hours}h`);
349 if (minutes > 0) tail.push(`${minutes}m`);
350 if (seconds > 0) tail.push(`${seconds}s`);
351 return tail.length > 0 ? `Expires in ${days}d ${tail.join(" ")}` : `Expires in ${days}d`;
352}