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

timestampFormat.ts

316 lines10.7 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): Intl.DateTimeFormat {
77 const cacheKey = `${timestampFormat}:${includeSeconds ? "seconds" : "minutes"}`;
78 const cachedFormatter = timestampFormatterCache.get(cacheKey);
79 if (cachedFormatter) {
80 return cachedFormatter;
81 }
82​
83 const formatter = new Intl.DateTimeFormat(
84 timestampLocale,
85 getTimestampFormatOptions(timestampFormat, includeSeconds),
86 );
87 timestampFormatterCache.set(cacheKey, formatter);
88 return formatter;
90​
91export function resolveHour12(timestampFormat: TimestampFormat): boolean {
92 return getTimestampFormatter(timestampFormat, false).resolvedOptions().hour12 ?? false;
94​
95export function parseTimestampDate(isoDate: string): Date | null {
96 const date = new Date(isoDate);
97 return Number.isNaN(date.getTime()) ? null : date;
99​
100// Deliberately not the host locale: the tooltip's ordinal suffix and
101// day-before-month order below are English, so a localized month alone would
102// read "4th Juni 2026".
103const monthNameFormatter = new Intl.DateTimeFormat("en-US", { month: "long" });
104​
105function ordinalSuffix(day: number): string {
106 const lastTwo = day % 100;
107 if (lastTwo >= 11 && lastTwo <= 13) return "th";
108 switch (day % 10) {
109 case 1:
110 return "st";
111 case 2:
112 return "nd";
113 case 3:
114 return "rd";
115 default:
116 return "th";
117 }
119​
120export function formatChatTimestampTooltip(
121 isoDate: string,
122 timestampFormat: TimestampFormat,
123): string {
124 const date = parseTimestampDate(isoDate);
125 if (!date) return "";
126 const time = formatShortTimestamp(isoDate, timestampFormat);
127 const day = date.getDate();
128 const month = monthNameFormatter.format(date);
129 const year = date.getFullYear();
130 return `${time}, ${day}${ordinalSuffix(day)} ${month} ${year}`;
132​
133export function formatShortTimestamp(isoDate: string, timestampFormat: TimestampFormat): string {
134 const date = parseTimestampDate(isoDate);
135 if (!date) return "";
136 return getTimestampFormatter(timestampFormat, false).format(date);
138​
139const numericDateFormatter = new Intl.DateTimeFormat(timestampLocale, {
140 month: "numeric",
141 day: "numeric",
142});
143const numericDateWithYearFormatter = new Intl.DateTimeFormat(timestampLocale, {
144 month: "numeric",
145 day: "numeric",
146 year: "numeric",
147});
148​
149export function formatDayAwareTimestamp(
150 isoDate: string,
151 timestampFormat: TimestampFormat,
152 nowMs: number = Date.now(),
153): string {
154 const date = parseTimestampDate(isoDate);
155 if (!date) return "";
156 const time = getTimestampFormatter(timestampFormat, false).format(date);
157​
158 const now = new Date(nowMs);
159 const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
160 const startOfMessageDay = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
161 // Round so DST-shifted 23/25 hour days still count as whole days.
162 const dayDiff = Math.round((startOfToday - startOfMessageDay) / 86_400_000);
163​
164 if (dayDiff <= 0) return time;
165 if (dayDiff === 1) return `yesterday at ${time}`;
166 const dateFormatter =
167 date.getFullYear() === now.getFullYear() ? numericDateFormatter : numericDateWithYearFormatter;
168 return `${dateFormatter.format(date)} ${time}`;
170​
171export function formatUpcomingTimestamp(
172 isoDate: string,
173 timestampFormat: TimestampFormat,
174 nowMs: number = Date.now(),
175): string {
176 const date = parseTimestampDate(isoDate);
177 if (!date) return "";
178 const time = getTimestampFormatter(timestampFormat, false).format(date);
179​
180 const now = new Date(nowMs);
181 const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
182 const startOfTargetDay = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
183 const dayDiff = Math.round((startOfTargetDay - startOfToday) / 86_400_000);
184​
185 if (dayDiff < 0) return formatDayAwareTimestamp(isoDate, timestampFormat, nowMs);
186 if (dayDiff === 0) return time;
187 if (dayDiff === 1) return `tomorrow at ${time}`;
188 const dateFormatter =
189 date.getFullYear() === now.getFullYear() ? numericDateFormatter : numericDateWithYearFormatter;
190 return `${dateFormatter.format(date)} ${time}`;
192​
193type RelativeTimeParts = { value: string; suffix: string | null };
194export type RelativeTimeState =
195 | { status: "missing" }
196 | { status: "invalid" }
197 | { status: "relative"; value: string; suffix: string | null };
198​
199const MINUTE_MS = 60_000;
200const HOUR_MS = 3_600_000;
201const DAY_MS = 86_400_000;
202​
203function relativeTimeUnitMs(elapsedMs: number): number {
204 if (elapsedMs < HOUR_MS) return MINUTE_MS;
205 if (elapsedMs < DAY_MS) return HOUR_MS;
206 return DAY_MS;
208​
209/** Elapsed time floored to formatRelativeTime precision; equal labels yield equal values. */
210export function relativeTimeElapsedMs(isoDate: string, nowMs: number = Date.now()): number | null {
211 const date = parseTimestampDate(isoDate);
212 if (!date) return null;
213 const elapsedMs = Math.max(0, nowMs - date.getTime());
214 const unitMs = relativeTimeUnitMs(elapsedMs);
215 return Math.floor(elapsedMs / unitMs) * unitMs;
217​
218export function msUntilRelativeTimeChange(
219 isoDate: string,
220 nowMs: number = Date.now(),
221): number | null {
222 const date = parseTimestampDate(isoDate);
223 if (!date) return null;
224 const elapsedMs = Math.max(0, nowMs - date.getTime());
225 const unitMs = relativeTimeUnitMs(elapsedMs);
226 const nextChangeMs = date.getTime() + (Math.floor(elapsedMs / unitMs) + 1) * unitMs;
227 // Delays above 2^31-1 fire immediately; cap safely and let callers reschedule.
228 return Math.min(nextChangeMs - nowMs, DAY_MS);
230​
231export function formatRelativeElapsed(elapsedMs: number): RelativeTimeParts {
232 const seconds = Math.floor(elapsedMs / 1000);
233 if (seconds < 60) return { value: "just now", suffix: null };
234 const minutes = Math.floor(seconds / 60);
235 if (minutes < 60) return { value: `${minutes}m`, suffix: "ago" };
236 const hours = Math.floor(minutes / 60);
237 if (hours < 24) return { value: `${hours}h`, suffix: "ago" };
238 const days = Math.floor(hours / 24);
239 return { value: `${days}d`, suffix: "ago" };
241​
242export function formatRelativeTime(
243 isoDate: string,
244 nowMs: number = Date.now(),
245): RelativeTimeParts | null {
246 const elapsedMs = relativeTimeElapsedMs(isoDate, nowMs);
247 return elapsedMs === null ? null : formatRelativeElapsed(elapsedMs);
249​
250export function formatRelativeTimeLabel(isoDate: string, nowMs: number = Date.now()) {
251 const relative = formatRelativeTime(isoDate, nowMs);
252 if (!relative) return "";
253 return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
255​
256export function formatElapsedDurationLabel(isoDate: string, nowMs: number = Date.now()): string {
257 const date = parseTimestampDate(isoDate);
258 if (!date) return "";
259 const diffMs = nowMs - date.getTime();
260 if (diffMs <= 0) return "just now";
261​
262 const seconds = Math.floor(diffMs / 1000);
263 if (seconds < 5) return "just now";
264 if (seconds < 60) return `${seconds}s`;
265​
266 const minutes = Math.floor(seconds / 60);
267 if (minutes < 60) return `${minutes}m`;
268​
269 const hours = Math.floor(minutes / 60);
270 if (hours < 24) return `${hours}h`;
271​
272 const days = Math.floor(hours / 24);
273 return `${days}d`;
275​
276/** Pass nowMs to match a parent-driven render tick. */
277export function formatExpiresInLabel(isoDate: string, nowMs: number = Date.now()): string {
278 const date = parseTimestampDate(isoDate);
279 if (!date) return "";
280 const diffMs = date.getTime() - nowMs;
281 if (diffMs <= 0) return "Expired";
282​
283 const totalSeconds = Math.floor(diffMs / 1000);
284 if (totalSeconds < 5) return "Expires in a moment";
285 if (totalSeconds < 60) return `Expires in ${totalSeconds}s`;
286​
287 if (totalSeconds < 3600) {
288 const minutes = Math.floor(totalSeconds / 60);
289 const seconds = totalSeconds % 60;
290 return seconds === 0 ? `Expires in ${minutes}m` : `Expires in ${minutes}m ${seconds}s`;
291 }
292​
293 if (totalSeconds < 86_400) {
294 const hours = Math.floor(totalSeconds / 3600);
295 const rem = totalSeconds % 3600;
296 const minutes = Math.floor(rem / 60);
297 const seconds = rem % 60;
298 const parts = [`${hours}h`];
299 if (minutes > 0) parts.push(`${minutes}m`);
300 if (seconds > 0) parts.push(`${seconds}s`);
301 return `Expires in ${parts.join(" ")}`;
302 }
303​
304 const days = Math.floor(totalSeconds / 86_400);
305 const remAfterDays = totalSeconds % 86_400;
306 if (remAfterDays === 0) return `Expires in ${days}d`;
307 const hours = Math.floor(remAfterDays / 3600);
308 const rem = remAfterDays % 3600;
309 const minutes = Math.floor(rem / 60);
310 const seconds = rem % 60;
311 const tail: string[] = [];
312 if (hours > 0) tail.push(`${hours}h`);
313 if (minutes > 0) tail.push(`${minutes}m`);
314 if (seconds > 0) tail.push(`${seconds}s`);
315 return tail.length > 0 ? `Expires in ${days}d ${tail.join(" ")}` : `Expires in ${days}d`;