diff --git a/e2e/editor.spec.ts b/e2e/editor.spec.ts index 59f31488b..4809b0c7c 100644 --- a/e2e/editor.spec.ts +++ b/e2e/editor.spec.ts @@ -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)); +}); diff --git a/src/features/viewers/markdown/Markdown.module.css b/src/features/viewers/markdown/Markdown.module.css index 55bda285f..fd8798dac 100644 --- a/src/features/viewers/markdown/Markdown.module.css +++ b/src/features/viewers/markdown/Markdown.module.css @@ -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)); diff --git a/src/features/viewers/markdown/MarkdownEditor.tsx b/src/features/viewers/markdown/MarkdownEditor.tsx index b4f0b01d0..ed273531e 100644 --- a/src/features/viewers/markdown/MarkdownEditor.tsx +++ b/src/features/viewers/markdown/MarkdownEditor.tsx @@ -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(null); + const editorRef = useRef(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 (
-
{children}
- {mode !== "editor" && } + + +
+ {children} +
+
+ {mode === "split" && } + {mode !== "editor" && ( + + + + )} +
{!actionsInTabs && ( @@ -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. diff --git a/src/features/viewers/markdown/live.ts b/src/features/viewers/markdown/live.ts index 3409d3252..2064ca1a4 100644 --- a/src/features/viewers/markdown/live.ts +++ b/src/features/viewers/markdown/live.ts @@ -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; } diff --git a/src/features/viewers/markdown/split.test.tsx b/src/features/viewers/markdown/split.test.tsx new file mode 100644 index 000000000..79853fd84 --- /dev/null +++ b/src/features/viewers/markdown/split.test.tsx @@ -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
; + } + + render( + + + , + ); + 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( + +
+ , + ); + const flexGrowOf = (root: HTMLElement, id: string) => + Number((root.querySelector(`[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( + +
+ , + ); + 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(); + 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( + +
+ , + ); + 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; + } + }); +}); diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 0d5a8fffe..2ff879742 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -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" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 1ba8bfd08..8152893bc 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -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 预览宽度" } diff --git a/src/ui/Splitter.test.tsx b/src/ui/Splitter.test.tsx index 1e87cbf16..6bba2fd23 100644 --- a/src/ui/Splitter.test.tsx +++ b/src/ui/Splitter.test.tsx @@ -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( + + + + + , + ); + 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( + + + + + + + , + ); + fireEvent.doubleClick(screen.getByRole("separator", { name: "First handle" })); + expect(ref.current!.getLayout()).toEqual({ a: 40, b: 40, c: 20 }); +}); diff --git a/src/ui/Splitter.tsx b/src/ui/Splitter.tsx index e586d9241..296b7204d 100644 --- a/src/ui/Splitter.tsx +++ b/src/ui/Splitter.tsx @@ -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 | 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 | null>(null); + const saveLayout = (layout: Record) => { + 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) => { 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 ( + { + if (meta.isUserInteraction) saveLayout(meta.requestedLayout ?? layout); + onLayoutChanged?.(layout, meta); + }} /> - ); - return ( - { - if (storageKey && meta.isUserInteraction) { - try { - localStorage.setItem(storageKey, JSON.stringify(meta.requestedLayout ?? layout)); - } catch { - /* Storage may be unavailable. */ - } - } - onLayoutChanged?.(layout, meta); - }} - /> + ); } @@ -114,6 +128,16 @@ export interface SplitHandleProps extends SeparatorProps { hairline?: boolean; } -export function SplitHandle({ className, hairline = true, ...rest }: SplitHandleProps) { - return ; +export function SplitHandle({ className, hairline = true, onDoubleClick, ...rest }: SplitHandleProps) { + const reset = useContext(SplitResetContext); + return ( + { + onDoubleClick?.(e); + if (!rest.disabled && !rest.disableDoubleClick) reset?.(e.currentTarget, e.defaultPrevented); + }} + {...rest} + /> + ); }