The best way to control Claude Code, Codex and more from any computer or phone

main
ts 62 lines 2.17 KB
Raw
1 import { msg } from "gt-react-native";
2
3 import { m, type MessageResolver } from "../i18n/messages";
4
5 // Host timestamps may carry UTC offsets or mixed fractions, so text order is not time order.
6 export function compareTimestamps(left: string, right: string): number {
7 return (Date.parse(left) || 0) - (Date.parse(right) || 0);
8 }
9
10 export function byTimestamp(newestFirst: boolean) {
11 return (left: { readonly date: string }, right: { readonly date: string }) =>
12 newestFirst
13 ? compareTimestamps(right.date, left.date)
14 : compareTimestamps(left.date, right.date);
15 }
16
17 export function relativeTime(
18 input: string,
19 nowMs: number = Date.now(),
20 resolve: MessageResolver = m,
21 ): string {
22 const underAMinute = () =>
23 resolve(msg("<1m", { $context: "compact elapsed time, under one minute" }));
24 const timestamp = Date.parse(input);
25 if (Number.isNaN(timestamp)) {
26 return underAMinute();
27 }
28
29 const deltaSeconds = Math.max(0, Math.floor((nowMs - timestamp) / 1000));
30 if (deltaSeconds < 60) return underAMinute();
31
32 const deltaMinutes = Math.floor(deltaSeconds / 60);
33 if (deltaMinutes < 60) {
34 return resolve(
35 msg("{count}m", { count: String(deltaMinutes), $context: "compact elapsed minutes" }),
36 );
37 }
38
39 const deltaHours = Math.floor(deltaMinutes / 60);
40 if (deltaHours < 24) {
41 return resolve(
42 msg("{count}h", { count: String(deltaHours), $context: "compact elapsed hours" }),
43 );
44 }
45
46 const deltaDays = Math.floor(deltaHours / 24);
47 return resolve(msg("{count}d", { count: String(deltaDays), $context: "compact elapsed days" }));
48 }
49
50 /** Milliseconds until the relative-time label next changes. */
51 export function msUntilRelativeTimeChange(
52 input: string,
53 nowMs: number = Date.now(),
54 ): number | null {
55 const timestamp = Date.parse(input);
56 if (Number.isNaN(timestamp)) return null;
57 const elapsedMs = Math.max(0, nowMs - timestamp);
58 const unitMs = elapsedMs < 3_600_000 ? 60_000 : elapsedMs < 86_400_000 ? 3_600_000 : 86_400_000;
59 const nextChangeMs = timestamp + (Math.floor(elapsedMs / unitMs) + 1) * unitMs;
60 // Far-future timestamps must not overflow setTimeout's signed 32-bit delay.
61 return Math.min(nextChangeMs - nowMs, 86_400_000);
62 }