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

BranchToolbarBranchSelector.tsx

893 lines32.3 KB

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