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

BranchToolbarBranchSelector.tsx

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