feat(markdown): make the editor and preview split resizable (#4060)

The Markdown editor and preview split is now a SplitGroup with a draggable handle (10-90%), one persisted ratio for all Markdown files, and double-click on the handle resets to 50/50. Double-click reset lives in SplitHandle, so every split gets it. The editor re-measures CodeMirror and the preview stays anchored to the editor's top line while the divider moves; wide preview tables scroll horizontally instead of overflowing.

Co-authored-by: dengliu <5108773+dengliu@users.noreply.github.com>
This commit is contained in:
Deng Liu
2026-11-18 10:21:46 +08:00
committed by GitHub
co-authored by dengliu
parent 0e29c78616
commit bb827d02f9
9 changed files with 412 additions and 40 deletions
+102
View File
@@ -436,3 +436,105 @@ test("dragging the vertical tab column's edge resizes it and the width is kept",
await placeLeft();
await expect.poll(async () => Math.round((await strip.boundingBox())!.width)).toBe(Math.round(narrowed));
});
test("dragging the Markdown split divider resizes and reflows editor and preview content, keeps the ratio, and resets on double-click", async ({
workbench: page,
}) => {
const applyDefaultSettings = () =>
page.evaluate(async () => {
const projectModule = "/src/platform/project.ts";
const schemaModule = "/src/features/settings/model/schema.ts";
const [{ useProject }, { DEFAULT_SETTINGS }] = await Promise.all([
import(/* @vite-ignore */ projectModule),
import(/* @vite-ignore */ schemaModule),
]);
useProject.setState({ settings: useProject.getState().settings ?? DEFAULT_SETTINGS });
});
await applyDefaultSettings();
const editor = await openFromTree(page, "README.md");
await page.evaluate(async () => {
const controllerModule = "/src/editor/core/controller.ts";
const { editorController } = await import(/* @vite-ignore */ controllerModule);
const view = editorController().activeSlot!.view!;
view.dispatch({
changes: {
from: 0,
to: view.state.doc.length,
insert: [
"# Order Service",
"",
"Event-driven order processing API with idempotent checkout, inventory reservation, webhook delivery, and automatic retry policies.",
"",
"| Method | Path | Description |",
"| :--- | :--- | :--- |",
"| `POST` | `/v1/orders/{id}/cancel` | Release reserved stock and emit cancellation event |",
].join("\n"),
},
selection: { anchor: 0 },
});
});
const preview = page.getByRole("document", { name: "Markdown preview" });
const handle = page.getByRole("separator", { name: "Resize Markdown preview" });
const cmContent = editor.locator(".cm-content");
await expect(preview).toContainText("Event-driven order processing API");
await expect(handle).toBeVisible();
await expect(cmContent).toHaveClass(/cm-lineWrapping/);
const initialEditor = (await editor.boundingBox())!.width;
const initialPreview = (await preview.boundingBox())!.width;
const initialContent = (await cmContent.boundingBox())!.width;
expect(Math.abs(initialEditor - initialPreview)).toBeLessThanOrEqual(2);
expect(initialContent).toBeLessThanOrEqual(initialEditor);
const box = (await handle.boundingBox())!;
const startX = box.x + box.width / 2;
const midY = box.y + box.height / 2;
await page.mouse.move(startX, midY);
await page.mouse.down();
await page.mouse.move(startX - 180, midY, { steps: 6 });
await expect(handle).toHaveAttribute("data-separator", "active");
await page.mouse.up();
await expect.poll(async () => (await editor.boundingBox())!.width).toBeLessThan(initialEditor - 150);
await expect.poll(async () => (await preview.boundingBox())!.width).toBeGreaterThan(initialPreview + 150);
const narrowedEditor = (await editor.boundingBox())!.width;
// Soft-wrapped editor content shrinks with the narrowed editor pane rather than overflowing.
await expect.poll(async () => (await cmContent.boundingBox())!.width).toBeLessThanOrEqual(narrowedEditor);
// Dragging right narrows the preview: table and prose stay within the preview content width.
const narrowedHandleBox = (await handle.boundingBox())!;
await page.mouse.move(narrowedHandleBox.x + narrowedHandleBox.width / 2, midY);
await page.mouse.down();
await page.mouse.move(narrowedHandleBox.x + narrowedHandleBox.width / 2 + 380, midY, { steps: 8 });
await page.mouse.up();
const widenedEditor = (await editor.boundingBox())!.width;
await expect.poll(async () => (await cmContent.boundingBox())!.width).toBeGreaterThan(initialContent + 140);
await expect.poll(async () => (await cmContent.boundingBox())!.width).toBeLessThanOrEqual(widenedEditor);
expect(await preview.evaluate((el) => el.scrollWidth <= el.clientWidth)).toBe(true);
// Editor Only and Preview Only both expand content to full pane width.
await page.getByRole("button", { name: "Editor Only" }).click();
await expect.poll(async () => (await cmContent.boundingBox())!.width).toBeGreaterThan(widenedEditor);
await page.getByRole("button", { name: "Preview Only" }).click();
await expect.poll(async () => (await preview.boundingBox())!.width).toBeGreaterThan(initialPreview * 1.8);
await page.getByRole("button", { name: "Editor and Preview" }).click();
await expect.poll(async () => Math.round((await editor.boundingBox())!.width)).toBe(Math.round(widenedEditor));
// Persists across reload.
await page.reload();
await applyDefaultSettings();
const reopenedEditor = await openFromTree(page, "README.md");
await expect
.poll(async () => Math.round((await reopenedEditor.boundingBox())!.width))
.toBe(Math.round(widenedEditor));
// Double-clicking the divider resets the split back to 50/50.
const reopenedHandle = page.getByRole("separator", { name: "Resize Markdown preview" });
await reopenedHandle.dblclick();
await expect
.poll(async () => Math.round((await reopenedEditor.boundingBox())!.width))
.toBe(Math.round(initialEditor));
});
@@ -5,17 +5,21 @@
display: flex;
position: relative;
}
.group {
flex: 1;
}
.editor {
flex: 1 1 50%;
flex: 1;
min-height: 0;
min-width: 0;
display: flex;
flex-direction: column;
}
.mode-preview .editor {
display: none;
.mode-preview > :global([data-group]) > :global([data-panel]:first-child) {
display: none !important;
}
.mode-split .editor {
border-right: 1px solid var(--border-editor-tabs, var(--border));
.mode-preview > :global([data-group]) > :global([data-panel]:last-child) {
flex-grow: 1 !important;
}
.layoutActions {
@@ -28,7 +32,8 @@
}
.preview {
flex: 1 1 50%;
flex: 1;
min-height: 0;
min-width: 0;
position: relative;
overflow: auto;
@@ -117,12 +122,21 @@
opacity: 0.8;
}
.preview :global(table) {
display: block;
width: max-content;
max-width: 100%;
overflow-x: auto;
border-collapse: collapse;
}
.preview :global(th),
.preview :global(td) {
padding: 4px 10px;
border: 1px solid var(--border-strong);
overflow-wrap: normal;
}
.preview :global(td code),
.preview :global(td a) {
overflow-wrap: anywhere;
}
.preview :global(th) {
background: var(--bg-editor-inline, var(--bg-elev));
@@ -22,9 +22,9 @@ import { call, commands, isTauri } from "@/platform/ipc";
import { editorPrefs, useEditorPrefs } from "@/platform/editorSettings";
import { useMarkdownPreviewFontSize } from "@/platform/languageSettings";
import { maybeEditorService, registerFontZoomSurface } from "@/workbench/contributions";
import { setShownLine } from "@/editor/api";
import { editorsFor, setShownLine } from "@/editor/api";
import { highlightInto } from "@/editor/lsp/markdown";
import { FloatingToolbar, selectableText } from "@/ui";
import { FloatingToolbar, SplitGroup, SplitHandle, SplitPanel, selectableText } from "@/ui";
import {
FIND_CURRENT_HIGHLIGHT,
FIND_HIGHLIGHT,
@@ -76,6 +76,8 @@ function openExternal(url: string) {
else window.open(url, "_blank", "noopener");
}
const SPLIT_STORAGE_KEY = "openidea.markdown.split";
export function MarkdownEditor({
path,
tabId,
@@ -89,10 +91,47 @@ export function MarkdownEditor({
}) {
const mode = useMarkdownModes((s) => modeOf(s, path));
const ref = useRef<HTMLDivElement>(null);
const editorRef = useRef<HTMLDivElement>(null);
// CodeMirror's internal ResizeObserver skips resizes within 75ms of a view update
// and debounces by 50ms; re-measure immediately on drag and mode transitions.
useEffect(() => {
const el = editorRef.current;
if (!el || typeof ResizeObserver === "undefined") return;
let width = el.clientWidth;
const ro = new ResizeObserver(() => {
const next = el.clientWidth;
if (next === width) return;
width = next;
if (next <= 0) return;
for (const ed of editorsFor(path)) {
if (!ed.tabId || ed.tabId === tabId) ed.view.requestMeasure();
}
});
ro.observe(el);
return () => ro.disconnect();
}, [path, tabId]);
const splitBounds = mode === "split" ? { minSize: "10%", maxSize: "90%" } : {};
return (
<div ref={ref} className={clsx(styles.split, styles[`mode-${mode}`])}>
<div className={styles.editor}>{children}</div>
{mode !== "editor" && <MarkdownPreview path={path} sync={mode === "split"} />}
<SplitGroup
orientation="horizontal"
className={styles.group}
storageKey={mode === "split" ? SPLIT_STORAGE_KEY : undefined}
>
<SplitPanel id="editor" style={{ overflow: "hidden" }} {...splitBounds}>
<div ref={editorRef} className={styles.editor}>
{children}
</div>
</SplitPanel>
{mode === "split" && <SplitHandle aria-label={tx("Resize Markdown preview")} />}
{mode !== "editor" && (
<SplitPanel id="preview" style={{ overflow: "hidden" }} {...splitBounds}>
<MarkdownPreview path={path} sync={mode === "split"} />
</SplitPanel>
)}
</SplitGroup>
{!actionsInTabs && (
<FloatingToolbar targetRef={ref}>
<MarkdownLayoutActions path={path} tabId={tabId} />
@@ -225,6 +264,21 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
root.scrollTop = topLine <= 0 ? 0 : previewOffsetForLine(blocksOf(root), topLine, root.scrollHeight);
}, [html, topLine, scrollSeq, sync, diagramsDrawn, fontZoom, fontSize]);
// Keep the split preview anchored to `topLine` as dragging the divider or resizing the window reflows text.
useEffect(() => {
const root = ref.current;
if (!root || !sync || typeof ResizeObserver === "undefined") return;
let width = root.clientWidth;
const ro = new ResizeObserver(() => {
if (root.clientWidth === width) return;
width = root.clientWidth;
const top = useLiveMarkdown.getState()[path]?.topLine ?? 0;
root.scrollTop = top <= 0 ? 0 : previewOffsetForLine(blocksOf(root), top, root.scrollHeight);
});
ro.observe(root);
return () => ro.disconnect();
}, [path, sync]);
// The preview's own scroll offset: tab switches and mode toggles unmount the
// preview, so Preview Only would otherwise start over at the top. Writes made
// by the split sync above are captured too — the last visible position wins.
+4
View File
@@ -237,6 +237,10 @@ function livePlugin(path: string) {
}
if (!u.docChanged) {
if (u.geometryChanged && u.view.scrollDOM.scrollTop > 0) {
const topLine = topLineOf(u.view);
if (topLine !== useLiveMarkdown.getState()[path]?.topLine) publish(path, { topLine });
}
if (u.selectionSet) this.publishCaret();
return;
}
@@ -0,0 +1,138 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
import { useEffect } from "react";
import type { EditorView } from "@codemirror/view";
import { _addEditor, _removeEditor, type TextEditorHandle } from "@/editor/api";
import { MarkdownEditor } from "./MarkdownEditor";
import { setMarkdownMode, useMarkdownModes } from "./modes";
const PATH = "/p/README.md";
const OTHER_PATH = "/p/OTHER.md";
const SPLIT_KEY = "openidea.markdown.split";
describe("Markdown split resizer", () => {
beforeEach(() => {
localStorage.clear();
useMarkdownModes.setState({ byPath: {}, fallback: "split" });
});
afterEach(() => {
cleanup();
localStorage.clear();
});
it("shows the separator only in split mode without remounting the editor across mode changes", () => {
let mounts = 0;
function Probe() {
useEffect(() => {
mounts++;
}, []);
return <div data-testid="editor-probe" />;
}
render(
<MarkdownEditor path={PATH} tabId="t">
<Probe />
</MarkdownEditor>,
);
expect(screen.getByRole("separator", { name: "Resize Markdown preview" })).toBeInTheDocument();
expect(mounts).toBe(1);
act(() => setMarkdownMode(PATH, "preview"));
expect(screen.queryByRole("separator", { name: "Resize Markdown preview" })).toBeNull();
expect(screen.getByTestId("editor-probe")).toBeInTheDocument();
expect(mounts).toBe(1);
act(() => setMarkdownMode(PATH, "editor"));
expect(screen.queryByRole("separator", { name: "Resize Markdown preview" })).toBeNull();
expect(screen.getByTestId("editor-probe")).toBeInTheDocument();
expect(mounts).toBe(1);
act(() => setMarkdownMode(PATH, "split"));
expect(screen.getByRole("separator", { name: "Resize Markdown preview" })).toBeInTheDocument();
expect(mounts).toBe(1);
});
it("shares one persisted split layout across Markdown files and resets to 50/50 on double-click", () => {
localStorage.setItem(SPLIT_KEY, JSON.stringify({ editor: 32, preview: 68 }));
const { container, unmount } = render(
<MarkdownEditor path={PATH} tabId="t">
<div />
</MarkdownEditor>,
);
const flexGrowOf = (root: HTMLElement, id: string) =>
Number((root.querySelector<HTMLElement>(`[data-panel]#${id}`)?.style.flexGrow ?? "0").trim());
expect(flexGrowOf(container, "editor")).toBe(32);
expect(flexGrowOf(container, "preview")).toBe(68);
unmount();
// Another Markdown file inherits the shared split ratio.
const second = render(
<MarkdownEditor path={OTHER_PATH} tabId="t2">
<div />
</MarkdownEditor>,
);
expect(flexGrowOf(second.container, "editor")).toBe(32);
expect(flexGrowOf(second.container, "preview")).toBe(68);
// Double-clicking the handle resets to 50/50 and updates localStorage.
fireEvent.doubleClick(screen.getByRole("separator", { name: "Resize Markdown preview" }));
expect(flexGrowOf(second.container, "editor")).toBe(50);
expect(flexGrowOf(second.container, "preview")).toBe(50);
expect(JSON.parse(localStorage.getItem(SPLIT_KEY)!)).toEqual({ editor: 50, preview: 50 });
});
it("re-measures the backing CodeMirror view whenever the editor pane width changes", () => {
const observers = new Map<Element, ResizeObserverCallback>();
const OrigRO = globalThis.ResizeObserver;
class MockRO {
constructor(private cb: ResizeObserverCallback) {}
observe(el: Element) {
observers.set(el, this.cb);
}
unobserve(el: Element) {
observers.delete(el);
}
disconnect() {}
}
globalThis.ResizeObserver = MockRO as unknown as typeof ResizeObserver;
const requestMeasure = vi.fn();
const handle: TextEditorHandle = {
view: { requestMeasure } as unknown as EditorView,
ctx: { doc: 1, path: PATH, language: "markdown", uiMode: null, readOnly: false },
tabId: "t",
};
_addEditor(handle);
try {
const { container } = render(
<MarkdownEditor path={PATH} tabId="t">
<div data-testid="inner-host" />
</MarkdownEditor>,
);
const editorEl = screen.getByTestId("inner-host").parentElement as HTMLElement;
expect(container.contains(editorEl)).toBe(true);
const notify = observers.get(editorEl)!;
let width = 500;
Object.defineProperty(editorEl, "clientWidth", { configurable: true, get: () => width });
width = 320;
notify([], {} as ResizeObserver);
expect(requestMeasure).toHaveBeenCalledTimes(1);
// Hidden in preview-only mode (0px), then shown again at full width -> measures again.
width = 0;
notify([], {} as ResizeObserver);
expect(requestMeasure).toHaveBeenCalledTimes(1);
width = 1000;
notify([], {} as ResizeObserver);
expect(requestMeasure).toHaveBeenCalledTimes(2);
} finally {
_removeEditor(handle);
globalThis.ResizeObserver = OrigRO;
}
});
});
+2 -1
View File
@@ -2451,5 +2451,6 @@
"Add as Maven Project": "Add as Maven Project",
"This Maven project is not loaded": "This Maven project is not loaded",
"Load Maven Project": "Load Maven Project",
"Skip": "Skip"
"Skip": "Skip",
"Resize Markdown preview": "Resize Markdown preview"
}
+2 -1
View File
@@ -8827,5 +8827,6 @@
"Show files only on right": "显示仅在右侧的文件",
"Add as Maven Project": "添加为 Maven 项目",
"This Maven project is not loaded": "此 Maven 项目尚未加载",
"Load Maven Project": "加载 Maven 项目"
"Load Maven Project": "加载 Maven 项目",
"Resize Markdown preview": "调整 Markdown 预览宽度"
}
+36 -2
View File
@@ -1,10 +1,13 @@
import { afterEach, expect, it } from "vitest";
import { createRef } from "react";
import { render } from "@testing-library/react";
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import type { GroupImperativeHandle } from "react-resizable-panels";
import { SplitGroup, SplitHandle, SplitPanel } from "./Splitter";
afterEach(() => localStorage.clear());
afterEach(() => {
cleanup();
localStorage.clear();
});
function Split({ storageKey, preview }: { storageKey: string; preview: boolean }) {
return (
@@ -41,3 +44,34 @@ it("ignores saved sizes for other panels", () => {
expect(Object.keys(ref.current!.getLayout()).sort()).toEqual(["preview", "tree"]);
expect(ref.current!.getLayout().tree).not.toBe(25);
});
it("resets the two adjacent panels to 50/50 on double-click and persists the reset", () => {
localStorage.setItem("split.even", JSON.stringify({ left: 30, right: 70 }));
render(
<SplitGroup orientation="horizontal" storageKey="split.even" groupRef={ref}>
<SplitPanel id="left" minSize="10%" maxSize="90%" />
<SplitHandle aria-label="Resize panes" />
<SplitPanel id="right" minSize="10%" maxSize="90%" />
</SplitGroup>,
);
expect(ref.current!.getLayout()).toEqual({ left: 30, right: 70 });
fireEvent.doubleClick(screen.getByRole("separator", { name: "Resize panes" }));
expect(ref.current!.getLayout()).toEqual({ left: 50, right: 50 });
expect(JSON.parse(localStorage.getItem("split.even")!)).toEqual({ left: 50, right: 50 });
});
it("equalizes only the two panels beside a double-clicked handle in a three-panel split", () => {
localStorage.setItem("split.three", JSON.stringify({ a: 20, b: 60, c: 20 }));
render(
<SplitGroup orientation="horizontal" storageKey="split.three" groupRef={ref}>
<SplitPanel id="a" />
<SplitHandle aria-label="First handle" />
<SplitPanel id="b" />
<SplitHandle aria-label="Second handle" />
<SplitPanel id="c" />
</SplitGroup>,
);
fireEvent.doubleClick(screen.getByRole("separator", { name: "First handle" }));
expect(ref.current!.getLayout()).toEqual({ a: 40, b: 40, c: 20 });
});
+50 -26
View File
@@ -12,9 +12,11 @@ import {
type SeparatorProps,
} from "react-resizable-panels";
import clsx from "clsx";
import { useEffect, useImperativeHandle, useRef, useState } from "react";
import { createContext, useContext, useEffect, useImperativeHandle, useRef, useState } from "react";
import styles from "./Splitter.module.css";
const SplitResetContext = createContext<((handle: HTMLElement, defaultHandled: boolean) => void) | null>(null);
function savedLayout(storageKey: string | undefined): Record<string, number> | undefined {
try {
const value: unknown = storageKey ? JSON.parse(localStorage.getItem(storageKey) ?? "null") : null;
@@ -46,6 +48,14 @@ export function SplitGroup({
const mountedKey = useRef(storageKey);
// Sizes to apply once the group's panels match them (a panel added with the new key registers later).
const pending = useRef<Record<string, number> | null>(null);
const saveLayout = (layout: Record<string, number>) => {
if (!storageKey || !Object.values(layout).every(Number.isFinite)) return;
try {
localStorage.setItem(storageKey, JSON.stringify(layout));
} catch {
/* Storage may be unavailable. */
}
};
const applyPending = (current: Record<string, number>) => {
const layout = pending.current;
if (!layout) return;
@@ -73,35 +83,39 @@ export function SplitGroup({
applyPending(layout);
rest.onLayoutChange?.(layout);
};
if (!storageKey)
return (
const resetHandle = (handle: HTMLElement, defaultHandled: boolean) => {
const g = group.current;
if (!g || rest.disabled) return;
if (!defaultHandled) {
let prev = handle.previousElementSibling;
while (prev && !prev.hasAttribute("data-panel")) prev = prev.previousElementSibling;
let next = handle.nextElementSibling;
while (next && !next.hasAttribute("data-panel")) next = next.nextElementSibling;
const current = g.getLayout();
const left = prev?.id ? current[prev.id] : undefined;
const right = next?.id ? current[next.id] : undefined;
if (prev?.id && next?.id && left !== undefined && right !== undefined) {
const half = (left + right) / 2;
g.setLayout({ ...current, [prev.id]: half, [next.id]: half });
}
}
const updated = g.getLayout();
if (Object.keys(updated).length) saveLayout(updated);
};
return (
<SplitResetContext.Provider value={resetHandle}>
<Group
className={clsx(styles.group, className)}
{...rest}
groupRef={group}
onLayoutChange={onLayoutChange}
defaultLayout={defaultLayout}
onLayoutChanged={onLayoutChanged}
defaultLayout={storageKey ? (saved ?? defaultLayout) : defaultLayout}
onLayoutChanged={(layout, meta) => {
if (meta.isUserInteraction) saveLayout(meta.requestedLayout ?? layout);
onLayoutChanged?.(layout, meta);
}}
/>
);
return (
<Group
className={clsx(styles.group, className)}
{...rest}
groupRef={group}
onLayoutChange={onLayoutChange}
defaultLayout={saved ?? defaultLayout}
onLayoutChanged={(layout, meta) => {
if (storageKey && meta.isUserInteraction) {
try {
localStorage.setItem(storageKey, JSON.stringify(meta.requestedLayout ?? layout));
} catch {
/* Storage may be unavailable. */
}
}
onLayoutChanged?.(layout, meta);
}}
/>
</SplitResetContext.Provider>
);
}
@@ -114,6 +128,16 @@ export interface SplitHandleProps extends SeparatorProps {
hairline?: boolean;
}
export function SplitHandle({ className, hairline = true, ...rest }: SplitHandleProps) {
return <Separator className={clsx(styles.handle, !hairline && styles.invisible, className)} {...rest} />;
export function SplitHandle({ className, hairline = true, onDoubleClick, ...rest }: SplitHandleProps) {
const reset = useContext(SplitResetContext);
return (
<Separator
className={clsx(styles.handle, !hairline && styles.invisible, className)}
onDoubleClick={(e) => {
onDoubleClick?.(e);
if (!rest.disabled && !rest.disableDoubleClick) reset?.(e.currentTarget, e.defaultPrevented);
}}
{...rest}
/>
);
}