mirror of
https://github.com/electron/electron.git
synced 2026-04-10 03:01:51 -04:00
* Event = Base event type (with preventDefault) * IpcMainEvent = Event that ipcMain emits (with sender, reply, etc.) * IpcRendererEvent = Event that ipcRenderer emits (with sender, senderId, etc.) * KeyboardEvent = Event that we emit with keyboard flags (ctrlKey, altKey, etc.) This will dramatically improve peoples TS experience with IPC events
30 lines
1.0 KiB
TypeScript
30 lines
1.0 KiB
TypeScript
import { ipcMainInternal } from '@electron/internal/browser/ipc-main-internal'
|
|
import * as errorUtils from '@electron/internal/common/error-utils'
|
|
|
|
type IPCHandler = (...args: any[]) => any
|
|
|
|
const callHandler = async function (handler: IPCHandler, event: ElectronInternal.IpcMainInternalEvent, args: any[], reply: (args: any[]) => void) {
|
|
try {
|
|
const result = await handler(event, ...args)
|
|
reply([null, result])
|
|
} catch (error) {
|
|
reply([errorUtils.serialize(error)])
|
|
}
|
|
}
|
|
|
|
export const handle = function <T extends IPCHandler> (channel: string, handler: T) {
|
|
ipcMainInternal.on(channel, (event, requestId, ...args) => {
|
|
callHandler(handler, event, args, responseArgs => {
|
|
event._replyInternal(`${channel}_RESPONSE_${requestId}`, ...responseArgs)
|
|
})
|
|
})
|
|
}
|
|
|
|
export const handleSync = function <T extends IPCHandler> (channel: string, handler: T) {
|
|
ipcMainInternal.on(channel, (event, ...args) => {
|
|
callHandler(handler, event, args, responseArgs => {
|
|
event.returnValue = responseArgs
|
|
})
|
|
})
|
|
}
|