forked from op7418/CodePilot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseGitStatus.ts
More file actions
63 lines (52 loc) · 1.88 KB
/
useGitStatus.ts
File metadata and controls
63 lines (52 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
"use client";
import { useState, useEffect, useCallback, useRef } from "react";
import type { GitStatus } from "@/types";
const POLL_INTERVAL = 10000; // 10s
export function useGitStatus(cwd: string) {
const [status, setStatus] = useState<GitStatus | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
const fetchStatus = useCallback(async () => {
if (!cwd) return;
setLoading(true);
setError(null);
try {
const res = await fetch(`/api/git/status?cwd=${encodeURIComponent(cwd)}`);
if (!res.ok) {
const data = await res.json();
throw new Error(data.error || 'Failed to fetch status');
}
const data: GitStatus = await res.json();
setStatus(data);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to fetch status');
} finally {
setLoading(false);
}
}, [cwd]);
// Initial fetch + polling
useEffect(() => {
if (!cwd) {
setStatus(null);
return;
}
fetchStatus();
intervalRef.current = setInterval(fetchStatus, POLL_INTERVAL);
const handleVisibility = () => {
if (document.visibilityState === 'visible') {
fetchStatus();
}
};
document.addEventListener('visibilitychange', handleVisibility);
// Listen for manual refresh events (e.g. after commit from topbar)
const handleRefreshEvent = () => fetchStatus();
window.addEventListener('git-refresh', handleRefreshEvent);
return () => {
if (intervalRef.current) clearInterval(intervalRef.current);
document.removeEventListener('visibilitychange', handleVisibility);
window.removeEventListener('git-refresh', handleRefreshEvent);
};
}, [cwd, fetchStatus]);
return { status, loading, error, refresh: fetchStatus };
}