@samitouri / QOS-React / commits / bb6b86ed59

refactor[react-devtools]: initialize renderer interface early (#30946)

The current state is that `rendererInterface`, which contains all the backend logic, like generating component stack or attaching errors to fibers, or traversing the Fiber tree, ..., is only mounted after the Frontend is created. For browser extension, this means that we don't patch console or track errors and warnings before Chrome DevTools is opened. With these changes, `rendererInterface` is created right after `renderer` is injected from React via global hook object (e. g. `__REACT_DEVTOOLS_GLOBAL_HOOK__.inject(...)`. Because of the current implementation, in case of multiple Reacts on the page, all of them will patch the console independently. This will be fixed in one of the next PRs, where I am moving console patching to the global Hook. This change of course makes `hook.js` script bigger, but I think it is a reasonable trade-off for better DevX. We later can add more heuristics to optimize the performance (if necessary) of `rendererInterface` for cases when Frontend was connected late and Backend is attempting to flush out too many recorded operations. This essentially reverts https://github.com/facebook/react/pull/26563.

Ruslan Lesiutin committed Sep 12, 2024 at 13:59 UTC bb6b86ed596399ddd8bf642404a9e68ae430a6ea
10 files changed +110 -134
packages/react-devtools-extensions/src/background/dynamicallyInjectContentScripts.js
-8
@@ -25,14 +25,6 @@ const contentScriptsToInject = [
25 runAt: 'document_start',
26 world: chrome.scripting.ExecutionWorld.MAIN,
27 },
28 - {
29 - id: '@react-devtools/renderer',
30 - js: ['build/renderer.js'],
31 - matches: ['<all_urls>'],
32 - persistAcrossSessions: true,
33 - runAt: 'document_start',
34 - world: chrome.scripting.ExecutionWorld.MAIN,
35 - },
28 ];
29
30 async function dynamicallyInjectContentScripts() {
packages/react-devtools-extensions/src/contentScripts/renderer.js deleted
-33
@@ -1,33 +0,0 @@
1 -/**
2 - * In order to support reload-and-profile functionality, the renderer needs to be injected before any other scripts.
3 - * Since it is a complex file (with imports) we can't just toString() it like we do with the hook itself,
4 - * So this entry point (one of the web_accessible_resources) provides a way to eagerly inject it.
5 - * The hook will look for the presence of a global __REACT_DEVTOOLS_ATTACH__ and attach an injected renderer early.
6 - * The normal case (not a reload-and-profile) will not make use of this entry point though.
7 - *
8 - * @flow
9 - */
10 -
11 -import {attach} from 'react-devtools-shared/src/backend/fiber/renderer';
12 -import {SESSION_STORAGE_RELOAD_AND_PROFILE_KEY} from 'react-devtools-shared/src/constants';
13 -import {sessionStorageGetItem} from 'react-devtools-shared/src/storage';
14 -
15 -if (
16 - sessionStorageGetItem(SESSION_STORAGE_RELOAD_AND_PROFILE_KEY) === 'true' &&
17 - !window.hasOwnProperty('__REACT_DEVTOOLS_ATTACH__')
18 -) {
19 - Object.defineProperty(
20 - window,
21 - '__REACT_DEVTOOLS_ATTACH__',
22 - ({
23 - enumerable: false,
24 - // This property needs to be configurable to allow third-party integrations
25 - // to attach their own renderer. Note that using third-party integrations
26 - // is not officially supported. Use at your own risk.
27 - configurable: true,
28 - get() {
29 - return attach;
30 - },
31 - }: Object),
32 - );
33 -}
packages/react-devtools-extensions/webpack.config.js
-1
@@ -55,7 +55,6 @@ module.exports = {
55 panel: './src/panel.js',
56 proxy: './src/contentScripts/proxy.js',
57 prepareInjection: './src/contentScripts/prepareInjection.js',
58 - renderer: './src/contentScripts/renderer.js',
58 installHook: './src/contentScripts/installHook.js',
59 },
60 output: {
packages/react-devtools-shared/src/attachRenderer.js new
+61
@@ -0,0 +1,61 @@
1 +/**
2 + * Copyright (c) Meta Platforms, Inc. and affiliates.
3 + *
4 + * This source code is licensed under the MIT license found in the
5 + * LICENSE file in the root directory of this source tree.
6 + *
7 + * @flow
8 + */
9 +
10 +import type {
11 + ReactRenderer,
12 + RendererInterface,
13 + DevToolsHook,
14 + RendererID,
15 +} from 'react-devtools-shared/src/backend/types';
16 +
17 +import {attach as attachFlight} from 'react-devtools-shared/src/backend/flight/renderer';
18 +import {attach as attachFiber} from 'react-devtools-shared/src/backend/fiber/renderer';
19 +import {attach as attachLegacy} from 'react-devtools-shared/src/backend/legacy/renderer';
20 +import {hasAssignedBackend} from 'react-devtools-shared/src/backend/utils';
21 +
22 +// this is the backend that is compatible with all older React versions
23 +function isMatchingRender(version: string): boolean {
24 + return !hasAssignedBackend(version);
25 +}
26 +
27 +export default function attachRenderer(
28 + hook: DevToolsHook,
29 + id: RendererID,
30 + renderer: ReactRenderer,
31 + global: Object,
32 +): RendererInterface | void {
33 + // only attach if the renderer is compatible with the current version of the backend
34 + if (!isMatchingRender(renderer.reconcilerVersion || renderer.version)) {
35 + return;
36 + }
37 + let rendererInterface = hook.rendererInterfaces.get(id);
38 +
39 + // Inject any not-yet-injected renderers (if we didn't reload-and-profile)
40 + if (rendererInterface == null) {
41 + if (typeof renderer.getCurrentComponentInfo === 'function') {
42 + // react-flight/client
43 + rendererInterface = attachFlight(hook, id, renderer, global);
44 + } else if (
45 + // v16-19
46 + typeof renderer.findFiberByHostInstance === 'function' ||
47 + // v16.8+
48 + renderer.currentDispatcherRef != null
49 + ) {
50 + // react-reconciler v16+
51 + rendererInterface = attachFiber(hook, id, renderer, global);
52 + } else if (renderer.ComponentTree) {
53 + // react-dom v15
54 + rendererInterface = attachLegacy(hook, id, renderer, global);
55 + } else {
56 + // Older react-dom or other unsupported renderer version
57 + }
58 + }
59 +
60 + return rendererInterface;
61 +}
packages/react-devtools-shared/src/backend/agent.js
+12 -3
@@ -152,6 +152,7 @@ export default class Agent extends EventEmitter<{
152 traceUpdates: [Set<HostInstance>],
153 drawTraceUpdates: [Array<HostInstance>],
154 disableTraceUpdates: [],
155 + getIfHasUnsupportedRendererVersion: [],
156 }> {
157 _bridge: BackendBridge;
158 _isProfiling: boolean = false;
@@ -221,6 +222,10 @@ export default class Agent extends EventEmitter<{
222 );
223 bridge.addListener('updateComponentFilters', this.updateComponentFilters);
224 bridge.addListener('getEnvironmentNames', this.getEnvironmentNames);
225 + bridge.addListener(
226 + 'getIfHasUnsupportedRendererVersion',
227 + this.getIfHasUnsupportedRendererVersion,
228 + );
229
230 // Temporarily support older standalone front-ends sending commands to newer embedded backends.
231 // We do this because React Native embeds the React DevTools backend,
@@ -709,7 +714,7 @@ export default class Agent extends EventEmitter<{
714 }
715 }
716
712 - setRendererInterface(
717 + registerRendererInterface(
718 rendererID: RendererID,
719 rendererInterface: RendererInterface,
720 ) {
@@ -940,8 +945,12 @@ export default class Agent extends EventEmitter<{
945 }
946 };
947
943 - onUnsupportedRenderer(rendererID: number) {
944 - this._bridge.send('unsupportedRendererVersion', rendererID);
948 + getIfHasUnsupportedRendererVersion: () => void = () => {
949 + this.emit('getIfHasUnsupportedRendererVersion');
950 + };
951 +
952 + onUnsupportedRenderer() {
953 + this._bridge.send('unsupportedRendererVersion');
954 }
955
956 _persistSelectionTimerScheduled: boolean = false;
packages/react-devtools-shared/src/backend/index.js
+22 -79
@@ -9,18 +9,7 @@
9
10 import Agent from './agent';
11
12 -import {attach as attachFiber} from './fiber/renderer';
13 -import {attach as attachFlight} from './flight/renderer';
14 -import {attach as attachLegacy} from './legacy/renderer';
15 -
16 -import {hasAssignedBackend} from './utils';
17 -
18 -import type {DevToolsHook, ReactRenderer, RendererInterface} from './types';
19 -
20 -// this is the backend that is compatible with all older React versions
21 -function isMatchingRender(version: string): boolean {
22 - return !hasAssignedBackend(version);
23 -}
12 +import type {DevToolsHook, RendererID, RendererInterface} from './types';
13
14 export type InitBackend = typeof initBackend;
15
@@ -34,29 +23,32 @@ export function initBackend(
23 return () => {};
24 }
25
26 + function registerRendererInterface(
27 + id: RendererID,
28 + rendererInterface: RendererInterface,
29 + ) {
30 + agent.registerRendererInterface(id, rendererInterface);
31 +
32 + // Now that the Store and the renderer interface are connected,
33 + // it's time to flush the pending operation codes to the frontend.
34 + rendererInterface.flushInitialOperations();
35 + }
36 +
37 const subs = [
38 hook.sub(
39 'renderer-attached',
40 ({
41 id,
42 - renderer,
42 rendererInterface,
43 }: {
44 id: number,
46 - renderer: ReactRenderer,
45 rendererInterface: RendererInterface,
48 - ...
46 }) => {
50 - agent.setRendererInterface(id, rendererInterface);
51 -
52 - // Now that the Store and the renderer interface are connected,
53 - // it's time to flush the pending operation codes to the frontend.
54 - rendererInterface.flushInitialOperations();
47 + registerRendererInterface(id, rendererInterface);
48 },
49 ),
57 -
58 - hook.sub('unsupported-renderer-version', (id: number) => {
59 - agent.onUnsupportedRenderer(id);
50 + hook.sub('unsupported-renderer-version', () => {
51 + agent.onUnsupportedRenderer();
52 }),
53
54 hook.sub('fastRefreshScheduled', agent.onFastRefreshScheduled),
@@ -66,68 +58,19 @@ export function initBackend(
58 // TODO Add additional subscriptions required for profiling mode
59 ];
60
69 - const attachRenderer = (id: number, renderer: ReactRenderer) => {
70 - // only attach if the renderer is compatible with the current version of the backend
71 - if (!isMatchingRender(renderer.reconcilerVersion || renderer.version)) {
72 - return;
73 - }
74 - let rendererInterface = hook.rendererInterfaces.get(id);
75 -
76 - // Inject any not-yet-injected renderers (if we didn't reload-and-profile)
77 - if (rendererInterface == null) {
78 - if (typeof renderer.getCurrentComponentInfo === 'function') {
79 - // react-flight/client
80 - rendererInterface = attachFlight(hook, id, renderer, global);
81 - } else if (
82 - // v16-19
83 - typeof renderer.findFiberByHostInstance === 'function' ||
84 - // v16.8+
85 - renderer.currentDispatcherRef != null
86 - ) {
87 - // react-reconciler v16+
88 - rendererInterface = attachFiber(hook, id, renderer, global);
89 - } else if (renderer.ComponentTree) {
90 - // react-dom v15
91 - rendererInterface = attachLegacy(hook, id, renderer, global);
92 - } else {
93 - // Older react-dom or other unsupported renderer version
94 - }
95 -
96 - if (rendererInterface != null) {
97 - hook.rendererInterfaces.set(id, rendererInterface);
98 - }
61 + agent.addListener('getIfHasUnsupportedRendererVersion', () => {
62 + if (hook.hasUnsupportedRendererAttached) {
63 + agent.onUnsupportedRenderer();
64 }
100 -
101 - // Notify the DevTools frontend about new renderers.
102 - // This includes any that were attached early (via __REACT_DEVTOOLS_ATTACH__).
103 - if (rendererInterface != null) {
104 - hook.emit('renderer-attached', {
105 - id,
106 - renderer,
107 - rendererInterface,
108 - });
109 - } else {
110 - hook.emit('unsupported-renderer-version', id);
111 - }
112 - };
113 -
114 - // Connect renderers that have already injected themselves.
115 - hook.renderers.forEach((renderer, id) => {
116 - attachRenderer(id, renderer);
65 });
66
119 - // Connect any new renderers that injected themselves.
120 - subs.push(
121 - hook.sub(
122 - 'renderer',
123 - ({id, renderer}: {id: number, renderer: ReactRenderer, ...}) => {
124 - attachRenderer(id, renderer);
125 - },
126 - ),
127 - );
67 + hook.rendererInterfaces.forEach((rendererInterface, id) => {
68 + registerRendererInterface(id, rendererInterface);
69 + });
70
71 hook.emit('react-devtools', agent);
72 hook.reactDevtoolsAgent = agent;
73 +
74 const onAgentShutdown = () => {
75 subs.forEach(fn => fn());
76 hook.rendererInterfaces.forEach(rendererInterface => {
packages/react-devtools-shared/src/backend/types.js
+1
@@ -492,6 +492,7 @@ export type DevToolsHook = {
492 listeners: {[key: string]: Array<Handler>, ...},
493 rendererInterfaces: Map<RendererID, RendererInterface>,
494 renderers: Map<RendererID, ReactRenderer>,
495 + hasUnsupportedRendererAttached: boolean,
496 backends: Map<string, DevToolsBackend>,
497
498 emit: (event: string, data: any) => void,
packages/react-devtools-shared/src/bridge.js
+2 -1
@@ -200,7 +200,7 @@ export type BackendEvents = {
200 stopInspectingHost: [boolean],
201 syncSelectionFromBuiltinElementsPanel: [],
202 syncSelectionToBuiltinElementsPanel: [],
203 - unsupportedRendererVersion: [RendererID],
203 + unsupportedRendererVersion: [],
204
205 // React Native style editor plug-in.
206 isNativeStyleEditorSupported: [
@@ -218,6 +218,7 @@ type FrontendEvents = {
218 deletePath: [DeletePath],
219 getBackendVersion: [],
220 getBridgeProtocol: [],
221 + getIfHasUnsupportedRendererVersion: [],
222 getOwnersList: [ElementAndRendererID],
223 getProfilingData: [{rendererID: RendererID}],
224 getProfilingStatus: [],
packages/react-devtools-shared/src/devtools/store.js
+1
@@ -1500,6 +1500,7 @@ export default class Store extends EventEmitter<{
1500 }
1501
1502 this._bridge.send('getBackendVersion');
1503 + this._bridge.send('getIfHasUnsupportedRendererVersion');
1504 };
1505
1506 // The Store should never throw an Error without also emitting an event.
packages/react-devtools-shared/src/hook.js
+11 -9
@@ -21,6 +21,7 @@ import {
21 FIREFOX_CONSOLE_DIMMING_COLOR,
22 ANSI_STYLE_DIMMING_TEMPLATE,
23 } from 'react-devtools-shared/src/constants';
24 +import attachRenderer from './attachRenderer';
25
26 declare var window: any;
27
@@ -358,7 +359,6 @@ export function installHook(target: any): DevToolsHook | null {
359 }
360
361 let uidCounter = 0;
361 -
362 function inject(renderer: ReactRenderer): number {
363 const id = ++uidCounter;
364 renderers.set(id, renderer);
@@ -367,20 +367,21 @@ export function installHook(target: any): DevToolsHook | null {
367 ? 'deadcode'
368 : detectReactBuildType(renderer);
369
370 - // If we have just reloaded to profile, we need to inject the renderer interface before the app loads.
371 - // Otherwise the renderer won't yet exist and we can skip this step.
372 - const attach = target.__REACT_DEVTOOLS_ATTACH__;
373 - if (typeof attach === 'function') {
374 - const rendererInterface = attach(hook, id, renderer, target);
375 - hook.rendererInterfaces.set(id, rendererInterface);
376 - }
377 -
370 hook.emit('renderer', {
371 id,
372 renderer,
373 reactBuildType,
374 });
375
376 + const rendererInterface = attachRenderer(hook, id, renderer, target);
377 + if (rendererInterface != null) {
378 + hook.rendererInterfaces.set(id, rendererInterface);
379 + hook.emit('renderer-attached', {id, rendererInterface});
380 + } else {
381 + hook.hasUnsupportedRendererAttached = true;
382 + hook.emit('unsupported-renderer-version');
383 + }
384 +
385 return id;
386 }
387
@@ -534,6 +535,7 @@ export function installHook(target: any): DevToolsHook | null {
535
536 // Fast Refresh for web relies on this.
537 renderers,
538 + hasUnsupportedRendererAttached: false,
539
540 emit,
541 getFiberRoots,