Resize panes and drag tabs into panes

- A divider between two panes changes their sizes, with the pointer or the keyboard. A double-click gives equal sizes.
- A tab that the user drags from the tab bar to a pane replaces its content, or opens a new pane on its right or bottom side.
- The file tree menu has "Open to the right", also for PDF files and boards.
- "New tab to the right" and "New tab below" of a browser tab open a new tab with the home page beside it. They replace "Split right" and "Split down".
- New smoke test: a PDF file beside a note.
This commit is contained in:
Knotty Wyvern
2026-11-10 12:24:17 -07:00
parent 190e5bf1bc
commit 42e18b4620
15 changed files with 555 additions and 63 deletions
+4 -3
View File
@@ -47,9 +47,10 @@ export async function activate(api: PluginApi) {
const id = `tab-${crypto.randomUUID()}`;
const saved: SavedView = { view: id, profileId, url, runtimeId: '' };
const run = (command: string, args?: Record<string, unknown>) => { void saved.control?.action(command, args); };
// A new tab with the home page of the profile opens in a pane beside this tab.
const split = (direction: 'right' | 'down') => {
const current = get(state)?.tabs.find(tab => tab.id === saved.runtimeId);
void open(current?.profileId || saved.profileId, current?.url || saved.url || 'about:blank', { split: direction, relativeTo: id });
void open(current?.profileId || saved.profileId, undefined, { split: direction, relativeTo: id });
};
api.registerView({ id, title: 'Browser', placement: 'editor', icon: 'globe', pinned, launcher: false,
tabDragData: ({ pinned }) => {
@@ -65,8 +66,8 @@ export async function activate(api: PluginApi) {
return [
{ separator: true },
{ label: tr("Move to new window"), icon: 'external', disabled: !ready, run: () => run('moveToWindow', { pinned }) },
{ label: tr("Split right"), icon: 'split-right', disabled: !ready, run: () => split('right') },
{ label: tr("Split down"), icon: 'split-down', disabled: !ready, run: () => split('down') },
{ label: tr("New tab to the right"), icon: 'split-right', disabled: !ready, run: () => split('right') },
{ label: tr("New tab below"), icon: 'split-down', disabled: !ready, run: () => split('down') },
{ separator: true },
{ label: tr("Find…"), icon: 'search', shortcut: keys('Mod+F'), disabled: !ready, run: () => { api.openView(id); void saved.control?.find(); } },
{ label: tr("Open in default browser"), icon: 'external', disabled: !web, run: () => run('openExternal') },
+6 -2
View File
@@ -3300,8 +3300,12 @@ export const messageRows: [string, string, string, string][] = [
["The workspace changed. File moves stopped.", "L’espace de travail a changé. Les déplacements de fichiers sont arrêtés.", "ワークスペースが変更されました。ファイルの移動を停止しました。", "工作区已更改。文件移动已停止。"],
["The workspace changed. Paste stopped.", "L’espace de travail a changé. Le collage est arrêté.", "ワークスペースが変更されました。貼り付けを停止しました。", "工作区已更改。粘贴已停止。"],
["Move to new window", "Déplacer vers une nouvelle fenêtre", "新しいウィンドウに移動", "移到新窗口"],
["Split right", "Scinder à droite", "右に分割", "向右拆分"],
["Split down", "Scinder vers le bas", "下に分割", "向下拆分"],
["New tab to the right", "Nouvel onglet à droite", "右に新しいタブ", "在右侧新建标签页"],
["New tab below", "Nouvel onglet en dessous", "下に新しいタブ", "在下方新建标签页"],
["Resize panes", "Redimensionner les volets", "ペインのサイズを変更", "调整窗格大小"],
["Drag to resize the panes. Double-click to give them equal sizes.", "Faites glisser pour redimensionner les volets. Double-cliquez pour leur donner la même taille.", "ドラッグしてペインのサイズを変更します。ダブルクリックすると同じサイズになります。", "拖动以调整窗格大小。双击使窗格大小相同。"],
["Show here", "Afficher ici", "ここに表示", "在此显示"],
["Open below", "Ouvrir en dessous", "下に開く", "在下方打开"],
["Find…", "Rechercher…", "検索…", "查找…"],
["Open in default browser", "Ouvrir dans le navigateur par défaut", "既定のブラウザーで開く", "在默认浏览器中打开"],
["Invalid browser tab transfer.", "Transfert d’onglet de navigateur non valide.", "ブラウザータブの移動が無効です。", "浏览器标签页转移无效。"],
+121 -16
View File
@@ -1,7 +1,8 @@
<script lang="ts">
// The document area: the panes of documents and plugin editor views, with the save conflict banner of each document.
// A plugin view stays in the plugin layer above the document panes, so that a move between panes does not mount it again.
// Over the whole area, the layer shows the focused plugin view and its plugin split. In a pane, the view covers its pane.
// Without a pane, the layer shows the focused plugin view over the whole area. In a pane, the view covers its pane.
// A divider between two panes changes the ratio of their split. A tab that the user drags over the area shows a drop hint.
import type { ComponentProps } from "svelte";
import { t } from "$lib/i18n";
import PluginEditor from "$lib/plugins/PluginEditor.svelte";
@@ -11,19 +12,21 @@
import EditorPane from "./EditorPane.svelte";
import Icon from "$lib/ui/Icon.svelte";
import IconButton from "$lib/ui/IconButton.svelte";
import { paneBounds, stackLayout, type SplitLayout } from "$lib/workspace/splitLayout";
import { paneBounds, splitDividers, stackLayout, type SplitDivider, type SplitLayout, type SplitPath } from "$lib/workspace/splitLayout";
import type { PaneDrop } from "$lib/workspace/documentPanes";
import { attachTooltip } from "$lib/ui/tooltip";
import type { ViewMode } from "./ViewModes.svelte";
import TabBar from "./TabBar.svelte";
type EditorProps = ComponentProps<typeof EditorPane>;
type DocumentView = { id: string; reading: boolean; split: boolean; buffer: OpenBuffer | null; pluginKey: string | null };
type Bounds = { left: number; top: number; width: number; height: number };
/** The pane under a dragged tab, and the place of the drop on it. */
type DropTarget = { pane: string; zone: PaneDrop };
type Props = {
/** The focused plugin view covers the whole area. */
pluginCover: boolean;
split: boolean;
pluginBounds: Record<string, Bounds | undefined>;
tabBar: ComponentProps<typeof TabBar>;
/** The drop hint of a dragged tab. */
drop: DropTarget | null;
onResize: (path: SplitPath, ratio: number) => void;
pluginPaneComponents: Record<string, PluginEditor | undefined>;
documentViews: DocumentView[];
layout: SplitLayout;
@@ -52,7 +55,7 @@
onCursor: (pane: DocumentView, line: number, column: number) => void;
onOpenLink: (pane: DocumentView, kind: "md" | "wiki", target: string) => void;
};
let { pluginCover, split, pluginBounds, tabBar, pluginPaneComponents = $bindable(), documentViews, layout, activePane, paneComponents = $bindable(),
let { pluginCover, drop, onResize, pluginPaneComponents = $bindable(), documentViews, layout, activePane, paneComponents = $bindable(),
documents, tabs, hasWorkspace, browserOpening, focusLine, onFocusPane, onCloseSplit, onSaveCopy, onOpenWorkspace, onNewFile, onNewNote,
onQuickOpen, onOpenBrowser, onChange, onInsertImage, onRenameTitle, tableActions, linkActions, onView, onSplitView, onCursor, onOpenLink }: Props = $props();
@@ -66,9 +69,85 @@
if (host) onFocusPane(host);
else if ($pluginView?.key !== view.key) selectPluginEditor(view);
}
let area: HTMLElement;
const full = { left: 0, top: 0, width: 100, height: 100 };
const dividers = $derived(pluginCover || !several ? [] : splitDividers(stacked ? stackLayout(layout) : layout));
/** The place of the divider: the line between the two sides of its split, in percent of the area. */
function dividerStyle(divider: SplitDivider) {
const { bounds: box, ratio } = divider;
return divider.direction === "right"
? `left:${box.left + box.width * ratio}%;top:${box.top}%;height:${box.height}%`
: `top:${box.top + box.height * ratio}%;left:${box.left}%;width:${box.width}%`;
}
function ratioAt(divider: SplitDivider, x: number, y: number) {
const rect = area.getBoundingClientRect(), box = divider.bounds;
return divider.direction === "right"
? (x - rect.left - rect.width * box.left / 100) / (rect.width * box.width / 100)
: (y - rect.top - rect.height * box.top / 100) / (rect.height * box.height / 100);
}
let resizing = $state<"right" | "down" | null>(null);
function startResize(event: PointerEvent, divider: SplitDivider) {
if (event.button !== 0) return;
event.preventDefault();
const handle = event.currentTarget as HTMLElement;
handle.setPointerCapture(event.pointerId);
handle.focus({ preventScroll: true });
resizing = divider.direction;
const move = (next: PointerEvent) => onResize(divider.path, ratioAt(divider, next.clientX, next.clientY));
const end = () => {
resizing = null;
handle.removeEventListener("pointermove", move);
handle.removeEventListener("pointerup", end);
handle.removeEventListener("pointercancel", end);
};
handle.addEventListener("pointermove", move);
handle.addEventListener("pointerup", end);
handle.addEventListener("pointercancel", end);
}
function resizeKey(event: KeyboardEvent, divider: SplitDivider) {
const steps: Record<string, number> = divider.direction === "right" ? { ArrowLeft: -0.05, ArrowRight: 0.05 } : { ArrowUp: -0.05, ArrowDown: 0.05 };
if (event.key in steps) onResize(divider.path, divider.ratio + steps[event.key]);
else if (event.key === "Home") onResize(divider.path, 0.1);
else if (event.key === "End") onResize(divider.path, 0.9);
else if (event.key === "Enter") onResize(divider.path, 0.5);
else return;
event.preventDefault();
}
function tooltip(node: HTMLElement, text: string) {
let label = text;
const dispose = attachTooltip(node, () => label);
return { update(value: string) { label = value; }, destroy: dispose };
}
/**
* The drop target under a point: a pane, and the place on it. The right and bottom sides open a new pane.
* While a plugin view covers the area, the area is one pane. A narrow area opens new panes only below.
*/
export function dropAt(x: number, y: number): DropTarget | null {
const rect = area?.getBoundingClientRect();
if (!rect || !rect.width || !rect.height || x < rect.left || x > rect.right || y < rect.top || y > rect.bottom) return null;
const px = (x - rect.left) / rect.width * 100, py = (y - rect.top) / rect.height * 100;
const pane = pluginCover ? activePane : documentViews.find(view => {
const box = bounds[view.id];
return box && px >= box.left && px <= box.left + box.width && py >= box.top && py <= box.top + box.height;
})?.id;
const box = pane ? (pluginCover ? full : bounds[pane]) : undefined;
if (!pane || !box) return null;
const rx = (px - box.left) / box.width, ry = (py - box.top) / box.height;
return { pane, zone: rx > 0.7 && !stacked ? "right" : ry > 0.7 ? "down" : "center" };
}
const dropBox = $derived.by(() => {
if (!drop) return null;
const box = pluginCover ? full : bounds[drop.pane];
if (!box) return null;
if (drop.zone === "right") return { ...box, left: box.left + box.width / 2, width: box.width / 2 };
if (drop.zone === "down") return { ...box, top: box.top + box.height / 2, height: box.height / 2 };
return box;
});
</script>
<main class="center" bind:clientWidth={width}>
<main class="center" class:resizing={!!resizing} class:resizing-down={resizing === "down"} bind:this={area} bind:clientWidth={width}>
<div class="editor-host" class:plugin-covered={pluginCover}>
<div class="document-panes" class:split={several}>
{#each documentViews as pane (pane.id)}
@@ -130,9 +209,9 @@
<div class="plugin-panes">
{#each $pluginEditors as view (view.key)}
{@const host = pluginCover ? undefined : hosts.get(view.key)}
{@const box = pluginCover ? pluginBounds[view.key] : host ? bounds[host] : undefined}
{@const box = pluginCover ? ($pluginView?.key === view.key ? full : undefined) : host ? bounds[host] : undefined}
<!-- svelte-ignore a11y_no_static_element_interactions (Focus selects the pane that owns the input.) -->
<div class="plugin-pane" class:inactive={!box} class:split={pluginCover && split} class:embedded={!!host}
<div class="plugin-pane" class:inactive={!box} class:embedded={!!host}
class:focused={host ? activePane === host : $pluginView?.key === view.key}
class:edge-left={!!host && (box?.left ?? 0) > 0} class:edge-top={!!host && (box?.top ?? 0) > 0}
data-plugin-pane={view.key}
@@ -140,9 +219,7 @@
style:width={`${box?.width ?? 100}%`} style:height={`${box?.height ?? 100}%`}
onfocusin={() => focusPlugin(view, host)}
onpointerdowncapture={() => focusPlugin(view, host)}>
{#if pluginCover && split && box}
<TabBar {...tabBar} tabs={tabBar.tabs.filter(tab => tab.id === view.key)} />
{:else if host && several}
{#if host && several}
<div class="pane-bar">
<span class="pane-title" title={view.title}>{view.title}</span>
<IconButton icon="close" label={$t("Close split")} onclick={() => onCloseSplit(host)} />
@@ -152,6 +229,22 @@
</div>
{/each}
</div>
{#each dividers as divider (divider.path.join("/"))}
<!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions (A focusable separator is the splitter pattern.) -->
<div class="divider" class:vertical={divider.direction === "right"} style={dividerStyle(divider)}
role="separator" tabindex="0" aria-label={$t("Resize panes")}
aria-orientation={divider.direction === "right" ? "vertical" : "horizontal"}
aria-valuemin={10} aria-valuemax={90} aria-valuenow={Math.round(divider.ratio * 100)}
use:tooltip={$t("Drag to resize the panes. Double-click to give them equal sizes.")}
onpointerdown={event => startResize(event, divider)}
ondblclick={() => onResize(divider.path, 0.5)}
onkeydown={event => resizeKey(event, divider)}></div>
{/each}
{#if dropBox && drop}
<div class="drop-hint" data-drop-zone={drop.zone} style:left={`${dropBox.left}%`} style:top={`${dropBox.top}%`} style:width={`${dropBox.width}%`} style:height={`${dropBox.height}%`}>
<span>{drop.zone === "center" ? $t("Show here") : drop.zone === "right" ? $t("Open to the right") : $t("Open below")}</span>
</div>
{/if}
</main>
<style>
@@ -197,11 +290,23 @@
.plugin-panes { position: absolute; inset: 0; overflow: hidden; pointer-events: none; }
.plugin-pane { position: absolute; display: flex; flex-direction: column; min-width: 0; min-height: 0; box-sizing: border-box; pointer-events: auto; }
.plugin-pane.embedded { background: var(--rs-bg); }
.plugin-pane.split { border: 1px solid var(--rs-border); }
.plugin-pane.split.focused { border-color: var(--rs-accent); }
.plugin-pane.inactive { display: none; }
/* The bar of a plugin view in a pane matches the chrome bar of a document pane. */
.pane-bar { display: flex; align-items: center; gap: 8px; min-height: 34px; flex: 0 0 auto; padding: 0 10px; background: var(--rs-bg); border-bottom: 1px solid var(--rs-border); color: var(--rs-text-dim); }
.plugin-pane.focused .pane-bar { background: var(--rs-bg-active); }
.pane-title { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
/* A divider is a wide, invisible target over the border between two panes. It shows the accent color on hover and focus. */
.divider { position: absolute; z-index: 3; height: 8px; margin-top: -4px; cursor: row-resize; touch-action: none; }
.divider.vertical { width: 8px; margin-top: 0; margin-left: -4px; cursor: col-resize; }
.divider::after { content: ""; position: absolute; inset: 3px 0; border-radius: 1px; }
.divider.vertical::after { inset: 0 3px; }
.divider:hover::after, .divider:focus-visible::after, .center.resizing .divider:focus::after { background: var(--rs-accent); }
.divider:focus-visible { outline: none; }
.center.resizing { cursor: col-resize; user-select: none; }
.center.resizing-down { cursor: row-resize; }
.center.resizing .document-panes, .center.resizing .plugin-pane { pointer-events: none; }
/* The drop hint shows where a dragged tab goes. */
.drop-hint { position: absolute; z-index: 4; box-sizing: border-box; display: flex; align-items: center; justify-content: center; pointer-events: none;
border: 2px solid var(--rs-accent); border-radius: var(--rs-control-radius); background: color-mix(in srgb, var(--rs-accent) 16%, transparent); }
.drop-hint span { padding: 4px 10px; border-radius: var(--rs-control-radius); background: var(--rs-accent); color: var(--rs-on-accent); font-weight: 600; }
</style>
+4
View File
@@ -43,6 +43,8 @@
workspaceRoot: string;
activePath: string | null;
onOpenFile: (entry: TreeEntry, newTab?: boolean) => void;
/** Open the file in a new pane to the right of the active pane. */
onOpenRight?: (entry: TreeEntry) => void;
session: WorkspaceSession;
onStatus?: (message: string) => void;
onCreated?: (entry: TreeEntry) => void;
@@ -56,6 +58,7 @@
workspaceRoot,
activePath,
onOpenFile,
onOpenRight,
session,
onStatus,
onCreated,
@@ -878,6 +881,7 @@
...(!multiple && entry.kind === "folder" ? [...paneMenuItems(entry.rel_path), { kind: "sep" as const }] : []),
...(!multiple && entry.kind === "file" ? [
{ kind: "action" as const, label: $t("Open in new tab"), icon: "tab" as const, run: () => onOpenFile(entry, true) },
...(onOpenRight ? [{ kind: "action" as const, label: $t("Open to the right"), icon: "split-right" as const, run: () => onOpenRight(entry) }] : []),
{ kind: "action" as const, label: $t("Open in default app"), icon: "external" as const, run: () => { void workspaceOpenDefault(entry.rel_path).catch(reason => error = String(reason)); } },
] : []),
terminalItem(parent),
+3 -1
View File
@@ -29,13 +29,14 @@
onHelp: () => void;
onSettings: () => void;
onOpenFile: (entry: TreeEntry, line?: number, target?: "current" | "new") => void;
onOpenRight?: (entry: TreeEntry) => void;
onCreated: (entry: TreeEntry) => void;
onSaveTemplate: (entry: TreeEntry) => void;
onManageTemplates: () => void;
onStatus: (message: string) => void;
};
let { workspace, session, leftView, keysActive, showInternal, activePath, searchRequest, fileTree = $bindable(), workspaceAnchor = $bindable(),
onOpenFile, onCreated, onSaveTemplate, onManageTemplates, onStatus, onChooseWorkspace, onHelp, onSettings }: Props = $props();
onOpenFile, onOpenRight, onCreated, onSaveTemplate, onManageTemplates, onStatus, onChooseWorkspace, onHelp, onSettings }: Props = $props();
function tooltip(node: HTMLElement, text: string) {
let current = text;
@@ -63,6 +64,7 @@
{onManageTemplates}
{activePath}
onOpenFile={(entry, newTab) => onOpenFile(entry, undefined, newTab ? "new" : "current")}
{onOpenRight}
{session}
{keysActive}
{onCreated}
+42 -3
View File
@@ -27,9 +27,14 @@
tabDragData?: (tab: WorkbenchTab) => string | undefined;
onDropTab?: (data: string, index: number) => void;
onDetach?: (tab: WorkbenchTab) => void;
/** A tab drag outside the tab bar. The result tells whether the point can take the tab, for example a document pane. */
onDragAt?: (relPath: string, x: number, y: number) => boolean;
/** A tab drop outside the tab bar. The result tells whether the drop used the tab. */
onDropAt?: (relPath: string, x: number, y: number) => boolean;
onDragEnd?: () => void;
};
let { tabs, activePath, onSelect, onClose, onMove, onCloseTabs, onPin, fileActions, tabActions = () => [], tabDragData = () => undefined, onDropTab, onDetach }: Props = $props();
let { tabs, activePath, onSelect, onClose, onMove, onCloseTabs, onPin, fileActions, tabActions = () => [], tabDragData = () => undefined, onDropTab, onDetach, onDragAt, onDropAt, onDragEnd }: Props = $props();
const transferType = "application/x-runestone-tab";
let bar: HTMLDivElement;
let dragged = $state<string | null>(null);
@@ -61,6 +66,34 @@
suppressClick = true;
event.dataTransfer.effectAllowed = "move";
event.dataTransfer.setData(transferType, data);
watchAreaDrop(tab.relPath);
}
// A tab that leaves the tab bar can go to a pane of the document area. The listeners run first, in the capture
// phase, so that an editor under the pointer does not take the drop.
let stopAreaDrop = () => {};
function watchAreaDrop(path: string) {
stopAreaDrop();
if (!onDragAt || !onDropAt) return;
const inBar = (event: DragEvent) => event.target instanceof Node && bar.contains(event.target);
const over = (event: DragEvent) => {
if (inBar(event) || !onDragAt?.(path, event.clientX, event.clientY)) return;
event.preventDefault(); event.stopPropagation();
if (event.dataTransfer) event.dataTransfer.dropEffect = "move";
};
const drop = (event: DragEvent) => {
if (inBar(event) || !onDropAt?.(path, event.clientX, event.clientY)) return;
event.preventDefault(); event.stopPropagation();
finishTabTransfer();
};
window.addEventListener("dragover", over, true);
window.addEventListener("drop", drop, true);
stopAreaDrop = () => {
window.removeEventListener("dragover", over, true);
window.removeEventListener("drop", drop, true);
stopAreaDrop = () => {};
onDragEnd?.();
};
}
function transferIndex(x: number) {
@@ -85,6 +118,7 @@
}
function finishTabTransfer() {
stopAreaDrop();
dragged = dropBefore = dropAfter = null; receiving = false; suppressClick = false;
cancelAnimationFrame(transferFrame); transferFrame = 0;
}
@@ -289,6 +323,7 @@
frame = requestAnimationFrame(scroll);
};
const clean = () => {
if (started) onDragEnd?.();
if (pointerTarget.hasPointerCapture(pointerId)) pointerTarget.releasePointerCapture(pointerId);
cancelAnimationFrame(frame);
dragged = dropBefore = dropAfter = null;
@@ -306,15 +341,19 @@
e.preventDefault();
if (!started) { started = true; suppressClick = true; dragged = path; frame = requestAnimationFrame(scroll); }
update();
if (destination === null) onDragAt?.(path, x, y);
else onDragEnd?.();
};
const onUp = (e: PointerEvent) => {
if (e.pointerId !== pointerId) return;
x = e.clientX; y = e.clientY;
if (started) update();
const target = destination;
const wasStarted = started;
clean();
if (started && target !== null) void move(path, target);
else if (started && (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight)) {
if (wasStarted && target !== null) void move(path, target);
else if (wasStarted && onDropAt?.(path, x, y)) return;
else if (wasStarted && (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight)) {
const tab = tabs.find(tab => tab.relPath === path);
if (tab) onDetach?.(tab);
}
+70 -15
View File
@@ -13,7 +13,7 @@
import { WorkspaceSession } from "$lib/workspace/session.svelte";
import { retainEditorStates } from "$lib/editor/editorStates";
import { initialDocumentPanes, syncDocumentPanes, splitDocumentPane, closeDocumentPane, selectPane, readDocumentPane, splitDocumentView,
paneOf, showInActivePane, splitWithContent, releaseSolePlugin, type PaneContent } from "$lib/workspace/documentPanes";
paneOf, showInActivePane, splitWithContent, releaseSolePlugin, dropInPane, resizeDocumentPanes, type PaneContent, type PaneDrop, type DocumentPanes } from "$lib/workspace/documentPanes";
import type { ViewMode } from "./ViewModes.svelte";
import { selectedEditorText } from "$lib/editor/selection";
import { pluginHost } from "$lib/plugins/registry";
@@ -267,29 +267,47 @@
document.querySelector<HTMLElement>(`[data-document-pane="${paneId}"]`)?.scrollIntoView({ block: "nearest", inline: "nearest" });
});
}
function closeSplit(paneId: string) {
const released = releaseSolePlugin(closeDocumentPane(documentPanes, paneId));
/** Use a new pane state and focus its active pane. The last pane does not keep a plugin view. The view covers the area again. */
function changePanes(next: DocumentPanes) {
const released = releaseSolePlugin(next);
documentPanes = released.state;
// The last pane does not keep a plugin view. The view covers the area again.
const view = $pluginEditors.find(view => view.key === released.pluginKey);
if (view) {
selectPluginEditor(view);
void tick().then(() => pluginPaneComponents[view.key]?.focus());
} else focusDocumentPane(documentPanes.active, true);
}
function closeSplit(paneId: string) {
changePanes(closeDocumentPane(documentPanes, paneId));
}
/** The plugin view that covers the document area moves into the active pane, so that a new pane can open beside it. */
function keepCoverInPane() {
if (coverKey) documentPanes = showInActivePane(documentPanes, { pluginKey: coverKey });
}
/** A plugin document that opens to the right, for example a PDF file: the source pane, and the plugin view that covers the area. */
let rightOf: { pane: string; cover: string | null } | null = null;
async function openToRight(file: TreeEntry, sourcePane: string) {
const current = documents;
const covered = sourcePane === documentPanes.active ? coverKey : null;
const source = documentPanes.panes.find(pane => pane.id === sourcePane);
if (!current || switching || !source) return;
const unchanged = () => {
const now = documentPanes.panes.find(pane => pane.id === sourcePane);
return documents === current && !switching && documentPanes.active === sourcePane && coverKey === covered
&& now?.documentId === source.documentId && now?.pluginKey === source.pluginKey;
};
const open = current.buffers.find(tab => tab.relPath === file.rel_path);
if (!(open && open.contents !== open.saved)) {
// The placement effect opens the plugin view in a new pane beside the source pane.
rightOf = { pane: sourcePane, cover: covered };
try {
const opened = await openPluginDocument(file.rel_path, unchanged);
await tick();
if (opened) return;
} finally { rightOf = null; }
}
await current.open(file, "background");
const now = documentPanes.panes.find(pane => pane.id === sourcePane);
if (documents !== current || switching || documentPanes.active !== sourcePane || coverKey !== covered
|| now?.documentId !== source.documentId || now?.pluginKey !== source.pluginKey) return;
if (!unchanged()) return;
const target = current.buffers.find(tab => tab.relPath === file.rel_path);
if (!target) return;
keepCoverInPane();
@@ -311,8 +329,36 @@
documentPanes = splitWithContent(documentPanes, documentPanes.active, tabContent(tab), crypto.randomUUID());
focusDocumentPane(documentPanes.active, true);
}
// A tab that the user drags from the tab bar to the document area: the pane and the place of the drop.
let documentArea: DocumentArea | undefined = $state();
let tabDrop = $state<{ pane: string; zone: PaneDrop } | null>(null);
function tabDropTarget(path: string, x: number, y: number) {
const tab = workingTabs.find(tab => tab.relPath === path);
const target = tab && !switching ? documentArea?.dropAt(x, y) ?? null : null;
if (!tab || !target) return null;
// A drop on the pane that shows the tab changes nothing.
if (coverKey ? "plugin" in tab && tab.plugin.key === coverKey : paneOf(documentPanes, tabContent(tab))?.id === target.pane) return null;
return { tab, target };
}
function tabDragAt(path: string, x: number, y: number) {
tabDrop = tabDropTarget(path, x, y)?.target ?? null;
return tabDrop !== null;
}
function tabDropAt(path: string, x: number, y: number) {
const found = tabDropTarget(path, x, y);
tabDrop = null;
if (!found) return false;
const { tab, target } = found;
if (coverKey) {
if (target.zone === "center") { selectWorkingTab(tab.relPath); return true; }
keepCoverInPane();
}
changePanes(dropInPane(documentPanes, tabContent(tab), target.pane, target.zone, crypto.randomUUID()));
return true;
}
// Each focused plugin view that is not in a pane gets a pane when the area has several panes.
// A new view that a plugin opens beside its own view, for example a browser tab, opens beside the pane of that view.
// When the own view covers the area, it moves into the pane first.
const placedPlugins = new Set<string>();
$effect(() => {
const view = $pluginEditorActive && $pluginView?.placement === "editor" ? $pluginView : null;
@@ -323,9 +369,19 @@
placedPlugins.add(view.key);
const shown = paneOf(documentPanes, { pluginKey: view.key });
if (shown) { documentPanes = selectPane(documentPanes, shown.id); return; }
if (documentPanes.panes.length < 2) return;
const right = rightOf;
if (right && documentPanes.panes.some(pane => pane.id === right.pane)) {
rightOf = null;
if (right.cover && right.cover !== view.key && !paneOf(documentPanes, { pluginKey: right.cover }))
documentPanes = showInActivePane(selectPane(documentPanes, right.pane), { pluginKey: right.cover });
documentPanes = splitWithContent(documentPanes, right.pane, { pluginKey: view.key }, crypto.randomUUID());
return;
}
const group = fresh ? splits.find(tree => containsPane(tree, view.key)) : undefined;
const beside = group ? splitSibling(group, view.key) : null;
if (documentPanes.panes.length < 2 && !beside) return;
if (beside && documentPanes.panes.length < 2 && !paneOf(documentPanes, { pluginKey: beside.sibling }))
documentPanes = showInActivePane(documentPanes, { pluginKey: beside.sibling });
const source = beside ? paneOf(documentPanes, { pluginKey: beside.sibling }) : undefined;
documentPanes = source && beside
? splitWithContent(documentPanes, source.id, { pluginKey: view.key }, crypto.randomUUID(), beside.direction)
@@ -438,9 +494,7 @@
} catch (reason) { error = String(reason); }
}
const activeTabPath = $derived(editorPluginVisible && $pluginView ? `plugin:${$pluginView.key}` : activePath);
const activeSplit = $derived($pluginSplits.find(tree => $pluginView && containsPane(tree, $pluginView.key)));
const pluginBounds = $derived(activeSplit ? paneBounds(activeSplit) : $pluginView ? paneBounds($pluginView.key) : {});
// The working tabs, for the header and for the tab bar of each plugin pane in a split.
// The working tabs of the header.
const tabBarProps = $derived({ tabs: workingTabs, activePath: activeTabPath, onSelect: selectWorkingTab, onClose: closeTab,
onCloseTabs: (path: string, scope: TabCloseScope) => void closeTabs(path, scope), onPin: pinWorkingTab, fileActions: workingTabFileActions,
tabActions: workingTabActions, onMove: moveWorkingTab, tabDragData: workingTabDragData, onDropTab: (data: string, index: number) => void receiveTab(data, index) });
@@ -1399,7 +1453,7 @@
{leftView}
{sidebarNavigation}
onSelectLeft={selectLeft}
tabBar={{ ...tabBarProps, onDetach: (tab) => { void detachTab(tab); } }}
tabBar={{ ...tabBarProps, onDetach: (tab) => { void detachTab(tab); }, onDragAt: tabDragAt, onDropAt: tabDropAt, onDragEnd: () => { tabDrop = null; } }}
onNewTab={newTab}
canOpenBrowser={!!browserContribution?.newTab}
{browserOpening}
@@ -1429,6 +1483,7 @@
activePath={editorPluginVisible ? $pluginView?.document?.path ?? null : activePath}
{searchRequest}
onOpenFile={(entry, line, target) => void openFile(entry, line, target)}
onOpenRight={(entry) => void openToRight(entry, documentPanes.active)}
onCreated={(entry) => { void openCreatedFile(entry); }}
onSaveTemplate={(entry) => { void saveTemplate(entry); }}
onManageTemplates={() => templateManager = true}
@@ -1455,12 +1510,12 @@
<div class="center-stack" class:terminal-maximized={terminalOpen && terminalMaximized} bind:this={centerStack}>
<DocumentArea
bind:this={documentArea}
bind:pluginPaneComponents
bind:paneComponents
pluginCover={coverKey !== null}
split={!!activeSplit}
{pluginBounds}
tabBar={tabBarProps}
drop={tabDrop}
onResize={(path, ratio) => { documentPanes = resizeDocumentPanes(documentPanes, path, ratio); }}
{documentViews}
layout={documentPanes.layout}
activePane={documentPanes.active}
+24 -1
View File
@@ -1,4 +1,4 @@
import { paneBounds, removePane, splitPane, type SplitLayout } from "./splitLayout.ts";
import { paneBounds, removePane, setSplitRatio, splitPane, type SplitLayout, type SplitPath } from "./splitLayout.ts";
/**
* A pane shows one document or one plugin editor view, for example a browser tab. A pane never shows both.
@@ -106,6 +106,29 @@ export function releaseSolePlugin(state: DocumentPanes): { state: DocumentPanes;
return { state: { ...state, panes: [{ ...pane, pluginKey: null }] }, pluginKey: pane.pluginKey };
}
/** The place of a tab drop on a pane: the pane itself, or a new pane on its right or bottom side. */
export type PaneDrop = "center" | "right" | "down";
/**
* Show the content in the `target` pane (`center`), or in a new pane beside it.
* The content leaves the pane that showed it before, so that it shows in one pane only.
* The content that the drop replaces stays open as a tab.
*/
export function dropInPane(state: DocumentPanes, content: PaneContent, target: string, zone: PaneDrop, paneId: string): DocumentPanes {
if (!state.panes.some(pane => pane.id === target)) return state;
const current = paneOf(state, content);
if (current?.id === target) return selectPane(state, target);
const cleared = state.panes.map(pane => pane.id === current?.id ? emptyPane(pane.id) : pane);
if (zone === "center") return collapse(state, cleared.map(pane => pane.id === target ? filled(target, content) : pane), target);
return splitWithContent(collapse(state, cleared, target), target, content, paneId, zone);
}
/** Give a new ratio to a split between panes. */
export function resizeDocumentPanes(state: DocumentPanes, path: SplitPath, ratio: number): DocumentPanes {
const layout = setSplitRatio(state.layout, path, ratio);
return layout === state.layout ? state : { ...state, layout };
}
export function readDocumentPane(state: DocumentPanes, id: string, reading: boolean): DocumentPanes {
return { ...state, panes: state.panes.map(pane => pane.id === id ? { ...pane, reading, split: reading ? false : pane.split } : pane) };
}
+36 -5
View File
@@ -1,5 +1,11 @@
export type SplitLayout = string | { direction: "right" | "down"; first: SplitLayout; second: SplitLayout };
/** A split gives `ratio` of its size to `first`. A split without a ratio divides its size in two equal parts. */
export type SplitLayout = string | { direction: "right" | "down"; first: SplitLayout; second: SplitLayout; ratio?: number };
export type PaneBounds = { left: number; top: number; width: number; height: number };
/** The path from the root to a split: the side of each split on the way. */
export type SplitPath = readonly ("first" | "second")[];
/** A divider between the two sides of a split. `bounds` is the area of the split, in percent of the root. */
export type SplitDivider = { path: SplitPath; direction: "right" | "down"; ratio: number; bounds: PaneBounds };
const ratioOf = (tree: Exclude<SplitLayout, string>) => tree.ratio ?? 0.5;
export function containsPane(tree: SplitLayout, key: string): boolean {
return typeof tree === "string" ? tree === key : containsPane(tree.first, key) || containsPane(tree.second, key);
@@ -18,15 +24,40 @@ export function removePane(tree: SplitLayout, key: string): SplitLayout | null {
export function paneBounds(tree: SplitLayout, bounds: PaneBounds = { left: 0, top: 0, width: 100, height: 100 }): Record<string, PaneBounds> {
if (typeof tree === "string") return { [tree]: bounds };
const a = { ...bounds }, b = { ...bounds };
if (tree.direction === "right") { a.width /= 2; b.width /= 2; b.left += a.width; }
else { a.height /= 2; b.height /= 2; b.top += a.height; }
const [a, b] = sides(tree, bounds);
return { ...paneBounds(tree.first, a), ...paneBounds(tree.second, b) };
}
function sides(tree: Exclude<SplitLayout, string>, bounds: PaneBounds): [PaneBounds, PaneBounds] {
const a = { ...bounds }, b = { ...bounds }, ratio = ratioOf(tree);
if (tree.direction === "right") { a.width = bounds.width * ratio; b.width = bounds.width - a.width; b.left += a.width; }
else { a.height = bounds.height * ratio; b.height = bounds.height - a.height; b.top += a.height; }
return [a, b];
}
/** Each split of the tree, with its place, for the dividers that change its ratio. */
export function splitDividers(tree: SplitLayout, bounds: PaneBounds = { left: 0, top: 0, width: 100, height: 100 }, path: SplitPath = []): SplitDivider[] {
if (typeof tree === "string") return [];
const [a, b] = sides(tree, bounds);
return [{ path, direction: tree.direction, ratio: ratioOf(tree), bounds },
...splitDividers(tree.first, a, [...path, "first"]), ...splitDividers(tree.second, b, [...path, "second"])];
}
/** Give a new ratio to the split at `path`. The ratio stays between 0.1 and 0.9. */
export function setSplitRatio(tree: SplitLayout, path: SplitPath, ratio: number): SplitLayout {
if (typeof tree === "string" || !Number.isFinite(ratio)) return tree;
if (!path.length) {
const next = Math.round(Math.max(0.1, Math.min(0.9, ratio)) * 1000) / 1000;
return next === ratioOf(tree) ? tree : { ...tree, ratio: next };
}
const [side, ...rest] = path;
const child = setSplitRatio(tree[side], rest, ratio);
return child === tree[side] ? tree : { ...tree, [side]: child };
}
/** The same panes in the same order, one above the other. A narrow area uses it. */
export function stackLayout(tree: SplitLayout): SplitLayout {
return typeof tree === "string" ? tree : { direction: "down", first: stackLayout(tree.first), second: stackLayout(tree.second) };
return typeof tree === "string" ? tree : { ...tree, direction: "down", first: stackLayout(tree.first), second: stackLayout(tree.second) };
}
/** The direction of the split that put `key` beside a different pane, and the first pane on the other side. */