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

timestampFormat.ts

479 lines16.7 KB

1import { type TimestampFormat } from "@t3tools/contracts/settings";
2import { msg } from "gt-react";
3​
4import { DEFAULT_LOCALE } from "./i18n/locales";
5import { getActiveLocale, m, type MessageResolver } from "./i18n/messages";
6​
7function getTimestampFormatOptions(
8 timestampFormat: TimestampFormat,
9 includeSeconds: boolean,
10): Intl.DateTimeFormatOptions {
11 const baseOptions: Intl.DateTimeFormatOptions = {
12 hour: "numeric",
13 minute: "2-digit",
14 ...(includeSeconds ? { second: "2-digit" } : {}),
15 };
16​
17 if (timestampFormat === "locale") {
18 return baseOptions;
19 }
20​
21 return {
22 ...baseOptions,
23 hour12: timestampFormat === "12-hour",
24 };
26​
27function resolveTimestampLocale(systemLocale: string | null | undefined): string | undefined {
28 const tag = systemLocale?.trim();
29 if (!tag) return undefined;
30​
31 try {
32 // Reject structurally invalid tags; let ICU fall back for valid tags it lacks data for.
33 Intl.DateTimeFormat.supportedLocalesOf([tag]);
34 return tag;
35 } catch {
36 return undefined;
37 }
39​
40function readHostSystemLocale(): string | null {
41 if (typeof window === "undefined") return null;
42 return window.desktopBridge?.getSystemLocale() ?? null;
44​
45const timestampLocale = resolveTimestampLocale(readHostSystemLocale());
46​
47const WEEKDAY_INDEXES = [0, 1, 2, 3, 4, 5, 6] as const;
48type WeekdayIndex = (typeof WEEKDAY_INDEXES)[number];
49​
50type LocaleWithWeekInfo = Intl.Locale & {
51 readonly weekInfo?: { readonly firstDay: number };
52 getWeekInfo?: () => { readonly firstDay: number };
53};
54​
55/**
56 * First weekday of a locale as a `Date#getDay` index (0 is Sunday), or
57 * `undefined` when the runtime has no week data, so callers keep their own
58 * default.
59 */
60function resolveWeekStartsOn(locale: string | undefined): WeekdayIndex | undefined {
61 try {
62 const resolved: LocaleWithWeekInfo = new Intl.Locale(
63 locale ?? Intl.DateTimeFormat().resolvedOptions().locale,
64 );
65 // Week info counts Monday as 1 and Sunday as 7.
66 const firstDay = resolved.getWeekInfo?.().firstDay ?? resolved.weekInfo?.firstDay;
67 return firstDay === undefined ? undefined : WEEKDAY_INDEXES[firstDay % 7];
68 } catch {
69 return undefined;
70 }
72​
73export const weekStartsOn = resolveWeekStartsOn(timestampLocale);
74​
75// A formatter keeps the default zone it was built in, so default-zone formatters run in UTC
76// on the wall-clock time, which Date reads from the current zone.
77function wallClockAsUtc(date: Date): Date {
78 return new Date(date.getTime() - date.getTimezoneOffset() * 60_000);
80​
81const timestampFormatterCache = new Map<string, Intl.DateTimeFormat>();
82​
83function getTimestampFormatter(
84 timestampFormat: TimestampFormat,
85 includeSeconds: boolean,
86 timeZone = "UTC",
87 locale = timestampLocale,
88): Intl.DateTimeFormat {
89 const cacheKey = `${timestampFormat}:${includeSeconds ? "seconds" : "minutes"}:${timeZone}:${locale ?? ""}`;
90 const cachedFormatter = timestampFormatterCache.get(cacheKey);
91 if (cachedFormatter) {
92 return cachedFormatter;
93 }
94​
95 const hourCycle =
96 timestampFormat === "locale" && locale !== timestampLocale
97 ? getTimestampFormatter(timestampFormat, includeSeconds).resolvedOptions().hourCycle
98 : undefined;
99 const formatter = new Intl.DateTimeFormat(locale, {
100 ...getTimestampFormatOptions(timestampFormat, includeSeconds),
101 ...(hourCycle === undefined ? {} : { hourCycle }),
102 timeZone,
103 });
104 timestampFormatterCache.set(cacheKey, formatter);
105 return formatter;
107​
108function formatTime(date: Date, timestampFormat: TimestampFormat, timeZone?: string): string {
109 return timeZone
110 ? getTimestampFormatter(timestampFormat, false, timeZone).format(date)
111 : getTimestampFormatter(timestampFormat, false).format(wallClockAsUtc(date));
113​
114export function resolveHour12(timestampFormat: TimestampFormat): boolean {
115 return getTimestampFormatter(timestampFormat, false).resolvedOptions().hour12 ?? false;
117​
118export function parseTimestampDate(isoDate: string): Date | null {
119 const date = new Date(isoDate);
120 return Number.isNaN(date.getTime()) ? null : date;
122​
123// English keeps its ordinal day-before-month form; other UI languages use their own long date.
124const monthNameFormatter = new Intl.DateTimeFormat("en-US", { month: "long", timeZone: "UTC" });
125const longDateFormatterCache = new Map<string, Intl.DateTimeFormat>();
126​
127function getLongDateFormatter(locale: string): Intl.DateTimeFormat {
128 let formatter = longDateFormatterCache.get(locale);
129 if (!formatter) {
130 formatter = new Intl.DateTimeFormat(locale, {
131 day: "numeric",
132 month: "long",
133 year: "numeric",
134 timeZone: "UTC",
135 });
136 longDateFormatterCache.set(locale, formatter);
137 }
138 return formatter;
140​
141function ordinalSuffix(day: number): string {
142 const lastTwo = day % 100;
143 if (lastTwo >= 11 && lastTwo <= 13) return "th";
144 switch (day % 10) {
145 case 1:
146 return "st";
147 case 2:
148 return "nd";
149 case 3:
150 return "rd";
151 default:
152 return "th";
153 }
155​
156export function formatChatTimestampTooltip(
157 isoDate: string,
158 timestampFormat: TimestampFormat,
159 resolve: MessageResolver = m,
160): string {
161 const date = parseTimestampDate(isoDate);
162 if (!date) return "";
163 const time = formatTime(date, timestampFormat);
164 const locale = getActiveLocale();
165 if (locale !== DEFAULT_LOCALE) {
166 const longDate = getLongDateFormatter(locale).format(wallClockAsUtc(date));
167 return resolve(
168 msg("{time}, {date}", { time, date: longDate, $context: "message time, then its date" }),
169 );
170 }
171 const day = date.getDate();
172 const month = monthNameFormatter.format(wallClockAsUtc(date));
173 const year = date.getFullYear();
174 return `${time}, ${day}${ordinalSuffix(day)} ${month} ${year}`;
176​
177export function formatFullTimestamp(isoDate: string, timestampFormat: TimestampFormat): string {
178 return new Date(isoDate).toLocaleString(
179 timestampLocale,
180 timestampFormat === "locale" ? undefined : { hour12: timestampFormat === "12-hour" },
181 );
183​
184export function formatShortTimestamp(
185 isoDate: string,
186 timestampFormat: TimestampFormat,
187 locale?: string,
188): string {
189 const date = parseTimestampDate(isoDate);
190 if (!date) return "";
191 return getTimestampFormatter(timestampFormat, false, "UTC", locale).format(wallClockAsUtc(date));
193​
194const dateTimeFormatterCache = new Map<TimestampFormat, Intl.DateTimeFormat>();
195​
196export function formatDateTimeTimestamp(isoDate: string, timestampFormat: TimestampFormat): string {
197 const date = parseTimestampDate(isoDate);
198 if (!date) return "";
199 let formatter = dateTimeFormatterCache.get(timestampFormat);
200 if (!formatter) {
201 formatter = new Intl.DateTimeFormat(timestampLocale, {
202 dateStyle: "medium",
203 timeStyle: "short",
204 timeZone: "UTC",
205 ...(timestampFormat === "locale" ? {} : { hour12: timestampFormat === "12-hour" }),
206 });
207 dateTimeFormatterCache.set(timestampFormat, formatter);
208 }
209 return formatter.format(wallClockAsUtc(date));
211​
212/** A wall-clock `H:MM` or `HH:MM` that names no date or zone, such as a daily schedule's time. */
213export function formatTimeOfDay(timeOfDay: string, timestampFormat: TimestampFormat): string {
214 const match = /^(\d{1,2}):(\d{2})$/.exec(timeOfDay);
215 if (!match) return timeOfDay;
216 // Default-zone formatters run in UTC, so the host zone cannot shift the wall time.
217 return getTimestampFormatter(timestampFormat, false).format(
218 Date.UTC(2000, 0, 1, Number(match[1]), Number(match[2])),
219 );
221​
222const numericDateOptions: Intl.DateTimeFormatOptions = { month: "numeric", day: "numeric" };
223const numericDateWithYearOptions: Intl.DateTimeFormatOptions = {
224 ...numericDateOptions,
225 year: "numeric",
226};
227const numericDateFormatter = new Intl.DateTimeFormat(timestampLocale, {
228 ...numericDateOptions,
229 timeZone: "UTC",
230});
231const numericDateWithYearFormatter = new Intl.DateTimeFormat(timestampLocale, {
232 ...numericDateWithYearOptions,
233 timeZone: "UTC",
234});
235​
236interface CalendarDay {
237 year: number;
238 /** Days since the epoch, so differences are whole days across DST shifts. */
239 index: number;
241​
242function calendarDay(date: Date, timeZone: string | undefined): CalendarDay {
243 if (!timeZone) {
244 const year = date.getFullYear();
245 return { year, index: Date.UTC(year, date.getMonth(), date.getDate()) / 86_400_000 };
246 }
247 const parts = new Intl.DateTimeFormat("en-US", {
248 timeZone,
249 year: "numeric",
250 month: "numeric",
251 day: "numeric",
252 }).formatToParts(date);
253 const part = (type: Intl.DateTimeFormatPartTypes) =>
254 Number(parts.find((entry) => entry.type === type)?.value);
255 const year = part("year");
256 return { year, index: Date.UTC(year, part("month") - 1, part("day")) / 86_400_000 };
258​
259function formatNumericDate(date: Date, sameYear: boolean, timeZone: string | undefined): string {
260 if (!timeZone) {
261 return (sameYear ? numericDateFormatter : numericDateWithYearFormatter).format(
262 wallClockAsUtc(date),
263 );
264 }
265 return new Intl.DateTimeFormat(timestampLocale, {
266 ...(sameYear ? numericDateOptions : numericDateWithYearOptions),
267 timeZone,
268 }).format(date);
270​
271export function formatDayAwareTimestamp(
272 isoDate: string,
273 timestampFormat: TimestampFormat,
274 nowMs: number = Date.now(),
275 timeZone?: string,
276 resolve: MessageResolver = m,
277): string {
278 const date = parseTimestampDate(isoDate);
279 if (!date) return "";
280 const time = formatTime(date, timestampFormat, timeZone);
281​
282 const today = calendarDay(new Date(nowMs), timeZone);
283 const messageDay = calendarDay(date, timeZone);
284 const dayDiff = today.index - messageDay.index;
285​
286 if (dayDiff <= 0) return time;
287 if (dayDiff === 1) return resolve(msg("yesterday at {time}", { time }));
288 return `${formatNumericDate(date, messageDay.year === today.year, timeZone)} ${time}`;
290​
291/** `timeZone` overrides the system's current zone. */
292export function formatUpcomingTimestamp(
293 isoDate: string,
294 timestampFormat: TimestampFormat,
295 nowMs: number = Date.now(),
296 timeZone?: string,
297 resolve: MessageResolver = m,
298): string {
299 const date = parseTimestampDate(isoDate);
300 if (!date) return "";
301 const time = formatTime(date, timestampFormat, timeZone);
302​
303 const today = calendarDay(new Date(nowMs), timeZone);
304 const targetDay = calendarDay(date, timeZone);
305 const dayDiff = targetDay.index - today.index;
306​
307 if (dayDiff < 0) {
308 return formatDayAwareTimestamp(isoDate, timestampFormat, nowMs, timeZone, resolve);
309 }
310 if (dayDiff === 0) return time;
311 if (dayDiff === 1) return resolve(msg("tomorrow at {time}", { time }));
312 return `${formatNumericDate(date, targetDay.year === today.year, timeZone)} ${time}`;
314​
315/** `label` is the whole phrase ("5m ago"); `value` and `suffix` split it for styled layouts. */
316type RelativeTimeParts = { value: string; suffix: string | null; label: string };
317export type RelativeTimeState =
318 | { status: "missing" }
319 | { status: "invalid" }
320 | ({ status: "relative" } & RelativeTimeParts);
321​
322const MINUTE_MS = 60_000;
323const HOUR_MS = 3_600_000;
324const DAY_MS = 86_400_000;
325​
326function relativeTimeUnitMs(elapsedMs: number): number {
327 if (elapsedMs < HOUR_MS) return MINUTE_MS;
328 if (elapsedMs < DAY_MS) return HOUR_MS;
329 return DAY_MS;
331​
332/** Elapsed time floored to formatRelativeTime precision; equal labels yield equal values. */
333export function relativeTimeElapsedMs(isoDate: string, nowMs: number = Date.now()): number | null {
334 const date = parseTimestampDate(isoDate);
335 if (!date) return null;
336 const elapsedMs = Math.max(0, nowMs - date.getTime());
337 const unitMs = relativeTimeUnitMs(elapsedMs);
338 return Math.floor(elapsedMs / unitMs) * unitMs;
340​
341export function msUntilRelativeTimeChange(
342 isoDate: string,
343 nowMs: number = Date.now(),
344): number | null {
345 const date = parseTimestampDate(isoDate);
346 if (!date) return null;
347 const elapsedMs = Math.max(0, nowMs - date.getTime());
348 const unitMs = relativeTimeUnitMs(elapsedMs);
349 const nextChangeMs = date.getTime() + (Math.floor(elapsedMs / unitMs) + 1) * unitMs;
350 // Delays above 2^31-1 fire immediately; cap safely and let callers reschedule.
351 return Math.min(nextChangeMs - nowMs, DAY_MS);
353​
354const secondsLabel = (count: number, resolve: MessageResolver) =>
355 resolve(msg("{count}s", { count, $context: "seconds, abbreviated" }));
356const minutesLabel = (count: number, resolve: MessageResolver) =>
357 resolve(msg("{count}m", { count, $context: "minutes, abbreviated" }));
358const hoursLabel = (count: number, resolve: MessageResolver) =>
359 resolve(msg("{count}h", { count, $context: "hours, abbreviated" }));
360const daysLabel = (count: number, resolve: MessageResolver) =>
361 resolve(msg("{count}d", { count, $context: "days, abbreviated" }));
362​
363function relativeElapsedLabel(elapsedMs: number, resolve: MessageResolver): string {
364 const seconds = Math.floor(elapsedMs / 1000);
365 if (seconds < 60) return resolve(msg("just now"));
366 const minutes = Math.floor(seconds / 60);
367 if (minutes < 60) return resolve(msg("{count}m ago", { count: minutes }));
368 const hours = Math.floor(minutes / 60);
369 if (hours < 24) return resolve(msg("{count}h ago", { count: hours }));
370 return resolve(msg("{count}d ago", { count: Math.floor(hours / 24) }));
372​
373export function formatRelativeElapsed(
374 elapsedMs: number,
375 resolve: MessageResolver = m,
376): RelativeTimeParts {
377 const label = relativeElapsedLabel(elapsedMs, resolve);
378 const seconds = Math.floor(elapsedMs / 1000);
379 if (seconds < 60) return { value: label, suffix: null, label };
380 const ago = resolve(msg("ago", { $context: "follows an elapsed time such as 5m" }));
381 const minutes = Math.floor(seconds / 60);
382 if (minutes < 60) return { value: minutesLabel(minutes, resolve), suffix: ago, label };
383 const hours = Math.floor(minutes / 60);
384 if (hours < 24) return { value: hoursLabel(hours, resolve), suffix: ago, label };
385 const days = Math.floor(hours / 24);
386 return { value: daysLabel(days, resolve), suffix: ago, label };
388​
389export function formatRelativeTime(
390 isoDate: string,
391 nowMs: number = Date.now(),
392 resolve: MessageResolver = m,
393): RelativeTimeParts | null {
394 const elapsedMs = relativeTimeElapsedMs(isoDate, nowMs);
395 return elapsedMs === null ? null : formatRelativeElapsed(elapsedMs, resolve);
397​
398export function formatRelativeTimeLabel(
399 isoDate: string,
400 nowMs: number = Date.now(),
401 resolve: MessageResolver = m,
402) {
403 const elapsedMs = relativeTimeElapsedMs(isoDate, nowMs);
404 return elapsedMs === null ? "" : relativeElapsedLabel(elapsedMs, resolve);
406​
407export function formatElapsedDurationLabel(
408 isoDate: string,
409 nowMs: number = Date.now(),
410 resolve: MessageResolver = m,
411): string {
412 const date = parseTimestampDate(isoDate);
413 if (!date) return "";
414 const diffMs = nowMs - date.getTime();
415 if (diffMs <= 0) return resolve(msg("just now"));
416​
417 const seconds = Math.floor(diffMs / 1000);
418 if (seconds < 5) return resolve(msg("just now"));
419 if (seconds < 60) return secondsLabel(seconds, resolve);
420​
421 const minutes = Math.floor(seconds / 60);
422 if (minutes < 60) return minutesLabel(minutes, resolve);
423​
424 const hours = Math.floor(minutes / 60);
425 if (hours < 24) return hoursLabel(hours, resolve);
426​
427 const days = Math.floor(hours / 24);
428 return daysLabel(days, resolve);
430​
431/** Pass nowMs to match a parent-driven render tick. */
432export function formatExpiresInLabel(
433 isoDate: string,
434 nowMs: number = Date.now(),
435 resolve: MessageResolver = m,
436): string {
437 const date = parseTimestampDate(isoDate);
438 if (!date) return "";
439 const diffMs = date.getTime() - nowMs;
440 if (diffMs <= 0) return resolve(msg("Expired"));
441​
442 const totalSeconds = Math.floor(diffMs / 1000);
443 if (totalSeconds < 5) return resolve(msg("Expires in a moment"));
444 const expiresIn = (parts: string[]) =>
445 resolve(msg("Expires in {duration}", { duration: parts.join(" ") }));
446 if (totalSeconds < 60) return expiresIn([secondsLabel(totalSeconds, resolve)]);
447​
448 if (totalSeconds < 3600) {
449 const minutes = Math.floor(totalSeconds / 60);
450 const seconds = totalSeconds % 60;
451 return seconds === 0
452 ? expiresIn([minutesLabel(minutes, resolve)])
453 : expiresIn([minutesLabel(minutes, resolve), secondsLabel(seconds, resolve)]);
454 }
455​
456 if (totalSeconds < 86_400) {
457 const hours = Math.floor(totalSeconds / 3600);
458 const rem = totalSeconds % 3600;
459 const minutes = Math.floor(rem / 60);
460 const seconds = rem % 60;
461 const parts = [hoursLabel(hours, resolve)];
462 if (minutes > 0) parts.push(minutesLabel(minutes, resolve));
463 if (seconds > 0) parts.push(secondsLabel(seconds, resolve));
464 return expiresIn(parts);
465 }
466​
467 const days = Math.floor(totalSeconds / 86_400);
468 const remAfterDays = totalSeconds % 86_400;
469 if (remAfterDays === 0) return expiresIn([daysLabel(days, resolve)]);
470 const hours = Math.floor(remAfterDays / 3600);
471 const rem = remAfterDays % 3600;
472 const minutes = Math.floor(rem / 60);
473 const seconds = rem % 60;
474 const parts = [daysLabel(days, resolve)];
475 if (hours > 0) parts.push(hoursLabel(hours, resolve));
476 if (minutes > 0) parts.push(minutesLabel(minutes, resolve));
477 if (seconds > 0) parts.push(secondsLabel(seconds, resolve));
478 return expiresIn(parts);