fix(editor): a fold click can miss folds that arrived asynchronously (#4165)

CodeMirror's fold gutter rebuilds its chevrons only on document, viewport or language changes, but backend folding ranges arrive through setBackendFolds, so a chevron could sit at a stale line and a click did nothing. The placeholder chip resolved its fold through the clicked line block, which can miss a fold starting at a line boundary (a Python docstring, an Allman header). The gutter now rebuilds whenever the backend fold field changes, and the chip resolves the fold at its own position, falling back to CodeMirror's handler.

Closes #4082

Co-authored-by: muutot <92625353+muutot@users.noreply.github.com>
This commit is contained in:
Muu
2026-11-18 17:06:47 +08:00
committed by GitHub
co-authored by muutot
parent bfd6f01471
commit 4d45ddc5a5
2 changed files with 120 additions and 5 deletions
+98 -1
View File
@@ -1,12 +1,17 @@
import { describe, expect, it } from "vitest";
import { EditorState } from "@codemirror/state";
import { codeFolding, foldEffect, foldService, foldedRanges } from "@codemirror/language";
import { EditorView } from "@codemirror/view";
import {
backendFoldingChanged,
backendFolds,
enclosingFoldRange,
expandToLevelEffects,
foldSelectionEffects,
foldToExpand,
foldsFromRanges,
foldingExtension,
foldToExpand,
setBackendFolds,
} from "./folding";
/** Folds `{ … }` blocks whose header line ends with `{`. */
@@ -159,3 +164,95 @@ describe("expandToLevelEffects", () => {
expect(folded(s.update({ effects: expandToLevelEffects(s, 2) }).state)).toEqual([]);
});
});
describe("fold gutter chevrons", () => {
const doc = ["def f():", ' """doc', " more", ' """', " pass"].join("\n");
it("backendFoldingChanged fires when backend folds arrive, not on selection moves", () => {
let changed = false;
const view = new EditorView({
state: EditorState.create({
doc,
extensions: [
foldingExtension(true),
// The same predicate the fold gutter's foldingChanged hook uses.
EditorView.updateListener.of((u) => {
if (backendFoldingChanged(u)) changed = true;
}),
],
}),
parent: document.body,
});
view.dispatch({ effects: setBackendFolds.of([{ start_line: 1, end_line: 3, kind: "comment" }]) });
expect(changed).toBe(true);
changed = false;
view.dispatch({ selection: { anchor: 0 } });
expect(changed).toBe(false);
view.destroy();
});
it("the gutter shows a chevron after backend folds arrive", () => {
const view = new EditorView({
state: EditorState.create({ doc, extensions: [foldingExtension(true)] }),
parent: document.body,
});
const markers = () =>
Array.from(view.dom.querySelectorAll<HTMLElement>(".cm-foldGutter .cm-gutterElement")).map(
(el) => el.firstElementChild?.className ?? "",
);
const before = markers();
view.dispatch({ effects: setBackendFolds.of([{ start_line: 1, end_line: 3, kind: "comment" }]) });
const after = markers();
expect(after.join("|")).not.toBe(before.join("|"));
view.destroy();
});
});
describe("fold placeholder chip", () => {
const doc = ["def f():", ' """doc', " more", ' """', " pass"].join("\n");
function foldedView() {
const view = new EditorView({
state: EditorState.create({ doc, extensions: [foldingExtension(true)] }),
parent: document.body,
});
view.dispatch({ effects: setBackendFolds.of([{ start_line: 1, end_line: 3, kind: "comment" }]) });
return view;
}
function folded(view: ReturnType<typeof foldedView>) {
const out: Array<[number, number]> = [];
foldedRanges(view.state).between(0, view.state.doc.length, (a, b) => void out.push([a, b]));
return out;
}
function fold(view: ReturnType<typeof foldedView>) {
const [f] = view.state.field(backendFolds);
view.dispatch({ effects: foldEffect.of({ from: f!.from, to: f!.to }) });
}
it("clicking the chip expands the fold, repeatedly", () => {
const view = foldedView();
for (let i = 0; i < 3; i++) {
fold(view);
const chip = view.dom.querySelector<HTMLElement>(".cm-foldPlaceholder");
expect(chip, `iteration ${i}`).not.toBeNull();
chip!.click();
expect(folded(view), `iteration ${i}`).toEqual([]);
}
view.destroy();
});
it("a chip whose position is the fold's start line still expands", () => {
const view = foldedView();
const [f] = view.state.field(backendFolds);
// A docstring fold starts at the end of its header line: a chip resolved
// through the line block would land on that line and find no fold.
expect(view.state.doc.lineAt(f!.from).to).toBe(f!.from);
fold(view);
const chip = view.dom.querySelector<HTMLElement>(".cm-foldPlaceholder")!;
chip.click();
expect(folded(view)).toEqual([]);
view.destroy();
});
});
+22 -4
View File
@@ -12,7 +12,7 @@ import {
type Extension,
type Line,
} from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import type { EditorView, ViewUpdate } from "@codemirror/view";
import {
codeFolding,
foldEffect,
@@ -392,22 +392,40 @@ function chevron(open: boolean): HTMLElement {
return span;
}
/**
* Backend folds arrive asynchronously (`setBackendFolds`) and are not a document,
* viewport or language change, so CodeMirror's fold gutter keeps the chevrons it
* built before they arrived. A click then hits a gutter element at a stale line
* and silently does nothing. Rebuild the markers whenever the backend field changes.
*/
export function backendFoldingChanged(update: ViewUpdate): boolean {
return update.startState.field(backendFolds, false) !== update.state.field(backendFolds, false);
}
export function foldingExtension(showOutline = true): Extension {
return [
// The chevron column sits right of contributed icon gutters (IDEA new UI).
showOutline ? Prec.lowest(foldGutter({ markerDOM: chevron })) : [],
showOutline ? Prec.lowest(foldGutter({ markerDOM: chevron, foldingChanged: backendFoldingChanged })) : [],
backendFolds,
backendFoldService,
codeFolding({
// A folded custom region shows its name, as in IDEA.
preparePlaceholder: (state, range) => regionNameAt(state, range.from),
placeholderDOM: (_view, onclick, name: string | null) => {
placeholderDOM: (view, onclick, name: string | null) => {
const el = document.createElement("span");
el.className = "cm-foldPlaceholder";
el.textContent = name ?? "…";
el.title = "Expand";
el.setAttribute("aria-label", "folded code");
el.onclick = onclick;
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,
// Allman header). Resolving at the chip's own position cannot miss.
const folded = foldToExpand(view.state, view.posAtDOM(el));
if (folded) view.dispatch({ effects: unfoldEffect.of(folded) });
else onclick(event);
event.preventDefault();
};
return el;
},
}),