perf(ui): keep pane dividers responsive on large documents (#5506)

Grabbing a divider beside a large Markdown document changed the cursor on every element (an inherited cursor on the document, or the split group's own cursor rule), restyling the whole preview. A transparent fixed surface now holds the resize cursor during the drag, shared by split panes, docked tool windows and scrollbar drags. Visible and nearby Markdown blocks rewrap live; distant blocks keep their last width (clipped so the preview gains no horizontal overflow) until the drag ends, then reflow with the reading position preserved.

Co-authored-by: faysou <[email protected]>
Цей коміт міститься в:
faysouтаfaysou authored and GitHub committed 2026-11-24 21:53:49 +08:00
1 джерело ff1ef2b2f0
коміт fb56bd211b
9 files changed
+175 -78

No files matched your search

+37
Переглянути файл
@@ -856,6 +856,43 @@ test("dragging the source scrollbar across the Markdown divider keeps the arrow
expect((await divider.boundingBox())!.x).toBeGreaterThan(boundary.x + 40);
});
test("visible Markdown reflows during a tool window drag and distant blocks catch up on release", async ({
workbench: page,
}) => {
const editor = await openFromTree(page, "README.md");
const content = editor.locator(".cm-content");
await content.click();
await page.keyboard.press("Meta+a");
await page.keyboard.insertText(
Array.from({ length: 180 }, (_, i) => `Paragraph ${i} with enough text to wrap across the pane.`).join("\n\n"),
);
const preview = page.getByRole("document", { name: "Markdown preview" });
await expect(preview).toContainText("Paragraph 179");
await content.press("Control+Home");
const near = preview.locator("[data-line][data-in-viewport]").first();
const far = preview.locator("[data-line]:not([data-in-viewport])").last();
const width = (el: typeof near) => el.evaluate((n) => n.getBoundingClientRect().width);
await expect(near).toBeAttached();
await expect(far).toBeAttached();
const before = await width(far);
await expect.poll(() => width(near)).toBe(before);
const handle = page.getByRole("separator", { name: "Resize left tool window", exact: true });
const box = (await handle.boundingBox())!;
const x = box.x + box.width / 2,
y = box.y + box.height / 2;
await page.mouse.move(x, y);
await page.mouse.down();
try {
await page.mouse.move(x + 160, y, { steps: 4 });
await expect.poll(() => width(near)).toBeLessThan(before - 30);
expect(await preview.evaluate((el) => el.scrollWidth - el.clientWidth)).toBe(0);
expect(await width(far)).toBe(before);
} finally {
await page.mouse.up();
}
await expect.poll(() => width(far)).toBe(await width(near));
});
test("dragging the Markdown split divider resizes and reflows editor and preview content, keeps the ratio, and resets on double-click", async ({
workbench: page,
}) => {
+9 -9
Переглянути файл
@@ -177,18 +177,18 @@ test("a tool window resize keeps its cursor over other controls until release",
const gap = page.locator('[data-gap="left"]');
const box = (await gap.boundingBox())!;
const hide = page.getByRole("region", { name: "Project" }).getByRole("button", { name: "Hide", exact: true });
const cursor = () => hide.evaluate((el) => getComputedStyle(el).cursor);
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
await page.mouse.down();
await page.mouse.move(box.x + 80, box.y + box.height / 2, { steps: 4 });
// The pointer is over the Project tree now; the button's own arrow cursor must not win.
await expect.poll(cursor).toBe("col-resize");
expect(await page.evaluate(() => document.documentElement.hasAttribute("data-drag-cursor"))).toBe(true);
const x = box.x + 80;
const y = box.y + box.height / 2;
await page.mouse.move(x, y, { steps: 4 });
const hitCursor = () =>
page.evaluate(({ x, y }) => getComputedStyle(document.elementFromPoint(x, y)!).cursor, { x, y });
await expect.poll(hitCursor).toBe("col-resize");
await expect(page.locator("[data-drag-cursor-surface]")).toHaveCount(1);
await page.mouse.up();
await expect.poll(cursor).toBe("default");
expect(await page.evaluate(() => document.documentElement.hasAttribute("data-drag-cursor"))).toBe(false);
await expect(page.locator("[data-drag-cursor-surface]")).toHaveCount(0);
await expect(hide).toHaveCSS("cursor", "default");
});
test("the Terminal sends typed commands to the shell and shows its output", async ({ workbench: page }) => {
+8 -7
Переглянути файл
@@ -8,12 +8,6 @@
.group {
flex: 1;
}
.group:has(> :global([data-separator="active"][aria-orientation="vertical"])) * {
cursor: col-resize !important;
}
.group:has(> :global([data-separator="active"][aria-orientation="horizontal"])) * {
cursor: row-resize !important;
}
.editor {
flex: 1;
min-height: 0;
@@ -69,6 +63,13 @@
line-height: 1.6;
overflow-wrap: break-word;
}
/* Offscreen blocks keep their last settled width between resize events. Their SVGs stay painted. */
.preview > :global([data-preview-blocks]) > :global([data-line]:not([data-in-viewport])) {
width: var(--markdown-block-width, auto);
}
.preview[data-constrain-blocks] > :global([data-preview-blocks]) {
overflow-x: clip;
}
.preview :global(h1),
.preview :global(h2) {
padding-bottom: 0.3em;
@@ -103,7 +104,7 @@
.preview :global(h3) {
font-size: 1.25em;
}
.preview > :global(div:first-child) > :first-child {
.preview > :global([data-preview-blocks]) > :global(div:first-child) > :first-child {
margin-top: 0;
}
.preview :global(p),
+62 -4
Переглянути файл
@@ -152,7 +152,6 @@ export function MarkdownEditor({
<div ref={ref} className={clsx(styles.split, styles[`mode-${mode}`])}>
<SplitGroup
orientation={stacked ? "vertical" : "horizontal"}
disableCursor
className={styles.group}
storageKey={mode === "split" ? storageKey : undefined}
defaultLayout={mode === "split" ? DEFAULT_SPLIT_LAYOUT : undefined}
@@ -190,7 +189,7 @@ export function MarkdownEditor({
}
const blocksOf = (root: HTMLElement) =>
[...root.querySelectorAll<HTMLElement>(":scope > [data-line]")].map((el) => ({
[...root.querySelectorAll<HTMLElement>(":scope > [data-preview-blocks] > [data-line]")].map((el) => ({
line: Number(el.dataset.line),
get top() {
return el.offsetTop;
@@ -355,6 +354,64 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
return () => ro.disconnect();
}, [path, sync]);
useEffect(() => {
const root = ref.current;
if (!root || !window.IntersectionObserver || !window.ResizeObserver) return;
const visibility = new IntersectionObserver(
(entries) => {
for (const entry of entries) entry.target.toggleAttribute("data-in-viewport", entry.isIntersecting);
},
{ root, rootMargin: "100% 0px" },
);
for (const block of root.querySelectorAll(":scope > [data-preview-blocks] > [data-line]"))
visibility.observe(block);
let width = 0;
let settled = 0;
let timer: number | undefined;
const apply = () => {
if (!width || width === settled) return;
const top = root.scrollTop;
const atBottom = top > 0 && top + root.clientHeight >= root.scrollHeight - 1;
const line = top > 0 ? previewLineAtOffset(blocks.current, top) : -1;
const block = line >= 0 ? blocks.current.find((b) => b.line === line) : undefined;
const within = block ? top - block.top : 0;
settled = width;
root.removeAttribute("data-constrain-blocks");
root.style.setProperty("--markdown-block-width", `${width}px`);
if (atBottom) root.scrollTop = root.scrollHeight;
else if (block) root.scrollTop = block.top + within;
};
const schedule = () => {
if (width === settled) return;
window.clearTimeout(timer);
timer = window.setTimeout(() => {
if (!document.querySelector('[data-drag-cursor-surface$="resize"], [data-separator="active"]')) apply();
}, 150);
};
const sizes = new ResizeObserver(([entry]) => {
if (!entry || width === entry.contentRect.width) return;
width = entry.contentRect.width;
root.toggleAttribute("data-constrain-blocks", width < settled);
if (!settled) apply();
else schedule();
});
sizes.observe(root);
document.addEventListener("pointerup", schedule, true);
document.addEventListener("pointercancel", schedule, true);
window.addEventListener("blur", schedule);
return () => {
visibility.disconnect();
sizes.disconnect();
window.clearTimeout(timer);
document.removeEventListener("pointerup", schedule, true);
document.removeEventListener("pointercancel", schedule, true);
window.removeEventListener("blur", schedule);
root.style.removeProperty("--markdown-block-width");
root.removeAttribute("data-constrain-blocks");
};
}, [html]);
// 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.
@@ -604,7 +661,8 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
aria-label={tx("Markdown preview")}
onClick={onClick}
onScroll={onScroll}
dangerouslySetInnerHTML={{ __html: html }}
/>
>
<div data-preview-blocks="" dangerouslySetInnerHTML={{ __html: html }} />
</div>
);
}
+2 -1
Переглянути файл
@@ -198,7 +198,8 @@ export function invalidatePreviewIndex(root: HTMLElement) {
function previewIndex(root: HTMLElement): PreviewIndex {
let index = previewIndexes.get(root);
if (!index) {
const els = [...root.querySelectorAll<HTMLElement>(":scope > [data-line]")];
const content = root.querySelector(":scope > [data-preview-blocks]") ?? root;
const els = [...content.querySelectorAll<HTMLElement>(":scope > [data-line]")];
const blocks = els.map((el) => ({ startLine: Number(el.dataset.line), runs: collectRuns(el) }));
index = { blocks, runs: blocks.length ? blocks.flatMap((b) => b.runs) : collectRuns(root) };
previewIndexes.set(root, index);
+4 -6
Переглянути файл
@@ -52,12 +52,10 @@ body {
cursor: default !important;
}
/* A resize drag owns the cursor until release, even over the editor or a button. */
html[data-drag-cursor],
html[data-drag-cursor] *,
html[data-drag-cursor] *::before,
html[data-drag-cursor] *::after {
cursor: var(--drag-cursor) !important;
[data-drag-cursor-surface] {
position: fixed;
inset: 0;
z-index: var(--z-tooltip);
}
html[data-selection-lock] *:not([data-selection-scope], [data-selection-scope] *) {
+25 -1
Переглянути файл
@@ -13,6 +13,7 @@ import {
} from "react-resizable-panels";
import clsx from "clsx";
import { createContext, useCallback, useContext, useEffect, useImperativeHandle, useRef, useState } from "react";
import { lockDragCursor } from "./dragCursor";
import styles from "./Splitter.module.css";
const SplitResetContext = createContext<((handle: HTMLElement, defaultHandled: boolean) => void) | null>(null);
@@ -113,6 +114,7 @@ export function SplitGroup({
<Group
className={clsx(styles.group, className)}
{...rest}
disableCursor
groupRef={group}
onLayoutChange={onLayoutChange}
defaultLayout={storageKey ? (saved ?? defaultLayout) : defaultLayout}
@@ -134,10 +136,32 @@ export interface SplitHandleProps extends SeparatorProps {
hairline?: boolean;
}
export function SplitHandle({ className, hairline = true, onDoubleClick, ...rest }: SplitHandleProps) {
export function SplitHandle({
className,
hairline = true,
onDoubleClick,
onGotPointerCapture,
onLostPointerCapture,
...rest
}: SplitHandleProps) {
const reset = useContext(SplitResetContext);
const release = useRef<(() => void) | undefined>(undefined);
useEffect(() => () => release.current?.(), []);
return (
<Separator
onGotPointerCapture={(event) => {
onGotPointerCapture?.(event);
if (event.currentTarget.dataset.separator === "active") {
release.current ??= lockDragCursor(
event.currentTarget.getAttribute("aria-orientation") === "vertical" ? "col-resize" : "row-resize",
);
}
}}
onLostPointerCapture={(event) => {
onLostPointerCapture?.(event);
release.current?.();
release.current = undefined;
}}
className={clsx(styles.handle, !hairline && styles.invisible, className)}
onDoubleClick={(e) => {
onDoubleClick?.(e);
+10 -16
Переглянути файл
@@ -1,48 +1,42 @@
import { afterEach, describe, expect, it } from "vitest";
import { lockDragCursor } from "./dragCursor";
const html = document.documentElement;
const surfaces = () => [...document.querySelectorAll<HTMLElement>("[data-drag-cursor-surface]")];
const cursors = () => surfaces().map((el) => el.style.cursor);
afterEach(() => {
html.removeAttribute("data-drag-cursor");
html.style.removeProperty("--drag-cursor");
});
afterEach(() => document.dispatchEvent(new Event("pointercancel")));
describe("lockDragCursor", () => {
it("holds the cursor until the drag ends", () => {
const release = lockDragCursor("col-resize");
expect(html.getAttribute("data-drag-cursor")).toBe("");
expect(html.style.getPropertyValue("--drag-cursor")).toBe("col-resize");
expect(cursors()).toEqual(["col-resize"]);
release();
expect(html.hasAttribute("data-drag-cursor")).toBe(false);
expect(html.style.getPropertyValue("--drag-cursor")).toBe("");
expect(cursors()).toEqual([]);
});
it("ignores a repeated release", () => {
const release = lockDragCursor("row-resize");
release();
release();
expect(html.hasAttribute("data-drag-cursor")).toBe(false);
expect(cursors()).toEqual([]);
});
it("restores an outer drag after a nested one ends", () => {
const outer = lockDragCursor("col-resize");
const inner = lockDragCursor("nwse-resize");
expect(html.style.getPropertyValue("--drag-cursor")).toBe("nwse-resize");
expect(cursors()).toEqual(["col-resize", "nwse-resize"]);
inner();
expect(html.getAttribute("data-drag-cursor")).toBe("");
expect(html.style.getPropertyValue("--drag-cursor")).toBe("col-resize");
expect(cursors()).toEqual(["col-resize"]);
outer();
expect(html.hasAttribute("data-drag-cursor")).toBe(false);
expect(cursors()).toEqual([]);
});
it("releases when the pointer goes up outside the handle", () => {
lockDragCursor("col-resize");
document.dispatchEvent(new Event("pointerup", { bubbles: true }));
expect(html.hasAttribute("data-drag-cursor")).toBe(false);
expect(html.style.getPropertyValue("--drag-cursor")).toBe("");
expect(cursors()).toEqual([]);
});
});
+18 -34
Переглянути файл
@@ -1,12 +1,3 @@
/**
* Keeps one cursor over the whole window while a resize drag runs.
*
* `document.body.style.cursor` is not enough: the pointer soon leaves the
* handle and elements with a cursor of their own (the editor's I-beam, a
* button's arrow) take over, so the resize cursor appears to fall back to the
* default one mid-drag. `global.css` keys off `data-drag-cursor` instead and
* wins over those cursors with `!important`.
*/
export type DragCursor = "col-resize" | "row-resize" | "ew-resize" | "ns-resize" | "nwse-resize";
const active = new Set<() => void>();
@@ -28,38 +19,31 @@ function listenForEnd() {
/** Returns the release function; call it when the drag ends or is cancelled. */
export function lockDragCursor(cursor: DragCursor): () => void {
const html = document.documentElement;
const previous = html.style.getPropertyValue("--drag-cursor");
const wasLocked = html.hasAttribute("data-drag-cursor");
html.style.setProperty("--drag-cursor", cursor);
html.setAttribute("data-drag-cursor", "");
return untilDragEnds(() => {
if (wasLocked) html.style.setProperty("--drag-cursor", previous);
else {
html.removeAttribute("data-drag-cursor");
html.style.removeProperty("--drag-cursor");
}
});
}
export function lockScrollbarCursor(): () => void {
// Changing an inherited cursor on the document restyles every glyph in a large preview.
const surface = document.createElement("div");
surface.setAttribute("data-scrollbar-drag-surface", "");
surface.setAttribute("aria-hidden", "true");
document.body.appendChild(surface);
return () => surface.remove();
}
function untilDragEnds(cleanup: () => void): () => void {
const surface = cursorSurface(cursor);
listenForEnd();
let released = false;
const release = () => {
if (released) return;
released = true;
active.delete(release);
cleanup();
surface.remove();
};
active.add(release);
return release;
}
export function lockScrollbarCursor(): () => void {
const surface = cursorSurface("default");
return () => surface.remove();
}
function cursorSurface(cursor: DragCursor | "default") {
// Changing an inherited cursor restyles every glyph in a large editor.
const surface = document.createElement("div");
if (cursor === "default") surface.setAttribute("data-scrollbar-drag-surface", "");
else surface.setAttribute("data-drag-cursor-surface", cursor);
surface.style.cursor = cursor;
surface.setAttribute("aria-hidden", "true");
document.body.appendChild(surface);
return surface;
}