Skip to content

Build your personal knowledge base with Trilium Notes

feat(electron): handle history navigation

Elian Doran9fee21b9b3ac
diff --git a/apps/client/src/types.d.ts b/apps/client/src/types.d.ts
index 580b86d662..841ec02132 100644
--- a/apps/client/src/types.d.ts
+++ b/apps/client/src/types.d.ts
@@ -77,6 +77,15 @@ declare global {
webContentsAction(action: "cut" | "copy" | "paste" | "pasteAndMatchStyle" | "insertText", text?: string): void;
openExternal(url: string): void;
addWordToDictionary(word: string): void;
+ navigationCanGoBack(): boolean;
+ navigationCanGoForward(): boolean;
+ navigationGetAllEntries(): Array<{ url: string; title: string }>;
+ navigationGetActiveIndex(): number;
+ navigationLength(): number;
+ navigationGoToIndex(index: number): void;
+ onDidNavigate(callback: () => void): void;
+ onDidNavigateInPage(callback: () => void): void;
+ removeDidNavigateListeners(): void;
}
interface ElectronContextMenuParams {
diff --git a/apps/client/src/widgets/TabHistoryNavigationButtons.tsx b/apps/client/src/widgets/TabHistoryNavigationButtons.tsx
index 42b461df0c..2aa9c7825b 100644
--- a/apps/client/src/widgets/TabHistoryNavigationButtons.tsx
+++ b/apps/client/src/widgets/TabHistoryNavigationButtons.tsx
@@ -1,17 +1,17 @@
import "./TabHistoryNavigationButtons.css";
-import { useEffect, useMemo, useState } from "preact/hooks";
+import { useEffect, useState } from "preact/hooks";
import { t } from "../services/i18n";
-import { dynamicRequire, isElectron } from "../services/utils";
+import { isElectron } from "../services/utils";
import { handleHistoryContextMenu } from "./launch_bar/HistoryNavigation";
import ActionButton from "./react/ActionButton";
import { useLauncherVisibility } from "./react/hooks";
export default function TabHistoryNavigationButtons() {
- const webContents = useMemo(() => isElectron() ? dynamicRequire("@electron/remote").getCurrentWebContents() : undefined, []);
- const onContextMenu = webContents ? handleHistoryContextMenu(webContents) : undefined;
- const { canGoBack, canGoForward } = useBackForwardState(webContents);
+ const hasApi = isElectron() && window.electronApi;
+ const onContextMenu = hasApi ? handleHistoryContextMenu() : undefined;
+ const { canGoBack, canGoForward } = useBackForwardState(hasApi);
const legacyBackVisible = useLauncherVisibility("_lbBackInHistory");
const legacyForwardVisible = useLauncherVisibility("_lbForwardInHistory");
@@ -35,30 +35,26 @@ export default function TabHistoryNavigationButtons() {
);
}
-function useBackForwardState(webContents: Electron.WebContents | undefined) {
- const [ canGoBack, setCanGoBack ] = useState(webContents?.navigationHistory.canGoBack());
- const [ canGoForward, setCanGoForward ] = useState(webContents?.navigationHistory.canGoForward());
+function useBackForwardState(hasApi: boolean | ElectronApi | undefined) {
+ const [ canGoBack, setCanGoBack ] = useState(() => hasApi ? window.electronApi!.navigationCanGoBack() : true);
+ const [ canGoForward, setCanGoForward ] = useState(() => hasApi ? window.electronApi!.navigationCanGoForward() : true);
useEffect(() => {
- if (!webContents) return;
+ if (!hasApi) return;
+ const api = window.electronApi!;
const updateNavigationState = () => {
- setCanGoBack(webContents.navigationHistory.canGoBack());
- setCanGoForward(webContents.navigationHistory.canGoForward());
+ setCanGoBack(api.navigationCanGoBack());
+ setCanGoForward(api.navigationCanGoForward());
};
- webContents.on("did-navigate", updateNavigationState);
- webContents.on("did-navigate-in-page", updateNavigationState);
+ api.onDidNavigate(updateNavigationState);
+ api.onDidNavigateInPage(updateNavigationState);
return () => {
- webContents.removeListener("did-navigate", updateNavigationState);
- webContents.removeListener("did-navigate-in-page", updateNavigationState);
+ api.removeDidNavigateListeners();
};
- }, [ webContents ]);
-
- if (!webContents) {
- return { canGoBack: true, canGoForward: true };
- }
+ }, [hasApi]);
return { canGoBack, canGoForward };
}
diff --git a/apps/client/src/widgets/launch_bar/HistoryNavigation.tsx b/apps/client/src/widgets/launch_bar/HistoryNavigation.tsx
index b35e38f337..16a60d8cfe 100644
--- a/apps/client/src/widgets/launch_bar/HistoryNavigation.tsx
+++ b/apps/client/src/widgets/launch_bar/HistoryNavigation.tsx
@@ -1,4 +1,3 @@
-import type { WebContents } from "electron";
import { useMemo } from "preact/hooks";
import FNote from "../../entities/fnote";
@@ -7,7 +6,7 @@ import { showLauncherContextMenu } from "../../menus/launcher_button_context_men
import froca from "../../services/froca";
import link from "../../services/link";
import tree from "../../services/tree";
-import { dynamicRequire, isElectron } from "../../services/utils";
+import { isElectron } from "../../services/utils";
import { LaunchBarActionButton, useLauncherIconAndTitle } from "./launch_bar_widgets";
interface HistoryNavigationProps {
@@ -19,7 +18,7 @@ const HISTORY_LIMIT = 20;
export default function HistoryNavigationButton({ launcherNote, command }: HistoryNavigationProps) {
const { icon, title } = useLauncherIconAndTitle(launcherNote);
- const webContents = useMemo(() => isElectron() ? dynamicRequire("@electron/remote").getCurrentWebContents() : undefined, []);
+ const hasApi = useMemo(() => isElectron() && !!window.electronApi, []);
return (
<LaunchBarActionButton
@@ -27,14 +26,13 @@ export default function HistoryNavigationButton({ launcherNote, command }: Histo
text={title}
triggerCommand={command}
onContextMenu={async (e) => {
- // Prevent the native menu synchronously before awaiting history items.
e.preventDefault();
- const items = webContents ? await getHistoryItems(webContents) : [];
+ const items = hasApi ? await getHistoryItems() : [];
showLauncherContextMenu<string>(launcherNote, e, {
extraItems: items,
onCommand: (cmd) => {
- if (cmd && webContents) {
- webContents.navigationHistory.goToIndex(parseInt(cmd, 10));
+ if (cmd && hasApi) {
+ window.electronApi!.navigationGoToIndex(parseInt(cmd, 10));
}
}
});
@@ -43,13 +41,14 @@ export default function HistoryNavigationButton({ launcherNote, command }: Histo
);
}
-async function getHistoryItems(webContents: WebContents): Promise<MenuCommandItem<string>[]> {
- if (webContents.navigationHistory.length() < 2) return [];
+async function getHistoryItems(): Promise<MenuCommandItem<string>[]> {
+ const api = window.electronApi!;
+ if (api.navigationLength() < 2) return [];
let items: MenuCommandItem<string>[] = [];
- const history = webContents.navigationHistory.getAllEntries();
- const activeIndex = webContents.navigationHistory.getActiveIndex();
+ const history = api.navigationGetAllEntries();
+ const activeIndex = api.navigationGetActiveIndex();
for (const idx in history) {
const { noteId, notePath } = link.parseNavigationStateFromUrl(history[idx].url);
@@ -77,11 +76,11 @@ async function getHistoryItems(webContents: WebContents): Promise<MenuCommandIte
return items;
}
-export function handleHistoryContextMenu(webContents: WebContents) {
+export function handleHistoryContextMenu() {
return async (e: MouseEvent) => {
e.preventDefault();
- const items = await getHistoryItems(webContents);
+ const items = await getHistoryItems();
if (items.length === 0) return;
contextMenu.show({
@@ -89,9 +88,9 @@ export function handleHistoryContextMenu(webContents: WebContents) {
y: e.pageY,
items,
selectMenuItemHandler: (item: MenuCommandItem<string>) => {
- if (item && item.command && webContents) {
+ if (item && item.command) {
const idx = parseInt(item.command, 10);
- webContents.navigationHistory.goToIndex(idx);
+ window.electronApi!.navigationGoToIndex(idx);
}
}
});
diff --git a/apps/desktop/spec/preload.spec.ts b/apps/desktop/spec/preload.spec.ts
index 36134eafae..669821e419 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 ipcRendererSyncResults = new Map<string, unknown>();
vi.mock("electron", () => ({
contextBridge: {
@@ -27,6 +28,12 @@ vi.mock("electron", () => ({
},
send(channel: string, ...args: unknown[]) {
ipcRendererSent.push({ channel, args });
+ },
+ sendSync(channel: string, ...args: unknown[]) {
+ return ipcRendererSyncResults.get(`${channel}:${args[0]}`);
+ },
+ removeAllListeners(channel: string) {
+ ipcRendererListeners.delete(channel);
}
}
}));
@@ -41,6 +48,7 @@ describe("preload script", () => {
mockZoomFactor = 1.0;
ipcRendererListeners.clear();
ipcRendererSent.length = 0;
+ ipcRendererSyncResults.clear();
vi.resetModules();
await import("../src/preload.js");
});
@@ -196,4 +204,61 @@ describe("preload script", () => {
expect(callback).toHaveBeenCalledWith(params);
});
});
+
+ describe("navigation history", () => {
+ it("navigationCanGoBack uses sendSync", () => {
+ ipcRendererSyncResults.set("navigation-history:canGoBack", true);
+ expect(getApi().navigationCanGoBack()).toBe(true);
+ });
+
+ it("navigationCanGoForward uses sendSync", () => {
+ ipcRendererSyncResults.set("navigation-history:canGoForward", false);
+ expect(getApi().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);
+ });
+
+ it("navigationGetActiveIndex uses sendSync", () => {
+ ipcRendererSyncResults.set("navigation-history:getActiveIndex", 3);
+ expect(getApi().navigationGetActiveIndex()).toBe(3);
+ });
+
+ it("navigationLength uses sendSync", () => {
+ ipcRendererSyncResults.set("navigation-history:length", 5);
+ expect(getApi().navigationLength()).toBe(5);
+ });
+
+ it("navigationGoToIndex sends correct IPC message", () => {
+ getApi().navigationGoToIndex(2);
+ expect(ipcRendererSent).toContainEqual({
+ channel: "navigation-history-go-to-index",
+ args: [2]
+ });
+ });
+
+ it("onDidNavigate registers and forwards did-navigate channel", () => {
+ const callback = vi.fn();
+ getApi().onDidNavigate(callback);
+
+ const listeners = ipcRendererListeners.get("did-navigate")!;
+ expect(listeners).toHaveLength(1);
+ listeners[0]();
+ expect(callback).toHaveBeenCalled();
+ });
+
+ it("removeDidNavigateListeners clears both navigation listeners", () => {
+ getApi().onDidNavigate(vi.fn());
+ getApi().onDidNavigateInPage(vi.fn());
+ expect(ipcRendererListeners.has("did-navigate")).toBe(true);
+ expect(ipcRendererListeners.has("did-navigate-in-page")).toBe(true);
+
+ getApi().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 cb0f5bdbc8..c2cec6a3a6 100644
--- a/apps/desktop/src/preload.ts
+++ b/apps/desktop/src/preload.ts
@@ -61,6 +61,36 @@ contextBridge.exposeInMainWorld("electronApi", {
// Dictionary
addWordToDictionary(word: string) {
ipcRenderer.send("add-word-to-dictionary", word);
+ },
+
+ // 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");
}
});
diff --git a/apps/server/src/services/window.ts b/apps/server/src/services/window.ts
index ddc767b692..413e03b0a4 100644
--- a/apps/server/src/services/window.ts
+++ b/apps/server/src/services/window.ts
@@ -130,6 +130,22 @@ electron.ipcMain.on("open-external", (_event, url: string) => {
electron.shell.openExternal(url);
});
+electron.ipcMain.on("navigation-history", (event, method: string) => {
+ const wc = event.sender;
+ switch (method) {
+ case "canGoBack": event.returnValue = wc.navigationHistory.canGoBack(); break;
+ case "canGoForward": event.returnValue = wc.navigationHistory.canGoForward(); break;
+ case "getAllEntries": event.returnValue = wc.navigationHistory.getAllEntries(); break;
+ case "getActiveIndex": event.returnValue = wc.navigationHistory.getActiveIndex(); break;
+ case "length": event.returnValue = wc.navigationHistory.length(); break;
+ default: event.returnValue = null;
+ }
+});
+
+electron.ipcMain.on("navigation-history-go-to-index", (event, index: number) => {
+ event.sender.navigationHistory.goToIndex(index);
+});
+
initPrintingHandlers();
async function createMainWindow(app: App) {
@@ -256,6 +272,10 @@ async function configureWebContents(webContents: WebContents, spellcheckEnabled:
win.on("leave-full-screen", () => webContents.send("leave-full-screen"));
}
+ // Forward navigation events to the renderer for back/forward button state.
+ webContents.on("did-navigate", () => webContents.send("did-navigate"));
+ webContents.on("did-navigate-in-page", () => webContents.send("did-navigate-in-page"));
+
// Forward context-menu event to the renderer with only the fields we need.
webContents.on("context-menu", (_event, params) => {
webContents.send("context-menu", {