Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add named hooks support to react-devtools-inline #22263

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 5 additions & 7 deletions packages/react-devtools-extensions/src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -287,33 +287,31 @@ function createPanelIfReactLoaded() {
};
}

// TODO (Webpack 5) Hopefully we can remove this prop after the Webpack 5 migration.
const hookNamesModuleLoaderFunction = () =>
import('react-devtools-inline/hookNames');

root = createRoot(document.createElement('div'));

render = (overrideTab = mostRecentOverrideTab) => {
mostRecentOverrideTab = overrideTab;
import('react-devtools-shared/src/hooks/parseHookNames').then(
({parseHookNames, prefetchSourceFiles, purgeCachedMetadata}) => {
root.render(
createElement(DevTools, {
bridge,
browserTheme: getBrowserTheme(),
componentsPortalContainer,
enabledInspectedElementContextMenu: true,
fetchFileWithCaching,
loadHookNames: parseHookNames,
hookNamesModuleLoaderFunction,
overrideTab,
prefetchSourceFiles,
profilerPortalContainer,
purgeCachedHookNamesMetadata: purgeCachedMetadata,
showTabBar: false,
store,
warnIfUnsupportedVersionDetected: true,
viewAttributeSourceFunction,
viewElementSourceFunction,
}),
);
},
);
};

render();
Expand Down
1 change: 1 addition & 0 deletions packages/react-devtools-extensions/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ module.exports = {
path: __dirname + '/build',
publicPath: '/build/',
filename: '[name].js',
chunkFilename: '[name].chunk.js',
},
node: {
// Don't define a polyfill on window.setImmediate
Expand Down
17 changes: 17 additions & 0 deletions packages/react-devtools-inline/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,23 @@ const DevTools = initialize(contentWindow);

## Examples

### Supporting named hooks

DevTools can display hook "names" for an inspected component, although determining the "names" requires loading the source (and source-maps), parsing the code, and infering the names based on which variables hook values get assigned to. Because the code for this is non-trivial, it's lazy-loaded only if the feature is enabled.

To configure this package to support this functionality, you'll need to provide a prop that dynamically imports the extra functionality:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the dynamic webpack public path override also necessary to get this working in OSS or is that something that's only necessary in react-devtools-shell?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TBH I'm not sure. Maybe it depends on which version of Webpack other projects are using?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If #22267 doesn't land, should we add that as a note in the README as well? It feels a bit unintuitive for developers otherwise (it definitely was for us 😅)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah...let's see what happens 😅 I'm not a Webpack expert so maybe there's a better way to do this than what I did.

TBH I don't think anyone (other than us, Code Sandbox, and Replay.io) uses the inline package.

```js
// Follow code examples above to configure the backend and frontend.
// When rendering DevTools, the important part is to pass a 'hookNamesModuleLoaderFunction' prop.
const hookNamesModuleLoaderFunction = () => import('react-devtools-inline/hookNames');

// Render:
<DevTools
hookNamesModuleLoaderFunction={hookNamesModuleLoaderFunction}
{...otherProps}
/>;
```

### Configuring a same-origin `iframe`

The simplest way to use this package is to install the hook from the parent `window`. This is possible if the `iframe` is not sandboxed and there are no cross-origin restrictions.
Expand Down
1 change: 1 addition & 0 deletions packages/react-devtools-inline/hookNames.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = require('./dist/hookNames');
5 changes: 4 additions & 1 deletion packages/react-devtools-inline/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@
"prepublish": "yarn run build",
"start": "cross-env NODE_ENV=development webpack --config webpack.config.js --watch"
},
"dependencies": {},
"dependencies": {
"source-map-js": "^0.6.2",
"sourcemap-codec": "^1.4.8"
},
"devDependencies": {
"@babel/core": "^7.11.1",
"@babel/plugin-proposal-class-properties": "^7.10.4",
Expand Down
9 changes: 9 additions & 0 deletions packages/react-devtools-inline/src/hookNames.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/** @flow */

import {
parseHookNames,
parseSourceAndMetadata,
purgeCachedMetadata,
} from 'react-devtools-shared/src/hooks/parseHookNames';

export {parseHookNames, parseSourceAndMetadata, purgeCachedMetadata};
2 changes: 2 additions & 0 deletions packages/react-devtools-inline/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,12 @@ module.exports = {
entry: {
backend: './src/backend.js',
frontend: './src/frontend.js',
hookNames: './src/hookNames.js',
},
output: {
path: __dirname + '/dist',
filename: '[name].js',
chunkFilename: '[name].chunk.js',
library: '[name]',
libraryTarget: 'commonjs2',
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

export const enableProfilerChangedHookIndices = true;
export const isInternalFacebookBuild = true;

export const enableNamedHooksFeature = false;
export const consoleManagedByDevToolsDuringStrictMode = false;

/************************************************************************
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

export const enableProfilerChangedHookIndices = false;
export const isInternalFacebookBuild = false;

export const enableNamedHooksFeature = false;
bvaughn marked this conversation as resolved.
Show resolved Hide resolved
export const consoleManagedByDevToolsDuringStrictMode = false;

/************************************************************************
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,5 @@

export const enableProfilerChangedHookIndices = false;
export const isInternalFacebookBuild = false;

export const enableNamedHooksFeature = true;
export const consoleManagedByDevToolsDuringStrictMode = true;
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

export const enableProfilerChangedHookIndices = true;
export const isInternalFacebookBuild = true;

export const enableNamedHooksFeature = true;
export const consoleManagedByDevToolsDuringStrictMode = true;

/************************************************************************
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

export const enableProfilerChangedHookIndices = true;
export const isInternalFacebookBuild = false;

export const enableNamedHooksFeature = true;
export const consoleManagedByDevToolsDuringStrictMode = true;

/************************************************************************
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/

import {createContext} from 'react';

export type FetchFileWithCaching = (url: string) => Promise<string>;
export type Context = FetchFileWithCaching | null;

const FetchFileWithCachingContext = createContext<Context>(null);
FetchFileWithCachingContext.displayName = 'FetchFileWithCachingContext';

export default FetchFileWithCachingContext;

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/

import type {Thenable} from 'shared/ReactTypes';

import {createContext} from 'react';
import typeof * as ParseHookNamesModule from 'react-devtools-shared/src/hooks/parseHookNames';

export type HookNamesModuleLoaderFunction = () => Thenable<ParseHookNamesModule>;
export type Context = HookNamesModuleLoaderFunction | null;

// TODO (Webpack 5) Hopefully we can remove this context entirely once the Webpack 5 upgrade is completed.
const HookNamesModuleLoaderContext = createContext<Context>(null);
HookNamesModuleLoaderContext.displayName = 'HookNamesModuleLoaderContext';

export default HookNamesModuleLoaderContext;
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,11 @@ import {
hasAlreadyLoadedHookNames,
loadHookNames,
} from 'react-devtools-shared/src/hookNamesCache';
import HookNamesContext from 'react-devtools-shared/src/devtools/views/Components/HookNamesContext';
import {loadModule} from 'react-devtools-shared/src/dynamicImportCache';
import FetchFileWithCachingContext from 'react-devtools-shared/src/devtools/views/Components/FetchFileWithCachingContext';
import HookNamesModuleLoaderContext from 'react-devtools-shared/src/devtools/views/Components/HookNamesModuleLoaderContext';
import {SettingsContext} from '../Settings/SettingsContext';
import {enableNamedHooksFeature} from 'react-devtools-feature-flags';

import type {HookNames} from 'react-devtools-shared/src/types';
import type {ReactNodeList} from 'shared/ReactTypes';
Expand Down Expand Up @@ -64,16 +67,17 @@ export type Props = {|

export function InspectedElementContextController({children}: Props) {
const {selectedElementID} = useContext(TreeStateContext);
const {
fetchFileWithCaching,
loadHookNames: loadHookNamesFunction,
prefetchSourceFiles,
purgeCachedMetadata,
} = useContext(HookNamesContext);
const fetchFileWithCaching = useContext(FetchFileWithCachingContext);
const bridge = useContext(BridgeContext);
const store = useContext(StoreContext);
const {parseHookNames: parseHookNamesByDefault} = useContext(SettingsContext);

// parseHookNames has a lot of code.
// Embedding it into a build makes the build large.
// This function enables DevTools to make use of Suspense to lazily import() it only if the feature will be used.
// TODO (Webpack 5) Hopefully we can remove this indirection once the Webpack 5 upgrade is completed.
const hookNamesModuleLoader = useContext(HookNamesModuleLoaderContext);
bvaughn marked this conversation as resolved.
Show resolved Hide resolved

const refresh = useCacheRefresh();

// Temporarily stores most recently-inspected (hydrated) path.
Expand Down Expand Up @@ -113,13 +117,26 @@ export function InspectedElementContextController({children}: Props) {
setParseHookNames(parseHookNamesByDefault || alreadyLoadedHookNames);
}

const purgeCachedMetadataRef = useRef(null);

// Don't load a stale element from the backend; it wastes bridge bandwidth.
let hookNames: HookNames | null = null;
let inspectedElement = null;
if (!elementHasChanged && element !== null) {
inspectedElement = inspectElement(element, state.path, store, bridge);

if (enableNamedHooksFeature) {
if (typeof hookNamesModuleLoader === 'function') {
if (parseHookNames || alreadyLoadedHookNames) {
const hookNamesModule = loadModule(hookNamesModuleLoader);
if (hookNamesModule !== null) {
const {
parseHookNames: loadHookNamesFunction,
purgeCachedMetadata,
} = hookNamesModule;

purgeCachedMetadataRef.current = purgeCachedMetadata;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a little clunky, but since we conditionally load this via Suspense, and refer to it in an effect, we have to stash it in a ref.


if (
inspectedElement !== null &&
inspectedElement.hooks !== null &&
Expand All @@ -134,6 +151,9 @@ export function InspectedElementContextController({children}: Props) {
}
}
}
}
}
}

const toggleParseHookNames: ToggleParseHookNames = useCallback<ToggleParseHookNames>(() => {
startTransition(() => {
Expand Down Expand Up @@ -163,14 +183,11 @@ export function InspectedElementContextController({children}: Props) {
inspectedElementRef.current !== inspectedElement
) {
inspectedElementRef.current = inspectedElement;

if (typeof prefetchSourceFiles === 'function') {
prefetchSourceFiles(inspectedElement.hooks, fetchFileWithCaching);
}
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This optimization wasn't really important given the in-memory caching we now do, so I cleaned it up while I was in here.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wouldn't this help speed things up in the case where the source files are loaded before devtools is open?

}
}, [inspectedElement, prefetchSourceFiles]);
}, [inspectedElement]);

useEffect(() => {
const purgeCachedMetadata = purgeCachedMetadataRef.current;
if (typeof purgeCachedMetadata === 'function') {
// When Fast Refresh updates a component, any cached AST metadata may be invalid.
const fastRefreshScheduled = () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,11 @@ import styles from './InspectedElementHooksTree.css';
import useContextMenu from '../../ContextMenu/useContextMenu';
import {meta} from '../../../hydration';
import {getHookSourceLocationKey} from 'react-devtools-shared/src/hookNamesCache';
import {enableProfilerChangedHookIndices} from 'react-devtools-feature-flags';
import HookNamesContext from 'react-devtools-shared/src/devtools/views/Components/HookNamesContext';
import {
enableNamedHooksFeature,
enableProfilerChangedHookIndices,
} from 'react-devtools-feature-flags';
import HookNamesModuleLoaderContext from 'react-devtools-shared/src/devtools/views/Components/HookNamesModuleLoaderContext';

import type {InspectedElement} from './types';
import type {HooksNode, HooksTree} from 'react-debug-tools/src/ReactDebugHooks';
Expand Down Expand Up @@ -53,8 +56,6 @@ export function InspectedElementHooksTree({
}: HooksTreeViewProps) {
const {hooks, id} = inspectedElement;

const {loadHookNames: loadHookNamesFunction} = useContext(HookNamesContext);

// Changing parseHookNames is done in a transition, because it suspends.
// This value is done outside of the transition, so the UI toggle feels responsive.
const [parseHookNamesOptimistic, setParseHookNamesOptimistic] = useState(
Expand All @@ -65,6 +66,8 @@ export function InspectedElementHooksTree({
toggleParseHookNames();
};

const hookNamesModuleLoader = useContext(HookNamesModuleLoaderContext);

const hookParsingFailed = parseHookNames && hookNames === null;

let toggleTitle;
Expand All @@ -85,7 +88,8 @@ export function InspectedElementHooksTree({
<div className={styles.HooksTreeView}>
<div className={styles.HeaderRow}>
<div className={styles.Header}>hooks</div>
{loadHookNamesFunction !== null &&
{enableNamedHooksFeature &&
typeof hookNamesModuleLoader === 'function' &&
(!parseHookNames || hookParsingFailed) && (
<Toggle
className={hookParsingFailed ? styles.ToggleError : null}
Expand Down
Loading