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
fix(client): keep the browser's menu for a right-click off the selection
Elian Doranbf0a4e3d1fec
diff --git a/apps/client/src/menus/note_context_menu.spec.ts b/apps/client/src/menus/note_context_menu.spec.tsindex a7d58239f7..aa4df9c271 100644--- a/apps/client/src/menus/note_context_menu.spec.ts+++ b/apps/client/src/menus/note_context_menu.spec.ts@@ -55,7 +55,9 @@ function fakeEditor(domRoot: Node | null, selectedHtml: string) {/*** 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.+ * `text` is what the selection stringifies to — what the browser menu's gate reads. happy-dom lays+ * nothing out, so the highlighted box is stated here: it covers the origin every `rightClick`+ * lands on unless that test says otherwise.*/function setSelection(anchorNode: Node | null, fallbackHtml = "", text = "") {const fragment = document.createDocumentFragment();@@ -67,7 +69,10 @@ function setSelection(anchorNode: Node | null, fallbackHtml = "", text = "") {vi.spyOn(window, "getSelection").mockReturnValue({anchorNode,rangeCount: anchorNode || fallbackHtml ? 1 : 0,- getRangeAt: () => ({ cloneContents: () => fragment.cloneNode(true) }),+ getRangeAt: () => ({+ cloneContents: () => fragment.cloneNode(true),+ getClientRects: () => [ { left: 0, top: 0, right: 200, bottom: 100 } ]+ }),toString: () => text} as unknown as Selection);}@@ -223,8 +228,17 @@ describe("setupContextMenu (browser)", () => {});/** Right-clicks `element`, holding Shift or letting another widget claim the event first. */- function rightClick(element: Element, { shiftKey = false, claimed = false } = {}) {- const event = new MouseEvent("contextmenu", { bubbles: true, cancelable: true, shiftKey });+ function rightClick(+ element: Element,+ { shiftKey = false, claimed = false, clientX = 0, clientY = 0 } = {}+ ) {+ const event = new MouseEvent("contextmenu", {+ bubbles: true,+ cancelable: true,+ shiftKey,+ clientX,+ clientY+ });if (claimed) {element.addEventListener("contextmenu", (e) => e.preventDefault(), { once: true });}@@ -272,6 +286,18 @@ describe("setupContextMenu (browser)", () => {expect(contextMenu.show).not.toHaveBeenCalled();});+ it("leaves it up for a click away from the selection, which is what the rows act on", async () => {+ const div = document.createElement("div");+ document.body.appendChild(div);+ setSelection(div, "<b>text</b>", "text");++ const event = rightClick(div, { clientX: 500, clientY: 500 });+ 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);diff --git a/apps/client/src/menus/note_context_menu.ts b/apps/client/src/menus/note_context_menu.tsindex 566a51cee3..c2ba4438a5 100644--- a/apps/client/src/menus/note_context_menu.ts+++ b/apps/client/src/menus/note_context_menu.ts@@ -25,11 +25,8 @@ export interface ContextMenuTarget {/*** 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.+ * out drops the rows that depend on it: a page reaches neither the spell checker's state nor a+ * paste cheaper than Ctrl+V, so a browser host supplies neither.*/export interface ContextMenuHost {spelling?: {@@ -51,12 +48,9 @@ export interface ContextMenuHost {}/**- * 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`.+ * Puts Trilium's menu over the browser's own wherever the pointer sits on a selection. A click at a+ * bare caret keeps the native menu, the only way to spelling corrections and the browser's paste.+ * Electron replaces the menu everywhere; see `electron_context_menu.ts`.*/export function setupContextMenu() {document.addEventListener("contextmenu", (event) => {@@ -66,18 +60,23 @@ export function setupContextMenu() {return;}- // Firefox suppresses the event outright on Shift+right-click, so its users already have a- // way back to the browser's menu — to the extension entries registered against a selection- // above all. Honoring the modifier gives Chrome and Safari, which have no bypass of their- // own, the same one.+ // Shift+right-click is Firefox's own way back to the browser's menu; honoring it gives+ // Chrome and Safari, which have no bypass of their own, the same one.if (event.shiftKey) {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()) {+ const selection = window.getSelection();+ const selectionText = selection?.toString() ?? "";+ if (!selection || !selectionText.trim()) {+ return;+ }++ // The rows act on the selection, so the pointer has to be on it. A right-click on the+ // surrounding UI, which takes no selection of its own, leaves an earlier one standing.+ if (!isPointInSelection(selection, event.clientX, event.clientY)) {return;}@@ -276,6 +275,19 @@ async function showBrowserContextMenu(x: number, y: number, target: ContextMenuTcontextMenu.show({ x, y, items, selectMenuItemHandler: () => {} });}+/** Whether the point (`x`, `y`), in viewport coordinates, lands on what `selection` highlights. */+function isPointInSelection(selection: Selection, x: number, y: number) {+ for (let i = 0; i < selection.rangeCount; i++) {+ for (const rect of Array.from(selection.getRangeAt(i).getClientRects())) {+ if (x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom) {+ return true;+ }+ }+ }++ return false;+}+/*** Whether `element` takes typing, which is what decides the rows that write to a note.*