feat(plugins): the caret and selections in editor panels (#3904)

An editor panel's page can read the caret and every selection of its group's editor with openidea.editor.selections() (main selection first, then the others in file order; 0-based lines, UTF-16 columns) and hear them through onSelections, at most once a frame, also after an edit or a file switch. Documented under API 1.10; the editor-panel minimap fixture tints the selected lines and the caret's line.

Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com>
This commit is contained in:
LU XIANGRUI
2026-11-17 13:29:00 +08:00
committed by GitHub
co-authored by wildcatDownstairs
parent 4201aad9f9
commit ea1f1e54d0
6 changed files with 164 additions and 10 deletions
@@ -23,7 +23,8 @@
<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; folded lines left out.
// scrolls the editor; the marker bar's problems as bars at the right edge; folded lines left out;
// the selected lines tinted and the caret's line marked.
const editor = window.openidea.editor;
const canvas = document.getElementById("map");
const ctx = canvas.getContext("2d");
@@ -35,6 +36,7 @@
let view = null;
let problems = [];
let folds = [];
let selections = [];
const PROBLEM_COLOR = { error: "--openidea-danger", warning: "--openidea-warning" };
const PROBLEM_RANK = { error: 2, warning: 1 };
let drag = null;
@@ -103,6 +105,16 @@
const last = Math.min(L, Math.ceil((offset + H) / LINE));
const missing = [];
const muted = cssVar("--openidea-fg-muted");
// Selections under the text: the lines they cover tinted, a caret's line a stronger strip.
ctx.fillStyle = cssVar("--openidea-accent");
for (const s of selections) {
const caret = s.anchor.line === s.head.line && s.anchor.column === s.head.column;
const from = Math.floor(rowOf(Math.min(s.anchor.line, s.head.line)));
const to = Math.floor(rowOf(Math.max(s.anchor.line, s.head.line)));
ctx.globalAlpha = caret ? 0.6 : 0.3;
ctx.fillRect(0, from * LINE - offset, W, (to - from + 1) * LINE);
}
ctx.globalAlpha = 1;
for (let row = first; row < last; row++) {
const i = lineOfRow(row);
const y = row * LINE - offset;
@@ -171,6 +183,7 @@
// `problems` is API 1.10.
problems = editor.problems ? await editor.problems() : [];
folds = editor.folded ? await editor.folded() : [];
selections = editor.selections ? await editor.selections() : [];
view = Object.assign(await editor.viewport(), { version: target.version });
redraw();
}
@@ -199,6 +212,11 @@
folds = l.folded;
redraw();
});
if (editor.onSelections)
editor.onSelections((s) => {
selections = s;
redraw();
});
window.openidea.onThemeChange(redraw);
new ResizeObserver(redraw).observe(canvas);
+10 -4
View File
@@ -458,6 +458,10 @@ matching SDK. Released 1.9 plugins keep working. New in 1.10:
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_.
- **The caret and selections in editor panels.** An editor panel's page reads
the caret and every selection of its group's editor with
`openidea.editor.selections()` and hears them move through `onSelections`. See
_Editor panels_.
### API 1.9
@@ -1938,17 +1942,19 @@ The page gets `openidea.editor` (only an editor panel's page has it). Lines are
| `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 |
| `selections()` | API 1.10: the caret and selections: `[{ anchor: { line, column }, head: { line, column } }]`, the main selection first, the others in file order; a caret is a selection whose `anchor` equals `head` |
| `onSelections(fn)` | API 1.10: called with `selections()` when the caret moves, a selection changes, 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`, `folded`, `wrapped` or
`onLayout`: check for them (`if (editor.problems)`) when the page also runs in
`onThemeChange`). Before API 1.10 there is no `problems`, `folded`, `wrapped`,
`onLayout` or `selections`: 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.
there yet: 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, folded lines left out) to install and try.
2 px, its frame draggable, problems marked at its right edge, folded lines left out, the selected lines and the caret's line tinted) to install and try.
### Web frame PTYs (API 1.3)
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { render, waitFor } from "@testing-library/react";
import { javascript } from "@codemirror/lang-javascript";
import { codeFolding, foldEffect, syntaxHighlighting, unfoldEffect } from "@codemirror/language";
import { EditorState, StateEffect } from "@codemirror/state";
import { EditorSelection, EditorState, StateEffect } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import type { Diagnostic, PluginInfo } from "@/bindings";
import type { TextEditorHandle } from "@/editor/api";
@@ -80,11 +80,13 @@ describe("frame bridge: openidea.editor", () => {
problems(): Promise<unknown>;
folded(): Promise<unknown>;
wrapped(from: number, to: number): Promise<unknown>;
selections(): 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;
onSelections(fn: (v: unknown) => void): void;
document: unknown;
};
expect(editor.document).toBe(api.document);
@@ -112,6 +114,8 @@ describe("frame bridge: openidea.editor", () => {
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 } });
void editor.selections();
expect(sent.at(-1)).toMatchObject({ op: "editor.selections" });
const events: unknown[] = [];
editor.onTarget((v) => events.push(["target", v]));
@@ -119,11 +123,13 @@ describe("frame bridge: openidea.editor", () => {
editor.onHighlights((v) => events.push(["highlights", v]));
editor.onProblems((v) => events.push(["problems", v]));
editor.onLayout((v) => events.push(["layout", v]));
editor.onSelections((v) => events.push(["selections", 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: "selections", value: [] });
send({ editor: "constructor", value: 1 });
expect(events).toEqual([
["target", null],
@@ -131,6 +137,7 @@ describe("frame bridge: openidea.editor", () => {
["highlights", { fromLine: 0, toLine: 4 }],
["problems", []],
["layout", { folded: [], softWrap: true }],
["selections", []],
]);
});
@@ -158,6 +165,7 @@ describe("WebView as an editor panel", () => {
},
problems: () => [{ line: 1, lastLine: 2, severity: "warning" }],
folded: () => [{ fromLine: 0, toLine: 2 }],
selections: () => [{ anchor: { line: 1, column: 0 }, head: { line: 1, column: 4 } }],
wrapped: (from, to) => {
calls.push(["wrapped", from, to]);
return [1, 3];
@@ -227,6 +235,8 @@ describe("WebView as an editor panel", () => {
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]);
send({ call: 14, op: "editor.selections" });
expect((await reply(14)).value).toEqual([{ anchor: { line: 1, column: 0 }, head: { line: 1, column: 4 } }]);
editor.fire({ editor: "highlights", value: { fromLine: 0, toLine: 3 } });
expect(posted.at(-1)).toEqual({ tag: FRAME_TAG, editor: "highlights", value: { fromLine: 0, toLine: 3 } });
@@ -561,6 +571,83 @@ describe("PanelEditor problems", () => {
});
});
describe("PanelEditor selections", () => {
const view = (doc: string) => {
const parent = document.createElement("div");
document.body.appendChild(parent);
return new EditorView({
parent,
state: EditorState.create({
doc,
extensions: [EditorState.allowMultipleSelections.of(true), editorPanelUpdates],
}),
});
};
const handleOf = (v: EditorView, path: string): TextEditorHandle => ({
view: v,
tabId: path,
ctx: { doc: 1, path, language: "javascript", uiMode: "JavaScript", readOnly: false },
});
const at = (line: number, column: number) => ({ line, column });
it("reports the caret and every selection, the main one first, and follows them", async () => {
// Line 0 is "é😀ab": the emoji takes two UTF-16 columns.
const a = view("é😀ab\nsecond\nthird");
const panel = new PanelEditor();
const events: FrameEditorEvent[] = [];
panel.subscribe((e) => events.push(e));
panel.bind(handleOf(a, "/p/a.js"));
await nextFrame();
// Showing a file: its caret (at the start).
expect(events).toContainEqual({ editor: "selections", value: [{ anchor: at(0, 0), head: at(0, 0) }] });
// Two selections and a caret; the main one (the last) comes first, the others in file order.
events.length = 0;
const three = EditorSelection.create(
[EditorSelection.range(1, 3), EditorSelection.range(12, 7), EditorSelection.cursor(15)],
2,
);
a.dispatch({ selection: three });
const shown = [
{ anchor: at(2, 2), head: at(2, 2) },
{ anchor: at(0, 1), head: at(0, 3) },
{ anchor: at(1, 6), head: at(1, 1) },
];
expect(panel.selections()).toEqual(shown);
// Several moves in one frame: one event.
a.dispatch({ selection: EditorSelection.cursor(0) });
a.dispatch({ selection: three });
await nextFrame();
expect(events.filter((e) => e.editor === "selections")).toEqual([{ editor: "selections", value: shown }]);
// An edit above moves the caret to another line.
events.length = 0;
a.dispatch({ changes: { from: 0, insert: "\n" }, selection: EditorSelection.cursor(1) });
await nextFrame();
expect(events).toContainEqual({ editor: "selections", value: [{ anchor: at(1, 0), head: at(1, 0) }] });
// Scrolling alone says nothing.
events.length = 0;
a.scrollDOM.dispatchEvent(new Event("scroll"));
await nextFrame();
expect(events.filter((e) => e.editor === "selections")).toEqual([]);
// Another file: its selections.
const b = view("x\ny");
b.dispatch({ selection: EditorSelection.range(0, 3) });
events.length = 0;
panel.bind(handleOf(b, "/p/b.js"));
await nextFrame();
expect(events).toContainEqual({ editor: "selections", value: [{ anchor: at(0, 0), head: at(1, 1) }] });
panel.bind(null);
expect(panel.selections()).toEqual([]);
panel.dispose();
a.destroy();
b.destroy();
});
});
describe("editorPanels projection", () => {
it("shows the panel only while `editor.read` is granted and `when` holds", () => {
const plugin = (granted: boolean) =>
+18 -1
View File
@@ -107,6 +107,18 @@ export interface EditorFold {
toLine: number;
}
/** A position in the document: 0-based line, UTF-16 column. */
export interface EditorPosition {
line: number;
column: number;
}
/** A selection, as `openidea.editor.selections()` returns it; the caret is one whose `anchor` equals `head`. */
export interface EditorSelection {
anchor: EditorPosition;
head: EditorPosition;
}
/** What `openidea.editor.onLayout` hears: the folds, and whether long lines wrap. */
export interface EditorLayout {
folded: EditorFold[];
@@ -118,7 +130,8 @@ export type FrameEditorEvent =
| { editor: "viewport"; value: EditorViewport }
| { editor: "highlights"; value: { fromLine: number; toLine: number } }
| { editor: "problems"; value: EditorProblem[] }
| { editor: "layout"; value: EditorLayout };
| { editor: "layout"; value: EditorLayout }
| { editor: "selections"; value: EditorSelection[] };
/** The text editor an editor panel's frame follows (`openidea.editor`). */
export interface FrameEditor {
@@ -132,6 +145,8 @@ export interface FrameEditor {
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;
/** The main selection first, then the others in file order. */
selections(): EditorSelection[];
subscribe(listener: (event: FrameEditorEvent) => void): () => void;
}
@@ -403,11 +418,13 @@ export function WebView({
case "editor.highlights":
case "editor.problems":
case "editor.folded":
case "editor.selections":
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.selections") return [editor.selections()];
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"))];
+24 -2
View File
@@ -3,7 +3,7 @@
* 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), the
* marker bar's problems, the folds and the rows of wrapped lines, and scrolls the editor — straight
* marker bar's problems, the folds and the rows of wrapped lines, the caret and selections, and scrolls the editor — straight
* from the editor, not through the plugin's code, since a minimap follows every frame of a scroll.
*/
import { foldedRanges, highlightingFor, syntaxTree } from "@codemirror/language";
@@ -25,6 +25,7 @@ import {
type DocumentState,
type EditorFold,
type EditorProblem,
type EditorSelection,
type EditorTarget,
type EditorViewport,
type FrameDocument,
@@ -79,6 +80,7 @@ const nothingPending = () => ({
document: false,
problems: false,
layout: false,
selections: false,
lines: null as [number, number] | null,
});
@@ -141,6 +143,8 @@ 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 });
// An edit can move a caret to another line without changing its offset.
if (u.docChanged || !u.state.selection.eq(u.startState.selection)) this.schedule({ selections: 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)) {
@@ -167,7 +171,7 @@ export class PanelEditor implements FrameEditor {
set.delete(onUpdate);
if (!set.size) updateListeners.delete(view);
};
this.schedule({ viewport: true, problems: true, layout: true });
this.schedule({ viewport: true, problems: true, layout: true, selections: true });
}
this.emit({ editor: "target", value: this.get() });
}
@@ -318,6 +322,21 @@ export class PanelEditor implements FrameEditor {
return out;
}
selections(): EditorSelection[] {
const view = this.handle?.view;
if (!view) return [];
const { doc, selection } = view.state;
const position = (pos: number) => {
const line = doc.lineAt(pos);
return { line: line.number - 1, column: pos - line.from };
};
const main = selection.main;
return [main, ...selection.ranges.filter((_, i) => i !== selection.mainIndex)].map((r) => ({
anchor: position(r.anchor),
head: position(r.head),
}));
}
/** 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");
@@ -346,6 +365,7 @@ export class PanelEditor implements FrameEditor {
document?: boolean;
problems?: boolean;
layout?: boolean;
selections?: boolean;
lines?: [number, number];
}) {
const q = this.pending;
@@ -353,6 +373,7 @@ export class PanelEditor implements FrameEditor {
q.document ||= !!p.document;
q.problems ||= !!p.problems;
q.layout ||= !!p.layout;
q.selections ||= !!p.selections;
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());
}
@@ -375,6 +396,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 } });
if (q.selections) this.emit({ editor: "selections", value: this.selections() });
}
}
+5 -1
View File
@@ -19,7 +19,7 @@
const listeners = [];
const themeListeners = [];
const documentListeners = [];
const editorListeners = { target: [], viewport: [], highlights: [], problems: [], layout: [] };
const editorListeners = { target: [], viewport: [], highlights: [], problems: [], layout: [], selections: [] };
const editorPanel = /(?:^|[?&])openidea=editor-panel(?:&|$)/.test(location.search.slice(1));
const pending = new Map();
const root = document.documentElement;
@@ -159,6 +159,10 @@
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),
/** The caret and selections: `[{ anchor: { line, column }, head: { line, column } }]`, the main one first; a caret has `anchor` equal to `head`. */
selections: () => call("editor.selections"),
/** Called with `selections()` when the caret moves, a selection changes, or the group shows another file, at most once a frame. */
onSelections: listen(editorListeners.selections),
});
window.openidea = Object.freeze({