Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(agentic-ide): editor groups side by side and stacked, with tabs that drag between them (#564)

Ruben Lütke30e3cb272d97
diff --git a/docs/code-editor.md b/docs/code-editor.md
index 1f37a33285..b0d0961419 100644
--- a/docs/code-editor.md
+++ b/docs/code-editor.md
@@ -16,7 +16,7 @@ terminals back without closing a file.
| Select several | **Ctrl/Cmd+click** adds a row, **Shift+click** selects a range; delete, cut, copy and drag act on the whole selection |
| Move, copy | Drag rows onto a folder (or the empty space for the root), or **Ctrl+X / Ctrl+C** then **Ctrl+V** on the target. Pasting into the same folder makes a "copy" |
| Right-click a file or folder | The menu opens at the pointer and acts on that row: new file or folder, open in the editor or on this computer, show it in the system file manager (**Shift+Alt+R**), open a terminal in that folder, find in folder (**Shift+Alt+F**), cut, copy, paste, copy path (**Shift+Alt+C**), copy relative path (**Ctrl+K Ctrl+Shift+C**), rename, delete. Right-click the empty space for the workspace root |
-| Two files side by side | Right-click a file and choose **Open to the side** (or **Ctrl+Enter** on it in the Folder tab), or right-click a tab. The file opens in a second editor on the right; drag the divider to resize, double-click it for equal halves. Files you open next go to the editor you last clicked in, and **Ctrl+S**, **Ctrl+Tab** and the status bar follow it. **Ctrl+W** in the second editor, or its close button, goes back to one editor and keeps the tab |
+| Editor groups side by side and stacked | Right-click a file and choose **Open to the side** (or **Ctrl+Enter** on it in the Folder tab): it opens in the group to the right of the one you are in, or in a new group when there is none. The split button at the right of a tab bar, and **Split right** in a tab's menu, show that tab's file again in a new group beside it. Every group has its own tabs, breadcrumbs and file actions. Drag a divider to resize two neighbours (double-click: equal sizes). Tabs drag: along a tab bar to reorder them, onto another group's tab bar or the middle of its text to move them there, and onto the left, right, top or bottom of a group's text to open a new group on that side, so the tabs of one group can be pulled apart into columns, rows, or both (one file on top, two side by side below it). While a tab is dragged, each group outlines where it can be dropped and highlights the side it would take. The group you last clicked in has the keyboard: files you open next go to it, and **Ctrl+S**, **Ctrl+W**, **Ctrl+Tab** and the status bar follow it. Closing a group's last tab closes the group. Reopening the app brings the tabs back in one group |
| Compare two files | Right-click one file and choose **Select for compare**, then right-click another and choose **Compare with …**: the two open side by side, the second one editable |
| Search in all files | **Ctrl+Shift+F** opens the **Search** tab: match case, whole word, regular expressions, include/exclude globs, and **Replace all** (a second click confirms; files with unsaved changes are left out) |
| See what changed | Coloured marks in the gutter (added, modified, deleted lines against the last commit), the **Changes** tab, or **Show changes**: the file against the last commit, editable on the right |
diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/CodeEditorStage.tsx b/jarvis/ui/web/frontend/src/components/agentic/editor/CodeEditorStage.tsx
index a7eb8a3449..2c53132fe3 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/editor/CodeEditorStage.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/CodeEditorStage.tsx
@@ -1,4 +1,4 @@
-import { Suspense, lazy, useEffect, useMemo, useRef, useState, type PointerEvent as ReactPointerEvent, type ReactNode } from "react";
+import { Fragment, Suspense, lazy, useEffect, useMemo, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent, type ReactNode } from "react";
import { useShallow } from "zustand/react/shallow";
import {
AlertTriangle,
@@ -22,7 +22,7 @@ import { attachToTerminal, openTerminalTarget } from "@/lib/agenticIdeApi";
import { cn } from "@/lib/utils";
import { useEventStore } from "@/store/events";
import { revealInExplorer } from "@/store/ideExplorer";
-import { tabsOf, useCodeEditorStore, type EditorTab } from "@/store/codeEditor";
+import { groupsOf, layoutFor, tabsOf, useCodeEditorStore, type EditorGroup, type EditorLayout, type EditorTab } from "@/store/codeEditor";
import { FileTypeIcon } from "@/components/agentic/sidePanel/explorer/FileTypeIcon";
import { absoluteWorkspacePath } from "@/components/agentic/sidePanel/explorer/explorerApi";
import { ThreadMenuHeading, ThreadMenuItem, ThreadMenuSeparator, ThreadPopover } from "@/components/agentic/threads/ThreadPopover";
@@ -40,11 +40,45 @@ const EditorSurface = lazy(() => import("./EditorSurface"));
const DISK_POLL_MS = 3000;
const DISK_JITTER_MS = 1500;
-/** How far the divider between two editors may be dragged, as a share of the width. */
-const SPLIT_MIN = 0.2;
-const SPLIT_MAX = 0.8;
+/** How far the divider between two groups may be dragged, as a share of their joint width. */
+const SPLIT_MIN = 0.15;
+const SPLIT_MAX = 0.85;
const clampSplit = (ratio: number) => Math.min(SPLIT_MAX, Math.max(SPLIT_MIN, ratio));
+/** A tab being dragged: within its tab bar, to another group, or out into a new one. */
+const TAB_DRAG_TYPE = "application/x-jarvis-editor-tab";
+
+type DropZone = "left" | "right" | "top" | "bottom" | "center";
+
+/** The part of a group's text area a dropped tab would take. */
+const ZONE_BOX: Record<DropZone, CSSProperties> = {
+ left: { left: 8, right: "50%", top: 8, bottom: 8 },
+ right: { left: "50%", right: 8, top: 8, bottom: 8 },
+ top: { left: 8, right: 8, top: 8, bottom: "50%" },
+ bottom: { left: 8, right: 8, top: "50%", bottom: 8 },
+ center: { left: 8, right: 8, top: 8, bottom: 8 },
+};
+
+/** A stable name for a part of the layout, to remember its size under. */
+const nodeKey = (node: EditorLayout): string =>
+ typeof node === "number" ? `g${node}` : `${node.dir}(${node.children.map(nodeKey).join(",")})`;
+
+/** The group in the top right corner, which carries the "Terminals" button. */
+const cornerOf = (node: EditorLayout): number =>
+ typeof node === "number" ? node : cornerOf(node.dir === "row" ? node.children[node.children.length - 1] : node.children[0]);
+/** Where the dragged tab would land: a spot in a tab bar, or a zone of a group's text area. */
+type DropHint = { group: number; before: number } | { group: number; zone: DropZone };
+
+/** The index of the tab a pointer at `x` would insert in front of; the tab count = after the last. */
+function insertionIndex(bar: HTMLElement, x: number): number {
+ const tabs = bar.querySelectorAll<HTMLElement>('[data-testid="code-editor-tab"]');
+ for (let index = 0; index < tabs.length; index += 1) {
+ const rect = tabs[index].getBoundingClientRect();
+ if (x < rect.left + rect.width / 2) return index;
+ }
+ return tabs.length;
+}
+
const baseName = (path: string) => path.split("/").pop() ?? path;
interface PendingClose {
@@ -61,6 +95,12 @@ function copyText(text: string): void {
/**
* The code editor, laid over the terminal grid of the Agentic IDE.
*
+ * It shows one or more editor groups, side by side or above each other. Each
+ * group has its own tab bar, breadcrumbs and text; "Open to the side" adds
+ * one, a dragged tab makes one where it is dropped, and closing a group's last
+ * tab removes it. The group last clicked in has the
+ * keyboard: opened files, shortcuts and the status bar go to it.
+ *
* Files open here from the side panel's Folder and Changes tabs, from a
* Ctrl+click on a path in a terminal, and from Go to File (Ctrl+P). The
* terminals stay mounted underneath; "Terminals" in the tab bar brings them
@@ -79,18 +119,21 @@ export function CodeEditorStage({
const stage = useRef<HTMLDivElement>(null);
const tabs = useCodeEditorStore(useShallow((state) => tabsOf(state, workspaceId)));
const activeKey = useCodeEditorStore((state) => (workspaceId ? (state.active[workspaceId] ?? null) : null));
- const sideKey = useCodeEditorStore((state) => (workspaceId ? (state.side[workspaceId] ?? null) : null));
- const sideHasKeyboard = useCodeEditorStore((state) => state.sideFocused);
+ const storedLayout = useCodeEditorStore((state) => (workspaceId ? state.layout[workspaceId] : undefined));
+ const groupActive = useCodeEditorStore((state) => (workspaceId ? state.groupActive[workspaceId] : undefined));
+ const focusedGroupId = useCodeEditorStore((state) => (workspaceId ? state.focusedGroup[workspaceId] : undefined));
const visible = useCodeEditorStore((state) => state.visible);
const quickOpen = useCodeEditorStore((state) => state.quickOpen);
const files = useCodeEditorStore((state) => state.files);
const diffBases = useCodeEditorStore((state) => state.diffBases);
const [pending, setPending] = useState<PendingClose | null>(null);
const [menu, setMenu] = useState<EditorTab | null>(null);
- // The first editor's share of the width while two are open.
- const [split, setSplit] = useState(0.5);
- const splitHost = useRef<HTMLDivElement>(null);
+ // Each part of the layout's share of its split, as a weight; one never resized has 1.
+ const [weights, setWeights] = useState<Readonly<Record<string, number>>>({});
const dragging = useRef(false);
+ // The tab being dragged, and where it would land if dropped now.
+ const [dragKey, setDragKey] = useState<string | null>(null);
+ const [dropHint, setDropHint] = useState<DropHint | null>(null);
// Tabs whose Markdown, HTML or SVG is shown rendered (Ctrl+Shift+V).
const [rendered, setRendered] = useState<ReadonlySet<string>>(() => new Set());
const toggleRendered = (key: string) =>
@@ -105,11 +148,31 @@ export function CodeEditorStage({
const menuAnchor = useRef<HTMLElement | null>(null);
const pushToast = useEventStore((state) => state.pushToast);
- const activeTab = tabs.find((tab) => tab.key === activeKey) ?? tabs[tabs.length - 1] ?? null;
- // A second editor beside the first ("Open to the side"). The breadcrumbs,
- // banners and status bar describe whichever of the two has the keyboard.
- const sideTab = activeTab && sideKey ? (tabs.find((tab) => tab.key === sideKey) ?? null) : null;
- const sideFocused = sideHasKeyboard && sideTab !== null;
+ const groups = useMemo(
+ () =>
+ workspaceId
+ ? groupsOf(
+ {
+ tabs,
+ layout: storedLayout === undefined ? {} : { [workspaceId]: storedLayout },
+ groupActive: { [workspaceId]: groupActive ?? {} },
+ focusedGroup: focusedGroupId === undefined ? {} : { [workspaceId]: focusedGroupId },
+ },
+ workspaceId,
+ )
+ : [],
+ [workspaceId, tabs, storedLayout, groupActive, focusedGroupId],
+ );
+ const tree = useMemo(
+ () =>
+ layoutFor(
+ storedLayout,
+ groups.filter((group) => group.tabs.length > 0).map((group) => group.id),
+ ),
+ [storedLayout, groups],
+ );
+ // The tab of the group that has the keyboard: what shortcuts and the status bar act on.
+ const activeTab = tabs.find((tab) => tab.key === activeKey) ?? groups.find((group) => group.focused)?.active ?? null;
const shown = visible && activeTab !== null;
// Reopen what this workspace had open last run, unsaved text included.
@@ -172,9 +235,8 @@ export function CodeEditorStage({
if (!state.visible || !host) return;
if (target && target !== document.body && !host.contains(target)) return;
const own = tabsOf(state, workspaceId);
- // Keys go to the editor that has the keyboard.
- const beside = state.sideFocused ? own.find((tab) => tab.key === state.side[workspaceId]) : undefined;
- const current = beside ?? own.find((tab) => tab.key === state.active[workspaceId]) ?? own[own.length - 1];
+ // Keys go to the group that has the keyboard.
+ const current = own.find((tab) => tab.key === state.active[workspaceId]) ?? own[own.length - 1];
if (!current) return;
const handled = () => {
event.preventDefault();
@@ -186,9 +248,7 @@ export function CodeEditorStage({
else void saveFile(current.fileKey);
} else if (key === "w" && !event.shiftKey) {
handled();
- // In the second editor, Ctrl+W ends the split; the tab stays open.
- if (beside) state.closeSide(workspaceId);
- else requestCloseRef.current([current.key]);
+ requestCloseRef.current([current.key]);
} else if (key === "tab" || key === "pagedown" || key === "pageup") {
handled();
state.cycle(workspaceId, event.shiftKey || key === "pageup" ? -1 : 1);
@@ -205,7 +265,7 @@ export function CodeEditorStage({
}, [workspaceId]);
// Notice an agent's edit to the open files: on a timer and when the window regains focus.
- const watchedFileKeys = shown ? [...new Set([activeTab.fileKey, ...(sideTab ? [sideTab.fileKey] : [])])].join("\n") : "";
+ const watchedFileKeys = shown ? [...new Set(groups.flatMap((group) => (group.active ? [group.active.fileKey] : [])))].join("\n") : "";
useEffect(() => {
if (!watchedFileKeys) return;
let alive = true;
@@ -252,32 +312,104 @@ export function CodeEditorStage({
{t("code_editor.starting")}
</p>
);
- const shownTab = sideFocused && sideTab ? sideTab : activeTab;
- const shownFile = files[shownTab.fileKey];
- const segments = shownTab.path.split("/");
-
- // Dragging the divider between the two editors.
- const dragSplit = (event: ReactPointerEvent<HTMLDivElement>) => {
- const host = splitHost.current;
- if (!dragging.current || !host) return;
- const rect = host.getBoundingClientRect();
- if (rect.width > 0) setSplit(clampSplit((event.clientX - rect.left) / rect.width));
+ const focusTab = activeTab;
+
+ const weightOf = (node: EditorLayout) => weights[nodeKey(node)] ?? 1;
+ /** Move the divider between two neighbours of a split; their joint size stays. */
+ const resizePair = (first: EditorLayout, second: EditorLayout, ratio: number) => {
+ const total = weightOf(first) + weightOf(second);
+ const share = clampSplit(ratio);
+ setWeights((current) => ({ ...current, [nodeKey(first)]: total * share, [nodeKey(second)]: total * (1 - share) }));
+ };
+ const dragDivider = (event: ReactPointerEvent<HTMLDivElement>, first: EditorLayout, second: EditorLayout, dir: "row" | "column") => {
+ if (!dragging.current) return;
+ const before = event.currentTarget.previousElementSibling?.getBoundingClientRect();
+ const after = event.currentTarget.nextElementSibling?.getBoundingClientRect();
+ if (!before || !after) return;
+ const [start, end, at] = dir === "row" ? [before.left, after.right, event.clientX] : [before.top, after.bottom, event.clientY];
+ if (end > start) resizePair(first, second, (at - start) / (end - start));
};
- return (
- <>
- <div
- ref={stage}
- data-testid="code-editor"
+ const draggedTab = dragKey ? (tabs.find((tab) => tab.key === dragKey) ?? null) : null;
+ const endDrag = () => {
+ setDragKey(null);
+ setDropHint(null);
+ };
+ /** Whether dropping the dragged tab on this zone of a group's text changes anything. */
+ const zoneTakes = (group: EditorGroup, zone: DropZone) => {
+ if (!draggedTab) return false;
+ const own = draggedTab.group === group.id;
+ // The middle moves the tab into the group; a side opens a new group there.
+ return zone === "center" ? !own : !(own && group.tabs.length === 1);
+ };
+ /** The zone of a group's text area under the pointer. */
+ const zoneAt = (group: EditorGroup, area: HTMLElement, x: number, y: number): DropZone => {
+ const rect = area.getBoundingClientRect();
+ const across = rect.width > 0 ? (x - rect.left) / rect.width : 0.5;
+ const down = rect.height > 0 ? (y - rect.top) / rect.height : 0.5;
+ // The middle takes the tab into the group; outside it, the nearest edge
+ // wins. A group's own tab can only go to an edge.
+ const inMiddle = across > 1 / 3 && across < 2 / 3 && down > 1 / 3 && down < 2 / 3;
+ if (inMiddle && zoneTakes(group, "center")) return "center";
+ const edges: [DropZone, number][] = [
+ ["left", across],
+ ["right", 1 - across],
+ ["top", down],
+ ["bottom", 1 - down],
+ ];
+ return edges.reduce((best, edge) => (edge[1] < best[1] ? edge : best))[0];
+ };
+
+ const renderGroup = (group: EditorGroup) => {
+ const shownTab = group.active;
+ if (!shownTab) return null;
+ const hint = dropHint?.group === group.id ? dropHint : null;
+ const marker = hint && "before" in hint ? hint.before : -1;
+ const zone = hint && "zone" in hint ? hint.zone : null;
+ const shownFile = files[shownTab.fileKey];
+ const segments = shownTab.path.split("/");
+ const last = group.id === cornerOf(tree);
+ return (
+ <section
+ key={group.id}
+ aria-label={fill(t("code_editor.group_label"), { n: String(groups.indexOf(group) + 1) })}
+ data-testid="code-editor-group"
+ data-group={group.id}
data-path={shownTab.path}
- className="absolute inset-0 z-20 flex min-h-0 flex-col bg-background"
+ data-focused={group.focused || undefined}
+ className="flex min-h-0 min-w-0 flex-col"
+ style={{ flex: `${weightOf(group.id)} 1 0%` }}
+ onFocusCapture={() => store.focusGroup(workspaceId, group.id)}
+ onPointerDownCapture={() => store.focusGroup(workspaceId, group.id)}
>
{/* Tab bar */}
- <div className="flex h-9 shrink-0 items-stretch border-b border-border/70 bg-sidebar">
+ <div
+ data-testid="code-editor-tabbar"
+ className="flex h-9 shrink-0 items-stretch border-b border-border/70 bg-sidebar"
+ // A dragged tab lands in front of the tab under the pointer, or at the end.
+ onDragOver={(event) => {
+ if (!event.dataTransfer.types.includes(TAB_DRAG_TYPE)) return;
+ event.preventDefault();
+ event.dataTransfer.dropEffect = "move";
+ const before = insertionIndex(event.currentTarget, event.clientX);
+ if (marker !== before) setDropHint({ group: group.id, before });
+ }}
+ onDragLeave={(event) => {
+ if (marker >= 0 && !event.currentTarget.contains(event.relatedTarget as Node | null)) setDropHint(null);
+ }}
+ onDrop={(event) => {
+ const key = event.dataTransfer.getData(TAB_DRAG_TYPE);
+ if (!key) return;
+ event.preventDefault();
+ const before = group.tabs[insertionIndex(event.currentTarget, event.clientX)]?.key;
+ endDrag();
+ store.moveTab(key, { group: group.id, before });
+ }}
+ >
<div role="tablist" aria-label={t("code_editor.tabs")} className="scrollbar-none flex min-w-0 flex-1 items-stretch overflow-x-auto">
- {tabs.map((tab) => {
+ {group.tabs.map((tab, position) => {
const file = files[tab.fileKey];
- const active = tab.key === activeTab.key;
+ const active = tab.key === shownTab.key;
const name = baseName(tab.path);
const folder = tab.path.split("/").slice(-2, -1)[0];
return (
@@ -290,6 +422,16 @@ export function CodeEditorStage({
data-preview={tab.preview || undefined}
data-dirty={file?.dirty || undefined}
tabIndex={0}
+ draggable
+ data-dragging={dragKey === tab.key || undefined}
+ onDragStart={(event) => {
+ event.dataTransfer.setData(TAB_DRAG_TYPE, tab.key);
+ event.dataTransfer.effectAllowed = "move";
+ // Once the browser has taken its picture of the tab: the
+ // drop zones come up over every group's text.
+ window.setTimeout(() => setDragKey(tab.key), 0);
+ }}
+ onDragEnd={endDrag}
title={tab.path}
onClick={() => store.activate(tab.key)}
onDoubleClick={() => store.pinTab(tab.key)}
@@ -309,19 +451,15 @@ export function CodeEditorStage({
setMenu(tab);
}}
className={cn(
- "group relative flex min-w-0 max-w-[220px] shrink-0 cursor-pointer items-center gap-1.5 border-r border-border/50 pl-3 pr-1.5 text-[13px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",
+ "group relative flex min-w-0 max-w-[220px] shrink-0 cursor-pointer items-center gap-1.5 border-r border-border/50 pl-3 pr-1.5 text-[13px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring data-[dragging]:opacity-50",
active ? "bg-background text-foreground-strong" : "text-muted-foreground hover:bg-secondary/60 hover:text-foreground",
)}
>
- {active && <span className={cn("absolute inset-x-0 top-0 h-px", sideFocused ? "bg-muted-foreground/50" : "bg-primary")} aria-hidden />}
+ {active && <span className={cn("absolute inset-x-0 top-0 h-px", group.focused ? "bg-primary" : "bg-muted-foreground/50")} aria-hidden />}
+ {marker === position && <span className="pointer-events-none absolute inset-y-1 left-0 z-10 w-0.5 rounded bg-primary" aria-hidden />}
{tab.mode === "diff" ? <FileDiff className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden /> : <FileTypeIcon path={tab.path} />}
<span className={cn("truncate", tab.preview && "italic", file?.deleted && "line-through decoration-destructive/70")}>{name}</span>
{(duplicateNames.get(name) ?? 0) > 1 && folder && <span className="shrink-0 truncate text-[11px] text-muted-foreground">{folder}</span>}
- {sideTab?.key === tab.key && (
- <span title={t("code_editor.side_tab_hint")} data-testid="code-editor-tab-side" className="inline-flex shrink-0 text-muted-foreground">
- <Columns2 className="h-3 w-3" aria-hidden />
- </span>
- )}
<button
type="button"
aria-label={fill(t("code_editor.close_tab"), { file: name })}
@@ -344,17 +482,30 @@ export function CodeEditorStage({
</div>
);
})}
+ {marker === group.tabs.length && <span className="pointer-events-none my-1 w-0.5 shrink-0 rounded bg-primary" aria-hidden />}
</div>
<button
type="button"
- data-testid="code-editor-hide"
- onClick={() => store.setVisible(false)}
- title={t("code_editor.show_terminals_hint")}
- className="inline-flex shrink-0 items-center gap-1.5 border-l border-border/60 px-3 text-xs text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
+ data-testid="code-editor-split"
+ aria-label={t("code_editor.split_right")}
+ title={t("code_editor.split_right")}
+ onClick={() => store.splitRight(shownTab.key)}
+ className="inline-flex w-8 shrink-0 items-center justify-center text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
>
- <SquareTerminal className="h-3.5 w-3.5" aria-hidden />
- {t("code_editor.show_terminals")}
+ <Columns2 className="h-3.5 w-3.5" aria-hidden />
</button>
+ {last && (
+ <button
+ type="button"
+ data-testid="code-editor-hide"
+ onClick={() => store.setVisible(false)}
+ title={t("code_editor.show_terminals_hint")}
+ className="inline-flex shrink-0 items-center gap-1.5 border-l border-border/60 px-3 text-xs text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
+ >
+ <SquareTerminal className="h-3.5 w-3.5" aria-hidden />
+ {t("code_editor.show_terminals")}
+ </button>
+ )}
</div>
{/* Breadcrumbs and file actions */}
@@ -421,101 +572,144 @@ export function CodeEditorStage({
<Banner tone="muted" testId="code-editor-deleted" text={t("code_editor.deleted")} />
)}
- <div ref={splitHost} className="flex min-h-0 flex-1">
- <div
- data-testid="code-editor-main"
- className="relative min-h-0 min-w-0"
- style={{ flex: sideTab ? `${split} 1 0%` : "1 1 0%" }}
- onFocusCapture={() => store.focusGroup(false)}
- onPointerDownCapture={() => store.focusGroup(false)}
- >
- <Suspense fallback={starting}>
- <EditorSurface tab={activeTab} rendered={rendered.has(activeTab.key)} onOpenExternally={openExternally} />
- </Suspense>
- </div>
- {sideTab && (
- <>
- <div
- role="separator"
- aria-orientation="vertical"
- aria-label={t("code_editor.resize_split")}
- aria-valuemin={SPLIT_MIN * 100}
- aria-valuemax={SPLIT_MAX * 100}
- aria-valuenow={Math.round(split * 100)}
- tabIndex={0}
- title={t("code_editor.resize_split")}
- data-testid="code-editor-split-handle"
- onPointerDown={(event) => {
- event.preventDefault();
- dragging.current = true;
- event.currentTarget.setPointerCapture?.(event.pointerId);
- }}
- onPointerMove={dragSplit}
- onPointerUp={(event) => {
- dragging.current = false;
- event.currentTarget.releasePointerCapture?.(event.pointerId);
- }}
- onPointerCancel={() => {
- dragging.current = false;
- }}
- onDoubleClick={() => setSplit(0.5)}
- onKeyDown={(event) => {
- if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;
- event.preventDefault();
- setSplit((current) => clampSplit(current + (event.key === "ArrowLeft" ? -0.05 : 0.05)));
- }}
- className="w-1 shrink-0 cursor-col-resize bg-border/70 transition-colors hover:bg-primary/60 focus-visible:bg-primary/60 focus-visible:outline-none"
- />
- <section
- aria-label={t("code_editor.side_label")}
- data-testid="code-editor-side"
- data-path={sideTab.path}
- data-focused={sideFocused || undefined}
- className="flex min-h-0 min-w-0 flex-col"
- style={{ flex: `${1 - split} 1 0%` }}
- onFocusCapture={() => store.focusGroup(true)}
- onPointerDownCapture={() => store.focusGroup(true)}
- >
- <div className="relative flex h-8 shrink-0 items-center gap-1.5 border-b border-border/50 bg-sidebar pl-3 pr-1.5 text-[13px]">
- {sideFocused && <span className="absolute inset-x-0 top-0 h-px bg-primary" aria-hidden />}
- {sideTab.mode === "diff" ? <FileDiff className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden /> : <FileTypeIcon path={sideTab.path} />}
- <span className={cn("min-w-0 flex-1 truncate", sideFocused ? "text-foreground-strong" : "text-muted-foreground")} title={sideTab.path}>
- {baseName(sideTab.path)}
- </span>
- {files[sideTab.fileKey]?.dirty && <span className="h-2 w-2 shrink-0 rounded-full bg-foreground/70" aria-hidden />}
- <button
- type="button"
- data-testid="code-editor-side-close"
- aria-label={t("code_editor.close_side")}
- title={t("code_editor.close_side")}
- onClick={() => store.closeSide(workspaceId)}
- className="inline-flex h-5 w-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- >
- <X className="h-3.5 w-3.5" aria-hidden />
- </button>
- </div>
- <div className="relative min-h-0 flex-1">
- <Suspense fallback={starting}>
- <EditorSurface tab={sideTab} rendered={rendered.has(sideTab.key)} secondary onOpenExternally={openExternally} />
- </Suspense>
- </div>
- </section>
- </>
+ <div className="relative min-h-0 flex-1">
+ <Suspense fallback={starting}>
+ <EditorSurface
+ tab={shownTab}
+ rendered={rendered.has(shownTab.key)}
+ focused={group.focused}
+ secondary={groups.length > 1}
+ onOpenExternally={openExternally}
+ />
+ </Suspense>
+ {/* While a tab is dragged, the text area takes the drop: its middle
+ moves the tab into this group, each of its four sides opens a
+ new group there. Laid over the editor so the text never sees it. */}
+ {draggedTab && (zoneTakes(group, "center") || zoneTakes(group, "left")) && (
+ <div
+ data-testid="code-editor-drop"
+ data-zone={zone ?? undefined}
+ className="absolute inset-0 z-10"
+ onDragOver={(event) => {
+ if (!event.dataTransfer.types.includes(TAB_DRAG_TYPE)) return;
+ const next = zoneAt(group, event.currentTarget, event.clientX, event.clientY);
+ event.preventDefault();
+ event.dataTransfer.dropEffect = "move";
+ if (zone !== next) setDropHint({ group: group.id, zone: next });
+ }}
+ onDragLeave={() => {
+ if (zone) setDropHint(null);
+ }}
+ onDrop={(event) => {
+ const key = event.dataTransfer.getData(TAB_DRAG_TYPE);
+ if (!key) return;
+ event.preventDefault();
+ // Where the pointer is now, not where the last painted hint was.
+ const landed = zoneAt(group, event.currentTarget, event.clientX, event.clientY);
+ endDrag();
+ store.moveTab(key, landed === "center" ? { group: group.id } : { beside: group.id, side: landed });
+ }}
+ >
+ <div className="pointer-events-none absolute inset-1 rounded-lg border-2 border-dashed border-primary/30" aria-hidden />
+ {zone && (
+ <div
+ aria-hidden
+ className="pointer-events-none absolute rounded-md bg-primary/25 ring-2 ring-primary transition-all duration-150 motion-reduce:transition-none"
+ style={ZONE_BOX[zone]}
+ />
+ )}
+ </div>
)}
</div>
+ </section>
+ );
+ };
+
+ /** A group, or a split with a draggable divider between each two of its parts. */
+ const renderNode = (node: EditorLayout): ReactNode => {
+ if (typeof node === "number") {
+ const group = groups.find((entry) => entry.id === node);
+ return group ? renderGroup(group) : null;
+ }
+ const row = node.dir === "row";
+ return (
+ <div
+ key={nodeKey(node)}
+ data-testid="code-editor-layout"
+ data-dir={node.dir}
+ className={cn("flex min-h-0 min-w-0", row ? "flex-row" : "flex-col")}
+ style={{ flex: `${weightOf(node)} 1 0%` }}
+ >
+ {node.children.map((child, index) => {
+ const previous = node.children[index - 1];
+ return (
+ <Fragment key={nodeKey(child)}>
+ {previous !== undefined && (
+ <div
+ role="separator"
+ aria-orientation={row ? "vertical" : "horizontal"}
+ aria-label={t("code_editor.resize_split")}
+ tabIndex={0}
+ title={t("code_editor.resize_split")}
+ data-testid="code-editor-split-handle"
+ onPointerDown={(event) => {
+ event.preventDefault();
+ dragging.current = true;
+ event.currentTarget.setPointerCapture?.(event.pointerId);
+ }}
+ onPointerMove={(event) => dragDivider(event, previous, child, node.dir)}
+ onPointerUp={(event) => {
+ dragging.current = false;
+ event.currentTarget.releasePointerCapture?.(event.pointerId);
+ }}
+ onPointerCancel={() => {
+ dragging.current = false;
+ }}
+ onDoubleClick={() => resizePair(previous, child, 0.5)}
+ onKeyDown={(event) => {
+ const back = row ? "ArrowLeft" : "ArrowUp";
+ const forth = row ? "ArrowRight" : "ArrowDown";
+ if (event.key !== back && event.key !== forth) return;
+ event.preventDefault();
+ const share = weightOf(previous) / (weightOf(previous) + weightOf(child));
+ resizePair(previous, child, share + (event.key === back ? -0.05 : 0.05));
+ }}
+ className={cn(
+ "shrink-0 bg-border/70 transition-colors hover:bg-primary/60 focus-visible:bg-primary/60 focus-visible:outline-none",
+ row ? "w-1 cursor-col-resize" : "h-1 cursor-row-resize",
+ )}
+ />
+ )}
+ {renderNode(child)}
+ </Fragment>
+ );
+ })}
+ </div>
+ );
+ };
+
+ return (
+ <>
+ <div
+ ref={stage}
+ data-testid="code-editor"
+ data-path={focusTab.path}
+ className="absolute inset-0 z-20 flex min-h-0 flex-col bg-background"
+ >
+ <div className="flex min-h-0 flex-1">{renderNode(tree)}</div>
- <StatusBar fileKey={shownTab.fileKey} />
+ <StatusBar fileKey={focusTab.fileKey} />
</div>
<ThreadPopover anchor={menuAnchor} open={menu !== null} onClose={() => setMenu(null)} label={t("code_editor.tab_menu")} width={230}>
{menu && (
<div role="menu">
<ThreadMenuItem icon={<X className="h-4 w-4" />} label={t("code_editor.menu.close")} hint="Ctrl+W" onSelect={() => { setMenu(null); requestClose([menu.key]); }} />
- <ThreadMenuItem icon={<span aria-hidden />} label={t("code_editor.menu.close_others")} onSelect={() => { setMenu(null); requestClose(tabs.filter((tab) => tab.key !== menu.key).map((tab) => tab.key)); }} />
- <ThreadMenuItem icon={<span aria-hidden />} label={t("code_editor.menu.close_saved")} onSelect={() => { setMenu(null); requestClose(tabs.filter((tab) => !files[tab.fileKey]?.dirty).map((tab) => tab.key)); }} />
- <ThreadMenuItem icon={<span aria-hidden />} label={t("code_editor.menu.close_all")} onSelect={() => { setMenu(null); requestClose(tabs.map((tab) => tab.key)); }} />
+ <ThreadMenuItem icon={<span aria-hidden />} label={t("code_editor.menu.close_others")} onSelect={() => { setMenu(null); requestClose(tabs.filter((tab) => tab.group === menu.group && tab.key !== menu.key).map((tab) => tab.key)); }} />
+ <ThreadMenuItem icon={<span aria-hidden />} label={t("code_editor.menu.close_saved")} onSelect={() => { setMenu(null); requestClose(tabs.filter((tab) => tab.group === menu.group && !files[tab.fileKey]?.dirty).map((tab) => tab.key)); }} />
+ <ThreadMenuItem icon={<span aria-hidden />} label={t("code_editor.menu.close_all")} onSelect={() => { setMenu(null); requestClose(tabs.filter((tab) => tab.group === menu.group).map((tab) => tab.key)); }} />
<ThreadMenuSeparator />
- <ThreadMenuItem icon={<Columns2 className="h-4 w-4" />} label={t("code_editor.menu.open_side")} onSelect={() => { setMenu(null); store.openToSide(workspaceId, menu.path, { mode: menu.mode }); }} />
+ <ThreadMenuItem icon={<Columns2 className="h-4 w-4" />} label={t("code_editor.split_right")} onSelect={() => { setMenu(null); store.splitRight(menu.key); }} />
<ThreadMenuSeparator />
<ThreadMenuItem icon={<Copy className="h-4 w-4" />} label={t("code_editor.menu.copy_path")} onSelect={() => { setMenu(null); copyText(absolute(menu.path)); }} />
<ThreadMenuItem icon={<span aria-hidden />} label={t("code_editor.menu.copy_relative_path")} onSelect={() => { setMenu(null); copyText(menu.path); }} />
diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/EditorSurface.tsx b/jarvis/ui/web/frontend/src/components/agentic/editor/EditorSurface.tsx
index 95c1141cdb..f7b3b0038f 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/editor/EditorSurface.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/EditorSurface.tsx
@@ -37,6 +37,8 @@ function watchCursor(editor: CodeEditor): monaco.IDisposable[] {
editor.onDidChangeCursorSelection(() => reportCursor(editor)),
editor.onDidChangeModel(() => reportCursor(editor)),
editor.onDidChangeModelOptions(() => reportCursor(editor)),
+ // With several editors side by side, the status bar follows the one typed in.
+ editor.onDidFocusEditorText(() => reportCursor(editor)),
];
}
@@ -51,11 +53,17 @@ const keepContextMenu = (event: MouseEvent) => event.stopPropagation();
export default function EditorSurface({
tab,
rendered,
+ focused = true,
secondary = false,
onOpenExternally,
}: {
tab: EditorTab;
- /** The second editor of a split view: closing it leaves the first one's status bar alone. */
+ /**
+ * This editor's group has the keyboard. Only that editor takes the focus
+ * when its tab changes and jumps to an "open at line" request.
+ */
+ focused?: boolean;
+ /** Other editors stand beside this one: closing it leaves the status bar to them. */
secondary?: boolean;
/** Show a Markdown, HTML or SVG file rendered instead of its source. */
rendered: boolean;
@@ -68,6 +76,10 @@ export default function EditorSurface({
const diffRef = useRef<monaco.editor.IStandaloneDiffEditor | null>(null);
const shown = useRef<string | null>(null);
const handledReveal = useRef(0);
+ const hasKeyboard = useRef(focused);
+ hasKeyboard.current = focused;
+ const beside = useRef(secondary);
+ beside.current = secondary;
const file = useCodeEditorStore((state) => state.files[tab.fileKey]);
const reveal = useCodeEditorStore((state) => state.reveal);
const status = file?.status ?? "loading";
@@ -98,10 +110,8 @@ export default function EditorSurface({
diffRef.current?.dispose();
diffRef.current = null;
editorRef.current = null;
- if (!secondary) useCodeEditorStore.getState().setCursor(null);
+ if (!beside.current) useCodeEditorStore.getState().setCursor(null);
};
- // `secondary` never changes for a mounted editor.
- // eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
@@ -120,10 +130,21 @@ export default function EditorSurface({
if (state) editor.restoreViewState(state);
shown.current = tab.key;
}
- reportCursor(editor);
- editor.focus();
+ if (hasKeyboard.current) {
+ reportCursor(editor);
+ editor.focus();
+ }
}, [tab.key, tab.fileKey, tab.mode, ready]);
+ // A group that gets the keyboard while nothing holds the focus (the group
+ // beside it just closed) puts the cursor back into its text.
+ useEffect(() => {
+ if (!focused || !ready) return;
+ const held = document.activeElement;
+ if (held && held !== document.body) return;
+ (tab.mode === "diff" ? diffRef.current?.getModifiedEditor() : editorRef.current)?.focus();
+ }, [focused, ready, tab.mode]);
+
// Gutter markers against the last commit: green added, blue modified, a red
// notch where lines were deleted. Recomputed shortly after each edit.
useEffect(() => {
@@ -204,8 +225,10 @@ export default function EditorSurface({
diff.setModel({ original, modified });
const right = diff.getModifiedEditor();
watchers = watchCursor(right);
- reportCursor(right);
- right.focus();
+ if (hasKeyboard.current) {
+ reportCursor(right);
+ right.focus();
+ }
});
return () => {
alive = false;
@@ -216,6 +239,12 @@ export default function EditorSurface({
// "Open at line": a Ctrl+click on `file.py:42` in a terminal, or Quick Open's `name:42`.
useEffect(() => {
if (!ready || !reveal || reveal.fileKey !== tab.fileKey || reveal.nonce === handledReveal.current) return;
+ // The same file may be open in several groups; only the one the file was
+ // opened in jumps to the line.
+ if (!hasKeyboard.current) {
+ handledReveal.current = reveal.nonce;
+ return;
+ }
const editor = tab.mode === "diff" ? diffRef.current?.getModifiedEditor() : editorRef.current;
if (!editor || editor.getModel() !== modelOf(tab.fileKey)) return;
handledReveal.current = reveal.nonce;
diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/editorPersistence.ts b/jarvis/ui/web/frontend/src/components/agentic/editor/editorPersistence.ts
index 1de42d53d1..777b85d33f 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/editor/editorPersistence.ts
+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/editorPersistence.ts
@@ -18,7 +18,11 @@ const lastSent = new Map<string, string>();
function snapshot(workspaceId: string) {
const state = useCodeEditorStore.getState();
- const tabs = tabsOf(state, workspaceId).map(({ path, mode, preview }) => ({ path, mode, preview }));
+ // A file open in two groups is remembered once; the split itself is not.
+ const seen = new Set<string>();
+ const tabs = tabsOf(state, workspaceId)
+ .filter(({ path, mode }) => !seen.has(`${mode}:${path}`) && seen.add(`${mode}:${path}`))
+ .map(({ path, mode, preview }) => ({ path, mode, preview }));
const active = tabsOf(state, workspaceId).find((tab) => tab.key === state.active[workspaceId])?.path ?? null;
return { tabs, active, key: JSON.stringify([tabs, active]) };
}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/monacoRuntime.ts b/jarvis/ui/web/frontend/src/components/agentic/editor/monacoRuntime.ts
index 2c7107f76c..f2cfc86ab8 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/editor/monacoRuntime.ts
+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/monacoRuntime.ts
@@ -84,7 +84,14 @@ function tokenHex(name: string, fallback: string): string {
return `#${[red, green, blue, Math.round(alpha * 255)].map((part) => part.toString(16).padStart(2, "0")).join("")}`;
}
-/** Re-read the app's colour tokens into the editor theme (light or dark). */
+let appliedTheme = "";
+
+/**
+ * Re-read the app's colour tokens into the editor theme (light or dark).
+ *
+ * Every editor on screen asks for this when the app's theme changes, and a
+ * theme change repaints all of them, so only the first call per change acts.
+ */
export function applyTheme(dark: boolean): void {
const background = tokenHex("--background", dark ? "#171717" : "#ffffff");
const foreground = tokenHex("--foreground", dark ? "#e5e5e5" : "#171717");
@@ -95,6 +102,9 @@ export function applyTheme(dark: boolean): void {
// The same thumb colours as the app's own scrollbars (index.css), so the
// editor's bars and the diff overview's viewport box read as one family.
const thumb = tokenHex("--border-strong", dark ? "#404040" : "#bdbdbd");
+ const signature = [dark, background, foreground, muted, border, lift, popover, thumb].join("|");
+ if (signature === appliedTheme) return;
+ appliedTheme = signature;
monaco.editor.defineTheme("jarvis", {
base: dark ? "vs-dark" : "vs",
inherit: true,
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/ExplorerPanel.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/ExplorerPanel.test.tsx
index 40e8882c64..17ccc03622 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/ExplorerPanel.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/ExplorerPanel.test.tsx
@@ -6,7 +6,7 @@ import { extractPaneDrop } from "@/components/agentic/paneDrop";
import { activateTerminalLink } from "@/lib/terminalLinks";
import { useEventStore } from "@/store/events";
import { useIdeChatStore } from "@/store/ideChat";
-import { useCodeEditorStore } from "@/store/codeEditor";
+import { groupsOf, useCodeEditorStore } from "@/store/codeEditor";
import { parsePrintedPath, useExplorerPathRouting } from "@/store/ideExplorer";
import { useIdeSidePanelStore } from "@/store/ideSidePanel";
@@ -277,18 +277,17 @@ describe("ExplorerPanel", () => {
expect(Object.values(state.diffBases)).toMatchObject([{ path: "README.md" }]);
});
- it("opens a file beside the one already open, from the menu and with Ctrl+Enter", async () => {
- useCodeEditorStore.setState({ side: {}, sideFocused: false });
+ it("opens a file in a group beside the one already open, from the menu and with Ctrl+Enter", async () => {
+ useCodeEditorStore.setState({ layout: {}, groupActive: {}, focusedGroup: {} });
useCodeEditorStore.getState().openFile("w1", "notes.md", { preview: false });
const { row, menu } = await openRowMenu("README.md");
fireEvent.click(item(menu, /Open to the side/)!);
- const tabKey = (path: string) => useCodeEditorStore.getState().tabs.find((tab) => tab.path === path)!.key;
- expect(useCodeEditorStore.getState().side.w1).toBe(tabKey("README.md"));
- expect(useCodeEditorStore.getState().active.w1).toBe(tabKey("notes.md"));
+ const columns = () => groupsOf(useCodeEditorStore.getState(), "w1").map((group) => group.tabs.map((tab) => tab.path));
+ expect(columns()).toEqual([["notes.md"], ["README.md"]]);
- useCodeEditorStore.getState().closeSide("w1");
+ // The new group has the keyboard, so Ctrl+Enter opens a third one beside it.
fireEvent.keyDown(row, { key: "Enter", ctrlKey: true });
- expect(useCodeEditorStore.getState().side.w1).toBe(tabKey("README.md"));
+ expect(columns()).toEqual([["notes.md"], ["README.md"], ["README.md"]]);
});
it("copies the path with Shift+Alt+C and the relative path with Ctrl+K Ctrl+Shift+C", async () => {
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 0279708ca1..c077cddd1a 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -7360,10 +7360,9 @@
"tabs": "Geöffnete Dateien",
"close_tab": "{file} schließen",
"close_tab_hint": "Schließen (Strg+W)",
- "close_side": "Seitlichen Editor schließen",
- "side_label": "Seitlicher Editor",
- "resize_split": "Größe der beiden Editoren ändern",
- "side_tab_hint": "Im seitlichen Editor geöffnet",
+ "group_label": "Editor-Gruppe {n}",
+ "split_right": "Editor nach rechts teilen",
+ "resize_split": "Größe der Editor-Gruppen ändern",
"show_terminals": "Terminals",
"show_terminals_hint": "Terminals zeigen; deine Dateien bleiben offen",
"breadcrumbs": "Dateipfad",
@@ -7390,7 +7389,6 @@
"close_all": "Alle schließen",
"copy_path": "Pfad kopieren",
"copy_relative_path": "Relativen Pfad kopieren",
- "open_side": "An der Seite öffnen",
"reveal": "Im Ordner zeigen"
},
"status": {
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index c23bdf97ad..5eb07a5e74 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -7360,10 +7360,9 @@
"tabs": "Open files",
"close_tab": "Close {file}",
"close_tab_hint": "Close (Ctrl+W)",
- "close_side": "Close the side editor",
- "side_label": "Side editor",
- "resize_split": "Resize the two editors",
- "side_tab_hint": "Shown in the side editor",
+ "group_label": "Editor group {n}",
+ "split_right": "Split editor right",
+ "resize_split": "Resize the editor groups",
"show_terminals": "Terminals",
"show_terminals_hint": "Show the terminals; your files stay open",
"breadcrumbs": "File path",
@@ -7390,7 +7389,6 @@
"close_all": "Close all",
"copy_path": "Copy path",
"copy_relative_path": "Copy relative path",
- "open_side": "Open to the side",
"reveal": "Reveal in Folder"
},
"status": {
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 826142797f..a29045bc00 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -7360,10 +7360,9 @@
"tabs": "Archivos abiertos",
"close_tab": "Cerrar {file}",
"close_tab_hint": "Cerrar (Ctrl+W)",
- "close_side": "Cerrar el editor lateral",
- "side_label": "Editor lateral",
- "resize_split": "Cambiar el tamaño de los dos editores",
- "side_tab_hint": "Abierto en el editor lateral",
+ "group_label": "Grupo de editores {n}",
+ "split_right": "Dividir el editor a la derecha",
+ "resize_split": "Cambiar el tamaño de los grupos de editores",
"show_terminals": "Terminales",
"show_terminals_hint": "Mostrar las terminales; tus archivos siguen abiertos",
"breadcrumbs": "Ruta del archivo",
@@ -7390,7 +7389,6 @@
"close_all": "Cerrar todas",
"copy_path": "Copiar ruta",
"copy_relative_path": "Copiar ruta relativa",
- "open_side": "Abrir al lado",
"reveal": "Mostrar en la carpeta"
},
"status": {
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/pt.json b/jarvis/ui/web/frontend/src/i18n/locales/pt.json
index e5ec5bd3fe..ce10fab066 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/pt.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/pt.json
@@ -7360,10 +7360,9 @@
"tabs": "Ficheiros abertos",
"close_tab": "Fechar {file}",
"close_tab_hint": "Fechar (Ctrl+W)",
- "close_side": "Fechar o editor lateral",
- "side_label": "Editor lateral",
- "resize_split": "Redimensionar os dois editores",
- "side_tab_hint": "Mostrado no editor lateral",
+ "group_label": "Grupo de editores {n}",
+ "split_right": "Dividir o editor à direita",
+ "resize_split": "Redimensionar os grupos de editores",
"show_terminals": "Terminais",
"show_terminals_hint": "Mostrar os terminais; os ficheiros continuam abertos",
"breadcrumbs": "Caminho do ficheiro",
@@ -7390,7 +7389,6 @@
"close_all": "Fechar todos",
"copy_path": "Copiar caminho",
"copy_relative_path": "Copiar caminho relativo",
- "open_side": "Abrir ao lado",
"reveal": "Mostrar na pasta"
},
"status": {
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/zh.json b/jarvis/ui/web/frontend/src/i18n/locales/zh.json
index ce10ab947f..7fda6646f8 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/zh.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/zh.json
@@ -7360,10 +7360,9 @@
"tabs": "已打开的文件",
"close_tab": "关闭 {file}",
"close_tab_hint": "关闭(Ctrl+W)",
- "close_side": "关闭侧边编辑器",
- "side_label": "侧边编辑器",
- "resize_split": "调整两个编辑器的大小",
- "side_tab_hint": "已在侧边编辑器中打开",
+ "group_label": "编辑器组 {n}",
+ "split_right": "向右拆分编辑器",
+ "resize_split": "调整编辑器组的大小",
"show_terminals": "终端",
"show_terminals_hint": "显示终端;你的文件保持打开",
"breadcrumbs": "文件路径",
@@ -7390,7 +7389,6 @@
"close_all": "全部关闭",
"copy_path": "复制路径",
"copy_relative_path": "复制相对路径",
- "open_side": "在侧边打开",
"reveal": "在文件夹中显示"
},
"status": {
diff --git a/jarvis/ui/web/frontend/src/store/codeEditor.groups.test.ts b/jarvis/ui/web/frontend/src/store/codeEditor.groups.test.ts
new file mode 100644
index 0000000000..dc1e8ca8be
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/store/codeEditor.groups.test.ts
@@ -0,0 +1,253 @@
+import { beforeEach, describe, expect, it } from "vitest";
+
+import { fileKeyOf, groupsOf, tabKeyOf, useCodeEditorStore } from "./codeEditor";
+
+const store = () => useCodeEditorStore.getState();
+const edit = (path: string, group = 0) => tabKeyOf("edit", fileKeyOf("w1", path), group);
+/** Each group's tabs, left to right, the shown one in brackets, the focused group starred. */
+const layout = () =>
+ groupsOf(store(), "w1").map(
+ (group) => `${group.focused ? "*" : ""}${group.tabs.map((tab) => (tab.key === group.active?.key ? `[${tab.path}]` : tab.path)).join(" ")}`,
+ );
+
+beforeEach(() => {
+ useCodeEditorStore.setState({
+ tabs: [],
+ active: {},
+ files: {},
+ visible: false,
+ quickOpen: false,
+ cursor: null,
+ reveal: null,
+ closed: [],
+ layout: {},
+ groupActive: {},
+ focusedGroup: {},
+ });
+});
+
+describe("editor groups side by side", () => {
+ it("starts as one empty group", () => {
+ expect(layout()).toEqual(["*"]);
+ expect(store().active.w1 ?? null).toBeNull();
+ });
+
+ it("opens a file in a new group to the right and hands it the keyboard", () => {
+ store().openFile("w1", "a.ts", { preview: false });
+ store().openToSide("w1", "b.ts");
+ expect(layout()).toEqual(["[a.ts]", "*[b.ts]"]);
+ expect(store().active.w1).toBe(edit("b.ts", 1));
+ expect(store().tabs.find((tab) => tab.path === "b.ts")?.preview).toBe(false);
+ });
+
+ it("simply opens the file when nothing is open yet", () => {
+ store().openToSide("w1", "a.ts");
+ expect(layout()).toEqual(["*[a.ts]"]);
+ });
+
+ it("shows the same file in two groups as two tabs", () => {
+ store().openFile("w1", "a.ts", { preview: false });
+ store().openToSide("w1", "a.ts");
+ expect(layout()).toEqual(["[a.ts]", "*[a.ts]"]);
+ expect(store().tabs).toHaveLength(2);
+ expect(Object.keys(store().files)).toHaveLength(1);
+ });
+
+ it("opens to the side into the group on the right when there is one, else adds a third", () => {
+ store().openFile("w1", "a.ts", { preview: false });
+ store().openToSide("w1", "b.ts");
+ store().focusGroup("w1", 0);
+ store().openToSide("w1", "c.ts");
+ // From the first group: the existing second group takes it.
+ expect(layout()).toEqual(["[a.ts]", "*b.ts [c.ts]"]);
+ // From the last group: a new one.
+ store().openToSide("w1", "d.ts");
+ expect(layout()).toEqual(["[a.ts]", "b.ts [c.ts]", "*[d.ts]"]);
+ });
+
+ it("splits a tab into a new group right beside its own, whichever group has the keyboard", () => {
+ store().openFile("w1", "a.ts", { preview: false });
+ store().openToSide("w1", "b.ts");
+ // The keyboard is in the second group; the split still stands beside the first.
+ store().splitRight(edit("a.ts"));
+ expect(layout()).toEqual(["[a.ts]", "*[a.ts]", "[b.ts]"]);
+ expect(store().tabs).toHaveLength(3);
+ });
+
+ it("keeps a compare's other file when its diff tab is split", () => {
+ const base = { ref: "file:b.ts", path: "b.ts", label: "b.ts ↔ a.ts" };
+ store().openFile("w1", "a.ts", { mode: "diff", preview: false, base });
+ store().splitRight(tabKeyOf("diff", fileKeyOf("w1", "a.ts")));
+ expect(store().diffBases[fileKeyOf("w1", "a.ts")]).toEqual(base);
+ expect(groupsOf(store(), "w1")).toHaveLength(2);
+ });
+
+ it("opens the next file in the group that has the keyboard", () => {
+ store().openFile("w1", "a.ts", { preview: false });
+ store().openToSide("w1", "b.ts");
+ store().openFile("w1", "c.ts", { preview: false });
+ expect(layout()).toEqual(["[a.ts]", "*b.ts [c.ts]"]);
+ store().focusGroup("w1", 0);
+ store().openFile("w1", "d.ts", { preview: false });
+ expect(layout()).toEqual(["*a.ts [d.ts]", "b.ts [c.ts]"]);
+ });
+
+ it("keeps one preview tab per group", () => {
+ store().openFile("w1", "a.ts");
+ store().openToSide("w1", "b.ts");
+ store().openFile("w1", "c.ts");
+ store().openFile("w1", "d.ts");
+ // d replaces the preview c on the right; the preview a on the left stays.
+ expect(layout()).toEqual(["[a.ts]", "*b.ts [d.ts]"]);
+ });
+
+ it("closes a group with its last tab and moves the keyboard to the neighbour", () => {
+ store().openFile("w1", "a.ts", { preview: false });
+ store().openToSide("w1", "b.ts");
+ store().openToSide("w1", "c.ts");
+ expect(layout()).toEqual(["[a.ts]", "[b.ts]", "*[c.ts]"]);
+ store().closeTab(edit("c.ts", 2));
+ expect(layout()).toEqual(["[a.ts]", "*[b.ts]"]);
+ store().focusGroup("w1", 0);
+ store().closeTab(edit("a.ts"));
+ expect(layout()).toEqual(["*[b.ts]"]);
+ expect(store().active.w1).toBe(edit("b.ts", 1));
+ });
+
+ it("closing a tab in one group leaves the same file open in the other", () => {
+ store().openFile("w1", "a.ts", { preview: false });
+ store().openToSide("w1", "a.ts");
+ store().closeTab(edit("a.ts", 1));
+ expect(layout()).toEqual(["*[a.ts]"]);
+ expect(Object.keys(store().files)).toHaveLength(1);
+ });
+
+ it("a click on a tab shows it in its own group and focuses that group", () => {
+ store().openFile("w1", "a.ts", { preview: false });
+ store().openFile("w1", "b.ts", { preview: false });
+ store().openToSide("w1", "c.ts");
+ store().activate(edit("a.ts"));
+ expect(layout()).toEqual(["*[a.ts] b.ts", "[c.ts]"]);
+ });
+
+ it("steps through the tabs of the group that has the keyboard", () => {
+ store().openFile("w1", "a.ts", { preview: false });
+ store().openFile("w1", "b.ts", { preview: false });
+ store().openToSide("w1", "c.ts");
+ store().openFile("w1", "d.ts", { preview: false });
+ store().cycle("w1", 1);
+ expect(layout()).toEqual(["a.ts [b.ts]", "*[c.ts] d.ts"]);
+ store().focusGroup("w1", 0);
+ store().cycle("w1", 1);
+ expect(layout()).toEqual(["*[a.ts] b.ts", "[c.ts] d.ts"]);
+ });
+
+ it("moves a dragged tab into another group", () => {
+ store().openFile("w1", "a.ts", { preview: false });
+ store().openFile("w1", "b.ts", { preview: false });
+ store().openToSide("w1", "c.ts");
+ store().moveTab(edit("b.ts"), { group: 1 });
+ expect(layout()).toEqual(["[a.ts]", "*c.ts [b.ts]"]);
+ // The last tab of a group moved away closes that group.
+ store().moveTab(edit("a.ts"), { group: 1 });
+ expect(layout()).toEqual(["*c.ts b.ts [a.ts]"]);
+ });
+
+ it("merges a dragged tab into the same file already open there", () => {
+ store().openFile("w1", "a.ts", { preview: false });
+ store().openFile("w1", "b.ts", { preview: false });
+ store().openToSide("w1", "a.ts");
+ store().moveTab(edit("a.ts"), { group: 1 });
+ expect(layout()).toEqual(["[b.ts]", "*[a.ts]"]);
+ });
+
+ it("reorders tabs within a tab bar", () => {
+ for (const path of ["a.ts", "b.ts", "c.ts"]) store().openFile("w1", path, { preview: false });
+ store().moveTab(edit("c.ts"), { group: 0, before: edit("a.ts") });
+ expect(layout()).toEqual(["*[c.ts] a.ts b.ts"]);
+ store().moveTab(edit("c.ts"), { group: 0 });
+ expect(layout()).toEqual(["*a.ts b.ts [c.ts]"]);
+ // Dropped on itself: nothing moves.
+ store().moveTab(edit("b.ts"), { group: 0, before: edit("b.ts") });
+ expect(layout()).toEqual(["*a.ts b.ts [c.ts]"]);
+ });
+
+ it("drops a tab in front of a tab of another group", () => {
+ store().openFile("w1", "a.ts", { preview: false });
+ store().openFile("w1", "b.ts", { preview: false });
+ store().openToSide("w1", "c.ts");
+ store().moveTab(edit("a.ts"), { group: 1, before: edit("c.ts", 1) });
+ expect(layout()).toEqual(["[b.ts]", "*[a.ts] c.ts"]);
+ });
+
+ it("pulls one of two tabs out into a new group on either side", () => {
+ store().openFile("w1", "a.ts", { preview: false });
+ store().openFile("w1", "b.ts", { preview: false });
+ // Dropped on the right half of its own group's text.
+ store().moveTab(edit("b.ts"), { beside: 0, side: "right" });
+ expect(layout()).toEqual(["[a.ts]", "*[b.ts]"]);
+ // A group's only tab dropped beside that same group stays put.
+ store().moveTab(edit("b.ts", 1), { beside: 1, side: "left" });
+ expect(layout()).toEqual(["[a.ts]", "*[b.ts]"]);
+ });
+
+ it("lays three tabs out as three groups by dragging", () => {
+ for (const path of ["a.ts", "b.ts", "c.ts"]) store().openFile("w1", path, { preview: false });
+ store().moveTab(edit("c.ts"), { beside: 0, side: "right" });
+ store().moveTab(edit("a.ts"), { beside: 0, side: "left" });
+ expect(layout()).toEqual(["*[a.ts]", "[b.ts]", "[c.ts]"]);
+ // A whole group dragged to the far side changes the order of the columns.
+ const first = groupsOf(store(), "w1")[0];
+ const last = groupsOf(store(), "w1")[2];
+ store().moveTab(first.tabs[0].key, { beside: last.id, side: "right" });
+ expect(layout()).toEqual(["[b.ts]", "[c.ts]", "*[a.ts]"]);
+ });
+
+ it("stacks a tab below or above a group", () => {
+ store().openFile("w1", "a.ts", { preview: false });
+ store().openFile("w1", "b.ts", { preview: false });
+ store().moveTab(edit("b.ts"), { beside: 0, side: "bottom" });
+ expect(store().layout.w1).toEqual({ dir: "column", children: [0, 1] });
+ expect(layout()).toEqual(["[a.ts]", "*[b.ts]"]);
+ store().openFile("w1", "c.ts", { preview: false });
+ store().moveTab(edit("c.ts", 1), { beside: 0, side: "top" });
+ expect(store().layout.w1).toEqual({ dir: "column", children: [2, 0, 1] });
+ });
+
+ it("splits one cell of a stack sideways and tidies up when a cell closes", () => {
+ store().openFile("w1", "a.ts", { preview: false });
+ store().openFile("w1", "b.ts", { preview: false });
+ store().openFile("w1", "c.ts", { preview: false });
+ store().moveTab(edit("b.ts"), { beside: 0, side: "bottom" });
+ store().moveTab(edit("c.ts"), { beside: 1, side: "right" });
+ // a on top; b and c side by side below it.
+ expect(store().layout.w1).toEqual({ dir: "column", children: [0, { dir: "row", children: [1, 2] }] });
+ expect(layout()).toEqual(["[a.ts]", "[b.ts]", "*[c.ts]"]);
+ store().closeTab(edit("b.ts", 1));
+ expect(store().layout.w1).toEqual({ dir: "column", children: [0, 2] });
+ store().closeTab(edit("a.ts"));
+ expect(store().layout.w1).toBe(2);
+ });
+
+ it("opens to the side beside a stacked group, inside its row", () => {
+ store().openFile("w1", "a.ts", { preview: false });
+ store().openFile("w1", "b.ts", { preview: false });
+ store().moveTab(edit("b.ts"), { beside: 0, side: "bottom" });
+ store().splitRight(edit("b.ts", 1));
+ expect(store().layout.w1).toEqual({ dir: "column", children: [0, { dir: "row", children: [1, 2] }] });
+ });
+
+ it("follows a rename of the files it shows", () => {
+ store().openFile("w1", "src/a.ts", { preview: false });
+ store().openToSide("w1", "src/b.ts");
+ store().renamePath("w1", "src", "lib");
+ expect(layout()).toEqual(["[lib/a.ts]", "*[lib/b.ts]"]);
+ expect(store().active.w1).toBe(edit("lib/b.ts", 1));
+ });
+
+ it("restores remembered tabs into the first group", () => {
+ store().restoreTabs("w1", [{ path: "a.ts", mode: "edit", preview: false }, { path: "b.ts", mode: "edit", preview: false }], "b.ts");
+ expect(layout()).toEqual(["*a.ts [b.ts]"]);
+ expect(store().active.w1).toBe(edit("b.ts"));
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/store/codeEditor.split.test.ts b/jarvis/ui/web/frontend/src/store/codeEditor.split.test.ts
deleted file mode 100644
index 5dd0ca8791..0000000000
--- a/jarvis/ui/web/frontend/src/store/codeEditor.split.test.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-import { beforeEach, describe, expect, it } from "vitest";
-
-import { fileKeyOf, tabKeyOf, useCodeEditorStore } from "./codeEditor";
-
-const store = () => useCodeEditorStore.getState();
-const edit = (path: string) => tabKeyOf("edit", fileKeyOf("w1", path));
-
-beforeEach(() => {
- useCodeEditorStore.setState({
- tabs: [],
- active: {},
- files: {},
- visible: false,
- quickOpen: false,
- cursor: null,
- reveal: null,
- closed: [],
- side: {},
- sideFocused: false,
- });
-});
-
-describe("two editors side by side", () => {
- it("opens a file beside the active one and gives it the keyboard", () => {
- store().openFile("w1", "a.ts", { preview: false });
- store().openToSide("w1", "b.ts");
- expect(store().active.w1).toBe(edit("a.ts"));
- expect(store().side.w1).toBe(edit("b.ts"));
- expect(store().sideFocused).toBe(true);
- expect(store().tabs.map((tab) => tab.path)).toEqual(["a.ts", "b.ts"]);
- expect(store().tabs[1].preview).toBe(false);
- });
-
- it("simply opens the file when nothing is open yet", () => {
- store().openToSide("w1", "a.ts");
- expect(store().active.w1).toBe(edit("a.ts"));
- expect(store().side.w1 ?? null).toBeNull();
- expect(store().sideFocused).toBe(false);
- });
-
- it("shows the same file twice when the active file is opened to the side", () => {
- store().openFile("w1", "a.ts", { preview: false });
- store().openToSide("w1", "a.ts");
- expect(store().active.w1).toBe(edit("a.ts"));
- expect(store().side.w1).toBe(edit("a.ts"));
- expect(store().tabs).toHaveLength(1);
- });
-
- it("sends the next opened file to the editor that has the keyboard", () => {
- store().openFile("w1", "a.ts", { preview: false });
- store().openToSide("w1", "b.ts");
- store().openFile("w1", "c.ts");
- expect(store().side.w1).toBe(edit("c.ts"));
- expect(store().active.w1).toBe(edit("a.ts"));
-
- store().focusGroup(false);
- store().openFile("w1", "d.ts", { preview: false });
- expect(store().active.w1).toBe(edit("d.ts"));
- expect(store().side.w1).toBe(edit("c.ts"));
- });
-
- it("never lets a preview replace the tab the other editor shows", () => {
- store().openFile("w1", "a.ts");
- store().openToSide("w1", "b.ts");
- expect(store().tabs.map((tab) => tab.path)).toEqual(["a.ts", "b.ts"]);
- // The first editor still shows its preview tab.
- expect(store().active.w1).toBe(edit("a.ts"));
-
- store().focusGroup(false);
- store().openFile("w1", "c.ts");
- // c replaces the preview a in the first editor, never b on the right.
- expect(store().tabs.map((tab) => tab.path)).toEqual(["c.ts", "b.ts"]);
- expect(store().side.w1).toBe(edit("b.ts"));
- });
-
- it("ends the split when its tab closes, or when one tab would be left twice", () => {
- store().openFile("w1", "a.ts", { preview: false });
- store().openToSide("w1", "b.ts");
- store().closeTab(edit("b.ts"));
- expect(store().side.w1).toBeNull();
- expect(store().active.w1).toBe(edit("a.ts"));
-
- store().openToSide("w1", "b.ts");
- store().closeTab(edit("a.ts"));
- expect(store().active.w1).toBe(edit("b.ts"));
- expect(store().side.w1).toBeNull();
- });
-
- it("closes the split and keeps the tab", () => {
- store().openFile("w1", "a.ts", { preview: false });
- store().openToSide("w1", "b.ts");
- store().closeSide("w1");
- expect(store().side.w1).toBeNull();
- expect(store().sideFocused).toBe(false);
- expect(store().tabs.map((tab) => tab.path)).toEqual(["a.ts", "b.ts"]);
- });
-
- it("gives the keyboard back to the first editor when a tab is clicked", () => {
- store().openFile("w1", "a.ts", { preview: false });
- store().openToSide("w1", "b.ts");
- store().activate(edit("b.ts"));
- expect(store().active.w1).toBe(edit("b.ts"));
- expect(store().sideFocused).toBe(false);
- });
-
- it("steps through the tabs of the editor that has the keyboard", () => {
- store().openFile("w1", "a.ts", { preview: false });
- store().openFile("w1", "b.ts", { preview: false });
- store().openToSide("w1", "c.ts");
- store().cycle("w1", 1);
- expect(store().side.w1).toBe(edit("a.ts"));
- expect(store().active.w1).toBe(edit("b.ts"));
-
- store().focusGroup(false);
- store().cycle("w1", 1);
- expect(store().active.w1).toBe(edit("c.ts"));
- });
-
- it("follows a rename of the file it shows", () => {
- store().openFile("w1", "a.ts", { preview: false });
- store().openToSide("w1", "src/b.ts");
- store().renamePath("w1", "src", "lib");
- expect(store().side.w1).toBe(edit("lib/b.ts"));
- });
-});
diff --git a/jarvis/ui/web/frontend/src/store/codeEditor.ts b/jarvis/ui/web/frontend/src/store/codeEditor.ts
index 046968a734..5fd2368069 100644
--- a/jarvis/ui/web/frontend/src/store/codeEditor.ts
+++ b/jarvis/ui/web/frontend/src/store/codeEditor.ts
@@ -27,6 +27,8 @@ export interface EditorTab {
path: string;
mode: EditorMode;
preview: boolean;
+ /** The editor group (column) the tab sits in; groups stand side by side. */
+ group: number;
}
/** `ready` = editable text; a ViewKind = shown with a viewer; the rest are read-only notices. */
@@ -95,15 +97,35 @@ export interface OpenOptions {
column?: number;
length?: number;
/**
- * true = the second editor, beside the first; false = the first. Omitted =
- * whichever of the two has the keyboard.
+ * Open in the group to the right of the one that has the keyboard, creating
+ * that group when there is none ("Open to the side").
*/
side?: boolean;
+ /** Always a new group, directly to the right of the one that has the keyboard ("Split right"). */
+ split?: boolean;
+ /** Open in this group; omitted = the group that has the keyboard. */
+ group?: number;
}
+/**
+ * How the groups of a workspace are arranged: one group (its id), or a split
+ * whose children stand side by side (`row`) or above each other (`column`).
+ */
+export type EditorLayout = number | { dir: "row" | "column"; children: EditorLayout[] };
+
+/** A side of a group a new group can be put on. */
+export type LayoutSide = "left" | "right" | "top" | "bottom";
+
+/** Where a dragged tab lands. */
+export type TabDrop =
+ /** In a group's tab bar, in front of the tab `before`; at the end when omitted. */
+ | { group: number; before?: string }
+ /** In a new group directly beside an existing one: left or right of it, above or below it. */
+ | { beside: number; side: LayoutSide };
+
interface CodeEditorState {
tabs: EditorTab[];
- /** The active tab per workspace. */
+ /** Per workspace: the tab shown by the group that has the keyboard. */
active: Record<string, string | null>;
files: Record<string, EditorFile>;
/** Whether the editor covers the terminals (tabs stay open when hidden). */
@@ -114,16 +136,20 @@ interface CodeEditorState {
closed: ClosedTab[];
/** Per file: the commit its diff tab compares against, when it is not the last commit. */
diffBases: Record<string, DiffBase>;
- /** Per workspace: the tab shown in a second editor beside the active one; null = one editor. */
- side: Record<string, string | null>;
- /** The second editor has the keyboard: opened files, saves and tab switches go to it. */
- sideFocused: boolean;
- /** Open a file in the second editor, splitting the view when it is not split yet. */
+ /** Per workspace: how the editor groups are laid out; missing = one group. */
+ layout: Record<string, EditorLayout>;
+ /** Per workspace and group: the tab that group shows. */
+ groupActive: Record<string, Record<number, string | null>>;
+ /** Per workspace: the group that has the keyboard; opened files, saves and tab switches go to it. */
+ focusedGroup: Record<string, number>;
+ /** Open a file in the group to the right, splitting the view when there is none. */
openToSide: (workspaceId: string, path: string, options?: OpenOptions) => void;
- /** Back to one editor; the tab stays open. */
- closeSide: (workspaceId: string) => void;
- /** Which of the two editors has the keyboard. */
- focusGroup: (side: boolean) => void;
+ /** Show a tab's file a second time, in a new group to the right of the tab's own. */
+ splitRight: (key: string) => void;
+ /** Hand the keyboard to a group. */
+ focusGroup: (workspaceId: string, group: number) => void;
+ /** Put a dragged tab where it was dropped: a spot in a tab bar, or a new group. */
+ moveTab: (key: string, drop: TabDrop) => void;
openFile: (workspaceId: string, path: string, options?: OpenOptions) => void;
closeTab: (key: string) => void;
closeTabs: (keys: string[]) => void;
@@ -147,7 +173,9 @@ interface CodeEditorState {
}
export const fileKeyOf = (workspaceId: string, path: string) => `${workspaceId}\u0000${path}`;
-export const tabKeyOf = (mode: EditorMode, fileKey: string) => `${mode}:${fileKey}`;
+/** A tab's key; the same file opened in two groups is two tabs. */
+export const tabKeyOf = (mode: EditorMode, fileKey: string, group = 0) =>
+ group === 0 ? `${mode}:${fileKey}` : `g${group}:${mode}:${fileKey}`;
/** True when `path` is `root` itself or lies inside the folder `root`. */
export const isUnder = (path: string, root: string) => path === root || path.startsWith(`${root}/`);
@@ -188,6 +216,114 @@ function successor(own: EditorTab[], key: string, closing: Set<string>): string
return (right ?? left)?.key ?? null;
}
+type GroupState = Pick<CodeEditorState, "tabs" | "layout" | "groupActive" | "focusedGroup">;
+
+/** The ids of a layout's groups, in reading order: left to right, top to bottom. */
+export function leavesOf(layout: EditorLayout): number[] {
+ return typeof layout === "number" ? [layout] : layout.children.flatMap(leavesOf);
+}
+
+/** Drop groups that are gone and collapse splits that are left with one child. */
+function tidy(layout: EditorLayout, alive: ReadonlySet<number>): EditorLayout | null {
+ if (typeof layout === "number") return alive.has(layout) ? layout : null;
+ const children = layout.children
+ .map((child) => tidy(child, alive))
+ .filter((child): child is EditorLayout => child !== null)
+ // A row inside a row is one row.
+ .flatMap((child) => (typeof child !== "number" && child.dir === layout.dir ? child.children : [child]));
+ if (children.length === 0) return null;
+ return children.length === 1 ? children[0] : { dir: layout.dir, children };
+}
+
+/**
+ * The layout for exactly these groups: the remembered one without the groups
+ * that are gone, and any group it does not know yet added on the right.
+ */
+export function layoutFor(stored: EditorLayout | undefined, ids: number[]): EditorLayout {
+ const kept = stored === undefined ? null : tidy(stored, new Set(ids));
+ const placed = new Set(kept === null ? [] : leavesOf(kept));
+ const missing = ids.filter((id) => !placed.has(id)).sort((a, b) => a - b);
+ if (kept === null) return missing.length === 0 ? 0 : missing.length === 1 ? missing[0] : { dir: "row", children: missing };
+ if (missing.length === 0) return kept;
+ return typeof kept !== "number" && kept.dir === "row"
+ ? { dir: "row", children: [...kept.children, ...missing] }
+ : { dir: "row", children: [kept, ...missing] };
+}
+
+/** Put a new group directly beside an existing one. */
+function insertBeside(layout: EditorLayout, target: number, id: number, side: LayoutSide): EditorLayout {
+ const dir = side === "left" || side === "right" ? "row" : "column";
+ const pair = side === "left" || side === "top" ? [id, target] : [target, id];
+ if (typeof layout === "number") return layout === target ? { dir, children: pair } : layout;
+ // Beside a group that already stands in a split of that direction: one more in it.
+ if (layout.dir === dir && layout.children.includes(target)) {
+ return { dir, children: layout.children.flatMap((child) => (child === target ? pair : [child])) };
+ }
+ return { dir: layout.dir, children: layout.children.map((child) => insertBeside(child, target, id, side)) };
+}
+
+/** One column of the editor: its own tabs, one of them shown. */
+export interface EditorGroup {
+ id: number;
+ tabs: EditorTab[];
+ /** The tab the group shows; null only for the single empty group. */
+ active: EditorTab | null;
+ /** This group has the keyboard. */
+ focused: boolean;
+}
+
+/**
+ * The editor groups of one workspace, in reading order.
+ *
+ * Derived from the tabs: a group exists exactly as long as it holds a tab, so
+ * closing its last tab closes the column. With nothing open there is one empty
+ * group.
+ */
+export function groupsOf(state: GroupState, workspaceId: string | null): EditorGroup[] {
+ if (!workspaceId) return [];
+ const byGroup = new Map<number, EditorTab[]>();
+ for (const tab of state.tabs) {
+ if (tab.workspaceId !== workspaceId) continue;
+ const id = tab.group ?? 0;
+ const tabs = byGroup.get(id);
+ if (tabs) tabs.push(tab);
+ else byGroup.set(id, [tab]);
+ }
+ if (byGroup.size === 0) return [{ id: 0, tabs: [], active: null, focused: true }];
+ const order = leavesOf(layoutFor(state.layout[workspaceId], [...byGroup.keys()]));
+ const wanted = state.focusedGroup[workspaceId];
+ const focused = wanted !== undefined && order.includes(wanted) ? wanted : order[0];
+ const actives = state.groupActive[workspaceId] ?? {};
+ return order.map((id) => {
+ const tabs = byGroup.get(id) ?? [];
+ const active = tabs.find((tab) => tab.key === actives[id]) ?? tabs[tabs.length - 1] ?? null;
+ return { id, tabs, active, focused: id === focused };
+ });
+}
+
+/** Bring the group bookkeeping and `active` of these workspaces in line with the tabs. */
+function settle(
+ state: GroupState & Pick<CodeEditorState, "active">,
+ workspaceIds: Iterable<string>,
+): Pick<CodeEditorState, "active" | "layout" | "groupActive" | "focusedGroup"> {
+ const active = { ...state.active };
+ const layout = { ...state.layout };
+ const groupActive = { ...state.groupActive };
+ const focusedGroup = { ...state.focusedGroup };
+ for (const workspaceId of workspaceIds) {
+ const groups = groupsOf(state, workspaceId);
+ const focused = groups.find((group) => group.focused) ?? groups[0];
+ layout[workspaceId] = layoutFor(
+ state.layout[workspaceId],
+ groups.filter((group) => group.tabs.length > 0).map((group) => group.id),
+ );
+ groupActive[workspaceId] = Object.fromEntries(groups.map((group) => [group.id, group.active?.key ?? null]));
+ focusedGroup[workspaceId] = focused.id;
+ active[workspaceId] = focused.active?.key ?? null;
+ }
+ return { active, layout, groupActive, focusedGroup };
+}
+
let revealNonce = 0;
export const useCodeEditorStore = create<CodeEditorState>((set, get) => ({
@@ -200,45 +336,116 @@ export const useCodeEditorStore = create<CodeEditorState>((set, get) => ({
reveal: null,
closed: [],
diffBases: {},
- side: {},
- sideFocused: false,
+ layout: {},
+ groupActive: {},
+ focusedGroup: {},
openToSide: (workspaceId, path, options = {}) => get().openFile(workspaceId, path, { preview: false, ...options, side: true }),
- closeSide: (workspaceId) => set((state) => ({ side: { ...state.side, [workspaceId]: null }, sideFocused: false })),
+ splitRight: (key) => {
+ const tab = get().tabs.find((entry) => entry.key === key);
+ if (!tab) return;
+ get().focusGroup(tab.workspaceId, tab.group ?? 0);
+ // A diff keeps comparing against what it compared against.
+ const base = tab.mode === "diff" ? get().diffBases[tab.fileKey] : undefined;
+ get().openFile(tab.workspaceId, tab.path, { mode: tab.mode, base, preview: false, split: true });
+ },
- focusGroup: (side) => {
- if (get().sideFocused !== side) set({ sideFocused: side });
+ focusGroup: (workspaceId, group) => {
+ const state = get();
+ if (groupsOf(state, workspaceId).find((entry) => entry.focused)?.id === group) return;
+ set(settle({ ...state, focusedGroup: { ...state.focusedGroup, [workspaceId]: group } }, [workspaceId]));
},
+ moveTab: (key, drop) =>
+ set((state) => {
+ const tab = state.tabs.find((entry) => entry.key === key);
+ if (!tab) return {};
+ const { workspaceId } = tab;
+ const groups = groupsOf(state, workspaceId);
+ const origin = tab.group ?? 0;
+ const source = groups.find((entry) => entry.id === origin);
+ const order = groups.map((entry) => entry.id);
+ let layout = layoutFor(state.layout[workspaceId], order);
+ let group: number;
+ let before: string | undefined;
+ if ("beside" in drop) {
+ if (!order.includes(drop.beside)) return {};
+ // A group's only tab dropped beside that same group is already there.
+ if (drop.beside === origin && source?.tabs.length === 1) return {};
+ group = Math.max(...order) + 1;
+ layout = insertBeside(layout, drop.beside, group, drop.side);
+ } else {
+ if (!order.includes(drop.group) || drop.before === key) return {};
+ group = drop.group;
+ before = drop.before;
+ }
+ const movedKey = tabKeyOf(tab.mode, tab.fileKey, group);
+ const rest = state.tabs.filter((entry) => entry.key !== key);
+ let tabs = rest;
+ // The same file already open in that group: the dragged tab closes into it.
+ if (group === origin || !rest.some((entry) => entry.key === movedKey)) {
+ const moved: EditorTab = { ...tab, key: movedKey, group };
+ const inGroup = (entry: EditorTab) => entry.workspaceId === workspaceId && (entry.group ?? 0) === group;
+ let at = before ? rest.findIndex((entry) => entry.key === before && inGroup(entry)) : -1;
+ // No tab to land in front of: after the group's last one.
+ if (at < 0) at = rest.reduce((last, entry, index) => (inGroup(entry) ? index + 1 : last), rest.length);
+ tabs = [...rest.slice(0, at), moved, ...rest.slice(at)];
+ }
+ const actives: Record<number, string | null> = { ...state.groupActive[workspaceId], [group]: movedKey };
+ if (group !== origin && source?.active?.key === key) actives[origin] = successor(source.tabs, key, new Set([key]));
+ return {
+ tabs,
+ ...settle(
+ {
+ ...state,
+ tabs,
+ layout: { ...state.layout, [workspaceId]: layout },
+ groupActive: { ...state.groupActive, [workspaceId]: actives },
+ focusedGroup: { ...state.focusedGroup, [workspaceId]: group },
+ },
+ [workspaceId],
+ ),
+ };
+ }),
+
openFile: (workspaceId, path, options = {}) => {
const mode = options.mode ?? "edit";
const preview = options.preview ?? true;
const fileKey = fileKeyOf(workspaceId, path);
- const key = tabKeyOf(mode, fileKey);
set((state) => {
+ // The group that takes the file: the one named, the one to the right of
+ // the group that has the keyboard ("to the side"), or that group itself.
+ const groups = groupsOf(state, workspaceId);
+ const focused = groups.find((entry) => entry.focused) ?? groups[0];
+ const order = groups.map((entry) => entry.id);
+ let layout = layoutFor(state.layout[workspaceId], order);
+ let group = options.group !== undefined && order.includes(options.group) ? options.group : focused.id;
+ // With nothing open there is nothing to stand beside: the file simply opens.
+ if (options.group === undefined && (options.side || options.split) && focused.tabs.length > 0) {
+ const at = order.indexOf(focused.id);
+ // "To the side" uses the group already standing there; a split never does.
+ const beside = options.split ? undefined : order[at + 1];
+ if (beside !== undefined) group = beside;
+ else {
+ group = Math.max(...order) + 1;
+ layout = insertBeside(layout, focused.id, group, "right");
+ }
+ }
+ const target = groups.find((entry) => entry.id === group);
+ const key = tabKeyOf(mode, fileKey, group);
let tabs = state.tabs;
- // Which of the two editors takes the file. The second one only exists
- // beside a first: with nothing open, the file simply opens.
- const mainKey = state.active[workspaceId] ?? null;
- const sideKey = state.side[workspaceId] ?? null;
- const hasMain = mainKey !== null && tabs.some((tab) => tab.key === mainKey);
- const toSide = hasMain && (options.side ?? (state.sideFocused && sideKey !== null));
- // The tab the other editor shows is never the one a preview replaces.
- const otherKey = toSide ? mainKey : sideKey;
const existing = tabs.find((tab) => tab.key === key);
if (existing) {
if (!preview && existing.preview) tabs = tabs.map((tab) => (tab.key === key ? { ...tab, preview: false } : tab));
} else {
- const tab: EditorTab = { key, fileKey, workspaceId, path, mode, preview };
- const replaced = tabs.find(
- (entry) =>
- entry.workspaceId === workspaceId && entry.preview && entry.key !== otherKey && !state.files[entry.fileKey]?.dirty,
- );
+ const tab: EditorTab = { key, fileKey, workspaceId, path, mode, preview, group };
+ // One preview tab per group: the next open in that group replaces it.
+ const replaced = target?.tabs.find((entry) => entry.preview && !state.files[entry.fileKey]?.dirty);
if (replaced) {
tabs = tabs.map((entry) => (entry.key === replaced.key ? tab : entry));
} else {
- const activeKey = state.active[workspaceId];
+ const activeKey = target?.active?.key;
const at = activeKey ? tabs.findIndex((entry) => entry.key === activeKey) : -1;
tabs = at < 0 ? [...tabs, tab] : [...tabs.slice(0, at + 1), tab, ...tabs.slice(at + 1)];
}
@@ -259,9 +466,16 @@ export const useCodeEditorStore = create<CodeEditorState>((set, get) => ({
return {
tabs,
files: prune(files, tabs),
- active: toSide ? state.active : { ...state.active, [workspaceId]: key },
- side: toSide ? { ...state.side, [workspaceId]: key } : state.side,
- sideFocused: toSide,
+ ...settle(
+ {
+ ...state,
+ tabs,
+ layout: { ...state.layout, [workspaceId]: layout },
+ groupActive: { ...state.groupActive, [workspaceId]: { ...state.groupActive[workspaceId], [group]: key } },
+ focusedGroup: { ...state.focusedGroup, [workspaceId]: group },
+ },
+ [workspaceId],
+ ),
visible: true,
reveal,
diffBases,
@@ -277,41 +491,66 @@ export const useCodeEditorStore = create<CodeEditorState>((set, get) => ({
const gone = state.tabs.filter((tab) => closing.has(tab.key));
if (gone.length === 0) return {};
const tabs = state.tabs.filter((tab) => !closing.has(tab.key));
- const active = { ...state.active };
- const side = { ...state.side };
- for (const workspaceId of new Set(gone.map((tab) => tab.workspaceId))) {
- const current = active[workspaceId];
- if (current && closing.has(current)) {
- active[workspaceId] = successor(state.tabs.filter((tab) => tab.workspaceId === workspaceId), current, closing);
+ const groupActive = { ...state.groupActive };
+ const focusedGroup = { ...state.focusedGroup };
+ const workspaceIds = new Set(gone.map((tab) => tab.workspaceId));
+ for (const workspaceId of workspaceIds) {
+ const groups = groupsOf(state, workspaceId);
+ const actives: Record<number, string | null> = { ...groupActive[workspaceId] };
+ for (const group of groups) {
+ if (group.active && closing.has(group.active.key)) actives[group.id] = successor(group.tabs, group.active.key, closing);
+ }
+ groupActive[workspaceId] = actives;
+ // A group whose last tab closes disappears; the keyboard goes to the
+ // group on its left, else to the one on its right.
+ const survives = (group: EditorGroup) => group.tabs.some((tab) => !closing.has(tab.key));
+ const at = groups.findIndex((group) => group.focused);
+ if (at >= 0 && !survives(groups[at])) {
+ const neighbour = groups.slice(0, at).reverse().find(survives) ?? groups.slice(at + 1).find(survives);
+ if (neighbour) focusedGroup[workspaceId] = neighbour.id;
}
- // The split ends when its tab closes, or when both editors would be
- // left showing the one tab that remains.
- const beside = side[workspaceId];
- if (beside && (closing.has(beside) || (closing.has(current ?? "") && active[workspaceId] === beside))) side[workspaceId] = null;
}
const closed = [...state.closed, ...gone.map(({ workspaceId, path, mode }) => ({ workspaceId, path, mode }))];
- return { tabs, active, side, files: prune(state.files, tabs), closed: closed.slice(-MAX_CLOSED) };
+ return {
+ tabs,
+ files: prune(state.files, tabs),
+ closed: closed.slice(-MAX_CLOSED),
+ ...settle({ ...state, tabs, groupActive, focusedGroup }, workspaceIds),
+ };
}),
- activate: (key) =>
- set((state) => {
- const tab = state.tabs.find((entry) => entry.key === key);
- return tab ? { active: { ...state.active, [tab.workspaceId]: key }, sideFocused: false, visible: true } : {};
- }),
+ // A click on a tab shows it in its group and hands that group the keyboard.
+ activate: (key) => {
+ const tab = get().tabs.find((entry) => entry.key === key);
+ if (!tab) return;
+ const group = tab.group ?? 0;
+ set((state) => ({
+ ...settle(
+ {
+ ...state,
+ groupActive: { ...state.groupActive, [tab.workspaceId]: { ...state.groupActive[tab.workspaceId], [group]: key } },
+ focusedGroup: { ...state.focusedGroup, [tab.workspaceId]: group },
+ },
+ [tab.workspaceId],
+ ),
+ visible: true,
+ }));
+ },
pinTab: (key) =>
set((state) => ({ tabs: state.tabs.map((tab) => (tab.key === key && tab.preview ? { ...tab, preview: false } : tab)) })),
cycle: (workspaceId, step) =>
set((state) => {
- const own = state.tabs.filter((tab) => tab.workspaceId === workspaceId);
- if (own.length === 0) return {};
- // Ctrl+Tab steps through the tabs of the editor that has the keyboard.
- const beside = state.side[workspaceId];
- const inSide = state.sideFocused && own.some((tab) => tab.key === beside);
- const index = own.findIndex((tab) => tab.key === (inSide ? beside : state.active[workspaceId]));
- const next = own[(index + step + own.length) % own.length];
- return inSide ? { side: { ...state.side, [workspaceId]: next.key } } : { active: { ...state.active, [workspaceId]: next.key } };
+ // Ctrl+Tab steps through the tabs of the group that has the keyboard.
+ const group = groupsOf(state, workspaceId).find((entry) => entry.focused);
+ if (!group || group.tabs.length === 0) return {};
+ const index = group.tabs.findIndex((tab) => tab.key === group.active?.key);
+ const next = group.tabs[(index + step + group.tabs.length) % group.tabs.length];
+ return settle(
+ { ...state, groupActive: { ...state.groupActive, [workspaceId]: { ...state.groupActive[workspaceId], [group.id]: next.key } } },
+ [workspaceId],
+ );
}),
reopenClosed: (workspaceId) => {
@@ -346,11 +585,14 @@ export const useCodeEditorStore = create<CodeEditorState>((set, get) => ({
renamePath: (workspaceId, from, to) =>
set((state) => {
const moved = (path: string) => (isUnder(path, from) ? to + path.slice(from.length) : path);
+ const rekeyed = new Map<string, string>();
const tabs = state.tabs.map((tab) => {
if (tab.workspaceId !== workspaceId || !isUnder(tab.path, from)) return tab;
const path = moved(tab.path);
const fileKey = fileKeyOf(workspaceId, path);
- return { ...tab, path, fileKey, key: tabKeyOf(tab.mode, fileKey) };
+ const key = tabKeyOf(tab.mode, fileKey, tab.group ?? 0);
+ rekeyed.set(tab.key, key);
+ return { ...tab, path, fileKey, key };
});
const files: Record<string, EditorFile> = {};
for (const [key, file] of Object.entries(state.files)) {
@@ -360,39 +602,50 @@ export const useCodeEditorStore = create<CodeEditorState>((set, get) => ({
files[fileKeyOf(workspaceId, path)] = { ...file, path };
}
}
- const activeKey = state.active[workspaceId];
- const activeTab = activeKey ? state.tabs.findIndex((tab) => tab.key === activeKey) : -1;
- const sideKey = state.side[workspaceId];
- const sideTab = sideKey ? state.tabs.findIndex((tab) => tab.key === sideKey) : -1;
+ // Each group keeps showing the tab it showed, under its new key.
+ const actives: Record<number, string | null> = {};
+ for (const group of groupsOf(state, workspaceId)) {
+ const key = group.active?.key ?? null;
+ actives[group.id] = key ? (rekeyed.get(key) ?? key) : null;
+ }
return {
tabs,
files,
- side: { ...state.side, [workspaceId]: sideTab >= 0 ? tabs[sideTab].key : null },
- active: { ...state.active, [workspaceId]: activeTab >= 0 ? tabs[activeTab].key : (activeKey ?? null) },
+ ...settle({ ...state, tabs, groupActive: { ...state.groupActive, [workspaceId]: actives } }, [workspaceId]),
};
}),
restoreTabs: (workspaceId, restored, activePath) =>
set((state) => {
+ // Restored tabs go into the first group; a split is not remembered.
+ const first = groupsOf(state, workspaceId)[0];
+ const group = first.id;
const known = new Set(state.tabs.map((tab) => tab.key));
const files = { ...state.files };
const added: EditorTab[] = [];
for (const entry of restored) {
const fileKey = fileKeyOf(workspaceId, entry.path);
- const key = tabKeyOf(entry.mode, fileKey);
+ const key = tabKeyOf(entry.mode, fileKey, group);
if (known.has(key)) continue;
known.add(key);
- added.push({ key, fileKey, workspaceId, path: entry.path, mode: entry.mode, preview: entry.preview });
+ added.push({ key, fileKey, workspaceId, path: entry.path, mode: entry.mode, preview: entry.preview, group });
files[fileKey] ??= newFile(workspaceId, entry.path);
}
if (added.length === 0) return {};
const tabs = [...state.tabs, ...added];
const activeKey =
- state.active[workspaceId] ??
+ first.active?.key ??
added.find((tab) => tab.path === activePath && tab.mode === "edit")?.key ??
added.find((tab) => tab.path === activePath)?.key ??
added[0].key;
- return { tabs, files, active: { ...state.active, [workspaceId]: activeKey } };
+ return {
+ tabs,
+ files,
+ ...settle(
+ { ...state, tabs, groupActive: { ...state.groupActive, [workspaceId]: { ...state.groupActive[workspaceId], [group]: activeKey } } },
+ [workspaceId],
+ ),
+ };
}),
markDeleted: (workspaceId, path) =>
@@ -405,7 +658,7 @@ export const useCodeEditorStore = create<CodeEditorState>((set, get) => ({
}),
}));
-/** The tabs of one workspace, in order. */
+/** The tabs of one workspace, every group's, in order. */
export function tabsOf(state: Pick<CodeEditorState, "tabs">, workspaceId: string | null): EditorTab[] {
return workspaceId ? state.tabs.filter((tab) => tab.workspaceId === workspaceId) : [];
}