diff --git a/src/editor/core/cm/folding.test.ts b/src/editor/core/cm/folding.test.ts index a12d1f99f..15c5c7199 100644 --- a/src/editor/core/cm/folding.test.ts +++ b/src/editor/core/cm/folding.test.ts @@ -284,6 +284,27 @@ describe("fold placeholder chip", () => { expect(folded(view)).toEqual([]); view.destroy(); }); + + it("the chip swallows mousedown so a caret move cannot replace it before the click", () => { + const view = foldedView(); + fold(view); + const chip = view.dom.querySelector(".cm-foldPlaceholder")!; + // A mousedown must not reach the editor: CM turns it into a mouse selection + // that moves the caret, and the caret change re-runs the inline blame refresh, + // which rebuilds this line's DOM and detaches the chip between mousedown and + // click, so the browser drops the click. jsdom cannot reproduce the DOM + // replacement; this locks the handler contract. + let reachedEditor = false; + view.contentDOM.addEventListener("mousedown", () => (reachedEditor = true)); + const event = new MouseEvent("mousedown", { bubbles: true, cancelable: true }); + chip.dispatchEvent(event); + expect(event.defaultPrevented).toBe(true); + expect(reachedEditor).toBe(false); + // The click still expands. + chip.click(); + expect(folded(view)).toEqual([]); + view.destroy(); + }); }); describe("comment placeholders", () => { diff --git a/src/editor/core/cm/folding.ts b/src/editor/core/cm/folding.ts index b7e65b9f1..cfa4186a4 100644 --- a/src/editor/core/cm/folding.ts +++ b/src/editor/core/cm/folding.ts @@ -488,6 +488,16 @@ export function foldingExtension(showOutline = true): Extension { el.textContent = name ?? "…"; el.title = "Expand"; el.setAttribute("aria-label", "folded code"); + // The chip is a button, not a text anchor. Letting the mousedown through + // starts a mouse selection that moves the caret to the chip's line; a caret + // change re-runs the inline blame refresh, which replaces this line's DOM + // before the click fires, so the browser never dispatches the click + // (its down-target is no longer connected). Swallowing the mousedown + // keeps the caret where it is and the click reliably reaches `onclick`. + el.onmousedown = (event) => { + event.preventDefault(); + event.stopPropagation(); + }; el.onclick = (event) => { // CodeMirror's own handler resolves the fold through the clicked line // block, which can miss a fold starting at a line boundary (docstring,