Skip to content

Build your personal knowledge base with Trilium Notes

test(codemirror): cover the search field's editor to the package's gate

Elian Dorancf5e03e787ff
diff --git a/packages/codemirror/src/extensions/trilium_note_chips.spec.ts b/packages/codemirror/src/extensions/trilium_note_chips.spec.ts
index 8ab7e626f1..2a1adb3a13 100644
--- a/packages/codemirror/src/extensions/trilium_note_chips.spec.ts
+++ b/packages/codemirror/src/extensions/trilium_note_chips.spec.ts
@@ -1,4 +1,5 @@
-import { EditorSelection } from "@codemirror/state";
+import { EditorSelection, type Extension } from "@codemirror/state";
+import { EditorView } from "@codemirror/view";
import { afterEach, describe, expect, it, vi } from "vitest";
import { createFieldEditor, type FieldEditor } from "../field_editor.js";
@@ -58,6 +59,60 @@ describe("triliumNoteChips", () => {
expect(editor?.state.doc.toString()).toBe("~author.noteId = abc123");
});
+ it("asks for a note once while the answer is still on its way", async () => {
+ let answer = (chip: NoteChip) => { void chip; };
+ const resolve = vi.fn<NoteChipResolver>(() => new Promise<NoteChip>((settle) => { answer = settle; }));
+ const parent = build("~author.noteId = abc123", resolve);
+
+ // The rebuild this edit triggers waits on the answer already asked for.
+ editorFor(parent).dispatch({ changes: { from: 0, insert: "#book " } });
+ expect(resolve).toHaveBeenCalledTimes(1);
+ expect(parent.querySelector(".cm-note-chip")).toBe(null);
+
+ answer(TOLKIEN);
+ await vi.waitFor(() => expect(parent.querySelector(".cm-note-chip")?.textContent).toBe("Tolkien"));
+ });
+
+ it("leaves the id as text when looking the note up fails", async () => {
+ const redrawn = vi.fn();
+ const resolve = vi.fn<NoteChipResolver>(() => Promise.reject(new Error("offline")));
+ const parent = build("~author.noteId = abc123", resolve, [ EditorView.updateListener.of(redrawn) ]);
+
+ // The failure redraws the field rather than reaching the editor as an unhandled rejection.
+ await vi.waitFor(() => expect(redrawn).toHaveBeenCalled());
+ expect(parent.querySelector(".cm-note-chip")).toBe(null);
+ expect(parent.textContent).toContain("abc123");
+ // Recorded the way a missing note is, so the redraw asks nothing more.
+ expect(resolve).toHaveBeenCalledTimes(1);
+ });
+
+ it("keeps a drawn chip across an edit elsewhere in the query", () => {
+ const parent = build("~author.noteId = abc123", () => TOLKIEN);
+ const chip = parent.querySelector(".cm-note-chip");
+ expect(chip).not.toBe(null);
+
+ editorFor(parent).dispatch({ changes: { from: editorFor(parent).state.doc.length, insert: " #book" } });
+
+ // The rebuilt widget equals the one already drawn, so its element is reused rather than replaced.
+ expect(parent.querySelector(".cm-note-chip")).toBe(chip);
+ });
+
+ it("keeps the field usable when the resolver throws", () => {
+ const logged = vi.spyOn(console, "error").mockImplementation(() => {});
+
+ try {
+ const view = editorFor(build("~author.noteId = abc123", () => { throw new Error("offline"); }));
+ view.dispatch({ selection: EditorSelection.cursor(0) });
+
+ // No chip and no atomic range to step over, so the caret moves a character at a time.
+ expect(view.moveByChar(view.state.selection.main, true).head).toBe(1);
+ expect(parentOf(view).querySelector(".cm-note-chip")).toBe(null);
+ expect(logged).toHaveBeenCalled();
+ } finally {
+ logged.mockRestore();
+ }
+ });
+
it("reads only a noteId comparison, leaving id-shaped words of the query alone", () => {
const resolve = vi.fn<NoteChipResolver>(() => TOLKIEN);
const parent = build("abc123 #book = abc123 ~author.title = abc123", resolve);
@@ -70,12 +125,12 @@ describe("triliumNoteChips", () => {
});
});
-function build(doc: string, resolve: NoteChipResolver) {
+function build(doc: string, resolve: NoteChipResolver, extensions: Extension[] = []) {
editor?.destroy();
const parent = document.createElement("div");
document.body.appendChild(parent);
- editor = createFieldEditor({ parent, doc, extensions: [ triliumNoteChips(resolve) ] });
+ editor = createFieldEditor({ parent, doc, extensions: [ triliumNoteChips(resolve), ...extensions ] });
return parent;
}
@@ -87,3 +142,12 @@ function editorFor(parent: HTMLElement): FieldEditor {
return editor;
}
+
+function parentOf(view: FieldEditor): HTMLElement {
+ const parent = view.dom.parentElement;
+ if (!parent) {
+ throw new Error("The editor was not built into an element.");
+ }
+
+ return parent;
+}
diff --git a/packages/codemirror/src/extensions/trilium_search_highlighter.spec.ts b/packages/codemirror/src/extensions/trilium_search_highlighter.spec.ts
index 591271542d..087ba9ff3b 100644
--- a/packages/codemirror/src/extensions/trilium_search_highlighter.spec.ts
+++ b/packages/codemirror/src/extensions/trilium_search_highlighter.spec.ts
@@ -1,3 +1,4 @@
+import { EditorSelection } from "@codemirror/state";
import { describe, expect, it } from "vitest";
import { createFieldEditor } from "../field_editor.js";
@@ -111,6 +112,13 @@ describe("triliumSearchHighlighter", () => {
expect(textOf(parent, ".cm-search-relation")).toEqual([ "~author" ]);
expect(textOf(parent, ".cm-search-property")).toEqual([ ".title" ]);
expect(textOf(parent, ".cm-search-string")).toEqual([ "'Tolkien'" ]);
+
+ // An edit recolours the query, while a transaction that changes no text keeps what is drawn.
+ editor.dispatch({ changes: { from: 0, to: 5, insert: "#novel" } });
+ expect(textOf(parent, ".cm-search-label")).toEqual([ "#novel" ]);
+
+ editor.dispatch({ selection: EditorSelection.cursor(0) });
+ expect(textOf(parent, ".cm-search-label")).toEqual([ "#novel" ]);
} finally {
editor.destroy();
}
diff --git a/packages/codemirror/src/extensions/trilium_search_lint.spec.ts b/packages/codemirror/src/extensions/trilium_search_lint.spec.ts
index 2dbce440f8..f0331e5817 100644
--- a/packages/codemirror/src/extensions/trilium_search_lint.spec.ts
+++ b/packages/codemirror/src/extensions/trilium_search_lint.spec.ts
@@ -1,6 +1,8 @@
+import { diagnosticCount, forceLinting } from "@codemirror/lint";
import { describe, expect, it, vi } from "vitest";
-import { diagnoseSearchQuery, type SearchLintMessages, searchDiagnostics, type SearchValidator } from "./trilium_search_lint.js";
+import { createFieldEditor } from "../field_editor.js";
+import { diagnoseSearchQuery, type SearchLintMessages, searchDiagnostics, type SearchValidator, triliumSearchLinter } from "./trilium_search_lint.js";
// The wording is the consumer's; the keys identify which rule answered.
const MESSAGES: SearchLintMessages = {
@@ -74,6 +76,12 @@ describe("diagnoseSearchQuery", () => {
expect(messagesFor("~author tolkien = x")).toEqual([]);
});
+ it("leaves an operator alone when nothing it could compare stands in front of it", () => {
+ // Nothing at all before the operator, then a value the rules have no opinion about.
+ expect(messagesFor("= hello")).toEqual([]);
+ expect(messagesFor("#book = 1 = 2")).toEqual([]);
+ });
+
it("marks each offending comparison in a query that holds several", () => {
expect(messagesFor("#book = 1 ~author = x note.text = y")).toEqual([ "relation", "text" ]);
});
@@ -118,6 +126,27 @@ describe("searchDiagnostics", () => {
});
});
+describe("triliumSearchLinter", () => {
+ it("marks the query in the editor with what the engine refuses", async () => {
+ const parent = document.createElement("div");
+ document.body.appendChild(parent);
+ const view = createFieldEditor({
+ parent,
+ doc: "#a and #b or #c",
+ extensions: [ triliumSearchLinter(MESSAGES, async () => "Mixed usage of AND/OR") ]
+ });
+
+ try {
+ forceLinting(view);
+
+ await vi.waitFor(() => expect(diagnosticCount(view.state)).toBe(1));
+ expect(parent.querySelector(".cm-lintRange-error")?.textContent).toBe("#a and #b or #c");
+ } finally {
+ view.destroy();
+ }
+ });
+});
+
/** Drives the real lint source and keeps only what a squiggle is drawn from. */
async function ranges(query: string, validate: SearchValidator) {
const diagnostics = await searchDiagnostics(query, MESSAGES, validate);
diff --git a/packages/codemirror/src/field_editor.spec.ts b/packages/codemirror/src/field_editor.spec.ts
index f1605402d1..e2158e4161 100644
--- a/packages/codemirror/src/field_editor.spec.ts
+++ b/packages/codemirror/src/field_editor.spec.ts
@@ -120,6 +120,53 @@ describe("createFieldEditor", () => {
// Shift-Enter is swallowed, rather than reaching the field as the flattened indentation.
expect(pressKey(editor, "Enter", { shiftKey: true })).toBe(true);
expect(editor.state.doc.toString()).toBe("#book #year = 1954");
+
+ // A change already on one line is left as it was written, as is one that edits no text.
+ editor.dispatch({ changes: { from: 0, insert: "@" } });
+ editor.dispatch({ selection: EditorSelection.cursor(0) });
+ expect(editor.state.doc.toString()).toBe("@#book #year = 1954");
+ expect(editor.state.selection.main.head).toBe(0);
+ });
+
+ it("leaves the keys it claims to an IME while it is composing", () => {
+ const onEnter = vi.fn();
+ const onArrowDown = vi.fn().mockReturnValue(true);
+ editor = build({ doc: "#book\n#year", onEnter, onArrowDown });
+ editor.dispatch({ selection: EditorSelection.cursor(0) });
+ Object.defineProperty(editor, "composing", { get: () => true });
+
+ pressKey(editor, "Enter");
+ pressKey(editor, "ArrowDown");
+
+ expect(onEnter).not.toHaveBeenCalled();
+ expect(onArrowDown).not.toHaveBeenCalled();
+ });
+
+ it("draws the placeholder and names the field for assistive technology", () => {
+ editor = build({ placeholder: "Search", ariaLabel: "Search string" });
+
+ expect(editor.dom.querySelector(".cm-placeholder")?.textContent).toBe("Search");
+ expect(editor.contentDOM.getAttribute("aria-label")).toBe("Search string");
+ });
+
+ it("draws a completion with the icon the consumer answers for it", async () => {
+ const view = build({
+ doc: "#b",
+ completionSource: () => ({ from: 0, options: [ { label: "#book" }, { label: "#borrowed" } ] }),
+ completionIcon: (completion) => completion.label === "#book" ? "bx bx-hash" : undefined
+ });
+ editor = view;
+ view.dispatch({ selection: EditorSelection.cursor(2) });
+
+ await openCompletion(view);
+
+ // The option answering nothing is drawn without a glyph, rather than with an empty one.
+ const glyphs = Array.from(document.querySelectorAll(".cm-tooltip-autocomplete li"))
+ .map((option) => option.querySelector(".cm-completion-glyph"));
+ expect(glyphs.map((glyph) => glyph?.className)).toEqual([ "cm-completion-glyph bx bx-hash", undefined ]);
+ expect(glyphs[0]?.getAttribute("aria-hidden")).toBe("true");
+ // Supplying the icons replaces CodeMirror's own.
+ expect(document.querySelector(".cm-completionIcon")).toBe(null);
});
it("keeps the line breaks in inserted text", () => {