Open History to see the last commit
1import { type TimestampFormat } from "@t3tools/contracts/settings";
2
3export function 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 };
21}
22
23const timestampFormatterCache = new Map<string, Intl.DateTimeFormat>();
24
25function getTimestampFormatter(
26 timestampFormat: TimestampFormat,
27 includeSeconds: boolean,
28): Intl.DateTimeFormat {
29 const cacheKey = `${timestampFormat}:${includeSeconds ? "seconds" : "minutes"}`;
30 const cachedFormatter = timestampFormatterCache.get(cacheKey);
31 if (cachedFormatter) {
32 return cachedFormatter;
33 }
34
35 const formatter = new Intl.DateTimeFormat(
36 undefined,
37 getTimestampFormatOptions(timestampFormat, includeSeconds),
38 );
39 timestampFormatterCache.set(cacheKey, formatter);
40 return formatter;
41}
42
43export function parseTimestampDate(isoDate: string): Date | null {
44 const date = new Date(isoDate);
45 return Number.isNaN(date.getTime()) ? null : date;
46}
47
48export function formatTimestamp(isoDate: string, timestampFormat: TimestampFormat): string {
49 const date = parseTimestampDate(isoDate);
50 if (!date) return "";
51 return getTimestampFormatter(timestampFormat, true).format(date);
52}
53
54const monthNameFormatter = new Intl.DateTimeFormat(undefined, { month: "long" });
55
56function ordinalSuffix(day: number): string {
57 const lastTwo = day % 100;
58 if (lastTwo >= 11 && lastTwo <= 13) return "th";
59 switch (day % 10) {
60 case 1:
61 return "st";
62 case 2:
63 return "nd";
64 case 3:
65 return "rd";
66 default:
67 return "th";
68 }
69}
70
71/**
72 * Long-form tooltip label, e.g. `12:04, 4th June`.
73 * Renders the wall-clock time without seconds followed by the ordinal day and month name.
74 */
75export function formatChatTimestampTooltip(
76 isoDate: string,
77 timestampFormat: TimestampFormat,
78): string {
79 const date = parseTimestampDate(isoDate);
80 if (!date) return "";
81 const time = formatShortTimestamp(isoDate, timestampFormat);
82 const day = date.getDate();
83 const month = monthNameFormatter.format(date);
84 const year = date.getFullYear();
85 return `${time}, ${day}${ordinalSuffix(day)} ${month} ${year}`;
86}
87
88export function formatShortTimestamp(isoDate: string, timestampFormat: TimestampFormat): string {
89 const date = parseTimestampDate(isoDate);
90 if (!date) return "";
91 return getTimestampFormatter(timestampFormat, false).format(date);
92}
93
94/**
95 * Format a relative time string from an ISO date.
96 * Returns `{ value: "20s", suffix: "ago" }` or `{ value: "just now", suffix: null }`
97 * so callers can style the numeric portion independently.
98 */
99type RelativeTimeParts = { value: string; suffix: string | null };
100export type RelativeTimeState =
101 | { status: "missing" }
102 | { status: "invalid" }
103 | { status: "relative"; value: string; suffix: string | null };
104
105export function formatRelativeTime(isoDate: string): RelativeTimeParts | null {
106 const date = parseTimestampDate(isoDate);
107 if (!date) return null;
108 const diffMs = Date.now() - date.getTime();
109 if (diffMs < 0) return { value: "just now", suffix: null };
110 const seconds = Math.floor(diffMs / 1000);
111 if (seconds < 60) return { value: "just now", suffix: null };
112 const minutes = Math.floor(seconds / 60);
113 if (minutes < 60) return { value: `${minutes}m`, suffix: "ago" };
114 const hours = Math.floor(minutes / 60);
115 if (hours < 24) return { value: `${hours}h`, suffix: "ago" };
116 const days = Math.floor(hours / 24);
117 return { value: `${days}d`, suffix: "ago" };
118}
119
120export function formatRelativeTimeLabel(isoDate: string) {
121 const relative = formatRelativeTime(isoDate);
122 if (!relative) return "";
123 return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
124}
125
126export function getRelativeTimeState(isoDate: string | null): RelativeTimeState {
127 if (!isoDate) return { status: "missing" };
128 const relative = formatRelativeTime(isoDate);
129 if (!relative) return { status: "invalid" };
130 return { status: "relative", ...relative };
131}
132
133/**
134 * Relative elapsed duration since an ISO instant, without an "ago" suffix.
135 * Useful for labels like "Connected for 3m".
136 */
137export function formatElapsedDurationLabel(isoDate: string, nowMs: number = Date.now()): string {
138 const date = parseTimestampDate(isoDate);
139 if (!date) return "";
140 const diffMs = nowMs - date.getTime();
141 if (diffMs <= 0) return "just now";
142
143 const seconds = Math.floor(diffMs / 1000);
144 if (seconds < 5) return "just now";
145 if (seconds < 60) return `${seconds}s`;
146
147 const minutes = Math.floor(seconds / 60);
148 if (minutes < 60) return `${minutes}m`;
149
150 const hours = Math.floor(minutes / 60);
151 if (hours < 24) return `${hours}h`;
152
153 const days = Math.floor(hours / 24);
154 return `${days}d`;
155}
156
157/**
158 * Relative time until an ISO instant (e.g. expiry). Mirrors {@link formatRelativeTime} but for future times.
159 */
160export function formatRelativeTimeUntil(isoDate: string): RelativeTimeParts | null {
161 const date = parseTimestampDate(isoDate);
162 if (!date) return null;
163 const diffMs = date.getTime() - Date.now();
164 if (diffMs <= 0) return { value: "Expired", suffix: null };
165 const seconds = Math.floor(diffMs / 1000);
166 if (seconds < 5) return { value: "Soon", suffix: null };
167 if (seconds < 60) return { value: `${seconds}s`, suffix: "left" };
168 const minutes = Math.floor(seconds / 60);
169 if (minutes < 60) return { value: `${minutes}m`, suffix: "left" };
170 const hours = Math.floor(minutes / 60);
171 if (hours < 24) return { value: `${hours}h`, suffix: "left" };
172 const days = Math.floor(hours / 24);
173 return { value: `${days}d`, suffix: "left" };
174}
175
176export function formatRelativeTimeUntilLabel(isoDate: string): string {
177 const relative = formatRelativeTimeUntil(isoDate);
178 if (!relative) return "";
179 return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
180}
181
182/**
183 * Countdown for a future instant (e.g. link expiry): "Expires in 4m 12s", with second precision under one hour.
184 * Pass `nowMs` when a parent tick drives re-renders so the diff matches that snapshot.
185 */
186export function formatExpiresInLabel(isoDate: string, nowMs: number = Date.now()): string {
187 const date = parseTimestampDate(isoDate);
188 if (!date) return "";
189 const diffMs = date.getTime() - nowMs;
190 if (diffMs <= 0) return "Expired";
191
192 const totalSeconds = Math.floor(diffMs / 1000);
193 if (totalSeconds < 5) return "Expires in a moment";
194 if (totalSeconds < 60) return `Expires in ${totalSeconds}s`;
195
196 if (totalSeconds < 3600) {
197 const minutes = Math.floor(totalSeconds / 60);
198 const seconds = totalSeconds % 60;
199 return seconds === 0 ? `Expires in ${minutes}m` : `Expires in ${minutes}m ${seconds}s`;
200 }
201
202 if (totalSeconds < 86_400) {
203 const hours = Math.floor(totalSeconds / 3600);
204 const rem = totalSeconds % 3600;
205 const minutes = Math.floor(rem / 60);
206 const seconds = rem % 60;
207 const parts = [`${hours}h`];
208 if (minutes > 0) parts.push(`${minutes}m`);
209 if (seconds > 0) parts.push(`${seconds}s`);
210 return `Expires in ${parts.join(" ")}`;
211 }
212
213 const days = Math.floor(totalSeconds / 86_400);
214 const remAfterDays = totalSeconds % 86_400;
215 if (remAfterDays === 0) return `Expires in ${days}d`;
216 const hours = Math.floor(remAfterDays / 3600);
217 const rem = remAfterDays % 3600;
218 const minutes = Math.floor(rem / 60);
219 const seconds = rem % 60;
220 const tail: string[] = [];
221 if (hours > 0) tail.push(`${hours}h`);
222 if (minutes > 0) tail.push(`${minutes}m`);
223 if (seconds > 0) tail.push(`${seconds}s`);
224 return tail.length > 0 ? `Expires in ${days}d ${tail.join(" ")}` : `Expires in ${days}d`;
225}