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
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
234export function formatElapsedDurationLabel(isoDate: string, nowMs: number = Date.now()): string {
235 const date = parseTimestampDate(isoDate);
236 if (!date) return "";
237 const diffMs = nowMs - date.getTime();
238 if (diffMs <= 0) return "just now";
239
240 const seconds = Math.floor(diffMs / 1000);
241 if (seconds < 5) return "just now";
242 if (seconds < 60) return `${seconds}s`;
243
244 const minutes = Math.floor(seconds / 60);
245 if (minutes < 60) return `${minutes}m`;
246
247 const hours = Math.floor(minutes / 60);
248 if (hours < 24) return `${hours}h`;
249
250 const days = Math.floor(hours / 24);
251 return `${days}d`;
252}
253
254export function formatRelativeTimeUntil(isoDate: string): RelativeTimeParts | null {
255 const date = parseTimestampDate(isoDate);
256 if (!date) return null;
257 const diffMs = date.getTime() - Date.now();
258 if (diffMs <= 0) return { value: "Expired", suffix: null };
259 const seconds = Math.floor(diffMs / 1000);
260 if (seconds < 5) return { value: "Soon", suffix: null };
261 if (seconds < 60) return { value: `${seconds}s`, suffix: "left" };
262 const minutes = Math.floor(seconds / 60);
263 if (minutes < 60) return { value: `${minutes}m`, suffix: "left" };
264 const hours = Math.floor(minutes / 60);
265 if (hours < 24) return { value: `${hours}h`, suffix: "left" };
266 const days = Math.floor(hours / 24);
267 return { value: `${days}d`, suffix: "left" };
268}
269
270export function formatRelativeTimeUntilLabel(isoDate: string): string {
271 const relative = formatRelativeTimeUntil(isoDate);
272 if (!relative) return "";
273 return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
274}
275
276/**
277 * Pass `nowMs` when a parent tick drives re-renders so the diff matches that snapshot.
278 */
279export function formatExpiresInLabel(isoDate: string, nowMs: number = Date.now()): string {
280 const date = parseTimestampDate(isoDate);
281 if (!date) return "";
282 const diffMs = date.getTime() - nowMs;
283 if (diffMs <= 0) return "Expired";
284
285 const totalSeconds = Math.floor(diffMs / 1000);
286 if (totalSeconds < 5) return "Expires in a moment";
287 if (totalSeconds < 60) return `Expires in ${totalSeconds}s`;
288
289 if (totalSeconds < 3600) {
290 const minutes = Math.floor(totalSeconds / 60);
291 const seconds = totalSeconds % 60;
292 return seconds === 0 ? `Expires in ${minutes}m` : `Expires in ${minutes}m ${seconds}s`;
293 }
294
295 if (totalSeconds < 86_400) {
296 const hours = Math.floor(totalSeconds / 3600);
297 const rem = totalSeconds % 3600;
298 const minutes = Math.floor(rem / 60);
299 const seconds = rem % 60;
300 const parts = [`${hours}h`];
301 if (minutes > 0) parts.push(`${minutes}m`);
302 if (seconds > 0) parts.push(`${seconds}s`);
303 return `Expires in ${parts.join(" ")}`;
304 }
305
306 const days = Math.floor(totalSeconds / 86_400);
307 const remAfterDays = totalSeconds % 86_400;
308 if (remAfterDays === 0) return `Expires in ${days}d`;
309 const hours = Math.floor(remAfterDays / 3600);
310 const rem = remAfterDays % 3600;
311 const minutes = Math.floor(rem / 60);
312 const seconds = rem % 60;
313 const tail: string[] = [];
314 if (hours > 0) tail.push(`${hours}h`);
315 if (minutes > 0) tail.push(`${minutes}m`);
316 if (seconds > 0) tail.push(`${seconds}s`);
317 return tail.length > 0 ? `Expires in ${days}d ${tail.join(" ")}` : `Expires in ${days}d`;
318}