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

BranchToolbarBranchSelector.tsx

891 lines32.1 KB

1import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
2import {
3 isAtomCommandInterrupted,
4 squashAtomCommandFailure,
5} from "@t3tools/client-runtime/state/runtime";
6import type { ContextMenuItem, EnvironmentId, VcsRef, ThreadId } from "@t3tools/contracts";
7import { LegendList, type LegendListRef } from "@legendapp/list/react";
8import { ChevronDownIcon, GitBranchIcon, RefreshCwIcon, SearchIcon } from "lucide-react";
9import {
10 useCallback,
11 useDeferredValue,
12 useEffect,
13 useId,
14 useLayoutEffect,
15 useMemo,
16 useOptimistic,
17 useRef,
18 useState,
19 useTransition,
20 type MouseEvent as ReactMouseEvent,
21} from "react";
22​
23import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
24import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
25import { readLocalApi } from "../localApi";
26import { useOpenPrLink } from "../lib/openPullRequestLink";
27import { shouldLoadNextBranchPageAfterScroll } from "../state/paginatedBranches";
28import { usePaginatedBranches } from "../state/queries";
29import { useProject, useThread } from "../state/entities";
30import { useEnvironmentQuery } from "../state/query";
31import { threadEnvironment } from "../state/threads";
32import { useAtomCommand } from "../state/use-atom-command";
33import { vcsEnvironment } from "../state/vcs";
34import { cn } from "../lib/utils";
35import { parsePullRequestReference } from "../pullRequestReference";
36import { getSourceControlPresentation } from "../sourceControlPresentation";
37import { composerFloatingLayerProps } from "./chat/composerEventScope";
38import {
39 deriveLocalBranchNameFromRemoteRef,
40 resolveBranchTriggerLabel,
41 resolveBranchToolbarPrBranch,
42 resolveBranchSelectionTarget,
43 resolveBranchToolbarValue,
44 resolveDraftEnvModeAfterBranchChange,
45 resolveEffectiveEnvMode,
46 sanitizeNewRefName,
47 shouldIncludeBranchPickerItem,
48} from "./BranchToolbar.logic";
49import {
50 ChangeRequestStatusIcon,
51 prStatusIndicator,
52 resolveThreadPr,
53} from "./ThreadStatusIndicators";
54import { Button } from "./ui/button";
55import { Switch } from "./ui/switch";
56import { getVirtualizedScrollFadeClassName } from "./ui/scroll-area";
57import {
58 Combobox,
59 ComboboxEmpty,
60 ComboboxInput,
61 ComboboxItem,
62 ComboboxListVirtualized,
63 ComboboxPopup,
64 ComboboxStatus,
65 ComboboxTrigger,
66} from "./ui/combobox";
67import { stackedThreadToast, toastManager } from "./ui/toast";
68import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
69​
70interface BranchToolbarBranchSelectorProps {
71 className?: string;
72 environmentId: EnvironmentId;
73 threadId: ThreadId;
74 draftId?: DraftId;
75 envLocked: boolean;
76 effectiveEnvModeOverride?: "local" | "worktree";
77 activeThreadBranchOverride?: string | null;
78 onActiveThreadBranchOverrideChange?: (refName: string | null) => void;
79 startFromOrigin: boolean;
80 onStartFromOriginChange: (startFromOrigin: boolean) => void;
81 onCheckoutPullRequestRequest?: (reference: string) => void;
82 onComposerFocusRequest?: () => void;
84​
85function toBranchActionErrorMessage(error: unknown): string {
86 return error instanceof Error ? error.message : "An error occurred.";
88​
89export function BranchToolbarBranchSelector({
90 className,
91 environmentId,
92 threadId,
93 draftId,
94 envLocked,
95 effectiveEnvModeOverride,
96 activeThreadBranchOverride,
97 onActiveThreadBranchOverrideChange,
98 startFromOrigin,
99 onStartFromOriginChange,
100 onCheckoutPullRequestRequest,
101 onComposerFocusRequest,
102}: BranchToolbarBranchSelectorProps) {
103 const startFromOriginSwitchId = useId();
104 const stopThreadSession = useAtomCommand(threadEnvironment.stopSession, "thread session stop");
105 const updateThreadMetadata = useAtomCommand(
106 threadEnvironment.updateMetadata,
107 "thread metadata update",
108 );
109 const switchRef = useAtomCommand(vcsEnvironment.switchRef, {
110 reportFailure: false,
111 });
112 const createRefMutation = useAtomCommand(vcsEnvironment.createRef, {
113 reportFailure: false,
114 });
115 // ---------------------------------------------------------------------------
116 // Thread / project state (pushed down from parent to colocate with mutation)
117 // ---------------------------------------------------------------------------
118 const threadRef = useMemo(
119 () => scopeThreadRef(environmentId, threadId),
120 [environmentId, threadId],
121 );
122 const draftThread = useComposerDraftStore((store) =>
123 draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef),
124 );
125 const serverThread = useThread(threadRef, { waitForShell: draftThread !== null });
126 const serverSession = serverThread?.session ?? null;
127 const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
128​
129 const activeProjectRef = serverThread
130 ? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
131 : draftThread
132 ? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
133 : null;
134 const activeProject = useProject(activeProjectRef);
135​
136 const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined);
137 const activeThreadBranch =
138 activeThreadBranchOverride !== undefined
139 ? activeThreadBranchOverride
140 : (serverThread?.branch ?? draftThread?.branch ?? null);
141 const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
142 const activeProjectCwd = activeProject?.workspaceRoot ?? null;
143 const branchCwd = activeWorktreePath ?? activeProjectCwd;
144 const hasServerThread = serverThread !== null;
145 const effectiveEnvMode =
146 effectiveEnvModeOverride ??
147 resolveEffectiveEnvMode({
148 activeWorktreePath,
149 hasServerThread,
150 draftThreadEnvMode: draftThread?.envMode,
151 });
152​
153 // ---------------------------------------------------------------------------
154 // Thread branch mutation (colocated — only this component calls it)
155 // ---------------------------------------------------------------------------
156 const setThreadBranch = useCallback(
157 (branch: string | null, worktreePath: string | null) => {
158 if (!activeThreadId || !activeProject) return;
159 if (serverSession && worktreePath !== activeWorktreePath) {
160 void stopThreadSession({
161 environmentId,
162 input: { threadId: activeThreadId },
163 });
164 }
165 if (hasServerThread) {
166 void updateThreadMetadata({
167 environmentId,
168 input: {
169 threadId: activeThreadId,
170 branch,
171 worktreePath,
172 },
173 });
174 }
175 if (hasServerThread) {
176 onActiveThreadBranchOverrideChange?.(branch);
177 return;
178 }
179 const nextDraftEnvMode = resolveDraftEnvModeAfterBranchChange({
180 nextWorktreePath: worktreePath,
181 currentWorktreePath: activeWorktreePath,
182 effectiveEnvMode,
183 });
184 setDraftThreadContext(draftId ?? threadRef, {
185 branch,
186 worktreePath,
187 envMode: nextDraftEnvMode,
188 projectRef: scopeProjectRef(environmentId, activeProject.id),
189 });
190 },
191 [
192 activeThreadId,
193 activeProject,
194 serverSession,
195 activeWorktreePath,
196 hasServerThread,
197 onActiveThreadBranchOverrideChange,
198 setDraftThreadContext,
199 draftId,
200 threadRef,
201 environmentId,
202 effectiveEnvMode,
203 stopThreadSession,
204 updateThreadMetadata,
205 ],
206 );
207​
208 // ---------------------------------------------------------------------------
209 // Git ref queries
210 // ---------------------------------------------------------------------------
211 const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
212 const [branchQuery, setBranchQuery] = useState("");
213 const deferredBranchQuery = useDeferredValue(branchQuery);
214​
215 const branchStatusQuery = useEnvironmentQuery(
216 branchCwd === null
217 ? null
218 : vcsEnvironment.status({
219 environmentId,
220 input: { cwd: branchCwd },
221 }),
222 );
223 const trimmedBranchQuery = branchQuery.trim();
224 const deferredTrimmedBranchQuery = deferredBranchQuery.trim();
225 // The server filters refs by substring, so it has to be given the sanitized
226 // name as well: querying the raw "new branch" drops an existing new-branch
227 // from the response entirely, which would defeat the collision check below.
228 // Ref names cannot contain an ASCII space, so sanitizing loses no matches.
229 const branchRefQuery = sanitizeNewRefName(deferredTrimmedBranchQuery);
230 const branchRefTarget = useMemo(
231 () => ({
232 environmentId,
233 cwd: branchCwd,
234 query: branchRefQuery,
235 }),
236 [branchCwd, branchRefQuery, environmentId],
237 );
238 const branchRefState = usePaginatedBranches(branchRefTarget);
239 const refs = branchRefState.refs;
240 const hasNextPage =
241 branchRefState.data?.nextCursor !== null && branchRefState.data?.nextCursor !== undefined;
242 const isFetchingNextPage = branchRefState.isFetchingNextPage;
243 const isInitialBranchesLoadPending = branchRefState.isPending && branchRefState.data === null;
244 const currentGitBranch =
245 branchStatusQuery.data?.refName ?? refs.find((refName) => refName.current)?.name ?? null;
246 const sourceControlPresentation = useMemo(
247 () => getSourceControlPresentation(branchStatusQuery.data?.sourceControlProvider),
248 [branchStatusQuery.data?.sourceControlProvider],
249 );
250 const SourceControlIcon = sourceControlPresentation.Icon;
251 const canonicalActiveBranch = resolveBranchToolbarValue({
252 envMode: effectiveEnvMode,
253 activeWorktreePath,
254 activeThreadBranch,
255 currentGitBranch,
256 });
257 const branchNames = useMemo(() => refs.map((refName) => refName.name), [refs]);
258 const branchByName = useMemo(
259 () => new Map(refs.map((refName) => [refName.name, refName] as const)),
260 [refs],
261 );
262 const normalizedDeferredBranchQuery = deferredTrimmedBranchQuery.toLowerCase();
263 const prReference = parsePullRequestReference(trimmedBranchQuery);
264 const isSelectingWorktreeBase =
265 effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath;
266 const checkoutPullRequestItemValue =
267 prReference && onCheckoutPullRequestRequest ? `__checkout_pull_request__:${prReference}` : null;
268 const canCreateBranch = !isSelectingWorktreeBase && trimmedBranchQuery.length > 0;
269 // The ref is created under its sanitized name, so the collision check has to
270 // use that name too. Matching on the raw query would offer to create a ref
271 // that already exists whenever sanitizing changes the name.
272 const newRefName = sanitizeNewRefName(trimmedBranchQuery);
273 const hasExactBranchMatch = branchByName.has(newRefName);
274 const createBranchItemValue = canCreateBranch
275 ? `__create_new_branch__:${trimmedBranchQuery}`
276 : null;
277 const branchPickerItems = useMemo(() => {
278 const items = [...branchNames];
279 if (createBranchItemValue && !hasExactBranchMatch) {
280 items.push(createBranchItemValue);
281 }
282 if (checkoutPullRequestItemValue) {
283 items.unshift(checkoutPullRequestItemValue);
284 }
285 return items;
286 }, [branchNames, checkoutPullRequestItemValue, createBranchItemValue, hasExactBranchMatch]);
287 const filteredBranchPickerItems = useMemo(
288 () =>
289 normalizedDeferredBranchQuery.length === 0
290 ? branchPickerItems
291 : branchPickerItems.filter((itemValue) =>
292 shouldIncludeBranchPickerItem({
293 itemValue,
294 normalizedQuery: normalizedDeferredBranchQuery,
295 createBranchItemValue,
296 checkoutPullRequestItemValue,
297 }),
298 ),
299 [
300 branchPickerItems,
301 checkoutPullRequestItemValue,
302 createBranchItemValue,
303 normalizedDeferredBranchQuery,
304 ],
305 );
306 const [resolvedActiveBranch, setOptimisticBranch] = useOptimistic(
307 canonicalActiveBranch,
308 (_currentBranch: string | null, optimisticBranch: string | null) => optimisticBranch,
309 );
310 const listedActiveBranch =
311 resolvedActiveBranch === null ? null : (branchByName.get(resolvedActiveBranch) ?? null);
312 const activeBranchRefQuery = useEnvironmentQuery(
313 branchCwd !== null && resolvedActiveBranch !== null
314 ? vcsEnvironment.listRefs({
315 environmentId,
316 input: {
317 cwd: branchCwd,
318 query: resolvedActiveBranch,
319 limit: 10,
320 },
321 })
322 : null,
323 );
324 const queriedActiveBranch = activeBranchRefQuery.data?.refs.find(
325 (refName) => refName.name === resolvedActiveBranch,
326 );
327 const resolvedActiveBranchIsRemote =
328 listedActiveBranch !== null
329 ? listedActiveBranch.isRemote === true
330 : queriedActiveBranch
331 ? queriedActiveBranch.isRemote === true
332 : null;
333 const [isBranchActionPending, startBranchActionTransition] = useTransition();
334 const totalBranchCount = branchRefState.data?.totalCount ?? 0;
335 const branchStatusText = isInitialBranchesLoadPending
336 ? "Loading refs..."
337 : isFetchingNextPage
338 ? "Loading more refs..."
339 : hasNextPage
340 ? `Showing ${refs.length} of ${totalBranchCount} refs`
341 : null;
342​
343 // ---------------------------------------------------------------------------
344 // Branch actions
345 // ---------------------------------------------------------------------------
346 const copyBranchName = useCallback((branchName: string) => {
347 void writeTextToClipboard(branchName, "branch name").then(
348 (didCopy) => {
349 if (!didCopy) return;
350 toastManager.add({
351 type: "success",
352 title: "Branch name copied",
353 description: branchName,
354 });
355 },
356 (error: unknown) => {
357 toastManager.add(
358 stackedThreadToast({
359 type: "error",
360 title: "Failed to copy branch name",
361 description: toBranchActionErrorMessage(error),
362 }),
363 );
364 },
365 );
366 }, []);
367​
368 const handleBranchContextMenu = useCallback(
369 (event: ReactMouseEvent, branchName: string | null) => {
370 if (!branchName) return;
371 const api = readLocalApi();
372 if (!api) return;
373 event.preventDefault();
374 event.stopPropagation();
375 const items: ContextMenuItem<"copy-branch-name">[] = [
376 { id: "copy-branch-name", label: "Copy branch name", icon: "copy" },
377 ];
378 void api.contextMenu.show(items, { x: event.clientX, y: event.clientY }).then((action) => {
379 if (action === "copy-branch-name") copyBranchName(branchName);
380 });
381 },
382 [copyBranchName],
383 );
384​
385 const runBranchAction = (action: () => Promise<void>) => {
386 startBranchActionTransition(async () => {
387 await action();
388 branchRefState.refresh();
389 branchStatusQuery.refresh();
390 });
391 };
392​
393 const selectBranch = (refName: VcsRef) => {
394 if (!branchCwd || !activeProjectCwd || isBranchActionPending) return;
395​
396 if (isSelectingWorktreeBase) {
397 setThreadBranch(refName.name, null);
398 setIsBranchMenuOpen(false);
399 onComposerFocusRequest?.();
400 return;
401 }
402​
403 const selectionTarget = resolveBranchSelectionTarget({
404 activeProjectCwd,
405 activeWorktreePath,
406 refName,
407 });
408​
409 if (selectionTarget.reuseExistingWorktree) {
410 setThreadBranch(refName.name, selectionTarget.nextWorktreePath);
411 setIsBranchMenuOpen(false);
412 onComposerFocusRequest?.();
413 return;
414 }
415​
416 const selectedBranchName = refName.isRemote
417 ? deriveLocalBranchNameFromRemoteRef(refName.name)
418 : refName.name;
419​
420 setIsBranchMenuOpen(false);
421 onComposerFocusRequest?.();
422​
423 runBranchAction(async () => {
424 const previousBranch = resolvedActiveBranch;
425 setOptimisticBranch(selectedBranchName);
426 const checkoutResult = await switchRef({
427 environmentId,
428 input: {
429 cwd: selectionTarget.checkoutCwd,
430 refName: refName.name,
431 },
432 });
433 if (checkoutResult._tag === "Success") {
434 const nextBranchName = refName.isRemote
435 ? (checkoutResult.value.refName ?? selectedBranchName)
436 : selectedBranchName;
437 setOptimisticBranch(nextBranchName);
438 setThreadBranch(nextBranchName, selectionTarget.nextWorktreePath);
439 return;
440 }
441 setOptimisticBranch(previousBranch);
442 if (!isAtomCommandInterrupted(checkoutResult)) {
443 toastManager.add(
444 stackedThreadToast({
445 type: "error",
446 title: "Failed to switch ref.",
447 description: toBranchActionErrorMessage(squashAtomCommandFailure(checkoutResult)),
448 }),
449 );
450 }
451 });
452 };
453​
454 const createRef = (rawName: string) => {
455 const name = sanitizeNewRefName(rawName);
456 if (!branchCwd || !name || isBranchActionPending) return;
457​
458 setIsBranchMenuOpen(false);
459 onComposerFocusRequest?.();
460​
461 runBranchAction(async () => {
462 const previousBranch = resolvedActiveBranch;
463 setOptimisticBranch(name);
464 const createBranchResult = await createRefMutation({
465 environmentId,
466 input: {
467 cwd: branchCwd,
468 refName: name,
469 switchRef: true,
470 },
471 });
472 if (createBranchResult._tag === "Success") {
473 setOptimisticBranch(createBranchResult.value.refName);
474 setThreadBranch(createBranchResult.value.refName, activeWorktreePath);
475 return;
476 }
477 setOptimisticBranch(previousBranch);
478 if (!isAtomCommandInterrupted(createBranchResult)) {
479 toastManager.add(
480 stackedThreadToast({
481 type: "error",
482 title: "Failed to create and switch ref.",
483 description: toBranchActionErrorMessage(squashAtomCommandFailure(createBranchResult)),
484 }),
485 );
486 }
487 });
488 };
489​
490 // Default the worktree base to the repo default branch (origin/HEAD), only
491 // falling back to the checked-out branch when no default is known.
492 const defaultBranchName = useMemo(
493 () => refs.find((refName) => refName.isDefault)?.name ?? null,
494 [refs],
495 );
496 const worktreeBaseBranchCandidate = isInitialBranchesLoadPending
497 ? null
498 : (defaultBranchName ?? currentGitBranch);
499​
500 useEffect(() => {
501 if (
502 effectiveEnvMode !== "worktree" ||
503 activeWorktreePath ||
504 activeThreadBranch ||
505 !worktreeBaseBranchCandidate
506 ) {
507 return;
508 }
509 setThreadBranch(worktreeBaseBranchCandidate, null);
510 }, [
511 activeThreadBranch,
512 activeWorktreePath,
513 effectiveEnvMode,
514 setThreadBranch,
515 worktreeBaseBranchCandidate,
516 ]);
517​
518 // ---------------------------------------------------------------------------
519 // Combobox / list plumbing
520 // ---------------------------------------------------------------------------
521 const branchListScrollElementRef = useRef<HTMLElement | null>(null);
522 const previousBranchListScrollTopRef = useRef<number | null>(null);
523 const handleOpenChange = useCallback((open: boolean) => {
524 previousBranchListScrollTopRef.current = null;
525 setIsBranchMenuOpen(open);
526 if (!open) {
527 setBranchQuery("");
528 }
529 }, []);
530​
531 const [showTopBranchScrollFade, setShowTopBranchScrollFade] = useState(false);
532 const [showBottomBranchScrollFade, setShowBottomBranchScrollFade] = useState(false);
533 const fetchNextBranchPage = useCallback(() => {
534 if (!hasNextPage || isFetchingNextPage) {
535 return;
536 }
537​
538 branchRefState.loadNext();
539 }, [branchRefState.loadNext, hasNextPage, isFetchingNextPage]);
540 const maybeFetchNextBranchPage = useCallback(() => {
541 const scrollElement = branchListScrollElementRef.current;
542 if (!scrollElement) {
543 return;
544 }
545​
546 const previousScrollTop = previousBranchListScrollTopRef.current;
547 previousBranchListScrollTopRef.current = scrollElement.scrollTop;
548 if (
549 !isBranchMenuOpen ||
550 !hasNextPage ||
551 isFetchingNextPage ||
552 !shouldLoadNextBranchPageAfterScroll({
553 previousScrollTop,
554 scrollTop: scrollElement.scrollTop,
555 scrollHeight: scrollElement.scrollHeight,
556 clientHeight: scrollElement.clientHeight,
557 })
558 ) {
559 return;
560 }
561​
562 fetchNextBranchPage();
563 }, [fetchNextBranchPage, hasNextPage, isBranchMenuOpen, isFetchingNextPage]);
564​
565 const branchListRef = useRef<LegendListRef | null>(null);
566 const updateBranchListScrollFades = useCallback(() => {
567 const scrollElement = branchListRef.current?.getScrollableNode?.();
568 if (!(scrollElement instanceof HTMLElement)) {
569 return;
570 }
571 branchListScrollElementRef.current = scrollElement;
572 const maxScrollOffset = Math.max(0, scrollElement.scrollHeight - scrollElement.clientHeight);
573 setShowTopBranchScrollFade(scrollElement.scrollTop > 1);
574 setShowBottomBranchScrollFade(maxScrollOffset - scrollElement.scrollTop > 1);
575 }, []);
576​
577 useLayoutEffect(() => {
578 if (!isBranchMenuOpen) {
579 return;
580 }
581​
582 setShowTopBranchScrollFade(false);
583 setShowBottomBranchScrollFade(filteredBranchPickerItems.length > 8);
584 let nestedFrame = 0;
585 const frame = requestAnimationFrame(() => {
586 updateBranchListScrollFades();
587 nestedFrame = requestAnimationFrame(updateBranchListScrollFades);
588 });
589 return () => {
590 cancelAnimationFrame(frame);
591 cancelAnimationFrame(nestedFrame);
592 };
593 }, [
594 deferredTrimmedBranchQuery,
595 filteredBranchPickerItems.length,
596 isBranchMenuOpen,
597 updateBranchListScrollFades,
598 ]);
599​
600 useEffect(() => {
601 if (!isBranchMenuOpen) {
602 return;
603 }
604​
605 void branchListRef.current?.scrollToOffset?.({ offset: 0, animated: false });
606 }, [deferredTrimmedBranchQuery, isBranchMenuOpen]);
607​
608 const triggerLabel = resolveBranchTriggerLabel({
609 activeWorktreePath,
610 effectiveEnvMode,
611 resolvedActiveBranch,
612 resolvedActiveBranchIsRemote,
613 startFromOrigin,
614 });
615​
616 // PR pill shown next to the branch selector when the active branch has one.
617 const branchPr = resolveThreadPr({
618 threadBranch: resolveBranchToolbarPrBranch({
619 activeThreadBranch,
620 resolvedActiveBranch,
621 }),
622 gitStatus: branchStatusQuery.data ?? null,
623 });
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 origin-left truncate transition-[opacity,transform] duration-180 ease-[cubic-bezier(0.32,0.72,0,1)] group-data-[compact]/composer-context:[transform:translateX(-0.25rem)_scaleX(0.95)] group-data-[compact]/composer-context:opacity-0 motion-reduce:transform-none motion-reduce:transition-opacity"
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 className="min-w-0 max-w-full font-normal text-muted-foreground/70 text-xs! hover:text-foreground/80"
778 disabled={isInitialBranchesLoadPending || isBranchActionPending}
779 >
780 <GitBranchIcon className="size-3 shrink-0 opacity-70" />
781 <span
782 data-composer-label
783 className="min-w-0 max-w-[240px] group-data-[compact]/composer-context:max-w-0"
784 >
785 <span
786 data-composer-label-motion
787 className="block w-full min-w-0 max-w-[240px] origin-left truncate transition-[opacity,transform] duration-180 ease-[cubic-bezier(0.32,0.72,0,1)] group-data-[compact]/composer-context:[transform:translateX(-0.25rem)_scaleX(0.95)] group-data-[compact]/composer-context:opacity-0 motion-reduce:transform-none motion-reduce:transition-opacity"
788 >
789 {triggerLabel}
790 </span>
791 </span>
792 <ChevronDownIcon className="size-3 shrink-0 opacity-50" />
793 </ComboboxTrigger>
794 </span>
795 </div>
796 <ComboboxPopup
797 align="end"
798 side="top"
799 className="flex w-80 flex-col"
800 {...composerFloatingLayerProps}
801 >
802 <div className="shrink-0 px-3 pt-2.5">
803 <div className="relative -translate-y-px border-b border-border/70 pb-1.5 transition-colors focus-within:border-ring">
804 <SearchIcon
805 aria-hidden="true"
806 className="pointer-events-none absolute top-1.5 left-0 size-4 shrink-0 text-muted-foreground/55"
807 />
808 <ComboboxInput
809 className="[&_input]:h-6.5 [&_input]:ps-5 [&_input]:font-sans [&_input]:leading-6.5"
810 inputClassName="rounded-none bg-transparent text-sm"
811 placeholder="Search refs..."
812 showTrigger={false}
813 size="sm"
814 unstyled
815 value={branchQuery}
816 onChange={(event) => setBranchQuery(event.target.value)}
817 />
818 </div>
819 </div>
820 <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
821 <ComboboxEmpty>No refs found.</ComboboxEmpty>
822 <div className="relative min-h-0 w-full max-h-56 flex-1 overflow-hidden">
823 <ComboboxListVirtualized className="size-full min-w-0 p-0">
824 <LegendList<string>
825 ref={branchListRef}
826 data={filteredBranchPickerItems}
827 keyExtractor={(item) => item}
828 getItemType={(item) =>
829 item === checkoutPullRequestItemValue
830 ? "checkout-pull-request"
831 : item === createBranchItemValue
832 ? "create-branch"
833 : "branch"
834 }
835 renderItem={({ item, index }) => renderPickerItem(item, index)}
836 estimatedItemSize={28}
837 drawDistance={336}
838 onLayout={() => {
839 updateBranchListScrollFades();
840 previousBranchListScrollTopRef.current =
841 branchListScrollElementRef.current?.scrollTop ?? null;
842 }}
843 onScroll={() => {
844 updateBranchListScrollFades();
845 maybeFetchNextBranchPage();
846 }}
847 className={cn(
848 "scrollbar-gutter-stable overflow-x-hidden overscroll-y-contain ps-1 pe-0 pt-2 pb-1",
849 getVirtualizedScrollFadeClassName({
850 top: showTopBranchScrollFade,
851 bottom: showBottomBranchScrollFade,
852 }),
853 )}
854 style={{ maxHeight: "14rem" }}
855 />
856 </ComboboxListVirtualized>
857 </div>
858 {isSelectingWorktreeBase ? (
859 <Tooltip>
860 <TooltipTrigger
861 render={
862 <label
863 htmlFor={startFromOriginSwitchId}
864 className="flex cursor-pointer items-center justify-between gap-3 border-t border-border/60 px-3 py-2 text-xs"
865 >
866 <span className="flex min-w-0 items-center gap-1.5 font-medium text-muted-foreground">
867 <RefreshCwIcon aria-hidden="true" className="size-3 shrink-0 opacity-70" />
868 <span className="truncate">Start from origin</span>
869 </span>
870 <Switch
871 id={startFromOriginSwitchId}
872 checked={startFromOrigin}
873 size="sm"
874 aria-label="Start worktree from origin"
875 onCheckedChange={(checked) => onStartFromOriginChange(Boolean(checked))}
876 />
877 </label>
878 }
879 />
880 <TooltipPopup side="top" className="max-w-72 whitespace-normal leading-tight">
881 Creates the worktree from the latest matching branch on origin instead of your local
882 branch.
883 </TooltipPopup>
884 </Tooltip>
885 ) : null}
886 {branchStatusText ? <ComboboxStatus>{branchStatusText}</ComboboxStatus> : null}
887 </div>
888 </ComboboxPopup>
889 </Combobox>
890 );