@samitouri / QOS-React / commits / 1b1dcb8a40

feat[devtools/extension]: show disclaimer when page doesnt run react and refactor react polling logic (#27373)

Changes: 1. Refactored react polling logic, now each `.eval()` call is wrapped in Promise, so we can chain them properly. 2. When user has browser DevTools opened and React DevTools panels were mounted, user might navigate to the page, which doesn't have React running. Previously, we would show just blank white page, now we will show disclaimer. Disclaimer appears after 5 failed attempts to find React. We will also show this disclaimer if it takes too long to load the page, but once any React instance is loaded and registered, we will update the panels. 3. Dark theme support for this disclaimer and popups in Firefox & Chromium-based browsers **Important**: this is only valid for case when React DevTools panels were already created, like when user started debugging React app and then switched to non-React page. If user starts to debug non-React app (by opening browser DevTools for it), we will not create these panels, just like before. Q: "Why do we poll to get information about react?" A: To handle case when react is loaded after the page has been loaded, some sandboxes for example. | Before | After | | --- | --- | | <img width="1840" alt="Screenshot 2023-09-14 at 15 37 37" src="https://github.com/facebook/react/assets/28902667/2e6ffb39-5698-461d-bfd6-be2defb41aad"> | <img width="1840" alt="Screenshot 2023-09-14 at 15 26 16" src="https://github.com/facebook/react/assets/28902667/1c8ad2b7-0955-41c5-b8cc-d0fdb03e13ca"> |

Ruslan Lesiutin committed Sep 20, 2023 at 13:30 UTC 1b1dcb8a40d002edcbca483b1f9caa78087a878f
5 files changed +184 -69
packages/react-devtools-extensions/panel.html
+34 -1
@@ -22,11 +22,44 @@
22 right: 0;
23 bottom: 0;
24 }
25 + .no-react-disclaimer {
26 + margin: 16px;
27 + font-family: Courier, monospace, serif;
28 + font-size: 16px;
29 + animation: fadeIn .5s ease-in-out forwards;
30 + }
31 +
32 + @keyframes fadeIn {
33 + 0% {
34 + opacity: 0;
35 + }
36 + 100% {
37 + opacity: 1;
38 + }
39 + }
40 +
41 + @media (prefers-color-scheme: dark) {
42 + :root {
43 + color-scheme: dark;
44 + }
45 +
46 + @supports (-moz-appearance:none) {
47 + :root {
48 + background: black;
49 + }
50 +
51 + body {
52 + color: white;
53 + }
54 + }
55 + }
56 </style>
57 </head>
58 <body>
59 <!-- main react mount point -->
29 - <div id="container">Unable to find React on the page.</div>
60 + <div id="container">
61 + <h1 class="no-react-disclaimer">Looks like this page doesn't have React, or it hasn't been loaded yet.</h1>
62 + </div>
63 <script src="./build/panel.js"></script>
64 </body>
65 </html>
packages/react-devtools-extensions/popups/shared.css
+11 -1
@@ -7,7 +7,17 @@ body {
7 }
8
9 @media (prefers-color-scheme: dark) {
10 - html {
10 + :root {
11 color-scheme: dark;
12 }
13 +
14 + @supports (-moz-appearance:none) {
15 + :root {
16 + background: black;
17 + }
18 +
19 + body {
20 + color: white;
21 + }
22 + }
23 }
packages/react-devtools-extensions/src/background/index.js
+2 -2
@@ -64,8 +64,8 @@ chrome.runtime.onConnect.addListener(port => {
64 const tabId = port.sender.tab.id;
65
66 if (ports[tabId]?.proxy) {
67 - port.disconnect();
68 - return;
67 + ports[tabId].disconnectPipe?.();
68 + ports[tabId].proxy.disconnect();
69 }
70
71 registerTab(tabId);
packages/react-devtools-extensions/src/main/index.js
+34 -65
@@ -22,6 +22,7 @@ import {
22 setBrowserSelectionFromReact,
23 setReactSelectionFromBrowser,
24 } from './elementSelection';
25 +import {startReactPolling} from './reactPolling';
26 import cloneStyleTags from './cloneStyleTags';
27 import injectBackendManager from './injectBackendManager';
28 import syncSavedPreferences from './syncSavedPreferences';
@@ -30,60 +31,6 @@ import getProfilingFlags from './getProfilingFlags';
31 import debounce from './debounce';
32 import './requestAnimationFramePolyfill';
33
33 -// Try polling for at least 5 seconds, in case if it takes too long to load react
34 -const REACT_POLLING_TICK_COOLDOWN = 250;
35 -const REACT_POLLING_ATTEMPTS_THRESHOLD = 20;
36 -
37 -let reactPollingTimeoutId = null;
38 -export function clearReactPollingTimeout() {
39 - clearTimeout(reactPollingTimeoutId);
40 - reactPollingTimeoutId = null;
41 -}
42 -
43 -export function executeIfReactHasLoaded(callback, attempt = 1) {
44 - clearReactPollingTimeout();
45 -
46 - if (attempt > REACT_POLLING_ATTEMPTS_THRESHOLD) {
47 - return;
48 - }
49 -
50 - chrome.devtools.inspectedWindow.eval(
51 - 'window.__REACT_DEVTOOLS_GLOBAL_HOOK__ && window.__REACT_DEVTOOLS_GLOBAL_HOOK__.renderers.size > 0',
52 - (pageHasReact, exceptionInfo) => {
53 - if (exceptionInfo) {
54 - const {code, description, isError, isException, value} = exceptionInfo;
55 -
56 - if (isException) {
57 - console.error(
58 - `Received error while checking if react has loaded: ${value}`,
59 - );
60 - return;
61 - }
62 -
63 - if (isError) {
64 - console.error(
65 - `Received error with code ${code} while checking if react has loaded: ${description}`,
66 - );
67 - return;
68 - }
69 - }
70 -
71 - if (pageHasReact) {
72 - callback();
73 - } else {
74 - reactPollingTimeoutId = setTimeout(
75 - executeIfReactHasLoaded,
76 - REACT_POLLING_TICK_COOLDOWN,
77 - callback,
78 - attempt + 1,
79 - );
80 - }
81 - },
82 - );
83 -}
84 -
85 -let lastSubscribedBridgeListener = null;
86 -
34 function createBridge() {
35 bridge = new Bridge({
36 listen(fn) {
@@ -370,6 +317,7 @@ function ensureInitialHTMLIsCleared(container) {
317 function createComponentsPanel() {
318 if (componentsPortalContainer) {
319 // Panel is created and user opened it at least once
320 + ensureInitialHTMLIsCleared(componentsPortalContainer);
321 render('components');
322
323 return;
@@ -389,7 +337,7 @@ function createComponentsPanel() {
337
338 createdPanel.onShown.addListener(portal => {
339 componentsPortalContainer = portal.container;
392 - if (componentsPortalContainer != null) {
340 + if (componentsPortalContainer != null && render) {
341 ensureInitialHTMLIsCleared(componentsPortalContainer);
342
343 render('components');
@@ -408,6 +356,7 @@ function createComponentsPanel() {
356 function createProfilerPanel() {
357 if (profilerPortalContainer) {
358 // Panel is created and user opened it at least once
359 + ensureInitialHTMLIsCleared(profilerPortalContainer);
360 render('profiler');
361
362 return;
@@ -427,7 +376,7 @@ function createProfilerPanel() {
376
377 createdPanel.onShown.addListener(portal => {
378 profilerPortalContainer = portal.container;
430 - if (profilerPortalContainer != null) {
379 + if (profilerPortalContainer != null && render) {
380 ensureInitialHTMLIsCleared(profilerPortalContainer);
381
382 render('profiler');
@@ -442,7 +391,7 @@ function createProfilerPanel() {
391
392 function performInTabNavigationCleanup() {
393 // Potentially, if react hasn't loaded yet and user performs in-tab navigation
445 - clearReactPollingTimeout();
394 + clearReactPollingInstance();
395
396 if (store !== null) {
397 // Store profiling data, so it can be used later
@@ -479,7 +428,7 @@ function performInTabNavigationCleanup() {
428
429 function performFullCleanup() {
430 // Potentially, if react hasn't loaded yet and user closed the browser DevTools
482 - clearReactPollingTimeout();
431 + clearReactPollingInstance();
432
433 if ((componentsPortalContainer || profilerPortalContainer) && root) {
434 // This should also emit bridge.shutdown, but only if this root was mounted
@@ -531,6 +480,8 @@ function connectExtensionPort() {
480 }
481
482 function mountReactDevTools() {
483 + reactPollingInstance = null;
484 +
485 registerEventsLogger();
486
487 createBridgeAndStore();
@@ -541,18 +492,36 @@ function mountReactDevTools() {
492 createProfilerPanel();
493 }
494
544 -// TODO: display some disclaimer if user performs in-tab navigation to non-react application
545 -// when React DevTools panels are already opened, currently we will display just blank white block
546 -function mountReactDevToolsWhenReactHasLoaded() {
547 - function onReactReady() {
548 - clearReactPollingTimeout();
549 - mountReactDevTools();
495 +let reactPollingInstance = null;
496 +function clearReactPollingInstance() {
497 + reactPollingInstance?.abort();
498 + reactPollingInstance = null;
499 +}
500 +
501 +function showNoReactDisclaimer() {
502 + if (componentsPortalContainer) {
503 + componentsPortalContainer.innerHTML =
504 + '<h1 class="no-react-disclaimer">Looks like this page doesn\'t have React, or it hasn\'t been loaded yet.</h1>';
505 + delete componentsPortalContainer._hasInitialHTMLBeenCleared;
506 + }
507 +
508 + if (profilerPortalContainer) {
509 + profilerPortalContainer.innerHTML =
510 + '<h1 class="no-react-disclaimer">Looks like this page doesn\'t have React, or it hasn\'t been loaded yet.</h1>';
511 + delete profilerPortalContainer._hasInitialHTMLBeenCleared;
512 }
513 +}
514
552 - executeIfReactHasLoaded(onReactReady, 1);
515 +function mountReactDevToolsWhenReactHasLoaded() {
516 + reactPollingInstance = startReactPolling(
517 + mountReactDevTools,
518 + 5, // ~5 seconds
519 + showNoReactDisclaimer,
520 + );
521 }
522
523 let bridge = null;
524 +let lastSubscribedBridgeListener = null;
525 let store = null;
526
527 let profilingData = null;
packages/react-devtools-extensions/src/main/reactPolling.js new
+103
@@ -0,0 +1,103 @@
1 +/* global chrome */
2 +
3 +class CouldNotFindReactOnThePageError extends Error {
4 + constructor() {
5 + super("Could not find React, or it hasn't been loaded yet");
6 +
7 + // Maintains proper stack trace for where our error was thrown (only available on V8)
8 + if (Error.captureStackTrace) {
9 + Error.captureStackTrace(this, CouldNotFindReactOnThePageError);
10 + }
11 +
12 + this.name = 'CouldNotFindReactOnThePageError';
13 + }
14 +}
15 +
16 +export function startReactPolling(
17 + onReactFound,
18 + attemptsThreshold,
19 + onCouldNotFindReactAfterReachingAttemptsThreshold,
20 +) {
21 + let status = 'idle';
22 +
23 + function abort() {
24 + status = 'aborted';
25 + }
26 +
27 + // This function will call onSuccess only if React was found and polling is not aborted, onError will be called for every other case
28 + function checkIfReactPresentInInspectedWindow(onSuccess, onError) {
29 + chrome.devtools.inspectedWindow.eval(
30 + 'window.__REACT_DEVTOOLS_GLOBAL_HOOK__ && window.__REACT_DEVTOOLS_GLOBAL_HOOK__.renderers.size > 0',
31 + (pageHasReact, exceptionInfo) => {
32 + if (status === 'aborted') {
33 + onError(
34 + 'Polling was aborted, user probably navigated to the other page',
35 + );
36 + return;
37 + }
38 +
39 + if (exceptionInfo) {
40 + const {code, description, isError, isException, value} =
41 + exceptionInfo;
42 +
43 + if (isException) {
44 + onError(
45 + `Received error while checking if react has loaded: ${value}`,
46 + );
47 + return;
48 + }
49 +
50 + if (isError) {
51 + onError(
52 + `Received error with code ${code} while checking if react has loaded: "${description}"`,
53 + );
54 + return;
55 + }
56 + }
57 +
58 + if (pageHasReact) {
59 + onSuccess();
60 + return;
61 + }
62 +
63 + onError(new CouldNotFindReactOnThePageError());
64 + },
65 + );
66 + }
67 +
68 + // Just a Promise wrapper around `checkIfReactPresentInInspectedWindow`
69 + // returns a Promise, which will resolve only if React has been found on the page
70 + function poll(attempt) {
71 + return new Promise((resolve, reject) => {
72 + checkIfReactPresentInInspectedWindow(resolve, reject);
73 + }).catch(error => {
74 + if (error instanceof CouldNotFindReactOnThePageError) {
75 + if (attempt === attemptsThreshold) {
76 + onCouldNotFindReactAfterReachingAttemptsThreshold();
77 + }
78 +
79 + // Start next attempt in 0.5s
80 + return new Promise(r => setTimeout(r, 500)).then(() =>
81 + poll(attempt + 1),
82 + );
83 + }
84 +
85 + // Propagating every other Error
86 + throw error;
87 + });
88 + }
89 +
90 + poll(1)
91 + .then(onReactFound)
92 + .catch(error => {
93 + // Log propagated errors only if polling was not aborted
94 + // Some errors are expected when user performs in-tab navigation and `.eval()` is still being executed
95 + if (status === 'aborted') {
96 + return;
97 + }
98 +
99 + console.error(error);
100 + });
101 +
102 + return {abort};
103 +}