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:
LU XIANGRUI
2026-11-17 12:32:03 +08:00
committed by GitHub
co-authored by wildcatDownstairs
parent 7096a1c374
commit ebc879dc8b
6 changed files with 271 additions and 27 deletions
+42 -10
View File
@@ -23,7 +23,7 @@
<script>
// A minimal minimap over `openidea.editor`: each line 2px high, each character 1px wide,
// in its highlight colour; the visible area as a frame that can be dragged; the wheel
// scrolls the editor; the marker bar's problems as bars at the right edge.
// scrolls the editor; the marker bar's problems as bars at the right edge; folded lines left out.
const editor = window.openidea.editor;
const canvas = document.getElementById("map");
const ctx = canvas.getContext("2d");
@@ -34,6 +34,7 @@
let loading = new Set();
let view = null;
let problems = [];
let folds = [];
const PROBLEM_COLOR = { error: "--openidea-danger", warning: "--openidea-warning" };
const PROBLEM_RANK = { error: 2, warning: 1 };
let drag = null;
@@ -45,17 +46,39 @@
};
const cssVar = (name) => (window.openidea.theme && window.openidea.theme.vars[name]) || "";
// Document lines ↔ minimap rows, without the lines folds hide (fractional within a fold's row).
const rowOf = (line) => {
let hidden = 0;
for (const f of folds) {
if (line >= f.toLine + 1) hidden += f.toLine - f.fromLine;
else if (line > f.fromLine) return f.fromLine - hidden + (line - f.fromLine) / (f.toLine + 1 - f.fromLine);
else break;
}
return line - hidden;
};
const lineOfRow = (row) => {
let hidden = 0;
for (const f of folds) {
const r = f.fromLine - hidden;
if (row >= r + 1) hidden += f.toLine - f.fromLine;
else if (row > r) return f.fromLine + (row - r) * (f.toLine + 1 - f.fromLine);
else break;
}
return row + hidden;
};
function layout() {
const H = canvas.clientHeight;
if (!view) return { H, offset: 0, top: 0, height: 0, range: 1, visible: 0 };
const L = Math.max(1, view.lineCount);
const visible = Math.max(0, view.lastLine - view.firstLine);
const L = Math.max(1, rowOf(view.lineCount));
const firstRow = rowOf(view.firstLine);
const visible = Math.max(0, rowOf(view.lastLine) - firstRow);
const scrollable = Math.max(1, view.scrollHeight - view.clientHeight);
const p = Math.min(1, Math.max(0, view.scrollTop / scrollable));
const mapH = L * LINE;
const offset = p * Math.max(0, mapH - H);
const range = Math.max(1, Math.min(H, mapH) - visible * LINE);
return { H, offset, top: view.firstLine * LINE - offset, height: visible * LINE, range, visible, L };
return { H, offset, top: firstRow * LINE - offset, height: visible * LINE, range, visible, L };
}
function redraw() {
@@ -68,7 +91,7 @@
queued = false;
const dpr = window.devicePixelRatio || 1;
const W = canvas.clientWidth;
const { H, offset, top, height } = layout();
const { H, offset, top, height, L } = layout();
if (canvas.width !== Math.round(W * dpr) || canvas.height !== Math.round(H * dpr)) {
canvas.width = Math.round(W * dpr);
canvas.height = Math.round(H * dpr);
@@ -77,11 +100,12 @@
ctx.clearRect(0, 0, W, H);
if (!view) return;
const first = Math.floor(offset / LINE);
const last = Math.min(text.length, Math.ceil((offset + H) / LINE));
const last = Math.min(L, Math.ceil((offset + H) / LINE));
const missing = [];
const muted = cssVar("--openidea-fg-muted");
for (let i = first; i < last; i++) {
const y = i * LINE - offset;
for (let row = first; row < last; row++) {
const i = lineOfRow(row);
const y = row * LINE - offset;
const line = text[i] || "";
// Text without a syntax colour: faint, so the coloured spans stand out.
ctx.globalAlpha = 0.2;
@@ -102,7 +126,8 @@
const ranked = [...problems].sort((a, b) => (PROBLEM_RANK[a.severity] || 0) - (PROBLEM_RANK[b.severity] || 0));
for (const p of ranked) {
ctx.fillStyle = cssVar(PROBLEM_COLOR[p.severity] || "--openidea-fg-muted");
ctx.fillRect(W - 3, p.line * LINE - offset, 3, Math.max(LINE, (p.lastLine - p.line + 1) * LINE));
const y = Math.floor(rowOf(p.line));
ctx.fillRect(W - 3, y * LINE - offset, 3, Math.max(LINE, (Math.floor(rowOf(p.lastLine)) - y + 1) * LINE));
}
// The visible area: a light accent tint and a 1px border, stronger while dragged.
const frameH = Math.max(height, 4);
@@ -145,6 +170,7 @@
text = doc.text.split("\n");
// `problems` is API 1.10.
problems = editor.problems ? await editor.problems() : [];
folds = editor.folded ? await editor.folded() : [];
view = Object.assign(await editor.viewport(), { version: target.version });
redraw();
}
@@ -167,6 +193,12 @@
problems = p;
redraw();
});
// `onLayout` is API 1.10.
if (editor.onLayout)
editor.onLayout((l) => {
folds = l.folded;
redraw();
});
window.openidea.onThemeChange(redraw);
new ResizeObserver(redraw).observe(canvas);
@@ -174,7 +206,7 @@
const scrollToFrameTop = (frameTop) => {
const { range, visible, L } = layout();
const p = Math.min(1, Math.max(0, frameTop / range));
void editor.scrollTo(p * Math.max(0, L - visible));
void editor.scrollTo(lineOfRow(p * Math.max(0, L - visible)));
};
canvas.addEventListener("pointerdown", (e) => {
if (!view) return;
+13 -4
View File
@@ -454,6 +454,10 @@ matching SDK. Released 1.9 plugins keep working. New in 1.10:
returns the colours the editor shows, semantic highlighting from the language
server layered over the syntax colours, and `onHighlights` reports the lines
whose colours change when semantic tokens arrive. See _Editor panels_.
- **Folds and soft wrap in editor panels.** An editor panel's page reads which
lines are folded with `openidea.editor.folded()`, how many rows each line takes
with soft wrap on with `wrapped(fromLine, toLine)`, and hears both change
through `onLayout`. See _Editor panels_.
### API 1.9
@@ -1931,15 +1935,20 @@ The page gets `openidea.editor` (only an editor panel's page has it). Lines are
| `onHighlights(fn)` | `{ fromLine, toLine }` whose colours may have changed: parsing progressed, the file was edited, the colour scheme changed, semantic tokens arrived (API 1.10) |
| `problems()` | API 1.10: the problems the marker bar shows, in file order: `[{ line, lastLine, severity }]`, `lastLine` the last line a problem covers, `severity` `error`, `warning` or `weakWarning` |
| `onProblems(fn)` | API 1.10: called with `problems()` when a problem appears or goes away, when edits move them, and when the group shows another file; at most once a frame |
| `folded()` | API 1.10: the folded ranges, in file order: `[{ fromLine, toLine }]`, `fromLine` the line that stays visible (with the placeholder), `toLine` the last line hidden. Folds inside a fold are part of it |
| `wrapped(fromLine, toLine)` | API 1.10: the visual rows of each line from `fromLine` up to `toLine` (exclusive, at most 2000 lines): 1 for a line that fits, 0 for a line a fold hides; `null` while soft wrap is off |
| `onLayout(fn)` | API 1.10: called with `{ folded, softWrap }` (`folded()`, and whether soft wrap is on) when folds change, soft wrap turns on or off, wrapped rows may have changed, and the group shows another file; at most once a frame |
Colours are the editor's: syntax highlighting and, from API 1.10, the semantic
highlighting over it (a semantic colour wins where both apply). The
panel's other colours are the frame's theme variables (`openidea.theme`,
`onThemeChange`). Before API 1.10 there is no `problems`: check for it
(`if (editor.problems)`) when the page also runs in older IDEs. Not there yet:
the caret and selections, and the marker bar's changes.
`onThemeChange`). Before API 1.10 there is no `problems`, `folded`, `wrapped` or
`onLayout`: check for them (`if (editor.problems)`) when the page also runs in
older IDEs. Outside the visible area the editor estimates wrapped rows from the
line's length until it lays the line out; `onLayout` follows when it does. Not
there yet: the caret and selections, and the marker bar's changes.
`crates/ide-plugin/tests/fixtures/editor-panel` is a minimal minimap (each line
2 px, its frame draggable, problems marked at its right edge) to install and try.
2 px, its frame draggable, problems marked at its right edge, folded lines left out) to install and try.
### Web frame PTYs (API 1.3)
@@ -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) => ({
+24 -3
View File
@@ -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": {
+62 -7
View File
@@ -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 } });
}
}
+7 -1
View File
@@ -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({