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 }}.`);
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: lineLabels[target.line] }}, position ${{ position: (findSidebarRowToken(next, key)?.index ?? 0) + 1 }} of ${{ count: next[target.line].length }}.`,
320 );
321 }
322 saveLayout(next);
323 };
324 const draggedToken = drag ? findSidebarRowToken(layout, drag.key)?.token : undefined;
325 const lineLabels: Record<SidebarRowLine, string> = {
326 top: gt({ context: "sidebar row line" })`Top`,
327 middle: gt({ context: "sidebar row line" })`Middle`,
328 bottom: gt({ context: "sidebar row line" })`Bottom`,
329 hidden: gt({ context: "sidebar row items that are not shown" })`Hidden`,
330 };
331
332 return (
333 <DndContext
334 sensors={sensors}
335 // Scrolling mid-drag would move everything away from the measured positions.
336 autoScroll={false}
337 accessibility={{
338 screenReaderInstructions: {
339 draggable: gt`Use the arrow keys to move this item: left and right within its line, up and down to another line.`,
340 },
341 announcements: {
342 onDragStart: ({ active }) =>
343 gt`Picked up ${{ item: label(tokenIdOf(layout, active.id)) }}.`,
344 onDragOver: () => undefined,
345 onDragMove: () => undefined,
346 onDragEnd: ({ active }) =>
347 dragRef.current?.target
348 ? gt`Dropped ${{ item: label(tokenIdOf(layout, active.id)) }}.`
349 : gt`Put ${{ item: label(tokenIdOf(layout, active.id)) }} back.`,
350 onDragCancel: ({ active }) =>
351 gt`Put ${{ item: label(tokenIdOf(layout, active.id)) }} back.`,
352 },
353 }}
354 onDragStart={handleDragStart}
355 onDragMove={handleDragMove}
356 onDragEnd={handleDragEnd}
357 onDragCancel={endDrag}
358 >
359 <div ref={rootRef} className="flex flex-col gap-5">
360 <div aria-live="polite" className="sr-only">
361 {announcement}
362 </div>
363 <section className="flex flex-col gap-2">
364 <PreviewSidebar layout={layout} />
365 </section>
366 <section className="flex flex-col gap-2">
367 <div className="flex items-center justify-between gap-2">
368 <span className="text-xs text-muted-foreground">
369 <T>Layout · drag items to move them</T>
370 </span>
371 <Button
372 type="button"
373 size="xs"
374 variant="ghost-muted"
375 onClick={() =>
376 saveLayout(
377 insertSidebarRowSpacer(layout, "bottom", Number.POSITIVE_INFINITY).layout,
378 )
379 }
380 >
381 <PlusIcon aria-hidden />
382 <T context="flexible empty space in a layout">Spacer</T>
383 </Button>
384 </div>
385 <div className="flex flex-col gap-1.5">
386 {LINES.map((line) => (
387 <Lane
388 key={line}
389 layout={layout}
390 line={line}
391 label={lineLabels[line]}
392 tokens={layout[line]}
393 draggingKey={drag?.key ?? null}
394 insertAt={drag?.target?.line === line ? drag.target.index : null}
395 refusesDrag={line === "hidden" && draggedToken?.id === "title"}
396 onKeyMove={moveWithKey}
397 />
398 ))}
399 </div>
400 </section>
401 <p className="-mt-3 text-muted-foreground text-xs">
402 <T>
403 A thread's status, such as Working or Done, shows in place of its time. With the time
404 hidden, the status stays at the end of the top line.
405 </T>
406 </p>
407 <RowHeightChoice layout={layout} />
408 </div>
409 {/* The dialog animates with a transform, which would offset a fixed overlay inside it.
410 Outside it, the overlay must let the release through, or the next click closes the dialog. */}
411 {createPortal(
412 <DragOverlay className="pointer-events-none" dropAnimation={null} zIndex={100}>
413 {draggedToken ? <ItemChip token={draggedToken} lifted /> : null}
414 </DragOverlay>,
415 document.body,
416 )}
417 </DndContext>
418 );
419}
420
421const tokenIdOf = (layout: SidebarRowLayout, key: string | number) =>
422 findSidebarRowToken(layout, String(key))?.token.id ?? "spacer";
423
424function Lane(props: {
425 layout: SidebarRowLayout;
426 line: SidebarRowLine;
427 label: string;
428 tokens: ReadonlyArray<SidebarRowToken>;
429 draggingKey: string | null;
430 insertAt: number | null;
431 refusesDrag: boolean;
432 onKeyMove: (key: string, event: ReactKeyboardEvent) => void;
433}) {
434 const hidden = props.line === "hidden";
435 // The insertion index skips the dragged item, matching how a move removes it first.
436 const nodes: ReactNode[] = [];
437 let position = 0;
438 const marker = <span key="insert" aria-hidden className={INSERTION_MARK_CLASS_NAME} />;
439 for (const token of props.tokens) {
440 if (props.insertAt === position && token.key !== props.draggingKey) nodes.push(marker);
441 if (token.key !== props.draggingKey) position++;
442 nodes.push(
443 <DraggableChip
444 key={token.key}
445 layout={props.layout}
446 token={token}
447 line={props.line}
448 dragging={token.key === props.draggingKey}
449 onKeyMove={props.onKeyMove}
450 />,
451 );
452 }
453 if (props.insertAt !== null && props.insertAt >= position) nodes.push(marker);
454 return (
455 <div
456 data-layout-line={props.line}
457 role="group"
458 aria-label={props.label}
459 className={cn(
460 "flex min-h-11 items-center gap-3 rounded-lg px-3 py-1.5",
461 hidden ? "border border-dashed border-border" : "bg-muted/50",
462 props.insertAt !== null && "bg-accent/50 ring-1 ring-ring/50 ring-inset",
463 props.refusesDrag && "opacity-50",
464 )}
465 >
466 <span className="w-14 shrink-0 text-xs text-muted-foreground">{props.label}</span>
467 <div className="flex min-w-0 flex-1 flex-wrap items-center gap-1.5">
468 {nodes}
469 {hidden && props.tokens.length === 0 && props.insertAt === null ? (
470 <span className="text-xs text-muted-foreground/70">
471 <T>Drop an item here to hide it.</T>
472 </span>
473 ) : null}
474 </div>
475 </div>
476 );
477}
478
479function DraggableChip(props: {
480 layout: SidebarRowLayout;
481 token: SidebarRowToken;
482 line: SidebarRowLine;
483 dragging: boolean;
484 onKeyMove: (key: string, event: ReactKeyboardEvent) => void;
485}) {
486 const gt = useGT();
487 const label = useItemLabel();
488 const { attributes, listeners, setNodeRef } = useDraggable({ id: props.token.key });
489 const name = label(props.token.id);
490 const chip = (
491 <span
492 ref={setNodeRef}
493 {...attributes}
494 {...listeners}
495 onKeyDown={(event) => props.onKeyMove(props.token.key, event)}
496 data-layout-key={props.token.key}
497 data-layout-item-line={props.line}
498 aria-label={gt`Move ${{ item: name }}`}
499 className={cn(
500 "cursor-grab touch-none rounded-md outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring active:cursor-grabbing",
501 props.token.id === "spacer" && "min-w-16 flex-1",
502 props.dragging && props.token.form === null && "opacity-40",
503 )}
504 >
505 <ItemChip token={props.token} joined={props.token.form !== null} />
506 </span>
507 );
508 if (props.token.id === "spacer") return chip;
509 const tooltip = (
510 <Tooltip>
511 <TooltipTrigger render={chip} />
512 <TooltipPopup side="top">{name}</TooltipPopup>
513 </Tooltip>
514 );
515 if (props.token.form === null) return tooltip;
516 return (
517 <span
518 className={cn(
519 "inline-flex h-7 items-center rounded-md border border-border bg-background pe-0.5",
520 props.dragging && "opacity-40",
521 )}
522 >
523 {tooltip}
524 <ItemFormMenu layout={props.layout} token={props.token} name={name} />
525 </span>
526 );
527}
528
529/** What each form is called, for the chip and its menu. */
530function useFormLabel() {
531 const gt = useGT();
532 return (form: SidebarRowItemForm) =>
533 form === "compact"
534 ? gt`Icon only`
535 : form === "wide"
536 ? gt`Icon and name`
537 : form === "truncate"
538 ? gt({ context: "thread title stays on one line" })`One line`
539 : gt({ context: "thread title may wrap" })`Wrap to two lines`;
540}
541
542/** Icon only keeps a name, such as a computer's, off the sidebar; hover still shows it. */
543function ItemFormMenu(props: { layout: SidebarRowLayout; token: SidebarRowToken; name: string }) {
544 const gt = useGT();
545 const formLabel = useFormLabel();
546 return (
547 <Menu>
548 <MenuTrigger
549 render={
550 <Button
551 type="button"
552 size="icon-xs"
553 variant="ghost-muted"
554 aria-label={gt`Show ${{ item: props.name }} as`}
555 />
556 }
557 >
558 <ChevronDownIcon aria-hidden />
559 </MenuTrigger>
560 <MenuPopup align="start">
561 <MenuGroup>
562 <MenuGroupLabel>{gt`Show ${{ item: props.name }} as`}</MenuGroupLabel>
563 <MenuRadioGroup
564 value={props.token.form}
565 onValueChange={(form: SidebarRowItemForm) =>
566 saveLayout(setSidebarRowTokenForm(props.layout, props.token.key, form))
567 }
568 >
569 {sidebarRowItemForms(props.token.id).map((form) => (
570 <MenuRadioItem key={form} value={form} closeOnClick>
571 <span className="flex items-center gap-3">
572 <span className="flex-1">{formLabel(form)}</span>
573 <span className="flex size-3.5 shrink-0">
574 <MenuRadioItemIndicator />
575 </span>
576 </span>
577 </MenuRadioItem>
578 ))}
579 </MenuRadioGroup>
580 </MenuGroup>
581 </MenuPopup>
582 </Menu>
583 );
584}
585
586/** A chip names its item; the preview above shows how the sidebar draws it. */
587function ItemChip(props: { token: SidebarRowToken; lifted?: boolean; joined?: boolean }) {
588 if (props.token.id === "spacer") {
589 return (
590 <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">
591 <T context="flexible empty space in a layout">space</T>
592 </span>
593 );
594 }
595 return (
596 <span
597 className={cn(
598 "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",
599 props.lifted && "shadow-md",
600 props.joined && "h-6 border-0 bg-transparent pe-0.5",
601 )}
602 >
603 <GripVerticalIcon aria-hidden className="size-3 shrink-0 text-muted-foreground/50" />
604 <ItemFace token={props.token} />
605 {props.lifted && props.token.form ? (
606 <ChevronDownIcon aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
607 ) : null}
608 </span>
609 );
610}
611
612const noop = () => {};
613const EMPTY_PROVIDER_ENTRIES = new Map<string, never>();
614
615// Mulberry32: one seed gives one mix, so a re-render keeps the threads it drew.
616function seededRandom(seed: number) {
617 let state = seed >>> 0;
618 return () => {
619 state = (state + 0x6d2b79f5) >>> 0;
620 let t = Math.imul(state ^ (state >>> 15), state | 1);
621 t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
622 return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
623 };
624}
625
626const PREVIEW_MIN_WIDTH = 13 * 16;
627
628function readSidebarWidth() {
629 try {
630 return resolveInitialThreadSidebarWidth(
631 getLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY, Schema.Finite),
632 );
633 } catch {
634 return resolveInitialThreadSidebarWidth(null);
635 }
636}
637
638/** Drags the preview's right edge like the sidebar's own resize handle; the column is centered,
639 * so it grows by twice the pointer's travel. Arrow keys step it, double-click resets it. */
640function PreviewWidthHandle(props: {
641 width: number;
642 onWidthChange: (width: number) => void;
643 onReset: () => void;
644}) {
645 const gt = useGT();
646 const dragRef = useRef<{ x: number; width: number } | null>(null);
647 // The column cannot outgrow the preview box, so neither can the width it is given.
648 const fit = (handle: HTMLElement, width: number) => {
649 const box = handle.parentElement?.parentElement;
650 const room = box ? box.clientWidth - 32 : Number.POSITIVE_INFINITY;
651 props.onWidthChange(Math.min(width, room));
652 };
653 return (
654 <div
655 role="separator"
656 aria-orientation="vertical"
657 aria-label={gt`Preview width`}
658 aria-valuenow={props.width}
659 tabIndex={0}
660 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"
661 onPointerDown={(event) => {
662 event.currentTarget.setPointerCapture(event.pointerId);
663 dragRef.current = { x: event.clientX, width: props.width };
664 }}
665 onPointerMove={(event) => {
666 const drag = dragRef.current;
667 if (drag) fit(event.currentTarget, drag.width + (event.clientX - drag.x) * 2);
668 }}
669 onPointerUp={() => {
670 dragRef.current = null;
671 }}
672 onPointerCancel={() => {
673 dragRef.current = null;
674 }}
675 onDoubleClick={props.onReset}
676 onKeyDown={(event) => {
677 if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;
678 event.preventDefault();
679 fit(event.currentTarget, props.width + (event.key === "ArrowRight" ? 16 : -16));
680 }}
681 />
682 );
683}
684
685/** Sample threads drawn by the sidebar's own row, so the preview cannot drift from the sidebar. */
686function PreviewSidebar(props: { layout: SidebarRowLayout }) {
687 const gt = useGT();
688 const m = useMessages();
689 const environmentId = usePrimaryEnvironmentId();
690 const environments = useEnvironmentIdentities();
691 const machines = useEnvironmentMachines();
692 const providerEntries = useAtomValue(sidebarProviderEntriesAtom);
693 const timestampFormat = useClientSettings((settings) => settings.timestampFormat);
694 const spansEnvironments = projectGroupsSpanEnvironments(useSidebarProjectGroups());
695 const [several, setSeveral] = useState<boolean | null>(null);
696 const [seed, setSeed] = useState<number | null>(null);
697 const [selectedId, setSelectedId] = useState<string | null>(null);
698 // Starts at the sidebar's own width, so the preview wraps and truncates where the sidebar does.
699 const [width, setWidth] = useState(readSidebarWidth);
700 const [now] = useState(() => Date.now());
701 if (environmentId === null) return null;
702 const entries = providerEntries.get(environmentId) ?? EMPTY_PROVIDER_ENTRIES;
703 const threads = previewThreads({
704 environmentId,
705 providerInstanceId: ProviderInstanceId.make(entries.keys().next().value ?? "codex"),
706 resolve: m,
707 now,
708 random: seed === null ? null : seededRandom(seed),
709 });
710 // With several machines, some sample threads run on a second one.
711 const showsEnvironments = several ?? spansEnvironments;
712 const { layout } = props;
713 const localLabel =
714 environments.find((environment) => environment.environmentId === environmentId)?.label ?? null;
715 return (
716 <>
717 <div className="flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground">
718 <span>
719 <T>Preview</T>
720 </span>
721 <span className="flex flex-wrap items-center gap-1">
722 {[false, true].map((value) => (
723 <Button
724 key={String(value)}
725 type="button"
726 size="xs"
727 variant={showsEnvironments === value ? "secondary" : "ghost-muted"}
728 aria-pressed={showsEnvironments === value}
729 onClick={() => setSeveral(value)}
730 >
731 {value ? gt`Multiple environments` : gt`One environment`}
732 </Button>
733 ))}
734 <Button
735 type="button"
736 size="xs"
737 variant="ghost-muted"
738 onClick={() => setSeed(Math.floor(Math.random() * 2 ** 32))}
739 >
740 <ShuffleIcon aria-hidden />
741 <T context="make a new random set of sample threads">Randomize</T>
742 </Button>
743 </span>
744 </div>
745 {/* The whole box scrolls, so the wheel works anywhere over the preview. */}
746 <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">
747 <div
748 className="relative h-fit max-w-full shrink-0 rounded-md bg-sidebar text-sidebar-foreground"
749 style={{ width }}
750 >
751 {/* Rows hover like the sidebar's, but a click only selects one: caught here before
752 any row control (Settle, Snooze, a pull request link) can act on a sample thread. */}
753 <ul
754 role="presentation"
755 className="flex flex-col p-1"
756 onClickCapture={(event) => {
757 event.preventDefault();
758 event.stopPropagation();
759 const row = (event.target as Element).closest<HTMLElement>("[data-thread-item]");
760 const id = row?.dataset.threadItem?.split(":").at(-1) ?? null;
761 setSelectedId((current) => (current === id ? null : id));
762 }}
763 onContextMenuCapture={(event) => {
764 event.preventDefault();
765 event.stopPropagation();
766 }}
767 onDoubleClickCapture={(event) => {
768 event.preventDefault();
769 event.stopPropagation();
770 }}
771 >
772 {threads.map((sample) => (
773 <SidebarThreadRow
774 key={sample.thread.id}
775 preview
776 thread={sample.thread}
777 variant="card"
778 layout={layout}
779 variantAction="settle"
780 settlementSupported
781 snoozeSupported
782 pinningSupported
783 isPinned={sample.pinned}
784 dropVerb={null}
785 dragOverPinned={false}
786 sweepAction={null}
787 snoozeWakeLabelText={null}
788 wokeAt={sample.wokeAt}
789 isActive={sample.thread.id === selectedId}
790 isRouteThread={false}
791 readOpensPullRequestsInRightPanel={() => false}
792 jumpLabel={null}
793 environmentLabel={
794 showsEnvironments && sample.remote
795 ? gt({ context: "sample computer name" })`Studio Mac`
796 : localLabel
797 }
798 environmentMachine={
799 showsEnvironments && sample.remote
800 ? "laptop"
801 : (machines.get(environmentId) ?? "server")
802 }
803 project={sample.project}
804 projectDisplayName={sample.project.title}
805 providerEntryByInstanceId={entries}
806 timestampFormat={timestampFormat}
807 onThreadClick={noop}
808 onThreadActivate={noop}
809 onStartRename={noop}
810 onRenameTitleChange={noop}
811 onCommitRename={noop}
812 onCancelRename={noop}
813 isRenaming={false}
814 renamingTitle=""
815 onContextMenu={noop}
816 onSettle={noop}
817 onActionSweepStart={noop}
818 onUnsettle={noop}
819 onSnooze={noop}
820 onUnsnooze={noop}
821 onUnpin={noop}
822 onAcknowledgeWoke={noop}
823 />
824 ))}
825 </ul>
826 <PreviewWidthHandle
827 width={width}
828 onWidthChange={(next) => setWidth(Math.max(PREVIEW_MIN_WIDTH, Math.round(next)))}
829 onReset={() => setWidth(readSidebarWidth())}
830 />
831 </div>
832 </div>
833 </>
834 );
835}
836
837const ITEM_ICONS: Record<Exclude<SidebarRowItemId, "spacer">, typeof TypeIcon> = {
838 title: TypeIcon,
839 projectIcon: SquareDashedIcon,
840 projectName: FolderIcon,
841 environment: LaptopIcon,
842 branch: GitBranchIcon,
843 terminals: TerminalIcon,
844 subagents: BotIcon,
845 pullRequest: PullRequestGlyph.pullRequest,
846 issues: IssueGlyph.issue,
847 agents: CpuIcon,
848 time: ClockIcon,
849};
850
851function ItemFace(props: { token: SidebarRowToken }) {
852 const label = useItemLabel();
853 const formLabel = useFormLabel();
854 if (props.token.id === "spacer") return null;
855 const Icon = ITEM_ICONS[props.token.id];
856 return (
857 <span className="flex min-w-0 items-center gap-1.5">
858 <Icon aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
859 <span className="min-w-0 truncate">{label(props.token.id)}</span>
860 {props.token.form ? (
861 <span className="shrink-0 text-muted-foreground/70">{formLabel(props.token.form)}</span>
862 ) : null}
863 </span>
864 );
865}
866
867/** Two sketched choices: rows that fold empty lines, or rows that all keep every line. */
868function RowHeightChoice(props: { layout: SidebarRowLayout }) {
869 const gt = useGT();
870 const fixed = props.layout.keepLines.length > 0;
871 const setFixed = (kept: boolean) =>
872 saveLayout(
873 setSidebarRowLineKept(setSidebarRowLineKept(props.layout, "middle", kept), "bottom", kept),
874 );
875 return (
876 <section className="flex flex-col gap-2">
877 <span id="sidebar-row-height-label" className="text-xs text-muted-foreground">
878 <T>Row height</T>
879 </span>
880 <RadioGroup
881 aria-labelledby="sidebar-row-height-label"
882 value={fixed ? "same" : "fit"}
883 onValueChange={(value) => setFixed(value === "same")}
884 className="grid grid-cols-1 sm:grid-cols-2"
885 >
886 {(["fit", "same"] as const).map((choice) => (
887 <label
888 key={choice}
889 className={cn(
890 "flex cursor-pointer items-center gap-3 rounded-lg border p-2.5 text-sm",
891 (choice === "same") === fixed ? "border-ring/60 bg-accent/40" : "border-border",
892 )}
893 >
894 <HeightSketch same={choice === "same"} />
895 <Radio value={choice} />
896 {choice === "same" ? gt`Same height` : gt`Fit each thread`}
897 </label>
898 ))}
899 </RadioGroup>
900 </section>
901 );
902}
903
904// Lines each sketched thread has: one full, one with only a title, one without a last line.
905const SKETCH_ROWS = [
906 { key: "full", lines: [true, true, true] },
907 { key: "title-only", lines: [false, true, false] },
908 { key: "no-last-line", lines: [true, true, false] },
909] as const;
910const SKETCH_LINES = ["project", "title", "details"] as const;
911const SKETCH_LINE_WIDTHS = ["w-3/5", "w-full", "w-4/5"] as const;
912
913function HeightSketch(props: { same: boolean }) {
914 // Fit each thread drops a thread's empty lines; Same height keeps them as blank space.
915 return (
916 <span
917 aria-hidden
918 className="flex w-24 shrink-0 flex-col gap-1 rounded-md bg-muted p-1.5 ring-1 ring-border ring-inset"
919 >
920 {SKETCH_ROWS.map(({ key, lines }) => (
921 <span
922 key={key}
923 className="flex flex-col gap-1 rounded-sm bg-background px-2 py-1.5 ring-1 ring-border/70"
924 >
925 {SKETCH_LINES.map((name, line) =>
926 lines[line] || props.same ? (
927 <span
928 key={name}
929 className={cn(
930 "h-1 rounded-full",
931 SKETCH_LINE_WIDTHS[line],
932 lines[line] && (line === 1 ? "bg-foreground/70" : "bg-muted-foreground/50"),
933 )}
934 />
935 ) : null,
936 )}
937 </span>
938 ))}
939 </span>
940 );
941}
942
943const INSERTION_MARK_CLASS_NAME =
944 // Negative margins cancel the lane's gap, so the mark does not push items aside.
945 "-mx-[4px] h-5 w-0.5 shrink-0 rounded-full bg-primary";
946
947type DropTarget = { line: SidebarRowLine; index: number };
948type Drag = { key: string; target: DropTarget | null };
949
950interface DragGeometry {
951 origin: { x: number; y: number };
952 lines: ReadonlyArray<{ line: SidebarRowLine; rect: DOMRect }>;
953 items: ReadonlyArray<{ key: string; line: SidebarRowLine; rect: DOMRect }>;
954}
955
956function measureGeometry(root: HTMLElement, activatorEvent: Event): DragGeometry {
957 const pointer = activatorEvent as PointerEvent;
958 return {
959 origin: { x: pointer.clientX ?? 0, y: pointer.clientY ?? 0 },
960 lines: [...root.querySelectorAll<HTMLElement>("[data-layout-line]")].map((element) => ({
961 line: element.dataset.layoutLine as SidebarRowLine,
962 rect: element.getBoundingClientRect(),
963 })),
964 items: [...root.querySelectorAll<HTMLElement>("[data-layout-key]")].map((element) => ({
965 key: element.dataset.layoutKey ?? "",
966 line: element.dataset.layoutItemLine as SidebarRowLine,
967 rect: element.getBoundingClientRect(),
968 })),
969 };
970}
971
972/** The lane under the pointer, and how many of its other items sit before the pointer. */
973function dropTargetAt(
974 geometry: DragGeometry,
975 key: string,
976 tokenId: SidebarRowItemId | undefined,
977 point: { x: number; y: number },
978): DropTarget | null {
979 const lane = geometry.lines.find(
980 ({ rect }) => point.y >= rect.top - 4 && point.y <= rect.bottom + 4,
981 );
982 if (!lane) return null;
983 if (lane.line === "hidden" && tokenId === "title") return null;
984 const index = geometry.items.filter(
985 (item) =>
986 item.line === lane.line &&
987 item.key !== key &&
988 (item.rect.bottom < point.y ||
989 (item.rect.top <= point.y && item.rect.left + item.rect.width / 2 < point.x)),
990 ).length;
991 return { line: lane.line, index };
992}