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

BranchToolbarBranchSelector.tsx

931 lines33.1 KB

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