Open History to see the last commit
1import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
2import {
3 isAtomCommandInterrupted,
4 squashAtomCommandFailure,
5} from "@t3tools/client-runtime/state/runtime";
6import type { ContextMenuItem, EnvironmentId, VcsRef, ThreadId } from "@t3tools/contracts";
7import { LegendList, type LegendListRef } from "@legendapp/list/react";
8import { ChevronDownIcon, GitBranchIcon, RefreshCwIcon, SearchIcon } from "lucide-react";
9import {
10 useCallback,
11 useDeferredValue,
12 useEffect,
13 useId,
14 useLayoutEffect,
15 useMemo,
16 useOptimistic,
17 useRef,
18 useState,
19 useTransition,
20 type MouseEvent as ReactMouseEvent,
21} from "react";
22
23import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
24import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
25import { readLocalApi } from "../localApi";
26import { useOpenPrLink } from "../lib/openPullRequestLink";
27import { shouldLoadNextBranchPageAfterScroll } from "../state/paginatedBranches";
28import { usePaginatedBranches } from "../state/queries";
29import { useProject, useThread } from "../state/entities";
30import { useEnvironmentQuery } from "../state/query";
31import { threadEnvironment } from "../state/threads";
32import { useAtomCommand } from "../state/use-atom-command";
33import { vcsEnvironment } from "../state/vcs";
34import { cn } from "../lib/utils";
35import { parsePullRequestReference } from "../pullRequestReference";
36import { getSourceControlPresentation } from "../sourceControlPresentation";
37import {
38 deriveLocalBranchNameFromRemoteRef,
39 resolveBranchTriggerLabel,
40 resolveBranchToolbarPrBranch,
41 resolveBranchSelectionTarget,
42 resolveBranchToolbarValue,
43 resolveDraftEnvModeAfterBranchChange,
44 resolveEffectiveEnvMode,
45 sanitizeNewRefName,
46 shouldIncludeBranchPickerItem,
47} from "./BranchToolbar.logic";
48import {
49 ChangeRequestStatusIcon,
50 prStatusIndicator,
51 resolveThreadPr,
52} from "./ThreadStatusIndicators";
53import { Button } from "./ui/button";
54import { Switch } from "./ui/switch";
55import { getVirtualizedScrollFadeClassName } from "./ui/scroll-area";
56import {
57 Combobox,
58 ComboboxEmpty,
59 ComboboxInput,
60 ComboboxItem,
61 ComboboxListVirtualized,
62 ComboboxPopup,
63 ComboboxStatus,
64 ComboboxTrigger,
65} from "./ui/combobox";
66import { stackedThreadToast, toastManager } from "./ui/toast";
67import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
68
69interface BranchToolbarBranchSelectorProps {
70 className?: string;
71 environmentId: EnvironmentId;
72 threadId: ThreadId;
73 draftId?: DraftId;
74 envLocked: boolean;
75 effectiveEnvModeOverride?: "local" | "worktree";
76 activeThreadBranchOverride?: string | null;
77 onActiveThreadBranchOverrideChange?: (refName: string | null) => void;
78 startFromOrigin: boolean;
79 onStartFromOriginChange: (startFromOrigin: boolean) => void;
80 onCheckoutPullRequestRequest?: (reference: string) => void;
81 onComposerFocusRequest?: () => void;
82}
83
84function toBranchActionErrorMessage(error: unknown): string {
85 return error instanceof Error ? error.message : "An error occurred.";
86}
87
88export function BranchToolbarBranchSelector({
89 className,
90 environmentId,
91 threadId,
92 draftId,
93 envLocked,
94 effectiveEnvModeOverride,
95 activeThreadBranchOverride,
96 onActiveThreadBranchOverrideChange,
97 startFromOrigin,
98 onStartFromOriginChange,
99 onCheckoutPullRequestRequest,
100 onComposerFocusRequest,
101}: BranchToolbarBranchSelectorProps) {
102 const startFromOriginSwitchId = useId();
103 const stopThreadSession = useAtomCommand(threadEnvironment.stopSession, "thread session stop");
104 const updateThreadMetadata = useAtomCommand(
105 threadEnvironment.updateMetadata,
106 "thread metadata update",
107 );
108 const switchRef = useAtomCommand(vcsEnvironment.switchRef, {
109 reportFailure: false,
110 });
111 const createRefMutation = useAtomCommand(vcsEnvironment.createRef, {
112 reportFailure: false,
113 });
114 // ---------------------------------------------------------------------------
115 // Thread / project state (pushed down from parent to colocate with mutation)
116 // ---------------------------------------------------------------------------
117 const threadRef = useMemo(
118 () => scopeThreadRef(environmentId, threadId),
119 [environmentId, threadId],
120 );
121 const draftThread = useComposerDraftStore((store) =>
122 draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef),
123 );
124 const serverThread = useThread(threadRef, { waitForShell: draftThread !== null });
125 const serverSession = serverThread?.session ?? null;
126 const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
127
128 const activeProjectRef = serverThread
129 ? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
130 : draftThread
131 ? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
132 : null;
133 const activeProject = useProject(activeProjectRef);
134
135 const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined);
136 const activeThreadBranch =
137 activeThreadBranchOverride !== undefined
138 ? activeThreadBranchOverride
139 : (serverThread?.branch ?? draftThread?.branch ?? null);
140 const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
141 const activeProjectCwd = activeProject?.workspaceRoot ?? null;
142 const branchCwd = activeWorktreePath ?? activeProjectCwd;
143 const hasServerThread = serverThread !== null;
144 const effectiveEnvMode =
145 effectiveEnvModeOverride ??
146 resolveEffectiveEnvMode({
147 activeWorktreePath,
148 hasServerThread,
149 draftThreadEnvMode: draftThread?.envMode,
150 });
151
152 // ---------------------------------------------------------------------------
153 // Thread branch mutation (colocated — only this component calls it)
154 // ---------------------------------------------------------------------------
155 const setThreadBranch = useCallback(
156 (branch: string | null, worktreePath: string | null) => {
157 if (!activeThreadId || !activeProject) return;
158 if (serverSession && worktreePath !== activeWorktreePath) {
159 void stopThreadSession({
160 environmentId,
161 input: { threadId: activeThreadId },
162 });
163 }
164 if (hasServerThread) {
165 void updateThreadMetadata({
166 environmentId,
167 input: {
168 threadId: activeThreadId,
169 branch,
170 worktreePath,
171 },
172 });
173 }
174 if (hasServerThread) {
175 onActiveThreadBranchOverrideChange?.(branch);
176 return;
177 }
178 const nextDraftEnvMode = resolveDraftEnvModeAfterBranchChange({
179 nextWorktreePath: worktreePath,
180 currentWorktreePath: activeWorktreePath,
181 effectiveEnvMode,
182 });
183 setDraftThreadContext(draftId ?? threadRef, {
184 branch,
185 worktreePath,
186 envMode: nextDraftEnvMode,
187 projectRef: scopeProjectRef(environmentId, activeProject.id),
188 });
189 },
190 [
191 activeThreadId,
192 activeProject,
193 serverSession,
194 activeWorktreePath,
195 hasServerThread,
196 onActiveThreadBranchOverrideChange,
197 setDraftThreadContext,
198 draftId,
199 threadRef,
200 environmentId,
201 effectiveEnvMode,
202 stopThreadSession,
203 updateThreadMetadata,
204 ],
205 );
206
207 // ---------------------------------------------------------------------------
208 // Git ref queries
209 // ---------------------------------------------------------------------------
210 const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
211 const [branchQuery, setBranchQuery] = useState("");
212 const deferredBranchQuery = useDeferredValue(branchQuery);
213
214 const branchStatusQuery = useEnvironmentQuery(
215 branchCwd === null
216 ? null
217 : vcsEnvironment.status({
218 environmentId,
219 input: { cwd: branchCwd },
220 }),
221 );
222 const trimmedBranchQuery = branchQuery.trim();
223 const deferredTrimmedBranchQuery = deferredBranchQuery.trim();
224 // The server filters refs by substring, so it has to be given the sanitized
225 // name as well: querying the raw "new branch" drops an existing new-branch
226 // from the response entirely, which would defeat the collision check below.
227 // Ref names cannot contain an ASCII space, so sanitizing loses no matches.
228 const branchRefQuery = sanitizeNewRefName(deferredTrimmedBranchQuery);
229 const branchRefTarget = useMemo(
230 () => ({
231 environmentId,
232 cwd: branchCwd,
233 query: branchRefQuery,
234 }),
235 [branchCwd, branchRefQuery, environmentId],
236 );
237 const branchRefState = usePaginatedBranches(branchRefTarget);
238 const refs = branchRefState.refs;
239 const hasNextPage =
240 branchRefState.data?.nextCursor !== null && branchRefState.data?.nextCursor !== undefined;
241 const isFetchingNextPage = branchRefState.isFetchingNextPage;
242 const isInitialBranchesLoadPending = branchRefState.isPending && branchRefState.data === null;
243 const currentGitBranch =
244 branchStatusQuery.data?.refName ?? refs.find((refName) => refName.current)?.name ?? null;
245 const sourceControlPresentation = useMemo(
246 () => getSourceControlPresentation(branchStatusQuery.data?.sourceControlProvider),
247 [branchStatusQuery.data?.sourceControlProvider],
248 );
249 const SourceControlIcon = sourceControlPresentation.Icon;
250 const canonicalActiveBranch = resolveBranchToolbarValue({
251 envMode: effectiveEnvMode,
252 activeWorktreePath,
253 activeThreadBranch,
254 currentGitBranch,
255 });
256 const branchNames = useMemo(() => refs.map((refName) => refName.name), [refs]);
257 const branchByName = useMemo(
258 () => new Map(refs.map((refName) => [refName.name, refName] as const)),
259 [refs],
260 );
261 const normalizedDeferredBranchQuery = deferredTrimmedBranchQuery.toLowerCase();
262 const prReference = parsePullRequestReference(trimmedBranchQuery);
263 const isSelectingWorktreeBase =
264 effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath;
265 const checkoutPullRequestItemValue =
266 prReference && onCheckoutPullRequestRequest ? `__checkout_pull_request__:${prReference}` : null;
267 const canCreateBranch = !isSelectingWorktreeBase && trimmedBranchQuery.length > 0;
268 // The ref is created under its sanitized name, so the collision check has to
269 // use that name too. Matching on the raw query would offer to create a ref
270 // that already exists whenever sanitizing changes the name.
271 const newRefName = sanitizeNewRefName(trimmedBranchQuery);
272 const hasExactBranchMatch = branchByName.has(newRefName);
273 const createBranchItemValue = canCreateBranch
274 ? `__create_new_branch__:${trimmedBranchQuery}`
275 : null;
276 const branchPickerItems = useMemo(() => {
277 const items = [...branchNames];
278 if (createBranchItemValue && !hasExactBranchMatch) {
279 items.push(createBranchItemValue);
280 }
281 if (checkoutPullRequestItemValue) {
282 items.unshift(checkoutPullRequestItemValue);
283 }
284 return items;
285 }, [branchNames, checkoutPullRequestItemValue, createBranchItemValue, hasExactBranchMatch]);
286 const filteredBranchPickerItems = useMemo(
287 () =>
288 normalizedDeferredBranchQuery.length === 0
289 ? branchPickerItems
290 : branchPickerItems.filter((itemValue) =>
291 shouldIncludeBranchPickerItem({
292 itemValue,
293 normalizedQuery: normalizedDeferredBranchQuery,
294 createBranchItemValue,
295 checkoutPullRequestItemValue,
296 }),
297 ),
298 [
299 branchPickerItems,
300 checkoutPullRequestItemValue,
301 createBranchItemValue,
302 normalizedDeferredBranchQuery,
303 ],
304 );
305 const [resolvedActiveBranch, setOptimisticBranch] = useOptimistic(
306 canonicalActiveBranch,
307 (_currentBranch: string | null, optimisticBranch: string | null) => optimisticBranch,
308 );
309 const listedActiveBranch =
310 resolvedActiveBranch === null ? null : (branchByName.get(resolvedActiveBranch) ?? null);
311 const activeBranchRefQuery = useEnvironmentQuery(
312 branchCwd !== null && resolvedActiveBranch !== null
313 ? vcsEnvironment.listRefs({
314 environmentId,
315 input: {
316 cwd: branchCwd,
317 query: resolvedActiveBranch,
318 limit: 10,
319 },
320 })
321 : null,
322 );
323 const queriedActiveBranch = activeBranchRefQuery.data?.refs.find(
324 (refName) => refName.name === resolvedActiveBranch,
325 );
326 const resolvedActiveBranchIsRemote =
327 listedActiveBranch !== null
328 ? listedActiveBranch.isRemote === true
329 : queriedActiveBranch
330 ? queriedActiveBranch.isRemote === true
331 : null;
332 const [isBranchActionPending, startBranchActionTransition] = useTransition();
333 const totalBranchCount = branchRefState.data?.totalCount ?? 0;
334 const branchStatusText = isInitialBranchesLoadPending
335 ? "Loading refs..."
336 : isFetchingNextPage
337 ? "Loading more refs..."
338 : hasNextPage
339 ? `Showing ${refs.length} of ${totalBranchCount} refs`
340 : null;
341
342 // ---------------------------------------------------------------------------
343 // Branch actions
344 // ---------------------------------------------------------------------------
345 const copyBranchName = useCallback((branchName: string) => {
346 void writeTextToClipboard(branchName, "branch name").then(
347 (didCopy) => {
348 if (!didCopy) return;
349 toastManager.add({
350 type: "success",
351 title: "Branch name copied",
352 description: branchName,
353 });
354 },
355 (error: unknown) => {
356 toastManager.add(
357 stackedThreadToast({
358 type: "error",
359 title: "Failed to copy branch name",
360 description: toBranchActionErrorMessage(error),
361 }),
362 );
363 },
364 );
365 }, []);
366
367 const handleBranchContextMenu = useCallback(
368 (event: ReactMouseEvent, branchName: string | null) => {
369 if (!branchName) return;
370 const api = readLocalApi();
371 if (!api) return;
372 event.preventDefault();
373 event.stopPropagation();
374 const items: ContextMenuItem<"copy-branch-name">[] = [
375 { id: "copy-branch-name", label: "Copy branch name", icon: "copy" },
376 ];
377 void api.contextMenu.show(items, { x: event.clientX, y: event.clientY }).then((action) => {
378 if (action === "copy-branch-name") copyBranchName(branchName);
379 });
380 },
381 [copyBranchName],
382 );
383
384 const runBranchAction = (action: () => Promise<void>) => {
385 startBranchActionTransition(async () => {
386 await action();
387 branchRefState.refresh();
388 branchStatusQuery.refresh();
389 });
390 };
391
392 const selectBranch = (refName: VcsRef) => {
393 if (!branchCwd || !activeProjectCwd || isBranchActionPending) return;
394
395 if (isSelectingWorktreeBase) {
396 setThreadBranch(refName.name, null);
397 setIsBranchMenuOpen(false);
398 onComposerFocusRequest?.();
399 return;
400 }
401
402 const selectionTarget = resolveBranchSelectionTarget({
403 activeProjectCwd,
404 activeWorktreePath,
405 refName,
406 });
407
408 if (selectionTarget.reuseExistingWorktree) {
409 setThreadBranch(refName.name, selectionTarget.nextWorktreePath);
410 setIsBranchMenuOpen(false);
411 onComposerFocusRequest?.();
412 return;
413 }
414
415 const selectedBranchName = refName.isRemote
416 ? deriveLocalBranchNameFromRemoteRef(refName.name)
417 : refName.name;
418
419 setIsBranchMenuOpen(false);
420 onComposerFocusRequest?.();
421
422 runBranchAction(async () => {
423 const previousBranch = resolvedActiveBranch;
424 setOptimisticBranch(selectedBranchName);
425 const checkoutResult = await switchRef({
426 environmentId,
427 input: {
428 cwd: selectionTarget.checkoutCwd,
429 refName: refName.name,
430 },
431 });
432 if (checkoutResult._tag === "Success") {
433 const nextBranchName = refName.isRemote
434 ? (checkoutResult.value.refName ?? selectedBranchName)
435 : selectedBranchName;
436 setOptimisticBranch(nextBranchName);
437 setThreadBranch(nextBranchName, selectionTarget.nextWorktreePath);
438 return;
439 }
440 setOptimisticBranch(previousBranch);
441 if (!isAtomCommandInterrupted(checkoutResult)) {
442 toastManager.add(
443 stackedThreadToast({
444 type: "error",
445 title: "Failed to switch ref.",
446 description: toBranchActionErrorMessage(squashAtomCommandFailure(checkoutResult)),
447 }),
448 );
449 }
450 });
451 };
452
453 const createRef = (rawName: string) => {
454 const name = sanitizeNewRefName(rawName);
455 if (!branchCwd || !name || isBranchActionPending) return;
456
457 setIsBranchMenuOpen(false);
458 onComposerFocusRequest?.();
459
460 runBranchAction(async () => {
461 const previousBranch = resolvedActiveBranch;
462 setOptimisticBranch(name);
463 const createBranchResult = await createRefMutation({
464 environmentId,
465 input: {
466 cwd: branchCwd,
467 refName: name,
468 switchRef: true,
469 },
470 });
471 if (createBranchResult._tag === "Success") {
472 setOptimisticBranch(createBranchResult.value.refName);
473 setThreadBranch(createBranchResult.value.refName, activeWorktreePath);
474 return;
475 }
476 setOptimisticBranch(previousBranch);
477 if (!isAtomCommandInterrupted(createBranchResult)) {
478 toastManager.add(
479 stackedThreadToast({
480 type: "error",
481 title: "Failed to create and switch ref.",
482 description: toBranchActionErrorMessage(squashAtomCommandFailure(createBranchResult)),
483 }),
484 );
485 }
486 });
487 };
488
489 // Default the worktree base to the repo default branch (origin/HEAD), only
490 // falling back to the checked-out branch when no default is known.
491 const defaultBranchName = useMemo(
492 () => refs.find((refName) => refName.isDefault)?.name ?? null,
493 [refs],
494 );
495 const worktreeBaseBranchCandidate = isInitialBranchesLoadPending
496 ? null
497 : (defaultBranchName ?? currentGitBranch);
498
499 useEffect(() => {
500 if (
501 effectiveEnvMode !== "worktree" ||
502 activeWorktreePath ||
503 activeThreadBranch ||
504 !worktreeBaseBranchCandidate
505 ) {
506 return;
507 }
508 setThreadBranch(worktreeBaseBranchCandidate, null);
509 }, [
510 activeThreadBranch,
511 activeWorktreePath,
512 effectiveEnvMode,
513 setThreadBranch,
514 worktreeBaseBranchCandidate,
515 ]);
516
517 // ---------------------------------------------------------------------------
518 // Combobox / list plumbing
519 // ---------------------------------------------------------------------------
520 const branchListScrollElementRef = useRef<HTMLElement | null>(null);
521 const previousBranchListScrollTopRef = useRef<number | null>(null);
522 const handleOpenChange = useCallback((open: boolean) => {
523 previousBranchListScrollTopRef.current = null;
524 setIsBranchMenuOpen(open);
525 if (!open) {
526 setBranchQuery("");
527 }
528 }, []);
529
530 const [showTopBranchScrollFade, setShowTopBranchScrollFade] = useState(false);
531 const [showBottomBranchScrollFade, setShowBottomBranchScrollFade] = useState(false);
532 const fetchNextBranchPage = useCallback(() => {
533 if (!hasNextPage || isFetchingNextPage) {
534 return;
535 }
536
537 branchRefState.loadNext();
538 }, [branchRefState.loadNext, hasNextPage, isFetchingNextPage]);
539 const maybeFetchNextBranchPage = useCallback(() => {
540 const scrollElement = branchListScrollElementRef.current;
541 if (!scrollElement) {
542 return;
543 }
544
545 const previousScrollTop = previousBranchListScrollTopRef.current;
546 previousBranchListScrollTopRef.current = scrollElement.scrollTop;
547 if (
548 !isBranchMenuOpen ||
549 !hasNextPage ||
550 isFetchingNextPage ||
551 !shouldLoadNextBranchPageAfterScroll({
552 previousScrollTop,
553 scrollTop: scrollElement.scrollTop,
554 scrollHeight: scrollElement.scrollHeight,
555 clientHeight: scrollElement.clientHeight,
556 })
557 ) {
558 return;
559 }
560
561 fetchNextBranchPage();
562 }, [fetchNextBranchPage, hasNextPage, isBranchMenuOpen, isFetchingNextPage]);
563
564 const branchListRef = useRef<LegendListRef | null>(null);
565 const updateBranchListScrollFades = useCallback(() => {
566 const scrollElement = branchListRef.current?.getScrollableNode?.();
567 if (!(scrollElement instanceof HTMLElement)) {
568 return;
569 }
570 branchListScrollElementRef.current = scrollElement;
571 const maxScrollOffset = Math.max(0, scrollElement.scrollHeight - scrollElement.clientHeight);
572 setShowTopBranchScrollFade(scrollElement.scrollTop > 1);
573 setShowBottomBranchScrollFade(maxScrollOffset - scrollElement.scrollTop > 1);
574 }, []);
575
576 useLayoutEffect(() => {
577 if (!isBranchMenuOpen) {
578 return;
579 }
580
581 setShowTopBranchScrollFade(false);
582 setShowBottomBranchScrollFade(filteredBranchPickerItems.length > 8);
583 let nestedFrame = 0;
584 const frame = requestAnimationFrame(() => {
585 updateBranchListScrollFades();
586 nestedFrame = requestAnimationFrame(updateBranchListScrollFades);
587 });
588 return () => {
589 cancelAnimationFrame(frame);
590 cancelAnimationFrame(nestedFrame);
591 };
592 }, [
593 deferredTrimmedBranchQuery,
594 filteredBranchPickerItems.length,
595 isBranchMenuOpen,
596 updateBranchListScrollFades,
597 ]);
598
599 useEffect(() => {
600 if (!isBranchMenuOpen) {
601 return;
602 }
603
604 void branchListRef.current?.scrollToOffset?.({ offset: 0, animated: false });
605 }, [deferredTrimmedBranchQuery, isBranchMenuOpen]);
606
607 const triggerLabel = resolveBranchTriggerLabel({
608 activeWorktreePath,
609 effectiveEnvMode,
610 resolvedActiveBranch,
611 resolvedActiveBranchIsRemote,
612 startFromOrigin,
613 });
614
615 // PR pill shown next to the branch selector when the active branch has one.
616 const branchPr = resolveThreadPr({
617 threadBranch: resolveBranchToolbarPrBranch({
618 activeThreadBranch,
619 resolvedActiveBranch,
620 }),
621 gitStatus: branchStatusQuery.data ?? null,
622 });
623 const branchPrStatus = prStatusIndicator(branchPr, branchStatusQuery.data?.sourceControlProvider);
624 // Action-oriented tooltip (the pill opens the PR), distinct from the sidebar's
625 // state-description tooltip.
626 const branchPrTooltip = branchPr
627 ? `Open ${sourceControlPresentation.terminology.singular} #${branchPr.number} (${branchPr.state})`
628 : "";
629 const openPrLink = useOpenPrLink(threadRef);
630
631 function renderPickerItem(itemValue: string, index: number) {
632 if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) {
633 return (
634 <ComboboxItem
635 hideIndicator
636 key={itemValue}
637 index={index}
638 value={itemValue}
639 className="pe-2"
640 onClick={() => {
641 if (!prReference || !onCheckoutPullRequestRequest) {
642 return;
643 }
644 setIsBranchMenuOpen(false);
645 setBranchQuery("");
646 onComposerFocusRequest?.();
647 onCheckoutPullRequestRequest(prReference);
648 }}
649 >
650 <div className="flex min-w-0 items-center gap-2 py-1">
651 <SourceControlIcon className="size-3.5 shrink-0 text-muted-foreground" />
652 <span className="flex min-w-0 flex-col items-start">
653 <span className="truncate font-medium">
654 Checkout {sourceControlPresentation.terminology.singular}
655 </span>
656 <span className="truncate text-muted-foreground text-xs">{prReference}</span>
657 </span>
658 </div>
659 </ComboboxItem>
660 );
661 }
662 if (createBranchItemValue && itemValue === createBranchItemValue) {
663 return (
664 <ComboboxItem
665 hideIndicator
666 key={itemValue}
667 index={index}
668 value={itemValue}
669 className="pe-1.5"
670 onClick={() => createRef(trimmedBranchQuery)}
671 >
672 <span className="truncate">Create new ref "{newRefName}"</span>
673 </ComboboxItem>
674 );
675 }
676
677 const refName = branchByName.get(itemValue);
678 if (!refName) return null;
679
680 const hasSecondaryWorktree =
681 refName.worktreePath && activeProjectCwd && refName.worktreePath !== activeProjectCwd;
682 const badge = refName.current
683 ? "current"
684 : hasSecondaryWorktree
685 ? "worktree"
686 : refName.isRemote
687 ? "remote"
688 : refName.isDefault
689 ? "default"
690 : null;
691 return (
692 <ComboboxItem
693 hideIndicator
694 key={itemValue}
695 index={index}
696 value={itemValue}
697 className="pe-1.5"
698 onClick={() => selectBranch(refName)}
699 onContextMenu={(event) => handleBranchContextMenu(event, itemValue)}
700 >
701 <div className="flex w-full min-w-0 items-center justify-between gap-2">
702 <span className="min-w-0 flex-1 truncate">{itemValue}</span>
703 {badge && <span className="shrink-0 text-[10px] text-muted-foreground/45">{badge}</span>}
704 </div>
705 </ComboboxItem>
706 );
707 }
708
709 return (
710 <Combobox
711 items={branchPickerItems}
712 filteredItems={filteredBranchPickerItems}
713 autoHighlight
714 virtualized
715 onItemHighlighted={(_value, eventDetails) => {
716 if (!isBranchMenuOpen || eventDetails.index < 0 || eventDetails.reason !== "keyboard") {
717 return;
718 }
719 void branchListRef.current?.scrollIndexIntoView?.({
720 index: eventDetails.index,
721 animated: false,
722 });
723 }}
724 onOpenChange={handleOpenChange}
725 open={isBranchMenuOpen}
726 value={resolvedActiveBranch}
727 >
728 <div
729 className={cn("flex min-w-0 items-center gap-1", className)}
730 data-composer-context-control
731 >
732 {branchPr && branchPrStatus ? (
733 <Tooltip>
734 <TooltipTrigger
735 render={
736 <button
737 type="button"
738 aria-label={branchPrTooltip}
739 onClick={(event) => openPrLink(event, branchPrStatus.url)}
740 className={cn(
741 "inline-flex shrink-0 items-center gap-0.5 rounded px-1 py-0.5 text-[11px] font-medium tabular-nums transition-colors hover:bg-muted/60",
742 branchPrStatus.colorClass,
743 )}
744 />
745 }
746 >
747 <ChangeRequestStatusIcon className="size-3" />
748 <span>#{branchPr.number}</span>
749 </TooltipTrigger>
750 <TooltipPopup side="top">{branchPrTooltip}</TooltipPopup>
751 </Tooltip>
752 ) : null}
753 {/* Context menu lives on the wrapper: the disabled Button has
754 pointer-events-none, so the trigger itself never sees right-clicks
755 while refs are loading or a branch action is pending. */}
756 <span
757 className="flex min-w-0"
758 onContextMenu={(event) => handleBranchContextMenu(event, resolvedActiveBranch)}
759 >
760 <ComboboxTrigger
761 render={<Button variant="ghost" size="xs" />}
762 className="min-w-0 max-w-full text-muted-foreground/70 hover:text-foreground/80"
763 disabled={isInitialBranchesLoadPending || isBranchActionPending}
764 >
765 <GitBranchIcon className="size-3 shrink-0 opacity-70" />
766 <span
767 data-composer-label
768 className="min-w-0 max-w-[240px] group-data-[compact]/composer-context:max-w-0"
769 >
770 <span
771 data-composer-label-motion
772 className="block w-full min-w-0 max-w-[240px] origin-left truncate transition-[opacity,transform] duration-180 ease-[cubic-bezier(0.32,0.72,0,1)] group-data-[compact]/composer-context:[transform:translateX(-0.25rem)_scaleX(0.95)] group-data-[compact]/composer-context:opacity-0 motion-reduce:transform-none motion-reduce:transition-opacity"
773 >
774 {triggerLabel}
775 </span>
776 </span>
777 <ChevronDownIcon className="size-3 shrink-0 opacity-50" />
778 </ComboboxTrigger>
779 </span>
780 </div>
781 <ComboboxPopup align="end" side="top" className="flex w-80 flex-col">
782 <div className="shrink-0 px-3 pt-2.5">
783 <div className="relative -translate-y-px border-b border-border/70 pb-1.5 transition-colors focus-within:border-ring">
784 <SearchIcon
785 aria-hidden="true"
786 className="pointer-events-none absolute top-1.5 left-0 size-4 shrink-0 text-muted-foreground/55"
787 />
788 <ComboboxInput
789 className="[&_input]:h-6.5 [&_input]:ps-5 [&_input]:font-sans [&_input]:leading-6.5"
790 inputClassName="rounded-none bg-transparent text-sm"
791 placeholder="Search refs..."
792 showTrigger={false}
793 size="sm"
794 unstyled
795 value={branchQuery}
796 onChange={(event) => setBranchQuery(event.target.value)}
797 />
798 </div>
799 </div>
800 <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
801 <ComboboxEmpty>No refs found.</ComboboxEmpty>
802 <div className="relative min-h-0 w-full max-h-56 flex-1 overflow-hidden">
803 <ComboboxListVirtualized className="size-full min-w-0 p-0">
804 <LegendList<string>
805 ref={branchListRef}
806 data={filteredBranchPickerItems}
807 keyExtractor={(item) => item}
808 getItemType={(item) =>
809 item === checkoutPullRequestItemValue
810 ? "checkout-pull-request"
811 : item === createBranchItemValue
812 ? "create-branch"
813 : "branch"
814 }
815 renderItem={({ item, index }) => renderPickerItem(item, index)}
816 estimatedItemSize={28}
817 drawDistance={336}
818 onLayout={() => {
819 updateBranchListScrollFades();
820 previousBranchListScrollTopRef.current =
821 branchListScrollElementRef.current?.scrollTop ?? null;
822 }}
823 onScroll={() => {
824 updateBranchListScrollFades();
825 maybeFetchNextBranchPage();
826 }}
827 className={cn(
828 "scrollbar-gutter-stable overflow-x-hidden overscroll-y-contain ps-1 pe-0 pt-2 pb-1",
829 getVirtualizedScrollFadeClassName({
830 top: showTopBranchScrollFade,
831 bottom: showBottomBranchScrollFade,
832 }),
833 )}
834 style={{ maxHeight: "14rem" }}
835 />
836 </ComboboxListVirtualized>
837 </div>
838 {isSelectingWorktreeBase ? (
839 <Tooltip>
840 <TooltipTrigger
841 render={
842 <label
843 htmlFor={startFromOriginSwitchId}
844 className="flex cursor-pointer items-center justify-between gap-3 border-t border-border/60 px-3 py-2 text-xs"
845 >
846 <span className="flex min-w-0 items-center gap-1.5 font-medium text-muted-foreground">
847 <RefreshCwIcon aria-hidden="true" className="size-3 shrink-0 opacity-70" />
848 <span className="truncate">Start from origin</span>
849 </span>
850 <Switch
851 id={startFromOriginSwitchId}
852 checked={startFromOrigin}
853 className="[--thumb-size:--spacing(3.5)]"
854 aria-label="Start worktree from origin"
855 onCheckedChange={(checked) => onStartFromOriginChange(Boolean(checked))}
856 />
857 </label>
858 }
859 />
860 <TooltipPopup side="top" className="max-w-72 whitespace-normal leading-tight">
861 Creates the worktree from the latest matching branch on origin instead of your local
862 branch.
863 </TooltipPopup>
864 </Tooltip>
865 ) : null}
866 {branchStatusText ? <ComboboxStatus>{branchStatusText}</ComboboxStatus> : null}
867 </div>
868 </ComboboxPopup>
869 </Combobox>
870 );
871}