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

timestampFormat.ts

354 lines11.9 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 // Reject structurally invalid tags; let ICU fall back for valid tags it lacks data for.
29 Intl.DateTimeFormat.supportedLocalesOf([tag]);
30 return tag;
31 } catch {
32 return undefined;
33 }
35​
36function readHostSystemLocale(): string | null {
37 if (typeof window === "undefined") return null;
38 return window.desktopBridge?.getSystemLocale() ?? null;
40​
41const timestampLocale = resolveTimestampLocale(readHostSystemLocale());
42​
43const WEEKDAY_INDEXES = [0, 1, 2, 3, 4, 5, 6] as const;
44type WeekdayIndex = (typeof WEEKDAY_INDEXES)[number];
45​
46type LocaleWithWeekInfo = Intl.Locale & {
47 readonly weekInfo?: { readonly firstDay: number };
48 getWeekInfo?: () => { readonly firstDay: number };
49};
50​
51/**
52 * First weekday of a locale as a `Date#getDay` index (0 is Sunday), or
53 * `undefined` when the runtime has no week data, so callers keep their own
54 * default.
55 */
56function resolveWeekStartsOn(locale: string | undefined): WeekdayIndex | undefined {
57 try {
58 const resolved: LocaleWithWeekInfo = new Intl.Locale(
59 locale ?? Intl.DateTimeFormat().resolvedOptions().locale,
60 );
61 // Week info counts Monday as 1 and Sunday as 7.
62 const firstDay = resolved.getWeekInfo?.().firstDay ?? resolved.weekInfo?.firstDay;
63 return firstDay === undefined ? undefined : WEEKDAY_INDEXES[firstDay % 7];
64 } catch {
65 return undefined;
66 }
68​
69export const weekStartsOn = resolveWeekStartsOn(timestampLocale);
70​
71const timestampFormatterCache = new Map<string, Intl.DateTimeFormat>();
72​
73function getTimestampFormatter(
74 timestampFormat: TimestampFormat,
75 includeSeconds: boolean,
76 timeZone?: string,
77): Intl.DateTimeFormat {
78 const cacheKey = `${timestampFormat}:${includeSeconds ? "seconds" : "minutes"}:${timeZone ?? ""}`;
79 const cachedFormatter = timestampFormatterCache.get(cacheKey);
80 if (cachedFormatter) {
81 return cachedFormatter;
82 }
83​
84 const formatter = new Intl.DateTimeFormat(timestampLocale, {
85 ...getTimestampFormatOptions(timestampFormat, includeSeconds),
86 ...(timeZone ? { timeZone } : {}),
87 });
88 timestampFormatterCache.set(cacheKey, formatter);
89 return formatter;
91​
92export function resolveHour12(timestampFormat: TimestampFormat): boolean {
93 return getTimestampFormatter(timestampFormat, false).resolvedOptions().hour12 ?? false;
95​
96export function parseTimestampDate(isoDate: string): Date | null {
97 const date = new Date(isoDate);
98 return Number.isNaN(date.getTime()) ? null : date;
100​
101// Deliberately not the host locale: the tooltip's ordinal suffix and
102// day-before-month order below are English, so a localized month alone would
103// read "4th Juni 2026".
104const monthNameFormatter = new Intl.DateTimeFormat("en-US", { month: "long" });
105​
106function ordinalSuffix(day: number): string {
107 const lastTwo = day % 100;
108 if (lastTwo >= 11 && lastTwo <= 13) return "th";
109 switch (day % 10) {
110 case 1:
111 return "st";
112 case 2:
113 return "nd";
114 case 3:
115 return "rd";
116 default:
117 return "th";
118 }
120​
121export function formatChatTimestampTooltip(
122 isoDate: string,
123 timestampFormat: TimestampFormat,
124): string {
125 const date = parseTimestampDate(isoDate);
126 if (!date) return "";
127 const time = formatShortTimestamp(isoDate, timestampFormat);
128 const day = date.getDate();
129 const month = monthNameFormatter.format(date);
130 const year = date.getFullYear();
131 return `${time}, ${day}${ordinalSuffix(day)} ${month} ${year}`;
133​
134export function formatFullTimestamp(isoDate: string, timestampFormat: TimestampFormat): string {
135 return new Date(isoDate).toLocaleString(
136 undefined,
137 timestampFormat === "locale" ? undefined : { hour12: timestampFormat === "12-hour" },
138 );
140​
141export function formatShortTimestamp(isoDate: string, timestampFormat: TimestampFormat): string {
142 const date = parseTimestampDate(isoDate);
143 if (!date) return "";
144 return getTimestampFormatter(timestampFormat, false).format(date);
146​
147const numericDateOptions: Intl.DateTimeFormatOptions = { month: "numeric", day: "numeric" };
148const numericDateWithYearOptions: Intl.DateTimeFormatOptions = {
149 ...numericDateOptions,
150 year: "numeric",
151};
152const numericDateFormatter = new Intl.DateTimeFormat(timestampLocale, numericDateOptions);
153const numericDateWithYearFormatter = new Intl.DateTimeFormat(
154 timestampLocale,
155 numericDateWithYearOptions,
156);
157​
158interface CalendarDay {
159 year: number;
160 /** Days since the epoch, so differences are whole days across DST shifts. */
161 index: number;
163​
164function calendarDay(date: Date, timeZone: string | undefined): CalendarDay {
165 if (!timeZone) {
166 const year = date.getFullYear();
167 return { year, index: Date.UTC(year, date.getMonth(), date.getDate()) / 86_400_000 };
168 }
169 const parts = new Intl.DateTimeFormat("en-US", {
170 timeZone,
171 year: "numeric",
172 month: "numeric",
173 day: "numeric",
174 }).formatToParts(date);
175 const part = (type: Intl.DateTimeFormatPartTypes) =>
176 Number(parts.find((entry) => entry.type === type)?.value);
177 const year = part("year");
178 return { year, index: Date.UTC(year, part("month") - 1, part("day")) / 86_400_000 };
180​
181function formatNumericDate(date: Date, sameYear: boolean, timeZone: string | undefined): string {
182 if (!timeZone) {
183 return (sameYear ? numericDateFormatter : numericDateWithYearFormatter).format(date);
184 }
185 return new Intl.DateTimeFormat(timestampLocale, {
186 ...(sameYear ? numericDateOptions : numericDateWithYearOptions),
187 timeZone,
188 }).format(date);
190​
191export function formatDayAwareTimestamp(
192 isoDate: string,
193 timestampFormat: TimestampFormat,
194 nowMs: number = Date.now(),
195 timeZone?: string,
196): string {
197 const date = parseTimestampDate(isoDate);
198 if (!date) return "";
199 const time = getTimestampFormatter(timestampFormat, false, timeZone).format(date);
200​
201 const today = calendarDay(new Date(nowMs), timeZone);
202 const messageDay = calendarDay(date, timeZone);
203 const dayDiff = today.index - messageDay.index;
204​
205 if (dayDiff <= 0) return time;
206 if (dayDiff === 1) return `yesterday at ${time}`;
207 return `${formatNumericDate(date, messageDay.year === today.year, timeZone)} ${time}`;
209​
210/** `timeZone` overrides the zone the formatters cached when they were built. */
211export function formatUpcomingTimestamp(
212 isoDate: string,
213 timestampFormat: TimestampFormat,
214 nowMs: number = Date.now(),
215 timeZone?: string,
216): string {
217 const date = parseTimestampDate(isoDate);
218 if (!date) return "";
219 const time = getTimestampFormatter(timestampFormat, false, timeZone).format(date);
220​
221 const today = calendarDay(new Date(nowMs), timeZone);
222 const targetDay = calendarDay(date, timeZone);
223 const dayDiff = targetDay.index - today.index;
224​
225 if (dayDiff < 0) return formatDayAwareTimestamp(isoDate, timestampFormat, nowMs, timeZone);
226 if (dayDiff === 0) return time;
227 if (dayDiff === 1) return `tomorrow at ${time}`;
228 return `${formatNumericDate(date, targetDay.year === today.year, timeZone)} ${time}`;
230​
231type RelativeTimeParts = { value: string; suffix: string | null };
232export type RelativeTimeState =
233 | { status: "missing" }
234 | { status: "invalid" }
235 | { status: "relative"; value: string; suffix: string | null };
236​
237const MINUTE_MS = 60_000;
238const HOUR_MS = 3_600_000;
239const DAY_MS = 86_400_000;
240​
241function relativeTimeUnitMs(elapsedMs: number): number {
242 if (elapsedMs < HOUR_MS) return MINUTE_MS;
243 if (elapsedMs < DAY_MS) return HOUR_MS;
244 return DAY_MS;
246​
247/** Elapsed time floored to formatRelativeTime precision; equal labels yield equal values. */
248export function relativeTimeElapsedMs(isoDate: string, nowMs: number = Date.now()): number | null {
249 const date = parseTimestampDate(isoDate);
250 if (!date) return null;
251 const elapsedMs = Math.max(0, nowMs - date.getTime());
252 const unitMs = relativeTimeUnitMs(elapsedMs);
253 return Math.floor(elapsedMs / unitMs) * unitMs;
255​
256export function msUntilRelativeTimeChange(
257 isoDate: string,
258 nowMs: number = Date.now(),
259): number | null {
260 const date = parseTimestampDate(isoDate);
261 if (!date) return null;
262 const elapsedMs = Math.max(0, nowMs - date.getTime());
263 const unitMs = relativeTimeUnitMs(elapsedMs);
264 const nextChangeMs = date.getTime() + (Math.floor(elapsedMs / unitMs) + 1) * unitMs;
265 // Delays above 2^31-1 fire immediately; cap safely and let callers reschedule.
266 return Math.min(nextChangeMs - nowMs, DAY_MS);
268​
269export function formatRelativeElapsed(elapsedMs: number): RelativeTimeParts {
270 const seconds = Math.floor(elapsedMs / 1000);
271 if (seconds < 60) return { value: "just now", suffix: null };
272 const minutes = Math.floor(seconds / 60);
273 if (minutes < 60) return { value: `${minutes}m`, suffix: "ago" };
274 const hours = Math.floor(minutes / 60);
275 if (hours < 24) return { value: `${hours}h`, suffix: "ago" };
276 const days = Math.floor(hours / 24);
277 return { value: `${days}d`, suffix: "ago" };
279​
280export function formatRelativeTime(
281 isoDate: string,
282 nowMs: number = Date.now(),
283): RelativeTimeParts | null {
284 const elapsedMs = relativeTimeElapsedMs(isoDate, nowMs);
285 return elapsedMs === null ? null : formatRelativeElapsed(elapsedMs);
287​
288export function formatRelativeTimeLabel(isoDate: string, nowMs: number = Date.now()) {
289 const relative = formatRelativeTime(isoDate, nowMs);
290 if (!relative) return "";
291 return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
293​
294export function formatElapsedDurationLabel(isoDate: string, nowMs: number = Date.now()): string {
295 const date = parseTimestampDate(isoDate);
296 if (!date) return "";
297 const diffMs = nowMs - date.getTime();
298 if (diffMs <= 0) return "just now";
299​
300 const seconds = Math.floor(diffMs / 1000);
301 if (seconds < 5) return "just now";
302 if (seconds < 60) return `${seconds}s`;
303​
304 const minutes = Math.floor(seconds / 60);
305 if (minutes < 60) return `${minutes}m`;
306​
307 const hours = Math.floor(minutes / 60);
308 if (hours < 24) return `${hours}h`;
309​
310 const days = Math.floor(hours / 24);
311 return `${days}d`;
313​
314/** Pass nowMs to match a parent-driven render tick. */
315export function formatExpiresInLabel(isoDate: string, nowMs: number = Date.now()): string {
316 const date = parseTimestampDate(isoDate);
317 if (!date) return "";
318 const diffMs = date.getTime() - nowMs;
319 if (diffMs <= 0) return "Expired";
320​
321 const totalSeconds = Math.floor(diffMs / 1000);
322 if (totalSeconds < 5) return "Expires in a moment";
323 if (totalSeconds < 60) return `Expires in ${totalSeconds}s`;
324​
325 if (totalSeconds < 3600) {
326 const minutes = Math.floor(totalSeconds / 60);
327 const seconds = totalSeconds % 60;
328 return seconds === 0 ? `Expires in ${minutes}m` : `Expires in ${minutes}m ${seconds}s`;
329 }
330​
331 if (totalSeconds < 86_400) {
332 const hours = Math.floor(totalSeconds / 3600);
333 const rem = totalSeconds % 3600;
334 const minutes = Math.floor(rem / 60);
335 const seconds = rem % 60;
336 const parts = [`${hours}h`];
337 if (minutes > 0) parts.push(`${minutes}m`);
338 if (seconds > 0) parts.push(`${seconds}s`);
339 return `Expires in ${parts.join(" ")}`;
340 }
341​
342 const days = Math.floor(totalSeconds / 86_400);
343 const remAfterDays = totalSeconds % 86_400;
344 if (remAfterDays === 0) return `Expires in ${days}d`;
345 const hours = Math.floor(remAfterDays / 3600);
346 const rem = remAfterDays % 3600;
347 const minutes = Math.floor(rem / 60);
348 const seconds = rem % 60;
349 const tail: string[] = [];
350 if (hours > 0) tail.push(`${hours}h`);
351 if (minutes > 0) tail.push(`${minutes}m`);
352 if (seconds > 0) tail.push(`${seconds}s`);
353 return tail.length > 0 ? `Expires in ${days}d ${tail.join(" ")}` : `Expires in ${days}d`;