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