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

BranchToolbarBranchSelector.tsx

770 lines26.8 KB

1import { ThreadDetailsControl } from "./chat/ThreadDetailsControl";
2import { ComposerContextLabel } from "./ComposerContextLabel";
3import { useSupportsMultiplePullRequests } from "~/hooks/useSupportsMultiplePullRequests";
4import { resolveThreadCurrentPullRequestLink } from "@t3tools/shared/threadPullRequests";
5import { useRightPanelStore } from "../rightPanelStore";
6import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
7import {
8 isAtomCommandInterrupted,
9 squashAtomCommandFailure,
10} from "@t3tools/client-runtime/state/runtime";
11import type { ContextMenuItem, EnvironmentId, VcsRef, ThreadId } from "@t3tools/contracts";
12import { ChevronDownIcon, GitBranchIcon } from "lucide-react";
13import {
14 useCallback,
15 useDeferredValue,
16 useEffect,
17 useImperativeHandle,
18 useMemo,
19 useOptimistic,
20 useState,
21 useTransition,
22 type MouseEvent as ReactMouseEvent,
23 type Ref,
24} from "react";
25​
26import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
27import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
28import { readLocalApi } from "../localApi";
29import { useOpenPrLink } from "../lib/openPullRequestLink";
30import { usePaginatedBranches } from "../state/queries";
31import { useProject, useThreadShell } from "../state/entities";
32import { useEnvironmentQuery } from "../state/query";
33import { threadEnvironment } from "../state/threads";
34import { useAtomCommand } from "../state/use-atom-command";
35import { vcsEnvironment } from "../state/vcs";
36import { cn } from "../lib/utils";
37import {
38 THREAD_DETAILS_PANEL_CHEVRON_CLASS,
39 THREAD_DETAILS_PANEL_ICON_CLASS,
40} from "./chat/threadDetailsPanelStyles";
41import { ThreadDetailsPrRows } from "./chat/ThreadDetailsPrRows";
42import { parsePullRequestReference } from "../pullRequestReference";
43import { getSourceControlPresentation } from "../sourceControlPresentation";
44import { useComposerMenuProps } from "./chat/composerEventScope";
45import {
46 deriveLocalBranchNameFromRemoteRef,
47 resolveBranchTriggerLabel,
48 resolveBranchToolbarPrBranch,
49 resolveBranchSelectionTarget,
50 resolveBranchToolbarValue,
51 resolveDraftEnvModeAfterBranchChange,
52 resolveEffectiveEnvMode,
53 sanitizeNewRefName,
54 shouldIncludeBranchPickerItem,
55} from "./BranchToolbar.logic";
56import {
57 ThreadPullRequestBadgeControl,
58 prStatusIndicator,
59 resolveThreadPullRequestBadge,
60 useLinkedThreadPullRequest,
61} from "./ThreadStatusIndicators";
62​
63import { ComboboxItem, ComboboxTrigger } from "./ui/combobox";
64import { ComposerControl } from "./chat/ComposerControl";
65import { MiddleTruncate } from "./ui/middle-truncate";
66import { BranchPicker, BranchPickerRefItem } from "./BranchPicker";
67import { stackedThreadToast, toastManager } from "./ui/toast";
68​
69export interface BranchToolbarBranchSelectorHandle {
70 open: () => void;
72​
73interface BranchToolbarBranchSelectorProps {
74 forceNewWorktree?: boolean;
75 ref?: Ref<BranchToolbarBranchSelectorHandle>;
76 className?: string;
77 displayMode?: "toolbar" | "panel";
78 environmentId: EnvironmentId;
79 threadId: ThreadId;
80 draftId?: DraftId;
81 envLocked: boolean;
82 effectiveEnvModeOverride?: "local" | "worktree";
83 activeThreadBranchOverride?: string | null;
84 onActiveThreadBranchOverrideChange?: (refName: string | null) => void;
85 startFromOrigin: boolean;
86 onStartFromOriginChange: (startFromOrigin: boolean) => void;
87 onCheckoutPullRequestRequest?: (reference: string) => void;
88 onComposerFocusRequest?: () => void;
90​
91function toBranchActionErrorMessage(error: unknown): string {
92 return error instanceof Error ? error.message : "An error occurred.";
94​
95export function BranchToolbarBranchSelector({
96 forceNewWorktree = false,
97 ref,
98 className,
99 displayMode = "toolbar",
100 environmentId,
101 threadId,
102 draftId,
103 envLocked,
104 effectiveEnvModeOverride,
105 activeThreadBranchOverride,
106 onActiveThreadBranchOverrideChange,
107 startFromOrigin,
108 onStartFromOriginChange,
109 onCheckoutPullRequestRequest,
110 onComposerFocusRequest,
111}: BranchToolbarBranchSelectorProps) {
112 const composerFloatingLayerProps = useComposerMenuProps();
113 const stopThreadSession = useAtomCommand(threadEnvironment.stopSession, "thread session stop");
114 const updateThreadMetadata = useAtomCommand(
115 threadEnvironment.updateMetadata,
116 "thread metadata update",
117 );
118 const switchRef = useAtomCommand(vcsEnvironment.switchRef, {
119 reportFailure: false,
120 });
121 const createRefMutation = useAtomCommand(vcsEnvironment.createRef, {
122 reportFailure: false,
123 });
124 // ---------------------------------------------------------------------------
125 // Thread / project state (pushed down from parent to colocate with mutation)
126 // ---------------------------------------------------------------------------
127 const threadRef = useMemo(
128 () => scopeThreadRef(environmentId, threadId),
129 [environmentId, threadId],
130 );
131 const serverThread = useThreadShell(threadRef);
132 const serverSession = serverThread?.runtime ?? null;
133 const draftThread = useComposerDraftStore((store) =>
134 draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef),
135 );
136 const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
137​
138 const activeProjectRef = serverThread
139 ? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
140 : draftThread
141 ? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
142 : null;
143 const activeProject = useProject(activeProjectRef);
144​
145 const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined);
146 const activeThreadBranch =
147 activeThreadBranchOverride !== undefined
148 ? activeThreadBranchOverride
149 : (serverThread?.branch ?? draftThread?.branch ?? null);
150 const activeWorktreePath = forceNewWorktree
151 ? null
152 : (serverThread?.worktreePath ?? draftThread?.worktreePath ?? null);
153 const activeProjectCwd = activeProject?.workspaceRoot ?? null;
154 const branchCwd = activeWorktreePath ?? activeProjectCwd;
155 const hasServerThread = serverThread !== null;
156 const effectiveEnvMode =
157 effectiveEnvModeOverride ??
158 resolveEffectiveEnvMode({
159 activeWorktreePath,
160 hasServerThread,
161 draftThreadEnvMode: draftThread?.envMode,
162 });
163​
164 // ---------------------------------------------------------------------------
165 // Thread branch mutation (colocated — only this component calls it)
166 // ---------------------------------------------------------------------------
167 const setThreadBranch = useCallback(
168 (branch: string | null, worktreePath: string | null, automatic = false) => {
169 if (!activeThreadId || !activeProject) return;
170 if (serverSession && worktreePath !== activeWorktreePath) {
171 void stopThreadSession({
172 environmentId,
173 input: { threadId: activeThreadId },
174 });
175 }
176 if (hasServerThread) {
177 void updateThreadMetadata({
178 environmentId,
179 input: {
180 threadId: activeThreadId,
181 branch,
182 worktreePath,
183 },
184 });
185 }
186 if (hasServerThread) {
187 onActiveThreadBranchOverrideChange?.(branch);
188 return;
189 }
190 const nextDraftEnvMode = resolveDraftEnvModeAfterBranchChange({
191 nextWorktreePath: worktreePath,
192 currentWorktreePath: activeWorktreePath,
193 effectiveEnvMode,
194 });
195 setDraftThreadContext(draftId ?? threadRef, {
196 branch,
197 worktreePath,
198 envMode: nextDraftEnvMode,
199 environmentSelection: automatic ? (draftThread?.environmentSelection ?? "auto") : "manual",
200 projectRef: scopeProjectRef(environmentId, activeProject.id),
201 });
202 },
203 [
204 activeThreadId,
205 activeProject,
206 serverSession,
207 activeWorktreePath,
208 hasServerThread,
209 onActiveThreadBranchOverrideChange,
210 setDraftThreadContext,
211 draftId,
212 threadRef,
213 environmentId,
214 effectiveEnvMode,
215 draftThread?.environmentSelection,
216 stopThreadSession,
217 updateThreadMetadata,
218 ],
219 );
220​
221 // ---------------------------------------------------------------------------
222 // Git ref queries
223 // ---------------------------------------------------------------------------
224 const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
225 const [branchQuery, setBranchQuery] = useState("");
226 const deferredBranchQuery = useDeferredValue(branchQuery);
227​
228 const branchStatusQuery = useEnvironmentQuery(
229 branchCwd === null
230 ? null
231 : vcsEnvironment.status({
232 environmentId,
233 input: { cwd: branchCwd },
234 }),
235 );
236 const trimmedBranchQuery = branchQuery.trim();
237 const deferredTrimmedBranchQuery = deferredBranchQuery.trim();
238 // The server filters refs by substring, so it has to be given the sanitized
239 // name as well: querying the raw "new branch" drops an existing new-branch
240 // from the response entirely, which would defeat the collision check below.
241 // Ref names cannot contain an ASCII space, so sanitizing loses no matches.
242 const branchRefQuery = sanitizeNewRefName(deferredTrimmedBranchQuery);
243 const branchRefState = usePaginatedBranches({
244 environmentId,
245 cwd: branchCwd,
246 query: branchRefQuery,
247 });
248 const refs = branchRefState.refs;
249 const hasNextPage =
250 branchRefState.data?.nextCursor !== null && branchRefState.data?.nextCursor !== undefined;
251 const isFetchingNextPage = branchRefState.isFetchingNextPage;
252 const isInitialBranchesLoadPending = branchRefState.isPending && branchRefState.data === null;
253 const currentGitBranch =
254 branchStatusQuery.data?.refName ?? refs.find((refName) => refName.current)?.name ?? null;
255 const sourceControlPresentation = useMemo(
256 () => getSourceControlPresentation(branchStatusQuery.data?.sourceControlProvider),
257 [branchStatusQuery.data?.sourceControlProvider],
258 );
259 const SourceControlIcon = sourceControlPresentation.Icon;
260 const canonicalActiveBranch = resolveBranchToolbarValue({
261 envMode: effectiveEnvMode,
262 activeWorktreePath,
263 activeThreadBranch,
264 currentGitBranch,
265 });
266 const branchNames = useMemo(() => refs.map((refName) => refName.name), [refs]);
267 const branchByName = useMemo(
268 () => new Map(refs.map((refName) => [refName.name, refName] as const)),
269 [refs],
270 );
271 const normalizedDeferredBranchQuery = deferredTrimmedBranchQuery.toLowerCase();
272 const prReference = parsePullRequestReference(trimmedBranchQuery);
273 const isSelectingWorktreeBase =
274 effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath;
275 const checkoutPullRequestItemValue =
276 prReference && onCheckoutPullRequestRequest ? `__checkout_pull_request__:${prReference}` : null;
277 const canCreateBranch = !isSelectingWorktreeBase && trimmedBranchQuery.length > 0;
278 // The ref is created under its sanitized name, so the collision check has to
279 // use that name too. Matching on the raw query would offer to create a ref
280 // that already exists whenever sanitizing changes the name.
281 const newRefName = sanitizeNewRefName(trimmedBranchQuery);
282 const hasExactBranchMatch = branchByName.has(newRefName);
283 const createBranchItemValue = canCreateBranch
284 ? `__create_new_branch__:${trimmedBranchQuery}`
285 : null;
286 const branchPickerItems = useMemo(() => {
287 const items = [...branchNames];
288 if (createBranchItemValue && !hasExactBranchMatch) {
289 items.push(createBranchItemValue);
290 }
291 if (checkoutPullRequestItemValue) {
292 items.unshift(checkoutPullRequestItemValue);
293 }
294 return items;
295 }, [branchNames, checkoutPullRequestItemValue, createBranchItemValue, hasExactBranchMatch]);
296 const filteredBranchPickerItems = useMemo(
297 () =>
298 normalizedDeferredBranchQuery.length === 0
299 ? branchPickerItems
300 : branchPickerItems.filter((itemValue) =>
301 shouldIncludeBranchPickerItem({
302 itemValue,
303 normalizedQuery: normalizedDeferredBranchQuery,
304 createBranchItemValue,
305 checkoutPullRequestItemValue,
306 }),
307 ),
308 [
309 branchPickerItems,
310 checkoutPullRequestItemValue,
311 createBranchItemValue,
312 normalizedDeferredBranchQuery,
313 ],
314 );
315 const [resolvedActiveBranch, setOptimisticBranch] = useOptimistic(
316 canonicalActiveBranch,
317 (_currentBranch: string | null, optimisticBranch: string | null) => optimisticBranch,
318 );
319 const listedActiveBranch =
320 resolvedActiveBranch === null ? null : (branchByName.get(resolvedActiveBranch) ?? null);
321 const activeBranchRefQuery = useEnvironmentQuery(
322 branchCwd !== null && resolvedActiveBranch !== null
323 ? vcsEnvironment.listRefs({
324 environmentId,
325 input: {
326 cwd: branchCwd,
327 query: resolvedActiveBranch,
328 limit: 10,
329 },
330 })
331 : null,
332 );
333 const queriedActiveBranch = activeBranchRefQuery.data?.refs.find(
334 (refName) => refName.name === resolvedActiveBranch,
335 );
336 const resolvedActiveBranchIsRemote =
337 listedActiveBranch !== null
338 ? listedActiveBranch.isRemote === true
339 : queriedActiveBranch
340 ? queriedActiveBranch.isRemote === true
341 : null;
342 const [isBranchActionPending, startBranchActionTransition] = useTransition();
343 const totalBranchCount = branchRefState.data?.totalCount ?? 0;
344 const branchStatusText = isInitialBranchesLoadPending
345 ? "Loading refs..."
346 : isFetchingNextPage
347 ? "Loading more refs..."
348 : hasNextPage
349 ? `Showing ${refs.length} of ${totalBranchCount} refs`
350 : null;
351​
352 // ---------------------------------------------------------------------------
353 // Branch actions
354 // ---------------------------------------------------------------------------
355 const copyBranchName = useCallback((branchName: string) => {
356 void writeTextToClipboard(branchName, "branch name").then(
357 (didCopy) => {
358 if (!didCopy) return;
359 toastManager.add({
360 type: "success",
361 title: "Branch name copied",
362 description: branchName,
363 });
364 },
365 (error: unknown) => {
366 toastManager.add(
367 stackedThreadToast({
368 type: "error",
369 title: "Failed to copy branch name",
370 description: toBranchActionErrorMessage(error),
371 }),
372 );
373 },
374 );
375 }, []);
376​
377 const handleBranchContextMenu = useCallback(
378 (event: ReactMouseEvent, branchName: string | null) => {
379 if (!branchName) return;
380 const api = readLocalApi();
381 if (!api) return;
382 event.preventDefault();
383 event.stopPropagation();
384 const items: ContextMenuItem<"copy-branch-name">[] = [
385 { id: "copy-branch-name", label: "Copy branch name", icon: "copy" },
386 ];
387 void api.contextMenu.show(items, { x: event.clientX, y: event.clientY }).then((action) => {
388 if (action === "copy-branch-name") copyBranchName(branchName);
389 });
390 },
391 [copyBranchName],
392 );
393​
394 const runBranchAction = (action: () => Promise<void>) => {
395 startBranchActionTransition(async () => {
396 await action();
397 branchRefState.refresh();
398 branchStatusQuery.refresh();
399 });
400 };
401​
402 const selectBranch = (refName: VcsRef) => {
403 if (!branchCwd || !activeProjectCwd || isBranchActionPending) return;
404​
405 if (isSelectingWorktreeBase) {
406 setThreadBranch(refName.name, null);
407 setIsBranchMenuOpen(false);
408 onComposerFocusRequest?.();
409 return;
410 }
411​
412 const selectionTarget = resolveBranchSelectionTarget({
413 activeProjectCwd,
414 activeWorktreePath,
415 refName,
416 });
417​
418 if (selectionTarget.reuseExistingWorktree) {
419 setThreadBranch(refName.name, selectionTarget.nextWorktreePath);
420 setIsBranchMenuOpen(false);
421 onComposerFocusRequest?.();
422 return;
423 }
424​
425 const selectedBranchName = refName.isRemote
426 ? deriveLocalBranchNameFromRemoteRef(refName.name)
427 : refName.name;
428​
429 setIsBranchMenuOpen(false);
430 onComposerFocusRequest?.();
431​
432 runBranchAction(async () => {
433 const previousBranch = resolvedActiveBranch;
434 setOptimisticBranch(selectedBranchName);
435 const checkoutResult = await switchRef({
436 environmentId,
437 input: {
438 cwd: selectionTarget.checkoutCwd,
439 refName: refName.name,
440 },
441 });
442 if (checkoutResult._tag === "Success") {
443 const nextBranchName = refName.isRemote
444 ? (checkoutResult.value.refName ?? selectedBranchName)
445 : selectedBranchName;
446 setOptimisticBranch(nextBranchName);
447 setThreadBranch(nextBranchName, selectionTarget.nextWorktreePath);
448 return;
449 }
450 setOptimisticBranch(previousBranch);
451 if (!isAtomCommandInterrupted(checkoutResult)) {
452 toastManager.add(
453 stackedThreadToast({
454 type: "error",
455 title: "Failed to switch ref.",
456 description: toBranchActionErrorMessage(squashAtomCommandFailure(checkoutResult)),
457 }),
458 );
459 }
460 });
461 };
462​
463 const createRef = (rawName: string) => {
464 const name = sanitizeNewRefName(rawName);
465 if (!branchCwd || !name || isBranchActionPending) return;
466​
467 setIsBranchMenuOpen(false);
468 onComposerFocusRequest?.();
469​
470 runBranchAction(async () => {
471 const previousBranch = resolvedActiveBranch;
472 setOptimisticBranch(name);
473 const createBranchResult = await createRefMutation({
474 environmentId,
475 input: {
476 cwd: branchCwd,
477 refName: name,
478 switchRef: true,
479 },
480 });
481 if (createBranchResult._tag === "Success") {
482 setOptimisticBranch(createBranchResult.value.refName);
483 setThreadBranch(createBranchResult.value.refName, activeWorktreePath);
484 return;
485 }
486 setOptimisticBranch(previousBranch);
487 if (!isAtomCommandInterrupted(createBranchResult)) {
488 toastManager.add(
489 stackedThreadToast({
490 type: "error",
491 title: "Failed to create and switch ref.",
492 description: toBranchActionErrorMessage(squashAtomCommandFailure(createBranchResult)),
493 }),
494 );
495 }
496 });
497 };
498​
499 // Default the worktree base to the repo default branch (origin/HEAD), only
500 // falling back to the checked-out branch when no default is known.
501 const defaultBranchName = useMemo(
502 () => refs.find((refName) => refName.isDefault)?.name ?? null,
503 [refs],
504 );
505 const worktreeBaseBranchCandidate = isInitialBranchesLoadPending
506 ? null
507 : (defaultBranchName ?? currentGitBranch);
508​
509 useEffect(() => {
510 if (
511 effectiveEnvMode !== "worktree" ||
512 activeWorktreePath ||
513 activeThreadBranch ||
514 !worktreeBaseBranchCandidate
515 ) {
516 return;
517 }
518 setThreadBranch(worktreeBaseBranchCandidate, null, true);
519 }, [
520 activeThreadBranch,
521 activeWorktreePath,
522 effectiveEnvMode,
523 setThreadBranch,
524 worktreeBaseBranchCandidate,
525 ]);
526​
527 // ---------------------------------------------------------------------------
528 // Combobox / list plumbing
529 // ---------------------------------------------------------------------------
530 const handleOpenChange = useCallback((open: boolean) => {
531 setIsBranchMenuOpen(open);
532 if (!open) {
533 setBranchQuery("");
534 }
535 }, []);
536​
537 useImperativeHandle(
538 ref,
539 () => ({
540 open: () => {
541 if (isInitialBranchesLoadPending || isBranchActionPending) return;
542 handleOpenChange(true);
543 },
544 }),
545 [handleOpenChange, isBranchActionPending, isInitialBranchesLoadPending],
546 );
547​
548 const triggerLabel = resolveBranchTriggerLabel({
549 activeWorktreePath,
550 effectiveEnvMode,
551 resolvedActiveBranch,
552 resolvedActiveBranchIsRemote,
553 startFromOrigin,
554 });
555​
556 // Branch status is the fallback when this thread has no linked pull requests.
557 const branchPrBranch = resolveBranchToolbarPrBranch({
558 activeThreadBranch,
559 resolvedActiveBranch,
560 });
561 const branchPr =
562 branchPrBranch !== null && branchStatusQuery.data?.refName === branchPrBranch
563 ? (branchStatusQuery.data.pr ?? null)
564 : null;
565 const supportsMultiplePullRequests = useSupportsMultiplePullRequests(environmentId);
566 const linkedStatus = useLinkedThreadPullRequest(
567 environmentId,
568 serverThread?.linkedPullRequest,
569 true,
570 serverThread?.pullRequests,
571 serverThread?.branchPullRequest,
572 );
573 const currentLinkedPr = supportsMultiplePullRequests
574 ? resolveThreadCurrentPullRequestLink(serverThread?.pullRequests ?? [])
575 : null;
576 const prBadge = supportsMultiplePullRequests
577 ? resolveThreadPullRequestBadge(serverThread?.pullRequests)
578 : null;
579 const displayedPr = linkedStatus?.pr ?? (currentLinkedPr === null ? branchPr : null);
580 const displayedPrStatus = prStatusIndicator(
581 displayedPr,
582 linkedStatus?.sourceControlProvider ?? branchStatusQuery.data?.sourceControlProvider,
583 );
584 const prNumber = currentLinkedPr?.number ?? displayedPr?.number;
585 const prUrl = currentLinkedPr?.url ?? displayedPr?.url;
586 const openPrLink = useOpenPrLink(threadRef);
587 const panelPrLabel =
588 prNumber === undefined
589 ? ""
590 : `#${prNumber}${displayedPr?.title.trim() ? `: ${displayedPr.title}` : ""}`;
591​
592 function selectPickerItem(itemValue: string) {
593 if (itemValue === checkoutPullRequestItemValue && prReference && onCheckoutPullRequestRequest) {
594 handleOpenChange(false);
595 onComposerFocusRequest?.();
596 onCheckoutPullRequestRequest(prReference);
597 } else if (itemValue === createBranchItemValue) {
598 createRef(trimmedBranchQuery);
599 } else {
600 const refName = branchByName.get(itemValue);
601 if (refName) selectBranch(refName);
602 }
603 }
604​
605 function renderPickerItem(itemValue: string, index: number) {
606 if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) {
607 return (
608 <ComboboxItem
609 hideIndicator
610 key={itemValue}
611 index={index}
612 value={itemValue}
613 onClick={() => selectPickerItem(itemValue)}
614 >
615 <div className="flex min-w-0 items-center gap-2 py-1">
616 <SourceControlIcon className="size-3.5 shrink-0 text-muted-foreground" />
617 <span className="flex min-w-0 flex-col items-start">
618 <span className="truncate font-medium">
619 Checkout {sourceControlPresentation.terminology.singular}
620 </span>
621 <span className="truncate text-muted-foreground text-xs">{prReference}</span>
622 </span>
623 </div>
624 </ComboboxItem>
625 );
626 }
627 if (createBranchItemValue && itemValue === createBranchItemValue) {
628 return (
629 <ComboboxItem
630 hideIndicator
631 key={itemValue}
632 index={index}
633 value={itemValue}
634 onClick={() => selectPickerItem(itemValue)}
635 >
636 <span className="truncate">Create new ref &quot;{newRefName}&quot;</span>
637 </ComboboxItem>
638 );
639 }
640​
641 const refName = branchByName.get(itemValue);
642 if (!refName) return null;
643​
644 return (
645 <BranchPickerRefItem
646 branch={refName}
647 projectCwd={activeProjectCwd}
648 index={index}
649 value={itemValue}
650 onClick={() => selectPickerItem(itemValue)}
651 onContextMenu={(event) => handleBranchContextMenu(event, itemValue)}
652 />
653 );
654 }
655​
656 return (
657 <BranchPicker
658 items={branchPickerItems}
659 filteredItems={filteredBranchPickerItems}
660 open={isBranchMenuOpen}
661 onOpenChange={handleOpenChange}
662 onSelectItem={selectPickerItem}
663 value={resolvedActiveBranch}
664 query={branchQuery}
665 resultsQuery={deferredTrimmedBranchQuery}
666 onQueryChange={setBranchQuery}
667 hasNextPage={hasNextPage}
668 isFetchingNextPage={isFetchingNextPage}
669 onLoadNext={branchRefState.loadNext}
670 statusText={branchStatusText}
671 renderItem={renderPickerItem}
672 getItemType={(item) =>
673 item === checkoutPullRequestItemValue
674 ? "checkout-pull-request"
675 : item === createBranchItemValue
676 ? "create-branch"
677 : "branch"
678 }
679 originControl={
680 isSelectingWorktreeBase
681 ? { checked: startFromOrigin, onCheckedChange: onStartFromOriginChange }
682 : undefined
683 }
684 popupProps={{
685 align: displayMode === "panel" ? "start" : "end",
686 side: displayMode === "panel" ? "bottom" : "top",
687 className: cn("flex flex-col", displayMode === "panel" ? "w-(--anchor-width)" : "w-80"),
688 ...(displayMode === "toolbar" ? composerFloatingLayerProps : {}),
689 }}
690 >
691 <div
692 className={cn(
693 "flex min-w-0",
694 displayMode === "panel" ? "w-full flex-col items-stretch" : "items-center gap-1",
695 className,
696 )}
697 >
698 {displayMode !== "panel" ? (
699 <ThreadPullRequestBadgeControl
700 render={<ComposerControl size="xs" />}
701 badge={prBadge}
702 pullRequests={serverThread?.pullRequests ?? []}
703 number={prNumber}
704 url={prUrl}
705 status={displayedPrStatus}
706 onOpenList={() => useRightPanelStore.getState().open(threadRef, "pull-requests")}
707 onOpenPullRequest={(event, targetUrl = prUrl) => {
708 if (targetUrl) openPrLink(event, targetUrl);
709 }}
710 />
711 ) : null}
712 <span
713 className="flex min-w-0"
714 onMouseDownCapture={(event) => {
715 if (event.button !== 0 || event.ctrlKey) {
716 event.stopPropagation();
717 }
718 }}
719 onContextMenu={(event) => handleBranchContextMenu(event, resolvedActiveBranch)}
720 >
721 <ComboboxTrigger
722 render={
723 displayMode === "panel" ? (
724 <ThreadDetailsControl part="select" />
725 ) : (
726 <ComposerControl size="xs" />
727 )
728 }
729 className="min-w-0 max-w-full active:scale-100"
730 disabled={isInitialBranchesLoadPending || isBranchActionPending}
731 >
732 <GitBranchIcon
733 className={cn(
734 "size-3 shrink-0 opacity-70",
735 displayMode === "panel" && THREAD_DETAILS_PANEL_ICON_CLASS,
736 )}
737 />
738 <ComposerContextLabel displayMode={displayMode}>
739 <MiddleTruncate value={triggerLabel} className="w-full" />
740 </ComposerContextLabel>
741 {displayMode === "panel" ? (
742 <span data-slot="select-icon">
743 <ChevronDownIcon className={THREAD_DETAILS_PANEL_CHEVRON_CLASS} />
744 </span>
745 ) : (
746 <ChevronDownIcon className="size-3 shrink-0 opacity-50" />
747 )}
748 </ComboboxTrigger>
749 </span>
750 {displayMode === "panel" && prNumber !== undefined && prUrl !== undefined ? (
751 <ThreadDetailsPrRows
752 links={serverThread?.pullRequests ?? []}
753 currentLink={currentLinkedPr}
754 onOpenLink={openPrLink}
755 environmentId={environmentId}
756 pr={displayedPr}
757 number={prNumber}
758 reference={currentLinkedPr}
759 status={displayedPrStatus}
760 project={activeProject}
761 label={panelPrLabel}
762 openAriaLabel={prUrl ?? "Open pull request"}
763 onOpen={(event) => openPrLink(event, prUrl)}
764 onActed={() => branchStatusQuery.refresh()}
765 />
766 ) : null}
767 </div>
768 </BranchPicker>
769 );