The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 03:37 UTC
| 1 | import { type TimestampFormat } from "@t3tools/contracts/settings"; |
| 2 | import { msg } from "gt-react"; |
| 3 | |
| 4 | import { DEFAULT_LOCALE } from "./i18n/locales"; |
| 5 | import { getActiveLocale, m, type MessageResolver } from "./i18n/messages"; |
| 6 | |
| 7 | function 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 | }; |
| 25 | } |
| 26 | |
| 27 | function 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 | } |
| 38 | } |
| 39 | |
| 40 | function readHostSystemLocale(): string | null { |
| 41 | if (typeof window === "undefined") return null; |
| 42 | return window.desktopBridge?.getSystemLocale() ?? null; |
| 43 | } |
| 44 | |
| 45 | const timestampLocale = resolveTimestampLocale(readHostSystemLocale()); |
| 46 | |
| 47 | const WEEKDAY_INDEXES = [0, 1, 2, 3, 4, 5, 6] as const; |
| 48 | type WeekdayIndex = (typeof WEEKDAY_INDEXES)[number]; |
| 49 | |
| 50 | type 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 | */ |
| 60 | function 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 | } |
| 71 | } |
| 72 | |
| 73 | export 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. |
| 77 | function wallClockAsUtc(date: Date): Date { |
| 78 | return new Date(date.getTime() - date.getTimezoneOffset() * 60_000); |
| 79 | } |
| 80 | |
| 81 | const timestampFormatterCache = new Map<string, Intl.DateTimeFormat>(); |
| 82 | |
| 83 | function getTimestampFormatter( |
| 84 | timestampFormat: TimestampFormat, |
| 85 | includeSeconds: boolean, |
| 86 | timeZone = "UTC", |
| 87 | ): Intl.DateTimeFormat { |
| 88 | const cacheKey = `${timestampFormat}:${includeSeconds ? "seconds" : "minutes"}:${timeZone}`; |
| 89 | const cachedFormatter = timestampFormatterCache.get(cacheKey); |
| 90 | if (cachedFormatter) { |
| 91 | return cachedFormatter; |
| 92 | } |
| 93 | |
| 94 | const formatter = new Intl.DateTimeFormat(timestampLocale, { |
| 95 | ...getTimestampFormatOptions(timestampFormat, includeSeconds), |
| 96 | timeZone, |
| 97 | }); |
| 98 | timestampFormatterCache.set(cacheKey, formatter); |
| 99 | return formatter; |
| 100 | } |
| 101 | |
| 102 | function formatTime(date: Date, timestampFormat: TimestampFormat, timeZone?: string): string { |
| 103 | return timeZone |
| 104 | ? getTimestampFormatter(timestampFormat, false, timeZone).format(date) |
| 105 | : getTimestampFormatter(timestampFormat, false).format(wallClockAsUtc(date)); |
| 106 | } |
| 107 | |
| 108 | export function resolveHour12(timestampFormat: TimestampFormat): boolean { |
| 109 | return getTimestampFormatter(timestampFormat, false).resolvedOptions().hour12 ?? false; |
| 110 | } |
| 111 | |
| 112 | export function parseTimestampDate(isoDate: string): Date | null { |
| 113 | const date = new Date(isoDate); |
| 114 | return Number.isNaN(date.getTime()) ? null : date; |
| 115 | } |
| 116 | |
| 117 | // English keeps its ordinal day-before-month form; other UI languages use their own long date. |
| 118 | const monthNameFormatter = new Intl.DateTimeFormat("en-US", { month: "long", timeZone: "UTC" }); |
| 119 | const longDateFormatterCache = new Map<string, Intl.DateTimeFormat>(); |
| 120 | |
| 121 | function getLongDateFormatter(locale: string): Intl.DateTimeFormat { |
| 122 | let formatter = longDateFormatterCache.get(locale); |
| 123 | if (!formatter) { |
| 124 | formatter = new Intl.DateTimeFormat(locale, { |
| 125 | day: "numeric", |
| 126 | month: "long", |
| 127 | year: "numeric", |
| 128 | timeZone: "UTC", |
| 129 | }); |
| 130 | longDateFormatterCache.set(locale, formatter); |
| 131 | } |
| 132 | return formatter; |
| 133 | } |
| 134 | |
| 135 | function ordinalSuffix(day: number): string { |
| 136 | const lastTwo = day % 100; |
| 137 | if (lastTwo >= 11 && lastTwo <= 13) return "th"; |
| 138 | switch (day % 10) { |
| 139 | case 1: |
| 140 | return "st"; |
| 141 | case 2: |
| 142 | return "nd"; |
| 143 | case 3: |
| 144 | return "rd"; |
| 145 | default: |
| 146 | return "th"; |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | export function formatChatTimestampTooltip( |
| 151 | isoDate: string, |
| 152 | timestampFormat: TimestampFormat, |
| 153 | resolve: MessageResolver = m, |
| 154 | ): string { |
| 155 | const date = parseTimestampDate(isoDate); |
| 156 | if (!date) return ""; |
| 157 | const time = formatTime(date, timestampFormat); |
| 158 | const locale = getActiveLocale(); |
| 159 | if (locale !== DEFAULT_LOCALE) { |
| 160 | const longDate = getLongDateFormatter(locale).format(wallClockAsUtc(date)); |
| 161 | return resolve( |
| 162 | msg("{time}, {date}", { time, date: longDate, $context: "message time, then its date" }), |
| 163 | ); |
| 164 | } |
| 165 | const day = date.getDate(); |
| 166 | const month = monthNameFormatter.format(wallClockAsUtc(date)); |
| 167 | const year = date.getFullYear(); |
| 168 | return `${time}, ${day}${ordinalSuffix(day)} ${month} ${year}`; |
| 169 | } |
| 170 | |
| 171 | export function formatFullTimestamp(isoDate: string, timestampFormat: TimestampFormat): string { |
| 172 | return new Date(isoDate).toLocaleString( |
| 173 | undefined, |
| 174 | timestampFormat === "locale" ? undefined : { hour12: timestampFormat === "12-hour" }, |
| 175 | ); |
| 176 | } |
| 177 | |
| 178 | export function formatShortTimestamp(isoDate: string, timestampFormat: TimestampFormat): string { |
| 179 | const date = parseTimestampDate(isoDate); |
| 180 | if (!date) return ""; |
| 181 | return formatTime(date, timestampFormat); |
| 182 | } |
| 183 | |
| 184 | const numericDateOptions: Intl.DateTimeFormatOptions = { month: "numeric", day: "numeric" }; |
| 185 | const numericDateWithYearOptions: Intl.DateTimeFormatOptions = { |
| 186 | ...numericDateOptions, |
| 187 | year: "numeric", |
| 188 | }; |
| 189 | const numericDateFormatter = new Intl.DateTimeFormat(timestampLocale, { |
| 190 | ...numericDateOptions, |
| 191 | timeZone: "UTC", |
| 192 | }); |
| 193 | const numericDateWithYearFormatter = new Intl.DateTimeFormat(timestampLocale, { |
| 194 | ...numericDateWithYearOptions, |
| 195 | timeZone: "UTC", |
| 196 | }); |
| 197 | |
| 198 | interface CalendarDay { |
| 199 | year: number; |
| 200 | /** Days since the epoch, so differences are whole days across DST shifts. */ |
| 201 | index: number; |
| 202 | } |
| 203 | |
| 204 | function calendarDay(date: Date, timeZone: string | undefined): CalendarDay { |
| 205 | if (!timeZone) { |
| 206 | const year = date.getFullYear(); |
| 207 | return { year, index: Date.UTC(year, date.getMonth(), date.getDate()) / 86_400_000 }; |
| 208 | } |
| 209 | const parts = new Intl.DateTimeFormat("en-US", { |
| 210 | timeZone, |
| 211 | year: "numeric", |
| 212 | month: "numeric", |
| 213 | day: "numeric", |
| 214 | }).formatToParts(date); |
| 215 | const part = (type: Intl.DateTimeFormatPartTypes) => |
| 216 | Number(parts.find((entry) => entry.type === type)?.value); |
| 217 | const year = part("year"); |
| 218 | return { year, index: Date.UTC(year, part("month") - 1, part("day")) / 86_400_000 }; |
| 219 | } |
| 220 | |
| 221 | function formatNumericDate(date: Date, sameYear: boolean, timeZone: string | undefined): string { |
| 222 | if (!timeZone) { |
| 223 | return (sameYear ? numericDateFormatter : numericDateWithYearFormatter).format( |
| 224 | wallClockAsUtc(date), |
| 225 | ); |
| 226 | } |
| 227 | return new Intl.DateTimeFormat(timestampLocale, { |
| 228 | ...(sameYear ? numericDateOptions : numericDateWithYearOptions), |
| 229 | timeZone, |
| 230 | }).format(date); |
| 231 | } |
| 232 | |
| 233 | export function formatDayAwareTimestamp( |
| 234 | isoDate: string, |
| 235 | timestampFormat: TimestampFormat, |
| 236 | nowMs: number = Date.now(), |
| 237 | timeZone?: string, |
| 238 | resolve: MessageResolver = m, |
| 239 | ): string { |
| 240 | const date = parseTimestampDate(isoDate); |
| 241 | if (!date) return ""; |
| 242 | const time = formatTime(date, timestampFormat, timeZone); |
| 243 | |
| 244 | const today = calendarDay(new Date(nowMs), timeZone); |
| 245 | const messageDay = calendarDay(date, timeZone); |
| 246 | const dayDiff = today.index - messageDay.index; |
| 247 | |
| 248 | if (dayDiff <= 0) return time; |
| 249 | if (dayDiff === 1) return resolve(msg("yesterday at {time}", { time })); |
| 250 | return `${formatNumericDate(date, messageDay.year === today.year, timeZone)} ${time}`; |
| 251 | } |
| 252 | |
| 253 | /** `timeZone` overrides the system's current zone. */ |
| 254 | export function formatUpcomingTimestamp( |
| 255 | isoDate: string, |
| 256 | timestampFormat: TimestampFormat, |
| 257 | nowMs: number = Date.now(), |
| 258 | timeZone?: string, |
| 259 | resolve: MessageResolver = m, |
| 260 | ): string { |
| 261 | const date = parseTimestampDate(isoDate); |
| 262 | if (!date) return ""; |
| 263 | const time = formatTime(date, timestampFormat, timeZone); |
| 264 | |
| 265 | const today = calendarDay(new Date(nowMs), timeZone); |
| 266 | const targetDay = calendarDay(date, timeZone); |
| 267 | const dayDiff = targetDay.index - today.index; |
| 268 | |
| 269 | if (dayDiff < 0) { |
| 270 | return formatDayAwareTimestamp(isoDate, timestampFormat, nowMs, timeZone, resolve); |
| 271 | } |
| 272 | if (dayDiff === 0) return time; |
| 273 | if (dayDiff === 1) return resolve(msg("tomorrow at {time}", { time })); |
| 274 | return `${formatNumericDate(date, targetDay.year === today.year, timeZone)} ${time}`; |
| 275 | } |
| 276 | |
| 277 | /** `label` is the whole phrase ("5m ago"); `value` and `suffix` split it for styled layouts. */ |
| 278 | type RelativeTimeParts = { value: string; suffix: string | null; label: string }; |
| 279 | export type RelativeTimeState = |
| 280 | | { status: "missing" } |
| 281 | | { status: "invalid" } |
| 282 | | ({ status: "relative" } & RelativeTimeParts); |
| 283 | |
| 284 | const MINUTE_MS = 60_000; |
| 285 | const HOUR_MS = 3_600_000; |
| 286 | const DAY_MS = 86_400_000; |
| 287 | |
| 288 | function relativeTimeUnitMs(elapsedMs: number): number { |
| 289 | if (elapsedMs < HOUR_MS) return MINUTE_MS; |
| 290 | if (elapsedMs < DAY_MS) return HOUR_MS; |
| 291 | return DAY_MS; |
| 292 | } |
| 293 | |
| 294 | /** Elapsed time floored to formatRelativeTime precision; equal labels yield equal values. */ |
| 295 | export function relativeTimeElapsedMs(isoDate: string, nowMs: number = Date.now()): number | null { |
| 296 | const date = parseTimestampDate(isoDate); |
| 297 | if (!date) return null; |
| 298 | const elapsedMs = Math.max(0, nowMs - date.getTime()); |
| 299 | const unitMs = relativeTimeUnitMs(elapsedMs); |
| 300 | return Math.floor(elapsedMs / unitMs) * unitMs; |
| 301 | } |
| 302 | |
| 303 | export function msUntilRelativeTimeChange( |
| 304 | isoDate: string, |
| 305 | nowMs: number = Date.now(), |
| 306 | ): number | null { |
| 307 | const date = parseTimestampDate(isoDate); |
| 308 | if (!date) return null; |
| 309 | const elapsedMs = Math.max(0, nowMs - date.getTime()); |
| 310 | const unitMs = relativeTimeUnitMs(elapsedMs); |
| 311 | const nextChangeMs = date.getTime() + (Math.floor(elapsedMs / unitMs) + 1) * unitMs; |
| 312 | // Delays above 2^31-1 fire immediately; cap safely and let callers reschedule. |
| 313 | return Math.min(nextChangeMs - nowMs, DAY_MS); |
| 314 | } |
| 315 | |
| 316 | const secondsLabel = (count: number, resolve: MessageResolver) => |
| 317 | resolve(msg("{count}s", { count, $context: "seconds, abbreviated" })); |
| 318 | const minutesLabel = (count: number, resolve: MessageResolver) => |
| 319 | resolve(msg("{count}m", { count, $context: "minutes, abbreviated" })); |
| 320 | const hoursLabel = (count: number, resolve: MessageResolver) => |
| 321 | resolve(msg("{count}h", { count, $context: "hours, abbreviated" })); |
| 322 | const daysLabel = (count: number, resolve: MessageResolver) => |
| 323 | resolve(msg("{count}d", { count, $context: "days, abbreviated" })); |
| 324 | |
| 325 | function relativeElapsedLabel(elapsedMs: number, resolve: MessageResolver): string { |
| 326 | const seconds = Math.floor(elapsedMs / 1000); |
| 327 | if (seconds < 60) return resolve(msg("just now")); |
| 328 | const minutes = Math.floor(seconds / 60); |
| 329 | if (minutes < 60) return resolve(msg("{count}m ago", { count: minutes })); |
| 330 | const hours = Math.floor(minutes / 60); |
| 331 | if (hours < 24) return resolve(msg("{count}h ago", { count: hours })); |
| 332 | return resolve(msg("{count}d ago", { count: Math.floor(hours / 24) })); |
| 333 | } |
| 334 | |
| 335 | export function formatRelativeElapsed( |
| 336 | elapsedMs: number, |
| 337 | resolve: MessageResolver = m, |
| 338 | ): RelativeTimeParts { |
| 339 | const label = relativeElapsedLabel(elapsedMs, resolve); |
| 340 | const seconds = Math.floor(elapsedMs / 1000); |
| 341 | if (seconds < 60) return { value: label, suffix: null, label }; |
| 342 | const ago = resolve(msg("ago", { $context: "follows an elapsed time such as 5m" })); |
| 343 | const minutes = Math.floor(seconds / 60); |
| 344 | if (minutes < 60) return { value: minutesLabel(minutes, resolve), suffix: ago, label }; |
| 345 | const hours = Math.floor(minutes / 60); |
| 346 | if (hours < 24) return { value: hoursLabel(hours, resolve), suffix: ago, label }; |
| 347 | const days = Math.floor(hours / 24); |
| 348 | return { value: daysLabel(days, resolve), suffix: ago, label }; |
| 349 | } |
| 350 | |
| 351 | export function formatRelativeTime( |
| 352 | isoDate: string, |
| 353 | nowMs: number = Date.now(), |
| 354 | resolve: MessageResolver = m, |
| 355 | ): RelativeTimeParts | null { |
| 356 | const elapsedMs = relativeTimeElapsedMs(isoDate, nowMs); |
| 357 | return elapsedMs === null ? null : formatRelativeElapsed(elapsedMs, resolve); |
| 358 | } |
| 359 | |
| 360 | export function formatRelativeTimeLabel( |
| 361 | isoDate: string, |
| 362 | nowMs: number = Date.now(), |
| 363 | resolve: MessageResolver = m, |
| 364 | ) { |
| 365 | const elapsedMs = relativeTimeElapsedMs(isoDate, nowMs); |
| 366 | return elapsedMs === null ? "" : relativeElapsedLabel(elapsedMs, resolve); |
| 367 | } |
| 368 | |
| 369 | export function formatElapsedDurationLabel( |
| 370 | isoDate: string, |
| 371 | nowMs: number = Date.now(), |
| 372 | resolve: MessageResolver = m, |
| 373 | ): string { |
| 374 | const date = parseTimestampDate(isoDate); |
| 375 | if (!date) return ""; |
| 376 | const diffMs = nowMs - date.getTime(); |
| 377 | if (diffMs <= 0) return resolve(msg("just now")); |
| 378 | |
| 379 | const seconds = Math.floor(diffMs / 1000); |
| 380 | if (seconds < 5) return resolve(msg("just now")); |
| 381 | if (seconds < 60) return secondsLabel(seconds, resolve); |
| 382 | |
| 383 | const minutes = Math.floor(seconds / 60); |
| 384 | if (minutes < 60) return minutesLabel(minutes, resolve); |
| 385 | |
| 386 | const hours = Math.floor(minutes / 60); |
| 387 | if (hours < 24) return hoursLabel(hours, resolve); |
| 388 | |
| 389 | const days = Math.floor(hours / 24); |
| 390 | return daysLabel(days, resolve); |
| 391 | } |
| 392 | |
| 393 | /** Pass nowMs to match a parent-driven render tick. */ |
| 394 | export function formatExpiresInLabel( |
| 395 | isoDate: string, |
| 396 | nowMs: number = Date.now(), |
| 397 | resolve: MessageResolver = m, |
| 398 | ): string { |
| 399 | const date = parseTimestampDate(isoDate); |
| 400 | if (!date) return ""; |
| 401 | const diffMs = date.getTime() - nowMs; |
| 402 | if (diffMs <= 0) return resolve(msg("Expired")); |
| 403 | |
| 404 | const totalSeconds = Math.floor(diffMs / 1000); |
| 405 | if (totalSeconds < 5) return resolve(msg("Expires in a moment")); |
| 406 | const expiresIn = (parts: string[]) => |
| 407 | resolve(msg("Expires in {duration}", { duration: parts.join(" ") })); |
| 408 | if (totalSeconds < 60) return expiresIn([secondsLabel(totalSeconds, resolve)]); |
| 409 | |
| 410 | if (totalSeconds < 3600) { |
| 411 | const minutes = Math.floor(totalSeconds / 60); |
| 412 | const seconds = totalSeconds % 60; |
| 413 | return seconds === 0 |
| 414 | ? expiresIn([minutesLabel(minutes, resolve)]) |
| 415 | : expiresIn([minutesLabel(minutes, resolve), secondsLabel(seconds, resolve)]); |
| 416 | } |
| 417 | |
| 418 | if (totalSeconds < 86_400) { |
| 419 | const hours = Math.floor(totalSeconds / 3600); |
| 420 | const rem = totalSeconds % 3600; |
| 421 | const minutes = Math.floor(rem / 60); |
| 422 | const seconds = rem % 60; |
| 423 | const parts = [hoursLabel(hours, resolve)]; |
| 424 | if (minutes > 0) parts.push(minutesLabel(minutes, resolve)); |
| 425 | if (seconds > 0) parts.push(secondsLabel(seconds, resolve)); |
| 426 | return expiresIn(parts); |
| 427 | } |
| 428 | |
| 429 | const days = Math.floor(totalSeconds / 86_400); |
| 430 | const remAfterDays = totalSeconds % 86_400; |
| 431 | if (remAfterDays === 0) return expiresIn([daysLabel(days, resolve)]); |
| 432 | const hours = Math.floor(remAfterDays / 3600); |
| 433 | const rem = remAfterDays % 3600; |
| 434 | const minutes = Math.floor(rem / 60); |
| 435 | const seconds = rem % 60; |
| 436 | const parts = [daysLabel(days, resolve)]; |
| 437 | if (hours > 0) parts.push(hoursLabel(hours, resolve)); |
| 438 | if (minutes > 0) parts.push(minutesLabel(minutes, resolve)); |
| 439 | if (seconds > 0) parts.push(secondsLabel(seconds, resolve)); |
| 440 | return expiresIn(parts); |
| 441 | } |