refactor(electron): create electron api package (#5334)

This commit is contained in:
EYHN
2023-12-27 06:38:37 +00:00
parent ce17daba42
commit 4e861d8118
53 changed files with 307 additions and 690 deletions
@@ -1,57 +1,15 @@
import { contextBridge, ipcRenderer } from 'electron';
import { contextBridge } from 'electron';
(async () => {
const { appInfo, getElectronAPIs } = await import(
'@toeverything/infra/preload/electron'
);
const { apis, events } = getElectronAPIs();
import { affine, appInfo, getElectronAPIs } from './electron-api';
contextBridge.exposeInMainWorld('appInfo', appInfo);
contextBridge.exposeInMainWorld('apis', apis);
contextBridge.exposeInMainWorld('events', events);
const { apis, events } = getElectronAPIs();
// Credit to microsoft/vscode
const globals = {
ipcRenderer: {
send(channel: string, ...args: any[]) {
ipcRenderer.send(channel, ...args);
},
contextBridge.exposeInMainWorld('appInfo', appInfo);
contextBridge.exposeInMainWorld('apis', apis);
contextBridge.exposeInMainWorld('events', events);
invoke(channel: string, ...args: any[]) {
return ipcRenderer.invoke(channel, ...args);
},
on(
channel: string,
listener: (event: Electron.IpcRendererEvent, ...args: any[]) => void
) {
ipcRenderer.on(channel, listener);
return this;
},
once(
channel: string,
listener: (event: Electron.IpcRendererEvent, ...args: any[]) => void
) {
ipcRenderer.once(channel, listener);
return this;
},
removeListener(
channel: string,
listener: (event: Electron.IpcRendererEvent, ...args: any[]) => void
) {
ipcRenderer.removeListener(channel, listener);
return this;
},
},
};
try {
contextBridge.exposeInMainWorld('affine', globals);
} catch (error) {
console.error('Failed to expose affine APIs to window object!', error);
}
})().catch(err => {
console.error('Failed to bootstrap preload script!', err);
});
try {
contextBridge.exposeInMainWorld('affine', affine);
} catch (error) {
console.error('Failed to expose affine APIs to window object!', error);
}