Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
39 changes: 27 additions & 12 deletions packages/react-devtools-inline/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,32 +177,47 @@ Below is an example of an advanced integration with a website like [Replay.io](h

```js
import {
createBridge,
activate as activateBackend,
createBridge as createBackendBridge,
initialize as initializeBackend,
} from 'react-devtools-inline/backend';
import {
createBridge as createFrontendBridge,
createStore,
initialize as createDevTools,
} from "react-devtools-inline/frontend";
} from 'react-devtools-inline/frontend';

// Custom Wall implementation enables serializing data
// using an API other than window.postMessage()
// DevTools uses "message" events and window.postMessage() by default,
// but we can override this behavior by creating a custom "Wall" object.
// For example...
const wall = {
emit() {},
_listeners: [],
listen(listener) {
wall._listener = listener;
wall._listeners.push(listener);
},
async send(event, payload) {
const response = await fetch(...).json();
wall._listener(response);
send(event, payload) {
wall._listeners.forEach(listener => listener({event, payload}));
},
};

// Create a Bridge and Store that use the custom Wall.
// Initialize the DevTools backend before importing React (or any other packages that might import React).
initializeBackend(contentWindow);

// Prepare DevTools for rendering.
// To use the custom Wall we've created, we need to also create our own "Bridge" and "Store" objects.
const bridge = createBridge(target, wall);
const store = createStore(bridge);
const DevTools = createDevTools(target, { bridge, store });

// Render DevTools with it.
<DevTools {...otherProps} />;
// You can render DevTools now:
const root = createRoot(container);
root.render(<DevTools {...otherProps} />);

// Lastly, let the DevTools backend know that the frontend is ready.
// To use the custom Wall we've created, we need to also pass in the "Bridge".
activateBackend(contentWindow, {
bridge: createBackendBridge(contentWindow, wall),
});
```

## Local development
Expand Down
68 changes: 46 additions & 22 deletions packages/react-devtools-inline/src/backend.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ import {
MESSAGE_TYPE_SAVED_PREFERENCES,
} from './constants';

function startActivation(contentWindow: window) {
import type {BackendBridge} from 'react-devtools-shared/src/bridge';
import type {Wall} from 'react-devtools-shared/src/types';

function startActivation(contentWindow: window, bridge: BackendBridge) {
const {parent} = contentWindow;

const onMessage = ({data}) => {
Expand Down Expand Up @@ -48,7 +51,7 @@ function startActivation(contentWindow: window) {
window.__REACT_DEVTOOLS_HIDE_CONSOLE_LOGS_IN_STRICT_MODE__ = hideConsoleLogsInStrictMode;
}

finishActivation(contentWindow);
finishActivation(contentWindow, bridge);
break;
default:
break;
Expand All @@ -61,27 +64,11 @@ function startActivation(contentWindow: window) {
// because they are stored in localStorage within the context of the extension (on the frontend).
// Instead it relies on the extension to pass preferences through.
// Because we might be in a sandboxed iframe, we have to ask for them by way of postMessage().
// TODO WHAT HUH
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Whoops. Left this note to myself to follow up on this and then forgot to. Will do momentarily.

parent.postMessage({type: MESSAGE_TYPE_GET_SAVED_PREFERENCES}, '*');
}

function finishActivation(contentWindow: window) {
const {parent} = contentWindow;

const bridge = new Bridge({
listen(fn) {
const onMessage = event => {
fn(event.data);
};
contentWindow.addEventListener('message', onMessage);
return () => {
contentWindow.removeEventListener('message', onMessage);
};
},
send(event: string, payload: any, transferable?: Array<any>) {
parent.postMessage({event, payload}, '*', transferable);
},
});

function finishActivation(contentWindow: window, bridge: BackendBridge) {
const agent = new Agent(bridge);

const hook = contentWindow.__REACT_DEVTOOLS_GLOBAL_HOOK__;
Expand All @@ -100,8 +87,45 @@ function finishActivation(contentWindow: window) {
}
}

export function activate(contentWindow: window): void {
startActivation(contentWindow);
export function activate(
contentWindow: window,
{
bridge,
}: {|
bridge?: BackendBridge,
|} = {},
): void {
if (bridge == null) {
bridge = createBridge(contentWindow);
}

startActivation(contentWindow, bridge);
}

export function createBridge(
contentWindow: window,
wall?: Wall,
): BackendBridge {
const {parent} = contentWindow;

if (wall == null) {
wall = {
listen(fn) {
const onMessage = ({data}) => {
fn(data);
};
window.addEventListener('message', onMessage);
return () => {
window.removeEventListener('message', onMessage);
};
},
send(event: string, payload: any, transferable?: Array<any>) {
parent.postMessage({event, payload}, '*', transferable);
},
};
}

return (new Bridge(wall): BackendBridge);
}

export function initialize(contentWindow: window): void {
Expand Down
4 changes: 4 additions & 0 deletions packages/react-devtools-shared/src/backend/agent.js
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,9 @@ export default class Agent extends EventEmitter<{|
bridge.send('profilingStatus', true);
}

// Send the Bridge protocol after initialization in case the frontend has already requested it.
this._bridge.send('bridgeProtocol', currentBridgeProtocol);

// Notify the frontend if the backend supports the Storage API (e.g. localStorage).
// If not, features like reload-and-profile will not work correctly and must be disabled.
let isBackendStorageAPISupported = false;
Expand Down Expand Up @@ -320,6 +323,7 @@ export default class Agent extends EventEmitter<{|
}

getBridgeProtocol = () => {
console.log('[agent] getBridgeProtocol -> bridge.send("bridgeProtocol")');
this._bridge.send('bridgeProtocol', currentBridgeProtocol);
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,6 @@
<!-- This script installs the hook, injects the backend, and renders the DevTools UI -->
<!-- In DEV mode, this file is served by the Webpack dev server -->
<!-- For production builds, it's built by Webpack and uploaded from the local file system -->
<script src="dist/devtools.js"></script>
<script src="dist/app-devtools.js"></script>
</body>
</html>
57 changes: 57 additions & 0 deletions packages/react-devtools-shell/multi.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<!doctype html>
<html>
<head>
<meta charset="utf8">
<title>React DevTools</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {
box-sizing: border-box;
}
body {
display: flex;
flex-direction: row;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: 0;
padding: 0;
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Helvetica, Arial,
sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol;
font-size: 12px;
line-height: 1.5;
}
.column {
display: flex;
flex-direction: column;
flex: 1 1 50%;
}
.column:first-of-type {
border-right: 1px solid #3d424a;
}
.iframe {
height: 50%;
flex: 0 0 50%;
border: none;
}
.devtools {
height: 50%;
flex: 0 0 50%;
}
</style>
</head>
<body>
<div class="column left-column">
<iframe id="iframe-left" class="iframe"></iframe>
<div id="devtools-left" class="devtools"></div>
</div>
<div class="column">
<iframe id="iframe-right" class="iframe"></iframe>
<div id="devtools-right" class="devtools"></div>
</div>

<script src="dist/multi-devtools.js"></script>
</body>
</html>
5 changes: 0 additions & 5 deletions packages/react-devtools-shell/now.json

This file was deleted.

6 changes: 3 additions & 3 deletions packages/react-devtools-shell/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
"name": "react-devtools-shell",
"version": "0.0.0",
"scripts": {
"build": "cross-env NODE_ENV=development cross-env TARGET=remote webpack --config webpack.config.js",
"deploy": "yarn run build && now deploy && now alias react-devtools-experimental",
"start": "cross-env NODE_ENV=development cross-env TARGET=local webpack-dev-server --open"
"start": "yarn start:app",
"start:app": "cross-env NODE_ENV=development cross-env TARGET=local webpack-dev-server --open-page app.html",
"start:multi": "cross-env NODE_ENV=development cross-env TARGET=local webpack-dev-server --open-page multi.html"
},
"dependencies": {
"immutable": "^4.0.0-rc.12",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ function hookNamesModuleLoaderFunction() {
return import('react-devtools-inline/hookNames');
}

inject('dist/app.js', () => {
inject('dist/app-index.js', () => {
initDevTools({
connect(cb) {
const root = createRoot(container);
Expand Down
71 changes: 71 additions & 0 deletions packages/react-devtools-shell/src/multi/devtools.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import * as React from 'react';
import {createRoot} from 'react-dom';
import {
activate as activateBackend,
createBridge as createBackendBridge,
initialize as initializeBackend,
} from 'react-devtools-inline/backend';
import {
createBridge as createFrontendBridge,
createStore,
initialize as createDevTools,
} from 'react-devtools-inline/frontend';
import {__DEBUG__} from 'react-devtools-shared/src/constants';

function inject(contentDocument, sourcePath, callback) {
const script = contentDocument.createElement('script');
script.onload = callback;
script.src = sourcePath;

((contentDocument.body: any): HTMLBodyElement).appendChild(script);
}

function init(appIframe, devtoolsContainer, appSource) {
const {contentDocument, contentWindow} = appIframe;

// Wire each DevTools instance directly to its app.
// By default, DevTools dispatches "message" events on the window,
// but this means that only one instance of DevTools can live on a page.
const wall = {
_listeners: [],
listen(listener) {
if (__DEBUG__) {
console.log('[Shell] Wall.listen()');
}

wall._listeners.push(listener);
},
send(event, payload) {
if (__DEBUG__) {
console.log('[Shell] Wall.send()', {event, payload});
}

wall._listeners.forEach(listener => listener({event, payload}));
},
};

const backendBridge = createBackendBridge(contentWindow, wall);

initializeBackend(contentWindow);

const frontendBridge = createFrontendBridge(contentWindow, wall);
const store = createStore(frontendBridge);
const DevTools = createDevTools(contentWindow, {
bridge: frontendBridge,
store,
});

inject(contentDocument, appSource, () => {
createRoot(devtoolsContainer).render(<DevTools />);
});

activateBackend(contentWindow, {bridge: backendBridge});
}

const appIframeLeft = document.getElementById('iframe-left');
const appIframeRight = document.getElementById('iframe-right');
const devtoolsContainerLeft = document.getElementById('devtools-left');
const devtoolsContainerRight = document.getElementById('devtools-right');

init(appIframeLeft, devtoolsContainerLeft, 'dist/multi-left.js');
init(appIframeRight, devtoolsContainerRight, 'dist/multi-right.js');
19 changes: 19 additions & 0 deletions packages/react-devtools-shell/src/multi/left.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import * as React from 'react';
import {useState} from 'react';
import {createRoot} from 'react-dom';

function createContainer() {
const container = document.createElement('div');

((document.body: any): HTMLBodyElement).appendChild(container);

return container;
}

function StatefulCounter() {
const [count, setCount] = useState(0);
const handleClick = () => setCount(count + 1);
return <button onClick={handleClick}>Count {count}</button>;
}

createRoot(createContainer()).render(<StatefulCounter />);
33 changes: 33 additions & 0 deletions packages/react-devtools-shell/src/multi/right.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import * as React from 'react';
import {useLayoutEffect, useRef, useState} from 'react';
import {render} from 'react-dom';

function createContainer() {
const container = document.createElement('div');

((document.body: any): HTMLBodyElement).appendChild(container);

return container;
}

function EffectWithState() {
const [didMount, setDidMount] = useState(0);

const renderCountRef = useRef(0);
renderCountRef.current++;

useLayoutEffect(() => {
if (!didMount) {
setDidMount(true);
}
}, [didMount]);

return (
<ul>
<li>Rendered {renderCountRef.current} times</li>
{didMount && <li>Mounted!</li>}
</ul>
);
}

render(<EffectWithState />, createContainer());
Loading