feat(editor): highlight unknown SQL objects

This commit is contained in:
大峰 authored and GitHub committed 2026-09-24 22:34:15 +08:00
1 parent cd24f69daa
commit 46cc9be7d9
4 files changed
+490 -56

No files matched your search

@@ -0,0 +1,147 @@
// @vitest-environment happy-dom
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { afterEach, describe, expect, it, vi } from "vitest";
import { createSqlUnknownObjectHighlights, refreshSqlUnknownObjectHighlights, setSqlUnknownObjectSpans, type SqlUnknownObjectSpan } from "@/lib/editor/codemirrorSqlUnknownObjectHighlights";
const DOC = "SELECT USER_ID FROM T";
let view: EditorView | null = null;
function mount(doc: string, options: { enabled?: boolean; load?: (view: EditorView) => Promise<SqlUnknownObjectSpan[]> } = {}) {
const parent = document.createElement("div");
document.body.appendChild(parent);
view = new EditorView({
parent,
state: EditorState.create({
doc,
extensions: [
createSqlUnknownObjectHighlights({
enabled: options.enabled ?? true,
load: options.load ?? (async () => []),
initialDelayMs: 0,
debounceMs: 0,
}),
],
}),
});
return view;
}
/** Let the zero-delay deferred task fire and its promise chain settle. */
async function settle() {
await new Promise((resolve) => setTimeout(resolve, 0));
await new Promise((resolve) => setTimeout(resolve, 0));
}
function highlightedText(current: EditorView): string[] {
return Array.from(current.dom.querySelectorAll(".cm-sql-unknown-object")).map((element) => element.textContent ?? "");
}
afterEach(() => {
view?.destroy();
view = null;
document.body.innerHTML = "";
});
describe("createSqlUnknownObjectHighlights", () => {
it("returns no extension when disabled", () => {
expect(createSqlUnknownObjectHighlights({ enabled: false, load: async () => [], initialDelayMs: 0, debounceMs: 0 })).toEqual([]);
});
it("colours the ranges supplied through the effect", () => {
const current = mount(DOC);
current.dispatch({ effects: setSqlUnknownObjectSpans.of([{ from: 7, to: 14 }]) });
expect(highlightedText(current)).toEqual(["USER_ID"]);
current.dispatch({ effects: setSqlUnknownObjectSpans.of([]) });
expect(highlightedText(current)).toEqual([]);
});
it("clamps, dedupes and orders the supplied ranges", () => {
const current = mount(DOC);
current.dispatch({
effects: setSqlUnknownObjectSpans.of([
{ from: 15, to: 500 },
{ from: 7, to: 14 },
{ from: 7, to: 14 },
{ from: 3, to: 3 },
]),
});
// Ordered by start, duplicate collapsed, out-of-range clipped to the document end, empty dropped.
expect(highlightedText(current)).toEqual(["USER_ID", "FROM T"]);
});
it("shifts existing highlights through document changes without clearing them", () => {
const current = mount(DOC);
current.dispatch({ effects: setSqlUnknownObjectSpans.of([{ from: 7, to: 14 }]) });
current.dispatch({ changes: { from: 0, insert: "XX" } });
expect(highlightedText(current)).toEqual(["USER_ID"]);
});
it("runs load on mount and applies the resolved spans", async () => {
const load = vi.fn(async () => [{ from: 7, to: 14 }]);
const current = mount(DOC, { load });
expect(highlightedText(current)).toEqual([]);
await settle();
expect(load).toHaveBeenCalledTimes(1);
expect(highlightedText(current)).toEqual(["USER_ID"]);
});
it("re-runs load when a refresh effect is dispatched", async () => {
const load = vi.fn(async () => [{ from: 7, to: 14 }]);
const current = mount(DOC, { load });
await settle();
expect(load).toHaveBeenCalledTimes(1);
current.dispatch({ effects: refreshSqlUnknownObjectHighlights.of(null) });
await settle();
expect(load).toHaveBeenCalledTimes(2);
expect(highlightedText(current)).toEqual(["USER_ID"]);
});
it("discards a result computed against an older document", async () => {
let resolveLoad: ((spans: SqlUnknownObjectSpan[]) => void) | null = null;
const load = () =>
new Promise<SqlUnknownObjectSpan[]>((resolve) => {
resolveLoad = resolve;
});
const current = mount(DOC, { load });
await settle();
current.dispatch({ changes: { from: 0, insert: "XX" } });
resolveLoad?.([{ from: 7, to: 14 }]);
await settle();
expect(highlightedText(current)).toEqual([]);
});
it("ignores a load failure", async () => {
const load = async () => {
throw new Error("metadata unavailable");
};
const current = mount(DOC, { load });
await settle();
expect(highlightedText(current)).toEqual([]);
});
it("emits an !important colour rule that outranks the table-name colour", () => {
mount(DOC);
const css = Array.from(document.querySelectorAll("style"))
.map((style) => style.textContent ?? "")
.join("\n");
// The repeated class is what beats .cm-sql-table-name (same specificity as a
// single class once the generated theme id prefix is accounted for).
expect(css).toContain(".cm-sql-unknown-object.cm-sql-unknown-object.cm-sql-unknown-object");
expect(css).toContain("var(--dbx-sql-unknown-object-color, #e5484d) !important");
});
});
@@ -0,0 +1,144 @@
import { StateEffect, StateField, type Extension } from "@codemirror/state";
import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from "@codemirror/view";
import { createDeferredEditorTask } from "@/lib/editor/deferredEditorTask";
/** Absolute document range that must be rendered with the "unknown object" colour. */
export interface SqlUnknownObjectSpan {
from: number;
to: number;
}
export const setSqlUnknownObjectSpans = StateEffect.define<SqlUnknownObjectSpan[]>();
/**
* Ask a mounted editor to re-run `load` immediately (used on tab activation,
* where KeepAlive does not necessarily produce a focus or viewport change).
*/
export const refreshSqlUnknownObjectHighlights = StateEffect.define<null>();
export interface SqlUnknownObjectHighlightOptions {
enabled: boolean;
/** Resolves the ranges to colour. Called off the typing path, never per keystroke. */
load: (view: EditorView) => Promise<SqlUnknownObjectSpan[]>;
initialDelayMs: number;
debounceMs: number;
}
const unknownObjectMark = Decoration.mark({
class: "cm-sql-unknown-object",
attributes: {
"data-sql-token": "unknown",
},
});
function buildDecorationSet(spans: readonly SqlUnknownObjectSpan[], docLength: number): DecorationSet {
const normalized: SqlUnknownObjectSpan[] = [];
const seen = new Set<string>();
for (const span of spans) {
const from = Math.max(0, Math.min(span.from, docLength));
const to = Math.max(0, Math.min(span.to, docLength));
if (to <= from) continue;
const key = `${from}:${to}`;
if (seen.has(key)) continue;
seen.add(key);
normalized.push({ from, to });
}
// DecorationSet requires ranges in ascending order.
normalized.sort((left, right) => left.from - right.from || left.to - right.to);
return Decoration.set(
normalized.map((span) => unknownObjectMark.range(span.from, span.to)),
true,
);
}
export function createSqlUnknownObjectHighlights(options: SqlUnknownObjectHighlightOptions): Extension {
if (!options.enabled) return [];
// Keeps the decorations as a DecorationSet so that typing shifts them through
// the ChangeSet instead of clearing them until the next deferred scan lands.
const spansField = StateField.define<DecorationSet>({
create: () => Decoration.none,
update(decorations, transaction) {
for (const effect of transaction.effects) {
if (effect.is(setSqlUnknownObjectSpans)) return buildDecorationSet(effect.value, transaction.state.doc.length);
}
if (transaction.docChanged) return decorations.map(transaction.changes);
return decorations;
},
provide: (field) => EditorView.decorations.from(field),
});
const plugin = ViewPlugin.fromClass(
class {
private running = false;
private view: EditorView;
private readonly runTask: () => void;
private readonly initialTask: ReturnType<typeof createDeferredEditorTask>;
private readonly changeTask: ReturnType<typeof createDeferredEditorTask>;
constructor(view: EditorView) {
this.view = view;
this.runTask = () => {
void this.run();
};
this.initialTask = createDeferredEditorTask(this.runTask, options.initialDelayMs);
this.changeTask = createDeferredEditorTask(this.runTask, options.debounceMs);
this.initialTask.schedule();
}
update(update: ViewUpdate) {
this.view = update.view;
if (update.docChanged) {
this.initialTask.cancel();
this.changeTask.schedule();
return;
}
if (update.transactions.some((transaction) => transaction.effects.some((effect) => effect.is(refreshSqlUnknownObjectHighlights)))) {
this.initialTask.cancel();
this.changeTask.cancel();
this.runTask();
}
}
destroy() {
this.initialTask.cancel();
this.changeTask.cancel();
}
private async run() {
if (this.running) return;
const view = this.view;
if (!view.dom.isConnected) return;
const doc = view.state.doc;
this.running = true;
let spans: SqlUnknownObjectSpan[] = [];
try {
spans = await options.load(view);
} catch {
spans = [];
} finally {
this.running = false;
}
// A result computed against an older document (or a detached editor) is
// stale: the next debounced run owns the current text.
if (!view.dom.isConnected || view.state.doc !== doc) return;
view.dispatch({ effects: setSqlUnknownObjectSpans.of(spans) });
}
},
);
return [
spansField,
plugin,
EditorView.baseTheme({
// The generated theme class prefixes this selector, and the table-name
// colour is an `!important` rule at the same specificity, so the class is
// repeated to win the cascade regardless of style-module injection order.
".cm-sql-unknown-object.cm-sql-unknown-object.cm-sql-unknown-object": {
color: "var(--dbx-sql-unknown-object-color, #e5484d) !important",
},
".cm-sql-unknown-object.cm-sql-unknown-object.cm-sql-unknown-object *": {
color: "var(--dbx-sql-unknown-object-color, #e5484d) !important",
},
}),
];
}