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 desktop startup
Elian Doran7b5dc95131ae
diff --git a/apps/client/src/desktop.ts b/apps/client/src/desktop.tsindex bb1f859809..4bec4d3e90 100644--- a/apps/client/src/desktop.ts+++ b/apps/client/src/desktop.ts@@ -1,8 +1,5 @@import "autocomplete.js/index_jquery.js";-import type ElectronRemote from "@electron/remote";-import type Electron from "electron";-import appContext from "./components/app_context.js";import electronContextMenu from "./menus/electron_context_menu.js";import bundleService from "./services/bundle.js";@@ -47,32 +44,32 @@ if (utils.isElectron()) {}function initOnElectron() {- const electron: typeof Electron = utils.dynamicRequire("electron");- electron.ipcRenderer.on("globalShortcut", async (event, actionName) => appContext.triggerCommand(actionName));- electron.ipcRenderer.on("openInSameTab", async (event, noteId) => appContext.tabManager.openInSameTab(noteId));- const electronRemote: typeof ElectronRemote = utils.dynamicRequire("@electron/remote");- const currentWindow = electronRemote.getCurrentWindow();+ const api = window.electronApi!;++ api.onGlobalShortcut(async (actionName) => appContext.triggerCommand(actionName));+ api.onOpenInSameTab(async (noteId) => appContext.tabManager.openInSameTab(noteId));+const style = window.getComputedStyle(document.body);initDarkOrLightMode();- initTransparencyEffects(style, currentWindow);- initFullScreenDetection(currentWindow);+ initTransparencyEffects(style);+ initFullScreenDetection();if (options.get("nativeTitleBarVisible") !== "true") {- initTitleBarButtons(style, currentWindow);+ initTitleBarButtons(style);}// Clear navigation history on frontend refresh.- currentWindow.webContents.navigationHistory.clear();+ api.clearNavigationHistory();}-function initTitleBarButtons(style: CSSStyleDeclaration, currentWindow: Electron.BrowserWindow) {+function initTitleBarButtons(style: CSSStyleDeclaration) {if (window.glob.platform === "win32") {const applyWindowsOverlay = () => {const color = style.getPropertyValue("--native-titlebar-background");const symbolColor = style.getPropertyValue("--native-titlebar-foreground");if (color && symbolColor) {- currentWindow.setTitleBarOverlay({ color, symbolColor });+ window.electronApi!.setTitleBarOverlay({ color, symbolColor });}};@@ -85,22 +82,22 @@ function initTitleBarButtons(style: CSSStyleDeclaration, currentWindow: Electronif (window.glob.platform === "darwin") {const xOffset = parseInt(style.getPropertyValue("--native-titlebar-darwin-x-offset"), 10);const yOffset = parseInt(style.getPropertyValue("--native-titlebar-darwin-y-offset"), 10);- currentWindow.setWindowButtonPosition({ x: xOffset, y: yOffset });+ window.electronApi!.setWindowButtonPosition({ x: xOffset, y: yOffset });}}-function initFullScreenDetection(currentWindow: Electron.BrowserWindow) {- currentWindow.on("enter-full-screen", () => document.body.classList.add("full-screen"));- currentWindow.on("leave-full-screen", () => document.body.classList.remove("full-screen"));+function initFullScreenDetection() {+ window.electronApi!.onEnterFullScreen(() => document.body.classList.add("full-screen"));+ window.electronApi!.onLeaveFullScreen(() => document.body.classList.remove("full-screen"));}-function initTransparencyEffects(style: CSSStyleDeclaration, currentWindow: Electron.BrowserWindow) {+function initTransparencyEffects(style: CSSStyleDeclaration) {const material = style.getPropertyValue("--background-material").trim();if (window.glob.platform === "win32") {const bgMaterialOptions = ["auto", "none", "mica", "acrylic", "tabbed"] as const;const foundBgMaterialOption = bgMaterialOptions.find((bgMaterialOption) => material === bgMaterialOption);if (foundBgMaterialOption) {- currentWindow.setBackgroundMaterial(foundBgMaterialOption);+ window.electronApi!.setBackgroundMaterial(foundBgMaterialOption);}}@@ -108,7 +105,7 @@ function initTransparencyEffects(style: CSSStyleDeclaration, currentWindow: Elecconst bgMaterialOptions = [ "popover", "tooltip", "titlebar", "selection", "menu", "sidebar", "header", "sheet", "window", "hud", "fullscreen-ui", "content", "under-window", "under-page" ] as const;const foundBgMaterialOption = bgMaterialOptions.find((bgMaterialOption) => material === bgMaterialOption);if (foundBgMaterialOption) {- currentWindow.setVibrancy(foundBgMaterialOption);+ window.electronApi!.setVibrancy(foundBgMaterialOption);}}}@@ -116,17 +113,14 @@ function initTransparencyEffects(style: CSSStyleDeclaration, currentWindow: Elec/*** Informs Electron that we prefer a dark or light theme. Apart from changing prefers-color-scheme at CSS level which is a side effect,* this fixes color issues with background effects or native title bars.- *- * @param style the root CSS element to read variables from.*/function initDarkOrLightMode() {- let themeSource: typeof nativeTheme.themeSource = "system";+ let themeSource: "system" | "light" | "dark" = "system";const themeStyle = window.glob.getThemeStyle();if (themeStyle !== "auto") {themeSource = themeStyle;}- const { nativeTheme } = utils.dynamicRequire("@electron/remote") as typeof ElectronRemote;- nativeTheme.themeSource = themeSource;+ window.electronApi!.setNativeThemeSource(themeSource);}diff --git a/apps/client/src/types.d.ts b/apps/client/src/types.d.tsindex a797c33855..87c645b878 100644--- a/apps/client/src/types.d.ts+++ b/apps/client/src/types.d.ts@@ -63,6 +63,16 @@ declare global {interface ElectronApi {setZoomFactor(factor: number): void;getZoomFactor(): number;+ onGlobalShortcut(callback: (actionName: string) => void): void;+ onOpenInSameTab(callback: (noteId: string) => void): void;+ setTitleBarOverlay(options: { color: string; symbolColor: string }): void;+ setWindowButtonPosition(position: { x: number; y: number }): void;+ onEnterFullScreen(callback: () => void): void;+ onLeaveFullScreen(callback: () => void): void;+ setBackgroundMaterial(material: string): void;+ setVibrancy(vibrancy: string): void;+ clearNavigationHistory(): void;+ setNativeThemeSource(source: "system" | "light" | "dark"): void;}interface WindowEventMap {diff --git a/apps/desktop/spec/preload.spec.ts b/apps/desktop/spec/preload.spec.tsindex 244f90ede9..8044ca9c1d 100644--- a/apps/desktop/spec/preload.spec.ts+++ b/apps/desktop/spec/preload.spec.ts@@ -1,13 +1,14 @@import { beforeEach, describe, expect, it, vi } from "vitest";-// Mock the electron module before importing the preload script.-let exposedApi: Record<string, unknown> = {};+let exposedApi: Record<string, Record<string, unknown>> = {};let mockZoomFactor = 1.0;+const ipcRendererListeners = new Map<string, Function[]>();+const ipcRendererSent: Array<{ channel: string; args: unknown[] }> = [];vi.mock("electron", () => ({contextBridge: {exposeInMainWorld(apiKey: string, api: Record<string, unknown>) {- exposedApi = { [apiKey]: api };+ exposedApi[apiKey] = api;}},webFrame: {@@ -17,15 +18,29 @@ vi.mock("electron", () => ({getZoomFactor() {return mockZoomFactor;}+ },+ ipcRenderer: {+ on(channel: string, listener: Function) {+ const listeners = ipcRendererListeners.get(channel) ?? [];+ listeners.push(listener);+ ipcRendererListeners.set(channel, listeners);+ },+ send(channel: string, ...args: unknown[]) {+ ipcRendererSent.push({ channel, args });+ }}}));+function getApi() {+ return exposedApi.electronApi as Record<string, Function>;+}+describe("preload script", () => {beforeEach(async () => {exposedApi = {};mockZoomFactor = 1.0;-- // Re-import to trigger contextBridge.exposeInMainWorld.+ ipcRendererListeners.clear();+ ipcRendererSent.length = 0;vi.resetModules();await import("../src/preload.js");});@@ -34,15 +49,107 @@ describe("preload script", () => {expect(exposedApi).toHaveProperty("electronApi");});- it("electronApi.setZoomFactor delegates to webFrame", () => {- const api = exposedApi.electronApi as { setZoomFactor(f: number): void };- api.setZoomFactor(1.5);- expect(mockZoomFactor).toBe(1.5);+ describe("zoom", () => {+ it("setZoomFactor delegates to webFrame", () => {+ getApi().setZoomFactor(1.5);+ expect(mockZoomFactor).toBe(1.5);+ });++ it("getZoomFactor delegates to webFrame", () => {+ mockZoomFactor = 0.8;+ expect(getApi().getZoomFactor()).toBe(0.8);+ });+ });++ describe("IPC listeners", () => {+ it("onGlobalShortcut registers and forwards globalShortcut channel", () => {+ const callback = vi.fn();+ getApi().onGlobalShortcut(callback);++ const listeners = ipcRendererListeners.get("globalShortcut")!;+ expect(listeners).toHaveLength(1);+ listeners[0]({}, "toggleNoteHoisting");+ expect(callback).toHaveBeenCalledWith("toggleNoteHoisting");+ });++ it("onOpenInSameTab registers and forwards openInSameTab channel", () => {+ const callback = vi.fn();+ getApi().onOpenInSameTab(callback);++ const listeners = ipcRendererListeners.get("openInSameTab")!;+ expect(listeners).toHaveLength(1);+ listeners[0]({}, "abc123");+ expect(callback).toHaveBeenCalledWith("abc123");+ });++ it("onEnterFullScreen registers and forwards enter-full-screen channel", () => {+ const callback = vi.fn();+ getApi().onEnterFullScreen(callback);++ const listeners = ipcRendererListeners.get("enter-full-screen")!;+ expect(listeners).toHaveLength(1);+ listeners[0]();+ expect(callback).toHaveBeenCalled();+ });++ it("onLeaveFullScreen registers and forwards leave-full-screen channel", () => {+ const callback = vi.fn();+ getApi().onLeaveFullScreen(callback);++ const listeners = ipcRendererListeners.get("leave-full-screen")!;+ expect(listeners).toHaveLength(1);+ listeners[0]();+ expect(callback).toHaveBeenCalled();+ });});- it("electronApi.getZoomFactor delegates to webFrame", () => {- mockZoomFactor = 0.8;- const api = exposedApi.electronApi as { getZoomFactor(): number };- expect(api.getZoomFactor()).toBe(0.8);+ describe("window management IPC senders", () => {+ it("setTitleBarOverlay sends correct IPC message", () => {+ getApi().setTitleBarOverlay({ color: "#fff", symbolColor: "#000" });+ expect(ipcRendererSent).toContainEqual({+ channel: "set-title-bar-overlay",+ args: [{ color: "#fff", symbolColor: "#000" }]+ });+ });++ it("setWindowButtonPosition sends correct IPC message", () => {+ getApi().setWindowButtonPosition({ x: 10, y: 20 });+ expect(ipcRendererSent).toContainEqual({+ channel: "set-window-button-position",+ args: [{ x: 10, y: 20 }]+ });+ });++ it("setBackgroundMaterial sends correct IPC message", () => {+ getApi().setBackgroundMaterial("mica");+ expect(ipcRendererSent).toContainEqual({+ channel: "set-background-material",+ args: ["mica"]+ });+ });++ it("setVibrancy sends correct IPC message", () => {+ getApi().setVibrancy("under-window");+ expect(ipcRendererSent).toContainEqual({+ channel: "set-vibrancy",+ args: ["under-window"]+ });+ });++ it("clearNavigationHistory sends correct IPC message", () => {+ getApi().clearNavigationHistory();+ expect(ipcRendererSent).toContainEqual({+ channel: "clear-navigation-history",+ args: []+ });+ });++ it("setNativeThemeSource sends correct IPC message", () => {+ getApi().setNativeThemeSource("dark");+ expect(ipcRendererSent).toContainEqual({+ channel: "set-native-theme-source",+ args: ["dark"]+ });+ });});});diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.tsindex 07ad4b2740..eb12e45a09 100644--- a/apps/desktop/src/preload.ts+++ b/apps/desktop/src/preload.ts@@ -1,10 +1,47 @@-import { contextBridge, webFrame } from "electron";+import { contextBridge, ipcRenderer, webFrame } from "electron";contextBridge.exposeInMainWorld("electronApi", {+ // ZoomsetZoomFactor(factor: number) {webFrame.setZoomFactor(factor);},getZoomFactor(): number {return webFrame.getZoomFactor();+ },++ // IPC: main → renderer (whitelisted channels only)+ onGlobalShortcut(callback: (actionName: string) => void) {+ ipcRenderer.on("globalShortcut", (_event, actionName) => callback(actionName));+ },+ onOpenInSameTab(callback: (noteId: string) => void) {+ ipcRenderer.on("openInSameTab", (_event, noteId) => callback(noteId));+ },++ // Window management (forwarded to main process via IPC)+ setTitleBarOverlay(options: { color: string; symbolColor: string }) {+ ipcRenderer.send("set-title-bar-overlay", options);+ },+ setWindowButtonPosition(position: { x: number; y: number }) {+ ipcRenderer.send("set-window-button-position", position);+ },+ onEnterFullScreen(callback: () => void) {+ ipcRenderer.on("enter-full-screen", () => callback());+ },+ onLeaveFullScreen(callback: () => void) {+ ipcRenderer.on("leave-full-screen", () => callback());+ },+ setBackgroundMaterial(material: string) {+ ipcRenderer.send("set-background-material", material);+ },+ setVibrancy(vibrancy: string) {+ ipcRenderer.send("set-vibrancy", vibrancy);+ },+ clearNavigationHistory() {+ ipcRenderer.send("clear-navigation-history");+ },++ // Theme+ setNativeThemeSource(source: "system" | "light" | "dark") {+ ipcRenderer.send("set-native-theme-source", source);}});diff --git a/apps/server/src/services/window.ts b/apps/server/src/services/window.tsindex 1429620e7c..019086a9a6 100644--- a/apps/server/src/services/window.ts+++ b/apps/server/src/services/window.ts@@ -88,6 +88,33 @@ electron.ipcMain.on("add-word-to-dictionary", (event, word: string) => {customDictionary.addWord(word);});+// Window management IPC handlers (replacing @electron/remote for renderer access)+electron.ipcMain.on("set-title-bar-overlay", (event, options: { color: string; symbolColor: string }) => {+ electron.BrowserWindow.fromWebContents(event.sender)?.setTitleBarOverlay(options);+});++electron.ipcMain.on("set-window-button-position", (event, position: { x: number; y: number }) => {+ electron.BrowserWindow.fromWebContents(event.sender)?.setWindowButtonPosition(position);+});++electron.ipcMain.on("set-background-material", (event, material: string) => {+ const win = electron.BrowserWindow.fromWebContents(event.sender);+ win?.setBackgroundMaterial(material as Parameters<typeof win.setBackgroundMaterial>[0]);+});++electron.ipcMain.on("set-vibrancy", (event, vibrancy: string) => {+ const win = electron.BrowserWindow.fromWebContents(event.sender);+ win?.setVibrancy(vibrancy as Parameters<typeof win.setVibrancy>[0]);+});++electron.ipcMain.on("clear-navigation-history", (event) => {+ electron.BrowserWindow.fromWebContents(event.sender)?.webContents.navigationHistory.clear();+});++electron.ipcMain.on("set-native-theme-source", (_event, source: "system" | "light" | "dark") => {+ electron.nativeTheme.themeSource = source;+});+initPrintingHandlers();async function createMainWindow(app: App) {@@ -206,6 +233,13 @@ async function configureWebContents(webContents: WebContents, spellcheckEnabled:if (spellcheckEnabled) {setupSpellcheckForSession(webContents.session);}++ // Forward full-screen events to the renderer via IPC.+ const win = electron.BrowserWindow.fromWebContents(webContents);+ if (win) {+ win.on("enter-full-screen", () => webContents.send("enter-full-screen"));+ win.on("leave-full-screen", () => webContents.send("leave-full-screen"));+ }}function setupSpellcheckForSession(session: Session) {