Open History to see the last commit
1import {
2 DndContext,
3 type DragMoveEvent,
4 type DragStartEvent,
5 DragOverlay,
6 useDraggable,
7 useSensor,
8 useSensors,
9} from "@dnd-kit/core";
10import { T, useGT, useMessages } from "gt-react";
11import {
12 BotIcon,
13 ChevronDownIcon,
14 ClockIcon,
15 FolderIcon,
16 GitBranchIcon,
17 GripVerticalIcon,
18 LaptopIcon,
19 PlusIcon,
20 ShuffleIcon,
21 CpuIcon,
22 SquareDashedIcon,
23 TerminalIcon,
24 TypeIcon,
25} from "lucide-react";
26import {
27 type KeyboardEvent as ReactKeyboardEvent,
28 type ReactNode,
29 type RefObject,
30 useLayoutEffect,
31 useRef,
32 useState,
33} from "react";
34import { createPortal } from "react-dom";
35import { useAtomValue } from "@effect/atom-react";
36import { ProviderInstanceId } from "@t3tools/contracts";
37
38import * as Schema from "effect/Schema";
39
40import { getLocalStorageItem } from "../../hooks/useLocalStorage";
41import { useSupportsMultiplePullRequests } from "../../hooks/useSupportsMultiplePullRequests";
42import { useSidebarProjectGroups } from "../../hooks/useSidebarProjectGroups";
43import {
44 resolveInitialThreadSidebarWidth,
45 THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
46} from "../threadSidebarWidth";
47import {
48 useEnvironmentIdentities,
49 useEnvironmentMachines,
50 usePrimaryEnvironmentId,
51} from "../../state/environments";
52import { projectGroupsSpanEnvironments } from "../../sidebarProjectGrouping";
53import { sidebarProviderEntriesAtom } from "../Sidebar";
54import { SidebarPointerSensor } from "../Sidebar.pointer";
55import { SidebarThreadRow } from "../sidebar/SidebarThreadRow";
56import { previewThreads } from "./sidebarRowPreviewThreads";
57
58import { cn } from "~/lib/utils";
59import { updateClientSettings, useClientSettings } from "../../hooks/useSettings";
60import { IssueGlyph } from "../issue/issuePresentation";
61import { PullRequestGlyph } from "../pullRequest/pullRequestIcons";
62import {
63 DEFAULT_SIDEBAR_ROW_LAYOUT,
64 SIDEBAR_ROW_ITEMS,
65 type SidebarRowItemForm,
66 type SidebarRowItemId,
67 type SidebarRowLayout,
68 type SidebarRowLine,
69 type SidebarRowToken,
70 findSidebarRowToken,
71 insertSidebarRowSpacer,
72 isDefaultSidebarRowLayout,
73 moveSidebarRowToken,
74 resolveSidebarRowLayout,
75 setSidebarRowLineKept,
76 setSidebarRowTokenForm,
77 sidebarRowItemForms,
78 storedSidebarRowLayout,
79} from "../sidebar/sidebarRowLayout";
80import { Button } from "../ui/button";
81import {
82 Menu,
83 MenuGroup,
84 MenuGroupLabel,
85 MenuPopup,
86 MenuRadioGroup,
87 MenuRadioItem,
88 MenuRadioItemIndicator,
89 MenuTrigger,
90} from "../ui/menu";
91import { Radio, RadioGroup } from "../ui/radio-group";
92import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
93import {
94 Dialog,
95 DialogClose,
96 DialogDescription,
97 DialogFooter,
98 DialogHeader,
99 DialogPanel,
100 DialogPopup,
101 DialogTitle,
102 DialogTrigger,
103} from "../ui/dialog";
104import { SettingResetButton, SettingsRow } from "./settingsLayout";
105import { useSearchableSetting } from "./settingsSearch";
106
107function saveLayout(layout: SidebarRowLayout) {
108 updateClientSettings({ sidebarRowLayout: storedSidebarRowLayout(layout) });
109}
110
111function useItemLabel() {
112 const m = useMessages();
113 return (id: SidebarRowItemId) =>
114 m(SIDEBAR_ROW_ITEMS.find((item) => item.id === id)?.label ?? SIDEBAR_ROW_ITEMS[0].label);
115}
116
117export function SidebarRowLayoutRow() {
118 const gt = useGT();
119 const searchableSetting = useSearchableSetting();
120 const isDefault = isDefaultSidebarRowLayout(
121 resolveSidebarRowLayout(useClientSettings((settings) => settings.sidebarRowLayout)),
122 );
123 const reset = () => saveLayout(DEFAULT_SIDEBAR_ROW_LAYOUT);
124 const doneRef = useRef<HTMLButtonElement>(null);
125 const sensorRef = useRef<SidebarPointerSensor | null>(null);
126 return (
127 <SettingsRow
128 {...searchableSetting("sidebar-row-layout")}
129 description={gt`Choose what sidebar thread cards show, and where.`}
130 resetAction={
131 isDefault ? null : (
132 <SettingResetButton
133 ariaLabel={gt`Reset sidebar thread rows to default`}
134 onClick={reset}
135 />
136 )
137 }
138 control={
139 <Dialog
140 onOpenChange={(open) => {
141 // The editor stays mounted during the exit transition.
142 if (!open) sensorRef.current?.cancel();
143 }}
144 >
145 <DialogTrigger
146 render={<Button type="button" variant="outline" size="sm" className="w-full sm:w-40" />}
147 >
148 <T>Customize</T>
149 </DialogTrigger>
150 <DialogPopup className="max-w-3xl">
151 <DialogHeader>
152 <DialogTitle>
153 <T>Sidebar thread rows</T>
154 </DialogTitle>
155 <DialogDescription>
156 <T>Choose what each thread row shows, and where.</T>
157 </DialogDescription>
158 </DialogHeader>
159 <DialogPanel>
160 <SidebarRowLayoutEditor sensorRef={sensorRef} />
161 </DialogPanel>
162 <DialogFooter variant="bare">
163 <Button
164 type="button"
165 variant="ghost"
166 disabled={isDefault}
167 onClick={() => {
168 reset();
169 // Reset disables itself, which would drop focus out of the dialog.
170 doneRef.current?.focus();
171 }}
172 >
173 <T>Reset</T>
174 </Button>
175 <DialogClose render={<Button ref={doneRef} type="button" />}>
176 <T>Done</T>
177 </DialogClose>
178 </DialogFooter>
179 </DialogPopup>
180 </Dialog>
181 }
182 />
183 );
184}
185
186const LINES = ["top", "middle", "bottom", "hidden"] as const;
187
188function SidebarRowLayoutEditor({
189 sensorRef,
190}: {
191 sensorRef: RefObject<SidebarPointerSensor | null>;
192}) {
193 const gt = useGT();
194 const label = useItemLabel();
195 const layout = resolveSidebarRowLayout(
196 useClientSettings((settings) => settings.sidebarRowLayout),
197 );
198 // Nothing moves while dragging: an insertion mark shows the drop spot, and the layout changes once
199 // on drop. Positions are measured when the drag starts so the mark cannot shift its own target.
200 const [drag, setDrag] = useState<Drag | null>(null);
201 const dragRef = useRef<Drag | null>(null);
202 const geometryRef = useRef<DragGeometry | null>(null);
203 const rootRef = useRef<HTMLDivElement>(null);
204 const focusKeyRef = useRef<string | null>(null);
205 const [announcement, setAnnouncement] = useState("");
206 // Dragging is pointer only: the dialog keeps arrow keys from reaching a keyboard drag, so arrows
207 // move a focused item directly instead.
208 const sensors = useSensors(
209 useSensor(SidebarPointerSensor, {
210 distance: 4,
211 onAttach: (sensor) => {
212 sensorRef.current = sensor;
213 },
214 onFinish: () => {
215 sensorRef.current = null;
216 },
217 }),
218 );
219 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Capture Escape before child popups and release the sensor when the editor unmounts.
220 useLayoutEffect(() => {
221 const cancelOnEscape = (event: KeyboardEvent) => {
222 const sensor = sensorRef.current;
223 if (event.key !== "Escape" || dragRef.current === null || sensor === null) return;
224 event.preventDefault();
225 event.stopPropagation();
226 sensor.cancel();
227 };
228 window.addEventListener("keydown", cancelOnEscape, true);
229 return () => {
230 window.removeEventListener("keydown", cancelOnEscape, true);
231 sensorRef.current?.cancel();
232 };
233 }, [sensorRef]);
234 const updateDrag = (next: Drag | null) => {
235 // Drop and Escape can arrive before React renders the latest drag state.
236 dragRef.current = next;
237 setDrag(next);
238 };
239
240 const handleDragStart = ({ active, activatorEvent }: DragStartEvent) => {
241 geometryRef.current = rootRef.current ? measureGeometry(rootRef.current, activatorEvent) : null;
242 updateDrag({ key: String(active.id), target: null });
243 };
244 const handleDragMove = ({ active, delta }: DragMoveEvent) => {
245 const geometry = geometryRef.current;
246 if (!geometry) return;
247 const key = String(active.id);
248 const target = dropTargetAt(geometry, key, findSidebarRowToken(layout, key)?.token.id, {
249 x: geometry.origin.x + delta.x,
250 y: geometry.origin.y + delta.y,
251 });
252 const current = dragRef.current;
253 if (
254 current?.key === key &&
255 current.target?.line === target?.line &&
256 current.target?.index === target?.index
257 )
258 return;
259 updateDrag({ key, target });
260 };
261 const endDrag = () => {
262 geometryRef.current = null;
263 updateDrag(null);
264 };
265 const handleDragEnd = () => {
266 const current = dragRef.current;
267 if (current?.target)
268 saveLayout(
269 moveSidebarRowToken(layout, current.key, current.target.line, current.target.index),
270 );
271 endDrag();
272 };
273 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- A moved item remounts in its new line; refocus it before workspace focus recovery scrolls to an older control.
274 useLayoutEffect(() => {
275 const key = focusKeyRef.current;
276 if (key === null) return;
277 const element = rootRef.current?.querySelector<HTMLElement>(
278 `[data-layout-key="${CSS.escape(key)}"]`,
279 );
280 if (!element) return;
281 focusKeyRef.current = null;
282 element.focus({ preventScroll: true });
283 });
284 const moveWithKey = (key: string, event: ReactKeyboardEvent) => {
285 const found = findSidebarRowToken(layout, key);
286 if (!found) return;
287 const lineIndex = LINES.indexOf(found.line);
288 const target: DropTarget | null =
289 event.key === "ArrowLeft"
290 ? found.index > 0
291 ? { line: found.line, index: found.index - 1 }
292 : null
293 : event.key === "ArrowRight"
294 ? found.index < layout[found.line].length - 1
295 ? { line: found.line, index: found.index + 1 }
296 : null
297 : event.key === "ArrowUp" || event.key === "ArrowDown"
298 ? (() => {
299 const line = LINES[lineIndex + (event.key === "ArrowUp" ? -1 : 1)];
300 if (!line || (line === "hidden" && found.token.id === "title")) return null;
301 return { line, index: Math.min(found.index, layout[line].length) };
302 })()
303 : null;
304 if (!["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) return;
305 event.preventDefault();
306 if (target === null) return;
307 const next = moveSidebarRowToken(layout, key, target.line, target.index);
308 const item = label(found.token.id);
309 if (findSidebarRowToken(next, key) === null) {
310 // A spacer moved to Hidden is removed, so focus goes to what now sits in its place.
311 const saved = resolveSidebarRowLayout(storedSidebarRowLayout(next))[found.line];
312 focusKeyRef.current = (saved[found.index] ?? saved[found.index - 1])?.key ?? null;
313 setAnnouncement(gt`Removed ${{ item }}.`);
314 } else {
315 // Saving renumbers spacers by position, so focus the token now at the moved one's place.
316 const moved = findSidebarRowToken(next, key)!;
317 focusKeyRef.current =
318 resolveSidebarRowLayout(storedSidebarRowLayout(next))[moved.line][moved.index]?.key ?? key;
319 setAnnouncement(
320 gt`${{ item }} moved to ${{ line: lineLabels[target.line] }}, position ${{ position: (findSidebarRowToken(next, key)?.index ?? 0) + 1 }} of ${{ count: next[target.line].length }}.`,
321 );
322 }
323 saveLayout(next);
324 };
325 const draggedToken = drag ? findSidebarRowToken(layout, drag.key)?.token : undefined;
326 const lineLabels: Record<SidebarRowLine, string> = {
327 top: gt({ context: "sidebar row line" })`Top`,
328 middle: gt({ context: "sidebar row line" })`Middle`,
329 bottom: gt({ context: "sidebar row line" })`Bottom`,
330 hidden: gt({ context: "sidebar row items that are not shown" })`Hidden`,
331 };
332
333 return (
334 <DndContext
335 sensors={sensors}
336 // Scrolling mid-drag would move everything away from the measured positions.
337 autoScroll={false}
338 accessibility={{
339 screenReaderInstructions: {
340 draggable: gt`Use the arrow keys to move this item: left and right within its line, up and down to another line.`,
341 },
342 announcements: {
343 onDragStart: ({ active }) =>
344 gt`Picked up ${{ item: label(tokenIdOf(layout, active.id)) }}.`,
345 onDragOver: () => undefined,
346 onDragMove: () => undefined,
347 onDragEnd: ({ active }) =>
348 dragRef.current?.target
349 ? gt`Dropped ${{ item: label(tokenIdOf(layout, active.id)) }}.`
350 : gt`Put ${{ item: label(tokenIdOf(layout, active.id)) }} back.`,
351 onDragCancel: ({ active }) =>
352 gt`Put ${{ item: label(tokenIdOf(layout, active.id)) }} back.`,
353 },
354 }}
355 onDragStart={handleDragStart}
356 onDragMove={handleDragMove}
357 onDragEnd={handleDragEnd}
358 onDragCancel={endDrag}
359 >
360 <div ref={rootRef} className="flex flex-col gap-5">
361 <div aria-live="polite" className="sr-only">
362 {announcement}
363 </div>
364 <section className="flex flex-col gap-2">
365 <PreviewSidebar layout={layout} />
366 </section>
367 <section className="flex flex-col gap-2">
368 <div className="flex items-center justify-between gap-2">
369 <span className="text-xs text-muted-foreground">
370 <T>Layout · drag items to move them</T>
371 </span>
372 <Button
373 type="button"
374 size="xs"
375 variant="ghost-muted"
376 onClick={() =>
377 saveLayout(
378 insertSidebarRowSpacer(layout, "bottom", Number.POSITIVE_INFINITY).layout,
379 )
380 }
381 >
382 <PlusIcon aria-hidden />
383 <T context="flexible empty space in a layout">Spacer</T>
384 </Button>
385 </div>
386 <div className="flex flex-col gap-1.5">
387 {LINES.map((line) => (
388 <Lane
389 key={line}
390 layout={layout}
391 line={line}
392 label={lineLabels[line]}
393 tokens={layout[line]}
394 draggingKey={drag?.key ?? null}
395 insertAt={drag?.target?.line === line ? drag.target.index : null}
396 refusesDrag={line === "hidden" && draggedToken?.id === "title"}
397 onKeyMove={moveWithKey}
398 />
399 ))}
400 </div>
401 </section>
402 <p className="-mt-3 text-muted-foreground text-xs">
403 <T>
404 A thread's status, such as Working or Done, shows in place of its time. With the time
405 hidden, the status stays at the end of the top line.
406 </T>
407 </p>
408 <RowHeightChoice layout={layout} />
409 </div>
410 {/* The dialog animates with a transform, which would offset a fixed overlay inside it.
411 Outside it, the overlay must let the release through, or the next click closes the dialog. */}
412 {createPortal(
413 <DragOverlay className="pointer-events-none" dropAnimation={null} zIndex={100}>
414 {draggedToken ? <ItemChip token={draggedToken} lifted /> : null}
415 </DragOverlay>,
416 document.body,
417 )}
418 </DndContext>
419 );
420}
421
422const tokenIdOf = (layout: SidebarRowLayout, key: string | number) =>
423 findSidebarRowToken(layout, String(key))?.token.id ?? "spacer";
424
425function Lane(props: {
426 layout: SidebarRowLayout;
427 line: SidebarRowLine;
428 label: string;
429 tokens: ReadonlyArray<SidebarRowToken>;
430 draggingKey: string | null;
431 insertAt: number | null;
432 refusesDrag: boolean;
433 onKeyMove: (key: string, event: ReactKeyboardEvent) => void;
434}) {
435 const hidden = props.line === "hidden";
436 // The insertion index skips the dragged item, matching how a move removes it first.
437 const nodes: ReactNode[] = [];
438 let position = 0;
439 const marker = <span key="insert" aria-hidden className={INSERTION_MARK_CLASS_NAME} />;
440 for (const token of props.tokens) {
441 if (props.insertAt === position && token.key !== props.draggingKey) nodes.push(marker);
442 if (token.key !== props.draggingKey) position++;
443 nodes.push(
444 <DraggableChip
445 key={token.key}
446 layout={props.layout}
447 token={token}
448 line={props.line}
449 dragging={token.key === props.draggingKey}
450 onKeyMove={props.onKeyMove}
451 />,
452 );
453 }
454 if (props.insertAt !== null && props.insertAt >= position) nodes.push(marker);
455 return (
456 <div
457 data-layout-line={props.line}
458 role="group"
459 aria-label={props.label}
460 className={cn(
461 "flex min-h-11 items-center gap-3 rounded-lg px-3 py-1.5",
462 hidden ? "border border-dashed border-border" : "bg-muted/50",
463 props.insertAt !== null && "bg-accent/50 ring-1 ring-ring/50 ring-inset",
464 props.refusesDrag && "opacity-50",
465 )}
466 >
467 <span className="w-14 shrink-0 text-xs text-muted-foreground">{props.label}</span>
468 <div className="flex min-w-0 flex-1 flex-wrap items-center gap-1.5">
469 {nodes}
470 {hidden && props.tokens.length === 0 && props.insertAt === null ? (
471 <span className="text-xs text-muted-foreground/70">
472 <T>Drop an item here to hide it.</T>
473 </span>
474 ) : null}
475 </div>
476 </div>
477 );
478}
479
480function DraggableChip(props: {
481 layout: SidebarRowLayout;
482 token: SidebarRowToken;
483 line: SidebarRowLine;
484 dragging: boolean;
485 onKeyMove: (key: string, event: ReactKeyboardEvent) => void;
486}) {
487 const gt = useGT();
488 const label = useItemLabel();
489 const { attributes, listeners, setNodeRef } = useDraggable({ id: props.token.key });
490 const name = label(props.token.id);
491 const chip = (
492 <span
493 ref={setNodeRef}
494 {...attributes}
495 {...listeners}
496 onKeyDown={(event) => props.onKeyMove(props.token.key, event)}
497 data-layout-key={props.token.key}
498 data-layout-item-line={props.line}
499 aria-label={gt`Move ${{ item: name }}`}
500 className={cn(
501 "cursor-grab touch-none rounded-md outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring active:cursor-grabbing",
502 props.token.id === "spacer" && "min-w-16 flex-1",
503 props.dragging && props.token.form === null && "opacity-40",
504 )}
505 >
506 <ItemChip token={props.token} joined={props.token.form !== null} />
507 </span>
508 );
509 if (props.token.id === "spacer") return chip;
510 const tooltip = (
511 <Tooltip>
512 <TooltipTrigger render={chip} />
513 <TooltipPopup side="top">{name}</TooltipPopup>
514 </Tooltip>
515 );
516 if (props.token.form === null) return tooltip;
517 return (
518 <span
519 className={cn(
520 "inline-flex h-7 items-center rounded-md border border-border bg-background pe-0.5",
521 props.dragging && "opacity-40",
522 )}
523 >
524 {tooltip}
525 <ItemFormMenu layout={props.layout} token={props.token} name={name} />
526 </span>
527 );
528}
529
530/** What each form is called, for the chip and its menu. */
531function useFormLabel() {
532 const gt = useGT();
533 return (form: SidebarRowItemForm) =>
534 form === "compact"
535 ? gt`Icon only`
536 : form === "wide"
537 ? gt`Icon and name`
538 : form === "truncate"
539 ? gt({ context: "thread title stays on one line" })`One line`
540 : gt({ context: "thread title may wrap" })`Wrap to two lines`;
541}
542
543/** Icon only keeps a name, such as a computer's, off the sidebar; hover still shows it. */
544function ItemFormMenu(props: { layout: SidebarRowLayout; token: SidebarRowToken; name: string }) {
545 const gt = useGT();
546 const formLabel = useFormLabel();
547 return (
548 <Menu>
549 <MenuTrigger
550 render={
551 <Button
552 type="button"
553 size="icon-xs"
554 variant="ghost-muted"
555 aria-label={gt`Show ${{ item: props.name }} as`}
556 />
557 }
558 >
559 <ChevronDownIcon aria-hidden />
560 </MenuTrigger>
561 <MenuPopup align="start">
562 <MenuGroup>
563 <MenuGroupLabel>{gt`Show ${{ item: props.name }} as`}</MenuGroupLabel>
564 <MenuRadioGroup
565 value={props.token.form}
566 onValueChange={(form: SidebarRowItemForm) =>
567 saveLayout(setSidebarRowTokenForm(props.layout, props.token.key, form))
568 }
569 >
570 {sidebarRowItemForms(props.token.id).map((form) => (
571 <MenuRadioItem key={form} value={form} closeOnClick>
572 <span className="flex items-center gap-3">
573 <span className="flex-1">{formLabel(form)}</span>
574 <span className="flex size-3.5 shrink-0">
575 <MenuRadioItemIndicator />
576 </span>
577 </span>
578 </MenuRadioItem>
579 ))}
580 </MenuRadioGroup>
581 </MenuGroup>
582 </MenuPopup>
583 </Menu>
584 );
585}
586
587/** A chip names its item; the preview above shows how the sidebar draws it. */
588function ItemChip(props: { token: SidebarRowToken; lifted?: boolean; joined?: boolean }) {
589 if (props.token.id === "spacer") {
590 return (
591 <span className="flex h-7 w-full items-center justify-center rounded-md border border-dashed border-muted-foreground/35 text-xs text-muted-foreground/60">
592 <T context="flexible empty space in a layout">space</T>
593 </span>
594 );
595 }
596 return (
597 <span
598 className={cn(
599 "inline-flex h-7 max-w-56 items-center gap-1.5 rounded-md border border-border bg-background ps-1 pe-2 text-xs",
600 props.lifted && "shadow-md",
601 props.joined && "h-6 border-0 bg-transparent pe-0.5",
602 )}
603 >
604 <GripVerticalIcon aria-hidden className="size-3 shrink-0 text-muted-foreground/50" />
605 <ItemFace token={props.token} />
606 {props.lifted && props.token.form ? (
607 <ChevronDownIcon aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
608 ) : null}
609 </span>
610 );
611}
612
613const noop = () => {};
614const EMPTY_PROVIDER_ENTRIES = new Map<string, never>();
615
616// Mulberry32: one seed gives one mix, so a re-render keeps the threads it drew.
617function seededRandom(seed: number) {
618 let state = seed >>> 0;
619 return () => {
620 state = (state + 0x6d2b79f5) >>> 0;
621 let t = Math.imul(state ^ (state >>> 15), state | 1);
622 t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
623 return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
624 };
625}
626
627const PREVIEW_MIN_WIDTH = 13 * 16;
628
629function readSidebarWidth() {
630 try {
631 return resolveInitialThreadSidebarWidth(
632 getLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY, Schema.Finite),
633 );
634 } catch {
635 return resolveInitialThreadSidebarWidth(null);
636 }
637}
638
639/** Drags the preview's right edge like the sidebar's own resize handle; the column is centered,
640 * so it grows by twice the pointer's travel. Arrow keys step it, double-click resets it. */
641function PreviewWidthHandle(props: {
642 width: number;
643 onWidthChange: (width: number) => void;
644 onReset: () => void;
645}) {
646 const gt = useGT();
647 const dragRef = useRef<{ x: number; width: number } | null>(null);
648 // The column cannot outgrow the preview box, so neither can the width it is given.
649 const fit = (handle: HTMLElement, width: number) => {
650 const box = handle.parentElement?.parentElement;
651 const room = box ? box.clientWidth - 32 : Number.POSITIVE_INFINITY;
652 props.onWidthChange(Math.min(width, room));
653 };
654 return (
655 <div
656 role="separator"
657 aria-orientation="vertical"
658 aria-label={gt`Preview width`}
659 aria-valuenow={props.width}
660 tabIndex={0}
661 className="absolute inset-y-0 -end-2 w-3 cursor-col-resize touch-none rounded-sm outline-none after:absolute after:inset-y-2 after:start-1/2 after:w-0.5 after:-translate-x-1/2 after:rounded-full after:bg-border hover:after:bg-primary/60 focus-visible:after:bg-primary"
662 onPointerDown={(event) => {
663 event.currentTarget.setPointerCapture(event.pointerId);
664 dragRef.current = { x: event.clientX, width: props.width };
665 }}
666 onPointerMove={(event) => {
667 const drag = dragRef.current;
668 if (drag) fit(event.currentTarget, drag.width + (event.clientX - drag.x) * 2);
669 }}
670 onPointerUp={() => {
671 dragRef.current = null;
672 }}
673 onPointerCancel={() => {
674 dragRef.current = null;
675 }}
676 onDoubleClick={props.onReset}
677 onKeyDown={(event) => {
678 if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;
679 event.preventDefault();
680 fit(event.currentTarget, props.width + (event.key === "ArrowRight" ? 16 : -16));
681 }}
682 />
683 );
684}
685
686/** Sample threads drawn by the sidebar's own row, so the preview cannot drift from the sidebar. */
687function PreviewSidebar(props: { layout: SidebarRowLayout }) {
688 const gt = useGT();
689 const m = useMessages();
690 const environmentId = usePrimaryEnvironmentId();
691 const multiplePullRequestsSupported = useSupportsMultiplePullRequests(environmentId);
692 const environments = useEnvironmentIdentities();
693 const machines = useEnvironmentMachines();
694 const providerEntries = useAtomValue(sidebarProviderEntriesAtom);
695 const timestampFormat = useClientSettings((settings) => settings.timestampFormat);
696 const spansEnvironments = projectGroupsSpanEnvironments(useSidebarProjectGroups());
697 const [several, setSeveral] = useState<boolean | null>(null);
698 const [seed, setSeed] = useState<number | null>(null);
699 const [selectedId, setSelectedId] = useState<string | null>(null);
700 // Starts at the sidebar's own width, so the preview wraps and truncates where the sidebar does.
701 const [width, setWidth] = useState(readSidebarWidth);
702 const [now] = useState(() => Date.now());
703 if (environmentId === null) return null;
704 const entries = providerEntries.get(environmentId) ?? EMPTY_PROVIDER_ENTRIES;
705 const threads = previewThreads({
706 environmentId,
707 providerInstanceId: ProviderInstanceId.make(entries.keys().next().value ?? "codex"),
708 resolve: m,
709 now,
710 random: seed === null ? null : seededRandom(seed),
711 });
712 // With several machines, some sample threads run on a second one.
713 const showsEnvironments = several ?? spansEnvironments;
714 const { layout } = props;
715 const localLabel =
716 environments.find((environment) => environment.environmentId === environmentId)?.label ?? null;
717 return (
718 <>
719 <div className="flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground">
720 <span>
721 <T>Preview</T>
722 </span>
723 <span className="flex flex-wrap items-center gap-1">
724 {[false, true].map((value) => (
725 <Button
726 key={String(value)}
727 type="button"
728 size="xs"
729 variant={showsEnvironments === value ? "secondary" : "ghost-muted"}
730 aria-pressed={showsEnvironments === value}
731 onClick={() => setSeveral(value)}
732 >
733 {value ? gt`Multiple environments` : gt`One environment`}
734 </Button>
735 ))}
736 <Button
737 type="button"
738 size="xs"
739 variant="ghost-muted"
740 onClick={() => setSeed(Math.floor(Math.random() * 2 ** 32))}
741 >
742 <ShuffleIcon aria-hidden />
743 <T context="make a new random set of sample threads">Randomize</T>
744 </Button>
745 </span>
746 </div>
747 {/* The whole box scrolls, so the wheel works anywhere over the preview. */}
748 <div className="flex max-h-96 justify-center overflow-y-auto overscroll-contain rounded-lg border border-border/60 bg-muted/60 px-4 py-3 [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
749 <div
750 className="relative h-fit max-w-full shrink-0 rounded-md bg-sidebar text-sidebar-foreground"
751 style={{ width }}
752 >
753 {/* Rows hover like the sidebar's, but a click only selects one: caught here before
754 any row control (Settle, Snooze, a pull request link) can act on a sample thread. */}
755 <ul
756 role="presentation"
757 className="flex flex-col p-1"
758 onClickCapture={(event) => {
759 event.preventDefault();
760 event.stopPropagation();
761 const row = (event.target as Element).closest<HTMLElement>("[data-thread-item]");
762 const id = row?.dataset.threadItem?.split(":").at(-1) ?? null;
763 setSelectedId((current) => (current === id ? null : id));
764 }}
765 onContextMenuCapture={(event) => {
766 event.preventDefault();
767 event.stopPropagation();
768 }}
769 onDoubleClickCapture={(event) => {
770 event.preventDefault();
771 event.stopPropagation();
772 }}
773 >
774 {threads.map((sample) => (
775 <SidebarThreadRow
776 key={sample.thread.id}
777 preview
778 thread={sample.thread}
779 variant="card"
780 layout={layout}
781 variantAction="settle"
782 settlementSupported
783 snoozeSupported
784 pinningSupported
785 multiplePullRequestsSupported={multiplePullRequestsSupported}
786 isPinned={sample.pinned}
787 dropVerb={null}
788 dragOverPinned={false}
789 sweepAction={null}
790 snoozeWakeLabelText={null}
791 wokeAt={sample.wokeAt}
792 isActive={sample.thread.id === selectedId}
793 isRouteThread={false}
794 readOpensPullRequestsInRightPanel={() => false}
795 jumpLabel={null}
796 environmentLabel={
797 showsEnvironments && sample.remote
798 ? gt({ context: "sample computer name" })`Studio Mac`
799 : localLabel
800 }
801 environmentMachine={
802 showsEnvironments && sample.remote
803 ? "laptop"
804 : (machines.get(environmentId) ?? "server")
805 }
806 project={sample.project}
807 projectDisplayName={sample.project.title}
808 providerEntryByInstanceId={entries}
809 timestampFormat={timestampFormat}
810 onThreadClick={noop}
811 onThreadActivate={noop}
812 onStartRename={noop}
813 onRenameTitleChange={noop}
814 onCommitRename={noop}
815 onCancelRename={noop}
816 isRenaming={false}
817 renamingTitle=""
818 onContextMenu={noop}
819 onSettle={noop}
820 onActionSweepStart={noop}
821 onUnsettle={noop}
822 onSnooze={noop}
823 onUnsnooze={noop}
824 onUnpin={noop}
825 onAcknowledgeWoke={noop}
826 />
827 ))}
828 </ul>
829 <PreviewWidthHandle
830 width={width}
831 onWidthChange={(next) => setWidth(Math.max(PREVIEW_MIN_WIDTH, Math.round(next)))}
832 onReset={() => setWidth(readSidebarWidth())}
833 />
834 </div>
835 </div>
836 </>
837 );
838}
839
840const ITEM_ICONS: Record<Exclude<SidebarRowItemId, "spacer">, typeof TypeIcon> = {
841 title: TypeIcon,
842 projectIcon: SquareDashedIcon,
843 projectName: FolderIcon,
844 environment: LaptopIcon,
845 branch: GitBranchIcon,
846 terminals: TerminalIcon,
847 subagents: BotIcon,
848 pullRequest: PullRequestGlyph.pullRequest,
849 issues: IssueGlyph.issue,
850 agents: CpuIcon,
851 time: ClockIcon,
852};
853
854function ItemFace(props: { token: SidebarRowToken }) {
855 const label = useItemLabel();
856 const formLabel = useFormLabel();
857 if (props.token.id === "spacer") return null;
858 const Icon = ITEM_ICONS[props.token.id];
859 return (
860 <span className="flex min-w-0 items-center gap-1.5">
861 <Icon aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
862 <span className="min-w-0 truncate">{label(props.token.id)}</span>
863 {props.token.form ? (
864 <span className="shrink-0 text-muted-foreground/70">{formLabel(props.token.form)}</span>
865 ) : null}
866 </span>
867 );
868}
869
870/** Two sketched choices: rows that fold empty lines, or rows that all keep every line. */
871function RowHeightChoice(props: { layout: SidebarRowLayout }) {
872 const gt = useGT();
873 const fixed = props.layout.keepLines.length > 0;
874 const setFixed = (kept: boolean) =>
875 saveLayout(
876 setSidebarRowLineKept(setSidebarRowLineKept(props.layout, "middle", kept), "bottom", kept),
877 );
878 return (
879 <section className="flex flex-col gap-2">
880 <span id="sidebar-row-height-label" className="text-xs text-muted-foreground">
881 <T>Row height</T>
882 </span>
883 <RadioGroup
884 aria-labelledby="sidebar-row-height-label"
885 value={fixed ? "same" : "fit"}
886 onValueChange={(value) => setFixed(value === "same")}
887 className="grid grid-cols-1 sm:grid-cols-2"
888 >
889 {(["fit", "same"] as const).map((choice) => (
890 <label
891 key={choice}
892 className={cn(
893 "flex cursor-pointer items-center gap-3 rounded-lg border p-2.5 text-sm",
894 (choice === "same") === fixed ? "border-ring/60 bg-accent/40" : "border-border",
895 )}
896 >
897 <HeightSketch same={choice === "same"} />
898 <Radio value={choice} />
899 {choice === "same" ? gt`Same height` : gt`Fit each thread`}
900 </label>
901 ))}
902 </RadioGroup>
903 </section>
904 );
905}
906
907// Lines each sketched thread has: one full, one with only a title, one without a last line.
908const SKETCH_ROWS = [
909 { key: "full", lines: [true, true, true] },
910 { key: "title-only", lines: [false, true, false] },
911 { key: "no-last-line", lines: [true, true, false] },
912] as const;
913const SKETCH_LINES = ["project", "title", "details"] as const;
914const SKETCH_LINE_WIDTHS = ["w-3/5", "w-full", "w-4/5"] as const;
915
916function HeightSketch(props: { same: boolean }) {
917 // Fit each thread drops a thread's empty lines; Same height keeps them as blank space.
918 return (
919 <span
920 aria-hidden
921 className="flex w-24 shrink-0 flex-col gap-1 rounded-md bg-muted p-1.5 ring-1 ring-border ring-inset"
922 >
923 {SKETCH_ROWS.map(({ key, lines }) => (
924 <span
925 key={key}
926 className="flex flex-col gap-1 rounded-sm bg-background px-2 py-1.5 ring-1 ring-border/70"
927 >
928 {SKETCH_LINES.map((name, line) =>
929 lines[line] || props.same ? (
930 <span
931 key={name}
932 className={cn(
933 "h-1 rounded-full",
934 SKETCH_LINE_WIDTHS[line],
935 lines[line] && (line === 1 ? "bg-foreground/70" : "bg-muted-foreground/50"),
936 )}
937 />
938 ) : null,
939 )}
940 </span>
941 ))}
942 </span>
943 );
944}
945
946const INSERTION_MARK_CLASS_NAME =
947 // Negative margins cancel the lane's gap, so the mark does not push items aside.
948 "-mx-[4px] h-5 w-0.5 shrink-0 rounded-full bg-primary";
949
950type DropTarget = { line: SidebarRowLine; index: number };
951type Drag = { key: string; target: DropTarget | null };
952
953interface DragGeometry {
954 origin: { x: number; y: number };
955 lines: ReadonlyArray<{ line: SidebarRowLine; rect: DOMRect }>;
956 items: ReadonlyArray<{ key: string; line: SidebarRowLine; rect: DOMRect }>;
957}
958
959function measureGeometry(root: HTMLElement, activatorEvent: Event): DragGeometry {
960 const pointer = activatorEvent as PointerEvent;
961 return {
962 origin: { x: pointer.clientX ?? 0, y: pointer.clientY ?? 0 },
963 lines: [...root.querySelectorAll<HTMLElement>("[data-layout-line]")].map((element) => ({
964 line: element.dataset.layoutLine as SidebarRowLine,
965 rect: element.getBoundingClientRect(),
966 })),
967 items: [...root.querySelectorAll<HTMLElement>("[data-layout-key]")].map((element) => ({
968 key: element.dataset.layoutKey ?? "",
969 line: element.dataset.layoutItemLine as SidebarRowLine,
970 rect: element.getBoundingClientRect(),
971 })),
972 };
973}
974
975/** The lane under the pointer, and how many of its other items sit before the pointer. */
976function dropTargetAt(
977 geometry: DragGeometry,
978 key: string,
979 tokenId: SidebarRowItemId | undefined,
980 point: { x: number; y: number },
981): DropTarget | null {
982 const lane = geometry.lines.find(
983 ({ rect }) => point.y >= rect.top - 4 && point.y <= rect.bottom + 4,
984 );
985 if (!lane) return null;
986 if (lane.line === "hidden" && tokenId === "title") return null;
987 const index = geometry.items.filter(
988 (item) =>
989 item.line === lane.line &&
990 item.key !== key &&
991 (item.rect.bottom < point.y ||
992 (item.rect.top <= point.y && item.rect.left + item.rect.width / 2 < point.x)),
993 ).length;
994 return { line: lane.line, index };
995}