mirror of
https://github.com/quine-global/hyper.git
synced 2026-01-13 04:28:41 -09:00
70 lines
1.3 KiB
JavaScript
70 lines
1.3 KiB
JavaScript
const { EventEmitter } = require('events');
|
|
const { ipcMain } = require('electron');
|
|
const uuid = require('uuid');
|
|
|
|
class Server {
|
|
|
|
constructor (win) {
|
|
this.win = win;
|
|
this.ipcListener = this.ipcListener.bind(this);
|
|
this.emitter = new EventEmitter();
|
|
|
|
if (this.destroyed) return;
|
|
|
|
const uid = uuid.v4();
|
|
this.id = uid;
|
|
|
|
ipcMain.on(uid, this.ipcListener);
|
|
|
|
// we intentionally subscribe to `on` instead of `once`
|
|
// to support reloading the window and re-initializing
|
|
// the channel
|
|
this.wc.on('did-finish-load', () => {
|
|
this.wc.send('init', uid);
|
|
});
|
|
}
|
|
|
|
get wc () {
|
|
return this.win.webContents;
|
|
}
|
|
|
|
ipcListener (event, { ev, data }) {
|
|
this.emitter.emit(ev, data);
|
|
}
|
|
|
|
emit (ch, data) {
|
|
this.wc.send(this.id, { ch, data });
|
|
}
|
|
|
|
on (ev, fn) {
|
|
this.emitter.on(ev, fn);
|
|
}
|
|
|
|
once (ev, fn) {
|
|
this.emitter.once(ev, fn);
|
|
}
|
|
|
|
removeListener (ev, fn) {
|
|
this.emitter.removeListener(ev, fn);
|
|
}
|
|
|
|
removeAllListeners () {
|
|
this.emitter.removeAllListeners();
|
|
}
|
|
|
|
destroy () {
|
|
this.removeAllListeners();
|
|
this.wc.removeAllListeners();
|
|
if (this.id) {
|
|
ipcMain.removeListener(this.id, this.ipcListener);
|
|
} else {
|
|
// mark for `genUid` in constructor
|
|
this.destroyed = true;
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
module.exports = function createRPC (win) {
|
|
return new Server(win);
|
|
};
|