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

BranchToolbar.tsx

539 lines20.3 KB

1import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
2import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
3import {
4 ChevronDownIcon,
5 CloudIcon,
6 FolderGit2Icon,
7 FolderGitIcon,
8 FolderIcon,
9 HistoryIcon,
10 MonitorIcon,
11} from "lucide-react";
12import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
13​
14import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
15import { useProject, useThread, useThreadShellsForProjectRefs } from "../state/entities";
16import { useIsMobile } from "../hooks/useMediaQuery";
17import {
18 type EnvMode,
19 type EnvironmentOption,
20 resolveCurrentWorkspaceLabel,
21 resolveEnvModeLabel,
22 resolveEffectiveEnvMode,
23 resolveLockedWorkspaceLabel,
24 resolvePreviousWorktreeLabel,
25 resolvePreviousWorktreeSeed,
26 shouldShowEnvironmentIndicator,
27} from "./BranchToolbar.logic";
28import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
29import { BranchToolbarEnvironmentSelector } from "./BranchToolbarEnvironmentSelector";
30import { BranchToolbarEnvModeSelector } from "./BranchToolbarEnvModeSelector";
31import { Button } from "./ui/button";
32import {
33 Menu,
34 MenuGroup,
35 MenuGroupLabel,
36 MenuPopup,
37 MenuRadioGroup,
38 MenuRadioItem,
39 MenuSeparator,
40 MenuTrigger,
41} from "./ui/menu";
42import { Separator } from "./ui/separator";
43​
44interface BranchToolbarProps {
45 environmentId: EnvironmentId;
46 threadId: ThreadId;
47 showGitControls: boolean;
48 draftId?: DraftId;
49 onEnvModeChange: (mode: EnvMode) => void;
50 effectiveEnvModeOverride?: EnvMode;
51 activeThreadBranchOverride?: string | null;
52 onActiveThreadBranchOverrideChange?: (branch: string | null) => void;
53 startFromOrigin: boolean;
54 onStartFromOriginChange: (startFromOrigin: boolean) => void;
55 envLocked: boolean;
56 onCheckoutPullRequestRequest?: (reference: string) => void;
57 onComposerFocusRequest?: () => void;
58 availableEnvironments?: readonly EnvironmentOption[];
59 onEnvironmentChange?: (environmentId: EnvironmentId) => void;
61​
62interface MobileRunContextSelectorProps {
63 envLocked: boolean;
64 envModeLocked: boolean;
65 environmentId: EnvironmentId;
66 availableEnvironments: readonly EnvironmentOption[] | undefined;
67 showEnvironmentPicker: boolean;
68 showEnvironmentIndicator: boolean;
69 onEnvironmentChange: ((environmentId: EnvironmentId) => void) | undefined;
70 effectiveEnvMode: EnvMode;
71 activeWorktreePath: string | null;
72 onEnvModeChange: (mode: EnvMode) => void;
73 previousWorktreeLabel: string | null;
74 onUsePreviousWorktree: () => void;
76​
77const MobileRunContextSelector = memo(function MobileRunContextSelector({
78 envLocked,
79 envModeLocked,
80 environmentId,
81 availableEnvironments,
82 showEnvironmentPicker,
83 showEnvironmentIndicator,
84 onEnvironmentChange,
85 effectiveEnvMode,
86 activeWorktreePath,
87 onEnvModeChange,
88 previousWorktreeLabel,
89 onUsePreviousWorktree,
90}: MobileRunContextSelectorProps) {
91 const activeEnvironment = useMemo(
92 () => availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null,
93 [availableEnvironments, environmentId],
94 );
95 const WorkspaceIcon =
96 effectiveEnvMode === "worktree"
97 ? FolderGit2Icon
98 : activeWorktreePath
99 ? FolderGitIcon
100 : FolderIcon;
101 const workspaceLabel = envModeLocked
102 ? resolveLockedWorkspaceLabel(activeWorktreePath)
103 : effectiveEnvMode === "worktree"
104 ? resolveEnvModeLabel("worktree")
105 : resolveCurrentWorkspaceLabel(activeWorktreePath);
106 const isLocked = envLocked || envModeLocked;
107 const EnvironmentIcon = activeEnvironment?.isPrimary ? MonitorIcon : CloudIcon;
108 const icon = showEnvironmentIndicator ? (
109 // Button's base styles apply `-mx-0.5` to descendant SVGs, which eats 4px
110 // out of whatever gap we set. mx-0! cancels that so gap-0.5 reads as 2px.
111 <span className="inline-flex shrink-0 items-center gap-0.5">
112 <EnvironmentIcon className="size-3 shrink-0 mx-0!" />
113 <WorkspaceIcon className="size-3 shrink-0 mx-0!" />
114 </span>
115 ) : (
116 <WorkspaceIcon className="size-3 shrink-0" />
117 );
118 const triggerContent = (
119 <>
120 {icon}
121 <span className="min-w-0 truncate">
122 {showEnvironmentIndicator ? (activeEnvironment?.label ?? "Run on") : workspaceLabel}
123 </span>
124 </>
125 );
126​
127 if (isLocked) {
128 return (
129 <span className="inline-flex h-7 min-w-0 max-w-[48%] flex-1 items-center justify-start gap-1 rounded-md border border-transparent px-[calc(--spacing(2)-1px)] text-sm font-medium text-muted-foreground/70 sm:h-6 md:hidden">
130 {triggerContent}
131 </span>
132 );
133 }
134​
135 return (
136 <Menu>
137 <MenuTrigger
138 render={<Button variant="ghost" size="xs" />}
139 className="min-w-0 max-w-[48%] flex-1 justify-start text-muted-foreground/70 hover:text-foreground/80 md:hidden"
140 >
141 {triggerContent}
142 <ChevronDownIcon className="size-3 shrink-0 opacity-50" />
143 </MenuTrigger>
144 <MenuPopup align="start" side="top" className="w-64">
145 {showEnvironmentPicker && availableEnvironments && onEnvironmentChange ? (
146 <>
147 <MenuGroup>
148 <MenuGroupLabel>Run on</MenuGroupLabel>
149 <MenuRadioGroup
150 value={environmentId}
151 onValueChange={(value) => onEnvironmentChange(value as EnvironmentId)}
152 >
153 {availableEnvironments.map((env) => {
154 const Icon = env.isPrimary ? MonitorIcon : CloudIcon;
155 return (
156 <MenuRadioItem
157 key={env.environmentId}
158 disabled={envLocked}
159 value={env.environmentId}
160 >
161 <span className="flex min-w-0 items-center gap-1.5">
162 <Icon className="size-3" />
163 <span className="min-w-0 truncate">{env.label}</span>
164 </span>
165 </MenuRadioItem>
166 );
167 })}
168 </MenuRadioGroup>
169 </MenuGroup>
170 <MenuSeparator />
171 </>
172 ) : null}
173 <MenuGroup>
174 <MenuGroupLabel>Workspace</MenuGroupLabel>
175 <MenuRadioGroup
176 value={effectiveEnvMode}
177 onValueChange={(value) => {
178 if (value === "previous-worktree") {
179 onUsePreviousWorktree();
180 return;
181 }
182 onEnvModeChange(value as EnvMode);
183 }}
184 >
185 <MenuRadioItem disabled={envModeLocked} value="local">
186 <span className="flex min-w-0 items-center gap-1.5">
187 {activeWorktreePath ? (
188 <FolderGitIcon className="size-3" />
189 ) : (
190 <FolderIcon className="size-3" />
191 )}
192 <span className="min-w-0 truncate">
193 {resolveCurrentWorkspaceLabel(activeWorktreePath)}
194 </span>
195 </span>
196 </MenuRadioItem>
197 <MenuRadioItem disabled={envModeLocked} value="worktree">
198 <span className="flex min-w-0 items-center gap-1.5">
199 <FolderGit2Icon className="size-3" />
200 <span className="min-w-0 truncate">{resolveEnvModeLabel("worktree")}</span>
201 </span>
202 </MenuRadioItem>
203 {previousWorktreeLabel ? (
204 <MenuRadioItem disabled={envModeLocked} value="previous-worktree">
205 <span className="flex min-w-0 items-center gap-1.5">
206 <HistoryIcon className="size-3" />
207 <span className="min-w-0 truncate">{previousWorktreeLabel}</span>
208 </span>
209 </MenuRadioItem>
210 ) : null}
211 </MenuRadioGroup>
212 </MenuGroup>
213 </MenuPopup>
214 </Menu>
215 );
216});
217​
218/**
219 * Collapse the strip's labels to icons only when the text no longer fits.
220 *
221 * Hidden labels stay measurable because their inner text keeps its natural
222 * width while the outer layout box collapses. This lets every pass recompute
223 * the expanded width without remembered values that could go stale or latch
224 * the strip compact. A small hysteresis keeps the boundary from flapping.
225 */
226const COMPACT_EXPAND_HYSTERESIS_PX = 16;
227const COMPOSER_CONTEXT_MOTION_DURATION_MS = 180;
228const COMPOSER_CONTEXT_MOTION_EASING = "cubic-bezier(0.32, 0.72, 0, 1)";
229const COMPOSER_CONTEXT_CONTROL_SELECTOR = "[data-composer-context-control]";
230​
231function useLabelsOverflow(element: HTMLDivElement | null): boolean {
232 const [overflows, setOverflows] = useState(false);
233 const pendingControlRectsRef = useRef<Map<HTMLElement, DOMRect> | null>(null);
234 const controlAnimationsRef = useRef(new Map<HTMLElement, Animation>());
235 // A render-synced mirror instead of useEffectEvent: the compiler memoizes
236 // the event callback, which left observers reading the first render's null
237 // element forever.
238 const stateRef = useRef({ element, overflows });
239 stateRef.current = { element, overflows };
240​
241 const measure = useCallback(() => {
242 const { element: current, overflows: compact } = stateRef.current;
243 if (!current) return;
244 const available = current.clientWidth;
245 if (available === 0) return;
246 // flex-1 stretches the groups to fill the strip, so their own boxes always
247 // measure "full". Sum the laid-out content instead, skipping hidden form
248 // artifacts and other out-of-flow nodes.
249 const contentWidth = (parent: Element): number => {
250 const gap = Number.parseFloat(getComputedStyle(parent).columnGap) || 0;
251 let width = 0;
252 let counted = 0;
253 for (const child of parent.children) {
254 if (!(child instanceof HTMLElement)) continue;
255 if (child.offsetWidth <= 1) continue;
256 const position = getComputedStyle(child).position;
257 if (position === "absolute" || position === "fixed") continue;
258 width += child.offsetWidth;
259 counted += 1;
260 }
261 return width + gap * Math.max(0, counted - 1);
262 };
263 const stripGap = Number.parseFloat(getComputedStyle(current).columnGap) || 0;
264 let needed = 0;
265 let groups = 0;
266 for (const child of current.children) {
267 if (!(child instanceof HTMLElement) || child.offsetWidth <= 1) continue;
268 needed += contentWidth(child);
269 groups += 1;
270 }
271 needed += stripGap * Math.max(0, groups - 1);
272 for (const label of current.querySelectorAll<HTMLElement>("[data-composer-label]")) {
273 // The clipping can happen below the marker (SelectValue truncates
274 // internally), where the outer span's scrollWidth matches its clipped
275 // box. The text's real width is the largest scrollWidth in the subtree.
276 let textWidth = label.scrollWidth;
277 for (const inner of label.querySelectorAll<HTMLElement>("*")) {
278 textWidth = Math.max(textWidth, inner.scrollWidth);
279 }
280 if (compact) {
281 // Compact: the label is squeezed to zero width but keeps reporting
282 // the full width it would need when expanded.
283 needed += textWidth;
284 } else {
285 // Expanded: the label is in flow; only the clipped remainder is
286 // missing from the content sum.
287 needed += Math.max(0, textWidth - label.clientWidth);
288 }
289 }
290 const nextOverflows = compact
291 ? needed > available - COMPACT_EXPAND_HYSTERESIS_PX
292 : needed > available;
293 if (nextOverflows !== compact) {
294 pendingControlRectsRef.current = new Map(
295 Array.from(current.querySelectorAll<HTMLElement>(COMPOSER_CONTEXT_CONTROL_SELECTOR)).map(
296 (control) => [control, control.getBoundingClientRect()],
297 ),
298 );
299 }
300 setOverflows(nextOverflows);
301 }, []);
302​
303 useLayoutEffect(() => {
304 const previousRects = pendingControlRectsRef.current;
305 if (!previousRects) return;
306 pendingControlRectsRef.current = null;
307​
308 for (const animation of controlAnimationsRef.current.values()) {
309 animation.cancel();
310 }
311 controlAnimationsRef.current.clear();
312​
313 if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
314​
315 for (const [control, previousRect] of previousRects) {
316 if (!control.isConnected) continue;
317 const nextRect = control.getBoundingClientRect();
318 const deltaX = previousRect.left - nextRect.left;
319 const deltaY = previousRect.top - nextRect.top;
320 if (Math.abs(deltaX) < 0.5 && Math.abs(deltaY) < 0.5) continue;
321​
322 const animation = control.animate(
323 [
324 { transform: `translate3d(${deltaX}px, ${deltaY}px, 0)` },
325 { transform: "translate3d(0, 0, 0)" },
326 ],
327 {
328 duration: COMPOSER_CONTEXT_MOTION_DURATION_MS,
329 easing: COMPOSER_CONTEXT_MOTION_EASING,
330 fill: "backwards",
331 },
332 );
333 controlAnimationsRef.current.set(control, animation);
334 animation.addEventListener(
335 "finish",
336 () => {
337 if (controlAnimationsRef.current.get(control) === animation) {
338 controlAnimationsRef.current.delete(control);
339 }
340 },
341 { once: true },
342 );
343 }
344 }, [overflows]);
345​
346 useEffect(
347 () => () => {
348 for (const animation of controlAnimationsRef.current.values()) {
349 animation.cancel();
350 }
351 },
352 [],
353 );
354​
355 // Label widths can change without the strip box moving (font family or
356 // size preferences), so re-measure on every render as well as on resize
357 // and font loads.
358 useEffect(() => {
359 measure();
360 });
361​
362 useEffect(() => {
363 if (!element) return;
364 const observer = new ResizeObserver(measure);
365 observer.observe(element);
366 document.fonts.addEventListener("loadingdone", measure);
367 return () => {
368 observer.disconnect();
369 document.fonts.removeEventListener("loadingdone", measure);
370 };
371 }, [element, measure]);
372​
373 return overflows;
375​
376export const BranchToolbar = memo(function BranchToolbar({
377 environmentId,
378 threadId,
379 showGitControls,
380 draftId,
381 onEnvModeChange,
382 effectiveEnvModeOverride,
383 activeThreadBranchOverride,
384 onActiveThreadBranchOverrideChange,
385 startFromOrigin,
386 onStartFromOriginChange,
387 envLocked,
388 onCheckoutPullRequestRequest,
389 onComposerFocusRequest,
390 availableEnvironments,
391 onEnvironmentChange,
392}: BranchToolbarProps) {
393 const threadRef = useMemo(
394 () => scopeThreadRef(environmentId, threadId),
395 [environmentId, threadId],
396 );
397 const draftThread = useComposerDraftStore((store) =>
398 draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef),
399 );
400 const serverThread = useThread(threadRef, { waitForShell: draftThread !== null });
401 const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
402 const activeProjectRef = serverThread
403 ? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
404 : draftThread
405 ? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
406 : null;
407 const activeProject = useProject(activeProjectRef);
408 const hasActiveThread = serverThread !== null || draftThread !== null;
409 const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
410 const effectiveEnvMode =
411 effectiveEnvModeOverride ??
412 resolveEffectiveEnvMode({
413 activeWorktreePath,
414 hasServerThread: serverThread !== null,
415 draftThreadEnvMode: draftThread?.envMode,
416 });
417 const envModeLocked = envLocked || (serverThread !== null && activeWorktreePath !== null);
418​
419 // "Previous worktree" hops a draft into the most recently active worktree
420 // of this project — the "keep going where I just was" follow-up flow. Only
421 // drafts can hop; started server threads have their workspace pinned.
422 const canUsePreviousWorktree = draftThread !== null && serverThread === null && !envModeLocked;
423 const projectRefsForWorktreeLookup = useMemo(
424 () => (canUsePreviousWorktree && activeProjectRef ? [activeProjectRef] : []),
425 [canUsePreviousWorktree, activeProjectRef],
426 );
427 const projectThreads = useThreadShellsForProjectRefs(projectRefsForWorktreeLookup);
428 const previousWorktreeSeed = useMemo(
429 () =>
430 canUsePreviousWorktree
431 ? resolvePreviousWorktreeSeed({
432 threads: projectThreads,
433 currentWorktreePath: activeWorktreePath,
434 })
435 : null,
436 [activeWorktreePath, canUsePreviousWorktree, projectThreads],
437 );
438 const previousWorktreeLabel = previousWorktreeSeed
439 ? resolvePreviousWorktreeLabel(previousWorktreeSeed)
440 : null;
441 const onUsePreviousWorktree = useCallback(() => {
442 if (!previousWorktreeSeed || !activeProjectRef) return;
443 // Same shape the branch selector writes when picking a branch that
444 // already lives in a worktree: point the draft at the existing tree.
445 setDraftThreadContext(draftId ?? threadRef, {
446 branch: previousWorktreeSeed.branch,
447 worktreePath: previousWorktreeSeed.worktreePath,
448 envMode: "worktree",
449 projectRef: activeProjectRef,
450 });
451 }, [activeProjectRef, draftId, previousWorktreeSeed, setDraftThreadContext, threadRef]);
452​
453 const showEnvironmentPicker = Boolean(
454 availableEnvironments && availableEnvironments.length > 1 && onEnvironmentChange,
455 );
456 const activeEnvironmentOption =
457 availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null;
458 const showEnvironmentIndicator = shouldShowEnvironmentIndicator({
459 activeEnvironment: activeEnvironmentOption,
460 canPickEnvironment: showEnvironmentPicker,
461 });
462 const isMobile = useIsMobile();
463 const [stripElement, setStripElement] = useState<HTMLDivElement | null>(null);
464 const labelsOverflow = useLabelsOverflow(stripElement);
465​
466 if (!hasActiveThread || !activeProject) return null;
467​
468 return (
469 <div
470 ref={setStripElement}
471 data-compact={labelsOverflow ? "" : undefined}
472 className="chat-composer-context-strip group/composer-context -mt-4 mx-auto flex w-[calc(100%-2.75rem)] max-w-[calc(48rem-2.75rem)] items-center gap-2 overflow-x-clip overflow-y-visible ps-1 pe-2 pt-5 pb-1"
473 >
474 {isMobile && showGitControls ? (
475 <MobileRunContextSelector
476 envLocked={envLocked}
477 envModeLocked={envModeLocked}
478 environmentId={environmentId}
479 availableEnvironments={availableEnvironments}
480 showEnvironmentPicker={showEnvironmentPicker}
481 showEnvironmentIndicator={showEnvironmentIndicator}
482 onEnvironmentChange={onEnvironmentChange}
483 effectiveEnvMode={effectiveEnvMode}
484 activeWorktreePath={activeWorktreePath}
485 onEnvModeChange={onEnvModeChange}
486 previousWorktreeLabel={previousWorktreeLabel}
487 onUsePreviousWorktree={onUsePreviousWorktree}
488 />
489 ) : (
490 <div className="flex min-w-0 flex-1 items-center gap-1">
491 {showEnvironmentIndicator && availableEnvironments && (
492 <>
493 <BranchToolbarEnvironmentSelector
494 envLocked={envLocked}
495 environmentId={environmentId}
496 availableEnvironments={availableEnvironments}
497 {...(showEnvironmentPicker && onEnvironmentChange ? { onEnvironmentChange } : {})}
498 />
499 {showGitControls ? (
500 <Separator
501 orientation="vertical"
502 className="mx-0.5 h-3.5!"
503 data-composer-context-control
504 />
505 ) : null}
506 </>
507 )}
508 {showGitControls ? (
509 <BranchToolbarEnvModeSelector
510 envLocked={envModeLocked}
511 effectiveEnvMode={effectiveEnvMode}
512 activeWorktreePath={activeWorktreePath}
513 onEnvModeChange={onEnvModeChange}
514 previousWorktreeLabel={previousWorktreeLabel}
515 onUsePreviousWorktree={onUsePreviousWorktree}
516 />
517 ) : null}
518 </div>
519 )}
520​
521 {showGitControls ? (
522 <BranchToolbarBranchSelector
523 className="min-w-0 flex-1 justify-end md:ml-auto md:flex-none"
524 environmentId={environmentId}
525 threadId={threadId}
526 {...(draftId ? { draftId } : {})}
527 envLocked={envLocked}
528 {...(effectiveEnvModeOverride ? { effectiveEnvModeOverride } : {})}
529 {...(activeThreadBranchOverride !== undefined ? { activeThreadBranchOverride } : {})}
530 {...(onActiveThreadBranchOverrideChange ? { onActiveThreadBranchOverrideChange } : {})}
531 startFromOrigin={startFromOrigin}
532 onStartFromOriginChange={onStartFromOriginChange}
533 {...(onCheckoutPullRequestRequest ? { onCheckoutPullRequestRequest } : {})}
534 {...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
535 />
536 ) : null}
537 </div>
538 );
539});