mirror of
https://github.com/docmost/docmost.git
synced 2026-05-20 08:34:04 +08:00
4f3577f009
* feat: non-inline comments support * enhance comments * fix types
33 lines
825 B
TypeScript
33 lines
825 B
TypeScript
import { timeAgo } from "@/lib/time.ts";
|
|
import { useMemo, useSyncExternalStore } from "react";
|
|
|
|
let tick = 0;
|
|
let intervalId: ReturnType<typeof setInterval> | null = null;
|
|
const listeners = new Set<() => void>();
|
|
|
|
function subscribe(callback: () => void) {
|
|
listeners.add(callback);
|
|
if (listeners.size === 1) {
|
|
intervalId = setInterval(() => {
|
|
tick++;
|
|
listeners.forEach((cb) => cb());
|
|
}, 60_000);
|
|
}
|
|
return () => {
|
|
listeners.delete(callback);
|
|
if (listeners.size === 0 && intervalId) {
|
|
clearInterval(intervalId);
|
|
intervalId = null;
|
|
}
|
|
};
|
|
}
|
|
|
|
function getSnapshot() {
|
|
return tick;
|
|
}
|
|
|
|
export function useTimeAgo(date: Date | string) {
|
|
const currentTick = useSyncExternalStore(subscribe, getSnapshot);
|
|
return useMemo(() => timeAgo(new Date(date)), [date, currentTick]);
|
|
}
|