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
23/**
24 * Pick the locale to format wall-clock times in, given the locale the host
25 * reports. Hosts that report nothing fall back to `undefined`, which is the
26 * runtime default and the right answer in a browser.
27 *
28 * A host reports a locale only when it knows better than the runtime does —
29 * see `getSystemLocale` on the desktop bridge for why desktop does.
30 */
31export function resolveTimestampLocale(
32 systemLocale: string | null | undefined,
33): string | undefined {
34 const tag = systemLocale?.trim();
35 if (!tag) return undefined;
36
37 try {
38 // Every timestamp in the UI runs through this formatter, so a tag the host
39 // could not normalize falls back rather than throwing. Throws on a
40 // structurally invalid tag; a well-formed tag ICU has no data for resolves
41 // here and is left to ICU's own fallback.
42 Intl.DateTimeFormat.supportedLocalesOf([tag]);
43 return tag;
44 } catch {
45 return undefined;
46 }
47}
48
49function readHostSystemLocale(): string | null {
50 if (typeof window === "undefined") return null;
51 return window.desktopBridge?.getSystemLocale?.() ?? null;
52}
53
54const timestampLocale = resolveTimestampLocale(readHostSystemLocale());
55
56const timestampFormatterCache = new Map<string, Intl.DateTimeFormat>();
57
58function getTimestampFormatter(
59 timestampFormat: TimestampFormat,
60 includeSeconds: boolean,
61): Intl.DateTimeFormat {
62 const cacheKey = `${timestampFormat}:${includeSeconds ? "seconds" : "minutes"}`;
63 const cachedFormatter = timestampFormatterCache.get(cacheKey);
64 if (cachedFormatter) {
65 return cachedFormatter;
66 }
67
68 const formatter = new Intl.DateTimeFormat(
69 timestampLocale,
70 getTimestampFormatOptions(timestampFormat, includeSeconds),
71 );
72 timestampFormatterCache.set(cacheKey, formatter);
73 return formatter;
74}
75
76export function parseTimestampDate(isoDate: string): Date | null {
77 const date = new Date(isoDate);
78 return Number.isNaN(date.getTime()) ? null : date;
79}
80
81export function formatTimestamp(isoDate: string, timestampFormat: TimestampFormat): string {
82 const date = parseTimestampDate(isoDate);
83 if (!date) return "";
84 return getTimestampFormatter(timestampFormat, true).format(date);
85}
86
87// Deliberately not the host locale: the tooltip's ordinal suffix and
88// day-before-month order below are English, so a localized month alone would
89// read "4th Juni 2026". Localizing the whole label is a separate change.
90const monthNameFormatter = new Intl.DateTimeFormat("en-US", { month: "long" });
91
92function ordinalSuffix(day: number): string {
93 const lastTwo = day % 100;
94 if (lastTwo >= 11 && lastTwo <= 13) return "th";
95 switch (day % 10) {
96 case 1:
97 return "st";
98 case 2:
99 return "nd";
100 case 3:
101 return "rd";
102 default:
103 return "th";
104 }
105}
106
107/**
108 * Long-form tooltip label, e.g. `12:04, 4th June`.
109 * Renders the wall-clock time without seconds followed by the ordinal day and month name.
110 */
111export function formatChatTimestampTooltip(
112 isoDate: string,
113 timestampFormat: TimestampFormat,
114): string {
115 const date = parseTimestampDate(isoDate);
116 if (!date) return "";
117 const time = formatShortTimestamp(isoDate, timestampFormat);
118 const day = date.getDate();
119 const month = monthNameFormatter.format(date);
120 const year = date.getFullYear();
121 return `${time}, ${day}${ordinalSuffix(day)} ${month} ${year}`;
122}
123
124export function formatShortTimestamp(isoDate: string, timestampFormat: TimestampFormat): string {
125 const date = parseTimestampDate(isoDate);
126 if (!date) return "";
127 return getTimestampFormatter(timestampFormat, false).format(date);
128}
129
130const numericDateFormatter = new Intl.DateTimeFormat(timestampLocale, {
131 month: "numeric",
132 day: "numeric",
133});
134const numericDateWithYearFormatter = new Intl.DateTimeFormat(timestampLocale, {
135 month: "numeric",
136 day: "numeric",
137 year: "numeric",
138});
139
140/**
141 * Chat timestamp that adds the date once the message is no longer from today:
142 * today `12:34 PM`, yesterday `yesterday at 12:34 PM`, older `8/13 12:34 PM`
143 * (locale digit order), with the year included once the calendar year differs.
144 * Boundaries are local calendar days, not 24-hour windows.
145 */
146export function formatDayAwareTimestamp(
147 isoDate: string,
148 timestampFormat: TimestampFormat,
149 nowMs: number = Date.now(),
150): string {
151 const date = parseTimestampDate(isoDate);
152 if (!date) return "";
153 const time = getTimestampFormatter(timestampFormat, false).format(date);
154
155 const now = new Date(nowMs);
156 const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
157 const startOfMessageDay = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
158 // Round so DST-shifted 23/25 hour days still count as whole days.
159 const dayDiff = Math.round((startOfToday - startOfMessageDay) / 86_400_000);
160
161 if (dayDiff <= 0) return time;
162 if (dayDiff === 1) return `yesterday at ${time}`;
163 const dateFormatter =
164 date.getFullYear() === now.getFullYear() ? numericDateFormatter : numericDateWithYearFormatter;
165 return `${dateFormatter.format(date)} ${time}`;
166}
167
168/**
169 * The forward-looking counterpart of {@link formatDayAwareTimestamp} for an
170 * instant that has not happened yet (a usage-limit reset): today `12:34 PM`,
171 * tomorrow `tomorrow at 12:34 PM`, later `8/13 12:34 PM`.
172 */
173export function formatUpcomingTimestamp(
174 isoDate: string,
175 timestampFormat: TimestampFormat,
176 nowMs: number = Date.now(),
177): string {
178 const date = parseTimestampDate(isoDate);
179 if (!date) return "";
180 const time = getTimestampFormatter(timestampFormat, false).format(date);
181
182 const now = new Date(nowMs);
183 const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
184 const startOfTargetDay = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
185 const dayDiff = Math.round((startOfTargetDay - startOfToday) / 86_400_000);
186
187 if (dayDiff < 0) return formatDayAwareTimestamp(isoDate, timestampFormat, nowMs);
188 if (dayDiff === 0) return time;
189 if (dayDiff === 1) return `tomorrow at ${time}`;
190 const dateFormatter =
191 date.getFullYear() === now.getFullYear() ? numericDateFormatter : numericDateWithYearFormatter;
192 return `${dateFormatter.format(date)} ${time}`;
193}
194
195/**
196 * Format a relative time string from an ISO date.
197 * Returns `{ value: "20s", suffix: "ago" }` or `{ value: "just now", suffix: null }`
198 * so callers can style the numeric portion independently.
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
206export function formatRelativeTime(isoDate: string): RelativeTimeParts | null {
207 const date = parseTimestampDate(isoDate);
208 if (!date) return null;
209 const diffMs = Date.now() - date.getTime();
210 if (diffMs < 0) return { value: "just now", suffix: null };
211 const seconds = Math.floor(diffMs / 1000);
212 if (seconds < 60) return { value: "just now", suffix: null };
213 const minutes = Math.floor(seconds / 60);
214 if (minutes < 60) return { value: `${minutes}m`, suffix: "ago" };
215 const hours = Math.floor(minutes / 60);
216 if (hours < 24) return { value: `${hours}h`, suffix: "ago" };
217 const days = Math.floor(hours / 24);
218 return { value: `${days}d`, suffix: "ago" };
219}
220
221export function formatRelativeTimeLabel(isoDate: string) {
222 const relative = formatRelativeTime(isoDate);
223 if (!relative) return "";
224 return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
225}
226
227export function getRelativeTimeState(isoDate: string | null): RelativeTimeState {
228 if (!isoDate) return { status: "missing" };
229 const relative = formatRelativeTime(isoDate);
230 if (!relative) return { status: "invalid" };
231 return { status: "relative", ...relative };
232}
233
234/**
235 * Relative elapsed duration since an ISO instant, without an "ago" suffix.
236 * Useful for labels like "Connected for 3m".
237 */
238export function formatElapsedDurationLabel(isoDate: string, nowMs: number = Date.now()): string {
239 const date = parseTimestampDate(isoDate);
240 if (!date) return "";
241 const diffMs = nowMs - date.getTime();
242 if (diffMs <= 0) return "just now";
243
244 const seconds = Math.floor(diffMs / 1000);
245 if (seconds < 5) return "just now";
246 if (seconds < 60) return `${seconds}s`;
247
248 const minutes = Math.floor(seconds / 60);
249 if (minutes < 60) return `${minutes}m`;
250
251 const hours = Math.floor(minutes / 60);
252 if (hours < 24) return `${hours}h`;
253
254 const days = Math.floor(hours / 24);
255 return `${days}d`;
256}
257
258/**
259 * Relative time until an ISO instant (e.g. expiry). Mirrors {@link formatRelativeTime} but for future times.
260 */
261export function formatRelativeTimeUntil(isoDate: string): RelativeTimeParts | null {
262 const date = parseTimestampDate(isoDate);
263 if (!date) return null;
264 const diffMs = date.getTime() - Date.now();
265 if (diffMs <= 0) return { value: "Expired", suffix: null };
266 const seconds = Math.floor(diffMs / 1000);
267 if (seconds < 5) return { value: "Soon", suffix: null };
268 if (seconds < 60) return { value: `${seconds}s`, suffix: "left" };
269 const minutes = Math.floor(seconds / 60);
270 if (minutes < 60) return { value: `${minutes}m`, suffix: "left" };
271 const hours = Math.floor(minutes / 60);
272 if (hours < 24) return { value: `${hours}h`, suffix: "left" };
273 const days = Math.floor(hours / 24);
274 return { value: `${days}d`, suffix: "left" };
275}
276
277export function formatRelativeTimeUntilLabel(isoDate: string): string {
278 const relative = formatRelativeTimeUntil(isoDate);
279 if (!relative) return "";
280 return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
281}
282
283/**
284 * Countdown for a future instant (e.g. link expiry): "Expires in 4m 12s", with second precision under one hour.
285 * Pass `nowMs` when a parent tick drives re-renders so the diff matches that snapshot.
286 */
287export function formatExpiresInLabel(isoDate: string, nowMs: number = Date.now()): string {
288 const date = parseTimestampDate(isoDate);
289 if (!date) return "";
290 const diffMs = date.getTime() - nowMs;
291 if (diffMs <= 0) return "Expired";
292
293 const totalSeconds = Math.floor(diffMs / 1000);
294 if (totalSeconds < 5) return "Expires in a moment";
295 if (totalSeconds < 60) return `Expires in ${totalSeconds}s`;
296
297 if (totalSeconds < 3600) {
298 const minutes = Math.floor(totalSeconds / 60);
299 const seconds = totalSeconds % 60;
300 return seconds === 0 ? `Expires in ${minutes}m` : `Expires in ${minutes}m ${seconds}s`;
301 }
302
303 if (totalSeconds < 86_400) {
304 const hours = Math.floor(totalSeconds / 3600);
305 const rem = totalSeconds % 3600;
306 const minutes = Math.floor(rem / 60);
307 const seconds = rem % 60;
308 const parts = [`${hours}h`];
309 if (minutes > 0) parts.push(`${minutes}m`);
310 if (seconds > 0) parts.push(`${seconds}s`);
311 return `Expires in ${parts.join(" ")}`;
312 }
313
314 const days = Math.floor(totalSeconds / 86_400);
315 const remAfterDays = totalSeconds % 86_400;
316 if (remAfterDays === 0) return `Expires in ${days}d`;
317 const hours = Math.floor(remAfterDays / 3600);
318 const rem = remAfterDays % 3600;
319 const minutes = Math.floor(rem / 60);
320 const seconds = rem % 60;
321 const tail: string[] = [];
322 if (hours > 0) tail.push(`${hours}h`);
323 if (minutes > 0) tail.push(`${minutes}m`);
324 if (seconds > 0) tail.push(`${seconds}s`);
325 return tail.length > 0 ? `Expires in ${days}d ${tail.join(" ")}` : `Expires in ${days}d`;
326}