Skip to content

Build your personal knowledge base with Trilium Notes

refactor(electron): group Electron API

Elian Doran1020448f4660
diff --git a/apps/client/src/components/entrypoints.ts b/apps/client/src/components/entrypoints.ts
index ac464e3c4a..249bd95e4d 100644
--- a/apps/client/src/components/entrypoints.ts
+++ b/apps/client/src/components/entrypoints.ts
@@ -20,7 +20,7 @@ export default class Entrypoints extends Component {
}
openDevToolsCommand() {
- window.electronApi?.toggleDevTools();
+ window.electronApi?.window.toggleDevTools();
}
async createNoteIntoInboxCommand() {
@@ -85,7 +85,7 @@ export default class Entrypoints extends Component {
}
toggleFullscreenCommand() {
- const api = window.electronApi;
+ const api = window.electronApi?.window;
if (api) {
api.setFullScreen(!api.isFullScreen());
} else {
@@ -103,7 +103,7 @@ export default class Entrypoints extends Component {
}
backInNoteHistoryCommand() {
- const api = window.electronApi;
+ const api = window.electronApi?.navigation;
if (api) {
const activeIndex = api.navigationGetActiveIndex();
api.navigationGoToIndex(activeIndex - 1);
@@ -113,7 +113,7 @@ export default class Entrypoints extends Component {
}
forwardInNoteHistoryCommand() {
- const api = window.electronApi;
+ const api = window.electronApi?.navigation;
if (api) {
const activeIndex = api.navigationGetActiveIndex();
api.navigationGoToIndex(activeIndex + 1);
@@ -138,7 +138,7 @@ export default class Entrypoints extends Component {
const extraWindowHash = linkService.calculateHash({ notePath, hoistedNoteId, viewScope });
if (window.electronApi) {
- window.electronApi.createExtraWindow(extraWindowHash);
+ window.electronApi.window.createExtraWindow(extraWindowHash);
} else {
const url = `${window.location.protocol}//${window.location.host}${window.location.pathname}?extraWindow=1${extraWindowHash}`;
diff --git a/apps/client/src/components/zoom.ts b/apps/client/src/components/zoom.ts
index 5386754146..633d703bb9 100644
--- a/apps/client/src/components/zoom.ts
+++ b/apps/client/src/components/zoom.ts
@@ -27,7 +27,7 @@ class ZoomComponent extends Component {
setZoomFactor(zoomFactor: string | number) {
const parsedZoomFactor = typeof zoomFactor !== "number" ? parseFloat(zoomFactor) : zoomFactor;
- window.electronApi?.setZoomFactor(parsedZoomFactor);
+ window.electronApi?.window.setZoomFactor(parsedZoomFactor);
}
async setZoomFactorAndSave(zoomFactor: number) {
@@ -43,7 +43,7 @@ class ZoomComponent extends Component {
}
getCurrentZoom() {
- return window.electronApi?.getZoomFactor() ?? 1.0;
+ return window.electronApi?.window.getZoomFactor() ?? 1.0;
}
zoomOutEvent() {
diff --git a/apps/client/src/desktop.ts b/apps/client/src/desktop.ts
index d8f2ca8341..263495dc32 100644
--- a/apps/client/src/desktop.ts
+++ b/apps/client/src/desktop.ts
@@ -1,5 +1,7 @@
import "autocomplete.js/index_jquery.js";
+import type { ElectronWindowApi } from "@triliumnext/commons";
+
import appContext from "./components/app_context.js";
import electronContextMenu from "./menus/electron_context_menu.js";
import bundleService from "./services/bundle.js";
@@ -47,30 +49,31 @@ function initOnElectron() {
const api = window.electronApi;
if (!api) return;
- api.onGlobalShortcut(async (actionName) => appContext.triggerCommand(actionName));
- api.onOpenInSameTab(async (noteId) => appContext.tabManager.openInSameTab(noteId));
+ const win = api.window;
+ win.onGlobalShortcut(async (actionName) => appContext.triggerCommand(actionName));
+ win.onOpenInSameTab(async (noteId) => appContext.tabManager.openInSameTab(noteId));
const style = window.getComputedStyle(document.body);
- initDarkOrLightMode(api);
- initTransparencyEffects(api, style);
- initFullScreenDetection(api);
+ initDarkOrLightMode(win);
+ initTransparencyEffects(win, style);
+ initFullScreenDetection(win);
if (options.get("nativeTitleBarVisible") !== "true") {
- initTitleBarButtons(api, style);
+ initTitleBarButtons(win, style);
}
// Clear navigation history on frontend refresh.
- api.clearNavigationHistory();
+ api.navigation.clearNavigationHistory();
}
-function initTitleBarButtons(api: ElectronApi, style: CSSStyleDeclaration) {
+function initTitleBarButtons(win: ElectronWindowApi, 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) {
- api.setTitleBarOverlay({ color, symbolColor });
+ win.setTitleBarOverlay({ color, symbolColor });
}
};
@@ -83,22 +86,22 @@ function initTitleBarButtons(api: ElectronApi, style: CSSStyleDeclaration) {
if (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);
- api.setWindowButtonPosition({ x: xOffset, y: yOffset });
+ win.setWindowButtonPosition({ x: xOffset, y: yOffset });
}
}
-function initFullScreenDetection(api: ElectronApi) {
- api.onEnterFullScreen(() => document.body.classList.add("full-screen"));
- api.onLeaveFullScreen(() => document.body.classList.remove("full-screen"));
+function initFullScreenDetection(win: ElectronWindowApi) {
+ win.onEnterFullScreen(() => document.body.classList.add("full-screen"));
+ win.onLeaveFullScreen(() => document.body.classList.remove("full-screen"));
}
-function initTransparencyEffects(api: ElectronApi, style: CSSStyleDeclaration) {
+function initTransparencyEffects(win: ElectronWindowApi, 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) {
- api.setBackgroundMaterial(foundBgMaterialOption);
+ win.setBackgroundMaterial(foundBgMaterialOption);
}
}
@@ -106,7 +109,7 @@ function initTransparencyEffects(api: ElectronApi, style: CSSStyleDeclaration) {
const 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) {
- api.setVibrancy(foundBgMaterialOption);
+ win.setVibrancy(foundBgMaterialOption);
}
}
}
@@ -115,7 +118,7 @@ function initTransparencyEffects(api: ElectronApi, style: CSSStyleDeclaration) {
* 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.
*/
-function initDarkOrLightMode(api: ElectronApi) {
+function initDarkOrLightMode(win: ElectronWindowApi) {
let themeSource: "system" | "light" | "dark" = "system";
const themeStyle = window.glob.getThemeStyle();
@@ -123,5 +126,5 @@ function initDarkOrLightMode(api: ElectronApi) {
themeSource = themeStyle;
}
- api.setNativeThemeSource(themeSource);
+ win.setNativeThemeSource(themeSource);
}
diff --git a/apps/client/src/menus/electron_context_menu.ts b/apps/client/src/menus/electron_context_menu.ts
index b8cbc97ac9..e6e46f671e 100644
--- a/apps/client/src/menus/electron_context_menu.ts
+++ b/apps/client/src/menus/electron_context_menu.ts
@@ -9,8 +9,9 @@ import utils from "../services/utils.js";
import contextMenu, { type MenuItem } from "./context_menu.js";
function setupContextMenu() {
- const api = window.electronApi;
- if (!api) return;
+ const eApi = window.electronApi;
+ if (!eApi) return;
+ const api = eApi.contextMenu;
const isMac = window.glob.platform === "darwin";
const platformModifier = isMac ? "Meta" : "Ctrl";
@@ -33,7 +34,7 @@ function setupContextMenu() {
items.push({
title: t("electron_context_menu.add-term-to-dictionary", { term: params.misspelledWord }),
uiIcon: "bx bx-plus",
- handler: () => api.addWordToDictionary(params.misspelledWord)
+ handler: () => eApi.spellcheck.addWordToDictionary(params.misspelledWord)
});
items.push({ kind: "separator" });
@@ -145,7 +146,7 @@ function setupContextMenu() {
items.push({
title: t("electron_context_menu.search_online", { term: shortenedSelection, searchEngine: searchEngineName }),
uiIcon: "bx bx-search-alt",
- handler: () => api.openExternal(searchUrl)
+ handler: () => eApi.shell.openExternal(searchUrl)
});
items.push({
diff --git a/apps/client/src/print.tsx b/apps/client/src/print.tsx
index 6a6645f5ac..d3f0819e02 100644
--- a/apps/client/src/print.tsx
+++ b/apps/client/src/print.tsx
@@ -58,7 +58,7 @@ function App({ note, noteId }: { note: FNote | null | undefined, noteId: string
const sentReadyEvent = useRef(false);
const onProgressChanged = useCallback((progress: number) => {
if (window.electronApi) {
- window.electronApi.sendPrintProgress(progress);
+ window.electronApi.printing.sendPrintProgress(progress);
} else {
window.dispatchEvent(new CustomEvent("note-load-progress", { detail: { progress } }));
}
diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.ts
index 75f990a7b8..5a1bb8bbbc 100644
--- a/apps/client/src/services/content_renderer.ts
+++ b/apps/client/src/services/content_renderer.ts
@@ -101,7 +101,7 @@ export async function getRenderedContent(this: {} | { ctx: string }, entity: FNo
const webViewSrc = entity.getLabelValue("webViewSrc");
if (webViewSrc) {
if (window.electronApi) {
- window.electronApi.openExternal(webViewSrc);
+ window.electronApi.shell.openExternal(webViewSrc);
} else {
window.open(webViewSrc, '_blank', 'noopener,noreferrer');
}
diff --git a/apps/client/src/services/link.ts b/apps/client/src/services/link.ts
index b7de937114..421133b2b7 100644
--- a/apps/client/src/services/link.ts
+++ b/apps/client/src/services/link.ts
@@ -349,11 +349,11 @@ export function goToLinkExt(evt: MouseEvent | JQuery.ClickEvent | JQuery.MouseDo
if (hrefLink.toLowerCase().startsWith("file:")) {
// shell.openExternal mishandles Unicode file:// URLs on Windows;
// convert to a filesystem path and use shell.openPath instead.
- window.electronApi.openFileUrl(hrefLink).then((err: string) => {
+ window.electronApi.shell.openFileUrl(hrefLink).then((err: string) => {
if (err) reportLinkError(new Error(err));
}).catch(reportLinkError);
} else {
- window.electronApi.openExternal(hrefLink);
+ window.electronApi.shell.openExternal(hrefLink);
}
} else {
window.open(hrefLink, "_blank");
diff --git a/apps/client/src/services/open.ts b/apps/client/src/services/open.ts
index f8a2e3d863..e8500d6cdb 100644
--- a/apps/client/src/services/open.ts
+++ b/apps/client/src/services/open.ts
@@ -157,7 +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 res = await window.electronApi?.openPath(resp.tmpFilePath);
+ const res = await window.electronApi?.shell.openPath(resp.tmpFilePath);
if (res) {
// fallback in case there's no default application for this file
@@ -199,7 +199,7 @@ async function openNoteOnServer(noteId: string) {
async function openDirectory(directory: string) {
try {
if (utils.isElectron()) {
- const res = await window.electronApi?.openPath(directory);
+ const res = await window.electronApi?.shell.openPath(directory);
if (res) {
console.error("Failed to open directory:", res);
}
diff --git a/apps/client/src/services/utils.ts b/apps/client/src/services/utils.ts
index b37cf030cc..2deec805f5 100644
--- a/apps/client/src/services/utils.ts
+++ b/apps/client/src/services/utils.ts
@@ -39,7 +39,7 @@ export function restartDesktopApp() {
* On any other platform than Electron, nothing happens.
*/
function reloadTray() {
- window.electronApi?.reloadTray();
+ window.electronApi?.tray.reloadTray();
}
function parseDate(str: string) {
diff --git a/apps/client/src/widgets/NoteDetail.tsx b/apps/client/src/widgets/NoteDetail.tsx
index 846c39e6ad..13022e80a3 100644
--- a/apps/client/src/widgets/NoteDetail.tsx
+++ b/apps/client/src/widgets/NoteDetail.tsx
@@ -140,7 +140,7 @@ export default function NoteDetail() {
// Handle toast notifications.
useEffect(() => {
- const api = window.electronApi;
+ const api = window.electronApi?.printing;
if (!api) return;
api.onPrintProgress(({ progress, action }) => showToast(action as "printing" | "exporting_pdf", progress));
api.onPrintDone((printReport) => {
diff --git a/apps/client/src/widgets/TabHistoryNavigationButtons.tsx b/apps/client/src/widgets/TabHistoryNavigationButtons.tsx
index 75a51af50c..493d00c41f 100644
--- a/apps/client/src/widgets/TabHistoryNavigationButtons.tsx
+++ b/apps/client/src/widgets/TabHistoryNavigationButtons.tsx
@@ -36,11 +36,11 @@ export default function TabHistoryNavigationButtons() {
}
function useBackForwardState(hasApi: boolean | ElectronApi | undefined) {
- const [ canGoBack, setCanGoBack ] = useState(() => hasApi ? window.electronApi?.navigationCanGoBack() ?? true : true);
- const [ canGoForward, setCanGoForward ] = useState(() => hasApi ? window.electronApi?.navigationCanGoForward() ?? true : true);
+ const [ canGoBack, setCanGoBack ] = useState(() => hasApi ? window.electronApi?.navigation.navigationCanGoBack() ?? true : true);
+ const [ canGoForward, setCanGoForward ] = useState(() => hasApi ? window.electronApi?.navigation.navigationCanGoForward() ?? true : true);
useEffect(() => {
- const api = window.electronApi;
+ const api = window.electronApi?.navigation;
if (!api) return;
const updateNavigationState = () => {
setCanGoBack(api.navigationCanGoBack());
diff --git a/apps/client/src/widgets/buttons/global_menu.tsx b/apps/client/src/widgets/buttons/global_menu.tsx
index 80a246e618..711c28d8e2 100644
--- a/apps/client/src/widgets/buttons/global_menu.tsx
+++ b/apps/client/src/widgets/buttons/global_menu.tsx
@@ -231,7 +231,7 @@ function ZoomControls({ parentComponent }: { parentComponent?: Component | null
}
function ToggleWindowOnTop() {
- const api = window.electronApi;
+ const api = window.electronApi?.window;
const [ isOnTop, setIsOnTop ] = useState(() => api?.isAlwaysOnTop() ?? false);
return (api &&
diff --git a/apps/client/src/widgets/dialogs/incorrect_cpu_arch.tsx b/apps/client/src/widgets/dialogs/incorrect_cpu_arch.tsx
index 1a601d9d17..588fa7cd47 100644
--- a/apps/client/src/widgets/dialogs/incorrect_cpu_arch.tsx
+++ b/apps/client/src/widgets/dialogs/incorrect_cpu_arch.tsx
@@ -26,7 +26,7 @@ export default function IncorrectCpuArchDialogComponent() {
onClick={() => {
// Open the releases page where users can download the correct version
if (window.electronApi) {
- window.electronApi.openExternal("https://github.com/TriliumNext/Trilium/releases/latest");
+ window.electronApi.shell.openExternal("https://github.com/TriliumNext/Trilium/releases/latest");
} else {
window.open("https://github.com/TriliumNext/Trilium/releases/latest", "_blank");
}
diff --git a/apps/client/src/widgets/dialogs/print_preview.tsx b/apps/client/src/widgets/dialogs/print_preview.tsx
index 9f710cc28a..3816bea543 100644
--- a/apps/client/src/widgets/dialogs/print_preview.tsx
+++ b/apps/client/src/widgets/dialogs/print_preview.tsx
@@ -115,7 +115,7 @@ export default function PrintPreviewDialog() {
const [destination, setDestination] = useState<string>(DESTINATION_PDF);
useEffect(() => {
- const api = window.electronApi;
+ const api = window.electronApi?.printing;
if (!shown || !api) return;
api.getPrinters().then((list) => {
const printerList = (list ?? []) as PrinterInfo[];
@@ -152,7 +152,7 @@ export default function PrintPreviewDialog() {
// dialog's lifecycle. A generation counter discards stale results when
// multiple requests overlap.
useEffect(() => {
- const api = window.electronApi;
+ const api = window.electronApi?.printing;
if (!shown || !api) return;
api.onExportAsPdfPreviewResult(({ buffer, error }) => {
@@ -182,7 +182,7 @@ export default function PrintPreviewDialog() {
}, [shown, updatePreview]);
const regeneratePreview = useCallback((opts: PreviewOpts) => {
- const api = window.electronApi;
+ const api = window.electronApi?.printing;
if (!api) return;
setLoading(true);
@@ -226,7 +226,7 @@ export default function PrintPreviewDialog() {
function handleExportPdf() {
if (!bufferRef.current) return;
- window.electronApi?.savePdf({
+ window.electronApi?.printing.savePdf({
title: note?.title ?? "",
buffer: bufferRef.current
});
@@ -234,7 +234,7 @@ export default function PrintPreviewDialog() {
}
function handlePrint(silent: boolean, deviceName?: string) {
- window.electronApi?.printFromPreview({
+ window.electronApi?.printing.printFromPreview({
notePath: notePathRef.current,
pageSize,
landscape,
diff --git a/apps/client/src/widgets/launch_bar/HistoryNavigation.tsx b/apps/client/src/widgets/launch_bar/HistoryNavigation.tsx
index 9e203c2bb6..8834654724 100644
--- a/apps/client/src/widgets/launch_bar/HistoryNavigation.tsx
+++ b/apps/client/src/widgets/launch_bar/HistoryNavigation.tsx
@@ -32,7 +32,7 @@ export default function HistoryNavigationButton({ launcherNote, command }: Histo
extraItems: items,
onCommand: (cmd) => {
if (cmd && hasApi) {
- window.electronApi?.navigationGoToIndex(parseInt(cmd, 10));
+ window.electronApi?.navigation.navigationGoToIndex(parseInt(cmd, 10));
}
}
});
@@ -42,7 +42,7 @@ export default function HistoryNavigationButton({ launcherNote, command }: Histo
}
async function getHistoryItems(): Promise<MenuCommandItem<string>[]> {
- const api = window.electronApi;
+ const api = window.electronApi?.navigation;
if (!api || api.navigationLength() < 2) return [];
let items: MenuCommandItem<string>[] = [];
@@ -90,7 +90,7 @@ export function handleHistoryContextMenu() {
selectMenuItemHandler: (item: MenuCommandItem<string>) => {
if (item && item.command) {
const idx = parseInt(item.command, 10);
- window.electronApi?.navigationGoToIndex(idx);
+ window.electronApi?.navigation.navigationGoToIndex(idx);
}
}
});
diff --git a/apps/client/src/widgets/title_bar_buttons.tsx b/apps/client/src/widgets/title_bar_buttons.tsx
index 84bb407b37..ae4ce4cba7 100644
--- a/apps/client/src/widgets/title_bar_buttons.tsx
+++ b/apps/client/src/widgets/title_bar_buttons.tsx
@@ -19,14 +19,14 @@ export default function TitleBarButtons() {
<TitleBarButton
className="minimize-btn"
icon="bx bx-minus"
- onClick={() => window.electronApi?.minimizeWindow()}
+ onClick={() => window.electronApi?.window.minimizeWindow()}
/>
<TitleBarButton
className="maximize-btn"
icon="bx bx-checkbox"
onClick={() => {
- const api = window.electronApi;
+ const api = window.electronApi?.window;
if (!api) return;
if (api.isMaximized()) {
api.unmaximizeWindow();
@@ -39,7 +39,7 @@ export default function TitleBarButtons() {
<TitleBarButton
className="close-btn"
icon="bx bx-x"
- onClick={() => window.electronApi?.closeWindow()}
+ onClick={() => window.electronApi?.window.closeWindow()}
/>
</>
)}
diff --git a/apps/client/src/widgets/type_widgets/options/spellcheck.tsx b/apps/client/src/widgets/type_widgets/options/spellcheck.tsx
index db16a9c084..7e1daae3b4 100644
--- a/apps/client/src/widgets/type_widgets/options/spellcheck.tsx
+++ b/apps/client/src/widgets/type_widgets/options/spellcheck.tsx
@@ -70,7 +70,7 @@ function SpellcheckLanguages() {
}, [setSpellCheckLanguageCode]);
const availableLanguages = useMemo<SpellcheckLanguage[]>(() => {
- const api = window.electronApi;
+ const api = window.electronApi?.spellcheck;
if (!api) {
return [];
}
diff --git a/apps/desktop/spec/preload.spec.ts b/apps/desktop/spec/preload.spec.ts
index 9b1441c4e3..197351423a 100644
--- a/apps/desktop/spec/preload.spec.ts
+++ b/apps/desktop/spec/preload.spec.ts
@@ -43,8 +43,8 @@ vi.mock("electron", () => ({
}
}));
-function getApi() {
- return exposedApi.electronApi as Record<string, Function>;
+function getGroup(name: string) {
+ return (exposedApi.electronApi as Record<string, Record<string, Function>>)[name];
}
describe("preload script", () => {
@@ -63,43 +63,46 @@ describe("preload script", () => {
expect(exposedApi).toHaveProperty("electronApi");
});
- describe("zoom", () => {
+ describe("window", () => {
+ const win = () => getGroup("window");
+
it("setZoomFactor delegates to webFrame", () => {
- getApi().setZoomFactor(1.5);
+ win().setZoomFactor(1.5);
expect(mockZoomFactor).toBe(1.5);
});
it("getZoomFactor delegates to webFrame", () => {
mockZoomFactor = 0.8;
- expect(getApi().getZoomFactor()).toBe(0.8);
+ expect(win().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("setNativeThemeSource sends correct IPC message", () => {
+ win().setNativeThemeSource("dark");
+ expect(ipcRendererSent).toContainEqual({
+ channel: "set-native-theme-source",
+ args: ["dark"]
+ });
});
- it("onOpenInSameTab registers and forwards openInSameTab channel", () => {
- const callback = vi.fn();
- getApi().onOpenInSameTab(callback);
+ it("setTitleBarOverlay sends correct IPC message", () => {
+ win().setTitleBarOverlay({ color: "#fff", symbolColor: "#000" });
+ expect(ipcRendererSent).toContainEqual({
+ channel: "set-title-bar-overlay",
+ args: [{ color: "#fff", symbolColor: "#000" }]
+ });
+ });
- const listeners = ipcRendererListeners.get("openInSameTab")!;
- expect(listeners).toHaveLength(1);
- listeners[0]({}, "abc123");
- expect(callback).toHaveBeenCalledWith("abc123");
+ it("setWindowButtonPosition sends correct IPC message", () => {
+ win().setWindowButtonPosition({ x: 10, y: 20 });
+ expect(ipcRendererSent).toContainEqual({
+ channel: "set-window-button-position",
+ args: [{ x: 10, y: 20 }]
+ });
});
it("onEnterFullScreen registers and forwards enter-full-screen channel", () => {
const callback = vi.fn();
- getApi().onEnterFullScreen(callback);
-
+ win().onEnterFullScreen(callback);
const listeners = ipcRendererListeners.get("enter-full-screen")!;
expect(listeners).toHaveLength(1);
listeners[0]();
@@ -108,191 +111,163 @@ describe("preload script", () => {
it("onLeaveFullScreen registers and forwards leave-full-screen channel", () => {
const callback = vi.fn();
- getApi().onLeaveFullScreen(callback);
-
+ win().onLeaveFullScreen(callback);
const listeners = ipcRendererListeners.get("leave-full-screen")!;
expect(listeners).toHaveLength(1);
listeners[0]();
expect(callback).toHaveBeenCalled();
});
- });
- 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("isFullScreen uses sendSync", () => {
+ ipcRendererSyncResults.set("is-full-screen:undefined", true);
+ expect(win().isFullScreen()).toBe(true);
});
- it("setWindowButtonPosition sends correct IPC message", () => {
- getApi().setWindowButtonPosition({ x: 10, y: 20 });
+ it("setFullScreen sends correct IPC message", () => {
+ win().setFullScreen(true);
expect(ipcRendererSent).toContainEqual({
- channel: "set-window-button-position",
- args: [{ x: 10, y: 20 }]
+ channel: "set-full-screen",
+ args: [true]
});
});
- it("setBackgroundMaterial sends correct IPC message", () => {
- getApi().setBackgroundMaterial("mica");
- expect(ipcRendererSent).toContainEqual({
- channel: "set-background-material",
- args: ["mica"]
- });
+ it("minimizeWindow sends correct IPC message", () => {
+ win().minimizeWindow();
+ expect(ipcRendererSent).toContainEqual({ channel: "minimize-window", args: [] });
});
- it("setVibrancy sends correct IPC message", () => {
- getApi().setVibrancy("under-window");
- expect(ipcRendererSent).toContainEqual({
- channel: "set-vibrancy",
- args: ["under-window"]
- });
+ it("maximizeWindow sends correct IPC message", () => {
+ win().maximizeWindow();
+ expect(ipcRendererSent).toContainEqual({ channel: "maximize-window", args: [] });
});
- it("clearNavigationHistory sends correct IPC message", () => {
- getApi().clearNavigationHistory();
- expect(ipcRendererSent).toContainEqual({
- channel: "clear-navigation-history",
- args: []
- });
+ it("unmaximizeWindow sends correct IPC message", () => {
+ win().unmaximizeWindow();
+ expect(ipcRendererSent).toContainEqual({ channel: "unmaximize-window", args: [] });
});
- it("setNativeThemeSource sends correct IPC message", () => {
- getApi().setNativeThemeSource("dark");
- expect(ipcRendererSent).toContainEqual({
- channel: "set-native-theme-source",
- args: ["dark"]
- });
+ it("isMaximized uses sendSync", () => {
+ ipcRendererSyncResults.set("is-maximized:undefined", true);
+ expect(win().isMaximized()).toBe(true);
});
- 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("closeWindow sends correct IPC message", () => {
+ win().closeWindow();
+ expect(ipcRendererSent).toContainEqual({ channel: "close-window", args: [] });
});
- it("openExternal sends correct IPC message", () => {
- getApi().openExternal("https://example.com");
+ it("createExtraWindow sends correct IPC message", () => {
+ win().createExtraWindow("#root/abc123");
expect(ipcRendererSent).toContainEqual({
- channel: "open-external",
- args: ["https://example.com"]
+ channel: "create-extra-window",
+ args: [{ extraWindowHash: "#root/abc123" }]
});
});
- it("openPath invokes correct IPC channel", async () => {
- await getApi().openPath("/tmp/test.txt");
- expect(ipcRendererInvoked).toContainEqual({
- channel: "open-path",
- args: ["/tmp/test.txt"]
- });
+ it("isAlwaysOnTop uses sendSync", () => {
+ ipcRendererSyncResults.set("is-always-on-top:undefined", true);
+ expect(win().isAlwaysOnTop()).toBe(true);
});
- 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("setAlwaysOnTop sends correct IPC message", () => {
+ win().setAlwaysOnTop(true);
+ expect(ipcRendererSent).toContainEqual({ channel: "set-always-on-top", args: [true] });
});
it("toggleDevTools sends correct IPC message", () => {
- getApi().toggleDevTools();
- expect(ipcRendererSent).toContainEqual({
- channel: "toggle-dev-tools",
- args: []
- });
+ win().toggleDevTools();
+ expect(ipcRendererSent).toContainEqual({ channel: "toggle-dev-tools", args: [] });
});
- it("isFullScreen uses sendSync", () => {
- ipcRendererSyncResults.set("is-full-screen:undefined", true);
- expect(getApi().isFullScreen()).toBe(true);
+ it("setBackgroundMaterial sends correct IPC message", () => {
+ win().setBackgroundMaterial("mica");
+ expect(ipcRendererSent).toContainEqual({ channel: "set-background-material", args: ["mica"] });
});
- it("setFullScreen sends correct IPC message", () => {
- getApi().setFullScreen(true);
- expect(ipcRendererSent).toContainEqual({
- channel: "set-full-screen",
- args: [true]
- });
+ it("setVibrancy sends correct IPC message", () => {
+ win().setVibrancy("under-window");
+ expect(ipcRendererSent).toContainEqual({ channel: "set-vibrancy", args: ["under-window"] });
});
- it("minimizeWindow sends correct IPC message", () => {
- getApi().minimizeWindow();
- expect(ipcRendererSent).toContainEqual({
- channel: "minimize-window",
- args: []
- });
+ it("onGlobalShortcut registers and forwards globalShortcut channel", () => {
+ const callback = vi.fn();
+ win().onGlobalShortcut(callback);
+ const listeners = ipcRendererListeners.get("globalShortcut")!;
+ expect(listeners).toHaveLength(1);
+ listeners[0]({}, "toggleNoteHoisting");
+ expect(callback).toHaveBeenCalledWith("toggleNoteHoisting");
});
- it("maximizeWindow sends correct IPC message", () => {
- getApi().maximizeWindow();
- expect(ipcRendererSent).toContainEqual({
- channel: "maximize-window",
- args: []
- });
+ it("onOpenInSameTab registers and forwards openInSameTab channel", () => {
+ const callback = vi.fn();
+ win().onOpenInSameTab(callback);
+ const listeners = ipcRendererListeners.get("openInSameTab")!;
+ expect(listeners).toHaveLength(1);
+ listeners[0]({}, "abc123");
+ expect(callback).toHaveBeenCalledWith("abc123");
});
+ });
- it("unmaximizeWindow sends correct IPC message", () => {
- getApi().unmaximizeWindow();
+ describe("shell", () => {
+ const shell = () => getGroup("shell");
+
+ it("openExternal sends correct IPC message", () => {
+ shell().openExternal("https://example.com");
expect(ipcRendererSent).toContainEqual({
- channel: "unmaximize-window",
- args: []
+ channel: "open-external",
+ args: ["https://example.com"]
});
});
- it("isMaximized uses sendSync", () => {
- ipcRendererSyncResults.set("is-maximized:undefined", true);
- expect(getApi().isMaximized()).toBe(true);
- });
-
- it("closeWindow sends correct IPC message", () => {
- getApi().closeWindow();
- expect(ipcRendererSent).toContainEqual({
- channel: "close-window",
- args: []
+ it("openPath invokes correct IPC channel", async () => {
+ await shell().openPath("/tmp/test.txt");
+ expect(ipcRendererInvoked).toContainEqual({
+ channel: "open-path",
+ args: ["/tmp/test.txt"]
});
});
- it("createExtraWindow sends correct IPC message", () => {
- getApi().createExtraWindow("#root/abc123");
- expect(ipcRendererSent).toContainEqual({
- channel: "create-extra-window",
- args: [{ extraWindowHash: "#root/abc123" }]
+ it("openFileUrl invokes correct IPC channel", async () => {
+ await shell().openFileUrl("file:///tmp/test.txt");
+ expect(ipcRendererInvoked).toContainEqual({
+ channel: "open-file-url",
+ args: ["file:///tmp/test.txt"]
});
});
+ });
- it("isAlwaysOnTop uses sendSync", () => {
- ipcRendererSyncResults.set("is-always-on-top:undefined", true);
- expect(getApi().isAlwaysOnTop()).toBe(true);
+ describe("contextMenu", () => {
+ const ctx = () => getGroup("contextMenu");
+
+ it("onContextMenu registers and forwards context-menu channel", () => {
+ const callback = vi.fn();
+ ctx().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);
});
- it("setAlwaysOnTop sends correct IPC message", () => {
- getApi().setAlwaysOnTop(true);
+ it("webContentsAction sends action and optional text", () => {
+ ctx().webContentsAction("cut");
expect(ipcRendererSent).toContainEqual({
- channel: "set-always-on-top",
- args: [true]
+ channel: "web-contents-action",
+ args: ["cut", undefined]
});
- });
-
- it("reloadTray sends correct IPC message", () => {
- getApi().reloadTray();
+ ctx().webContentsAction("insertText", "hello");
expect(ipcRendererSent).toContainEqual({
- channel: "reload-tray",
- args: []
+ channel: "web-contents-action",
+ args: ["insertText", "hello"]
});
});
+ });
+
+ describe("spellcheck", () => {
+ const spell = () => getGroup("spellcheck");
it("addWordToDictionary sends correct IPC message", () => {
- getApi().addWordToDictionary("trilium");
+ spell().addWordToDictionary("trilium");
expect(ipcRendererSent).toContainEqual({
channel: "add-word-to-dictionary",
args: ["trilium"]
@@ -301,30 +276,30 @@ describe("preload script", () => {
it("getAvailableSpellCheckerLanguages uses sendSync", () => {
ipcRendererSyncResults.set("get-available-spellchecker-languages:undefined", ["en-US", "de-DE"]);
- const result = getApi().getAvailableSpellCheckerLanguages();
- expect(result).toEqual(["en-US", "de-DE"]);
+ expect(spell().getAvailableSpellCheckerLanguages()).toEqual(["en-US", "de-DE"]);
});
});
- 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);
+ describe("tray", () => {
+ const tray = () => getGroup("tray");
- const params = { x: 100, y: 200, selectionText: "test" };
- listeners[0]({}, params);
- expect(callback).toHaveBeenCalledWith(params);
+ it("reloadTray sends correct IPC message", () => {
+ tray().reloadTray();
+ expect(ipcRendererSent).toContainEqual({ channel: "reload-tray", args: [] });
});
});
describe("printing", () => {
+ const printing = () => getGroup("printing");
+
+ it("sendPrintProgress sends correct IPC message", () => {
+ printing().sendPrintProgress(50);
+ expect(ipcRendererSent).toContainEqual({ channel: "print-progress", args: [50] });
+ });
+
it("onPrintProgress registers and forwards print-progress channel", () => {
const callback = vi.fn();
- getApi().onPrintProgress(callback);
-
+ printing().onPrintProgress(callback);
const listeners = ipcRendererListeners.get("print-progress")!;
expect(listeners).toHaveLength(1);
listeners[0]({}, { progress: 50, action: "printing" });
@@ -333,56 +308,37 @@ describe("preload script", () => {
it("onPrintDone registers and forwards print-done channel", () => {
const callback = vi.fn();
- getApi().onPrintDone(callback);
-
+ printing().onPrintDone(callback);
const listeners = ipcRendererListeners.get("print-done")!;
expect(listeners).toHaveLength(1);
listeners[0]({}, { success: true });
expect(callback).toHaveBeenCalledWith({ success: true });
});
- it("sendPrintProgress sends correct IPC message", () => {
- getApi().sendPrintProgress(50);
- expect(ipcRendererSent).toContainEqual({
- channel: "print-progress",
- args: [50]
- });
- });
-
it("removePrintListeners clears both print listeners", () => {
- getApi().onPrintProgress(vi.fn());
- getApi().onPrintDone(vi.fn());
+ printing().onPrintProgress(vi.fn());
+ printing().onPrintDone(vi.fn());
expect(ipcRendererListeners.has("print-progress")).toBe(true);
expect(ipcRendererListeners.has("print-done")).toBe(true);
-
- getApi().removePrintListeners();
+ printing().removePrintListeners();
expect(ipcRendererListeners.has("print-progress")).toBe(false);
expect(ipcRendererListeners.has("print-done")).toBe(false);
});
- });
- describe("print preview", () => {
it("getPrinters invokes correct IPC channel", async () => {
- await getApi().getPrinters();
- expect(ipcRendererInvoked).toContainEqual({
- channel: "get-printers",
- args: []
- });
+ await printing().getPrinters();
+ expect(ipcRendererInvoked).toContainEqual({ channel: "get-printers", args: [] });
});
it("exportAsPdfPreview sends correct IPC message", () => {
const opts = { notePath: "root/abc", pageSize: "A4" };
- getApi().exportAsPdfPreview(opts);
- expect(ipcRendererSent).toContainEqual({
- channel: "export-as-pdf-preview",
- args: [opts]
- });
+ printing().exportAsPdfPreview(opts);
+ expect(ipcRendererSent).toContainEqual({ channel: "export-as-pdf-preview", args: [opts] });
});
it("onExportAsPdfPreviewResult registers and forwards channel", () => {
const callback = vi.fn();
- getApi().onExportAsPdfPreviewResult(callback);
-
+ printing().onExportAsPdfPreviewResult(callback);
const listeners = ipcRendererListeners.get("export-as-pdf-preview-result")!;
expect(listeners).toHaveLength(1);
const result = { buffer: new Uint8Array([1, 2, 3]) };
@@ -391,60 +347,61 @@ describe("preload script", () => {
});
it("removeExportAsPdfPreviewResultListener clears listener", () => {
- getApi().onExportAsPdfPreviewResult(vi.fn());
+ printing().onExportAsPdfPreviewResult(vi.fn());
expect(ipcRendererListeners.has("export-as-pdf-preview-result")).toBe(true);
- getApi().removeExportAsPdfPreviewResultListener();
+ printing().removeExportAsPdfPreviewResultListener();
expect(ipcRendererListeners.has("export-as-pdf-preview-result")).toBe(false);
});
it("savePdf sends correct IPC message", () => {
const data = { title: "Test", buffer: new Uint8Array([1]) };
- getApi().savePdf(data);
- expect(ipcRendererSent).toContainEqual({
- channel: "save-pdf",
- args: [data]
- });
+ printing().savePdf(data);
+ expect(ipcRendererSent).toContainEqual({ channel: "save-pdf", args: [data] });
});
it("printFromPreview sends correct IPC message", () => {
const opts = { notePath: "root/abc", silent: true };
- getApi().printFromPreview(opts);
- expect(ipcRendererSent).toContainEqual({
- channel: "print-from-preview",
- args: [opts]
- });
+ printing().printFromPreview(opts);
+ expect(ipcRendererSent).toContainEqual({ channel: "print-from-preview", args: [opts] });
});
});
- describe("navigation history", () => {
+ describe("navigation", () => {
+ const nav = () => getGroup("navigation");
+
+ it("clearNavigationHistory sends correct IPC message", () => {
+ nav().clearNavigationHistory();
+ expect(ipcRendererSent).toContainEqual({ channel: "clear-navigation-history", args: [] });
+ });
+
it("navigationCanGoBack uses sendSync", () => {
ipcRendererSyncResults.set("navigation-history:canGoBack", true);
- expect(getApi().navigationCanGoBack()).toBe(true);
+ expect(nav().navigationCanGoBack()).toBe(true);
});
it("navigationCanGoForward uses sendSync", () => {
ipcRendererSyncResults.set("navigation-history:canGoForward", false);
- expect(getApi().navigationCanGoForward()).toBe(false);
+ expect(nav().navigationCanGoForward()).toBe(false);
});
it("navigationGetAllEntries uses sendSync", () => {
const entries = [{ url: "trilium-app://app/?#abc", title: "Note" }];
ipcRendererSyncResults.set("navigation-history:getAllEntries", entries);
- expect(getApi().navigationGetAllEntries()).toEqual(entries);
+ expect(nav().navigationGetAllEntries()).toEqual(entries);
});
it("navigationGetActiveIndex uses sendSync", () => {
ipcRendererSyncResults.set("navigation-history:getActiveIndex", 3);
- expect(getApi().navigationGetActiveIndex()).toBe(3);
+ expect(nav().navigationGetActiveIndex()).toBe(3);
});
it("navigationLength uses sendSync", () => {
ipcRendererSyncResults.set("navigation-history:length", 5);
- expect(getApi().navigationLength()).toBe(5);
+ expect(nav().navigationLength()).toBe(5);
});
it("navigationGoToIndex sends correct IPC message", () => {
- getApi().navigationGoToIndex(2);
+ nav().navigationGoToIndex(2);
expect(ipcRendererSent).toContainEqual({
channel: "navigation-history-go-to-index",
args: [2]
@@ -453,8 +410,7 @@ describe("preload script", () => {
it("onDidNavigate registers and forwards did-navigate channel", () => {
const callback = vi.fn();
- getApi().onDidNavigate(callback);
-
+ nav().onDidNavigate(callback);
const listeners = ipcRendererListeners.get("did-navigate")!;
expect(listeners).toHaveLength(1);
listeners[0]();
@@ -462,12 +418,11 @@ describe("preload script", () => {
});
it("removeDidNavigateListeners clears both navigation listeners", () => {
- getApi().onDidNavigate(vi.fn());
- getApi().onDidNavigateInPage(vi.fn());
+ nav().onDidNavigate(vi.fn());
+ nav().onDidNavigateInPage(vi.fn());
expect(ipcRendererListeners.has("did-navigate")).toBe(true);
expect(ipcRendererListeners.has("did-navigate-in-page")).toBe(true);
-
- getApi().removeDidNavigateListeners();
+ nav().removeDidNavigateListeners();
expect(ipcRendererListeners.has("did-navigate")).toBe(false);
expect(ipcRendererListeners.has("did-navigate-in-page")).toBe(false);
});
diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts
index 13287e429c..0f0b478860 100644
--- a/apps/desktop/src/preload.ts
+++ b/apps/desktop/src/preload.ts
@@ -2,177 +2,189 @@ import type { ElectronApi, ElectronContextMenuParams } from "@triliumnext/common
import { contextBridge, ipcRenderer, webFrame } from "electron";
contextBridge.exposeInMainWorld("electronApi", {
- // Zoom
- setZoomFactor(factor: number) {
- webFrame.setZoomFactor(factor);
- },
- getZoomFactor(): number {
- return webFrame.getZoomFactor();
- },
+ window: {
+ // Zoom
+ setZoomFactor(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));
- },
+ // Theme
+ setNativeThemeSource(source: "system" | "light" | "dark") {
+ ipcRenderer.send("set-native-theme-source", source);
+ },
- // 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");
- },
+ // Title bar
+ 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);
+ },
- // Theme
- setNativeThemeSource(source: "system" | "light" | "dark") {
- ipcRenderer.send("set-native-theme-source", source);
- },
+ // Full screen
+ onEnterFullScreen(callback: () => void) {
+ ipcRenderer.on("enter-full-screen", () => callback());
+ },
+ onLeaveFullScreen(callback: () => void) {
+ ipcRenderer.on("leave-full-screen", () => callback());
+ },
+ isFullScreen(): boolean {
+ return ipcRenderer.sendSync("is-full-screen");
+ },
+ setFullScreen(enabled: boolean) {
+ ipcRenderer.send("set-full-screen", enabled);
+ },
- // Context menu
- onContextMenu(callback: (params: ElectronContextMenuParams) => void) {
- ipcRenderer.on("context-menu", (_event, params: ElectronContextMenuParams) => callback(params));
- },
- webContentsAction(action: "cut" | "copy" | "paste" | "pasteAndMatchStyle" | "insertText", text?: string) {
- ipcRenderer.send("web-contents-action", action, text);
- },
+ // Window state
+ minimizeWindow() {
+ ipcRenderer.send("minimize-window");
+ },
+ maximizeWindow() {
+ ipcRenderer.send("maximize-window");
+ },
+ unmaximizeWindow() {
+ ipcRenderer.send("unmaximize-window");
+ },
+ isMaximized(): boolean {
+ return ipcRenderer.sendSync("is-maximized");
+ },
+ closeWindow() {
+ ipcRenderer.send("close-window");
+ },
+ createExtraWindow(extraWindowHash: string) {
+ ipcRenderer.send("create-extra-window", { extraWindowHash });
+ },
+ isAlwaysOnTop(): boolean {
+ return ipcRenderer.sendSync("is-always-on-top");
+ },
+ setAlwaysOnTop(enabled: boolean) {
+ ipcRenderer.send("set-always-on-top", enabled);
+ },
+ toggleDevTools() {
+ ipcRenderer.send("toggle-dev-tools");
+ },
- // Shell
- 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);
- },
+ // Background effects
+ setBackgroundMaterial(material: string) {
+ ipcRenderer.send("set-background-material", material);
+ },
+ setVibrancy(vibrancy: string) {
+ ipcRenderer.send("set-vibrancy", vibrancy);
+ },
- // Window state
- isAlwaysOnTop(): boolean {
- return ipcRenderer.sendSync("is-always-on-top");
- },
- setAlwaysOnTop(enabled: boolean) {
- ipcRenderer.send("set-always-on-top", enabled);
- },
- toggleDevTools() {
- ipcRenderer.send("toggle-dev-tools");
- },
- isFullScreen(): boolean {
- return ipcRenderer.sendSync("is-full-screen");
- },
- setFullScreen(enabled: boolean) {
- ipcRenderer.send("set-full-screen", enabled);
- },
- minimizeWindow() {
- ipcRenderer.send("minimize-window");
- },
- maximizeWindow() {
- ipcRenderer.send("maximize-window");
- },
- unmaximizeWindow() {
- ipcRenderer.send("unmaximize-window");
- },
- isMaximized(): boolean {
- return ipcRenderer.sendSync("is-maximized");
- },
- closeWindow() {
- ipcRenderer.send("close-window");
- },
- createExtraWindow(extraWindowHash: string) {
- ipcRenderer.send("create-extra-window", { extraWindowHash });
+ // Main → renderer events
+ onGlobalShortcut(callback: (actionName: string) => void) {
+ ipcRenderer.on("globalShortcut", (_event, actionName) => callback(actionName));
+ },
+ onOpenInSameTab(callback: (noteId: string) => void) {
+ ipcRenderer.on("openInSameTab", (_event, noteId) => callback(noteId));
+ }
},
- // Tray
- reloadTray() {
- ipcRenderer.send("reload-tray");
+ shell: {
+ 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);
+ }
},
- // Dictionary / Spellcheck
- addWordToDictionary(word: string) {
- ipcRenderer.send("add-word-to-dictionary", word);
- },
- getAvailableSpellCheckerLanguages(): string[] {
- return ipcRenderer.sendSync("get-available-spellchecker-languages");
+ contextMenu: {
+ onContextMenu(callback: (params: ElectronContextMenuParams) => void) {
+ ipcRenderer.on("context-menu", (_event, params: ElectronContextMenuParams) => callback(params));
+ },
+ webContentsAction(action: "cut" | "copy" | "paste" | "pasteAndMatchStyle" | "insertText", text?: string) {
+ ipcRenderer.send("web-contents-action", action, text);
+ }
},
- // Printing
- sendPrintProgress(progress: number) {
- ipcRenderer.send("print-progress", progress);
- },
- onPrintProgress(callback: (data: { progress: number; action: string }) => void) {
- ipcRenderer.on("print-progress", (_event, data) => callback(data));
- },
- onPrintDone(callback: (printReport: unknown) => void) {
- ipcRenderer.on("print-done", (_event, printReport) => callback(printReport));
- },
- removePrintListeners() {
- ipcRenderer.removeAllListeners("print-progress");
- ipcRenderer.removeAllListeners("print-done");
- },
- getPrinters(): Promise<unknown[]> {
- return ipcRenderer.invoke("get-printers");
- },
- exportAsPdfPreview(opts: Record<string, unknown>) {
- ipcRenderer.send("export-as-pdf-preview", opts);
- },
- onExportAsPdfPreviewResult(callback: (result: { buffer?: Uint8Array; error?: string }) => void) {
- ipcRenderer.on("export-as-pdf-preview-result", (_event, result) => callback(result));
- },
- removeExportAsPdfPreviewResultListener() {
- ipcRenderer.removeAllListeners("export-as-pdf-preview-result");
- },
- savePdf(data: { title: string; buffer: Uint8Array }) {
- ipcRenderer.send("save-pdf", data);
- },
- printFromPreview(opts: Record<string, unknown>) {
- ipcRenderer.send("print-from-preview", opts);
+ spellcheck: {
+ addWordToDictionary(word: string) {
+ ipcRenderer.send("add-word-to-dictionary", word);
+ },
+ getAvailableSpellCheckerLanguages(): string[] {
+ return ipcRenderer.sendSync("get-available-spellchecker-languages");
+ }
},
- // Navigation history
- navigationCanGoBack(): boolean {
- return ipcRenderer.sendSync("navigation-history", "canGoBack");
- },
- navigationCanGoForward(): boolean {
- return ipcRenderer.sendSync("navigation-history", "canGoForward");
- },
- navigationGetAllEntries(): Array<{ url: string; title: string }> {
- return ipcRenderer.sendSync("navigation-history", "getAllEntries");
- },
- navigationGetActiveIndex(): number {
- return ipcRenderer.sendSync("navigation-history", "getActiveIndex");
+ tray: {
+ reloadTray() {
+ ipcRenderer.send("reload-tray");
+ }
},
- navigationLength(): number {
- return ipcRenderer.sendSync("navigation-history", "length");
- },
- navigationGoToIndex(index: number) {
- ipcRenderer.send("navigation-history-go-to-index", index);
- },
- onDidNavigate(callback: () => void) {
- ipcRenderer.on("did-navigate", () => callback());
- },
- onDidNavigateInPage(callback: () => void) {
- ipcRenderer.on("did-navigate-in-page", () => callback());
+
+ printing: {
+ sendPrintProgress(progress: number) {
+ ipcRenderer.send("print-progress", progress);
+ },
+ onPrintProgress(callback: (data: { progress: number; action: string }) => void) {
+ ipcRenderer.on("print-progress", (_event, data) => callback(data));
+ },
+ onPrintDone(callback: (printReport: unknown) => void) {
+ ipcRenderer.on("print-done", (_event, printReport) => callback(printReport));
+ },
+ removePrintListeners() {
+ ipcRenderer.removeAllListeners("print-progress");
+ ipcRenderer.removeAllListeners("print-done");
+ },
+ getPrinters(): Promise<unknown[]> {
+ return ipcRenderer.invoke("get-printers");
+ },
+ exportAsPdfPreview(opts: Record<string, unknown>) {
+ ipcRenderer.send("export-as-pdf-preview", opts);
+ },
+ onExportAsPdfPreviewResult(callback: (result: { buffer?: Uint8Array; error?: string }) => void) {
+ ipcRenderer.on("export-as-pdf-preview-result", (_event, result) => callback(result));
+ },
+ removeExportAsPdfPreviewResultListener() {
+ ipcRenderer.removeAllListeners("export-as-pdf-preview-result");
+ },
+ savePdf(data: { title: string; buffer: Uint8Array }) {
+ ipcRenderer.send("save-pdf", data);
+ },
+ printFromPreview(opts: Record<string, unknown>) {
+ ipcRenderer.send("print-from-preview", opts);
+ }
},
- removeDidNavigateListeners() {
- ipcRenderer.removeAllListeners("did-navigate");
- ipcRenderer.removeAllListeners("did-navigate-in-page");
+
+ navigation: {
+ clearNavigationHistory() {
+ ipcRenderer.send("clear-navigation-history");
+ },
+ navigationCanGoBack(): boolean {
+ return ipcRenderer.sendSync("navigation-history", "canGoBack");
+ },
+ navigationCanGoForward(): boolean {
+ return ipcRenderer.sendSync("navigation-history", "canGoForward");
+ },
+ navigationGetAllEntries(): Array<{ url: string; title: string }> {
+ return ipcRenderer.sendSync("navigation-history", "getAllEntries");
+ },
+ navigationGetActiveIndex(): number {
+ return ipcRenderer.sendSync("navigation-history", "getActiveIndex");
+ },
+ navigationLength(): number {
+ return ipcRenderer.sendSync("navigation-history", "length");
+ },
+ navigationGoToIndex(index: number) {
+ ipcRenderer.send("navigation-history-go-to-index", index);
+ },
+ onDidNavigate(callback: () => void) {
+ ipcRenderer.on("did-navigate", () => callback());
+ },
+ onDidNavigateInPage(callback: () => void) {
+ ipcRenderer.on("did-navigate-in-page", () => callback());
+ },
+ removeDidNavigateListeners() {
+ ipcRenderer.removeAllListeners("did-navigate");
+ ipcRenderer.removeAllListeners("did-navigate-in-page");
+ }
}
} satisfies ElectronApi);
diff --git a/packages/commons/src/lib/electron_api_interface.ts b/packages/commons/src/lib/electron_api_interface.ts
index 44970c88be..76aeca30ec 100644
--- a/packages/commons/src/lib/electron_api_interface.ts
+++ b/packages/commons/src/lib/electron_api_interface.ts
@@ -15,57 +15,65 @@ export interface ElectronContextMenuParams {
};
}
-export interface ElectronApi {
+export interface ElectronWindowApi {
// Zoom
setZoomFactor(factor: number): void;
getZoomFactor(): number;
- // IPC: main → renderer
- onGlobalShortcut(callback: (actionName: string) => void): void;
- onOpenInSameTab(callback: (noteId: string) => void): void;
+ // Theme
+ setNativeThemeSource(source: "system" | "light" | "dark"): void;
- // Window management
+ // Title bar
setTitleBarOverlay(options: { color: string; symbolColor: string }): void;
setWindowButtonPosition(position: { x: number; y: number }): void;
+
+ // Full screen
onEnterFullScreen(callback: () => void): void;
onLeaveFullScreen(callback: () => void): void;
- setBackgroundMaterial(material: string): void;
- setVibrancy(vibrancy: string): void;
- clearNavigationHistory(): void;
-
- // Theme
- setNativeThemeSource(source: "system" | "light" | "dark"): void;
-
- // Context menu
- onContextMenu(callback: (params: ElectronContextMenuParams) => void): void;
- webContentsAction(action: "cut" | "copy" | "paste" | "pasteAndMatchStyle" | "insertText", text?: string): void;
-
- // Shell
- openExternal(url: string): void;
- openPath(path: string): Promise<string>;
- openFileUrl(fileUrl: string): Promise<string>;
-
- // Window state
- toggleDevTools(): void;
isFullScreen(): boolean;
setFullScreen(enabled: boolean): void;
- isAlwaysOnTop(): boolean;
- setAlwaysOnTop(enabled: boolean): void;
+
+ // Window state
minimizeWindow(): void;
maximizeWindow(): void;
unmaximizeWindow(): void;
isMaximized(): boolean;
closeWindow(): void;
createExtraWindow(extraWindowHash: string): void;
+ isAlwaysOnTop(): boolean;
+ setAlwaysOnTop(enabled: boolean): void;
+ toggleDevTools(): void;
- // Tray
- reloadTray(): void;
+ // Background effects
+ setBackgroundMaterial(material: string): void;
+ setVibrancy(vibrancy: string): void;
+
+ // Main → renderer events
+ onGlobalShortcut(callback: (actionName: string) => void): void;
+ onOpenInSameTab(callback: (noteId: string) => void): void;
+}
+
+export interface ElectronShellApi {
+ openExternal(url: string): void;
+ openPath(path: string): Promise<string>;
+ openFileUrl(fileUrl: string): Promise<string>;
+}
- // Dictionary / Spellcheck
+export interface ElectronContextMenuApi {
+ onContextMenu(callback: (params: ElectronContextMenuParams) => void): void;
+ webContentsAction(action: "cut" | "copy" | "paste" | "pasteAndMatchStyle" | "insertText", text?: string): void;
+}
+
+export interface ElectronSpellcheckApi {
addWordToDictionary(word: string): void;
getAvailableSpellCheckerLanguages(): string[];
+}
- // Printing
+export interface ElectronTrayApi {
+ reloadTray(): void;
+}
+
+export interface ElectronPrintingApi {
sendPrintProgress(progress: number): void;
onPrintProgress(callback: (data: { progress: number; action: string }) => void): void;
onPrintDone(callback: (printReport: unknown) => void): void;
@@ -76,8 +84,10 @@ export interface ElectronApi {
removeExportAsPdfPreviewResultListener(): void;
savePdf(data: { title: string; buffer: Uint8Array }): void;
printFromPreview(opts: Record<string, unknown>): void;
+}
- // Navigation history
+export interface ElectronNavigationApi {
+ clearNavigationHistory(): void;
navigationCanGoBack(): boolean;
navigationCanGoForward(): boolean;
navigationGetAllEntries(): Array<{ url: string; title: string }>;
@@ -88,3 +98,13 @@ export interface ElectronApi {
onDidNavigateInPage(callback: () => void): void;
removeDidNavigateListeners(): void;
}
+
+export interface ElectronApi {
+ window: ElectronWindowApi;
+ shell: ElectronShellApi;
+ contextMenu: ElectronContextMenuApi;
+ spellcheck: ElectronSpellcheckApi;
+ tray: ElectronTrayApi;
+ printing: ElectronPrintingApi;
+ navigation: ElectronNavigationApi;
+}