Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

BranchToolbarBranchSelector.tsx

861 lines30.6 KB

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