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

BranchToolbarBranchSelector.tsx

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