diff --git a/.prettierrc.js b/.prettierrc.js index 6e5dcb710f0f0..4f7ef193130c9 100644 --- a/.prettierrc.js +++ b/.prettierrc.js @@ -8,8 +8,8 @@ module.exports = { jsxBracketSameLine: true, trailingComma: 'es5', printWidth: 80, - parser: 'babel', - + parser: 'flow', + arrowParens: 'avoid', overrides: [ { files: esNextPaths, diff --git a/CHANGELOG.md b/CHANGELOG.md index 57d319384e44a..8f6df415e32a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -102,6 +102,10 @@ The existing `renderToString` method keeps working but is discouraged. * **Layout Effects with Suspense**: When a tree re-suspends and reverts to a fallback, React will now clean up layout effects, and then re-create them when the content inside the boundary is shown again. This fixes an issue which prevented component libraries from correctly measuring layout when used with Suspense. * **New JS Environment Requirements**: React now depends on modern browsers features including `Promise`, `Symbol`, and `Object.assign`. If you support older browsers and devices such as Internet Explorer which do not provide modern browser features natively or have non-compliant implementations, consider including a global polyfill in your bundled application. +### Scheduler (Experimental) + +* Remove unstable `scheduler/tracing` API + ## Notable Changes ### React @@ -193,6 +197,10 @@ The existing `renderToString` method keeps working but is discouraged. * Fix a mistake in the Node loader. ([#22537](https://github.com/facebook/react/pull/22537) by [@btea](https://github.com/btea)) * Use `globalThis` instead of `window` for edge environments. ([#22777](https://github.com/facebook/react/pull/22777) by [@huozhi](https://github.com/huozhi)) +### Scheduler (Experimental) + +* Remove unstable `scheduler/tracing` API ([#20037](https://github.com/facebook/react/pull/20037) by [@bvaughn](https://github.com/bvaughn)) + ## 17.0.2 (March 22, 2021) ### React DOM diff --git a/dangerfile.js b/dangerfile.js index 2322e85654474..e29426afda7a9 100644 --- a/dangerfile.js +++ b/dangerfile.js @@ -97,7 +97,7 @@ function row(result, baseSha, headSha) { return rowArr.join(' | '); } -(async function() { +(async function () { // Use git locally to grab the commit which represents the place // where the branches differ @@ -241,8 +241,9 @@ Comparing: ${baseSha}...${headSha} ## Critical size changes -Includes critical production bundles, as well as any change greater than ${CRITICAL_THRESHOLD * - 100}%: +Includes critical production bundles, as well as any change greater than ${ + CRITICAL_THRESHOLD * 100 + }%: ${header} ${criticalResults.join('\n')} diff --git a/fixtures/attribute-behavior/src/App.js b/fixtures/attribute-behavior/src/App.js index 36415c33817cd..9307d6a2c81de 100644 --- a/fixtures/attribute-behavior/src/App.js +++ b/fixtures/attribute-behavior/src/App.js @@ -902,8 +902,9 @@ class App extends React.Component { let log = ''; for (let attribute of attributes) { - log += `## \`${attribute.name}\` (on \`<${attribute.tagName || - 'div'}>\` inside \`<${attribute.containerTagName || 'div'}>\`)\n`; + log += `## \`${attribute.name}\` (on \`<${ + attribute.tagName || 'div' + }>\` inside \`<${attribute.containerTagName || 'div'}>\`)\n`; log += '| Test Case | Flags | Result |\n'; log += '| --- | --- | --- |\n'; diff --git a/fixtures/devtools/scheduling-profiler/run.js b/fixtures/devtools/scheduling-profiler/run.js index 9006956915ae7..259755a366e43 100755 --- a/fixtures/devtools/scheduling-profiler/run.js +++ b/fixtures/devtools/scheduling-profiler/run.js @@ -39,7 +39,7 @@ function initServer() { const host = 'localhost'; const port = 8000; - const requestListener = function(request, response) { + const requestListener = function (request, response) { let contents; switch (request.url) { case '/react.js': diff --git a/fixtures/dom/public/renderer.js b/fixtures/dom/public/renderer.js index fa8eca8b632e3..19d89160ca85a 100644 --- a/fixtures/dom/public/renderer.js +++ b/fixtures/dom/public/renderer.js @@ -4,7 +4,7 @@ 'use strict'; -(function() { +(function () { var Fixture = null; var output = document.getElementById('output'); var status = document.getElementById('status'); @@ -60,7 +60,7 @@ setStatus('Generating markup'); return Promise.resolve() - .then(function() { + .then(function () { const element = createElement(Fixture); // 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 - return new Promise(function(resolve) { + return new Promise(function (resolve) { React.renderComponentToString(element, resolve); }); }) - .then(function(string) { + .then(function (string) { output.innerHTML = string; setStatus('Markup only (No React)'); }) @@ -124,13 +124,13 @@ } function loadScript(src) { - return new Promise(function(resolve, reject) { + return new Promise(function (resolve, reject) { var script = document.createElement('script'); script.async = true; script.src = src; script.onload = resolve; - script.onerror = function(error) { + script.onerror = function (error) { reject(new Error('Unable to load ' + src)); }; @@ -145,7 +145,7 @@ setStatus('Failed'); output.innerHTML = 'Please name your root component "Fixture"'; } else { - prerender().then(function() { + prerender().then(function () { if (getBooleanQueryParam('hydrate')) { render(); } @@ -161,14 +161,14 @@ window.onerror = handleError; - reload.onclick = function() { + reload.onclick = function () { window.location.reload(); }; hydrate.onclick = render; loadScript(getQueryParam('reactPath')) - .then(function() { + .then(function () { if (needsReactDOM) { return Promise.all([ loadScript(getQueryParam('reactDOMPath')), @@ -176,12 +176,12 @@ ]); } }) - .then(function() { + .then(function () { if (failed) { return; } - window.addEventListener('message', function(event) { + window.addEventListener('message', function (event) { var data = JSON.parse(event.data); switch (data.type) { diff --git a/fixtures/dom/src/components/fixtures/error-handling/index.js b/fixtures/dom/src/components/fixtures/error-handling/index.js index 904bef4788c56..917f9ace38074 100644 --- a/fixtures/dom/src/components/fixtures/error-handling/index.js +++ b/fixtures/dom/src/components/fixtures/error-handling/index.js @@ -243,7 +243,7 @@ class TrySilenceFatalError extends React.Component { function naiveMemoize(fn) { let memoizedEntry; - return function() { + return function () { if (!memoizedEntry) { memoizedEntry = {result: null}; memoizedEntry.result = fn(); @@ -251,7 +251,7 @@ function naiveMemoize(fn) { return memoizedEntry.result; }; } -let memoizedFunction = naiveMemoize(function() { +let memoizedFunction = naiveMemoize(function () { throw new Error('Passed'); }); diff --git a/fixtures/dom/src/components/fixtures/hydration/Code.js b/fixtures/dom/src/components/fixtures/hydration/Code.js index 55c44a8c3a098..b76f015fa6257 100644 --- a/fixtures/dom/src/components/fixtures/hydration/Code.js +++ b/fixtures/dom/src/components/fixtures/hydration/Code.js @@ -34,7 +34,7 @@ export class CodeEditor extends React.Component { lineNumbers: true, }); - this.editor.on('change', function(doc) { + this.editor.on('change', function (doc) { onChange(doc.getValue()); }); } diff --git a/fixtures/dom/src/components/fixtures/mouse-events/mouse-enter.js b/fixtures/dom/src/components/fixtures/mouse-events/mouse-enter.js index c0fbcbda6a432..91cd11c3a6560 100644 --- a/fixtures/dom/src/components/fixtures/mouse-events/mouse-enter.js +++ b/fixtures/dom/src/components/fixtures/mouse-events/mouse-enter.js @@ -6,7 +6,7 @@ const ReactDOM = window.ReactDOM; const MouseEnter = () => { const containerRef = React.useRef(); - React.useEffect(function() { + React.useEffect(function () { const hostEl = containerRef.current; ReactDOM.render(, hostEl, () => { ReactDOM.render(, hostEl.childNodes[1]); diff --git a/fixtures/dom/src/polyfills.js b/fixtures/dom/src/polyfills.js index ed6e08f59beb5..1bf276292b4ab 100644 --- a/fixtures/dom/src/polyfills.js +++ b/fixtures/dom/src/polyfills.js @@ -8,7 +8,7 @@ import 'core-js/es6/map'; // requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel // MIT license -(function() { +(function () { var lastTime = 0; var vendors = ['ms', 'moz', 'webkit', 'o']; for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { @@ -19,10 +19,10 @@ import 'core-js/es6/map'; } if (!window.requestAnimationFrame) - window.requestAnimationFrame = function(callback, element) { + window.requestAnimationFrame = function (callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); - var id = window.setTimeout(function() { + var id = window.setTimeout(function () { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; @@ -30,7 +30,7 @@ import 'core-js/es6/map'; }; if (!window.cancelAnimationFrame) - window.cancelAnimationFrame = function(id) { + window.cancelAnimationFrame = function (id) { clearTimeout(id); }; })(); diff --git a/fixtures/fiber-debugger/src/Fibers.js b/fixtures/fiber-debugger/src/Fibers.js index fa8387c05d4ce..0ae596948fbb0 100644 --- a/fixtures/fiber-debugger/src/Fibers.js +++ b/fixtures/fiber-debugger/src/Fibers.js @@ -29,7 +29,7 @@ function Graph(props) { }); var edgeLabels = {}; - React.Children.forEach(props.children, function(child) { + React.Children.forEach(props.children, function (child) { if (!child) { return; } diff --git a/fixtures/fizz/server/server.js b/fixtures/fizz/server/server.js index 44a8e9936c4ca..104548bf2a6b2 100644 --- a/fixtures/fizz/server/server.js +++ b/fixtures/fizz/server/server.js @@ -30,28 +30,28 @@ const app = express(); app.use(compress()); app.get( '/', - handleErrors(async function(req, res) { + handleErrors(async function (req, res) { await waitForWebpack(); renderToStream(req.url, res); }) ); app.get( '/string', - handleErrors(async function(req, res) { + handleErrors(async function (req, res) { await waitForWebpack(); renderToString(req.url, res); }) ); app.get( '/stream', - handleErrors(async function(req, res) { + handleErrors(async function (req, res) { await waitForWebpack(); renderToStream(req.url, res); }) ); app.get( '/buffer', - handleErrors(async function(req, res) { + handleErrors(async function (req, res) { await waitForWebpack(); renderToBuffer(req.url, res); }) @@ -63,7 +63,7 @@ app .listen(PORT, () => { console.log(`Listening at ${PORT}...`); }) - .on('error', function(error) { + .on('error', function (error) { if (error.syscall !== 'listen') { throw error; } @@ -84,7 +84,7 @@ app }); function handleErrors(fn) { - return async function(req, res, next) { + return async function (req, res, next) { try { return await fn(req, res); } catch (x) { diff --git a/fixtures/flight/config/webpack.config.js b/fixtures/flight/config/webpack.config.js index 05590ff0353ed..e3af39826a1d0 100644 --- a/fixtures/flight/config/webpack.config.js +++ b/fixtures/flight/config/webpack.config.js @@ -91,7 +91,7 @@ const hasJsxRuntime = (() => { // This is the production and development configuration. // 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 isEnvProduction = webpackEnv === 'production'; diff --git a/fixtures/flight/config/webpackDevServer.config.js b/fixtures/flight/config/webpackDevServer.config.js index b934754fd9db4..5b06a4f53b44d 100644 --- a/fixtures/flight/config/webpackDevServer.config.js +++ b/fixtures/flight/config/webpackDevServer.config.js @@ -13,7 +13,7 @@ const sockHost = process.env.WDS_SOCKET_HOST; const sockPath = process.env.WDS_SOCKET_PATH; // default: '/ws' const sockPort = process.env.WDS_SOCKET_PORT; -module.exports = function(proxy, allowedHost) { +module.exports = function (proxy, allowedHost) { const disableFirewall = !proxy || process.env.DANGEROUSLY_DISABLE_HOST_CHECK === 'true'; return { diff --git a/fixtures/flight/scripts/start.js b/fixtures/flight/scripts/start.js index 1473c3bff20a7..75966a7d31f28 100644 --- a/fixtures/flight/scripts/start.js +++ b/fixtures/flight/scripts/start.js @@ -131,8 +131,8 @@ checkBrowsers(paths.appPath, isInteractive) openBrowser(urls.localUrlForBrowser); }); - ['SIGINT', 'SIGTERM'].forEach(function(sig) { - process.on(sig, function() { + ['SIGINT', 'SIGTERM'].forEach(function (sig) { + process.on(sig, function () { devServer.close(); process.exit(); }); @@ -140,7 +140,7 @@ checkBrowsers(paths.appPath, isInteractive) if (process.env.CI !== 'true') { // Gracefully exit when stdin ends - process.stdin.on('end', function() { + process.stdin.on('end', function () { devServer.close(); process.exit(); }); diff --git a/fixtures/flight/server/cli.server.js b/fixtures/flight/server/cli.server.js index 3b60f05796148..5d58f1d0358d9 100644 --- a/fixtures/flight/server/cli.server.js +++ b/fixtures/flight/server/cli.server.js @@ -10,7 +10,7 @@ babelRegister({ babelrc: false, ignore: [ /\/(build|node_modules)\//, - function(file) { + function (file) { if ((path.dirname(file) + '/').startsWith(__dirname + '/')) { // Ignore everything in this folder // because it's a mix of CJS and ESM @@ -28,11 +28,11 @@ const express = require('express'); const app = express(); // Application -app.get('/', function(req, res) { +app.get('/', function (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.json([ { @@ -50,7 +50,7 @@ app.listen(3001, () => { console.log('Flight Server listening on port 3001...'); }); -app.on('error', function(error) { +app.on('error', function (error) { if (error.syscall !== 'listen') { throw error; } diff --git a/fixtures/flight/server/handler.server.js b/fixtures/flight/server/handler.server.js index fbba850b31bcc..251833a52d15b 100644 --- a/fixtures/flight/server/handler.server.js +++ b/fixtures/flight/server/handler.server.js @@ -5,7 +5,7 @@ const {readFile} = require('fs'); const {resolve} = require('path'); const React = require('react'); -module.exports = function(req, res) { +module.exports = function (req, res) { // const m = require('../src/App.server.js'); import('../src/App.server.js').then(m => { const dist = process.env.NODE_ENV === 'development' ? 'dist' : 'build'; diff --git a/fixtures/legacy-jsx-runtimes/react-14/react-14.test.js b/fixtures/legacy-jsx-runtimes/react-14/react-14.test.js index 9ddeecef7daa2..f8df0a93a6ecf 100644 --- a/fixtures/legacy-jsx-runtimes/react-14/react-14.test.js +++ b/fixtures/legacy-jsx-runtimes/react-14/react-14.test.js @@ -257,10 +257,10 @@ it('does not warn for arrays of elements with keys', () => { it('does not warn for iterable elements with keys', () => { const iterable = { - '@@iterator': function() { + '@@iterator': function () { let i = 0; return { - next: function() { + next: function () { const done = ++i > 2; return { value: done ? undefined : , @@ -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', () => { const iterable = { - '@@iterator': function() { + '@@iterator': function () { let i = 0; return { - next: function() { + next: function () { const done = ++i > 2; return {value: done ? undefined : [i, ], done: done}; }, @@ -319,9 +319,7 @@ it('should give context for PropType errors in nested components.', () => { return ; } } - expect(() => - ReactTestUtils.renderIntoDocument() - ).toErrorDev( + expect(() => ReactTestUtils.renderIntoDocument()).toErrorDev( 'Warning: Failed prop type: ' + 'Invalid prop `color` of type `number` supplied to `MyComp`, ' + 'expected `string`.', @@ -334,9 +332,7 @@ it('gives a helpful error when passing null, undefined, or boolean', () => { const Null = null; const True = true; const Div = 'div'; - expect( - () => void () - ).toErrorDev( + expect(() => void ()).toErrorDev( 'Warning: React.jsx: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + '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} ); - expect( - () => void () - ).toErrorDev( + expect(() => void ()).toErrorDev( 'Warning: React.jsx: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: null.' + @@ -358,9 +352,7 @@ it('gives a helpful error when passing null, undefined, or boolean', () => { : ''), {withoutStack: true} ); - expect( - () => void () - ).toErrorDev( + expect(() => void ()).toErrorDev( 'Warning: React.jsx: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: boolean.' + @@ -721,9 +713,7 @@ it('should warn when `key` is being accessed on composite element', () => { ); } } - expect(() => - ReactDOM.render(, container) - ).toErrorDev( + expect(() => ReactDOM.render(, container)).toErrorDev( 'Child: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + '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(() => - ReactDOM.render(, container) - ).toErrorDev( + expect(() => ReactDOM.render(, container)).toErrorDev( 'Child: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + diff --git a/fixtures/legacy-jsx-runtimes/react-15/react-15.test.js b/fixtures/legacy-jsx-runtimes/react-15/react-15.test.js index c24b23ce1e41f..e85ecb6aec330 100644 --- a/fixtures/legacy-jsx-runtimes/react-15/react-15.test.js +++ b/fixtures/legacy-jsx-runtimes/react-15/react-15.test.js @@ -254,10 +254,10 @@ it('does not warn for arrays of elements with keys', () => { it('does not warn for iterable elements with keys', () => { const iterable = { - '@@iterator': function() { + '@@iterator': function () { let i = 0; return { - next: function() { + next: function () { const done = ++i > 2; return { value: done ? undefined : , @@ -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', () => { const iterable = { - '@@iterator': function() { + '@@iterator': function () { let i = 0; return { - next: function() { + next: function () { const done = ++i > 2; return {value: done ? undefined : [i, ], done: done}; }, @@ -330,9 +330,7 @@ it('gives a helpful error when passing null, undefined, or boolean', () => { const Null = null; const True = true; const Div = 'div'; - expect( - () => void () - ).toErrorDev( + expect(() => void ()).toErrorDev( 'Warning: React.jsx: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + '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} ); - expect( - () => void () - ).toErrorDev( + expect(() => void ()).toErrorDev( 'Warning: React.jsx: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: null.' + @@ -354,9 +350,7 @@ it('gives a helpful error when passing null, undefined, or boolean', () => { : ''), {withoutStack: true} ); - expect( - () => void () - ).toErrorDev( + expect(() => void ()).toErrorDev( 'Warning: React.jsx: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: boolean.' + @@ -716,9 +710,7 @@ it('should warn when `key` is being accessed on composite element', () => { ); } } - expect(() => - ReactDOM.render(, container) - ).toErrorDev( + expect(() => ReactDOM.render(, container)).toErrorDev( 'Child: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + '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(() => - ReactDOM.render(, container) - ).toErrorDev( + expect(() => ReactDOM.render(, container)).toErrorDev( 'Child: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + diff --git a/fixtures/legacy-jsx-runtimes/react-16/react-16.test.js b/fixtures/legacy-jsx-runtimes/react-16/react-16.test.js index aadf6e8dbf5d0..66a82ed165156 100644 --- a/fixtures/legacy-jsx-runtimes/react-16/react-16.test.js +++ b/fixtures/legacy-jsx-runtimes/react-16/react-16.test.js @@ -254,10 +254,10 @@ it('does not warn for arrays of elements with keys', () => { it('does not warn for iterable elements with keys', () => { const iterable = { - '@@iterator': function() { + '@@iterator': function () { let i = 0; return { - next: function() { + next: function () { const done = ++i > 2; return { value: done ? undefined : , @@ -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', () => { const iterable = { - '@@iterator': function() { + '@@iterator': function () { let i = 0; return { - next: function() { + next: function () { const done = ++i > 2; return {value: done ? undefined : [i, ], done: done}; }, @@ -330,9 +330,7 @@ it('gives a helpful error when passing null, undefined, or boolean', () => { const Null = null; const True = true; const Div = 'div'; - expect( - () => void () - ).toErrorDev( + expect(() => void ()).toErrorDev( 'Warning: React.jsx: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + '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} ); - expect( - () => void () - ).toErrorDev( + expect(() => void ()).toErrorDev( 'Warning: React.jsx: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: null.' + @@ -354,9 +350,7 @@ it('gives a helpful error when passing null, undefined, or boolean', () => { : ''), {withoutStack: true} ); - expect( - () => void () - ).toErrorDev( + expect(() => void ()).toErrorDev( 'Warning: React.jsx: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: boolean.' + diff --git a/fixtures/legacy-jsx-runtimes/react-17/react-17.test.js b/fixtures/legacy-jsx-runtimes/react-17/react-17.test.js index ea5a0aa585c8f..ab47ee0d947a4 100644 --- a/fixtures/legacy-jsx-runtimes/react-17/react-17.test.js +++ b/fixtures/legacy-jsx-runtimes/react-17/react-17.test.js @@ -254,10 +254,10 @@ it('does not warn for arrays of elements with keys', () => { it('does not warn for iterable elements with keys', () => { const iterable = { - '@@iterator': function() { + '@@iterator': function () { let i = 0; return { - next: function() { + next: function () { const done = ++i > 2; return { value: done ? undefined : , @@ -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', () => { const iterable = { - '@@iterator': function() { + '@@iterator': function () { let i = 0; return { - next: function() { + next: function () { const done = ++i > 2; return {value: done ? undefined : [i, ], done: done}; }, @@ -330,9 +330,7 @@ it('gives a helpful error when passing null, undefined, or boolean', () => { const Null = null; const True = true; const Div = 'div'; - expect( - () => void () - ).toErrorDev( + expect(() => void ()).toErrorDev( 'Warning: React.jsx: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + '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} ); - expect( - () => void () - ).toErrorDev( + expect(() => void ()).toErrorDev( 'Warning: React.jsx: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: null.' + @@ -354,9 +350,7 @@ it('gives a helpful error when passing null, undefined, or boolean', () => { : ''), {withoutStack: true} ); - expect( - () => void () - ).toErrorDev( + expect(() => void ()).toErrorDev( 'Warning: React.jsx: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: boolean.' + diff --git a/fixtures/legacy-jsx-runtimes/setupTests.js b/fixtures/legacy-jsx-runtimes/setupTests.js index 3e675b3f7c2c5..72116dea9df4b 100644 --- a/fixtures/legacy-jsx-runtimes/setupTests.js +++ b/fixtures/legacy-jsx-runtimes/setupTests.js @@ -49,7 +49,7 @@ function normalizeCodeLocInfo(str) { // at Component (/path/filename.js:123:45) // React format: // 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 **)'; }); } diff --git a/fixtures/nesting/src/modern/lazyLegacyRoot.js b/fixtures/nesting/src/modern/lazyLegacyRoot.js index 648b2aea3fe2b..a4a1fdbd79afc 100644 --- a/fixtures/nesting/src/modern/lazyLegacyRoot.js +++ b/fixtures/nesting/src/modern/lazyLegacyRoot.js @@ -19,8 +19,9 @@ export default function lazyLegacyRoot(getLegacyComponent) { }; return function Wrapper(props) { - const createLegacyRoot = readModule(rendererModule, () => - import('../legacy/createLegacyRoot') + const createLegacyRoot = readModule( + rendererModule, + () => import('../legacy/createLegacyRoot') ).default; const Component = readModule(componentModule, getLegacyComponent).default; const containerRef = useRef(null); diff --git a/fixtures/packaging/rjs/dev/input.js b/fixtures/packaging/rjs/dev/input.js index 510e71da20221..6c0a9d4fd246e 100644 --- a/fixtures/packaging/rjs/dev/input.js +++ b/fixtures/packaging/rjs/dev/input.js @@ -1,4 +1,4 @@ -require(['react', 'react-dom'], function(React, ReactDOM) { +require(['react', 'react-dom'], function (React, ReactDOM) { ReactDOM.render( React.createElement('h1', null, 'Hello World!'), document.getElementById('container') diff --git a/fixtures/packaging/rjs/prod/input.js b/fixtures/packaging/rjs/prod/input.js index 510e71da20221..6c0a9d4fd246e 100644 --- a/fixtures/packaging/rjs/prod/input.js +++ b/fixtures/packaging/rjs/prod/input.js @@ -1,4 +1,4 @@ -require(['react', 'react-dom'], function(React, ReactDOM) { +require(['react', 'react-dom'], function (React, ReactDOM) { ReactDOM.render( React.createElement('h1', null, 'Hello World!'), document.getElementById('container') diff --git a/fixtures/packaging/systemjs-builder/dev/build.js b/fixtures/packaging/systemjs-builder/dev/build.js index d476c09a64624..964f6991f1ede 100644 --- a/fixtures/packaging/systemjs-builder/dev/build.js +++ b/fixtures/packaging/systemjs-builder/dev/build.js @@ -3,10 +3,10 @@ var Builder = require('systemjs-builder'); var builder = new Builder('/', './config.js'); builder .buildStatic('./input.js', './output.js') - .then(function() { + .then(function () { console.log('Build complete'); }) - .catch(function(err) { + .catch(function (err) { console.log('Build error'); console.log(err); }); diff --git a/fixtures/packaging/systemjs-builder/prod/build.js b/fixtures/packaging/systemjs-builder/prod/build.js index d476c09a64624..964f6991f1ede 100644 --- a/fixtures/packaging/systemjs-builder/prod/build.js +++ b/fixtures/packaging/systemjs-builder/prod/build.js @@ -3,10 +3,10 @@ var Builder = require('systemjs-builder'); var builder = new Builder('/', './config.js'); builder .buildStatic('./input.js', './output.js') - .then(function() { + .then(function () { console.log('Build complete'); }) - .catch(function(err) { + .catch(function (err) { console.log('Build error'); console.log(err); }); diff --git a/fixtures/ssr/server/index.js b/fixtures/ssr/server/index.js index 2b41c6d9fdebb..dd8a783b50842 100644 --- a/fixtures/ssr/server/index.js +++ b/fixtures/ssr/server/index.js @@ -14,7 +14,7 @@ const app = express(); // Application 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 // get automatic hot reloading. for (var key in require.cache) { @@ -25,7 +25,7 @@ if (process.env.NODE_ENV === 'development') { }); } else { const render = require('./render').default; - app.get('/', function(req, res) { + app.get('/', function (req, res) { render(req.url, res); }); } @@ -48,7 +48,7 @@ app.listen(3000, () => { console.log('Listening on port 3000...'); }); -app.on('error', function(error) { +app.on('error', function (error) { if (error.syscall !== 'listen') { throw error; } diff --git a/fixtures/ssr2/server/server.js b/fixtures/ssr2/server/server.js index 25dd6e194b72d..4e5b90f400fdd 100644 --- a/fixtures/ssr2/server/server.js +++ b/fixtures/ssr2/server/server.js @@ -38,7 +38,7 @@ app.use((req, res, next) => { app.use(compress()); app.get( '/', - handleErrors(async function(req, res) { + handleErrors(async function (req, res) { await waitForWebpack(); render(req.url, res); }) @@ -50,7 +50,7 @@ app .listen(PORT, () => { console.log(`Listening at ${PORT}...`); }) - .on('error', function(error) { + .on('error', function (error) { if (error.syscall !== 'listen') { throw error; } @@ -71,7 +71,7 @@ app }); function handleErrors(fn) { - return async function(req, res, next) { + return async function (req, res, next) { try { return await fn(req, res); } catch (x) { diff --git a/fixtures/stacks/BabelClasses-compiled.js b/fixtures/stacks/BabelClasses-compiled.js index 7350dba8eff94..521646fd324e4 100644 --- a/fixtures/stacks/BabelClasses-compiled.js +++ b/fixtures/stacks/BabelClasses-compiled.js @@ -29,7 +29,7 @@ function _inheritsLoose(subClass, superClass) { // Compile this with Babel. // 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); function BabelClass() { @@ -45,7 +45,7 @@ let BabelClass = /*#__PURE__*/ (function(_React$Component) { return BabelClass; })(React.Component); -let BabelClassWithFields = /*#__PURE__*/ (function(_React$Component2) { +let BabelClassWithFields = /*#__PURE__*/ (function (_React$Component2) { _inheritsLoose(BabelClassWithFields, _React$Component2); function BabelClassWithFields(...args) { diff --git a/package.json b/package.json index db02b9ecd8a9d..97e1343213eb0 100644 --- a/package.json +++ b/package.json @@ -78,7 +78,7 @@ "mkdirp": "^0.5.1", "ncp": "^2.0.0", "pacote": "^10.3.0", - "prettier": "1.19.1", + "prettier": "2.8.3", "prop-types": "^15.6.2", "random-seed": "^0.3.0", "react-lifecycles-compat": "^3.0.4", @@ -87,7 +87,7 @@ "rollup-plugin-babel": "^4.0.1", "rollup-plugin-commonjs": "^9.3.4", "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-strip-banner": "^0.2.0", "semver": "^7.1.1", diff --git a/packages/dom-event-testing-library/domEnvironment.js b/packages/dom-event-testing-library/domEnvironment.js index 2c654c413f8a8..3ec9e016bff90 100644 --- a/packages/dom-event-testing-library/domEnvironment.js +++ b/packages/dom-event-testing-library/domEnvironment.js @@ -13,7 +13,7 @@ * Change environment support for PointerEvent. */ -const emptyFunction = function() {}; +const emptyFunction = function () {}; export function hasPointerEvent() { return global != null && global.PointerEvent != null; diff --git a/packages/dom-event-testing-library/index.js b/packages/dom-event-testing-library/index.js index 71f303a908368..0bab0a84089e2 100644 --- a/packages/dom-event-testing-library/index.js +++ b/packages/dom-event-testing-library/index.js @@ -93,7 +93,7 @@ const createEventTarget = node => ({ * Utilities */ setBoundingClientRect({x, y, width, height}) { - node.getBoundingClientRect = function() { + node.getBoundingClientRect = function () { return { width, height, diff --git a/packages/eslint-plugin-react-hooks/__tests__/ESLintRuleExhaustiveDeps-test.js b/packages/eslint-plugin-react-hooks/__tests__/ESLintRuleExhaustiveDeps-test.js index 914c2d526107c..706613e401b28 100644 --- a/packages/eslint-plugin-react-hooks/__tests__/ESLintRuleExhaustiveDeps-test.js +++ b/packages/eslint-plugin-react-hooks/__tests__/ESLintRuleExhaustiveDeps-test.js @@ -1525,8 +1525,7 @@ const tests = { 'Either include it or remove the dependency array.', suggestions: [ { - desc: - 'Update the dependencies array to be: [props.foo?.bar?.baz]', + desc: 'Update the dependencies array to be: [props.foo?.bar?.baz]', output: normalizeIndent` function MyComponent(props) { useCallback(() => { @@ -2662,8 +2661,7 @@ const tests = { 'Either include them or remove the dependency array.', suggestions: [ { - desc: - 'Update the dependencies array to be: [props.bar, props.foo]', + desc: 'Update the dependencies array to be: [props.bar, props.foo]', output: normalizeIndent` function MyComponent(props) { const local = {}; @@ -2819,8 +2817,7 @@ const tests = { 'Either include it or remove the dependency array.', suggestions: [ { - desc: - 'Update the dependencies array to be: [color, props.foo.bar.baz]', + desc: 'Update the dependencies array to be: [color, props.foo.bar.baz]', output: normalizeIndent` function MyComponent(props) { let color = {} @@ -2884,8 +2881,7 @@ const tests = { 'Either include them or remove the dependency array.', suggestions: [ { - desc: - 'Update the dependencies array to be: [props.foo.bar.baz, props.foo.fizz.bizz]', + desc: 'Update the dependencies array to be: [props.foo.bar.baz, props.foo.fizz.bizz]', output: normalizeIndent` function MyComponent(props) { const fn = useCallback(() => { @@ -3095,8 +3091,7 @@ const tests = { 'Either include them or remove the dependency array.', suggestions: [ { - desc: - 'Update the dependencies array to be: [props.bar, props.foo]', + desc: 'Update the dependencies array to be: [props.bar, props.foo]', output: normalizeIndent` function MyComponent(props) { useEffect(() => { @@ -3127,8 +3122,7 @@ const tests = { // Don't alphabetize if it wasn't alphabetized in the first place. suggestions: [ { - desc: - 'Update the dependencies array to be: [c, a, g, b, e, d, f]', + desc: 'Update the dependencies array to be: [c, a, g, b, e, d, f]', output: normalizeIndent` function MyComponent(props) { let a, b, c, d, e, f, g; @@ -3159,8 +3153,7 @@ const tests = { // Alphabetize if it was alphabetized. suggestions: [ { - desc: - 'Update the dependencies array to be: [a, b, c, d, e, f, g]', + desc: 'Update the dependencies array to be: [a, b, c, d, e, f, g]', output: normalizeIndent` function MyComponent(props) { let a, b, c, d, e, f, g; @@ -3191,8 +3184,7 @@ const tests = { // Alphabetize if it was empty. suggestions: [ { - desc: - 'Update the dependencies array to be: [a, b, c, d, e, f, g]', + desc: 'Update the dependencies array to be: [a, b, c, d, e, f, g]', output: normalizeIndent` function MyComponent(props) { let a, b, c, d, e, f, g; @@ -3224,8 +3216,7 @@ const tests = { 'Either include them or remove the dependency array.', suggestions: [ { - desc: - 'Update the dependencies array to be: [local, props.bar, props.foo]', + desc: 'Update the dependencies array to be: [local, props.bar, props.foo]', output: normalizeIndent` function MyComponent(props) { const local = {}; @@ -3812,8 +3803,7 @@ const tests = { 'Either include them or remove the dependency array.', suggestions: [ { - desc: - 'Update the dependencies array to be: [props.color, props.someOtherRefs]', + desc: 'Update the dependencies array to be: [props.color, props.someOtherRefs]', output: normalizeIndent` function MyComponent(props) { const ref1 = useRef(); @@ -3853,8 +3843,7 @@ const tests = { "because mutating them doesn't re-render the component.", suggestions: [ { - desc: - 'Update the dependencies array to be: [props.someOtherRefs, props.color]', + desc: 'Update the dependencies array to be: [props.someOtherRefs, props.color]', output: normalizeIndent` function MyComponent(props) { const ref1 = useRef(); @@ -3894,8 +3883,7 @@ const tests = { "because mutating them doesn't re-render the component.", suggestions: [ { - desc: - 'Update the dependencies array to be: [props.someOtherRefs, props.color]', + desc: 'Update the dependencies array to be: [props.someOtherRefs, props.color]', output: normalizeIndent` function MyComponent(props) { const ref1 = useRef(); @@ -4287,8 +4275,7 @@ const tests = { `props inside useEffect.`, suggestions: [ { - desc: - 'Update the dependencies array to be: [skillsCount, props.isEditMode, props.toggleEditMode, props]', + desc: 'Update the dependencies array to be: [skillsCount, props.isEditMode, props.toggleEditMode, props]', output: normalizeIndent` function MyComponent(props) { const [skillsCount] = useState(); @@ -4719,8 +4706,7 @@ const tests = { 'Either include it or remove the dependency array.', suggestions: [ { - desc: - 'Update the dependencies array to be: [local1, local3, local4]', + desc: 'Update the dependencies array to be: [local1, local3, local4]', output: normalizeIndent` function MyComponent() { const local1 = 42; @@ -5562,8 +5548,7 @@ const tests = { // the easy fix and you can't just move it into effect. suggestions: [ { - desc: - "Wrap the definition of 'handleNext' in its own useCallback() Hook.", + desc: "Wrap the definition of 'handleNext' in its own useCallback() Hook.", output: normalizeIndent` function MyComponent(props) { let [, setState] = useState(); @@ -5737,8 +5722,7 @@ const tests = { // because they are only referenced outside the effect. suggestions: [ { - desc: - "Wrap the definition of 'handleNext2' in its own useCallback() Hook.", + desc: "Wrap the definition of 'handleNext2' in its own useCallback() Hook.", output: normalizeIndent` function MyComponent(props) { function handleNext1() { @@ -5787,8 +5771,7 @@ const tests = { // because they are only referenced outside the effect. suggestions: [ { - desc: - "Wrap the definition of 'handleNext3' in its own useCallback() Hook.", + desc: "Wrap the definition of 'handleNext3' in its own useCallback() Hook.", output: normalizeIndent` function MyComponent(props) { function handleNext1() { @@ -5862,8 +5845,7 @@ const tests = { "definition of 'handleNext1' in its own useCallback() Hook.", suggestions: [ { - desc: - "Wrap the definition of 'handleNext1' in its own useCallback() Hook.", + desc: "Wrap the definition of 'handleNext1' in its own useCallback() Hook.", output: normalizeIndent` function MyComponent(props) { const handleNext1 = useCallback(() => { @@ -5892,8 +5874,7 @@ const tests = { "definition of 'handleNext1' in its own useCallback() Hook.", suggestions: [ { - desc: - "Wrap the definition of 'handleNext1' in its own useCallback() Hook.", + desc: "Wrap the definition of 'handleNext1' in its own useCallback() Hook.", output: normalizeIndent` function MyComponent(props) { const handleNext1 = useCallback(() => { @@ -5959,8 +5940,7 @@ const tests = { // it only wraps the first definition. But seems ok. suggestions: [ { - desc: - "Wrap the definition of 'handleNext' in its own useCallback() Hook.", + desc: "Wrap the definition of 'handleNext' in its own useCallback() Hook.", output: normalizeIndent` function MyComponent(props) { let handleNext = useCallback(() => { @@ -6493,8 +6473,7 @@ const tests = { `find the parent component that defines it and wrap that definition in useCallback.`, suggestions: [ { - desc: - 'Update the dependencies array to be: [fetchPodcasts, fetchPodcasts2, id]', + desc: 'Update the dependencies array to be: [fetchPodcasts, fetchPodcasts2, id]', output: normalizeIndent` function Podcasts({ fetchPodcasts, fetchPodcasts2, id }) { let [podcasts, setPodcasts] = useState(null); @@ -7135,8 +7114,7 @@ const tests = { 'Either include them or remove the dependency array.', suggestions: [ { - desc: - 'Update the dependencies array to be: [foo.bar, props.foo.bar]', + desc: 'Update the dependencies array to be: [foo.bar, props.foo.bar]', output: normalizeIndent` function MyComponent(props) { let foo = {} @@ -7845,8 +7823,7 @@ const testsTypescript = { 'Either include them or remove the dependency array.', suggestions: [ { - desc: - 'Update the dependencies array to be: [pizza.crust, pizza?.toppings]', + desc: 'Update the dependencies array to be: [pizza.crust, pizza?.toppings]', output: normalizeIndent` function MyComponent() { const pizza = {}; @@ -7981,8 +7958,7 @@ const testsTypescript = { 'Either include it or remove the dependency array.', suggestions: [ { - desc: - 'Update the dependencies array to be: [props.upperViewHeight]', + desc: 'Update the dependencies array to be: [props.upperViewHeight]', output: normalizeIndent` function Example(props) { useEffect(() => { @@ -8013,8 +7989,7 @@ const testsTypescript = { 'Either include it or remove the dependency array.', suggestions: [ { - desc: - 'Update the dependencies array to be: [props?.upperViewHeight]', + desc: 'Update the dependencies array to be: [props?.upperViewHeight]', output: normalizeIndent` function Example(props) { useEffect(() => { diff --git a/packages/eslint-plugin-react-hooks/src/ExhaustiveDeps.js b/packages/eslint-plugin-react-hooks/src/ExhaustiveDeps.js index fd5bcd1c95ab3..da1e3e754e1d8 100644 --- a/packages/eslint-plugin-react-hooks/src/ExhaustiveDeps.js +++ b/packages/eslint-plugin-react-hooks/src/ExhaustiveDeps.js @@ -76,7 +76,7 @@ export default { const functionWithoutCapturedValueCache = new WeakMap(); const useEffectEventVariables = new WeakSet(); function memoizeWithWeakMap(fn, map) { - return function(arg) { + return function (arg) { if (map.has(arg)) { // to verify cache hits: // console.log(arg.name) diff --git a/packages/eslint-plugin-react-hooks/src/RulesOfHooks.js b/packages/eslint-plugin-react-hooks/src/RulesOfHooks.js index ded525e08545f..e6a71cec116b0 100644 --- a/packages/eslint-plugin-react-hooks/src/RulesOfHooks.js +++ b/packages/eslint-plugin-react-hooks/src/RulesOfHooks.js @@ -383,9 +383,8 @@ export default { // 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. - const isSomewhereInsideComponentOrHook = isInsideComponentOrHook( - codePathNode, - ); + const isSomewhereInsideComponentOrHook = + isInsideComponentOrHook(codePathNode); const isDirectlyInsideComponentOrHook = codePathFunctionName ? isComponentName(codePathFunctionName) || isHook(codePathFunctionName) diff --git a/packages/jest-mock-scheduler/README.md b/packages/jest-mock-scheduler/README.md deleted file mode 100644 index 387f015246617..0000000000000 --- a/packages/jest-mock-scheduler/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# `jest-mock-scheduler` - -Jest matchers and utilities for testing the `scheduler` package. - -This package is experimental. APIs may change between releases. \ No newline at end of file diff --git a/packages/jest-mock-scheduler/npm/index.js b/packages/jest-mock-scheduler/npm/index.js deleted file mode 100644 index 9a1d6ca4d1495..0000000000000 --- a/packages/jest-mock-scheduler/npm/index.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict'; - -module.exports = require('scheduler/unstable_mock'); diff --git a/packages/jest-mock-scheduler/package.json b/packages/jest-mock-scheduler/package.json deleted file mode 100644 index 16761b19d3750..0000000000000 --- a/packages/jest-mock-scheduler/package.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "jest-mock-scheduler", - "private": true, - "version": "0.1.0", - "description": "Jest matchers and utilities for testing the scheduler package.", - "main": "index.js", - "repository": { - "type" : "git", - "url" : "https://github.com/facebook/react.git", - "directory": "packages/jest-mock-scheduler" - }, - "keywords": [ - "jest", - "scheduler" - ], - "license": "MIT", - "bugs": { - "url": "https://github.com/facebook/react/issues" - }, - "homepage": "https://reactjs.org/", - "peerDependencies": { - "jest": "^23.0.1 || ^24.0.0 || ^25.1.0", - "scheduler": "^0.20.0" - }, - "files": [ - "LICENSE", - "README.md", - "index.js", - "cjs/" - ] -} diff --git a/packages/react-art/src/ReactART.js b/packages/react-art/src/ReactART.js index 2bd66260f6d78..9b065a2b1185c 100644 --- a/packages/react-art/src/ReactART.js +++ b/packages/react-art/src/ReactART.js @@ -127,7 +127,7 @@ class Text extends React.Component { // ref directly. ['height', 'width', 'x', 'y'].forEach(key => { Object.defineProperty(this, key, { - get: function() { + get: function () { return this._text ? this._text[key] : undefined; }, }); diff --git a/packages/react-art/src/__tests__/ReactART-test.js b/packages/react-art/src/__tests__/ReactART-test.js index 59233e51b2a62..6cc38b47b8d7a 100644 --- a/packages/react-art/src/__tests__/ReactART-test.js +++ b/packages/react-art/src/__tests__/ReactART-test.js @@ -59,7 +59,7 @@ function testDOMNodeStructure(domNode, expectedStructure) { } } if (expectedStructure.children) { - expectedStructure.children.forEach(function(subTree, index) { + expectedStructure.children.forEach(function (subTree, index) { testDOMNodeStructure(domNode.childNodes[index], subTree); }); } diff --git a/packages/react-client/src/ReactFlightClient.js b/packages/react-client/src/ReactFlightClient.js index 5293bc794af26..86455c3dfe6ad 100644 --- a/packages/react-client/src/ReactFlightClient.js +++ b/packages/react-client/src/ReactFlightClient.js @@ -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 Chunk.prototype = (Object.create(Promise.prototype): any); // TODO: This doesn't return a new Promise chain unlike the real .then -Chunk.prototype.then = function( +Chunk.prototype.then = function ( this: SomeChunk, resolve: (value: T) => mixed, reject: (reason: mixed) => mixed, diff --git a/packages/react-client/src/ReactFlightClientStream.js b/packages/react-client/src/ReactFlightClientStream.js index 4709ca8085ddc..bcdcda4375a8f 100644 --- a/packages/react-client/src/ReactFlightClientStream.js +++ b/packages/react-client/src/ReactFlightClientStream.js @@ -123,7 +123,7 @@ export function processBinaryChunk( function createFromJSONCallback(response: Response) { // $FlowFixMe[missing-this-annot] - return function(key: string, value: JSONValue) { + return function (key: string, value: JSONValue) { if (typeof value === 'string') { // We can't use .bind here because we need the "this" value. return parseModelString(response, this, key, value); diff --git a/packages/react-client/src/__tests__/ReactFlight-test.js b/packages/react-client/src/__tests__/ReactFlight-test.js index 416ad45bc671b..56d4deb3fb39f 100644 --- a/packages/react-client/src/__tests__/ReactFlight-test.js +++ b/packages/react-client/src/__tests__/ReactFlight-test.js @@ -93,7 +93,7 @@ describe('ReactFlight', () => { function clientReference(value) { return Object.defineProperties( - function() { + function () { throw new Error('Cannot call a client function from the server.'); }, { @@ -378,7 +378,7 @@ describe('ReactFlight', () => { function EventHandlerProp() { return ( -
+
Test
); @@ -397,7 +397,7 @@ describe('ReactFlight', () => { function EventHandlerPropClient() { return ( - + Test ); diff --git a/packages/react-debug-tools/src/__tests__/ReactHooksInspectionIntegration-test.js b/packages/react-debug-tools/src/__tests__/ReactHooksInspectionIntegration-test.js index af31e5e6fd600..0b95cf215abcb 100644 --- a/packages/react-debug-tools/src/__tests__/ReactHooksInspectionIntegration-test.js +++ b/packages/react-debug-tools/src/__tests__/ReactHooksInspectionIntegration-test.js @@ -58,10 +58,8 @@ describe('ReactHooksInspectionIntegration', () => { }, ]); - const { - onMouseDown: setStateA, - onMouseUp: setStateB, - } = renderer.root.findByType('div').props; + const {onMouseDown: setStateA, onMouseUp: setStateB} = + renderer.root.findByType('div').props; act(() => setStateA('Hi')); @@ -469,8 +467,8 @@ describe('ReactHooksInspectionIntegration', () => { }); it('should inspect forwardRef', () => { - const obj = function() {}; - const Foo = React.forwardRef(function(props, ref) { + const obj = function () {}; + const Foo = React.forwardRef(function (props, ref) { React.useImperativeHandle(ref, () => obj); return
; }); diff --git a/packages/react-devtools-core/src/backend.js b/packages/react-devtools-core/src/backend.js index d2127b6d16363..3a43c9bef70e8 100644 --- a/packages/react-devtools-core/src/backend.js +++ b/packages/react-devtools-core/src/backend.js @@ -42,7 +42,8 @@ installHook(window); const hook: ?DevToolsHook = window.__REACT_DEVTOOLS_GLOBAL_HOOK__; -let savedComponentFilters: Array = getDefaultComponentFilters(); +let savedComponentFilters: Array = + getDefaultComponentFilters(); function debug(methodName: string, ...args: Array) { if (__DEBUG__) { @@ -114,7 +115,7 @@ export function connectToDevTools(options: ?ConnectOptions) { ws.onclose = handleClose; ws.onerror = handleFailed; ws.onmessage = handleMessage; - ws.onopen = function() { + ws.onopen = function () { bridge = new Bridge({ listen(fn) { messageListeners.push(fn); diff --git a/packages/react-devtools-core/src/cachedSettings.js b/packages/react-devtools-core/src/cachedSettings.js index cb6dddfec313b..945c0cf60a42c 100644 --- a/packages/react-devtools-core/src/cachedSettings.js +++ b/packages/react-devtools-core/src/cachedSettings.js @@ -33,7 +33,8 @@ function initializeConsolePatchSettings( if (devToolsSettingsManager.getConsolePatchSettings == null) { return; } - const consolePatchSettingsString = devToolsSettingsManager.getConsolePatchSettings(); + const consolePatchSettingsString = + devToolsSettingsManager.getConsolePatchSettings(); if (consolePatchSettingsString == null) { return; } diff --git a/packages/react-devtools-core/src/editor.js b/packages/react-devtools-core/src/editor.js index 2afeba9a82b8e..0172d0a1568df 100644 --- a/packages/react-devtools-core/src/editor.js +++ b/packages/react-devtools-core/src/editor.js @@ -186,9 +186,9 @@ export function launchEditor( } else { childProcess = spawn(editor, args, {stdio: 'inherit'}); } - childProcess.on('error', function() {}); + childProcess.on('error', function () {}); // $FlowFixMe[incompatible-use] found when upgrading Flow - childProcess.on('exit', function(errorCode) { + childProcess.on('exit', function (errorCode) { childProcess = null; }); } diff --git a/packages/react-devtools-core/src/standalone.js b/packages/react-devtools-core/src/standalone.js index 22cf1677003e1..71e744741ec21 100644 --- a/packages/react-devtools-core/src/standalone.js +++ b/packages/react-devtools-core/src/standalone.js @@ -283,7 +283,7 @@ function connectToSocket(socket: WebSocket): {close(): void} { initialize(socket); return { - close: function() { + close: function () { onDisconnected(); }, }; @@ -390,7 +390,7 @@ function startServer( }); return { - close: function() { + close: function () { connected = null; onDisconnected(); if (startServerTimeoutID !== null) { diff --git a/packages/react-devtools-extensions/deploy.js b/packages/react-devtools-extensions/deploy.js index c9bfdaf6af73f..f177240909a55 100644 --- a/packages/react-devtools-extensions/deploy.js +++ b/packages/react-devtools-extensions/deploy.js @@ -27,10 +27,7 @@ const main = async buildId => { const json = JSON.parse(file); const alias = json.alias[0]; - const commit = execSync('git rev-parse HEAD') - .toString() - .trim() - .substr(0, 7); + const commit = execSync('git rev-parse HEAD').toString().trim().substr(0, 7); let date = new Date(); date = `${date.toLocaleDateString()} – ${date.toLocaleTimeString()}`; diff --git a/packages/react-devtools-extensions/popups/shared.js b/packages/react-devtools-extensions/popups/shared.js index 53b2bc1d16e22..9793429b4998a 100644 --- a/packages/react-devtools-extensions/popups/shared.js +++ b/packages/react-devtools-extensions/popups/shared.js @@ -2,14 +2,14 @@ 'use strict'; -document.addEventListener('DOMContentLoaded', function() { +document.addEventListener('DOMContentLoaded', function () { // Make links work const links = document.getElementsByTagName('a'); for (let i = 0; i < links.length; i++) { - (function() { + (function () { const ln = links[i]; const location = ln.href; - ln.onclick = function() { + ln.onclick = function () { chrome.tabs.create({active: true, url: location}); return false; }; @@ -19,7 +19,7 @@ document.addEventListener('DOMContentLoaded', function() { // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=428044 document.body.style.opacity = 0; document.body.style.transition = 'opacity ease-out .4s'; - requestAnimationFrame(function() { + requestAnimationFrame(function () { document.body.style.opacity = 1; }); }); diff --git a/packages/react-devtools-extensions/src/backend.js b/packages/react-devtools-extensions/src/backend.js index 5c397c3ee2128..acfead859d4e4 100644 --- a/packages/react-devtools-extensions/src/backend.js +++ b/packages/react-devtools-extensions/src/backend.js @@ -51,8 +51,8 @@ function setup(hook: any) { const Agent = require('react-devtools-shared/src/backend/agent').default; const Bridge = require('react-devtools-shared/src/bridge').default; const {initBackend} = require('react-devtools-shared/src/backend'); - const setupNativeStyleEditor = require('react-devtools-shared/src/backend/NativeStyleEditor/setupNativeStyleEditor') - .default; + const setupNativeStyleEditor = + require('react-devtools-shared/src/backend/NativeStyleEditor/setupNativeStyleEditor').default; const bridge = new Bridge({ listen(fn) { diff --git a/packages/react-devtools-extensions/src/background.js b/packages/react-devtools-extensions/src/background.js index 5b33330994581..70c2420b0df18 100644 --- a/packages/react-devtools-extensions/src/background.js +++ b/packages/react-devtools-extensions/src/background.js @@ -30,7 +30,7 @@ if (!IS_FIREFOX) { ]); } -chrome.runtime.onConnect.addListener(function(port) { +chrome.runtime.onConnect.addListener(function (port) { let tab = null; let name = null; if (isNumeric(port.name)) { @@ -61,7 +61,7 @@ function isNumeric(str: string): boolean { function installProxy(tabId: number) { if (IS_FIREFOX) { - chrome.tabs.executeScript(tabId, {file: '/build/proxy.js'}, function() {}); + chrome.tabs.executeScript(tabId, {file: '/build/proxy.js'}, function () {}); } else { chrome.scripting.executeScript({ target: {tabId: tabId}, diff --git a/packages/react-devtools-extensions/src/contentScripts/installHook.js b/packages/react-devtools-extensions/src/contentScripts/installHook.js index 8517ff5ff999f..c02a66342ffc2 100644 --- a/packages/react-devtools-extensions/src/contentScripts/installHook.js +++ b/packages/react-devtools-extensions/src/contentScripts/installHook.js @@ -5,17 +5,18 @@ if (!window.hasOwnProperty('__REACT_DEVTOOLS_GLOBAL_HOOK__')) { installHook(window); // detect react - window.__REACT_DEVTOOLS_GLOBAL_HOOK__.on('renderer', function({ - reactBuildType, - }) { - window.postMessage( - { - source: 'react-devtools-detector', - reactBuildType, - }, - '*', - ); - }); + window.__REACT_DEVTOOLS_GLOBAL_HOOK__.on( + 'renderer', + function ({reactBuildType}) { + window.postMessage( + { + source: 'react-devtools-detector', + reactBuildType, + }, + '*', + ); + }, + ); // save native values window.__REACT_DEVTOOLS_GLOBAL_HOOK__.nativeObjectCreate = Object.create; diff --git a/packages/react-devtools-extensions/src/contentScripts/prepareInjection.js b/packages/react-devtools-extensions/src/contentScripts/prepareInjection.js index c609b58c909d6..b5d667d26254a 100644 --- a/packages/react-devtools-extensions/src/contentScripts/prepareInjection.js +++ b/packages/react-devtools-extensions/src/contentScripts/prepareInjection.js @@ -8,7 +8,7 @@ import {IS_FIREFOX} from '../utils'; function injectScriptSync(src) { let code = ''; const request = new XMLHttpRequest(); - request.addEventListener('load', function() { + request.addEventListener('load', function () { code = this.responseText; }); request.open('GET', src, false); @@ -26,7 +26,7 @@ function injectScriptSync(src) { function injectScriptAsync(src) { const script = document.createElement('script'); script.src = src; - script.onload = function() { + script.onload = function () { script.remove(); }; 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, // replay the last detection result if the content script is active and the // document has been hidden and shown again. -window.addEventListener('pageshow', function({target}) { +window.addEventListener('pageshow', function ({target}) { if (!lastDetectionResult || target !== window.document) { return; } diff --git a/packages/react-devtools-extensions/src/main.js b/packages/react-devtools-extensions/src/main.js index 69f5c21e79621..1e1fd25ad0d08 100644 --- a/packages/react-devtools-extensions/src/main.js +++ b/packages/react-devtools-extensions/src/main.js @@ -39,10 +39,10 @@ if (isChrome || isEdge) { // The polyfill is based on https://gist.github.com/jalbam/5fe05443270fa6d8136238ec72accbc0 const FRAME_TIME = 16; let lastTime = 0; - window.requestAnimationFrame = function(callback, element) { + window.requestAnimationFrame = function (callback, element) { const now = window.performance.now(); const nextTime = Math.max(lastTime + FRAME_TIME, now); - return setTimeout(function() { + return setTimeout(function () { callback((lastTime = nextTime)); }, nextTime - now); }; @@ -91,7 +91,7 @@ function createPanelIfReactLoaded() { chrome.devtools.inspectedWindow.eval( 'window.__REACT_DEVTOOLS_GLOBAL_HOOK__ && window.__REACT_DEVTOOLS_GLOBAL_HOOK__.renderers.size > 0', - function(pageHasReact, error) { + function (pageHasReact, error) { if (!pageHasReact || panelCreated) { return; } @@ -199,7 +199,7 @@ function createPanelIfReactLoaded() { // Otherwise the Store may miss important initial tree op codes. chrome.devtools.inspectedWindow.eval( `window.postMessage({ source: 'react-devtools-inject-backend' }, '*');`, - function(response, evalError) { + function (response, evalError) { if (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 // after page load -const loadCheckInterval = setInterval(function() { +const loadCheckInterval = setInterval(function () { createPanelIfReactLoaded(); }, 1000); diff --git a/packages/react-devtools-inline/__tests__/__e2e__/components.test.js b/packages/react-devtools-inline/__tests__/__e2e__/components.test.js index 4df0318b0fce0..dfa6775da6bab 100644 --- a/packages/react-devtools-inline/__tests__/__e2e__/components.test.js +++ b/packages/react-devtools-inline/__tests__/__e2e__/components.test.js @@ -61,10 +61,8 @@ test.describe('Components', () => { // Then read the inspected values. const [propName, propValue, sourceText] = await page.evaluate( isEditable => { - const { - createTestNameSelector, - findAllNodes, - } = window.REACT_DOM_DEVTOOLS; + const {createTestNameSelector, findAllNodes} = + window.REACT_DOM_DEVTOOLS; const container = document.getElementById('devtools'); // Get name of first prop @@ -150,10 +148,8 @@ test.describe('Components', () => { // Make sure the expected hook names are parsed and displayed eventually. await page.waitForFunction( hookNames => { - const { - createTestNameSelector, - findAllNodes, - } = window.REACT_DOM_DEVTOOLS; + const {createTestNameSelector, findAllNodes} = + window.REACT_DOM_DEVTOOLS; const container = document.getElementById('devtools'); const hooksTree = findAllNodes(container, [ @@ -181,10 +177,8 @@ test.describe('Components', () => { test('should allow searching for component by name', async () => { async function getComponentSearchResultsCount() { return await page.evaluate(() => { - const { - createTestNameSelector, - findAllNodes, - } = window.REACT_DOM_DEVTOOLS; + const {createTestNameSelector, findAllNodes} = + window.REACT_DOM_DEVTOOLS; const container = document.getElementById('devtools'); const element = findAllNodes(container, [ diff --git a/packages/react-devtools-inline/__tests__/__e2e__/devtools-utils.js b/packages/react-devtools-inline/__tests__/__e2e__/devtools-utils.js index 25b96c7c4bfdc..ca59fa3d914e2 100644 --- a/packages/react-devtools-inline/__tests__/__e2e__/devtools-utils.js +++ b/packages/react-devtools-inline/__tests__/__e2e__/devtools-utils.js @@ -16,11 +16,8 @@ async function clickButton(page, buttonTestName) { async function getElementCount(page, displayName) { return await page.evaluate(listItemText => { - const { - createTestNameSelector, - createTextSelector, - findAllNodes, - } = window.REACT_DOM_DEVTOOLS; + const {createTestNameSelector, createTextSelector, findAllNodes} = + window.REACT_DOM_DEVTOOLS; const container = document.getElementById('devtools'); const rows = findAllNodes(container, [ createTestNameSelector('ComponentTreeListItem'), @@ -32,11 +29,8 @@ async function getElementCount(page, displayName) { async function selectElement(page, displayName, waitForOwnersText) { await page.evaluate(listItemText => { - const { - createTestNameSelector, - createTextSelector, - findAllNodes, - } = window.REACT_DOM_DEVTOOLS; + const {createTestNameSelector, createTextSelector, findAllNodes} = + window.REACT_DOM_DEVTOOLS; const container = document.getElementById('devtools'); const listItem = findAllNodes(container, [ @@ -50,10 +44,8 @@ async function selectElement(page, displayName, waitForOwnersText) { // Wait for selected element's props to load. await page.waitForFunction( ({titleText, ownersListText}) => { - const { - createTestNameSelector, - findAllNodes, - } = window.REACT_DOM_DEVTOOLS; + const {createTestNameSelector, findAllNodes} = + window.REACT_DOM_DEVTOOLS; const container = document.getElementById('devtools'); const title = findAllNodes(container, [ diff --git a/packages/react-devtools-inline/__tests__/__e2e__/profiler.test.js b/packages/react-devtools-inline/__tests__/__e2e__/profiler.test.js index 191c32fc7fd7d..a5bda6fb70530 100644 --- a/packages/react-devtools-inline/__tests__/__e2e__/profiler.test.js +++ b/packages/react-devtools-inline/__tests__/__e2e__/profiler.test.js @@ -27,10 +27,8 @@ test.describe('Profiler', () => { runOnlyForReactRange('>=16.5'); async function getSnapshotSelectorText() { return await page.evaluate(() => { - const { - createTestNameSelector, - findAllNodes, - } = window.REACT_DOM_DEVTOOLS; + const {createTestNameSelector, findAllNodes} = + window.REACT_DOM_DEVTOOLS; const container = document.getElementById('devtools'); const input = findAllNodes(container, [ diff --git a/packages/react-devtools-inline/src/backend.js b/packages/react-devtools-inline/src/backend.js index 72d56cefe9094..8f949fbc8c8b4 100644 --- a/packages/react-devtools-inline/src/backend.js +++ b/packages/react-devtools-inline/src/backend.js @@ -24,11 +24,15 @@ function startActivation(contentWindow: any, bridge: BackendBridge) { hideConsoleLogsInStrictMode, } = data; - contentWindow.__REACT_DEVTOOLS_APPEND_COMPONENT_STACK__ = appendComponentStack; - contentWindow.__REACT_DEVTOOLS_BREAK_ON_CONSOLE_ERRORS__ = breakOnConsoleErrors; + contentWindow.__REACT_DEVTOOLS_APPEND_COMPONENT_STACK__ = + appendComponentStack; + contentWindow.__REACT_DEVTOOLS_BREAK_ON_CONSOLE_ERRORS__ = + breakOnConsoleErrors; contentWindow.__REACT_DEVTOOLS_COMPONENT_FILTERS__ = componentFilters; - contentWindow.__REACT_DEVTOOLS_SHOW_INLINE_WARNINGS_AND_ERRORS__ = showInlineWarningsAndErrors; - contentWindow.__REACT_DEVTOOLS_HIDE_CONSOLE_LOGS_IN_STRICT_MODE__ = hideConsoleLogsInStrictMode; + contentWindow.__REACT_DEVTOOLS_SHOW_INLINE_WARNINGS_AND_ERRORS__ = + showInlineWarningsAndErrors; + contentWindow.__REACT_DEVTOOLS_HIDE_CONSOLE_LOGS_IN_STRICT_MODE__ = + hideConsoleLogsInStrictMode; // TRICKY // 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_BREAK_ON_CONSOLE_ERRORS__ = breakOnConsoleErrors; window.__REACT_DEVTOOLS_COMPONENT_FILTERS__ = componentFilters; - window.__REACT_DEVTOOLS_SHOW_INLINE_WARNINGS_AND_ERRORS__ = showInlineWarningsAndErrors; - window.__REACT_DEVTOOLS_HIDE_CONSOLE_LOGS_IN_STRICT_MODE__ = hideConsoleLogsInStrictMode; + window.__REACT_DEVTOOLS_SHOW_INLINE_WARNINGS_AND_ERRORS__ = + showInlineWarningsAndErrors; + window.__REACT_DEVTOOLS_HIDE_CONSOLE_LOGS_IN_STRICT_MODE__ = + hideConsoleLogsInStrictMode; } finishActivation(contentWindow, bridge); diff --git a/packages/react-devtools-shared/src/__tests__/TimelineProfiler-test.js b/packages/react-devtools-shared/src/__tests__/TimelineProfiler-test.js index 180c1a5726687..107182bb445af 100644 --- a/packages/react-devtools-shared/src/__tests__/TimelineProfiler-test.js +++ b/packages/react-devtools-shared/src/__tests__/TimelineProfiler-test.js @@ -112,8 +112,8 @@ describe('Timeline profiler', () => { } beforeEach(() => { - setPerformanceMock = require('react-devtools-shared/src/backend/profilingHooks') - .setPerformanceMock_ONLY_FOR_TESTING; + setPerformanceMock = + require('react-devtools-shared/src/backend/profilingHooks').setPerformanceMock_ONLY_FOR_TESTING; setPerformanceMock(createUserTimingPolyfill()); }); diff --git a/packages/react-devtools-shared/src/__tests__/__serializers__/dehydratedValueSerializer.js b/packages/react-devtools-shared/src/__tests__/__serializers__/dehydratedValueSerializer.js index 69f4ebf93a537..9825f4a2ac82c 100644 --- a/packages/react-devtools-shared/src/__tests__/__serializers__/dehydratedValueSerializer.js +++ b/packages/react-devtools-shared/src/__tests__/__serializers__/dehydratedValueSerializer.js @@ -11,9 +11,8 @@ export function test(maybeDehydratedValue) { const {meta} = require('react-devtools-shared/src/hydration'); - const hasOwnProperty = Object.prototype.hasOwnProperty.bind( - maybeDehydratedValue, - ); + const hasOwnProperty = + Object.prototype.hasOwnProperty.bind(maybeDehydratedValue); return ( maybeDehydratedValue !== null && typeof maybeDehydratedValue === 'object' && diff --git a/packages/react-devtools-shared/src/__tests__/console-test.js b/packages/react-devtools-shared/src/__tests__/console-test.js index edba7922f5e67..e70c8e3a0afa8 100644 --- a/packages/react-devtools-shared/src/__tests__/console-test.js +++ b/packages/react-devtools-shared/src/__tests__/console-test.js @@ -430,7 +430,7 @@ describe('console', () => { it('should be resilient to prepareStackTrace', () => { global.__REACT_DEVTOOLS_APPEND_COMPONENT_STACK__ = true; - Error.prepareStackTrace = function(error, callsites) { + Error.prepareStackTrace = function (error, callsites) { const stack = ['An error occurred:', error.message]; for (let i = 0; i < callsites.length; i++) { const callsite = callsites[i]; diff --git a/packages/react-devtools-shared/src/__tests__/inspectedElement-test.js b/packages/react-devtools-shared/src/__tests__/inspectedElement-test.js index db248a98ca7f2..2606213faa4a7 100644 --- a/packages/react-devtools-shared/src/__tests__/inspectedElement-test.js +++ b/packages/react-devtools-shared/src/__tests__/inspectedElement-test.js @@ -59,18 +59,18 @@ describe('InspectedElement', () => { TestRenderer = utils.requireTestRenderer(); TestRendererAct = require('jest-react').act; - BridgeContext = require('react-devtools-shared/src/devtools/views/context') - .BridgeContext; - InspectedElementContext = require('react-devtools-shared/src/devtools/views/Components/InspectedElementContext') - .InspectedElementContext; - InspectedElementContextController = require('react-devtools-shared/src/devtools/views/Components/InspectedElementContext') - .InspectedElementContextController; - SettingsContextController = require('react-devtools-shared/src/devtools/views/Settings/SettingsContext') - .SettingsContextController; - StoreContext = require('react-devtools-shared/src/devtools/views/context') - .StoreContext; - TreeContextController = require('react-devtools-shared/src/devtools/views/Components/TreeContext') - .TreeContextController; + BridgeContext = + require('react-devtools-shared/src/devtools/views/context').BridgeContext; + InspectedElementContext = + require('react-devtools-shared/src/devtools/views/Components/InspectedElementContext').InspectedElementContext; + InspectedElementContextController = + require('react-devtools-shared/src/devtools/views/Components/InspectedElementContext').InspectedElementContextController; + SettingsContextController = + require('react-devtools-shared/src/devtools/views/Settings/SettingsContext').SettingsContextController; + StoreContext = + require('react-devtools-shared/src/devtools/views/context').StoreContext; + TreeContextController = + require('react-devtools-shared/src/devtools/views/Components/TreeContext').TreeContextController; // Used by inspectElementAtIndex() helper function utils.act(() => { @@ -616,8 +616,8 @@ describe('InspectedElement', () => { const instance = new Class(); const proxyInstance = new Proxy(() => {}, { - get: function(_, name) { - return function() { + get: function (_, name) { + return function () { 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); await inspectElementAtIndex(0, () => { @@ -1864,7 +1865,8 @@ describe('InspectedElement', () => { const id = ((store.getElementIDAtIndex(0): any): number); - let copyPath: CopyInspectedElementPath = ((null: any): CopyInspectedElementPath); + let copyPath: CopyInspectedElementPath = + ((null: any): CopyInspectedElementPath); await inspectElementAtIndex(0, () => { copyPath = (path: Array) => { diff --git a/packages/react-devtools-shared/src/__tests__/ownersListContext-test.js b/packages/react-devtools-shared/src/__tests__/ownersListContext-test.js index b9b7c56c88fba..dfdea1c21a1f1 100644 --- a/packages/react-devtools-shared/src/__tests__/ownersListContext-test.js +++ b/packages/react-devtools-shared/src/__tests__/ownersListContext-test.js @@ -39,16 +39,16 @@ describe('OwnersListContext', () => { React = require('react'); TestRenderer = utils.requireTestRenderer(); - BridgeContext = require('react-devtools-shared/src/devtools/views/context') - .BridgeContext; - OwnersListContext = require('react-devtools-shared/src/devtools/views/Components/OwnersListContext') - .OwnersListContext; - OwnersListContextController = require('react-devtools-shared/src/devtools/views/Components/OwnersListContext') - .OwnersListContextController; - StoreContext = require('react-devtools-shared/src/devtools/views/context') - .StoreContext; - TreeContextController = require('react-devtools-shared/src/devtools/views/Components/TreeContext') - .TreeContextController; + BridgeContext = + require('react-devtools-shared/src/devtools/views/context').BridgeContext; + OwnersListContext = + require('react-devtools-shared/src/devtools/views/Components/OwnersListContext').OwnersListContext; + OwnersListContextController = + require('react-devtools-shared/src/devtools/views/Components/OwnersListContext').OwnersListContextController; + StoreContext = + require('react-devtools-shared/src/devtools/views/context').StoreContext; + TreeContextController = + require('react-devtools-shared/src/devtools/views/Components/TreeContext').TreeContextController; }); const Contexts = ({children, defaultOwnerID = null}) => ( diff --git a/packages/react-devtools-shared/src/__tests__/preprocessData-test.js b/packages/react-devtools-shared/src/__tests__/preprocessData-test.js index 218783657bc81..282b33eba59ed 100644 --- a/packages/react-devtools-shared/src/__tests__/preprocessData-test.js +++ b/packages/react-devtools-shared/src/__tests__/preprocessData-test.js @@ -82,8 +82,8 @@ describe('Timeline profiler', () => { ReactDOMClient = require('react-dom/client'); Scheduler = require('scheduler'); - setPerformanceMock = require('react-devtools-shared/src/backend/profilingHooks') - .setPerformanceMock_ONLY_FOR_TESTING; + setPerformanceMock = + require('react-devtools-shared/src/backend/profilingHooks').setPerformanceMock_ONLY_FOR_TESTING; setPerformanceMock(createUserTimingPolyfill()); const store = global.store; @@ -105,8 +105,8 @@ describe('Timeline profiler', () => { let getLanesFromTransportDecimalBitmask; beforeEach(() => { - getLanesFromTransportDecimalBitmask = require('react-devtools-timeline/src/import-worker/preprocessData') - .getLanesFromTransportDecimalBitmask; + getLanesFromTransportDecimalBitmask = + require('react-devtools-timeline/src/import-worker/preprocessData').getLanesFromTransportDecimalBitmask; }); // @reactVersion >= 18.0 @@ -115,11 +115,7 @@ describe('Timeline profiler', () => { expect(getLanesFromTransportDecimalBitmask('512')).toEqual([9]); expect(getLanesFromTransportDecimalBitmask('3')).toEqual([0, 1]); expect(getLanesFromTransportDecimalBitmask('1234')).toEqual([ - 1, - 4, - 6, - 7, - 10, + 1, 4, 6, 7, 10, ]); // 2 + 16 + 64 + 128 + 1024 expect( getLanesFromTransportDecimalBitmask('1073741824'), // 0b1000000000000000000000000000000 @@ -139,8 +135,8 @@ describe('Timeline profiler', () => { // @reactVersion >= 18.0 it('should ignore lanes outside REACT_TOTAL_NUM_LANES', () => { - const REACT_TOTAL_NUM_LANES = require('react-devtools-timeline/src/constants') - .REACT_TOTAL_NUM_LANES; + const 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. expect(REACT_TOTAL_NUM_LANES).toBe(31); @@ -157,8 +153,8 @@ describe('Timeline profiler', () => { let preprocessData; beforeEach(() => { - preprocessData = require('react-devtools-timeline/src/import-worker/preprocessData') - .default; + preprocessData = + require('react-devtools-timeline/src/import-worker/preprocessData').default; }); // These should be dynamic to mimic a real profile, @@ -177,8 +173,8 @@ describe('Timeline profiler', () => { } function createProfilerVersionEntry() { - const SCHEDULING_PROFILER_VERSION = require('react-devtools-timeline/src/constants') - .SCHEDULING_PROFILER_VERSION; + const SCHEDULING_PROFILER_VERSION = + require('react-devtools-timeline/src/constants').SCHEDULING_PROFILER_VERSION; return createUserTimingEntry({ cat: 'blink.user_timing', name: '--profiler-version-' + SCHEDULING_PROFILER_VERSION, @@ -195,8 +191,7 @@ describe('Timeline profiler', () => { function createLaneLabelsEntry() { return createUserTimingEntry({ cat: 'blink.user_timing', - 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', + 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', }); } diff --git a/packages/react-devtools-shared/src/__tests__/profilerContext-test.js b/packages/react-devtools-shared/src/__tests__/profilerContext-test.js index 1d35e44b186a9..325e6e5075386 100644 --- a/packages/react-devtools-shared/src/__tests__/profilerContext-test.js +++ b/packages/react-devtools-shared/src/__tests__/profilerContext-test.js @@ -45,20 +45,20 @@ describe('ProfilerContext', () => { ReactDOM = require('react-dom'); TestRenderer = utils.requireTestRenderer(); - BridgeContext = require('react-devtools-shared/src/devtools/views/context') - .BridgeContext; - ProfilerContext = require('react-devtools-shared/src/devtools/views/Profiler/ProfilerContext') - .ProfilerContext; - ProfilerContextController = require('react-devtools-shared/src/devtools/views/Profiler/ProfilerContext') - .ProfilerContextController; - StoreContext = require('react-devtools-shared/src/devtools/views/context') - .StoreContext; - TreeContextController = require('react-devtools-shared/src/devtools/views/Components/TreeContext') - .TreeContextController; - TreeDispatcherContext = require('react-devtools-shared/src/devtools/views/Components/TreeContext') - .TreeDispatcherContext; - TreeStateContext = require('react-devtools-shared/src/devtools/views/Components/TreeContext') - .TreeStateContext; + BridgeContext = + require('react-devtools-shared/src/devtools/views/context').BridgeContext; + ProfilerContext = + require('react-devtools-shared/src/devtools/views/Profiler/ProfilerContext').ProfilerContext; + ProfilerContextController = + require('react-devtools-shared/src/devtools/views/Profiler/ProfilerContext').ProfilerContextController; + StoreContext = + require('react-devtools-shared/src/devtools/views/context').StoreContext; + TreeContextController = + require('react-devtools-shared/src/devtools/views/Components/TreeContext').TreeContextController; + TreeDispatcherContext = + require('react-devtools-shared/src/devtools/views/Components/TreeContext').TreeDispatcherContext; + TreeStateContext = + require('react-devtools-shared/src/devtools/views/Components/TreeContext').TreeStateContext; }); const Contexts = ({ diff --git a/packages/react-devtools-shared/src/__tests__/profilingCache-test.js b/packages/react-devtools-shared/src/__tests__/profilingCache-test.js index bca507212a8a7..dbee76a5ce3fd 100644 --- a/packages/react-devtools-shared/src/__tests__/profilingCache-test.js +++ b/packages/react-devtools-shared/src/__tests__/profilingCache-test.js @@ -182,14 +182,14 @@ describe('ProfilingCache', () => { const rootID = store.roots[0]; - const prevCommitData = store.profilerStore.getDataForRoot(rootID) - .commitData; + const prevCommitData = + store.profilerStore.getDataForRoot(rootID).commitData; expect(prevCommitData).toHaveLength(4); utils.exportImportHelper(bridge, store); - const nextCommitData = store.profilerStore.getDataForRoot(rootID) - .commitData; + const nextCommitData = + store.profilerStore.getDataForRoot(rootID).commitData; expect(nextCommitData).toHaveLength(4); nextCommitData.forEach((commitData, index) => { expect(commitData).toEqual(prevCommitData[index]); @@ -1094,8 +1094,10 @@ describe('ProfilingCache', () => { utils.act(() => setChildUnmounted(true)); utils.act(() => store.profilerStore.stopProfiling()); - const updaters = store.profilerStore.getCommitData(store.roots[0], 0) - .updaters; + const updaters = store.profilerStore.getCommitData( + store.roots[0], + 0, + ).updaters; expect(updaters.length).toEqual(1); expect(updaters[0].displayName).toEqual('App'); }); @@ -1129,8 +1131,10 @@ describe('ProfilingCache', () => { utils.act(() => setChildUnmounted(true)); utils.act(() => store.profilerStore.stopProfiling()); - const updaters = store.profilerStore.getCommitData(store.roots[0], 0) - .updaters; + const updaters = store.profilerStore.getCommitData( + store.roots[0], + 0, + ).updaters; expect(updaters.length).toEqual(1); expect(updaters[0].displayName).toEqual('App'); }); @@ -1159,8 +1163,10 @@ describe('ProfilingCache', () => { utils.act(() => setChildUnmounted(true)); utils.act(() => store.profilerStore.stopProfiling()); - const updaters = store.profilerStore.getCommitData(store.roots[0], 0) - .updaters; + const updaters = store.profilerStore.getCommitData( + store.roots[0], + 0, + ).updaters; expect(updaters.length).toEqual(1); expect(updaters[0].displayName).toEqual('App'); }); diff --git a/packages/react-devtools-shared/src/__tests__/store-test.js b/packages/react-devtools-shared/src/__tests__/store-test.js index 67797ae7fccef..b6af0aaff2921 100644 --- a/packages/react-devtools-shared/src/__tests__/store-test.js +++ b/packages/react-devtools-shared/src/__tests__/store-test.js @@ -1444,9 +1444,8 @@ describe('Store', () => { )); const MyComponent3 = (props, ref) => null; - const ForwardRefComponentWithCustomDisplayName = React.forwardRef( - MyComponent3, - ); + const ForwardRefComponentWithCustomDisplayName = + React.forwardRef(MyComponent3); ForwardRefComponentWithCustomDisplayName.displayName = 'Custom'; const MyComponent4 = (props, ref) => null; const MemoComponent = React.memo(MyComponent4); @@ -1467,9 +1466,8 @@ describe('Store', () => { ); MemoizedFakeHigherOrderComponentWithDisplayNameOverride.displayName = 'memoRefOverride'; - const ForwardRefFakeHigherOrderComponentWithDisplayNameOverride = React.forwardRef( - FakeHigherOrderComponent, - ); + const ForwardRefFakeHigherOrderComponentWithDisplayNameOverride = + React.forwardRef(FakeHigherOrderComponent); ForwardRefFakeHigherOrderComponentWithDisplayNameOverride.displayName = 'forwardRefOverride'; diff --git a/packages/react-devtools-shared/src/__tests__/treeContext-test.js b/packages/react-devtools-shared/src/__tests__/treeContext-test.js index bd80bd6fa0309..38b38a47e4df3 100644 --- a/packages/react-devtools-shared/src/__tests__/treeContext-test.js +++ b/packages/react-devtools-shared/src/__tests__/treeContext-test.js @@ -47,10 +47,10 @@ describe('TreeListContext', () => { ReactDOM = require('react-dom'); TestRenderer = utils.requireTestRenderer(); - BridgeContext = require('react-devtools-shared/src/devtools/views/context') - .BridgeContext; - StoreContext = require('react-devtools-shared/src/devtools/views/context') - .StoreContext; + BridgeContext = + require('react-devtools-shared/src/devtools/views/context').BridgeContext; + StoreContext = + require('react-devtools-shared/src/devtools/views/context').StoreContext; TreeContext = require('react-devtools-shared/src/devtools/views/Components/TreeContext'); }); diff --git a/packages/react-devtools-shared/src/__tests__/utils-test.js b/packages/react-devtools-shared/src/__tests__/utils-test.js index bd99dc71ef3b7..ecb2cac33eb2a 100644 --- a/packages/react-devtools-shared/src/__tests__/utils-test.js +++ b/packages/react-devtools-shared/src/__tests__/utils-test.js @@ -190,9 +190,9 @@ describe('utils', () => { // 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 - expect( - formatWithStyles(['%s %s', 'a', 'b', 'c'], 'color: gray'), - ).toEqual(['%c%s %s', 'color: gray', 'a', 'b', 'c']); + expect(formatWithStyles(['%s %s', 'a', 'b', 'c'], 'color: gray')).toEqual( + ['%c%s %s', 'color: gray', 'a', 'b', 'c'], + ); }); // @reactVersion >= 16.0 diff --git a/packages/react-devtools-shared/src/__tests__/utils.js b/packages/react-devtools-shared/src/__tests__/utils.js index e9bfdc685d7eb..59b92659b8f44 100644 --- a/packages/react-devtools-shared/src/__tests__/utils.js +++ b/packages/react-devtools-shared/src/__tests__/utils.js @@ -203,7 +203,8 @@ export function exportImportHelper(bridge: FrontendBridge, store: Store): void { expect(profilerStore.profilingData).not.toBeNull(); - const profilingDataFrontendInitial = ((profilerStore.profilingData: any): ProfilingDataFrontend); + const profilingDataFrontendInitial = + ((profilerStore.profilingData: any): ProfilingDataFrontend); expect(profilingDataFrontendInitial.imported).toBe(false); const profilingDataExport = prepareProfilingDataExport( @@ -301,7 +302,7 @@ export function normalizeCodeLocInfo(str) { // at Component (/path/filename.js:123:45) // React format: // 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 **)'; }); } diff --git a/packages/react-devtools-shared/src/backend/DevToolsComponentStackFrame.js b/packages/react-devtools-shared/src/backend/DevToolsComponentStackFrame.js index a5145d76ded5f..3473b230cde1b 100644 --- a/packages/react-devtools-shared/src/backend/DevToolsComponentStackFrame.js +++ b/packages/react-devtools-shared/src/backend/DevToolsComponentStackFrame.js @@ -95,12 +95,12 @@ export function describeNativeComponentFrame( // This should throw. if (construct) { // Something should be setting the props in the constructor. - const Fake = function() { + const Fake = function () { throw Error(); }; // $FlowFixMe Object.defineProperty(Fake.prototype, 'props', { - set: function() { + set: function () { // We use a throwing setter instead of frozen or non-writable props // because that won't throw in a non-strict mode function. throw Error(); diff --git a/packages/react-devtools-shared/src/backend/agent.js b/packages/react-devtools-shared/src/backend/agent.js index 0af2033cf955f..8f83437634e43 100644 --- a/packages/react-devtools-shared/src/backend/agent.js +++ b/packages/react-devtools-shared/src/backend/agent.js @@ -569,20 +569,19 @@ export default class Agent extends EventEmitter<{ } }; - reloadAndProfile: ( - recordChangeDescriptions: boolean, - ) => void = recordChangeDescriptions => { - sessionStorageSetItem(SESSION_STORAGE_RELOAD_AND_PROFILE_KEY, 'true'); - sessionStorageSetItem( - SESSION_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY, - recordChangeDescriptions ? 'true' : 'false', - ); + reloadAndProfile: (recordChangeDescriptions: boolean) => void = + recordChangeDescriptions => { + sessionStorageSetItem(SESSION_STORAGE_RELOAD_AND_PROFILE_KEY, 'true'); + sessionStorageSetItem( + SESSION_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY, + recordChangeDescriptions ? 'true' : 'false', + ); - // 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. - // The agent can't do this in a way that is renderer agnostic. - this._bridge.send('reloadAppForProfiling'); - }; + // 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. + // The agent can't do this in a way that is renderer agnostic. + this._bridge.send('reloadAppForProfiling'); + }; renamePath: RenamePathParams => void = ({ hookID, @@ -628,20 +627,19 @@ export default class Agent extends EventEmitter<{ } } - setTraceUpdatesEnabled: ( - traceUpdatesEnabled: boolean, - ) => void = traceUpdatesEnabled => { - this._traceUpdatesEnabled = traceUpdatesEnabled; + setTraceUpdatesEnabled: (traceUpdatesEnabled: boolean) => void = + traceUpdatesEnabled => { + this._traceUpdatesEnabled = traceUpdatesEnabled; - setTraceUpdatesEnabled(traceUpdatesEnabled); + setTraceUpdatesEnabled(traceUpdatesEnabled); - for (const rendererID in this._rendererInterfaces) { - const renderer = ((this._rendererInterfaces[ - (rendererID: any) - ]: any): RendererInterface); - renderer.setTraceUpdatesEnabled(traceUpdatesEnabled); - } - }; + for (const rendererID in this._rendererInterfaces) { + const renderer = ((this._rendererInterfaces[ + (rendererID: any) + ]: any): RendererInterface); + renderer.setTraceUpdatesEnabled(traceUpdatesEnabled); + } + }; syncSelectionFromNativeElementsPanel: () => void = () => { const target = window.__REACT_DEVTOOLS_GLOBAL_HOOK__.$0; @@ -656,19 +654,18 @@ export default class Agent extends EventEmitter<{ this.emit('shutdown'); }; - startProfiling: ( - recordChangeDescriptions: boolean, - ) => void = recordChangeDescriptions => { - this._recordChangeDescriptions = recordChangeDescriptions; - this._isProfiling = true; - for (const rendererID in this._rendererInterfaces) { - const renderer = ((this._rendererInterfaces[ - (rendererID: any) - ]: any): RendererInterface); - renderer.startProfiling(recordChangeDescriptions); - } - this._bridge.send('profilingStatus', this._isProfiling); - }; + startProfiling: (recordChangeDescriptions: boolean) => void = + recordChangeDescriptions => { + this._recordChangeDescriptions = recordChangeDescriptions; + this._isProfiling = true; + for (const rendererID in this._rendererInterfaces) { + const renderer = ((this._rendererInterfaces[ + (rendererID: any) + ]: any): RendererInterface); + renderer.startProfiling(recordChangeDescriptions); + } + this._bridge.send('profilingStatus', this._isProfiling); + }; stopProfiling: () => void = () => { this._isProfiling = false; @@ -726,16 +723,15 @@ export default class Agent extends EventEmitter<{ }); }; - updateComponentFilters: ( - componentFilters: Array, - ) => void = componentFilters => { - for (const rendererID in this._rendererInterfaces) { - const renderer = ((this._rendererInterfaces[ - (rendererID: any) - ]: any): RendererInterface); - renderer.updateComponentFilters(componentFilters); - } - }; + updateComponentFilters: (componentFilters: Array) => void = + componentFilters => { + for (const rendererID in this._rendererInterfaces) { + const renderer = ((this._rendererInterfaces[ + (rendererID: any) + ]: any): RendererInterface); + renderer.updateComponentFilters(componentFilters); + } + }; viewAttributeSource: CopyElementParams => void = ({id, path, rendererID}) => { const renderer = this._rendererInterfaces[rendererID]; diff --git a/packages/react-devtools-shared/src/backend/console.js b/packages/react-devtools-shared/src/backend/console.js index ac3d33306ecb4..2eb6f90c64164 100644 --- a/packages/react-devtools-shared/src/backend/console.js +++ b/packages/react-devtools-shared/src/backend/console.js @@ -354,8 +354,10 @@ export function patchForStrictMode() { } }; - overrideMethod.__REACT_DEVTOOLS_STRICT_MODE_ORIGINAL_METHOD__ = originalMethod; - originalMethod.__REACT_DEVTOOLS_STRICT_MODE_OVERRIDE_METHOD__ = overrideMethod; + overrideMethod.__REACT_DEVTOOLS_STRICT_MODE_ORIGINAL_METHOD__ = + originalMethod; + originalMethod.__REACT_DEVTOOLS_STRICT_MODE_OVERRIDE_METHOD__ = + overrideMethod; targetConsole[method] = overrideMethod; } catch (error) {} diff --git a/packages/react-devtools-shared/src/backend/legacy/renderer.js b/packages/react-devtools-shared/src/backend/legacy/renderer.js index 69a193ecb08fc..80619eb70e946 100644 --- a/packages/react-devtools-shared/src/backend/legacy/renderer.js +++ b/packages/react-devtools-shared/src/backend/legacy/renderer.js @@ -137,16 +137,13 @@ export function attach( global: Object, ): RendererInterface { const idToInternalInstanceMap: Map = new Map(); - const internalInstanceToIDMap: WeakMap< - InternalInstance, - number, - > = new WeakMap(); - const internalInstanceToRootIDMap: WeakMap< - InternalInstance, - number, - > = new WeakMap(); - - let getInternalIDForNative: GetFiberIDForNative = ((null: any): GetFiberIDForNative); + const internalInstanceToIDMap: WeakMap = + new WeakMap(); + const internalInstanceToRootIDMap: WeakMap = + new WeakMap(); + + let getInternalIDForNative: GetFiberIDForNative = + ((null: any): GetFiberIDForNative); let findNativeNodeForInternalID: (id: number) => ?NativeType; let getFiberForNative = (node: NativeType) => { // Not implemented. @@ -155,9 +152,8 @@ export function attach( if (renderer.ComponentTree) { getInternalIDForNative = (node, findNearestUnfilteredAncestor) => { - const internalInstance = renderer.ComponentTree.getClosestInstanceFromNode( - node, - ); + const internalInstance = + renderer.ComponentTree.getClosestInstanceFromNode(node); return internalInstanceToIDMap.get(internalInstance) || null; }; findNativeNodeForInternalID = (id: number) => { @@ -510,8 +506,8 @@ export function attach( const operations = new Array( // Identify which renderer this update is coming from. 2 + // [rendererID, rootFiberID] - // How big is the string table? - 1 + // [stringTableLength] + // How big is the string table? + 1 + // [stringTableLength] // Then goes the actual string table. pendingStringTableLength + // All unmounts are batched in a single message. diff --git a/packages/react-devtools-shared/src/backend/legacy/utils.js b/packages/react-devtools-shared/src/backend/legacy/utils.js index 91dc1ff3798fe..d828133e6bd88 100644 --- a/packages/react-devtools-shared/src/backend/legacy/utils.js +++ b/packages/react-devtools-shared/src/backend/legacy/utils.js @@ -12,7 +12,7 @@ import type {InternalInstance} from './renderer'; export function decorate(object: Object, attr: string, fn: Function): Function { const old = object[attr]; // $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 old; diff --git a/packages/react-devtools-shared/src/backend/profilingHooks.js b/packages/react-devtools-shared/src/backend/profilingHooks.js index 7f7c766fc45e8..e68f60450af44 100644 --- a/packages/react-devtools-shared/src/backend/profilingHooks.js +++ b/packages/react-devtools-shared/src/backend/profilingHooks.js @@ -54,11 +54,11 @@ if (supportsUserTiming) { const CHECK_V3_MARK = '__v3'; const markOptions = ({}: {startTime?: number}); Object.defineProperty(markOptions, 'startTime', { - get: function() { + get: function () { supportsUserTimingV3 = true; return 0; }, - set: function() {}, + set: function () {}, }); try { @@ -237,10 +237,8 @@ export function createProfilingHooks({ currentReactMeasuresStack.push(reactMeasure); if (currentTimelineData) { - const { - batchUIDToMeasuresMap, - laneToReactMeasureMap, - } = currentTimelineData; + const {batchUIDToMeasuresMap, laneToReactMeasureMap} = + currentTimelineData; let reactMeasures = batchUIDToMeasuresMap.get(currentBatchUID); if (reactMeasures != null) { diff --git a/packages/react-devtools-shared/src/backend/renderer.js b/packages/react-devtools-shared/src/backend/renderer.js index 87a7b141d02ca..1028e35726cad 100644 --- a/packages/react-devtools-shared/src/backend/renderer.js +++ b/packages/react-devtools-shared/src/backend/renderer.js @@ -154,9 +154,7 @@ const getCurrentTime = ? () => performance.now() : () => Date.now(); -export function getInternalReactConstants( - version: string, -): { +export function getInternalReactConstants(version: string): { getDisplayNameForFiber: getDisplayNameForFiberType, getTypeSymbol: getTypeSymbolType, ReactPriorityLevels: ReactPriorityLevelsType, @@ -843,12 +841,7 @@ export function attach( 'color: purple;', 'color: black;', ); - console.log( - new Error().stack - .split('\n') - .slice(1) - .join('\n'), - ); + console.log(new Error().stack.split('\n').slice(1).join('\n')); console.groupEnd(); } }; @@ -1800,8 +1793,8 @@ export function attach( const operations = new Array( // Identify which renderer this update is coming from. 2 + // [rendererID, rootFiberID] - // How big is the string table? - 1 + // [stringTableLength] + // How big is the string table? + 1 + // [stringTableLength] // Then goes the actual string table. pendingStringTableLength + // 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. // Also remember whether to do the same for siblings. - const mightSiblingsBeOnTrackedPath = updateTrackedPathStateBeforeMount( - fiber, - ); + const mightSiblingsBeOnTrackedPath = + updateTrackedPathStateBeforeMount(fiber); const shouldIncludeInTree = !shouldFilterFiber(fiber); 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. // 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". - const metadata = ((currentCommitProfilingMetadata: any): CommitProfilingData); + const metadata = + ((currentCommitProfilingMetadata: any): CommitProfilingData); metadata.durations.push(id, actualDuration, selfDuration); metadata.maxActualDuration = Math.max( metadata.maxActualDuration, @@ -2633,13 +2626,13 @@ export function attach( function handlePostCommitFiberRoot(root: any) { if (isProfiling && rootSupportsProfiling(root)) { if (currentCommitProfilingMetadata !== null) { - const {effectDuration, passiveEffectDuration} = getEffectDurations( - root, - ); + const {effectDuration, passiveEffectDuration} = + getEffectDurations(root); // $FlowFixMe[incompatible-use] found when upgrading Flow currentCommitProfilingMetadata.effectDuration = effectDuration; // $FlowFixMe[incompatible-use] found when upgrading Flow - currentCommitProfilingMetadata.passiveEffectDuration = passiveEffectDuration; + currentCommitProfilingMetadata.passiveEffectDuration = + passiveEffectDuration; } } } @@ -2719,9 +2712,10 @@ export function attach( if (isProfiling && isProfilingSupported) { if (!shouldBailoutWithPendingOperations()) { - const commitProfilingMetadata = ((rootToCommitProfilingMetadataMap: any): CommitProfilingMetadataMap).get( - currentRootID, - ); + const commitProfilingMetadata = + ((rootToCommitProfilingMetadataMap: any): CommitProfilingMetadataMap).get( + currentRootID, + ); if (commitProfilingMetadata != null) { commitProfilingMetadata.push( @@ -3964,7 +3958,8 @@ export function attach( let isProfiling: boolean = false; let profilingStartTime: number = 0; let recordChangeDescriptions: boolean = false; - let rootToCommitProfilingMetadataMap: CommitProfilingMetadataMap | null = null; + let rootToCommitProfilingMetadataMap: CommitProfilingMetadataMap | null = + null; function getProfilingData(): ProfilingDataBackend { const dataForRoots: Array = []; diff --git a/packages/react-devtools-shared/src/backend/utils.js b/packages/react-devtools-shared/src/backend/utils.js index 37f83f3099806..be5bfa56a869a 100644 --- a/packages/react-devtools-shared/src/backend/utils.js +++ b/packages/react-devtools-shared/src/backend/utils.js @@ -119,9 +119,10 @@ export function copyWithSet( return updated; } -export function getEffectDurations( - root: Object, -): {effectDuration: any | null, passiveEffectDuration: any | null} { +export function getEffectDurations(root: Object): { + effectDuration: any | null, + passiveEffectDuration: any | null, +} { // Profiling durations are only available for certain builds. // If available, they'll be stored on the HostRoot. let effectDuration = null; diff --git a/packages/react-devtools-shared/src/backend/views/Highlighter/Overlay.js b/packages/react-devtools-shared/src/backend/views/Highlighter/Overlay.js index f19a335bf79d7..29f425cee614b 100644 --- a/packages/react-devtools-shared/src/backend/views/Highlighter/Overlay.js +++ b/packages/react-devtools-shared/src/backend/views/Highlighter/Overlay.js @@ -233,9 +233,8 @@ export default class Overlay { name = elements[0].nodeName.toLowerCase(); const node = elements[0]; - const rendererInterface = this.agent.getBestMatchingRendererInterface( - node, - ); + const rendererInterface = + this.agent.getBestMatchingRendererInterface(node); if (rendererInterface) { const id = rendererInterface.getFiberIDForNative(node, true); if (id) { diff --git a/packages/react-devtools-shared/src/backend/views/Highlighter/index.js b/packages/react-devtools-shared/src/backend/views/Highlighter/index.js index dada3978e2e3a..8b30c27b12153 100644 --- a/packages/react-devtools-shared/src/backend/views/Highlighter/index.js +++ b/packages/react-devtools-shared/src/backend/views/Highlighter/index.js @@ -56,7 +56,7 @@ export default function setupHighlighter( function stopInspectingNative() { hideOverlay(agent); removeListenersOnWindow(window); - iframesListeningTo.forEach(function(frame) { + iframesListeningTo.forEach(function (frame) { try { removeListenersOnWindow(frame.contentWindow); } catch (error) { diff --git a/packages/react-devtools-shared/src/backend/views/utils.js b/packages/react-devtools-shared/src/backend/views/utils.js index dc9f8f5e54b5a..47808a4b27b6b 100644 --- a/packages/react-devtools-shared/src/backend/views/utils.js +++ b/packages/react-devtools-shared/src/backend/views/utils.js @@ -108,9 +108,7 @@ export function getNestedBoundingClientRect( } } -export function getElementDimensions( - domElement: Element, -): { +export function getElementDimensions(domElement: Element): { borderBottom: number, borderLeft: number, borderRight: number, diff --git a/packages/react-devtools-shared/src/bridge.js b/packages/react-devtools-shared/src/bridge.js index 19549e1b0dbe2..cc70ba6785246 100644 --- a/packages/react-devtools-shared/src/bridge.js +++ b/packages/react-devtools-shared/src/bridge.js @@ -340,9 +340,9 @@ class Bridge< // Disable the API inherited from EventEmitter that can add more listeners and send more messages. // $FlowFixMe This property is not writable. - this.addListener = function() {}; + this.addListener = function () {}; // $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. // Unsubscribe this bridge incoming message listeners to be sure, and so they don't have to do that. diff --git a/packages/react-devtools-shared/src/devtools/ContextMenu/ContextMenu.js b/packages/react-devtools-shared/src/devtools/ContextMenu/ContextMenu.js index 3b4d2b6964965..afc7ada8d7aa5 100644 --- a/packages/react-devtools-shared/src/devtools/ContextMenu/ContextMenu.js +++ b/packages/react-devtools-shared/src/devtools/ContextMenu/ContextMenu.js @@ -54,9 +54,8 @@ type Props = { }; export default function ContextMenu({children, id}: Props): React.Node { - const {hideMenu, registerMenu} = useContext( - RegistryContext, - ); + const {hideMenu, registerMenu} = + useContext(RegistryContext); const [state, setState] = useState(HIDDEN_STATE); diff --git a/packages/react-devtools-shared/src/devtools/ContextMenu/Contexts.js b/packages/react-devtools-shared/src/devtools/ContextMenu/Contexts.js index 4a7fd1b4e2fb1..9d8b49e7d9250 100644 --- a/packages/react-devtools-shared/src/devtools/ContextMenu/Contexts.js +++ b/packages/react-devtools-shared/src/devtools/ContextMenu/Contexts.js @@ -83,10 +83,9 @@ export type RegistryContextType = { registerMenu: typeof registerMenu, }; -export const RegistryContext: ReactContext = createContext( - { +export const RegistryContext: ReactContext = + createContext({ hideMenu, showMenu, registerMenu, - }, -); + }); diff --git a/packages/react-devtools-shared/src/devtools/ProfilerStore.js b/packages/react-devtools-shared/src/devtools/ProfilerStore.js index 5de36bfb08106..0f9caaabc5a14 100644 --- a/packages/react-devtools-shared/src/devtools/ProfilerStore.js +++ b/packages/react-devtools-shared/src/devtools/ProfilerStore.js @@ -249,37 +249,36 @@ export default class ProfilerStore extends EventEmitter<{ } }; - onBridgeProfilingData: ( - dataBackend: ProfilingDataBackend, - ) => void = dataBackend => { - if (this._isProfiling) { - // This should never happen, but if it does- ignore previous profiling data. - return; - } + onBridgeProfilingData: (dataBackend: ProfilingDataBackend) => void = + dataBackend => { + if (this._isProfiling) { + // This should never happen, but if it does- ignore previous profiling data. + return; + } - const {rendererID} = dataBackend; + const {rendererID} = dataBackend; - if (!this._rendererQueue.has(rendererID)) { - throw Error( - `Unexpected profiling data update from renderer "${rendererID}"`, - ); - } + if (!this._rendererQueue.has(rendererID)) { + throw Error( + `Unexpected profiling data update from renderer "${rendererID}"`, + ); + } - this._dataBackends.push(dataBackend); - this._rendererQueue.delete(rendererID); + this._dataBackends.push(dataBackend); + this._rendererQueue.delete(rendererID); - if (this._rendererQueue.size === 0) { - this._dataFrontend = prepareProfilingDataFrontendFromBackendAndStore( - this._dataBackends, - this._inProgressOperationsByRootID, - this._initialSnapshotsByRootID, - ); + if (this._rendererQueue.size === 0) { + this._dataFrontend = prepareProfilingDataFrontendFromBackendAndStore( + this._dataBackends, + this._inProgressOperationsByRootID, + this._initialSnapshotsByRootID, + ); - this._dataBackends.splice(0); + this._dataBackends.splice(0); - this.emit('isProcessingData'); - } - }; + this.emit('isProcessingData'); + } + }; onBridgeShutdown: () => void = () => { this._bridge.removeListener('operations', this.onBridgeOperations); diff --git a/packages/react-devtools-shared/src/devtools/store.js b/packages/react-devtools-shared/src/devtools/store.js index fd9264eed5a2b..93251b839f81f 100644 --- a/packages/react-devtools-shared/src/devtools/store.js +++ b/packages/react-devtools-shared/src/devtools/store.js @@ -117,10 +117,8 @@ export default class Store extends EventEmitter<{ _componentFilters: Array; // Map of ID to number of recorded error and warning message IDs. - _errorsAndWarnings: Map< - number, - {errorCount: number, warningCount: number}, - > = new Map(); + _errorsAndWarnings: Map = + new Map(); // At least one of the injected renderers contains (DEV only) owner metadata. _hasOwnerMetadata: boolean = false; @@ -584,9 +582,10 @@ export default class Store extends EventEmitter<{ } } - getErrorAndWarningCountForElementID( - id: number, - ): {errorCount: number, warningCount: number} { + getErrorAndWarningCountForElementID(id: number): { + errorCount: number, + warningCount: number, + } { return this._errorsAndWarnings.get(id) || {errorCount: 0, warningCount: 0}; } @@ -1029,10 +1028,8 @@ export default class Store extends EventEmitter<{ ): any): Element); parentElement.children.push(id); - const [ - displayNameWithoutHOCs, - hocDisplayNames, - ] = separateDisplayNameAndHOCs(displayName, type); + const [displayNameWithoutHOCs, hocDisplayNames] = + separateDisplayNameAndHOCs(displayName, type); const element: Element = { children: [], @@ -1280,8 +1277,8 @@ export default class Store extends EventEmitter<{ if (haveRootsChanged) { const prevRootSupportsProfiling = this._rootSupportsBasicProfiling; - const prevRootSupportsTimelineProfiling = this - ._rootSupportsTimelineProfiling; + const prevRootSupportsTimelineProfiling = + this._rootSupportsTimelineProfiling; this._hasOwnerMetadata = false; this._rootSupportsBasicProfiling = false; @@ -1399,22 +1396,21 @@ export default class Store extends EventEmitter<{ this.emit('backendVersion'); }; - onBridgeProtocol: ( - bridgeProtocol: BridgeProtocol, - ) => void = bridgeProtocol => { - if (this._onBridgeProtocolTimeoutID !== null) { - clearTimeout(this._onBridgeProtocolTimeoutID); - this._onBridgeProtocolTimeoutID = null; - } + onBridgeProtocol: (bridgeProtocol: BridgeProtocol) => void = + bridgeProtocol => { + if (this._onBridgeProtocolTimeoutID !== null) { + clearTimeout(this._onBridgeProtocolTimeoutID); + this._onBridgeProtocolTimeoutID = null; + } - this._bridgeProtocol = bridgeProtocol; + this._bridgeProtocol = bridgeProtocol; - if (bridgeProtocol.version !== currentBridgeProtocol.version) { - // Technically newer versions of the frontend can, at least for now, - // gracefully handle older versions of the backend protocol. - // So for now we don't need to display the unsupported dialog. - } - }; + if (bridgeProtocol.version !== currentBridgeProtocol.version) { + // Technically newer versions of the frontend can, at least for now, + // gracefully handle older versions of the backend protocol. + // So for now we don't need to display the unsupported dialog. + } + }; onBridgeProtocolTimeout: () => void = () => { this._onBridgeProtocolTimeoutID = null; diff --git a/packages/react-devtools-shared/src/devtools/utils.js b/packages/react-devtools-shared/src/devtools/utils.js index 304483fd03f7f..d1aa778d19847 100644 --- a/packages/react-devtools-shared/src/devtools/utils.js +++ b/packages/react-devtools-shared/src/devtools/utils.js @@ -40,8 +40,9 @@ export function printElement( suffix = ` (${element.isCollapsed ? 1 : element.weight})`; } - return `${' '.repeat(element.depth + 1)}${prefix} <${element.displayName || - 'null'}${key}>${hocs}${suffix}`; + return `${' '.repeat(element.depth + 1)}${prefix} <${ + element.displayName || 'null' + }${key}>${hocs}${suffix}`; } export function printOwnersList( @@ -70,10 +71,8 @@ export function printStore( } function printErrorsAndWarnings(element: Element): string { - const { - errorCount, - warningCount, - } = store.getErrorAndWarningCountForElementID(element.id); + const {errorCount, warningCount} = + store.getErrorAndWarningCountForElementID(element.id); if (errorCount === 0 && warningCount === 0) { return ''; } diff --git a/packages/react-devtools-shared/src/devtools/views/Components/Element.js b/packages/react-devtools-shared/src/devtools/views/Components/Element.js index c43164b511039..0cbf7e06e0e63 100644 --- a/packages/react-devtools-shared/src/devtools/views/Components/Element.js +++ b/packages/react-devtools-shared/src/devtools/views/Components/Element.js @@ -34,9 +34,8 @@ type Props = { export default function Element({data, index, style}: Props): React.Node { const store = useContext(StoreContext); - const {ownerFlatTree, ownerID, selectedElementID} = useContext( - TreeStateContext, - ); + const {ownerFlatTree, ownerID, selectedElementID} = + useContext(TreeStateContext); const dispatch = useContext(TreeDispatcherContext); const {showInlineWarningsAndErrors} = React.useContext(SettingsContext); diff --git a/packages/react-devtools-shared/src/devtools/views/Components/FetchFileWithCachingContext.js b/packages/react-devtools-shared/src/devtools/views/Components/FetchFileWithCachingContext.js index c9fd7dc66a8f7..6bbcf0cd40911 100644 --- a/packages/react-devtools-shared/src/devtools/views/Components/FetchFileWithCachingContext.js +++ b/packages/react-devtools-shared/src/devtools/views/Components/FetchFileWithCachingContext.js @@ -14,9 +14,8 @@ import {createContext} from 'react'; export type FetchFileWithCaching = (url: string) => Promise; export type Context = FetchFileWithCaching | null; -const FetchFileWithCachingContext: ReactContext = createContext( - null, -); +const FetchFileWithCachingContext: ReactContext = + createContext(null); FetchFileWithCachingContext.displayName = 'FetchFileWithCachingContext'; export default FetchFileWithCachingContext; diff --git a/packages/react-devtools-shared/src/devtools/views/Components/HookNamesModuleLoaderContext.js b/packages/react-devtools-shared/src/devtools/views/Components/HookNamesModuleLoaderContext.js index 21e8b35afbe3b..63586ad7762fb 100644 --- a/packages/react-devtools-shared/src/devtools/views/Components/HookNamesModuleLoaderContext.js +++ b/packages/react-devtools-shared/src/devtools/views/Components/HookNamesModuleLoaderContext.js @@ -14,13 +14,13 @@ import type {Thenable} from 'shared/ReactTypes'; import {createContext} from 'react'; import typeof * as ParseHookNamesModule from 'react-devtools-shared/src/hooks/parseHookNames'; -export type HookNamesModuleLoaderFunction = () => Thenable; +export type HookNamesModuleLoaderFunction = + () => Thenable; export type Context = HookNamesModuleLoaderFunction | null; // TODO (Webpack 5) Hopefully we can remove this context entirely once the Webpack 5 upgrade is completed. -const HookNamesModuleLoaderContext: ReactContext = createContext( - null, -); +const HookNamesModuleLoaderContext: ReactContext = + createContext(null); HookNamesModuleLoaderContext.displayName = 'HookNamesModuleLoaderContext'; export default HookNamesModuleLoaderContext; diff --git a/packages/react-devtools-shared/src/devtools/views/Components/InspectedElement.js b/packages/react-devtools-shared/src/devtools/views/Components/InspectedElement.js index d2c7419769303..bae0f8a11732c 100644 --- a/packages/react-devtools-shared/src/devtools/views/Components/InspectedElement.js +++ b/packages/react-devtools-shared/src/devtools/views/Components/InspectedElement.js @@ -48,12 +48,8 @@ export default function InspectedElementWrapper(_: Props): React.Node { } = useContext(OptionsContext); const {dispatch: modalDialogDispatch} = useContext(ModalDialogContext); - const { - hookNames, - inspectedElement, - parseHookNames, - toggleParseHookNames, - } = useContext(InspectedElementContext); + const {hookNames, inspectedElement, parseHookNames, toggleParseHookNames} = + useContext(InspectedElementContext); const element = inspectedElementID !== null diff --git a/packages/react-devtools-shared/src/devtools/views/Components/InspectedElementContext.js b/packages/react-devtools-shared/src/devtools/views/Components/InspectedElementContext.js index a5c63953c1801..19c950f96ad33 100644 --- a/packages/react-devtools-shared/src/devtools/views/Components/InspectedElementContext.js +++ b/packages/react-devtools-shared/src/devtools/views/Components/InspectedElementContext.js @@ -57,9 +57,8 @@ type Context = { toggleParseHookNames: ToggleParseHookNames, }; -export const InspectedElementContext: ReactContext = createContext( - ((null: any): Context), -); +export const InspectedElementContext: ReactContext = + createContext(((null: any): Context)); const POLL_INTERVAL = 1000; @@ -134,10 +133,8 @@ export function InspectedElementContextController({ if (parseHookNames || alreadyLoadedHookNames) { const hookNamesModule = loadModule(hookNamesModuleLoader); if (hookNamesModule !== null) { - const { - parseHookNames: loadHookNamesFunction, - purgeCachedMetadata, - } = hookNamesModule; + const {parseHookNames: loadHookNamesFunction, purgeCachedMetadata} = + hookNamesModule; purgeCachedMetadataRef.current = purgeCachedMetadata; @@ -159,12 +156,13 @@ export function InspectedElementContextController({ } } - const toggleParseHookNames: ToggleParseHookNames = useCallback(() => { - startTransition(() => { - setParseHookNames(value => !value); - refresh(); - }); - }, [setParseHookNames]); + const toggleParseHookNames: ToggleParseHookNames = + useCallback(() => { + startTransition(() => { + setParseHookNames(value => !value); + refresh(); + }); + }, [setParseHookNames]); const inspectPaths: InspectPathFunction = useCallback( (path: Path) => { diff --git a/packages/react-devtools-shared/src/devtools/views/Components/InspectedElementErrorsAndWarningsTree.js b/packages/react-devtools-shared/src/devtools/views/Components/InspectedElementErrorsAndWarningsTree.js index fca55c0146728..c5b71122d629a 100644 --- a/packages/react-devtools-shared/src/devtools/views/Components/InspectedElementErrorsAndWarningsTree.js +++ b/packages/react-devtools-shared/src/devtools/views/Components/InspectedElementErrorsAndWarningsTree.js @@ -40,10 +40,8 @@ export default function InspectedElementErrorsAndWarningsTree({ }: Props): React.Node { const refresh = useCacheRefresh(); - const [ - isErrorsTransitionPending, - startClearErrorsTransition, - ] = useTransition(); + const [isErrorsTransitionPending, startClearErrorsTransition] = + useTransition(); const clearErrorsForInspectedElement = () => { const {id} = inspectedElement; const rendererID = store.getRendererIDForElement(id); @@ -59,10 +57,8 @@ export default function InspectedElementErrorsAndWarningsTree({ } }; - const [ - isWarningsTransitionPending, - startClearWarningsTransition, - ] = useTransition(); + const [isWarningsTransitionPending, startClearWarningsTransition] = + useTransition(); const clearWarningsForInspectedElement = () => { const {id} = inspectedElement; const rendererID = store.getRendererIDForElement(id); diff --git a/packages/react-devtools-shared/src/devtools/views/Components/InspectedElementHooksTree.js b/packages/react-devtools-shared/src/devtools/views/Components/InspectedElementHooksTree.js index 6744cf4bc6477..61260d6d05d38 100644 --- a/packages/react-devtools-shared/src/devtools/views/Components/InspectedElementHooksTree.js +++ b/packages/react-devtools-shared/src/devtools/views/Components/InspectedElementHooksTree.js @@ -59,9 +59,8 @@ export function InspectedElementHooksTree({ // Changing parseHookNames is done in a transition, because it suspends. // This value is done outside of the transition, so the UI toggle feels responsive. - const [parseHookNamesOptimistic, setParseHookNamesOptimistic] = useState( - parseHookNames, - ); + const [parseHookNamesOptimistic, setParseHookNamesOptimistic] = + useState(parseHookNames); const handleChange = () => { setParseHookNamesOptimistic(!parseHookNames); toggleParseHookNames(); @@ -168,11 +167,8 @@ function HookView({ inspectedElement, path, }: HookViewProps) { - const { - canEditHooks, - canEditHooksAndDeletePaths, - canEditHooksAndRenamePaths, - } = inspectedElement; + const {canEditHooks, canEditHooksAndDeletePaths, canEditHooksAndRenamePaths} = + inspectedElement; const {id: hookID, isStateEditable, subHooks, value} = hook; const isReadOnly = hookID == null || !isStateEditable; diff --git a/packages/react-devtools-shared/src/devtools/views/Components/InspectedElementView.js b/packages/react-devtools-shared/src/devtools/views/Components/InspectedElementView.js index 38238bf84ed39..4804662f31007 100644 --- a/packages/react-devtools-shared/src/devtools/views/Components/InspectedElementView.js +++ b/packages/react-devtools-shared/src/devtools/views/Components/InspectedElementView.js @@ -61,13 +61,8 @@ export default function InspectedElementView({ toggleParseHookNames, }: Props): React.Node { const {id} = element; - const { - owners, - rendererPackageName, - rendererVersion, - rootType, - source, - } = inspectedElement; + const {owners, rendererPackageName, rendererVersion, rootType, source} = + inspectedElement; const bridge = useContext(BridgeContext); const store = useContext(StoreContext); @@ -297,10 +292,8 @@ function OwnerView({ type, }: OwnerViewProps) { const dispatch = useContext(TreeDispatcherContext); - const { - highlightNativeElement, - clearHighlightNativeElement, - } = useHighlightNativeElement(); + const {highlightNativeElement, clearHighlightNativeElement} = + useHighlightNativeElement(); const handleClick = useCallback(() => { logEvent({ diff --git a/packages/react-devtools-shared/src/devtools/views/Components/NativeStyleEditor/context.js b/packages/react-devtools-shared/src/devtools/views/Components/NativeStyleEditor/context.js index 3e76b05dd4ec0..62d3cbce6315c 100644 --- a/packages/react-devtools-shared/src/devtools/views/Components/NativeStyleEditor/context.js +++ b/packages/react-devtools-shared/src/devtools/views/Components/NativeStyleEditor/context.js @@ -55,33 +55,30 @@ type InProgressRequest = { }; const inProgressRequests: WeakMap = new WeakMap(); -const resource: Resource< - Element, - Element, - StyleAndLayoutFrontend, -> = createResource( - (element: Element) => { - const request = inProgressRequests.get(element); - if (request != null) { - return request.promise; - } +const resource: Resource = + createResource( + (element: Element) => { + const request = inProgressRequests.get(element); + if (request != null) { + return request.promise; + } - let resolveFn: - | ResolveFn - | (( - result: Promise | StyleAndLayoutFrontend, - ) => void) = ((null: any): ResolveFn); - const promise = new Promise(resolve => { - resolveFn = resolve; - }); - - inProgressRequests.set(element, {promise, resolveFn}); - - return promise; - }, - (element: Element) => element, - {useWeakMap: true}, -); + let resolveFn: + | ResolveFn + | (( + result: Promise | StyleAndLayoutFrontend, + ) => void) = ((null: any): ResolveFn); + const promise = new Promise(resolve => { + resolveFn = resolve; + }); + + inProgressRequests.set(element, {promise, resolveFn}); + + return promise; + }, + (element: Element) => element, + {useWeakMap: true}, + ); type Props = { 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). const {selectedElementID} = useContext(TreeStateContext); - const [ - currentStyleAndLayout, - setCurrentStyleAndLayout, - ] = useState(null); + const [currentStyleAndLayout, setCurrentStyleAndLayout] = + useState(null); // This effect handler invalidates the suspense cache and schedules rendering updates with React. useEffect(() => { diff --git a/packages/react-devtools-shared/src/devtools/views/Components/OwnersListContext.js b/packages/react-devtools-shared/src/devtools/views/Components/OwnersListContext.js index 50a58798849a2..36d818a26b540 100644 --- a/packages/react-devtools-shared/src/devtools/views/Components/OwnersListContext.js +++ b/packages/react-devtools-shared/src/devtools/views/Components/OwnersListContext.js @@ -102,10 +102,8 @@ function OwnersListContextController({children}: Props): React.Node { ownersList.owners === null ? null : ownersList.owners.map(owner => { - const [ - displayNameWithoutHOCs, - hocDisplayNames, - ] = separateDisplayNameAndHOCs(owner.displayName, owner.type); + const [displayNameWithoutHOCs, hocDisplayNames] = + separateDisplayNameAndHOCs(owner.displayName, owner.type); return { ...owner, diff --git a/packages/react-devtools-shared/src/devtools/views/Components/Tree.js b/packages/react-devtools-shared/src/devtools/views/Components/Tree.js index 7374e4d70ff32..57f01ca4d719c 100644 --- a/packages/react-devtools-shared/src/devtools/views/Components/Tree.js +++ b/packages/react-devtools-shared/src/devtools/views/Components/Tree.js @@ -64,13 +64,10 @@ export default function Tree(props: Props): React.Node { const bridge = useContext(BridgeContext); const store = useContext(StoreContext); const {hideSettings} = useContext(OptionsContext); - const [isNavigatingWithKeyboard, setIsNavigatingWithKeyboard] = useState( - false, - ); - const { - highlightNativeElement, - clearHighlightNativeElement, - } = useHighlightNativeElement(); + const [isNavigatingWithKeyboard, setIsNavigatingWithKeyboard] = + useState(false); + const {highlightNativeElement, clearHighlightNativeElement} = + useHighlightNativeElement(); const treeRef = useRef(null); const focusTargetRef = useRef(null); diff --git a/packages/react-devtools-shared/src/devtools/views/Components/TreeContext.js b/packages/react-devtools-shared/src/devtools/views/Components/TreeContext.js index f0655b41b8569..9233a2aea4cc2 100644 --- a/packages/react-devtools-shared/src/devtools/views/Components/TreeContext.js +++ b/packages/react-devtools-shared/src/devtools/views/Components/TreeContext.js @@ -150,14 +150,12 @@ type Action = export type DispatcherContext = (action: Action) => void; -const TreeStateContext: ReactContext = createContext( - ((null: any): StateContext), -); +const TreeStateContext: ReactContext = + createContext(((null: any): StateContext)); TreeStateContext.displayName = 'TreeStateContext'; -const TreeDispatcherContext: ReactContext = createContext( - ((null: any): DispatcherContext), -); +const TreeDispatcherContext: ReactContext = + createContext(((null: any): DispatcherContext)); TreeDispatcherContext.displayName = 'TreeDispatcherContext'; type State = { @@ -379,7 +377,8 @@ function reduceTreeState(store: Store, state: State, action: Action): State { } break; case 'SELECT_PREVIOUS_ELEMENT_WITH_ERROR_OR_WARNING_IN_TREE': { - const elementIndicesWithErrorsOrWarnings = store.getElementsWithErrorsAndWarnings(); + const elementIndicesWithErrorsOrWarnings = + store.getElementsWithErrorsAndWarnings(); if (elementIndicesWithErrorsOrWarnings.length === 0) { return state; } @@ -420,7 +419,8 @@ function reduceTreeState(store: Store, state: State, action: Action): State { break; } case 'SELECT_NEXT_ELEMENT_WITH_ERROR_OR_WARNING_IN_TREE': { - const elementIndicesWithErrorsOrWarnings = store.getElementsWithErrorsAndWarnings(); + const elementIndicesWithErrorsOrWarnings = + store.getElementsWithErrorsAndWarnings(); if (elementIndicesWithErrorsOrWarnings.length === 0) { return state; } @@ -522,10 +522,8 @@ function reduceSearchState(store: Store, state: State, action: Action): State { break; case 'HANDLE_STORE_MUTATION': if (searchText !== '') { - const [ - addedElementIDs, - removedElementIDs, - ] = (action: ACTION_HANDLE_STORE_MUTATION).payload; + const [addedElementIDs, removedElementIDs] = + (action: ACTION_HANDLE_STORE_MUTATION).payload; removedElementIDs.forEach((parentID, id) => { // 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, // so it's okay for the reducer to have an empty dependencies array. const reducer = useMemo( - () => (state: State, action: Action): State => { - const {type} = action; - switch (type) { - case 'GO_TO_NEXT_SEARCH_RESULT': - case 'GO_TO_PREVIOUS_SEARCH_RESULT': - case 'HANDLE_STORE_MUTATION': - case 'RESET_OWNER_STACK': - case 'SELECT_ELEMENT_AT_INDEX': - case 'SELECT_ELEMENT_BY_ID': - case 'SELECT_CHILD_ELEMENT_IN_TREE': - case 'SELECT_NEXT_ELEMENT_IN_TREE': - case 'SELECT_NEXT_ELEMENT_WITH_ERROR_OR_WARNING_IN_TREE': - case 'SELECT_NEXT_SIBLING_IN_TREE': - case 'SELECT_OWNER_LIST_NEXT_ELEMENT_IN_TREE': - case 'SELECT_OWNER_LIST_PREVIOUS_ELEMENT_IN_TREE': - case 'SELECT_PARENT_ELEMENT_IN_TREE': - case 'SELECT_PREVIOUS_ELEMENT_IN_TREE': - case 'SELECT_PREVIOUS_ELEMENT_WITH_ERROR_OR_WARNING_IN_TREE': - case 'SELECT_PREVIOUS_SIBLING_IN_TREE': - case 'SELECT_OWNER': - case 'UPDATE_INSPECTED_ELEMENT_ID': - case 'SET_SEARCH_TEXT': - state = reduceTreeState(store, state, action); - state = reduceSearchState(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. - // We'll know the correct index after the layout effect will toggle the tree, - // and the store tree is mutated to account for that. - if ( - state.selectedElementID !== null && - store.isInsideCollapsedSubTree(state.selectedElementID) - ) { - return { - ...state, - selectedElementIndex: null, - }; - } + () => + (state: State, action: Action): State => { + const {type} = action; + switch (type) { + case 'GO_TO_NEXT_SEARCH_RESULT': + case 'GO_TO_PREVIOUS_SEARCH_RESULT': + case 'HANDLE_STORE_MUTATION': + case 'RESET_OWNER_STACK': + case 'SELECT_ELEMENT_AT_INDEX': + case 'SELECT_ELEMENT_BY_ID': + case 'SELECT_CHILD_ELEMENT_IN_TREE': + case 'SELECT_NEXT_ELEMENT_IN_TREE': + case 'SELECT_NEXT_ELEMENT_WITH_ERROR_OR_WARNING_IN_TREE': + case 'SELECT_NEXT_SIBLING_IN_TREE': + case 'SELECT_OWNER_LIST_NEXT_ELEMENT_IN_TREE': + case 'SELECT_OWNER_LIST_PREVIOUS_ELEMENT_IN_TREE': + case 'SELECT_PARENT_ELEMENT_IN_TREE': + case 'SELECT_PREVIOUS_ELEMENT_IN_TREE': + case 'SELECT_PREVIOUS_ELEMENT_WITH_ERROR_OR_WARNING_IN_TREE': + case 'SELECT_PREVIOUS_SIBLING_IN_TREE': + case 'SELECT_OWNER': + case 'UPDATE_INSPECTED_ELEMENT_ID': + case 'SET_SEARCH_TEXT': + state = reduceTreeState(store, state, action); + state = reduceSearchState(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. + // We'll know the correct index after the layout effect will toggle the tree, + // and the store tree is mutated to account for that. + if ( + state.selectedElementID !== null && + store.isInsideCollapsedSubTree(state.selectedElementID) + ) { + return { + ...state, + selectedElementIndex: null, + }; + } - return state; - default: - throw new Error(`Unrecognized action "${type}"`); - } - }, + return state; + default: + throw new Error(`Unrecognized action "${type}"`); + } + }, [store], ); diff --git a/packages/react-devtools-shared/src/devtools/views/ErrorBoundary/ErrorBoundary.js b/packages/react-devtools-shared/src/devtools/views/ErrorBoundary/ErrorBoundary.js index 8e501137923e2..ffba7769bc756 100644 --- a/packages/react-devtools-shared/src/devtools/views/ErrorBoundary/ErrorBoundary.js +++ b/packages/react-devtools-shared/src/devtools/views/ErrorBoundary/ErrorBoundary.js @@ -56,9 +56,7 @@ const InitialState: State = { export default class ErrorBoundary extends Component { state: State = InitialState; - static getDerivedStateFromError( - error: any, - ): { + static getDerivedStateFromError(error: any): { callStack: string | null, errorMessage: string | null, hasError: boolean, @@ -84,10 +82,7 @@ export default class ErrorBoundary extends Component { typeof error === 'object' && error !== null && typeof error.stack === 'string' - ? error.stack - .split('\n') - .slice(1) - .join('\n') + ? error.stack.split('\n').slice(1).join('\n') : null; return { diff --git a/packages/react-devtools-shared/src/devtools/views/ErrorBoundary/cache.js b/packages/react-devtools-shared/src/devtools/views/ErrorBoundary/cache.js index 2a568815e4568..9890b6402f327 100644 --- a/packages/react-devtools-shared/src/devtools/views/ErrorBoundary/cache.js +++ b/packages/react-devtools-shared/src/devtools/views/ErrorBoundary/cache.js @@ -93,7 +93,8 @@ export function findGitHubIssue(errorMessage: string): GitHubIssue | null { } if (maybeItem) { - const resolvedRecord = ((newRecord: any): ResolvedRecord); + const resolvedRecord = + ((newRecord: any): ResolvedRecord); resolvedRecord.status = Resolved; resolvedRecord.value = maybeItem; } else { diff --git a/packages/react-devtools-shared/src/devtools/views/ModalDialog.js b/packages/react-devtools-shared/src/devtools/views/ModalDialog.js index cf927e055de71..542961b4c932b 100644 --- a/packages/react-devtools-shared/src/devtools/views/ModalDialog.js +++ b/packages/react-devtools-shared/src/devtools/views/ModalDialog.js @@ -56,9 +56,8 @@ type ModalDialogContextType = { dispatch: Dispatch, }; -const ModalDialogContext: ReactContext = createContext( - ((null: any): ModalDialogContextType), -); +const ModalDialogContext: ReactContext = + createContext(((null: any): ModalDialogContextType)); ModalDialogContext.displayName = 'ModalDialogContext'; function dialogReducer(state: State, action: Action) { diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/CommitFlamegraph.js b/packages/react-devtools-shared/src/devtools/views/Profiler/CommitFlamegraph.js index 424441f4df81c..f552964e0ca2e 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/CommitFlamegraph.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/CommitFlamegraph.js @@ -40,9 +40,8 @@ export type ItemData = { export default function CommitFlamegraphAutoSizer(_: {}): React.Node { const {profilerStore} = useContext(StoreContext); - const {rootID, selectedCommitIndex, selectFiber} = useContext( - ProfilerContext, - ); + const {rootID, selectedCommitIndex, selectFiber} = + useContext(ProfilerContext); const {profilingCache} = profilerStore; const deselectCurrentFiber = useCallback( @@ -98,16 +97,12 @@ type Props = { }; function CommitFlamegraph({chartData, commitTree, height, width}: Props) { - const [ - hoveredFiberData, - setHoveredFiberData, - ] = useState(null); + const [hoveredFiberData, setHoveredFiberData] = + useState(null); const {lineHeight} = useContext(SettingsContext); const {selectFiber, selectedFiberID} = useContext(ProfilerContext); - const { - highlightNativeElement, - clearHighlightNativeElement, - } = useHighlightNativeElement(); + const {highlightNativeElement, clearHighlightNativeElement} = + useHighlightNativeElement(); const selectedChartNodeIndex = useMemo(() => { if (selectedFiberID === null) { diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/CommitRanked.js b/packages/react-devtools-shared/src/devtools/views/Profiler/CommitRanked.js index ad890bae14231..ad72920477c79 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/CommitRanked.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/CommitRanked.js @@ -40,9 +40,8 @@ export type ItemData = { export default function CommitRankedAutoSizer(_: {}): React.Node { const {profilerStore} = useContext(StoreContext); - const {rootID, selectedCommitIndex, selectFiber} = useContext( - ProfilerContext, - ); + const {rootID, selectedCommitIndex, selectFiber} = + useContext(ProfilerContext); const {profilingCache} = profilerStore; const deselectCurrentFiber = useCallback( @@ -96,16 +95,12 @@ type Props = { }; function CommitRanked({chartData, commitTree, height, width}: Props) { - const [ - hoveredFiberData, - setHoveredFiberData, - ] = useState(null); + const [hoveredFiberData, setHoveredFiberData] = + useState(null); const {lineHeight} = useContext(SettingsContext); const {selectedFiberID, selectFiber} = useContext(ProfilerContext); - const { - highlightNativeElement, - clearHighlightNativeElement, - } = useHighlightNativeElement(); + const {highlightNativeElement, clearHighlightNativeElement} = + useHighlightNativeElement(); const selectedFiberIndex = useMemo( () => getNodeIndex(chartData, selectedFiberID), diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/FlamegraphChartBuilder.js b/packages/react-devtools-shared/src/devtools/views/Profiler/FlamegraphChartBuilder.js index ecd5078c7cad8..4b04e4118ac27 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/FlamegraphChartBuilder.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/FlamegraphChartBuilder.js @@ -71,13 +71,8 @@ export function getChartData({ throw Error(`Could not find node with id "${id}" in commit tree`); } - const { - children, - displayName, - hocDisplayNames, - key, - treeBaseDuration, - } = node; + const {children, displayName, hocDisplayNames, key, treeBaseDuration} = + node; const actualDuration = fiberActualDurations.get(id) || 0; const selfDuration = fiberSelfDurations.get(id) || 0; diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/HoveredFiberInfo.js b/packages/react-devtools-shared/src/devtools/views/Profiler/HoveredFiberInfo.js index a803690a06996..a5f565a01af1d 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/HoveredFiberInfo.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/HoveredFiberInfo.js @@ -44,10 +44,8 @@ export default function HoveredFiberInfo({fiberData}: Props): React.Node { for (i = 0; i < commitIndices.length; i++) { const commitIndex = commitIndices[i]; if (selectedCommitIndex === commitIndex) { - const { - fiberActualDurations, - fiberSelfDurations, - } = profilerStore.getCommitData(((rootID: any): number), commitIndex); + const {fiberActualDurations, fiberSelfDurations} = + profilerStore.getCommitData(((rootID: any): number), commitIndex); const actualDuration = fiberActualDurations.get(id) || 0; const selfDuration = fiberSelfDurations.get(id) || 0; diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/Profiler.js b/packages/react-devtools-shared/src/devtools/views/Profiler/Profiler.js index 5db5c11cc3850..5cac9fc6ef2b3 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/Profiler.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/Profiler.js @@ -50,9 +50,8 @@ function Profiler(_: {}) { supportsProfiling, } = useContext(ProfilerContext); - const {file: timelineTraceEventData, searchInputContainerRef} = useContext( - TimelineContext, - ); + const {file: timelineTraceEventData, searchInputContainerRef} = + useContext(TimelineContext); const {supportsTimeline} = useContext(StoreContext); diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/ProfilerContext.js b/packages/react-devtools-shared/src/devtools/views/Profiler/ProfilerContext.js index d91446b8acc74..f4ebc26a07259 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/ProfilerContext.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/ProfilerContext.js @@ -125,10 +125,8 @@ function ProfilerContextController({children}: Props): React.Node { supportsProfiling, } = useSubscription(subscription); - const [ - prevProfilingData, - setPrevProfilingData, - ] = useState(null); + const [prevProfilingData, setPrevProfilingData] = + useState(null); const [rootID, setRootID] = useState(null); const [selectedFiberID, selectFiberID] = useState(null); const [selectedFiberName, selectFiberName] = useState(null); @@ -179,9 +177,8 @@ function ProfilerContextController({children}: Props): React.Node { if (rootID === null || !dataForRoots.has(rootID)) { let selectedElementRootID = null; if (selectedElementID !== null) { - selectedElementRootID = store.getRootIDForElement( - selectedElementID, - ); + selectedElementRootID = + store.getRootIDForElement(selectedElementID); } if ( selectedElementRootID !== null && @@ -196,10 +193,8 @@ function ProfilerContextController({children}: Props): React.Node { }); } - const [ - isCommitFilterEnabled, - setIsCommitFilterEnabled, - ] = useLocalStorage('React::DevTools::isCommitFilterEnabled', false); + const [isCommitFilterEnabled, setIsCommitFilterEnabled] = + useLocalStorage('React::DevTools::isCommitFilterEnabled', false); const [minCommitDuration, setMinCommitDuration] = useLocalStorage( 'minCommitDuration', 0, @@ -228,9 +223,10 @@ function ProfilerContextController({children}: Props): React.Node { }); store.profilerStore.startProfiling(); }, [store, selectedTabID]); - const stopProfiling = useCallback(() => store.profilerStore.stopProfiling(), [ - store, - ]); + const stopProfiling = useCallback( + () => store.profilerStore.stopProfiling(), + [store], + ); if (isProfiling) { batchedUpdates(() => { diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/ProfilingImportExportButtons.js b/packages/react-devtools-shared/src/devtools/views/Profiler/ProfilingImportExportButtons.js index 9b2d27f78686c..6bb3e229fbd15 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/ProfilingImportExportButtons.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/ProfilingImportExportButtons.js @@ -96,9 +96,8 @@ export default function ProfilingImportExportButtons(): React.Node { try { const profilingDataExport = ((json: any): ProfilingDataExport); - profilerStore.profilingData = prepareProfilingDataFrontendFromExport( - profilingDataExport, - ); + profilerStore.profilingData = + prepareProfilingDataFrontendFromExport(profilingDataExport); } catch (error) { modalDialogDispatch({ id: 'ProfilingImportExportButtons', diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/RecordToggle.js b/packages/react-devtools-shared/src/devtools/views/Profiler/RecordToggle.js index 6e64a0ef53267..7e79df9e08146 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/RecordToggle.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/RecordToggle.js @@ -20,9 +20,8 @@ export type Props = { }; export default function RecordToggle({disabled}: Props): React.Node { - const {isProfiling, startProfiling, stopProfiling} = useContext( - ProfilerContext, - ); + const {isProfiling, startProfiling, stopProfiling} = + useContext(ProfilerContext); let className = styles.InactiveRecordToggle; if (disabled) { diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/ReloadAndProfileButton.js b/packages/react-devtools-shared/src/devtools/views/Profiler/ReloadAndProfileButton.js index e80e2c84a3024..90dba6f7d8359 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/ReloadAndProfileButton.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/ReloadAndProfileButton.js @@ -44,10 +44,8 @@ export default function ReloadAndProfileButton({ }), [store], ); - const { - recordChangeDescriptions, - supportsReloadAndProfile, - } = useSubscription(subscription); + const {recordChangeDescriptions, supportsReloadAndProfile} = + useSubscription(subscription); const reloadAndProfile = useCallback(() => { // TODO If we want to support reload-and-profile for e.g. React Native, diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/WhatChanged.js b/packages/react-devtools-shared/src/devtools/views/Profiler/WhatChanged.js index 52913e9005fde..71002cbea99d0 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/WhatChanged.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/WhatChanged.js @@ -63,14 +63,8 @@ export default function WhatChanged({fiberID}: Props): React.Node { return null; } - const { - context, - didHooksChange, - hooks, - isFirstMount, - props, - state, - } = changeDescription; + const {context, didHooksChange, hooks, isFirstMount, props, state} = + changeDescription; if (isFirstMount) { return ( diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/utils.js b/packages/react-devtools-shared/src/devtools/views/Profiler/utils.js index c0d2d65f64687..0738870c56ac9 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/utils.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/utils.js @@ -250,53 +250,54 @@ export function prepareProfilingDataFrontendFromExport( export function prepareProfilingDataExport( profilingDataFrontend: ProfilingDataFrontend, ): ProfilingDataExport { - const timelineData: Array = profilingDataFrontend.timelineData.map( - ({ - batchUIDToMeasuresMap, - componentMeasures, - duration, - flamechart, - internalModuleSourceToRanges, - laneToLabelMap, - laneToReactMeasureMap, - nativeEvents, - networkMeasures, - otherUserTimingMarks, - reactVersion, - schedulingEvents, - snapshots, - snapshotHeight, - startTime, - suspenseEvents, - thrownErrors, - }) => ({ - // Most of the data is safe to serialize as-is, - // but we need to convert the Maps to nested Arrays. - batchUIDToMeasuresKeyValueArray: Array.from( - batchUIDToMeasuresMap.entries(), - ), - componentMeasures: componentMeasures, - duration, - flamechart, - internalModuleSourceToRanges: Array.from( - internalModuleSourceToRanges.entries(), - ), - laneToLabelKeyValueArray: Array.from(laneToLabelMap.entries()), - laneToReactMeasureKeyValueArray: Array.from( - laneToReactMeasureMap.entries(), - ), - nativeEvents, - networkMeasures, - otherUserTimingMarks, - reactVersion, - schedulingEvents, - snapshots, - snapshotHeight, - startTime, - suspenseEvents, - thrownErrors, - }), - ); + const timelineData: Array = + profilingDataFrontend.timelineData.map( + ({ + batchUIDToMeasuresMap, + componentMeasures, + duration, + flamechart, + internalModuleSourceToRanges, + laneToLabelMap, + laneToReactMeasureMap, + nativeEvents, + networkMeasures, + otherUserTimingMarks, + reactVersion, + schedulingEvents, + snapshots, + snapshotHeight, + startTime, + suspenseEvents, + thrownErrors, + }) => ({ + // Most of the data is safe to serialize as-is, + // but we need to convert the Maps to nested Arrays. + batchUIDToMeasuresKeyValueArray: Array.from( + batchUIDToMeasuresMap.entries(), + ), + componentMeasures: componentMeasures, + duration, + flamechart, + internalModuleSourceToRanges: Array.from( + internalModuleSourceToRanges.entries(), + ), + laneToLabelKeyValueArray: Array.from(laneToLabelMap.entries()), + laneToReactMeasureKeyValueArray: Array.from( + laneToReactMeasureMap.entries(), + ), + nativeEvents, + networkMeasures, + otherUserTimingMarks, + reactVersion, + schedulingEvents, + snapshots, + snapshotHeight, + startTime, + suspenseEvents, + thrownErrors, + }), + ); const dataForRoots: Array = []; profilingDataFrontend.dataForRoots.forEach( @@ -373,15 +374,14 @@ export const formatPercentage = (percentage: number): number => export const formatTime = (timestamp: number): number => Math.round(Math.round(timestamp) / 100) / 10; -export const scale = ( - minValue: number, - maxValue: number, - minRange: number, - maxRange: number, -): ((value: number, fallbackValue: number) => number) => ( - value: number, - fallbackValue: number, -) => - maxValue - minValue === 0 - ? fallbackValue - : ((value - minValue) / (maxValue - minValue)) * (maxRange - minRange); +export const scale = + ( + minValue: number, + maxValue: number, + minRange: number, + maxRange: number, + ): ((value: number, fallbackValue: number) => number) => + (value: number, fallbackValue: number) => + maxValue - minValue === 0 + ? fallbackValue + : ((value - minValue) / (maxValue - minValue)) * (maxRange - minRange); diff --git a/packages/react-devtools-shared/src/devtools/views/Settings/SettingsContext.js b/packages/react-devtools-shared/src/devtools/views/Settings/SettingsContext.js index 4fed25258d3da..a9c601a3a186d 100644 --- a/packages/react-devtools-shared/src/devtools/views/Settings/SettingsContext.js +++ b/packages/react-devtools-shared/src/devtools/views/Settings/SettingsContext.js @@ -107,56 +107,44 @@ function SettingsContextController({ }: Props): React.Node { const bridge = useContext(BridgeContext); - const [ - displayDensity, - setDisplayDensity, - ] = useLocalStorageWithLog( - 'React::DevTools::displayDensity', - 'compact', - ); + const [displayDensity, setDisplayDensity] = + useLocalStorageWithLog( + 'React::DevTools::displayDensity', + 'compact', + ); const [theme, setTheme] = useLocalStorageWithLog( LOCAL_STORAGE_BROWSER_THEME, 'auto', ); - const [ - appendComponentStack, - setAppendComponentStack, - ] = useLocalStorageWithLog( - LOCAL_STORAGE_SHOULD_APPEND_COMPONENT_STACK_KEY, - true, - ); - const [ - breakOnConsoleErrors, - setBreakOnConsoleErrors, - ] = useLocalStorageWithLog( - LOCAL_STORAGE_SHOULD_BREAK_ON_CONSOLE_ERRORS, - false, - ); + const [appendComponentStack, setAppendComponentStack] = + useLocalStorageWithLog( + LOCAL_STORAGE_SHOULD_APPEND_COMPONENT_STACK_KEY, + true, + ); + const [breakOnConsoleErrors, setBreakOnConsoleErrors] = + useLocalStorageWithLog( + LOCAL_STORAGE_SHOULD_BREAK_ON_CONSOLE_ERRORS, + false, + ); const [parseHookNames, setParseHookNames] = useLocalStorageWithLog( LOCAL_STORAGE_PARSE_HOOK_NAMES_KEY, false, ); - const [ - hideConsoleLogsInStrictMode, - setHideConsoleLogsInStrictMode, - ] = useLocalStorageWithLog( - LOCAL_STORAGE_HIDE_CONSOLE_LOGS_IN_STRICT_MODE, - false, - ); - const [ - showInlineWarningsAndErrors, - setShowInlineWarningsAndErrors, - ] = useLocalStorageWithLog( - LOCAL_STORAGE_SHOW_INLINE_WARNINGS_AND_ERRORS_KEY, - true, - ); - const [ - traceUpdatesEnabled, - setTraceUpdatesEnabled, - ] = useLocalStorageWithLog( - LOCAL_STORAGE_TRACE_UPDATES_ENABLED_KEY, - false, - ); + const [hideConsoleLogsInStrictMode, setHideConsoleLogsInStrictMode] = + useLocalStorageWithLog( + LOCAL_STORAGE_HIDE_CONSOLE_LOGS_IN_STRICT_MODE, + false, + ); + const [showInlineWarningsAndErrors, setShowInlineWarningsAndErrors] = + useLocalStorageWithLog( + LOCAL_STORAGE_SHOW_INLINE_WARNINGS_AND_ERRORS_KEY, + true, + ); + const [traceUpdatesEnabled, setTraceUpdatesEnabled] = + useLocalStorageWithLog( + LOCAL_STORAGE_TRACE_UPDATES_ENABLED_KEY, + false, + ); const documentElements = useMemo(() => { const array: Array = [ diff --git a/packages/react-devtools-shared/src/devtools/views/Settings/SettingsModal.js b/packages/react-devtools-shared/src/devtools/views/Settings/SettingsModal.js index 0fa166ea669c5..ecaa80ea5ea5b 100644 --- a/packages/react-devtools-shared/src/devtools/views/Settings/SettingsModal.js +++ b/packages/react-devtools-shared/src/devtools/views/Settings/SettingsModal.js @@ -59,9 +59,10 @@ export default function SettingsModal(_: {}): React.Node { function SettingsModalImpl(_: {}) { const {setIsModalShowing} = useContext(SettingsModalContext); - const dismissModal = useCallback(() => setIsModalShowing(false), [ - setIsModalShowing, - ]); + const dismissModal = useCallback( + () => setIsModalShowing(false), + [setIsModalShowing], + ); const [selectedTabID, selectTab] = useLocalStorage( 'React::DevTools::selectedSettingsTabID', diff --git a/packages/react-devtools-shared/src/devtools/views/Settings/SettingsModalContext.js b/packages/react-devtools-shared/src/devtools/views/Settings/SettingsModalContext.js index 5eea2cc61a6b1..465d01ec3e4b7 100644 --- a/packages/react-devtools-shared/src/devtools/views/Settings/SettingsModalContext.js +++ b/packages/react-devtools-shared/src/devtools/views/Settings/SettingsModalContext.js @@ -33,10 +33,10 @@ function SettingsModalContextController({ }): React.Node { const [isModalShowing, setIsModalShowing] = useState(false); - const value = useMemo(() => ({isModalShowing, setIsModalShowing}), [ - isModalShowing, - setIsModalShowing, - ]); + const value = useMemo( + () => ({isModalShowing, setIsModalShowing}), + [isModalShowing, setIsModalShowing], + ); return ( diff --git a/packages/react-devtools-shared/src/devtools/views/Settings/SettingsModalContextToggle.js b/packages/react-devtools-shared/src/devtools/views/Settings/SettingsModalContextToggle.js index a37ef5fc5dfee..306f0715111ba 100644 --- a/packages/react-devtools-shared/src/devtools/views/Settings/SettingsModalContextToggle.js +++ b/packages/react-devtools-shared/src/devtools/views/Settings/SettingsModalContextToggle.js @@ -20,9 +20,10 @@ export default function SettingsModalContextToggle(): React.Node { const store = useContext(StoreContext); const {profilerStore} = store; - const showFilterModal = useCallback(() => setIsModalShowing(true), [ - setIsModalShowing, - ]); + const showFilterModal = useCallback( + () => setIsModalShowing(true), + [setIsModalShowing], + ); // Updating preferences while profiling is in progress could break things (e.g. filtering) // Explicitly disallow it for now. diff --git a/packages/react-devtools-shared/src/devtools/views/Toggle.js b/packages/react-devtools-shared/src/devtools/views/Toggle.js index 0bb5745613f15..2d42b42dacd22 100644 --- a/packages/react-devtools-shared/src/devtools/views/Toggle.js +++ b/packages/react-devtools-shared/src/devtools/views/Toggle.js @@ -42,10 +42,10 @@ export default function Toggle({ defaultClassName = styles.ToggleOff; } - const handleClick = useCallback(() => onChange(!isChecked), [ - isChecked, - onChange, - ]); + const handleClick = useCallback( + () => onChange(!isChecked), + [isChecked, onChange], + ); let toggle = (