Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

timestampFormat.ts

299 lines10.5 KB

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 };
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 }
48​
49function readHostSystemLocale(): string | null {
50 if (typeof window === "undefined") return null;
51 return window.desktopBridge?.getSystemLocale?.() ?? null;
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;
75​
76export function parseTimestampDate(isoDate: string): Date | null {
77 const date = new Date(isoDate);
78 return Number.isNaN(date.getTime()) ? null : date;
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);
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(undefined, { 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 }
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}`;
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);
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}`;
167​
168/**
169 * Format a relative time string from an ISO date.
170 * Returns `{ value: "20s", suffix: "ago" }` or `{ value: "just now", suffix: null }`
171 * so callers can style the numeric portion independently.
172 */
173type RelativeTimeParts = { value: string; suffix: string | null };
174export type RelativeTimeState =
175 | { status: "missing" }
176 | { status: "invalid" }
177 | { status: "relative"; value: string; suffix: string | null };
178​
179export function formatRelativeTime(isoDate: string): RelativeTimeParts | null {
180 const date = parseTimestampDate(isoDate);
181 if (!date) return null;
182 const diffMs = Date.now() - date.getTime();
183 if (diffMs < 0) return { value: "just now", suffix: null };
184 const seconds = Math.floor(diffMs / 1000);
185 if (seconds < 60) return { value: "just now", suffix: null };
186 const minutes = Math.floor(seconds / 60);
187 if (minutes < 60) return { value: `${minutes}m`, suffix: "ago" };
188 const hours = Math.floor(minutes / 60);
189 if (hours < 24) return { value: `${hours}h`, suffix: "ago" };
190 const days = Math.floor(hours / 24);
191 return { value: `${days}d`, suffix: "ago" };
193​
194export function formatRelativeTimeLabel(isoDate: string) {
195 const relative = formatRelativeTime(isoDate);
196 if (!relative) return "";
197 return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
199​
200export function getRelativeTimeState(isoDate: string | null): RelativeTimeState {
201 if (!isoDate) return { status: "missing" };
202 const relative = formatRelativeTime(isoDate);
203 if (!relative) return { status: "invalid" };
204 return { status: "relative", ...relative };
206​
207/**
208 * Relative elapsed duration since an ISO instant, without an "ago" suffix.
209 * Useful for labels like "Connected for 3m".
210 */
211export function formatElapsedDurationLabel(isoDate: string, nowMs: number = Date.now()): string {
212 const date = parseTimestampDate(isoDate);
213 if (!date) return "";
214 const diffMs = nowMs - date.getTime();
215 if (diffMs <= 0) return "just now";
216​
217 const seconds = Math.floor(diffMs / 1000);
218 if (seconds < 5) return "just now";
219 if (seconds < 60) return `${seconds}s`;
220​
221 const minutes = Math.floor(seconds / 60);
222 if (minutes < 60) return `${minutes}m`;
223​
224 const hours = Math.floor(minutes / 60);
225 if (hours < 24) return `${hours}h`;
226​
227 const days = Math.floor(hours / 24);
228 return `${days}d`;
230​
231/**
232 * Relative time until an ISO instant (e.g. expiry). Mirrors {@link formatRelativeTime} but for future times.
233 */
234export function formatRelativeTimeUntil(isoDate: string): RelativeTimeParts | null {
235 const date = parseTimestampDate(isoDate);
236 if (!date) return null;
237 const diffMs = date.getTime() - Date.now();
238 if (diffMs <= 0) return { value: "Expired", suffix: null };
239 const seconds = Math.floor(diffMs / 1000);
240 if (seconds < 5) return { value: "Soon", suffix: null };
241 if (seconds < 60) return { value: `${seconds}s`, suffix: "left" };
242 const minutes = Math.floor(seconds / 60);
243 if (minutes < 60) return { value: `${minutes}m`, suffix: "left" };
244 const hours = Math.floor(minutes / 60);
245 if (hours < 24) return { value: `${hours}h`, suffix: "left" };
246 const days = Math.floor(hours / 24);
247 return { value: `${days}d`, suffix: "left" };
249​
250export function formatRelativeTimeUntilLabel(isoDate: string): string {
251 const relative = formatRelativeTimeUntil(isoDate);
252 if (!relative) return "";
253 return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
255​
256/**
257 * Countdown for a future instant (e.g. link expiry): "Expires in 4m 12s", with second precision under one hour.
258 * Pass `nowMs` when a parent tick drives re-renders so the diff matches that snapshot.
259 */
260export function formatExpiresInLabel(isoDate: string, nowMs: number = Date.now()): string {
261 const date = parseTimestampDate(isoDate);
262 if (!date) return "";
263 const diffMs = date.getTime() - nowMs;
264 if (diffMs <= 0) return "Expired";
265​
266 const totalSeconds = Math.floor(diffMs / 1000);
267 if (totalSeconds < 5) return "Expires in a moment";
268 if (totalSeconds < 60) return `Expires in ${totalSeconds}s`;
269​
270 if (totalSeconds < 3600) {
271 const minutes = Math.floor(totalSeconds / 60);
272 const seconds = totalSeconds % 60;
273 return seconds === 0 ? `Expires in ${minutes}m` : `Expires in ${minutes}m ${seconds}s`;
274 }
275​
276 if (totalSeconds < 86_400) {
277 const hours = Math.floor(totalSeconds / 3600);
278 const rem = totalSeconds % 3600;
279 const minutes = Math.floor(rem / 60);
280 const seconds = rem % 60;
281 const parts = [`${hours}h`];
282 if (minutes > 0) parts.push(`${minutes}m`);
283 if (seconds > 0) parts.push(`${seconds}s`);
284 return `Expires in ${parts.join(" ")}`;
285 }
286​
287 const days = Math.floor(totalSeconds / 86_400);
288 const remAfterDays = totalSeconds % 86_400;
289 if (remAfterDays === 0) return `Expires in ${days}d`;
290 const hours = Math.floor(remAfterDays / 3600);
291 const rem = remAfterDays % 3600;
292 const minutes = Math.floor(rem / 60);
293 const seconds = rem % 60;
294 const tail: string[] = [];
295 if (hours > 0) tail.push(`${hours}h`);
296 if (minutes > 0) tail.push(`${minutes}m`);
297 if (seconds > 0) tail.push(`${seconds}s`);
298 return tail.length > 0 ? `Expires in ${days}d ${tail.join(" ")}` : `Expires in ${days}d`;