Open History to see the last commit
1import type { GitBranch } from "@t3tools/contracts";
2import { useQuery, useQueryClient } from "@tanstack/react-query";
3import { useVirtualizer } from "@tanstack/react-virtual";
4import { ChevronDownIcon } from "lucide-react";
5import {
6 type CSSProperties,
7 useCallback,
8 useDeferredValue,
9 useEffect,
10 useMemo,
11 useOptimistic,
12 useRef,
13 useState,
14 useTransition,
15} from "react";
16
17import {
18 gitBranchesQueryOptions,
19 gitQueryKeys,
20 gitStatusQueryOptions,
21 invalidateGitQueries,
22} from "../lib/gitReactQuery";
23import { readNativeApi } from "../nativeApi";
24import { parsePullRequestReference } from "../pullRequestReference";
25import {
26 dedupeRemoteBranchesWithLocalMatches,
27 deriveLocalBranchNameFromRemoteRef,
28 EnvMode,
29 resolveBranchSelectionTarget,
30 resolveBranchToolbarValue,
31 shouldIncludeBranchPickerItem,
32} from "./BranchToolbar.logic";
33import { Button } from "./ui/button";
34import {
35 Combobox,
36 ComboboxEmpty,
37 ComboboxInput,
38 ComboboxItem,
39 ComboboxList,
40 ComboboxPopup,
41 ComboboxTrigger,
42} from "./ui/combobox";
43import { toastManager } from "./ui/toast";
44
45interface BranchToolbarBranchSelectorProps {
46 activeProjectCwd: string;
47 activeThreadBranch: string | null;
48 activeWorktreePath: string | null;
49 branchCwd: string | null;
50 effectiveEnvMode: EnvMode;
51 envLocked: boolean;
52 onSetThreadBranch: (branch: string | null, worktreePath: string | null) => void;
53 onCheckoutPullRequestRequest?: (reference: string) => void;
54 onComposerFocusRequest?: () => void;
55}
56
57function toBranchActionErrorMessage(error: unknown): string {
58 return error instanceof Error ? error.message : "An error occurred.";
59}
60
61function getBranchTriggerLabel(input: {
62 activeWorktreePath: string | null;
63 effectiveEnvMode: EnvMode;
64 resolvedActiveBranch: string | null;
65}): string {
66 const { activeWorktreePath, effectiveEnvMode, resolvedActiveBranch } = input;
67 if (!resolvedActiveBranch) {
68 return "Select branch";
69 }
70 if (effectiveEnvMode === "worktree" && !activeWorktreePath) {
71 return `From ${resolvedActiveBranch}`;
72 }
73 return resolvedActiveBranch;
74}
75
76export function BranchToolbarBranchSelector({
77 activeProjectCwd,
78 activeThreadBranch,
79 activeWorktreePath,
80 branchCwd,
81 effectiveEnvMode,
82 envLocked,
83 onSetThreadBranch,
84 onCheckoutPullRequestRequest,
85 onComposerFocusRequest,
86}: BranchToolbarBranchSelectorProps) {
87 const queryClient = useQueryClient();
88 const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
89 const [branchQuery, setBranchQuery] = useState("");
90 const deferredBranchQuery = useDeferredValue(branchQuery);
91
92 const branchesQuery = useQuery(gitBranchesQueryOptions(branchCwd));
93 const branchStatusQuery = useQuery(gitStatusQueryOptions(branchCwd));
94 const branches = useMemo(
95 () => dedupeRemoteBranchesWithLocalMatches(branchesQuery.data?.branches ?? []),
96 [branchesQuery.data?.branches],
97 );
98 const currentGitBranch =
99 branchStatusQuery.data?.branch ?? branches.find((branch) => branch.current)?.name ?? null;
100 const canonicalActiveBranch = resolveBranchToolbarValue({
101 envMode: effectiveEnvMode,
102 activeWorktreePath,
103 activeThreadBranch,
104 currentGitBranch,
105 });
106 const branchNames = useMemo(() => branches.map((branch) => branch.name), [branches]);
107 const branchByName = useMemo(
108 () => new Map(branches.map((branch) => [branch.name, branch] as const)),
109 [branches],
110 );
111 const trimmedBranchQuery = branchQuery.trim();
112 const deferredTrimmedBranchQuery = deferredBranchQuery.trim();
113 const normalizedDeferredBranchQuery = deferredTrimmedBranchQuery.toLowerCase();
114 const prReference = parsePullRequestReference(trimmedBranchQuery);
115 const isSelectingWorktreeBase =
116 effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath;
117 const checkoutPullRequestItemValue =
118 prReference && onCheckoutPullRequestRequest ? `__checkout_pull_request__:${prReference}` : null;
119 const canCreateBranch = !isSelectingWorktreeBase && trimmedBranchQuery.length > 0;
120 const hasExactBranchMatch = branchByName.has(trimmedBranchQuery);
121 const createBranchItemValue = canCreateBranch
122 ? `__create_new_branch__:${trimmedBranchQuery}`
123 : null;
124 const branchPickerItems = useMemo(() => {
125 const items = [...branchNames];
126 if (createBranchItemValue && !hasExactBranchMatch) {
127 items.push(createBranchItemValue);
128 }
129 if (checkoutPullRequestItemValue) {
130 items.unshift(checkoutPullRequestItemValue);
131 }
132 return items;
133 }, [branchNames, checkoutPullRequestItemValue, createBranchItemValue, hasExactBranchMatch]);
134 const filteredBranchPickerItems = useMemo(
135 () =>
136 normalizedDeferredBranchQuery.length === 0
137 ? branchPickerItems
138 : branchPickerItems.filter((itemValue) =>
139 shouldIncludeBranchPickerItem({
140 itemValue,
141 normalizedQuery: normalizedDeferredBranchQuery,
142 createBranchItemValue,
143 checkoutPullRequestItemValue,
144 }),
145 ),
146 [
147 branchPickerItems,
148 checkoutPullRequestItemValue,
149 createBranchItemValue,
150 normalizedDeferredBranchQuery,
151 ],
152 );
153 const [resolvedActiveBranch, setOptimisticBranch] = useOptimistic(
154 canonicalActiveBranch,
155 (_currentBranch: string | null, optimisticBranch: string | null) => optimisticBranch,
156 );
157 const [isBranchActionPending, startBranchActionTransition] = useTransition();
158 const shouldVirtualizeBranchList = filteredBranchPickerItems.length > 40;
159
160 const runBranchAction = (action: () => Promise<void>) => {
161 startBranchActionTransition(async () => {
162 await action().catch(() => undefined);
163 await invalidateGitQueries(queryClient).catch(() => undefined);
164 });
165 };
166
167 const selectBranch = (branch: GitBranch) => {
168 const api = readNativeApi();
169 if (!api || !branchCwd || isBranchActionPending) return;
170
171 // In new-worktree mode, selecting a branch sets the base branch.
172 if (isSelectingWorktreeBase) {
173 onSetThreadBranch(branch.name, null);
174 setIsBranchMenuOpen(false);
175 onComposerFocusRequest?.();
176 return;
177 }
178
179 const selectionTarget = resolveBranchSelectionTarget({
180 activeProjectCwd,
181 activeWorktreePath,
182 branch,
183 });
184
185 // If the branch already lives in a worktree, point the thread there.
186 if (selectionTarget.reuseExistingWorktree) {
187 onSetThreadBranch(branch.name, selectionTarget.nextWorktreePath);
188 setIsBranchMenuOpen(false);
189 onComposerFocusRequest?.();
190 return;
191 }
192
193 const selectedBranchName = branch.isRemote
194 ? deriveLocalBranchNameFromRemoteRef(branch.name)
195 : branch.name;
196
197 setIsBranchMenuOpen(false);
198 onComposerFocusRequest?.();
199
200 runBranchAction(async () => {
201 setOptimisticBranch(selectedBranchName);
202 try {
203 await api.git.checkout({ cwd: selectionTarget.checkoutCwd, branch: branch.name });
204 await invalidateGitQueries(queryClient);
205 } catch (error) {
206 toastManager.add({
207 type: "error",
208 title: "Failed to checkout branch.",
209 description: toBranchActionErrorMessage(error),
210 });
211 return;
212 }
213
214 let nextBranchName = selectedBranchName;
215 if (branch.isRemote) {
216 const status = await api.git.status({ cwd: branchCwd }).catch(() => null);
217 if (status?.branch) {
218 nextBranchName = status.branch;
219 }
220 }
221
222 setOptimisticBranch(nextBranchName);
223 onSetThreadBranch(nextBranchName, selectionTarget.nextWorktreePath);
224 });
225 };
226
227 const createBranch = (rawName: string) => {
228 const name = rawName.trim();
229 const api = readNativeApi();
230 if (!api || !branchCwd || !name || isBranchActionPending) return;
231
232 setIsBranchMenuOpen(false);
233 onComposerFocusRequest?.();
234
235 runBranchAction(async () => {
236 setOptimisticBranch(name);
237
238 try {
239 await api.git.createBranch({ cwd: branchCwd, branch: name });
240 try {
241 await api.git.checkout({ cwd: branchCwd, branch: name });
242 } catch (error) {
243 toastManager.add({
244 type: "error",
245 title: "Failed to checkout branch.",
246 description: toBranchActionErrorMessage(error),
247 });
248 return;
249 }
250 } catch (error) {
251 toastManager.add({
252 type: "error",
253 title: "Failed to create branch.",
254 description: toBranchActionErrorMessage(error),
255 });
256 return;
257 }
258
259 setOptimisticBranch(name);
260 onSetThreadBranch(name, activeWorktreePath);
261 setBranchQuery("");
262 });
263 };
264
265 useEffect(() => {
266 if (
267 effectiveEnvMode !== "worktree" ||
268 activeWorktreePath ||
269 activeThreadBranch ||
270 !currentGitBranch
271 ) {
272 return;
273 }
274 onSetThreadBranch(currentGitBranch, null);
275 }, [
276 activeThreadBranch,
277 activeWorktreePath,
278 currentGitBranch,
279 effectiveEnvMode,
280 onSetThreadBranch,
281 ]);
282
283 const handleOpenChange = useCallback(
284 (open: boolean) => {
285 setIsBranchMenuOpen(open);
286 if (!open) {
287 setBranchQuery("");
288 return;
289 }
290 void queryClient.invalidateQueries({
291 queryKey: gitQueryKeys.branches(branchCwd),
292 });
293 },
294 [branchCwd, queryClient],
295 );
296
297 const branchListScrollElementRef = useRef<HTMLDivElement | null>(null);
298 const branchListVirtualizer = useVirtualizer({
299 count: filteredBranchPickerItems.length,
300 estimateSize: (index) =>
301 filteredBranchPickerItems[index] === checkoutPullRequestItemValue ? 44 : 28,
302 getScrollElement: () => branchListScrollElementRef.current,
303 overscan: 12,
304 enabled: isBranchMenuOpen && shouldVirtualizeBranchList,
305 initialRect: {
306 height: 224,
307 width: 0,
308 },
309 });
310 const virtualBranchRows = branchListVirtualizer.getVirtualItems();
311 const setBranchListRef = useCallback(
312 (element: HTMLDivElement | null) => {
313 branchListScrollElementRef.current =
314 (element?.parentElement as HTMLDivElement | null) ?? null;
315 if (element) {
316 branchListVirtualizer.measure();
317 }
318 },
319 [branchListVirtualizer],
320 );
321
322 useEffect(() => {
323 if (!isBranchMenuOpen || !shouldVirtualizeBranchList) return;
324 queueMicrotask(() => {
325 branchListVirtualizer.measure();
326 });
327 }, [
328 branchListVirtualizer,
329 filteredBranchPickerItems.length,
330 isBranchMenuOpen,
331 shouldVirtualizeBranchList,
332 ]);
333
334 const triggerLabel = getBranchTriggerLabel({
335 activeWorktreePath,
336 effectiveEnvMode,
337 resolvedActiveBranch,
338 });
339
340 function renderPickerItem(itemValue: string, index: number, style?: CSSProperties) {
341 if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) {
342 return (
343 <ComboboxItem
344 hideIndicator
345 key={itemValue}
346 index={index}
347 value={itemValue}
348 style={style}
349 onClick={() => {
350 if (!prReference || !onCheckoutPullRequestRequest) {
351 return;
352 }
353 setIsBranchMenuOpen(false);
354 setBranchQuery("");
355 onComposerFocusRequest?.();
356 onCheckoutPullRequestRequest(prReference);
357 }}
358 >
359 <div className="flex min-w-0 flex-col items-start py-1">
360 <span className="truncate font-medium">Checkout Pull Request</span>
361 <span className="truncate text-muted-foreground text-xs">{prReference}</span>
362 </div>
363 </ComboboxItem>
364 );
365 }
366 if (createBranchItemValue && itemValue === createBranchItemValue) {
367 return (
368 <ComboboxItem
369 hideIndicator
370 key={itemValue}
371 index={index}
372 value={itemValue}
373 style={style}
374 onClick={() => createBranch(trimmedBranchQuery)}
375 >
376 <span className="truncate">Create new branch "{trimmedBranchQuery}"</span>
377 </ComboboxItem>
378 );
379 }
380
381 const branch = branchByName.get(itemValue);
382 if (!branch) return null;
383
384 const hasSecondaryWorktree = branch.worktreePath && branch.worktreePath !== activeProjectCwd;
385 const badge = branch.current
386 ? "current"
387 : hasSecondaryWorktree
388 ? "worktree"
389 : branch.isRemote
390 ? "remote"
391 : branch.isDefault
392 ? "default"
393 : null;
394 return (
395 <ComboboxItem
396 hideIndicator
397 key={itemValue}
398 index={index}
399 value={itemValue}
400 style={style}
401 onClick={() => selectBranch(branch)}
402 >
403 <div className="flex w-full items-center justify-between gap-2">
404 <span className="truncate">{itemValue}</span>
405 {badge && <span className="shrink-0 text-[10px] text-muted-foreground/45">{badge}</span>}
406 </div>
407 </ComboboxItem>
408 );
409 }
410
411 return (
412 <Combobox
413 items={branchPickerItems}
414 filteredItems={filteredBranchPickerItems}
415 autoHighlight
416 virtualized={shouldVirtualizeBranchList}
417 onItemHighlighted={(_value, eventDetails) => {
418 if (!isBranchMenuOpen || eventDetails.index < 0) return;
419 branchListVirtualizer.scrollToIndex(eventDetails.index, { align: "auto" });
420 }}
421 onOpenChange={handleOpenChange}
422 open={isBranchMenuOpen}
423 value={resolvedActiveBranch}
424 >
425 <ComboboxTrigger
426 render={<Button variant="ghost" size="xs" />}
427 className="text-muted-foreground/70 hover:text-foreground/80"
428 disabled={(branchesQuery.isLoading && branches.length === 0) || isBranchActionPending}
429 >
430 <span className="max-w-[240px] truncate">{triggerLabel}</span>
431 <ChevronDownIcon />
432 </ComboboxTrigger>
433 <ComboboxPopup align="end" side="top" className="w-80">
434 <div className="border-b p-1">
435 <ComboboxInput
436 className="[&_input]:font-sans rounded-md"
437 inputClassName="ring-0"
438 placeholder="Search branches..."
439 showTrigger={false}
440 size="sm"
441 value={branchQuery}
442 onChange={(event) => setBranchQuery(event.target.value)}
443 />
444 </div>
445 <ComboboxEmpty>No branches found.</ComboboxEmpty>
446
447 <ComboboxList ref={setBranchListRef} className="max-h-56">
448 {shouldVirtualizeBranchList ? (
449 <div
450 className="relative"
451 style={{
452 height: `${branchListVirtualizer.getTotalSize()}px`,
453 }}
454 >
455 {virtualBranchRows.map((virtualRow) => {
456 const itemValue = filteredBranchPickerItems[virtualRow.index];
457 if (!itemValue) return null;
458 return renderPickerItem(itemValue, virtualRow.index, {
459 position: "absolute",
460 top: 0,
461 left: 0,
462 width: "100%",
463 transform: `translateY(${virtualRow.start}px)`,
464 });
465 })}
466 </div>
467 ) : (
468 filteredBranchPickerItems.map((itemValue, index) => renderPickerItem(itemValue, index))
469 )}
470 </ComboboxList>
471 </ComboboxPopup>
472 </Combobox>
473 );
474}