feat(plugins): the change-marker lane's VCS changes in editor panels (#3905)

An editor panel's page can read the added, modified and deleted lines the change-marker lane shows with openidea.editor.changes() ([{ line, lastLine, kind }] in file order, [] outside version control) and hear them through onChanges, at most once a frame. The values are the lane's own hunks: hunkField provides a new lineChanges facet in src/editor/api.ts, so the panel reads them without importing the VCS feature. Frames get the lane's colours as --openidea-change-added / -modified / -deleted. Documented under API 1.10; the minimap fixture marks changes at its left edge.

Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com>
This commit is contained in:
LU XIANGRUI
2026-11-17 13:30:29 +08:00
committed by GitHub
co-authored by wildcatDownstairs
parent ea1f1e54d0
commit 449db6baa7
9 changed files with 193 additions and 12 deletions
@@ -24,7 +24,7 @@
// 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;
// the selected lines tinted and the caret's line marked.
// the selected lines tinted and the caret's line marked; VCS changes at the left edge.
const editor = window.openidea.editor;
const canvas = document.getElementById("map");
const ctx = canvas.getContext("2d");
@@ -37,6 +37,7 @@
let problems = [];
let folds = [];
let selections = [];
let changes = [];
const PROBLEM_COLOR = { error: "--openidea-danger", warning: "--openidea-warning" };
const PROBLEM_RANK = { error: 2, warning: 1 };
let drag = null;
@@ -134,6 +135,13 @@
ctx.fillRect(s.from, y, s.to - s.from, LINE - 0.5);
}
}
// Changes in the gutter's colours: a bar over changed lines, a notch where lines were deleted.
for (const c of changes) {
ctx.fillStyle = cssVar(`--openidea-change-${c.kind}`);
const y = Math.floor(rowOf(c.line)) * LINE - offset;
if (c.kind === "deleted") ctx.fillRect(0, y - 1, 4, 2);
else ctx.fillRect(0, y, 2, (Math.floor(rowOf(c.lastLine)) - Math.floor(rowOf(c.line)) + 1) * LINE);
}
// Problems: errors drawn last, on top; weak warnings in the muted colour.
const ranked = [...problems].sort((a, b) => (PROBLEM_RANK[a.severity] || 0) - (PROBLEM_RANK[b.severity] || 0));
for (const p of ranked) {
@@ -184,6 +192,7 @@
problems = editor.problems ? await editor.problems() : [];
folds = editor.folded ? await editor.folded() : [];
selections = editor.selections ? await editor.selections() : [];
changes = editor.changes ? await editor.changes() : [];
view = Object.assign(await editor.viewport(), { version: target.version });
redraw();
}
@@ -217,6 +226,11 @@
selections = s;
redraw();
});
if (editor.onChanges)
editor.onChanges((c) => {
changes = c;
redraw();
});
window.openidea.onThemeChange(redraw);
new ResizeObserver(redraw).observe(canvas);
+11 -4
View File
@@ -462,6 +462,11 @@ matching SDK. Released 1.9 plugins keep working. New in 1.10:
the caret and every selection of its group's editor with
`openidea.editor.selections()` and hears them move through `onSelections`. See
_Editor panels_.
- **VCS changes in editor panels.** An editor panel's page reads the added,
modified and deleted lines its group's change-marker lane shows with
`openidea.editor.changes()` and hears them change through `onChanges`. Frames
get the lane's colours as `--openidea-change-added`, `--openidea-change-modified`
and `--openidea-change-deleted`. See _Editor panels_.
### API 1.9
@@ -1766,6 +1771,7 @@ values (the body already uses the text colour, UI font and size):
| `--openidea-border`, `--openidea-focus-ring`, `--openidea-link` | Lines, focus, links |
| `--openidea-accent`, `--openidea-fg-on-accent` | Accent and text on it |
| `--openidea-danger`, `--openidea-warning`, `--openidea-success`, `--openidea-info` | Status colours |
| `--openidea-change-added`, `--openidea-change-modified`, `--openidea-change-deleted` | API 1.10: the editor's VCS change markers |
| `--openidea-font-ui`, `--openidea-font-mono`, `--openidea-font-size` | Fonts (web fonts the IDE bundles are not available in the frame) |
Scripts get the same as `openidea.theme` (`{ dark, vars }`) and
@@ -1944,17 +1950,18 @@ The page gets `openidea.editor` (only an editor panel's page has it). Lines are
| `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 |
| `changes()` | API 1.10: the VCS changes beside the line numbers, in file order: `[{ line, lastLine, kind }]`, `kind` `added`, `modified` or `deleted`; a deletion's `line` is the line below the deleted text. `[]` outside version control |
| `onChanges(fn)` | API 1.10: called with `changes()` when the changes are recomputed or edits move them, and when 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`,
`onLayout` or `selections`: check for them (`if (editor.problems)`) when the page also runs in
`onLayout`, `selections` or `changes`: 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 marker bar's changes.
line's length until it lays the line out; `onLayout` follows when it does.
`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, the selected lines and the caret's line tinted) 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, VCS changes at its left edge) to install and try.
### Web frame PTYs (API 1.3)
+16
View File
@@ -30,6 +30,7 @@ import {
} from "@codemirror/state";
import { GutterMarker, ViewPlugin, type EditorView, type ViewUpdate } from "@codemirror/view";
import type { LanguageDescription } from "@codemirror/language";
import type { HunkKind } from "@/bindings";
import type { LineEnding } from "@/platform/ipc";
import { create } from "zustand";
import { maybeEditorService, type EditorInput } from "@/workbench/contributions";
@@ -374,6 +375,21 @@ export const scrollbarMarks = Facet.define<readonly ScrollbarMark[], readonly Sc
*/
export const gutterLaneMarkers = Facet.define<RangeSet<GutterMarker>>();
/**
* The VCS changes the change-marker lane shows, as document offsets of this state (mapped
* through edits), in file order. `to <= from` draws a deletion notch on the line at `from`.
* Editor panels read them (`openidea.editor.changes()`).
*/
export interface LineChange {
kind: HunkKind;
from: number;
to: number;
}
export const lineChanges = Facet.define<readonly LineChange[], readonly LineChange[]>({
combine: (values) => values[0] ?? [],
});
/** Marker for `gutterLaneMarkers`: a solid 3px bar (or a small wedge for `deleted`). */
export class LaneMarker extends GutterMarker {
constructor(
@@ -4,10 +4,11 @@ import { javascript } from "@codemirror/lang-javascript";
import { codeFolding, foldEffect, syntaxHighlighting, unfoldEffect } from "@codemirror/language";
import { EditorSelection, EditorState, StateEffect } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import type { Diagnostic, PluginInfo } from "@/bindings";
import type { Diagnostic, LineHunk, PluginInfo } from "@/bindings";
import type { TextEditorHandle } from "@/editor/api";
import { diagnosticsExtension, setFileDiagnostics } from "@/editor/lsp/diagnostics";
import { lspDoc } from "@/editor/lsp/lsp";
import { hunkField, setHunksEffect } from "@/features/vcs/gutter";
import { openideaHighlightStyle } from "@/editor/core/cm/highlight";
import { setContext } from "@/platform/context";
import { useEditorGroupPanels } from "@/workbench/contributions";
@@ -81,12 +82,14 @@ describe("frame bridge: openidea.editor", () => {
folded(): Promise<unknown>;
wrapped(from: number, to: number): Promise<unknown>;
selections(): Promise<unknown>;
changes(): 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;
onChanges(fn: (v: unknown) => void): void;
document: unknown;
};
expect(editor.document).toBe(api.document);
@@ -116,6 +119,8 @@ describe("frame bridge: openidea.editor", () => {
expect(sent.at(-1)).toMatchObject({ op: "editor.wrapped", args: { fromLine: 4, toLine: 9 } });
void editor.selections();
expect(sent.at(-1)).toMatchObject({ op: "editor.selections" });
void editor.changes();
expect(sent.at(-1)).toMatchObject({ op: "editor.changes" });
const events: unknown[] = [];
editor.onTarget((v) => events.push(["target", v]));
@@ -124,12 +129,14 @@ describe("frame bridge: openidea.editor", () => {
editor.onProblems((v) => events.push(["problems", v]));
editor.onLayout((v) => events.push(["layout", v]));
editor.onSelections((v) => events.push(["selections", v]));
editor.onChanges((v) => events.push(["changes", 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: "changes", value: [] });
send({ editor: "constructor", value: 1 });
expect(events).toEqual([
["target", null],
@@ -138,6 +145,7 @@ describe("frame bridge: openidea.editor", () => {
["problems", []],
["layout", { folded: [], softWrap: true }],
["selections", []],
["changes", []],
]);
});
@@ -166,6 +174,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 } }],
changes: () => [{ line: 0, lastLine: 1, kind: "added" }],
wrapped: (from, to) => {
calls.push(["wrapped", from, to]);
return [1, 3];
@@ -237,6 +246,8 @@ describe("WebView as an editor panel", () => {
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 } }]);
send({ call: 15, op: "editor.changes" });
expect((await reply(15)).value).toEqual([{ line: 0, lastLine: 1, kind: "added" }]);
editor.fire({ editor: "highlights", value: { fromLine: 0, toLine: 3 } });
expect(posted.at(-1)).toEqual({ tag: FRAME_TAG, editor: "highlights", value: { fromLine: 0, toLine: 3 } });
@@ -648,6 +659,80 @@ describe("PanelEditor selections", () => {
});
});
describe("PanelEditor changes", () => {
const hunk = (kind: LineHunk["kind"], start: number, lines: number): LineHunk => ({
kind,
start,
lines,
oldStart: start,
oldLines: kind === "added" ? 0 : 1,
oldText: kind === "added" ? "" : "old\n",
});
it("reports the change lane's hunks by line and follows them", async () => {
const parent = document.createElement("div");
document.body.appendChild(parent);
const view = new EditorView({
parent,
state: EditorState.create({ doc: "a\nb\nc\nd\ne\nf", extensions: [hunkField, 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();
// Showing a file: its changes (none yet, as outside version control).
expect(events).toContainEqual({ editor: "changes", value: [] });
events.length = 0;
view.dispatch({ effects: setHunksEffect.of([hunk("added", 0, 1), hunk("modified", 2, 2), hunk("deleted", 5, 0)]) });
const shown = [
{ line: 0, lastLine: 0, kind: "added" },
{ line: 2, lastLine: 3, kind: "modified" },
// Deleted above line 5: marked on line 5.
{ line: 5, lastLine: 5, kind: "deleted" },
];
expect(panel.changes()).toEqual(shown);
await nextFrame();
expect(events.filter((e) => e.editor === "changes")).toEqual([{ editor: "changes", value: shown }]);
// An edit above moves them; deleting the added line leaves a deletion, as the lane shows it.
events.length = 0;
view.dispatch({ changes: { from: 0, to: 2 } });
await nextFrame();
expect(events.filter((e) => e.editor === "changes")).toEqual([
{
editor: "changes",
value: [
{ line: 0, lastLine: 0, kind: "deleted" },
{ line: 1, lastLine: 2, kind: "modified" },
{ line: 4, lastLine: 4, kind: "deleted" },
],
},
]);
// Moving the caret alone says nothing.
events.length = 0;
view.dispatch({ selection: { anchor: 1 } });
await nextFrame();
expect(events.filter((e) => e.editor === "changes")).toEqual([]);
// No changes any more.
events.length = 0;
view.dispatch({ effects: setHunksEffect.of([]) });
await nextFrame();
expect(events).toEqual([{ editor: "changes", value: [] }]);
panel.dispose();
view.destroy();
});
});
describe("editorPanels projection", () => {
it("shows the panel only while `editor.read` is granted and `when` holds", () => {
const plugin = (granted: boolean) =>
+13 -1
View File
@@ -107,6 +107,14 @@ export interface EditorFold {
toLine: number;
}
/** A VCS change of the change-marker lane, as `openidea.editor.changes()` returns it: 0-based lines. */
export interface EditorChange {
line: number;
/** The last changed line; `line` for a deletion, marked on the line the deleted text was above. */
lastLine: number;
kind: "added" | "modified" | "deleted";
}
/** A position in the document: 0-based line, UTF-16 column. */
export interface EditorPosition {
line: number;
@@ -131,7 +139,8 @@ export type FrameEditorEvent =
| { editor: "highlights"; value: { fromLine: number; toLine: number } }
| { editor: "problems"; value: EditorProblem[] }
| { editor: "layout"; value: EditorLayout }
| { editor: "selections"; value: EditorSelection[] };
| { editor: "selections"; value: EditorSelection[] }
| { editor: "changes"; value: EditorChange[] };
/** The text editor an editor panel's frame follows (`openidea.editor`). */
export interface FrameEditor {
@@ -147,6 +156,7 @@ export interface FrameEditor {
wrapped(fromLine: number, toLine: number): number[] | null;
/** The main selection first, then the others in file order. */
selections(): EditorSelection[];
changes(): EditorChange[];
subscribe(listener: (event: FrameEditorEvent) => void): () => void;
}
@@ -419,12 +429,14 @@ export function WebView({
case "editor.problems":
case "editor.folded":
case "editor.selections":
case "editor.changes":
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.changes") return [editor.changes()];
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"))];
+27 -3
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, the caret and selections, and scrolls the editor — straight
* marker bar's problems, the folds and the rows of wrapped lines, the caret and selections, the VCS changes, 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";
@@ -12,7 +12,7 @@ import { BlockType, Decoration, ViewPlugin, type EditorView, type ViewUpdate } f
import { highlightTree } from "@lezer/highlight";
import { useEffect, useMemo } from "react";
import type { Severity } from "@/bindings";
import { useEditorRegistry, type TextEditorHandle } from "@/editor/api";
import { lineChanges, useEditorRegistry, type TextEditorHandle } from "@/editor/api";
import { markerBarProblems } from "@/editor/lsp/diagnostics";
import { semanticHighlights } from "@/editor/lsp/semantic";
import { evaluateWhen, useContextKeys } from "@/platform/context";
@@ -24,6 +24,7 @@ import {
WebView,
type DocumentState,
type EditorFold,
type EditorChange,
type EditorProblem,
type EditorSelection,
type EditorTarget,
@@ -81,6 +82,7 @@ const nothingPending = () => ({
problems: false,
layout: false,
selections: false,
changes: false,
lines: null as [number, number] | null,
});
@@ -145,6 +147,7 @@ export class PanelEditor implements FrameEditor {
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 });
if (u.startState.facet(lineChanges) !== u.state.facet(lineChanges)) this.schedule({ changes: 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)) {
@@ -171,7 +174,7 @@ export class PanelEditor implements FrameEditor {
set.delete(onUpdate);
if (!set.size) updateListeners.delete(view);
};
this.schedule({ viewport: true, problems: true, layout: true, selections: true });
this.schedule({ viewport: true, problems: true, layout: true, selections: true, changes: true });
}
this.emit({ editor: "target", value: this.get() });
}
@@ -337,6 +340,24 @@ export class PanelEditor implements FrameEditor {
}));
}
changes(): EditorChange[] {
const view = this.handle?.view;
if (!view) return [];
const doc = view.state.doc;
return view.state.facet(lineChanges).map((c) => {
// As the lane draws them: a hunk whose lines were all deleted is a deletion.
if (c.kind === "deleted" || c.to <= c.from) {
const line = doc.lineAt(Math.min(c.from, doc.length)).number - 1;
return { line, lastLine: line, kind: "deleted" };
}
return {
line: doc.lineAt(c.from).number - 1,
lastLine: doc.lineAt(Math.max(c.from, c.to - 1)).number - 1,
kind: c.kind,
};
});
}
/** 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");
@@ -366,6 +387,7 @@ export class PanelEditor implements FrameEditor {
problems?: boolean;
layout?: boolean;
selections?: boolean;
changes?: boolean;
lines?: [number, number];
}) {
const q = this.pending;
@@ -374,6 +396,7 @@ export class PanelEditor implements FrameEditor {
q.problems ||= !!p.problems;
q.layout ||= !!p.layout;
q.selections ||= !!p.selections;
q.changes ||= !!p.changes;
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());
}
@@ -397,6 +420,7 @@ export class PanelEditor implements FrameEditor {
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() });
if (q.changes) this.emit({ editor: "changes", value: this.changes() });
}
}
+13 -1
View File
@@ -19,7 +19,15 @@
const listeners = [];
const themeListeners = [];
const documentListeners = [];
const editorListeners = { target: [], viewport: [], highlights: [], problems: [], layout: [], selections: [] };
const editorListeners = {
target: [],
viewport: [],
highlights: [],
problems: [],
layout: [],
selections: [],
changes: [],
};
const editorPanel = /(?:^|[?&])openidea=editor-panel(?:&|$)/.test(location.search.slice(1));
const pending = new Map();
const root = document.documentElement;
@@ -163,6 +171,10 @@
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),
/** The VCS changes beside the line numbers: `[{ line, lastLine, kind }]`, kind `added`, `modified` or `deleted` (`lastLine` equals `line`, the line below the deleted text). */
changes: () => call("editor.changes"),
/** Called with `changes()` when the changes are recomputed or edits move them, or the group shows another file, at most once a frame. */
onChanges: listen(editorListeners.changes),
});
window.openidea = Object.freeze({
+3
View File
@@ -48,6 +48,9 @@ export const FRAME_THEME_TOKENS = {
"--openidea-warning": "--warning",
"--openidea-success": "--success",
"--openidea-info": "--info",
"--openidea-change-added": "--gutter-added",
"--openidea-change-modified": "--gutter-modified",
"--openidea-change-deleted": "--gutter-deleted",
} as const;
/** Non-colour variables: public name → IDE token. */
+9 -1
View File
@@ -9,7 +9,14 @@ import { EditorView, GutterMarker, ViewPlugin, type PluginValue, type ViewUpdate
import { foldState, foldedRanges } from "@codemirror/language";
import type { HunkKind, LineHunk } from "@/bindings";
import { call, commands, isTauri } from "@/platform/ipc";
import { LaneMarker, gutterLaneMarkers, scrollbarMarks, type EditorDocContext, type ScrollbarMark } from "@/editor/api";
import {
LaneMarker,
gutterLaneMarkers,
lineChanges,
scrollbarMarks,
type EditorDocContext,
type ScrollbarMark,
} from "@/editor/api";
import { lineStarts } from "./hunks";
import { useVcs } from "./store";
@@ -85,6 +92,7 @@ export const hunkField = StateField.define<HunkState>({
});
return { hunks, markers: buildMarkers(hunks, tr.state.doc) };
},
provide: (f) => lineChanges.from(f, (v) => v.hunks),
});
export function editorHunks(state: EditorState): EditorHunk[] {