diff --git a/src/editor/core/cm/folding.test.ts b/src/editor/core/cm/folding.test.ts index a02b6df94..c1414c1cb 100644 --- a/src/editor/core/cm/folding.test.ts +++ b/src/editor/core/cm/folding.test.ts @@ -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(".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) { + 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) { + 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(".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(".cm-foldPlaceholder")!; + chip.click(); + expect(folded(view)).toEqual([]); + view.destroy(); + }); +}); diff --git a/src/editor/core/cm/folding.ts b/src/editor/core/cm/folding.ts index f999d4c69..8eecb31ea 100644 --- a/src/editor/core/cm/folding.ts +++ b/src/editor/core/cm/folding.ts @@ -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; }, }),