react/packages/react-devtools-extensions/src/main.js

385 lines
13 KiB
JavaScript
Raw Normal View History

2019-01-24 10:06:21 +08:00
/* global chrome */
2019-08-14 08:58:03 +08:00
import {createElement} from 'react';
import {createRoot, flushSync} from 'react-dom';
2019-08-14 06:59:43 +08:00
import Bridge from 'react-devtools-shared/src/bridge';
import Store from 'react-devtools-shared/src/devtools/store';
import {getBrowserName, getBrowserTheme} from './utils';
import {LOCAL_STORAGE_TRACE_UPDATES_ENABLED_KEY} from 'react-devtools-shared/src/constants';
2019-08-14 08:58:03 +08:00
import {
getSavedComponentFilters,
getAppendComponentStack,
} from 'react-devtools-shared/src/utils';
import {
localStorageGetItem,
localStorageRemoveItem,
localStorageSetItem,
2019-08-14 06:59:43 +08:00
} from 'react-devtools-shared/src/storage';
import DevTools from 'react-devtools-shared/src/devtools/views/DevTools';
const LOCAL_STORAGE_SUPPORTS_PROFILING_KEY =
'React::DevTools::supportsProfiling';
const isChrome = getBrowserName() === 'Chrome';
2019-01-24 10:06:21 +08:00
let panelCreated = false;
// The renderer interface can't read saved component filters directly,
// because they are stored in localStorage within the context of the extension.
// Instead it relies on the extension to pass filters through.
function syncSavedPreferences() {
const componentFilters = getSavedComponentFilters();
chrome.devtools.inspectedWindow.eval(
`window.__REACT_DEVTOOLS_COMPONENT_FILTERS__ = ${JSON.stringify(
2019-08-14 12:59:07 +08:00
componentFilters,
)};`,
);
const appendComponentStack = getAppendComponentStack();
chrome.devtools.inspectedWindow.eval(
`window.__REACT_DEVTOOLS_APPEND_COMPONENT_STACK__ = ${JSON.stringify(
2019-08-14 12:59:07 +08:00
appendComponentStack,
)};`,
);
}
syncSavedPreferences();
2019-01-24 10:06:21 +08:00
function createPanelIfReactLoaded() {
if (panelCreated) {
return;
}
2019-01-24 10:06:21 +08:00
chrome.devtools.inspectedWindow.eval(
2019-02-05 02:01:44 +08:00
'window.__REACT_DEVTOOLS_GLOBAL_HOOK__ && window.__REACT_DEVTOOLS_GLOBAL_HOOK__.renderers.size > 0',
function(pageHasReact, error) {
2019-01-24 10:06:21 +08:00
if (!pageHasReact || panelCreated) {
return;
}
panelCreated = true;
clearInterval(loadCheckInterval);
let bridge = null;
let store = null;
2019-03-19 00:20:00 +08:00
let profilingData = null;
2019-04-03 02:53:46 +08:00
let componentsPortalContainer = null;
let profilerPortalContainer = null;
2019-03-19 00:20:00 +08:00
let cloneStyleTags = null;
let mostRecentOverrideTab = null;
let render = null;
let root = null;
2019-05-31 00:27:28 +08:00
const tabId = chrome.devtools.inspectedWindow.tabId;
function initBridgeAndStore() {
const port = chrome.runtime.connect({
2019-05-31 00:27:28 +08:00
name: '' + tabId,
2019-01-24 10:06:21 +08:00
});
Fix for 'Attempting to use a disconnected port object' Fixes https://github.com/bvaughn/react-devtools-experimental/issues/217 The error reproduces with any two React websites, e.g. `https://reactjs.org` and `https://nextjs.org`, by keeping the DevTools Components tab open and switching between these websites in the same browser tab. There are several issues with the code that contribute to this: 1. `Bridge` leaves behind a dangling timer that fires `_flush` after the bridge has been abandoned ("shutdown"). 2. `bridge.send('shutdown')` is asynchronous, so the event handlers do not get unsubscribed in time. 3. `port.onDisconnect` does not trigger on in-tab navigation like new URL or back/forward navigation. 4. State management design of the code that uses shared variables and callbacks makes it hard to handle race conditions originating from the browser. This commit cleans up some of the lacking symmetry when using `addListener`/`removeListener`, but the code in `shells/browser/shared/src/main.js` is hard to reason about with regards to race conditions, and there are many possible race conditions originating from the browser, so maybe there could be a better design paradigm (like a formal state machine) to manage the state changes in response to sequences of events than plain old event listeners, callbacks, and shared variables. Unrelated, but clicking Chrome Back/Forward/Back/Forward very fast makes the browser and the DevTools and the DevTools of DevTools stall and become unresponsive for some time, then recovers but the Back/Forward/Stop/Refresh button and favicon loading indicator may remain broken. Looks like a Chrome bug, some kind of a temporary deadlock in handling the browser history.
2019-04-26 19:30:04 +08:00
// Looks like `port.onDisconnect` does not trigger on in-tab navigation like new URL or back/forward navigation,
// so it makes no sense to handle it here.
bridge = new Bridge({
listen(fn) {
Fix for 'Attempting to use a disconnected port object' Fixes https://github.com/bvaughn/react-devtools-experimental/issues/217 The error reproduces with any two React websites, e.g. `https://reactjs.org` and `https://nextjs.org`, by keeping the DevTools Components tab open and switching between these websites in the same browser tab. There are several issues with the code that contribute to this: 1. `Bridge` leaves behind a dangling timer that fires `_flush` after the bridge has been abandoned ("shutdown"). 2. `bridge.send('shutdown')` is asynchronous, so the event handlers do not get unsubscribed in time. 3. `port.onDisconnect` does not trigger on in-tab navigation like new URL or back/forward navigation. 4. State management design of the code that uses shared variables and callbacks makes it hard to handle race conditions originating from the browser. This commit cleans up some of the lacking symmetry when using `addListener`/`removeListener`, but the code in `shells/browser/shared/src/main.js` is hard to reason about with regards to race conditions, and there are many possible race conditions originating from the browser, so maybe there could be a better design paradigm (like a formal state machine) to manage the state changes in response to sequences of events than plain old event listeners, callbacks, and shared variables. Unrelated, but clicking Chrome Back/Forward/Back/Forward very fast makes the browser and the DevTools and the DevTools of DevTools stall and become unresponsive for some time, then recovers but the Back/Forward/Stop/Refresh button and favicon loading indicator may remain broken. Looks like a Chrome bug, some kind of a temporary deadlock in handling the browser history.
2019-04-26 19:30:04 +08:00
const listener = message => fn(message);
// Store the reference so that we unsubscribe from the same object.
const portOnMessage = port.onMessage;
portOnMessage.addListener(listener);
return () => {
portOnMessage.removeListener(listener);
};
},
send(event: string, payload: any, transferable?: Array<any>) {
2019-08-14 08:58:03 +08:00
port.postMessage({event, payload}, transferable);
},
});
bridge.addListener('reloadAppForProfiling', () => {
localStorageSetItem(LOCAL_STORAGE_SUPPORTS_PROFILING_KEY, 'true');
chrome.devtools.inspectedWindow.eval('window.location.reload();');
});
2019-04-14 01:55:51 +08:00
bridge.addListener('syncSelectionToNativeElementsPanel', () => {
setBrowserSelectionFromReact();
});
// This flag lets us tip the Store off early that we expect to be profiling.
// This avoids flashing a temporary "Profiling not supported" message in the Profiler tab,
// after a user has clicked the "reload and profile" button.
let isProfiling = false;
let supportsProfiling = false;
if (
localStorageGetItem(LOCAL_STORAGE_SUPPORTS_PROFILING_KEY) === 'true'
) {
supportsProfiling = true;
isProfiling = true;
localStorageRemoveItem(LOCAL_STORAGE_SUPPORTS_PROFILING_KEY);
}
if (store !== null) {
profilingData = store.profilerStore.profilingData;
}
bridge.addListener('extensionBackendInitialized', () => {
// Initialize the renderer's trace-updates setting.
// This handles the case of navigating to a new page after the DevTools have already been shown.
bridge.send(
'setTraceUpdatesEnabled',
localStorageGetItem(LOCAL_STORAGE_TRACE_UPDATES_ENABLED_KEY) ===
'true',
);
});
store = new Store(bridge, {
isProfiling,
supportsReloadAndProfile: isChrome,
supportsProfiling,
supportsTraceUpdates: true,
});
store.profilerStore.profilingData = profilingData;
// Initialize the backend only once the Store has been initialized.
// Otherwise the Store may miss important initial tree op codes.
chrome.devtools.inspectedWindow.eval(
`window.postMessage({ source: 'react-devtools-inject-backend' }, '*');`,
function(response, evalError) {
if (evalError) {
console.error(evalError);
}
},
);
const viewAttributeSourceFunction = (id, path) => {
const rendererID = store.getRendererIDForElement(id);
if (rendererID != null) {
// Ask the renderer interface to find the specified attribute,
// and store it as a global variable on the window.
bridge.send('viewAttributeSource', {id, path, rendererID});
setTimeout(() => {
// Ask Chrome to display the location of the attribute,
// assuming the renderer found a match.
chrome.devtools.inspectedWindow.eval(`
if (window.$attribute != null) {
inspect(window.$attribute);
}
`);
}, 100);
}
};
const viewElementSourceFunction = id => {
const rendererID = store.getRendererIDForElement(id);
if (rendererID != null) {
// Ask the renderer interface to determine the component function,
// and store it as a global variable on the window
bridge.send('viewElementSource', {id, rendererID});
setTimeout(() => {
// Ask Chrome to display the location of the component function,
// or a render method if it is a Class (ideally Class instance, not type)
// assuming the renderer found one.
chrome.devtools.inspectedWindow.eval(`
if (window.$type != null) {
if (
window.$type &&
window.$type.prototype &&
window.$type.prototype.isReactComponent
) {
// inspect Component.render, not constructor
inspect(window.$type.prototype.render);
} else {
// inspect Functional Component
inspect(window.$type);
}
}
`);
}, 100);
}
};
2019-03-18 04:52:37 +08:00
root = createRoot(document.createElement('div'));
render = (overrideTab = mostRecentOverrideTab) => {
mostRecentOverrideTab = overrideTab;
2019-03-18 04:52:37 +08:00
root.render(
createElement(DevTools, {
bridge,
browserTheme: getBrowserTheme(),
2019-04-03 02:53:46 +08:00
componentsPortalContainer,
enabledInspectedElementContextMenu: true,
2019-03-18 04:52:37 +08:00
overrideTab,
profilerPortalContainer,
2019-03-18 04:52:37 +08:00
showTabBar: false,
store,
warnIfUnsupportedVersionDetected: true,
viewAttributeSourceFunction: isChrome
? viewAttributeSourceFunction
: null,
viewElementSourceFunction,
2019-08-14 12:59:07 +08:00
}),
2019-03-18 04:52:37 +08:00
);
};
render();
}
2019-03-18 04:52:37 +08:00
cloneStyleTags = () => {
const linkTags = [];
2019-08-14 12:59:07 +08:00
// eslint-disable-next-line no-for-of-loops/no-for-of-loops
for (let linkTag of document.getElementsByTagName('link')) {
if (linkTag.rel === 'stylesheet') {
const newLinkTag = document.createElement('link');
2019-08-14 12:59:07 +08:00
// eslint-disable-next-line no-for-of-loops/no-for-of-loops
for (let attribute of linkTag.attributes) {
newLinkTag.setAttribute(attribute.nodeName, attribute.nodeValue);
2019-03-18 04:52:37 +08:00
}
linkTags.push(newLinkTag);
2019-03-18 04:52:37 +08:00
}
}
return linkTags;
};
initBridgeAndStore();
2019-04-08 22:29:51 +08:00
function ensureInitialHTMLIsCleared(container) {
if (container._hasInitialHTMLBeenCleared) {
return;
}
container.innerHTML = '';
container._hasInitialHTMLBeenCleared = true;
}
2019-04-14 01:55:51 +08:00
function setBrowserSelectionFromReact() {
// This is currently only called on demand when you press "view DOM".
// In the future, if Chrome adds an inspect() that doesn't switch tabs,
// we could make this happen automatically when you select another component.
chrome.devtools.inspectedWindow.eval(
'(window.__REACT_DEVTOOLS_GLOBAL_HOOK__.$0 !== $0) ?' +
'(inspect(window.__REACT_DEVTOOLS_GLOBAL_HOOK__.$0), true) :' +
'false',
2019-08-14 12:59:07 +08:00
(didSelectionChange, evalError) => {
if (evalError) {
console.error(evalError);
2019-04-14 01:55:51 +08:00
}
2019-08-14 12:59:07 +08:00
},
2019-04-14 01:55:51 +08:00
);
}
2019-04-09 08:30:40 +08:00
function setReactSelectionFromBrowser() {
// When the user chooses a different node in the browser Elements tab,
// copy it over to the hook object so that we can sync the selection.
chrome.devtools.inspectedWindow.eval(
2019-04-10 03:04:33 +08:00
'(window.__REACT_DEVTOOLS_GLOBAL_HOOK__.$0 !== $0) ?' +
'(window.__REACT_DEVTOOLS_GLOBAL_HOOK__.$0 = $0, true) :' +
'false',
2019-08-14 12:59:07 +08:00
(didSelectionChange, evalError) => {
if (evalError) {
console.error(evalError);
2019-04-10 03:04:33 +08:00
} else if (didSelectionChange) {
// Remember to sync the selection next time we show Components tab.
needsToSyncElementSelection = true;
}
2019-08-14 12:59:07 +08:00
},
);
}
2019-04-10 03:04:33 +08:00
setReactSelectionFromBrowser();
chrome.devtools.panels.elements.onSelectionChanged.addListener(() => {
2019-04-09 08:30:40 +08:00
setReactSelectionFromBrowser();
2019-04-10 03:04:33 +08:00
});
let currentPanel = null;
2019-04-10 03:04:33 +08:00
let needsToSyncElementSelection = false;
2019-08-15 01:33:33 +08:00
chrome.devtools.panels.create(
isChrome ? '⚛ Components' : 'Components',
2019-08-15 01:33:33 +08:00
'',
'panel.html',
extensionPanel => {
extensionPanel.onShown.addListener(panel => {
if (needsToSyncElementSelection) {
needsToSyncElementSelection = false;
bridge.send('syncSelectionFromNativeElementsPanel');
}
2019-04-10 03:04:33 +08:00
2019-08-15 01:33:33 +08:00
if (currentPanel === panel) {
return;
}
2019-08-15 01:33:33 +08:00
currentPanel = panel;
componentsPortalContainer = panel.container;
2019-08-15 01:33:33 +08:00
if (componentsPortalContainer != null) {
ensureInitialHTMLIsCleared(componentsPortalContainer);
render('components');
panel.injectStyles(cloneStyleTags);
}
});
extensionPanel.onHidden.addListener(panel => {
// TODO: Stop highlighting and stuff.
});
},
);
2019-08-15 01:33:33 +08:00
chrome.devtools.panels.create(
isChrome ? '⚛ Profiler' : 'Profiler',
2019-08-15 01:33:33 +08:00
'',
'panel.html',
extensionPanel => {
extensionPanel.onShown.addListener(panel => {
if (currentPanel === panel) {
return;
}
2019-08-15 01:33:33 +08:00
currentPanel = panel;
profilerPortalContainer = panel.container;
2019-08-15 01:33:33 +08:00
if (profilerPortalContainer != null) {
ensureInitialHTMLIsCleared(profilerPortalContainer);
render('profiler');
panel.injectStyles(cloneStyleTags);
}
});
},
);
chrome.devtools.network.onNavigated.removeListener(checkPageForReact);
// Re-initialize DevTools panel when a new page is loaded.
chrome.devtools.network.onNavigated.addListener(function onNavigated() {
// Re-initialize saved filters on navigation,
// since global values stored on window get reset in this case.
syncSavedPreferences();
// It's easiest to recreate the DevTools panel (to clean up potential stale state).
// We can revisit this in the future as a small optimization.
flushSync(() => {
root.unmount(() => {
initBridgeAndStore();
});
});
});
2019-08-14 12:59:07 +08:00
},
2019-01-24 10:06:21 +08:00
);
}
// Load (or reload) the DevTools extension when the user navigates to a new page.
function checkPageForReact() {
syncSavedPreferences();
2019-01-24 10:06:21 +08:00
createPanelIfReactLoaded();
}
chrome.devtools.network.onNavigated.addListener(checkPageForReact);
2019-01-24 10:06:21 +08:00
// Check to see if React has loaded once per second in case React is added
// after page load
const loadCheckInterval = setInterval(function() {
createPanelIfReactLoaded();
}, 1000);
createPanelIfReactLoaded();