Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

preload.ts

46 lines2.0 KB

1import { contextBridge, ipcRenderer } from "electron";
2import type { DesktopBridge } from "@t3tools/contracts";
3​
4const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
5const CONFIRM_CHANNEL = "desktop:confirm";
6const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
7const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
8const MENU_ACTION_CHANNEL = "desktop:menu-action";
9const UPDATE_STATE_CHANNEL = "desktop:update-state";
10const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
11const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
12const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
13const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
14​
15contextBridge.exposeInMainWorld("desktopBridge", {
16 getWsUrl: () => wsUrl,
17 pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
18 confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
19 showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
20 openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url),
21 onMenuAction: (listener) => {
22 const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
23 if (typeof action !== "string") return;
24 listener(action);
25 };
26​
27 ipcRenderer.on(MENU_ACTION_CHANNEL, wrappedListener);
28 return () => {
29 ipcRenderer.removeListener(MENU_ACTION_CHANNEL, wrappedListener);
30 };
31 },
32 getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
33 downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
34 installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
35 onUpdateState: (listener) => {
36 const wrappedListener = (_event: Electron.IpcRendererEvent, state: unknown) => {
37 if (typeof state !== "object" || state === null) return;
38 listener(state as Parameters<typeof listener>[0]);
39 };
40​
41 ipcRenderer.on(UPDATE_STATE_CHANNEL, wrappedListener);
42 return () => {
43 ipcRenderer.removeListener(UPDATE_STATE_CHANNEL, wrappedListener);
44 };
45 },
46} satisfies DesktopBridge);