mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-24 16:04:21 +00:00
feat(plugins): folded ranges and wrapped rows for editor panels (#3890)
An editor panel's page could not tell which lines are folded or how many rows a soft-wrapped line takes, so a minimap drew folded code and drifted from the editor. openidea.editor now has folded() ([{ fromLine, toLine }], nested folds merged), wrapped(fromLine, toLine) (visual rows per line, 0 for folded-away lines, null without soft wrap, at most 2000 lines) and onLayout(fn) with { folded, softWrap }, at most once a frame. Folds come from foldedRanges and rows from the editor's own line blocks.
Closes #3867
Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com>
This commit is contained in:
co-authored by
wildcatDownstairs
parent
7096a1c374
commit
ebc879dc8b
@@ -1,8 +1,8 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { render, waitFor } from "@testing-library/react";
|
||||
import { javascript } from "@codemirror/lang-javascript";
|
||||
import { syntaxHighlighting } from "@codemirror/language";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { codeFolding, foldEffect, syntaxHighlighting, unfoldEffect } from "@codemirror/language";
|
||||
import { EditorState, StateEffect } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import type { Diagnostic, PluginInfo } from "@/bindings";
|
||||
import type { TextEditorHandle } from "@/editor/api";
|
||||
@@ -78,10 +78,13 @@ describe("frame bridge: openidea.editor", () => {
|
||||
scrollBy(pixels: number): Promise<unknown>;
|
||||
highlights(from: number, to: number): Promise<unknown>;
|
||||
problems(): Promise<unknown>;
|
||||
folded(): Promise<unknown>;
|
||||
wrapped(from: number, to: number): Promise<unknown>;
|
||||
onTarget(fn: (v: unknown) => void): void;
|
||||
onViewport(fn: (v: unknown) => void): void;
|
||||
onHighlights(fn: (v: unknown) => void): void;
|
||||
onProblems(fn: (v: unknown) => void): void;
|
||||
onLayout(fn: (v: unknown) => void): void;
|
||||
document: unknown;
|
||||
};
|
||||
expect(editor.document).toBe(api.document);
|
||||
@@ -105,22 +108,29 @@ describe("frame bridge: openidea.editor", () => {
|
||||
expect(sent.at(-1)).toMatchObject({ op: "editor.problems" });
|
||||
send({ reply: sent.at(-1)!.call, value: [{ line: 2, lastLine: 2, severity: "error" }] });
|
||||
await expect(problems).resolves.toEqual([{ line: 2, lastLine: 2, severity: "error" }]);
|
||||
void editor.folded();
|
||||
expect(sent.at(-1)).toMatchObject({ op: "editor.folded" });
|
||||
void editor.wrapped(4, 9);
|
||||
expect(sent.at(-1)).toMatchObject({ op: "editor.wrapped", args: { fromLine: 4, toLine: 9 } });
|
||||
|
||||
const events: unknown[] = [];
|
||||
editor.onTarget((v) => events.push(["target", v]));
|
||||
editor.onViewport((v) => events.push(["viewport", v]));
|
||||
editor.onHighlights((v) => events.push(["highlights", v]));
|
||||
editor.onProblems((v) => events.push(["problems", v]));
|
||||
editor.onLayout((v) => events.push(["layout", v]));
|
||||
send({ editor: "target", value: null });
|
||||
send({ editor: "viewport", value: { firstLine: 1.5 } });
|
||||
send({ editor: "highlights", value: { fromLine: 0, toLine: 4 } });
|
||||
send({ editor: "problems", value: [] });
|
||||
send({ editor: "layout", value: { folded: [], softWrap: true } });
|
||||
send({ editor: "constructor", value: 1 });
|
||||
expect(events).toEqual([
|
||||
["target", null],
|
||||
["viewport", { firstLine: 1.5 }],
|
||||
["highlights", { fromLine: 0, toLine: 4 }],
|
||||
["problems", []],
|
||||
["layout", { folded: [], softWrap: true }],
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -147,6 +157,11 @@ describe("WebView as an editor panel", () => {
|
||||
return [[{ from: 0, to: 5, color: "rgb(1, 2, 3)" }]];
|
||||
},
|
||||
problems: () => [{ line: 1, lastLine: 2, severity: "warning" }],
|
||||
folded: () => [{ fromLine: 0, toLine: 2 }],
|
||||
wrapped: (from, to) => {
|
||||
calls.push(["wrapped", from, to]);
|
||||
return [1, 3];
|
||||
},
|
||||
subscribe: (l) => {
|
||||
listeners.add(l);
|
||||
return () => void listeners.delete(l);
|
||||
@@ -203,6 +218,15 @@ describe("WebView as an editor panel", () => {
|
||||
expect((await reply(8)).error).toBeDefined();
|
||||
send({ call: 9, op: "editor.problems" });
|
||||
expect((await reply(9)).value).toEqual([{ line: 1, lastLine: 2, severity: "warning" }]);
|
||||
send({ call: 10, op: "editor.folded" });
|
||||
expect((await reply(10)).value).toEqual([{ fromLine: 0, toLine: 2 }]);
|
||||
send({ call: 11, op: "editor.wrapped", args: { fromLine: 1, toLine: 3 } });
|
||||
expect((await reply(11)).value).toEqual([1, 3]);
|
||||
send({ call: 12, op: "editor.wrapped", args: { fromLine: 0, toLine: 2001 } });
|
||||
expect(String((await reply(12)).error)).toContain("2000");
|
||||
send({ call: 13, op: "editor.wrapped", args: { fromLine: 0.5, toLine: 2 } });
|
||||
expect((await reply(13)).error).toBeDefined();
|
||||
expect(calls.at(-1)).toEqual(["wrapped", 1, 3]);
|
||||
|
||||
editor.fire({ editor: "highlights", value: { fromLine: 0, toLine: 3 } });
|
||||
expect(posted.at(-1)).toEqual({ tag: FRAME_TAG, editor: "highlights", value: { fromLine: 0, toLine: 3 } });
|
||||
@@ -358,6 +382,103 @@ describe("PanelEditor semantic highlights", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("PanelEditor layout", () => {
|
||||
it("reports the folded lines and the rows of wrapped lines, and follows them", async () => {
|
||||
const long = "x".repeat(200);
|
||||
const parent = document.createElement("div");
|
||||
document.body.appendChild(parent);
|
||||
const view = new EditorView({
|
||||
parent,
|
||||
state: EditorState.create({
|
||||
doc: `function f() {\n a;\n b;\n}\n${long}\nend`,
|
||||
extensions: [codeFolding(), editorPanelUpdates],
|
||||
}),
|
||||
});
|
||||
const handle: TextEditorHandle = {
|
||||
view,
|
||||
tabId: "t1",
|
||||
ctx: { doc: 1, path: "/p/src/a.js", language: "javascript", uiMode: "JavaScript", readOnly: false },
|
||||
};
|
||||
const panel = new PanelEditor();
|
||||
const events: FrameEditorEvent[] = [];
|
||||
panel.subscribe((e) => events.push(e));
|
||||
panel.bind(handle);
|
||||
await nextFrame();
|
||||
// Neither: no folds, no rows (switching to a file says so).
|
||||
expect(panel.folded()).toEqual([]);
|
||||
expect(panel.wrapped(0, 6)).toBeNull();
|
||||
expect(events.filter((e) => e.editor === "layout")).toEqual([
|
||||
{ editor: "layout", value: { folded: [], softWrap: false } },
|
||||
]);
|
||||
|
||||
// Folding lines 1–2 (the `{` line stays, `}` joins it), and a fold inside it.
|
||||
events.length = 0;
|
||||
const open = view.state.doc.line(1).to;
|
||||
const close = view.state.doc.line(4).from;
|
||||
view.dispatch({
|
||||
effects: [foldEffect.of({ from: open, to: close }), foldEffect.of({ from: open + 3, to: open + 6 })],
|
||||
});
|
||||
await nextFrame();
|
||||
const folds = [{ fromLine: 0, toLine: 3 }];
|
||||
expect(panel.folded()).toEqual(folds);
|
||||
expect(events.filter((e) => e.editor === "layout")).toEqual([
|
||||
{ editor: "layout", value: { folded: folds, softWrap: false } },
|
||||
]);
|
||||
|
||||
// Soft wrap on: the long line takes several rows, the folded ones none. jsdom lays nothing
|
||||
// out, so the measured state stands in: wrapping on, the long line's block three rows high.
|
||||
events.length = 0;
|
||||
let wrapping = false;
|
||||
Object.defineProperty(view, "lineWrapping", { get: () => wrapping });
|
||||
const lineBlockAt = view.lineBlockAt.bind(view);
|
||||
vi.spyOn(view, "lineBlockAt").mockImplementation((pos) => {
|
||||
const b = lineBlockAt(pos);
|
||||
return b.from === view.state.doc.line(5).from
|
||||
? Object.assign(Object.create(b), { height: 3 * view.defaultLineHeight })
|
||||
: b;
|
||||
});
|
||||
wrapping = true;
|
||||
view.dispatch({ effects: StateEffect.appendConfig.of(EditorView.lineWrapping) });
|
||||
await nextFrame();
|
||||
const rows = panel.wrapped(0, 6)!;
|
||||
expect(rows).toEqual([1, 0, 0, 0, 3, 1]);
|
||||
expect(panel.wrapped(4, 99)).toEqual(rows.slice(4));
|
||||
expect(events.filter((e) => e.editor === "layout")).toEqual([
|
||||
{ editor: "layout", value: { folded: folds, softWrap: true } },
|
||||
]);
|
||||
|
||||
// The outer fold opened: the lines come back, but for the inner fold's.
|
||||
events.length = 0;
|
||||
view.dispatch({ effects: unfoldEffect.of({ from: open, to: close }) });
|
||||
await nextFrame();
|
||||
const inner = [{ fromLine: 1, toLine: 2 }];
|
||||
expect(panel.folded()).toEqual(inner);
|
||||
expect(panel.wrapped(0, 4)).toEqual([1, 1, 0, 1]);
|
||||
expect(events.filter((e) => e.editor === "layout")).toEqual([
|
||||
{ editor: "layout", value: { folded: inner, softWrap: true } },
|
||||
]);
|
||||
|
||||
// Soft wrap off: no rows.
|
||||
events.length = 0;
|
||||
wrapping = false;
|
||||
view.dispatch({ effects: StateEffect.reconfigure.of([codeFolding(), editorPanelUpdates]) });
|
||||
await nextFrame();
|
||||
expect(panel.wrapped(0, 4)).toBeNull();
|
||||
expect(events.filter((e) => e.editor === "layout")).toEqual([
|
||||
{ editor: "layout", value: { folded: inner, softWrap: false } },
|
||||
]);
|
||||
|
||||
// Selecting alone says nothing.
|
||||
events.length = 0;
|
||||
view.dispatch({ selection: { anchor: 2 } });
|
||||
await nextFrame();
|
||||
expect(events.filter((e) => e.editor === "layout")).toEqual([]);
|
||||
|
||||
panel.dispose();
|
||||
view.destroy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("PanelEditor problems", () => {
|
||||
const PATH = "/p/src/problems.js";
|
||||
const at = (line: number, col: number, endLine = line, endCol = col + 1) => ({
|
||||
|
||||
@@ -99,11 +99,26 @@ export interface EditorProblem {
|
||||
severity: "error" | "warning" | "weakWarning";
|
||||
}
|
||||
|
||||
/** A fold, as `openidea.editor.folded()` returns it: 0-based lines. */
|
||||
export interface EditorFold {
|
||||
/** The line that stays visible, showing the placeholder. */
|
||||
fromLine: number;
|
||||
/** The last line the fold hides. */
|
||||
toLine: number;
|
||||
}
|
||||
|
||||
/** What `openidea.editor.onLayout` hears: the folds, and whether long lines wrap. */
|
||||
export interface EditorLayout {
|
||||
folded: EditorFold[];
|
||||
softWrap: boolean;
|
||||
}
|
||||
|
||||
export type FrameEditorEvent =
|
||||
| { editor: "target"; value: EditorTarget | null }
|
||||
| { editor: "viewport"; value: EditorViewport }
|
||||
| { editor: "highlights"; value: { fromLine: number; toLine: number } }
|
||||
| { editor: "problems"; value: EditorProblem[] };
|
||||
| { editor: "problems"; value: EditorProblem[] }
|
||||
| { editor: "layout"; value: EditorLayout };
|
||||
|
||||
/** The text editor an editor panel's frame follows (`openidea.editor`). */
|
||||
export interface FrameEditor {
|
||||
@@ -114,6 +129,9 @@ export interface FrameEditor {
|
||||
/** Lines `fromLine` up to `toLine` (exclusive); throws over {@link MAX_HIGHLIGHT_LINES}. */
|
||||
highlights(fromLine: number, toLine: number): HighlightSpan[][];
|
||||
problems(): EditorProblem[];
|
||||
folded(): EditorFold[];
|
||||
/** Visual rows of lines `fromLine` up to `toLine` (0 for lines folds hide), or null without soft wrap. */
|
||||
wrapped(fromLine: number, toLine: number): number[] | null;
|
||||
subscribe(listener: (event: FrameEditorEvent) => void): () => void;
|
||||
}
|
||||
|
||||
@@ -383,10 +401,13 @@ export function WebView({
|
||||
case "editor.scrollTo":
|
||||
case "editor.scrollBy":
|
||||
case "editor.highlights":
|
||||
case "editor.problems": {
|
||||
case "editor.problems":
|
||||
case "editor.folded":
|
||||
case "editor.wrapped": {
|
||||
if (!editor) throw new Error("this view is not an editor panel");
|
||||
if (op === "editor.get") return [editor.get()];
|
||||
if (op === "editor.problems") return [editor.problems()];
|
||||
if (op === "editor.folded") return [editor.folded()];
|
||||
if (op === "editor.viewport") return [editor.viewport()];
|
||||
if (op === "editor.scrollTo") return [editor.scrollTo(finite(args.line, "line"))];
|
||||
if (op === "editor.scrollBy") return [editor.scrollBy(finite(args.pixels, "pixels"))];
|
||||
@@ -395,7 +416,7 @@ export function WebView({
|
||||
if (!Number.isInteger(from) || !Number.isInteger(to) || from < 0 || to < from)
|
||||
throw new Error("lines are 0 ≤ fromLine ≤ toLine, whole numbers");
|
||||
if (to - from > MAX_HIGHLIGHT_LINES) throw new Error(`at most ${MAX_HIGHLIGHT_LINES} lines at a time`);
|
||||
return [editor.highlights(from, to)];
|
||||
return [op === "editor.wrapped" ? editor.wrapped(from, to) : editor.highlights(from, to)];
|
||||
}
|
||||
case "saveFile":
|
||||
case "openFile": {
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
* Plugin editor panels (`[[contributes.editorPanels]]`): a web page at the right edge of every
|
||||
* editor group, following the group's text editor (a minimap, say). Each group has one frame,
|
||||
* kept while the group switches tabs: the page hears `onTarget` instead of reloading. Through
|
||||
* `openidea.editor` it reads the file (read-only), the viewport, the colours (syntax and semantic) and the
|
||||
* marker bar's problems, and scrolls the editor — straight from the editor, not through the
|
||||
* plugin's code, since a minimap follows every frame of a scroll.
|
||||
* `openidea.editor` it reads the file (read-only), the viewport, the colours (syntax and semantic), the
|
||||
* marker bar's problems, the folds and the rows of wrapped lines, and scrolls the editor — straight
|
||||
* from the editor, not through the plugin's code, since a minimap follows every frame of a scroll.
|
||||
*/
|
||||
import { highlightingFor, syntaxTree } from "@codemirror/language";
|
||||
import { foldedRanges, highlightingFor, syntaxTree } from "@codemirror/language";
|
||||
import { RangeSet, type Range } from "@codemirror/state";
|
||||
import { Decoration, ViewPlugin, type EditorView, type ViewUpdate } from "@codemirror/view";
|
||||
import { BlockType, Decoration, ViewPlugin, type EditorView, type ViewUpdate } from "@codemirror/view";
|
||||
import { highlightTree } from "@lezer/highlight";
|
||||
import { useEffect, useMemo } from "react";
|
||||
import type { Severity } from "@/bindings";
|
||||
@@ -23,6 +23,7 @@ import { basename } from "./customEditor";
|
||||
import {
|
||||
WebView,
|
||||
type DocumentState,
|
||||
type EditorFold,
|
||||
type EditorProblem,
|
||||
type EditorTarget,
|
||||
type EditorViewport,
|
||||
@@ -81,6 +82,7 @@ const nothingPending = () => ({
|
||||
viewport: false,
|
||||
document: false,
|
||||
problems: false,
|
||||
layout: false,
|
||||
lines: null as [number, number] | null,
|
||||
});
|
||||
|
||||
@@ -123,6 +125,7 @@ export class PanelEditor implements FrameEditor {
|
||||
if (handle) {
|
||||
const { view } = handle;
|
||||
const onScroll = () => this.schedule({ viewport: true });
|
||||
let softWrap = view.lineWrapping;
|
||||
const onUpdate = (u: ViewUpdate) => {
|
||||
const lines = u.state.doc.lines;
|
||||
if (u.docChanged) {
|
||||
@@ -142,6 +145,12 @@ export class PanelEditor implements FrameEditor {
|
||||
}
|
||||
if (u.geometryChanged || u.heightChanged || u.viewportChanged) this.schedule({ viewport: true });
|
||||
if (markerBarProblems(u.startState) !== markerBarProblems(u.state)) this.schedule({ problems: true });
|
||||
// Wrapped rows follow the line blocks' heights.
|
||||
const wrap = u.view.lineWrapping;
|
||||
if (foldedRanges(u.startState) !== foldedRanges(u.state) || wrap !== softWrap || (wrap && u.heightChanged)) {
|
||||
softWrap = wrap;
|
||||
this.schedule({ layout: true });
|
||||
}
|
||||
const semBefore = semanticHighlights(u.startState);
|
||||
const semAfter = semanticHighlights(u.state);
|
||||
if (semBefore !== semAfter) {
|
||||
@@ -162,7 +171,7 @@ export class PanelEditor implements FrameEditor {
|
||||
set.delete(onUpdate);
|
||||
if (!set.size) updateListeners.delete(view);
|
||||
};
|
||||
this.schedule({ viewport: true, problems: true });
|
||||
this.schedule({ viewport: true, problems: true, layout: true });
|
||||
}
|
||||
this.emit({ editor: "target", value: this.get() });
|
||||
}
|
||||
@@ -275,6 +284,44 @@ export class PanelEditor implements FrameEditor {
|
||||
}));
|
||||
}
|
||||
|
||||
folded(): EditorFold[] {
|
||||
const view = this.handle?.view;
|
||||
if (!view) return [];
|
||||
const doc = view.state.doc;
|
||||
const out: EditorFold[] = [];
|
||||
foldedRanges(view.state).between(0, doc.length, (from, to) => {
|
||||
const fromLine = doc.lineAt(from).number - 1;
|
||||
const toLine = doc.lineAt(to).number - 1;
|
||||
const last = out.at(-1);
|
||||
// Folds inside a fold, or starting on the row it ends on, are part of it.
|
||||
if (last && fromLine <= last.toLine) last.toLine = Math.max(last.toLine, toLine);
|
||||
else if (toLine > fromLine) out.push({ fromLine, toLine });
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
wrapped(fromLine: number, toLine: number): number[] | null {
|
||||
const view = this.handle?.view;
|
||||
if (!view?.lineWrapping) return null;
|
||||
const doc = view.state.doc;
|
||||
const out: number[] = [];
|
||||
for (let n = fromLine + 1; n <= Math.min(toLine, doc.lines); n++) {
|
||||
const line = doc.line(n);
|
||||
// The editor's own line blocks: measured in the viewport, estimated elsewhere.
|
||||
const block = view.lineBlockAt(line.from);
|
||||
if (block.from < line.from) {
|
||||
out.push(0);
|
||||
continue;
|
||||
}
|
||||
// Block widgets (above or below the line) are not rows of its text.
|
||||
const height = Array.isArray(block.type)
|
||||
? block.type.reduce((h, b) => (b.type === BlockType.Text ? h + b.height : h), 0)
|
||||
: block.height;
|
||||
out.push(Math.max(1, Math.round(height / view.defaultLineHeight)));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The text colour of spans nested with these classes (outermost first), as the current scheme resolves it. */
|
||||
private color(view: EditorView, nested: string[]): string {
|
||||
const key = nested.join("\n");
|
||||
@@ -298,11 +345,18 @@ export class PanelEditor implements FrameEditor {
|
||||
for (const l of this.listeners) l(e);
|
||||
}
|
||||
|
||||
private schedule(p: { viewport?: boolean; document?: boolean; problems?: boolean; lines?: [number, number] }) {
|
||||
private schedule(p: {
|
||||
viewport?: boolean;
|
||||
document?: boolean;
|
||||
problems?: boolean;
|
||||
layout?: boolean;
|
||||
lines?: [number, number];
|
||||
}) {
|
||||
const q = this.pending;
|
||||
q.viewport ||= !!p.viewport;
|
||||
q.document ||= !!p.document;
|
||||
q.problems ||= !!p.problems;
|
||||
q.layout ||= !!p.layout;
|
||||
if (p.lines) q.lines = q.lines ? [Math.min(q.lines[0], p.lines[0]), Math.max(q.lines[1], p.lines[1])] : p.lines;
|
||||
if (!this.frame) this.frame = requestAnimationFrame(() => this.flush());
|
||||
}
|
||||
@@ -324,6 +378,7 @@ export class PanelEditor implements FrameEditor {
|
||||
}
|
||||
if (q.viewport) this.emit({ editor: "viewport", value: this.viewport()! });
|
||||
if (q.problems) this.emit({ editor: "problems", value: this.problems() });
|
||||
if (q.layout) this.emit({ editor: "layout", value: { folded: this.folded(), softWrap: view.lineWrapping } });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
const listeners = [];
|
||||
const themeListeners = [];
|
||||
const documentListeners = [];
|
||||
const editorListeners = { target: [], viewport: [], highlights: [], problems: [] };
|
||||
const editorListeners = { target: [], viewport: [], highlights: [], problems: [], layout: [] };
|
||||
const editorPanel = /(?:^|[?&])openidea=editor-panel(?:&|$)/.test(location.search.slice(1));
|
||||
const pending = new Map();
|
||||
const root = document.documentElement;
|
||||
@@ -153,6 +153,12 @@
|
||||
problems: () => call("editor.problems"),
|
||||
/** Called with `problems()` when a problem appears or goes away, or its lines move, at most once a frame. */
|
||||
onProblems: listen(editorListeners.problems),
|
||||
/** The folded ranges: `[{ fromLine, toLine }]`, the line that stays visible and the last one hidden. */
|
||||
folded: () => call("editor.folded"),
|
||||
/** Visual rows of lines `fromLine` up to `toLine` (exclusive), at most 2000; 0 for folded-away lines. Null without soft wrap. */
|
||||
wrapped: (fromLine, toLine) => call("editor.wrapped", { fromLine: Number(fromLine), toLine: Number(toLine) }),
|
||||
/** Called with `{ folded, softWrap }` when folds change, soft wrap turns on or off, or wrapped rows may have changed, at most once a frame. */
|
||||
onLayout: listen(editorListeners.layout),
|
||||
});
|
||||
|
||||
window.openidea = Object.freeze({
|
||||
|
||||
Reference in New Issue
Block a user