/
devtools.js
91 lines (76 loc) · 2.45 KB
/
devtools.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/** @flow */
import { createElement } from 'react';
// $FlowFixMe Flow does not yet know about createRoot()
import { unstable_createRoot as createRoot } from 'react-dom';
import Bridge from 'src/bridge';
import { installHook } from 'src/hook';
import { initDevTools } from 'src/devtools';
import Store from 'src/devtools/Store';
import DevTools from 'src/devtools/views/DevTools';
const iframe = ((document.getElementById('target'): any): HTMLIFrameElement);
const { contentDocument, contentWindow } = iframe;
installHook(contentWindow);
const container = ((document.getElementById('devtools'): any): HTMLElement);
let isTestAppMounted = true;
const mountButton = ((document.getElementById(
'mountButton'
): any): HTMLButtonElement);
mountButton.addEventListener('click', function() {
if (isTestAppMounted) {
if (typeof window.unmountTestApp === 'function') {
window.unmountTestApp();
mountButton.innerText = 'Mount test app';
isTestAppMounted = false;
}
} else {
if (typeof window.mountTestApp === 'function') {
window.mountTestApp();
mountButton.innerText = 'Unmount test app';
isTestAppMounted = true;
}
}
});
inject('./build/app.js', () => {
initDevTools({
connect(cb) {
const bridge = new Bridge({
listen(fn) {
contentWindow.parent.addEventListener('message', ({ data }) => {
fn(data);
});
},
send(event: string, payload: any, transferable?: Array<any>) {
contentWindow.postMessage({ event, payload }, '*', transferable);
},
});
cb(bridge);
const store = new Store(bridge);
const root = createRoot(container);
const batch = root.createBatch();
batch.render(
createElement(DevTools, {
bridge,
browserName: 'Chrome',
browserTheme: 'light',
showTabBar: true,
store,
})
);
batch.then(() => {
batch.commit();
// Initialize the backend only once the DevTools frontend Store has been initialized.
// Otherwise the Store may miss important initial tree op codes.
inject('./build/backend.js');
});
},
onReload(reloadFn) {
iframe.onload = reloadFn;
},
});
});
function inject(sourcePath, callback) {
const script = contentDocument.createElement('script');
script.onload = callback;
script.src = sourcePath;
((contentDocument.body: any): HTMLBodyElement).appendChild(script);
}