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
feat(client): show the note context menu in the browser build
Elian Doran5b598e7b5ad9
diff --git a/apps/client/src/desktop.ts b/apps/client/src/desktop.tsindex 5d6e9c6852..082be7539b 100644--- a/apps/client/src/desktop.ts+++ b/apps/client/src/desktop.ts@@ -4,6 +4,7 @@ import type { ElectronWindowApi } from "@triliumnext/commons";import appContext, { type CommandNames } from "./components/app_context.js";import electronContextMenu from "./menus/electron_context_menu.js";+import { setupContextMenu as setupBrowserContextMenu } from "./menus/note_context_menu.js";import bundleService from "./services/bundle.js";import { setupClipboardImageEmbed } from "./services/clipboard_image_embed.js";import glob from "./services/glob.js";@@ -59,6 +60,8 @@ setupClipboardImageEmbed();if (utils.isElectron()) {electronContextMenu.setupContextMenu();+} else {+ setupBrowserContextMenu();}function initOnElectron() {diff --git a/apps/client/src/menus/electron_context_menu.spec.ts b/apps/client/src/menus/electron_context_menu.spec.tsdeleted file mode 100644index f2d522af41..0000000000--- a/apps/client/src/menus/electron_context_menu.spec.ts+++ /dev/null@@ -1,132 +0,0 @@-import { 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,- getActiveContextNote: () => tabManager.activeNote,- getActiveContext: () => tabManager.activeContext- };- return { tabManager };-});--vi.mock("../components/app_context.js", () => ({- default: { tabManager: h.tabManager }-}));--// The module under test pulls in several DOM/jQuery-heavy collaborators at import-// time; stub them so importing stays cheap and side-effect free.-vi.mock("../components/zoom.js", () => ({ default: {} }));-vi.mock("../services/clipboard_ext.js", () => ({ copyTextWithToast: vi.fn() }));-vi.mock("../services/i18n.js", () => ({ t: (key: string) => key }));-vi.mock("../services/options.js", () => ({ default: { get: () => "" } }));-vi.mock("../services/server.js", () => ({ default: { post: vi.fn() } }));-vi.mock("../services/utils.js", () => ({ default: { escapeHtml: (s: string) => s } }));-vi.mock("./context_menu.js", () => ({ default: { show: vi.fn() } }));--import { getSelectedHtmlForMarkdown } from "./electron_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) {- return {- editing: { view: { getDomRoot: () => domRoot } },- getSelectedHtml: vi.fn(() => selectedHtml)- };-}--/** Points window.getSelection() at `anchorNode`, cloning `fallbackHtml` for the DOM-range path. */-function setSelection(anchorNode: Node | null, fallbackHtml = "") {- const fragment = document.createDocumentFragment();- if (fallbackHtml) {- const holder = document.createElement("div");- holder.innerHTML = fallbackHtml;- while (holder.firstChild) fragment.appendChild(holder.firstChild);- }- vi.spyOn(window, "getSelection").mockReturnValue({- anchorNode,- rangeCount: anchorNode || fallbackHtml ? 1 : 0,- getRangeAt: () => ({ cloneContents: () => fragment.cloneNode(true) })- } as unknown as Selection);-}--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 () => {- const editorRoot = document.createElement("div");- 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, "<b>dom clone</b>");-- expect(await getSelectedHtmlForMarkdown()).toBe("<p>clean</p>");- expect(editor.getSelectedHtml).toHaveBeenCalled();- });-- it("falls back to the DOM clone when the selection is outside the editor", async () => {- const editorRoot = document.createElement("div");- 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>");- expect(editor.getSelectedHtml).not.toHaveBeenCalled();- });-- it("falls back to the DOM clone when the editor selection is empty", async () => {- const editorRoot = document.createElement("div");- const anchor = document.createElement("span");- 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>");-- 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/electron_context_menu.ts b/apps/client/src/menus/electron_context_menu.tsindex f47c339d01..4cb9626b6a 100644--- a/apps/client/src/menus/electron_context_menu.ts+++ b/apps/client/src/menus/electron_context_menu.ts@@ -1,167 +1,28 @@-import type { CommandNames } from "../components/app_context.js";-import appContext from "../components/app_context.js";+import type { ElectronApi, ElectronContextMenuParams } from "@triliumnext/commons";+import zoomService from "../components/zoom.js";-import * as clipboardExt from "../services/clipboard_ext.js";-import { t } from "../services/i18n.js";-import options from "../services/options.js";-import server from "../services/server.js";-import utils from "../services/utils.js";-import contextMenu, { type MenuItem } from "./context_menu.js";-import { buildAiActionsMenuItem, getTextEditorAtSelection } from "./text_editor_context_menu.js";+import contextMenu from "./context_menu.js";+import { buildNoteContextMenuItems, type ContextMenuHost } from "./note_context_menu.js";+/**+ * Replaces the browser's menu with Trilium's throughout the Electron window.+ *+ * Unlike the browser build, this claims every right-click: Chromium hands the embedding+ * application its spell-check state and its clipboard, so nothing is lost by taking the menu over.+ */function setupContextMenu() {const eApi = window.electronApi;if (!eApi) return;const api = eApi.contextMenu;- const isMac = window.glob.platform === "darwin";- const platformModifier = isMac ? "Meta" : "Ctrl";api.onContextMenu(async (params) => {- const { editFlags } = params;- const hasText = params.selectionText.trim().length > 0;-- const items: MenuItem<CommandNames>[] = [];-- // Resolved before the menu is built rather than lazily in a handler: the rows it produces- // depend on how the editor answers, and `isEditable` keeps the lookup off every click that- // lands somewhere a completion could not be committed anyway (a read-only note, the tree).- const aiActions = params.isEditable ? await buildAiActionsMenuItem() : null;-- if (params.misspelledWord) {- for (const suggestion of params.dictionarySuggestions) {- items.push({- title: suggestion,- command: "replaceMisspelling",- spellingSuggestion: suggestion,- uiIcon: "bx bx-empty"- });- }-- items.push({- title: t("electron_context_menu.add-term-to-dictionary", { term: params.misspelledWord }),- uiIcon: "bx bx-plus",- handler: () => eApi.spellcheck.addWordToDictionary(params.misspelledWord)- });-- items.push({ kind: "separator" });- }-- if (aiActions) {- items.push(aiActions, { kind: "separator" });- }-- if (params.isEditable) {- items.push({- enabled: editFlags.canCut && hasText,- title: t("electron_context_menu.cut"),- shortcut: `${platformModifier}+X`,- uiIcon: "bx bx-cut",- handler: () => api.webContentsAction("cut")- });- }-- if (params.isEditable || hasText) {- items.push({- enabled: editFlags.canCopy && hasText,- title: t("electron_context_menu.copy"),- shortcut: `${platformModifier}+C`,- uiIcon: "bx bx-copy",- handler: () => api.webContentsAction("copy")- });-- items.push({- enabled: hasText,- title: t("electron_context_menu.copy-as-markdown"),- uiIcon: "bx bx-copy-alt",- handler: async () => {- const htmlContent = await getSelectedHtmlForMarkdown();- if (!htmlContent) return;-- try {- const { markdownContent } = await server.post<{ markdownContent: string }>(- "other/to-markdown",- { htmlContent }- );- await clipboardExt.copyTextWithToast(markdownContent);- } catch (error) {- console.error("Failed to copy as markdown:", error);- }- }- });- }-- if (!["", "javascript:", "about:blank#blocked"].includes(params.linkURL) && params.mediaType === "none") {- items.push({- title: t("electron_context_menu.copy-link"),- uiIcon: "bx bx-copy",- handler: async () => {- const linkText = params.linkText || params.linkURL;- const html = `<a href="${utils.escapeHtml(params.linkURL)}">${utils.escapeHtml(linkText)}</a>`;- await navigator.clipboard.write([- new ClipboardItem({- "text/html": new Blob([html], { type: "text/html" }),- "text/plain": new Blob([params.linkURL], { type: "text/plain" })- })- ]);- }- });- }-- if (params.isEditable) {- items.push({- enabled: editFlags.canPaste,- title: t("electron_context_menu.paste"),- shortcut: `${platformModifier}+V`,- uiIcon: "bx bx-paste",- handler: () => api.webContentsAction("paste")- });- }-- if (params.isEditable) {- items.push({- enabled: editFlags.canPaste,- title: t("electron_context_menu.paste-as-plain-text"),- shortcut: `${platformModifier}+Shift+V`,- uiIcon: "bx bx-paste",- handler: () => api.webContentsAction("pasteAndMatchStyle")- });- }-- if (hasText) {- const shortenedSelection = params.selectionText.length > 15 ? `${params.selectionText.substr(0, 13)}…` : params.selectionText;-- const customSearchEngineName = options.get("customSearchEngineName");- const customSearchEngineUrl = options.get("customSearchEngineUrl") as string;- let searchEngineName;- let searchEngineUrl;- if (customSearchEngineName && customSearchEngineUrl) {- searchEngineName = customSearchEngineName;- searchEngineUrl = customSearchEngineUrl;- } else {- searchEngineName = "DuckDuckGo";- searchEngineUrl = "https://duckduckgo.com/?q={keyword}";- }-- const searchUrl = searchEngineUrl.replace("{keyword}", encodeURIComponent(params.selectionText));-- items.push({ kind: "separator" });-- items.push({- title: t("electron_context_menu.search_online", { term: shortenedSelection, searchEngine: searchEngineName }),- uiIcon: "bx bx-search-alt",- handler: () => eApi.shell.openExternal(searchUrl)- });-- items.push({- title: t("electron_context_menu.search_in_trilium", { term: shortenedSelection }),- uiIcon: "bx bx-search",- handler: async () => {- await appContext.triggerCommand("searchNotes", {- searchString: params.selectionText- });- }- });- }+ const items = await buildNoteContextMenuItems({+ linkURL: params.linkURL,+ linkText: params.linkText,+ isMedia: params.mediaType !== "none",+ isEditable: params.isEditable,+ selectionText: params.selectionText+ }, electronHost(eApi, params));if (items.length === 0) {return;@@ -182,27 +43,28 @@ function setupContextMenu() {});}-/**- * Returns the HTML to feed to the Markdown converter for the "Copy as Markdown" action.- *- * When the selection lives inside the active text note's CKEditor, we take the editor's- * data-pipeline HTML (`getSelectedHtml()`) — clean stored markup without the editing-view- * artifacts (`data-list-item-id`, collapsible handle/arrow spans, bogus-paragraph wrappers)- * that cloning the live DOM range drags along. For any other selection (read-only notes,- * dialogs, plain inputs) we fall back to cloning the DOM range.- */-export async function getSelectedHtmlForMarkdown(): Promise<string> {- const editor = await getTextEditorAtSelection();- const selectedHtml = editor?.getSelectedHtml();- if (selectedHtml) return selectedHtml;-- const selection = window.getSelection();- if (!selection || !selection.rangeCount) return "";-- const range = selection.getRangeAt(0);- const div = document.createElement("div");- div.appendChild(range.cloneContents());- return div.innerHTML;+/** The host for Electron, where Chromium answers for the clipboard and the spell checker. */+function electronHost(eApi: ElectronApi, params: ElectronContextMenuParams): ContextMenuHost {+ const api = eApi.contextMenu;+ const { editFlags } = params;++ return {+ spelling: {+ misspelledWord: params.misspelledWord,+ suggestions: params.dictionarySuggestions,+ addToDictionary: (word) => eApi.spellcheck.addWordToDictionary(word)+ },+ paste: {+ enabled: editFlags.canPaste,+ run: () => api.webContentsAction("paste"),+ runAsPlainText: () => api.webContentsAction("pasteAndMatchStyle")+ },+ canCut: editFlags.canCut,+ cut: () => api.webContentsAction("cut"),+ canCopy: editFlags.canCopy,+ copy: () => api.webContentsAction("copy"),+ openExternal: (url) => eApi.shell.openExternal(url)+ };}export default {diff --git a/apps/client/src/menus/note_context_menu.spec.ts b/apps/client/src/menus/note_context_menu.spec.tsnew file mode 100644index 0000000000..4606c2f3d4--- /dev/null+++ b/apps/client/src/menus/note_context_menu.spec.ts@@ -0,0 +1,360 @@+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,+ getActiveContextNote: () => tabManager.activeNote,+ getActiveContext: () => tabManager.activeContext+ };+ return { tabManager, triggerCommand: vi.fn() };+});++vi.mock("../components/app_context.js", () => ({+ default: { tabManager: h.tabManager, triggerCommand: h.triggerCommand }+}));++// The module under test pulls in several DOM/jQuery-heavy collaborators at import+// time; stub them so importing stays cheap and side-effect free.+vi.mock("../components/zoom.js", () => ({ default: {} }));+vi.mock("../services/clipboard_ext.js", () => ({ copyHtml: vi.fn(), copyTextWithToast: vi.fn() }));+vi.mock("../services/i18n.js", () => ({ t: (key: string) => key }));+vi.mock("../services/options.js", () => ({ default: { get: () => "" } }));+vi.mock("../services/server.js", () => ({ default: { post: vi.fn() } }));+vi.mock("../services/utils.js", () => ({+ default: { escapeHtml: (s: string) => s, isMac: () => false }+}));+vi.mock("./context_menu.js", () => ({ default: { show: vi.fn() } }));++import { copyHtml, copyTextWithToast } from "../services/clipboard_ext.js";+import server from "../services/server.js";+import contextMenu, { type MenuCommandItem, type MenuItem } from "./context_menu.js";+import {+ buildNoteContextMenuItems,+ type ContextMenuHost,+ type ContextMenuTarget,+ getSelectedHtmlForMarkdown,+ 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) {+ return {+ editing: { view: { getDomRoot: () => domRoot } },+ getSelectedHtml: vi.fn(() => selectedHtml),+ // Without the plugin the AI assistant row is skipped, keeping these tests off it.+ plugins: { has: () => false },+ isReadOnly: false,+ execute: vi.fn()+ };+}++/**+ * Points window.getSelection() at `anchorNode`, cloning `fallbackHtml` for the DOM-range path.+ * `text` is what the selection stringifies to — what the browser menu's gate reads.+ */+function setSelection(anchorNode: Node | null, fallbackHtml = "", text = "") {+ const fragment = document.createDocumentFragment();+ if (fallbackHtml) {+ const holder = document.createElement("div");+ holder.innerHTML = fallbackHtml;+ while (holder.firstChild) fragment.appendChild(holder.firstChild);+ }+ vi.spyOn(window, "getSelection").mockReturnValue({+ anchorNode,+ rangeCount: anchorNode || fallbackHtml ? 1 : 0,+ getRangeAt: () => ({ cloneContents: () => fragment.cloneNode(true) }),+ toString: () => text+ } as unknown as Selection);+}++/** A host with nothing optional, standing in for the browser. */+function browserLikeHost(overrides: Partial<ContextMenuHost> = {}): ContextMenuHost {+ return {+ canCut: true,+ cut: vi.fn(),+ canCopy: true,+ copy: vi.fn(),+ openExternal: vi.fn(),+ ...overrides+ };+}++function target(overrides: Partial<ContextMenuTarget> = {}): ContextMenuTarget {+ return {+ linkURL: "",+ linkText: "",+ isMedia: false,+ isEditable: false,+ selectionText: "hello",+ ...overrides+ };+}++/** Builds the menu for a target, defaulting whatever the test does not care about. */+function build(targetOverrides: Partial<ContextMenuTarget> = {}, host = browserLikeHost()) {+ return buildNoteContextMenuItems(target(targetOverrides), host);+}++/** The titles of `items`, with separators rendered as "---" so ordering stays readable. */+function titles(items: MenuItem<any>[]) {+ return items.map((item) => ("kind" in item && item.kind === "separator"+ ? "---"+ : (item as MenuCommandItem<any>).title));+}++function findItem(items: MenuItem<any>[], title: string) {+ const found = items.find((item) => !("kind" in item) && item.title === title);+ return found as MenuCommandItem<any> | undefined;+}++/**+ * Picks the row titled `title`, as clicking it would. `MenuHandler` declares a `void` return, so+ * the promise an async row hands back has to be recovered here for a test to await it.+ */+function run(items: MenuItem<any>[], title: string): void | Promise<void> {+ return findItem(items, title)?.handler?.({} as never, {} as never);+}++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 () => {+ const items = await build();++ expect(titles(items)).toEqual([+ "electron_context_menu.copy",+ "electron_context_menu.copy-as-markdown",+ "---",+ "electron_context_menu.search_online",+ "electron_context_menu.search_in_trilium"+ ]);+ });++ it("omits the spelling and paste rows when the host does not supply them", async () => {+ const shown = titles(await build({ isEditable: true }));++ expect(shown).not.toContain("electron_context_menu.paste");+ expect(shown).not.toContain("electron_context_menu.paste-as-plain-text");+ expect(shown).not.toContain("electron_context_menu.add-term-to-dictionary");+ // Cut is editable-only, and a browser host does serve it by deleting through the editor.+ expect(shown).toContain("electron_context_menu.cut");+ });++ it("emits the spelling suggestions and paste rows a richer host supplies", async () => {+ const addToDictionary = vi.fn();+ const items = await build({ isEditable: true }, browserLikeHost({+ spelling: { misspelledWord: "teh", suggestions: [ "the", "ten" ], addToDictionary },+ paste: { enabled: true, run: vi.fn(), runAsPlainText: vi.fn() }+ }));++ expect(titles(items).slice(0, 4)).toEqual([+ "the",+ "ten",+ "electron_context_menu.add-term-to-dictionary",+ "---"+ ]);+ // The suggestions carry a command rather than a handler: only the host can commit one.+ expect(findItem(items, "the")?.command).toBe("replaceMisspelling");+ expect(findItem(items, "the")?.spellingSuggestion).toBe("the");+ expect(titles(items)).toContain("electron_context_menu.paste-as-plain-text");++ run(items, "electron_context_menu.add-term-to-dictionary");+ expect(addToDictionary).toHaveBeenCalledWith("teh");+ });++ it("offers copy-link for a real link but not over media", async () => {+ const url = "https://example.com";+ const overLink = await build({ linkURL: url, linkText: "Example" });+ expect(titles(overLink)).toContain("electron_context_menu.copy-link");++ const overImage = await build({ linkURL: url, isMedia: true });+ expect(titles(overImage)).not.toContain("electron_context_menu.copy-link");++ const blocked = await build({ linkURL: "javascript:" });+ expect(titles(blocked)).not.toContain("electron_context_menu.copy-link");++ run(overLink, "electron_context_menu.copy-link");+ expect(copyHtml).toHaveBeenCalledWith(`<a href="${url}">Example</a>`, url);+ });++ it("searches through the host for the web and through the app for notes", async () => {+ const host = browserLikeHost();+ const items = await build({ selectionText: "trilium notes" }, host);++ run(items, "electron_context_menu.search_online");+ expect(host.openExternal).toHaveBeenCalledWith("https://duckduckgo.com/?q=trilium%20notes");++ run(items, "electron_context_menu.search_in_trilium");+ expect(h.triggerCommand).toHaveBeenCalledWith("searchNotes", {+ searchString: "trilium notes"+ });+ });++ it("converts the selection through the to-markdown route", async () => {+ vi.mocked(server.post).mockResolvedValue({ markdownContent: "# Hi" });+ setSelection(document.createElement("span"), "<h1>Hi</h1>");++ const items = await build();+ await run(items, "electron_context_menu.copy-as-markdown");++ expect(server.post).toHaveBeenCalledWith("other/to-markdown", {+ htmlContent: "<h1>Hi</h1>"+ });+ expect(copyTextWithToast).toHaveBeenCalledWith("# Hi");+ });+});++describe("setupContextMenu (browser)", () => {+ beforeAll(() => setupContextMenu());++ beforeEach(() => {+ vi.clearAllMocks();+ tabManager.activeNote = null;+ tabManager.activeContext = null;+ });++ /** Right-clicks `element`, optionally with the event already claimed by another widget. */+ function rightClick(element: Element, claimedByAnotherWidget = false) {+ const event = new MouseEvent("contextmenu", { bubbles: true, cancelable: true });+ if (claimedByAnotherWidget) {+ element.addEventListener("contextmenu", (e) => e.preventDefault(), { once: true });+ }+ element.dispatchEvent(event);+ return event;+ }++ /** Lets the listener's async tail run, so a menu it would raise has been raised by now. */+ const settle = () => new Promise((resolve) => setTimeout(resolve, 0));++ it("leaves the browser's own menu up when nothing is selected", async () => {+ const div = document.createElement("div");+ document.body.appendChild(div);+ setSelection(null, "", " ");++ const event = rightClick(div);+ await settle();++ expect(event.defaultPrevented).toBe(false);+ expect(contextMenu.show).not.toHaveBeenCalled();+ });++ it("stands aside for a widget that already answered the click", async () => {+ const div = document.createElement("div");+ document.body.appendChild(div);+ setSelection(div, "<b>text</b>", "text");++ rightClick(div, true);+ await settle();++ expect(contextMenu.show).not.toHaveBeenCalled();+ });++ it("takes the menu over for a selection, and reads the link under the pointer", async () => {+ const link = document.createElement("a");+ link.href = "https://example.com/";+ link.textContent = "Example";+ document.body.appendChild(link);+ setSelection(link, "<b>text</b>", "text");++ const event = rightClick(link);+ expect(event.defaultPrevented).toBe(true);++ await vi.waitFor(() => expect(contextMenu.show).toHaveBeenCalled());+ const shown = vi.mocked(contextMenu.show).mock.calls[0][0];+ expect(titles(shown.items)).toEqual([+ "electron_context_menu.copy",+ "electron_context_menu.copy-as-markdown",+ "electron_context_menu.copy-link",+ "---",+ "electron_context_menu.search_online",+ "electron_context_menu.search_in_trilium"+ ]);+ });+});++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 () => {+ const editorRoot = document.createElement("div");+ 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, "<b>dom clone</b>");++ expect(await getSelectedHtmlForMarkdown()).toBe("<p>clean</p>");+ expect(editor.getSelectedHtml).toHaveBeenCalled();+ });++ it("falls back to the DOM clone when the selection is outside the editor", async () => {+ const editorRoot = document.createElement("div");+ 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>");+ expect(editor.getSelectedHtml).not.toHaveBeenCalled();+ });++ it("falls back to the DOM clone when the editor selection is empty", async () => {+ const editorRoot = document.createElement("div");+ const anchor = document.createElement("span");+ 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>");++ 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/note_context_menu.ts b/apps/client/src/menus/note_context_menu.tsnew file mode 100644index 0000000000..43c76c945e--- /dev/null+++ b/apps/client/src/menus/note_context_menu.ts@@ -0,0 +1,312 @@+import type { CKTextEditor } from "@triliumnext/ckeditor5";++import appContext, { type CommandNames } from "../components/app_context.js";+import { copyHtml, copyTextWithToast } from "../services/clipboard_ext.js";+import { t } from "../services/i18n.js";+import options from "../services/options.js";+import server from "../services/server.js";+import utils from "../services/utils.js";+import contextMenu, { type MenuItem } from "./context_menu.js";+import { buildAiActionsMenuItem, getTextEditorAtSelection } from "./text_editor_context_menu.js";++/** What the pointer was over when the menu was summoned. */+export interface ContextMenuTarget {+ /** URL of the link under the pointer, or an empty string. */+ linkURL: string;+ /** Visible text of that link, or an empty string. */+ linkText: string;+ /** Whether the pointer is over an image, video or audio element. */+ isMedia: boolean;+ /** Whether the element under the pointer accepts typing. */+ isEditable: boolean;+ /** The selected text, or an empty string. */+ selectionText: string;+}++/**+ * What the surrounding application can run on the menu's behalf. An optional member the host leaves+ * out drops the rows that depend on it.+ *+ * Chromium reports its spell checker's state to the application embedding it but not to a page,+ * and a page's paste costs a permission prompt in Chrome and an extra click in Firefox and+ * Safari — more than the Ctrl+V it would stand in for. A browser host therefore supplies neither.+ */+export interface ContextMenuHost {+ spelling?: {+ misspelledWord: string;+ suggestions: string[];+ addToDictionary(word: string): void;+ };+ paste?: {+ enabled: boolean;+ run(): void;+ runAsPlainText(): void;+ };+ canCut: boolean;+ cut(): void | Promise<void>;+ canCopy: boolean;+ copy(): void | Promise<void>;+ /** Opens a URL outside the note, in whatever the host uses for external links. */+ openExternal(url: string): void;+}++/**+ * Puts Trilium's menu over the browser's own wherever there is a selection to act on.+ *+ * The gate is what keeps the native menu reachable: spelling corrections and the browser's paste+ * live there, no web API exposes either, and a right-click at a bare caret is the gesture for+ * fixing a typo — so that click is left alone. Electron has no such constraint and replaces the+ * menu everywhere; see `electron_context_menu.ts`.+ */+export function setupContextMenu() {+ document.addEventListener("contextmenu", (event) => {+ // A widget that answers the click itself — the note tree, an internal link — has already+ // put its own menu up.+ if (event.defaultPrevented) {+ return;+ }++ // `window.getSelection()` does not report a selection inside an `<input>` or `<textarea>`,+ // so those keep the browser's menu, which is the better one for a plain text field.+ const selectionText = window.getSelection()?.toString() ?? "";+ if (!selectionText.trim()) {+ return;+ }++ // Claimed before the items are built: after an await the default action has already run.+ event.preventDefault();++ const element = event.target instanceof HTMLElement ? event.target : null;+ const link = element?.closest("a[href]");++ void showBrowserContextMenu(event.pageX, event.pageY, {+ linkURL: link instanceof HTMLAnchorElement ? link.href : "",+ linkText: link?.textContent ?? "",+ isMedia: !!element?.closest("img, video, audio"),+ isEditable: !!element?.isContentEditable,+ selectionText+ });+ });+}++/**+ * The rows the menu shows for `target`, in order, leaving out whatever `host` cannot serve.+ *+ * Callers own the positioning and the `selectMenuItemHandler`, because the spelling suggestions+ * carry a `replaceMisspelling` command rather than a handler — only the host that produced them+ * can commit one.+ */+export async function buildNoteContextMenuItems(+ target: ContextMenuTarget,+ host: ContextMenuHost+): Promise<MenuItem<CommandNames>[]> {+ const hasText = target.selectionText.trim().length > 0;+ const platformModifier = utils.isMac() ? "Meta" : "Ctrl";+ const items: MenuItem<CommandNames>[] = [];++ // Resolved before the menu is built rather than lazily in a handler: the rows it produces+ // depend on how the editor answers, and `isEditable` keeps the lookup off every click that+ // lands somewhere a completion could not be committed anyway (a read-only note, the tree).+ const aiActions = target.isEditable ? await buildAiActionsMenuItem() : null;++ if (host.spelling?.misspelledWord) {+ const { misspelledWord, suggestions, addToDictionary } = host.spelling;++ for (const suggestion of suggestions) {+ items.push({+ title: suggestion,+ command: "replaceMisspelling",+ spellingSuggestion: suggestion,+ uiIcon: "bx bx-empty"+ });+ }++ items.push({+ title: t("electron_context_menu.add-term-to-dictionary", { term: misspelledWord }),+ uiIcon: "bx bx-plus",+ handler: () => addToDictionary(misspelledWord)+ });++ items.push({ kind: "separator" });+ }++ if (aiActions) {+ items.push(aiActions, { kind: "separator" });+ }++ if (target.isEditable) {+ items.push({+ enabled: host.canCut && hasText,+ title: t("electron_context_menu.cut"),+ shortcut: `${platformModifier}+X`,+ uiIcon: "bx bx-cut",+ handler: () => host.cut()+ });+ }++ if (target.isEditable || hasText) {+ items.push({+ enabled: host.canCopy && hasText,+ title: t("electron_context_menu.copy"),+ shortcut: `${platformModifier}+C`,+ uiIcon: "bx bx-copy",+ handler: () => host.copy()+ });++ items.push({+ enabled: hasText,+ title: t("electron_context_menu.copy-as-markdown"),+ uiIcon: "bx bx-copy-alt",+ handler: copySelectionAsMarkdown+ });+ }++ const unlinkable = [ "", "javascript:", "about:blank#blocked" ];+ if (!unlinkable.includes(target.linkURL) && !target.isMedia) {+ items.push({+ title: t("electron_context_menu.copy-link"),+ uiIcon: "bx bx-copy",+ handler: () => {+ const text = utils.escapeHtml(target.linkText || target.linkURL);+ const html = `<a href="${utils.escapeHtml(target.linkURL)}">${text}</a>`;+ void copyHtml(html, target.linkURL);+ }+ });+ }++ if (host.paste && target.isEditable) {+ const { enabled, run, runAsPlainText } = host.paste;++ items.push({+ enabled,+ title: t("electron_context_menu.paste"),+ shortcut: `${platformModifier}+V`,+ uiIcon: "bx bx-paste",+ handler: run+ });++ items.push({+ enabled,+ title: t("electron_context_menu.paste-as-plain-text"),+ shortcut: `${platformModifier}+Shift+V`,+ uiIcon: "bx bx-paste",+ handler: runAsPlainText+ });+ }++ if (hasText) {+ const { selectionText } = target;+ const shortenedSelection = selectionText.length > 15+ ? `${selectionText.slice(0, 13)}…`+ : selectionText;++ const customSearchEngineName = options.get("customSearchEngineName");+ const customSearchEngineUrl = options.get("customSearchEngineUrl") as string;+ let searchEngineName;+ let searchEngineUrl;+ if (customSearchEngineName && customSearchEngineUrl) {+ searchEngineName = customSearchEngineName;+ searchEngineUrl = customSearchEngineUrl;+ } else {+ searchEngineName = "DuckDuckGo";+ searchEngineUrl = "https://duckduckgo.com/?q={keyword}";+ }++ const searchUrl = searchEngineUrl.replace("{keyword}", encodeURIComponent(selectionText));++ items.push({ kind: "separator" });++ items.push({+ title: t("electron_context_menu.search_online", {+ term: shortenedSelection,+ searchEngine: searchEngineName+ }),+ uiIcon: "bx bx-search-alt",+ handler: () => host.openExternal(searchUrl)+ });++ items.push({+ title: t("electron_context_menu.search_in_trilium", { term: shortenedSelection }),+ uiIcon: "bx bx-search",+ handler: async () => {+ await appContext.triggerCommand("searchNotes", { searchString: selectionText });+ }+ });+ }++ return items;+}++/**+ * Returns the HTML to feed to the Markdown converter for the "Copy as Markdown" action.+ *+ * When the selection lives inside the active text note's CKEditor, we take the editor's+ * data-pipeline HTML (`getSelectedHtml()`) — clean stored markup without the editing-view+ * artifacts (`data-list-item-id`, collapsible handle/arrow spans, bogus-paragraph wrappers)+ * that cloning the live DOM range drags along. For any other selection (read-only notes,+ * dialogs, plain inputs) we fall back to cloning the DOM range.+ */+export async function getSelectedHtmlForMarkdown(): Promise<string> {+ const editor = await getTextEditorAtSelection();+ const selectedHtml = editor?.getSelectedHtml();+ if (selectedHtml) return selectedHtml;++ const selection = window.getSelection();+ if (!selection || !selection.rangeCount) return "";++ const range = selection.getRangeAt(0);+ const div = document.createElement("div");+ div.appendChild(range.cloneContents());+ return div.innerHTML;+}++async function showBrowserContextMenu(x: number, y: number, target: ContextMenuTarget) {+ const editor = await getTextEditorAtSelection();+ const items = await buildNoteContextMenuItems(target, browserHost(editor));+ if (!items.length) return;++ contextMenu.show({ x, y, items, selectMenuItemHandler: () => {} });+}++/**+ * The host for a page, which has web APIs and nothing more.+ *+ * `editor` is what the selection sits in, when it sits in a text note at all. Cut needs somewhere+ * to delete from, and the editor is the only thing in a note that answers that.+ */+function browserHost(editor: CKTextEditor | null): ContextMenuHost {+ return {+ canCut: !!editor && !editor.isReadOnly,+ async cut() {+ await copySelection();+ editor?.execute("delete");+ },+ canCopy: true,+ copy: copySelection,+ openExternal: (url) => window.open(url, "_blank", "noopener")+ };+}++/** Copies the selection as rich text, so that it pastes back into a note with its formatting. */+async function copySelection() {+ const html = await getSelectedHtmlForMarkdown();+ const plainText = window.getSelection()?.toString() ?? "";+ if (!html && !plainText) return;++ await copyHtml(html || utils.escapeHtml(plainText), plainText);+}++async function copySelectionAsMarkdown() {+ const htmlContent = await getSelectedHtmlForMarkdown();+ if (!htmlContent) return;++ try {+ const { markdownContent } = await server.post<{ markdownContent: string }>(+ "other/to-markdown",+ { htmlContent }+ );+ copyTextWithToast(markdownContent);+ } catch (error) {+ console.error("Failed to copy as markdown:", error);+ }+}