diff --git a/e2e/editor.spec.ts b/e2e/editor.spec.ts index 405289c68..84ee08e0b 100644 --- a/e2e/editor.spec.ts +++ b/e2e/editor.spec.ts @@ -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, }) => { diff --git a/e2e/toolwindows.spec.ts b/e2e/toolwindows.spec.ts index 374d9c898..76e8bfbcb 100644 --- a/e2e/toolwindows.spec.ts +++ b/e2e/toolwindows.spec.ts @@ -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 }) => { diff --git a/src/features/viewers/markdown/Markdown.module.css b/src/features/viewers/markdown/Markdown.module.css index 8c5b0898b..0a7c734a7 100644 --- a/src/features/viewers/markdown/Markdown.module.css +++ b/src/features/viewers/markdown/Markdown.module.css @@ -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), diff --git a/src/features/viewers/markdown/MarkdownEditor.tsx b/src/features/viewers/markdown/MarkdownEditor.tsx index 1dc9073d6..ea82b0700 100644 --- a/src/features/viewers/markdown/MarkdownEditor.tsx +++ b/src/features/viewers/markdown/MarkdownEditor.tsx @@ -152,7 +152,6 @@ export function MarkdownEditor({
- [...root.querySelectorAll(":scope > [data-line]")].map((el) => ({ + [...root.querySelectorAll(":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 }} - /> + > +
+
); } diff --git a/src/features/viewers/markdown/highlight.ts b/src/features/viewers/markdown/highlight.ts index 970c474e5..c283b96d2 100644 --- a/src/features/viewers/markdown/highlight.ts +++ b/src/features/viewers/markdown/highlight.ts @@ -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(":scope > [data-line]")]; + const content = root.querySelector(":scope > [data-preview-blocks]") ?? root; + const els = [...content.querySelectorAll(":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); diff --git a/src/styles/global.css b/src/styles/global.css index da79ab4ed..3965281b7 100644 --- a/src/styles/global.css +++ b/src/styles/global.css @@ -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] *) { diff --git a/src/ui/Splitter.tsx b/src/ui/Splitter.tsx index 378ea0c02..606b6e866 100644 --- a/src/ui/Splitter.tsx +++ b/src/ui/Splitter.tsx @@ -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({ void) | undefined>(undefined); + useEffect(() => () => release.current?.(), []); return ( { + 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); diff --git a/src/ui/dragCursor.test.ts b/src/ui/dragCursor.test.ts index 8362f29fa..f0104d2ca 100644 --- a/src/ui/dragCursor.test.ts +++ b/src/ui/dragCursor.test.ts @@ -1,48 +1,42 @@ import { afterEach, describe, expect, it } from "vitest"; import { lockDragCursor } from "./dragCursor"; -const html = document.documentElement; +const surfaces = () => [...document.querySelectorAll("[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([]); }); }); diff --git a/src/ui/dragCursor.ts b/src/ui/dragCursor.ts index af1408735..3ebd0c267 100644 --- a/src/ui/dragCursor.ts +++ b/src/ui/dragCursor.ts @@ -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; +}