import { useEffect, useState } from "react"; import type { ReactNode } from "react"; import { readSheetCatchUp } from "./sheetApi"; import type { SheetCatchUpStatus } from "./sheetApi"; export default function SheetCatchUp({ workbookId, revision, children }: { workbookId: string; revision: number; children: ReactNode; }) { const [status, setStatus] = useState({ active: false }); useEffect(() => { let active = true; let pending: AbortController | null = null; const read = async () => { if (pending) return; const controller = new AbortController(); pending = controller; const timeout = window.setTimeout(() => controller.abort(), 4000); try { const result = await readSheetCatchUp(workbookId, controller.signal); if (!active) return; if (result.ok) setStatus(result.value); else if (result.status === 403 || result.status === 404) setStatus({ active: false }); } finally { window.clearTimeout(timeout); pending = null; } }; void read(); const timer = window.setInterval(() => { void read(); }, 2000); return () => { active = false; window.clearInterval(timer); pending?.abort(); }; }, [workbookId, revision]); if (!status.active) { if (!status.behind?.length) return children; return <> {status.behind.map((entry) => `${entry.source} is behind. ${entry.reason}`).join(" ")} {children} ; } const { done, total } = status; const measured = typeof done === "number" && Number.isSafeInteger(done) && done >= 0 && typeof total === "number" && Number.isSafeInteger(total) && total > 0 && done <= total; return
Updating {measured && <> {done} of {total} }
; }