Upgrade prettier (#26081)

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

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

View File

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

View File

@ -241,8 +241,9 @@ Comparing: ${baseSha}...${headSha}
## Critical size changes ## Critical size changes
Includes critical production bundles, as well as any change greater than ${CRITICAL_THRESHOLD * Includes critical production bundles, as well as any change greater than ${
100}%: CRITICAL_THRESHOLD * 100
}%:
${header} ${header}
${criticalResults.join('\n')} ${criticalResults.join('\n')}

View File

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

View File

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

View File

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

View File

@ -330,9 +330,7 @@ it('gives a helpful error when passing null, undefined, or boolean', () => {
const Null = null; const Null = null;
const True = true; const True = true;
const Div = 'div'; const Div = 'div';
expect( expect(() => void (<Undefined />)).toErrorDev(
() => void (<Undefined />)
).toErrorDev(
'Warning: React.jsx: type is invalid -- expected a string ' + 'Warning: React.jsx: type is invalid -- expected a string ' +
'(for built-in components) or a class/function (for composite ' + '(for built-in components) or a class/function (for composite ' +
'components) but got: undefined. You likely forgot to export your ' + 'components) but got: undefined. You likely forgot to export your ' +
@ -343,9 +341,7 @@ it('gives a helpful error when passing null, undefined, or boolean', () => {
: ''), : ''),
{withoutStack: true} {withoutStack: true}
); );
expect( expect(() => void (<Null />)).toErrorDev(
() => void (<Null />)
).toErrorDev(
'Warning: React.jsx: type is invalid -- expected a string ' + 'Warning: React.jsx: type is invalid -- expected a string ' +
'(for built-in components) or a class/function (for composite ' + '(for built-in components) or a class/function (for composite ' +
'components) but got: null.' + 'components) but got: null.' +
@ -354,9 +350,7 @@ it('gives a helpful error when passing null, undefined, or boolean', () => {
: ''), : ''),
{withoutStack: true} {withoutStack: true}
); );
expect( expect(() => void (<True />)).toErrorDev(
() => void (<True />)
).toErrorDev(
'Warning: React.jsx: type is invalid -- expected a string ' + 'Warning: React.jsx: type is invalid -- expected a string ' +
'(for built-in components) or a class/function (for composite ' + '(for built-in components) or a class/function (for composite ' +
'components) but got: boolean.' + 'components) but got: boolean.' +

View File

@ -330,9 +330,7 @@ it('gives a helpful error when passing null, undefined, or boolean', () => {
const Null = null; const Null = null;
const True = true; const True = true;
const Div = 'div'; const Div = 'div';
expect( expect(() => void (<Undefined />)).toErrorDev(
() => void (<Undefined />)
).toErrorDev(
'Warning: React.jsx: type is invalid -- expected a string ' + 'Warning: React.jsx: type is invalid -- expected a string ' +
'(for built-in components) or a class/function (for composite ' + '(for built-in components) or a class/function (for composite ' +
'components) but got: undefined. You likely forgot to export your ' + 'components) but got: undefined. You likely forgot to export your ' +
@ -343,9 +341,7 @@ it('gives a helpful error when passing null, undefined, or boolean', () => {
: ''), : ''),
{withoutStack: true} {withoutStack: true}
); );
expect( expect(() => void (<Null />)).toErrorDev(
() => void (<Null />)
).toErrorDev(
'Warning: React.jsx: type is invalid -- expected a string ' + 'Warning: React.jsx: type is invalid -- expected a string ' +
'(for built-in components) or a class/function (for composite ' + '(for built-in components) or a class/function (for composite ' +
'components) but got: null.' + 'components) but got: null.' +
@ -354,9 +350,7 @@ it('gives a helpful error when passing null, undefined, or boolean', () => {
: ''), : ''),
{withoutStack: true} {withoutStack: true}
); );
expect( expect(() => void (<True />)).toErrorDev(
() => void (<True />)
).toErrorDev(
'Warning: React.jsx: type is invalid -- expected a string ' + 'Warning: React.jsx: type is invalid -- expected a string ' +
'(for built-in components) or a class/function (for composite ' + '(for built-in components) or a class/function (for composite ' +
'components) but got: boolean.' + 'components) but got: boolean.' +

View File

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

View File

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

View File

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

View File

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

View File

@ -58,10 +58,8 @@ describe('ReactHooksInspectionIntegration', () => {
}, },
]); ]);
const { const {onMouseDown: setStateA, onMouseUp: setStateB} =
onMouseDown: setStateA, renderer.root.findByType('div').props;
onMouseUp: setStateB,
} = renderer.root.findByType('div').props;
act(() => setStateA('Hi')); act(() => setStateA('Hi'));

View File

@ -42,7 +42,8 @@ installHook(window);
const hook: ?DevToolsHook = window.__REACT_DEVTOOLS_GLOBAL_HOOK__; const hook: ?DevToolsHook = window.__REACT_DEVTOOLS_GLOBAL_HOOK__;
let savedComponentFilters: Array<ComponentFilter> = getDefaultComponentFilters(); let savedComponentFilters: Array<ComponentFilter> =
getDefaultComponentFilters();
function debug(methodName: string, ...args: Array<mixed>) { function debug(methodName: string, ...args: Array<mixed>) {
if (__DEBUG__) { if (__DEBUG__) {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -203,7 +203,8 @@ export function exportImportHelper(bridge: FrontendBridge, store: Store): void {
expect(profilerStore.profilingData).not.toBeNull(); expect(profilerStore.profilingData).not.toBeNull();
const profilingDataFrontendInitial = ((profilerStore.profilingData: any): ProfilingDataFrontend); const profilingDataFrontendInitial =
((profilerStore.profilingData: any): ProfilingDataFrontend);
expect(profilingDataFrontendInitial.imported).toBe(false); expect(profilingDataFrontendInitial.imported).toBe(false);
const profilingDataExport = prepareProfilingDataExport( const profilingDataExport = prepareProfilingDataExport(

View File

@ -569,9 +569,8 @@ export default class Agent extends EventEmitter<{
} }
}; };
reloadAndProfile: ( reloadAndProfile: (recordChangeDescriptions: boolean) => void =
recordChangeDescriptions: boolean, recordChangeDescriptions => {
) => void = recordChangeDescriptions => {
sessionStorageSetItem(SESSION_STORAGE_RELOAD_AND_PROFILE_KEY, 'true'); sessionStorageSetItem(SESSION_STORAGE_RELOAD_AND_PROFILE_KEY, 'true');
sessionStorageSetItem( sessionStorageSetItem(
SESSION_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY, SESSION_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY,
@ -628,9 +627,8 @@ export default class Agent extends EventEmitter<{
} }
} }
setTraceUpdatesEnabled: ( setTraceUpdatesEnabled: (traceUpdatesEnabled: boolean) => void =
traceUpdatesEnabled: boolean, traceUpdatesEnabled => {
) => void = traceUpdatesEnabled => {
this._traceUpdatesEnabled = traceUpdatesEnabled; this._traceUpdatesEnabled = traceUpdatesEnabled;
setTraceUpdatesEnabled(traceUpdatesEnabled); setTraceUpdatesEnabled(traceUpdatesEnabled);
@ -656,9 +654,8 @@ export default class Agent extends EventEmitter<{
this.emit('shutdown'); this.emit('shutdown');
}; };
startProfiling: ( startProfiling: (recordChangeDescriptions: boolean) => void =
recordChangeDescriptions: boolean, recordChangeDescriptions => {
) => void = recordChangeDescriptions => {
this._recordChangeDescriptions = recordChangeDescriptions; this._recordChangeDescriptions = recordChangeDescriptions;
this._isProfiling = true; this._isProfiling = true;
for (const rendererID in this._rendererInterfaces) { for (const rendererID in this._rendererInterfaces) {
@ -726,9 +723,8 @@ export default class Agent extends EventEmitter<{
}); });
}; };
updateComponentFilters: ( updateComponentFilters: (componentFilters: Array<ComponentFilter>) => void =
componentFilters: Array<ComponentFilter>, componentFilters => {
) => void = componentFilters => {
for (const rendererID in this._rendererInterfaces) { for (const rendererID in this._rendererInterfaces) {
const renderer = ((this._rendererInterfaces[ const renderer = ((this._rendererInterfaces[
(rendererID: any) (rendererID: any)

View File

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

View File

@ -137,16 +137,13 @@ export function attach(
global: Object, global: Object,
): RendererInterface { ): RendererInterface {
const idToInternalInstanceMap: Map<number, InternalInstance> = new Map(); const idToInternalInstanceMap: Map<number, InternalInstance> = new Map();
const internalInstanceToIDMap: WeakMap< const internalInstanceToIDMap: WeakMap<InternalInstance, number> =
InternalInstance, new WeakMap();
number, const internalInstanceToRootIDMap: WeakMap<InternalInstance, number> =
> = new WeakMap(); new WeakMap();
const internalInstanceToRootIDMap: WeakMap<
InternalInstance,
number,
> = new WeakMap();
let getInternalIDForNative: GetFiberIDForNative = ((null: any): GetFiberIDForNative); let getInternalIDForNative: GetFiberIDForNative =
((null: any): GetFiberIDForNative);
let findNativeNodeForInternalID: (id: number) => ?NativeType; let findNativeNodeForInternalID: (id: number) => ?NativeType;
let getFiberForNative = (node: NativeType) => { let getFiberForNative = (node: NativeType) => {
// Not implemented. // Not implemented.
@ -155,9 +152,8 @@ export function attach(
if (renderer.ComponentTree) { if (renderer.ComponentTree) {
getInternalIDForNative = (node, findNearestUnfilteredAncestor) => { getInternalIDForNative = (node, findNearestUnfilteredAncestor) => {
const internalInstance = renderer.ComponentTree.getClosestInstanceFromNode( const internalInstance =
node, renderer.ComponentTree.getClosestInstanceFromNode(node);
);
return internalInstanceToIDMap.get(internalInstance) || null; return internalInstanceToIDMap.get(internalInstance) || null;
}; };
findNativeNodeForInternalID = (id: number) => { findNativeNodeForInternalID = (id: number) => {

View File

@ -237,10 +237,8 @@ export function createProfilingHooks({
currentReactMeasuresStack.push(reactMeasure); currentReactMeasuresStack.push(reactMeasure);
if (currentTimelineData) { if (currentTimelineData) {
const { const {batchUIDToMeasuresMap, laneToReactMeasureMap} =
batchUIDToMeasuresMap, currentTimelineData;
laneToReactMeasureMap,
} = currentTimelineData;
let reactMeasures = batchUIDToMeasuresMap.get(currentBatchUID); let reactMeasures = batchUIDToMeasuresMap.get(currentBatchUID);
if (reactMeasures != null) { if (reactMeasures != null) {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -249,9 +249,8 @@ export default class ProfilerStore extends EventEmitter<{
} }
}; };
onBridgeProfilingData: ( onBridgeProfilingData: (dataBackend: ProfilingDataBackend) => void =
dataBackend: ProfilingDataBackend, dataBackend => {
) => void = dataBackend => {
if (this._isProfiling) { if (this._isProfiling) {
// This should never happen, but if it does- ignore previous profiling data. // This should never happen, but if it does- ignore previous profiling data.
return; return;

View File

@ -117,10 +117,8 @@ export default class Store extends EventEmitter<{
_componentFilters: Array<ComponentFilter>; _componentFilters: Array<ComponentFilter>;
// Map of ID to number of recorded error and warning message IDs. // Map of ID to number of recorded error and warning message IDs.
_errorsAndWarnings: Map< _errorsAndWarnings: Map<number, {errorCount: number, warningCount: number}> =
number, new Map();
{errorCount: number, warningCount: number},
> = new Map();
// At least one of the injected renderers contains (DEV only) owner metadata. // At least one of the injected renderers contains (DEV only) owner metadata.
_hasOwnerMetadata: boolean = false; _hasOwnerMetadata: boolean = false;
@ -584,9 +582,10 @@ export default class Store extends EventEmitter<{
} }
} }
getErrorAndWarningCountForElementID( getErrorAndWarningCountForElementID(id: number): {
id: number, errorCount: number,
): {errorCount: number, warningCount: number} { warningCount: number,
} {
return this._errorsAndWarnings.get(id) || {errorCount: 0, warningCount: 0}; return this._errorsAndWarnings.get(id) || {errorCount: 0, warningCount: 0};
} }
@ -1029,10 +1028,8 @@ export default class Store extends EventEmitter<{
): any): Element); ): any): Element);
parentElement.children.push(id); parentElement.children.push(id);
const [ const [displayNameWithoutHOCs, hocDisplayNames] =
displayNameWithoutHOCs, separateDisplayNameAndHOCs(displayName, type);
hocDisplayNames,
] = separateDisplayNameAndHOCs(displayName, type);
const element: Element = { const element: Element = {
children: [], children: [],
@ -1280,8 +1277,8 @@ export default class Store extends EventEmitter<{
if (haveRootsChanged) { if (haveRootsChanged) {
const prevRootSupportsProfiling = this._rootSupportsBasicProfiling; const prevRootSupportsProfiling = this._rootSupportsBasicProfiling;
const prevRootSupportsTimelineProfiling = this const prevRootSupportsTimelineProfiling =
._rootSupportsTimelineProfiling; this._rootSupportsTimelineProfiling;
this._hasOwnerMetadata = false; this._hasOwnerMetadata = false;
this._rootSupportsBasicProfiling = false; this._rootSupportsBasicProfiling = false;
@ -1399,9 +1396,8 @@ export default class Store extends EventEmitter<{
this.emit('backendVersion'); this.emit('backendVersion');
}; };
onBridgeProtocol: ( onBridgeProtocol: (bridgeProtocol: BridgeProtocol) => void =
bridgeProtocol: BridgeProtocol, bridgeProtocol => {
) => void = bridgeProtocol => {
if (this._onBridgeProtocolTimeoutID !== null) { if (this._onBridgeProtocolTimeoutID !== null) {
clearTimeout(this._onBridgeProtocolTimeoutID); clearTimeout(this._onBridgeProtocolTimeoutID);
this._onBridgeProtocolTimeoutID = null; this._onBridgeProtocolTimeoutID = null;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -150,14 +150,12 @@ type Action =
export type DispatcherContext = (action: Action) => void; export type DispatcherContext = (action: Action) => void;
const TreeStateContext: ReactContext<StateContext> = createContext<StateContext>( const TreeStateContext: ReactContext<StateContext> =
((null: any): StateContext), createContext<StateContext>(((null: any): StateContext));
);
TreeStateContext.displayName = 'TreeStateContext'; TreeStateContext.displayName = 'TreeStateContext';
const TreeDispatcherContext: ReactContext<DispatcherContext> = createContext<DispatcherContext>( const TreeDispatcherContext: ReactContext<DispatcherContext> =
((null: any): DispatcherContext), createContext<DispatcherContext>(((null: any): DispatcherContext));
);
TreeDispatcherContext.displayName = 'TreeDispatcherContext'; TreeDispatcherContext.displayName = 'TreeDispatcherContext';
type State = { type State = {
@ -379,7 +377,8 @@ function reduceTreeState(store: Store, state: State, action: Action): State {
} }
break; break;
case 'SELECT_PREVIOUS_ELEMENT_WITH_ERROR_OR_WARNING_IN_TREE': { case 'SELECT_PREVIOUS_ELEMENT_WITH_ERROR_OR_WARNING_IN_TREE': {
const elementIndicesWithErrorsOrWarnings = store.getElementsWithErrorsAndWarnings(); const elementIndicesWithErrorsOrWarnings =
store.getElementsWithErrorsAndWarnings();
if (elementIndicesWithErrorsOrWarnings.length === 0) { if (elementIndicesWithErrorsOrWarnings.length === 0) {
return state; return state;
} }
@ -420,7 +419,8 @@ function reduceTreeState(store: Store, state: State, action: Action): State {
break; break;
} }
case 'SELECT_NEXT_ELEMENT_WITH_ERROR_OR_WARNING_IN_TREE': { case 'SELECT_NEXT_ELEMENT_WITH_ERROR_OR_WARNING_IN_TREE': {
const elementIndicesWithErrorsOrWarnings = store.getElementsWithErrorsAndWarnings(); const elementIndicesWithErrorsOrWarnings =
store.getElementsWithErrorsAndWarnings();
if (elementIndicesWithErrorsOrWarnings.length === 0) { if (elementIndicesWithErrorsOrWarnings.length === 0) {
return state; return state;
} }
@ -522,10 +522,8 @@ function reduceSearchState(store: Store, state: State, action: Action): State {
break; break;
case 'HANDLE_STORE_MUTATION': case 'HANDLE_STORE_MUTATION':
if (searchText !== '') { if (searchText !== '') {
const [ const [addedElementIDs, removedElementIDs] =
addedElementIDs, (action: ACTION_HANDLE_STORE_MUTATION).payload;
removedElementIDs,
] = (action: ACTION_HANDLE_STORE_MUTATION).payload;
removedElementIDs.forEach((parentID, id) => { removedElementIDs.forEach((parentID, id) => {
// Prune this item from the search results. // Prune this item from the search results.
@ -847,7 +845,8 @@ function TreeContextController({
// The store is mutable, but the Store itself is global and lives for the lifetime of the DevTools, // The store is mutable, but the Store itself is global and lives for the lifetime of the DevTools,
// so it's okay for the reducer to have an empty dependencies array. // so it's okay for the reducer to have an empty dependencies array.
const reducer = useMemo( const reducer = useMemo(
() => (state: State, action: Action): State => { () =>
(state: State, action: Action): State => {
const {type} = action; const {type} = action;
switch (type) { switch (type) {
case 'GO_TO_NEXT_SEARCH_RESULT': case 'GO_TO_NEXT_SEARCH_RESULT':

View File

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

View File

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

View File

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

View File

@ -40,9 +40,8 @@ export type ItemData = {
export default function CommitFlamegraphAutoSizer(_: {}): React.Node { export default function CommitFlamegraphAutoSizer(_: {}): React.Node {
const {profilerStore} = useContext(StoreContext); const {profilerStore} = useContext(StoreContext);
const {rootID, selectedCommitIndex, selectFiber} = useContext( const {rootID, selectedCommitIndex, selectFiber} =
ProfilerContext, useContext(ProfilerContext);
);
const {profilingCache} = profilerStore; const {profilingCache} = profilerStore;
const deselectCurrentFiber = useCallback( const deselectCurrentFiber = useCallback(
@ -98,16 +97,12 @@ type Props = {
}; };
function CommitFlamegraph({chartData, commitTree, height, width}: Props) { function CommitFlamegraph({chartData, commitTree, height, width}: Props) {
const [ const [hoveredFiberData, setHoveredFiberData] =
hoveredFiberData, useState<TooltipFiberData | null>(null);
setHoveredFiberData,
] = useState<TooltipFiberData | null>(null);
const {lineHeight} = useContext(SettingsContext); const {lineHeight} = useContext(SettingsContext);
const {selectFiber, selectedFiberID} = useContext(ProfilerContext); const {selectFiber, selectedFiberID} = useContext(ProfilerContext);
const { const {highlightNativeElement, clearHighlightNativeElement} =
highlightNativeElement, useHighlightNativeElement();
clearHighlightNativeElement,
} = useHighlightNativeElement();
const selectedChartNodeIndex = useMemo<number>(() => { const selectedChartNodeIndex = useMemo<number>(() => {
if (selectedFiberID === null) { if (selectedFiberID === null) {

View File

@ -40,9 +40,8 @@ export type ItemData = {
export default function CommitRankedAutoSizer(_: {}): React.Node { export default function CommitRankedAutoSizer(_: {}): React.Node {
const {profilerStore} = useContext(StoreContext); const {profilerStore} = useContext(StoreContext);
const {rootID, selectedCommitIndex, selectFiber} = useContext( const {rootID, selectedCommitIndex, selectFiber} =
ProfilerContext, useContext(ProfilerContext);
);
const {profilingCache} = profilerStore; const {profilingCache} = profilerStore;
const deselectCurrentFiber = useCallback( const deselectCurrentFiber = useCallback(
@ -96,16 +95,12 @@ type Props = {
}; };
function CommitRanked({chartData, commitTree, height, width}: Props) { function CommitRanked({chartData, commitTree, height, width}: Props) {
const [ const [hoveredFiberData, setHoveredFiberData] =
hoveredFiberData, useState<TooltipFiberData | null>(null);
setHoveredFiberData,
] = useState<TooltipFiberData | null>(null);
const {lineHeight} = useContext(SettingsContext); const {lineHeight} = useContext(SettingsContext);
const {selectedFiberID, selectFiber} = useContext(ProfilerContext); const {selectedFiberID, selectFiber} = useContext(ProfilerContext);
const { const {highlightNativeElement, clearHighlightNativeElement} =
highlightNativeElement, useHighlightNativeElement();
clearHighlightNativeElement,
} = useHighlightNativeElement();
const selectedFiberIndex = useMemo( const selectedFiberIndex = useMemo(
() => getNodeIndex(chartData, selectedFiberID), () => getNodeIndex(chartData, selectedFiberID),

View File

@ -71,13 +71,8 @@ export function getChartData({
throw Error(`Could not find node with id "${id}" in commit tree`); throw Error(`Could not find node with id "${id}" in commit tree`);
} }
const { const {children, displayName, hocDisplayNames, key, treeBaseDuration} =
children, node;
displayName,
hocDisplayNames,
key,
treeBaseDuration,
} = node;
const actualDuration = fiberActualDurations.get(id) || 0; const actualDuration = fiberActualDurations.get(id) || 0;
const selfDuration = fiberSelfDurations.get(id) || 0; const selfDuration = fiberSelfDurations.get(id) || 0;

View File

@ -44,10 +44,8 @@ export default function HoveredFiberInfo({fiberData}: Props): React.Node {
for (i = 0; i < commitIndices.length; i++) { for (i = 0; i < commitIndices.length; i++) {
const commitIndex = commitIndices[i]; const commitIndex = commitIndices[i];
if (selectedCommitIndex === commitIndex) { if (selectedCommitIndex === commitIndex) {
const { const {fiberActualDurations, fiberSelfDurations} =
fiberActualDurations, profilerStore.getCommitData(((rootID: any): number), commitIndex);
fiberSelfDurations,
} = profilerStore.getCommitData(((rootID: any): number), commitIndex);
const actualDuration = fiberActualDurations.get(id) || 0; const actualDuration = fiberActualDurations.get(id) || 0;
const selfDuration = fiberSelfDurations.get(id) || 0; const selfDuration = fiberSelfDurations.get(id) || 0;

View File

@ -50,9 +50,8 @@ function Profiler(_: {}) {
supportsProfiling, supportsProfiling,
} = useContext(ProfilerContext); } = useContext(ProfilerContext);
const {file: timelineTraceEventData, searchInputContainerRef} = useContext( const {file: timelineTraceEventData, searchInputContainerRef} =
TimelineContext, useContext(TimelineContext);
);
const {supportsTimeline} = useContext(StoreContext); const {supportsTimeline} = useContext(StoreContext);

View File

@ -125,10 +125,8 @@ function ProfilerContextController({children}: Props): React.Node {
supportsProfiling, supportsProfiling,
} = useSubscription<StoreProfilingState>(subscription); } = useSubscription<StoreProfilingState>(subscription);
const [ const [prevProfilingData, setPrevProfilingData] =
prevProfilingData, useState<ProfilingDataFrontend | null>(null);
setPrevProfilingData,
] = useState<ProfilingDataFrontend | null>(null);
const [rootID, setRootID] = useState<number | null>(null); const [rootID, setRootID] = useState<number | null>(null);
const [selectedFiberID, selectFiberID] = useState<number | null>(null); const [selectedFiberID, selectFiberID] = useState<number | null>(null);
const [selectedFiberName, selectFiberName] = useState<string | null>(null); const [selectedFiberName, selectFiberName] = useState<string | null>(null);
@ -179,9 +177,8 @@ function ProfilerContextController({children}: Props): React.Node {
if (rootID === null || !dataForRoots.has(rootID)) { if (rootID === null || !dataForRoots.has(rootID)) {
let selectedElementRootID = null; let selectedElementRootID = null;
if (selectedElementID !== null) { if (selectedElementID !== null) {
selectedElementRootID = store.getRootIDForElement( selectedElementRootID =
selectedElementID, store.getRootIDForElement(selectedElementID);
);
} }
if ( if (
selectedElementRootID !== null && selectedElementRootID !== null &&
@ -196,10 +193,8 @@ function ProfilerContextController({children}: Props): React.Node {
}); });
} }
const [ const [isCommitFilterEnabled, setIsCommitFilterEnabled] =
isCommitFilterEnabled, useLocalStorage<boolean>('React::DevTools::isCommitFilterEnabled', false);
setIsCommitFilterEnabled,
] = useLocalStorage<boolean>('React::DevTools::isCommitFilterEnabled', false);
const [minCommitDuration, setMinCommitDuration] = useLocalStorage<number>( const [minCommitDuration, setMinCommitDuration] = useLocalStorage<number>(
'minCommitDuration', 'minCommitDuration',
0, 0,
@ -228,9 +223,10 @@ function ProfilerContextController({children}: Props): React.Node {
}); });
store.profilerStore.startProfiling(); store.profilerStore.startProfiling();
}, [store, selectedTabID]); }, [store, selectedTabID]);
const stopProfiling = useCallback(() => store.profilerStore.stopProfiling(), [ const stopProfiling = useCallback(
store, () => store.profilerStore.stopProfiling(),
]); [store],
);
if (isProfiling) { if (isProfiling) {
batchedUpdates(() => { batchedUpdates(() => {

View File

@ -96,9 +96,8 @@ export default function ProfilingImportExportButtons(): React.Node {
try { try {
const profilingDataExport = ((json: any): ProfilingDataExport); const profilingDataExport = ((json: any): ProfilingDataExport);
profilerStore.profilingData = prepareProfilingDataFrontendFromExport( profilerStore.profilingData =
profilingDataExport, prepareProfilingDataFrontendFromExport(profilingDataExport);
);
} catch (error) { } catch (error) {
modalDialogDispatch({ modalDialogDispatch({
id: 'ProfilingImportExportButtons', id: 'ProfilingImportExportButtons',

View File

@ -20,9 +20,8 @@ export type Props = {
}; };
export default function RecordToggle({disabled}: Props): React.Node { export default function RecordToggle({disabled}: Props): React.Node {
const {isProfiling, startProfiling, stopProfiling} = useContext( const {isProfiling, startProfiling, stopProfiling} =
ProfilerContext, useContext(ProfilerContext);
);
let className = styles.InactiveRecordToggle; let className = styles.InactiveRecordToggle;
if (disabled) { if (disabled) {

View File

@ -44,10 +44,8 @@ export default function ReloadAndProfileButton({
}), }),
[store], [store],
); );
const { const {recordChangeDescriptions, supportsReloadAndProfile} =
recordChangeDescriptions, useSubscription<SubscriptionData>(subscription);
supportsReloadAndProfile,
} = useSubscription<SubscriptionData>(subscription);
const reloadAndProfile = useCallback(() => { const reloadAndProfile = useCallback(() => {
// TODO If we want to support reload-and-profile for e.g. React Native, // TODO If we want to support reload-and-profile for e.g. React Native,

View File

@ -63,14 +63,8 @@ export default function WhatChanged({fiberID}: Props): React.Node {
return null; return null;
} }
const { const {context, didHooksChange, hooks, isFirstMount, props, state} =
context, changeDescription;
didHooksChange,
hooks,
isFirstMount,
props,
state,
} = changeDescription;
if (isFirstMount) { if (isFirstMount) {
return ( return (

View File

@ -250,7 +250,8 @@ export function prepareProfilingDataFrontendFromExport(
export function prepareProfilingDataExport( export function prepareProfilingDataExport(
profilingDataFrontend: ProfilingDataFrontend, profilingDataFrontend: ProfilingDataFrontend,
): ProfilingDataExport { ): ProfilingDataExport {
const timelineData: Array<TimelineDataExport> = profilingDataFrontend.timelineData.map( const timelineData: Array<TimelineDataExport> =
profilingDataFrontend.timelineData.map(
({ ({
batchUIDToMeasuresMap, batchUIDToMeasuresMap,
componentMeasures, componentMeasures,
@ -373,15 +374,14 @@ export const formatPercentage = (percentage: number): number =>
export const formatTime = (timestamp: number): number => export const formatTime = (timestamp: number): number =>
Math.round(Math.round(timestamp) / 100) / 10; Math.round(Math.round(timestamp) / 100) / 10;
export const scale = ( export const scale =
(
minValue: number, minValue: number,
maxValue: number, maxValue: number,
minRange: number, minRange: number,
maxRange: number, maxRange: number,
): ((value: number, fallbackValue: number) => number) => ( ): ((value: number, fallbackValue: number) => number) =>
value: number, (value: number, fallbackValue: number) =>
fallbackValue: number,
) =>
maxValue - minValue === 0 maxValue - minValue === 0
? fallbackValue ? fallbackValue
: ((value - minValue) / (maxValue - minValue)) * (maxRange - minRange); : ((value - minValue) / (maxValue - minValue)) * (maxRange - minRange);

View File

@ -107,10 +107,8 @@ function SettingsContextController({
}: Props): React.Node { }: Props): React.Node {
const bridge = useContext(BridgeContext); const bridge = useContext(BridgeContext);
const [ const [displayDensity, setDisplayDensity] =
displayDensity, useLocalStorageWithLog<DisplayDensity>(
setDisplayDensity,
] = useLocalStorageWithLog<DisplayDensity>(
'React::DevTools::displayDensity', 'React::DevTools::displayDensity',
'compact', 'compact',
); );
@ -118,17 +116,13 @@ function SettingsContextController({
LOCAL_STORAGE_BROWSER_THEME, LOCAL_STORAGE_BROWSER_THEME,
'auto', 'auto',
); );
const [ const [appendComponentStack, setAppendComponentStack] =
appendComponentStack, useLocalStorageWithLog<boolean>(
setAppendComponentStack,
] = useLocalStorageWithLog<boolean>(
LOCAL_STORAGE_SHOULD_APPEND_COMPONENT_STACK_KEY, LOCAL_STORAGE_SHOULD_APPEND_COMPONENT_STACK_KEY,
true, true,
); );
const [ const [breakOnConsoleErrors, setBreakOnConsoleErrors] =
breakOnConsoleErrors, useLocalStorageWithLog<boolean>(
setBreakOnConsoleErrors,
] = useLocalStorageWithLog<boolean>(
LOCAL_STORAGE_SHOULD_BREAK_ON_CONSOLE_ERRORS, LOCAL_STORAGE_SHOULD_BREAK_ON_CONSOLE_ERRORS,
false, false,
); );
@ -136,24 +130,18 @@ function SettingsContextController({
LOCAL_STORAGE_PARSE_HOOK_NAMES_KEY, LOCAL_STORAGE_PARSE_HOOK_NAMES_KEY,
false, false,
); );
const [ const [hideConsoleLogsInStrictMode, setHideConsoleLogsInStrictMode] =
hideConsoleLogsInStrictMode, useLocalStorageWithLog<boolean>(
setHideConsoleLogsInStrictMode,
] = useLocalStorageWithLog<boolean>(
LOCAL_STORAGE_HIDE_CONSOLE_LOGS_IN_STRICT_MODE, LOCAL_STORAGE_HIDE_CONSOLE_LOGS_IN_STRICT_MODE,
false, false,
); );
const [ const [showInlineWarningsAndErrors, setShowInlineWarningsAndErrors] =
showInlineWarningsAndErrors, useLocalStorageWithLog<boolean>(
setShowInlineWarningsAndErrors,
] = useLocalStorageWithLog<boolean>(
LOCAL_STORAGE_SHOW_INLINE_WARNINGS_AND_ERRORS_KEY, LOCAL_STORAGE_SHOW_INLINE_WARNINGS_AND_ERRORS_KEY,
true, true,
); );
const [ const [traceUpdatesEnabled, setTraceUpdatesEnabled] =
traceUpdatesEnabled, useLocalStorageWithLog<boolean>(
setTraceUpdatesEnabled,
] = useLocalStorageWithLog<boolean>(
LOCAL_STORAGE_TRACE_UPDATES_ENABLED_KEY, LOCAL_STORAGE_TRACE_UPDATES_ENABLED_KEY,
false, false,
); );

View File

@ -59,9 +59,10 @@ export default function SettingsModal(_: {}): React.Node {
function SettingsModalImpl(_: {}) { function SettingsModalImpl(_: {}) {
const {setIsModalShowing} = useContext(SettingsModalContext); const {setIsModalShowing} = useContext(SettingsModalContext);
const dismissModal = useCallback(() => setIsModalShowing(false), [ const dismissModal = useCallback(
setIsModalShowing, () => setIsModalShowing(false),
]); [setIsModalShowing],
);
const [selectedTabID, selectTab] = useLocalStorage<TabID>( const [selectedTabID, selectTab] = useLocalStorage<TabID>(
'React::DevTools::selectedSettingsTabID', 'React::DevTools::selectedSettingsTabID',

View File

@ -33,10 +33,10 @@ function SettingsModalContextController({
}): React.Node { }): React.Node {
const [isModalShowing, setIsModalShowing] = useState<boolean>(false); const [isModalShowing, setIsModalShowing] = useState<boolean>(false);
const value = useMemo(() => ({isModalShowing, setIsModalShowing}), [ const value = useMemo(
isModalShowing, () => ({isModalShowing, setIsModalShowing}),
setIsModalShowing, [isModalShowing, setIsModalShowing],
]); );
return ( return (
<SettingsModalContext.Provider value={value}> <SettingsModalContext.Provider value={value}>

View File

@ -20,9 +20,10 @@ export default function SettingsModalContextToggle(): React.Node {
const store = useContext(StoreContext); const store = useContext(StoreContext);
const {profilerStore} = store; const {profilerStore} = store;
const showFilterModal = useCallback(() => setIsModalShowing(true), [ const showFilterModal = useCallback(
setIsModalShowing, () => setIsModalShowing(true),
]); [setIsModalShowing],
);
// Updating preferences while profiling is in progress could break things (e.g. filtering) // Updating preferences while profiling is in progress could break things (e.g. filtering)
// Explicitly disallow it for now. // Explicitly disallow it for now.

View File

@ -42,10 +42,10 @@ export default function Toggle({
defaultClassName = styles.ToggleOff; defaultClassName = styles.ToggleOff;
} }
const handleClick = useCallback(() => onChange(!isChecked), [ const handleClick = useCallback(
isChecked, () => onChange(!isChecked),
onChange, [isChecked, onChange],
]); );
let toggle = ( let toggle = (
<button <button

View File

@ -14,9 +14,8 @@ import Store from '../store';
import type {ViewAttributeSource} from 'react-devtools-shared/src/devtools/views/DevTools'; import type {ViewAttributeSource} from 'react-devtools-shared/src/devtools/views/DevTools';
import type {FrontendBridge} from 'react-devtools-shared/src/bridge'; import type {FrontendBridge} from 'react-devtools-shared/src/bridge';
export const BridgeContext: ReactContext<FrontendBridge> = createContext<FrontendBridge>( export const BridgeContext: ReactContext<FrontendBridge> =
((null: any): FrontendBridge), createContext<FrontendBridge>(((null: any): FrontendBridge));
);
BridgeContext.displayName = 'BridgeContext'; BridgeContext.displayName = 'BridgeContext';
export const StoreContext: ReactContext<Store> = createContext<Store>( export const StoreContext: ReactContext<Store> = createContext<Store>(
@ -29,12 +28,11 @@ export type ContextMenuContextType = {
viewAttributeSourceFunction: ViewAttributeSource | null, viewAttributeSourceFunction: ViewAttributeSource | null,
}; };
export const ContextMenuContext: ReactContext<ContextMenuContextType> = createContext<ContextMenuContextType>( export const ContextMenuContext: ReactContext<ContextMenuContextType> =
{ createContext<ContextMenuContextType>({
isEnabledForInspectedElement: false, isEnabledForInspectedElement: false,
viewAttributeSourceFunction: null, viewAttributeSourceFunction: null,
}, });
);
ContextMenuContext.displayName = 'ContextMenuContext'; ContextMenuContext.displayName = 'ContextMenuContext';
export type OptionsContextType = { export type OptionsContextType = {
@ -46,13 +44,12 @@ export type OptionsContextType = {
hideViewSourceAction: boolean, hideViewSourceAction: boolean,
}; };
export const OptionsContext: ReactContext<OptionsContextType> = createContext<OptionsContextType>( export const OptionsContext: ReactContext<OptionsContextType> =
{ createContext<OptionsContextType>({
readOnly: false, readOnly: false,
hideSettings: false, hideSettings: false,
hideToggleErrorAction: false, hideToggleErrorAction: false,
hideToggleSuspenseAction: false, hideToggleSuspenseAction: false,
hideLogAction: false, hideLogAction: false,
hideViewSourceAction: false, hideViewSourceAction: false,
}, });
);

View File

@ -40,10 +40,8 @@ type ModuleLoaderFunction = () => Thenable<Module>;
// This is intentionally a module-level Map, rather than a React-managed one. // This is intentionally a module-level Map, rather than a React-managed one.
// Otherwise, refreshing the inspected element cache would also clear this cache. // Otherwise, refreshing the inspected element cache would also clear this cache.
// Modules are static anyway. // Modules are static anyway.
const moduleLoaderFunctionToModuleMap: Map< const moduleLoaderFunctionToModuleMap: Map<ModuleLoaderFunction, Module> =
ModuleLoaderFunction, new Map();
Module,
> = new Map();
function readRecord<T>(record: Record<T>): ResolvedRecord<T> | RejectedRecord { function readRecord<T>(record: Record<T>): ResolvedRecord<T> | RejectedRecord {
if (record.status === Resolved) { if (record.status === Resolved) {

View File

@ -303,8 +303,10 @@ export function installHook(target: any): DevToolsHook | null {
} }
}; };
overrideMethod.__REACT_DEVTOOLS_STRICT_MODE_ORIGINAL_METHOD__ = originalMethod; overrideMethod.__REACT_DEVTOOLS_STRICT_MODE_ORIGINAL_METHOD__ =
originalMethod.__REACT_DEVTOOLS_STRICT_MODE_OVERRIDE_METHOD__ = overrideMethod; originalMethod;
originalMethod.__REACT_DEVTOOLS_STRICT_MODE_OVERRIDE_METHOD__ =
overrideMethod;
targetConsole[method] = overrideMethod; targetConsole[method] = overrideMethod;
} catch (error) {} } catch (error) {}
@ -555,7 +557,8 @@ export function installHook(target: any): DevToolsHook | null {
}; };
if (__TEST__) { if (__TEST__) {
hook.dangerous_setTargetConsoleForTesting = dangerous_setTargetConsoleForTesting; hook.dangerous_setTargetConsoleForTesting =
dangerous_setTargetConsoleForTesting;
} }
Object.defineProperty( Object.defineProperty(

View File

@ -143,7 +143,8 @@ export function loadHookNames(
} }
if (hookNames) { if (hookNames) {
const resolvedRecord = ((newRecord: any): ResolvedRecord<HookNames>); const resolvedRecord =
((newRecord: any): ResolvedRecord<HookNames>);
resolvedRecord.status = Resolved; resolvedRecord.status = Resolved;
resolvedRecord.value = hookNames; resolvedRecord.value = hookNames;
} else { } else {

View File

@ -56,16 +56,16 @@ describe('parseHookNames', () => {
fetchMock = initFetchMock(); fetchMock = initFetchMock();
inspectHooks = require('react-debug-tools/src/ReactDebugHooks') inspectHooks =
.inspectHooks; require('react-debug-tools/src/ReactDebugHooks').inspectHooks;
// Jest can't run the workerized version of this module. // Jest can't run the workerized version of this module.
const { const {
flattenHooksList, flattenHooksList,
loadSourceAndMetadata, loadSourceAndMetadata,
} = require('../parseHookNames/loadSourceAndMetadata'); } = require('../parseHookNames/loadSourceAndMetadata');
const parseSourceAndMetadata = require('../parseHookNames/parseSourceAndMetadata') const parseSourceAndMetadata =
.parseSourceAndMetadata; require('../parseHookNames/parseSourceAndMetadata').parseSourceAndMetadata;
parseHookNames = async hooksTree => { parseHookNames = async hooksTree => {
const hooksList = flattenHooksList(hooksTree); const hooksList = flattenHooksList(hooksTree);
@ -105,22 +105,22 @@ describe('parseHookNames', () => {
} }
it('should parse names for useState()', async () => { it('should parse names for useState()', async () => {
const Component = require('./__source__/__untransformed__/ComponentWithUseState') const Component =
.Component; require('./__source__/__untransformed__/ComponentWithUseState').Component;
const hookNames = await getHookNamesForComponent(Component); const hookNames = await getHookNamesForComponent(Component);
expectHookNamesToEqual(hookNames, ['foo', 'bar', 'baz', null]); expectHookNamesToEqual(hookNames, ['foo', 'bar', 'baz', null]);
}); });
it('should parse names for useReducer()', async () => { it('should parse names for useReducer()', async () => {
const Component = require('./__source__/__untransformed__/ComponentWithUseReducer') const Component =
.Component; require('./__source__/__untransformed__/ComponentWithUseReducer').Component;
const hookNames = await getHookNamesForComponent(Component); const hookNames = await getHookNamesForComponent(Component);
expectHookNamesToEqual(hookNames, ['foo', 'bar', 'baz']); expectHookNamesToEqual(hookNames, ['foo', 'bar', 'baz']);
}); });
it('should skip loading source files for unnamed hooks like useEffect', async () => { it('should skip loading source files for unnamed hooks like useEffect', async () => {
const Component = require('./__source__/__untransformed__/ComponentWithUseEffect') const Component =
.Component; require('./__source__/__untransformed__/ComponentWithUseEffect').Component;
// Since this component contains only unnamed hooks, the source code should not even be loaded. // Since this component contains only unnamed hooks, the source code should not even be loaded.
fetchMock.mockIf(/.+$/, request => { fetchMock.mockIf(/.+$/, request => {
@ -132,8 +132,8 @@ describe('parseHookNames', () => {
}); });
it('should skip loading source files for unnamed hooks like useEffect (alternate)', async () => { it('should skip loading source files for unnamed hooks like useEffect (alternate)', async () => {
const Component = require('./__source__/__untransformed__/ComponentWithExternalUseEffect') const Component =
.Component; require('./__source__/__untransformed__/ComponentWithExternalUseEffect').Component;
fetchMock.mockIf(/.+$/, request => { fetchMock.mockIf(/.+$/, request => {
// Since the custom hook contains only unnamed hooks, the source code should not be loaded. // Since the custom hook contains only unnamed hooks, the source code should not be loaded.
@ -148,8 +148,8 @@ describe('parseHookNames', () => {
}); });
it('should parse names for custom hooks', async () => { it('should parse names for custom hooks', async () => {
const Component = require('./__source__/__untransformed__/ComponentWithNamedCustomHooks') const Component =
.Component; require('./__source__/__untransformed__/ComponentWithNamedCustomHooks').Component;
const hookNames = await getHookNamesForComponent(Component); const hookNames = await getHookNamesForComponent(Component);
expectHookNamesToEqual(hookNames, [ expectHookNamesToEqual(hookNames, [
'foo', 'foo',
@ -159,15 +159,15 @@ describe('parseHookNames', () => {
}); });
it('should parse names for code using hooks indirectly', async () => { it('should parse names for code using hooks indirectly', async () => {
const Component = require('./__source__/__untransformed__/ComponentUsingHooksIndirectly') const Component =
.Component; require('./__source__/__untransformed__/ComponentUsingHooksIndirectly').Component;
const hookNames = await getHookNamesForComponent(Component); const hookNames = await getHookNamesForComponent(Component);
expectHookNamesToEqual(hookNames, ['count', 'darkMode', 'isDarkMode']); expectHookNamesToEqual(hookNames, ['count', 'darkMode', 'isDarkMode']);
}); });
it('should parse names for code using nested hooks', async () => { it('should parse names for code using nested hooks', async () => {
const Component = require('./__source__/__untransformed__/ComponentWithNestedHooks') const Component =
.Component; require('./__source__/__untransformed__/ComponentWithNestedHooks').Component;
let InnerComponent; let InnerComponent;
const hookNames = await getHookNamesForComponent(Component, { const hookNames = await getHookNamesForComponent(Component, {
callback: innerComponent => { callback: innerComponent => {
@ -180,8 +180,8 @@ describe('parseHookNames', () => {
}); });
it('should return null for custom hooks without explicit names', async () => { it('should return null for custom hooks without explicit names', async () => {
const Component = require('./__source__/__untransformed__/ComponentWithUnnamedCustomHooks') const Component =
.Component; require('./__source__/__untransformed__/ComponentWithUnnamedCustomHooks').Component;
const hookNames = await getHookNamesForComponent(Component); const hookNames = await getHookNamesForComponent(Component);
expectHookNamesToEqual(hookNames, [ expectHookNamesToEqual(hookNames, [
null, // Custom hooks can have names, but this one does not even return a value. null, // Custom hooks can have names, but this one does not even return a value.
@ -923,8 +923,8 @@ describe('parseHookNames worker', () => {
}; };
}); });
inspectHooks = require('react-debug-tools/src/ReactDebugHooks') inspectHooks =
.inspectHooks; require('react-debug-tools/src/ReactDebugHooks').inspectHooks;
parseHookNames = require('../parseHookNames').parseHookNames; parseHookNames = require('../parseHookNames').parseHookNames;
}); });
@ -935,8 +935,8 @@ describe('parseHookNames worker', () => {
} }
it('should use worker', async () => { it('should use worker', async () => {
const Component = require('./__source__/__untransformed__/ComponentWithUseState') const Component =
.Component; require('./__source__/__untransformed__/ComponentWithUseState').Component;
window.Worker = true; window.Worker = true;

View File

@ -244,8 +244,9 @@ function getHookNameFromNode(
// const flagState = useState(true); -> later referenced as // const flagState = useState(true); -> later referenced as
// const flag = flagState[0]; // const flag = flagState[0];
// const setFlag = flagState[1]; // const setFlag = flagState[1];
nodesAssociatedWithReactHookASTNode = nodesAssociatedWithReactHookASTNode.filter( nodesAssociatedWithReactHookASTNode =
hookPath => filterMemberWithHookVariableName(hookPath), nodesAssociatedWithReactHookASTNode.filter(hookPath =>
filterMemberWithHookVariableName(hookPath),
); );
if (nodesAssociatedWithReactHookASTNode.length !== 1) { if (nodesAssociatedWithReactHookASTNode.length !== 1) {

View File

@ -17,7 +17,8 @@ import WorkerizedParseSourceAndMetadata from './parseSourceAndMetadata.worker';
import typeof * as ParseSourceAndMetadataModule from './parseSourceAndMetadata'; import typeof * as ParseSourceAndMetadataModule from './parseSourceAndMetadata';
import {flattenHooksList, loadSourceAndMetadata} from './loadSourceAndMetadata'; import {flattenHooksList, loadSourceAndMetadata} from './loadSourceAndMetadata';
const workerizedParseHookNames: ParseSourceAndMetadataModule = WorkerizedParseSourceAndMetadata(); const workerizedParseHookNames: ParseSourceAndMetadataModule =
WorkerizedParseSourceAndMetadata();
export function parseSourceAndMetadata( export function parseSourceAndMetadata(
hooksList: Array<HooksNode>, hooksList: Array<HooksNode>,

View File

@ -149,7 +149,8 @@ function extractAndLoadSourceMapJSON(
const setterPromises = []; const setterPromises = [];
locationKeyToHookSourceAndMetadata.forEach(hookSourceAndMetadata => { locationKeyToHookSourceAndMetadata.forEach(hookSourceAndMetadata => {
const sourceMapRegex = / ?sourceMappingURL=([^\s'"]+)/gm; const sourceMapRegex = / ?sourceMappingURL=([^\s'"]+)/gm;
const runtimeSourceCode = ((hookSourceAndMetadata.runtimeSourceCode: any): string); const runtimeSourceCode =
((hookSourceAndMetadata.runtimeSourceCode: any): string);
// TODO (named hooks) Search for our custom metadata first. // TODO (named hooks) Search for our custom metadata first.
// If it's found, we should use it rather than source maps. // If it's found, we should use it rather than source maps.
@ -415,7 +416,8 @@ function initializeHookSourceAndMetadata(
hooksList: Array<HooksNode>, hooksList: Array<HooksNode>,
): LocationKeyToHookSourceAndMetadata { ): LocationKeyToHookSourceAndMetadata {
// Create map of unique source locations (file names plus line and column numbers) to metadata about hooks. // Create map of unique source locations (file names plus line and column numbers) to metadata about hooks.
const locationKeyToHookSourceAndMetadata: LocationKeyToHookSourceAndMetadata = new Map(); const locationKeyToHookSourceAndMetadata: LocationKeyToHookSourceAndMetadata =
new Map();
for (let i = 0; i < hooksList.length; i++) { for (let i = 0; i < hooksList.length; i++) {
const hook = hooksList[i]; const hook = hooksList[i];

View File

@ -64,22 +64,21 @@ type CachedRuntimeCodeMetadata = {
sourceMapConsumer: SourceMapConsumerType | null, sourceMapConsumer: SourceMapConsumerType | null,
}; };
const runtimeURLToMetadataCache: LRUCache< const runtimeURLToMetadataCache: LRUCache<string, CachedRuntimeCodeMetadata> =
string, new LRU({max: 50});
CachedRuntimeCodeMetadata,
> = new LRU({max: 50});
type CachedSourceCodeMetadata = { type CachedSourceCodeMetadata = {
originalSourceAST: AST, originalSourceAST: AST,
originalSourceCode: string, originalSourceCode: string,
}; };
const originalURLToMetadataCache: LRUCache< const originalURLToMetadataCache: LRUCache<string, CachedSourceCodeMetadata> =
string, new LRU({
CachedSourceCodeMetadata,
> = new LRU({
max: 50, max: 50,
dispose: (originalSourceURL: string, metadata: CachedSourceCodeMetadata) => { dispose: (
originalSourceURL: string,
metadata: CachedSourceCodeMetadata,
) => {
if (__DEBUG__) { if (__DEBUG__) {
console.log( console.log(
`originalURLToMetadataCache.dispose() Evicting cached metadata for "${originalSourceURL}"`, `originalURLToMetadataCache.dispose() Evicting cached metadata for "${originalSourceURL}"`,
@ -196,7 +195,8 @@ function initializeHookParsedMetadata(
locationKeyToHookSourceAndMetadata: LocationKeyToHookSourceAndMetadata, locationKeyToHookSourceAndMetadata: LocationKeyToHookSourceAndMetadata,
) { ) {
// Create map of unique source locations (file names plus line and column numbers) to metadata about hooks. // Create map of unique source locations (file names plus line and column numbers) to metadata about hooks.
const locationKeyToHookParsedMetadata: LocationKeyToHookParsedMetadata = new Map(); const locationKeyToHookParsedMetadata: LocationKeyToHookParsedMetadata =
new Map();
locationKeyToHookSourceAndMetadata.forEach( locationKeyToHookSourceAndMetadata.forEach(
(hookSourceAndMetadata, locationKey) => { (hookSourceAndMetadata, locationKey) => {
const hookParsedMetadata: HookParsedMetadata = { const hookParsedMetadata: HookParsedMetadata = {
@ -222,9 +222,8 @@ function parseSourceAST(
): void { ): void {
locationKeyToHookSourceAndMetadata.forEach( locationKeyToHookSourceAndMetadata.forEach(
(hookSourceAndMetadata, locationKey) => { (hookSourceAndMetadata, locationKey) => {
const hookParsedMetadata = locationKeyToHookParsedMetadata.get( const hookParsedMetadata =
locationKey, locationKeyToHookParsedMetadata.get(locationKey);
);
if (hookParsedMetadata == null) { if (hookParsedMetadata == null) {
throw Error(`Expected to find HookParsedMetadata for "${locationKey}"`); throw Error(`Expected to find HookParsedMetadata for "${locationKey}"`);
} }
@ -250,7 +249,8 @@ function parseSourceAST(
} }
const {metadataConsumer, sourceMapConsumer} = hookParsedMetadata; const {metadataConsumer, sourceMapConsumer} = hookParsedMetadata;
const runtimeSourceCode = ((hookSourceAndMetadata.runtimeSourceCode: any): string); const runtimeSourceCode =
((hookSourceAndMetadata.runtimeSourceCode: any): string);
let hasHookMap = false; let hasHookMap = false;
let originalSourceURL; let originalSourceURL;
let originalSourceCode; let originalSourceCode;
@ -268,12 +268,8 @@ function parseSourceAST(
// Namespace them? // Namespace them?
originalSourceURL = hookSourceAndMetadata.runtimeSourceURL; originalSourceURL = hookSourceAndMetadata.runtimeSourceURL;
} else { } else {
const { const {column, line, sourceContent, sourceURL} =
column, sourceMapConsumer.originalPositionFor({
line,
sourceContent,
sourceURL,
} = sourceMapConsumer.originalPositionFor({
columnNumber, columnNumber,
lineNumber, lineNumber,
}); });
@ -287,7 +283,8 @@ function parseSourceAST(
hookParsedMetadata.originalSourceCode = originalSourceCode; hookParsedMetadata.originalSourceCode = originalSourceCode;
hookParsedMetadata.originalSourceURL = originalSourceURL; hookParsedMetadata.originalSourceURL = originalSourceURL;
hookParsedMetadata.originalSourceLineNumber = originalSourceLineNumber; hookParsedMetadata.originalSourceLineNumber = originalSourceLineNumber;
hookParsedMetadata.originalSourceColumnNumber = originalSourceColumnNumber; hookParsedMetadata.originalSourceColumnNumber =
originalSourceColumnNumber;
if ( if (
metadataConsumer != null && metadataConsumer != null &&
@ -381,9 +378,8 @@ function parseSourceMaps(
) { ) {
locationKeyToHookSourceAndMetadata.forEach( locationKeyToHookSourceAndMetadata.forEach(
(hookSourceAndMetadata, locationKey) => { (hookSourceAndMetadata, locationKey) => {
const hookParsedMetadata = locationKeyToHookParsedMetadata.get( const hookParsedMetadata =
locationKey, locationKeyToHookParsedMetadata.get(locationKey);
);
if (hookParsedMetadata == null) { if (hookParsedMetadata == null) {
throw Error(`Expected to find HookParsedMetadata for "${locationKey}"`); throw Error(`Expected to find HookParsedMetadata for "${locationKey}"`);
} }

View File

@ -132,7 +132,8 @@ export function inspectElement(
InspectedElementFrontend, InspectedElementFrontend,
InspectedElementResponseType, InspectedElementResponseType,
]) => { ]) => {
const resolvedRecord = ((newRecord: any): ResolvedRecord<InspectedElementFrontend>); const resolvedRecord =
((newRecord: any): ResolvedRecord<InspectedElementFrontend>);
resolvedRecord.status = Resolved; resolvedRecord.status = Resolved;
resolvedRecord.value = inspectedElement; resolvedRecord.value = inspectedElement;

View File

@ -39,10 +39,8 @@ import UnknownHookError from 'react-devtools-shared/src/errors/UnknownHookError'
// This doens't work properly though when component filters are changed, // This doens't work properly though when component filters are changed,
// because this will cause the Store to dump all roots and re-initialize the tree (recreating the Element objects). // because this will cause the Store to dump all roots and re-initialize the tree (recreating the Element objects).
// So instead we key on Element ID (which is stable in this case) and use an LRU for eviction. // So instead we key on Element ID (which is stable in this case) and use an LRU for eviction.
const inspectedElementCache: LRUCache< const inspectedElementCache: LRUCache<number, InspectedElementFrontend> =
number, new LRU({
InspectedElementFrontend,
> = new LRU({
max: 25, max: 25,
}); });

View File

@ -39,9 +39,10 @@ type StatefulFunctionProps = {name: string};
function StatefulFunction({name}: StatefulFunctionProps) { function StatefulFunction({name}: StatefulFunctionProps) {
const [count, updateCount] = useState(0); const [count, updateCount] = useState(0);
const debouncedCount = useDebounce(count, 1000); const debouncedCount = useDebounce(count, 1000);
const handleUpdateCountClick = useCallback(() => updateCount(count + 1), [ const handleUpdateCountClick = useCallback(
count, () => updateCount(count + 1),
]); [count],
);
const [data, dispatch] = useReducer(reducer, initialData); const [data, dispatch] = useReducer(reducer, initialData);
const handleUpdateReducerClick = useCallback( const handleUpdateReducerClick = useCallback(
@ -109,9 +110,10 @@ const ForwardRef = forwardRef<{name: string}, HTMLUListElement>(
({name}, ref) => { ({name}, ref) => {
const [count, updateCount] = useState(0); const [count, updateCount] = useState(0);
const debouncedCount = useDebounce(count, 1000); const debouncedCount = useDebounce(count, 1000);
const handleUpdateCountClick = useCallback(() => updateCount(count + 1), [ const handleUpdateCountClick = useCallback(
count, () => updateCount(count + 1),
]); [count],
);
return ( return (
<ul ref={ref}> <ul ref={ref}>
<li>Name: {name}</li> <li>Name: {name}</li>

View File

@ -24,9 +24,9 @@ export default function LargeSubtree(): React.Node {
window.requestAnimationFrame(() => { window.requestAnimationFrame(() => {
const afterRenderTime = performance.now(); const afterRenderTime = performance.now();
console.log( console.log(
`Time spent on ${ `Time spent on ${showList ? 'unmounting' : 'mounting'} the subtree: ${
showList ? 'unmounting' : 'mounting' afterRenderTime - startTime
} the subtree: ${afterRenderTime - startTime}ms`, }ms`,
); );
}); });
}; };

View File

@ -794,9 +794,9 @@ function AutoSizedCanvas({
<ContextMenuItem <ContextMenuItem
onClick={() => onClick={() =>
copy( copy(
`line ${flamechartStackFrame.locationLine ?? `line ${
''}, column ${flamechartStackFrame.locationColumn ?? flamechartStackFrame.locationLine ?? ''
''}`, }, column ${flamechartStackFrame.locationColumn ?? ''}`,
) )
} }
title="Copy location"> title="Copy location">

View File

@ -33,13 +33,8 @@ import {TimelineSearchContextController} from './TimelineSearchContext';
import styles from './Timeline.css'; import styles from './Timeline.css';
export function Timeline(_: {}): React.Node { export function Timeline(_: {}): React.Node {
const { const {file, inMemoryTimelineData, isTimelineSupported, setFile, viewState} =
file, useContext(TimelineContext);
inMemoryTimelineData,
isTimelineSupported,
setFile,
viewState,
} = useContext(TimelineContext);
const {didRecordCommits, isProfiling} = useContext(ProfilerContext); const {didRecordCommits, isProfiling} = useContext(ProfilerContext);
const ref = useRef(null); const ref = useRef(null);

View File

@ -82,8 +82,10 @@ function TimelineContextController({children}: Props): React.Node {
// Recreate view state any time new profiling data is imported. // Recreate view state any time new profiling data is imported.
const viewState = useMemo<ViewState>(() => { const viewState = useMemo<ViewState>(() => {
const horizontalScrollStateChangeCallbacks: Set<HorizontalScrollStateChangeCallback> = new Set(); const horizontalScrollStateChangeCallbacks: Set<HorizontalScrollStateChangeCallback> =
const searchRegExpStateChangeCallbacks: Set<SearchRegExpStateChangeCallback> = new Set(); new Set();
const searchRegExpStateChangeCallbacks: Set<SearchRegExpStateChangeCallback> =
new Set();
const horizontalScrollState = { const horizontalScrollState = {
offset: 0, offset: 0,

View File

@ -92,13 +92,8 @@ export class ComponentMeasuresView extends View {
showHoverHighlight: boolean, showHoverHighlight: boolean,
): boolean { ): boolean {
const {frame} = this; const {frame} = this;
const { const {componentName, duration, timestamp, type, warning} =
componentName, componentMeasure;
duration,
timestamp,
type,
warning,
} = componentMeasure;
const xStart = timestampToPosition(timestamp, scaleFactor, frame); const xStart = timestampToPosition(timestamp, scaleFactor, frame);
const xStop = timestampToPosition(timestamp + duration, scaleFactor, frame); const xStop = timestampToPosition(timestamp + duration, scaleFactor, frame);

View File

@ -203,13 +203,8 @@ export class ReactMeasuresView extends View {
} }
draw(context: CanvasRenderingContext2D): void { draw(context: CanvasRenderingContext2D): void {
const { const {frame, _hoveredMeasure, _lanesToRender, _profilerData, visibleArea} =
frame, this;
_hoveredMeasure,
_lanesToRender,
_profilerData,
visibleArea,
} = this;
context.fillStyle = COLORS.PRIORITY_BACKGROUND; context.fillStyle = COLORS.PRIORITY_BACKGROUND;
context.fillRect( context.fillRect(

View File

@ -27,18 +27,7 @@ export const TEXT_PADDING = 3;
export const SNAPSHOT_SCRUBBER_SIZE = 3; export const SNAPSHOT_SCRUBBER_SIZE = 3;
export const INTERVAL_TIMES = [ export const INTERVAL_TIMES = [
1, 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000,
2,
5,
10,
20,
50,
100,
200,
500,
1000,
2000,
5000,
]; ];
export const MIN_INTERVAL_SIZE_PX = 70; export const MIN_INTERVAL_SIZE_PX = 70;

View File

@ -552,13 +552,9 @@ function processTimelineEvent(
type: 'thrown-error', type: 'thrown-error',
}); });
} else if (name.startsWith('--suspense-suspend-')) { } else if (name.startsWith('--suspense-suspend-')) {
const [ const [id, componentName, phase, laneBitmaskString, promiseName] = name
id, .substr(19)
componentName, .split('-');
phase,
laneBitmaskString,
promiseName,
] = name.substr(19).split('-');
const lanes = getLanesFromTransportDecimalBitmask(laneBitmaskString); const lanes = getLanesFromTransportDecimalBitmask(laneBitmaskString);
const availableDepths = new Array( const availableDepths = new Array(
@ -978,14 +974,22 @@ function preprocessFlamechart(rawData: TimelineEvent[]): Flamechart {
}); });
const flamechart: Flamechart = speedscopeFlamechart.getLayers().map(layer => const flamechart: Flamechart = speedscopeFlamechart.getLayers().map(layer =>
layer.map(({start, end, node: {frame: {name, file, line, col}}}) => ({ layer.map(
({
start,
end,
node: {
frame: {name, file, line, col},
},
}) => ({
name, name,
timestamp: start / 1000, timestamp: start / 1000,
duration: (end - start) / 1000, duration: (end - start) / 1000,
scriptUrl: file, scriptUrl: file,
locationLine: line, locationLine: line,
locationColumn: col, locationColumn: col,
})), }),
),
); );
return flamechart; return flamechart;

View File

@ -79,7 +79,8 @@ export function importFile(file: File): TimelineData | Error {
importFileWorker(file).then(data => { importFileWorker(file).then(data => {
switch (data.status) { switch (data.status) {
case 'SUCCESS': case 'SUCCESS':
const resolvedRecord = ((newRecord: any): ResolvedRecord<TimelineData>); const resolvedRecord =
((newRecord: any): ResolvedRecord<TimelineData>);
resolvedRecord.status = Resolved; resolvedRecord.status = Resolved;
resolvedRecord.value = data.processedData; resolvedRecord.value = data.processedData;
break; break;

View File

@ -44,9 +44,9 @@ export default function useSmartTooltip({
// mouse cursor or finally aligned with the window's top edge. // mouse cursor or finally aligned with the window's top edge.
if (mouseY - TOOLTIP_OFFSET_TOP - element.offsetHeight > 0) { if (mouseY - TOOLTIP_OFFSET_TOP - element.offsetHeight > 0) {
// We position the tooltip above the mouse cursor if it fits there. // We position the tooltip above the mouse cursor if it fits there.
element.style.top = `${mouseY - element.style.top = `${
element.offsetHeight - mouseY - element.offsetHeight - TOOLTIP_OFFSET_TOP
TOOLTIP_OFFSET_TOP}px`; }px`;
} else { } else {
// Otherwise we align the tooltip with the window's top edge. // Otherwise we align the tooltip with the window's top edge.
element.style.top = '0px'; element.style.top = '0px';
@ -64,9 +64,9 @@ export default function useSmartTooltip({
if (mouseX - TOOLTIP_OFFSET_TOP - element.offsetWidth > 0) { if (mouseX - TOOLTIP_OFFSET_TOP - element.offsetWidth > 0) {
// We position the tooltip at the left of the mouse cursor if it fits // We position the tooltip at the left of the mouse cursor if it fits
// there. // there.
element.style.left = `${mouseX - element.style.left = `${
element.offsetWidth - mouseX - element.offsetWidth - TOOLTIP_OFFSET_TOP
TOOLTIP_OFFSET_TOP}px`; }px`;
} else { } else {
// Otherwise, align the tooltip with the window's left edge. // Otherwise, align the tooltip with the window's left edge.
element.style.left = '0px'; element.style.left = '0px';

View File

@ -142,12 +142,10 @@ if (__DEV__) {
if (didWarnInvalidHydration) { if (didWarnInvalidHydration) {
return; return;
} }
const normalizedClientValue = normalizeMarkupForTextOrAttribute( const normalizedClientValue =
clientValue, normalizeMarkupForTextOrAttribute(clientValue);
); const normalizedServerValue =
const normalizedServerValue = normalizeMarkupForTextOrAttribute( normalizeMarkupForTextOrAttribute(serverValue);
serverValue,
);
if (normalizedServerValue === normalizedClientValue) { if (normalizedServerValue === normalizedClientValue) {
return; return;
} }
@ -387,9 +385,8 @@ export function createElement(
// We create tags in the namespace of their parent container, except HTML // We create tags in the namespace of their parent container, except HTML
// tags get no namespace. // tags get no namespace.
const ownerDocument: Document = getOwnerDocumentFromRootContainer( const ownerDocument: Document =
rootContainerElement, getOwnerDocumentFromRootContainer(rootContainerElement);
);
let domElement: Element; let domElement: Element;
let namespaceURI = parentNamespace; let namespaceURI = parentNamespace;
if (namespaceURI === HTML_NAMESPACE) { if (namespaceURI === HTML_NAMESPACE) {

View File

@ -39,9 +39,7 @@ import {
enableHostSingletons, enableHostSingletons,
} from 'shared/ReactFeatureFlags'; } from 'shared/ReactFeatureFlags';
const randomKey = Math.random() const randomKey = Math.random().toString(36).slice(2);
.toString(36)
.slice(2);
const internalInstanceKey = '__reactFiber$' + randomKey; const internalInstanceKey = '__reactFiber$' + randomKey;
const internalPropsKey = '__reactProps$' + randomKey; const internalPropsKey = '__reactProps$' + randomKey;
const internalContainerInstanceKey = '__reactContainer$' + randomKey; const internalContainerInstanceKey = '__reactContainer$' + randomKey;

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