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(electron): handle file opening
Elian Doranb3397b67bf5b
diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.tsindex e17b9fe5f9..75f990a7b8 100644--- a/apps/client/src/services/content_renderer.ts+++ b/apps/client/src/services/content_renderer.ts@@ -18,7 +18,7 @@ import protectedSessionHolder from "./protected_session_holder.js";import renderService from "./render.js";import server from "./server.js";import { applySingleBlockSyntaxHighlight } from "./syntax_highlight.js";-import utils, { getErrorMessage } from "./utils.js";+import { getErrorMessage } from "./utils.js";let idCounter = 1;@@ -100,9 +100,8 @@ export async function getRenderedContent(this: {} | { ctx: string }, entity: FNo.on("click", () => {const webViewSrc = entity.getLabelValue("webViewSrc");if (webViewSrc) {- if (utils.isElectron()) {- const electron = utils.dynamicRequire("electron");- electron.shell.openExternal(webViewSrc);+ if (window.electronApi) {+ window.electronApi.openExternal(webViewSrc);} else {window.open(webViewSrc, '_blank', 'noopener,noreferrer');}diff --git a/apps/client/src/services/link.ts b/apps/client/src/services/link.tsindex 5938735413..b7de937114 100644--- a/apps/client/src/services/link.ts+++ b/apps/client/src/services/link.ts@@ -339,8 +339,7 @@ export function goToLinkExt(evt: MouseEvent | JQuery.ClickEvent | JQuery.MouseDowindow.open(hrefLink, "_blank");} else if (ALLOWED_PROTOCOLS.some((protocol) => hrefLink.toLowerCase().startsWith(`${protocol}:`))) {// Enable protocols supported by CKEditor 5 to be clickable.- if (utils.isElectron()) {- const electron = utils.dynamicRequire("electron");+ if (window.electronApi) {const reportLinkError = (e: unknown) => {const message = e instanceof Error ? e.message : String(e);logError(`Failed to open link '${hrefLink}': ${message}`);@@ -350,14 +349,11 @@ export function goToLinkExt(evt: MouseEvent | JQuery.ClickEvent | JQuery.MouseDoif (hrefLink.toLowerCase().startsWith("file:")) {// shell.openExternal mishandles Unicode file:// URLs on Windows;// convert to a filesystem path and use shell.openPath instead.- // Normalize file://c:/... (2 slashes — drive read as host) to file:///c:/...- const normalized = hrefLink.replace(/^file:\/\/(?=[a-zA-Z]:)/i, "file:///");- const { fileURLToPath } = utils.dynamicRequire("url");- electron.shell.openPath(fileURLToPath(normalized)).then((err: string) => {+ window.electronApi.openFileUrl(hrefLink).then((err: string) => {if (err) reportLinkError(new Error(err));}).catch(reportLinkError);} else {- electron.shell.openExternal(hrefLink).catch(reportLinkError);+ window.electronApi.openExternal(hrefLink);}} else {window.open(hrefLink, "_blank");diff --git a/apps/client/src/services/open.ts b/apps/client/src/services/open.tsindex b40ed0116e..f8a2e3d863 100644--- a/apps/client/src/services/open.ts+++ b/apps/client/src/services/open.ts@@ -157,8 +157,7 @@ async function openExternally(type: string, entityId: string, mime: string) {if (utils.isElectron()) {const resp = await server.post<TmpResponse>(`${type}/${entityId}/save-to-tmp-dir`);- const electron = utils.dynamicRequire("electron");- const res = await electron.shell.openPath(resp.tmpFilePath);+ const res = await window.electronApi?.openPath(resp.tmpFilePath);if (res) {// fallback in case there's no default application for this file@@ -200,8 +199,7 @@ async function openNoteOnServer(noteId: string) {async function openDirectory(directory: string) {try {if (utils.isElectron()) {- const electron = utils.dynamicRequire("electron");- const res = await electron.shell.openPath(directory);+ const res = await window.electronApi?.openPath(directory);if (res) {console.error("Failed to open directory:", res);}diff --git a/apps/client/src/types.d.ts b/apps/client/src/types.d.tsindex 21cbb836d6..49f212cfcf 100644--- a/apps/client/src/types.d.ts+++ b/apps/client/src/types.d.ts@@ -76,6 +76,8 @@ declare global {onContextMenu(callback: (params: ElectronContextMenuParams) => void): void;webContentsAction(action: "cut" | "copy" | "paste" | "pasteAndMatchStyle" | "insertText", text?: string): void;openExternal(url: string): void;+ openPath(path: string): Promise<string>;+ openFileUrl(fileUrl: string): Promise<string>;reloadTray(): void;addWordToDictionary(word: string): void;onPrintProgress(callback: (data: { progress: number; action: string }) => void): void;diff --git a/apps/client/src/widgets/dialogs/incorrect_cpu_arch.tsx b/apps/client/src/widgets/dialogs/incorrect_cpu_arch.tsxindex 438cff1f3b..1a601d9d17 100644--- a/apps/client/src/widgets/dialogs/incorrect_cpu_arch.tsx+++ b/apps/client/src/widgets/dialogs/incorrect_cpu_arch.tsx@@ -25,9 +25,8 @@ export default function IncorrectCpuArchDialogComponent() {icon="bx bx-download"onClick={() => {// Open the releases page where users can download the correct version- if (utils.isElectron()) {- const { shell } = utils.dynamicRequire("electron");- shell.openExternal("https://github.com/TriliumNext/Trilium/releases/latest");+ if (window.electronApi) {+ window.electronApi.openExternal("https://github.com/TriliumNext/Trilium/releases/latest");} else {window.open("https://github.com/TriliumNext/Trilium/releases/latest", "_blank");}diff --git a/apps/desktop/spec/preload.spec.ts b/apps/desktop/spec/preload.spec.tsindex b92f1df57d..6694135251 100644--- a/apps/desktop/spec/preload.spec.ts+++ b/apps/desktop/spec/preload.spec.ts@@ -4,6 +4,7 @@ let exposedApi: Record<string, Record<string, unknown>> = {};let mockZoomFactor = 1.0;const ipcRendererListeners = new Map<string, Function[]>();const ipcRendererSent: Array<{ channel: string; args: unknown[] }> = [];+const ipcRendererInvoked: Array<{ channel: string; args: unknown[] }> = [];const ipcRendererSyncResults = new Map<string, unknown>();vi.mock("electron", () => ({@@ -29,6 +30,10 @@ vi.mock("electron", () => ({send(channel: string, ...args: unknown[]) {ipcRendererSent.push({ channel, args });},+ invoke(channel: string, ...args: unknown[]) {+ ipcRendererInvoked.push({ channel, args });+ return Promise.resolve("");+ },sendSync(channel: string, ...args: unknown[]) {return ipcRendererSyncResults.get(`${channel}:${args[0]}`);},@@ -48,6 +53,7 @@ describe("preload script", () => {mockZoomFactor = 1.0;ipcRendererListeners.clear();ipcRendererSent.length = 0;+ ipcRendererInvoked.length = 0;ipcRendererSyncResults.clear();vi.resetModules();await import("../src/preload.js");@@ -182,6 +188,22 @@ describe("preload script", () => {});});+ it("openPath invokes correct IPC channel", async () => {+ await getApi().openPath("/tmp/test.txt");+ expect(ipcRendererInvoked).toContainEqual({+ channel: "open-path",+ args: ["/tmp/test.txt"]+ });+ });++ it("openFileUrl invokes correct IPC channel", async () => {+ await getApi().openFileUrl("file:///tmp/test.txt");+ expect(ipcRendererInvoked).toContainEqual({+ channel: "open-file-url",+ args: ["file:///tmp/test.txt"]+ });+ });+it("reloadTray sends correct IPC message", () => {getApi().reloadTray();expect(ipcRendererSent).toContainEqual({diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.tsindex d4aa707b00..552781c453 100644--- a/apps/desktop/src/preload.ts+++ b/apps/desktop/src/preload.ts@@ -57,6 +57,12 @@ contextBridge.exposeInMainWorld("electronApi", {openExternal(url: string) {ipcRenderer.send("open-external", url);},+ openPath(path: string): Promise<string> {+ return ipcRenderer.invoke("open-path", path);+ },+ openFileUrl(fileUrl: string): Promise<string> {+ return ipcRenderer.invoke("open-file-url", fileUrl);+ },// TrayreloadTray() {diff --git a/apps/server/src/services/window.ts b/apps/server/src/services/window.tsindex 413e03b0a4..a4ab4e7014 100644--- a/apps/server/src/services/window.ts+++ b/apps/server/src/services/window.ts@@ -130,6 +130,15 @@ electron.ipcMain.on("open-external", (_event, url: string) => {electron.shell.openExternal(url);});+electron.ipcMain.handle("open-path", (_event, filePath: string) => {+ return electron.shell.openPath(filePath);+});++electron.ipcMain.handle("open-file-url", (_event, fileUrl: string) => {+ const normalized = fileUrl.replace(/^file:\/\/(?=[a-zA-Z]:)/i, "file:///");+ return electron.shell.openPath(url.fileURLToPath(normalized));+});+electron.ipcMain.on("navigation-history", (event, method: string) => {const wc = event.sender;switch (method) {