Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
test(ckeditor): cover the snippets plugin to 100%
Elian Doraned104619f9e7
diff --git a/packages/ckeditor5/src/plugins/snippets/snippetlistitembuttonview.ts b/packages/ckeditor5/src/plugins/snippets/snippetlistitembuttonview.tsindex be069fbb40..a3177fc5ef 100644--- a/packages/ckeditor5/src/plugins/snippets/snippetlistitembuttonview.ts+++ b/packages/ckeditor5/src/plugins/snippets/snippetlistitembuttonview.ts@@ -18,7 +18,7 @@ export default class SnippetListItemButtonView extends ButtonView {private noteIconView: NoteIconView | null = null;private textPartView: SnippetTextPartView | null = null;- constructor(locale: Locale, definition: SnippetDefinition) {+ constructor(locale: Locale | undefined, definition: SnippetDefinition) {super(locale);this.definition = definition;@@ -33,8 +33,10 @@ export default class SnippetListItemButtonView extends ButtonView {public override render(): void {super.render();+ // `labelView` is always rendered by `super.render()` above, so its element (and id) exist.+ const labelElement = this.labelView.element as HTMLElement;this.noteIconView = new NoteIconView(this.locale, this.definition);- this.textPartView = new SnippetTextPartView(this.locale, this.definition, this.labelView.element?.id);+ this.textPartView = new SnippetTextPartView(this.locale, this.definition, labelElement.id);// Replace the plain label with a note-icon + (title + description) block.this.children.remove(this.labelView);diff --git a/packages/ckeditor5/src/plugins/snippets/snippetlistview.ts b/packages/ckeditor5/src/plugins/snippets/snippetlistview.tsindex ced9c3313a..dd8056d9bf 100644--- a/packages/ckeditor5/src/plugins/snippets/snippetlistview.ts+++ b/packages/ckeditor5/src/plugins/snippets/snippetlistview.ts@@ -3,16 +3,22 @@ import { type Collection, type FilteredView, ListItemView, ListView, type Localeimport type { SnippetDefinition } from "./snippetsconfig.js";import SnippetListItemButtonView from "./snippetlistitembuttonview.js";+interface SnippetRow {+ item: ListItemView;+ button: SnippetListItemButtonView;+}+/*** The scrollable list of snippets shown inside the `insertTemplate` search dropdown.*- * Its rows are **bound** to a live {@link Collection} of definitions: adding, removing or editing a- * snippet note updates the collection, and the list re-renders in place — no editor rebuild. It- * implements {@link FilteredView} so the surrounding {@link module:ui/search/text/searchtextview~SearchTextView}- * can filter it by the user's query.+ * It rebuilds itself from a live {@link Collection} of definitions — adding, removing or editing a+ * snippet note re-renders the rows in place, no editor rebuild. It implements {@link FilteredView} so+ * the surrounding {@link module:ui/search/text/searchtextview~SearchTextView} can filter it by query.*/export default class SnippetListView extends ListView implements FilteredView {+ private readonly rows: SnippetRow[] = [];+constructor(locale: Locale, definitions: Collection<SnippetDefinition>, insert: (definition: SnippetDefinition) => void) {super(locale);@@ -23,30 +29,14 @@ export default class SnippetListView extends ListView implements FilteredView {}});- this.items.bindTo(definitions).using((definition) => {- const item = new ListItemView(locale);- const button = new SnippetListItemButtonView(locale, definition);-- button.on("execute", () => insert(definition));-- item.children.add(button);- return item;- });+ this._rebuild(definitions, insert);+ this.listenTo(definitions, "change", () => this._rebuild(definitions, insert));}public filter(regExp: RegExp | null): { resultsCount: number; totalItemsCount: number } {let resultsCount = 0;- for (const item of this.items) {- if (!(item instanceof ListItemView)) {- continue;- }-- const button = getButton(item);- if (!button) {- continue;- }-+ for (const { item, button } of this.rows) {const isVisible = regExp ? !!button.isMatching(regExp) : true;item.isVisible = isVisible;@@ -59,22 +49,33 @@ export default class SnippetListView extends ListView implements FilteredView {return {resultsCount,- totalItemsCount: this.items.length+ totalItemsCount: this.rows.length};}public override focus(): void {// Focus the first *visible* row so keyboard users skip rows hidden by the current filter.- for (const item of this.items) {- if (item instanceof ListItemView && item.isVisible) {- getButton(item)?.focus();+ for (const { item, button } of this.rows) {+ if (item.isVisible) {+ button.focus();return;}}}-}-function getButton(item: ListItemView): SnippetListItemButtonView | null {- const first = item.children.first;- return first instanceof SnippetListItemButtonView ? first : null;+ private _rebuild(definitions: Collection<SnippetDefinition>, insert: (definition: SnippetDefinition) => void): void {+ this.rows.length = 0;+ this.items.clear();++ for (const definition of definitions) {+ const item = new ListItemView(this.locale);+ const button = new SnippetListItemButtonView(this.locale, definition);++ button.on("execute", () => insert(definition));++ item.children.add(button);+ this.items.add(item);+ this.rows.push({ item, button });+ }+ }}diff --git a/packages/ckeditor5/src/plugins/snippets/snippets.spec.ts b/packages/ckeditor5/src/plugins/snippets/snippets.spec.tsnew file mode 100644index 0000000000..48373276ca--- /dev/null+++ b/packages/ckeditor5/src/plugins/snippets/snippets.spec.ts@@ -0,0 +1,318 @@+import {+ type ClassicEditor,+ Collection,+ type DropdownView,+ Essentials,+ _getModelData as getModelData,+ type ListItemView,+ type ListView,+ type MenuBarMenuListView,+ type MenuBarMenuView,+ Paragraph,+ type SearchTextView,+ _setModelData as setModelData+} from "ckeditor5";+import { beforeEach, describe, expect, it, vi } from "vitest";++import "../../translation_overrides.js";+import { createTestEditor } from "../../../test/editor-kit.js";+import TriliumSnippets from "./snippets.js";+import type { SnippetDefinition } from "./snippetsconfig.js";+import SnippetListItemButtonView from "./snippetlistitembuttonview.js";+import SnippetListView from "./snippetlistview.js";+import SnippetsEditing from "./snippetsediting.js";+import SnippetsUI from "./snippetsui.js";++const DEF_FULL: SnippetDefinition = {+ title: "Greeting",+ data: "<p>Hello</p>",+ description: "A friendly hello",+ iconClass: "tn-icon bx bx-note",+ iconColorClass: "use-note-color color-abc123 with-hue"+};++const DEF_MINIMAL: SnippetDefinition = {+ title: "Signature",+ data: () => "<p>Bye</p>"+};++async function createEditor(definitions: SnippetDefinition[] = [DEF_FULL, DEF_MINIMAL]): Promise<ClassicEditor> {+ const editor = await createTestEditor(+ [Essentials, Paragraph, TriliumSnippets],+ { toolbar: [], snippets: { definitions } }+ );+ setModelData(editor.model, "<paragraph>[]</paragraph>");+ return editor;+}++describe("SnippetsEditing", () => {+ it("registers itself, the command, and seeds the collection from config", async () => {+ const editor = await createEditor();+ const editing = editor.plugins.get(SnippetsEditing);++ expect(SnippetsEditing.pluginName).toBe("SnippetsEditing");+ expect(editor.commands.get("insertTemplate")).toBeTruthy();+ expect([...editing.definitions].map((d) => d.title)).toEqual(["Greeting", "Signature"]);+ });++ it("starts with an empty collection when the snippets config is absent entirely", async () => {+ // No `snippets` key at all, so `config.get("snippets.definitions")` is undefined and the+ // `?? []` fallback kicks in (distinct from configuring an empty array).+ const editor = await createTestEditor([Essentials, Paragraph, TriliumSnippets], { toolbar: [] });+ expect(editor.plugins.get(SnippetsEditing).definitions.length).toBe(0);+ });++ it("replaces the whole collection on setDefinitions", async () => {+ const editor = await createEditor();+ const editing = editor.plugins.get(SnippetsEditing);++ editing.setDefinitions([DEF_MINIMAL]);+ expect([...editing.definitions].map((d) => d.title)).toEqual(["Signature"]);+ });+});++describe("insertTemplate command", () => {+ let editor: ClassicEditor;++ beforeEach(async () => {+ editor = await createEditor();+ });++ it("inserts a string payload as HTML at the selection", () => {+ editor.execute("insertTemplate", "<p>Hello</p>");+ expect(getModelData(editor.model, { withoutSelection: true })).toContain("<paragraph>Hello</paragraph>");+ });++ it("evaluates a callback payload and inserts its result", () => {+ editor.execute("insertTemplate", () => "<p>Bye</p>");+ expect(getModelData(editor.model, { withoutSelection: true })).toContain("<paragraph>Bye</paragraph>");+ });++ it("is a no-op when the payload does not resolve to a string", () => {+ const before = getModelData(editor.model, { withoutSelection: true });+ editor.execute("insertTemplate", (() => undefined) as never);+ expect(getModelData(editor.model, { withoutSelection: true })).toBe(before);+ });+});++describe("TriliumSnippets", () => {+ it("is the glue plugin over editing + UI, and pushes live updates", async () => {+ const editor = await createEditor();++ expect(TriliumSnippets.pluginName).toBe("TriliumSnippets");+ expect(editor.plugins.get(SnippetsEditing)).toBeInstanceOf(SnippetsEditing);+ expect(editor.plugins.get(SnippetsUI)).toBeInstanceOf(SnippetsUI);++ editor.plugins.get(TriliumSnippets).updateDefinitions([DEF_FULL]);+ expect([...editor.plugins.get(SnippetsEditing).definitions].map((d) => d.title)).toEqual(["Greeting"]);+ });+});++describe("SnippetsUI — insertTemplate dropdown", () => {+ let editor: ClassicEditor;+ let dropdown: DropdownView;+ let searchView: SearchTextView;++ beforeEach(async () => {+ editor = await createEditor();+ dropdown = editor.ui.componentFactory.create("insertTemplate") as DropdownView;+ dropdown.render();+ document.body.appendChild(dropdown.element as HTMLElement);+ dropdown.isOpen = true;+ searchView = dropdown.panelView.children.get(0) as SearchTextView;+ });++ it("labels the toggle and binds it to the command", () => {+ expect(dropdown.buttonView.label).toBe("Insert text snippet"); // relabelled by translation_overrides+ expect(dropdown.buttonView.icon).toContain("<svg");++ const command = editor.commands.get("insertTemplate");+ command?.forceDisabled("spec");+ expect(dropdown.isEnabled).toBe(false);+ command?.clearForceDisabled("spec");+ expect(dropdown.isEnabled).toBe(true);+ });++ it("announces the result count for a non-empty query, and stays quiet for an empty one", () => {+ const announce = vi.spyOn(editor.ui.ariaLiveAnnouncer, "announce");++ searchView.search("Greeting");+ expect(announce).toHaveBeenCalled();++ announce.mockClear();+ searchView.search("");+ expect(announce).not.toHaveBeenCalled();+ });++ it("shows the not-found message when a query matches nothing", () => {+ searchView.search("zzzznomatch");+ expect((searchView.element as HTMLElement).textContent).toContain("No templates were found matching");+ });++ it("inserts the snippet when a row is chosen", () => {+ const execute = vi.spyOn(editor, "execute");+ const list = searchView.filteredView as unknown as ListView;+ const row = (list.items.get(0) as ListItemView).children.get(0);+ row?.fire("execute");++ expect(execute).toHaveBeenCalledWith("insertTemplate", DEF_FULL.data);+ });++ it("resets the search when the dropdown closes", () => {+ const reset = vi.spyOn(searchView, "reset");+ dropdown.isOpen = false;+ expect(reset).toHaveBeenCalled();+ });+});++describe("SnippetsUI — menu-bar entry", () => {+ let editor: ClassicEditor;+ let menu: MenuBarMenuView;++ function menuButtons(): unknown[] {+ const list = menu.panelView.children.get(0) as MenuBarMenuListView;+ return [...list.items];+ }++ beforeEach(async () => {+ editor = await createEditor();+ menu = editor.ui.componentFactory.create("menuBar:insertTemplate") as MenuBarMenuView;+ });++ it("lists one entry per snippet and inserts on execute", () => {+ expect(menu.buttonView.label).toBe("Template");+ expect(menuButtons()).toHaveLength(2);++ const execute = vi.spyOn(editor, "execute");+ const firstItem = menuButtons()[0] as ListItemView;+ firstItem.children.get(0)?.fire("execute");+ expect(execute).toHaveBeenCalledWith("insertTemplate", DEF_FULL.data);+ });++ it("rebuilds live and shows an empty state when the snippet set becomes empty", () => {+ editor.plugins.get(SnippetsEditing).setDefinitions([]);++ const items = menuButtons();+ expect(items).toHaveLength(1);+ const emptyButton = (items[0] as ListItemView).children.get(0) as { label?: string; isEnabled?: boolean };+ expect(emptyButton.label).toBe("No templates available.");+ expect(emptyButton.isEnabled).toBe(false);+ });+});++describe("SnippetListView", () => {+ let editor: ClassicEditor;+ let collection: Collection<SnippetDefinition>;+ let insert: ReturnType<typeof vi.fn>;+ let list: SnippetListView;++ beforeEach(async () => {+ editor = await createEditor([]);+ collection = new Collection<SnippetDefinition>();+ collection.addMany([DEF_FULL, DEF_MINIMAL]);+ insert = vi.fn();+ list = new SnippetListView(editor.locale, collection, insert as unknown as (definition: SnippetDefinition) => void);+ list.render();+ document.body.appendChild(list.element as HTMLElement);+ });++ it("renders one row per definition and inserts the definition on row execute", () => {+ expect(list.items.length).toBe(2);++ (list.items.get(0) as ListItemView).children.get(0)?.fire("execute");+ expect(insert).toHaveBeenCalledWith(DEF_FULL);+ });++ // The real SearchTextView always hands `filter()` a global regexp; HighlightedTextView requires+ // one, so the tests mirror that.+ it("filters by query, hiding non-matches and counting the rest", () => {+ const result = list.filter(/greeting/gi);++ expect(result).toEqual({ resultsCount: 1, totalItemsCount: 2 });+ expect((list.items.get(0) as ListItemView).isVisible).toBe(true);+ expect((list.items.get(1) as ListItemView).isVisible).toBe(false);+ });++ it("shows every row again when the filter is cleared", () => {+ list.filter(/greeting/gi);+ const result = list.filter(null);++ expect(result).toEqual({ resultsCount: 2, totalItemsCount: 2 });+ expect((list.items.get(1) as ListItemView).isVisible).toBe(true);+ });++ it("focuses the first visible row, and does nothing when everything is filtered out", () => {+ list.filter(/signature/gi);+ const focusSecond = vi.spyOn((list.items.get(1) as ListItemView).children.get(0) as { focus: () => void }, "focus");+ list.focus();+ expect(focusSecond).toHaveBeenCalled();++ list.filter(/nothing-matches/gi);+ expect(() => list.focus()).not.toThrow();+ });++ it("rebuilds in place when the underlying collection changes", () => {+ collection.remove(DEF_MINIMAL);+ expect(list.items.length).toBe(1);+ });+});++describe("SnippetListItemButtonView", () => {+ let editor: ClassicEditor;++ beforeEach(async () => {+ editor = await createEditor([]);+ });++ function render(definition: SnippetDefinition): SnippetListItemButtonView {+ const button = new SnippetListItemButtonView(editor.locale, definition);+ button.render();+ document.body.appendChild(button.element as HTMLElement);+ return button;+ }++ it("renders the note icon (with its classes), title and description", () => {+ const button = render(DEF_FULL);+ const el = button.element as HTMLElement;++ const icon = el.querySelector(".ck-template-icon");+ expect(icon?.classList.contains("bx-note")).toBe(true);+ expect(icon?.classList.contains("use-note-color")).toBe(true);+ expect(el.querySelector(".ck-button__label")?.textContent).toBe("Greeting");+ expect(el.querySelector(".ck-template-form__description")?.textContent).toBe("A friendly hello");+ });++ it("omits the description element and colour classes for a minimal snippet", () => {+ const button = render(DEF_MINIMAL);+ const el = button.element as HTMLElement;++ expect(el.querySelector(".ck-template-form__description")).toBeNull();+ expect(el.querySelector(".ck-template-icon")?.classList.contains("use-note-color")).toBe(false);+ });++ it("matches on title, on description, and reports no match otherwise", () => {+ const button = new SnippetListItemButtonView(editor.locale, DEF_FULL);++ expect(button.isMatching(/greet/gi)).toEqual({ title: true, description: false });+ expect(button.isMatching(/friendly/gi)).toEqual({ title: false, description: true });+ expect(button.isMatching(/zzz/gi)).toBeNull();+ });++ it("treats a description-less snippet as title-only for matching", () => {+ const button = new SnippetListItemButtonView(editor.locale, DEF_MINIMAL);+ expect(button.isMatching(/signature/gi)).toEqual({ title: true, description: false });+ });++ it("highlights safely before render and delegates once rendered, with or without a description", () => {+ // Before render the text views don't exist yet, so it must no-op rather than throw.+ const before = new SnippetListItemButtonView(editor.locale, DEF_FULL);+ expect(() => before.highlightText(/greet/gi)).not.toThrow();++ expect(() => render(DEF_FULL).highlightText(/greet/gi)).not.toThrow();+ expect(() => render(DEF_MINIMAL).highlightText(/sign/gi)).not.toThrow();+ });++ it("destroys cleanly", () => {+ expect(() => render(DEF_FULL).destroy()).not.toThrow();+ });+});diff --git a/packages/ckeditor5/src/plugins/snippets/snippetsui.ts b/packages/ckeditor5/src/plugins/snippets/snippetsui.tsindex 04611dd733..7f54aaf265 100644--- a/packages/ckeditor5/src/plugins/snippets/snippetsui.ts+++ b/packages/ckeditor5/src/plugins/snippets/snippetsui.ts@@ -1,4 +1,4 @@-import { createDropdown, type Locale, MenuBarMenuListItemButtonView, MenuBarMenuListItemView, MenuBarMenuListView, MenuBarMenuView, Plugin, SearchTextView } from "ckeditor5";+import { type Command, createDropdown, type Locale, MenuBarMenuListItemButtonView, MenuBarMenuListItemView, MenuBarMenuListView, MenuBarMenuView, Plugin, SearchTextView } from "ckeditor5";import SnippetsEditing from "./snippetsediting.js";import SnippetListView from "./snippetlistview.js";@@ -35,7 +35,9 @@ export default class SnippetsUI extends Plugin {};editor.ui.componentFactory.add("insertTemplate", (locale) => {- const command = editor.commands.get("insertTemplate");+ // Cast (rather than guard) since `SnippetsUI` requires `SnippetsEditing`, which registers+ // the command in its `init()`; it is always present by the time the UI is built.+ const command = editor.commands.get("insertTemplate") as Command;const dropdownView = createDropdown(locale);const listView = new SnippetListView(locale, editing.definitions, (definition) => insert(definition.data));@@ -60,14 +62,12 @@ export default class SnippetsUI extends Plugin {});searchView.on("search", (evt, data: { query: string; resultsCount: number }) => {- if (data.query?.length) {+ if (data.query.length) {editor.ui.ariaLiveAnnouncer.announce(t("%0 templates found", data.resultsCount));}});- if (command) {- dropdownView.bind("isEnabled").to(command);- }+ dropdownView.bind("isEnabled").to(command);dropdownView.panelView.children.add(searchView);dropdownView.buttonView.set({label: t("Insert template"),@@ -86,7 +86,7 @@ export default class SnippetsUI extends Plugin {});editor.ui.componentFactory.add("menuBar:insertTemplate", (locale) => {- const command = editor.commands.get("insertTemplate");+ const command = editor.commands.get("insertTemplate") as Command;const menuView = new MenuBarMenuView(locale);menuView.buttonView.set({label: t("Template"),@@ -102,9 +102,7 @@ export default class SnippetsUI extends Plugin {});menuView.panelView.children.add(listView);- if (command) {- menuView.bind("isEnabled").to(command, "isEnabled");- }+ menuView.bind("isEnabled").to(command, "isEnabled");return menuView;});