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