Skip to content

Build your personal knowledge base with Trilium Notes

feat(electron): handle context menu

Elian Dorana59596411874
diff --git a/apps/client/src/menus/electron_context_menu.ts b/apps/client/src/menus/electron_context_menu.ts
index ababf8feef..8584984c59 100644
--- a/apps/client/src/menus/electron_context_menu.ts
+++ b/apps/client/src/menus/electron_context_menu.ts
@@ -1,5 +1,3 @@
-import type { BrowserWindow } from "electron";
-
import type { CommandNames } from "../components/app_context.js";
import appContext from "../components/app_context.js";
import zoomService from "../components/zoom.js";
@@ -11,17 +9,13 @@ import utils from "../services/utils.js";
import contextMenu, { type MenuItem } from "./context_menu.js";
function setupContextMenu() {
- const electron = utils.dynamicRequire("electron");
-
- const remote = utils.dynamicRequire("@electron/remote");
- // FIXME: Remove typecast once Electron is properly integrated.
- const { webContents } = remote.getCurrentWindow() as BrowserWindow;
+ const api = window.electronApi!;
+ const isMac = window.glob.platform === "darwin";
+ const platformModifier = isMac ? "Meta" : "Ctrl";
- webContents.on("context-menu", (event, params) => {
+ api.onContextMenu((params) => {
const { editFlags } = params;
const hasText = params.selectionText.trim().length > 0;
- const isMac = process.platform === "darwin";
- const platformModifier = isMac ? "Meta" : "Ctrl";
const items: MenuItem<CommandNames>[] = [];
@@ -38,7 +32,7 @@ function setupContextMenu() {
items.push({
title: t("electron_context_menu.add-term-to-dictionary", { term: params.misspelledWord }),
uiIcon: "bx bx-plus",
- handler: () => electron.ipcRenderer.send("add-word-to-dictionary", params.misspelledWord)
+ handler: () => api.addWordToDictionary(params.misspelledWord)
});
items.push({ kind: "separator" });
@@ -50,7 +44,7 @@ function setupContextMenu() {
title: t("electron_context_menu.cut"),
shortcut: `${platformModifier}+X`,
uiIcon: "bx bx-cut",
- handler: () => webContents.cut()
+ handler: () => api.webContentsAction("cut")
});
}
@@ -60,7 +54,7 @@ function setupContextMenu() {
title: t("electron_context_menu.copy"),
shortcut: `${platformModifier}+C`,
uiIcon: "bx bx-copy",
- handler: () => webContents.copy()
+ handler: () => api.webContentsAction("copy")
});
items.push({
@@ -114,7 +108,7 @@ function setupContextMenu() {
title: t("electron_context_menu.paste"),
shortcut: `${platformModifier}+V`,
uiIcon: "bx bx-paste",
- handler: () => webContents.paste()
+ handler: () => api.webContentsAction("paste")
});
}
@@ -124,14 +118,13 @@ function setupContextMenu() {
title: t("electron_context_menu.paste-as-plain-text"),
shortcut: `${platformModifier}+Shift+V`,
uiIcon: "bx bx-paste",
- handler: () => webContents.pasteAndMatchStyle()
+ handler: () => api.webContentsAction("pasteAndMatchStyle")
});
}
if (hasText) {
const shortenedSelection = params.selectionText.length > 15 ? `${params.selectionText.substr(0, 13)}…` : params.selectionText;
- // Read the search engine from the options and fallback to DuckDuckGo if the option is not set.
const customSearchEngineName = options.get("customSearchEngineName");
const customSearchEngineUrl = options.get("customSearchEngineUrl") as string;
let searchEngineName;
@@ -144,7 +137,6 @@ function setupContextMenu() {
searchEngineUrl = "https://duckduckgo.com/?q={keyword}";
}
- // Replace the placeholder with the real search keyword.
const searchUrl = searchEngineUrl.replace("{keyword}", encodeURIComponent(params.selectionText));
items.push({ kind: "separator" });
@@ -152,7 +144,7 @@ function setupContextMenu() {
items.push({
title: t("electron_context_menu.search_online", { term: shortenedSelection, searchEngine: searchEngineName }),
uiIcon: "bx bx-search-alt",
- handler: () => electron.shell.openExternal(searchUrl)
+ handler: () => api.openExternal(searchUrl)
});
items.push({
@@ -178,7 +170,7 @@ function setupContextMenu() {
items,
selectMenuItemHandler: ({ command, spellingSuggestion }) => {
if (command === "replaceMisspelling" && spellingSuggestion) {
- webContents.insertText(spellingSuggestion);
+ api.webContentsAction("insertText", spellingSuggestion);
}
}
});
diff --git a/apps/client/src/types.d.ts b/apps/client/src/types.d.ts
index 87c645b878..580b86d662 100644
--- a/apps/client/src/types.d.ts
+++ b/apps/client/src/types.d.ts
@@ -73,6 +73,27 @@ declare global {
setVibrancy(vibrancy: string): void;
clearNavigationHistory(): void;
setNativeThemeSource(source: "system" | "light" | "dark"): void;
+ onContextMenu(callback: (params: ElectronContextMenuParams) => void): void;
+ webContentsAction(action: "cut" | "copy" | "paste" | "pasteAndMatchStyle" | "insertText", text?: string): void;
+ openExternal(url: string): void;
+ addWordToDictionary(word: string): void;
+ }
+
+ interface ElectronContextMenuParams {
+ x: number;
+ y: number;
+ linkURL: string;
+ linkText: string;
+ mediaType: string;
+ isEditable: boolean;
+ selectionText: string;
+ misspelledWord: string;
+ dictionarySuggestions: string[];
+ editFlags: {
+ canCut: boolean;
+ canCopy: boolean;
+ canPaste: boolean;
+ };
}
interface WindowEventMap {
diff --git a/apps/desktop/spec/preload.spec.ts b/apps/desktop/spec/preload.spec.ts
index 8044ca9c1d..36134eafae 100644
--- a/apps/desktop/spec/preload.spec.ts
+++ b/apps/desktop/spec/preload.spec.ts
@@ -151,5 +151,49 @@ describe("preload script", () => {
args: ["dark"]
});
});
+
+ it("webContentsAction sends action and optional text", () => {
+ getApi().webContentsAction("cut");
+ expect(ipcRendererSent).toContainEqual({
+ channel: "web-contents-action",
+ args: ["cut", undefined]
+ });
+
+ getApi().webContentsAction("insertText", "hello");
+ expect(ipcRendererSent).toContainEqual({
+ channel: "web-contents-action",
+ args: ["insertText", "hello"]
+ });
+ });
+
+ it("openExternal sends correct IPC message", () => {
+ getApi().openExternal("https://example.com");
+ expect(ipcRendererSent).toContainEqual({
+ channel: "open-external",
+ args: ["https://example.com"]
+ });
+ });
+
+ it("addWordToDictionary sends correct IPC message", () => {
+ getApi().addWordToDictionary("trilium");
+ expect(ipcRendererSent).toContainEqual({
+ channel: "add-word-to-dictionary",
+ args: ["trilium"]
+ });
+ });
+ });
+
+ describe("context menu listener", () => {
+ it("onContextMenu registers and forwards context-menu channel", () => {
+ const callback = vi.fn();
+ getApi().onContextMenu(callback);
+
+ const listeners = ipcRendererListeners.get("context-menu")!;
+ expect(listeners).toHaveLength(1);
+
+ const params = { x: 100, y: 200, selectionText: "test" };
+ listeners[0]({}, params);
+ expect(callback).toHaveBeenCalledWith(params);
+ });
});
});
diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts
index eb12e45a09..cb0f5bdbc8 100644
--- a/apps/desktop/src/preload.ts
+++ b/apps/desktop/src/preload.ts
@@ -43,5 +43,40 @@ contextBridge.exposeInMainWorld("electronApi", {
// Theme
setNativeThemeSource(source: "system" | "light" | "dark") {
ipcRenderer.send("set-native-theme-source", source);
+ },
+
+ // Context menu
+ onContextMenu(callback: (params: ContextMenuParams) => void) {
+ ipcRenderer.on("context-menu", (_event, params: ContextMenuParams) => callback(params));
+ },
+ webContentsAction(action: "cut" | "copy" | "paste" | "pasteAndMatchStyle" | "insertText", text?: string) {
+ ipcRenderer.send("web-contents-action", action, text);
+ },
+
+ // Shell
+ openExternal(url: string) {
+ ipcRenderer.send("open-external", url);
+ },
+
+ // Dictionary
+ addWordToDictionary(word: string) {
+ ipcRenderer.send("add-word-to-dictionary", word);
}
});
+
+interface ContextMenuParams {
+ x: number;
+ y: number;
+ linkURL: string;
+ linkText: string;
+ mediaType: string;
+ isEditable: boolean;
+ selectionText: string;
+ misspelledWord: string;
+ dictionarySuggestions: string[];
+ editFlags: {
+ canCut: boolean;
+ canCopy: boolean;
+ canPaste: boolean;
+ };
+}
diff --git a/apps/server/src/services/window.ts b/apps/server/src/services/window.ts
index 019086a9a6..ddc767b692 100644
--- a/apps/server/src/services/window.ts
+++ b/apps/server/src/services/window.ts
@@ -115,6 +115,21 @@ electron.ipcMain.on("set-native-theme-source", (_event, source: "system" | "ligh
electron.nativeTheme.themeSource = source;
});
+electron.ipcMain.on("web-contents-action", (event, action: string, text?: string) => {
+ const wc = event.sender;
+ switch (action) {
+ case "cut": wc.cut(); break;
+ case "copy": wc.copy(); break;
+ case "paste": wc.paste(); break;
+ case "pasteAndMatchStyle": wc.pasteAndMatchStyle(); break;
+ case "insertText": if (text) wc.insertText(text); break;
+ }
+});
+
+electron.ipcMain.on("open-external", (_event, url: string) => {
+ electron.shell.openExternal(url);
+});
+
initPrintingHandlers();
async function createMainWindow(app: App) {
@@ -240,6 +255,26 @@ async function configureWebContents(webContents: WebContents, spellcheckEnabled:
win.on("enter-full-screen", () => webContents.send("enter-full-screen"));
win.on("leave-full-screen", () => webContents.send("leave-full-screen"));
}
+
+ // Forward context-menu event to the renderer with only the fields we need.
+ webContents.on("context-menu", (_event, params) => {
+ webContents.send("context-menu", {
+ x: params.x,
+ y: params.y,
+ linkURL: params.linkURL,
+ linkText: params.linkText,
+ mediaType: params.mediaType,
+ isEditable: params.isEditable,
+ selectionText: params.selectionText,
+ misspelledWord: params.misspelledWord,
+ dictionarySuggestions: params.dictionarySuggestions,
+ editFlags: {
+ canCut: params.editFlags.canCut,
+ canCopy: params.editFlags.canCopy,
+ canPaste: params.editFlags.canPaste
+ }
+ });
+ });
}
function setupSpellcheckForSession(session: Session) {