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

BranchToolbarBranchSelector.tsx

755 lines26.1 KB

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