Open History to see the last commit
1import { useMessages } from "gt-react-native";
2import { useSyncExternalStore } from "react";
3import { msUntilRelativeTimeChange, relativeTime } from "../lib/time";
4
5// The React Compiler caches inline relativeTime calls on the timestamp alone.
6export function RelativeTime(props: { timestamp: string }) {
7 const messages = useMessages();
8 const subscribe = (onChange: () => void) => {
9 let timer: ReturnType<typeof setTimeout> | undefined;
10 const schedule = () => {
11 const delayMs = msUntilRelativeTimeChange(props.timestamp);
12 if (delayMs === null) return;
13 timer = setTimeout(() => {
14 onChange();
15 schedule();
16 }, delayMs);
17 };
18 schedule();
19 return () => clearTimeout(timer);
20 };
21 const getSnapshot = () => relativeTime(props.timestamp, Date.now(), messages);
22 return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
23}