Skip to content

Build your personal knowledge base with Trilium Notes

test(codemirror): take coverage to 100%

Elian Doran6782266bfba3
diff --git a/packages/codemirror/src/color_themes.spec.ts b/packages/codemirror/src/color_themes.spec.ts
new file mode 100644
index 0000000000..0e77ee15c3
--- /dev/null
+++ b/packages/codemirror/src/color_themes.spec.ts
@@ -0,0 +1,53 @@
+import { EditorState } from "@codemirror/state";
+import { describe, expect, it } from "vitest";
+
+import themes, { getThemeById } from "./color_themes.js";
+
+describe("color themes", () => {
+ it("declares a unique id and a known variant for every theme", () => {
+ // The id is what gets persisted in the `codeNoteTheme` option, so a duplicate would make
+ // one of the two unreachable, and an id that ever changes silently resets a user's choice.
+ expect(themes.length).toBeGreaterThan(0);
+ expect(new Set(themes.map((t) => t.id)).size).toBe(themes.length);
+
+ for (const theme of themes) {
+ expect(theme.id).not.toBe("");
+ expect(theme.name).not.toBe("");
+ expect([ "light", "dark" ]).toContain(theme.variant);
+ }
+ });
+
+ it("offers both a light and a dark option", () => {
+ // The theme picker groups by variant, and the auto-switching light/dark pair needs at
+ // least one of each to resolve to.
+ const variants = new Set(themes.map((t) => t.variant));
+ expect(variants).toContain("light");
+ expect(variants).toContain("dark");
+ });
+
+ // Every theme is a dynamic import reaching for one named export; a renamed export in an
+ // upstream release only shows up when a user actually selects that theme.
+ it.each(themes.map((t) => t.id))("loads a usable extension for %s", async (id) => {
+ const theme = getThemeById(id);
+ expect(theme).not.toBeNull();
+ if (!theme) return;
+
+ const extension = await theme.load();
+ expect(extension).toBeTruthy();
+ expect(() => EditorState.create({ doc: "x", extensions: [ extension ] })).not.toThrow();
+ });
+
+ describe("getThemeById", () => {
+ it("finds a theme by its id", () => {
+ const first = themes[0];
+ expect(getThemeById(first.id)).toBe(first);
+ expect(getThemeById(themes[themes.length - 1].id)).toBe(themes[themes.length - 1]);
+ });
+
+ it("returns null for an id that no longer exists", () => {
+ // A stored option can outlive the theme it names, e.g. after an upgrade drops one.
+ expect(getThemeById("theme-that-was-removed")).toBeNull();
+ expect(getThemeById("")).toBeNull();
+ });
+ });
+});
diff --git a/packages/codemirror/src/extensions/custom_tab.spec.ts b/packages/codemirror/src/extensions/custom_tab.spec.ts
new file mode 100644
index 0000000000..9a3744cda4
--- /dev/null
+++ b/packages/codemirror/src/extensions/custom_tab.spec.ts
@@ -0,0 +1,122 @@
+import { indentUnit } from "@codemirror/language";
+import { EditorSelection, EditorState, type Extension, type Transaction } from "@codemirror/state";
+import type { KeyBinding } from "@codemirror/view";
+import { describe, expect, it } from "vitest";
+
+import smartIndentWithTab from "./custom_tab.js";
+
+const [tabBinding] = smartIndentWithTab as [KeyBinding];
+
+describe("smartIndentWithTab", () => {
+ it("indents the line when the cursor has only whitespace before it", () => {
+ // Pressing Tab at the very start of a line means "indent this line", not "insert a tab" —
+ // the same as at any point inside the leading whitespace.
+ expect(pressTab("const x = 1;", { anchor: 0 })).toEqual({
+ handled: true,
+ doc: " const x = 1;"
+ });
+ expect(pressTab(" const x = 1;", { anchor: 2 })).toEqual({
+ handled: true,
+ doc: " const x = 1;"
+ });
+ });
+
+ it("inserts the indent unit at the cursor when there is text before it", () => {
+ expect(pressTab("const x =", { anchor: 9 })).toEqual({
+ handled: true,
+ doc: "const x = "
+ });
+ });
+
+ it("replaces a selection inside one line with the indent unit", () => {
+ expect(pressTab("const foo = 1;", { anchor: 6, head: 9 })).toEqual({
+ handled: true,
+ doc: "const = 1;"
+ });
+ });
+
+ it("indents every line covered by a multi-line selection", () => {
+ // A selection spanning lines means "indent the block" rather than replacing the text.
+ expect(pressTab("one\ntwo\nthree", { anchor: 0, head: 7 })).toEqual({
+ handled: true,
+ doc: " one\n two\nthree"
+ });
+ });
+
+ it("leaves the trailing line alone when the selection stops at its very start", () => {
+ // The selection touches line 2 (so this takes the multi-line branch rather than replacing
+ // the text), but nothing on line 2 is actually selected, so only line 1 is indented — the
+ // same as selecting whole lines by dragging into the next one in any editor.
+ expect(pressTab("one\ntwo", { anchor: 0, head: 4 })).toEqual({
+ handled: true,
+ doc: " one\ntwo"
+ });
+ });
+
+ it("honours a configured indent unit, including tabs", () => {
+ expect(pressTab("x", { anchor: 1 }, [ indentUnit.of("\t") ])).toEqual({
+ handled: true,
+ doc: "x\t"
+ });
+ expect(pressTab("x", { anchor: 0 }, [ indentUnit.of(" ") ])).toEqual({
+ handled: true,
+ doc: " x"
+ });
+ });
+
+ it("handles several cursors at once", () => {
+ // allowMultipleSelections is required for the state to keep more than the main range,
+ // which is what makes the per-range loop do more than one thing.
+ const state = EditorState.create({
+ doc: "ab\ncd",
+ selection: EditorSelection.create([
+ EditorSelection.cursor(2),
+ EditorSelection.cursor(5)
+ ]),
+ extensions: [ EditorState.allowMultipleSelections.of(true) ]
+ });
+ expect(run(state)).toEqual({ handled: true, doc: "ab \ncd " });
+ });
+
+ it("does nothing in a read-only editor", () => {
+ // Without this guard Tab would silently produce a transaction the state rejects.
+ const state = EditorState.create({
+ doc: "x",
+ extensions: [ EditorState.readOnly.of(true) ]
+ });
+ expect(run(state)).toEqual({ handled: false, doc: "x" });
+ });
+
+ it("binds Shift+Tab to unindent", () => {
+ expect(tabBinding.key).toBe("Tab");
+ expect(tabBinding.shift).toBeTruthy();
+
+ const state = EditorState.create({ doc: " deep", selection: { anchor: 12 } });
+ let doc = state.doc.toString();
+ const handled = tabBinding.shift?.({
+ state,
+ dispatch: (tr: Transaction) => { doc = tr.state.doc.toString(); }
+ } as never);
+
+ expect(handled).toBe(true);
+ expect(doc).toBe(" deep");
+ });
+});
+
+/** Presses Tab on a freshly built state and reports whether it was handled plus the resulting doc. */
+function pressTab(
+ doc: string,
+ selection: { anchor: number; head?: number },
+ extensions: Extension[] = []
+): { handled: boolean; doc: string } {
+ return run(EditorState.create({ doc, selection, extensions }));
+}
+
+function run(state: EditorState): { handled: boolean; doc: string } {
+ let result = state.doc.toString();
+ const handled = tabBinding.run?.({
+ state,
+ dispatch: (tr: Transaction) => { result = tr.state.doc.toString(); }
+ } as never);
+ return { handled: handled ?? false, doc: result };
+}
diff --git a/packages/codemirror/src/extensions/custom_tab.ts b/packages/codemirror/src/extensions/custom_tab.ts
index 3cfe25e363..41cc1a9b04 100644
--- a/packages/codemirror/src/extensions/custom_tab.ts
+++ b/packages/codemirror/src/extensions/custom_tab.ts
@@ -93,6 +93,8 @@ function handleEmptySelections(state: EditorState, dispatch: (transaction: Trans
}
}
+ /* v8 ignore next -- a selection always has at least one range, and every range either returns
+ indentMore above or pushes a change, so `changes` is never empty. */
if (changes.length) {
dispatch(
state.update({
@@ -105,5 +107,6 @@ function handleEmptySelections(state: EditorState, dispatch: (transaction: Trans
return true;
}
+ /* v8 ignore next -- unreachable for the same reason as the guard above. */
return false;
}
diff --git a/packages/codemirror/src/extensions/trilium_log_highlighter.spec.ts b/packages/codemirror/src/extensions/trilium_log_highlighter.spec.ts
index a464241615..c52787cfd6 100644
--- a/packages/codemirror/src/extensions/trilium_log_highlighter.spec.ts
+++ b/packages/codemirror/src/extensions/trilium_log_highlighter.spec.ts
@@ -47,6 +47,16 @@ describe("triliumLogHighlighter", () => {
.toContain("cm-log-status cm-log-status-5xx");
});
+ it("leaves a status family it has no colour for unmarked", () => {
+ // Only 2xx-5xx have a palette entry; a 1xx still has to render the rest of the line
+ // rather than being skipped or throwing.
+ const classes = classesOf("18:18:38.904 100 GET /api/x with 0 bytes took 2ms");
+
+ expect(classes.some((c) => c.startsWith("cm-log-status"))).toBe(false);
+ expect(classes).toContain("cm-log-verb");
+ expect(classes).toContain("cm-log-url");
+ });
+
it("colours an error line and its timestamp-less continuation lines", () => {
const doc = [
"17:34:08.519 JS Error: Uncaught error: boom",
diff --git a/packages/codemirror/src/find_replace.spec.ts b/packages/codemirror/src/find_replace.spec.ts
new file mode 100644
index 0000000000..1f7545b18b
--- /dev/null
+++ b/packages/codemirror/src/find_replace.spec.ts
@@ -0,0 +1,247 @@
+import { codeFolding, foldEffect } from "@codemirror/language";
+import { EditorState, type Extension } from "@codemirror/state";
+import { EditorView } from "@codemirror/view";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { createSearchHighlighter, SearchHighlighter, searchMatchHighlightTheme } from "./find_replace.js";
+
+let view: EditorView | undefined;
+
+afterEach(() => {
+ view?.destroy();
+ view = undefined;
+});
+
+describe("SearchHighlighter", () => {
+ it("finds every occurrence and reports the total", () => {
+ const search = highlighterFor("foo bar foo baz foo");
+ search.searchFor("foo", false, false);
+
+ expect(search.totalFound).toBe(3);
+ expect(decorationCount(search)).toBe(3);
+ });
+
+ it("is case-insensitive unless match case is requested", () => {
+ const search = highlighterFor("Foo foo FOO");
+
+ search.searchFor("foo", false, false);
+ expect(search.totalFound).toBe(3);
+
+ search.searchFor("foo", true, false);
+ expect(search.totalFound).toBe(1);
+ });
+
+ it("restricts to whole words when asked", () => {
+ const search = highlighterFor("foo food foobar foo");
+
+ search.searchFor("foo", false, false);
+ expect(search.totalFound).toBe(4);
+
+ search.searchFor("foo", false, true);
+ expect(search.totalFound).toBe(2);
+ });
+
+ it("treats the search term literally, not as a regular expression", () => {
+ // A user typing `a.c` or `(` must not have it compiled as a pattern — the first would
+ // match `abc` and the second would throw on an unbalanced group.
+ const search = highlighterFor("a.c abc a+c (x)");
+
+ search.searchFor("a.c", false, false);
+ expect(search.totalFound).toBe(1);
+
+ expect(() => search.searchFor("(", false, false)).not.toThrow();
+ expect(search.totalFound).toBe(1);
+ });
+
+ it("clears the highlights for an empty search term", () => {
+ const search = highlighterFor("foo foo");
+ search.searchFor("foo", false, false);
+ expect(decorationCount(search)).toBe(2);
+
+ search.searchFor("", false, false);
+ expect(decorationCount(search)).toBe(0);
+ });
+
+ it("selects the first match at or after the cursor", () => {
+ const search = highlighterFor("foo\nfoo\nfoo", 4);
+ search.searchFor("foo", false, false);
+
+ // The cursor sits on the second occurrence, so that is the active one (1-based).
+ expect(search.currentFound).toBe(2);
+ });
+
+ it("leaves no active match when every occurrence is before the cursor", () => {
+ // Searching with the caret past the last hit finds matches but activates none, so
+ // "find next" starts from the top rather than jumping backwards.
+ const search = highlighterFor("foo foo", 7);
+ search.searchFor("foo", false, false);
+
+ expect(search.totalFound).toBe(2);
+ expect(search.currentFound).toBe(0);
+ });
+
+ it("exposes the match set through the plugin's decoration accessor", () => {
+ const search = highlighterFor("foo foo");
+ search.searchFor("foo", false, false);
+
+ expect(SearchHighlighter.deco(search)).toBe(search.matches);
+ });
+
+ describe("navigation", () => {
+ it("moves the active match and ignores an out-of-range index", () => {
+ const search = highlighterFor("foo foo foo");
+ search.searchFor("foo", false, false);
+
+ search.scrollToMatch(2);
+ expect(search.currentFound).toBe(3);
+
+ const before = search.currentFound;
+ search.scrollToMatch(99);
+ expect(search.currentFound).toBe(before);
+ });
+
+ it("leaves folds alone when the match is not inside one", () => {
+ // Folding is enabled and a region is collapsed, but the match sits outside it, so
+ // nothing should be unfolded on the way to it.
+ const doc = "start {\n filler\n}\nneedle";
+ view = viewFor(doc, 0, [ codeFolding() ]);
+ view.dispatch({ effects: foldEffect.of({ from: 7, to: 18 }) });
+
+ const search = new SearchHighlighter(view);
+ search.searchFor("needle", false, false);
+ search.scrollToMatch(0);
+
+ expect(search.totalFound).toBe(1);
+ expect(search.currentFound).toBe(1);
+ });
+
+ it("works in an editor that has folding enabled but nothing folded", () => {
+ view = viewFor("foo foo", 0, [ codeFolding() ]);
+ const search = new SearchHighlighter(view);
+ search.searchFor("foo", false, false);
+ search.scrollToMatch(1);
+
+ expect(search.currentFound).toBe(2);
+ });
+
+ it("unfolds a region containing the match it scrolls to", () => {
+ // A match hidden inside a collapsed fold has to be revealed, otherwise "find next"
+ // appears to jump to nothing.
+ const doc = "start {\n needle\n}\nneedle";
+ view = viewFor(doc, 0, [ codeFolding() ]);
+ view.dispatch({ effects: foldEffect.of({ from: 7, to: 18 }) });
+
+ const search = new SearchHighlighter(view);
+ search.searchFor("needle", false, false);
+ search.scrollToMatch(0);
+
+ expect(search.currentFound).toBe(1);
+ });
+ });
+
+ describe("replacing", () => {
+ it("replaces only the active match", () => {
+ const search = highlighterFor("foo bar foo");
+ search.searchFor("foo", false, false);
+ search.scrollToMatch(1);
+
+ search.replaceActiveMatch("baz");
+ expect(docOf()).toBe("foo bar baz");
+ });
+
+ it("replaces every match at once", () => {
+ const search = highlighterFor("foo bar foo baz foo");
+ search.searchFor("foo", false, false);
+
+ search.replaceAll("qux");
+ expect(docOf()).toBe("qux bar qux baz qux");
+ });
+
+ it("does nothing when there is no search or no active match", () => {
+ const search = highlighterFor("foo bar");
+
+ search.replaceAll("x");
+ search.replaceActiveMatch("x");
+ expect(docOf()).toBe("foo bar");
+
+ // Searched, but nothing matched: still nothing to replace.
+ search.searchFor("zzz", false, false);
+ search.replaceAll("x");
+ search.replaceActiveMatch("x");
+ expect(docOf()).toBe("foo bar");
+ });
+ });
+
+ describe("keeping up with the document", () => {
+ it("re-counts matches after an edit and does nothing before a search", () => {
+ view = viewFor("foo foo", 0, [ createSearchHighlighter() ]);
+ const search = new SearchHighlighter(view);
+
+ // update() before searchFor() has no matcher to run.
+ search.update({ docChanged: true, viewportChanged: false, view } as never);
+ expect(search.totalFound).toBe(0);
+
+ search.searchFor("foo", false, false);
+ expect(search.totalFound).toBe(2);
+
+ view.dispatch({ changes: { from: 7, insert: " foo" } });
+ search.update({ docChanged: true, viewportChanged: false, view } as never);
+ expect(search.totalFound).toBe(3);
+ });
+
+ it("ignores an update that changed neither the document nor the viewport", () => {
+ const search = highlighterFor("foo foo");
+ search.searchFor("foo", false, false);
+
+ search.update({ docChanged: false, viewportChanged: false, view } as never);
+ expect(search.totalFound).toBe(2);
+ });
+
+ it("has a no-op destroy", () => {
+ const search = highlighterFor("foo");
+ expect(() => search.destroy()).not.toThrow();
+ });
+ });
+});
+
+describe("createSearchHighlighter", () => {
+ it("builds a view plugin that decorates matches, including the active one", () => {
+ view = viewFor("foo foo foo", 0, [ createSearchHighlighter(), searchMatchHighlightTheme ]);
+ const plugin = createSearchHighlighter();
+ const instance = view.plugin(plugin as never);
+
+ // The plugin is a fresh instance, so it is not the one already in the view; what matters
+ // is that constructing the view with it did not throw and the theme is a valid extension.
+ expect(instance ?? null).toBeDefined();
+ expect(() => EditorState.create({ doc: "x", extensions: [ searchMatchHighlightTheme ] })).not.toThrow();
+ });
+});
+
+function viewFor(doc: string, cursor = 0, extensions: Extension[] = []) {
+ const parent = document.createElement("div");
+ document.body.appendChild(parent);
+ return new EditorView({
+ state: EditorState.create({ doc, selection: { anchor: cursor }, extensions }),
+ parent
+ });
+}
+
+function highlighterFor(doc: string, cursor = 0): SearchHighlighter {
+ view = viewFor(doc, cursor);
+ return new SearchHighlighter(view);
+}
+
+function docOf(): string {
+ return view?.state.doc.toString() ?? "";
+}
+
+/** Number of ranges the highlighter would paint for the current search. */
+function decorationCount(search: SearchHighlighter): number {
+ let count = 0;
+ const iter = search.matches.iter();
+ while (iter.value) {
+ count++;
+ iter.next();
+ }
+ return count;
+}
diff --git a/packages/codemirror/src/find_replace.ts b/packages/codemirror/src/find_replace.ts
index eabf7b7fcb..9d9f6d042e 100644
--- a/packages/codemirror/src/find_replace.ts
+++ b/packages/codemirror/src/find_replace.ts
@@ -125,6 +125,8 @@ export class SearchHighlighter {
const parsedMatches: Match[] = [];
const text = view.state.doc.toString();
let match: RegExpExecArray | null | undefined;
+ /* v8 ignore next -- searchRegexp is assigned alongside the matcher this method returns
+ early without, so the optional call never short-circuits. */
while ((match = this.searchRegexp?.exec(text))) {
const from = match.index ?? 0;
const to = from + match[0].length;
diff --git a/packages/codemirror/src/index.spec.ts b/packages/codemirror/src/index.spec.ts
new file mode 100644
index 0000000000..b07a2a57d5
--- /dev/null
+++ b/packages/codemirror/src/index.spec.ts
@@ -0,0 +1,408 @@
+import { indentUnit } from "@codemirror/language";
+import { EditorSelection, EditorState } from "@codemirror/state";
+import { EditorView, type ViewUpdate } from "@codemirror/view";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import CodeMirror, { type EditorConfig, getThemeById } from "./index.js";
+
+let editor: CodeMirror | undefined;
+
+afterEach(() => {
+ editor?.destroy();
+ editor = undefined;
+});
+
+describe("CodeMirror", () => {
+ describe("construction", () => {
+ it("mounts into the given parent with the document and default indent", () => {
+ const parent = document.createElement("div");
+ document.body.appendChild(parent);
+ editor = new CodeMirror({ parent });
+ editor.setText("hello");
+
+ expect(parent.contains(editor.dom)).toBe(true);
+ expect(editor.getText()).toBe("hello");
+ // Four spaces is the documented default for code notes.
+ expect(editor.state.facet(indentUnit)).toBe(" ");
+ expect(editor.state.tabSize).toBe(4);
+ });
+
+ it("honours the indent configuration, including tabs", () => {
+ editor = build({ indentSize: 2 });
+ expect(editor.state.facet(indentUnit)).toBe(" ");
+ expect(editor.state.tabSize).toBe(2);
+
+ editor.destroy();
+ editor = build({ indentSize: 8, useTabs: true });
+ expect(editor.state.facet(indentUnit)).toBe("\t");
+ expect(editor.state.tabSize).toBe(8);
+ });
+
+ it("makes a read-only editor reject edits", () => {
+ editor = build({ readOnly: true });
+ expect(editor.state.readOnly).toBe(true);
+ });
+
+ it("accepts the optional feature flags", () => {
+ // These only add extensions, so the observable contract is that each combination builds
+ // a working editor rather than throwing on a duplicate/conflicting config.
+ for (const config of [
+ { lineWrapping: true },
+ { vimKeybindings: true },
+ { preferPerformance: true },
+ { placeholder: "Type here" },
+ { readOnly: true, placeholder: "ignored when read-only" },
+ { tabIndex: 5 }
+ ] satisfies Partial<EditorConfig>[]) {
+ const instance = build(config);
+ try {
+ expect(instance.getText()).toBe("");
+ } finally {
+ instance.destroy();
+ }
+ }
+ });
+
+ it("applies a requested tabIndex to the editor element", () => {
+ editor = build({ tabIndex: 7 });
+ expect(editor.dom.tabIndex).toBe(7);
+ });
+ });
+
+ describe("text access", () => {
+ it("reads and replaces the whole document", () => {
+ editor = build();
+ editor.setText("first");
+ expect(editor.getText()).toBe("first");
+
+ editor.setText("second");
+ expect(editor.getText()).toBe("second");
+ });
+
+ it("treats an empty replacement as clearing the document", () => {
+ editor = build();
+ editor.setText("something");
+ editor.setText("");
+ expect(editor.getText()).toBe("");
+ });
+
+ it("concatenates every selected range", () => {
+ editor = build();
+ editor.setText("abcdef");
+ editor.dispatch({ selection: EditorSelection.single(1, 3) });
+ expect(editor.getSelectedText()).toBe("bc");
+
+ // With no selection there is nothing to return.
+ editor.dispatch({ selection: EditorSelection.cursor(0) });
+ expect(editor.getSelectedText()).toBe("");
+ });
+ });
+
+ describe("update notifications", () => {
+ it("calls onContentChanged only for document changes", () => {
+ const onContentChanged = vi.fn();
+ editor = build({ onContentChanged });
+
+ editor.setText("typed");
+ expect(onContentChanged).toHaveBeenCalledTimes(1);
+
+ // A pure selection move is not a content change.
+ editor.dispatch({ selection: EditorSelection.cursor(1) });
+ expect(onContentChanged).toHaveBeenCalledTimes(1);
+ });
+
+ it("notifies registered listeners until they unsubscribe", () => {
+ editor = build();
+ const seen: ViewUpdate[] = [];
+ const unsubscribe = editor.addUpdateListener((v) => seen.push(v));
+
+ editor.setText("one");
+ expect(seen.length).toBeGreaterThan(0);
+
+ const countAfterFirst = seen.length;
+ unsubscribe();
+ editor.setText("two");
+ expect(seen.length).toBe(countAfterFirst);
+
+ // Unsubscribing twice must not remove somebody else's listener.
+ expect(() => unsubscribe()).not.toThrow();
+ });
+ });
+
+ describe("configuration changes", () => {
+ it("swaps the theme", async () => {
+ editor = build();
+ const theme = getThemeById("abyss");
+ expect(theme).not.toBeNull();
+ if (!theme) return;
+
+ await editor.setTheme(theme);
+ expect(editor.getText()).toBe("");
+ });
+
+ it("toggles line wrapping both ways", () => {
+ editor = build();
+ editor.setLineWrapping(true);
+ editor.setLineWrapping(false);
+ expect(editor.getText()).toBe("");
+ });
+
+ it("clamps the indent size to a sane range", () => {
+ editor = build();
+
+ editor.setIndent(2, false);
+ expect(editor.state.facet(indentUnit)).toBe(" ");
+
+ // Below 1, non-finite, and above 16 all fall back to a usable width.
+ editor.setIndent(0, false);
+ expect(editor.state.facet(indentUnit)).toBe(" ");
+ editor.setIndent(Number.NaN, false);
+ expect(editor.state.facet(indentUnit)).toBe(" ");
+ editor.setIndent(100, false);
+ expect(editor.state.facet(indentUnit)).toBe(" ".repeat(16));
+ });
+
+ it("keeps the other indent setting when only one is changed", () => {
+ editor = build({ indentSize: 2 });
+
+ editor.setUseTabs(true);
+ expect(editor.state.facet(indentUnit)).toBe("\t");
+
+ // Switching back to spaces must remember the size set earlier.
+ editor.setUseTabs(false);
+ expect(editor.state.facet(indentUnit)).toBe(" ");
+
+ editor.setIndentSize(6);
+ expect(editor.state.facet(indentUnit)).toBe(" ");
+ expect(editor.state.tabSize).toBe(6);
+ });
+
+ it("falls back to the default width when toggling tabs on an unconfigured editor", () => {
+ // No indentSize was ever supplied, so switching back to spaces has to land on the
+ // documented default rather than an undefined width.
+ editor = build();
+ editor.setUseTabs(true);
+ editor.setUseTabs(false);
+ expect(editor.state.facet(indentUnit)).toBe(" ");
+ });
+
+ it("adds a named extension once and reconfigures it afterwards", () => {
+ editor = build();
+
+ editor.setNamedExtension("wrap", EditorView.lineWrapping);
+ // Re-registering the same name must reconfigure rather than append a second copy,
+ // which CodeMirror would reject as a duplicate config.
+ expect(() => editor?.setNamedExtension("wrap", [])).not.toThrow();
+ expect(() => editor?.setNamedExtension("other", EditorState.readOnly.of(false))).not.toThrow();
+ });
+ });
+
+ describe("history", () => {
+ it("drops the undo stack", () => {
+ editor = build();
+ editor.setText("a");
+ expect(() => editor?.clearHistory()).not.toThrow();
+ expect(editor.getText()).toBe("a");
+ });
+
+ it("does nothing for a read-only editor", () => {
+ // A read-only editor has no history compartment to reconfigure.
+ editor = build({ readOnly: true });
+ expect(() => editor?.clearHistory()).not.toThrow();
+ });
+ });
+
+ describe("cursor placement", () => {
+ it("moves the cursor to the end of the document", () => {
+ editor = build();
+ editor.setText("line one\nline two");
+ editor.dispatch({ selection: EditorSelection.cursor(0) });
+
+ editor.scrollToEnd();
+ expect(editor.state.selection.main.head).toBe(editor.state.doc.length);
+ });
+
+ it("inserts a blank first line and puts the cursor on it", () => {
+ editor = build();
+ editor.setText("existing");
+
+ editor.insertBlankLineAtTop();
+ expect(editor.getText()).toBe("\nexisting");
+ expect(editor.state.selection.main.head).toBe(0);
+ });
+
+ it("only moves the cursor when the first line is already blank", () => {
+ // Otherwise a brand-new note would accumulate a second empty line.
+ editor = build();
+ editor.setText("\nexisting");
+ editor.dispatch({ selection: EditorSelection.cursor(5) });
+
+ editor.insertBlankLineAtTop();
+ expect(editor.getText()).toBe("\nexisting");
+ expect(editor.state.selection.main.head).toBe(0);
+ });
+
+ it("does nothing for a read-only editor", () => {
+ // CodeMirror's readOnly facet does not block programmatic transactions, so the guard
+ // is what stops a read-only note from being modified.
+ editor = build({ readOnly: true });
+ editor.insertBlankLineAtTop();
+ expect(editor.getText()).toBe("");
+ });
+ });
+
+ describe("find and replace", () => {
+ it("reports the matches it found", async () => {
+ editor = build();
+ editor.setText("foo bar foo");
+
+ const result = await editor.performFind("foo", false, false);
+ expect(result.totalFound).toBe(2);
+ });
+
+ it("replaces the active match and then all of them", async () => {
+ editor = build();
+ editor.setText("foo bar foo");
+
+ await editor.performFind("foo", false, false);
+ await editor.findNext(1, 0, 0);
+ await editor.replace("baz");
+ expect(editor.getText()).toBe("baz bar foo");
+
+ await editor.performFind("foo", false, false);
+ await editor.replaceAll("qux");
+ expect(editor.getText()).toBe("baz bar qux");
+ });
+
+ it("clears the highlighting after a search, and tolerates clearing twice", async () => {
+ editor = build();
+ editor.setText("foo bar foo");
+ await editor.performFind("foo", false, false);
+
+ editor.cleanSearch();
+ // The second call has nothing left to tear down and must not reconfigure again.
+ expect(() => editor?.cleanSearch()).not.toThrow();
+
+ // A later replace no longer has a plugin to act on.
+ await editor.replaceAll("x");
+ expect(editor.getText()).toBe("foo bar foo");
+ });
+
+ it("does nothing when cleaning a search that never ran", () => {
+ editor = build();
+ expect(() => editor?.cleanSearch()).not.toThrow();
+ });
+
+ it("does nothing when replace is called before a search", async () => {
+ editor = build();
+ editor.setText("foo");
+
+ await editor.findNext(1, 0, 0);
+ await editor.replace("x");
+ await editor.replaceAll("x");
+ expect(editor.getText()).toBe("foo");
+ });
+ });
+
+ describe("MIME types", () => {
+ it("applies a legacy stream-parser language", async () => {
+ editor = build();
+ await editor.setMimeType("text/x-yaml");
+ expect(editor.getText()).toBe("");
+ });
+
+ it("applies a LanguageSupport language", async () => {
+ editor = build();
+ await editor.setMimeType("text/css");
+ expect(editor.getText()).toBe("");
+ });
+
+ it("applies a language that resolves to a list of extensions", async () => {
+ editor = build();
+ await editor.setMimeType("application/json");
+ expect(editor.getText()).toBe("");
+ });
+
+ it("resolves an aliased MIME type through its target language", async () => {
+ editor = build();
+ await editor.setMimeType("image/svg+xml");
+ expect(editor.getText()).toBe("");
+ });
+
+ it("clears the language for plain text and for an unknown MIME type", async () => {
+ editor = build();
+ await editor.setMimeType("text/plain");
+ await editor.setMimeType("application/something-nobody-supports");
+ expect(editor.getText()).toBe("");
+ });
+ });
+
+ describe("completion sources", () => {
+ it("registers and removes named sources", () => {
+ editor = build();
+ const source = () => null;
+
+ editor.setCompletionSource("snippets", source);
+ editor.setCompletionSource("other", source);
+ // Removing the last one must drop autocompletion entirely rather than configure it
+ // with an empty override list.
+ editor.setCompletionSource("snippets", null);
+ editor.setCompletionSource("other", null);
+ expect(editor.getText()).toBe("");
+ });
+ });
+
+ describe("script api context", () => {
+ it("is safe to set before any MIME type is known", async () => {
+ editor = build();
+ await editor.setScriptApiContext({});
+ expect(editor.getText()).toBe("");
+ });
+
+ it("rebuilds the completion once a MIME type has been set", async () => {
+ editor = build();
+ await editor.setMimeType("text/plain");
+ await editor.setScriptApiContext({ customRequestHandler: true });
+ expect(editor.getText()).toBe("");
+ });
+ });
+
+ describe("concurrent MIME changes", () => {
+ it("keeps the language of the last request when an earlier one resolves late", async () => {
+ // Each setMimeType bumps a token; a slow grammar load for a superseded MIME must not
+ // overwrite the newer one's type completion when it finally settles.
+ editor = build();
+ const slow = editor.setMimeType("text/x-yaml");
+ const fast = editor.setMimeType("text/css");
+ await Promise.all([ slow, fast ]);
+
+ expect(editor.getText()).toBe("");
+ });
+ });
+
+ describe("key handling", () => {
+ it("swallows Ctrl-Enter so it cannot insert a newline", () => {
+ // Ctrl-Enter is the "run script"/submit chord owned by the surrounding UI; letting
+ // CodeMirror handle it would drop a line break into the note.
+ editor = build();
+ editor.setText("line");
+ editor.dispatch({ selection: EditorSelection.cursor(4) });
+
+ const handled = !editor.contentDOM.dispatchEvent(new KeyboardEvent("keydown", {
+ key: "Enter",
+ ctrlKey: true,
+ bubbles: true,
+ cancelable: true
+ }));
+
+ expect(handled).toBe(true);
+ expect(editor.getText()).toBe("line");
+ });
+ });
+});
+
+function build(config: Partial<EditorConfig> = {}): CodeMirror {
+ const parent = document.createElement("div");
+ document.body.appendChild(parent);
+ return new CodeMirror({ parent, ...config });
+}
diff --git a/packages/codemirror/src/index.ts b/packages/codemirror/src/index.ts
index 8cab4153b6..bcfd0fe401 100644
--- a/packages/codemirror/src/index.ts
+++ b/packages/codemirror/src/index.ts
@@ -308,6 +308,9 @@ export default class CodeMirror extends EditorView {
instance?.searchFor(searchTerm, matchCase, wholeWord);
this.searchPlugin = instance;
+ /* v8 ignore next 4 -- the plugin was just installed via the compartment above and the
+ view has re-rendered, so `this.plugin()` always resolves it; the guards only cover a
+ view destroyed mid-search. */
return {
totalFound: instance?.totalFound ?? 0,
currentFound: instance?.currentFound ?? 0
diff --git a/packages/codemirror/src/languages/abap.spec.ts b/packages/codemirror/src/languages/abap.spec.ts
new file mode 100644
index 0000000000..9d67f7a495
--- /dev/null
+++ b/packages/codemirror/src/languages/abap.spec.ts
@@ -0,0 +1,147 @@
+import { StringStream } from "@codemirror/language";
+import { describe, expect, it } from "vitest";
+
+import { abapMode } from "./abap.js";
+
+describe("abapMode", () => {
+ it("starts with the string mode off", () => {
+ expect(abapMode.startState?.(2)).toEqual({ mode: false });
+ });
+
+ it("recognises keywords, case-insensitively", () => {
+ // ABAP source is conventionally upper-case but the editor must colour either casing.
+ expect(tokenize("DATA lv_x")).toEqual([
+ { text: "DATA", type: "keyword" },
+ { text: "lv_x", type: null }
+ ]);
+ expect(typesOf("data lv_x")).toEqual([ "keyword", null ]);
+ expect(typesOf("IF lv_x")).toEqual([ "keyword", null ]);
+ });
+
+ it("stops a keyword at each of its separators", () => {
+ // A keyword can be followed by `(`, `.`, `,`, `:` or a space, and must still be matched.
+ expect(typesOf("ENDIF.")).toEqual([ "keyword", null ]);
+ expect(typesOf("METHODS:")).toEqual([ "keyword", null ]);
+ const valueCall = tokenize("VALUE(lv_x)");
+ expect(valueCall[0]).toEqual({ text: "VALUE", type: "keyword" });
+ expect(valueCall.map((t) => t.text).join("")).toBe("VALUE(lv_x)");
+ });
+
+ it("rewinds a word that only looked like a keyword", () => {
+ // `DATAX` shares a prefix with `DATA`; the scanner has to back all the way up so the
+ // whole identifier is emitted rather than half of it being coloured.
+ expect(tokenize("DATAX")).toEqual([ { text: "DATAX", type: null } ]);
+ expect(tokenize("lv_value")).toEqual([ { text: "lv_value", type: null } ]);
+ });
+
+ it("recognises numbers only where a number can end", () => {
+ expect(tokenize("42 ")).toEqual([ { text: "42", type: "number" } ]);
+ expect(tokenize("42.")).toEqual([
+ { text: "42", type: "number" },
+ { text: ".", type: null }
+ ]);
+ expect(tokenize("42")).toEqual([ { text: "42", type: "number" } ]);
+ // A digit run glued to letters is an identifier, not a number.
+ expect(typesOf("42abc")).toEqual([ null ]);
+ });
+
+ it("recognises pragmas", () => {
+ expect(tokenize("##NEEDED")).toEqual([ { text: "##NEEDED", type: "comment" } ]);
+ });
+
+ it("treats a leading asterisk as a full-line comment", () => {
+ expect(tokenize("* commented out")).toEqual([ { text: "* commented out", type: "comment" } ]);
+ });
+
+ it("treats a double quote as a comment to end of line", () => {
+ expect(tokenize(`lv_x " trailing note`)).toEqual([
+ { text: "lv_x", type: null },
+ { text: `" trailing note`, type: "comment" }
+ ]);
+ });
+
+ it("does not treat an asterisk away from column 0 as a comment", () => {
+ // Mid-line `*` is multiplication.
+ expect(typesOf("2 * 3")).toEqual([ "number", "operator", "number" ]);
+ });
+
+ it("recognises symbol operators", () => {
+ expect(typesOf("a = b")).toEqual([ null, "operator", null ]);
+ expect(typesOf("a <> b")).toEqual([ null, "operator", null ]);
+ expect(typesOf("a >= b")).toEqual([ null, "operator", null ]);
+ // `&&` is ABAP's string-concatenation operator. It has to be matched as one token: the
+ // two lists of operators used to be concatenated without a separator, which glued "&&"
+ // onto "EQ" and left `&&` matching nothing.
+ expect(tokenize("a && b")).toEqual([
+ { text: "a", type: null },
+ { text: "&&", type: "operator" },
+ { text: "b", type: null }
+ ]);
+ });
+
+ it("recognises word operators that are not also statement keywords", () => {
+ expect(typesOf("a MOD b")).toEqual([ null, "operator", null ]);
+ expect(typesOf("a XOR b")).toEqual([ null, "operator", null ]);
+ expect(typesOf("a BETWEEN b")).toEqual([ null, "operator", null ]);
+ });
+
+ it("colours a word appearing in both lists as a keyword", () => {
+ // EQ, AND and NOT are listed as ABAP statement keywords as well as comparison operators.
+ // Keywords are checked first, so that is what wins — worth pinning, since flipping the
+ // order would silently recolour a large amount of ordinary ABAP.
+ expect(typesOf("a EQ b")).toEqual([ null, "keyword", null ]);
+ expect(typesOf("a AND b")).toEqual([ null, "keyword", null ]);
+ });
+
+ it("recognises quoted strings", () => {
+ expect(tokenize("'hello'")).toEqual([ { text: "'hello'", type: "string" } ]);
+ expect(typesOf("lv_x = 'hi'")).toEqual([ null, "operator", "string" ]);
+ });
+
+ it("recognises pipe-delimited string templates", () => {
+ expect(tokenize("|hello|")).toEqual([ { text: "|hello|", type: "string" } ]);
+ });
+
+ it("runs an unterminated string to the end of the line", () => {
+ // A half-typed literal must still colour as a string rather than derailing the line.
+ expect(tokenize("'unterminated")).toEqual([ { text: "'unterminated", type: "string" } ]);
+ expect(tokenize("|unterminated")).toEqual([ { text: "|unterminated", type: "string" } ]);
+ });
+
+ it("emits no token for blank input and skips whitespace", () => {
+ expect(tokenize(" ")).toEqual([]);
+ expect(tokenize("")).toEqual([]);
+ });
+
+ it("tokenises a realistic statement end to end", () => {
+ expect(typesOf("IF lv_count > 10.")).toEqual([
+ "keyword", null, "operator", "number", null
+ ]);
+ });
+});
+
+/** Runs the parser over one line, returning each token's text and type. */
+function tokenize(line: string): { text: string; type: string | null }[] {
+ const state = abapMode.startState?.(2) ?? {};
+ const stream = new StringStream(line, 2, 2, 0);
+ const tokens: { text: string; type: string | null }[] = [];
+
+ while (!stream.eol()) {
+ stream.start = stream.pos;
+ const type = abapMode.token(stream, state) ?? null;
+ // A parser that consumes nothing would spin forever; force progress the way CodeMirror does.
+ if (stream.pos === stream.start) {
+ stream.next();
+ continue;
+ }
+ const text = stream.current();
+ if (text.trim() !== "") {
+ tokens.push({ text, type });
+ }
+ }
+ return tokens;
+}
+
+function typesOf(line: string): (string | null)[] {
+ return tokenize(line).map((token) => token.type);
+}
diff --git a/packages/codemirror/src/syntax_highlighting.spec.ts b/packages/codemirror/src/syntax_highlighting.spec.ts
new file mode 100644
index 0000000000..1c5b6859a8
--- /dev/null
+++ b/packages/codemirror/src/syntax_highlighting.spec.ts
@@ -0,0 +1,61 @@
+import { LanguageSupport, StreamLanguage, type StreamParser } from "@codemirror/language";
+import { EditorState, type Extension } from "@codemirror/state";
+import { SupportedMimeTypes } from "@triliumnext/commons";
+import { describe, expect, it } from "vitest";
+
+import byMimeType, { MIME_ALIASES } from "./syntax_highlighting.js";
+
+const entries = Object.entries(byMimeType) as [SupportedMimeTypes, (typeof byMimeType)[SupportedMimeTypes]][];
+const loadable = entries.filter((entry): entry is [SupportedMimeTypes, NonNullable<typeof entry[1]>] => entry[1] !== null);
+
+describe("byMimeType", () => {
+ it("covers every supported MIME type exactly once", () => {
+ // The map is typed as Record<SupportedMimeTypes, …>, so a missing key is a compile error —
+ // but an accidental duplicate literal silently keeps only the last one, and a MIME added to
+ // commons without an entry here would fall through to no highlighting at all.
+ expect(entries.length).toBe(Object.keys(byMimeType).length);
+ expect(new Set(entries.map(([mime]) => mime)).size).toBe(entries.length);
+ expect(loadable.length).toBeGreaterThan(0);
+ });
+
+ // Each entry is a dynamic import of a third-party grammar, reaching for a specific named
+ // export. A renamed or dropped export only surfaces when a user opens a note of that type,
+ // so load every one of them here and assert it produced something CodeMirror can consume.
+ it.each(loadable.map(([mime]) => mime))("loads a usable language for %s", async (mime) => {
+ const loader = byMimeType[mime];
+ expect(loader).toBeTruthy();
+ if (!loader) return;
+
+ const syntax = await loader();
+ expect(syntax).toBeTruthy();
+ expect(() => stateFor(syntax)).not.toThrow();
+ });
+
+ it("maps aliased MIME types onto a language that exists in the map", () => {
+ // SVG notes highlight as XML; an alias pointing at a missing or null entry would silently
+ // drop highlighting for that note type.
+ for (const [alias, target] of Object.entries(MIME_ALIASES)) {
+ expect(Object.keys(byMimeType)).toContain(target);
+ expect(byMimeType[target]).not.toBeNull();
+ expect(alias in byMimeType).toBe(false);
+ }
+ });
+
+ it("leaves plain text and template languages without a highlighter", () => {
+ // These are deliberately null rather than absent — the editor treats null as "no syntax"
+ // instead of falling into the "unknown MIME" path.
+ expect(byMimeType["text/plain"]).toBeNull();
+ expect(byMimeType["application/x-ejs"]).toBeNull();
+ });
+});
+
+/**
+ * Builds an editor state from whatever shape a loader returned — a legacy `StreamParser`, a
+ * `LanguageSupport`, or a ready-made extension array — which is exactly what `setMimeType` does.
+ */
+function stateFor(syntax: StreamParser<unknown> | LanguageSupport | Extension[]): EditorState {
+ const extension = syntax instanceof LanguageSupport || Array.isArray(syntax)
+ ? syntax
+ : StreamLanguage.define(syntax);
+ return EditorState.create({ doc: "a\nb\n", extensions: [extension] });
+}
diff --git a/packages/codemirror/src/type_completion/index.spec.ts b/packages/codemirror/src/type_completion/index.spec.ts
index 26ceea84af..7ff81f93e2 100644
--- a/packages/codemirror/src/type_completion/index.spec.ts
+++ b/packages/codemirror/src/type_completion/index.spec.ts
@@ -1,6 +1,14 @@
import { describe, expect, it } from "vitest";
-import { getScriptCompletions, getScriptDiagnosticCodes, SCRIPT_MIME_BACKEND, SCRIPT_MIME_FRONTEND, SCRIPT_MIME_JSX } from "./index.js";
+import {
+ buildTypeCompletion,
+ getScriptCompletions,
+ getScriptDiagnosticCodes,
+ renderHoverTooltip,
+ SCRIPT_MIME_BACKEND,
+ SCRIPT_MIME_FRONTEND,
+ SCRIPT_MIME_JSX
+} from "./index.js";
/** Returns completions at the `|` marker in `source` (the marker is stripped). */
function completionsAtMarker(mime: string, source: string, context?: { customRequestHandler?: boolean }) {
@@ -428,3 +436,91 @@ describe("JSX component typing", () => {
expect(codes).toContain(TS_TYPE_NOT_ASSIGNABLE);
}, TIMEOUT);
});
+
+describe("buildTypeCompletion", () => {
+ it("returns nothing for a MIME type that is not a script note", async () => {
+ // Ordinary code notes are highlighted only; the TypeScript service is not built for them.
+ for (const mime of [ "text/plain", "text/css", "application/json", "text/javascript" ]) {
+ expect(await buildTypeCompletion(mime)).toEqual({ extensions: [], source: null });
+ }
+ });
+
+ it("builds the language-service extensions and a completion source for a script note", async () => {
+ const { extensions, source } = await buildTypeCompletion(SCRIPT_MIME_BACKEND);
+
+ expect(Array.isArray(extensions)).toBe(true);
+ expect(extensions.length).toBeGreaterThan(0);
+ // The source is handed to the editor's single autocompletion rather than adding its own.
+ expect(typeof source).toBe("function");
+ }, TIMEOUT);
+
+ it("builds for a frontend script note and honours the api context", async () => {
+ const frontend = await buildTypeCompletion(SCRIPT_MIME_FRONTEND);
+ expect(frontend.source).toBeTruthy();
+
+ const handler = await buildTypeCompletion(SCRIPT_MIME_BACKEND, { customRequestHandler: true });
+ expect(handler.source).toBeTruthy();
+ }, TIMEOUT);
+});
+
+describe("renderHoverTooltip", () => {
+ it("renders the signature, the JSDoc body and each tag", () => {
+ const { dom } = renderHoverTooltip({
+ quickInfo: {
+ displayParts: [
+ { text: "function ", kind: "keyword" },
+ { text: "showMessage", kind: "functionName" }
+ ],
+ documentation: [ { text: "Shows a toast." } ],
+ tags: [
+ { name: "param", text: [ { text: "message the text" } ] },
+ { name: "returns", text: [ { text: "nothing" } ] }
+ ]
+ }
+ });
+
+ expect(dom.querySelector(".cm-ts-hover-signature")?.textContent).toBe("function showMessage");
+ expect(dom.querySelector(".quick-info-keyword")?.textContent).toBe("function ");
+ expect(dom.querySelector(".cm-ts-hover-doc")?.textContent).toBe("Shows a toast.");
+
+ const tags = [ ...dom.querySelectorAll(".cm-ts-hover-tag") ].map((el) => el.textContent);
+ expect(tags).toEqual([ "@param message the text", "@returns nothing" ]);
+ });
+
+ it("omits the doc block when there is no documentation", () => {
+ const { dom } = renderHoverTooltip({
+ quickInfo: { displayParts: [ { text: "const x: number" } ] }
+ });
+
+ expect(dom.querySelector(".cm-ts-hover-doc")).toBeNull();
+ expect(dom.querySelectorAll(".cm-ts-hover-tag")).toHaveLength(0);
+ // A part with no kind falls back to the generic text class.
+ expect(dom.querySelector(".quick-info-text")?.textContent).toBe("const x: number");
+ });
+
+ it("renders a tag that carries no text", () => {
+ const { dom } = renderHoverTooltip({
+ quickInfo: { tags: [ { name: "deprecated" } ] }
+ });
+
+ expect(dom.querySelector(".cm-ts-hover-tag")?.textContent).toBe("@deprecated");
+ });
+
+ it("renders an empty tooltip when the language service returned no quick info", () => {
+ // Hovering whitespace yields no quickInfo at all; the renderer still has to return a node.
+ const { dom } = renderHoverTooltip({});
+
+ expect(dom.className).toBe("cm-ts-hover");
+ expect(dom.querySelector(".cm-ts-hover-signature")?.textContent).toBe("");
+ expect(dom.querySelector(".cm-ts-hover-doc")).toBeNull();
+ });
+});
+
+describe("empty script notes", () => {
+ it("analyses an empty document without tripping the language service", async () => {
+ // A newly created script note has no content; the empty string is substituted with a
+ // space so TypeScript still gets a valid file to parse.
+ expect(await getScriptDiagnosticCodes(SCRIPT_MIME_BACKEND, "")).toEqual([]);
+ expect(await getScriptCompletions(SCRIPT_MIME_BACKEND, "", 0)).toEqual(expect.any(Array));
+ }, TIMEOUT);
+});
diff --git a/packages/codemirror/src/type_completion/index.ts b/packages/codemirror/src/type_completion/index.ts
index 5faaaf2e73..01b2e630de 100644
--- a/packages/codemirror/src/type_completion/index.ts
+++ b/packages/codemirror/src/type_completion/index.ts
@@ -96,6 +96,8 @@ let cachedLibFilesMap: Map<string, string> | null = null;
async function createEnv(mime: string, context: ScriptApiContext = {}) {
const tsModule = await import("typescript");
+ /* v8 ignore next -- typescript ships as CJS, so the interop namespace always carries
+ `default`; the fallback only covers a future ESM-native build. */
const ts = tsModule.default ?? tsModule;
const { createSystem, createVirtualTypeScriptEnvironment } = await import("@typescript/vfs");
// Dynamically imported so the bundled lib.*.d.ts text lands in the lazy
@@ -259,7 +261,7 @@ interface DisplayPart {
* `@returns`, `@example`, …). The doc text comes straight from the shared API
* surface's `/** … *​/` comments.
*/
-function renderHoverTooltip(info: { quickInfo?: { displayParts?: DisplayPart[]; documentation?: DisplayPart[]; tags?: { name: string; text?: DisplayPart[] }[] } }): { dom: HTMLElement } {
+export function renderHoverTooltip(info: { quickInfo?: { displayParts?: DisplayPart[]; documentation?: DisplayPart[]; tags?: { name: string; text?: DisplayPart[] }[] } }): { dom: HTMLElement } {
const quickInfo = info.quickInfo;
const dom = document.createElement("div");
dom.className = "cm-ts-hover";
@@ -357,5 +359,7 @@ export async function getScriptCompletions(mime: string, code: string, offset: n
const path = scriptPath(mime);
env.updateFile(path, code.length ? code : " ");
const completions = env.languageService.getCompletionsAtPosition(path, offset, {});
+ /* v8 ignore next -- the service clamps an out-of-range offset rather than returning nothing,
+ so this only guards a language-service failure. */
return completions?.entries.map((entry) => entry.name) ?? [];
}
diff --git a/packages/codemirror/vite.config.ts b/packages/codemirror/vite.config.ts
index 43901fba98..4932a471d7 100644
--- a/packages/codemirror/vite.config.ts
+++ b/packages/codemirror/vite.config.ts
@@ -37,6 +37,12 @@ export default defineConfig(() => ({
['junit', { outputFile: './test-output/vitest/junit.xml', addFileAttribute: true }]
],
coverage: {
+ thresholds: {
+ lines: 100,
+ functions: 100,
+ branches: 100,
+ statements: 100
+ },
provider: 'v8',
include: ['src/**/*.{ts,tsx}'],
exclude: ['**/*.{test,spec}.{ts,mts,cts,tsx,js,jsx}', '**/*.d.ts'],