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

preload.ts

53 lines2.3 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 SET_THEME_CHANNEL = "desktop:set-theme";
7const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
8const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
9const MENU_ACTION_CHANNEL = "desktop:menu-action";
10const UPDATE_STATE_CHANNEL = "desktop:update-state";
11const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
12const UPDATE_CHECK_CHANNEL = "desktop:update-check";
13const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
14const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
15const GET_WS_URL_CHANNEL = "desktop:get-ws-url";
16​
17contextBridge.exposeInMainWorld("desktopBridge", {
18 getWsUrl: () => {
19 const result = ipcRenderer.sendSync(GET_WS_URL_CHANNEL);
20 return typeof result === "string" ? result : null;
21 },
22 pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
23 confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
24 setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
25 showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
26 openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url),
27 onMenuAction: (listener) => {
28 const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
29 if (typeof action !== "string") return;
30 listener(action);
31 };
32​
33 ipcRenderer.on(MENU_ACTION_CHANNEL, wrappedListener);
34 return () => {
35 ipcRenderer.removeListener(MENU_ACTION_CHANNEL, wrappedListener);
36 };
37 },
38 getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
39 checkForUpdate: () => ipcRenderer.invoke(UPDATE_CHECK_CHANNEL),
40 downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
41 installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
42 onUpdateState: (listener) => {
43 const wrappedListener = (_event: Electron.IpcRendererEvent, state: unknown) => {
44 if (typeof state !== "object" || state === null) return;
45 listener(state as Parameters<typeof listener>[0]);
46 };
47​
48 ipcRenderer.on(UPDATE_STATE_CHANNEL, wrappedListener);
49 return () => {
50 ipcRenderer.removeListener(UPDATE_STATE_CHANNEL, wrappedListener);
51 };
52 },
53} satisfies DesktopBridge);