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