| 1 | import { useCallback, useLayoutEffect, useRef, useState } from "react"; |
| 2 | import { loadWorkspaceGitStats } from "./workspaceGitStats"; |
| 3 | import { createSerialWorkspacePoll } from "./serialWorkspacePoll"; |
| 4 | |
| 5 | export interface DiffStats { |
| 6 | added: number; |
| 7 | removed: number; |
| 8 | incomplete: boolean; |
| 9 | } |
| 10 | |
| 11 | export function useWorkspaceDiffStats(tabId: string, scopeKey: string, workspaceRoot: string, enabled: boolean) { |
| 12 | const [snapshot, setSnapshot] = useState<{ key: string; stats: DiffStats } | null>(null); |
| 13 | const key = JSON.stringify([tabId, scopeKey, workspaceRoot]); |
| 14 | const pollRef = useRef<ReturnType<typeof createSerialWorkspacePoll> | null>(null); |
| 15 | if (!pollRef.current) pollRef.current = createSerialWorkspacePoll({ |
| 16 | schedule: (callback, delay) => window.setTimeout(callback, delay), |
| 17 | cancel: (handle) => window.clearTimeout(handle as number), |
| 18 | }); |
| 19 | |
| 20 | useLayoutEffect(() => { |
| 21 | const poll = pollRef.current!; |
| 22 | let generation = 0; |
| 23 | const reconcile = () => { |
| 24 | const request = ++generation; |
| 25 | if (!enabled || !tabId || document.visibilityState === "hidden") { |
| 26 | poll.setJob(null); |
| 27 | return; |
| 28 | } |
| 29 | poll.setJob(async () => { |
| 30 | try { |
| 31 | const result = await loadWorkspaceGitStats(tabId, workspaceRoot, () => request === generation); |
| 32 | if (request !== generation) return; |
| 33 | setSnapshot({ key, stats: { |
| 34 | added: result?.added ?? 0, removed: result?.removed ?? 0, |
| 35 | incomplete: result?.incomplete === true || result?.gitAvailable !== true, |
| 36 | } }); |
| 37 | } catch { |
| 38 | if (request !== generation) return; |
| 39 | setSnapshot(current => ({ key, stats: { |
| 40 | added: current?.key === key ? current.stats.added : 0, |
| 41 | removed: current?.key === key ? current.stats.removed : 0, incomplete: true, |
| 42 | } })); |
| 43 | } |
| 44 | }); |
| 45 | }; |
| 46 | reconcile(); |
| 47 | document.addEventListener("visibilitychange", reconcile); |
| 48 | return () => { |
| 49 | generation++; |
| 50 | poll.setJob(null); |
| 51 | document.removeEventListener("visibilitychange", reconcile); |
| 52 | }; |
| 53 | }, [enabled, tabId, workspaceRoot, key]); |
| 54 | |
| 55 | const reloadDiffStats = useCallback(() => pollRef.current?.refresh(), []); |
| 56 | return { diffStats: snapshot?.key === key ? snapshot.stats : null, reloadDiffStats }; |
| 57 | } |
| 58 |