-
Notifications
You must be signed in to change notification settings - Fork 0
/
useConnect.js
51 lines (43 loc) · 1.29 KB
/
useConnect.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const { ipcRenderer } = require('electron');
const { useEffect, useState } = require('react');
// Used in Renderer process
const noop = () => {};
/**
* A custom hook to create ipc connection between BrowserView and ControlView
*
* @param {object} options
* @param {function} options.onTabsUpdate - trigger after tabs updated(title, favicon, loading etc.)
* @param {function} options.onTabActive - trigger after active tab changed
*/
module.exports = function useConnect(options = {}) {
const { onTabsUpdate = noop, onTabActive = noop } = options;
const [tabs, setTabs] = useState({});
const [tabIDs, setTabIDs] = useState([]);
const [activeID, setActiveID] = useState(null);
const channels = [
[
'tabs-update',
(e, v) => {
setTabIDs(v.tabs);
setTabs(v.confs);
onTabsUpdate(v);
}
],
[
'active-update',
(e, v) => {
setActiveID(v);
const activeTab = tabs[v] || {};
onTabActive(activeTab);
}
]
];
useEffect(() => {
ipcRenderer.send('control-ready');
channels.forEach(([name, listener]) => ipcRenderer.on(name, listener));
return () => {
channels.forEach(([name, listener]) => ipcRenderer.removeListener(name, listener));
};
}, []);
return { tabIDs, tabs, activeID };
};