Upgrade prettier (#26081)

The old version of prettier we were using didn't support the Flow syntax
to access properties in a type using `SomeType['prop']`. This updates
`prettier` and `rollup-plugin-prettier` to the latest versions.

I added the prettier config `arrowParens: "avoid"` to reduce the diff
size as the default has changed in Prettier 2.0. The largest amount of
changes comes from function expressions now having a space. This doesn't
have an option to preserve the old behavior, so we have to update this.
This commit is contained in:
Jan Kassens 2023-01-31 08:25:05 -05:00 committed by GitHub
parent 1f5ce59dd7
commit 6b30832666
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
421 changed files with 3444 additions and 4257 deletions

View File

@ -8,8 +8,8 @@ module.exports = {
jsxBracketSameLine: true, jsxBracketSameLine: true,
trailingComma: 'es5', trailingComma: 'es5',
printWidth: 80, printWidth: 80,
parser: 'babel', parser: 'flow',
arrowParens: 'avoid',
overrides: [ overrides: [
{ {
files: esNextPaths, files: esNextPaths,

View File

@ -97,7 +97,7 @@ function row(result, baseSha, headSha) {
return rowArr.join(' | '); return rowArr.join(' | ');
} }
(async function() { (async function () {
// Use git locally to grab the commit which represents the place // Use git locally to grab the commit which represents the place
// where the branches differ // where the branches differ
@ -241,8 +241,9 @@ Comparing: ${baseSha}...${headSha}
## Critical size changes ## Critical size changes
Includes critical production bundles, as well as any change greater than ${CRITICAL_THRESHOLD * Includes critical production bundles, as well as any change greater than ${
100}%: CRITICAL_THRESHOLD * 100
}%:
${header} ${header}
${criticalResults.join('\n')} ${criticalResults.join('\n')}

View File

@ -902,8 +902,9 @@ class App extends React.Component {
let log = ''; let log = '';
for (let attribute of attributes) { for (let attribute of attributes) {
log += `## \`${attribute.name}\` (on \`<${attribute.tagName || log += `## \`${attribute.name}\` (on \`<${
'div'}>\` inside \`<${attribute.containerTagName || 'div'}>\`)\n`; attribute.tagName || 'div'
}>\` inside \`<${attribute.containerTagName || 'div'}>\`)\n`;
log += '| Test Case | Flags | Result |\n'; log += '| Test Case | Flags | Result |\n';
log += '| --- | --- | --- |\n'; log += '| --- | --- | --- |\n';

View File

@ -39,7 +39,7 @@ function initServer() {
const host = 'localhost'; const host = 'localhost';
const port = 8000; const port = 8000;
const requestListener = function(request, response) { const requestListener = function (request, response) {
let contents; let contents;
switch (request.url) { switch (request.url) {
case '/react.js': case '/react.js':

View File

@ -4,7 +4,7 @@
'use strict'; 'use strict';
(function() { (function () {
var Fixture = null; var Fixture = null;
var output = document.getElementById('output'); var output = document.getElementById('output');
var status = document.getElementById('status'); var status = document.getElementById('status');
@ -60,7 +60,7 @@
setStatus('Generating markup'); setStatus('Generating markup');
return Promise.resolve() return Promise.resolve()
.then(function() { .then(function () {
const element = createElement(Fixture); const element = createElement(Fixture);
// Server rendering moved to a separate package along with ReactDOM // Server rendering moved to a separate package along with ReactDOM
@ -80,11 +80,11 @@
} }
// Finally, React 0.4 and lower emits markup in a callback // Finally, React 0.4 and lower emits markup in a callback
return new Promise(function(resolve) { return new Promise(function (resolve) {
React.renderComponentToString(element, resolve); React.renderComponentToString(element, resolve);
}); });
}) })
.then(function(string) { .then(function (string) {
output.innerHTML = string; output.innerHTML = string;
setStatus('Markup only (No React)'); setStatus('Markup only (No React)');
}) })
@ -124,13 +124,13 @@
} }
function loadScript(src) { function loadScript(src) {
return new Promise(function(resolve, reject) { return new Promise(function (resolve, reject) {
var script = document.createElement('script'); var script = document.createElement('script');
script.async = true; script.async = true;
script.src = src; script.src = src;
script.onload = resolve; script.onload = resolve;
script.onerror = function(error) { script.onerror = function (error) {
reject(new Error('Unable to load ' + src)); reject(new Error('Unable to load ' + src));
}; };
@ -145,7 +145,7 @@
setStatus('Failed'); setStatus('Failed');
output.innerHTML = 'Please name your root component "Fixture"'; output.innerHTML = 'Please name your root component "Fixture"';
} else { } else {
prerender().then(function() { prerender().then(function () {
if (getBooleanQueryParam('hydrate')) { if (getBooleanQueryParam('hydrate')) {
render(); render();
} }
@ -161,14 +161,14 @@
window.onerror = handleError; window.onerror = handleError;
reload.onclick = function() { reload.onclick = function () {
window.location.reload(); window.location.reload();
}; };
hydrate.onclick = render; hydrate.onclick = render;
loadScript(getQueryParam('reactPath')) loadScript(getQueryParam('reactPath'))
.then(function() { .then(function () {
if (needsReactDOM) { if (needsReactDOM) {
return Promise.all([ return Promise.all([
loadScript(getQueryParam('reactDOMPath')), loadScript(getQueryParam('reactDOMPath')),
@ -176,12 +176,12 @@
]); ]);
} }
}) })
.then(function() { .then(function () {
if (failed) { if (failed) {
return; return;
} }
window.addEventListener('message', function(event) { window.addEventListener('message', function (event) {
var data = JSON.parse(event.data); var data = JSON.parse(event.data);
switch (data.type) { switch (data.type) {

View File

@ -243,7 +243,7 @@ class TrySilenceFatalError extends React.Component {
function naiveMemoize(fn) { function naiveMemoize(fn) {
let memoizedEntry; let memoizedEntry;
return function() { return function () {
if (!memoizedEntry) { if (!memoizedEntry) {
memoizedEntry = {result: null}; memoizedEntry = {result: null};
memoizedEntry.result = fn(); memoizedEntry.result = fn();
@ -251,7 +251,7 @@ function naiveMemoize(fn) {
return memoizedEntry.result; return memoizedEntry.result;
}; };
} }
let memoizedFunction = naiveMemoize(function() { let memoizedFunction = naiveMemoize(function () {
throw new Error('Passed'); throw new Error('Passed');
}); });

View File

@ -34,7 +34,7 @@ export class CodeEditor extends React.Component {
lineNumbers: true, lineNumbers: true,
}); });
this.editor.on('change', function(doc) { this.editor.on('change', function (doc) {
onChange(doc.getValue()); onChange(doc.getValue());
}); });
} }

View File

@ -6,7 +6,7 @@ const ReactDOM = window.ReactDOM;
const MouseEnter = () => { const MouseEnter = () => {
const containerRef = React.useRef(); const containerRef = React.useRef();
React.useEffect(function() { React.useEffect(function () {
const hostEl = containerRef.current; const hostEl = containerRef.current;
ReactDOM.render(<MouseEnterDetect />, hostEl, () => { ReactDOM.render(<MouseEnterDetect />, hostEl, () => {
ReactDOM.render(<MouseEnterDetect />, hostEl.childNodes[1]); ReactDOM.render(<MouseEnterDetect />, hostEl.childNodes[1]);

View File

@ -8,7 +8,7 @@ import 'core-js/es6/map';
// requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel // requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel
// MIT license // MIT license
(function() { (function () {
var lastTime = 0; var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o']; var vendors = ['ms', 'moz', 'webkit', 'o'];
for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
@ -19,10 +19,10 @@ import 'core-js/es6/map';
} }
if (!window.requestAnimationFrame) if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) { window.requestAnimationFrame = function (callback, element) {
var currTime = new Date().getTime(); var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { var id = window.setTimeout(function () {
callback(currTime + timeToCall); callback(currTime + timeToCall);
}, timeToCall); }, timeToCall);
lastTime = currTime + timeToCall; lastTime = currTime + timeToCall;
@ -30,7 +30,7 @@ import 'core-js/es6/map';
}; };
if (!window.cancelAnimationFrame) if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) { window.cancelAnimationFrame = function (id) {
clearTimeout(id); clearTimeout(id);
}; };
})(); })();

View File

@ -29,7 +29,7 @@ function Graph(props) {
}); });
var edgeLabels = {}; var edgeLabels = {};
React.Children.forEach(props.children, function(child) { React.Children.forEach(props.children, function (child) {
if (!child) { if (!child) {
return; return;
} }

View File

@ -30,28 +30,28 @@ const app = express();
app.use(compress()); app.use(compress());
app.get( app.get(
'/', '/',
handleErrors(async function(req, res) { handleErrors(async function (req, res) {
await waitForWebpack(); await waitForWebpack();
renderToStream(req.url, res); renderToStream(req.url, res);
}) })
); );
app.get( app.get(
'/string', '/string',
handleErrors(async function(req, res) { handleErrors(async function (req, res) {
await waitForWebpack(); await waitForWebpack();
renderToString(req.url, res); renderToString(req.url, res);
}) })
); );
app.get( app.get(
'/stream', '/stream',
handleErrors(async function(req, res) { handleErrors(async function (req, res) {
await waitForWebpack(); await waitForWebpack();
renderToStream(req.url, res); renderToStream(req.url, res);
}) })
); );
app.get( app.get(
'/buffer', '/buffer',
handleErrors(async function(req, res) { handleErrors(async function (req, res) {
await waitForWebpack(); await waitForWebpack();
renderToBuffer(req.url, res); renderToBuffer(req.url, res);
}) })
@ -63,7 +63,7 @@ app
.listen(PORT, () => { .listen(PORT, () => {
console.log(`Listening at ${PORT}...`); console.log(`Listening at ${PORT}...`);
}) })
.on('error', function(error) { .on('error', function (error) {
if (error.syscall !== 'listen') { if (error.syscall !== 'listen') {
throw error; throw error;
} }
@ -84,7 +84,7 @@ app
}); });
function handleErrors(fn) { function handleErrors(fn) {
return async function(req, res, next) { return async function (req, res, next) {
try { try {
return await fn(req, res); return await fn(req, res);
} catch (x) { } catch (x) {

View File

@ -91,7 +91,7 @@ const hasJsxRuntime = (() => {
// This is the production and development configuration. // This is the production and development configuration.
// It is focused on developer experience, fast rebuilds, and a minimal bundle. // It is focused on developer experience, fast rebuilds, and a minimal bundle.
module.exports = function(webpackEnv) { module.exports = function (webpackEnv) {
const isEnvDevelopment = webpackEnv === 'development'; const isEnvDevelopment = webpackEnv === 'development';
const isEnvProduction = webpackEnv === 'production'; const isEnvProduction = webpackEnv === 'production';

View File

@ -13,7 +13,7 @@ const sockHost = process.env.WDS_SOCKET_HOST;
const sockPath = process.env.WDS_SOCKET_PATH; // default: '/ws' const sockPath = process.env.WDS_SOCKET_PATH; // default: '/ws'
const sockPort = process.env.WDS_SOCKET_PORT; const sockPort = process.env.WDS_SOCKET_PORT;
module.exports = function(proxy, allowedHost) { module.exports = function (proxy, allowedHost) {
const disableFirewall = const disableFirewall =
!proxy || process.env.DANGEROUSLY_DISABLE_HOST_CHECK === 'true'; !proxy || process.env.DANGEROUSLY_DISABLE_HOST_CHECK === 'true';
return { return {

View File

@ -131,8 +131,8 @@ checkBrowsers(paths.appPath, isInteractive)
openBrowser(urls.localUrlForBrowser); openBrowser(urls.localUrlForBrowser);
}); });
['SIGINT', 'SIGTERM'].forEach(function(sig) { ['SIGINT', 'SIGTERM'].forEach(function (sig) {
process.on(sig, function() { process.on(sig, function () {
devServer.close(); devServer.close();
process.exit(); process.exit();
}); });
@ -140,7 +140,7 @@ checkBrowsers(paths.appPath, isInteractive)
if (process.env.CI !== 'true') { if (process.env.CI !== 'true') {
// Gracefully exit when stdin ends // Gracefully exit when stdin ends
process.stdin.on('end', function() { process.stdin.on('end', function () {
devServer.close(); devServer.close();
process.exit(); process.exit();
}); });

View File

@ -10,7 +10,7 @@ babelRegister({
babelrc: false, babelrc: false,
ignore: [ ignore: [
/\/(build|node_modules)\//, /\/(build|node_modules)\//,
function(file) { function (file) {
if ((path.dirname(file) + '/').startsWith(__dirname + '/')) { if ((path.dirname(file) + '/').startsWith(__dirname + '/')) {
// Ignore everything in this folder // Ignore everything in this folder
// because it's a mix of CJS and ESM // because it's a mix of CJS and ESM
@ -28,11 +28,11 @@ const express = require('express');
const app = express(); const app = express();
// Application // Application
app.get('/', function(req, res) { app.get('/', function (req, res) {
require('./handler.server.js')(req, res); require('./handler.server.js')(req, res);
}); });
app.get('/todos', function(req, res) { app.get('/todos', function (req, res) {
res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Origin', '*');
res.json([ res.json([
{ {
@ -50,7 +50,7 @@ app.listen(3001, () => {
console.log('Flight Server listening on port 3001...'); console.log('Flight Server listening on port 3001...');
}); });
app.on('error', function(error) { app.on('error', function (error) {
if (error.syscall !== 'listen') { if (error.syscall !== 'listen') {
throw error; throw error;
} }

View File

@ -5,7 +5,7 @@ const {readFile} = require('fs');
const {resolve} = require('path'); const {resolve} = require('path');
const React = require('react'); const React = require('react');
module.exports = function(req, res) { module.exports = function (req, res) {
// const m = require('../src/App.server.js'); // const m = require('../src/App.server.js');
import('../src/App.server.js').then(m => { import('../src/App.server.js').then(m => {
const dist = process.env.NODE_ENV === 'development' ? 'dist' : 'build'; const dist = process.env.NODE_ENV === 'development' ? 'dist' : 'build';

View File

@ -257,10 +257,10 @@ it('does not warn for arrays of elements with keys', () => {
it('does not warn for iterable elements with keys', () => { it('does not warn for iterable elements with keys', () => {
const iterable = { const iterable = {
'@@iterator': function() { '@@iterator': function () {
let i = 0; let i = 0;
return { return {
next: function() { next: function () {
const done = ++i > 2; const done = ++i > 2;
return { return {
value: done ? undefined : <Component key={'#' + i} />, value: done ? undefined : <Component key={'#' + i} />,
@ -276,10 +276,10 @@ it('does not warn for iterable elements with keys', () => {
it('does not warn for numeric keys in entry iterable as a child', () => { it('does not warn for numeric keys in entry iterable as a child', () => {
const iterable = { const iterable = {
'@@iterator': function() { '@@iterator': function () {
let i = 0; let i = 0;
return { return {
next: function() { next: function () {
const done = ++i > 2; const done = ++i > 2;
return {value: done ? undefined : [i, <Component />], done: done}; return {value: done ? undefined : [i, <Component />], done: done};
}, },
@ -319,9 +319,7 @@ it('should give context for PropType errors in nested components.', () => {
return <MyComp color={123} />; return <MyComp color={123} />;
} }
} }
expect(() => expect(() => ReactTestUtils.renderIntoDocument(<ParentComp />)).toErrorDev(
ReactTestUtils.renderIntoDocument(<ParentComp />)
).toErrorDev(
'Warning: Failed prop type: ' + 'Warning: Failed prop type: ' +
'Invalid prop `color` of type `number` supplied to `MyComp`, ' + 'Invalid prop `color` of type `number` supplied to `MyComp`, ' +
'expected `string`.', 'expected `string`.',
@ -334,9 +332,7 @@ it('gives a helpful error when passing null, undefined, or boolean', () => {
const Null = null; const Null = null;
const True = true; const True = true;
const Div = 'div'; const Div = 'div';
expect( expect(() => void (<Undefined />)).toErrorDev(
() => void (<Undefined />)
).toErrorDev(
'Warning: React.jsx: type is invalid -- expected a string ' + 'Warning: React.jsx: type is invalid -- expected a string ' +
'(for built-in components) or a class/function (for composite ' + '(for built-in components) or a class/function (for composite ' +
'components) but got: undefined. You likely forgot to export your ' + 'components) but got: undefined. You likely forgot to export your ' +
@ -347,9 +343,7 @@ it('gives a helpful error when passing null, undefined, or boolean', () => {
: ''), : ''),
{withoutStack: true} {withoutStack: true}
); );
expect( expect(() => void (<Null />)).toErrorDev(
() => void (<Null />)
).toErrorDev(
'Warning: React.jsx: type is invalid -- expected a string ' + 'Warning: React.jsx: type is invalid -- expected a string ' +
'(for built-in components) or a class/function (for composite ' + '(for built-in components) or a class/function (for composite ' +
'components) but got: null.' + 'components) but got: null.' +
@ -358,9 +352,7 @@ it('gives a helpful error when passing null, undefined, or boolean', () => {
: ''), : ''),
{withoutStack: true} {withoutStack: true}
); );
expect( expect(() => void (<True />)).toErrorDev(
() => void (<True />)
).toErrorDev(
'Warning: React.jsx: type is invalid -- expected a string ' + 'Warning: React.jsx: type is invalid -- expected a string ' +
'(for built-in components) or a class/function (for composite ' + '(for built-in components) or a class/function (for composite ' +
'components) but got: boolean.' + 'components) but got: boolean.' +
@ -721,9 +713,7 @@ it('should warn when `key` is being accessed on composite element', () => {
); );
} }
} }
expect(() => expect(() => ReactDOM.render(<Parent />, container)).toErrorDev(
ReactDOM.render(<Parent />, container)
).toErrorDev(
'Child: `key` is not a prop. Trying to access it will result ' + 'Child: `key` is not a prop. Trying to access it will result ' +
'in `undefined` being returned. If you need to access the same ' + 'in `undefined` being returned. If you need to access the same ' +
'value within the child component, you should pass it as a different ' + 'value within the child component, you should pass it as a different ' +
@ -748,9 +738,7 @@ it('should warn when `ref` is being accessed', () => {
); );
} }
} }
expect(() => expect(() => ReactDOM.render(<Parent />, container)).toErrorDev(
ReactDOM.render(<Parent />, container)
).toErrorDev(
'Child: `ref` is not a prop. Trying to access it will result ' + 'Child: `ref` is not a prop. Trying to access it will result ' +
'in `undefined` being returned. If you need to access the same ' + 'in `undefined` being returned. If you need to access the same ' +
'value within the child component, you should pass it as a different ' + 'value within the child component, you should pass it as a different ' +

View File

@ -254,10 +254,10 @@ it('does not warn for arrays of elements with keys', () => {
it('does not warn for iterable elements with keys', () => { it('does not warn for iterable elements with keys', () => {
const iterable = { const iterable = {
'@@iterator': function() { '@@iterator': function () {
let i = 0; let i = 0;
return { return {
next: function() { next: function () {
const done = ++i > 2; const done = ++i > 2;
return { return {
value: done ? undefined : <Component key={'#' + i} />, value: done ? undefined : <Component key={'#' + i} />,
@ -273,10 +273,10 @@ it('does not warn for iterable elements with keys', () => {
it('does not warn for numeric keys in entry iterable as a child', () => { it('does not warn for numeric keys in entry iterable as a child', () => {
const iterable = { const iterable = {
'@@iterator': function() { '@@iterator': function () {
let i = 0; let i = 0;
return { return {
next: function() { next: function () {
const done = ++i > 2; const done = ++i > 2;
return {value: done ? undefined : [i, <Component />], done: done}; return {value: done ? undefined : [i, <Component />], done: done};
}, },
@ -330,9 +330,7 @@ it('gives a helpful error when passing null, undefined, or boolean', () => {
const Null = null; const Null = null;
const True = true; const True = true;
const Div = 'div'; const Div = 'div';
expect( expect(() => void (<Undefined />)).toErrorDev(
() => void (<Undefined />)
).toErrorDev(
'Warning: React.jsx: type is invalid -- expected a string ' + 'Warning: React.jsx: type is invalid -- expected a string ' +
'(for built-in components) or a class/function (for composite ' + '(for built-in components) or a class/function (for composite ' +
'components) but got: undefined. You likely forgot to export your ' + 'components) but got: undefined. You likely forgot to export your ' +
@ -343,9 +341,7 @@ it('gives a helpful error when passing null, undefined, or boolean', () => {
: ''), : ''),
{withoutStack: true} {withoutStack: true}
); );
expect( expect(() => void (<Null />)).toErrorDev(
() => void (<Null />)
).toErrorDev(
'Warning: React.jsx: type is invalid -- expected a string ' + 'Warning: React.jsx: type is invalid -- expected a string ' +
'(for built-in components) or a class/function (for composite ' + '(for built-in components) or a class/function (for composite ' +
'components) but got: null.' + 'components) but got: null.' +
@ -354,9 +350,7 @@ it('gives a helpful error when passing null, undefined, or boolean', () => {
: ''), : ''),
{withoutStack: true} {withoutStack: true}
); );
expect( expect(() => void (<True />)).toErrorDev(
() => void (<True />)
).toErrorDev(
'Warning: React.jsx: type is invalid -- expected a string ' + 'Warning: React.jsx: type is invalid -- expected a string ' +
'(for built-in components) or a class/function (for composite ' + '(for built-in components) or a class/function (for composite ' +
'components) but got: boolean.' + 'components) but got: boolean.' +
@ -716,9 +710,7 @@ it('should warn when `key` is being accessed on composite element', () => {
); );
} }
} }
expect(() => expect(() => ReactDOM.render(<Parent />, container)).toErrorDev(
ReactDOM.render(<Parent />, container)
).toErrorDev(
'Child: `key` is not a prop. Trying to access it will result ' + 'Child: `key` is not a prop. Trying to access it will result ' +
'in `undefined` being returned. If you need to access the same ' + 'in `undefined` being returned. If you need to access the same ' +
'value within the child component, you should pass it as a different ' + 'value within the child component, you should pass it as a different ' +
@ -743,9 +735,7 @@ it('should warn when `ref` is being accessed', () => {
); );
} }
} }
expect(() => expect(() => ReactDOM.render(<Parent />, container)).toErrorDev(
ReactDOM.render(<Parent />, container)
).toErrorDev(
'Child: `ref` is not a prop. Trying to access it will result ' + 'Child: `ref` is not a prop. Trying to access it will result ' +
'in `undefined` being returned. If you need to access the same ' + 'in `undefined` being returned. If you need to access the same ' +
'value within the child component, you should pass it as a different ' + 'value within the child component, you should pass it as a different ' +

View File

@ -254,10 +254,10 @@ it('does not warn for arrays of elements with keys', () => {
it('does not warn for iterable elements with keys', () => { it('does not warn for iterable elements with keys', () => {
const iterable = { const iterable = {
'@@iterator': function() { '@@iterator': function () {
let i = 0; let i = 0;
return { return {
next: function() { next: function () {
const done = ++i > 2; const done = ++i > 2;
return { return {
value: done ? undefined : <Component key={'#' + i} />, value: done ? undefined : <Component key={'#' + i} />,
@ -273,10 +273,10 @@ it('does not warn for iterable elements with keys', () => {
it('does not warn for numeric keys in entry iterable as a child', () => { it('does not warn for numeric keys in entry iterable as a child', () => {
const iterable = { const iterable = {
'@@iterator': function() { '@@iterator': function () {
let i = 0; let i = 0;
return { return {
next: function() { next: function () {
const done = ++i > 2; const done = ++i > 2;
return {value: done ? undefined : [i, <Component />], done: done}; return {value: done ? undefined : [i, <Component />], done: done};
}, },
@ -330,9 +330,7 @@ it('gives a helpful error when passing null, undefined, or boolean', () => {
const Null = null; const Null = null;
const True = true; const True = true;
const Div = 'div'; const Div = 'div';
expect( expect(() => void (<Undefined />)).toErrorDev(
() => void (<Undefined />)
).toErrorDev(
'Warning: React.jsx: type is invalid -- expected a string ' + 'Warning: React.jsx: type is invalid -- expected a string ' +
'(for built-in components) or a class/function (for composite ' + '(for built-in components) or a class/function (for composite ' +
'components) but got: undefined. You likely forgot to export your ' + 'components) but got: undefined. You likely forgot to export your ' +
@ -343,9 +341,7 @@ it('gives a helpful error when passing null, undefined, or boolean', () => {
: ''), : ''),
{withoutStack: true} {withoutStack: true}
); );
expect( expect(() => void (<Null />)).toErrorDev(
() => void (<Null />)
).toErrorDev(
'Warning: React.jsx: type is invalid -- expected a string ' + 'Warning: React.jsx: type is invalid -- expected a string ' +
'(for built-in components) or a class/function (for composite ' + '(for built-in components) or a class/function (for composite ' +
'components) but got: null.' + 'components) but got: null.' +
@ -354,9 +350,7 @@ it('gives a helpful error when passing null, undefined, or boolean', () => {
: ''), : ''),
{withoutStack: true} {withoutStack: true}
); );
expect( expect(() => void (<True />)).toErrorDev(
() => void (<True />)
).toErrorDev(
'Warning: React.jsx: type is invalid -- expected a string ' + 'Warning: React.jsx: type is invalid -- expected a string ' +
'(for built-in components) or a class/function (for composite ' + '(for built-in components) or a class/function (for composite ' +
'components) but got: boolean.' + 'components) but got: boolean.' +

View File

@ -254,10 +254,10 @@ it('does not warn for arrays of elements with keys', () => {
it('does not warn for iterable elements with keys', () => { it('does not warn for iterable elements with keys', () => {
const iterable = { const iterable = {
'@@iterator': function() { '@@iterator': function () {
let i = 0; let i = 0;
return { return {
next: function() { next: function () {
const done = ++i > 2; const done = ++i > 2;
return { return {
value: done ? undefined : <Component key={'#' + i} />, value: done ? undefined : <Component key={'#' + i} />,
@ -273,10 +273,10 @@ it('does not warn for iterable elements with keys', () => {
it('does not warn for numeric keys in entry iterable as a child', () => { it('does not warn for numeric keys in entry iterable as a child', () => {
const iterable = { const iterable = {
'@@iterator': function() { '@@iterator': function () {
let i = 0; let i = 0;
return { return {
next: function() { next: function () {
const done = ++i > 2; const done = ++i > 2;
return {value: done ? undefined : [i, <Component />], done: done}; return {value: done ? undefined : [i, <Component />], done: done};
}, },
@ -330,9 +330,7 @@ it('gives a helpful error when passing null, undefined, or boolean', () => {
const Null = null; const Null = null;
const True = true; const True = true;
const Div = 'div'; const Div = 'div';
expect( expect(() => void (<Undefined />)).toErrorDev(
() => void (<Undefined />)
).toErrorDev(
'Warning: React.jsx: type is invalid -- expected a string ' + 'Warning: React.jsx: type is invalid -- expected a string ' +
'(for built-in components) or a class/function (for composite ' + '(for built-in components) or a class/function (for composite ' +
'components) but got: undefined. You likely forgot to export your ' + 'components) but got: undefined. You likely forgot to export your ' +
@ -343,9 +341,7 @@ it('gives a helpful error when passing null, undefined, or boolean', () => {
: ''), : ''),
{withoutStack: true} {withoutStack: true}
); );
expect( expect(() => void (<Null />)).toErrorDev(
() => void (<Null />)
).toErrorDev(
'Warning: React.jsx: type is invalid -- expected a string ' + 'Warning: React.jsx: type is invalid -- expected a string ' +
'(for built-in components) or a class/function (for composite ' + '(for built-in components) or a class/function (for composite ' +
'components) but got: null.' + 'components) but got: null.' +
@ -354,9 +350,7 @@ it('gives a helpful error when passing null, undefined, or boolean', () => {
: ''), : ''),
{withoutStack: true} {withoutStack: true}
); );
expect( expect(() => void (<True />)).toErrorDev(
() => void (<True />)
).toErrorDev(
'Warning: React.jsx: type is invalid -- expected a string ' + 'Warning: React.jsx: type is invalid -- expected a string ' +
'(for built-in components) or a class/function (for composite ' + '(for built-in components) or a class/function (for composite ' +
'components) but got: boolean.' + 'components) but got: boolean.' +

View File

@ -49,7 +49,7 @@ function normalizeCodeLocInfo(str) {
// at Component (/path/filename.js:123:45) // at Component (/path/filename.js:123:45)
// React format: // React format:
// in Component (at filename.js:123) // in Component (at filename.js:123)
return str.replace(/\n +(?:at|in) ([\S]+)[^\n]*/g, function(m, name) { return str.replace(/\n +(?:at|in) ([\S]+)[^\n]*/g, function (m, name) {
return '\n in ' + name + ' (at **)'; return '\n in ' + name + ' (at **)';
}); });
} }

View File

@ -19,8 +19,9 @@ export default function lazyLegacyRoot(getLegacyComponent) {
}; };
return function Wrapper(props) { return function Wrapper(props) {
const createLegacyRoot = readModule(rendererModule, () => const createLegacyRoot = readModule(
import('../legacy/createLegacyRoot') rendererModule,
() => import('../legacy/createLegacyRoot')
).default; ).default;
const Component = readModule(componentModule, getLegacyComponent).default; const Component = readModule(componentModule, getLegacyComponent).default;
const containerRef = useRef(null); const containerRef = useRef(null);

View File

@ -1,4 +1,4 @@
require(['react', 'react-dom'], function(React, ReactDOM) { require(['react', 'react-dom'], function (React, ReactDOM) {
ReactDOM.render( ReactDOM.render(
React.createElement('h1', null, 'Hello World!'), React.createElement('h1', null, 'Hello World!'),
document.getElementById('container') document.getElementById('container')

View File

@ -1,4 +1,4 @@
require(['react', 'react-dom'], function(React, ReactDOM) { require(['react', 'react-dom'], function (React, ReactDOM) {
ReactDOM.render( ReactDOM.render(
React.createElement('h1', null, 'Hello World!'), React.createElement('h1', null, 'Hello World!'),
document.getElementById('container') document.getElementById('container')

View File

@ -3,10 +3,10 @@ var Builder = require('systemjs-builder');
var builder = new Builder('/', './config.js'); var builder = new Builder('/', './config.js');
builder builder
.buildStatic('./input.js', './output.js') .buildStatic('./input.js', './output.js')
.then(function() { .then(function () {
console.log('Build complete'); console.log('Build complete');
}) })
.catch(function(err) { .catch(function (err) {
console.log('Build error'); console.log('Build error');
console.log(err); console.log(err);
}); });

View File

@ -3,10 +3,10 @@ var Builder = require('systemjs-builder');
var builder = new Builder('/', './config.js'); var builder = new Builder('/', './config.js');
builder builder
.buildStatic('./input.js', './output.js') .buildStatic('./input.js', './output.js')
.then(function() { .then(function () {
console.log('Build complete'); console.log('Build complete');
}) })
.catch(function(err) { .catch(function (err) {
console.log('Build error'); console.log('Build error');
console.log(err); console.log(err);
}); });

View File

@ -14,7 +14,7 @@ const app = express();
// Application // Application
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
app.get('/', function(req, res) { app.get('/', function (req, res) {
// In development mode we clear the module cache between each request to // In development mode we clear the module cache between each request to
// get automatic hot reloading. // get automatic hot reloading.
for (var key in require.cache) { for (var key in require.cache) {
@ -25,7 +25,7 @@ if (process.env.NODE_ENV === 'development') {
}); });
} else { } else {
const render = require('./render').default; const render = require('./render').default;
app.get('/', function(req, res) { app.get('/', function (req, res) {
render(req.url, res); render(req.url, res);
}); });
} }
@ -48,7 +48,7 @@ app.listen(3000, () => {
console.log('Listening on port 3000...'); console.log('Listening on port 3000...');
}); });
app.on('error', function(error) { app.on('error', function (error) {
if (error.syscall !== 'listen') { if (error.syscall !== 'listen') {
throw error; throw error;
} }

View File

@ -38,7 +38,7 @@ app.use((req, res, next) => {
app.use(compress()); app.use(compress());
app.get( app.get(
'/', '/',
handleErrors(async function(req, res) { handleErrors(async function (req, res) {
await waitForWebpack(); await waitForWebpack();
render(req.url, res); render(req.url, res);
}) })
@ -50,7 +50,7 @@ app
.listen(PORT, () => { .listen(PORT, () => {
console.log(`Listening at ${PORT}...`); console.log(`Listening at ${PORT}...`);
}) })
.on('error', function(error) { .on('error', function (error) {
if (error.syscall !== 'listen') { if (error.syscall !== 'listen') {
throw error; throw error;
} }
@ -71,7 +71,7 @@ app
}); });
function handleErrors(fn) { function handleErrors(fn) {
return async function(req, res, next) { return async function (req, res, next) {
try { try {
return await fn(req, res); return await fn(req, res);
} catch (x) { } catch (x) {

View File

@ -29,7 +29,7 @@ function _inheritsLoose(subClass, superClass) {
// Compile this with Babel. // Compile this with Babel.
// babel --config-file ./babel.config.json BabelClasses.js --out-file BabelClasses-compiled.js --source-maps // babel --config-file ./babel.config.json BabelClasses.js --out-file BabelClasses-compiled.js --source-maps
let BabelClass = /*#__PURE__*/ (function(_React$Component) { let BabelClass = /*#__PURE__*/ (function (_React$Component) {
_inheritsLoose(BabelClass, _React$Component); _inheritsLoose(BabelClass, _React$Component);
function BabelClass() { function BabelClass() {
@ -45,7 +45,7 @@ let BabelClass = /*#__PURE__*/ (function(_React$Component) {
return BabelClass; return BabelClass;
})(React.Component); })(React.Component);
let BabelClassWithFields = /*#__PURE__*/ (function(_React$Component2) { let BabelClassWithFields = /*#__PURE__*/ (function (_React$Component2) {
_inheritsLoose(BabelClassWithFields, _React$Component2); _inheritsLoose(BabelClassWithFields, _React$Component2);
function BabelClassWithFields(...args) { function BabelClassWithFields(...args) {

View File

@ -79,7 +79,7 @@
"mkdirp": "^0.5.1", "mkdirp": "^0.5.1",
"ncp": "^2.0.0", "ncp": "^2.0.0",
"pacote": "^10.3.0", "pacote": "^10.3.0",
"prettier": "1.19.1", "prettier": "2.8.3",
"prop-types": "^15.6.2", "prop-types": "^15.6.2",
"random-seed": "^0.3.0", "random-seed": "^0.3.0",
"react-lifecycles-compat": "^3.0.4", "react-lifecycles-compat": "^3.0.4",
@ -88,7 +88,7 @@
"rollup-plugin-babel": "^4.0.1", "rollup-plugin-babel": "^4.0.1",
"rollup-plugin-commonjs": "^9.3.4", "rollup-plugin-commonjs": "^9.3.4",
"rollup-plugin-node-resolve": "^2.1.1", "rollup-plugin-node-resolve": "^2.1.1",
"rollup-plugin-prettier": "^0.6.0", "rollup-plugin-prettier": "^3.0.0",
"rollup-plugin-replace": "^2.2.0", "rollup-plugin-replace": "^2.2.0",
"rollup-plugin-strip-banner": "^0.2.0", "rollup-plugin-strip-banner": "^0.2.0",
"semver": "^7.1.1", "semver": "^7.1.1",

View File

@ -13,7 +13,7 @@
* Change environment support for PointerEvent. * Change environment support for PointerEvent.
*/ */
const emptyFunction = function() {}; const emptyFunction = function () {};
export function hasPointerEvent() { export function hasPointerEvent() {
return global != null && global.PointerEvent != null; return global != null && global.PointerEvent != null;

View File

@ -93,7 +93,7 @@ const createEventTarget = node => ({
* Utilities * Utilities
*/ */
setBoundingClientRect({x, y, width, height}) { setBoundingClientRect({x, y, width, height}) {
node.getBoundingClientRect = function() { node.getBoundingClientRect = function () {
return { return {
width, width,
height, height,

View File

@ -1525,8 +1525,7 @@ const tests = {
'Either include it or remove the dependency array.', 'Either include it or remove the dependency array.',
suggestions: [ suggestions: [
{ {
desc: desc: 'Update the dependencies array to be: [props.foo?.bar?.baz]',
'Update the dependencies array to be: [props.foo?.bar?.baz]',
output: normalizeIndent` output: normalizeIndent`
function MyComponent(props) { function MyComponent(props) {
useCallback(() => { useCallback(() => {
@ -2662,8 +2661,7 @@ const tests = {
'Either include them or remove the dependency array.', 'Either include them or remove the dependency array.',
suggestions: [ suggestions: [
{ {
desc: desc: 'Update the dependencies array to be: [props.bar, props.foo]',
'Update the dependencies array to be: [props.bar, props.foo]',
output: normalizeIndent` output: normalizeIndent`
function MyComponent(props) { function MyComponent(props) {
const local = {}; const local = {};
@ -2819,8 +2817,7 @@ const tests = {
'Either include it or remove the dependency array.', 'Either include it or remove the dependency array.',
suggestions: [ suggestions: [
{ {
desc: desc: 'Update the dependencies array to be: [color, props.foo.bar.baz]',
'Update the dependencies array to be: [color, props.foo.bar.baz]',
output: normalizeIndent` output: normalizeIndent`
function MyComponent(props) { function MyComponent(props) {
let color = {} let color = {}
@ -2884,8 +2881,7 @@ const tests = {
'Either include them or remove the dependency array.', 'Either include them or remove the dependency array.',
suggestions: [ suggestions: [
{ {
desc: desc: 'Update the dependencies array to be: [props.foo.bar.baz, props.foo.fizz.bizz]',
'Update the dependencies array to be: [props.foo.bar.baz, props.foo.fizz.bizz]',
output: normalizeIndent` output: normalizeIndent`
function MyComponent(props) { function MyComponent(props) {
const fn = useCallback(() => { const fn = useCallback(() => {
@ -3095,8 +3091,7 @@ const tests = {
'Either include them or remove the dependency array.', 'Either include them or remove the dependency array.',
suggestions: [ suggestions: [
{ {
desc: desc: 'Update the dependencies array to be: [props.bar, props.foo]',
'Update the dependencies array to be: [props.bar, props.foo]',
output: normalizeIndent` output: normalizeIndent`
function MyComponent(props) { function MyComponent(props) {
useEffect(() => { useEffect(() => {
@ -3127,8 +3122,7 @@ const tests = {
// Don't alphabetize if it wasn't alphabetized in the first place. // Don't alphabetize if it wasn't alphabetized in the first place.
suggestions: [ suggestions: [
{ {
desc: desc: 'Update the dependencies array to be: [c, a, g, b, e, d, f]',
'Update the dependencies array to be: [c, a, g, b, e, d, f]',
output: normalizeIndent` output: normalizeIndent`
function MyComponent(props) { function MyComponent(props) {
let a, b, c, d, e, f, g; let a, b, c, d, e, f, g;
@ -3159,8 +3153,7 @@ const tests = {
// Alphabetize if it was alphabetized. // Alphabetize if it was alphabetized.
suggestions: [ suggestions: [
{ {
desc: desc: 'Update the dependencies array to be: [a, b, c, d, e, f, g]',
'Update the dependencies array to be: [a, b, c, d, e, f, g]',
output: normalizeIndent` output: normalizeIndent`
function MyComponent(props) { function MyComponent(props) {
let a, b, c, d, e, f, g; let a, b, c, d, e, f, g;
@ -3191,8 +3184,7 @@ const tests = {
// Alphabetize if it was empty. // Alphabetize if it was empty.
suggestions: [ suggestions: [
{ {
desc: desc: 'Update the dependencies array to be: [a, b, c, d, e, f, g]',
'Update the dependencies array to be: [a, b, c, d, e, f, g]',
output: normalizeIndent` output: normalizeIndent`
function MyComponent(props) { function MyComponent(props) {
let a, b, c, d, e, f, g; let a, b, c, d, e, f, g;
@ -3224,8 +3216,7 @@ const tests = {
'Either include them or remove the dependency array.', 'Either include them or remove the dependency array.',
suggestions: [ suggestions: [
{ {
desc: desc: 'Update the dependencies array to be: [local, props.bar, props.foo]',
'Update the dependencies array to be: [local, props.bar, props.foo]',
output: normalizeIndent` output: normalizeIndent`
function MyComponent(props) { function MyComponent(props) {
const local = {}; const local = {};
@ -3812,8 +3803,7 @@ const tests = {
'Either include them or remove the dependency array.', 'Either include them or remove the dependency array.',
suggestions: [ suggestions: [
{ {
desc: desc: 'Update the dependencies array to be: [props.color, props.someOtherRefs]',
'Update the dependencies array to be: [props.color, props.someOtherRefs]',
output: normalizeIndent` output: normalizeIndent`
function MyComponent(props) { function MyComponent(props) {
const ref1 = useRef(); const ref1 = useRef();
@ -3853,8 +3843,7 @@ const tests = {
"because mutating them doesn't re-render the component.", "because mutating them doesn't re-render the component.",
suggestions: [ suggestions: [
{ {
desc: desc: 'Update the dependencies array to be: [props.someOtherRefs, props.color]',
'Update the dependencies array to be: [props.someOtherRefs, props.color]',
output: normalizeIndent` output: normalizeIndent`
function MyComponent(props) { function MyComponent(props) {
const ref1 = useRef(); const ref1 = useRef();
@ -3894,8 +3883,7 @@ const tests = {
"because mutating them doesn't re-render the component.", "because mutating them doesn't re-render the component.",
suggestions: [ suggestions: [
{ {
desc: desc: 'Update the dependencies array to be: [props.someOtherRefs, props.color]',
'Update the dependencies array to be: [props.someOtherRefs, props.color]',
output: normalizeIndent` output: normalizeIndent`
function MyComponent(props) { function MyComponent(props) {
const ref1 = useRef(); const ref1 = useRef();
@ -4287,8 +4275,7 @@ const tests = {
`props inside useEffect.`, `props inside useEffect.`,
suggestions: [ suggestions: [
{ {
desc: desc: 'Update the dependencies array to be: [skillsCount, props.isEditMode, props.toggleEditMode, props]',
'Update the dependencies array to be: [skillsCount, props.isEditMode, props.toggleEditMode, props]',
output: normalizeIndent` output: normalizeIndent`
function MyComponent(props) { function MyComponent(props) {
const [skillsCount] = useState(); const [skillsCount] = useState();
@ -4719,8 +4706,7 @@ const tests = {
'Either include it or remove the dependency array.', 'Either include it or remove the dependency array.',
suggestions: [ suggestions: [
{ {
desc: desc: 'Update the dependencies array to be: [local1, local3, local4]',
'Update the dependencies array to be: [local1, local3, local4]',
output: normalizeIndent` output: normalizeIndent`
function MyComponent() { function MyComponent() {
const local1 = 42; const local1 = 42;
@ -5562,8 +5548,7 @@ const tests = {
// the easy fix and you can't just move it into effect. // the easy fix and you can't just move it into effect.
suggestions: [ suggestions: [
{ {
desc: desc: "Wrap the definition of 'handleNext' in its own useCallback() Hook.",
"Wrap the definition of 'handleNext' in its own useCallback() Hook.",
output: normalizeIndent` output: normalizeIndent`
function MyComponent(props) { function MyComponent(props) {
let [, setState] = useState(); let [, setState] = useState();
@ -5737,8 +5722,7 @@ const tests = {
// because they are only referenced outside the effect. // because they are only referenced outside the effect.
suggestions: [ suggestions: [
{ {
desc: desc: "Wrap the definition of 'handleNext2' in its own useCallback() Hook.",
"Wrap the definition of 'handleNext2' in its own useCallback() Hook.",
output: normalizeIndent` output: normalizeIndent`
function MyComponent(props) { function MyComponent(props) {
function handleNext1() { function handleNext1() {
@ -5787,8 +5771,7 @@ const tests = {
// because they are only referenced outside the effect. // because they are only referenced outside the effect.
suggestions: [ suggestions: [
{ {
desc: desc: "Wrap the definition of 'handleNext3' in its own useCallback() Hook.",
"Wrap the definition of 'handleNext3' in its own useCallback() Hook.",
output: normalizeIndent` output: normalizeIndent`
function MyComponent(props) { function MyComponent(props) {
function handleNext1() { function handleNext1() {
@ -5862,8 +5845,7 @@ const tests = {
"definition of 'handleNext1' in its own useCallback() Hook.", "definition of 'handleNext1' in its own useCallback() Hook.",
suggestions: [ suggestions: [
{ {
desc: desc: "Wrap the definition of 'handleNext1' in its own useCallback() Hook.",
"Wrap the definition of 'handleNext1' in its own useCallback() Hook.",
output: normalizeIndent` output: normalizeIndent`
function MyComponent(props) { function MyComponent(props) {
const handleNext1 = useCallback(() => { const handleNext1 = useCallback(() => {
@ -5892,8 +5874,7 @@ const tests = {
"definition of 'handleNext1' in its own useCallback() Hook.", "definition of 'handleNext1' in its own useCallback() Hook.",
suggestions: [ suggestions: [
{ {
desc: desc: "Wrap the definition of 'handleNext1' in its own useCallback() Hook.",
"Wrap the definition of 'handleNext1' in its own useCallback() Hook.",
output: normalizeIndent` output: normalizeIndent`
function MyComponent(props) { function MyComponent(props) {
const handleNext1 = useCallback(() => { const handleNext1 = useCallback(() => {
@ -5959,8 +5940,7 @@ const tests = {
// it only wraps the first definition. But seems ok. // it only wraps the first definition. But seems ok.
suggestions: [ suggestions: [
{ {
desc: desc: "Wrap the definition of 'handleNext' in its own useCallback() Hook.",
"Wrap the definition of 'handleNext' in its own useCallback() Hook.",
output: normalizeIndent` output: normalizeIndent`
function MyComponent(props) { function MyComponent(props) {
let handleNext = useCallback(() => { let handleNext = useCallback(() => {
@ -6493,8 +6473,7 @@ const tests = {
`find the parent component that defines it and wrap that definition in useCallback.`, `find the parent component that defines it and wrap that definition in useCallback.`,
suggestions: [ suggestions: [
{ {
desc: desc: 'Update the dependencies array to be: [fetchPodcasts, fetchPodcasts2, id]',
'Update the dependencies array to be: [fetchPodcasts, fetchPodcasts2, id]',
output: normalizeIndent` output: normalizeIndent`
function Podcasts({ fetchPodcasts, fetchPodcasts2, id }) { function Podcasts({ fetchPodcasts, fetchPodcasts2, id }) {
let [podcasts, setPodcasts] = useState(null); let [podcasts, setPodcasts] = useState(null);
@ -7135,8 +7114,7 @@ const tests = {
'Either include them or remove the dependency array.', 'Either include them or remove the dependency array.',
suggestions: [ suggestions: [
{ {
desc: desc: 'Update the dependencies array to be: [foo.bar, props.foo.bar]',
'Update the dependencies array to be: [foo.bar, props.foo.bar]',
output: normalizeIndent` output: normalizeIndent`
function MyComponent(props) { function MyComponent(props) {
let foo = {} let foo = {}
@ -7845,8 +7823,7 @@ const testsTypescript = {
'Either include them or remove the dependency array.', 'Either include them or remove the dependency array.',
suggestions: [ suggestions: [
{ {
desc: desc: 'Update the dependencies array to be: [pizza.crust, pizza?.toppings]',
'Update the dependencies array to be: [pizza.crust, pizza?.toppings]',
output: normalizeIndent` output: normalizeIndent`
function MyComponent() { function MyComponent() {
const pizza = {}; const pizza = {};
@ -7981,8 +7958,7 @@ const testsTypescript = {
'Either include it or remove the dependency array.', 'Either include it or remove the dependency array.',
suggestions: [ suggestions: [
{ {
desc: desc: 'Update the dependencies array to be: [props.upperViewHeight]',
'Update the dependencies array to be: [props.upperViewHeight]',
output: normalizeIndent` output: normalizeIndent`
function Example(props) { function Example(props) {
useEffect(() => { useEffect(() => {
@ -8013,8 +7989,7 @@ const testsTypescript = {
'Either include it or remove the dependency array.', 'Either include it or remove the dependency array.',
suggestions: [ suggestions: [
{ {
desc: desc: 'Update the dependencies array to be: [props?.upperViewHeight]',
'Update the dependencies array to be: [props?.upperViewHeight]',
output: normalizeIndent` output: normalizeIndent`
function Example(props) { function Example(props) {
useEffect(() => { useEffect(() => {

View File

@ -76,7 +76,7 @@ export default {
const functionWithoutCapturedValueCache = new WeakMap(); const functionWithoutCapturedValueCache = new WeakMap();
const useEffectEventVariables = new WeakSet(); const useEffectEventVariables = new WeakSet();
function memoizeWithWeakMap(fn, map) { function memoizeWithWeakMap(fn, map) {
return function(arg) { return function (arg) {
if (map.has(arg)) { if (map.has(arg)) {
// to verify cache hits: // to verify cache hits:
// console.log(arg.name) // console.log(arg.name)

View File

@ -383,9 +383,8 @@ export default {
// This is a valid code path for React hooks if we are directly in a React // This is a valid code path for React hooks if we are directly in a React
// function component or we are in a hook function. // function component or we are in a hook function.
const isSomewhereInsideComponentOrHook = isInsideComponentOrHook( const isSomewhereInsideComponentOrHook =
codePathNode, isInsideComponentOrHook(codePathNode);
);
const isDirectlyInsideComponentOrHook = codePathFunctionName const isDirectlyInsideComponentOrHook = codePathFunctionName
? isComponentName(codePathFunctionName) || ? isComponentName(codePathFunctionName) ||
isHook(codePathFunctionName) isHook(codePathFunctionName)

View File

@ -127,7 +127,7 @@ class Text extends React.Component {
// ref directly. // ref directly.
['height', 'width', 'x', 'y'].forEach(key => { ['height', 'width', 'x', 'y'].forEach(key => {
Object.defineProperty(this, key, { Object.defineProperty(this, key, {
get: function() { get: function () {
return this._text ? this._text[key] : undefined; return this._text ? this._text[key] : undefined;
}, },
}); });

View File

@ -59,7 +59,7 @@ function testDOMNodeStructure(domNode, expectedStructure) {
} }
} }
if (expectedStructure.children) { if (expectedStructure.children) {
expectedStructure.children.forEach(function(subTree, index) { expectedStructure.children.forEach(function (subTree, index) {
testDOMNodeStructure(domNode.childNodes[index], subTree); testDOMNodeStructure(domNode.childNodes[index], subTree);
}); });
} }

View File

@ -104,7 +104,7 @@ function Chunk(status: any, value: any, reason: any, response: Response) {
// We subclass Promise.prototype so that we get other methods like .catch // We subclass Promise.prototype so that we get other methods like .catch
Chunk.prototype = (Object.create(Promise.prototype): any); Chunk.prototype = (Object.create(Promise.prototype): any);
// TODO: This doesn't return a new Promise chain unlike the real .then // TODO: This doesn't return a new Promise chain unlike the real .then
Chunk.prototype.then = function<T>( Chunk.prototype.then = function <T>(
this: SomeChunk<T>, this: SomeChunk<T>,
resolve: (value: T) => mixed, resolve: (value: T) => mixed,
reject: (reason: mixed) => mixed, reject: (reason: mixed) => mixed,

View File

@ -123,7 +123,7 @@ export function processBinaryChunk(
function createFromJSONCallback(response: Response) { function createFromJSONCallback(response: Response) {
// $FlowFixMe[missing-this-annot] // $FlowFixMe[missing-this-annot]
return function(key: string, value: JSONValue) { return function (key: string, value: JSONValue) {
if (typeof value === 'string') { if (typeof value === 'string') {
// We can't use .bind here because we need the "this" value. // We can't use .bind here because we need the "this" value.
return parseModelString(response, this, key, value); return parseModelString(response, this, key, value);

View File

@ -93,7 +93,7 @@ describe('ReactFlight', () => {
function clientReference(value) { function clientReference(value) {
return Object.defineProperties( return Object.defineProperties(
function() { function () {
throw new Error('Cannot call a client function from the server.'); throw new Error('Cannot call a client function from the server.');
}, },
{ {
@ -378,7 +378,7 @@ describe('ReactFlight', () => {
function EventHandlerProp() { function EventHandlerProp() {
return ( return (
<div className="foo" onClick={function() {}}> <div className="foo" onClick={function () {}}>
Test Test
</div> </div>
); );
@ -397,7 +397,7 @@ describe('ReactFlight', () => {
function EventHandlerPropClient() { function EventHandlerPropClient() {
return ( return (
<Client className="foo" onClick={function() {}}> <Client className="foo" onClick={function () {}}>
Test Test
</Client> </Client>
); );

View File

@ -58,10 +58,8 @@ describe('ReactHooksInspectionIntegration', () => {
}, },
]); ]);
const { const {onMouseDown: setStateA, onMouseUp: setStateB} =
onMouseDown: setStateA, renderer.root.findByType('div').props;
onMouseUp: setStateB,
} = renderer.root.findByType('div').props;
act(() => setStateA('Hi')); act(() => setStateA('Hi'));
@ -469,8 +467,8 @@ describe('ReactHooksInspectionIntegration', () => {
}); });
it('should inspect forwardRef', () => { it('should inspect forwardRef', () => {
const obj = function() {}; const obj = function () {};
const Foo = React.forwardRef(function(props, ref) { const Foo = React.forwardRef(function (props, ref) {
React.useImperativeHandle(ref, () => obj); React.useImperativeHandle(ref, () => obj);
return <div />; return <div />;
}); });

View File

@ -42,7 +42,8 @@ installHook(window);
const hook: ?DevToolsHook = window.__REACT_DEVTOOLS_GLOBAL_HOOK__; const hook: ?DevToolsHook = window.__REACT_DEVTOOLS_GLOBAL_HOOK__;
let savedComponentFilters: Array<ComponentFilter> = getDefaultComponentFilters(); let savedComponentFilters: Array<ComponentFilter> =
getDefaultComponentFilters();
function debug(methodName: string, ...args: Array<mixed>) { function debug(methodName: string, ...args: Array<mixed>) {
if (__DEBUG__) { if (__DEBUG__) {
@ -114,7 +115,7 @@ export function connectToDevTools(options: ?ConnectOptions) {
ws.onclose = handleClose; ws.onclose = handleClose;
ws.onerror = handleFailed; ws.onerror = handleFailed;
ws.onmessage = handleMessage; ws.onmessage = handleMessage;
ws.onopen = function() { ws.onopen = function () {
bridge = new Bridge({ bridge = new Bridge({
listen(fn) { listen(fn) {
messageListeners.push(fn); messageListeners.push(fn);

View File

@ -33,7 +33,8 @@ function initializeConsolePatchSettings(
if (devToolsSettingsManager.getConsolePatchSettings == null) { if (devToolsSettingsManager.getConsolePatchSettings == null) {
return; return;
} }
const consolePatchSettingsString = devToolsSettingsManager.getConsolePatchSettings(); const consolePatchSettingsString =
devToolsSettingsManager.getConsolePatchSettings();
if (consolePatchSettingsString == null) { if (consolePatchSettingsString == null) {
return; return;
} }

View File

@ -186,9 +186,9 @@ export function launchEditor(
} else { } else {
childProcess = spawn(editor, args, {stdio: 'inherit'}); childProcess = spawn(editor, args, {stdio: 'inherit'});
} }
childProcess.on('error', function() {}); childProcess.on('error', function () {});
// $FlowFixMe[incompatible-use] found when upgrading Flow // $FlowFixMe[incompatible-use] found when upgrading Flow
childProcess.on('exit', function(errorCode) { childProcess.on('exit', function (errorCode) {
childProcess = null; childProcess = null;
}); });
} }

View File

@ -283,7 +283,7 @@ function connectToSocket(socket: WebSocket): {close(): void} {
initialize(socket); initialize(socket);
return { return {
close: function() { close: function () {
onDisconnected(); onDisconnected();
}, },
}; };
@ -390,7 +390,7 @@ function startServer(
}); });
return { return {
close: function() { close: function () {
connected = null; connected = null;
onDisconnected(); onDisconnected();
if (startServerTimeoutID !== null) { if (startServerTimeoutID !== null) {

View File

@ -27,10 +27,7 @@ const main = async buildId => {
const json = JSON.parse(file); const json = JSON.parse(file);
const alias = json.alias[0]; const alias = json.alias[0];
const commit = execSync('git rev-parse HEAD') const commit = execSync('git rev-parse HEAD').toString().trim().substr(0, 7);
.toString()
.trim()
.substr(0, 7);
let date = new Date(); let date = new Date();
date = `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`; date = `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`;

View File

@ -2,14 +2,14 @@
'use strict'; 'use strict';
document.addEventListener('DOMContentLoaded', function() { document.addEventListener('DOMContentLoaded', function () {
// Make links work // Make links work
const links = document.getElementsByTagName('a'); const links = document.getElementsByTagName('a');
for (let i = 0; i < links.length; i++) { for (let i = 0; i < links.length; i++) {
(function() { (function () {
const ln = links[i]; const ln = links[i];
const location = ln.href; const location = ln.href;
ln.onclick = function() { ln.onclick = function () {
chrome.tabs.create({active: true, url: location}); chrome.tabs.create({active: true, url: location});
return false; return false;
}; };
@ -19,7 +19,7 @@ document.addEventListener('DOMContentLoaded', function() {
// Work around https://bugs.chromium.org/p/chromium/issues/detail?id=428044 // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=428044
document.body.style.opacity = 0; document.body.style.opacity = 0;
document.body.style.transition = 'opacity ease-out .4s'; document.body.style.transition = 'opacity ease-out .4s';
requestAnimationFrame(function() { requestAnimationFrame(function () {
document.body.style.opacity = 1; document.body.style.opacity = 1;
}); });
}); });

View File

@ -51,8 +51,8 @@ function setup(hook: any) {
const Agent = require('react-devtools-shared/src/backend/agent').default; const Agent = require('react-devtools-shared/src/backend/agent').default;
const Bridge = require('react-devtools-shared/src/bridge').default; const Bridge = require('react-devtools-shared/src/bridge').default;
const {initBackend} = require('react-devtools-shared/src/backend'); const {initBackend} = require('react-devtools-shared/src/backend');
const setupNativeStyleEditor = require('react-devtools-shared/src/backend/NativeStyleEditor/setupNativeStyleEditor') const setupNativeStyleEditor =
.default; require('react-devtools-shared/src/backend/NativeStyleEditor/setupNativeStyleEditor').default;
const bridge = new Bridge({ const bridge = new Bridge({
listen(fn) { listen(fn) {

View File

@ -30,7 +30,7 @@ if (!IS_FIREFOX) {
]); ]);
} }
chrome.runtime.onConnect.addListener(function(port) { chrome.runtime.onConnect.addListener(function (port) {
let tab = null; let tab = null;
let name = null; let name = null;
if (isNumeric(port.name)) { if (isNumeric(port.name)) {
@ -61,7 +61,7 @@ function isNumeric(str: string): boolean {
function installProxy(tabId: number) { function installProxy(tabId: number) {
if (IS_FIREFOX) { if (IS_FIREFOX) {
chrome.tabs.executeScript(tabId, {file: '/build/proxy.js'}, function() {}); chrome.tabs.executeScript(tabId, {file: '/build/proxy.js'}, function () {});
} else { } else {
chrome.scripting.executeScript({ chrome.scripting.executeScript({
target: {tabId: tabId}, target: {tabId: tabId},

View File

@ -5,17 +5,18 @@ if (!window.hasOwnProperty('__REACT_DEVTOOLS_GLOBAL_HOOK__')) {
installHook(window); installHook(window);
// detect react // detect react
window.__REACT_DEVTOOLS_GLOBAL_HOOK__.on('renderer', function({ window.__REACT_DEVTOOLS_GLOBAL_HOOK__.on(
reactBuildType, 'renderer',
}) { function ({reactBuildType}) {
window.postMessage( window.postMessage(
{ {
source: 'react-devtools-detector', source: 'react-devtools-detector',
reactBuildType, reactBuildType,
}, },
'*', '*',
); );
}); },
);
// save native values // save native values
window.__REACT_DEVTOOLS_GLOBAL_HOOK__.nativeObjectCreate = Object.create; window.__REACT_DEVTOOLS_GLOBAL_HOOK__.nativeObjectCreate = Object.create;

View File

@ -8,7 +8,7 @@ import {IS_FIREFOX} from '../utils';
function injectScriptSync(src) { function injectScriptSync(src) {
let code = ''; let code = '';
const request = new XMLHttpRequest(); const request = new XMLHttpRequest();
request.addEventListener('load', function() { request.addEventListener('load', function () {
code = this.responseText; code = this.responseText;
}); });
request.open('GET', src, false); request.open('GET', src, false);
@ -26,7 +26,7 @@ function injectScriptSync(src) {
function injectScriptAsync(src) { function injectScriptAsync(src) {
const script = document.createElement('script'); const script = document.createElement('script');
script.src = src; script.src = src;
script.onload = function() { script.onload = function () {
script.remove(); script.remove();
}; };
nullthrows(document.documentElement).appendChild(script); nullthrows(document.documentElement).appendChild(script);
@ -105,7 +105,7 @@ window.addEventListener('message', function onMessage({data, source}) {
// while navigating the history to a document that has not been destroyed yet, // while navigating the history to a document that has not been destroyed yet,
// replay the last detection result if the content script is active and the // replay the last detection result if the content script is active and the
// document has been hidden and shown again. // document has been hidden and shown again.
window.addEventListener('pageshow', function({target}) { window.addEventListener('pageshow', function ({target}) {
if (!lastDetectionResult || target !== window.document) { if (!lastDetectionResult || target !== window.document) {
return; return;
} }

View File

@ -39,10 +39,10 @@ if (isChrome || isEdge) {
// The polyfill is based on https://gist.github.com/jalbam/5fe05443270fa6d8136238ec72accbc0 // The polyfill is based on https://gist.github.com/jalbam/5fe05443270fa6d8136238ec72accbc0
const FRAME_TIME = 16; const FRAME_TIME = 16;
let lastTime = 0; let lastTime = 0;
window.requestAnimationFrame = function(callback, element) { window.requestAnimationFrame = function (callback, element) {
const now = window.performance.now(); const now = window.performance.now();
const nextTime = Math.max(lastTime + FRAME_TIME, now); const nextTime = Math.max(lastTime + FRAME_TIME, now);
return setTimeout(function() { return setTimeout(function () {
callback((lastTime = nextTime)); callback((lastTime = nextTime));
}, nextTime - now); }, nextTime - now);
}; };
@ -91,7 +91,7 @@ function createPanelIfReactLoaded() {
chrome.devtools.inspectedWindow.eval( chrome.devtools.inspectedWindow.eval(
'window.__REACT_DEVTOOLS_GLOBAL_HOOK__ && window.__REACT_DEVTOOLS_GLOBAL_HOOK__.renderers.size > 0', 'window.__REACT_DEVTOOLS_GLOBAL_HOOK__ && window.__REACT_DEVTOOLS_GLOBAL_HOOK__.renderers.size > 0',
function(pageHasReact, error) { function (pageHasReact, error) {
if (!pageHasReact || panelCreated) { if (!pageHasReact || panelCreated) {
return; return;
} }
@ -199,7 +199,7 @@ function createPanelIfReactLoaded() {
// Otherwise the Store may miss important initial tree op codes. // Otherwise the Store may miss important initial tree op codes.
chrome.devtools.inspectedWindow.eval( chrome.devtools.inspectedWindow.eval(
`window.postMessage({ source: 'react-devtools-inject-backend' }, '*');`, `window.postMessage({ source: 'react-devtools-inject-backend' }, '*');`,
function(response, evalError) { function (response, evalError) {
if (evalError) { if (evalError) {
console.error(evalError); console.error(evalError);
} }
@ -553,7 +553,7 @@ chrome.devtools.network.onNavigated.addListener(checkPageForReact);
// Check to see if React has loaded once per second in case React is added // Check to see if React has loaded once per second in case React is added
// after page load // after page load
const loadCheckInterval = setInterval(function() { const loadCheckInterval = setInterval(function () {
createPanelIfReactLoaded(); createPanelIfReactLoaded();
}, 1000); }, 1000);

View File

@ -61,10 +61,8 @@ test.describe('Components', () => {
// Then read the inspected values. // Then read the inspected values.
const [propName, propValue, sourceText] = await page.evaluate( const [propName, propValue, sourceText] = await page.evaluate(
isEditable => { isEditable => {
const { const {createTestNameSelector, findAllNodes} =
createTestNameSelector, window.REACT_DOM_DEVTOOLS;
findAllNodes,
} = window.REACT_DOM_DEVTOOLS;
const container = document.getElementById('devtools'); const container = document.getElementById('devtools');
// Get name of first prop // Get name of first prop
@ -150,10 +148,8 @@ test.describe('Components', () => {
// Make sure the expected hook names are parsed and displayed eventually. // Make sure the expected hook names are parsed and displayed eventually.
await page.waitForFunction( await page.waitForFunction(
hookNames => { hookNames => {
const { const {createTestNameSelector, findAllNodes} =
createTestNameSelector, window.REACT_DOM_DEVTOOLS;
findAllNodes,
} = window.REACT_DOM_DEVTOOLS;
const container = document.getElementById('devtools'); const container = document.getElementById('devtools');
const hooksTree = findAllNodes(container, [ const hooksTree = findAllNodes(container, [
@ -181,10 +177,8 @@ test.describe('Components', () => {
test('should allow searching for component by name', async () => { test('should allow searching for component by name', async () => {
async function getComponentSearchResultsCount() { async function getComponentSearchResultsCount() {
return await page.evaluate(() => { return await page.evaluate(() => {
const { const {createTestNameSelector, findAllNodes} =
createTestNameSelector, window.REACT_DOM_DEVTOOLS;
findAllNodes,
} = window.REACT_DOM_DEVTOOLS;
const container = document.getElementById('devtools'); const container = document.getElementById('devtools');
const element = findAllNodes(container, [ const element = findAllNodes(container, [

View File

@ -16,11 +16,8 @@ async function clickButton(page, buttonTestName) {
async function getElementCount(page, displayName) { async function getElementCount(page, displayName) {
return await page.evaluate(listItemText => { return await page.evaluate(listItemText => {
const { const {createTestNameSelector, createTextSelector, findAllNodes} =
createTestNameSelector, window.REACT_DOM_DEVTOOLS;
createTextSelector,
findAllNodes,
} = window.REACT_DOM_DEVTOOLS;
const container = document.getElementById('devtools'); const container = document.getElementById('devtools');
const rows = findAllNodes(container, [ const rows = findAllNodes(container, [
createTestNameSelector('ComponentTreeListItem'), createTestNameSelector('ComponentTreeListItem'),
@ -32,11 +29,8 @@ async function getElementCount(page, displayName) {
async function selectElement(page, displayName, waitForOwnersText) { async function selectElement(page, displayName, waitForOwnersText) {
await page.evaluate(listItemText => { await page.evaluate(listItemText => {
const { const {createTestNameSelector, createTextSelector, findAllNodes} =
createTestNameSelector, window.REACT_DOM_DEVTOOLS;
createTextSelector,
findAllNodes,
} = window.REACT_DOM_DEVTOOLS;
const container = document.getElementById('devtools'); const container = document.getElementById('devtools');
const listItem = findAllNodes(container, [ const listItem = findAllNodes(container, [
@ -50,10 +44,8 @@ async function selectElement(page, displayName, waitForOwnersText) {
// Wait for selected element's props to load. // Wait for selected element's props to load.
await page.waitForFunction( await page.waitForFunction(
({titleText, ownersListText}) => { ({titleText, ownersListText}) => {
const { const {createTestNameSelector, findAllNodes} =
createTestNameSelector, window.REACT_DOM_DEVTOOLS;
findAllNodes,
} = window.REACT_DOM_DEVTOOLS;
const container = document.getElementById('devtools'); const container = document.getElementById('devtools');
const title = findAllNodes(container, [ const title = findAllNodes(container, [

View File

@ -27,10 +27,8 @@ test.describe('Profiler', () => {
runOnlyForReactRange('>=16.5'); runOnlyForReactRange('>=16.5');
async function getSnapshotSelectorText() { async function getSnapshotSelectorText() {
return await page.evaluate(() => { return await page.evaluate(() => {
const { const {createTestNameSelector, findAllNodes} =
createTestNameSelector, window.REACT_DOM_DEVTOOLS;
findAllNodes,
} = window.REACT_DOM_DEVTOOLS;
const container = document.getElementById('devtools'); const container = document.getElementById('devtools');
const input = findAllNodes(container, [ const input = findAllNodes(container, [

View File

@ -24,11 +24,15 @@ function startActivation(contentWindow: any, bridge: BackendBridge) {
hideConsoleLogsInStrictMode, hideConsoleLogsInStrictMode,
} = data; } = data;
contentWindow.__REACT_DEVTOOLS_APPEND_COMPONENT_STACK__ = appendComponentStack; contentWindow.__REACT_DEVTOOLS_APPEND_COMPONENT_STACK__ =
contentWindow.__REACT_DEVTOOLS_BREAK_ON_CONSOLE_ERRORS__ = breakOnConsoleErrors; appendComponentStack;
contentWindow.__REACT_DEVTOOLS_BREAK_ON_CONSOLE_ERRORS__ =
breakOnConsoleErrors;
contentWindow.__REACT_DEVTOOLS_COMPONENT_FILTERS__ = componentFilters; contentWindow.__REACT_DEVTOOLS_COMPONENT_FILTERS__ = componentFilters;
contentWindow.__REACT_DEVTOOLS_SHOW_INLINE_WARNINGS_AND_ERRORS__ = showInlineWarningsAndErrors; contentWindow.__REACT_DEVTOOLS_SHOW_INLINE_WARNINGS_AND_ERRORS__ =
contentWindow.__REACT_DEVTOOLS_HIDE_CONSOLE_LOGS_IN_STRICT_MODE__ = hideConsoleLogsInStrictMode; showInlineWarningsAndErrors;
contentWindow.__REACT_DEVTOOLS_HIDE_CONSOLE_LOGS_IN_STRICT_MODE__ =
hideConsoleLogsInStrictMode;
// TRICKY // TRICKY
// The backend entry point may be required in the context of an iframe or the parent window. // The backend entry point may be required in the context of an iframe or the parent window.
@ -40,8 +44,10 @@ function startActivation(contentWindow: any, bridge: BackendBridge) {
window.__REACT_DEVTOOLS_APPEND_COMPONENT_STACK__ = appendComponentStack; window.__REACT_DEVTOOLS_APPEND_COMPONENT_STACK__ = appendComponentStack;
window.__REACT_DEVTOOLS_BREAK_ON_CONSOLE_ERRORS__ = breakOnConsoleErrors; window.__REACT_DEVTOOLS_BREAK_ON_CONSOLE_ERRORS__ = breakOnConsoleErrors;
window.__REACT_DEVTOOLS_COMPONENT_FILTERS__ = componentFilters; window.__REACT_DEVTOOLS_COMPONENT_FILTERS__ = componentFilters;
window.__REACT_DEVTOOLS_SHOW_INLINE_WARNINGS_AND_ERRORS__ = showInlineWarningsAndErrors; window.__REACT_DEVTOOLS_SHOW_INLINE_WARNINGS_AND_ERRORS__ =
window.__REACT_DEVTOOLS_HIDE_CONSOLE_LOGS_IN_STRICT_MODE__ = hideConsoleLogsInStrictMode; showInlineWarningsAndErrors;
window.__REACT_DEVTOOLS_HIDE_CONSOLE_LOGS_IN_STRICT_MODE__ =
hideConsoleLogsInStrictMode;
} }
finishActivation(contentWindow, bridge); finishActivation(contentWindow, bridge);

View File

@ -112,8 +112,8 @@ describe('Timeline profiler', () => {
} }
beforeEach(() => { beforeEach(() => {
setPerformanceMock = require('react-devtools-shared/src/backend/profilingHooks') setPerformanceMock =
.setPerformanceMock_ONLY_FOR_TESTING; require('react-devtools-shared/src/backend/profilingHooks').setPerformanceMock_ONLY_FOR_TESTING;
setPerformanceMock(createUserTimingPolyfill()); setPerformanceMock(createUserTimingPolyfill());
}); });

View File

@ -11,9 +11,8 @@
export function test(maybeDehydratedValue) { export function test(maybeDehydratedValue) {
const {meta} = require('react-devtools-shared/src/hydration'); const {meta} = require('react-devtools-shared/src/hydration');
const hasOwnProperty = Object.prototype.hasOwnProperty.bind( const hasOwnProperty =
maybeDehydratedValue, Object.prototype.hasOwnProperty.bind(maybeDehydratedValue);
);
return ( return (
maybeDehydratedValue !== null && maybeDehydratedValue !== null &&
typeof maybeDehydratedValue === 'object' && typeof maybeDehydratedValue === 'object' &&

View File

@ -430,7 +430,7 @@ describe('console', () => {
it('should be resilient to prepareStackTrace', () => { it('should be resilient to prepareStackTrace', () => {
global.__REACT_DEVTOOLS_APPEND_COMPONENT_STACK__ = true; global.__REACT_DEVTOOLS_APPEND_COMPONENT_STACK__ = true;
Error.prepareStackTrace = function(error, callsites) { Error.prepareStackTrace = function (error, callsites) {
const stack = ['An error occurred:', error.message]; const stack = ['An error occurred:', error.message];
for (let i = 0; i < callsites.length; i++) { for (let i = 0; i < callsites.length; i++) {
const callsite = callsites[i]; const callsite = callsites[i];

View File

@ -59,18 +59,18 @@ describe('InspectedElement', () => {
TestRenderer = utils.requireTestRenderer(); TestRenderer = utils.requireTestRenderer();
TestRendererAct = require('jest-react').act; TestRendererAct = require('jest-react').act;
BridgeContext = require('react-devtools-shared/src/devtools/views/context') BridgeContext =
.BridgeContext; require('react-devtools-shared/src/devtools/views/context').BridgeContext;
InspectedElementContext = require('react-devtools-shared/src/devtools/views/Components/InspectedElementContext') InspectedElementContext =
.InspectedElementContext; require('react-devtools-shared/src/devtools/views/Components/InspectedElementContext').InspectedElementContext;
InspectedElementContextController = require('react-devtools-shared/src/devtools/views/Components/InspectedElementContext') InspectedElementContextController =
.InspectedElementContextController; require('react-devtools-shared/src/devtools/views/Components/InspectedElementContext').InspectedElementContextController;
SettingsContextController = require('react-devtools-shared/src/devtools/views/Settings/SettingsContext') SettingsContextController =
.SettingsContextController; require('react-devtools-shared/src/devtools/views/Settings/SettingsContext').SettingsContextController;
StoreContext = require('react-devtools-shared/src/devtools/views/context') StoreContext =
.StoreContext; require('react-devtools-shared/src/devtools/views/context').StoreContext;
TreeContextController = require('react-devtools-shared/src/devtools/views/Components/TreeContext') TreeContextController =
.TreeContextController; require('react-devtools-shared/src/devtools/views/Components/TreeContext').TreeContextController;
// Used by inspectElementAtIndex() helper function // Used by inspectElementAtIndex() helper function
utils.act(() => { utils.act(() => {
@ -616,8 +616,8 @@ describe('InspectedElement', () => {
const instance = new Class(); const instance = new Class();
const proxyInstance = new Proxy(() => {}, { const proxyInstance = new Proxy(() => {}, {
get: function(_, name) { get: function (_, name) {
return function() { return function () {
return null; return null;
}; };
}, },
@ -1777,7 +1777,8 @@ describe('InspectedElement', () => {
), ),
); );
let copyPath: CopyInspectedElementPath = ((null: any): CopyInspectedElementPath); let copyPath: CopyInspectedElementPath =
((null: any): CopyInspectedElementPath);
const id = ((store.getElementIDAtIndex(0): any): number); const id = ((store.getElementIDAtIndex(0): any): number);
await inspectElementAtIndex(0, () => { await inspectElementAtIndex(0, () => {
@ -1864,7 +1865,8 @@ describe('InspectedElement', () => {
const id = ((store.getElementIDAtIndex(0): any): number); const id = ((store.getElementIDAtIndex(0): any): number);
let copyPath: CopyInspectedElementPath = ((null: any): CopyInspectedElementPath); let copyPath: CopyInspectedElementPath =
((null: any): CopyInspectedElementPath);
await inspectElementAtIndex(0, () => { await inspectElementAtIndex(0, () => {
copyPath = (path: Array<string | number>) => { copyPath = (path: Array<string | number>) => {

View File

@ -39,16 +39,16 @@ describe('OwnersListContext', () => {
React = require('react'); React = require('react');
TestRenderer = utils.requireTestRenderer(); TestRenderer = utils.requireTestRenderer();
BridgeContext = require('react-devtools-shared/src/devtools/views/context') BridgeContext =
.BridgeContext; require('react-devtools-shared/src/devtools/views/context').BridgeContext;
OwnersListContext = require('react-devtools-shared/src/devtools/views/Components/OwnersListContext') OwnersListContext =
.OwnersListContext; require('react-devtools-shared/src/devtools/views/Components/OwnersListContext').OwnersListContext;
OwnersListContextController = require('react-devtools-shared/src/devtools/views/Components/OwnersListContext') OwnersListContextController =
.OwnersListContextController; require('react-devtools-shared/src/devtools/views/Components/OwnersListContext').OwnersListContextController;
StoreContext = require('react-devtools-shared/src/devtools/views/context') StoreContext =
.StoreContext; require('react-devtools-shared/src/devtools/views/context').StoreContext;
TreeContextController = require('react-devtools-shared/src/devtools/views/Components/TreeContext') TreeContextController =
.TreeContextController; require('react-devtools-shared/src/devtools/views/Components/TreeContext').TreeContextController;
}); });
const Contexts = ({children, defaultOwnerID = null}) => ( const Contexts = ({children, defaultOwnerID = null}) => (

View File

@ -82,8 +82,8 @@ describe('Timeline profiler', () => {
ReactDOMClient = require('react-dom/client'); ReactDOMClient = require('react-dom/client');
Scheduler = require('scheduler'); Scheduler = require('scheduler');
setPerformanceMock = require('react-devtools-shared/src/backend/profilingHooks') setPerformanceMock =
.setPerformanceMock_ONLY_FOR_TESTING; require('react-devtools-shared/src/backend/profilingHooks').setPerformanceMock_ONLY_FOR_TESTING;
setPerformanceMock(createUserTimingPolyfill()); setPerformanceMock(createUserTimingPolyfill());
const store = global.store; const store = global.store;
@ -105,8 +105,8 @@ describe('Timeline profiler', () => {
let getLanesFromTransportDecimalBitmask; let getLanesFromTransportDecimalBitmask;
beforeEach(() => { beforeEach(() => {
getLanesFromTransportDecimalBitmask = require('react-devtools-timeline/src/import-worker/preprocessData') getLanesFromTransportDecimalBitmask =
.getLanesFromTransportDecimalBitmask; require('react-devtools-timeline/src/import-worker/preprocessData').getLanesFromTransportDecimalBitmask;
}); });
// @reactVersion >= 18.0 // @reactVersion >= 18.0
@ -115,11 +115,7 @@ describe('Timeline profiler', () => {
expect(getLanesFromTransportDecimalBitmask('512')).toEqual([9]); expect(getLanesFromTransportDecimalBitmask('512')).toEqual([9]);
expect(getLanesFromTransportDecimalBitmask('3')).toEqual([0, 1]); expect(getLanesFromTransportDecimalBitmask('3')).toEqual([0, 1]);
expect(getLanesFromTransportDecimalBitmask('1234')).toEqual([ expect(getLanesFromTransportDecimalBitmask('1234')).toEqual([
1, 1, 4, 6, 7, 10,
4,
6,
7,
10,
]); // 2 + 16 + 64 + 128 + 1024 ]); // 2 + 16 + 64 + 128 + 1024
expect( expect(
getLanesFromTransportDecimalBitmask('1073741824'), // 0b1000000000000000000000000000000 getLanesFromTransportDecimalBitmask('1073741824'), // 0b1000000000000000000000000000000
@ -139,8 +135,8 @@ describe('Timeline profiler', () => {
// @reactVersion >= 18.0 // @reactVersion >= 18.0
it('should ignore lanes outside REACT_TOTAL_NUM_LANES', () => { it('should ignore lanes outside REACT_TOTAL_NUM_LANES', () => {
const REACT_TOTAL_NUM_LANES = require('react-devtools-timeline/src/constants') const REACT_TOTAL_NUM_LANES =
.REACT_TOTAL_NUM_LANES; require('react-devtools-timeline/src/constants').REACT_TOTAL_NUM_LANES;
// Sanity check; this test may need to be updated when the no. of fiber lanes are changed. // Sanity check; this test may need to be updated when the no. of fiber lanes are changed.
expect(REACT_TOTAL_NUM_LANES).toBe(31); expect(REACT_TOTAL_NUM_LANES).toBe(31);
@ -157,8 +153,8 @@ describe('Timeline profiler', () => {
let preprocessData; let preprocessData;
beforeEach(() => { beforeEach(() => {
preprocessData = require('react-devtools-timeline/src/import-worker/preprocessData') preprocessData =
.default; require('react-devtools-timeline/src/import-worker/preprocessData').default;
}); });
// These should be dynamic to mimic a real profile, // These should be dynamic to mimic a real profile,
@ -177,8 +173,8 @@ describe('Timeline profiler', () => {
} }
function createProfilerVersionEntry() { function createProfilerVersionEntry() {
const SCHEDULING_PROFILER_VERSION = require('react-devtools-timeline/src/constants') const SCHEDULING_PROFILER_VERSION =
.SCHEDULING_PROFILER_VERSION; require('react-devtools-timeline/src/constants').SCHEDULING_PROFILER_VERSION;
return createUserTimingEntry({ return createUserTimingEntry({
cat: 'blink.user_timing', cat: 'blink.user_timing',
name: '--profiler-version-' + SCHEDULING_PROFILER_VERSION, name: '--profiler-version-' + SCHEDULING_PROFILER_VERSION,
@ -195,8 +191,7 @@ describe('Timeline profiler', () => {
function createLaneLabelsEntry() { function createLaneLabelsEntry() {
return createUserTimingEntry({ return createUserTimingEntry({
cat: 'blink.user_timing', cat: 'blink.user_timing',
name: name: '--react-lane-labels-Sync,InputContinuousHydration,InputContinuous,DefaultHydration,Default,TransitionHydration,Transition,Transition,Transition,Transition,Transition,Transition,Transition,Transition,Transition,Transition,Transition,Transition,Transition,Transition,Transition,Transition,Retry,Retry,Retry,Retry,Retry,SelectiveHydration,IdleHydration,Idle,Offscreen',
'--react-lane-labels-Sync,InputContinuousHydration,InputContinuous,DefaultHydration,Default,TransitionHydration,Transition,Transition,Transition,Transition,Transition,Transition,Transition,Transition,Transition,Transition,Transition,Transition,Transition,Transition,Transition,Transition,Retry,Retry,Retry,Retry,Retry,SelectiveHydration,IdleHydration,Idle,Offscreen',
}); });
} }

View File

@ -45,20 +45,20 @@ describe('ProfilerContext', () => {
ReactDOM = require('react-dom'); ReactDOM = require('react-dom');
TestRenderer = utils.requireTestRenderer(); TestRenderer = utils.requireTestRenderer();
BridgeContext = require('react-devtools-shared/src/devtools/views/context') BridgeContext =
.BridgeContext; require('react-devtools-shared/src/devtools/views/context').BridgeContext;
ProfilerContext = require('react-devtools-shared/src/devtools/views/Profiler/ProfilerContext') ProfilerContext =
.ProfilerContext; require('react-devtools-shared/src/devtools/views/Profiler/ProfilerContext').ProfilerContext;
ProfilerContextController = require('react-devtools-shared/src/devtools/views/Profiler/ProfilerContext') ProfilerContextController =
.ProfilerContextController; require('react-devtools-shared/src/devtools/views/Profiler/ProfilerContext').ProfilerContextController;
StoreContext = require('react-devtools-shared/src/devtools/views/context') StoreContext =
.StoreContext; require('react-devtools-shared/src/devtools/views/context').StoreContext;
TreeContextController = require('react-devtools-shared/src/devtools/views/Components/TreeContext') TreeContextController =
.TreeContextController; require('react-devtools-shared/src/devtools/views/Components/TreeContext').TreeContextController;
TreeDispatcherContext = require('react-devtools-shared/src/devtools/views/Components/TreeContext') TreeDispatcherContext =
.TreeDispatcherContext; require('react-devtools-shared/src/devtools/views/Components/TreeContext').TreeDispatcherContext;
TreeStateContext = require('react-devtools-shared/src/devtools/views/Components/TreeContext') TreeStateContext =
.TreeStateContext; require('react-devtools-shared/src/devtools/views/Components/TreeContext').TreeStateContext;
}); });
const Contexts = ({ const Contexts = ({

View File

@ -182,14 +182,14 @@ describe('ProfilingCache', () => {
const rootID = store.roots[0]; const rootID = store.roots[0];
const prevCommitData = store.profilerStore.getDataForRoot(rootID) const prevCommitData =
.commitData; store.profilerStore.getDataForRoot(rootID).commitData;
expect(prevCommitData).toHaveLength(4); expect(prevCommitData).toHaveLength(4);
utils.exportImportHelper(bridge, store); utils.exportImportHelper(bridge, store);
const nextCommitData = store.profilerStore.getDataForRoot(rootID) const nextCommitData =
.commitData; store.profilerStore.getDataForRoot(rootID).commitData;
expect(nextCommitData).toHaveLength(4); expect(nextCommitData).toHaveLength(4);
nextCommitData.forEach((commitData, index) => { nextCommitData.forEach((commitData, index) => {
expect(commitData).toEqual(prevCommitData[index]); expect(commitData).toEqual(prevCommitData[index]);
@ -1094,8 +1094,10 @@ describe('ProfilingCache', () => {
utils.act(() => setChildUnmounted(true)); utils.act(() => setChildUnmounted(true));
utils.act(() => store.profilerStore.stopProfiling()); utils.act(() => store.profilerStore.stopProfiling());
const updaters = store.profilerStore.getCommitData(store.roots[0], 0) const updaters = store.profilerStore.getCommitData(
.updaters; store.roots[0],
0,
).updaters;
expect(updaters.length).toEqual(1); expect(updaters.length).toEqual(1);
expect(updaters[0].displayName).toEqual('App'); expect(updaters[0].displayName).toEqual('App');
}); });
@ -1129,8 +1131,10 @@ describe('ProfilingCache', () => {
utils.act(() => setChildUnmounted(true)); utils.act(() => setChildUnmounted(true));
utils.act(() => store.profilerStore.stopProfiling()); utils.act(() => store.profilerStore.stopProfiling());
const updaters = store.profilerStore.getCommitData(store.roots[0], 0) const updaters = store.profilerStore.getCommitData(
.updaters; store.roots[0],
0,
).updaters;
expect(updaters.length).toEqual(1); expect(updaters.length).toEqual(1);
expect(updaters[0].displayName).toEqual('App'); expect(updaters[0].displayName).toEqual('App');
}); });
@ -1159,8 +1163,10 @@ describe('ProfilingCache', () => {
utils.act(() => setChildUnmounted(true)); utils.act(() => setChildUnmounted(true));
utils.act(() => store.profilerStore.stopProfiling()); utils.act(() => store.profilerStore.stopProfiling());
const updaters = store.profilerStore.getCommitData(store.roots[0], 0) const updaters = store.profilerStore.getCommitData(
.updaters; store.roots[0],
0,
).updaters;
expect(updaters.length).toEqual(1); expect(updaters.length).toEqual(1);
expect(updaters[0].displayName).toEqual('App'); expect(updaters[0].displayName).toEqual('App');
}); });

View File

@ -1444,9 +1444,8 @@ describe('Store', () => {
<MyComponent2 /> <MyComponent2 />
)); ));
const MyComponent3 = (props, ref) => null; const MyComponent3 = (props, ref) => null;
const ForwardRefComponentWithCustomDisplayName = React.forwardRef( const ForwardRefComponentWithCustomDisplayName =
MyComponent3, React.forwardRef(MyComponent3);
);
ForwardRefComponentWithCustomDisplayName.displayName = 'Custom'; ForwardRefComponentWithCustomDisplayName.displayName = 'Custom';
const MyComponent4 = (props, ref) => null; const MyComponent4 = (props, ref) => null;
const MemoComponent = React.memo(MyComponent4); const MemoComponent = React.memo(MyComponent4);
@ -1467,9 +1466,8 @@ describe('Store', () => {
); );
MemoizedFakeHigherOrderComponentWithDisplayNameOverride.displayName = MemoizedFakeHigherOrderComponentWithDisplayNameOverride.displayName =
'memoRefOverride'; 'memoRefOverride';
const ForwardRefFakeHigherOrderComponentWithDisplayNameOverride = React.forwardRef( const ForwardRefFakeHigherOrderComponentWithDisplayNameOverride =
FakeHigherOrderComponent, React.forwardRef(FakeHigherOrderComponent);
);
ForwardRefFakeHigherOrderComponentWithDisplayNameOverride.displayName = ForwardRefFakeHigherOrderComponentWithDisplayNameOverride.displayName =
'forwardRefOverride'; 'forwardRefOverride';

View File

@ -47,10 +47,10 @@ describe('TreeListContext', () => {
ReactDOM = require('react-dom'); ReactDOM = require('react-dom');
TestRenderer = utils.requireTestRenderer(); TestRenderer = utils.requireTestRenderer();
BridgeContext = require('react-devtools-shared/src/devtools/views/context') BridgeContext =
.BridgeContext; require('react-devtools-shared/src/devtools/views/context').BridgeContext;
StoreContext = require('react-devtools-shared/src/devtools/views/context') StoreContext =
.StoreContext; require('react-devtools-shared/src/devtools/views/context').StoreContext;
TreeContext = require('react-devtools-shared/src/devtools/views/Components/TreeContext'); TreeContext = require('react-devtools-shared/src/devtools/views/Components/TreeContext');
}); });

View File

@ -190,9 +190,9 @@ describe('utils', () => {
// The last letter isn't gray here but I think it's not a big // The last letter isn't gray here but I think it's not a big
// deal, since there is a string substituion but it's incorrect // deal, since there is a string substituion but it's incorrect
expect( expect(formatWithStyles(['%s %s', 'a', 'b', 'c'], 'color: gray')).toEqual(
formatWithStyles(['%s %s', 'a', 'b', 'c'], 'color: gray'), ['%c%s %s', 'color: gray', 'a', 'b', 'c'],
).toEqual(['%c%s %s', 'color: gray', 'a', 'b', 'c']); );
}); });
// @reactVersion >= 16.0 // @reactVersion >= 16.0

View File

@ -203,7 +203,8 @@ export function exportImportHelper(bridge: FrontendBridge, store: Store): void {
expect(profilerStore.profilingData).not.toBeNull(); expect(profilerStore.profilingData).not.toBeNull();
const profilingDataFrontendInitial = ((profilerStore.profilingData: any): ProfilingDataFrontend); const profilingDataFrontendInitial =
((profilerStore.profilingData: any): ProfilingDataFrontend);
expect(profilingDataFrontendInitial.imported).toBe(false); expect(profilingDataFrontendInitial.imported).toBe(false);
const profilingDataExport = prepareProfilingDataExport( const profilingDataExport = prepareProfilingDataExport(
@ -301,7 +302,7 @@ export function normalizeCodeLocInfo(str) {
// at Component (/path/filename.js:123:45) // at Component (/path/filename.js:123:45)
// React format: // React format:
// in Component (at filename.js:123) // in Component (at filename.js:123)
return str.replace(/\n +(?:at|in) ([\S]+)[^\n]*/g, function(m, name) { return str.replace(/\n +(?:at|in) ([\S]+)[^\n]*/g, function (m, name) {
return '\n in ' + name + ' (at **)'; return '\n in ' + name + ' (at **)';
}); });
} }

View File

@ -95,12 +95,12 @@ export function describeNativeComponentFrame(
// This should throw. // This should throw.
if (construct) { if (construct) {
// Something should be setting the props in the constructor. // Something should be setting the props in the constructor.
const Fake = function() { const Fake = function () {
throw Error(); throw Error();
}; };
// $FlowFixMe // $FlowFixMe
Object.defineProperty(Fake.prototype, 'props', { Object.defineProperty(Fake.prototype, 'props', {
set: function() { set: function () {
// We use a throwing setter instead of frozen or non-writable props // We use a throwing setter instead of frozen or non-writable props
// because that won't throw in a non-strict mode function. // because that won't throw in a non-strict mode function.
throw Error(); throw Error();

View File

@ -569,20 +569,19 @@ export default class Agent extends EventEmitter<{
} }
}; };
reloadAndProfile: ( reloadAndProfile: (recordChangeDescriptions: boolean) => void =
recordChangeDescriptions: boolean, recordChangeDescriptions => {
) => void = recordChangeDescriptions => { sessionStorageSetItem(SESSION_STORAGE_RELOAD_AND_PROFILE_KEY, 'true');
sessionStorageSetItem(SESSION_STORAGE_RELOAD_AND_PROFILE_KEY, 'true'); sessionStorageSetItem(
sessionStorageSetItem( SESSION_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY,
SESSION_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY, recordChangeDescriptions ? 'true' : 'false',
recordChangeDescriptions ? 'true' : 'false', );
);
// This code path should only be hit if the shell has explicitly told the Store that it supports profiling. // This code path should only be hit if the shell has explicitly told the Store that it supports profiling.
// In that case, the shell must also listen for this specific message to know when it needs to reload the app. // In that case, the shell must also listen for this specific message to know when it needs to reload the app.
// The agent can't do this in a way that is renderer agnostic. // The agent can't do this in a way that is renderer agnostic.
this._bridge.send('reloadAppForProfiling'); this._bridge.send('reloadAppForProfiling');
}; };
renamePath: RenamePathParams => void = ({ renamePath: RenamePathParams => void = ({
hookID, hookID,
@ -628,20 +627,19 @@ export default class Agent extends EventEmitter<{
} }
} }
setTraceUpdatesEnabled: ( setTraceUpdatesEnabled: (traceUpdatesEnabled: boolean) => void =
traceUpdatesEnabled: boolean, traceUpdatesEnabled => {
) => void = traceUpdatesEnabled => { this._traceUpdatesEnabled = traceUpdatesEnabled;
this._traceUpdatesEnabled = traceUpdatesEnabled;
setTraceUpdatesEnabled(traceUpdatesEnabled); setTraceUpdatesEnabled(traceUpdatesEnabled);
for (const rendererID in this._rendererInterfaces) { for (const rendererID in this._rendererInterfaces) {
const renderer = ((this._rendererInterfaces[ const renderer = ((this._rendererInterfaces[
(rendererID: any) (rendererID: any)
]: any): RendererInterface); ]: any): RendererInterface);
renderer.setTraceUpdatesEnabled(traceUpdatesEnabled); renderer.setTraceUpdatesEnabled(traceUpdatesEnabled);
} }
}; };
syncSelectionFromNativeElementsPanel: () => void = () => { syncSelectionFromNativeElementsPanel: () => void = () => {
const target = window.__REACT_DEVTOOLS_GLOBAL_HOOK__.$0; const target = window.__REACT_DEVTOOLS_GLOBAL_HOOK__.$0;
@ -656,19 +654,18 @@ export default class Agent extends EventEmitter<{
this.emit('shutdown'); this.emit('shutdown');
}; };
startProfiling: ( startProfiling: (recordChangeDescriptions: boolean) => void =
recordChangeDescriptions: boolean, recordChangeDescriptions => {
) => void = recordChangeDescriptions => { this._recordChangeDescriptions = recordChangeDescriptions;
this._recordChangeDescriptions = recordChangeDescriptions; this._isProfiling = true;
this._isProfiling = true; for (const rendererID in this._rendererInterfaces) {
for (const rendererID in this._rendererInterfaces) { const renderer = ((this._rendererInterfaces[
const renderer = ((this._rendererInterfaces[ (rendererID: any)
(rendererID: any) ]: any): RendererInterface);
]: any): RendererInterface); renderer.startProfiling(recordChangeDescriptions);
renderer.startProfiling(recordChangeDescriptions); }
} this._bridge.send('profilingStatus', this._isProfiling);
this._bridge.send('profilingStatus', this._isProfiling); };
};
stopProfiling: () => void = () => { stopProfiling: () => void = () => {
this._isProfiling = false; this._isProfiling = false;
@ -726,16 +723,15 @@ export default class Agent extends EventEmitter<{
}); });
}; };
updateComponentFilters: ( updateComponentFilters: (componentFilters: Array<ComponentFilter>) => void =
componentFilters: Array<ComponentFilter>, componentFilters => {
) => void = componentFilters => { for (const rendererID in this._rendererInterfaces) {
for (const rendererID in this._rendererInterfaces) { const renderer = ((this._rendererInterfaces[
const renderer = ((this._rendererInterfaces[ (rendererID: any)
(rendererID: any) ]: any): RendererInterface);
]: any): RendererInterface); renderer.updateComponentFilters(componentFilters);
renderer.updateComponentFilters(componentFilters); }
} };
};
viewAttributeSource: CopyElementParams => void = ({id, path, rendererID}) => { viewAttributeSource: CopyElementParams => void = ({id, path, rendererID}) => {
const renderer = this._rendererInterfaces[rendererID]; const renderer = this._rendererInterfaces[rendererID];

View File

@ -354,8 +354,10 @@ export function patchForStrictMode() {
} }
}; };
overrideMethod.__REACT_DEVTOOLS_STRICT_MODE_ORIGINAL_METHOD__ = originalMethod; overrideMethod.__REACT_DEVTOOLS_STRICT_MODE_ORIGINAL_METHOD__ =
originalMethod.__REACT_DEVTOOLS_STRICT_MODE_OVERRIDE_METHOD__ = overrideMethod; originalMethod;
originalMethod.__REACT_DEVTOOLS_STRICT_MODE_OVERRIDE_METHOD__ =
overrideMethod;
targetConsole[method] = overrideMethod; targetConsole[method] = overrideMethod;
} catch (error) {} } catch (error) {}

View File

@ -137,16 +137,13 @@ export function attach(
global: Object, global: Object,
): RendererInterface { ): RendererInterface {
const idToInternalInstanceMap: Map<number, InternalInstance> = new Map(); const idToInternalInstanceMap: Map<number, InternalInstance> = new Map();
const internalInstanceToIDMap: WeakMap< const internalInstanceToIDMap: WeakMap<InternalInstance, number> =
InternalInstance, new WeakMap();
number, const internalInstanceToRootIDMap: WeakMap<InternalInstance, number> =
> = new WeakMap(); new WeakMap();
const internalInstanceToRootIDMap: WeakMap<
InternalInstance,
number,
> = new WeakMap();
let getInternalIDForNative: GetFiberIDForNative = ((null: any): GetFiberIDForNative); let getInternalIDForNative: GetFiberIDForNative =
((null: any): GetFiberIDForNative);
let findNativeNodeForInternalID: (id: number) => ?NativeType; let findNativeNodeForInternalID: (id: number) => ?NativeType;
let getFiberForNative = (node: NativeType) => { let getFiberForNative = (node: NativeType) => {
// Not implemented. // Not implemented.
@ -155,9 +152,8 @@ export function attach(
if (renderer.ComponentTree) { if (renderer.ComponentTree) {
getInternalIDForNative = (node, findNearestUnfilteredAncestor) => { getInternalIDForNative = (node, findNearestUnfilteredAncestor) => {
const internalInstance = renderer.ComponentTree.getClosestInstanceFromNode( const internalInstance =
node, renderer.ComponentTree.getClosestInstanceFromNode(node);
);
return internalInstanceToIDMap.get(internalInstance) || null; return internalInstanceToIDMap.get(internalInstance) || null;
}; };
findNativeNodeForInternalID = (id: number) => { findNativeNodeForInternalID = (id: number) => {
@ -510,8 +506,8 @@ export function attach(
const operations = new Array( const operations = new Array(
// Identify which renderer this update is coming from. // Identify which renderer this update is coming from.
2 + // [rendererID, rootFiberID] 2 + // [rendererID, rootFiberID]
// How big is the string table? // How big is the string table?
1 + // [stringTableLength] 1 + // [stringTableLength]
// Then goes the actual string table. // Then goes the actual string table.
pendingStringTableLength + pendingStringTableLength +
// All unmounts are batched in a single message. // All unmounts are batched in a single message.

View File

@ -12,7 +12,7 @@ import type {InternalInstance} from './renderer';
export function decorate(object: Object, attr: string, fn: Function): Function { export function decorate(object: Object, attr: string, fn: Function): Function {
const old = object[attr]; const old = object[attr];
// $FlowFixMe[missing-this-annot] webpack config needs to be updated to allow `this` type annotations // $FlowFixMe[missing-this-annot] webpack config needs to be updated to allow `this` type annotations
object[attr] = function(instance: InternalInstance) { object[attr] = function (instance: InternalInstance) {
return fn.call(this, old, arguments); return fn.call(this, old, arguments);
}; };
return old; return old;

View File

@ -54,11 +54,11 @@ if (supportsUserTiming) {
const CHECK_V3_MARK = '__v3'; const CHECK_V3_MARK = '__v3';
const markOptions = ({}: {startTime?: number}); const markOptions = ({}: {startTime?: number});
Object.defineProperty(markOptions, 'startTime', { Object.defineProperty(markOptions, 'startTime', {
get: function() { get: function () {
supportsUserTimingV3 = true; supportsUserTimingV3 = true;
return 0; return 0;
}, },
set: function() {}, set: function () {},
}); });
try { try {
@ -237,10 +237,8 @@ export function createProfilingHooks({
currentReactMeasuresStack.push(reactMeasure); currentReactMeasuresStack.push(reactMeasure);
if (currentTimelineData) { if (currentTimelineData) {
const { const {batchUIDToMeasuresMap, laneToReactMeasureMap} =
batchUIDToMeasuresMap, currentTimelineData;
laneToReactMeasureMap,
} = currentTimelineData;
let reactMeasures = batchUIDToMeasuresMap.get(currentBatchUID); let reactMeasures = batchUIDToMeasuresMap.get(currentBatchUID);
if (reactMeasures != null) { if (reactMeasures != null) {

View File

@ -154,9 +154,7 @@ const getCurrentTime =
? () => performance.now() ? () => performance.now()
: () => Date.now(); : () => Date.now();
export function getInternalReactConstants( export function getInternalReactConstants(version: string): {
version: string,
): {
getDisplayNameForFiber: getDisplayNameForFiberType, getDisplayNameForFiber: getDisplayNameForFiberType,
getTypeSymbol: getTypeSymbolType, getTypeSymbol: getTypeSymbolType,
ReactPriorityLevels: ReactPriorityLevelsType, ReactPriorityLevels: ReactPriorityLevelsType,
@ -843,12 +841,7 @@ export function attach(
'color: purple;', 'color: purple;',
'color: black;', 'color: black;',
); );
console.log( console.log(new Error().stack.split('\n').slice(1).join('\n'));
new Error().stack
.split('\n')
.slice(1)
.join('\n'),
);
console.groupEnd(); console.groupEnd();
} }
}; };
@ -1800,8 +1793,8 @@ export function attach(
const operations = new Array( const operations = new Array(
// Identify which renderer this update is coming from. // Identify which renderer this update is coming from.
2 + // [rendererID, rootFiberID] 2 + // [rendererID, rootFiberID]
// How big is the string table? // How big is the string table?
1 + // [stringTableLength] 1 + // [stringTableLength]
// Then goes the actual string table. // Then goes the actual string table.
pendingStringTableLength + pendingStringTableLength +
// All unmounts are batched in a single message. // All unmounts are batched in a single message.
@ -2072,9 +2065,8 @@ export function attach(
// If we have the tree selection from previous reload, try to match this Fiber. // If we have the tree selection from previous reload, try to match this Fiber.
// Also remember whether to do the same for siblings. // Also remember whether to do the same for siblings.
const mightSiblingsBeOnTrackedPath = updateTrackedPathStateBeforeMount( const mightSiblingsBeOnTrackedPath =
fiber, updateTrackedPathStateBeforeMount(fiber);
);
const shouldIncludeInTree = !shouldFilterFiber(fiber); const shouldIncludeInTree = !shouldFilterFiber(fiber);
if (shouldIncludeInTree) { if (shouldIncludeInTree) {
@ -2232,7 +2224,8 @@ export function attach(
// Note that we should do this for any fiber we performed work on, regardless of its actualDuration value. // Note that we should do this for any fiber we performed work on, regardless of its actualDuration value.
// In some cases actualDuration might be 0 for fibers we worked on (particularly if we're using Date.now) // In some cases actualDuration might be 0 for fibers we worked on (particularly if we're using Date.now)
// In other cases (e.g. Memo) actualDuration might be greater than 0 even if we "bailed out". // In other cases (e.g. Memo) actualDuration might be greater than 0 even if we "bailed out".
const metadata = ((currentCommitProfilingMetadata: any): CommitProfilingData); const metadata =
((currentCommitProfilingMetadata: any): CommitProfilingData);
metadata.durations.push(id, actualDuration, selfDuration); metadata.durations.push(id, actualDuration, selfDuration);
metadata.maxActualDuration = Math.max( metadata.maxActualDuration = Math.max(
metadata.maxActualDuration, metadata.maxActualDuration,
@ -2633,13 +2626,13 @@ export function attach(
function handlePostCommitFiberRoot(root: any) { function handlePostCommitFiberRoot(root: any) {
if (isProfiling && rootSupportsProfiling(root)) { if (isProfiling && rootSupportsProfiling(root)) {
if (currentCommitProfilingMetadata !== null) { if (currentCommitProfilingMetadata !== null) {
const {effectDuration, passiveEffectDuration} = getEffectDurations( const {effectDuration, passiveEffectDuration} =
root, getEffectDurations(root);
);
// $FlowFixMe[incompatible-use] found when upgrading Flow // $FlowFixMe[incompatible-use] found when upgrading Flow
currentCommitProfilingMetadata.effectDuration = effectDuration; currentCommitProfilingMetadata.effectDuration = effectDuration;
// $FlowFixMe[incompatible-use] found when upgrading Flow // $FlowFixMe[incompatible-use] found when upgrading Flow
currentCommitProfilingMetadata.passiveEffectDuration = passiveEffectDuration; currentCommitProfilingMetadata.passiveEffectDuration =
passiveEffectDuration;
} }
} }
} }
@ -2719,9 +2712,10 @@ export function attach(
if (isProfiling && isProfilingSupported) { if (isProfiling && isProfilingSupported) {
if (!shouldBailoutWithPendingOperations()) { if (!shouldBailoutWithPendingOperations()) {
const commitProfilingMetadata = ((rootToCommitProfilingMetadataMap: any): CommitProfilingMetadataMap).get( const commitProfilingMetadata =
currentRootID, ((rootToCommitProfilingMetadataMap: any): CommitProfilingMetadataMap).get(
); currentRootID,
);
if (commitProfilingMetadata != null) { if (commitProfilingMetadata != null) {
commitProfilingMetadata.push( commitProfilingMetadata.push(
@ -3964,7 +3958,8 @@ export function attach(
let isProfiling: boolean = false; let isProfiling: boolean = false;
let profilingStartTime: number = 0; let profilingStartTime: number = 0;
let recordChangeDescriptions: boolean = false; let recordChangeDescriptions: boolean = false;
let rootToCommitProfilingMetadataMap: CommitProfilingMetadataMap | null = null; let rootToCommitProfilingMetadataMap: CommitProfilingMetadataMap | null =
null;
function getProfilingData(): ProfilingDataBackend { function getProfilingData(): ProfilingDataBackend {
const dataForRoots: Array<ProfilingDataForRootBackend> = []; const dataForRoots: Array<ProfilingDataForRootBackend> = [];

View File

@ -119,9 +119,10 @@ export function copyWithSet(
return updated; return updated;
} }
export function getEffectDurations( export function getEffectDurations(root: Object): {
root: Object, effectDuration: any | null,
): {effectDuration: any | null, passiveEffectDuration: any | null} { passiveEffectDuration: any | null,
} {
// Profiling durations are only available for certain builds. // Profiling durations are only available for certain builds.
// If available, they'll be stored on the HostRoot. // If available, they'll be stored on the HostRoot.
let effectDuration = null; let effectDuration = null;

View File

@ -233,9 +233,8 @@ export default class Overlay {
name = elements[0].nodeName.toLowerCase(); name = elements[0].nodeName.toLowerCase();
const node = elements[0]; const node = elements[0];
const rendererInterface = this.agent.getBestMatchingRendererInterface( const rendererInterface =
node, this.agent.getBestMatchingRendererInterface(node);
);
if (rendererInterface) { if (rendererInterface) {
const id = rendererInterface.getFiberIDForNative(node, true); const id = rendererInterface.getFiberIDForNative(node, true);
if (id) { if (id) {

View File

@ -56,7 +56,7 @@ export default function setupHighlighter(
function stopInspectingNative() { function stopInspectingNative() {
hideOverlay(agent); hideOverlay(agent);
removeListenersOnWindow(window); removeListenersOnWindow(window);
iframesListeningTo.forEach(function(frame) { iframesListeningTo.forEach(function (frame) {
try { try {
removeListenersOnWindow(frame.contentWindow); removeListenersOnWindow(frame.contentWindow);
} catch (error) { } catch (error) {

View File

@ -108,9 +108,7 @@ export function getNestedBoundingClientRect(
} }
} }
export function getElementDimensions( export function getElementDimensions(domElement: Element): {
domElement: Element,
): {
borderBottom: number, borderBottom: number,
borderLeft: number, borderLeft: number,
borderRight: number, borderRight: number,

View File

@ -340,9 +340,9 @@ class Bridge<
// Disable the API inherited from EventEmitter that can add more listeners and send more messages. // Disable the API inherited from EventEmitter that can add more listeners and send more messages.
// $FlowFixMe This property is not writable. // $FlowFixMe This property is not writable.
this.addListener = function() {}; this.addListener = function () {};
// $FlowFixMe This property is not writable. // $FlowFixMe This property is not writable.
this.emit = function() {}; this.emit = function () {};
// NOTE: There's also EventEmitter API like `on` and `prependListener` that we didn't add to our Flow type of EventEmitter. // NOTE: There's also EventEmitter API like `on` and `prependListener` that we didn't add to our Flow type of EventEmitter.
// Unsubscribe this bridge incoming message listeners to be sure, and so they don't have to do that. // Unsubscribe this bridge incoming message listeners to be sure, and so they don't have to do that.

View File

@ -54,9 +54,8 @@ type Props = {
}; };
export default function ContextMenu({children, id}: Props): React.Node { export default function ContextMenu({children, id}: Props): React.Node {
const {hideMenu, registerMenu} = useContext<RegistryContextType>( const {hideMenu, registerMenu} =
RegistryContext, useContext<RegistryContextType>(RegistryContext);
);
const [state, setState] = useState(HIDDEN_STATE); const [state, setState] = useState(HIDDEN_STATE);

View File

@ -83,10 +83,9 @@ export type RegistryContextType = {
registerMenu: typeof registerMenu, registerMenu: typeof registerMenu,
}; };
export const RegistryContext: ReactContext<RegistryContextType> = createContext<RegistryContextType>( export const RegistryContext: ReactContext<RegistryContextType> =
{ createContext<RegistryContextType>({
hideMenu, hideMenu,
showMenu, showMenu,
registerMenu, registerMenu,
}, });
);

View File

@ -249,37 +249,36 @@ export default class ProfilerStore extends EventEmitter<{
} }
}; };
onBridgeProfilingData: ( onBridgeProfilingData: (dataBackend: ProfilingDataBackend) => void =
dataBackend: ProfilingDataBackend, dataBackend => {
) => void = dataBackend => { if (this._isProfiling) {
if (this._isProfiling) { // This should never happen, but if it does- ignore previous profiling data.
// This should never happen, but if it does- ignore previous profiling data. return;
return; }
}
const {rendererID} = dataBackend; const {rendererID} = dataBackend;
if (!this._rendererQueue.has(rendererID)) { if (!this._rendererQueue.has(rendererID)) {
throw Error( throw Error(
`Unexpected profiling data update from renderer "${rendererID}"`, `Unexpected profiling data update from renderer "${rendererID}"`,
); );
} }
this._dataBackends.push(dataBackend); this._dataBackends.push(dataBackend);
this._rendererQueue.delete(rendererID); this._rendererQueue.delete(rendererID);
if (this._rendererQueue.size === 0) { if (this._rendererQueue.size === 0) {
this._dataFrontend = prepareProfilingDataFrontendFromBackendAndStore( this._dataFrontend = prepareProfilingDataFrontendFromBackendAndStore(
this._dataBackends, this._dataBackends,
this._inProgressOperationsByRootID, this._inProgressOperationsByRootID,
this._initialSnapshotsByRootID, this._initialSnapshotsByRootID,
); );
this._dataBackends.splice(0); this._dataBackends.splice(0);
this.emit('isProcessingData'); this.emit('isProcessingData');
} }
}; };
onBridgeShutdown: () => void = () => { onBridgeShutdown: () => void = () => {
this._bridge.removeListener('operations', this.onBridgeOperations); this._bridge.removeListener('operations', this.onBridgeOperations);

View File

@ -117,10 +117,8 @@ export default class Store extends EventEmitter<{
_componentFilters: Array<ComponentFilter>; _componentFilters: Array<ComponentFilter>;
// Map of ID to number of recorded error and warning message IDs. // Map of ID to number of recorded error and warning message IDs.
_errorsAndWarnings: Map< _errorsAndWarnings: Map<number, {errorCount: number, warningCount: number}> =
number, new Map();
{errorCount: number, warningCount: number},
> = new Map();
// At least one of the injected renderers contains (DEV only) owner metadata. // At least one of the injected renderers contains (DEV only) owner metadata.
_hasOwnerMetadata: boolean = false; _hasOwnerMetadata: boolean = false;
@ -584,9 +582,10 @@ export default class Store extends EventEmitter<{
} }
} }
getErrorAndWarningCountForElementID( getErrorAndWarningCountForElementID(id: number): {
id: number, errorCount: number,
): {errorCount: number, warningCount: number} { warningCount: number,
} {
return this._errorsAndWarnings.get(id) || {errorCount: 0, warningCount: 0}; return this._errorsAndWarnings.get(id) || {errorCount: 0, warningCount: 0};
} }
@ -1029,10 +1028,8 @@ export default class Store extends EventEmitter<{
): any): Element); ): any): Element);
parentElement.children.push(id); parentElement.children.push(id);
const [ const [displayNameWithoutHOCs, hocDisplayNames] =
displayNameWithoutHOCs, separateDisplayNameAndHOCs(displayName, type);
hocDisplayNames,
] = separateDisplayNameAndHOCs(displayName, type);
const element: Element = { const element: Element = {
children: [], children: [],
@ -1280,8 +1277,8 @@ export default class Store extends EventEmitter<{
if (haveRootsChanged) { if (haveRootsChanged) {
const prevRootSupportsProfiling = this._rootSupportsBasicProfiling; const prevRootSupportsProfiling = this._rootSupportsBasicProfiling;
const prevRootSupportsTimelineProfiling = this const prevRootSupportsTimelineProfiling =
._rootSupportsTimelineProfiling; this._rootSupportsTimelineProfiling;
this._hasOwnerMetadata = false; this._hasOwnerMetadata = false;
this._rootSupportsBasicProfiling = false; this._rootSupportsBasicProfiling = false;
@ -1399,22 +1396,21 @@ export default class Store extends EventEmitter<{
this.emit('backendVersion'); this.emit('backendVersion');
}; };
onBridgeProtocol: ( onBridgeProtocol: (bridgeProtocol: BridgeProtocol) => void =
bridgeProtocol: BridgeProtocol, bridgeProtocol => {
) => void = bridgeProtocol => { if (this._onBridgeProtocolTimeoutID !== null) {
if (this._onBridgeProtocolTimeoutID !== null) { clearTimeout(this._onBridgeProtocolTimeoutID);
clearTimeout(this._onBridgeProtocolTimeoutID); this._onBridgeProtocolTimeoutID = null;
this._onBridgeProtocolTimeoutID = null; }
}
this._bridgeProtocol = bridgeProtocol; this._bridgeProtocol = bridgeProtocol;
if (bridgeProtocol.version !== currentBridgeProtocol.version) { if (bridgeProtocol.version !== currentBridgeProtocol.version) {
// Technically newer versions of the frontend can, at least for now, // Technically newer versions of the frontend can, at least for now,
// gracefully handle older versions of the backend protocol. // gracefully handle older versions of the backend protocol.
// So for now we don't need to display the unsupported dialog. // So for now we don't need to display the unsupported dialog.
} }
}; };
onBridgeProtocolTimeout: () => void = () => { onBridgeProtocolTimeout: () => void = () => {
this._onBridgeProtocolTimeoutID = null; this._onBridgeProtocolTimeoutID = null;

View File

@ -40,8 +40,9 @@ export function printElement(
suffix = ` (${element.isCollapsed ? 1 : element.weight})`; suffix = ` (${element.isCollapsed ? 1 : element.weight})`;
} }
return `${' '.repeat(element.depth + 1)}${prefix} <${element.displayName || return `${' '.repeat(element.depth + 1)}${prefix} <${
'null'}${key}>${hocs}${suffix}`; element.displayName || 'null'
}${key}>${hocs}${suffix}`;
} }
export function printOwnersList( export function printOwnersList(
@ -70,10 +71,8 @@ export function printStore(
} }
function printErrorsAndWarnings(element: Element): string { function printErrorsAndWarnings(element: Element): string {
const { const {errorCount, warningCount} =
errorCount, store.getErrorAndWarningCountForElementID(element.id);
warningCount,
} = store.getErrorAndWarningCountForElementID(element.id);
if (errorCount === 0 && warningCount === 0) { if (errorCount === 0 && warningCount === 0) {
return ''; return '';
} }

View File

@ -34,9 +34,8 @@ type Props = {
export default function Element({data, index, style}: Props): React.Node { export default function Element({data, index, style}: Props): React.Node {
const store = useContext(StoreContext); const store = useContext(StoreContext);
const {ownerFlatTree, ownerID, selectedElementID} = useContext( const {ownerFlatTree, ownerID, selectedElementID} =
TreeStateContext, useContext(TreeStateContext);
);
const dispatch = useContext(TreeDispatcherContext); const dispatch = useContext(TreeDispatcherContext);
const {showInlineWarningsAndErrors} = React.useContext(SettingsContext); const {showInlineWarningsAndErrors} = React.useContext(SettingsContext);

View File

@ -14,9 +14,8 @@ import {createContext} from 'react';
export type FetchFileWithCaching = (url: string) => Promise<string>; export type FetchFileWithCaching = (url: string) => Promise<string>;
export type Context = FetchFileWithCaching | null; export type Context = FetchFileWithCaching | null;
const FetchFileWithCachingContext: ReactContext<Context> = createContext<Context>( const FetchFileWithCachingContext: ReactContext<Context> =
null, createContext<Context>(null);
);
FetchFileWithCachingContext.displayName = 'FetchFileWithCachingContext'; FetchFileWithCachingContext.displayName = 'FetchFileWithCachingContext';
export default FetchFileWithCachingContext; export default FetchFileWithCachingContext;

View File

@ -14,13 +14,13 @@ import type {Thenable} from 'shared/ReactTypes';
import {createContext} from 'react'; import {createContext} from 'react';
import typeof * as ParseHookNamesModule from 'react-devtools-shared/src/hooks/parseHookNames'; import typeof * as ParseHookNamesModule from 'react-devtools-shared/src/hooks/parseHookNames';
export type HookNamesModuleLoaderFunction = () => Thenable<ParseHookNamesModule>; export type HookNamesModuleLoaderFunction =
() => Thenable<ParseHookNamesModule>;
export type Context = HookNamesModuleLoaderFunction | null; export type Context = HookNamesModuleLoaderFunction | null;
// TODO (Webpack 5) Hopefully we can remove this context entirely once the Webpack 5 upgrade is completed. // TODO (Webpack 5) Hopefully we can remove this context entirely once the Webpack 5 upgrade is completed.
const HookNamesModuleLoaderContext: ReactContext<Context> = createContext<Context>( const HookNamesModuleLoaderContext: ReactContext<Context> =
null, createContext<Context>(null);
);
HookNamesModuleLoaderContext.displayName = 'HookNamesModuleLoaderContext'; HookNamesModuleLoaderContext.displayName = 'HookNamesModuleLoaderContext';
export default HookNamesModuleLoaderContext; export default HookNamesModuleLoaderContext;

View File

@ -48,12 +48,8 @@ export default function InspectedElementWrapper(_: Props): React.Node {
} = useContext(OptionsContext); } = useContext(OptionsContext);
const {dispatch: modalDialogDispatch} = useContext(ModalDialogContext); const {dispatch: modalDialogDispatch} = useContext(ModalDialogContext);
const { const {hookNames, inspectedElement, parseHookNames, toggleParseHookNames} =
hookNames, useContext(InspectedElementContext);
inspectedElement,
parseHookNames,
toggleParseHookNames,
} = useContext(InspectedElementContext);
const element = const element =
inspectedElementID !== null inspectedElementID !== null

View File

@ -57,9 +57,8 @@ type Context = {
toggleParseHookNames: ToggleParseHookNames, toggleParseHookNames: ToggleParseHookNames,
}; };
export const InspectedElementContext: ReactContext<Context> = createContext<Context>( export const InspectedElementContext: ReactContext<Context> =
((null: any): Context), createContext<Context>(((null: any): Context));
);
const POLL_INTERVAL = 1000; const POLL_INTERVAL = 1000;
@ -134,10 +133,8 @@ export function InspectedElementContextController({
if (parseHookNames || alreadyLoadedHookNames) { if (parseHookNames || alreadyLoadedHookNames) {
const hookNamesModule = loadModule(hookNamesModuleLoader); const hookNamesModule = loadModule(hookNamesModuleLoader);
if (hookNamesModule !== null) { if (hookNamesModule !== null) {
const { const {parseHookNames: loadHookNamesFunction, purgeCachedMetadata} =
parseHookNames: loadHookNamesFunction, hookNamesModule;
purgeCachedMetadata,
} = hookNamesModule;
purgeCachedMetadataRef.current = purgeCachedMetadata; purgeCachedMetadataRef.current = purgeCachedMetadata;
@ -159,12 +156,13 @@ export function InspectedElementContextController({
} }
} }
const toggleParseHookNames: ToggleParseHookNames = useCallback<ToggleParseHookNames>(() => { const toggleParseHookNames: ToggleParseHookNames =
startTransition(() => { useCallback<ToggleParseHookNames>(() => {
setParseHookNames(value => !value); startTransition(() => {
refresh(); setParseHookNames(value => !value);
}); refresh();
}, [setParseHookNames]); });
}, [setParseHookNames]);
const inspectPaths: InspectPathFunction = useCallback<InspectPathFunction>( const inspectPaths: InspectPathFunction = useCallback<InspectPathFunction>(
(path: Path) => { (path: Path) => {

View File

@ -40,10 +40,8 @@ export default function InspectedElementErrorsAndWarningsTree({
}: Props): React.Node { }: Props): React.Node {
const refresh = useCacheRefresh(); const refresh = useCacheRefresh();
const [ const [isErrorsTransitionPending, startClearErrorsTransition] =
isErrorsTransitionPending, useTransition();
startClearErrorsTransition,
] = useTransition();
const clearErrorsForInspectedElement = () => { const clearErrorsForInspectedElement = () => {
const {id} = inspectedElement; const {id} = inspectedElement;
const rendererID = store.getRendererIDForElement(id); const rendererID = store.getRendererIDForElement(id);
@ -59,10 +57,8 @@ export default function InspectedElementErrorsAndWarningsTree({
} }
}; };
const [ const [isWarningsTransitionPending, startClearWarningsTransition] =
isWarningsTransitionPending, useTransition();
startClearWarningsTransition,
] = useTransition();
const clearWarningsForInspectedElement = () => { const clearWarningsForInspectedElement = () => {
const {id} = inspectedElement; const {id} = inspectedElement;
const rendererID = store.getRendererIDForElement(id); const rendererID = store.getRendererIDForElement(id);

View File

@ -59,9 +59,8 @@ export function InspectedElementHooksTree({
// Changing parseHookNames is done in a transition, because it suspends. // Changing parseHookNames is done in a transition, because it suspends.
// This value is done outside of the transition, so the UI toggle feels responsive. // This value is done outside of the transition, so the UI toggle feels responsive.
const [parseHookNamesOptimistic, setParseHookNamesOptimistic] = useState( const [parseHookNamesOptimistic, setParseHookNamesOptimistic] =
parseHookNames, useState(parseHookNames);
);
const handleChange = () => { const handleChange = () => {
setParseHookNamesOptimistic(!parseHookNames); setParseHookNamesOptimistic(!parseHookNames);
toggleParseHookNames(); toggleParseHookNames();
@ -168,11 +167,8 @@ function HookView({
inspectedElement, inspectedElement,
path, path,
}: HookViewProps) { }: HookViewProps) {
const { const {canEditHooks, canEditHooksAndDeletePaths, canEditHooksAndRenamePaths} =
canEditHooks, inspectedElement;
canEditHooksAndDeletePaths,
canEditHooksAndRenamePaths,
} = inspectedElement;
const {id: hookID, isStateEditable, subHooks, value} = hook; const {id: hookID, isStateEditable, subHooks, value} = hook;
const isReadOnly = hookID == null || !isStateEditable; const isReadOnly = hookID == null || !isStateEditable;

View File

@ -61,13 +61,8 @@ export default function InspectedElementView({
toggleParseHookNames, toggleParseHookNames,
}: Props): React.Node { }: Props): React.Node {
const {id} = element; const {id} = element;
const { const {owners, rendererPackageName, rendererVersion, rootType, source} =
owners, inspectedElement;
rendererPackageName,
rendererVersion,
rootType,
source,
} = inspectedElement;
const bridge = useContext(BridgeContext); const bridge = useContext(BridgeContext);
const store = useContext(StoreContext); const store = useContext(StoreContext);
@ -297,10 +292,8 @@ function OwnerView({
type, type,
}: OwnerViewProps) { }: OwnerViewProps) {
const dispatch = useContext(TreeDispatcherContext); const dispatch = useContext(TreeDispatcherContext);
const { const {highlightNativeElement, clearHighlightNativeElement} =
highlightNativeElement, useHighlightNativeElement();
clearHighlightNativeElement,
} = useHighlightNativeElement();
const handleClick = useCallback(() => { const handleClick = useCallback(() => {
logEvent({ logEvent({

View File

@ -55,33 +55,30 @@ type InProgressRequest = {
}; };
const inProgressRequests: WeakMap<Element, InProgressRequest> = new WeakMap(); const inProgressRequests: WeakMap<Element, InProgressRequest> = new WeakMap();
const resource: Resource< const resource: Resource<Element, Element, StyleAndLayoutFrontend> =
Element, createResource(
Element, (element: Element) => {
StyleAndLayoutFrontend, const request = inProgressRequests.get(element);
> = createResource( if (request != null) {
(element: Element) => { return request.promise;
const request = inProgressRequests.get(element); }
if (request != null) {
return request.promise;
}
let resolveFn: let resolveFn:
| ResolveFn | ResolveFn
| (( | ((
result: Promise<StyleAndLayoutFrontend> | StyleAndLayoutFrontend, result: Promise<StyleAndLayoutFrontend> | StyleAndLayoutFrontend,
) => void) = ((null: any): ResolveFn); ) => void) = ((null: any): ResolveFn);
const promise = new Promise(resolve => { const promise = new Promise(resolve => {
resolveFn = resolve; resolveFn = resolve;
}); });
inProgressRequests.set(element, {promise, resolveFn}); inProgressRequests.set(element, {promise, resolveFn});
return promise; return promise;
}, },
(element: Element) => element, (element: Element) => element,
{useWeakMap: true}, {useWeakMap: true},
); );
type Props = { type Props = {
children: React$Node, children: React$Node,
@ -108,10 +105,8 @@ function NativeStyleContextController({children}: Props): React.Node {
// would itself be blocked by the same render that suspends (waiting for the data). // would itself be blocked by the same render that suspends (waiting for the data).
const {selectedElementID} = useContext<StateContext>(TreeStateContext); const {selectedElementID} = useContext<StateContext>(TreeStateContext);
const [ const [currentStyleAndLayout, setCurrentStyleAndLayout] =
currentStyleAndLayout, useState<StyleAndLayoutFrontend | null>(null);
setCurrentStyleAndLayout,
] = useState<StyleAndLayoutFrontend | null>(null);
// This effect handler invalidates the suspense cache and schedules rendering updates with React. // This effect handler invalidates the suspense cache and schedules rendering updates with React.
useEffect(() => { useEffect(() => {

View File

@ -102,10 +102,8 @@ function OwnersListContextController({children}: Props): React.Node {
ownersList.owners === null ownersList.owners === null
? null ? null
: ownersList.owners.map(owner => { : ownersList.owners.map(owner => {
const [ const [displayNameWithoutHOCs, hocDisplayNames] =
displayNameWithoutHOCs, separateDisplayNameAndHOCs(owner.displayName, owner.type);
hocDisplayNames,
] = separateDisplayNameAndHOCs(owner.displayName, owner.type);
return { return {
...owner, ...owner,

View File

@ -64,13 +64,10 @@ export default function Tree(props: Props): React.Node {
const bridge = useContext(BridgeContext); const bridge = useContext(BridgeContext);
const store = useContext(StoreContext); const store = useContext(StoreContext);
const {hideSettings} = useContext(OptionsContext); const {hideSettings} = useContext(OptionsContext);
const [isNavigatingWithKeyboard, setIsNavigatingWithKeyboard] = useState( const [isNavigatingWithKeyboard, setIsNavigatingWithKeyboard] =
false, useState(false);
); const {highlightNativeElement, clearHighlightNativeElement} =
const { useHighlightNativeElement();
highlightNativeElement,
clearHighlightNativeElement,
} = useHighlightNativeElement();
const treeRef = useRef<HTMLDivElement | null>(null); const treeRef = useRef<HTMLDivElement | null>(null);
const focusTargetRef = useRef<HTMLDivElement | null>(null); const focusTargetRef = useRef<HTMLDivElement | null>(null);

View File

@ -150,14 +150,12 @@ type Action =
export type DispatcherContext = (action: Action) => void; export type DispatcherContext = (action: Action) => void;
const TreeStateContext: ReactContext<StateContext> = createContext<StateContext>( const TreeStateContext: ReactContext<StateContext> =
((null: any): StateContext), createContext<StateContext>(((null: any): StateContext));
);
TreeStateContext.displayName = 'TreeStateContext'; TreeStateContext.displayName = 'TreeStateContext';
const TreeDispatcherContext: ReactContext<DispatcherContext> = createContext<DispatcherContext>( const TreeDispatcherContext: ReactContext<DispatcherContext> =
((null: any): DispatcherContext), createContext<DispatcherContext>(((null: any): DispatcherContext));
);
TreeDispatcherContext.displayName = 'TreeDispatcherContext'; TreeDispatcherContext.displayName = 'TreeDispatcherContext';
type State = { type State = {
@ -379,7 +377,8 @@ function reduceTreeState(store: Store, state: State, action: Action): State {
} }
break; break;
case 'SELECT_PREVIOUS_ELEMENT_WITH_ERROR_OR_WARNING_IN_TREE': { case 'SELECT_PREVIOUS_ELEMENT_WITH_ERROR_OR_WARNING_IN_TREE': {
const elementIndicesWithErrorsOrWarnings = store.getElementsWithErrorsAndWarnings(); const elementIndicesWithErrorsOrWarnings =
store.getElementsWithErrorsAndWarnings();
if (elementIndicesWithErrorsOrWarnings.length === 0) { if (elementIndicesWithErrorsOrWarnings.length === 0) {
return state; return state;
} }
@ -420,7 +419,8 @@ function reduceTreeState(store: Store, state: State, action: Action): State {
break; break;
} }
case 'SELECT_NEXT_ELEMENT_WITH_ERROR_OR_WARNING_IN_TREE': { case 'SELECT_NEXT_ELEMENT_WITH_ERROR_OR_WARNING_IN_TREE': {
const elementIndicesWithErrorsOrWarnings = store.getElementsWithErrorsAndWarnings(); const elementIndicesWithErrorsOrWarnings =
store.getElementsWithErrorsAndWarnings();
if (elementIndicesWithErrorsOrWarnings.length === 0) { if (elementIndicesWithErrorsOrWarnings.length === 0) {
return state; return state;
} }
@ -522,10 +522,8 @@ function reduceSearchState(store: Store, state: State, action: Action): State {
break; break;
case 'HANDLE_STORE_MUTATION': case 'HANDLE_STORE_MUTATION':
if (searchText !== '') { if (searchText !== '') {
const [ const [addedElementIDs, removedElementIDs] =
addedElementIDs, (action: ACTION_HANDLE_STORE_MUTATION).payload;
removedElementIDs,
] = (action: ACTION_HANDLE_STORE_MUTATION).payload;
removedElementIDs.forEach((parentID, id) => { removedElementIDs.forEach((parentID, id) => {
// Prune this item from the search results. // Prune this item from the search results.
@ -847,51 +845,52 @@ function TreeContextController({
// The store is mutable, but the Store itself is global and lives for the lifetime of the DevTools, // The store is mutable, but the Store itself is global and lives for the lifetime of the DevTools,
// so it's okay for the reducer to have an empty dependencies array. // so it's okay for the reducer to have an empty dependencies array.
const reducer = useMemo( const reducer = useMemo(
() => (state: State, action: Action): State => { () =>
const {type} = action; (state: State, action: Action): State => {
switch (type) { const {type} = action;
case 'GO_TO_NEXT_SEARCH_RESULT': switch (type) {
case 'GO_TO_PREVIOUS_SEARCH_RESULT': case 'GO_TO_NEXT_SEARCH_RESULT':
case 'HANDLE_STORE_MUTATION': case 'GO_TO_PREVIOUS_SEARCH_RESULT':
case 'RESET_OWNER_STACK': case 'HANDLE_STORE_MUTATION':
case 'SELECT_ELEMENT_AT_INDEX': case 'RESET_OWNER_STACK':
case 'SELECT_ELEMENT_BY_ID': case 'SELECT_ELEMENT_AT_INDEX':
case 'SELECT_CHILD_ELEMENT_IN_TREE': case 'SELECT_ELEMENT_BY_ID':
case 'SELECT_NEXT_ELEMENT_IN_TREE': case 'SELECT_CHILD_ELEMENT_IN_TREE':
case 'SELECT_NEXT_ELEMENT_WITH_ERROR_OR_WARNING_IN_TREE': case 'SELECT_NEXT_ELEMENT_IN_TREE':
case 'SELECT_NEXT_SIBLING_IN_TREE': case 'SELECT_NEXT_ELEMENT_WITH_ERROR_OR_WARNING_IN_TREE':
case 'SELECT_OWNER_LIST_NEXT_ELEMENT_IN_TREE': case 'SELECT_NEXT_SIBLING_IN_TREE':
case 'SELECT_OWNER_LIST_PREVIOUS_ELEMENT_IN_TREE': case 'SELECT_OWNER_LIST_NEXT_ELEMENT_IN_TREE':
case 'SELECT_PARENT_ELEMENT_IN_TREE': case 'SELECT_OWNER_LIST_PREVIOUS_ELEMENT_IN_TREE':
case 'SELECT_PREVIOUS_ELEMENT_IN_TREE': case 'SELECT_PARENT_ELEMENT_IN_TREE':
case 'SELECT_PREVIOUS_ELEMENT_WITH_ERROR_OR_WARNING_IN_TREE': case 'SELECT_PREVIOUS_ELEMENT_IN_TREE':
case 'SELECT_PREVIOUS_SIBLING_IN_TREE': case 'SELECT_PREVIOUS_ELEMENT_WITH_ERROR_OR_WARNING_IN_TREE':
case 'SELECT_OWNER': case 'SELECT_PREVIOUS_SIBLING_IN_TREE':
case 'UPDATE_INSPECTED_ELEMENT_ID': case 'SELECT_OWNER':
case 'SET_SEARCH_TEXT': case 'UPDATE_INSPECTED_ELEMENT_ID':
state = reduceTreeState(store, state, action); case 'SET_SEARCH_TEXT':
state = reduceSearchState(store, state, action); state = reduceTreeState(store, state, action);
state = reduceOwnersState(store, state, action); state = reduceSearchState(store, state, action);
state = reduceSuspenseState(store, state, action); state = reduceOwnersState(store, state, action);
state = reduceSuspenseState(store, state, action);
// If the selected ID is in a collapsed subtree, reset the selected index to null. // If the selected ID is in a collapsed subtree, reset the selected index to null.
// We'll know the correct index after the layout effect will toggle the tree, // We'll know the correct index after the layout effect will toggle the tree,
// and the store tree is mutated to account for that. // and the store tree is mutated to account for that.
if ( if (
state.selectedElementID !== null && state.selectedElementID !== null &&
store.isInsideCollapsedSubTree(state.selectedElementID) store.isInsideCollapsedSubTree(state.selectedElementID)
) { ) {
return { return {
...state, ...state,
selectedElementIndex: null, selectedElementIndex: null,
}; };
} }
return state; return state;
default: default:
throw new Error(`Unrecognized action "${type}"`); throw new Error(`Unrecognized action "${type}"`);
} }
}, },
[store], [store],
); );

View File

@ -56,9 +56,7 @@ const InitialState: State = {
export default class ErrorBoundary extends Component<Props, State> { export default class ErrorBoundary extends Component<Props, State> {
state: State = InitialState; state: State = InitialState;
static getDerivedStateFromError( static getDerivedStateFromError(error: any): {
error: any,
): {
callStack: string | null, callStack: string | null,
errorMessage: string | null, errorMessage: string | null,
hasError: boolean, hasError: boolean,
@ -84,10 +82,7 @@ export default class ErrorBoundary extends Component<Props, State> {
typeof error === 'object' && typeof error === 'object' &&
error !== null && error !== null &&
typeof error.stack === 'string' typeof error.stack === 'string'
? error.stack ? error.stack.split('\n').slice(1).join('\n')
.split('\n')
.slice(1)
.join('\n')
: null; : null;
return { return {

View File

@ -93,7 +93,8 @@ export function findGitHubIssue(errorMessage: string): GitHubIssue | null {
} }
if (maybeItem) { if (maybeItem) {
const resolvedRecord = ((newRecord: any): ResolvedRecord<GitHubIssue>); const resolvedRecord =
((newRecord: any): ResolvedRecord<GitHubIssue>);
resolvedRecord.status = Resolved; resolvedRecord.status = Resolved;
resolvedRecord.value = maybeItem; resolvedRecord.value = maybeItem;
} else { } else {

View File

@ -56,9 +56,8 @@ type ModalDialogContextType = {
dispatch: Dispatch, dispatch: Dispatch,
}; };
const ModalDialogContext: ReactContext<ModalDialogContextType> = createContext<ModalDialogContextType>( const ModalDialogContext: ReactContext<ModalDialogContextType> =
((null: any): ModalDialogContextType), createContext<ModalDialogContextType>(((null: any): ModalDialogContextType));
);
ModalDialogContext.displayName = 'ModalDialogContext'; ModalDialogContext.displayName = 'ModalDialogContext';
function dialogReducer(state: State, action: Action) { function dialogReducer(state: State, action: Action) {

Some files were not shown because too many files have changed in this diff Show More