react/packages/react-devtools-shell/src/devtools.js

79 lines
2.2 KiB
JavaScript
Raw Normal View History

2019-01-23 03:04:37 +08:00
/** @flow */
2019-08-14 08:58:03 +08:00
import {createElement} from 'react';
// $FlowFixMe Flow does not yet know about createRoot()
import {unstable_createRoot as createRoot} from 'react-dom';
import {
activate as activateBackend,
initialize as initializeBackend,
} from 'react-devtools-inline/backend';
2019-08-14 08:58:03 +08:00
import {initialize as initializeFrontend} from 'react-devtools-inline/frontend';
import {initDevTools} from 'react-devtools-shared/src/devtools';
2019-01-23 03:04:37 +08:00
const iframe = ((document.getElementById('target'): any): HTMLIFrameElement);
2019-08-14 08:58:03 +08:00
const {contentDocument, contentWindow} = iframe;
2019-01-23 03:04:37 +08:00
// Helps with positioning Overlay UI.
contentWindow.__REACT_DEVTOOLS_TARGET_WINDOW__ = window;
initializeBackend(contentWindow);
2019-01-23 03:04:37 +08:00
const container = ((document.getElementById('devtools'): any): HTMLElement);
let isTestAppMounted = true;
const mountButton = ((document.getElementById(
2019-08-14 09:12:19 +08:00
'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;
}
}
});
2019-05-03 23:55:31 +08:00
inject('dist/app.js', () => {
initDevTools({
connect(cb) {
const DevTools = initializeFrontend(contentWindow);
2019-01-23 03:04:37 +08:00
// Activate the backend only once the DevTools frontend Store has been initialized.
// Otherwise the Store may miss important initial tree op codes.
activateBackend(contentWindow);
const root = createRoot(container);
root.render(
createElement(DevTools, {
browserTheme: 'light',
enabledInspectedElementContextMenu: true,
showTabBar: true,
warnIfLegacyBackendDetected: true,
warnIfUnsupportedVersionDetected: true,
2019-08-14 09:12:19 +08:00
}),
2019-01-23 03:04:37 +08:00
);
},
2019-01-23 03:04:37 +08:00
onReload(reloadFn) {
iframe.onload = reloadFn;
},
});
});
2019-01-23 03:04:37 +08:00
function inject(sourcePath, callback) {
2019-01-24 00:45:19 +08:00
const script = contentDocument.createElement('script');
2019-01-23 03:04:37 +08:00
script.onload = callback;
script.src = sourcePath;
((contentDocument.body: any): HTMLBodyElement).appendChild(script);
2019-01-24 00:45:19 +08:00
}