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