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