fix(editor): keep the gutter icon area's width while editing (#3722)

After an edit each icon source places its icons again on its own schedule (run icons before the language server's inheritance icons, plugin line markers cleared and refilled), so a line's icons briefly part and the shared icon area narrowed and widened again, shifting the code. The area now widens at once but narrows only after the text and the icon count stayed unchanged for 2 seconds, and its width follows the line with the most icons in the whole file.

Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com>
This commit is contained in:
LU XIANGRUI
2026-11-16 17:35:47 +08:00
committed by GitHub
co-authored by wildcatDownstairs
parent c805173467
commit faa9a91953
2 changed files with 167 additions and 13 deletions
+84 -3
View File
@@ -1,8 +1,8 @@
import { afterEach, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { fireEvent } from "@testing-library/react";
import { EditorState, RangeSet } from "@codemirror/state";
import { EditorState, RangeSet, StateEffect, StateField } from "@codemirror/state";
import { EditorView, GutterMarker } from "@codemirror/view";
import { iconAreaExtension, iconAreaSource } from "./iconArea";
import { SETTLE_MS, iconAreaExtension, iconAreaSource } from "./iconArea";
class Dot extends GutterMarker {
constructor(readonly name: string) {
@@ -73,3 +73,84 @@ it("keeps an icon's width only while a source asks for it", () => {
const v = open([{ order: 1, markers: () => RangeSet.empty, reserve: () => true }]);
expect(v.dom.querySelector(".cm-openidea-iconArea .cm-openidea-iconSpacer")).toBeTruthy();
});
describe("while edits place icons again", () => {
// Line numbers each source has an icon on, as set by the test.
const setRun = StateEffect.define<number[]>();
const setImpl = StateEffect.define<number[]>();
const linesField = (effect: typeof setRun, initial: number[]) =>
StateField.define<number[]>({
create: () => initial,
update: (value, tr) => tr.effects.find((e) => e.is(effect))?.value ?? value,
});
const run = linesField(setRun, [2]);
const impl = linesField(setImpl, [2]);
const dots = (name: string, field: StateField<number[]>) => (view: EditorView) =>
RangeSet.of(view.state.field(field).map((l) => new Dot(name).range(lineStart(view.state, l))));
const spacerIcons = (v: EditorView) => v.dom.querySelectorAll(".cm-openidea-iconSpacer").length;
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());
function openTwoSources() {
view = new EditorView({
state: EditorState.create({
doc: DOC,
extensions: [
run,
impl,
iconAreaExtension,
iconAreaSource.of({ order: 10, markers: dots("run", run) }),
iconAreaSource.of({ order: 50, markers: dots("impl", impl) }),
],
}),
parent: document.body,
});
return view;
}
// Enter at the start of line 2: the run icon moves to line 3 first, the inheritance icon later.
const pressEnter = (v: EditorView) => v.dispatch({ changes: { from: lineStart(v.state, 2), insert: "\n" } });
it("keeps the widest line's width while a line's icons are apart, then narrows once they settle", () => {
const v = openTwoSources();
expect(spacerIcons(v)).toBe(2);
pressEnter(v);
v.dispatch({ effects: setRun.of([3]) });
expect(spacerIcons(v)).toBe(2);
vi.advanceTimersByTime(SETTLE_MS - 1);
v.dispatch({ effects: setImpl.of([3]) });
expect(spacerIcons(v)).toBe(2);
// An icon that really went away: the area narrows only after nothing changed for a while.
v.dispatch({ effects: setImpl.of([]) });
vi.advanceTimersByTime(SETTLE_MS - 1);
expect(spacerIcons(v)).toBe(2);
vi.advanceTimersByTime(1);
expect(spacerIcons(v)).toBe(1);
});
it("does not narrow while typing goes on", () => {
const v = openTwoSources();
v.dispatch({ effects: setImpl.of([]) });
for (let i = 0; i < 5; i++) {
vi.advanceTimersByTime(SETTLE_MS / 2);
pressEnter(v);
expect(spacerIcons(v)).toBe(2);
}
vi.advanceTimersByTime(SETTLE_MS);
expect(spacerIcons(v)).toBe(1);
});
it("widens at once", () => {
const v = openTwoSources();
v.dispatch({ effects: setImpl.of([]) });
vi.advanceTimersByTime(SETTLE_MS);
expect(spacerIcons(v)).toBe(1);
pressEnter(v);
v.dispatch({ effects: setImpl.of([2]) });
expect(spacerIcons(v)).toBe(2);
});
});
+83 -10
View File
@@ -4,7 +4,15 @@
* column per kind that stays empty on the lines where another kind has its icon.
*/
import { Facet, type EditorState, type Extension, type RangeSet } from "@codemirror/state";
import { EditorView, GutterMarker, gutter, type BlockInfo, type ViewUpdate, type WidgetType } from "@codemirror/view";
import {
EditorView,
GutterMarker,
ViewPlugin,
gutter,
type BlockInfo,
type ViewUpdate,
type WidgetType,
} from "@codemirror/view";
export interface IconAreaSource {
/** Left to right within a line: lower first. */
@@ -24,19 +32,80 @@ export const iconAreaSource = Facet.define<IconAreaSource, readonly IconAreaSour
combine: (sources) => [...sources].sort((a, b) => a.order - b.order),
});
/** The width of one icon, for the reserved column. Hidden; not a button. */
/** `count` icons of width, the room the area keeps. Hidden; not buttons. */
class IconSpacer extends GutterMarker {
constructor(readonly count: number) {
super();
}
override eq(other: GutterMarker): boolean {
return other instanceof IconSpacer && other.count === this.count;
}
override toDOM(): Node {
const el = document.createElement("span");
el.className = "cm-openidea-iconSpacer";
el.className = "cm-openidea-iconAreaSpacer";
for (let i = 0; i < this.count; i++)
el.appendChild(document.createElement("span")).className = "cm-openidea-iconSpacer";
return el;
}
}
const iconSpacer = new IconSpacer();
const noSpacer = new (class extends GutterMarker {})();
const reserved = (state: EditorState) => state.facet(iconAreaSource).some((s) => s.reserve?.(state));
/** The most icons on one line, at least one while a source reserves room. */
function mostIcons(view: EditorView): number {
const sources = view.state.facet(iconAreaSource);
const lines = new Map<number, number>();
let most = sources.some((s) => s.reserve?.(view.state)) ? 1 : 0;
for (const s of sources)
for (const it = s.markers(view).iter(); it.value; it.next()) {
const line = view.state.doc.lineAt(it.from).from;
const n = (lines.get(line) ?? 0) + 1;
lines.set(line, n);
most = Math.max(most, n);
}
return most;
}
/** How long the text and its icons stay unchanged before the area may narrow. */
export const SETTLE_MS = 2000;
/**
* After an edit each source places its icons again on its own schedule (a run icon before the
* language server's inheritance icons), so a line's icons briefly part. The area widens at once
* but narrows only once nothing changed for `SETTLE_MS`, so the text does not shift back and forth.
*/
const areaWidth = ViewPlugin.fromClass(
class {
private holdUntil = 0;
/** The most icons on a line now, and the icons of width the spacer keeps. */
private icons = 0;
private kept = 0;
private timer: ReturnType<typeof setTimeout> | undefined;
constructor(readonly view: EditorView) {}
spacer(prev: GutterMarker | null, update: ViewUpdate | null): GutterMarker {
const icons = mostIcons(this.view);
const now = Date.now();
if (update && (update.docChanged || icons !== this.icons)) {
this.holdUntil = now + SETTLE_MS;
clearTimeout(this.timer);
// Once settled, any update asks for the spacer again.
this.timer = setTimeout(() => this.kept > this.icons && this.view.dispatch({}), SETTLE_MS);
}
this.icons = icons;
if (prev && now < this.holdUntil && icons < this.kept) return prev;
this.kept = icons;
return icons ? new IconSpacer(icons) : noSpacer;
}
destroy() {
clearTimeout(this.timer);
}
},
);
const spacer = (view: EditorView, prev: GutterMarker | null, update: ViewUpdate | null) =>
view.plugin(areaWidth)?.spacer(prev, update) ?? noSpacer;
const areaGutter = gutter({
class: "cm-openidea-iconArea",
@@ -51,8 +120,8 @@ const areaGutter = gutter({
lineMarkerChange: (update) =>
update.startState.facet(iconAreaSource) !== update.state.facet(iconAreaSource) ||
update.state.facet(iconAreaSource).some((s) => s.lineMarkerChange?.(update)),
initialSpacer: (view) => (reserved(view.state) ? iconSpacer : noSpacer),
updateSpacer: (_spacer, update) => (reserved(update.state) ? iconSpacer : noSpacer),
initialSpacer: (view) => spacer(view, null, null),
updateSpacer: (prev, update) => spacer(update.view, prev, update),
domEventHandlers: {
mousedown: (view, block, event) =>
view.state.facet(iconAreaSource).some((s) => s.mousedown?.(view, block, event as MouseEvent) ?? false),
@@ -67,10 +136,14 @@ const areaTheme = EditorView.baseTheme({
gap: "2px",
},
// Room around the icons, not the element: an area without icons takes no width.
".cm-openidea-iconArea .cm-gutterElement > *": { margin: "0 1px" },
".cm-openidea-iconArea .cm-gutterElement > :first-child": { marginLeft: "5px" },
".cm-openidea-iconArea .cm-gutterElement > *, .cm-openidea-iconAreaSpacer > *": { margin: "0 1px" },
".cm-openidea-iconArea .cm-gutterElement > :first-child, .cm-openidea-iconAreaSpacer > :first-child": {
marginLeft: "5px",
},
// The spacer's icons are laid out as the line's own.
".cm-openidea-iconAreaSpacer": { display: "contents" },
".cm-openidea-iconSpacer": { display: "inline-block", width: "14px" },
});
/** Installed in every editor; empty (no width) while no source has markers or reserves room. */
export const iconAreaExtension: Extension = [areaGutter, areaTheme];
export const iconAreaExtension: Extension = [areaWidth, areaGutter, areaTheme];