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

timestampFormat.ts

348 lines12.1 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​
23function resolveTimestampLocale(systemLocale: string | null | undefined): string | undefined {
24 const tag = systemLocale?.trim();
25 if (!tag) return undefined;
26​
27 try {
28 // Every timestamp in the UI runs through this formatter, so a tag the host
29 // could not normalize falls back rather than throwing. Throws on a
30 // structurally invalid tag; a well-formed tag ICU has no data for resolves
31 // here and is left to ICU's own fallback.
32 Intl.DateTimeFormat.supportedLocalesOf([tag]);
33 return tag;
34 } catch {
35 return undefined;
36 }
38​
39function readHostSystemLocale(): string | null {
40 if (typeof window === "undefined") return null;
41 return window.desktopBridge?.getSystemLocale?.() ?? null;
43​
44const timestampLocale = resolveTimestampLocale(readHostSystemLocale());
45​
46const WEEKDAY_INDEXES = [0, 1, 2, 3, 4, 5, 6] as const;
47type WeekdayIndex = (typeof WEEKDAY_INDEXES)[number];
48​
49type LocaleWithWeekInfo = Intl.Locale & {
50 readonly weekInfo?: { readonly firstDay: number };
51 getWeekInfo?: () => { readonly firstDay: number };
52};
53​
54/**
55 * First weekday of a locale as a `Date#getDay` index (0 is Sunday), or
56 * `undefined` when the runtime has no week data, so callers keep their own
57 * default.
58 */
59function resolveWeekStartsOn(locale: string | undefined): WeekdayIndex | undefined {
60 try {
61 const resolved: LocaleWithWeekInfo = new Intl.Locale(
62 locale ?? Intl.DateTimeFormat().resolvedOptions().locale,
63 );
64 // Week info counts Monday as 1 and Sunday as 7.
65 const firstDay = resolved.getWeekInfo?.().firstDay ?? resolved.weekInfo?.firstDay;
66 return firstDay === undefined ? undefined : WEEKDAY_INDEXES[firstDay % 7];
67 } catch {
68 return undefined;
69 }
71​
72export const weekStartsOn = resolveWeekStartsOn(timestampLocale);
73​
74const timestampFormatterCache = new Map<string, Intl.DateTimeFormat>();
75​
76function getTimestampFormatter(
77 timestampFormat: TimestampFormat,
78 includeSeconds: boolean,
79): Intl.DateTimeFormat {
80 const cacheKey = `${timestampFormat}:${includeSeconds ? "seconds" : "minutes"}`;
81 const cachedFormatter = timestampFormatterCache.get(cacheKey);
82 if (cachedFormatter) {
83 return cachedFormatter;
84 }
85​
86 const formatter = new Intl.DateTimeFormat(
87 timestampLocale,
88 getTimestampFormatOptions(timestampFormat, includeSeconds),
89 );
90 timestampFormatterCache.set(cacheKey, formatter);
91 return formatter;
93​
94export function resolveHour12(timestampFormat: TimestampFormat): boolean {
95 return getTimestampFormatter(timestampFormat, false).resolvedOptions().hour12 ?? false;
97​
98export function parseTimestampDate(isoDate: string): Date | null {
99 const date = new Date(isoDate);
100 return Number.isNaN(date.getTime()) ? null : date;
102​
103// Deliberately not the host locale: the tooltip's ordinal suffix and
104// day-before-month order below are English, so a localized month alone would
105// read "4th Juni 2026".
106const monthNameFormatter = new Intl.DateTimeFormat("en-US", { month: "long" });
107​
108function ordinalSuffix(day: number): string {
109 const lastTwo = day % 100;
110 if (lastTwo >= 11 && lastTwo <= 13) return "th";
111 switch (day % 10) {
112 case 1:
113 return "st";
114 case 2:
115 return "nd";
116 case 3:
117 return "rd";
118 default:
119 return "th";
120 }
122​
123export function formatChatTimestampTooltip(
124 isoDate: string,
125 timestampFormat: TimestampFormat,
126): string {
127 const date = parseTimestampDate(isoDate);
128 if (!date) return "";
129 const time = formatShortTimestamp(isoDate, timestampFormat);
130 const day = date.getDate();
131 const month = monthNameFormatter.format(date);
132 const year = date.getFullYear();
133 return `${time}, ${day}${ordinalSuffix(day)} ${month} ${year}`;
135​
136export function formatShortTimestamp(isoDate: string, timestampFormat: TimestampFormat): string {
137 const date = parseTimestampDate(isoDate);
138 if (!date) return "";
139 return getTimestampFormatter(timestampFormat, false).format(date);
141​
142const numericDateFormatter = new Intl.DateTimeFormat(timestampLocale, {
143 month: "numeric",
144 day: "numeric",
145});
146const numericDateWithYearFormatter = new Intl.DateTimeFormat(timestampLocale, {
147 month: "numeric",
148 day: "numeric",
149 year: "numeric",
150});
151​
152export function formatDayAwareTimestamp(
153 isoDate: string,
154 timestampFormat: TimestampFormat,
155 nowMs: number = Date.now(),
156): string {
157 const date = parseTimestampDate(isoDate);
158 if (!date) return "";
159 const time = getTimestampFormatter(timestampFormat, false).format(date);
160​
161 const now = new Date(nowMs);
162 const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
163 const startOfMessageDay = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
164 // Round so DST-shifted 23/25 hour days still count as whole days.
165 const dayDiff = Math.round((startOfToday - startOfMessageDay) / 86_400_000);
166​
167 if (dayDiff <= 0) return time;
168 if (dayDiff === 1) return `yesterday at ${time}`;
169 const dateFormatter =
170 date.getFullYear() === now.getFullYear() ? numericDateFormatter : numericDateWithYearFormatter;
171 return `${dateFormatter.format(date)} ${time}`;
173​
174export function formatUpcomingTimestamp(
175 isoDate: string,
176 timestampFormat: TimestampFormat,
177 nowMs: number = Date.now(),
178): string {
179 const date = parseTimestampDate(isoDate);
180 if (!date) return "";
181 const time = getTimestampFormatter(timestampFormat, false).format(date);
182​
183 const now = new Date(nowMs);
184 const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
185 const startOfTargetDay = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
186 const dayDiff = Math.round((startOfTargetDay - startOfToday) / 86_400_000);
187​
188 if (dayDiff < 0) return formatDayAwareTimestamp(isoDate, timestampFormat, nowMs);
189 if (dayDiff === 0) return time;
190 if (dayDiff === 1) return `tomorrow at ${time}`;
191 const dateFormatter =
192 date.getFullYear() === now.getFullYear() ? numericDateFormatter : numericDateWithYearFormatter;
193 return `${dateFormatter.format(date)} ${time}`;
195​
196type RelativeTimeParts = { value: string; suffix: string | null };
197export type RelativeTimeState =
198 | { status: "missing" }
199 | { status: "invalid" }
200 | { status: "relative"; value: string; suffix: string | null };
201​
202const MINUTE_MS = 60_000;
203const HOUR_MS = 3_600_000;
204const DAY_MS = 86_400_000;
205​
206function relativeTimeUnitMs(elapsedMs: number): number {
207 if (elapsedMs < HOUR_MS) return MINUTE_MS;
208 if (elapsedMs < DAY_MS) return HOUR_MS;
209 return DAY_MS;
211​
212/**
213 * Elapsed time floored to the precision `formatRelativeTime` shows, so two
214 * instants with the same label return the same number.
215 */
216export function relativeTimeElapsedMs(isoDate: string, nowMs: number = Date.now()): number | null {
217 const date = parseTimestampDate(isoDate);
218 if (!date) return null;
219 const elapsedMs = Math.max(0, nowMs - date.getTime());
220 const unitMs = relativeTimeUnitMs(elapsedMs);
221 return Math.floor(elapsedMs / unitMs) * unitMs;
223​
224/** Milliseconds until the `formatRelativeTime` label for `isoDate` next changes. */
225export function msUntilRelativeTimeChange(
226 isoDate: string,
227 nowMs: number = Date.now(),
228): number | null {
229 const date = parseTimestampDate(isoDate);
230 if (!date) return null;
231 const elapsedMs = Math.max(0, nowMs - date.getTime());
232 const unitMs = relativeTimeUnitMs(elapsedMs);
233 const nextChangeMs = date.getTime() + (Math.floor(elapsedMs / unitMs) + 1) * unitMs;
234 // setTimeout fires at once past 2^31-1 ms, which would loop on a far-future
235 // timestamp. Waking early is harmless: the caller re-reads and re-schedules.
236 return Math.min(nextChangeMs - nowMs, DAY_MS);
238​
239export function formatRelativeElapsed(elapsedMs: number): RelativeTimeParts {
240 const seconds = Math.floor(elapsedMs / 1000);
241 if (seconds < 60) return { value: "just now", suffix: null };
242 const minutes = Math.floor(seconds / 60);
243 if (minutes < 60) return { value: `${minutes}m`, suffix: "ago" };
244 const hours = Math.floor(minutes / 60);
245 if (hours < 24) return { value: `${hours}h`, suffix: "ago" };
246 const days = Math.floor(hours / 24);
247 return { value: `${days}d`, suffix: "ago" };
249​
250export function formatRelativeTime(
251 isoDate: string,
252 nowMs: number = Date.now(),
253): RelativeTimeParts | null {
254 const elapsedMs = relativeTimeElapsedMs(isoDate, nowMs);
255 return elapsedMs === null ? null : formatRelativeElapsed(elapsedMs);
257​
258export function formatRelativeTimeLabel(isoDate: string, nowMs: number = Date.now()) {
259 const relative = formatRelativeTime(isoDate, nowMs);
260 if (!relative) return "";
261 return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
263​
264export function formatElapsedDurationLabel(isoDate: string, nowMs: number = Date.now()): string {
265 const date = parseTimestampDate(isoDate);
266 if (!date) return "";
267 const diffMs = nowMs - date.getTime();
268 if (diffMs <= 0) return "just now";
269​
270 const seconds = Math.floor(diffMs / 1000);
271 if (seconds < 5) return "just now";
272 if (seconds < 60) return `${seconds}s`;
273​
274 const minutes = Math.floor(seconds / 60);
275 if (minutes < 60) return `${minutes}m`;
276​
277 const hours = Math.floor(minutes / 60);
278 if (hours < 24) return `${hours}h`;
279​
280 const days = Math.floor(hours / 24);
281 return `${days}d`;
283​
284function formatRelativeTimeUntil(isoDate: string): RelativeTimeParts | null {
285 const date = parseTimestampDate(isoDate);
286 if (!date) return null;
287 const diffMs = date.getTime() - Date.now();
288 if (diffMs <= 0) return { value: "Expired", suffix: null };
289 const seconds = Math.floor(diffMs / 1000);
290 if (seconds < 5) return { value: "Soon", suffix: null };
291 if (seconds < 60) return { value: `${seconds}s`, suffix: "left" };
292 const minutes = Math.floor(seconds / 60);
293 if (minutes < 60) return { value: `${minutes}m`, suffix: "left" };
294 const hours = Math.floor(minutes / 60);
295 if (hours < 24) return { value: `${hours}h`, suffix: "left" };
296 const days = Math.floor(hours / 24);
297 return { value: `${days}d`, suffix: "left" };
299​
300export function formatRelativeTimeUntilLabel(isoDate: string): string {
301 const relative = formatRelativeTimeUntil(isoDate);
302 if (!relative) return "";
303 return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
305​
306/**
307 * Pass `nowMs` when a parent tick drives re-renders so the diff matches that snapshot.
308 */
309export function formatExpiresInLabel(isoDate: string, nowMs: number = Date.now()): string {
310 const date = parseTimestampDate(isoDate);
311 if (!date) return "";
312 const diffMs = date.getTime() - nowMs;
313 if (diffMs <= 0) return "Expired";
314​
315 const totalSeconds = Math.floor(diffMs / 1000);
316 if (totalSeconds < 5) return "Expires in a moment";
317 if (totalSeconds < 60) return `Expires in ${totalSeconds}s`;
318​
319 if (totalSeconds < 3600) {
320 const minutes = Math.floor(totalSeconds / 60);
321 const seconds = totalSeconds % 60;
322 return seconds === 0 ? `Expires in ${minutes}m` : `Expires in ${minutes}m ${seconds}s`;
323 }
324​
325 if (totalSeconds < 86_400) {
326 const hours = Math.floor(totalSeconds / 3600);
327 const rem = totalSeconds % 3600;
328 const minutes = Math.floor(rem / 60);
329 const seconds = rem % 60;
330 const parts = [`${hours}h`];
331 if (minutes > 0) parts.push(`${minutes}m`);
332 if (seconds > 0) parts.push(`${seconds}s`);
333 return `Expires in ${parts.join(" ")}`;
334 }
335​
336 const days = Math.floor(totalSeconds / 86_400);
337 const remAfterDays = totalSeconds % 86_400;
338 if (remAfterDays === 0) return `Expires in ${days}d`;
339 const hours = Math.floor(remAfterDays / 3600);
340 const rem = remAfterDays % 3600;
341 const minutes = Math.floor(rem / 60);
342 const seconds = rem % 60;
343 const tail: string[] = [];
344 if (hours > 0) tail.push(`${hours}h`);
345 if (minutes > 0) tail.push(`${minutes}m`);
346 if (seconds > 0) tail.push(`${seconds}s`);
347 return tail.length > 0 ? `Expires in ${days}d ${tail.join(" ")}` : `Expires in ${days}d`;