-
Notifications
You must be signed in to change notification settings - Fork 0
/
useConnect.ts
56 lines (46 loc) · 1.6 KB
/
useConnect.ts
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
52
53
54
55
56
import type { IpcRendererEvent, IpcRenderer } from 'electron';
import { useEffect, useState } from 'react';
import type { TabID, Tab, Tabs } from './index.d.ts';
// Used in Renderer process
const noop = () => { };
interface Options {
ipcRenderer: IpcRenderer
onTabsUpdate?: (tab: Tab) => void
onTabActive?: (tab: Tab) => void
}
type Listener = (event: IpcRendererEvent, ...args: any[]) => void
/**
* 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
*/
export default function useConnect(options: Options) {
const { onTabsUpdate = noop, onTabActive = noop, ipcRenderer } = options;
const [tabs, setTabs] = useState({} as Tabs);
const [tabIDs, setTabIDs] = useState([] as TabID[]);
const [activeID, setActiveID] = useState(0 as TabID);
const channels: Record<string, Listener> = {
'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');
Object.entries(channels).forEach(([name, listener]) => ipcRenderer.on(name, listener));
return () => {
Object.entries(channels).forEach(([name, listener]) => ipcRenderer.removeListener(name, listener));
};
}, []);
return { tabIDs, tabs, activeID };
};