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

timestampFormat.ts

325 lines11.5 KB

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 };
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("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 }
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 * 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 time;
188 if (dayDiff === 1) return `tomorrow at ${time}`;
189 const dateFormatter =
190 date.getFullYear() === now.getFullYear() ? numericDateFormatter : numericDateWithYearFormatter;
191 return `${dateFormatter.format(date)} ${time}`;
193​
194/**
195 * Format a relative time string from an ISO date.
196 * Returns `{ value: "20s", suffix: "ago" }` or `{ value: "just now", suffix: null }`
197 * so callers can style the numeric portion independently.
198 */
199type RelativeTimeParts = { value: string; suffix: string | null };
200export type RelativeTimeState =
201 | { status: "missing" }
202 | { status: "invalid" }
203 | { status: "relative"; value: string; suffix: string | null };
204​
205export function formatRelativeTime(isoDate: string): RelativeTimeParts | null {
206 const date = parseTimestampDate(isoDate);
207 if (!date) return null;
208 const diffMs = Date.now() - date.getTime();
209 if (diffMs < 0) return { value: "just now", suffix: null };
210 const seconds = Math.floor(diffMs / 1000);
211 if (seconds < 60) return { value: "just now", suffix: null };
212 const minutes = Math.floor(seconds / 60);
213 if (minutes < 60) return { value: `${minutes}m`, suffix: "ago" };
214 const hours = Math.floor(minutes / 60);
215 if (hours < 24) return { value: `${hours}h`, suffix: "ago" };
216 const days = Math.floor(hours / 24);
217 return { value: `${days}d`, suffix: "ago" };
219​
220export function formatRelativeTimeLabel(isoDate: string) {
221 const relative = formatRelativeTime(isoDate);
222 if (!relative) return "";
223 return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
225​
226export function getRelativeTimeState(isoDate: string | null): RelativeTimeState {
227 if (!isoDate) return { status: "missing" };
228 const relative = formatRelativeTime(isoDate);
229 if (!relative) return { status: "invalid" };
230 return { status: "relative", ...relative };
232​
233/**
234 * Relative elapsed duration since an ISO instant, without an "ago" suffix.
235 * Useful for labels like "Connected for 3m".
236 */
237export function formatElapsedDurationLabel(isoDate: string, nowMs: number = Date.now()): string {
238 const date = parseTimestampDate(isoDate);
239 if (!date) return "";
240 const diffMs = nowMs - date.getTime();
241 if (diffMs <= 0) return "just now";
242​
243 const seconds = Math.floor(diffMs / 1000);
244 if (seconds < 5) return "just now";
245 if (seconds < 60) return `${seconds}s`;
246​
247 const minutes = Math.floor(seconds / 60);
248 if (minutes < 60) return `${minutes}m`;
249​
250 const hours = Math.floor(minutes / 60);
251 if (hours < 24) return `${hours}h`;
252​
253 const days = Math.floor(hours / 24);
254 return `${days}d`;
256​
257/**
258 * Relative time until an ISO instant (e.g. expiry). Mirrors {@link formatRelativeTime} but for future times.
259 */
260export function formatRelativeTimeUntil(isoDate: string): RelativeTimeParts | null {
261 const date = parseTimestampDate(isoDate);
262 if (!date) return null;
263 const diffMs = date.getTime() - Date.now();
264 if (diffMs <= 0) return { value: "Expired", suffix: null };
265 const seconds = Math.floor(diffMs / 1000);
266 if (seconds < 5) return { value: "Soon", suffix: null };
267 if (seconds < 60) return { value: `${seconds}s`, suffix: "left" };
268 const minutes = Math.floor(seconds / 60);
269 if (minutes < 60) return { value: `${minutes}m`, suffix: "left" };
270 const hours = Math.floor(minutes / 60);
271 if (hours < 24) return { value: `${hours}h`, suffix: "left" };
272 const days = Math.floor(hours / 24);
273 return { value: `${days}d`, suffix: "left" };
275​
276export function formatRelativeTimeUntilLabel(isoDate: string): string {
277 const relative = formatRelativeTimeUntil(isoDate);
278 if (!relative) return "";
279 return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
281​
282/**
283 * Countdown for a future instant (e.g. link expiry): "Expires in 4m 12s", with second precision under one hour.
284 * Pass `nowMs` when a parent tick drives re-renders so the diff matches that snapshot.
285 */
286export function formatExpiresInLabel(isoDate: string, nowMs: number = Date.now()): string {
287 const date = parseTimestampDate(isoDate);
288 if (!date) return "";
289 const diffMs = date.getTime() - nowMs;
290 if (diffMs <= 0) return "Expired";
291​
292 const totalSeconds = Math.floor(diffMs / 1000);
293 if (totalSeconds < 5) return "Expires in a moment";
294 if (totalSeconds < 60) return `Expires in ${totalSeconds}s`;
295​
296 if (totalSeconds < 3600) {
297 const minutes = Math.floor(totalSeconds / 60);
298 const seconds = totalSeconds % 60;
299 return seconds === 0 ? `Expires in ${minutes}m` : `Expires in ${minutes}m ${seconds}s`;
300 }
301​
302 if (totalSeconds < 86_400) {
303 const hours = Math.floor(totalSeconds / 3600);
304 const rem = totalSeconds % 3600;
305 const minutes = Math.floor(rem / 60);
306 const seconds = rem % 60;
307 const parts = [`${hours}h`];
308 if (minutes > 0) parts.push(`${minutes}m`);
309 if (seconds > 0) parts.push(`${seconds}s`);
310 return `Expires in ${parts.join(" ")}`;
311 }
312​
313 const days = Math.floor(totalSeconds / 86_400);
314 const remAfterDays = totalSeconds % 86_400;
315 if (remAfterDays === 0) return `Expires in ${days}d`;
316 const hours = Math.floor(remAfterDays / 3600);
317 const rem = remAfterDays % 3600;
318 const minutes = Math.floor(rem / 60);
319 const seconds = rem % 60;
320 const tail: string[] = [];
321 if (hours > 0) tail.push(`${hours}h`);
322 if (minutes > 0) tail.push(`${minutes}m`);
323 if (seconds > 0) tail.push(`${seconds}s`);
324 return tail.length > 0 ? `Expires in ${days}d ${tail.join(" ")}` : `Expires in ${days}d`;