Skip to content

Build your personal knowledge base with Trilium Notes

client: fix some issues

Adorian Doranc5bdb961db7f
diff --git a/apps/client/src/menus/link_context_menu.ts b/apps/client/src/menus/link_context_menu.ts
index 986706e609..be71a326e4 100644
--- a/apps/client/src/menus/link_context_menu.ts
+++ b/apps/client/src/menus/link_context_menu.ts
@@ -366,7 +366,7 @@ async function isInReadOnlyNote(element: Element | null) {
/** The text editor containing `element`, or `null` when there is none or it is read-only. */
async function getEditingTextEditor(element: Element | null) {
- // Checked first: a note shown read-only has no editor, and asking for one waits for a timeout.
+ // An editor in read-only mode renders its editable with `contenteditable="false"`.
if (!element?.closest(".ck-editor__editable[contenteditable='true']")) {
return null;
}
diff --git a/apps/client/src/menus/note_context_menu.spec.ts b/apps/client/src/menus/note_context_menu.spec.ts
index 7ae7a8d59d..53a2e7fd62 100644
--- a/apps/client/src/menus/note_context_menu.spec.ts
+++ b/apps/client/src/menus/note_context_menu.spec.ts
@@ -2,19 +2,10 @@ import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
// All mutable mock state lives in a hoisted holder so the (hoisted) vi.mock
// factory below can reference it.
-const h = vi.hoisted(() => {
- const tabManager = {
- activeNote: null as { type: string } | null,
- activeContext: null as { getTextEditor: () => Promise<unknown> } | null,
- getActiveContext: () => tabManager.activeContext
- && { note: tabManager.activeNote, ...tabManager.activeContext },
- getNoteContexts: () => []
- };
- return { tabManager, triggerCommand: vi.fn() };
-});
+const h = vi.hoisted(() => ({ triggerCommand: vi.fn() }));
vi.mock("../components/app_context.js", () => ({
- default: { tabManager: h.tabManager, triggerCommand: h.triggerCommand }
+ default: { triggerCommand: h.triggerCommand }
}));
// The module under test pulls in several DOM/jQuery-heavy collaborators at import
@@ -39,6 +30,7 @@ vi.mock("./table_context_menu.js", () => ({
import { buildBlockReferenceMenuItems } from "../services/block_reference.js";
import { copyHtml, copyTextWithToast } from "../services/clipboard_ext.js";
import server from "../services/server.js";
+import { setEditorNoteId } from "../widgets/react/NoteStore.js";
import contextMenu, { type MenuCommandItem, type MenuItem } from "./context_menu.js";
import {
buildTableContextMenuSections,
@@ -53,12 +45,13 @@ import {
setupContextMenu
} from "./note_context_menu.js";
-const { tabManager } = h;
-
-/** Builds an editor whose editable DOM root is `domRoot` and selection HTML is `selectedHtml`. */
-function fakeEditor(domRoot: Node | null, selectedHtml: string, plainText = "") {
+/**
+ * Builds an editor whose editable DOM root is `domRoot` and selection HTML is `selectedHtml`. It
+ * holds the content of a note unless `holdsNote` is `false`, as the attribute editor does not.
+ */
+function fakeEditor(domRoot: HTMLElement, selectedHtml: string, plainText = "", holdsNote = true) {
const pasteTarget = { paste: vi.fn(), release: vi.fn() };
- return {
+ const editor = {
editing: { view: { getDomRoot: () => domRoot } },
getSelectedHtml: vi.fn(() => selectedHtml),
getSelectedPlainText: vi.fn(() => plainText),
@@ -69,6 +62,12 @@ function fakeEditor(domRoot: Node | null, selectedHtml: string, plainText = "")
isReadOnly: false,
execute: vi.fn()
};
+ domRoot.classList.add("ck-editor__editable");
+ Object.assign(domRoot, { ckeditorInstance: editor });
+ if (holdsNote) {
+ setEditorNoteId(editor, "note1");
+ }
+ return editor;
}
/**
@@ -151,8 +150,6 @@ function submenu(items: MenuItem<any>[], title: string): MenuItem<any>[] {
describe("buildNoteContextMenuItems", () => {
beforeEach(() => {
vi.clearAllMocks();
- tabManager.activeNote = null;
- tabManager.activeContext = null;
});
it("offers copy, copy-as-markdown and the search rows for a plain selection", async () => {
@@ -432,8 +429,6 @@ describe("setupContextMenu (browser)", () => {
beforeEach(() => {
vi.clearAllMocks();
- tabManager.activeNote = null;
- tabManager.activeContext = null;
});
/** Right-clicks `element`, holding Shift or letting another widget claim the event first. */
@@ -621,7 +616,6 @@ describe("setupContextMenu (browser)", () => {
const execCommand = stubExecCommand();
const content = codeEditable();
- tabManager.activeNote = { type: "code" }; // so no CKEditor answers for the selection
setSelection(content, "<span>code</span>", "code");
const codeRows = await menuFor(content);
@@ -635,8 +629,6 @@ describe("setupContextMenu (browser)", () => {
const anchor = document.createElement("span");
editorRoot.appendChild(anchor);
const editor = fakeEditor(editorRoot, "<p>clean</p>");
- tabManager.activeNote = { type: "text" };
- tabManager.activeContext = { getTextEditor: async () => editor };
setSelection(anchor, "<p>clean</p>", "clean");
await run(await menuFor(editorRoot), "electron_context_menu.cut");
@@ -650,8 +642,6 @@ describe("setupContextMenu (browser)", () => {
const anchor = document.createElement("span");
editorRoot.appendChild(anchor);
const editor = fakeEditor(editorRoot, "<table><tr><td>a1</td></tr></table>", "a1");
- tabManager.activeNote = { type: "text" };
- tabManager.activeContext = { getTextEditor: async () => editor };
setSelection(anchor, "", "Selected 1 cell");
await run(await menuFor(editorRoot), "electron_context_menu.copy");
@@ -678,8 +668,6 @@ describe("setupContextMenu (browser)", () => {
const anchor = document.createElement("span");
editorRoot.appendChild(anchor);
const editor = fakeEditor(editorRoot, "<p>clean</p>");
- tabManager.activeNote = { type: "text" };
- tabManager.activeContext = { getTextEditor: async () => editor };
setSelection(anchor, "<p>clean</p>", "clean");
const rows = await menuFor(editorRoot);
@@ -717,8 +705,6 @@ describe("setupContextMenu (browser)", () => {
const anchor = document.createElement("span");
editorRoot.appendChild(anchor);
const editor = fakeEditor(editorRoot, "<p>clean</p>");
- tabManager.activeNote = { type: "text" };
- tabManager.activeContext = { getTextEditor: async () => editor };
setSelection(anchor, "<p>clean</p>", "clean");
await run(await menuFor(editorRoot), "electron_context_menu.paste");
@@ -747,7 +733,6 @@ describe("setupContextMenu (browser)", () => {
try {
const content = codeEditable();
- tabManager.activeNote = { type: "code" };
setSelection(content, "<span>code</span>", "code");
await run(await menuFor(content), "electron_context_menu.paste");
@@ -765,7 +750,6 @@ describe("setupContextMenu (browser)", () => {
try {
const content = codeEditable();
- tabManager.activeNote = { type: "code" };
setSelection(content, "<span>code</span>", "code");
const shown = titles(await menuFor(content));
@@ -779,7 +763,6 @@ describe("setupContextMenu (browser)", () => {
it("drops the cut row in a read-only code note", async () => {
const content = codeEditable(true);
- tabManager.activeNote = { type: "code" };
setSelection(content, "<span>code</span>", "code");
const rows = await menuFor(content);
@@ -815,8 +798,6 @@ describe("setupContextMenu (browser)", () => {
describe("getSelectedHtmlForMarkdown", () => {
beforeEach(() => {
vi.restoreAllMocks();
- tabManager.activeNote = null;
- tabManager.activeContext = null;
});
it("uses the editor's data-pipeline HTML when the selection is inside the editor", async () => {
@@ -825,8 +806,6 @@ describe("getSelectedHtmlForMarkdown", () => {
editorRoot.appendChild(anchor);
const editor = fakeEditor(editorRoot, "<p>clean</p>");
- tabManager.activeNote = { type: "text" };
- tabManager.activeContext = { getTextEditor: async () => editor };
setSelection(anchor, "<b>dom clone</b>");
expect(await getSelectedHtmlForMarkdown()).toBe("<p>clean</p>");
@@ -838,8 +817,6 @@ describe("getSelectedHtmlForMarkdown", () => {
const outsideAnchor = document.createElement("span"); // not appended to editorRoot
const editor = fakeEditor(editorRoot, "<p>clean</p>");
- tabManager.activeNote = { type: "text" };
- tabManager.activeContext = { getTextEditor: async () => editor };
setSelection(outsideAnchor, "<b>dom clone</b>");
expect(await getSelectedHtmlForMarkdown()).toBe("<b>dom clone</b>");
@@ -852,38 +829,22 @@ describe("getSelectedHtmlForMarkdown", () => {
editorRoot.appendChild(anchor);
const editor = fakeEditor(editorRoot, ""); // empty model selection
- tabManager.activeNote = { type: "text" };
- tabManager.activeContext = { getTextEditor: async () => editor };
setSelection(anchor, "<b>dom clone</b>");
expect(await getSelectedHtmlForMarkdown()).toBe("<b>dom clone</b>");
});
- it("skips the editor path entirely for a non-text note", async () => {
- const editor = fakeEditor(document.createElement("div"), "<p>clean</p>");
- tabManager.activeNote = { type: "code" };
- tabManager.activeContext = { getTextEditor: async () => editor };
- setSelection(document.createElement("span"), "<b>dom clone</b>");
+ it("skips an editor that holds no note, such as the attribute editor", async () => {
+ const editorRoot = document.createElement("div");
+ const anchor = editorRoot.appendChild(document.createElement("span"));
+ const editor = fakeEditor(editorRoot, "<p>clean</p>", "", false);
+ setSelection(anchor, "<b>dom clone</b>");
expect(await getSelectedHtmlForMarkdown()).toBe("<b>dom clone</b>");
expect(editor.getSelectedHtml).not.toHaveBeenCalled();
});
- it("falls back when resolving the text editor throws or times out", async () => {
- vi.spyOn(console, "error").mockImplementation(() => {}); // the catch logs the timeout
- tabManager.activeNote = { type: "text" };
- tabManager.activeContext = {
- getTextEditor: async () => {
- throw new Error("timed out");
- }
- };
- setSelection(document.createElement("span"), "<b>dom clone</b>");
-
- expect(await getSelectedHtmlForMarkdown()).toBe("<b>dom clone</b>");
- });
-
it("returns an empty string when there is no selection at all", async () => {
- tabManager.activeNote = { type: "text" };
setSelection(null);
expect(await getSelectedHtmlForMarkdown()).toBe("");
diff --git a/apps/client/src/menus/text_editor_context_menu.spec.ts b/apps/client/src/menus/text_editor_context_menu.spec.ts
index ed826f298e..6fd01841a9 100644
--- a/apps/client/src/menus/text_editor_context_menu.spec.ts
+++ b/apps/client/src/menus/text_editor_context_menu.spec.ts
@@ -1,31 +1,12 @@
import type { AiQuickAction, AiQuickActionFooter, AiQuickActionGroup } from "@triliumnext/ckeditor5";
import { beforeEach, describe, expect, it, vi } from "vitest";
-const h = vi.hoisted(() => {
- interface FakeContext {
- ntxId?: string;
- note?: { type: string } | null;
- getTextEditor: () => Promise<unknown>;
- }
- const tabManager = {
- activeNote: null as { type: string } | null,
- activeContext: null as FakeContext | null,
- contexts: [] as FakeContext[],
- getActiveContext: () => tabManager.activeContext
- && { note: tabManager.activeNote, ...tabManager.activeContext },
- getNoteContexts: () => tabManager.contexts
- };
- return { tabManager };
-});
-
-vi.mock("../components/app_context.js", () => ({ default: { tabManager: h.tabManager } }));
vi.mock("../services/i18n.js", () => ({ t: (key: string) => key }));
+import { setEditorNoteId } from "../widgets/react/NoteStore.js";
import type { MenuCommandItem, MenuItem } from "./context_menu.js";
import { buildAiActionsMenuItem, getTextEditorAtSelection } from "./text_editor_context_menu.js";
-const { tabManager } = h;
-
const GROUPS: AiQuickActionGroup[] = [
{
id: "edit",
@@ -63,7 +44,7 @@ function fakeEditor({
isEnabled = true,
hasPlugin = true
}: {
- domRoot: Node | null;
+ domRoot: HTMLElement;
groups?: AiQuickActionGroup[];
menuFooter?: AiQuickActionFooter[];
hasContext?: boolean;
@@ -79,11 +60,28 @@ function fakeEditor({
commands: { get: () => ({ isEnabled }) },
execute: vi.fn()
};
- tabManager.activeNote = { type: "text" };
- tabManager.activeContext = { getTextEditor: () => Promise.resolve(editor) };
+ makeNoteEditorRoot(domRoot, editor, "note1");
return { editor, ui };
}
+/**
+ * An editable root of `editor`, as CKEditor renders it, in a text editor that holds the content
+ * of `noteId`.
+ */
+function noteEditorRoot(editor: object, noteId?: string) {
+ return makeNoteEditorRoot(document.createElement("div"), editor, noteId);
+}
+
+/** Turns `element` into an editable root of `editor`, which holds the content of `noteId`. */
+function makeNoteEditorRoot(element: HTMLElement, editor: object, noteId?: string) {
+ element.classList.add("ck-editor__editable");
+ Object.assign(element, { ckeditorInstance: editor });
+ if (noteId) {
+ setEditorNoteId(editor, noteId);
+ }
+ return element;
+}
+
/** Points `window.getSelection()` at `anchorNode`. */
function setSelection(anchorNode: Node | null) {
vi.spyOn(window, "getSelection").mockReturnValue({ anchorNode } as unknown as Selection);
@@ -100,34 +98,31 @@ function commandItems(items: MenuItem<string>[]) {
describe("getTextEditorAtSelection", () => {
beforeEach(() => {
vi.restoreAllMocks();
- tabManager.activeNote = null;
- tabManager.activeContext = null;
- tabManager.contexts = [];
});
- it("returns the editor only when the selection is inside its DOM root", async () => {
- const root = document.createElement("div");
- const inside = document.createTextNode("hello");
- root.appendChild(inside);
+ it("finds the editor of the note holding the selection, wherever it is", async () => {
+ for (const holder of [ "note-split", "modal popup-editor-dialog" ]) {
+ const container = document.createElement("div");
+ container.className = holder;
+ const editor = {};
+ const root = container.appendChild(noteEditorRoot(editor, "note1"));
+ const inside = root.appendChild(document.createTextNode("hello"));
- const { editor } = fakeEditor({ domRoot: root });
- setSelection(inside);
- expect(await getTextEditorAtSelection()).toBe(editor);
+ setSelection(inside);
+ expect(await getTextEditorAtSelection(), holder).toBe(editor);
+ }
- // Same editor, but the click landed in a dialog rather than in the note.
setSelection(document.createTextNode("elsewhere"));
expect(await getTextEditorAtSelection()).toBeNull();
+ setSelection(null);
+ expect(await getTextEditorAtSelection()).toBeNull();
});
it("returns the editor of an included note that is edited inside the note", async () => {
- const root = document.createElement("div");
- root.className = "ck-editor__editable";
- const { editor } = fakeEditor({ domRoot: root });
- const nestedEditor = { editing: { view: {} } };
- const nestedRoot = Object.assign(document.createElement("div"), {
- className: "ck-editor__editable",
- ckeditorInstance: nestedEditor
- });
+ const editor = {};
+ const root = noteEditorRoot(editor, "note1");
+ const nestedEditor = {};
+ const nestedRoot = noteEditorRoot(nestedEditor, "note2");
const caption = document.createElement("div");
caption.className = "ck-editor__editable ck-editor__nested-editable";
root.append(nestedRoot, caption);
@@ -143,43 +138,10 @@ describe("getTextEditorAtSelection", () => {
expect(await getTextEditorAtSelection()).toBe(editor);
});
- it("returns null for a non-text note, and swallows a failing editor lookup", async () => {
- setSelection(document.createTextNode("hello"));
-
- tabManager.activeNote = { type: "code" };
- tabManager.activeContext = { getTextEditor: () => Promise.reject(new Error("timed out")) };
- expect(await getTextEditorAtSelection()).toBeNull();
-
- tabManager.activeNote = { type: "text" };
- vi.spyOn(console, "error").mockImplementation(() => {});
- expect(await getTextEditorAtSelection()).toBeNull();
- });
-
- it("looks the editor up in the split pane holding the node, active or not", async () => {
- const pane = document.createElement("div");
- pane.dataset.ntxId = "ntx-right";
- const root = document.createElement("div");
- const inside = document.createTextNode("cell");
- root.appendChild(inside);
- pane.appendChild(root);
-
- const editor = { editing: { view: { getDomRoot: () => root } } };
- tabManager.activeNote = { type: "code" };
- tabManager.activeContext = { ntxId: "ntx-left", getTextEditor: () => Promise.reject() };
- tabManager.contexts = [
- { ntxId: "ntx-left", note: { type: "code" }, getTextEditor: () => Promise.reject() },
- { ntxId: "ntx-right", note: { type: "text" }, getTextEditor: async () => editor }
- ];
-
- setSelection(inside);
- expect(await getTextEditorAtSelection()).toBe(editor);
+ it("leaves out an editor that holds no note, such as the attribute editor", async () => {
+ const root = noteEditorRoot({});
+ setSelection(root.appendChild(document.createTextNode("#label")));
- // A pane whose note context is gone, or holds another note type.
- tabManager.contexts = [];
- expect(await getTextEditorAtSelection()).toBeNull();
- tabManager.contexts = [
- { ntxId: "ntx-right", note: { type: "code" }, getTextEditor: async () => editor }
- ];
expect(await getTextEditorAtSelection()).toBeNull();
});
});
diff --git a/apps/client/src/menus/text_editor_context_menu.ts b/apps/client/src/menus/text_editor_context_menu.ts
index cf08e86b26..d82e647d22 100644
--- a/apps/client/src/menus/text_editor_context_menu.ts
+++ b/apps/client/src/menus/text_editor_context_menu.ts
@@ -1,9 +1,8 @@
import type { AiQuickAction, AiQuickActionFooter, AiQuickActionGroup, CKTextEditor } from "@triliumnext/ckeditor5";
import type { CommandNames } from "../components/app_context.js";
-import appContext from "../components/app_context.js";
-import type NoteContext from "../components/note_context.js";
import { t } from "../services/i18n.js";
+import { getEditorNoteId } from "../widgets/react/NoteStore.js";
import type { MenuItem } from "./context_menu.js";
/**
@@ -144,58 +143,23 @@ export async function getTextEditorAtSelection(): Promise<CKTextEditor | null> {
}
/**
- * Returns the text editor whose editable contains `node`, or `null` when no text editor does.
- * Takes the right-click target instead of the DOM selection, because a right-click does not move
- * the selection in every browser.
+ * Returns the text editor of a note whose editable contains `node`, or `null` when no such editor
+ * does. Takes the right-click target instead of the DOM selection, because a right-click does not
+ * move the selection in every browser.
*
- * Looks up the editor in the split pane that contains `node`, because a right-click does not
- * activate that pane. Inside an included note edited in place, the editor of that note answers.
+ * Reads the editor off the innermost editable root around `node`, so it finds the editor of a split
+ * pane the right-click did not activate, of a dialog such as the quick edit, and of an included
+ * note edited in place. An editor that holds no note, such as the attribute editor, does not count.
*/
export async function getTextEditorContaining(
node: Node | null | undefined
): Promise<CKTextEditor | null> {
- const noteContext = node ? getNoteContextContaining(node) : null;
- if (!node || noteContext?.note?.type !== "text") {
- return null;
- }
-
- try {
- const editor = await noteContext.getTextEditor();
- const domRoot = editor?.editing.view.getDomRoot();
-
- if (editor && domRoot && domRoot.contains(node)) {
- return getNestedEditor(node, domRoot) ?? editor;
- }
- } catch (error) {
- // Editor not ready or the request timed out.
- console.error("Failed to read the text editor at the selection:", error);
- }
-
- return null;
+ const element = node instanceof Element ? node : node?.parentElement;
+ const editor = element?.closest<EditorRootElement>(EDITOR_ROOT_SELECTOR)?.ckeditorInstance;
+ return editor && getEditorNoteId(editor) ? editor : null;
}
-/** The editor of an included note edited inside the editable `domRoot`, which contains `node`. */
-function getNestedEditor(node: Node, domRoot: HTMLElement) {
- const element = node instanceof Element ? node : node.parentElement;
- const editable = element?.closest<HTMLElement & { ckeditorInstance?: CKTextEditor }>(
- ".ck-editor__editable:not(.ck-editor__nested-editable)"
- );
- return editable && editable !== domRoot && domRoot.contains(editable)
- ? editable.ckeditorInstance ?? null
- : null;
-}
+/** The editable root of a text editor, which CKEditor gives a reference to the editor. */
+type EditorRootElement = HTMLElement & { ckeditorInstance?: CKTextEditor | null };
-/**
- * Returns the note context whose `ntxId` matches the `data-ntx-id` of the split pane that contains
- * `node`, or the active note context when `node` is outside every pane, e.g. in a dialog.
- */
-function getNoteContextContaining(node: Node): NoteContext | null {
- const { tabManager } = appContext;
- const element = node instanceof Element ? node : node.parentElement;
- const ntxId = element?.closest<HTMLElement>("[data-ntx-id]")?.dataset.ntxId;
- if (!ntxId) {
- return tabManager.getActiveContext();
- }
-
- return tabManager.getNoteContexts().find((noteContext) => noteContext.ntxId === ntxId) ?? null;
-}
+const EDITOR_ROOT_SELECTOR = ".ck-editor__editable:not(.ck-editor__nested-editable)";