-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBranchContext.tsx
More file actions
262 lines (227 loc) · 7.2 KB
/
BranchContext.tsx
File metadata and controls
262 lines (227 loc) · 7.2 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
"use client";
import {
createContext,
useCallback,
useContext,
useEffect,
useImperativeHandle,
useState,
type ReactNode,
type Ref,
} from "react";
import {
branchesApi,
type BranchInfo,
} from "@/lib/api/revisions";
// --- sessionStorage helpers ---
function getStoredBranch(projectId: string): string | null {
try {
return sessionStorage.getItem(`ontokit:branch:${projectId}`);
} catch {
return null;
}
}
function setStoredBranch(projectId: string, branch: string): void {
try {
sessionStorage.setItem(`ontokit:branch:${projectId}`, branch);
} catch {
/* ignore */
}
}
// --- Context ---
interface BranchContextValue {
// State
branches: BranchInfo[];
currentBranch: string;
defaultBranch: string;
isLoading: boolean;
error: string | null;
isFeatureBranch: boolean;
pendingChanges: boolean;
hasGitHubRemote: boolean;
lastSyncAt: string | null;
syncStatus: string | null;
// Actions
loadBranches: () => Promise<void>;
createBranch: (name: string, fromBranch?: string) => Promise<BranchInfo>;
switchBranch: (name: string) => Promise<void>;
deleteBranch: (name: string, force?: boolean) => Promise<void>;
setPendingChanges: (pending: boolean) => void;
}
const BranchContext = createContext<BranchContextValue | null>(null);
export interface BranchProviderHandle {
refreshBranches: () => Promise<void>;
}
interface BranchProviderProps {
projectId: string;
accessToken?: string;
initialBranch?: string;
refreshRef?: Ref<BranchProviderHandle>;
children: ReactNode;
}
export function BranchProvider({
projectId,
accessToken,
initialBranch,
refreshRef,
children,
}: BranchProviderProps) {
const [branches, setBranches] = useState<BranchInfo[]>([]);
// Priority: URL param (initialBranch) > sessionStorage > "main" placeholder
const [currentBranch, setCurrentBranch] = useState<string>(
() => initialBranch || getStoredBranch(projectId) || "main"
);
const [defaultBranch, setDefaultBranch] = useState<string>("main");
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [pendingChanges, setPendingChanges] = useState(false);
const [hasGitHubRemote, setHasGitHubRemote] = useState(false);
const [lastSyncAt, setLastSyncAt] = useState<string | null>(null);
const [syncStatus, setSyncStatus] = useState<string | null>(null);
const isFeatureBranch = currentBranch !== defaultBranch;
const loadBranches = useCallback(async () => {
if (!projectId) return;
setIsLoading(true);
setError(null);
try {
const response = await branchesApi.list(projectId, accessToken);
setBranches(response.items);
setDefaultBranch(response.default_branch);
setHasGitHubRemote(response.has_github_remote);
setLastSyncAt(response.last_sync_at);
setSyncStatus(response.sync_status);
// Validate current branch exists; fall back to DB preference or default
setCurrentBranch((prev) => {
const prevExists = response.items.some((b) => b.name === prev);
if (prevExists) return prev;
// Stored/initial branch was deleted — clear stale sessionStorage
try {
sessionStorage.removeItem(`ontokit:branch:${projectId}`);
} catch {
/* ignore */
}
const prefExists =
response.preferred_branch &&
response.items.some((b) => b.name === response.preferred_branch);
return prefExists
? response.preferred_branch!
: response.current_branch;
});
} catch (err) {
const message =
err instanceof Error ? err.message : "Failed to load branches";
setError(message);
} finally {
setIsLoading(false);
}
}, [projectId, accessToken]);
const createBranch = useCallback(
async (name: string, fromBranch?: string): Promise<BranchInfo> => {
if (!accessToken) {
throw new Error("Authentication required");
}
const newBranch = await branchesApi.create(
projectId,
{ name, from_branch: fromBranch },
accessToken
);
// Refresh branches list
await loadBranches();
// Switch to the new branch directly — avoids stale closure in switchBranch
// which would check the pre-update branches array
setCurrentBranch(name);
setStoredBranch(projectId, name);
branchesApi.savePreference(projectId, name, accessToken).catch(() => {});
return newBranch;
},
[projectId, accessToken, loadBranches]
);
const switchBranch = useCallback(
async (name: string) => {
if (pendingChanges) {
throw new Error(
"You have pending changes. Please commit or discard them before switching branches."
);
}
// Validate branch exists locally — no backend call needed
const branchExists = branches.some((b) => b.name === name);
if (!branchExists) {
throw new Error(`Branch not found: ${name}`);
}
setCurrentBranch(name);
setStoredBranch(projectId, name);
// Fire-and-forget: persist to DB for cross-session restore
if (accessToken) {
branchesApi.savePreference(projectId, name, accessToken).catch(() => {});
}
},
[branches, pendingChanges, projectId, accessToken]
);
const deleteBranch = useCallback(
async (name: string, force = false) => {
if (!accessToken) {
throw new Error("Authentication required");
}
if (name === currentBranch) {
throw new Error("Cannot delete the current branch");
}
if (name === defaultBranch) {
throw new Error("Cannot delete the default branch");
}
await branchesApi.delete(projectId, name, accessToken, force);
// Refresh branches list
await loadBranches();
},
[projectId, accessToken, currentBranch, defaultBranch, loadBranches]
);
// Load branches on mount
useEffect(() => {
loadBranches();
}, [loadBranches]);
// Set initial branch if specified and different from current (client-side only)
const [initialBranchHandled, setInitialBranchHandled] = useState(false);
useEffect(() => {
if (
initialBranch &&
!initialBranchHandled &&
!isLoading &&
branches.length > 0
) {
const branchExists = branches.some((b) => b.name === initialBranch);
if (branchExists && initialBranch !== currentBranch) {
setCurrentBranch(initialBranch);
}
setInitialBranchHandled(true);
}
}, [initialBranch, initialBranchHandled, isLoading, branches, currentBranch]);
useImperativeHandle(refreshRef, () => ({
refreshBranches: loadBranches,
}), [loadBranches]);
const value: BranchContextValue = {
branches,
currentBranch,
defaultBranch,
isLoading,
error,
isFeatureBranch,
pendingChanges,
hasGitHubRemote,
lastSyncAt,
syncStatus,
loadBranches,
createBranch,
switchBranch,
deleteBranch,
setPendingChanges,
};
return (
<BranchContext.Provider value={value}>{children}</BranchContext.Provider>
);
}
export function useBranch(): BranchContextValue {
const context = useContext(BranchContext);
if (!context) {
throw new Error("useBranch must be used within a BranchProvider");
}
return context;
}