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
94const numericDateFormatter = new Intl.DateTimeFormat(undefined, {
95 month: "numeric",
96 day: "numeric",
97});
98const numericDateWithYearFormatter = new Intl.DateTimeFormat(undefined, {
99 month: "numeric",
100 day: "numeric",
101 year: "numeric",
102});
103
104/**
105 * Chat timestamp that adds the date once the message is no longer from today:
106 * today `12:34 PM`, yesterday `yesterday at 12:34 PM`, older `8/13 12:34 PM`
107 * (locale digit order), with the year included once the calendar year differs.
108 * Boundaries are local calendar days, not 24-hour windows.
109 */
110export function formatDayAwareTimestamp(
111 isoDate: string,
112 timestampFormat: TimestampFormat,
113 nowMs: number = Date.now(),
114): string {
115 const date = parseTimestampDate(isoDate);
116 if (!date) return "";
117 const time = getTimestampFormatter(timestampFormat, false).format(date);
118
119 const now = new Date(nowMs);
120 const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
121 const startOfMessageDay = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
122 // Round so DST-shifted 23/25 hour days still count as whole days.
123 const dayDiff = Math.round((startOfToday - startOfMessageDay) / 86_400_000);
124
125 if (dayDiff <= 0) return time;
126 if (dayDiff === 1) return `yesterday at ${time}`;
127 const dateFormatter =
128 date.getFullYear() === now.getFullYear() ? numericDateFormatter : numericDateWithYearFormatter;
129 return `${dateFormatter.format(date)} ${time}`;
130}
131
132/**
133 * Format a relative time string from an ISO date.
134 * Returns `{ value: "20s", suffix: "ago" }` or `{ value: "just now", suffix: null }`
135 * so callers can style the numeric portion independently.
136 */
137type RelativeTimeParts = { value: string; suffix: string | null };
138export type RelativeTimeState =
139 | { status: "missing" }
140 | { status: "invalid" }
141 | { status: "relative"; value: string; suffix: string | null };
142
143export function formatRelativeTime(isoDate: string): RelativeTimeParts | null {
144 const date = parseTimestampDate(isoDate);
145 if (!date) return null;
146 const diffMs = Date.now() - date.getTime();
147 if (diffMs < 0) return { value: "just now", suffix: null };
148 const seconds = Math.floor(diffMs / 1000);
149 if (seconds < 60) return { value: "just now", suffix: null };
150 const minutes = Math.floor(seconds / 60);
151 if (minutes < 60) return { value: `${minutes}m`, suffix: "ago" };
152 const hours = Math.floor(minutes / 60);
153 if (hours < 24) return { value: `${hours}h`, suffix: "ago" };
154 const days = Math.floor(hours / 24);
155 return { value: `${days}d`, suffix: "ago" };
156}
157
158export function formatRelativeTimeLabel(isoDate: string) {
159 const relative = formatRelativeTime(isoDate);
160 if (!relative) return "";
161 return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
162}
163
164export function getRelativeTimeState(isoDate: string | null): RelativeTimeState {
165 if (!isoDate) return { status: "missing" };
166 const relative = formatRelativeTime(isoDate);
167 if (!relative) return { status: "invalid" };
168 return { status: "relative", ...relative };
169}
170
171/**
172 * Relative elapsed duration since an ISO instant, without an "ago" suffix.
173 * Useful for labels like "Connected for 3m".
174 */
175export function formatElapsedDurationLabel(isoDate: string, nowMs: number = Date.now()): string {
176 const date = parseTimestampDate(isoDate);
177 if (!date) return "";
178 const diffMs = nowMs - date.getTime();
179 if (diffMs <= 0) return "just now";
180
181 const seconds = Math.floor(diffMs / 1000);
182 if (seconds < 5) return "just now";
183 if (seconds < 60) return `${seconds}s`;
184
185 const minutes = Math.floor(seconds / 60);
186 if (minutes < 60) return `${minutes}m`;
187
188 const hours = Math.floor(minutes / 60);
189 if (hours < 24) return `${hours}h`;
190
191 const days = Math.floor(hours / 24);
192 return `${days}d`;
193}
194
195/**
196 * Relative time until an ISO instant (e.g. expiry). Mirrors {@link formatRelativeTime} but for future times.
197 */
198export function formatRelativeTimeUntil(isoDate: string): RelativeTimeParts | null {
199 const date = parseTimestampDate(isoDate);
200 if (!date) return null;
201 const diffMs = date.getTime() - Date.now();
202 if (diffMs <= 0) return { value: "Expired", suffix: null };
203 const seconds = Math.floor(diffMs / 1000);
204 if (seconds < 5) return { value: "Soon", suffix: null };
205 if (seconds < 60) return { value: `${seconds}s`, suffix: "left" };
206 const minutes = Math.floor(seconds / 60);
207 if (minutes < 60) return { value: `${minutes}m`, suffix: "left" };
208 const hours = Math.floor(minutes / 60);
209 if (hours < 24) return { value: `${hours}h`, suffix: "left" };
210 const days = Math.floor(hours / 24);
211 return { value: `${days}d`, suffix: "left" };
212}
213
214export function formatRelativeTimeUntilLabel(isoDate: string): string {
215 const relative = formatRelativeTimeUntil(isoDate);
216 if (!relative) return "";
217 return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
218}
219
220/**
221 * Countdown for a future instant (e.g. link expiry): "Expires in 4m 12s", with second precision under one hour.
222 * Pass `nowMs` when a parent tick drives re-renders so the diff matches that snapshot.
223 */
224export function formatExpiresInLabel(isoDate: string, nowMs: number = Date.now()): string {
225 const date = parseTimestampDate(isoDate);
226 if (!date) return "";
227 const diffMs = date.getTime() - nowMs;
228 if (diffMs <= 0) return "Expired";
229
230 const totalSeconds = Math.floor(diffMs / 1000);
231 if (totalSeconds < 5) return "Expires in a moment";
232 if (totalSeconds < 60) return `Expires in ${totalSeconds}s`;
233
234 if (totalSeconds < 3600) {
235 const minutes = Math.floor(totalSeconds / 60);
236 const seconds = totalSeconds % 60;
237 return seconds === 0 ? `Expires in ${minutes}m` : `Expires in ${minutes}m ${seconds}s`;
238 }
239
240 if (totalSeconds < 86_400) {
241 const hours = Math.floor(totalSeconds / 3600);
242 const rem = totalSeconds % 3600;
243 const minutes = Math.floor(rem / 60);
244 const seconds = rem % 60;
245 const parts = [`${hours}h`];
246 if (minutes > 0) parts.push(`${minutes}m`);
247 if (seconds > 0) parts.push(`${seconds}s`);
248 return `Expires in ${parts.join(" ")}`;
249 }
250
251 const days = Math.floor(totalSeconds / 86_400);
252 const remAfterDays = totalSeconds % 86_400;
253 if (remAfterDays === 0) return `Expires in ${days}d`;
254 const hours = Math.floor(remAfterDays / 3600);
255 const rem = remAfterDays % 3600;
256 const minutes = Math.floor(rem / 60);
257 const seconds = rem % 60;
258 const tail: string[] = [];
259 if (hours > 0) tail.push(`${hours}h`);
260 if (minutes > 0) tail.push(`${minutes}m`);
261 if (seconds > 0) tail.push(`${seconds}s`);
262 return tail.length > 0 ? `Expires in ${days}d ${tail.join(" ")}` : `Expires in ${days}d`;
263}