Prettier
Brian Vaughn committed
Aug 13, 2019 at 17:58 UTC
183f96f2ac35c36772781cb37bc3ce842e2dc78b
173 files changed
+3253
-3133
fixtures/devtools/regression/server.js
+1
-1
@@ -5,7 +5,7 @@ const http = require('http');
5
const serveStatic = require('serve-static');
6
7
// Serve fixtures folder
8
-const serve = serveStatic(__dirname, { index: 'index.html' });
8
+const serve = serveStatic(__dirname, {index: 'index.html'});
9
10
// Create server
11
const server = http.createServer(function onRequest(req, res) {
fixtures/devtools/regression/shared.js
+13
-15
@@ -10,7 +10,7 @@ const minor =
10
pieces[0] === '0' ? parseInt(pieces[2], 10) : parseInt(pieces[1], 10);
11
12
// Convenience wrapper to organize API features in DevTools.
13
-function Feature({ children, label, version }) {
13
+function Feature({children, label, version}) {
14
return (
15
<div className="Feature">
16
<div className="FeatureHeader">
@@ -60,10 +60,10 @@ switch (major) {
60
}
61
case 6:
62
// memo
63
- function LabelComponent({ label }) {
63
+ function LabelComponent({label}) {
64
return <label>{label}</label>;
65
}
66
- const AnonymousMemoized = React.memo(({ label }) => (
66
+ const AnonymousMemoized = React.memo(({label}) => (
67
<label>{label}</label>
68
));
69
const Memoized = React.memo(LabelComponent);
@@ -91,8 +91,8 @@ switch (major) {
91
getResourceKey
92
);
93
class Suspending extends React.Component {
94
- state = { useSuspense: false };
95
- useSuspense = () => this.setState({ useSuspense: true });
94
+ state = {useSuspense: false};
95
+ useSuspense = () => this.setState({useSuspense: true});
96
render() {
97
if (this.state.useSuspense) {
98
const text = Resource.read(['loaded', 2000]);
@@ -141,9 +141,9 @@ switch (major) {
141
case 4:
142
// unstable_Profiler
143
class ProfilerChild extends React.Component {
144
- state = { count: 0 };
144
+ state = {count: 0};
145
incrementCount = () =>
146
- this.setState(prevState => ({ count: prevState.count + 1 }));
146
+ this.setState(prevState => ({count: prevState.count + 1}));
147
render() {
148
return (
149
<div>
@@ -159,8 +159,7 @@ switch (major) {
159
<Feature
160
key="unstable_Profiler"
161
label="unstable_Profiler"
162
- version="16.4+"
163
- >
162
+ version="16.4+">
163
<Profiler id="count" onRender={onRender}>
164
<div>
165
<ProfilerChild />
@@ -230,8 +229,7 @@ switch (major) {
229
<Feature
230
key="AsyncMode/ConcurrentMode"
231
label="AsyncMode/ConcurrentMode"
233
- version="16.3+"
234
- >
232
+ version="16.3+">
233
<ConcurrentMode>
234
<div>
235
unstable_AsyncMode was added in 16.3, renamed to
@@ -271,13 +269,13 @@ function Even() {
269
270
// Simple stateful app shared by all React versions
271
class SimpleApp extends React.Component {
274
- state = { count: 0 };
272
+ state = {count: 0};
273
incrementCount = () => {
276
- const updaterFn = prevState => ({ count: prevState.count + 1 });
274
+ const updaterFn = prevState => ({count: prevState.count + 1});
275
trace('Updating count', performance.now(), () => this.setState(updaterFn));
276
};
277
render() {
280
- const { count } = this.state;
278
+ const {count} = this.state;
279
return (
280
<div>
281
{count % 2 === 0 ? (
@@ -299,7 +297,7 @@ apps.push(
297
);
298
299
// This component, with the version prop, helps organize DevTools at a glance.
302
-function TopLevelWrapperForDevTools({ version }) {
300
+function TopLevelWrapperForDevTools({version}) {
301
let header = <h1>React {version}</h1>;
302
if (version.includes('canary')) {
303
const commitSha = version.match(/.+canary-(.+)/)[1];
fixtures/devtools/shell/app/DeeplyNestedComponents/index.js
+1
-1
@@ -1,6 +1,6 @@
1
// @flow
2
3
-import React, { Fragment } from 'react';
3
+import React, {Fragment} from 'react';
4
5
function wrapWithHoc(Component, index) {
6
function HOC() {
fixtures/devtools/shell/app/EditableProps/index.js
+10
-10
@@ -13,20 +13,20 @@ import React, {
13
useState,
14
} from 'react';
15
16
-const initialData = { foo: 'FOO', bar: 'BAR' };
16
+const initialData = {foo: 'FOO', bar: 'BAR'};
17
18
function reducer(state, action) {
19
switch (action.type) {
20
case 'swap':
21
- return { foo: state.bar, bar: state.foo };
21
+ return {foo: state.bar, bar: state.foo};
22
default:
23
throw new Error();
24
}
25
}
26
27
-type StatefulFunctionProps = {| name: string |};
27
+type StatefulFunctionProps = {|name: string|};
28
29
-function StatefulFunction({ name }: StatefulFunctionProps) {
29
+function StatefulFunction({name}: StatefulFunctionProps) {
30
const [count, updateCount] = useState(0);
31
const debouncedCount = useDebounce(count, 1000);
32
const handleUpdateCountClick = useCallback(() => updateCount(count + 1), [
@@ -35,7 +35,7 @@ function StatefulFunction({ name }: StatefulFunctionProps) {
35
36
const [data, dispatch] = useReducer(reducer, initialData);
37
const handleUpdateReducerClick = useCallback(
38
- () => dispatch({ type: 'swap' }),
38
+ () => dispatch({type: 'swap'}),
39
[]
40
);
41
@@ -60,8 +60,8 @@ function StatefulFunction({ name }: StatefulFunctionProps) {
60
const BoolContext = createContext(true);
61
BoolContext.displayName = 'BoolContext';
62
63
-type Props = {| name: string, toggle: boolean |};
64
-type State = {| cities: Array<string>, state: string |};
63
+type Props = {|name: string, toggle: boolean|};
64
+type State = {|cities: Array<string>, state: string|};
65
66
class StatefulClass extends Component<Props, State> {
67
static contextType = BoolContext;
@@ -71,7 +71,7 @@ class StatefulClass extends Component<Props, State> {
71
state: 'California',
72
};
73
74
- handleChange = ({ target }) =>
74
+ handleChange = ({target}) =>
75
this.setState({
76
state: target.value,
77
});
@@ -94,8 +94,8 @@ class StatefulClass extends Component<Props, State> {
94
const MemoizedStatefulClass = memo(StatefulClass);
95
const MemoizedStatefulFunction = memo(StatefulFunction);
96
97
-const ForwardRef = forwardRef<{| name: string |}, HTMLUListElement>(
98
- ({ name }, ref) => {
97
+const ForwardRef = forwardRef<{|name: string|}, HTMLUListElement>(
98
+ ({name}, ref) => {
99
const [count, updateCount] = useState(0);
100
const debouncedCount = useDebounce(count, 1000);
101
const handleUpdateCountClick = useCallback(() => updateCount(count + 1), [
fixtures/devtools/shell/app/Hydration/index.js
+2
-2
@@ -1,6 +1,6 @@
1
// @flow
2
3
-import React, { Fragment, useDebugValue, useState } from 'react';
3
+import React, {Fragment, useDebugValue, useState} from 'react';
4
5
const div = document.createElement('div');
6
const exmapleFunction = () => {};
@@ -110,7 +110,7 @@ export default function Hydration() {
110
);
111
}
112
113
-function DehydratableProps({ array, object }: any) {
113
+function DehydratableProps({array, object}: any) {
114
return (
115
<ul>
116
<li>array: {JSON.stringify(array, null, 2)}</li>
fixtures/devtools/shell/app/Iframe/index.js
+2
-2
@@ -1,6 +1,6 @@
1
/** @flow */
2
3
-import React, { Fragment } from 'react';
3
+import React, {Fragment} from 'react';
4
import ReactDOM from 'react-dom';
5
6
export default function Iframe() {
@@ -16,7 +16,7 @@ export default function Iframe() {
16
);
17
}
18
19
-const iframeStyle = { border: '2px solid #eee', height: 80 };
19
+const iframeStyle = {border: '2px solid #eee', height: 80};
20
21
function Frame(props) {
22
const [element, setElement] = React.useState(null);
fixtures/devtools/shell/app/InspectableElements/Contexts.js
+2
-2
@@ -1,6 +1,6 @@
1
// @flow
2
3
-import React, { createContext, Component, Fragment, useContext } from 'react';
3
+import React, {createContext, Component, Fragment, useContext} from 'react';
4
import PropTypes from 'prop-types';
5
6
function someNamedFunction() {}
@@ -10,7 +10,7 @@ const contextData = {
10
bool: true,
11
func: someNamedFunction,
12
number: 123,
13
- object: { outer: { inner: {} } },
13
+ object: {outer: {inner: {}}},
14
string: 'abc',
15
symbol: Symbol.for('symbol'),
16
null: null,
fixtures/devtools/shell/app/InspectableElements/CustomHooks.js
+1
-1
@@ -17,7 +17,7 @@ const object = {
17
null: null,
18
undefined: undefined,
19
array: ['a', 'b', 'c'],
20
- object: { foo: 1, bar: 2, baz: 3 },
20
+ object: {foo: 1, bar: 2, baz: 3},
21
};
22
23
function useNestedInnerHook() {
fixtures/devtools/shell/app/InspectableElements/InspectableElements.js
+1
-1
@@ -1,6 +1,6 @@
1
// @flow
2
3
-import React, { Fragment } from 'react';
3
+import React, {Fragment} from 'react';
4
import Contexts from './Contexts';
5
import CustomHooks from './CustomHooks';
6
import CustomObject from './CustomObject';
fixtures/devtools/shell/app/InspectableElements/NestedProps.js
+1
-1
@@ -22,7 +22,7 @@ export default function ObjectProps() {
22
}}
23
array={['first', 'second', 'third']}
24
objectInArray={[object]}
25
- arrayInObject={{ array: ['first', 'second', 'third'] }}
25
+ arrayInObject={{array: ['first', 'second', 'third']}}
26
deepObject={{
27
// Known limitation: we won't go deeper than several levels.
28
// In the future, we might offer a way to request deeper access on demand.
fixtures/devtools/shell/app/InteractionTracing/index.js
+53
-41
@@ -1,7 +1,7 @@
1
// @flow
2
3
-import React, { Fragment, useCallback, useEffect, useState } from 'react';
4
-import { unstable_batchedUpdates as batchedUpdates } from 'react-dom';
3
+import React, {Fragment, useCallback, useEffect, useState} from 'react';
4
+import {unstable_batchedUpdates as batchedUpdates} from 'react-dom';
5
import {
6
unstable_trace as trace,
7
unstable_wrap as wrap,
@@ -11,54 +11,66 @@ export default function InteractionTracing() {
11
const [count, setCount] = useState(0);
12
const [shouldCascade, setShouldCascade] = useState(false);
13
14
- const handleUpdate = useCallback(() => {
15
- trace('count', performance.now(), () => {
16
- setTimeout(
17
- wrap(() => {
18
- setCount(count + 1);
19
- }),
20
- count * 100
21
- );
22
- });
23
- }, [count]);
24
-
25
- const handleCascadingUpdate = useCallback(() => {
26
- trace('cascade', performance.now(), () => {
27
- setTimeout(
28
- wrap(() => {
29
- batchedUpdates(() => {
14
+ const handleUpdate = useCallback(
15
+ () => {
16
+ trace('count', performance.now(), () => {
17
+ setTimeout(
18
+ wrap(() => {
19
setCount(count + 1);
31
- setShouldCascade(true);
32
- });
33
- }),
34
- count * 100
35
- );
36
- });
37
- }, [count]);
20
+ }),
21
+ count * 100
22
+ );
23
+ });
24
+ },
25
+ [count]
26
+ );
27
39
- const handleMultiple = useCallback(() => {
40
- trace('first', performance.now(), () => {
41
- trace('second', performance.now(), () => {
28
+ const handleCascadingUpdate = useCallback(
29
+ () => {
30
+ trace('cascade', performance.now(), () => {
31
setTimeout(
32
wrap(() => {
44
- setCount(count + 1);
33
+ batchedUpdates(() => {
34
+ setCount(count + 1);
35
+ setShouldCascade(true);
36
+ });
37
}),
38
count * 100
39
);
40
});
49
- });
50
- }, [count]);
41
+ },
42
+ [count]
43
+ );
44
52
- useEffect(() => {
53
- if (shouldCascade) {
54
- setTimeout(
55
- wrap(() => {
56
- setShouldCascade(false);
57
- }),
58
- count * 100
59
- );
60
- }
61
- }, [count, shouldCascade]);
45
+ const handleMultiple = useCallback(
46
+ () => {
47
+ trace('first', performance.now(), () => {
48
+ trace('second', performance.now(), () => {
49
+ setTimeout(
50
+ wrap(() => {
51
+ setCount(count + 1);
52
+ }),
53
+ count * 100
54
+ );
55
+ });
56
+ });
57
+ },
58
+ [count]
59
+ );
60
+
61
+ useEffect(
62
+ () => {
63
+ if (shouldCascade) {
64
+ setTimeout(
65
+ wrap(() => {
66
+ setShouldCascade(false);
67
+ }),
68
+ count * 100
69
+ );
70
+ }
71
+ },
72
+ [count, shouldCascade]
73
+ );
74
75
return (
76
<Fragment>
fixtures/devtools/shell/app/PriorityLevels/index.js
+1
-1
@@ -1,6 +1,6 @@
1
// @flow
2
3
-import React, { Fragment, useCallback, useState } from 'react';
3
+import React, {Fragment, useCallback, useState} from 'react';
4
import {
5
unstable_IdlePriority as IdlePriority,
6
unstable_LowPriority as LowPriority,
fixtures/devtools/shell/app/ReactNativeWeb/index.js
+4
-4
@@ -1,7 +1,7 @@
1
// @flow
2
3
-import React, { Fragment, useState } from 'react';
4
-import { Button, Text, View } from 'react-native-web';
3
+import React, {Fragment, useState} from 'react';
4
+import {Button, Text, View} from 'react-native-web';
5
6
export default function ReactNativeWeb() {
7
const [backgroundColor, setBackgroundColor] = useState('blue');
@@ -17,13 +17,13 @@ export default function ReactNativeWeb() {
17
'\u0623\u062D\u0628 \u0627\u0644\u0644\u063A\u0629 \u0627\u0644\u0639\u0631\u0628\u064A\u0629 auto (default) - arabic RTL'
18
}
19
</Text>
20
- <Text style={{ textAlign: 'left' }}>
20
+ <Text style={{textAlign: 'left'}}>
21
left left left left left left left left left left left left left left
22
left
23
</Text>
24
<Button
25
onPress={toggleColor}
26
- style={{ backgroundColor }}
26
+ style={{backgroundColor}}
27
title={`Switch background color to "${
28
backgroundColor === 'purple' ? 'green' : 'purple'
29
}"`}
fixtures/devtools/shell/app/SuspenseTree/index.js
+7
-8
@@ -1,6 +1,6 @@
1
// @flow
2
3
-import React, { Fragment, Suspense, useState } from 'react';
3
+import React, {Fragment, Suspense, useState} from 'react';
4
5
function SuspenseTree() {
6
return (
@@ -15,7 +15,7 @@ function SuspenseTree() {
15
);
16
}
17
18
-function PrimaryFallbackTest({ initialSuspend }) {
18
+function PrimaryFallbackTest({initialSuspend}) {
19
const [suspend, setSuspend] = useState(initialSuspend);
20
const fallbackStep = useTestSequence('fallback', Fallback1, Fallback2);
21
const primaryStep = useTestSequence('primary', Primary1, Primary2);
@@ -101,8 +101,7 @@ function LoadLater() {
101
<Suspense
102
fallback={
103
<Fallback1 onClick={() => setLoadChild(true)}>Click to load</Fallback1>
104
- }
105
- >
104
+ }>
105
{loadChild ? (
106
<Primary1 onClick={() => setLoadChild(false)}>
107
Loaded! Click to suspend again.
@@ -118,19 +117,19 @@ function Never() {
117
throw new Promise(resolve => {});
118
}
119
121
-function Fallback1({ prop, ...rest }: any) {
120
+function Fallback1({prop, ...rest}: any) {
121
return <span {...rest} />;
122
}
123
125
-function Fallback2({ prop, ...rest }: any) {
124
+function Fallback2({prop, ...rest}: any) {
125
return <span {...rest} />;
126
}
127
129
-function Primary1({ prop, ...rest }: any) {
128
+function Primary1({prop, ...rest}: any) {
129
return <span {...rest} />;
130
}
131
133
-function Primary2({ prop, ...rest }: any) {
132
+function Primary2({prop, ...rest}: any) {
133
return <span {...rest} />;
134
}
135
fixtures/devtools/shell/app/ToDoList/List.js
+22
-20
@@ -1,6 +1,6 @@
1
// @flow
2
3
-import React, { Fragment, useCallback, useState } from 'react';
3
+import React, {Fragment, useCallback, useState} from 'react';
4
import ListItem from './ListItem';
5
import styles from './List.css';
6
@@ -15,26 +15,29 @@ type Props = {||};
15
export default function List(props: Props) {
16
const [newItemText, setNewItemText] = useState<string>('');
17
const [items, setItems] = useState<Array<Item>>([
18
- { id: 1, isComplete: true, text: 'First' },
19
- { id: 2, isComplete: true, text: 'Second' },
20
- { id: 3, isComplete: false, text: 'Third' },
18
+ {id: 1, isComplete: true, text: 'First'},
19
+ {id: 2, isComplete: true, text: 'Second'},
20
+ {id: 3, isComplete: false, text: 'Third'},
21
]);
22
const [uid, setUID] = useState<number>(4);
23
24
- const handleClick = useCallback(() => {
25
- if (newItemText !== '') {
26
- setItems([
27
- ...items,
28
- {
29
- id: uid,
30
- isComplete: false,
31
- text: newItemText,
32
- },
33
- ]);
34
- setUID(uid + 1);
35
- setNewItemText('');
36
- }
37
- }, [newItemText, items, uid]);
24
+ const handleClick = useCallback(
25
+ () => {
26
+ if (newItemText !== '') {
27
+ setItems([
28
+ ...items,
29
+ {
30
+ id: uid,
31
+ isComplete: false,
32
+ text: newItemText,
33
+ },
34
+ ]);
35
+ setUID(uid + 1);
36
+ setNewItemText('');
37
+ }
38
+ },
39
+ [newItemText, items, uid]
40
+ );
41
42
const handleKeyPress = useCallback(
43
event => {
@@ -88,8 +91,7 @@ export default function List(props: Props) {
91
<button
92
className={styles.IconButton}
93
disabled={newItemText === ''}
91
- onClick={handleClick}
92
- >
94
+ onClick={handleClick}>
95
<span role="img" aria-label="Add item">
96
➕
97
</span>
fixtures/devtools/shell/app/ToDoList/ListItem.js
+15
-9
@@ -1,9 +1,9 @@
1
// @flow
2
3
-import React, { memo, useCallback } from 'react';
3
+import React, {memo, useCallback} from 'react';
4
import styles from './ListItem.css';
5
6
-import type { Item } from './List';
6
+import type {Item} from './List';
7
8
type Props = {|
9
item: Item,
@@ -11,14 +11,20 @@ type Props = {|
11
toggleItem: (item: Item) => void,
12
|};
13
14
-function ListItem({ item, removeItem, toggleItem }: Props) {
15
- const handleDelete = useCallback(() => {
16
- removeItem(item);
17
- }, [item, removeItem]);
14
+function ListItem({item, removeItem, toggleItem}: Props) {
15
+ const handleDelete = useCallback(
16
+ () => {
17
+ removeItem(item);
18
+ },
19
+ [item, removeItem]
20
+ );
21
19
- const handleToggle = useCallback(() => {
20
- toggleItem(item);
21
- }, [item, toggleItem]);
22
+ const handleToggle = useCallback(
23
+ () => {
24
+ toggleItem(item);
25
+ },
26
+ [item, toggleItem]
27
+ );
28
29
return (
30
<li className={styles.ListItem}>
fixtures/devtools/shell/app/Toggle/index.js
+2
-2
@@ -1,4 +1,4 @@
1
-import React, { useState } from 'react';
1
+import React, {useState} from 'react';
2
3
export default function Toggle() {
4
const [show, setShow] = useState(false);
@@ -16,6 +16,6 @@ export default function Toggle() {
16
);
17
}
18
19
-function Greeting({ children }) {
19
+function Greeting({children}) {
20
return <p>{children}</p>;
21
}
fixtures/devtools/shell/app/index.js
+2
-2
@@ -2,7 +2,7 @@
2
3
// This test harness mounts each test app as a separate root to test multi-root applications.
4
5
-import { createElement } from 'react';
5
+import {createElement} from 'react';
6
import {
7
// $FlowFixMe Flow does not yet know about createRoot()
8
unstable_createRoot as createRoot,
@@ -19,7 +19,7 @@ import ReactNativeWeb from './ReactNativeWeb';
19
import ToDoList from './ToDoList';
20
import Toggle from './Toggle';
21
import SuspenseTree from './SuspenseTree';
22
-import { ignoreErrors, ignoreWarnings } from './console';
22
+import {ignoreErrors, ignoreWarnings} from './console';
23
24
import './styles.css';
25
fixtures/devtools/shell/src/devtools.js
+5
-5
@@ -1,18 +1,18 @@
1
/** @flow */
2
3
-import { createElement } from 'react';
3
+import {createElement} from 'react';
4
// $FlowFixMe Flow does not yet know about createRoot()
5
-import { unstable_createRoot as createRoot } from 'react-dom';
5
+import {unstable_createRoot as createRoot} from 'react-dom';
6
import {
7
activate as activateBackend,
8
initialize as initializeBackend,
9
} from 'react-devtools-inline/backend';
10
-import { initialize as initializeFrontend } from 'react-devtools-inline/frontend';
11
-import { initDevTools } from 'src/devtools';
10
+import {initialize as initializeFrontend} from 'react-devtools-inline/frontend';
11
+import {initDevTools} from 'src/devtools';
12
13
const iframe = ((document.getElementById('target'): any): HTMLIFrameElement);
14
15
-const { contentDocument, contentWindow } = iframe;
15
+const {contentDocument, contentWindow} = iframe;
16
17
// Helps with positioning Overlay UI.
18
contentWindow.__REACT_DEVTOOLS_TARGET_WINDOW__ = window;
fixtures/devtools/shell/webpack.config.js
+3
-3
@@ -1,6 +1,6 @@
1
-const { resolve } = require('path');
2
-const { DefinePlugin } = require('webpack');
3
-const { getGitHubURL, getVersionString } = require('../utils');
1
+const {resolve} = require('path');
2
+const {DefinePlugin} = require('webpack');
3
+const {getGitHubURL, getVersionString} = require('../utils');
4
5
const NODE_ENV = process.env.NODE_ENV;
6
if (!NODE_ENV) {
packages/react-devtools-core/src/backend.js
+25
-22
@@ -2,16 +2,16 @@
2
3
import Agent from 'react-devtools-shared/src/backend/agent';
4
import Bridge from 'react-devtools-shared/src/bridge';
5
-import { installHook } from 'react-devtools-shared/src/hook';
6
-import { initBackend } from 'react-devtools-shared/src/backend';
7
-import { __DEBUG__ } from 'react-devtools-shared/src/constants';
5
+import {installHook} from 'react-devtools-shared/src/hook';
6
+import {initBackend} from 'react-devtools-shared/src/backend';
7
+import {__DEBUG__} from 'react-devtools-shared/src/constants';
8
import setupNativeStyleEditor from 'react-devtools-shared/src/backend/NativeStyleEditor/setupNativeStyleEditor';
9
-import { getDefaultComponentFilters } from 'react-devtools-shared/src/utils';
9
+import {getDefaultComponentFilters} from 'react-devtools-shared/src/utils';
10
11
-import type { BackendBridge } from 'react-devtools-shared/src/bridge';
12
-import type { ComponentFilter } from 'react-devtools-shared/src/types';
13
-import type { DevToolsHook } from 'react-devtools-shared/src/backend/types';
14
-import type { ResolveNativeStyle } from 'react-devtools-shared/src/backend/NativeStyleEditor/setupNativeStyleEditor';
11
+import type {BackendBridge} from 'react-devtools-shared/src/bridge';
12
+import type {ComponentFilter} from 'react-devtools-shared/src/types';
13
+import type {DevToolsHook} from 'react-devtools-shared/src/backend/types';
14
+import type {ResolveNativeStyle} from 'react-devtools-shared/src/backend/NativeStyleEditor/setupNativeStyleEditor';
15
16
type ConnectOptions = {
17
host?: string,
@@ -26,7 +26,9 @@ installHook(window);
26
27
const hook: DevToolsHook = window.__REACT_DEVTOOLS_GLOBAL_HOOK__;
28
29
-let savedComponentFilters: Array<ComponentFilter> = getDefaultComponentFilters();
29
+let savedComponentFilters: Array<
30
+ ComponentFilter,
31
+> = getDefaultComponentFilters();
32
33
function debug(methodName: string, ...args) {
34
if (__DEBUG__) {
@@ -34,7 +36,7 @@ function debug(methodName: string, ...args) {
36
`%c[core/backend] %c${methodName}`,
37
'color: teal; font-weight: bold;',
38
'font-weight: bold;',
37
- ...args
39
+ ...args,
40
);
41
}
42
}
@@ -47,7 +49,8 @@ export function connectToDevTools(options: ?ConnectOptions) {
49
websocket,
50
resolveRNStyle = null,
51
isAppActive = () => true,
50
- } = options || {};
52
+ } =
53
+ options || {};
54
55
let retryTimeoutID: TimeoutID | null = null;
56
@@ -94,12 +97,12 @@ export function connectToDevTools(options: ?ConnectOptions) {
97
debug('wall.send()', event, payload);
98
}
99
97
- ws.send(JSON.stringify({ event, payload }));
100
+ ws.send(JSON.stringify({event, payload}));
101
} else {
102
if (__DEBUG__) {
103
debug(
104
'wall.send()',
102
- 'Shutting down bridge because of closed WebSocket connection'
105
+ 'Shutting down bridge because of closed WebSocket connection',
106
);
107
}
108
@@ -113,18 +116,18 @@ export function connectToDevTools(options: ?ConnectOptions) {
116
});
117
bridge.addListener(
118
'inspectElement',
116
- ({ id, rendererID }: { id: number, rendererID: number }) => {
119
+ ({id, rendererID}: {id: number, rendererID: number}) => {
120
const renderer = agent.rendererInterfaces[rendererID];
121
if (renderer != null) {
122
// Send event for RN to highlight.
123
const nodes: ?Array<HTMLElement> = renderer.findNativeNodesForFiberID(
121
- id
124
+ id,
125
);
126
if (nodes != null && nodes[0] != null) {
127
agent.emit('showNativeHighlight', nodes[0]);
128
}
129
}
127
- }
130
+ },
131
);
132
bridge.addListener(
133
'updateComponentFilters',
@@ -133,7 +136,7 @@ export function connectToDevTools(options: ?ConnectOptions) {
136
// In that case, the renderer will already be using the updated values.
137
// We'll lose these in between backend reloads but that can't be helped.
138
savedComponentFilters = componentFilters;
136
- }
139
+ },
140
);
141
142
// The renderer interface doesn't read saved component filters directly,
@@ -166,7 +169,7 @@ export function connectToDevTools(options: ?ConnectOptions) {
169
((resolveRNStyle || hook.resolveRNStyle: any): ResolveNativeStyle),
170
nativeStyleEditorValidAttributes ||
171
hook.nativeStyleEditorValidAttributes ||
169
- null
172
+ null,
173
);
174
} else {
175
// Otherwise listen to detect if the environment later supports it.
@@ -181,7 +184,7 @@ export function connectToDevTools(options: ?ConnectOptions) {
184
bridge,
185
agent,
186
lazyResolveRNStyle,
184
- lazyNativeStyleEditorValidAttributes
187
+ lazyNativeStyleEditorValidAttributes,
188
);
189
}
190
};
@@ -198,7 +201,7 @@ export function connectToDevTools(options: ?ConnectOptions) {
201
lazyResolveRNStyle = value;
202
initAfterTick();
203
},
201
- }: Object)
204
+ }: Object),
205
);
206
Object.defineProperty(
207
hook,
@@ -212,7 +215,7 @@ export function connectToDevTools(options: ?ConnectOptions) {
215
lazyNativeStyleEditorValidAttributes = value;
216
initAfterTick();
217
},
215
- }: Object)
218
+ }: Object),
219
);
220
}
221
};
@@ -250,7 +253,7 @@ export function connectToDevTools(options: ?ConnectOptions) {
253
}
254
} catch (e) {
255
console.error(
253
- '[React DevTools] Failed to parse JSON: ' + String(event.data)
256
+ '[React DevTools] Failed to parse JSON: ' + String(event.data),
257
);
258
return;
259
}
packages/react-devtools-core/src/editor.js
+9
-9
@@ -1,9 +1,9 @@
1
// @flow
2
3
-import { existsSync } from 'fs';
4
-import { basename, join, isAbsolute } from 'path';
5
-import { execSync, spawn } from 'child_process';
6
-import { parse } from 'shell-quote';
3
+import {existsSync} from 'fs';
4
+import {basename, join, isAbsolute} from 'path';
5
+import {execSync, spawn} from 'child_process';
6
+import {parse} from 'shell-quote';
7
8
function isTerminalEditor(editor: string): boolean {
9
switch (editor) {
@@ -33,7 +33,7 @@ const COMMON_EDITORS = {
33
function getArgumentsForLineNumber(
34
editor: string,
35
filePath: string,
36
- lineNumber: number
36
+ lineNumber: number,
37
): Array<string> {
38
switch (basename(editor)) {
39
case 'vim':
@@ -104,7 +104,7 @@ let childProcess = null;
104
105
export function getValidFilePath(
106
maybeRelativePath: string,
107
- absoluteProjectRoots: Array<string>
107
+ absoluteProjectRoots: Array<string>,
108
): string | null {
109
// We use relative paths at Facebook with deterministic builds.
110
// This is why our internal tooling calls React DevTools with absoluteProjectRoots.
@@ -128,7 +128,7 @@ export function getValidFilePath(
128
129
export function doesFilePathExist(
130
maybeRelativePath: string,
131
- absoluteProjectRoots: Array<string>
131
+ absoluteProjectRoots: Array<string>,
132
): boolean {
133
return getValidFilePath(maybeRelativePath, absoluteProjectRoots) !== null;
134
}
@@ -136,7 +136,7 @@ export function doesFilePathExist(
136
export function launchEditor(
137
maybeRelativePath: string,
138
lineNumber: number,
139
- absoluteProjectRoots: Array<string>
139
+ absoluteProjectRoots: Array<string>,
140
) {
141
const filePath = getValidFilePath(maybeRelativePath, absoluteProjectRoots);
142
if (filePath === null) {
@@ -174,7 +174,7 @@ export function launchEditor(
174
stdio: 'inherit',
175
});
176
} else {
177
- childProcess = spawn(editor, args, { stdio: 'inherit' });
177
+ childProcess = spawn(editor, args, {stdio: 'inherit'});
178
}
179
childProcess.on('error', function() {});
180
childProcess.on('exit', function(errorCode) {
packages/react-devtools-core/src/standalone.js
+26
-23
@@ -1,6 +1,6 @@
1
// @flow
2
3
-import { createElement } from 'react';
3
+import {createElement} from 'react';
4
import {
5
// $FlowFixMe Flow does not yet know about flushSync()
6
flushSync,
@@ -9,16 +9,19 @@ import {
9
} from 'react-dom';
10
import Bridge from 'react-devtools-shared/src/bridge';
11
import Store from 'react-devtools-shared/src/devtools/store';
12
-import { getSavedComponentFilters, getAppendComponentStack } from 'react-devtools-shared/src/utils';
13
-import { Server } from 'ws';
14
-import { existsSync, readFileSync } from 'fs';
15
-import { installHook } from 'react-devtools-shared/src/hook';
12
+import {
13
+ getSavedComponentFilters,
14
+ getAppendComponentStack,
15
+} from 'react-devtools-shared/src/utils';
16
+import {Server} from 'ws';
17
+import {existsSync, readFileSync} from 'fs';
18
+import {installHook} from 'react-devtools-shared/src/hook';
19
import DevTools from 'react-devtools-shared/src/devtools/views/DevTools';
17
-import { doesFilePathExist, launchEditor } from './editor';
18
-import { __DEBUG__ } from 'react-devtools-shared/src/constants';
20
+import {doesFilePathExist, launchEditor} from './editor';
21
+import {__DEBUG__} from 'react-devtools-shared/src/constants';
22
20
-import type { FrontendBridge } from 'react-devtools-shared/src/bridge';
21
-import type { InspectedElement } from 'react-devtools-shared/src/devtools/views/Components/types';
23
+import type {FrontendBridge} from 'react-devtools-shared/src/bridge';
24
+import type {InspectedElement} from 'react-devtools-shared/src/devtools/views/Components/types';
25
26
installHook(window);
27
@@ -71,7 +74,7 @@ function debug(methodName: string, ...args) {
74
`%c[core/standalone] %c${methodName}`,
75
'color: teal; font-weight: bold;',
76
'font-weight: bold;',
74
- ...args
77
+ ...args,
78
);
79
}
80
}
@@ -101,13 +104,13 @@ function reload() {
104
store: ((store: any): Store),
105
warnIfLegacyBackendDetected: true,
106
viewElementSourceFunction,
104
- })
107
+ }),
108
);
109
}, 100);
110
}
111
112
function canViewElementSourceFunction(
110
- inspectedElement: InspectedElement
113
+ inspectedElement: InspectedElement,
114
): boolean {
115
if (
116
inspectedElement.canViewSource === false ||
@@ -116,16 +119,16 @@ function canViewElementSourceFunction(
119
return false;
120
}
121
119
- const { source } = inspectedElement;
122
+ const {source} = inspectedElement;
123
124
return doesFilePathExist(source.fileName, projectRoots);
125
}
126
127
function viewElementSourceFunction(
128
id: number,
126
- inspectedElement: InspectedElement
129
+ inspectedElement: InspectedElement,
130
): void {
128
- const { source } = inspectedElement;
131
+ const {source} = inspectedElement;
132
if (source !== null) {
133
launchEditor(source.fileName, source.lineNumber, projectRoots);
134
} else {
@@ -139,7 +142,7 @@ function onDisconnected() {
142
node.innerHTML = nodeWaitingToConnectHTML;
143
}
144
142
-function onError({ code, message }) {
145
+function onError({code, message}) {
146
safeUnmount();
147
148
if (code === 'EADDRINUSE') {
@@ -189,7 +192,7 @@ function initialize(socket: WebSocket) {
192
},
193
send(event: string, payload: any, transferable?: Array<any>) {
194
if (socket.readyState === socket.OPEN) {
192
- socket.send(JSON.stringify({ event, payload }));
195
+ socket.send(JSON.stringify({event, payload}));
196
}
197
},
198
});
@@ -197,7 +200,7 @@ function initialize(socket: WebSocket) {
200
socket.close();
201
});
202
200
- store = new Store(bridge, { supportsNativeInspection: false });
203
+ store = new Store(bridge, {supportsNativeInspection: false});
204
205
log('Connected');
206
reload();
@@ -225,14 +228,14 @@ function connectToSocket(socket: WebSocket) {
228
229
function startServer(port?: number = 8097) {
230
const httpServer = require('http').createServer();
228
- const server = new Server({ server: httpServer });
231
+ const server = new Server({server: httpServer});
232
let connected: WebSocket | null = null;
233
server.on('connection', (socket: WebSocket) => {
234
if (connected !== null) {
235
connected.close();
236
log.warn(
237
'Only one connection allowed at a time.',
235
- 'Closing the previous connection'
238
+ 'Closing the previous connection',
239
);
240
}
241
connected = socket;
@@ -271,10 +274,10 @@ function startServer(port?: number = 8097) {
274
// This will ensure that saved filters are shared across different web pages.
275
const savedPreferencesString = `
276
window.__REACT_DEVTOOLS_COMPONENT_FILTERS__ = ${JSON.stringify(
274
- getSavedComponentFilters()
277
+ getSavedComponentFilters(),
278
)};
279
window.__REACT_DEVTOOLS_APPEND_COMPONENT_STACK__ = ${JSON.stringify(
277
- getAppendComponentStack()
280
+ getAppendComponentStack(),
281
)};`;
282
283
response.end(
@@ -282,7 +285,7 @@ function startServer(port?: number = 8097) {
285
'\n;' +
286
backendFile.toString() +
287
'\n;' +
285
- 'ReactDevToolsBackend.connectToDevTools();'
288
+ 'ReactDevToolsBackend.connectToDevTools();',
289
);
290
});
291
packages/react-devtools-core/webpack.backend.js
+3
-3
@@ -1,6 +1,6 @@
1
-const { resolve } = require('path');
2
-const { DefinePlugin } = require('webpack');
3
-const { getGitHubURL, getVersionString } = require('../../shells/utils');
1
+const {resolve} = require('path');
2
+const {DefinePlugin} = require('webpack');
3
+const {getGitHubURL, getVersionString} = require('../../shells/utils');
4
5
const NODE_ENV = process.env.NODE_ENV;
6
if (!NODE_ENV) {
packages/react-devtools-core/webpack.standalone.js
+3
-3
@@ -1,6 +1,6 @@
1
-const { resolve } = require('path');
2
-const { DefinePlugin } = require('webpack');
3
-const { getGitHubURL, getVersionString } = require('../../shells/utils');
1
+const {resolve} = require('path');
2
+const {DefinePlugin} = require('webpack');
3
+const {getGitHubURL, getVersionString} = require('../../shells/utils');
4
5
const NODE_ENV = process.env.NODE_ENV;
6
if (!NODE_ENV) {
packages/react-devtools-extensions/babel.config.js
+3
-3
@@ -4,7 +4,7 @@ const firefoxManifest = require('./shells/browser/firefox/manifest.json');
4
const minChromeVersion = parseInt(chromeManifest.minimum_chrome_version, 10);
5
const minFirefoxVersion = parseInt(
6
firefoxManifest.applications.gecko.strict_min_version,
7
- 10
7
+ 10,
8
);
9
validateVersion(minChromeVersion);
10
validateVersion(minFirefoxVersion);
@@ -30,7 +30,7 @@ module.exports = api => {
30
}
31
const plugins = [
32
['@babel/plugin-transform-flow-strip-types'],
33
- ['@babel/plugin-proposal-class-properties', { loose: false }],
33
+ ['@babel/plugin-proposal-class-properties', {loose: false}],
34
];
35
if (process.env.NODE_ENV !== 'production') {
36
plugins.push(['@babel/plugin-transform-react-jsx-source']);
@@ -38,7 +38,7 @@ module.exports = api => {
38
return {
39
plugins,
40
presets: [
41
- ['@babel/preset-env', { targets }],
41
+ ['@babel/preset-env', {targets}],
42
'@babel/preset-react',
43
'@babel/preset-flow',
44
],
packages/react-devtools-extensions/chrome/build.js
+5
-5
@@ -1,14 +1,14 @@
1
#!/usr/bin/env node
2
3
const chalk = require('chalk');
4
-const { execSync } = require('child_process');
5
-const { existsSync } = require('fs');
6
-const { isAbsolute, join, relative } = require('path');
7
-const { argv } = require('yargs');
4
+const {execSync} = require('child_process');
5
+const {existsSync} = require('fs');
6
+const {isAbsolute, join, relative} = require('path');
7
+const {argv} = require('yargs');
8
const build = require('../shared/build');
9
10
const main = async () => {
11
- const { crx, keyPath } = argv;
11
+ const {crx, keyPath} = argv;
12
13
if (crx) {
14
if (!keyPath || !existsSync(keyPath)) {
packages/react-devtools-extensions/chrome/test.js
+1
-1
@@ -1,7 +1,7 @@
1
#!/usr/bin/env node
2
3
const chromeLaunch = require('chrome-launch'); // eslint-disable-line import/no-extraneous-dependencies
4
-const { resolve } = require('path');
4
+const {resolve} = require('path');
5
6
const EXTENSION_PATH = resolve('shells/browser/chrome/build/unpacked');
7
const START_URL = 'https://facebook.github.io/react/';
packages/react-devtools-extensions/firefox/build.js
+1
-1
@@ -32,4 +32,4 @@ const main = async () => {
32
33
main();
34
35
-module.exports = { main };
35
+module.exports = {main};
packages/react-devtools-extensions/firefox/test.js
+3
-3
@@ -1,8 +1,8 @@
1
#!/usr/bin/env node
2
3
-const { exec } = require('child-process-promise');
4
-const { Finder } = require('firefox-profile');
5
-const { resolve } = require('path');
3
+const {exec} = require('child-process-promise');
4
+const {Finder} = require('firefox-profile');
5
+const {resolve} = require('path');
6
7
const EXTENSION_PATH = resolve('shells/browser/firefox/build/unpacked');
8
const START_URL = 'https://facebook.github.io/react/';
packages/react-devtools-extensions/flow-typed/chrome.js
+1
-1
@@ -42,7 +42,7 @@ declare var chrome: {
42
browserAction: {
43
setIcon: (options: {
44
tabId: number,
45
- path: { [key: string]: string },
45
+ path: {[key: string]: string},
46
}) => void,
47
setPopup: (options: {
48
tabId: number,
packages/react-devtools-extensions/flow-typed/jest.js
+12
-12
@@ -19,7 +19,7 @@ type JestMockFn<TArguments: $ReadOnlyArray<*>, TReturn> = {
19
* An array that contains all the object results that have been
20
* returned by this mock function call
21
*/
22
- results: Array<{ isThrow: boolean, value: TReturn }>,
22
+ results: Array<{isThrow: boolean, value: TReturn}>,
23
},
24
/**
25
* Resets all information stored in the mockFn.mock.calls and
@@ -204,7 +204,7 @@ type EnzymeMatchersType = {
204
toIncludeText(text: string): void,
205
toMatchElement(
206
element: React$Element<any>,
207
- options?: {| ignoreProps?: boolean, verbose?: boolean |}
207
+ options?: {|ignoreProps?: boolean, verbose?: boolean|}
208
): void,
209
toMatchSelector(selector: string): void,
210
// 7.x
@@ -222,11 +222,11 @@ type DomTestingLibraryType = {
222
toHaveAttribute(name: string, expectedValue?: string): void,
223
toHaveClass(...classNames: string[]): void,
224
toHaveFocus(): void,
225
- toHaveFormValues(expectedValues: { [name: string]: any }): void,
225
+ toHaveFormValues(expectedValues: {[name: string]: any}): void,
226
toHaveStyle(css: string): void,
227
toHaveTextContent(
228
content: string | RegExp,
229
- options?: { normalizeWhitespace: boolean }
229
+ options?: {normalizeWhitespace: boolean}
230
): void,
231
toBeInTheDOM(): void,
232
};
@@ -243,7 +243,7 @@ type JestJQueryMatchersType = {
243
toHaveText(text: string | RegExp): void,
244
toHaveData(key: string, val?: any): void,
245
toHaveValue(val: any): void,
246
- toHaveCss(css: { [key: string]: any }): void,
246
+ toHaveCss(css: {[key: string]: any}): void,
247
toBeChecked(): void,
248
toBeDisabled(): void,
249
toBeEmpty(): void,
@@ -1079,11 +1079,11 @@ declare var xit: typeof it;
1079
declare var xtest: typeof it;
1080
1081
type JestPrettyFormatColors = {
1082
- comment: { close: string, open: string },
1083
- content: { close: string, open: string },
1084
- prop: { close: string, open: string },
1085
- tag: { close: string, open: string },
1086
- value: { close: string, open: string },
1082
+ comment: {close: string, open: string},
1083
+ content: {close: string, open: string},
1084
+ prop: {close: string, open: string},
1085
+ tag: {close: string, open: string},
1086
+ value: {close: string, open: string},
1087
};
1088
1089
type JestPrettyFormatIndent = string => string;
@@ -1141,7 +1141,7 @@ declare var expect: {
1141
JestExtendedMatchersType,
1142
1143
/** Add additional Jasmine matchers to Jest's roster */
1144
- extend(matchers: { [name: string]: JestMatcher }): void,
1144
+ extend(matchers: {[name: string]: JestMatcher}): void,
1145
/** Add a module that formats application-specific data structures. */
1146
addSnapshotSerializer(pluginModule: JestPrettyFormatPlugin): void,
1147
assertions(expectedAssertions: number): void,
@@ -1182,7 +1182,7 @@ declare var jasmine: {
1182
createSpyObj(
1183
baseName: string,
1184
methodNames: Array<string>
1185
- ): { [methodName: string]: JestSpyType },
1185
+ ): {[methodName: string]: JestSpyType},
1186
objectContaining(value: Object): Object,
1187
stringMatching(value: string): string,
1188
};
packages/react-devtools-extensions/flow-typed/npm/react-test-renderer_v16.x.x.js
+7
-7
@@ -8,7 +8,7 @@ type ReactComponentInstance = React$Component<any>;
8
9
type ReactTestRendererJSON = {
10
type: string,
11
- props: { [propName: string]: any },
11
+ props: {[propName: string]: any},
12
children: null | ReactTestRendererJSON[],
13
};
14
@@ -21,25 +21,25 @@ type ReactTestRendererTree = ReactTestRendererJSON & {
21
type ReactTestInstance = {
22
instance: ?ReactComponentInstance,
23
type: string,
24
- props: { [propName: string]: any },
24
+ props: {[propName: string]: any},
25
parent: null | ReactTestInstance,
26
children: Array<ReactTestInstance | string>,
27
28
find(predicate: (node: ReactTestInstance) => boolean): ReactTestInstance,
29
findByType(type: React$ElementType): ReactTestInstance,
30
- findByProps(props: { [propName: string]: any }): ReactTestInstance,
30
+ findByProps(props: {[propName: string]: any}): ReactTestInstance,
31
32
findAll(
33
predicate: (node: ReactTestInstance) => boolean,
34
- options?: { deep: boolean }
34
+ options?: {deep: boolean}
35
): ReactTestInstance[],
36
findAllByType(
37
type: React$ElementType,
38
- options?: { deep: boolean }
38
+ options?: {deep: boolean}
39
): ReactTestInstance[],
40
findAllByProps(
41
- props: { [propName: string]: any },
42
- options?: { deep: boolean }
41
+ props: {[propName: string]: any},
42
+ options?: {deep: boolean}
43
): ReactTestInstance[],
44
};
45
packages/react-devtools-extensions/flow.js
+1
-1
@@ -4,7 +4,7 @@ declare module 'node-events' {
4
declare class EventEmitter<Events: Object> {
5
addListener<Event: $Keys<Events>>(
6
event: Event,
7
- listener: (...$ElementType<Events, Event>) => any
7
+ listener: (...$ElementType<Events, Event>) => any,
8
): void;
9
emit: <Event: $Keys<Events>>(
10
event: Event,
packages/react-devtools-extensions/shared/build.js
+6
-6
@@ -1,11 +1,11 @@
1
#!/usr/bin/env node
2
3
const archiver = require('archiver');
4
-const { execSync } = require('child_process');
5
-const { readFileSync, writeFileSync, createWriteStream } = require('fs');
6
-const { copy, ensureDir, move, remove } = require('fs-extra');
7
-const { join } = require('path');
8
-const { getGitCommit } = require('../../utils');
4
+const {execSync} = require('child_process');
5
+const {readFileSync, writeFileSync, createWriteStream} = require('fs');
6
+const {copy, ensureDir, move, remove} = require('fs-extra');
7
+const {join} = require('path');
8
+const {getGitCommit} = require('../../utils');
9
10
// These files are copied along with Webpack-bundled files
11
// to produce the final web extension
@@ -72,7 +72,7 @@ const build = async (tempPath, manifestPath) => {
72
writeFileSync(copiedManifestPath, JSON.stringify(manifest, null, 2));
73
74
// Pack the extension
75
- const archive = archiver('zip', { zlib: { level: 9 } });
75
+ const archive = archiver('zip', {zlib: {level: 9}});
76
const zipStream = createWriteStream(join(tempPath, 'ReactDevTools.zip'));
77
await new Promise((resolve, reject) => {
78
archive
packages/react-devtools-extensions/shared/deploy.js
+3
-3
@@ -1,8 +1,8 @@
1
#!/usr/bin/env node
2
3
-const { exec, execSync } = require('child_process');
4
-const { readFileSync, writeFileSync } = require('fs');
5
-const { join } = require('path');
3
+const {exec, execSync} = require('child_process');
4
+const {readFileSync, writeFileSync} = require('fs');
5
+const {join} = require('path');
6
7
const main = async buildId => {
8
const root = join(__dirname, '..', buildId);
packages/react-devtools-extensions/shared/popups/shared.js
+1
-1
@@ -8,7 +8,7 @@ document.addEventListener('DOMContentLoaded', function() {
8
const ln = links[i];
9
const location = ln.href;
10
ln.onclick = function() {
11
- chrome.tabs.create({ active: true, url: location });
11
+ chrome.tabs.create({active: true, url: location});
12
};
13
})();
14
}
packages/react-devtools-extensions/shared/src/backend.js
+2
-2
@@ -22,7 +22,7 @@ window.addEventListener('message', welcome);
22
function setup(hook) {
23
const Agent = require('react-devtools-shared/src/backend/agent').default;
24
const Bridge = require('react-devtools-shared/src/bridge').default;
25
- const { initBackend } = require('react-devtools-shared/src/backend');
25
+ const {initBackend} = require('react-devtools-shared/src/backend');
26
const setupNativeStyleEditor = require('react-devtools-shared/src/backend/NativeStyleEditor/setupNativeStyleEditor')
27
.default;
28
@@ -48,7 +48,7 @@ function setup(hook) {
48
window.postMessage(
49
{
50
source: 'react-devtools-bridge',
51
- payload: { event, payload },
51
+ payload: {event, payload},
52
},
53
'*',
54
transferable
packages/react-devtools-extensions/shared/src/background.js
+1
-1
@@ -36,7 +36,7 @@ function isNumeric(str: string): boolean {
36
function installContentScript(tabId: number) {
37
chrome.tabs.executeScript(
38
tabId,
39
- { file: '/build/contentScript.js' },
39
+ {file: '/build/contentScript.js'},
40
function() {}
41
);
42
}
packages/react-devtools-extensions/shared/src/injectGlobalHook.js
+3
-3
@@ -1,9 +1,9 @@
1
/* global chrome */
2
3
import nullthrows from 'nullthrows';
4
-import { installHook } from 'react-devtools-shared/src/hook';
5
-import { SESSION_STORAGE_RELOAD_AND_PROFILE_KEY } from 'react-devtools-shared/src/constants';
6
-import { sessionStorageGetItem } from 'react-devtools-shared/src/storage';
4
+import {installHook} from 'react-devtools-shared/src/hook';
5
+import {SESSION_STORAGE_RELOAD_AND_PROFILE_KEY} from 'react-devtools-shared/src/constants';
6
+import {sessionStorageGetItem} from 'react-devtools-shared/src/storage';
7
8
function injectCode(code) {
9
const script = document.createElement('script');
packages/react-devtools-extensions/shared/src/main.js
+7
-4
@@ -1,7 +1,7 @@
1
/* global chrome */
2
3
-import { createElement } from 'react';
4
-import { unstable_createRoot as createRoot, flushSync } from 'react-dom';
3
+import {createElement} from 'react';
4
+import {unstable_createRoot as createRoot, flushSync} from 'react-dom';
5
import Bridge from 'react-devtools-shared/src/bridge';
6
import Store from 'react-devtools-shared/src/devtools/store';
7
import inject from './inject';
@@ -10,7 +10,10 @@ import {
10
getBrowserName,
11
getBrowserTheme,
12
} from './utils';
13
-import { getSavedComponentFilters, getAppendComponentStack } from 'react-devtools-shared/src/utils';
13
+import {
14
+ getSavedComponentFilters,
15
+ getAppendComponentStack,
16
+} from 'react-devtools-shared/src/utils';
17
import {
18
localStorageGetItem,
19
localStorageRemoveItem,
@@ -93,7 +96,7 @@ function createPanelIfReactLoaded() {
96
};
97
},
98
send(event: string, payload: any, transferable?: Array<any>) {
96
- port.postMessage({ event, payload }, transferable);
99
+ port.postMessage({event, payload}, transferable);
100
},
101
});
102
bridge.addListener('reloadAppForProfiling', () => {
packages/react-devtools-extensions/shared/src/renderer.js
+1
-1
@@ -8,7 +8,7 @@
8
* @flow
9
*/
10
11
-import { attach } from 'react-devtools-shared/src/backend/renderer';
11
+import {attach} from 'react-devtools-shared/src/backend/renderer';
12
13
Object.defineProperty(
14
window,
packages/react-devtools-extensions/shared/src/utils.js
+1
-1
@@ -8,7 +8,7 @@ export function createViewElementSource(bridge: Bridge, store: Store) {
8
if (rendererID != null) {
9
// Ask the renderer interface to determine the component function,
10
// and store it as a global variable on the window
11
- bridge.send('viewElementSource', { id, rendererID });
11
+ bridge.send('viewElementSource', {id, rendererID});
12
13
setTimeout(() => {
14
// Ask Chrome to display the location of the component function,
packages/react-devtools-extensions/shared/webpack.backend.js
+3
-3
@@ -1,6 +1,6 @@
1
-const { resolve } = require('path');
2
-const { DefinePlugin } = require('webpack');
3
-const { getGitHubURL, getVersionString } = require('../utils');
1
+const {resolve} = require('path');
2
+const {DefinePlugin} = require('webpack');
3
+const {getGitHubURL, getVersionString} = require('../utils');
4
5
const NODE_ENV = process.env.NODE_ENV;
6
if (!NODE_ENV) {
packages/react-devtools-extensions/shared/webpack.config.js
+3
-3
@@ -1,6 +1,6 @@
1
-const { resolve } = require('path');
2
-const { DefinePlugin } = require('webpack');
3
-const { getGitHubURL, getVersionString } = require('../utils');
1
+const {resolve} = require('path');
2
+const {DefinePlugin} = require('webpack');
3
+const {getGitHubURL, getVersionString} = require('../utils');
4
5
const NODE_ENV = process.env.NODE_ENV;
6
if (!NODE_ENV) {
packages/react-devtools-extensions/utils.js
+5
-5
@@ -1,6 +1,6 @@
1
-const { execSync } = require('child_process');
2
-const { readFileSync } = require('fs');
3
-const { resolve } = require('path');
1
+const {execSync} = require('child_process');
2
+const {readFileSync} = require('fs');
3
+const {resolve} = require('path');
4
5
function getGitCommit() {
6
return execSync('git show -s --format=%h')
@@ -26,7 +26,7 @@ function getGitHubURL() {
26
27
function getVersionString() {
28
const packageVersion = JSON.parse(
29
- readFileSync(resolve(__dirname, '../package.json'))
29
+ readFileSync(resolve(__dirname, '../package.json')),
30
).version;
31
32
const commit = getGitCommit();
@@ -34,4 +34,4 @@ function getVersionString() {
34
return `${packageVersion}-${commit}`;
35
}
36
37
-module.exports = { getGitCommit, getGitHubURL, getVersionString };
37
+module.exports = {getGitCommit, getGitHubURL, getVersionString};
packages/react-devtools-inline/src/backend.js
+9
-9
@@ -2,8 +2,8 @@
2
3
import Agent from 'react-devtools-shared/src/backend/agent';
4
import Bridge from 'react-devtools-shared/src/bridge';
5
-import { initBackend } from 'react-devtools-shared/src/backend';
6
-import { installHook } from 'react-devtools-shared/src/hook';
5
+import {initBackend} from 'react-devtools-shared/src/backend';
6
+import {installHook} from 'react-devtools-shared/src/hook';
7
import setupNativeStyleEditor from 'react-devtools-shared/src/backend/NativeStyleEditor/setupNativeStyleEditor';
8
import {
9
MESSAGE_TYPE_GET_SAVED_PREFERENCES,
@@ -11,16 +11,16 @@ import {
11
} from './constants';
12
13
function startActivation(contentWindow: window) {
14
- const { parent } = contentWindow;
14
+ const {parent} = contentWindow;
15
16
- const onMessage = ({ data }) => {
16
+ const onMessage = ({data}) => {
17
switch (data.type) {
18
case MESSAGE_TYPE_SAVED_PREFERENCES:
19
// This is the only message we're listening for,
20
// so it's safe to cleanup after we've received it.
21
contentWindow.removeEventListener('message', onMessage);
22
23
- const { appendComponentStack, componentFilters } = data;
23
+ const {appendComponentStack, componentFilters} = data;
24
25
contentWindow.__REACT_DEVTOOLS_APPEND_COMPONENT_STACK__ = appendComponentStack;
26
contentWindow.__REACT_DEVTOOLS_COMPONENT_FILTERS__ = componentFilters;
@@ -49,11 +49,11 @@ function startActivation(contentWindow: window) {
49
// because they are stored in localStorage within the context of the extension (on the frontend).
50
// Instead it relies on the extension to pass preferences through.
51
// Because we might be in a sandboxed iframe, we have to ask for them by way of postMessage().
52
- parent.postMessage({ type: MESSAGE_TYPE_GET_SAVED_PREFERENCES }, '*');
52
+ parent.postMessage({type: MESSAGE_TYPE_GET_SAVED_PREFERENCES}, '*');
53
}
54
55
function finishActivation(contentWindow: window) {
56
- const { parent } = contentWindow;
56
+ const {parent} = contentWindow;
57
58
const bridge = new Bridge({
59
listen(fn) {
@@ -66,7 +66,7 @@ function finishActivation(contentWindow: window) {
66
};
67
},
68
send(event: string, payload: any, transferable?: Array<any>) {
69
- parent.postMessage({ event, payload }, '*', transferable);
69
+ parent.postMessage({event, payload}, '*', transferable);
70
},
71
});
72
@@ -82,7 +82,7 @@ function finishActivation(contentWindow: window) {
82
bridge,
83
agent,
84
hook.resolveRNStyle,
85
- hook.nativeStyleEditorValidAttributes
85
+ hook.nativeStyleEditorValidAttributes,
86
);
87
}
88
}
packages/react-devtools-inline/src/frontend.js
+12
-9
@@ -1,22 +1,25 @@
1
/** @flow */
2
3
-import React, { forwardRef } from 'react';
3
+import React, {forwardRef} from 'react';
4
import Bridge from 'react-devtools-shared/src/bridge';
5
import Store from 'react-devtools-shared/src/devtools/store';
6
import DevTools from 'react-devtools-shared/src/devtools/views/DevTools';
7
-import { getSavedComponentFilters, getAppendComponentStack } from 'react-devtools-shared/src/utils';
7
+import {
8
+ getSavedComponentFilters,
9
+ getAppendComponentStack,
10
+} from 'react-devtools-shared/src/utils';
11
import {
12
MESSAGE_TYPE_GET_SAVED_PREFERENCES,
13
MESSAGE_TYPE_SAVED_PREFERENCES,
14
} from './constants';
15
13
-import type { FrontendBridge } from 'react-devtools-shared/src/bridge';
14
-import type { Props } from 'react-devtools-shared/src/devtools/views/DevTools';
16
+import type {FrontendBridge} from 'react-devtools-shared/src/bridge';
17
+import type {Props} from 'react-devtools-shared/src/devtools/views/DevTools';
18
19
export function initialize(
17
- contentWindow: window
20
+ contentWindow: window,
21
): React.AbstractComponent<Props, mixed> {
19
- const onMessage = ({ data, source }) => {
22
+ const onMessage = ({data, source}) => {
23
if (source === 'react-devtools-content-script') {
24
// Ignore messages from the DevTools browser extension.
25
}
@@ -36,7 +39,7 @@ export function initialize(
39
appendComponentStack: getAppendComponentStack(),
40
componentFilters: getSavedComponentFilters(),
41
},
39
- '*'
42
+ '*',
43
);
44
break;
45
default:
@@ -48,7 +51,7 @@ export function initialize(
51
52
const bridge: FrontendBridge = new Bridge({
53
listen(fn) {
51
- const onMessage = ({ data }) => {
54
+ const onMessage = ({data}) => {
55
fn(data);
56
};
57
window.addEventListener('message', onMessage);
@@ -57,7 +60,7 @@ export function initialize(
60
};
61
},
62
send(event: string, payload: any, transferable?: Array<any>) {
60
- contentWindow.postMessage({ event, payload }, '*', transferable);
63
+ contentWindow.postMessage({event, payload}, '*', transferable);
64
},
65
});
66
packages/react-devtools-inline/webpack.config.js
+3
-3
@@ -1,6 +1,6 @@
1
-const { resolve } = require('path');
2
-const { DefinePlugin } = require('webpack');
3
-const { getGitHubURL, getVersionString } = require('../../shells/utils');
1
+const {resolve} = require('path');
2
+const {DefinePlugin} = require('webpack');
3
+const {getGitHubURL, getVersionString} = require('../../shells/utils');
4
5
const NODE_ENV = process.env.NODE_ENV;
6
if (!NODE_ENV) {
packages/react-devtools-shared/src/__tests__/bridge-test.js
+1
-1
@@ -36,7 +36,7 @@ describe('Bridge', () => {
36
jest.runAllTimers();
37
expect(wall.send).not.toHaveBeenCalled();
38
expect(console.warn).toHaveBeenCalledWith(
39
- 'Cannot send message "should not send" through a Bridge that has been shutdown.'
39
+ 'Cannot send message "should not send" through a Bridge that has been shutdown.',
40
);
41
});
42
});
packages/react-devtools-shared/src/__tests__/console-test.js
+20
-20
@@ -61,7 +61,7 @@ describe('console', () => {
61
});
62
63
it('should only patch the console once', () => {
64
- const { error, warn } = fakeConsole;
64
+ const {error, warn} = fakeConsole;
65
66
patchConsole();
67
@@ -109,7 +109,7 @@ describe('console', () => {
109
expect(mockWarn).toHaveBeenCalledTimes(1);
110
expect(mockWarn.mock.calls[0]).toHaveLength(1);
111
expect(mockWarn.mock.calls[0][0]).toBe(
112
- 'warn\n in Child (at fake.js:123)'
112
+ 'warn\n in Child (at fake.js:123)',
113
);
114
expect(mockError).toHaveBeenCalledTimes(1);
115
expect(mockError.mock.calls[0]).toHaveLength(2);
@@ -118,7 +118,7 @@ describe('console', () => {
118
});
119
120
it('should append component stacks to errors and warnings logged during render', () => {
121
- const Intermediate = ({ children }) => children;
121
+ const Intermediate = ({children}) => children;
122
const Parent = () => (
123
<Intermediate>
124
<Child />
@@ -140,18 +140,18 @@ describe('console', () => {
140
expect(mockWarn.mock.calls[0]).toHaveLength(2);
141
expect(mockWarn.mock.calls[0][0]).toBe('warn');
142
expect(normalizeCodeLocInfo(mockWarn.mock.calls[0][1])).toEqual(
143
- '\n in Child (at **)\n in Parent (at **)'
143
+ '\n in Child (at **)\n in Parent (at **)',
144
);
145
expect(mockError).toHaveBeenCalledTimes(1);
146
expect(mockError.mock.calls[0]).toHaveLength(2);
147
expect(mockError.mock.calls[0][0]).toBe('error');
148
expect(normalizeCodeLocInfo(mockError.mock.calls[0][1])).toBe(
149
- '\n in Child (at **)\n in Parent (at **)'
149
+ '\n in Child (at **)\n in Parent (at **)',
150
);
151
});
152
153
it('should append component stacks to errors and warnings logged from effects', () => {
154
- const Intermediate = ({ children }) => children;
154
+ const Intermediate = ({children}) => children;
155
const Parent = () => (
156
<Intermediate>
157
<Child />
@@ -182,28 +182,28 @@ describe('console', () => {
182
expect(mockWarn.mock.calls[0]).toHaveLength(2);
183
expect(mockWarn.mock.calls[0][0]).toBe('active warn');
184
expect(normalizeCodeLocInfo(mockWarn.mock.calls[0][1])).toEqual(
185
- '\n in Child (at **)\n in Parent (at **)'
185
+ '\n in Child (at **)\n in Parent (at **)',
186
);
187
expect(mockWarn.mock.calls[1]).toHaveLength(2);
188
expect(mockWarn.mock.calls[1][0]).toBe('passive warn');
189
expect(normalizeCodeLocInfo(mockWarn.mock.calls[1][1])).toEqual(
190
- '\n in Child (at **)\n in Parent (at **)'
190
+ '\n in Child (at **)\n in Parent (at **)',
191
);
192
expect(mockError).toHaveBeenCalledTimes(2);
193
expect(mockError.mock.calls[0]).toHaveLength(2);
194
expect(mockError.mock.calls[0][0]).toBe('active error');
195
expect(normalizeCodeLocInfo(mockError.mock.calls[0][1])).toBe(
196
- '\n in Child (at **)\n in Parent (at **)'
196
+ '\n in Child (at **)\n in Parent (at **)',
197
);
198
expect(mockError.mock.calls[1]).toHaveLength(2);
199
expect(mockError.mock.calls[1][0]).toBe('passive error');
200
expect(normalizeCodeLocInfo(mockError.mock.calls[1][1])).toBe(
201
- '\n in Child (at **)\n in Parent (at **)'
201
+ '\n in Child (at **)\n in Parent (at **)',
202
);
203
});
204
205
it('should append component stacks to errors and warnings logged from commit hooks', () => {
206
- const Intermediate = ({ children }) => children;
206
+ const Intermediate = ({children}) => children;
207
const Parent = () => (
208
<Intermediate>
209
<Child />
@@ -238,28 +238,28 @@ describe('console', () => {
238
expect(mockWarn.mock.calls[0]).toHaveLength(2);
239
expect(mockWarn.mock.calls[0][0]).toBe('didMount warn');
240
expect(normalizeCodeLocInfo(mockWarn.mock.calls[0][1])).toEqual(
241
- '\n in Child (at **)\n in Parent (at **)'
241
+ '\n in Child (at **)\n in Parent (at **)',
242
);
243
expect(mockWarn.mock.calls[1]).toHaveLength(2);
244
expect(mockWarn.mock.calls[1][0]).toBe('didUpdate warn');
245
expect(normalizeCodeLocInfo(mockWarn.mock.calls[1][1])).toEqual(
246
- '\n in Child (at **)\n in Parent (at **)'
246
+ '\n in Child (at **)\n in Parent (at **)',
247
);
248
expect(mockError).toHaveBeenCalledTimes(2);
249
expect(mockError.mock.calls[0]).toHaveLength(2);
250
expect(mockError.mock.calls[0][0]).toBe('didMount error');
251
expect(normalizeCodeLocInfo(mockError.mock.calls[0][1])).toBe(
252
- '\n in Child (at **)\n in Parent (at **)'
252
+ '\n in Child (at **)\n in Parent (at **)',
253
);
254
expect(mockError.mock.calls[1]).toHaveLength(2);
255
expect(mockError.mock.calls[1][0]).toBe('didUpdate error');
256
expect(normalizeCodeLocInfo(mockError.mock.calls[1][1])).toBe(
257
- '\n in Child (at **)\n in Parent (at **)'
257
+ '\n in Child (at **)\n in Parent (at **)',
258
);
259
});
260
261
it('should append component stacks to errors and warnings logged from gDSFP', () => {
262
- const Intermediate = ({ children }) => children;
262
+ const Intermediate = ({children}) => children;
263
const Parent = () => (
264
<Intermediate>
265
<Child />
@@ -287,13 +287,13 @@ describe('console', () => {
287
expect(mockWarn.mock.calls[0]).toHaveLength(2);
288
expect(mockWarn.mock.calls[0][0]).toBe('warn');
289
expect(normalizeCodeLocInfo(mockWarn.mock.calls[0][1])).toEqual(
290
- '\n in Child (at **)\n in Parent (at **)'
290
+ '\n in Child (at **)\n in Parent (at **)',
291
);
292
expect(mockError).toHaveBeenCalledTimes(1);
293
expect(mockError.mock.calls[0]).toHaveLength(2);
294
expect(mockError.mock.calls[0][0]).toBe('error');
295
expect(normalizeCodeLocInfo(mockError.mock.calls[0][1])).toBe(
296
- '\n in Child (at **)\n in Parent (at **)'
296
+ '\n in Child (at **)\n in Parent (at **)',
297
);
298
});
299
@@ -321,13 +321,13 @@ describe('console', () => {
321
expect(mockWarn.mock.calls[1]).toHaveLength(2);
322
expect(mockWarn.mock.calls[1][0]).toBe('warn');
323
expect(normalizeCodeLocInfo(mockWarn.mock.calls[1][1])).toEqual(
324
- '\n in Child (at **)'
324
+ '\n in Child (at **)',
325
);
326
expect(mockError).toHaveBeenCalledTimes(2);
327
expect(mockError.mock.calls[1]).toHaveLength(2);
328
expect(mockError.mock.calls[1][0]).toBe('error');
329
expect(normalizeCodeLocInfo(mockError.mock.calls[1][1])).toBe(
330
- '\n in Child (at **)'
330
+ '\n in Child (at **)',
331
);
332
});
333
});
packages/react-devtools-shared/src/__tests__/inspectedElementContext-test.js
+85
-95
@@ -1,8 +1,8 @@
1
// @flow
2
3
import typeof ReactTestRenderer from 'react-test-renderer';
4
-import type { GetInspectedElementPath } from 'react-devtools-shared/src/devtools/views/Components/InspectedElementContext';
5
-import type { FrontendBridge } from 'react-devtools-shared/src/bridge';
4
+import type {GetInspectedElementPath} from 'react-devtools-shared/src/devtools/views/Components/InspectedElementContext';
5
+import type {FrontendBridge} from 'react-devtools-shared/src/bridge';
6
import type Store from 'react-devtools-shared/src/devtools/store';
7
8
describe('InspectedElementContext', () => {
@@ -36,12 +36,14 @@ describe('InspectedElementContext', () => {
36
TestUtils = require('react-dom/test-utils');
37
TestRenderer = utils.requireTestRenderer();
38
39
- BridgeContext = require('react-devtools-shared/src/devtools/views/context').BridgeContext;
39
+ BridgeContext = require('react-devtools-shared/src/devtools/views/context')
40
+ .BridgeContext;
41
InspectedElementContext = require('react-devtools-shared/src/devtools/views/Components/InspectedElementContext')
42
.InspectedElementContext;
43
InspectedElementContextController = require('react-devtools-shared/src/devtools/views/Components/InspectedElementContext')
44
.InspectedElementContextController;
44
- StoreContext = require('react-devtools-shared/src/devtools/views/context').StoreContext;
45
+ StoreContext = require('react-devtools-shared/src/devtools/views/context')
46
+ .StoreContext;
47
TreeContextController = require('react-devtools-shared/src/devtools/views/Components/TreeContext')
48
.TreeContextController;
49
});
@@ -55,8 +57,7 @@ describe('InspectedElementContext', () => {
57
<StoreContext.Provider value={store}>
58
<TreeContextController
59
defaultSelectedElementID={defaultSelectedElementID}
58
- defaultSelectedElementIndex={defaultSelectedElementIndex}
59
- >
60
+ defaultSelectedElementIndex={defaultSelectedElementIndex}>
61
<InspectedElementContextController>
62
{children}
63
</InspectedElementContextController>
@@ -73,15 +74,15 @@ describe('InspectedElementContext', () => {
74
75
const container = document.createElement('div');
76
await utils.actAsync(() =>
76
- ReactDOM.render(<Example a={1} b="abc" />, container)
77
+ ReactDOM.render(<Example a={1} b="abc" />, container),
78
);
79
80
const id = ((store.getElementIDAtIndex(0): any): number);
81
82
let didFinish = false;
83
83
- function Suspender({ target }) {
84
- const { getInspectedElement } = React.useContext(InspectedElementContext);
84
+ function Suspender({target}) {
85
+ const {getInspectedElement} = React.useContext(InspectedElementContext);
86
const inspectedElement = getInspectedElement(id);
87
expect(inspectedElement).toMatchSnapshot(`1: Inspected element ${id}`);
88
didFinish = true;
@@ -93,14 +94,13 @@ describe('InspectedElementContext', () => {
94
TestRenderer.create(
95
<Contexts
96
defaultSelectedElementID={id}
96
- defaultSelectedElementIndex={0}
97
- >
97
+ defaultSelectedElementIndex={0}>
98
<React.Suspense fallback={null}>
99
<Suspender target={id} />
100
</React.Suspense>
101
- </Contexts>
101
+ </Contexts>,
102
),
103
- false
103
+ false,
104
);
105
expect(didFinish).toBe(true);
106
@@ -113,15 +113,15 @@ describe('InspectedElementContext', () => {
113
const container = document.createElement('div');
114
await utils.actAsync(
115
() => ReactDOM.render(<Example a={1} b="abc" />, container),
116
- false
116
+ false,
117
);
118
119
const id = ((store.getElementIDAtIndex(0): any): number);
120
121
let inspectedElement = null;
122
123
- function Suspender({ target }) {
124
- const { getInspectedElement } = React.useContext(InspectedElementContext);
123
+ function Suspender({target}) {
124
+ const {getInspectedElement} = React.useContext(InspectedElementContext);
125
inspectedElement = getInspectedElement(id);
126
return null;
127
}
@@ -134,14 +134,14 @@ describe('InspectedElementContext', () => {
134
<React.Suspense fallback={null}>
135
<Suspender target={id} />
136
</React.Suspense>
137
- </Contexts>
137
+ </Contexts>,
138
);
139
}, false);
140
expect(inspectedElement).toMatchSnapshot('1: initial render');
141
142
await utils.actAsync(
143
() => ReactDOM.render(<Example a={2} b="def" />, container),
144
- false
144
+ false,
145
);
146
147
inspectedElement = null;
@@ -150,14 +150,13 @@ describe('InspectedElementContext', () => {
150
renderer.update(
151
<Contexts
152
defaultSelectedElementID={id}
153
- defaultSelectedElementIndex={0}
154
- >
153
+ defaultSelectedElementIndex={0}>
154
<React.Suspense fallback={null}>
155
<Suspender target={id} />
156
</React.Suspense>
158
- </Contexts>
157
+ </Contexts>,
158
),
160
- false
159
+ false,
160
);
161
expect(inspectedElement).toMatchSnapshot('2: updated state');
162
@@ -167,7 +166,7 @@ describe('InspectedElementContext', () => {
166
it('should not re-render a function with hooks if it did not update since it was last inspected', async done => {
167
let targetRenderCount = 0;
168
170
- const Wrapper = ({ children }) => children;
169
+ const Wrapper = ({children}) => children;
170
const Target = React.memo(props => {
171
targetRenderCount++;
172
React.useState(0);
@@ -180,16 +179,16 @@ describe('InspectedElementContext', () => {
179
<Wrapper>
180
<Target a={1} b="abc" />
181
</Wrapper>,
183
- container
184
- )
182
+ container,
183
+ ),
184
);
185
186
const id = ((store.getElementIDAtIndex(1): any): number);
187
188
let inspectedElement = null;
189
191
- function Suspender({ target }) {
192
- const { getInspectedElement } = React.useContext(InspectedElementContext);
190
+ function Suspender({target}) {
191
+ const {getInspectedElement} = React.useContext(InspectedElementContext);
192
inspectedElement = getInspectedElement(target);
193
return null;
194
}
@@ -202,14 +201,13 @@ describe('InspectedElementContext', () => {
201
(renderer = TestRenderer.create(
202
<Contexts
203
defaultSelectedElementID={id}
205
- defaultSelectedElementIndex={1}
206
- >
204
+ defaultSelectedElementIndex={1}>
205
<React.Suspense fallback={null}>
206
<Suspender target={id} />
207
</React.Suspense>
210
- </Contexts>
208
+ </Contexts>,
209
)),
212
- false
210
+ false,
211
);
212
expect(targetRenderCount).toBe(1);
213
expect(inspectedElement).toMatchSnapshot('1: initial render');
@@ -223,14 +221,13 @@ describe('InspectedElementContext', () => {
221
renderer.update(
222
<Contexts
223
defaultSelectedElementID={id}
226
- defaultSelectedElementIndex={1}
227
- >
224
+ defaultSelectedElementIndex={1}>
225
<React.Suspense fallback={null}>
226
<Suspender target={id} />
227
</React.Suspense>
231
- </Contexts>
228
+ </Contexts>,
229
),
233
- false
230
+ false,
231
);
232
expect(targetRenderCount).toBe(0);
233
expect(inspectedElement).toEqual(initialInspectedElement);
@@ -243,9 +240,9 @@ describe('InspectedElementContext', () => {
240
<Wrapper>
241
<Target a={2} b="def" />
242
</Wrapper>,
246
- container
243
+ container,
244
),
248
- false
245
+ false,
246
);
247
248
// Target should have been rendered once (by ReactDOM) and once by DevTools for inspection.
@@ -275,7 +272,7 @@ describe('InspectedElementContext', () => {
272
273
const container = document.createElement('div');
274
await utils.actAsync(() =>
278
- ReactDOM.render(<Target a={1} b="abc" />, container)
275
+ ReactDOM.render(<Target a={1} b="abc" />, container),
276
);
277
278
expect(targetRenderCount).toBe(1);
@@ -292,8 +289,8 @@ describe('InspectedElementContext', () => {
289
290
let inspectedElement = null;
291
295
- function Suspender({ target }) {
296
- const { getInspectedElement } = React.useContext(InspectedElementContext);
292
+ function Suspender({target}) {
293
+ const {getInspectedElement} = React.useContext(InspectedElementContext);
294
inspectedElement = getInspectedElement(target);
295
return null;
296
}
@@ -303,14 +300,13 @@ describe('InspectedElementContext', () => {
300
TestRenderer.create(
301
<Contexts
302
defaultSelectedElementID={id}
306
- defaultSelectedElementIndex={1}
307
- >
303
+ defaultSelectedElementIndex={1}>
304
<React.Suspense fallback={null}>
305
<Suspender target={id} />
306
</React.Suspense>
311
- </Contexts>
307
+ </Contexts>,
308
),
313
- false
309
+ false,
310
);
311
312
expect(inspectedElement).not.toBe(null);
@@ -342,15 +338,15 @@ describe('InspectedElementContext', () => {
338
value_null={null}
339
value_undefined={undefined}
340
/>,
345
- container
346
- )
341
+ container,
342
+ ),
343
);
344
345
const id = ((store.getElementIDAtIndex(0): any): number);
346
let inspectedElement = null;
347
352
- function Suspender({ target }) {
353
- const { getInspectedElement } = React.useContext(InspectedElementContext);
348
+ function Suspender({target}) {
349
+ const {getInspectedElement} = React.useContext(InspectedElementContext);
350
inspectedElement = getInspectedElement(id);
351
return null;
352
}
@@ -360,20 +356,19 @@ describe('InspectedElementContext', () => {
356
TestRenderer.create(
357
<Contexts
358
defaultSelectedElementID={id}
363
- defaultSelectedElementIndex={0}
364
- >
359
+ defaultSelectedElementIndex={0}>
360
<React.Suspense fallback={null}>
361
<Suspender target={id} />
362
</React.Suspense>
368
- </Contexts>
363
+ </Contexts>,
364
),
370
- false
365
+ false,
366
);
367
368
expect(inspectedElement).not.toBeNull();
369
expect(inspectedElement).toMatchSnapshot('1: Initial inspection');
370
376
- const { props } = (inspectedElement: any);
371
+ const {props} = (inspectedElement: any);
372
expect(props.boolean_false).toBe(false);
373
expect(props.boolean_true).toBe(true);
374
expect(Number.isFinite(props.infinity)).toBe(false);
@@ -408,16 +403,16 @@ describe('InspectedElementContext', () => {
403
typed_array={typedArray}
404
date={new Date()}
405
/>,
411
- container
412
- )
406
+ container,
407
+ ),
408
);
409
410
const id = ((store.getElementIDAtIndex(0): any): number);
411
412
let inspectedElement = null;
413
419
- function Suspender({ target }) {
420
- const { getInspectedElement } = React.useContext(InspectedElementContext);
414
+ function Suspender({target}) {
415
+ const {getInspectedElement} = React.useContext(InspectedElementContext);
416
inspectedElement = getInspectedElement(id);
417
return null;
418
}
@@ -427,14 +422,13 @@ describe('InspectedElementContext', () => {
422
TestRenderer.create(
423
<Contexts
424
defaultSelectedElementID={id}
430
- defaultSelectedElementIndex={0}
431
- >
425
+ defaultSelectedElementIndex={0}>
426
<React.Suspense fallback={null}>
427
<Suspender target={id} />
428
</React.Suspense>
435
- </Contexts>
429
+ </Contexts>,
430
),
437
- false
431
+ false,
432
);
433
434
expect(inspectedElement).not.toBeNull();
@@ -488,7 +482,7 @@ describe('InspectedElementContext', () => {
482
483
const descriptor = ((Object.getOwnPropertyDescriptor(
484
CustomData.prototype,
491
- 'number'
485
+ 'number',
486
): any): PropertyDescriptor<number>);
487
descriptor.enumerable = true;
488
Object.defineProperty(CustomData.prototype, 'number', descriptor);
@@ -497,15 +491,15 @@ describe('InspectedElementContext', () => {
491
492
const container = document.createElement('div');
493
await utils.actAsync(() =>
500
- ReactDOM.render(<Example data={new CustomData()} />, container)
494
+ ReactDOM.render(<Example data={new CustomData()} />, container),
495
);
496
497
const id = ((store.getElementIDAtIndex(0): any): number);
498
499
let didFinish = false;
500
507
- function Suspender({ target }) {
508
- const { getInspectedElement } = React.useContext(InspectedElementContext);
501
+ function Suspender({target}) {
502
+ const {getInspectedElement} = React.useContext(InspectedElementContext);
503
const inspectedElement = getInspectedElement(id);
504
expect(inspectedElement).toMatchSnapshot(`1: Inspected element ${id}`);
505
didFinish = true;
@@ -517,14 +511,13 @@ describe('InspectedElementContext', () => {
511
TestRenderer.create(
512
<Contexts
513
defaultSelectedElementID={id}
520
- defaultSelectedElementIndex={0}
521
- >
514
+ defaultSelectedElementIndex={0}>
515
<React.Suspense fallback={null}>
516
<Suspender target={id} />
517
</React.Suspense>
525
- </Contexts>
518
+ </Contexts>,
519
),
527
- false
520
+ false,
521
);
522
expect(didFinish).toBe(true);
523
@@ -562,8 +555,8 @@ describe('InspectedElementContext', () => {
555
},
556
}}
557
/>,
565
- container
566
- )
558
+ container,
559
+ ),
560
);
561
562
const id = ((store.getElementIDAtIndex(0): any): number);
@@ -571,7 +564,7 @@ describe('InspectedElementContext', () => {
564
let getInspectedElementPath: GetInspectedElementPath = ((null: any): GetInspectedElementPath);
565
let inspectedElement = null;
566
574
- function Suspender({ target }) {
567
+ function Suspender({target}) {
568
const context = React.useContext(InspectedElementContext);
569
getInspectedElementPath = context.getInspectedElementPath;
570
inspectedElement = context.getInspectedElement(target);
@@ -583,14 +576,13 @@ describe('InspectedElementContext', () => {
576
TestRenderer.create(
577
<Contexts
578
defaultSelectedElementID={id}
586
- defaultSelectedElementIndex={0}
587
- >
579
+ defaultSelectedElementIndex={0}>
580
<React.Suspense fallback={null}>
581
<Suspender target={id} />
582
</React.Suspense>
591
- </Contexts>
583
+ </Contexts>,
584
),
593
- false
585
+ false,
586
);
587
expect(getInspectedElementPath).not.toBeNull();
588
expect(inspectedElement).not.toBeNull();
@@ -615,7 +607,7 @@ describe('InspectedElementContext', () => {
607
});
608
expect(inspectedElement).not.toBeNull();
609
expect(inspectedElement).toMatchSnapshot(
618
- '3: Inspect props.nestedObject.a.b.c'
610
+ '3: Inspect props.nestedObject.a.b.c',
611
);
612
613
inspectedElement = null;
@@ -635,7 +627,7 @@ describe('InspectedElementContext', () => {
627
});
628
expect(inspectedElement).not.toBeNull();
629
expect(inspectedElement).toMatchSnapshot(
638
- '4: Inspect props.nestedObject.a.b.c.0.d'
630
+ '4: Inspect props.nestedObject.a.b.c.0.d',
631
);
632
633
inspectedElement = null;
@@ -657,7 +649,7 @@ describe('InspectedElementContext', () => {
649
});
650
expect(inspectedElement).not.toBeNull();
651
expect(inspectedElement).toMatchSnapshot(
660
- '6: Inspect hooks.0.value.foo.bar'
652
+ '6: Inspect hooks.0.value.foo.bar',
653
);
654
655
done();
@@ -688,8 +680,8 @@ describe('InspectedElementContext', () => {
680
},
681
}}
682
/>,
691
- container
692
- )
683
+ container,
684
+ ),
685
);
686
687
const id = ((store.getElementIDAtIndex(0): any): number);
@@ -697,7 +689,7 @@ describe('InspectedElementContext', () => {
689
let getInspectedElementPath: GetInspectedElementPath = ((null: any): GetInspectedElementPath);
690
let inspectedElement = null;
691
700
- function Suspender({ target }) {
692
+ function Suspender({target}) {
693
const context = React.useContext(InspectedElementContext);
694
getInspectedElementPath = context.getInspectedElementPath;
695
inspectedElement = context.getInspectedElement(id);
@@ -709,14 +701,13 @@ describe('InspectedElementContext', () => {
701
TestRenderer.create(
702
<Contexts
703
defaultSelectedElementID={id}
712
- defaultSelectedElementIndex={0}
713
- >
704
+ defaultSelectedElementIndex={0}>
705
<React.Suspense fallback={null}>
706
<Suspender target={id} />
707
</React.Suspense>
717
- </Contexts>
708
+ </Contexts>,
709
),
719
- false
710
+ false,
711
);
712
expect(getInspectedElementPath).not.toBeNull();
713
expect(inspectedElement).not.toBeNull();
@@ -760,7 +751,7 @@ describe('InspectedElementContext', () => {
751
},
752
}}
753
/>,
763
- container
754
+ container,
755
);
756
});
757
});
@@ -792,8 +783,8 @@ describe('InspectedElementContext', () => {
783
},
784
}}
785
/>,
795
- container
796
- )
786
+ container,
787
+ ),
788
);
789
790
const id = ((store.getElementIDAtIndex(0): any): number);
@@ -801,7 +792,7 @@ describe('InspectedElementContext', () => {
792
let getInspectedElementPath: GetInspectedElementPath = ((null: any): GetInspectedElementPath);
793
let inspectedElement = null;
794
804
- function Suspender({ target }) {
795
+ function Suspender({target}) {
796
const context = React.useContext(InspectedElementContext);
797
getInspectedElementPath = context.getInspectedElementPath;
798
inspectedElement = context.getInspectedElement(id);
@@ -813,14 +804,13 @@ describe('InspectedElementContext', () => {
804
TestRenderer.create(
805
<Contexts
806
defaultSelectedElementID={id}
816
- defaultSelectedElementIndex={0}
817
- >
807
+ defaultSelectedElementIndex={0}>
808
<React.Suspense fallback={null}>
809
<Suspender target={id} />
810
</React.Suspense>
821
- </Contexts>
811
+ </Contexts>,
812
),
823
- false
813
+ false,
814
);
815
expect(getInspectedElementPath).not.toBeNull();
816
expect(inspectedElement).not.toBeNull();
@@ -839,7 +829,7 @@ describe('InspectedElementContext', () => {
829
},
830
}}
831
/>,
842
- container
832
+ container,
833
);
834
});
835
packages/react-devtools-shared/src/__tests__/inspectedElementSerializer.js
+1
-1
@@ -23,6 +23,6 @@ export function print(inspectedElement, serialize, indent) {
23
state: inspectedElement.state,
24
},
25
null,
26
- 2
26
+ 2,
27
);
28
}
packages/react-devtools-shared/src/__tests__/legacy/inspectElement-test.js
+21
-21
@@ -1,8 +1,8 @@
1
// @flow
2
3
-import type { InspectedElementPayload } from 'react-devtools-shared/src/backend/types';
4
-import type { DehydratedData } from 'react-devtools-shared/src/devtools/views/Components/types';
5
-import type { FrontendBridge } from 'react-devtools-shared/src/bridge';
3
+import type {InspectedElementPayload} from 'react-devtools-shared/src/backend/types';
4
+import type {DehydratedData} from 'react-devtools-shared/src/devtools/views/Components/types';
5
+import type {FrontendBridge} from 'react-devtools-shared/src/bridge';
6
import type Store from 'react-devtools-shared/src/devtools/store';
7
8
describe('InspectedElementContext', () => {
@@ -20,7 +20,7 @@ describe('InspectedElementContext', () => {
20
};
21
22
function dehydrateHelper(
23
- dehydratedData: DehydratedData | null
23
+ dehydratedData: DehydratedData | null,
24
): Object | null {
25
if (dehydratedData !== null) {
26
return hydrate(dehydratedData.data, dehydratedData.cleaned);
@@ -31,7 +31,7 @@ describe('InspectedElementContext', () => {
31
32
async function read(
33
id: number,
34
- path?: Array<string | number>
34
+ path?: Array<string | number>,
35
): Promise<Object> {
36
return new Promise((resolve, reject) => {
37
const rendererID = ((store.getRendererIDForElement(id): any): number);
@@ -49,7 +49,7 @@ describe('InspectedElementContext', () => {
49
};
50
51
bridge.addListener('inspectedElement', onInspectedElement);
52
- bridge.send('inspectElement', { id, path, rendererID });
52
+ bridge.send('inspectElement', {id, path, rendererID});
53
54
jest.runOnlyPendingTimers();
55
});
@@ -66,7 +66,7 @@ describe('InspectedElementContext', () => {
66
// We use the UMD because Jest doesn't enable us to mock deep imports (e.g. "react/lib/Something").
67
jest.mock('react', () => jest.requireActual('react-15/dist/react.js'));
68
jest.mock('react-dom', () =>
69
- jest.requireActual('react-dom-15/dist/react-dom.js')
69
+ jest.requireActual('react-dom-15/dist/react-dom.js'),
70
);
71
72
React = require('react');
@@ -77,7 +77,7 @@ describe('InspectedElementContext', () => {
77
const Example = () => null;
78
79
act(() =>
80
- ReactDOM.render(<Example a={1} b="abc" />, document.createElement('div'))
80
+ ReactDOM.render(<Example a={1} b="abc" />, document.createElement('div')),
81
);
82
83
const id = ((store.getElementIDAtIndex(0): any): number);
@@ -106,8 +106,8 @@ describe('InspectedElementContext', () => {
106
value_null={null}
107
value_undefined={undefined}
108
/>,
109
- document.createElement('div')
110
- )
109
+ document.createElement('div'),
110
+ ),
111
);
112
113
const id = ((store.getElementIDAtIndex(0): any): number);
@@ -115,7 +115,7 @@ describe('InspectedElementContext', () => {
115
116
expect(inspectedElement).toMatchSnapshot('1: Initial inspection');
117
118
- const { props } = inspectedElement.value;
118
+ const {props} = inspectedElement.value;
119
expect(props.boolean_false).toBe(false);
120
expect(props.boolean_true).toBe(true);
121
expect(Number.isFinite(props.infinity)).toBe(false);
@@ -149,8 +149,8 @@ describe('InspectedElementContext', () => {
149
typed_array={typedArray}
150
date={new Date()}
151
/>,
152
- document.createElement('div')
153
- )
152
+ document.createElement('div'),
153
+ ),
154
);
155
156
const id = ((store.getElementIDAtIndex(0): any): number);
@@ -206,18 +206,18 @@ describe('InspectedElementContext', () => {
206
207
const descriptor = ((Object.getOwnPropertyDescriptor(
208
CustomData.prototype,
209
- 'number'
209
+ 'number',
210
): any): PropertyDescriptor<number>);
211
descriptor.enumerable = true;
212
Object.defineProperty(CustomData.prototype, 'number', descriptor);
213
214
- const Example = ({ data }) => null;
214
+ const Example = ({data}) => null;
215
216
act(() =>
217
ReactDOM.render(
218
<Example data={new CustomData()} />,
219
- document.createElement('div')
220
- )
219
+ document.createElement('div'),
220
+ ),
221
);
222
223
const id = ((store.getElementIDAtIndex(0): any): number);
@@ -248,8 +248,8 @@ describe('InspectedElementContext', () => {
248
},
249
}}
250
/>,
251
- document.createElement('div')
252
- )
251
+ document.createElement('div'),
252
+ ),
253
);
254
255
const id = ((store.getElementIDAtIndex(0): any): number);
@@ -262,7 +262,7 @@ describe('InspectedElementContext', () => {
262
263
inspectedElement = await read(id, ['props', 'nestedObject', 'a', 'b', 'c']);
264
expect(inspectedElement).toMatchSnapshot(
265
- '3: Inspect props.nestedObject.a.b.c'
265
+ '3: Inspect props.nestedObject.a.b.c',
266
);
267
268
inspectedElement = await read(id, [
@@ -275,7 +275,7 @@ describe('InspectedElementContext', () => {
275
'd',
276
]);
277
expect(inspectedElement).toMatchSnapshot(
278
- '4: Inspect props.nestedObject.a.b.c.0.d'
278
+ '4: Inspect props.nestedObject.a.b.c.0.d',
279
);
280
281
done();
packages/react-devtools-shared/src/__tests__/legacy/storeLegacy-v15-test.js
+47
-59
@@ -18,7 +18,7 @@ describe('Store (legacy)', () => {
18
// We use the UMD because Jest doesn't enable us to mock deep imports (e.g. "react/lib/Something").
19
jest.mock('react', () => jest.requireActual('react-15/dist/react.js'));
20
jest.mock('react-dom', () =>
21
- jest.requireActual('react-dom-15/dist/react-dom.js')
21
+ jest.requireActual('react-dom-15/dist/react-dom.js'),
22
);
23
24
React = require('react');
@@ -29,7 +29,7 @@ describe('Store (legacy)', () => {
29
const Component = () => <div>Hi</div>;
30
31
act(() =>
32
- ReactDOM.render(<Component count={4} />, document.createElement('div'))
32
+ ReactDOM.render(<Component count={4} />, document.createElement('div')),
33
);
34
expect(store).toMatchSnapshot('1: mount');
35
@@ -38,7 +38,7 @@ describe('Store (legacy)', () => {
38
const rootID = store.roots[0];
39
40
expect(() => store.toggleIsCollapsed(rootID, true)).toThrow(
41
- 'Root nodes cannot be collapsed'
41
+ 'Root nodes cannot be collapsed',
42
);
43
});
44
@@ -48,17 +48,15 @@ describe('Store (legacy)', () => {
48
});
49
50
it('should support mount and update operations', () => {
51
- const Grandparent = ({ count }) => (
51
+ const Grandparent = ({count}) => (
52
<div>
53
<Parent count={count} />
54
<Parent count={count} />
55
</div>
56
);
57
- const Parent = ({ count }) => (
57
+ const Parent = ({count}) => (
58
<div>
59
- {new Array(count).fill(true).map((_, index) => (
60
- <Child key={index} />
61
- ))}
59
+ {new Array(count).fill(true).map((_, index) => <Child key={index} />)}
60
</div>
61
);
62
const Child = () => <div>Hi!</div>;
@@ -76,11 +74,9 @@ describe('Store (legacy)', () => {
74
});
75
76
it('should support mount and update operations for multiple roots', () => {
79
- const Parent = ({ count }) => (
77
+ const Parent = ({count}) => (
78
<div>
81
- {new Array(count).fill(true).map((_, index) => (
82
- <Child key={index} />
83
- ))}
79
+ {new Array(count).fill(true).map((_, index) => <Child key={index} />)}
80
</div>
81
);
82
const Child = () => <div>Hi!</div>;
@@ -108,7 +104,7 @@ describe('Store (legacy)', () => {
104
});
105
106
it('should not filter DOM nodes from the store tree', () => {
111
- const Grandparent = ({ flip }) => (
107
+ const Grandparent = ({flip}) => (
108
<div>
109
<div>
110
<Parent flip={flip} />
@@ -117,7 +113,7 @@ describe('Store (legacy)', () => {
113
<Nothing />
114
</div>
115
);
120
- const Parent = ({ flip }) => (
116
+ const Parent = ({flip}) => (
117
<div>
118
{flip ? 'foo' : null}
119
<Child />
@@ -130,12 +126,12 @@ describe('Store (legacy)', () => {
126
127
const container = document.createElement('div');
128
act(() =>
133
- ReactDOM.render(<Grandparent count={4} flip={false} />, container)
129
+ ReactDOM.render(<Grandparent count={4} flip={false} />, container),
130
);
131
expect(store).toMatchSnapshot('1: mount');
132
133
act(() =>
138
- ReactDOM.render(<Grandparent count={4} flip={true} />, container)
134
+ ReactDOM.render(<Grandparent count={4} flip={true} />, container),
135
);
136
expect(store).toMatchSnapshot('2: update');
137
@@ -144,17 +140,15 @@ describe('Store (legacy)', () => {
140
});
141
142
it('should support collapsing parts of the tree', () => {
147
- const Grandparent = ({ count }) => (
143
+ const Grandparent = ({count}) => (
144
<div>
145
<Parent count={count} />
146
<Parent count={count} />
147
</div>
148
);
153
- const Parent = ({ count }) => (
149
+ const Parent = ({count}) => (
150
<div>
155
- {new Array(count).fill(true).map((_, index) => (
156
- <Child key={index} />
157
- ))}
151
+ {new Array(count).fill(true).map((_, index) => <Child key={index} />)}
152
</div>
153
);
154
const Child = () => <div>Hi!</div>;
@@ -162,8 +156,8 @@ describe('Store (legacy)', () => {
156
act(() =>
157
ReactDOM.render(
158
<Grandparent count={2} />,
165
- document.createElement('div')
166
- )
159
+ document.createElement('div'),
160
+ ),
161
);
162
expect(store).toMatchSnapshot('1: mount');
163
@@ -188,7 +182,7 @@ describe('Store (legacy)', () => {
182
});
183
184
it('should support adding and removing children', () => {
191
- const Root = ({ children }) => <div>{children}</div>;
185
+ const Root = ({children}) => <div>{children}</div>;
186
const Component = () => <div />;
187
188
const container = document.createElement('div');
@@ -198,8 +192,8 @@ describe('Store (legacy)', () => {
192
<Root>
193
<Component key="a" />
194
</Root>,
201
- container
202
- )
195
+ container,
196
+ ),
197
);
198
expect(store).toMatchSnapshot('1: mount');
199
@@ -209,8 +203,8 @@ describe('Store (legacy)', () => {
203
<Component key="a" />
204
<Component key="b" />
205
</Root>,
212
- container
213
- )
206
+ container,
207
+ ),
208
);
209
expect(store).toMatchSnapshot('2: add child');
210
@@ -219,14 +213,14 @@ describe('Store (legacy)', () => {
213
<Root>
214
<Component key="b" />
215
</Root>,
222
- container
223
- )
216
+ container,
217
+ ),
218
);
219
expect(store).toMatchSnapshot('3: remove child');
220
});
221
222
it('should support reordering of children', () => {
229
- const Root = ({ children }) => <div>{children}</div>;
223
+ const Root = ({children}) => <div>{children}</div>;
224
const Component = () => <div />;
225
226
const Foo = () => <div>{[<Component key="0" />]}</div>;
@@ -258,11 +252,9 @@ describe('Store (legacy)', () => {
252
});
253
254
it('should support mount and update operations', () => {
261
- const Parent = ({ count }) => (
255
+ const Parent = ({count}) => (
256
<div>
263
- {new Array(count).fill(true).map((_, index) => (
264
- <Child key={index} />
265
- ))}
257
+ {new Array(count).fill(true).map((_, index) => <Child key={index} />)}
258
</div>
259
);
260
const Child = () => <div>Hi!</div>;
@@ -275,8 +267,8 @@ describe('Store (legacy)', () => {
267
<Parent count={1} />
268
<Parent count={3} />
269
</div>,
278
- container
279
- )
270
+ container,
271
+ ),
272
);
273
expect(store).toMatchSnapshot('1: mount');
274
@@ -286,8 +278,8 @@ describe('Store (legacy)', () => {
278
<Parent count={2} />
279
<Parent count={1} />
280
</div>,
289
- container
290
- )
281
+ container,
282
+ ),
283
);
284
expect(store).toMatchSnapshot('2: update');
285
@@ -296,11 +288,9 @@ describe('Store (legacy)', () => {
288
});
289
290
it('should support mount and update operations for multiple roots', () => {
299
- const Parent = ({ count }) => (
291
+ const Parent = ({count}) => (
292
<div>
301
- {new Array(count).fill(true).map((_, index) => (
302
- <Child key={index} />
303
- ))}
293
+ {new Array(count).fill(true).map((_, index) => <Child key={index} />)}
294
</div>
295
);
296
const Child = () => <div>Hi!</div>;
@@ -328,7 +318,7 @@ describe('Store (legacy)', () => {
318
});
319
320
it('should not filter DOM nodes from the store tree', () => {
331
- const Grandparent = ({ flip }) => (
321
+ const Grandparent = ({flip}) => (
322
<div>
323
<div>
324
<Parent flip={flip} />
@@ -337,7 +327,7 @@ describe('Store (legacy)', () => {
327
<Nothing />
328
</div>
329
);
340
- const Parent = ({ flip }) => (
330
+ const Parent = ({flip}) => (
331
<div>
332
{flip ? 'foo' : null}
333
<Child />
@@ -350,7 +340,7 @@ describe('Store (legacy)', () => {
340
341
const container = document.createElement('div');
342
act(() =>
353
- ReactDOM.render(<Grandparent count={4} flip={false} />, container)
343
+ ReactDOM.render(<Grandparent count={4} flip={false} />, container),
344
);
345
expect(store).toMatchSnapshot('1: mount');
346
@@ -361,7 +351,7 @@ describe('Store (legacy)', () => {
351
expect(store).toMatchSnapshot('3: expand div');
352
353
act(() =>
364
- ReactDOM.render(<Grandparent count={4} flip={true} />, container)
354
+ ReactDOM.render(<Grandparent count={4} flip={true} />, container),
355
);
356
expect(store).toMatchSnapshot('4: final update');
357
@@ -370,17 +360,15 @@ describe('Store (legacy)', () => {
360
});
361
362
it('should support expanding parts of the tree', () => {
373
- const Grandparent = ({ count }) => (
363
+ const Grandparent = ({count}) => (
364
<div>
365
<Parent count={count} />
366
<Parent count={count} />
367
</div>
368
);
379
- const Parent = ({ count }) => (
369
+ const Parent = ({count}) => (
370
<div>
381
- {new Array(count).fill(true).map((_, index) => (
382
- <Child key={index} />
383
- ))}
371
+ {new Array(count).fill(true).map((_, index) => <Child key={index} />)}
372
</div>
373
);
374
const Child = () => <div>Hi!</div>;
@@ -388,8 +376,8 @@ describe('Store (legacy)', () => {
376
act(() =>
377
ReactDOM.render(
378
<Grandparent count={2} />,
391
- document.createElement('div')
392
- )
379
+ document.createElement('div'),
380
+ ),
381
);
382
expect(store).toMatchSnapshot('1: mount');
383
@@ -422,10 +410,10 @@ describe('Store (legacy)', () => {
410
});
411
412
it('should support expanding deep parts of the tree', () => {
425
- const Wrapper = ({ forwardedRef }) => (
413
+ const Wrapper = ({forwardedRef}) => (
414
<Nested depth={3} forwardedRef={forwardedRef} />
415
);
428
- const Nested = ({ depth, forwardedRef }) =>
416
+ const Nested = ({depth, forwardedRef}) =>
417
depth > 0 ? (
418
<Nested depth={depth - 1} forwardedRef={forwardedRef} />
419
) : (
@@ -440,8 +428,8 @@ describe('Store (legacy)', () => {
428
act(() =>
429
ReactDOM.render(
430
<Wrapper forwardedRef={refSetter} />,
443
- document.createElement('div')
444
- )
431
+ document.createElement('div'),
432
+ ),
433
);
434
expect(store).toMatchSnapshot('1: mount');
435
@@ -468,7 +456,7 @@ describe('Store (legacy)', () => {
456
});
457
458
it('should support reordering of children', () => {
471
- const Root = ({ children }) => <div>{children}</div>;
459
+ const Root = ({children}) => <div>{children}</div>;
460
const Component = () => <div />;
461
462
const Foo = () => <div>{[<Component key="0" />]}</div>;
packages/react-devtools-shared/src/__tests__/ownersListContext-test.js
+24
-22
@@ -1,8 +1,8 @@
1
// @flow
2
3
import typeof ReactTestRenderer from 'react-test-renderer';
4
-import type { Element } from 'react-devtools-shared/src/devtools/views/Components/types';
5
-import type { FrontendBridge } from 'react-devtools-shared/src/bridge';
4
+import type {Element} from 'react-devtools-shared/src/devtools/views/Components/types';
5
+import type {FrontendBridge} from 'react-devtools-shared/src/bridge';
6
import type Store from 'react-devtools-shared/src/devtools/store';
7
8
describe('OwnersListContext', () => {
@@ -31,17 +31,19 @@ describe('OwnersListContext', () => {
31
ReactDOM = require('react-dom');
32
TestRenderer = utils.requireTestRenderer();
33
34
- BridgeContext = require('react-devtools-shared/src/devtools/views/context').BridgeContext;
34
+ BridgeContext = require('react-devtools-shared/src/devtools/views/context')
35
+ .BridgeContext;
36
OwnersListContext = require('react-devtools-shared/src/devtools/views/Components/OwnersListContext')
37
.OwnersListContext;
38
OwnersListContextController = require('react-devtools-shared/src/devtools/views/Components/OwnersListContext')
39
.OwnersListContextController;
39
- StoreContext = require('react-devtools-shared/src/devtools/views/context').StoreContext;
40
+ StoreContext = require('react-devtools-shared/src/devtools/views/context')
41
+ .StoreContext;
42
TreeContextController = require('react-devtools-shared/src/devtools/views/Components/TreeContext')
43
.TreeContextController;
44
});
45
44
- const Contexts = ({ children, defaultOwnerID = null }) => (
46
+ const Contexts = ({children, defaultOwnerID = null}) => (
47
<BridgeContext.Provider value={bridge}>
48
<StoreContext.Provider value={store}>
49
<TreeContextController defaultOwnerID={defaultOwnerID}>
@@ -64,7 +66,7 @@ describe('OwnersListContext', () => {
66
const Child = () => null;
67
68
utils.act(() =>
67
- ReactDOM.render(<Grandparent />, document.createElement('div'))
69
+ ReactDOM.render(<Grandparent />, document.createElement('div')),
70
);
71
72
expect(store).toMatchSnapshot('mount');
@@ -74,11 +76,11 @@ describe('OwnersListContext', () => {
76
77
let didFinish = false;
78
77
- function Suspender({ owner }) {
79
+ function Suspender({owner}) {
80
const read = React.useContext(OwnersListContext);
81
const owners = read(owner.id);
82
expect(owners).toMatchSnapshot(
81
- `owners for "${(owner && owner.displayName) || ''}"`
83
+ `owners for "${(owner && owner.displayName) || ''}"`,
84
);
85
didFinish = true;
86
return null;
@@ -90,8 +92,8 @@ describe('OwnersListContext', () => {
92
<React.Suspense fallback={null}>
93
<Suspender owner={parent} />
94
</React.Suspense>
93
- </Contexts>
94
- )
95
+ </Contexts>,
96
+ ),
97
);
98
expect(didFinish).toBe(true);
99
@@ -102,8 +104,8 @@ describe('OwnersListContext', () => {
104
<React.Suspense fallback={null}>
105
<Suspender owner={firstChild} />
106
</React.Suspense>
105
- </Contexts>
106
- )
107
+ </Contexts>,
108
+ ),
109
);
110
expect(didFinish).toBe(true);
111
@@ -125,7 +127,7 @@ describe('OwnersListContext', () => {
127
const Child = () => null;
128
129
utils.act(() =>
128
- ReactDOM.render(<Grandparent />, document.createElement('div'))
130
+ ReactDOM.render(<Grandparent />, document.createElement('div')),
131
);
132
133
expect(store).toMatchSnapshot('mount');
@@ -134,11 +136,11 @@ describe('OwnersListContext', () => {
136
137
let didFinish = false;
138
137
- function Suspender({ owner }) {
139
+ function Suspender({owner}) {
140
const read = React.useContext(OwnersListContext);
141
const owners = read(owner.id);
142
expect(owners).toMatchSnapshot(
141
- `owners for "${(owner && owner.displayName) || ''}"`
143
+ `owners for "${(owner && owner.displayName) || ''}"`,
144
);
145
didFinish = true;
146
return null;
@@ -150,8 +152,8 @@ describe('OwnersListContext', () => {
152
<React.Suspense fallback={null}>
153
<Suspender owner={firstChild} />
154
</React.Suspense>
153
- </Contexts>
154
- )
155
+ </Contexts>,
156
+ ),
157
);
158
expect(didFinish).toBe(true);
159
@@ -165,7 +167,7 @@ describe('OwnersListContext', () => {
167
const Parent = () => null;
168
169
utils.act(() =>
168
- ReactDOM.render(<Grandparent />, document.createElement('div'))
170
+ ReactDOM.render(<Grandparent />, document.createElement('div')),
171
);
172
173
expect(store).toMatchSnapshot('mount');
@@ -174,11 +176,11 @@ describe('OwnersListContext', () => {
176
177
let didFinish = false;
178
177
- function Suspender({ owner }) {
179
+ function Suspender({owner}) {
180
const read = React.useContext(OwnersListContext);
181
const owners = read(owner.id);
182
expect(owners).toMatchSnapshot(
181
- `owners for "${(owner && owner.displayName) || ''}"`
183
+ `owners for "${(owner && owner.displayName) || ''}"`,
184
);
185
didFinish = true;
186
return null;
@@ -190,8 +192,8 @@ describe('OwnersListContext', () => {
192
<React.Suspense fallback={null}>
193
<Suspender owner={grandparent} />
194
</React.Suspense>
193
- </Contexts>
194
- )
195
+ </Contexts>,
196
+ ),
197
);
198
expect(didFinish).toBe(true);
199
packages/react-devtools-shared/src/__tests__/profilerContext-test.js
+30
-31
@@ -1,9 +1,9 @@
1
// @flow
2
3
import typeof ReactTestRenderer from 'react-test-renderer';
4
-import type { FrontendBridge } from 'react-devtools-shared/src/bridge';
5
-import type { Context } from 'react-devtools-shared/src/devtools/views/Profiler/ProfilerContext';
6
-import type { DispatcherContext } from 'react-devtools-shared/src/devtools/views/Components/TreeContext';
4
+import type {FrontendBridge} from 'react-devtools-shared/src/bridge';
5
+import type {Context} from 'react-devtools-shared/src/devtools/views/Profiler/ProfilerContext';
6
+import type {DispatcherContext} from 'react-devtools-shared/src/devtools/views/Components/TreeContext';
7
import type Store from 'react-devtools-shared/src/devtools/store';
8
9
describe('ProfilerContext', () => {
@@ -35,12 +35,14 @@ describe('ProfilerContext', () => {
35
ReactDOM = require('react-dom');
36
TestRenderer = utils.requireTestRenderer();
37
38
- BridgeContext = require('react-devtools-shared/src/devtools/views/context').BridgeContext;
38
+ BridgeContext = require('react-devtools-shared/src/devtools/views/context')
39
+ .BridgeContext;
40
ProfilerContext = require('react-devtools-shared/src/devtools/views/Profiler/ProfilerContext')
41
.ProfilerContext;
42
ProfilerContextController = require('react-devtools-shared/src/devtools/views/Profiler/ProfilerContext')
43
.ProfilerContextController;
43
- StoreContext = require('react-devtools-shared/src/devtools/views/context').StoreContext;
44
+ StoreContext = require('react-devtools-shared/src/devtools/views/context')
45
+ .StoreContext;
46
TreeContextController = require('react-devtools-shared/src/devtools/views/Components/TreeContext')
47
.TreeContextController;
48
TreeDispatcherContext = require('react-devtools-shared/src/devtools/views/Components/TreeContext')
@@ -58,8 +60,7 @@ describe('ProfilerContext', () => {
60
<StoreContext.Provider value={store}>
61
<TreeContextController
62
defaultSelectedElementID={defaultSelectedElementID}
61
- defaultSelectedElementIndex={defaultSelectedElementIndex}
62
- >
63
+ defaultSelectedElementIndex={defaultSelectedElementIndex}>
64
<ProfilerContextController>{children}</ProfilerContextController>
65
</TreeContextController>
66
</StoreContext.Provider>
@@ -79,7 +80,7 @@ describe('ProfilerContext', () => {
80
TestRenderer.create(
81
<Contexts>
82
<ContextReader />
82
- </Contexts>
83
+ </Contexts>,
84
);
85
});
86
@@ -105,7 +106,7 @@ describe('ProfilerContext', () => {
106
const Example = () => null;
107
108
utils.act(() =>
108
- ReactDOM.render(<Example />, document.createElement('div'))
109
+ ReactDOM.render(<Example />, document.createElement('div')),
110
);
111
112
let context: Context = ((null: any): Context);
@@ -121,7 +122,7 @@ describe('ProfilerContext', () => {
122
TestRenderer.create(
123
<Contexts>
124
<ContextReader />
124
- </Contexts>
125
+ </Contexts>,
126
);
127
});
128
expect(context).not.toBeNull();
@@ -167,16 +168,15 @@ describe('ProfilerContext', () => {
168
TestRenderer.create(
169
<Contexts
170
defaultSelectedElementID={store.getElementIDAtIndex(3)}
170
- defaultSelectedElementIndex={3}
171
- >
171
+ defaultSelectedElementIndex={3}>
172
<ContextReader />
173
- </Contexts>
174
- )
173
+ </Contexts>,
174
+ ),
175
);
176
177
expect(context).not.toBeNull();
178
expect(context.rootID).toBe(
179
- store.getRootIDForElement(((store.getElementIDAtIndex(3): any): number))
179
+ store.getRootIDForElement(((store.getElementIDAtIndex(3): any): number)),
180
);
181
182
done();
@@ -208,17 +208,16 @@ describe('ProfilerContext', () => {
208
TestRenderer.create(
209
<Contexts
210
defaultSelectedElementID={store.getElementIDAtIndex(3)}
211
- defaultSelectedElementIndex={3}
212
- >
211
+ defaultSelectedElementIndex={3}>
212
<ContextReader />
214
- </Contexts>
215
- )
213
+ </Contexts>,
214
+ ),
215
);
216
217
// Verify the default profiling root is the first one.
218
expect(context).not.toBeNull();
219
expect(context.rootID).toBe(
221
- store.getRootIDForElement(((store.getElementIDAtIndex(0): any): number))
220
+ store.getRootIDForElement(((store.getElementIDAtIndex(0): any): number)),
221
);
222
223
done();
@@ -257,8 +256,8 @@ describe('ProfilerContext', () => {
256
TestRenderer.create(
257
<Contexts defaultSelectedElementID={id} defaultSelectedElementIndex={3}>
258
<ContextReader />
260
- </Contexts>
261
- )
259
+ </Contexts>,
260
+ ),
261
);
262
263
expect(selectedElementID).toBe(id);
@@ -272,7 +271,7 @@ describe('ProfilerContext', () => {
271
const otherID = ((store.getElementIDAtIndex(0): any): number);
272
273
// Change the selected element within a the Components tab.
275
- utils.act(() => dispatch({ type: 'SELECT_ELEMENT_AT_INDEX', payload: 0 }));
274
+ utils.act(() => dispatch({type: 'SELECT_ELEMENT_AT_INDEX', payload: 0}));
275
276
// Verify that the initial Profiler root selection is maintained.
277
expect(selectedElementID).toBe(otherID);
@@ -283,15 +282,15 @@ describe('ProfilerContext', () => {
282
});
283
284
it('should sync selected element in the Components tab too, provided the element is a match', async done => {
286
- const GrandParent = ({ includeChild }) => (
285
+ const GrandParent = ({includeChild}) => (
286
<Parent includeChild={includeChild} />
287
);
289
- const Parent = ({ includeChild }) => (includeChild ? <Child /> : null);
288
+ const Parent = ({includeChild}) => (includeChild ? <Child /> : null);
289
const Child = () => null;
290
291
const container = document.createElement('div');
292
utils.act(() =>
294
- ReactDOM.render(<GrandParent includeChild={true} />, container)
293
+ ReactDOM.render(<GrandParent includeChild={true} />, container),
294
);
295
expect(store).toMatchSnapshot('mounted');
296
@@ -301,10 +300,10 @@ describe('ProfilerContext', () => {
300
// Profile and record updates.
301
await utils.actAsync(() => store.profilerStore.startProfiling());
302
await utils.actAsync(() =>
304
- ReactDOM.render(<GrandParent includeChild={true} />, container)
303
+ ReactDOM.render(<GrandParent includeChild={true} />, container),
304
);
305
await utils.actAsync(() =>
307
- ReactDOM.render(<GrandParent includeChild={false} />, container)
306
+ ReactDOM.render(<GrandParent includeChild={false} />, container),
307
);
308
await utils.actAsync(() => store.profilerStore.stopProfiling());
309
@@ -322,8 +321,8 @@ describe('ProfilerContext', () => {
321
TestRenderer.create(
322
<Contexts>
323
<ContextReader />
325
- </Contexts>
326
- )
324
+ </Contexts>,
325
+ ),
326
);
327
expect(selectedElementID).toBeNull();
328
@@ -340,7 +339,7 @@ describe('ProfilerContext', () => {
339
expect(selectedElementID).toBe(parentID);
340
341
expect(console.warn).toHaveBeenCalledWith(
343
- `No element found with id "${childID}"`
342
+ `No element found with id "${childID}"`,
343
);
344
345
done();
packages/react-devtools-shared/src/__tests__/profilerStore-test.js
+2
-2
@@ -21,7 +21,7 @@ describe('ProfilerStore', () => {
21
});
22
23
it('should not remove profiling data when roots are unmounted', async () => {
24
- const Parent = ({ count }) =>
24
+ const Parent = ({count}) =>
25
new Array(count)
26
.fill(true)
27
.map((_, index) => <Child key={index} duration={index} />);
@@ -66,7 +66,7 @@ describe('ProfilerStore', () => {
66
expect(store.profilerStore.profilingData).not.toBe(fauxProfilingData);
67
expect(console.warn).toHaveBeenCalledTimes(1);
68
expect(console.warn).toHaveBeenCalledWith(
69
- 'Profiling data cannot be updated while profiling is in progress.'
69
+ 'Profiling data cannot be updated while profiling is in progress.',
70
);
71
utils.act(() => store.profilerStore.stopProfiling());
72
store.profilerStore.profilingData = fauxProfilingData;
packages/react-devtools-shared/src/__tests__/profilingCache-test.js
+50
-50
@@ -1,7 +1,7 @@
1
// @flow
2
3
import typeof ReactTestRenderer from 'react-test-renderer';
4
-import type { FrontendBridge } from 'react-devtools-shared/src/bridge';
4
+import type {FrontendBridge} from 'react-devtools-shared/src/bridge';
5
import type Store from 'react-devtools-shared/src/devtools/store';
6
7
describe('ProfilingCache', () => {
@@ -33,7 +33,7 @@ describe('ProfilingCache', () => {
33
});
34
35
it('should collect data for each root (including ones added or mounted after profiling started)', () => {
36
- const Parent = ({ count }) => {
36
+ const Parent = ({count}) => {
37
Scheduler.unstable_advanceTime(10);
38
const children = new Array(count)
39
.fill(true)
@@ -45,7 +45,7 @@ describe('ProfilingCache', () => {
45
</React.Fragment>
46
);
47
};
48
- const Child = ({ duration }) => {
48
+ const Child = ({duration}) => {
49
Scheduler.unstable_advanceTime(duration);
50
return null;
51
};
@@ -67,13 +67,13 @@ describe('ProfilingCache', () => {
67
68
let allProfilingDataForRoots = [];
69
70
- function Validator({ previousProfilingDataForRoot, rootID }) {
70
+ function Validator({previousProfilingDataForRoot, rootID}) {
71
const profilingDataForRoot = store.profilerStore.getDataForRoot(rootID);
72
if (previousProfilingDataForRoot != null) {
73
expect(profilingDataForRoot).toEqual(previousProfilingDataForRoot);
74
} else {
75
expect(profilingDataForRoot).toMatchSnapshot(
76
- `Data for root ${profilingDataForRoot.displayName}`
76
+ `Data for root ${profilingDataForRoot.displayName}`,
77
);
78
}
79
allProfilingDataForRoots.push(profilingDataForRoot);
@@ -94,8 +94,8 @@ describe('ProfilingCache', () => {
94
<Validator
95
previousProfilingDataForRoot={null}
96
rootID={dataForRoot.rootID}
97
- />
98
- )
97
+ />,
98
+ ),
99
);
100
});
101
}
@@ -110,14 +110,14 @@ describe('ProfilingCache', () => {
110
<Validator
111
previousProfilingDataForRoot={profilingDataForRoot}
112
rootID={profilingDataForRoot.rootID}
113
- />
114
- )
113
+ />,
114
+ ),
115
);
116
});
117
});
118
119
it('should collect data for each commit', () => {
120
- const Parent = ({ count }) => {
120
+ const Parent = ({count}) => {
121
Scheduler.unstable_advanceTime(10);
122
const children = new Array(count)
123
.fill(true)
@@ -129,7 +129,7 @@ describe('ProfilingCache', () => {
129
</React.Fragment>
130
);
131
};
132
- const Child = ({ duration }) => {
132
+ const Child = ({duration}) => {
133
Scheduler.unstable_advanceTime(duration);
134
return null;
135
};
@@ -146,14 +146,14 @@ describe('ProfilingCache', () => {
146
147
const allCommitData = [];
148
149
- function Validator({ commitIndex, previousCommitDetails, rootID }) {
149
+ function Validator({commitIndex, previousCommitDetails, rootID}) {
150
const commitData = store.profilerStore.getCommitData(rootID, commitIndex);
151
if (previousCommitDetails != null) {
152
expect(commitData).toEqual(previousCommitDetails);
153
} else {
154
allCommitData.push(commitData);
155
expect(commitData).toMatchSnapshot(
156
- `CommitDetails commitIndex: ${commitIndex}`
156
+ `CommitDetails commitIndex: ${commitIndex}`,
157
);
158
}
159
return null;
@@ -168,7 +168,7 @@ describe('ProfilingCache', () => {
168
commitIndex={commitIndex}
169
previousCommitDetails={null}
170
rootID={rootID}
171
- />
171
+ />,
172
);
173
});
174
}
@@ -184,7 +184,7 @@ describe('ProfilingCache', () => {
184
commitIndex={commitIndex}
185
previousCommitDetails={allCommitData[commitIndex]}
186
rootID={rootID}
187
- />
187
+ />,
188
);
189
});
190
}
@@ -197,12 +197,12 @@ describe('ProfilingCache', () => {
197
198
class LegacyContextProvider extends React.Component<
199
any,
200
- {| count: number |}
200
+ {|count: number|},
201
> {
202
static childContextTypes = {
203
count: PropTypes.number,
204
};
205
- state = { count: 0 };
205
+ state = {count: 0};
206
getChildContext() {
207
return this.state;
208
}
@@ -219,7 +219,7 @@ describe('ProfilingCache', () => {
219
}
220
}
221
222
- const FunctionComponentWithHooks = ({ count }) => {
222
+ const FunctionComponentWithHooks = ({count}) => {
223
React.useMemo(() => count, [count]);
224
return null;
225
};
@@ -245,26 +245,26 @@ describe('ProfilingCache', () => {
245
utils.act(() => store.profilerStore.startProfiling());
246
utils.act(() => ReactDOM.render(<LegacyContextProvider />, container));
247
expect(instance).not.toBeNull();
248
- utils.act(() => (instance: any).setState({ count: 1 }));
248
+ utils.act(() => (instance: any).setState({count: 1}));
249
utils.act(() =>
250
- ReactDOM.render(<LegacyContextProvider foo={123} />, container)
250
+ ReactDOM.render(<LegacyContextProvider foo={123} />, container),
251
);
252
utils.act(() =>
253
- ReactDOM.render(<LegacyContextProvider bar="abc" />, container)
253
+ ReactDOM.render(<LegacyContextProvider bar="abc" />, container),
254
);
255
utils.act(() => ReactDOM.render(<LegacyContextProvider />, container));
256
utils.act(() => store.profilerStore.stopProfiling());
257
258
const allCommitData = [];
259
260
- function Validator({ commitIndex, previousCommitDetails, rootID }) {
260
+ function Validator({commitIndex, previousCommitDetails, rootID}) {
261
const commitData = store.profilerStore.getCommitData(rootID, commitIndex);
262
if (previousCommitDetails != null) {
263
expect(commitData).toEqual(previousCommitDetails);
264
} else {
265
allCommitData.push(commitData);
266
expect(commitData).toMatchSnapshot(
267
- `CommitDetails commitIndex: ${commitIndex}`
267
+ `CommitDetails commitIndex: ${commitIndex}`,
268
);
269
}
270
return null;
@@ -279,7 +279,7 @@ describe('ProfilingCache', () => {
279
commitIndex={commitIndex}
280
previousCommitDetails={null}
281
rootID={rootID}
282
- />
282
+ />,
283
);
284
});
285
}
@@ -295,7 +295,7 @@ describe('ProfilingCache', () => {
295
commitIndex={commitIndex}
296
previousCommitDetails={allCommitData[commitIndex]}
297
rootID={rootID}
298
- />
298
+ />,
299
);
300
});
301
}
@@ -324,16 +324,16 @@ describe('ProfilingCache', () => {
324
325
utils.act(() => store.profilerStore.startProfiling());
326
utils.act(() =>
327
- ReactDOM.render(<Grandparent />, document.createElement('div'))
327
+ ReactDOM.render(<Grandparent />, document.createElement('div')),
328
);
329
utils.act(() => store.profilerStore.stopProfiling());
330
331
let commitData = null;
332
333
- function Validator({ commitIndex, rootID }) {
333
+ function Validator({commitIndex, rootID}) {
334
commitData = store.profilerStore.getCommitData(rootID, commitIndex);
335
expect(commitData).toMatchSnapshot(
336
- `CommitDetails with filtered self durations`
336
+ `CommitDetails with filtered self durations`,
337
);
338
return null;
339
}
@@ -380,17 +380,17 @@ describe('ProfilingCache', () => {
380
381
utils.act(() => store.profilerStore.startProfiling());
382
await utils.actAsync(() =>
383
- ReactDOM.render(<Parent />, document.createElement('div'))
383
+ ReactDOM.render(<Parent />, document.createElement('div')),
384
);
385
utils.act(() => store.profilerStore.stopProfiling());
386
387
const allCommitData = [];
388
389
- function Validator({ commitIndex, rootID }) {
389
+ function Validator({commitIndex, rootID}) {
390
const commitData = store.profilerStore.getCommitData(rootID, commitIndex);
391
allCommitData.push(commitData);
392
expect(commitData).toMatchSnapshot(
393
- `CommitDetails with filtered self durations`
393
+ `CommitDetails with filtered self durations`,
394
);
395
return null;
396
}
@@ -400,7 +400,7 @@ describe('ProfilingCache', () => {
400
for (let commitIndex = 0; commitIndex < 2; commitIndex++) {
401
utils.act(() => {
402
TestRenderer.create(
403
- <Validator commitIndex={commitIndex} rootID={rootID} />
403
+ <Validator commitIndex={commitIndex} rootID={rootID} />,
404
);
405
});
406
}
@@ -411,7 +411,7 @@ describe('ProfilingCache', () => {
411
});
412
413
it('should collect data for each rendered fiber', () => {
414
- const Parent = ({ count }) => {
414
+ const Parent = ({count}) => {
415
Scheduler.unstable_advanceTime(10);
416
const children = new Array(count)
417
.fill(true)
@@ -423,7 +423,7 @@ describe('ProfilingCache', () => {
423
</React.Fragment>
424
);
425
};
426
- const Child = ({ duration }) => {
426
+ const Child = ({duration}) => {
427
Scheduler.unstable_advanceTime(duration);
428
return null;
429
};
@@ -439,7 +439,7 @@ describe('ProfilingCache', () => {
439
440
const allFiberCommits = [];
441
442
- function Validator({ fiberID, previousFiberCommits, rootID }) {
442
+ function Validator({fiberID, previousFiberCommits, rootID}) {
443
const fiberCommits = store.profilerStore.profilingCache.getFiberCommits({
444
fiberID,
445
rootID,
@@ -449,7 +449,7 @@ describe('ProfilingCache', () => {
449
} else {
450
allFiberCommits.push(fiberCommits);
451
expect(fiberCommits).toMatchSnapshot(
452
- `FiberCommits: element ${fiberID}`
452
+ `FiberCommits: element ${fiberID}`,
453
);
454
}
455
return null;
@@ -468,7 +468,7 @@ describe('ProfilingCache', () => {
468
fiberID={fiberID}
469
previousFiberCommits={null}
470
rootID={rootID}
471
- />
471
+ />,
472
);
473
});
474
}
@@ -488,14 +488,14 @@ describe('ProfilingCache', () => {
488
fiberID={fiberID}
489
previousFiberCommits={allFiberCommits[index]}
490
rootID={rootID}
491
- />
491
+ />,
492
);
493
});
494
}
495
});
496
497
it('should report every traced interaction', () => {
498
- const Parent = ({ count }) => {
498
+ const Parent = ({count}) => {
499
Scheduler.unstable_advanceTime(10);
500
const children = new Array(count)
501
.fill(true)
@@ -507,7 +507,7 @@ describe('ProfilingCache', () => {
507
</React.Fragment>
508
);
509
};
510
- const Child = ({ duration }) => {
510
+ const Child = ({duration}) => {
511
Scheduler.unstable_advanceTime(duration);
512
return null;
513
};
@@ -520,25 +520,25 @@ describe('ProfilingCache', () => {
520
SchedulerTracing.unstable_trace(
521
'mount: one child',
522
Scheduler.unstable_now(),
523
- () => ReactDOM.render(<Parent count={1} />, container)
524
- )
523
+ () => ReactDOM.render(<Parent count={1} />, container),
524
+ ),
525
);
526
utils.act(() =>
527
SchedulerTracing.unstable_trace(
528
'update: two children',
529
Scheduler.unstable_now(),
530
- () => ReactDOM.render(<Parent count={2} />, container)
531
- )
530
+ () => ReactDOM.render(<Parent count={2} />, container),
531
+ ),
532
);
533
utils.act(() => store.profilerStore.stopProfiling());
534
535
let interactions = null;
536
537
- function Validator({ previousInteractions, rootID }) {
537
+ function Validator({previousInteractions, rootID}) {
538
interactions = store.profilerStore.profilingCache.getInteractionsChartData(
539
{
540
rootID,
541
- }
541
+ },
542
).interactions;
543
if (previousInteractions != null) {
544
expect(interactions).toEqual(previousInteractions);
@@ -552,8 +552,8 @@ describe('ProfilingCache', () => {
552
553
utils.act(() =>
554
TestRenderer.create(
555
- <Validator previousInteractions={null} rootID={rootID} />
556
- )
555
+ <Validator previousInteractions={null} rootID={rootID} />,
556
+ ),
557
);
558
559
expect(interactions).not.toBeNull();
@@ -562,8 +562,8 @@ describe('ProfilingCache', () => {
562
563
utils.act(() =>
564
TestRenderer.create(
565
- <Validator previousInteractions={interactions} rootID={rootID} />
566
- )
565
+ <Validator previousInteractions={interactions} rootID={rootID} />,
566
+ ),
567
);
568
});
569
});
packages/react-devtools-shared/src/__tests__/profilingCharts-test.js
+25
-25
@@ -41,7 +41,7 @@ describe('profiling charts', () => {
41
};
42
43
// Memoize children to verify that chart doesn't include in the update.
44
- const Child = React.memo(function Child({ duration }) {
44
+ const Child = React.memo(function Child({duration}) {
45
Scheduler.unstable_advanceTime(duration);
46
return null;
47
});
@@ -51,21 +51,21 @@ describe('profiling charts', () => {
51
utils.act(() => store.profilerStore.startProfiling());
52
utils.act(() =>
53
SchedulerTracing.unstable_trace('mount', Scheduler.unstable_now(), () =>
54
- ReactDOM.render(<Parent />, container)
55
- )
54
+ ReactDOM.render(<Parent />, container),
55
+ ),
56
);
57
utils.act(() =>
58
SchedulerTracing.unstable_trace(
59
'update',
60
Scheduler.unstable_now(),
61
- () => ReactDOM.render(<Parent />, container)
62
- )
61
+ () => ReactDOM.render(<Parent />, container),
62
+ ),
63
);
64
utils.act(() => store.profilerStore.stopProfiling());
65
66
let renderFinished = false;
67
68
- function Validator({ commitIndex, rootID }) {
68
+ function Validator({commitIndex, rootID}) {
69
const commitTree = store.profilerStore.profilingCache.getCommitTree({
70
commitIndex,
71
rootID,
@@ -75,11 +75,11 @@ describe('profiling charts', () => {
75
commitIndex,
76
commitTree,
77
rootID,
78
- }
78
+ },
79
);
80
expect(commitTree).toMatchSnapshot(`${commitIndex}: CommitTree`);
81
expect(chartData).toMatchSnapshot(
82
- `${commitIndex}: FlamegraphChartData`
82
+ `${commitIndex}: FlamegraphChartData`,
83
);
84
renderFinished = true;
85
return null;
@@ -92,7 +92,7 @@ describe('profiling charts', () => {
92
93
utils.act(() => {
94
TestRenderer.create(
95
- <Validator commitIndex={commitIndex} rootID={rootID} />
95
+ <Validator commitIndex={commitIndex} rootID={rootID} />,
96
);
97
});
98
@@ -117,7 +117,7 @@ describe('profiling charts', () => {
117
};
118
119
// Memoize children to verify that chart doesn't include in the update.
120
- const Child = React.memo(function Child({ duration }) {
120
+ const Child = React.memo(function Child({duration}) {
121
Scheduler.unstable_advanceTime(duration);
122
return null;
123
});
@@ -127,21 +127,21 @@ describe('profiling charts', () => {
127
utils.act(() => store.profilerStore.startProfiling());
128
utils.act(() =>
129
SchedulerTracing.unstable_trace('mount', Scheduler.unstable_now(), () =>
130
- ReactDOM.render(<Parent />, container)
131
- )
130
+ ReactDOM.render(<Parent />, container),
131
+ ),
132
);
133
utils.act(() =>
134
SchedulerTracing.unstable_trace(
135
'update',
136
Scheduler.unstable_now(),
137
- () => ReactDOM.render(<Parent />, container)
138
- )
137
+ () => ReactDOM.render(<Parent />, container),
138
+ ),
139
);
140
utils.act(() => store.profilerStore.stopProfiling());
141
142
let renderFinished = false;
143
144
- function Validator({ commitIndex, rootID }) {
144
+ function Validator({commitIndex, rootID}) {
145
const commitTree = store.profilerStore.profilingCache.getCommitTree({
146
commitIndex,
147
rootID,
@@ -151,7 +151,7 @@ describe('profiling charts', () => {
151
commitIndex,
152
commitTree,
153
rootID,
154
- }
154
+ },
155
);
156
expect(commitTree).toMatchSnapshot(`${commitIndex}: CommitTree`);
157
expect(chartData).toMatchSnapshot(`${commitIndex}: RankedChartData`);
@@ -166,7 +166,7 @@ describe('profiling charts', () => {
166
167
utils.act(() => {
168
TestRenderer.create(
169
- <Validator commitIndex={commitIndex} rootID={rootID} />
169
+ <Validator commitIndex={commitIndex} rootID={rootID} />,
170
);
171
});
172
@@ -189,7 +189,7 @@ describe('profiling charts', () => {
189
};
190
191
// Memoize children to verify that chart doesn't include in the update.
192
- const Child = React.memo(function Child({ duration }) {
192
+ const Child = React.memo(function Child({duration}) {
193
Scheduler.unstable_advanceTime(duration);
194
return null;
195
});
@@ -199,25 +199,25 @@ describe('profiling charts', () => {
199
utils.act(() => store.profilerStore.startProfiling());
200
utils.act(() =>
201
SchedulerTracing.unstable_trace('mount', Scheduler.unstable_now(), () =>
202
- ReactDOM.render(<Parent />, container)
203
- )
202
+ ReactDOM.render(<Parent />, container),
203
+ ),
204
);
205
utils.act(() =>
206
SchedulerTracing.unstable_trace(
207
'update',
208
Scheduler.unstable_now(),
209
- () => ReactDOM.render(<Parent />, container)
210
- )
209
+ () => ReactDOM.render(<Parent />, container),
210
+ ),
211
);
212
utils.act(() => store.profilerStore.stopProfiling());
213
214
let renderFinished = false;
215
216
- function Validator({ commitIndex, rootID }) {
216
+ function Validator({commitIndex, rootID}) {
217
const chartData = store.profilerStore.profilingCache.getInteractionsChartData(
218
{
219
rootID,
220
- }
220
+ },
221
);
222
expect(chartData).toMatchSnapshot('Interactions');
223
renderFinished = true;
@@ -231,7 +231,7 @@ describe('profiling charts', () => {
231
232
utils.act(() => {
233
TestRenderer.create(
234
- <Validator commitIndex={commitIndex} rootID={rootID} />
234
+ <Validator commitIndex={commitIndex} rootID={rootID} />,
235
);
236
});
237
packages/react-devtools-shared/src/__tests__/profilingCommitTreeBuilder-test.js
+3
-3
@@ -26,7 +26,7 @@ describe('commit tree', () => {
26
});
27
28
it('should be able to rebuild the store tree for each commit', () => {
29
- const Parent = ({ count }) => {
29
+ const Parent = ({count}) => {
30
Scheduler.unstable_advanceTime(10);
31
return new Array(count)
32
.fill(true)
@@ -48,7 +48,7 @@ describe('commit tree', () => {
48
49
let renderFinished = false;
50
51
- function Validator({ commitIndex, rootID }) {
51
+ function Validator({commitIndex, rootID}) {
52
const commitTree = store.profilerStore.profilingCache.getCommitTree({
53
commitIndex,
54
rootID,
@@ -65,7 +65,7 @@ describe('commit tree', () => {
65
66
utils.act(() => {
67
TestRenderer.create(
68
- <Validator commitIndex={commitIndex} rootID={rootID} />
68
+ <Validator commitIndex={commitIndex} rootID={rootID} />,
69
);
70
});
71
packages/react-devtools-shared/src/__tests__/profilingUtils-test.js
+2
-2
@@ -13,8 +13,8 @@ describe('profiling utils', () => {
13
({
14
version: 0,
15
dataForRoots: [],
16
- }: any)
17
- )
16
+ }: any),
17
+ ),
18
).toThrow('Unsupported profiler export version "0"');
19
});
20
});
packages/react-devtools-shared/src/__tests__/setupTests.js
+7
-4
@@ -1,6 +1,9 @@
1
// @flow
2
3
-import type { BackendBridge, FrontendBridge } from 'react-devtools-shared/src/bridge';
3
+import type {
4
+ BackendBridge,
5
+ FrontendBridge,
6
+} from 'react-devtools-shared/src/bridge';
7
8
const env = jasmine.getEnv();
9
env.beforeEach(() => {
@@ -9,10 +12,10 @@ env.beforeEach(() => {
12
// That's because we reset modules between tests,
13
// which disconnects the DevTool's cache from the current dispatcher ref.
14
const Agent = require('react-devtools-shared/src/backend/agent').default;
12
- const { initBackend } = require('react-devtools-shared/src/backend');
15
+ const {initBackend} = require('react-devtools-shared/src/backend');
16
const Bridge = require('react-devtools-shared/src/bridge').default;
17
const Store = require('react-devtools-shared/src/devtools/store').default;
15
- const { installHook } = require('react-devtools-shared/src/hook');
18
+ const {installHook} = require('react-devtools-shared/src/hook');
19
const {
20
getDefaultComponentFilters,
21
saveComponentFilters,
@@ -49,7 +52,7 @@ env.beforeEach(() => {
52
};
53
},
54
send(event: string, payload: any, transferable?: Array<any>) {
52
- bridgeListeners.forEach(callback => callback({ event, payload }));
55
+ bridgeListeners.forEach(callback => callback({event, payload}));
56
},
57
});
58
packages/react-devtools-shared/src/__tests__/store-test.js
+62
-62
@@ -24,7 +24,7 @@ describe('Store', () => {
24
const Component = () => <div>Hi</div>;
25
26
act(() =>
27
- ReactDOM.render(<Component count={4} />, document.createElement('div'))
27
+ ReactDOM.render(<Component count={4} />, document.createElement('div')),
28
);
29
expect(store).toMatchSnapshot('1: mount');
30
@@ -33,12 +33,12 @@ describe('Store', () => {
33
const rootID = store.roots[0];
34
35
expect(() => store.toggleIsCollapsed(rootID, true)).toThrow(
36
- 'Root nodes cannot be collapsed'
36
+ 'Root nodes cannot be collapsed',
37
);
38
});
39
40
it('should properly handle a root with no visible nodes', () => {
41
- const Root = ({ children }) => children;
41
+ const Root = ({children}) => children;
42
43
const container = document.createElement('div');
44
@@ -55,13 +55,13 @@ describe('Store', () => {
55
});
56
57
it('should support mount and update operations', () => {
58
- const Grandparent = ({ count }) => (
58
+ const Grandparent = ({count}) => (
59
<React.Fragment>
60
<Parent count={count} />
61
<Parent count={count} />
62
</React.Fragment>
63
);
64
- const Parent = ({ count }) =>
64
+ const Parent = ({count}) =>
65
new Array(count).fill(true).map((_, index) => <Child key={index} />);
66
const Child = () => <div>Hi!</div>;
67
@@ -78,7 +78,7 @@ describe('Store', () => {
78
});
79
80
it('should support mount and update operations for multiple roots', () => {
81
- const Parent = ({ count }) =>
81
+ const Parent = ({count}) =>
82
new Array(count).fill(true).map((_, index) => <Child key={index} />);
83
const Child = () => <div>Hi!</div>;
84
@@ -123,8 +123,8 @@ describe('Store', () => {
123
act(() =>
124
ReactDOM.render(
125
<Grandparent count={4} />,
126
- document.createElement('div')
127
- )
126
+ document.createElement('div'),
127
+ ),
128
);
129
expect(store).toMatchSnapshot('1: mount');
130
});
@@ -137,7 +137,7 @@ describe('Store', () => {
137
const Component = () => {
138
return <div>Hello</div>;
139
};
140
- const Wrapper = ({ shouldSuspense }) => (
140
+ const Wrapper = ({shouldSuspense}) => (
141
<React.Fragment>
142
<Component key="Outside" />
143
<React.Suspense fallback={<Loading />}>
@@ -207,8 +207,8 @@ describe('Store', () => {
207
suspendFirst={false}
208
suspendSecond={false}
209
/>,
210
- container
211
- )
210
+ container,
211
+ ),
212
);
213
expect(store).toMatchSnapshot('1: third child is suspended');
214
act(() =>
@@ -218,8 +218,8 @@ describe('Store', () => {
218
suspendFirst={true}
219
suspendSecond={false}
220
/>,
221
- container
222
- )
221
+ container,
222
+ ),
223
);
224
expect(store).toMatchSnapshot('2: first and third child are suspended');
225
act(() =>
@@ -229,8 +229,8 @@ describe('Store', () => {
229
suspendFirst={false}
230
suspendSecond={true}
231
/>,
232
- container
233
- )
232
+ container,
233
+ ),
234
);
235
expect(store).toMatchSnapshot('3: second and third child are suspended');
236
act(() =>
@@ -240,8 +240,8 @@ describe('Store', () => {
240
suspendFirst={true}
241
suspendSecond={false}
242
/>,
243
- container
244
- )
243
+ container,
244
+ ),
245
);
246
expect(store).toMatchSnapshot('4: first and third child are suspended');
247
act(() =>
@@ -251,8 +251,8 @@ describe('Store', () => {
251
suspendFirst={true}
252
suspendSecond={false}
253
/>,
254
- container
255
- )
254
+ container,
255
+ ),
256
);
257
expect(store).toMatchSnapshot('5: parent is suspended');
258
act(() =>
@@ -262,8 +262,8 @@ describe('Store', () => {
262
suspendFirst={true}
263
suspendSecond={true}
264
/>,
265
- container
266
- )
265
+ container,
266
+ ),
267
);
268
expect(store).toMatchSnapshot('6: all children are suspended');
269
act(() =>
@@ -273,8 +273,8 @@ describe('Store', () => {
273
suspendFirst={false}
274
suspendSecond={false}
275
/>,
276
- container
277
- )
276
+ container,
277
+ ),
278
);
279
expect(store).toMatchSnapshot('7: only third child is suspended');
280
@@ -284,7 +284,7 @@ describe('Store', () => {
284
id: store.getElementIDAtIndex(4),
285
rendererID,
286
forceFallback: true,
287
- })
287
+ }),
288
);
289
expect(store).toMatchSnapshot('8: first and third child are suspended');
290
act(() =>
@@ -292,7 +292,7 @@ describe('Store', () => {
292
id: store.getElementIDAtIndex(2),
293
rendererID,
294
forceFallback: true,
295
- })
295
+ }),
296
);
297
expect(store).toMatchSnapshot('9: parent is suspended');
298
act(() =>
@@ -302,8 +302,8 @@ describe('Store', () => {
302
suspendFirst={true}
303
suspendSecond={true}
304
/>,
305
- container
306
- )
305
+ container,
306
+ ),
307
);
308
expect(store).toMatchSnapshot('10: parent is suspended');
309
act(() =>
@@ -311,7 +311,7 @@ describe('Store', () => {
311
id: store.getElementIDAtIndex(2),
312
rendererID,
313
forceFallback: false,
314
- })
314
+ }),
315
);
316
expect(store).toMatchSnapshot('11: all children are suspended');
317
act(() =>
@@ -319,7 +319,7 @@ describe('Store', () => {
319
id: store.getElementIDAtIndex(4),
320
rendererID,
321
forceFallback: false,
322
- })
322
+ }),
323
);
324
expect(store).toMatchSnapshot('12: all children are suspended');
325
act(() =>
@@ -329,28 +329,28 @@ describe('Store', () => {
329
suspendFirst={false}
330
suspendSecond={false}
331
/>,
332
- container
333
- )
332
+ container,
333
+ ),
334
);
335
expect(store).toMatchSnapshot('13: third child is suspended');
336
});
337
338
it('should support collapsing parts of the tree', () => {
339
- const Grandparent = ({ count }) => (
339
+ const Grandparent = ({count}) => (
340
<React.Fragment>
341
<Parent count={count} />
342
<Parent count={count} />
343
</React.Fragment>
344
);
345
- const Parent = ({ count }) =>
345
+ const Parent = ({count}) =>
346
new Array(count).fill(true).map((_, index) => <Child key={index} />);
347
const Child = () => <div>Hi!</div>;
348
349
act(() =>
350
ReactDOM.render(
351
<Grandparent count={2} />,
352
- document.createElement('div')
353
- )
352
+ document.createElement('div'),
353
+ ),
354
);
355
expect(store).toMatchSnapshot('1: mount');
356
@@ -375,7 +375,7 @@ describe('Store', () => {
375
});
376
377
it('should support reordering of children', () => {
378
- const Root = ({ children }) => children;
378
+ const Root = ({children}) => children;
379
const Component = () => null;
380
381
const Foo = () => [<Component key="0" />];
@@ -405,7 +405,7 @@ describe('Store', () => {
405
});
406
407
it('should support mount and update operations', () => {
408
- const Parent = ({ count }) =>
408
+ const Parent = ({count}) =>
409
new Array(count).fill(true).map((_, index) => <Child key={index} />);
410
const Child = () => <div>Hi!</div>;
411
@@ -417,8 +417,8 @@ describe('Store', () => {
417
<Parent count={1} />
418
<Parent count={3} />
419
</React.Fragment>,
420
- container
421
- )
420
+ container,
421
+ ),
422
);
423
expect(store).toMatchSnapshot('1: mount');
424
@@ -428,8 +428,8 @@ describe('Store', () => {
428
<Parent count={2} />
429
<Parent count={1} />
430
</React.Fragment>,
431
- container
432
- )
431
+ container,
432
+ ),
433
);
434
expect(store).toMatchSnapshot('2: update');
435
@@ -438,7 +438,7 @@ describe('Store', () => {
438
});
439
440
it('should support mount and update operations for multiple roots', () => {
441
- const Parent = ({ count }) =>
441
+ const Parent = ({count}) =>
442
new Array(count).fill(true).map((_, index) => <Child key={index} />);
443
const Child = () => <div>Hi!</div>;
444
@@ -483,8 +483,8 @@ describe('Store', () => {
483
act(() =>
484
ReactDOM.render(
485
<Grandparent count={4} />,
486
- document.createElement('div')
487
- )
486
+ document.createElement('div'),
487
+ ),
488
);
489
expect(store).toMatchSnapshot('1: mount');
490
@@ -503,7 +503,7 @@ describe('Store', () => {
503
const Component = () => {
504
return <div>Hello</div>;
505
};
506
- const Wrapper = ({ shouldSuspense }) => (
506
+ const Wrapper = ({shouldSuspense}) => (
507
<React.Fragment>
508
<Component key="Outside" />
509
<React.Suspense fallback={<Loading />}>
@@ -532,21 +532,21 @@ describe('Store', () => {
532
});
533
534
it('should support expanding parts of the tree', () => {
535
- const Grandparent = ({ count }) => (
535
+ const Grandparent = ({count}) => (
536
<React.Fragment>
537
<Parent count={count} />
538
<Parent count={count} />
539
</React.Fragment>
540
);
541
- const Parent = ({ count }) =>
541
+ const Parent = ({count}) =>
542
new Array(count).fill(true).map((_, index) => <Child key={index} />);
543
const Child = () => <div>Hi!</div>;
544
545
act(() =>
546
ReactDOM.render(
547
<Grandparent count={2} />,
548
- document.createElement('div')
549
- )
548
+ document.createElement('div'),
549
+ ),
550
);
551
expect(store).toMatchSnapshot('1: mount');
552
@@ -575,10 +575,10 @@ describe('Store', () => {
575
});
576
577
it('should support expanding deep parts of the tree', () => {
578
- const Wrapper = ({ forwardedRef }) => (
578
+ const Wrapper = ({forwardedRef}) => (
579
<Nested depth={3} forwardedRef={forwardedRef} />
580
);
581
- const Nested = ({ depth, forwardedRef }) =>
581
+ const Nested = ({depth, forwardedRef}) =>
582
depth > 0 ? (
583
<Nested depth={depth - 1} forwardedRef={forwardedRef} />
584
) : (
@@ -590,8 +590,8 @@ describe('Store', () => {
590
act(() =>
591
ReactDOM.render(
592
<Wrapper forwardedRef={ref} />,
593
- document.createElement('div')
594
- )
593
+ document.createElement('div'),
594
+ ),
595
);
596
expect(store).toMatchSnapshot('1: mount');
597
@@ -618,7 +618,7 @@ describe('Store', () => {
618
});
619
620
it('should support reordering of children', () => {
621
- const Root = ({ children }) => children;
621
+ const Root = ({children}) => children;
622
const Component = () => null;
623
624
const Foo = () => [<Component key="0" />];
@@ -661,7 +661,7 @@ describe('Store', () => {
661
const Child = () => null;
662
663
act(() =>
664
- ReactDOM.render(<SuspenseTree />, document.createElement('div'))
664
+ ReactDOM.render(<SuspenseTree />, document.createElement('div')),
665
);
666
expect(store).toMatchSnapshot('1: mount');
667
@@ -677,7 +677,7 @@ describe('Store', () => {
677
id: suspenseID,
678
rendererID,
679
forceFallback: true,
680
- })
680
+ }),
681
);
682
expect(store).toMatchSnapshot('3: toggle fallback on');
683
@@ -686,7 +686,7 @@ describe('Store', () => {
686
id: suspenseID,
687
rendererID,
688
forceFallback: false,
689
- })
689
+ }),
690
);
691
expect(store).toMatchSnapshot('4: toggle fallback on');
692
});
@@ -708,7 +708,7 @@ describe('Store', () => {
708
const Child = () => null;
709
710
act(() =>
711
- ReactDOM.render(<Grandparent />, document.createElement('div'))
711
+ ReactDOM.render(<Grandparent />, document.createElement('div')),
712
);
713
714
for (let i = 0; i < store.numElements; i++) {
@@ -742,8 +742,8 @@ describe('Store', () => {
742
<Grandparent />
743
<Grandparent />
744
</React.Fragment>,
745
- document.createElement('div')
746
- )
745
+ document.createElement('div'),
746
+ ),
747
);
748
749
for (let i = 0; i < store.numElements; i++) {
@@ -762,14 +762,14 @@ describe('Store', () => {
762
<Grandparent />
763
<Grandparent />
764
</React.Fragment>,
765
- document.createElement('div')
765
+ document.createElement('div'),
766
);
767
ReactDOM.render(
768
<React.Fragment>
769
<Grandparent />
770
<Grandparent />
771
</React.Fragment>,
772
- document.createElement('div')
772
+ document.createElement('div'),
773
);
774
});
775
packages/react-devtools-shared/src/__tests__/storeComponentFilters-test.js
+21
-21
@@ -1,6 +1,6 @@
1
// @flow
2
3
-import type { FrontendBridge } from 'react-devtools-shared/src/bridge';
3
+import type {FrontendBridge} from 'react-devtools-shared/src/bridge';
4
import type Store from 'react-devtools-shared/src/devtools/store';
5
6
describe('Store component filters', () => {
@@ -36,12 +36,12 @@ describe('Store component filters', () => {
36
it('should throw if filters are updated while profiling', () => {
37
act(() => store.profilerStore.startProfiling());
38
expect(() => (store.componentFilters = [])).toThrow(
39
- 'Cannot modify filter preferences while profiling'
39
+ 'Cannot modify filter preferences while profiling',
40
);
41
});
42
43
it('should support filtering by element type', () => {
44
- class Root extends React.Component<{| children: React$Node |}> {
44
+ class Root extends React.Component<{|children: React$Node|}> {
45
render() {
46
return <div>{this.props.children}</div>;
47
}
@@ -53,8 +53,8 @@ describe('Store component filters', () => {
53
<Root>
54
<Component />
55
</Root>,
56
- document.createElement('div')
57
- )
56
+ document.createElement('div'),
57
+ ),
58
);
59
expect(store).toMatchSnapshot('1: mount');
60
@@ -62,7 +62,7 @@ describe('Store component filters', () => {
62
() =>
63
(store.componentFilters = [
64
utils.createElementTypeFilter(Types.ElementTypeHostComponent),
65
- ])
65
+ ]),
66
);
67
68
expect(store).toMatchSnapshot('2: hide host components');
@@ -71,7 +71,7 @@ describe('Store component filters', () => {
71
() =>
72
(store.componentFilters = [
73
utils.createElementTypeFilter(Types.ElementTypeClass),
74
- ])
74
+ ]),
75
);
76
77
expect(store).toMatchSnapshot('3: hide class components');
@@ -81,7 +81,7 @@ describe('Store component filters', () => {
81
(store.componentFilters = [
82
utils.createElementTypeFilter(Types.ElementTypeClass),
83
utils.createElementTypeFilter(Types.ElementTypeFunction),
84
- ])
84
+ ]),
85
);
86
87
expect(store).toMatchSnapshot('4: hide class and function components');
@@ -91,7 +91,7 @@ describe('Store component filters', () => {
91
(store.componentFilters = [
92
utils.createElementTypeFilter(Types.ElementTypeClass, false),
93
utils.createElementTypeFilter(Types.ElementTypeFunction, false),
94
- ])
94
+ ]),
95
);
96
97
expect(store).toMatchSnapshot('5: disable all filters');
@@ -107,14 +107,14 @@ describe('Store component filters', () => {
107
() =>
108
(store.componentFilters = [
109
utils.createElementTypeFilter(Types.ElementTypeRoot),
110
- ])
110
+ ]),
111
);
112
113
expect(store).toMatchSnapshot('2: add invalid filter');
114
});
115
116
it('should filter by display name', () => {
117
- const Text = ({ label }) => label;
117
+ const Text = ({label}) => label;
118
const Foo = () => <Text label="foo" />;
119
const Bar = () => <Text label="bar" />;
120
const Baz = () => <Text label="baz" />;
@@ -126,13 +126,13 @@ describe('Store component filters', () => {
126
<Bar />
127
<Baz />
128
</React.Fragment>,
129
- document.createElement('div')
130
- )
129
+ document.createElement('div'),
130
+ ),
131
);
132
expect(store).toMatchSnapshot('1: mount');
133
134
act(
135
- () => (store.componentFilters = [utils.createDisplayNameFilter('Foo')])
135
+ () => (store.componentFilters = [utils.createDisplayNameFilter('Foo')]),
136
);
137
expect(store).toMatchSnapshot('2: filter "Foo"');
138
@@ -140,7 +140,7 @@ describe('Store component filters', () => {
140
expect(store).toMatchSnapshot('3: filter "Ba"');
141
142
act(
143
- () => (store.componentFilters = [utils.createDisplayNameFilter('B.z')])
143
+ () => (store.componentFilters = [utils.createDisplayNameFilter('B.z')]),
144
);
145
expect(store).toMatchSnapshot('4: filter "B.z"');
146
});
@@ -155,18 +155,18 @@ describe('Store component filters', () => {
155
() =>
156
(store.componentFilters = [
157
utils.createLocationFilter(__filename.replace(__dirname, '')),
158
- ])
158
+ ]),
159
);
160
161
expect(store).toMatchSnapshot(
162
- '2: hide all components declared within this test filed'
162
+ '2: hide all components declared within this test filed',
163
);
164
165
act(
166
() =>
167
(store.componentFilters = [
168
utils.createLocationFilter('this:is:a:made:up:path'),
169
- ])
169
+ ]),
170
);
171
172
expect(store).toMatchSnapshot('3: hide components in a made up fake path');
@@ -203,21 +203,21 @@ describe('Store component filters', () => {
203
(store.componentFilters = [
204
utils.createHOCFilter(false),
205
utils.createHOCFilter(true),
206
- ])
206
+ ]),
207
);
208
act(
209
() =>
210
(store.componentFilters = [
211
utils.createHOCFilter(true),
212
utils.createLocationFilter('abc', false),
213
- ])
213
+ ]),
214
);
215
act(
216
() =>
217
(store.componentFilters = [
218
utils.createHOCFilter(true),
219
utils.createElementTypeFilter(Types.ElementTypeHostComponent, false),
220
- ])
220
+ ]),
221
);
222
});
223
});
packages/react-devtools-shared/src/__tests__/storeOwners-test.js
+27
-27
@@ -1,6 +1,6 @@
1
// @flow
2
3
-const { printOwnersList } = require('../devtools/utils');
3
+const {printOwnersList} = require('../devtools/utils');
4
5
describe('Store owners list', () => {
6
let React;
@@ -25,21 +25,21 @@ describe('Store owners list', () => {
25
</div>
26
</Intermediate>
27
);
28
- const Wrapper = ({ children }) => children;
28
+ const Wrapper = ({children}) => children;
29
const Leaf = () => <div>Leaf</div>;
30
- const Intermediate = ({ children }) => <Wrapper>{children}</Wrapper>;
30
+ const Intermediate = ({children}) => <Wrapper>{children}</Wrapper>;
31
32
act(() => ReactDOM.render(<Root />, document.createElement('div')));
33
expect(store).toMatchSnapshot('1: mount');
34
35
const rootID = store.getElementIDAtIndex(0);
36
expect(
37
- printOwnersList(store.getOwnersListForElement(rootID))
37
+ printOwnersList(store.getOwnersListForElement(rootID)),
38
).toMatchSnapshot('2: components owned by <Root>');
39
40
const intermediateID = store.getElementIDAtIndex(1);
41
expect(
42
- printOwnersList(store.getOwnersListForElement(intermediateID))
42
+ printOwnersList(store.getOwnersListForElement(intermediateID)),
43
).toMatchSnapshot('3: components owned by <Intermediate>');
44
});
45
@@ -50,9 +50,9 @@ describe('Store owners list', () => {
50
</Intermediate>,
51
<Leaf key="leaf" />,
52
];
53
- const Wrapper = ({ children }) => children;
53
+ const Wrapper = ({children}) => children;
54
const Leaf = () => <div>Leaf</div>;
55
- const Intermediate = ({ children }) => [
55
+ const Intermediate = ({children}) => [
56
<Leaf key="leaf" />,
57
<Wrapper key="wrapper">{children}</Wrapper>,
58
];
@@ -62,17 +62,17 @@ describe('Store owners list', () => {
62
63
const rootID = store.getElementIDAtIndex(0);
64
expect(
65
- printOwnersList(store.getOwnersListForElement(rootID))
65
+ printOwnersList(store.getOwnersListForElement(rootID)),
66
).toMatchSnapshot('2: components owned by <Root>');
67
68
const intermediateID = store.getElementIDAtIndex(1);
69
expect(
70
- printOwnersList(store.getOwnersListForElement(intermediateID))
70
+ printOwnersList(store.getOwnersListForElement(intermediateID)),
71
).toMatchSnapshot('3: components owned by <Intermediate>');
72
});
73
74
it('should show the proper owners list order and contents after insertions and deletions', () => {
75
- const Root = ({ includeDirect, includeIndirect }) => (
75
+ const Root = ({includeDirect, includeIndirect}) => (
76
<div>
77
{includeDirect ? <Leaf /> : null}
78
{includeIndirect ? (
@@ -82,64 +82,64 @@ describe('Store owners list', () => {
82
) : null}
83
</div>
84
);
85
- const Wrapper = ({ children }) => children;
85
+ const Wrapper = ({children}) => children;
86
const Leaf = () => <div>Leaf</div>;
87
- const Intermediate = ({ children }) => <Wrapper>{children}</Wrapper>;
87
+ const Intermediate = ({children}) => <Wrapper>{children}</Wrapper>;
88
89
const container = document.createElement('div');
90
91
act(() =>
92
ReactDOM.render(
93
<Root includeDirect={false} includeIndirect={true} />,
94
- container
95
- )
94
+ container,
95
+ ),
96
);
97
expect(store).toMatchSnapshot('1: mount');
98
99
const rootID = store.getElementIDAtIndex(0);
100
expect(
101
- printOwnersList(store.getOwnersListForElement(rootID))
101
+ printOwnersList(store.getOwnersListForElement(rootID)),
102
).toMatchSnapshot('2: components owned by <Root>');
103
104
act(() =>
105
ReactDOM.render(
106
<Root includeDirect={true} includeIndirect={true} />,
107
- container
108
- )
107
+ container,
108
+ ),
109
);
110
expect(store).toMatchSnapshot('3: update to add direct');
111
112
expect(
113
- printOwnersList(store.getOwnersListForElement(rootID))
113
+ printOwnersList(store.getOwnersListForElement(rootID)),
114
).toMatchSnapshot('4: components owned by <Root>');
115
116
act(() =>
117
ReactDOM.render(
118
<Root includeDirect={true} includeIndirect={false} />,
119
- container
120
- )
119
+ container,
120
+ ),
121
);
122
expect(store).toMatchSnapshot('5: update to remove indirect');
123
124
expect(
125
- printOwnersList(store.getOwnersListForElement(rootID))
125
+ printOwnersList(store.getOwnersListForElement(rootID)),
126
).toMatchSnapshot('6: components owned by <Root>');
127
128
act(() =>
129
ReactDOM.render(
130
<Root includeDirect={false} includeIndirect={false} />,
131
- container
132
- )
131
+ container,
132
+ ),
133
);
134
expect(store).toMatchSnapshot('7: update to remove both');
135
136
expect(
137
- printOwnersList(store.getOwnersListForElement(rootID))
137
+ printOwnersList(store.getOwnersListForElement(rootID)),
138
).toMatchSnapshot('8: components owned by <Root>');
139
});
140
141
it('should show the proper owners list ordering after reordered children', () => {
142
- const Root = ({ ascending }) =>
142
+ const Root = ({ascending}) =>
143
ascending
144
? [<Leaf key="A" />, <Leaf key="B" />, <Leaf key="C" />]
145
: [<Leaf key="C" />, <Leaf key="B" />, <Leaf key="A" />];
@@ -151,14 +151,14 @@ describe('Store owners list', () => {
151
152
const rootID = store.getElementIDAtIndex(0);
153
expect(
154
- printOwnersList(store.getOwnersListForElement(rootID))
154
+ printOwnersList(store.getOwnersListForElement(rootID)),
155
).toMatchSnapshot('2: components owned by <Root>');
156
157
act(() => ReactDOM.render(<Root ascending={false} />, container));
158
expect(store).toMatchSnapshot('3: update (descending)');
159
160
expect(
161
- printOwnersList(store.getOwnersListForElement(rootID))
161
+ printOwnersList(store.getOwnersListForElement(rootID)),
162
).toMatchSnapshot('4: components owned by <Root>');
163
});
164
});
packages/react-devtools-shared/src/__tests__/storeSerializer.js
+6
-3
@@ -1,11 +1,14 @@
1
-import { printStore } from 'react-devtools-shared/src/devtools/utils'
1
+import {printStore} from 'react-devtools-shared/src/devtools/utils';
2
3
// test() is part of Jest's serializer API
4
export function test(maybeStore) {
5
// It's important to lazy-require the Store rather than imported at the head of the module.
6
// Because we reset modules between tests, different Store implementations will be used for each test.
7
// Unfortunately Jest does not reset its own serializer modules.
8
- return maybeStore instanceof require('react-devtools-shared/src/devtools/store').default;
8
+ return (
9
+ maybeStore instanceof
10
+ require('react-devtools-shared/src/devtools/store').default
11
+ );
12
}
13
14
// print() is part of Jest's serializer API
@@ -15,4 +18,4 @@ export function print(store, serialize, indent) {
18
19
// Used for Jest snapshot testing.
20
// May also be useful for visually debugging the tree, so it lives on the Store.
18
-export { printStore };
21
+export {printStore};
packages/react-devtools-shared/src/__tests__/storeStressSync-test.js
+79
-79
@@ -43,7 +43,7 @@ describe('StoreStress (Sync Mode)', () => {
43
const d = <D key="d" />;
44
const e = <E key="e" />;
45
46
- function Parent({ children }) {
46
+ function Parent({children}) {
47
return children;
48
}
49
@@ -195,7 +195,7 @@ describe('StoreStress (Sync Mode)', () => {
195
[c, a],
196
];
197
198
- const Root = ({ children }) => {
198
+ const Root = ({children}) => {
199
return children;
200
};
201
@@ -235,8 +235,8 @@ describe('StoreStress (Sync Mode)', () => {
235
<Root>
236
<div>{steps[i]}</div>
237
</Root>,
238
- container
239
- )
238
+ container,
239
+ ),
240
);
241
expect(print(store)).toMatch(snapshots[i]);
242
act(() =>
@@ -244,8 +244,8 @@ describe('StoreStress (Sync Mode)', () => {
244
<Root>
245
<div>{steps[j]}</div>
246
</Root>,
247
- container
248
- )
247
+ container,
248
+ ),
249
);
250
expect(print(store)).toMatch(snapshots[j]);
251
act(() =>
@@ -253,8 +253,8 @@ describe('StoreStress (Sync Mode)', () => {
253
<Root>
254
<div>{steps[i]}</div>
255
</Root>,
256
- container
257
- )
256
+ container,
257
+ ),
258
);
259
expect(print(store)).toMatch(snapshots[i]);
260
act(() => ReactDOM.unmountComponentAtNode(container));
@@ -295,7 +295,7 @@ describe('StoreStress (Sync Mode)', () => {
295
throw new Promise(() => {});
296
};
297
298
- const Root = ({ children }) => {
298
+ const Root = ({children}) => {
299
return children;
300
};
301
@@ -311,8 +311,8 @@ describe('StoreStress (Sync Mode)', () => {
311
<React.Suspense fallback={z}>{steps[i]}</React.Suspense>
312
<Y />
313
</Root>,
314
- container
315
- )
314
+ container,
315
+ ),
316
);
317
// We snapshot each step once so it doesn't regress.
318
expect(store).toMatchSnapshot();
@@ -334,8 +334,8 @@ describe('StoreStress (Sync Mode)', () => {
334
</React.Suspense>
335
<Y />
336
</Root>,
337
- container
338
- )
337
+ container,
338
+ ),
339
);
340
expect(print(store)).toEqual(snapshots[i]);
341
act(() => ReactDOM.unmountComponentAtNode(container));
@@ -354,8 +354,8 @@ describe('StoreStress (Sync Mode)', () => {
354
<React.Suspense fallback={z}>{steps[i]}</React.Suspense>
355
<Y />
356
</Root>,
357
- container
358
- )
357
+ container,
358
+ ),
359
);
360
expect(print(store)).toEqual(snapshots[i]);
361
// Re-render with steps[j].
@@ -366,8 +366,8 @@ describe('StoreStress (Sync Mode)', () => {
366
<React.Suspense fallback={z}>{steps[j]}</React.Suspense>
367
<Y />
368
</Root>,
369
- container
370
- )
369
+ container,
370
+ ),
371
);
372
// Verify the successful transition to steps[j].
373
expect(print(store)).toEqual(snapshots[j]);
@@ -379,8 +379,8 @@ describe('StoreStress (Sync Mode)', () => {
379
<React.Suspense fallback={z}>{steps[i]}</React.Suspense>
380
<Y />
381
</Root>,
382
- container
383
- )
382
+ container,
383
+ ),
384
);
385
expect(print(store)).toEqual(snapshots[i]);
386
// Clean up after every iteration.
@@ -405,8 +405,8 @@ describe('StoreStress (Sync Mode)', () => {
405
</React.Suspense>
406
<Y />
407
</Root>,
408
- container
409
- )
408
+ container,
409
+ ),
410
);
411
expect(print(store)).toEqual(snapshots[i]);
412
// Re-render with steps[j].
@@ -421,8 +421,8 @@ describe('StoreStress (Sync Mode)', () => {
421
</React.Suspense>
422
<Y />
423
</Root>,
424
- container
425
- )
424
+ container,
425
+ ),
426
);
427
// Verify the successful transition to steps[j].
428
expect(print(store)).toEqual(snapshots[j]);
@@ -438,8 +438,8 @@ describe('StoreStress (Sync Mode)', () => {
438
</React.Suspense>
439
<Y />
440
</Root>,
441
- container
442
- )
441
+ container,
442
+ ),
443
);
444
expect(print(store)).toEqual(snapshots[i]);
445
// Clean up after every iteration.
@@ -460,8 +460,8 @@ describe('StoreStress (Sync Mode)', () => {
460
<React.Suspense fallback={z}>{steps[i]}</React.Suspense>
461
<Y />
462
</Root>,
463
- container
464
- )
463
+ container,
464
+ ),
465
);
466
expect(print(store)).toEqual(snapshots[i]);
467
// Re-render with steps[j].
@@ -476,8 +476,8 @@ describe('StoreStress (Sync Mode)', () => {
476
</React.Suspense>
477
<Y />
478
</Root>,
479
- container
480
- )
479
+ container,
480
+ ),
481
);
482
// Verify the successful transition to steps[j].
483
expect(print(store)).toEqual(snapshots[j]);
@@ -489,8 +489,8 @@ describe('StoreStress (Sync Mode)', () => {
489
<React.Suspense fallback={z}>{steps[i]}</React.Suspense>
490
<Y />
491
</Root>,
492
- container
493
- )
492
+ container,
493
+ ),
494
);
495
expect(print(store)).toEqual(snapshots[i]);
496
// Clean up after every iteration.
@@ -515,8 +515,8 @@ describe('StoreStress (Sync Mode)', () => {
515
</React.Suspense>
516
<Y />
517
</Root>,
518
- container
519
- )
518
+ container,
519
+ ),
520
);
521
expect(print(store)).toEqual(snapshots[i]);
522
// Re-render with steps[j].
@@ -527,8 +527,8 @@ describe('StoreStress (Sync Mode)', () => {
527
<React.Suspense fallback={z}>{steps[j]}</React.Suspense>
528
<Y />
529
</Root>,
530
- container
531
- )
530
+ container,
531
+ ),
532
);
533
// Verify the successful transition to steps[j].
534
expect(print(store)).toEqual(snapshots[j]);
@@ -544,8 +544,8 @@ describe('StoreStress (Sync Mode)', () => {
544
</React.Suspense>
545
<Y />
546
</Root>,
547
- container
548
- )
547
+ container,
548
+ ),
549
);
550
expect(print(store)).toEqual(snapshots[i]);
551
// Clean up after every iteration.
@@ -566,8 +566,8 @@ describe('StoreStress (Sync Mode)', () => {
566
<React.Suspense fallback={steps[j]}>{steps[i]}</React.Suspense>
567
<Y />
568
</Root>,
569
- container
570
- )
569
+ container,
570
+ ),
571
);
572
573
// We get ID from the index in the tree above:
@@ -609,8 +609,8 @@ describe('StoreStress (Sync Mode)', () => {
609
</React.Suspense>
610
<Y />
611
</Root>,
612
- container
613
- )
612
+ container,
613
+ ),
614
);
615
expect(print(store)).toEqual(snapshots[j]);
616
@@ -633,8 +633,8 @@ describe('StoreStress (Sync Mode)', () => {
633
<React.Suspense fallback={steps[j]}>{steps[i]}</React.Suspense>
634
<Y />
635
</Root>,
636
- container
637
- )
636
+ container,
637
+ ),
638
);
639
// Fallback is still forced though.
640
expect(print(store)).toEqual(snapshots[j]);
@@ -689,7 +689,7 @@ describe('StoreStress (Sync Mode)', () => {
689
throw new Promise(() => {});
690
};
691
692
- const MaybeSuspend = ({ children, suspend }) => {
692
+ const MaybeSuspend = ({children, suspend}) => {
693
if (suspend) {
694
return (
695
<div>
@@ -707,7 +707,7 @@ describe('StoreStress (Sync Mode)', () => {
707
);
708
};
709
710
- const Root = ({ children }) => {
710
+ const Root = ({children}) => {
711
return children;
712
};
713
@@ -725,8 +725,8 @@ describe('StoreStress (Sync Mode)', () => {
725
</React.Suspense>
726
<Y />
727
</Root>,
728
- container
729
- )
728
+ container,
729
+ ),
730
);
731
// We snapshot each step once so it doesn't regress.
732
expect(store).toMatchSnapshot();
@@ -751,8 +751,8 @@ describe('StoreStress (Sync Mode)', () => {
751
</React.Suspense>
752
<Y />
753
</Root>,
754
- container
755
- )
754
+ container,
755
+ ),
756
);
757
// We snapshot each step once so it doesn't regress.
758
expect(store).toMatchSnapshot();
@@ -775,8 +775,8 @@ describe('StoreStress (Sync Mode)', () => {
775
</React.Suspense>
776
<Y />
777
</Root>,
778
- container
779
- )
778
+ container,
779
+ ),
780
);
781
expect(print(store)).toEqual(snapshots[i]);
782
// Re-render with steps[j].
@@ -789,8 +789,8 @@ describe('StoreStress (Sync Mode)', () => {
789
</React.Suspense>
790
<Y />
791
</Root>,
792
- container
793
- )
792
+ container,
793
+ ),
794
);
795
// Verify the successful transition to steps[j].
796
expect(print(store)).toEqual(snapshots[j]);
@@ -804,8 +804,8 @@ describe('StoreStress (Sync Mode)', () => {
804
</React.Suspense>
805
<Y />
806
</Root>,
807
- container
808
- )
807
+ container,
808
+ ),
809
);
810
expect(print(store)).toEqual(snapshots[i]);
811
// Clean up after every iteration.
@@ -833,8 +833,8 @@ describe('StoreStress (Sync Mode)', () => {
833
</React.Suspense>
834
<Y />
835
</Root>,
836
- container
837
- )
836
+ container,
837
+ ),
838
);
839
expect(print(store)).toEqual(fallbackSnapshots[i]);
840
// Re-render with steps[j].
@@ -852,8 +852,8 @@ describe('StoreStress (Sync Mode)', () => {
852
</React.Suspense>
853
<Y />
854
</Root>,
855
- container
856
- )
855
+ container,
856
+ ),
857
);
858
// Verify the successful transition to steps[j].
859
expect(print(store)).toEqual(fallbackSnapshots[j]);
@@ -872,8 +872,8 @@ describe('StoreStress (Sync Mode)', () => {
872
</React.Suspense>
873
<Y />
874
</Root>,
875
- container
876
- )
875
+ container,
876
+ ),
877
);
878
expect(print(store)).toEqual(fallbackSnapshots[i]);
879
// Clean up after every iteration.
@@ -896,8 +896,8 @@ describe('StoreStress (Sync Mode)', () => {
896
</React.Suspense>
897
<Y />
898
</Root>,
899
- container
900
- )
899
+ container,
900
+ ),
901
);
902
expect(print(store)).toEqual(snapshots[i]);
903
// Re-render with steps[j].
@@ -910,8 +910,8 @@ describe('StoreStress (Sync Mode)', () => {
910
</React.Suspense>
911
<Y />
912
</Root>,
913
- container
914
- )
913
+ container,
914
+ ),
915
);
916
// Verify the successful transition to steps[j].
917
expect(print(store)).toEqual(fallbackSnapshots[j]);
@@ -925,8 +925,8 @@ describe('StoreStress (Sync Mode)', () => {
925
</React.Suspense>
926
<Y />
927
</Root>,
928
- container
929
- )
928
+ container,
929
+ ),
930
);
931
expect(print(store)).toEqual(snapshots[i]);
932
// Clean up after every iteration.
@@ -949,8 +949,8 @@ describe('StoreStress (Sync Mode)', () => {
949
</React.Suspense>
950
<Y />
951
</Root>,
952
- container
953
- )
952
+ container,
953
+ ),
954
);
955
expect(print(store)).toEqual(fallbackSnapshots[i]);
956
// Re-render with steps[j].
@@ -963,8 +963,8 @@ describe('StoreStress (Sync Mode)', () => {
963
</React.Suspense>
964
<Y />
965
</Root>,
966
- container
967
- )
966
+ container,
967
+ ),
968
);
969
// Verify the successful transition to steps[j].
970
expect(print(store)).toEqual(snapshots[j]);
@@ -978,8 +978,8 @@ describe('StoreStress (Sync Mode)', () => {
978
</React.Suspense>
979
<Y />
980
</Root>,
981
- container
982
- )
981
+ container,
982
+ ),
983
);
984
expect(print(store)).toEqual(fallbackSnapshots[i]);
985
// Clean up after every iteration.
@@ -1002,8 +1002,8 @@ describe('StoreStress (Sync Mode)', () => {
1002
</React.Suspense>
1003
<Y />
1004
</Root>,
1005
- container
1006
- )
1005
+ container,
1006
+ ),
1007
);
1008
1009
// We get ID from the index in the tree above:
@@ -1043,8 +1043,8 @@ describe('StoreStress (Sync Mode)', () => {
1043
</React.Suspense>
1044
<Y />
1045
</Root>,
1046
- container
1047
- )
1046
+ container,
1047
+ ),
1048
);
1049
expect(print(store)).toEqual(fallbackSnapshots[j]);
1050
@@ -1069,8 +1069,8 @@ describe('StoreStress (Sync Mode)', () => {
1069
</React.Suspense>
1070
<Y />
1071
</Root>,
1072
- container
1073
- )
1072
+ container,
1073
+ ),
1074
);
1075
// Fallback is still forced though.
1076
expect(print(store)).toEqual(fallbackSnapshots[j]);
packages/react-devtools-shared/src/__tests__/storeStressTestConcurrent-test.js
+79
-79
@@ -43,7 +43,7 @@ describe('StoreStressConcurrent', () => {
43
const d = <D key="d" />;
44
const e = <E key="e" />;
45
46
- function Parent({ children }) {
46
+ function Parent({children}) {
47
return children;
48
}
49
@@ -201,7 +201,7 @@ describe('StoreStressConcurrent', () => {
201
[c, a],
202
];
203
204
- const Root = ({ children }) => {
204
+ const Root = ({children}) => {
205
return children;
206
};
207
@@ -246,24 +246,24 @@ describe('StoreStressConcurrent', () => {
246
root.render(
247
<Root>
248
<div>{steps[i]}</div>
249
- </Root>
250
- )
249
+ </Root>,
250
+ ),
251
);
252
expect(print(store)).toMatch(snapshots[i]);
253
act(() =>
254
root.render(
255
<Root>
256
<div>{steps[j]}</div>
257
- </Root>
258
- )
257
+ </Root>,
258
+ ),
259
);
260
expect(print(store)).toMatch(snapshots[j]);
261
act(() =>
262
root.render(
263
<Root>
264
<div>{steps[i]}</div>
265
- </Root>
266
- )
265
+ </Root>,
266
+ ),
267
);
268
expect(print(store)).toMatch(snapshots[i]);
269
act(() => root.unmount());
@@ -304,7 +304,7 @@ describe('StoreStressConcurrent', () => {
304
throw new Promise(() => {});
305
};
306
307
- const Root = ({ children }) => {
307
+ const Root = ({children}) => {
308
return children;
309
};
310
@@ -321,8 +321,8 @@ describe('StoreStressConcurrent', () => {
321
<X />
322
<React.Suspense fallback={z}>{steps[i]}</React.Suspense>
323
<Y />
324
- </Root>
325
- )
324
+ </Root>,
325
+ ),
326
);
327
// We snapshot each step once so it doesn't regress.
328
expect(store).toMatchSnapshot();
@@ -343,8 +343,8 @@ describe('StoreStressConcurrent', () => {
343
<Z />
344
</React.Suspense>
345
<Y />
346
- </Root>
347
- )
346
+ </Root>,
347
+ ),
348
);
349
expect(print(store)).toEqual(snapshots[i]);
350
act(() => root.unmount());
@@ -364,8 +364,8 @@ describe('StoreStressConcurrent', () => {
364
<X />
365
<React.Suspense fallback={z}>{steps[i]}</React.Suspense>
366
<Y />
367
- </Root>
368
- )
367
+ </Root>,
368
+ ),
369
);
370
expect(print(store)).toEqual(snapshots[i]);
371
// Re-render with steps[j].
@@ -375,8 +375,8 @@ describe('StoreStressConcurrent', () => {
375
<X />
376
<React.Suspense fallback={z}>{steps[j]}</React.Suspense>
377
<Y />
378
- </Root>
379
- )
378
+ </Root>,
379
+ ),
380
);
381
// Verify the successful transition to steps[j].
382
expect(print(store)).toEqual(snapshots[j]);
@@ -387,8 +387,8 @@ describe('StoreStressConcurrent', () => {
387
<X />
388
<React.Suspense fallback={z}>{steps[i]}</React.Suspense>
389
<Y />
390
- </Root>
391
- )
390
+ </Root>,
391
+ ),
392
);
393
expect(print(store)).toEqual(snapshots[i]);
394
// Clean up after every iteration.
@@ -414,8 +414,8 @@ describe('StoreStressConcurrent', () => {
414
<Z />
415
</React.Suspense>
416
<Y />
417
- </Root>
418
- )
417
+ </Root>,
418
+ ),
419
);
420
expect(print(store)).toEqual(snapshots[i]);
421
// Re-render with steps[j].
@@ -429,8 +429,8 @@ describe('StoreStressConcurrent', () => {
429
<Z />
430
</React.Suspense>
431
<Y />
432
- </Root>
433
- )
432
+ </Root>,
433
+ ),
434
);
435
// Verify the successful transition to steps[j].
436
expect(print(store)).toEqual(snapshots[j]);
@@ -445,8 +445,8 @@ describe('StoreStressConcurrent', () => {
445
<Z />
446
</React.Suspense>
447
<Y />
448
- </Root>
449
- )
448
+ </Root>,
449
+ ),
450
);
451
expect(print(store)).toEqual(snapshots[i]);
452
// Clean up after every iteration.
@@ -468,8 +468,8 @@ describe('StoreStressConcurrent', () => {
468
<X />
469
<React.Suspense fallback={z}>{steps[i]}</React.Suspense>
470
<Y />
471
- </Root>
472
- )
471
+ </Root>,
472
+ ),
473
);
474
expect(print(store)).toEqual(snapshots[i]);
475
// Re-render with steps[j].
@@ -483,8 +483,8 @@ describe('StoreStressConcurrent', () => {
483
<Z />
484
</React.Suspense>
485
<Y />
486
- </Root>
487
- )
486
+ </Root>,
487
+ ),
488
);
489
// Verify the successful transition to steps[j].
490
expect(print(store)).toEqual(snapshots[j]);
@@ -495,8 +495,8 @@ describe('StoreStressConcurrent', () => {
495
<X />
496
<React.Suspense fallback={z}>{steps[i]}</React.Suspense>
497
<Y />
498
- </Root>
499
- )
498
+ </Root>,
499
+ ),
500
);
501
expect(print(store)).toEqual(snapshots[i]);
502
// Clean up after every iteration.
@@ -522,8 +522,8 @@ describe('StoreStressConcurrent', () => {
522
<Z />
523
</React.Suspense>
524
<Y />
525
- </Root>
526
- )
525
+ </Root>,
526
+ ),
527
);
528
expect(print(store)).toEqual(snapshots[i]);
529
// Re-render with steps[j].
@@ -533,8 +533,8 @@ describe('StoreStressConcurrent', () => {
533
<X />
534
<React.Suspense fallback={z}>{steps[j]}</React.Suspense>
535
<Y />
536
- </Root>
537
- )
536
+ </Root>,
537
+ ),
538
);
539
// Verify the successful transition to steps[j].
540
expect(print(store)).toEqual(snapshots[j]);
@@ -549,8 +549,8 @@ describe('StoreStressConcurrent', () => {
549
<Z />
550
</React.Suspense>
551
<Y />
552
- </Root>
553
- )
552
+ </Root>,
553
+ ),
554
);
555
expect(print(store)).toEqual(snapshots[i]);
556
// Clean up after every iteration.
@@ -572,8 +572,8 @@ describe('StoreStressConcurrent', () => {
572
<X />
573
<React.Suspense fallback={steps[j]}>{steps[i]}</React.Suspense>
574
<Y />
575
- </Root>
576
- )
575
+ </Root>,
576
+ ),
577
);
578
579
// We get ID from the index in the tree above:
@@ -614,8 +614,8 @@ describe('StoreStressConcurrent', () => {
614
<Z />
615
</React.Suspense>
616
<Y />
617
- </Root>
618
- )
617
+ </Root>,
618
+ ),
619
);
620
expect(print(store)).toEqual(snapshots[j]);
621
@@ -637,8 +637,8 @@ describe('StoreStressConcurrent', () => {
637
<X />
638
<React.Suspense fallback={steps[j]}>{steps[i]}</React.Suspense>
639
<Y />
640
- </Root>
641
- )
640
+ </Root>,
641
+ ),
642
);
643
// Fallback is still forced though.
644
expect(print(store)).toEqual(snapshots[j]);
@@ -693,7 +693,7 @@ describe('StoreStressConcurrent', () => {
693
throw new Promise(() => {});
694
};
695
696
- const MaybeSuspend = ({ children, suspend }) => {
696
+ const MaybeSuspend = ({children, suspend}) => {
697
if (suspend) {
698
return (
699
<div>
@@ -711,7 +711,7 @@ describe('StoreStressConcurrent', () => {
711
);
712
};
713
714
- const Root = ({ children }) => {
714
+ const Root = ({children}) => {
715
return children;
716
};
717
@@ -730,8 +730,8 @@ describe('StoreStressConcurrent', () => {
730
<MaybeSuspend suspend={false}>{steps[i]}</MaybeSuspend>
731
</React.Suspense>
732
<Y />
733
- </Root>
734
- )
733
+ </Root>,
734
+ ),
735
);
736
// We snapshot each step once so it doesn't regress.
737
expect(store).toMatchSnapshot();
@@ -755,8 +755,8 @@ describe('StoreStressConcurrent', () => {
755
<Z />
756
</React.Suspense>
757
<Y />
758
- </Root>
759
- )
758
+ </Root>,
759
+ ),
760
);
761
// We snapshot each step once so it doesn't regress.
762
expect(store).toMatchSnapshot();
@@ -780,8 +780,8 @@ describe('StoreStressConcurrent', () => {
780
<MaybeSuspend suspend={false}>{steps[i]}</MaybeSuspend>
781
</React.Suspense>
782
<Y />
783
- </Root>
784
- )
783
+ </Root>,
784
+ ),
785
);
786
expect(print(store)).toEqual(snapshots[i]);
787
// Re-render with steps[j].
@@ -793,8 +793,8 @@ describe('StoreStressConcurrent', () => {
793
<MaybeSuspend suspend={false}>{steps[j]}</MaybeSuspend>
794
</React.Suspense>
795
<Y />
796
- </Root>
797
- )
796
+ </Root>,
797
+ ),
798
);
799
// Verify the successful transition to steps[j].
800
expect(print(store)).toEqual(snapshots[j]);
@@ -807,8 +807,8 @@ describe('StoreStressConcurrent', () => {
807
<MaybeSuspend suspend={false}>{steps[i]}</MaybeSuspend>
808
</React.Suspense>
809
<Y />
810
- </Root>
811
- )
810
+ </Root>,
811
+ ),
812
);
813
expect(print(store)).toEqual(snapshots[i]);
814
// Clean up after every iteration.
@@ -837,8 +837,8 @@ describe('StoreStressConcurrent', () => {
837
<Z />
838
</React.Suspense>
839
<Y />
840
- </Root>
841
- )
840
+ </Root>,
841
+ ),
842
);
843
expect(print(store)).toEqual(fallbackSnapshots[i]);
844
// Re-render with steps[j].
@@ -855,8 +855,8 @@ describe('StoreStressConcurrent', () => {
855
<Z />
856
</React.Suspense>
857
<Y />
858
- </Root>
859
- )
858
+ </Root>,
859
+ ),
860
);
861
// Verify the successful transition to steps[j].
862
expect(print(store)).toEqual(fallbackSnapshots[j]);
@@ -874,8 +874,8 @@ describe('StoreStressConcurrent', () => {
874
<Z />
875
</React.Suspense>
876
<Y />
877
- </Root>
878
- )
877
+ </Root>,
878
+ ),
879
);
880
expect(print(store)).toEqual(fallbackSnapshots[i]);
881
// Clean up after every iteration.
@@ -899,8 +899,8 @@ describe('StoreStressConcurrent', () => {
899
<MaybeSuspend suspend={false}>{steps[i]}</MaybeSuspend>
900
</React.Suspense>
901
<Y />
902
- </Root>
903
- )
902
+ </Root>,
903
+ ),
904
);
905
expect(print(store)).toEqual(snapshots[i]);
906
// Re-render with steps[j].
@@ -912,8 +912,8 @@ describe('StoreStressConcurrent', () => {
912
<MaybeSuspend suspend={true}>{steps[i]}</MaybeSuspend>
913
</React.Suspense>
914
<Y />
915
- </Root>
916
- )
915
+ </Root>,
916
+ ),
917
);
918
// Verify the successful transition to steps[j].
919
expect(print(store)).toEqual(fallbackSnapshots[j]);
@@ -926,8 +926,8 @@ describe('StoreStressConcurrent', () => {
926
<MaybeSuspend suspend={false}>{steps[i]}</MaybeSuspend>
927
</React.Suspense>
928
<Y />
929
- </Root>
930
- )
929
+ </Root>,
930
+ ),
931
);
932
expect(print(store)).toEqual(snapshots[i]);
933
// Clean up after every iteration.
@@ -951,8 +951,8 @@ describe('StoreStressConcurrent', () => {
951
<MaybeSuspend suspend={true}>{steps[j]}</MaybeSuspend>
952
</React.Suspense>
953
<Y />
954
- </Root>
955
- )
954
+ </Root>,
955
+ ),
956
);
957
expect(print(store)).toEqual(fallbackSnapshots[i]);
958
// Re-render with steps[j].
@@ -964,8 +964,8 @@ describe('StoreStressConcurrent', () => {
964
<MaybeSuspend suspend={false}>{steps[j]}</MaybeSuspend>
965
</React.Suspense>
966
<Y />
967
- </Root>
968
- )
967
+ </Root>,
968
+ ),
969
);
970
// Verify the successful transition to steps[j].
971
expect(print(store)).toEqual(snapshots[j]);
@@ -978,8 +978,8 @@ describe('StoreStressConcurrent', () => {
978
<MaybeSuspend suspend={true}>{steps[j]}</MaybeSuspend>
979
</React.Suspense>
980
<Y />
981
- </Root>
982
- )
981
+ </Root>,
982
+ ),
983
);
984
expect(print(store)).toEqual(fallbackSnapshots[i]);
985
// Clean up after every iteration.
@@ -1003,8 +1003,8 @@ describe('StoreStressConcurrent', () => {
1003
<MaybeSuspend suspend={false}>{steps[i]}</MaybeSuspend>
1004
</React.Suspense>
1005
<Y />
1006
- </Root>
1007
- )
1006
+ </Root>,
1007
+ ),
1008
);
1009
1010
// We get ID from the index in the tree above:
@@ -1043,8 +1043,8 @@ describe('StoreStressConcurrent', () => {
1043
<MaybeSuspend suspend={true}>{steps[i]}</MaybeSuspend>
1044
</React.Suspense>
1045
<Y />
1046
- </Root>
1047
- )
1046
+ </Root>,
1047
+ ),
1048
);
1049
expect(print(store)).toEqual(fallbackSnapshots[j]);
1050
@@ -1068,8 +1068,8 @@ describe('StoreStressConcurrent', () => {
1068
<MaybeSuspend suspend={false}>{steps[i]}</MaybeSuspend>
1069
</React.Suspense>
1070
<Y />
1071
- </Root>
1072
- )
1071
+ </Root>,
1072
+ ),
1073
);
1074
// Fallback is still forced though.
1075
expect(print(store)).toEqual(fallbackSnapshots[j]);
packages/react-devtools-shared/src/__tests__/treeContext-test.js
+69
-71
@@ -1,7 +1,7 @@
1
// @flow
2
3
import typeof ReactTestRenderer from 'react-test-renderer';
4
-import type { FrontendBridge } from 'react-devtools-shared/src/bridge';
4
+import type {FrontendBridge} from 'react-devtools-shared/src/bridge';
5
import type Store from 'react-devtools-shared/src/devtools/store';
6
import type {
7
DispatcherContext,
@@ -35,8 +35,10 @@ describe('TreeListContext', () => {
35
ReactDOM = require('react-dom');
36
TestRenderer = utils.requireTestRenderer();
37
38
- BridgeContext = require('react-devtools-shared/src/devtools/views/context').BridgeContext;
39
- StoreContext = require('react-devtools-shared/src/devtools/views/context').StoreContext;
38
+ BridgeContext = require('react-devtools-shared/src/devtools/views/context')
39
+ .BridgeContext;
40
+ StoreContext = require('react-devtools-shared/src/devtools/views/context')
41
+ .StoreContext;
42
TreeContext = require('react-devtools-shared/src/devtools/views/Components/TreeContext');
43
});
44
@@ -76,7 +78,7 @@ describe('TreeListContext', () => {
78
const Child = () => null;
79
80
utils.act(() =>
79
- ReactDOM.render(<Grandparent />, document.createElement('div'))
81
+ ReactDOM.render(<Grandparent />, document.createElement('div')),
82
);
83
84
expect(store).toMatchSnapshot('0: mount');
@@ -85,7 +87,7 @@ describe('TreeListContext', () => {
87
utils.act(() => (renderer = TestRenderer.create(<Contexts />)));
88
expect(state).toMatchSnapshot('1: initial state');
89
88
- utils.act(() => dispatch({ type: 'SELECT_NEXT_ELEMENT_IN_TREE' }));
90
+ utils.act(() => dispatch({type: 'SELECT_NEXT_ELEMENT_IN_TREE'}));
91
utils.act(() => renderer.update(<Contexts />));
92
expect(state).toMatchSnapshot('2: select first element');
93
@@ -94,7 +96,7 @@ describe('TreeListContext', () => {
96
state.selectedElementIndex < store.numElements - 1
97
) {
98
const index = ((state.selectedElementIndex: any): number);
97
- utils.act(() => dispatch({ type: 'SELECT_NEXT_ELEMENT_IN_TREE' }));
99
+ utils.act(() => dispatch({type: 'SELECT_NEXT_ELEMENT_IN_TREE'}));
100
utils.act(() => renderer.update(<Contexts />));
101
expect(state).toMatchSnapshot(`3: select element after (${index})`);
102
}
@@ -104,16 +106,16 @@ describe('TreeListContext', () => {
106
state.selectedElementIndex > 0
107
) {
108
const index = ((state.selectedElementIndex: any): number);
107
- utils.act(() => dispatch({ type: 'SELECT_PREVIOUS_ELEMENT_IN_TREE' }));
109
+ utils.act(() => dispatch({type: 'SELECT_PREVIOUS_ELEMENT_IN_TREE'}));
110
utils.act(() => renderer.update(<Contexts />));
111
expect(state).toMatchSnapshot(`4: select element before (${index})`);
112
}
113
112
- utils.act(() => dispatch({ type: 'SELECT_PREVIOUS_ELEMENT_IN_TREE' }));
114
+ utils.act(() => dispatch({type: 'SELECT_PREVIOUS_ELEMENT_IN_TREE'}));
115
utils.act(() => renderer.update(<Contexts />));
116
expect(state).toMatchSnapshot('5: select previous wraps around to last');
117
116
- utils.act(() => dispatch({ type: 'SELECT_NEXT_ELEMENT_IN_TREE' }));
118
+ utils.act(() => dispatch({type: 'SELECT_NEXT_ELEMENT_IN_TREE'}));
119
utils.act(() => renderer.update(<Contexts />));
120
expect(state).toMatchSnapshot('6: select next wraps around to first');
121
});
@@ -134,7 +136,7 @@ describe('TreeListContext', () => {
136
const Child = () => null;
137
138
utils.act(() =>
137
- ReactDOM.render(<Grandparent />, document.createElement('div'))
139
+ ReactDOM.render(<Grandparent />, document.createElement('div')),
140
);
141
142
expect(store).toMatchSnapshot('0: mount');
@@ -143,24 +145,22 @@ describe('TreeListContext', () => {
145
utils.act(() => (renderer = TestRenderer.create(<Contexts />)));
146
expect(state).toMatchSnapshot('1: initial state');
147
146
- utils.act(() =>
147
- dispatch({ type: 'SELECT_ELEMENT_AT_INDEX', payload: 0 })
148
- );
148
+ utils.act(() => dispatch({type: 'SELECT_ELEMENT_AT_INDEX', payload: 0}));
149
utils.act(() => renderer.update(<Contexts />));
150
expect(state).toMatchSnapshot('2: select first element');
151
152
- utils.act(() => dispatch({ type: 'SELECT_CHILD_ELEMENT_IN_TREE' }));
152
+ utils.act(() => dispatch({type: 'SELECT_CHILD_ELEMENT_IN_TREE'}));
153
utils.act(() => renderer.update(<Contexts />));
154
expect(state).toMatchSnapshot('3: select Parent');
155
156
- utils.act(() => dispatch({ type: 'SELECT_CHILD_ELEMENT_IN_TREE' }));
156
+ utils.act(() => dispatch({type: 'SELECT_CHILD_ELEMENT_IN_TREE'}));
157
utils.act(() => renderer.update(<Contexts />));
158
expect(state).toMatchSnapshot('4: select Child');
159
160
const previousState = state;
161
162
// There are no more children to select, so this should be a no-op
163
- utils.act(() => dispatch({ type: 'SELECT_CHILD_ELEMENT_IN_TREE' }));
163
+ utils.act(() => dispatch({type: 'SELECT_CHILD_ELEMENT_IN_TREE'}));
164
utils.act(() => renderer.update(<Contexts />));
165
expect(state).toEqual(previousState);
166
});
@@ -181,7 +181,7 @@ describe('TreeListContext', () => {
181
const Child = () => null;
182
183
utils.act(() =>
184
- ReactDOM.render(<Grandparent />, document.createElement('div'))
184
+ ReactDOM.render(<Grandparent />, document.createElement('div')),
185
);
186
187
expect(store).toMatchSnapshot('0: mount');
@@ -193,23 +193,23 @@ describe('TreeListContext', () => {
193
const lastChildID = store.getElementIDAtIndex(store.numElements - 1);
194
195
utils.act(() =>
196
- dispatch({ type: 'SELECT_ELEMENT_BY_ID', payload: lastChildID })
196
+ dispatch({type: 'SELECT_ELEMENT_BY_ID', payload: lastChildID}),
197
);
198
utils.act(() => renderer.update(<Contexts />));
199
expect(state).toMatchSnapshot('2: select last child');
200
201
- utils.act(() => dispatch({ type: 'SELECT_PARENT_ELEMENT_IN_TREE' }));
201
+ utils.act(() => dispatch({type: 'SELECT_PARENT_ELEMENT_IN_TREE'}));
202
utils.act(() => renderer.update(<Contexts />));
203
expect(state).toMatchSnapshot('3: select Parent');
204
205
- utils.act(() => dispatch({ type: 'SELECT_PARENT_ELEMENT_IN_TREE' }));
205
+ utils.act(() => dispatch({type: 'SELECT_PARENT_ELEMENT_IN_TREE'}));
206
utils.act(() => renderer.update(<Contexts />));
207
expect(state).toMatchSnapshot('4: select Grandparent');
208
209
const previousState = state;
210
211
// There are no more ancestors to select, so this should be a no-op
212
- utils.act(() => dispatch({ type: 'SELECT_PARENT_ELEMENT_IN_TREE' }));
212
+ utils.act(() => dispatch({type: 'SELECT_PARENT_ELEMENT_IN_TREE'}));
213
utils.act(() => renderer.update(<Contexts />));
214
expect(state).toEqual(previousState);
215
});
@@ -228,8 +228,8 @@ describe('TreeListContext', () => {
228
<Child />
229
</Parent>
230
</Grandparent>,
231
- container
232
- )
231
+ container,
232
+ ),
233
);
234
235
expect(store).toMatchSnapshot('0: mount');
@@ -238,9 +238,7 @@ describe('TreeListContext', () => {
238
utils.act(() => (renderer = TestRenderer.create(<Contexts />)));
239
expect(state).toMatchSnapshot('1: initial state');
240
241
- utils.act(() =>
242
- dispatch({ type: 'SELECT_ELEMENT_AT_INDEX', payload: 3 })
243
- );
241
+ utils.act(() => dispatch({type: 'SELECT_ELEMENT_AT_INDEX', payload: 3}));
242
utils.act(() => renderer.update(<Contexts />));
243
expect(state).toMatchSnapshot('2: select second child');
244
@@ -249,16 +247,16 @@ describe('TreeListContext', () => {
247
<Grandparent>
248
<Parent />
249
</Grandparent>,
252
- container
253
- )
250
+ container,
251
+ ),
252
);
253
expect(state).toMatchSnapshot(
256
- '3: remove children (parent should now be selected)'
254
+ '3: remove children (parent should now be selected)',
255
);
256
257
await utils.actAsync(() => ReactDOM.unmountComponentAtNode(container));
258
expect(state).toMatchSnapshot(
261
- '4: unmount root (nothing should be selected)'
259
+ '4: unmount root (nothing should be selected)',
260
);
261
262
done();
@@ -282,8 +280,8 @@ describe('TreeListContext', () => {
280
<Baz />
281
<Qux />
282
</React.Fragment>,
285
- document.createElement('div')
286
- )
283
+ document.createElement('div'),
284
+ ),
285
);
286
287
expect(store).toMatchSnapshot('0: mount');
@@ -293,22 +291,22 @@ describe('TreeListContext', () => {
291
expect(state).toMatchSnapshot('1: initial state');
292
293
// NOTE: multi-match
296
- utils.act(() => dispatch({ type: 'SET_SEARCH_TEXT', payload: 'ba' }));
294
+ utils.act(() => dispatch({type: 'SET_SEARCH_TEXT', payload: 'ba'}));
295
utils.act(() => renderer.update(<Contexts />));
296
expect(state).toMatchSnapshot('2: search for "ba"');
297
298
// NOTE: single match
301
- utils.act(() => dispatch({ type: 'SET_SEARCH_TEXT', payload: 'f' }));
299
+ utils.act(() => dispatch({type: 'SET_SEARCH_TEXT', payload: 'f'}));
300
utils.act(() => renderer.update(<Contexts />));
301
expect(state).toMatchSnapshot('3: search for "f"');
302
303
// NOTE: no match
306
- utils.act(() => dispatch({ type: 'SET_SEARCH_TEXT', payload: 'y' }));
304
+ utils.act(() => dispatch({type: 'SET_SEARCH_TEXT', payload: 'y'}));
305
utils.act(() => renderer.update(<Contexts />));
306
expect(state).toMatchSnapshot('4: search for "y"');
307
308
// NOTE: HOC match
311
- utils.act(() => dispatch({ type: 'SET_SEARCH_TEXT', payload: 'w' }));
309
+ utils.act(() => dispatch({type: 'SET_SEARCH_TEXT', payload: 'w'}));
310
utils.act(() => renderer.update(<Contexts />));
311
expect(state).toMatchSnapshot('5: search for "w"');
312
});
@@ -326,8 +324,8 @@ describe('TreeListContext', () => {
324
<Bar />
325
<Baz />
326
</React.Fragment>,
329
- document.createElement('div')
330
- )
327
+ document.createElement('div'),
328
+ ),
329
);
330
331
expect(store).toMatchSnapshot('0: mount');
@@ -336,31 +334,31 @@ describe('TreeListContext', () => {
334
utils.act(() => (renderer = TestRenderer.create(<Contexts />)));
335
expect(state).toMatchSnapshot('1: initial state');
336
339
- utils.act(() => dispatch({ type: 'SET_SEARCH_TEXT', payload: 'ba' }));
337
+ utils.act(() => dispatch({type: 'SET_SEARCH_TEXT', payload: 'ba'}));
338
utils.act(() => renderer.update(<Contexts />));
339
expect(state).toMatchSnapshot('2: search for "ba"');
340
343
- utils.act(() => dispatch({ type: 'GO_TO_NEXT_SEARCH_RESULT' }));
341
+ utils.act(() => dispatch({type: 'GO_TO_NEXT_SEARCH_RESULT'}));
342
utils.act(() => renderer.update(<Contexts />));
343
expect(state).toMatchSnapshot('3: go to second result');
344
347
- utils.act(() => dispatch({ type: 'GO_TO_NEXT_SEARCH_RESULT' }));
345
+ utils.act(() => dispatch({type: 'GO_TO_NEXT_SEARCH_RESULT'}));
346
utils.act(() => renderer.update(<Contexts />));
347
expect(state).toMatchSnapshot('4: go to third result');
348
351
- utils.act(() => dispatch({ type: 'GO_TO_PREVIOUS_SEARCH_RESULT' }));
349
+ utils.act(() => dispatch({type: 'GO_TO_PREVIOUS_SEARCH_RESULT'}));
350
utils.act(() => renderer.update(<Contexts />));
351
expect(state).toMatchSnapshot('5: go to second result');
352
355
- utils.act(() => dispatch({ type: 'GO_TO_PREVIOUS_SEARCH_RESULT' }));
353
+ utils.act(() => dispatch({type: 'GO_TO_PREVIOUS_SEARCH_RESULT'}));
354
utils.act(() => renderer.update(<Contexts />));
355
expect(state).toMatchSnapshot('6: go to first result');
356
359
- utils.act(() => dispatch({ type: 'GO_TO_PREVIOUS_SEARCH_RESULT' }));
357
+ utils.act(() => dispatch({type: 'GO_TO_PREVIOUS_SEARCH_RESULT'}));
358
utils.act(() => renderer.update(<Contexts />));
359
expect(state).toMatchSnapshot('7: wrap to last result');
360
363
- utils.act(() => dispatch({ type: 'GO_TO_NEXT_SEARCH_RESULT' }));
361
+ utils.act(() => dispatch({type: 'GO_TO_NEXT_SEARCH_RESULT'}));
362
utils.act(() => renderer.update(<Contexts />));
363
expect(state).toMatchSnapshot('8: wrap to first result');
364
});
@@ -378,8 +376,8 @@ describe('TreeListContext', () => {
376
<Foo />
377
<Bar />
378
</React.Fragment>,
381
- container
382
- )
379
+ container,
380
+ ),
381
);
382
383
expect(store).toMatchSnapshot('0: mount');
@@ -388,7 +386,7 @@ describe('TreeListContext', () => {
386
utils.act(() => (renderer = TestRenderer.create(<Contexts />)));
387
expect(state).toMatchSnapshot('1: initial state');
388
391
- utils.act(() => dispatch({ type: 'SET_SEARCH_TEXT', payload: 'ba' }));
389
+ utils.act(() => dispatch({type: 'SET_SEARCH_TEXT', payload: 'ba'}));
390
utils.act(() => renderer.update(<Contexts />));
391
expect(state).toMatchSnapshot('2: search for "ba"');
392
@@ -399,8 +397,8 @@ describe('TreeListContext', () => {
397
<Bar />
398
<Baz />
399
</React.Fragment>,
402
- container
403
- )
400
+ container,
401
+ ),
402
);
403
utils.act(() => renderer.update(<Contexts />));
404
expect(state).toMatchSnapshot('3: mount Baz');
@@ -422,8 +420,8 @@ describe('TreeListContext', () => {
420
<Bar />
421
<Baz />
422
</React.Fragment>,
425
- container
426
- )
423
+ container,
424
+ ),
425
);
426
427
expect(store).toMatchSnapshot('0: mount');
@@ -432,11 +430,11 @@ describe('TreeListContext', () => {
430
utils.act(() => (renderer = TestRenderer.create(<Contexts />)));
431
expect(state).toMatchSnapshot('1: initial state');
432
435
- utils.act(() => dispatch({ type: 'SET_SEARCH_TEXT', payload: 'ba' }));
433
+ utils.act(() => dispatch({type: 'SET_SEARCH_TEXT', payload: 'ba'}));
434
utils.act(() => renderer.update(<Contexts />));
435
expect(state).toMatchSnapshot('2: search for "ba"');
436
439
- utils.act(() => dispatch({ type: 'GO_TO_NEXT_SEARCH_RESULT' }));
437
+ utils.act(() => dispatch({type: 'GO_TO_NEXT_SEARCH_RESULT'}));
438
utils.act(() => renderer.update(<Contexts />));
439
expect(state).toMatchSnapshot('3: go to second result');
440
@@ -446,8 +444,8 @@ describe('TreeListContext', () => {
444
<Foo />
445
<Bar />
446
</React.Fragment>,
449
- container
450
- )
447
+ container,
448
+ ),
449
);
450
utils.act(() => renderer.update(<Contexts />));
451
expect(state).toMatchSnapshot('4: unmount Baz');
@@ -468,7 +466,7 @@ describe('TreeListContext', () => {
466
const Child = () => null;
467
468
utils.act(() =>
471
- ReactDOM.render(<Grandparent />, document.createElement('div'))
469
+ ReactDOM.render(<Grandparent />, document.createElement('div')),
470
);
471
472
expect(store).toMatchSnapshot('0: mount');
@@ -478,18 +476,18 @@ describe('TreeListContext', () => {
476
expect(state).toMatchSnapshot('1: initial state');
477
478
let parentID = ((store.getElementIDAtIndex(1): any): number);
481
- utils.act(() => dispatch({ type: 'SELECT_OWNER', payload: parentID }));
479
+ utils.act(() => dispatch({type: 'SELECT_OWNER', payload: parentID}));
480
utils.act(() => renderer.update(<Contexts />));
481
expect(state).toMatchSnapshot('2: parent owners tree');
482
485
- utils.act(() => dispatch({ type: 'RESET_OWNER_STACK' }));
483
+ utils.act(() => dispatch({type: 'RESET_OWNER_STACK'}));
484
utils.act(() => renderer.update(<Contexts />));
485
expect(state).toMatchSnapshot('3: final state');
486
});
487
488
it('should remove an element from the owners list if it is unmounted', async done => {
491
- const Grandparent = ({ count }) => <Parent count={count} />;
492
- const Parent = ({ count }) =>
489
+ const Grandparent = ({count}) => <Parent count={count} />;
490
+ const Parent = ({count}) =>
491
new Array(count).fill(true).map((_, index) => <Child key={index} />);
492
const Child = () => null;
493
@@ -503,17 +501,17 @@ describe('TreeListContext', () => {
501
expect(state).toMatchSnapshot('1: initial state');
502
503
let parentID = ((store.getElementIDAtIndex(1): any): number);
506
- utils.act(() => dispatch({ type: 'SELECT_OWNER', payload: parentID }));
504
+ utils.act(() => dispatch({type: 'SELECT_OWNER', payload: parentID}));
505
utils.act(() => renderer.update(<Contexts />));
506
expect(state).toMatchSnapshot('2: parent owners tree');
507
508
await utils.actAsync(() =>
511
- ReactDOM.render(<Grandparent count={1} />, container)
509
+ ReactDOM.render(<Grandparent count={1} />, container),
510
);
511
expect(state).toMatchSnapshot('3: remove second child');
512
513
await utils.actAsync(() =>
516
- ReactDOM.render(<Grandparent count={0} />, container)
514
+ ReactDOM.render(<Grandparent count={0} />, container),
515
);
516
expect(state).toMatchSnapshot('4: remove first child');
517
@@ -530,8 +528,8 @@ describe('TreeListContext', () => {
528
<Parent>
529
<Child />
530
</Parent>,
533
- container
534
- )
531
+ container,
532
+ ),
533
);
534
535
expect(store).toMatchSnapshot('0: mount');
@@ -541,7 +539,7 @@ describe('TreeListContext', () => {
539
expect(state).toMatchSnapshot('1: initial state');
540
541
let childID = ((store.getElementIDAtIndex(1): any): number);
544
- utils.act(() => dispatch({ type: 'SELECT_OWNER', payload: childID }));
542
+ utils.act(() => dispatch({type: 'SELECT_OWNER', payload: childID}));
543
utils.act(() => renderer.update(<Contexts />));
544
expect(state).toMatchSnapshot('2: child owners tree');
545
@@ -549,7 +547,7 @@ describe('TreeListContext', () => {
547
expect(state).toMatchSnapshot('3: remove child');
548
549
let parentID = ((store.getElementIDAtIndex(0): any): number);
552
- utils.act(() => dispatch({ type: 'SELECT_OWNER', payload: parentID }));
550
+ utils.act(() => dispatch({type: 'SELECT_OWNER', payload: parentID}));
551
utils.act(() => renderer.update(<Contexts />));
552
expect(state).toMatchSnapshot('4: parent owners tree');
553
@@ -586,20 +584,20 @@ describe('TreeListContext', () => {
584
const childID = ((store.getElementIDAtIndex(2): any): number);
585
const innerSuspenseID = ((store.getElementIDAtIndex(3): any): number);
586
589
- utils.act(() => dispatch({ type: 'SELECT_OWNER', payload: childID }));
587
+ utils.act(() => dispatch({type: 'SELECT_OWNER', payload: childID}));
588
utils.act(() => renderer.update(<Contexts />));
589
expect(state).toMatchSnapshot('2: child owners tree');
590
591
// Toggling a Suspense boundary inside of the flat list should update selected index
592
utils.act(() =>
595
- dispatch({ type: 'SELECT_ELEMENT_BY_ID', payload: innerSuspenseID })
593
+ dispatch({type: 'SELECT_ELEMENT_BY_ID', payload: innerSuspenseID}),
594
);
595
utils.act(() => renderer.update(<Contexts />));
596
expect(state).toMatchSnapshot('3: child owners tree');
597
598
// Toggling a Suspense boundary outside of the flat list should exit owners list and update index
599
utils.act(() =>
602
- dispatch({ type: 'SELECT_ELEMENT_BY_ID', payload: outerSuspenseID })
600
+ dispatch({type: 'SELECT_ELEMENT_BY_ID', payload: outerSuspenseID}),
601
);
602
utils.act(() => renderer.update(<Contexts />));
603
expect(state).toMatchSnapshot('4: main tree');
packages/react-devtools-shared/src/__tests__/utils.js
+17
-17
@@ -2,14 +2,14 @@
2
3
import typeof ReactTestRenderer from 'react-test-renderer';
4
5
-import type { FrontendBridge } from 'react-devtools-shared/src/bridge';
5
+import type {FrontendBridge} from 'react-devtools-shared/src/bridge';
6
import type Store from 'react-devtools-shared/src/devtools/store';
7
-import type { ProfilingDataFrontend } from 'react-devtools-shared/src/devtools/views/Profiler/types';
8
-import type { ElementType } from 'react-devtools-shared/src/types';
7
+import type {ProfilingDataFrontend} from 'react-devtools-shared/src/devtools/views/Profiler/types';
8
+import type {ElementType} from 'react-devtools-shared/src/types';
9
10
export function act(callback: Function): void {
11
- const { act: actTestRenderer } = require('react-test-renderer');
12
- const { act: actDOM } = require('react-dom/test-utils');
11
+ const {act: actTestRenderer} = require('react-test-renderer');
12
+ const {act: actDOM} = require('react-dom/test-utils');
13
14
actDOM(() => {
15
actTestRenderer(() => {
@@ -27,10 +27,10 @@ export function act(callback: Function): void {
27
28
export async function actAsync(
29
cb: () => *,
30
- recursivelyFlush: boolean = true
30
+ recursivelyFlush: boolean = true,
31
): Promise<void> {
32
- const { act: actTestRenderer } = require('react-test-renderer');
33
- const { act: actDOM } = require('react-dom/test-utils');
32
+ const {act: actTestRenderer} = require('react-test-renderer');
33
+ const {act: actDOM} = require('react-dom/test-utils');
34
35
// $FlowFixMe Flow doens't know about "await act()" yet
36
await actDOM(async () => {
@@ -67,13 +67,13 @@ export function beforeEachProfiling(): void {
67
jest
68
.spyOn(performance, 'now')
69
.mockImplementation(
70
- jest.requireActual('scheduler/unstable_mock').unstable_now
70
+ jest.requireActual('scheduler/unstable_mock').unstable_now,
71
);
72
}
73
74
export function createDisplayNameFilter(
75
source: string,
76
- isEnabled: boolean = true
76
+ isEnabled: boolean = true,
77
) {
78
const Types = require('react-devtools-shared/src/types');
79
let isValid = true;
@@ -101,7 +101,7 @@ export function createHOCFilter(isEnabled: boolean = true) {
101
102
export function createElementTypeFilter(
103
elementType: ElementType,
104
- isEnabled: boolean = true
104
+ isEnabled: boolean = true,
105
) {
106
const Types = require('react-devtools-shared/src/types');
107
return {
@@ -113,7 +113,7 @@ export function createElementTypeFilter(
113
114
export function createLocationFilter(
115
source: string,
116
- isEnabled: boolean = true
116
+ isEnabled: boolean = true,
117
) {
118
const Types = require('react-devtools-shared/src/types');
119
let isValid = true;
@@ -162,32 +162,32 @@ export function requireTestRenderer(): ReactTestRenderer {
162
}
163
164
export function exportImportHelper(bridge: FrontendBridge, store: Store): void {
165
- const { act } = require('./utils');
165
+ const {act} = require('./utils');
166
const {
167
prepareProfilingDataExport,
168
prepareProfilingDataFrontendFromExport,
169
} = require('react-devtools-shared/src/devtools/views/Profiler/utils');
170
171
- const { profilerStore } = store;
171
+ const {profilerStore} = store;
172
173
expect(profilerStore.profilingData).not.toBeNull();
174
175
const profilingDataFrontendInitial = ((profilerStore.profilingData: any): ProfilingDataFrontend);
176
177
const profilingDataExport = prepareProfilingDataExport(
178
- profilingDataFrontendInitial
178
+ profilingDataFrontendInitial,
179
);
180
181
// Simulate writing/reading to disk.
182
const serializedProfilingDataExport = JSON.stringify(
183
profilingDataExport,
184
null,
185
- 2
185
+ 2,
186
);
187
const parsedProfilingDataExport = JSON.parse(serializedProfilingDataExport);
188
189
const profilingDataFrontend = prepareProfilingDataFrontendFromExport(
190
- (parsedProfilingDataExport: any)
190
+ (parsedProfilingDataExport: any),
191
);
192
193
// Sanity check that profiling snapshots are serialized correctly.
packages/react-devtools-shared/src/backend/NativeStyleEditor/resolveBoxStyle.js
+2
-2
@@ -1,6 +1,6 @@
1
// @flow
2
3
-import type { BoxStyle } from './types';
3
+import type {BoxStyle} from './types';
4
5
/**
6
* This mirrors react-native/Libraries/Inspector/resolveBoxStyle.js (but without RTL support).
@@ -12,7 +12,7 @@ import type { BoxStyle } from './types';
12
*/
13
export default function resolveBoxStyle(
14
prefix: string,
15
- style: Object
15
+ style: Object,
16
): BoxStyle | null {
17
let hasParts = false;
18
const result = {
packages/react-devtools-shared/src/backend/NativeStyleEditor/setupNativeStyleEditor.js
+34
-30
@@ -3,9 +3,9 @@
3
import Agent from 'react-devtools-shared/src/backend/agent';
4
import resolveBoxStyle from './resolveBoxStyle';
5
6
-import type { BackendBridge } from 'react-devtools-shared/src/bridge';
7
-import type { RendererID } from '../types';
8
-import type { StyleAndLayout } from './types';
6
+import type {BackendBridge} from 'react-devtools-shared/src/bridge';
7
+import type {RendererID} from '../types';
8
+import type {StyleAndLayout} from './types';
9
10
export type ResolveNativeStyle = (stylesheetID: any) => ?Object;
11
@@ -13,13 +13,13 @@ export default function setupNativeStyleEditor(
13
bridge: BackendBridge,
14
agent: Agent,
15
resolveNativeStyle: ResolveNativeStyle,
16
- validAttributes?: $ReadOnlyArray<string> | null
16
+ validAttributes?: $ReadOnlyArray<string> | null,
17
) {
18
bridge.addListener(
19
'NativeStyleEditor_measure',
20
- ({ id, rendererID }: {| id: number, rendererID: RendererID |}) => {
20
+ ({id, rendererID}: {|id: number, rendererID: RendererID|}) => {
21
measureStyle(agent, bridge, resolveNativeStyle, id, rendererID);
22
- }
22
+ },
23
);
24
25
bridge.addListener(
@@ -39,9 +39,9 @@ export default function setupNativeStyleEditor(
39
|}) => {
40
renameStyle(agent, id, rendererID, oldName, newName, value);
41
setTimeout(() =>
42
- measureStyle(agent, bridge, resolveNativeStyle, id, rendererID)
42
+ measureStyle(agent, bridge, resolveNativeStyle, id, rendererID),
43
);
44
- }
44
+ },
45
);
46
47
bridge.addListener(
@@ -59,9 +59,9 @@ export default function setupNativeStyleEditor(
59
|}) => {
60
setStyle(agent, id, rendererID, name, value);
61
setTimeout(() =>
62
- measureStyle(agent, bridge, resolveNativeStyle, id, rendererID)
62
+ measureStyle(agent, bridge, resolveNativeStyle, id, rendererID),
63
);
64
- }
64
+ },
65
);
66
67
bridge.send('isNativeStyleEditorSupported', {
@@ -84,9 +84,9 @@ function measureStyle(
84
bridge: BackendBridge,
85
resolveNativeStyle: ResolveNativeStyle,
86
id: number,
87
- rendererID: RendererID
87
+ rendererID: RendererID,
88
) {
89
- const data = agent.getInstanceAndStyle({ id, rendererID });
89
+ const data = agent.getInstanceAndStyle({id, rendererID});
90
if (!data || !data.style) {
91
bridge.send(
92
'NativeStyleEditor_styleAndLayout',
@@ -94,12 +94,12 @@ function measureStyle(
94
id,
95
layout: null,
96
style: null,
97
- }: StyleAndLayout)
97
+ }: StyleAndLayout),
98
);
99
return;
100
}
101
102
- const { instance, style } = data;
102
+ const {instance, style} = data;
103
104
let resolvedStyle = resolveNativeStyle(style);
105
@@ -116,7 +116,7 @@ function measureStyle(
116
id,
117
layout: null,
118
style: resolvedStyle || null,
119
- }: StyleAndLayout)
119
+ }: StyleAndLayout),
120
);
121
return;
122
}
@@ -132,12 +132,16 @@ function measureStyle(
132
id,
133
layout: null,
134
style: resolvedStyle || null,
135
- }: StyleAndLayout)
135
+ }: StyleAndLayout),
136
);
137
return;
138
}
139
- const margin = resolvedStyle != null && resolveBoxStyle('margin', resolvedStyle) || EMPTY_BOX_STYLE;
140
- const padding = resolvedStyle != null && resolveBoxStyle('padding', resolvedStyle) || EMPTY_BOX_STYLE;
139
+ const margin =
140
+ (resolvedStyle != null && resolveBoxStyle('margin', resolvedStyle)) ||
141
+ EMPTY_BOX_STYLE;
142
+ const padding =
143
+ (resolvedStyle != null && resolveBoxStyle('padding', resolvedStyle)) ||
144
+ EMPTY_BOX_STYLE;
145
bridge.send(
146
'NativeStyleEditor_styleAndLayout',
147
({
@@ -153,7 +157,7 @@ function measureStyle(
157
padding,
158
},
159
style: resolvedStyle || null,
156
- }: StyleAndLayout)
160
+ }: StyleAndLayout),
161
);
162
});
163
}
@@ -172,18 +176,18 @@ function renameStyle(
176
rendererID: RendererID,
177
oldName: string,
178
newName: string,
175
- value: string
179
+ value: string,
180
): void {
177
- const data = agent.getInstanceAndStyle({ id, rendererID });
181
+ const data = agent.getInstanceAndStyle({id, rendererID});
182
if (!data || !data.style) {
183
return;
184
}
185
182
- const { instance, style } = data;
186
+ const {instance, style} = data;
187
188
const newStyle = newName
185
- ? { [oldName]: undefined, [newName]: value }
186
- : { [oldName]: undefined };
189
+ ? {[oldName]: undefined, [newName]: value}
190
+ : {[oldName]: undefined};
191
192
let customStyle;
193
@@ -198,7 +202,7 @@ function renameStyle(
202
Object.assign(styleOverrides, newStyle);
203
}
204
// TODO Fabric does not support setNativeProps; chat with Sebastian or Eli
201
- instance.setNativeProps({ style: newStyle });
205
+ instance.setNativeProps({style: newStyle});
206
} else if (Array.isArray(style)) {
207
const lastIndex = style.length - 1;
208
if (
@@ -259,15 +263,15 @@ function setStyle(
263
id: number,
264
rendererID: RendererID,
265
name: string,
262
- value: string
266
+ value: string,
267
) {
264
- const data = agent.getInstanceAndStyle({ id, rendererID });
268
+ const data = agent.getInstanceAndStyle({id, rendererID});
269
if (!data || !data.style) {
270
return;
271
}
272
269
- const { instance, style } = data;
270
- const newStyle = { [name]: value };
273
+ const {instance, style} = data;
274
+ const newStyle = {[name]: value};
275
276
// TODO It would be nice if the renderer interface abstracted this away somehow.
277
if (instance !== null && typeof instance.setNativeProps === 'function') {
@@ -280,7 +284,7 @@ function setStyle(
284
Object.assign(styleOverrides, newStyle);
285
}
286
// TODO Fabric does not support setNativeProps; chat with Sebastian or Eli
283
- instance.setNativeProps({ style: newStyle });
287
+ instance.setNativeProps({style: newStyle});
288
} else if (Array.isArray(style)) {
289
const lastLength = style.length - 1;
290
if (
packages/react-devtools-shared/src/backend/agent.js
+22
-22
@@ -14,9 +14,9 @@ import {
14
sessionStorageSetItem,
15
} from 'react-devtools-shared/src/storage';
16
import setupHighlighter from './views/Highlighter';
17
-import { patch as patchConsole, unpatch as unpatchConsole } from './console';
17
+import {patch as patchConsole, unpatch as unpatchConsole} from './console';
18
19
-import type { BackendBridge } from 'react-devtools-shared/src/bridge';
19
+import type {BackendBridge} from 'react-devtools-shared/src/bridge';
20
import type {
21
InstanceAndStyle,
22
NativeType,
@@ -26,7 +26,7 @@ import type {
26
RendererID,
27
RendererInterface,
28
} from './types';
29
-import type { ComponentFilter } from '../types';
29
+import type {ComponentFilter} from '../types';
30
31
const debug = (methodName, ...args) => {
32
if (__DEBUG__) {
@@ -34,7 +34,7 @@ const debug = (methodName, ...args) => {
34
`%cAgent %c${methodName}`,
35
'color: purple; font-weight: bold;',
36
'font-weight: bold;',
37
- ...args
37
+ ...args,
38
);
39
}
40
};
@@ -84,7 +84,7 @@ export default class Agent extends EventEmitter<{|
84
_bridge: BackendBridge;
85
_isProfiling: boolean = false;
86
_recordChangeDescriptions: boolean = false;
87
- _rendererInterfaces: { [key: RendererID]: RendererInterface } = {};
87
+ _rendererInterfaces: {[key: RendererID]: RendererInterface} = {};
88
_persistedSelection: PersistedSelection | null = null;
89
_persistedSelectionMatch: PathMatch | null = null;
90
@@ -96,7 +96,7 @@ export default class Agent extends EventEmitter<{|
96
) {
97
this._recordChangeDescriptions =
98
sessionStorageGetItem(
99
- SESSION_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY
99
+ SESSION_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY,
100
) === 'true';
101
this._isProfiling = true;
102
@@ -105,7 +105,7 @@ export default class Agent extends EventEmitter<{|
105
}
106
107
const persistedSelectionString = sessionStorageGetItem(
108
- SESSION_STORAGE_LAST_SELECTION_KEY
108
+ SESSION_STORAGE_LAST_SELECTION_KEY,
109
);
110
if (persistedSelectionString != null) {
111
this._persistedSelection = JSON.parse(persistedSelectionString);
@@ -128,12 +128,12 @@ export default class Agent extends EventEmitter<{|
128
bridge.addListener('stopProfiling', this.stopProfiling);
129
bridge.addListener(
130
'syncSelectionFromNativeElementsPanel',
131
- this.syncSelectionFromNativeElementsPanel
131
+ this.syncSelectionFromNativeElementsPanel,
132
);
133
bridge.addListener('shutdown', this.shutdown);
134
bridge.addListener(
135
'updateAppendComponentStack',
136
- this.updateAppendComponentStack
136
+ this.updateAppendComponentStack,
137
);
138
bridge.addListener('updateComponentFilters', this.updateComponentFilters);
139
bridge.addListener('viewElementSource', this.viewElementSource);
@@ -154,7 +154,7 @@ export default class Agent extends EventEmitter<{|
154
setupHighlighter(bridge, this);
155
}
156
157
- get rendererInterfaces(): { [key: RendererID]: RendererInterface } {
157
+ get rendererInterfaces(): {[key: RendererID]: RendererInterface} {
158
return this._rendererInterfaces;
159
}
160
@@ -189,7 +189,7 @@ export default class Agent extends EventEmitter<{|
189
return null;
190
}
191
192
- getProfilingData = ({ rendererID }: {| rendererID: RendererID |}) => {
192
+ getProfilingData = ({rendererID}: {|rendererID: RendererID|}) => {
193
const renderer = this._rendererInterfaces[rendererID];
194
if (renderer == null) {
195
console.warn(`Invalid renderer id "${rendererID}"`);
@@ -202,17 +202,17 @@ export default class Agent extends EventEmitter<{|
202
this._bridge.send('profilingStatus', this._isProfiling);
203
};
204
205
- getOwnersList = ({ id, rendererID }: ElementAndRendererID) => {
205
+ getOwnersList = ({id, rendererID}: ElementAndRendererID) => {
206
const renderer = this._rendererInterfaces[rendererID];
207
if (renderer == null) {
208
console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`);
209
} else {
210
const owners = renderer.getOwnersList(id);
211
- this._bridge.send('ownersList', ({ id, owners }: OwnersList));
211
+ this._bridge.send('ownersList', ({id, owners}: OwnersList));
212
}
213
};
214
215
- inspectElement = ({ id, path, rendererID }: InspectElementParams) => {
215
+ inspectElement = ({id, path, rendererID}: InspectElementParams) => {
216
const renderer = this._rendererInterfaces[rendererID];
217
if (renderer == null) {
218
console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`);
@@ -239,7 +239,7 @@ export default class Agent extends EventEmitter<{|
239
}
240
};
241
242
- logElementToConsole = ({ id, rendererID }: ElementAndRendererID) => {
242
+ logElementToConsole = ({id, rendererID}: ElementAndRendererID) => {
243
const renderer = this._rendererInterfaces[rendererID];
244
if (renderer == null) {
245
console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`);
@@ -252,7 +252,7 @@ export default class Agent extends EventEmitter<{|
252
sessionStorageSetItem(SESSION_STORAGE_RELOAD_AND_PROFILE_KEY, 'true');
253
sessionStorageSetItem(
254
SESSION_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY,
255
- recordChangeDescriptions ? 'true' : 'false'
255
+ recordChangeDescriptions ? 'true' : 'false',
256
);
257
258
// This code path should only be hit if the shell has explicitly told the Store that it supports profiling.
@@ -261,7 +261,7 @@ export default class Agent extends EventEmitter<{|
261
this._bridge.send('reloadAppForProfiling');
262
};
263
264
- overrideContext = ({ id, path, rendererID, value }: SetInParams) => {
264
+ overrideContext = ({id, path, rendererID, value}: SetInParams) => {
265
const renderer = this._rendererInterfaces[rendererID];
266
if (renderer == null) {
267
console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`);
@@ -285,7 +285,7 @@ export default class Agent extends EventEmitter<{|
285
}
286
};
287
288
- overrideProps = ({ id, path, rendererID, value }: SetInParams) => {
288
+ overrideProps = ({id, path, rendererID, value}: SetInParams) => {
289
const renderer = this._rendererInterfaces[rendererID];
290
if (renderer == null) {
291
console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`);
@@ -294,7 +294,7 @@ export default class Agent extends EventEmitter<{|
294
}
295
};
296
297
- overrideState = ({ id, path, rendererID, value }: SetInParams) => {
297
+ overrideState = ({id, path, rendererID, value}: SetInParams) => {
298
const renderer = this._rendererInterfaces[rendererID];
299
if (renderer == null) {
300
console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`);
@@ -325,7 +325,7 @@ export default class Agent extends EventEmitter<{|
325
326
setRendererInterface(
327
rendererID: RendererID,
328
- rendererInterface: RendererInterface
328
+ rendererInterface: RendererInterface,
329
) {
330
this._rendererInterfaces[rendererID] = rendererInterface;
331
@@ -400,7 +400,7 @@ export default class Agent extends EventEmitter<{|
400
}
401
};
402
403
- viewElementSource = ({ id, rendererID }: ElementAndRendererID) => {
403
+ viewElementSource = ({id, rendererID}: ElementAndRendererID) => {
404
const renderer = this._rendererInterfaces[rendererID];
405
if (renderer == null) {
406
console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`);
@@ -476,7 +476,7 @@ export default class Agent extends EventEmitter<{|
476
if (path !== null) {
477
sessionStorageSetItem(
478
SESSION_STORAGE_LAST_SELECTION_KEY,
479
- JSON.stringify(({ rendererID, path }: PersistedSelection))
479
+ JSON.stringify(({rendererID, path}: PersistedSelection)),
480
);
481
} else {
482
sessionStorageRemoveItem(SESSION_STORAGE_LAST_SELECTION_KEY);
packages/react-devtools-shared/src/backend/console.js
+7
-7
@@ -1,9 +1,9 @@
1
// @flow
2
3
-import { getInternalReactConstants } from './renderer';
3
+import {getInternalReactConstants} from './renderer';
4
import describeComponentFrame from './describeComponentFrame';
5
6
-import type { Fiber, ReactRenderer } from './types';
6
+import type {Fiber, ReactRenderer} from './types';
7
8
const APPEND_STACK_TO_METHODS = ['error', 'trace', 'warn'];
9
@@ -14,7 +14,7 @@ const injectedRenderers: Map<
14
{|
15
getCurrentFiber: () => Fiber | null,
16
getDisplayNameForFiber: (fiber: Fiber) => string | null,
17
- |}
17
+ |},
18
> = new Map();
19
20
let targetConsole: Object = console;
@@ -27,7 +27,7 @@ let unpatchFn: null | (() => void) = null;
27
28
// Enables e.g. Jest tests to inject a mock console object.
29
export function dangerous_setTargetConsoleForTesting(
30
- targetConsoleForTesting: Object
30
+ targetConsoleForTesting: Object,
31
): void {
32
targetConsole = targetConsoleForTesting;
33
@@ -41,7 +41,7 @@ export function dangerous_setTargetConsoleForTesting(
41
// These internals will be used if the console is patched.
42
// Injecting them separately allows the console to easily be patched or unpacted later (at runtime).
43
export function registerRenderer(renderer: ReactRenderer): void {
44
- const { getCurrentFiber, findFiberByHostInstance, version } = renderer;
44
+ const {getCurrentFiber, findFiberByHostInstance, version} = renderer;
45
46
// Ignore React v15 and older because they don't expose a component stack anyway.
47
if (typeof findFiberByHostInstance !== 'function') {
@@ -49,7 +49,7 @@ export function registerRenderer(renderer: ReactRenderer): void {
49
}
50
51
if (typeof getCurrentFiber === 'function') {
52
- const { getDisplayNameForFiber } = getInternalReactConstants(version);
52
+ const {getDisplayNameForFiber} = getInternalReactConstants(version);
53
54
injectedRenderers.set(renderer, {
55
getCurrentFiber,
@@ -107,7 +107,7 @@ export function patch(): void {
107
ownerStack += describeComponentFrame(
108
name,
109
current._debugSource,
110
- ownerName
110
+ ownerName,
111
);
112
113
current = owner;
packages/react-devtools-shared/src/backend/describeComponentFrame.js
+1
-1
@@ -10,7 +10,7 @@ const BEFORE_SLASH_RE = /^(.*)[\\/]/;
10
export default function describeComponentFrame(
11
name: null | string,
12
source: any,
13
- ownerName: null | string
13
+ ownerName: null | string,
14
) {
15
let sourceInfo = '';
16
if (source) {
packages/react-devtools-shared/src/backend/index.js
+8
-8
@@ -2,15 +2,15 @@
2
3
import Agent from './agent';
4
5
-import { attach } from './renderer';
6
-import { attach as attachLegacy } from './legacy/renderer';
5
+import {attach} from './renderer';
6
+import {attach as attachLegacy} from './legacy/renderer';
7
8
-import type { DevToolsHook, ReactRenderer, RendererInterface } from './types';
8
+import type {DevToolsHook, ReactRenderer, RendererInterface} from './types';
9
10
export function initBackend(
11
hook: DevToolsHook,
12
agent: Agent,
13
- global: Object
13
+ global: Object,
14
): () => void {
15
const subs = [
16
hook.sub(
@@ -29,7 +29,7 @@ export function initBackend(
29
// Now that the Store and the renderer interface are connected,
30
// it's time to flush the pending operation codes to the frontend.
31
rendererInterface.flushInitialOperations();
32
- }
32
+ },
33
),
34
35
hook.sub('operations', agent.onHookOperations),
@@ -69,10 +69,10 @@ export function initBackend(
69
subs.push(
70
hook.sub(
71
'renderer',
72
- ({ id, renderer }: { id: number, renderer: ReactRenderer }) => {
72
+ ({id, renderer}: {id: number, renderer: ReactRenderer}) => {
73
attachRenderer(id, renderer);
74
- }
75
- )
74
+ },
75
+ ),
76
);
77
78
hook.emit('react-devtools', agent);
packages/react-devtools-shared/src/backend/legacy/renderer.js
+30
-27
@@ -7,16 +7,16 @@ import {
7
ElementTypeHostComponent,
8
ElementTypeOtherOrUnknown,
9
} from 'react-devtools-shared/src/types';
10
-import { getUID, utfEncodeString, printOperationsArray } from '../../utils';
11
-import { cleanForBridge, copyWithSet } from '../utils';
12
-import { getDisplayName } from 'react-devtools-shared/src/utils';
10
+import {getUID, utfEncodeString, printOperationsArray} from '../../utils';
11
+import {cleanForBridge, copyWithSet} from '../utils';
12
+import {getDisplayName} from 'react-devtools-shared/src/utils';
13
import {
14
__DEBUG__,
15
TREE_OPERATION_ADD,
16
TREE_OPERATION_REMOVE,
17
TREE_OPERATION_REORDER_CHILDREN,
18
} from '../../constants';
19
-import { decorateMany, forceUpdate, restoreMany } from './utils';
19
+import {decorateMany, forceUpdate, restoreMany} from './utils';
20
21
import type {
22
DevToolsHook,
@@ -28,8 +28,11 @@ import type {
28
PathMatch,
29
RendererInterface,
30
} from '../types';
31
-import type { ComponentFilter, ElementType } from 'react-devtools-shared/src/types';
32
-import type { Owner, InspectedElement } from '../types';
31
+import type {
32
+ ComponentFilter,
33
+ ElementType,
34
+} from 'react-devtools-shared/src/types';
35
+import type {Owner, InspectedElement} from '../types';
36
37
export type InternalInstance = Object;
38
type LegacyRenderer = Object;
@@ -112,16 +115,16 @@ export function attach(
115
hook: DevToolsHook,
116
rendererID: number,
117
renderer: LegacyRenderer,
115
- global: Object
118
+ global: Object,
119
): RendererInterface {
120
const idToInternalInstanceMap: Map<number, InternalInstance> = new Map();
121
const internalInstanceToIDMap: WeakMap<
122
InternalInstance,
120
- number
123
+ number,
124
> = new WeakMap();
125
const internalInstanceToRootIDMap: WeakMap<
126
InternalInstance,
124
- number
127
+ number,
128
> = new WeakMap();
129
130
let getInternalIDForNative: GetFiberIDForNative = ((null: any): GetFiberIDForNative);
@@ -130,7 +133,7 @@ export function attach(
133
if (renderer.ComponentTree) {
134
getInternalIDForNative = (node, findNearestUnfilteredAncestor) => {
135
const internalInstance = renderer.ComponentTree.getClosestInstanceFromNode(
133
- node
136
+ node,
137
);
138
return internalInstanceToIDMap.get(internalInstance) || null;
139
};
@@ -203,7 +206,7 @@ export function attach(
206
// Remember the root.
207
internalInstanceToRootIDMap.set(
208
internalInstance,
206
- getID(hostContainerInfo._topLevelWrapper)
209
+ getID(hostContainerInfo._topLevelWrapper),
210
);
211
212
try {
@@ -337,7 +340,7 @@ export function attach(
340
function recordMount(
341
internalInstance: InternalInstance,
342
id: number,
340
- parentID: number
343
+ parentID: number,
344
) {
345
const isRoot = parentID === 0;
346
@@ -346,7 +349,7 @@ export function attach(
349
'%crecordMount()',
350
'color: green; font-weight: bold;',
351
id,
349
- getData(internalInstance).displayName
352
+ getData(internalInstance).displayName,
353
);
354
}
355
@@ -363,7 +366,7 @@ export function attach(
366
pushOperation(hasOwnerMetadata ? 1 : 0);
367
} else {
368
const type = getElementType(internalInstance);
366
- const { displayName, key } = getData(internalInstance);
369
+ const {displayName, key} = getData(internalInstance);
370
371
const ownerID =
372
internalInstance._currentElement != null &&
@@ -386,7 +389,7 @@ export function attach(
389
function recordReorder(
390
internalInstance: InternalInstance,
391
id: number,
389
- nextChildren: Array<InternalInstance>
392
+ nextChildren: Array<InternalInstance>,
393
) {
394
pushOperation(TREE_OPERATION_REORDER_CHILDREN);
395
pushOperation(id);
@@ -405,7 +408,7 @@ export function attach(
408
function crawlAndRecordInitialMounts(
409
id: number,
410
parentID: number,
408
- rootID: number
411
+ rootID: number,
412
) {
413
if (__DEBUG__) {
414
console.group('crawlAndRecordInitialMounts() id:', id);
@@ -416,7 +419,7 @@ export function attach(
419
internalInstanceToRootIDMap.set(internalInstance, rootID);
420
recordMount(internalInstance, id, parentID);
421
getChildren(internalInstance).forEach(child =>
419
- crawlAndRecordInitialMounts(getID(child), id, rootID)
422
+ crawlAndRecordInitialMounts(getID(child), id, rootID),
423
);
424
}
425
@@ -469,7 +472,7 @@ export function attach(
472
// [TREE_OPERATION_REMOVE, removedIDLength, ...ids]
473
(numUnmountIDs > 0 ? 2 + numUnmountIDs : 0) +
474
// Mount operations
472
- pendingOperations.length
475
+ pendingOperations.length,
476
);
477
478
// Identify which renderer this update is coming from.
@@ -532,7 +535,7 @@ export function attach(
535
if (!Number.isInteger(op)) {
536
console.error(
537
'pushOperation() was called but the value is not an integer.',
535
- op
538
+ op,
539
);
540
}
541
}
@@ -641,7 +644,7 @@ export function attach(
644
645
function inspectElement(
646
id: number,
644
- path?: Array<string | number>
647
+ path?: Array<string | number>,
648
): InspectedElementPayload {
649
if (currentlyInspectedElementID !== id) {
650
currentlyInspectedElementID = id;
@@ -667,15 +670,15 @@ export function attach(
670
671
inspectedElement.context = cleanForBridge(
672
inspectedElement.context,
670
- createIsPathWhitelisted('context')
673
+ createIsPathWhitelisted('context'),
674
);
675
inspectedElement.props = cleanForBridge(
676
inspectedElement.props,
674
- createIsPathWhitelisted('props')
677
+ createIsPathWhitelisted('props'),
678
);
679
inspectedElement.state = cleanForBridge(
680
inspectedElement.state,
678
- createIsPathWhitelisted('state')
681
+ createIsPathWhitelisted('state'),
682
);
683
684
return {
@@ -692,7 +695,7 @@ export function attach(
695
return null;
696
}
697
695
- const { displayName } = getData(internalInstance);
698
+ const {displayName} = getData(internalInstance);
699
const type = getElementType(internalInstance);
700
701
let context = null;
@@ -773,7 +776,7 @@ export function attach(
776
console.groupCollapsed(
777
`[Click to expand] %c<${result.displayName || 'Component'} />`,
778
// --dom-tag-name-color is the CSS variable Chrome styles HTML elements with in the console.
776
- 'color: var(--dom-tag-name-color); font-weight: normal;'
779
+ 'color: var(--dom-tag-name-color); font-weight: normal;',
780
);
781
}
782
if (result.props !== null) {
@@ -791,7 +794,7 @@ export function attach(
794
}
795
if (window.chrome || /firefox/i.test(navigator.userAgent)) {
796
console.log(
794
- 'Right-click any value to save it as a global variable for further inspection.'
797
+ 'Right-click any value to save it as a global variable for further inspection.',
798
);
799
}
800
if (supportsGroup) {
@@ -854,7 +857,7 @@ export function attach(
857
const parent = path.reduce(
858
// $FlowFixMe
859
(reduced, attr) => (reduced ? reduced[attr] : null),
857
- obj
860
+ obj,
861
);
862
if (parent) {
863
// $FlowFixMe
packages/react-devtools-shared/src/backend/legacy/utils.js
+2
-2
@@ -1,6 +1,6 @@
1
// @flow
2
3
-import type { InternalInstance } from './renderer';
3
+import type {InternalInstance} from './renderer';
4
5
export function decorate(object: Object, attr: string, fn: Function): Function {
6
const old = object[attr];
@@ -12,7 +12,7 @@ export function decorate(object: Object, attr: string, fn: Function): Function {
12
13
export function decorateMany(
14
source: Object,
15
- fns: { [attr: string]: Function }
15
+ fns: {[attr: string]: Function},
16
): Object {
17
const olds = {};
18
for (const name in fns) {
packages/react-devtools-shared/src/backend/renderer.js
+74
-71
@@ -1,6 +1,6 @@
1
// @flow
2
3
-import { gte } from 'semver';
3
+import {gte} from 'semver';
4
import {
5
ComponentFilterDisplayName,
6
ComponentFilterElementType,
@@ -25,8 +25,8 @@ import {
25
setInObject,
26
utfEncodeString,
27
} from 'react-devtools-shared/src/utils';
28
-import { sessionStorageGetItem } from 'react-devtools-shared/src/storage';
29
-import { cleanForBridge, copyWithSet } from './utils';
28
+import {sessionStorageGetItem} from 'react-devtools-shared/src/storage';
29
+import {cleanForBridge, copyWithSet} from './utils';
30
import {
31
__DEBUG__,
32
SESSION_STORAGE_RELOAD_AND_PROFILE_KEY,
@@ -36,7 +36,7 @@ import {
36
TREE_OPERATION_REORDER_CHILDREN,
37
TREE_OPERATION_UPDATE_TREE_BASE_DURATION,
38
} from '../constants';
39
-import { inspectHooksOfFiber } from 'react-debug-tools';
39
+import {inspectHooksOfFiber} from 'react-debug-tools';
40
import {
41
patch as patchConsole,
42
registerRenderer as registerRendererWithConsole,
@@ -58,8 +58,11 @@ import type {
58
ReactRenderer,
59
RendererInterface,
60
} from './types';
61
-import type { Interaction } from 'react-devtools-shared/src/devtools/views/Profiler/types';
62
-import type { ComponentFilter, ElementType } from 'react-devtools-shared/src/types';
61
+import type {Interaction} from 'react-devtools-shared/src/devtools/views/Profiler/types';
62
+import type {
63
+ ComponentFilter,
64
+ ElementType,
65
+} from 'react-devtools-shared/src/types';
66
67
type getDisplayNameForFiberType = (fiber: Fiber) => string | null;
68
type getTypeSymbolType = (type: any) => Symbol | number;
@@ -138,7 +141,7 @@ const getCurrentTime =
141
: () => Date.now();
142
143
export function getInternalReactConstants(
141
- version: string
144
+ version: string,
145
): {|
146
getDisplayNameForFiber: getDisplayNameForFiberType,
147
getTypeSymbol: getTypeSymbolType,
@@ -325,7 +328,7 @@ export function getInternalReactConstants(
328
329
// NOTICE Keep in sync with shouldFilterFiber() and other get*ForFiber methods
330
function getDisplayNameForFiber(fiber: Fiber): string | null {
328
- const { elementType, type, tag } = fiber;
331
+ const {elementType, type, tag} = fiber;
332
333
// This is to support lazy components with a Promise as the type.
334
// see https://github.com/facebook/react/pull/13397
@@ -422,7 +425,7 @@ export function attach(
425
hook: DevToolsHook,
426
rendererID: number,
427
renderer: ReactRenderer,
425
- global: Object
428
+ global: Object,
429
): RendererInterface {
430
const {
431
getDisplayNameForFiber,
@@ -432,7 +435,7 @@ export function attach(
435
ReactSymbols,
436
ReactTypeOfSideEffect,
437
} = getInternalReactConstants(renderer.version);
435
- const { NoEffect, PerformedWork, Placement } = ReactTypeOfSideEffect;
438
+ const {NoEffect, PerformedWork, Placement} = ReactTypeOfSideEffect;
439
const {
440
FunctionComponent,
441
ClassComponent,
@@ -515,7 +518,7 @@ export function attach(
518
}`,
519
'color: red; font-weight: bold;',
520
'color: blue;',
518
- 'color: purple;'
521
+ 'color: purple;',
522
);
523
}
524
};
@@ -539,7 +542,7 @@ export function attach(
542
case ComponentFilterDisplayName:
543
if (componentFilter.isValid && componentFilter.value !== '') {
544
hideElementsWithDisplayNames.add(
542
- new RegExp(componentFilter.value, 'i')
545
+ new RegExp(componentFilter.value, 'i'),
546
);
547
}
548
break;
@@ -556,7 +559,7 @@ export function attach(
559
break;
560
default:
561
console.warn(
559
- `Invalid component filter type "${componentFilter.type}"`
562
+ `Invalid component filter type "${componentFilter.type}"`,
563
);
564
break;
565
}
@@ -614,7 +617,7 @@ export function attach(
617
618
// NOTICE Keep in sync with get*ForFiber methods
619
function shouldFilterFiber(fiber: Fiber): boolean {
617
- const { _debugSource, tag, type } = fiber;
620
+ const {_debugSource, tag, type} = fiber;
621
622
switch (tag) {
623
case DehydratedSuspenseComponent:
@@ -663,7 +666,7 @@ export function attach(
666
}
667
668
if (_debugSource != null && hideElementsWithPaths.size > 0) {
666
- const { fileName } = _debugSource;
669
+ const {fileName} = _debugSource;
670
for (let pathRegExp of hideElementsWithPaths) {
671
if (pathRegExp.test(fileName)) {
672
return true;
@@ -675,7 +678,7 @@ export function attach(
678
}
679
// NOTICE Keep in sync with shouldFilterFiber() and other get*ForFiber methods
680
function getElementTypeForFiber(fiber: Fiber): ElementType {
678
- const { type, tag } = fiber;
681
+ const {type, tag} = fiber;
682
683
switch (tag) {
684
case ClassComponent:
@@ -735,7 +738,7 @@ export function attach(
738
if (primaryFibers.has(fiber)) {
739
return fiber;
740
}
738
- const { alternate } = fiber;
741
+ const {alternate} = fiber;
742
if (alternate != null && primaryFibers.has(alternate)) {
743
return alternate;
744
}
@@ -771,7 +774,7 @@ export function attach(
774
775
function getChangeDescription(
776
prevFiber: Fiber | null,
774
- nextFiber: Fiber
777
+ nextFiber: Fiber,
778
): ChangeDescription | null {
779
switch (getElementTypeForFiber(nextFiber)) {
780
case ElementTypeClass:
@@ -791,16 +794,16 @@ export function attach(
794
context: getContextChangedKeys(nextFiber),
795
didHooksChange: didHooksChange(
796
prevFiber.memoizedState,
794
- nextFiber.memoizedState
797
+ nextFiber.memoizedState,
798
),
799
isFirstMount: false,
800
props: getChangedKeys(
801
prevFiber.memoizedProps,
799
- nextFiber.memoizedProps
802
+ nextFiber.memoizedProps,
803
),
804
state: getChangedKeys(
805
prevFiber.memoizedState,
803
- nextFiber.memoizedState
806
+ nextFiber.memoizedState,
807
),
808
};
809
}
@@ -984,7 +987,7 @@ export function attach(
987
if (!Number.isInteger(op)) {
988
console.error(
989
'pushOperation() was called but the value is not an integer.',
987
- op
990
+ op,
991
);
992
}
993
}
@@ -1022,7 +1025,7 @@ export function attach(
1025
// [TREE_OPERATION_REMOVE, removedIDLength, ...ids]
1026
(numUnmountIDs > 0 ? 2 + numUnmountIDs : 0) +
1027
// Regular operations
1025
- pendingOperations.length
1028
+ pendingOperations.length,
1029
);
1030
1031
// Identify which renderer this update is coming from.
@@ -1134,10 +1137,10 @@ export function attach(
1137
}
1138
}
1139
} else {
1137
- const { key } = fiber;
1140
+ const {key} = fiber;
1141
const displayName = getDisplayNameForFiber(fiber);
1142
const elementType = getElementTypeForFiber(fiber);
1140
- const { _debugOwner } = fiber;
1143
+ const {_debugOwner} = fiber;
1144
1145
const ownerID =
1146
_debugOwner != null ? getFiberID(getPrimaryFiber(_debugOwner)) : 0;
@@ -1217,7 +1220,7 @@ export function attach(
1220
function mountFiberRecursively(
1221
fiber: Fiber,
1222
parentFiber: Fiber | null,
1220
- traverseSiblings = false
1223
+ traverseSiblings = false,
1224
) {
1225
if (__DEBUG__) {
1226
debug('mountFiberRecursively()', fiber, parentFiber);
@@ -1226,7 +1229,7 @@ export function attach(
1229
// If we have the tree selection from previous reload, try to match this Fiber.
1230
// Also remember whether to do the same for siblings.
1231
const mightSiblingsBeOnTrackedPath = updateTrackedPathStateBeforeMount(
1229
- fiber
1232
+ fiber,
1233
);
1234
1235
const shouldIncludeInTree = !shouldFilterFiber(fiber);
@@ -1253,7 +1256,7 @@ export function attach(
1256
mountFiberRecursively(
1257
fallbackChild,
1258
shouldIncludeInTree ? fiber : parentFiber,
1256
- true
1259
+ true,
1260
);
1261
}
1262
} else {
@@ -1261,7 +1264,7 @@ export function attach(
1264
mountFiberRecursively(
1265
fiber.child,
1266
shouldIncludeInTree ? fiber : parentFiber,
1264
- true
1267
+ true,
1268
);
1269
}
1270
}
@@ -1311,12 +1314,12 @@ export function attach(
1314
1315
function recordProfilingDurations(fiber: Fiber) {
1316
const id = getFiberID(getPrimaryFiber(fiber));
1314
- const { actualDuration, treeBaseDuration } = fiber;
1317
+ const {actualDuration, treeBaseDuration} = fiber;
1318
1319
idToTreeBaseDurationMap.set(id, fiber.treeBaseDuration || 0);
1320
1321
if (isProfiling) {
1319
- const { alternate } = fiber;
1322
+ const {alternate} = fiber;
1323
1324
if (
1325
alternate == null ||
@@ -1325,7 +1328,7 @@ export function attach(
1328
// Tree base duration updates are included in the operations typed array.
1329
// So we have to convert them from milliseconds to microseconds so we can send them as ints.
1330
const treeBaseDuration = Math.floor(
1328
- (fiber.treeBaseDuration || 0) * 1000
1331
+ (fiber.treeBaseDuration || 0) * 1000,
1332
);
1333
pushOperation(TREE_OPERATION_UPDATE_TREE_BASE_DURATION);
1334
pushOperation(id);
@@ -1355,7 +1358,7 @@ export function attach(
1358
metadata.durations.push(id, actualDuration, selfDuration);
1359
metadata.maxActualDuration = Math.max(
1360
metadata.maxActualDuration,
1358
- actualDuration
1361
+ actualDuration,
1362
);
1363
1364
if (recordChangeDescriptions) {
@@ -1402,7 +1405,7 @@ export function attach(
1405
1406
function findReorderedChildrenRecursively(
1407
fiber: Fiber,
1405
- nextChildren: Array<number>
1408
+ nextChildren: Array<number>,
1409
) {
1410
if (!shouldFilterFiber(fiber)) {
1411
nextChildren.push(getFiberID(getPrimaryFiber(fiber)));
@@ -1419,7 +1422,7 @@ export function attach(
1422
function updateFiberRecursively(
1423
nextFiber: Fiber,
1424
prevFiber: Fiber,
1422
- parentFiber: Fiber | null
1425
+ parentFiber: Fiber | null,
1426
): boolean {
1427
if (__DEBUG__) {
1428
debug('updateFiberRecursively()', nextFiber, parentFiber);
@@ -1470,7 +1473,7 @@ export function attach(
1473
updateFiberRecursively(
1474
nextFallbackChildSet,
1475
prevFallbackChildSet,
1473
- nextFiber
1476
+ nextFiber,
1477
)
1478
) {
1479
shouldResetChildren = true;
@@ -1519,7 +1522,7 @@ export function attach(
1522
updateFiberRecursively(
1523
nextChild,
1524
prevChild,
1522
- shouldIncludeInTree ? nextFiber : parentFiber
1525
+ shouldIncludeInTree ? nextFiber : parentFiber,
1526
)
1527
) {
1528
// If a nested tree child order changed but it can't handle its own
@@ -1536,7 +1539,7 @@ export function attach(
1539
} else {
1540
mountFiberRecursively(
1541
nextChild,
1539
- shouldIncludeInTree ? nextFiber : parentFiber
1542
+ shouldIncludeInTree ? nextFiber : parentFiber,
1543
);
1544
shouldResetChildren = true;
1545
}
@@ -1626,7 +1629,7 @@ export function attach(
1629
(interaction: Interaction) => ({
1630
...interaction,
1631
timestamp: interaction.timestamp - profilingStartTime,
1629
- })
1632
+ }),
1633
),
1634
maxActualDuration: 0,
1635
priorityLevel: null,
@@ -1670,7 +1673,7 @@ export function attach(
1673
(interaction: Interaction) => ({
1674
...interaction,
1675
timestamp: interaction.timestamp - profilingStartTime,
1673
- })
1676
+ }),
1677
),
1678
maxActualDuration: 0,
1679
priorityLevel:
@@ -1705,16 +1708,16 @@ export function attach(
1708
1709
if (isProfiling) {
1710
const commitProfilingMetadata = ((rootToCommitProfilingMetadataMap: any): CommitProfilingMetadataMap).get(
1708
- currentRootID
1711
+ currentRootID,
1712
);
1713
if (commitProfilingMetadata != null) {
1714
commitProfilingMetadata.push(
1712
- ((currentCommitProfilingMetadata: any): CommitProfilingData)
1715
+ ((currentCommitProfilingMetadata: any): CommitProfilingData),
1716
);
1717
} else {
1718
((rootToCommitProfilingMetadataMap: any): CommitProfilingMetadataMap).set(
1719
currentRootID,
1717
- [((currentCommitProfilingMetadata: any): CommitProfilingData)]
1720
+ [((currentCommitProfilingMetadata: any): CommitProfilingData)],
1721
);
1722
}
1723
}
@@ -1786,7 +1789,7 @@ export function attach(
1789
1790
function getFiberIDForNative(
1791
hostInstance,
1789
- findNearestUnfilteredAncestor = false
1792
+ findNearestUnfilteredAncestor = false,
1793
) {
1794
let fiber = renderer.findFiberByHostInstance(hostInstance);
1795
if (fiber != null) {
@@ -1962,7 +1965,7 @@ export function attach(
1965
if (!didFindChild) {
1966
throw Error(
1967
'Child was not found in either parent set. This indicates a bug ' +
1965
- 'in React related to the return pointer. Please file an issue.'
1968
+ 'in React related to the return pointer. Please file an issue.',
1969
);
1970
}
1971
}
@@ -1971,7 +1974,7 @@ export function attach(
1974
if (a.alternate !== b) {
1975
throw Error(
1976
"Return fibers should always be each others' alternates. " +
1974
- 'This error is likely caused by a bug in React. Please file an issue.'
1977
+ 'This error is likely caused by a bug in React. Please file an issue.',
1978
);
1979
}
1980
}
@@ -1996,7 +1999,7 @@ export function attach(
1999
return;
2000
}
2001
1999
- const { elementType, tag, type } = fiber;
2002
+ const {elementType, tag, type} = fiber;
2003
2004
switch (tag) {
2005
case ClassComponent:
@@ -2027,7 +2030,7 @@ export function attach(
2030
return null;
2031
}
2032
2030
- const { _debugOwner } = fiber;
2033
+ const {_debugOwner} = fiber;
2034
2035
const owners = [
2036
{
@@ -2065,7 +2068,7 @@ export function attach(
2068
style = fiber.memoizedProps.style;
2069
}
2070
2068
- return { instance, style };
2071
+ return {instance, style};
2072
}
2073
2074
function inspectElementRaw(id: number): InspectedElement | null {
@@ -2146,7 +2149,7 @@ export function attach(
2149
if (context !== null) {
2150
// To simplify hydration and display logic for context, wrap in a value object.
2151
// Otherwise simple values (e.g. strings, booleans) become harder to handle.
2149
- context = { value: context };
2152
+ context = {value: context};
2153
}
2154
2155
let owners = null;
@@ -2182,7 +2185,7 @@ export function attach(
2185
try {
2186
hooks = inspectHooksOfFiber(
2187
fiber,
2185
- (renderer.currentDispatcherRef: any)
2188
+ (renderer.currentDispatcherRef: any),
2189
);
2190
} finally {
2191
// Restore original console functionality.
@@ -2259,7 +2262,7 @@ export function attach(
2262
2263
function createIsPathWhitelisted(
2264
key: string | null,
2262
- secondaryCategory: 'hooks' | null
2265
+ secondaryCategory: 'hooks' | null,
2266
) {
2267
// This function helps prevent previously-inspected paths from being dehydrated in updates.
2268
// This is important to avoid a bad user experience where expanded toggles collapse on update.
@@ -2300,7 +2303,7 @@ export function attach(
2303
}
2304
2305
function updateSelectedElement(inspectedElement: InspectedElement): void {
2303
- const { hooks, id, props } = inspectedElement;
2306
+ const {hooks, id, props} = inspectedElement;
2307
2308
let fiber = idToFiberMap.get(id);
2309
if (fiber == null) {
@@ -2308,7 +2311,7 @@ export function attach(
2311
return;
2312
}
2313
2311
- const { elementType, stateNode, tag, type } = fiber;
2314
+ const {elementType, stateNode, tag, type} = fiber;
2315
2316
switch (tag) {
2317
case ClassComponent:
@@ -2347,7 +2350,7 @@ export function attach(
2350
2351
function inspectElement(
2352
id: number,
2350
- path?: Array<string | number>
2353
+ path?: Array<string | number>,
2354
): InspectedElementPayload {
2355
const isCurrent = isMostRecentlyInspectedElementCurrent(id);
2356
@@ -2369,10 +2372,10 @@ export function attach(
2372
value: cleanForBridge(
2373
getInObject(
2374
((mostRecentlyInspectedElement: any): InspectedElement),
2372
- path
2375
+ path,
2376
),
2377
createIsPathWhitelisted(null, secondaryCategory),
2375
- path
2378
+ path,
2379
),
2380
};
2381
} else {
@@ -2413,22 +2416,22 @@ export function attach(
2416
// Clone before cleaning so that we preserve the full data.
2417
// This will enable us to send patches without re-inspecting if hydrated paths are requested.
2418
// (Reducing how often we shallow-render is a better DX for function components that use hooks.)
2416
- const cleanedInspectedElement = { ...mostRecentlyInspectedElement };
2419
+ const cleanedInspectedElement = {...mostRecentlyInspectedElement};
2420
cleanedInspectedElement.context = cleanForBridge(
2421
cleanedInspectedElement.context,
2419
- createIsPathWhitelisted('context', null)
2422
+ createIsPathWhitelisted('context', null),
2423
);
2424
cleanedInspectedElement.hooks = cleanForBridge(
2425
cleanedInspectedElement.hooks,
2423
- createIsPathWhitelisted('hooks', 'hooks')
2426
+ createIsPathWhitelisted('hooks', 'hooks'),
2427
);
2428
cleanedInspectedElement.props = cleanForBridge(
2429
cleanedInspectedElement.props,
2427
- createIsPathWhitelisted('props', null)
2430
+ createIsPathWhitelisted('props', null),
2431
);
2432
cleanedInspectedElement.state = cleanForBridge(
2433
cleanedInspectedElement.state,
2431
- createIsPathWhitelisted('state', null)
2434
+ createIsPathWhitelisted('state', null),
2435
);
2436
2437
return {
@@ -2453,7 +2456,7 @@ export function attach(
2456
console.groupCollapsed(
2457
`[Click to expand] %c<${result.displayName || 'Component'} />`,
2458
// --dom-tag-name-color is the CSS variable Chrome styles HTML elements with in the console.
2456
- 'color: var(--dom-tag-name-color); font-weight: normal;'
2459
+ 'color: var(--dom-tag-name-color); font-weight: normal;',
2460
);
2461
}
2462
if (result.props !== null) {
@@ -2474,7 +2477,7 @@ export function attach(
2477
}
2478
if (window.chrome || /firefox/i.test(navigator.userAgent)) {
2479
console.log(
2477
- 'Right-click any value to save it as a global variable for further inspection.'
2480
+ 'Right-click any value to save it as a global variable for further inspection.',
2481
);
2482
}
2483
if (supportsGroup) {
@@ -2486,7 +2489,7 @@ export function attach(
2489
id: number,
2490
index: number,
2491
path: Array<string | number>,
2489
- value: any
2492
+ value: any,
2493
) {
2494
const fiber = findCurrentFiberUsingSlowPathById(id);
2495
if (fiber !== null) {
@@ -2566,7 +2569,7 @@ export function attach(
2569
2570
if (rootToCommitProfilingMetadataMap === null) {
2571
throw Error(
2569
- 'getProfilingData() called before any profiling data was recorded'
2572
+ 'getProfilingData() called before any profiling data was recorded',
2573
);
2574
}
2575
@@ -2651,7 +2654,7 @@ export function attach(
2654
interactions: Array.from(allInteractions.entries()),
2655
rootID,
2656
});
2654
- }
2657
+ },
2658
);
2659
2660
return {
@@ -2680,7 +2683,7 @@ export function attach(
2683
const rootID = getFiberID(getPrimaryFiber(root.current));
2684
((displayNamesByRootID: any): DisplayNamesByRootID).set(
2685
rootID,
2683
- getDisplayNameForRoot(root.current)
2686
+ getDisplayNameForRoot(root.current),
2687
);
2688
2689
if (shouldRecordChangeDescriptions) {
@@ -2707,7 +2710,7 @@ export function attach(
2710
) {
2711
startProfiling(
2712
sessionStorageGetItem(SESSION_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY) ===
2710
- 'true'
2713
+ 'true',
2714
);
2715
}
2716
@@ -2730,7 +2733,7 @@ export function attach(
2733
typeof scheduleUpdate !== 'function'
2734
) {
2735
throw new Error(
2733
- 'Expected overrideSuspense() to not get called for earlier React versions.'
2736
+ 'Expected overrideSuspense() to not get called for earlier React versions.',
2737
);
2738
}
2739
if (forceFallback) {
@@ -2890,7 +2893,7 @@ export function attach(
2893
}
2894
2895
function getPathFrame(fiber: Fiber): PathFrame {
2893
- const { key } = fiber;
2896
+ const {key} = fiber;
2897
let displayName = getDisplayNameForFiber(fiber);
2898
const index = fiber.index;
2899
switch (fiber.tag) {
packages/react-devtools-shared/src/backend/types.js
+15
-12
@@ -1,8 +1,11 @@
1
// @flow
2
3
-import type { ComponentFilter, ElementType } from 'react-devtools-shared/src/types';
4
-import type { Interaction } from 'react-devtools-shared/src/devtools/views/Profiler/types';
5
-import type { ResolveNativeStyle } from 'react-devtools-shared/src/backend/NativeStyleEditor/setupNativeStyleEditor';
3
+import type {
4
+ ComponentFilter,
5
+ ElementType,
6
+} from 'react-devtools-shared/src/types';
7
+import type {Interaction} from 'react-devtools-shared/src/devtools/views/Profiler/types';
8
+import type {ResolveNativeStyle} from 'react-devtools-shared/src/backend/NativeStyleEditor/setupNativeStyleEditor';
9
10
type BundleType =
11
| 0 // PROD
@@ -50,7 +53,7 @@ export type Fiber = {|
53
sibling: Fiber | null,
54
index: number,
55
53
- ref: null | (((handle: mixed) => void) & { _stringRef: ?string }) | RefObject,
56
+ ref: null | (((handle: mixed) => void) & {_stringRef: ?string}) | RefObject,
57
58
pendingProps: any, // This type will be more specific once we overload the tag.
59
memoizedProps: any, // The props used to create the output.
@@ -87,7 +90,7 @@ type Dispatcher = any;
90
91
export type GetFiberIDForNative = (
92
component: NativeType,
90
- findNearestUnfilteredAncestor?: boolean
93
+ findNearestUnfilteredAncestor?: boolean,
94
) => number | null;
95
export type FindNativeNodesForFiberID = (id: number) => ?Array<NativeType>;
96
@@ -122,14 +125,14 @@ export type ReactRenderer = {
125
fiber: Object,
126
id: number,
127
path: Array<string | number>,
125
- value: any
128
+ value: any,
129
) => void,
130
131
// 16.7+
132
overrideProps?: ?(
133
fiber: Object,
134
path: Array<string | number>,
132
- value: any
135
+ value: any,
136
) => void,
137
138
// 16.9+
@@ -137,7 +140,7 @@ export type ReactRenderer = {
140
setSuspenseHandler?: ?(shouldSuspend: (fiber: Object) => boolean) => void,
141
142
// Only injected by React v16.8+ in order to support hooks inspection.
140
- currentDispatcherRef?: {| current: null | Dispatcher |},
143
+ currentDispatcherRef?: {|current: null | Dispatcher|},
144
145
// Only injected by React v16.9+ in DEV mode.
146
// Enables DevTools to append owners-only component stack to error messages.
@@ -293,7 +296,7 @@ export type RendererInterface = {
296
handleCommitFiberUnmount: (fiber: Object) => void,
297
inspectElement: (
298
id: number,
296
- path?: Array<string | number>
299
+ path?: Array<string | number>,
300
) => InspectedElementPayload,
301
logElementToConsole: (id: number) => void,
302
overrideSuspense: (id: number, forceFallback: boolean) => void,
@@ -304,7 +307,7 @@ export type RendererInterface = {
307
id: number,
308
index: number,
309
path: Array<string | number>,
307
- value: any
310
+ value: any,
311
) => void,
312
setInProps: (id: number, path: Array<string | number>, value: any) => void,
313
setInState: (id: number, path: Array<string | number>, value: any) => void,
@@ -317,7 +320,7 @@ export type RendererInterface = {
320
export type Handler = (data: any) => void;
321
322
export type DevToolsHook = {
320
- listeners: { [key: string]: Array<Handler> },
323
+ listeners: {[key: string]: Array<Handler>},
324
rendererInterfaces: Map<RendererID, RendererInterface>,
325
renderers: Map<RendererID, ReactRenderer>,
326
@@ -339,7 +342,7 @@ export type DevToolsHook = {
342
onCommitFiberRoot: (
343
rendererID: RendererID,
344
fiber: Object,
342
- commitPriority?: number
345
+ commitPriority?: number,
346
) => void,
347
};
348
packages/react-devtools-shared/src/backend/utils.js
+5
-5
@@ -1,13 +1,13 @@
1
// @flow
2
3
-import { dehydrate } from '../hydration';
3
+import {dehydrate} from '../hydration';
4
5
-import type { DehydratedData } from 'react-devtools-shared/src/devtools/views/Components/types';
5
+import type {DehydratedData} from 'react-devtools-shared/src/devtools/views/Components/types';
6
7
export function cleanForBridge(
8
data: Object | null,
9
isPathWhitelisted: (path: Array<string | number>) => boolean,
10
- path?: Array<string | number> = []
10
+ path?: Array<string | number> = [],
11
): DehydratedData | null {
12
if (data !== null) {
13
const cleaned = [];
@@ -25,14 +25,14 @@ export function copyWithSet(
25
obj: Object | Array<any>,
26
path: Array<string | number>,
27
value: any,
28
- index: number = 0
28
+ index: number = 0,
29
): Object | Array<any> {
30
console.log('[utils] copyWithSet()', obj, path, index, value);
31
if (index >= path.length) {
32
return value;
33
}
34
const key = path[index];
35
- const updated = Array.isArray(obj) ? obj.slice() : { ...obj };
35
+ const updated = Array.isArray(obj) ? obj.slice() : {...obj};
36
// $FlowFixMe number or string is fine here
37
updated[key] = copyWithSet(obj[key], path, value, index + 1);
38
return updated;
packages/react-devtools-shared/src/backend/views/Highlighter/Highlighter.js
+1
-1
@@ -19,7 +19,7 @@ export function hideOverlay() {
19
export function showOverlay(
20
elements: Array<HTMLElement> | null,
21
componentName: string | null,
22
- hideAfterTimeout: boolean
22
+ hideAfterTimeout: boolean,
23
) {
24
// TODO (npm-packages) Detect RN and support it somehow
25
if (window.document == null) {
packages/react-devtools-shared/src/backend/views/Highlighter/Overlay.js
+9
-9
@@ -11,7 +11,7 @@ type Rect = {
11
width: number,
12
};
13
14
-type Box = {| top: number, left: number, width: number, height: number |};
14
+type Box = {|top: number, left: number, width: number, height: number|};
15
16
// Note that the Overlay components are not affected by the active Theme,
17
// because they highlight elements in the main Chrome window (outside of devtools).
@@ -211,11 +211,11 @@ export default class Overlay {
211
outerBox.top = Math.min(outerBox.top, box.top - dims.marginTop);
212
outerBox.right = Math.max(
213
outerBox.right,
214
- box.left + box.width + dims.marginRight
214
+ box.left + box.width + dims.marginRight,
215
);
216
outerBox.bottom = Math.max(
217
outerBox.bottom,
218
- box.top + box.height + dims.marginBottom
218
+ box.top + box.height + dims.marginBottom,
219
);
220
outerBox.left = Math.min(outerBox.left, box.left - dims.marginLeft);
221
@@ -234,11 +234,11 @@ export default class Overlay {
234
this.tip.updateText(
235
name,
236
outerBox.right - outerBox.left,
237
- outerBox.bottom - outerBox.top
237
+ outerBox.bottom - outerBox.top,
238
);
239
const tipBounds = getNestedBoundingClientRect(
240
this.tipBoundsWindow.document.documentElement,
241
- this.window
241
+ this.window,
242
);
243
244
this.tip.updatePosition(
@@ -253,7 +253,7 @@ export default class Overlay {
253
left: tipBounds.left + this.tipBoundsWindow.scrollX,
254
height: this.tipBoundsWindow.innerHeight,
255
width: this.tipBoundsWindow.innerWidth,
256
- }
256
+ },
257
);
258
}
259
}
@@ -280,7 +280,7 @@ function getFiber(node) {
280
return (node: any)[lastFoundInternalKey];
281
}
282
let internalKey = Object.keys(node).find(
283
- key => key.indexOf('__reactInternalInstance') === 0
283
+ key => key.indexOf('__reactInternalInstance') === 0,
284
);
285
if (internalKey) {
286
lastFoundInternalKey = internalKey;
@@ -322,7 +322,7 @@ function findTipPos(dims, bounds, tipSize) {
322
top += 'px';
323
left += 'px';
324
return {
325
- style: { top, left },
325
+ style: {top, left},
326
};
327
}
328
@@ -407,7 +407,7 @@ function mergeRectOffsets(rects: Array<Rect>): Rect {
407
// taking into account any offsets caused by intermediate iframes.
408
function getNestedBoundingClientRect(
409
node: HTMLElement,
410
- boundaryWindow: typeof window
410
+ boundaryWindow: typeof window,
411
): Rect {
412
const ownerIframe = getOwnerIframe(node);
413
if (ownerIframe && ownerIframe !== boundaryWindow) {
packages/react-devtools-shared/src/backend/views/Highlighter/index.js
+9
-9
@@ -3,9 +3,9 @@
3
import memoize from 'memoize-one';
4
import throttle from 'lodash.throttle';
5
import Agent from 'react-devtools-shared/src/backend/agent';
6
-import { hideOverlay, showOverlay } from './Highlighter';
6
+import {hideOverlay, showOverlay} from './Highlighter';
7
8
-import type { BackendBridge } from 'react-devtools-shared/src/bridge';
8
+import type {BackendBridge} from 'react-devtools-shared/src/bridge';
9
10
// This plug-in provides in-page highlighting of the selected element.
11
// It is used by the browser extension nad the standalone DevTools shell (when connected to a browser).
@@ -16,11 +16,11 @@ let iframesListeningTo: Set<HTMLIFrameElement> = new Set();
16
17
export default function setupHighlighter(
18
bridge: BackendBridge,
19
- agent: Agent
19
+ agent: Agent,
20
): void {
21
bridge.addListener(
22
'clearNativeElementHighlight',
23
- clearNativeElementHighlight
23
+ clearNativeElementHighlight,
24
);
25
bridge.addListener('highlightNativeElement', highlightNativeElement);
26
bridge.addListener('shutdown', stopInspectingNative);
@@ -96,9 +96,9 @@ export default function setupHighlighter(
96
97
let nodes: ?Array<HTMLElement> = null;
98
if (renderer !== null) {
99
- nodes = ((renderer.findNativeNodesForFiberID(
100
- id
101
- ): any): ?Array<HTMLElement>);
99
+ nodes = ((renderer.findNativeNodesForFiberID(id): any): ?Array<
100
+ HTMLElement,
101
+ >);
102
}
103
104
if (nodes != null && nodes[0] != null) {
@@ -107,7 +107,7 @@ export default function setupHighlighter(
107
// If the node isn't visible show it before highlighting it.
108
// We may want to reconsider this; it might be a little disruptive.
109
// $FlowFixMe Flow only knows about 'start' | 'end'
110
- node.scrollIntoView({ block: 'nearest', inline: 'nearest' });
110
+ node.scrollIntoView({block: 'nearest', inline: 'nearest'});
111
}
112
113
showOverlay(nodes, displayName, hideAfterTimeout);
@@ -183,6 +183,6 @@ export default function setupHighlighter(
183
200,
184
// Don't change the selection in the very first 200ms
185
// because those are usually unintentional as you lift the cursor.
186
- { leading: false }
186
+ {leading: false},
187
);
188
}
packages/react-devtools-shared/src/bridge.js
+7
-7
@@ -2,18 +2,18 @@
2
3
import EventEmitter from 'node-events';
4
5
-import type { ComponentFilter, Wall } from './types';
5
+import type {ComponentFilter, Wall} from './types';
6
import type {
7
InspectedElementPayload,
8
OwnersList,
9
ProfilingDataBackend,
10
RendererID,
11
} from 'react-devtools-shared/src/backend/types';
12
-import type { StyleAndLayout as StyleAndLayoutPayload } from 'react-devtools-shared/src/backend/NativeStyleEditor/types';
12
+import type {StyleAndLayout as StyleAndLayoutPayload} from 'react-devtools-shared/src/backend/NativeStyleEditor/types';
13
14
const BATCH_DURATION = 100;
15
16
-type ElementAndRendererID = {| id: number, rendererID: RendererID |};
16
+type ElementAndRendererID = {|id: number, rendererID: RendererID|};
17
18
type Message = {|
19
event: string,
@@ -79,7 +79,7 @@ type BackendEvents = {|
79
80
// React Native style editor plug-in.
81
isNativeStyleEditorSupported: [
82
- {| isSupported: boolean, validAttributes: ?$ReadOnlyArray<string> |},
82
+ {|isSupported: boolean, validAttributes: ?$ReadOnlyArray<string>|},
83
],
84
NativeStyleEditor_styleAndLayout: [StyleAndLayoutPayload],
85
|};
@@ -87,7 +87,7 @@ type BackendEvents = {|
87
type FrontendEvents = {|
88
clearNativeElementHighlight: [],
89
getOwnersList: [ElementAndRendererID],
90
- getProfilingData: [{| rendererID: RendererID |}],
90
+ getProfilingData: [{|rendererID: RendererID|}],
91
getProfilingStatus: [],
92
highlightNativeElement: [HighlightElementInDOM],
93
inspectElement: [InspectElementParams],
@@ -117,7 +117,7 @@ type FrontendEvents = {|
117
118
class Bridge<
119
OutgoingEvents: Object,
120
- IncomingEvents: Object
120
+ IncomingEvents: Object,
121
> extends EventEmitter<{|
122
...IncomingEvents,
123
...OutgoingEvents,
@@ -151,7 +151,7 @@ class Bridge<
151
) {
152
if (this._isShutdown) {
153
console.warn(
154
- `Cannot send message "${event}" through a Bridge that has been shutdown.`
154
+ `Cannot send message "${event}" through a Bridge that has been shutdown.`,
155
);
156
return;
157
}
packages/react-devtools-shared/src/constants.js
+1
-1
@@ -57,4 +57,4 @@ try {
57
COMPACT_LINE_HEIGHT = 10;
58
}
59
60
-export { COMFORTABLE_LINE_HEIGHT, COMPACT_LINE_HEIGHT };
60
+export {COMFORTABLE_LINE_HEIGHT, COMPACT_LINE_HEIGHT};
packages/react-devtools-shared/src/devtools/ProfilerStore.js
+12
-12
@@ -1,12 +1,12 @@
1
// @flow
2
3
import EventEmitter from 'node-events';
4
-import { prepareProfilingDataFrontendFromBackendAndStore } from './views/Profiler/utils';
4
+import {prepareProfilingDataFrontendFromBackendAndStore} from './views/Profiler/utils';
5
import ProfilingCache from './ProfilingCache';
6
import Store from './store';
7
8
-import type { FrontendBridge } from 'react-devtools-shared/src/bridge';
9
-import type { ProfilingDataBackend } from 'react-devtools-shared/src/backend/types';
8
+import type {FrontendBridge} from 'react-devtools-shared/src/bridge';
9
+import type {ProfilingDataBackend} from 'react-devtools-shared/src/backend/types';
10
import type {
11
CommitDataFrontend,
12
ProfilingDataForRootFrontend,
@@ -71,7 +71,7 @@ export default class ProfilerStore extends EventEmitter<{|
71
constructor(
72
bridge: FrontendBridge,
73
store: Store,
74
- defaultIsProfiling: boolean
74
+ defaultIsProfiling: boolean,
75
) {
76
super();
77
@@ -103,7 +103,7 @@ export default class ProfilerStore extends EventEmitter<{|
103
}
104
105
throw Error(
106
- `Could not find commit data for root "${rootID}" and commit ${commitIndex}`
106
+ `Could not find commit data for root "${rootID}" and commit ${commitIndex}`,
107
);
108
}
109
@@ -143,7 +143,7 @@ export default class ProfilerStore extends EventEmitter<{|
143
set profilingData(value: ProfilingDataFrontend | null): void {
144
if (this._isProfiling) {
145
console.warn(
146
- 'Profiling data cannot be updated while profiling is in progress.'
146
+ 'Profiling data cannot be updated while profiling is in progress.',
147
);
148
return;
149
}
@@ -193,7 +193,7 @@ export default class ProfilerStore extends EventEmitter<{|
193
194
_takeProfilingSnapshotRecursive = (
195
elementID: number,
196
- profilingSnapshots: Map<number, SnapshotNode>
196
+ profilingSnapshots: Map<number, SnapshotNode>,
197
) => {
198
const element = this._store.getElementByID(elementID);
199
if (element !== null) {
@@ -207,7 +207,7 @@ export default class ProfilerStore extends EventEmitter<{|
207
profilingSnapshots.set(elementID, snapshotNode);
208
209
element.children.forEach(childID =>
210
- this._takeProfilingSnapshotRecursive(childID, profilingSnapshots)
210
+ this._takeProfilingSnapshotRecursive(childID, profilingSnapshots),
211
);
212
}
213
};
@@ -242,11 +242,11 @@ export default class ProfilerStore extends EventEmitter<{|
242
return;
243
}
244
245
- const { rendererID } = dataBackend;
245
+ const {rendererID} = dataBackend;
246
247
if (!this._rendererQueue.has(rendererID)) {
248
throw Error(
249
- `Unexpected profiling data update from renderer "${rendererID}"`
249
+ `Unexpected profiling data update from renderer "${rendererID}"`,
250
);
251
}
252
@@ -257,7 +257,7 @@ export default class ProfilerStore extends EventEmitter<{|
257
this._dataFrontend = prepareProfilingDataFrontendFromBackendAndStore(
258
this._dataBackends,
259
this._inProgressOperationsByRootID,
260
- this._initialSnapshotsByRootID
260
+ this._initialSnapshotsByRootID,
261
);
262
263
this._dataBackends.splice(0);
@@ -319,7 +319,7 @@ export default class ProfilerStore extends EventEmitter<{|
319
if (!this._rendererQueue.has(rendererID)) {
320
this._rendererQueue.add(rendererID);
321
322
- this._bridge.send('getProfilingData', { rendererID });
322
+ this._bridge.send('getProfilingData', {rendererID});
323
}
324
});
325
packages/react-devtools-shared/src/devtools/ProfilingCache.js
+4
-4
@@ -18,10 +18,10 @@ import {
18
invalidateChartData as invalidateRankedChartData,
19
} from 'react-devtools-shared/src/devtools/views/Profiler/RankedChartBuilder';
20
21
-import type { CommitTree } from 'react-devtools-shared/src/devtools/views/Profiler/types';
22
-import type { ChartData as FlamegraphChartData } from 'react-devtools-shared/src/devtools/views/Profiler/FlamegraphChartBuilder';
23
-import type { ChartData as InteractionsChartData } from 'react-devtools-shared/src/devtools/views/Profiler/InteractionsChartBuilder';
24
-import type { ChartData as RankedChartData } from 'react-devtools-shared/src/devtools/views/Profiler/RankedChartBuilder';
21
+import type {CommitTree} from 'react-devtools-shared/src/devtools/views/Profiler/types';
22
+import type {ChartData as FlamegraphChartData} from 'react-devtools-shared/src/devtools/views/Profiler/FlamegraphChartBuilder';
23
+import type {ChartData as InteractionsChartData} from 'react-devtools-shared/src/devtools/views/Profiler/InteractionsChartBuilder';
24
+import type {ChartData as RankedChartData} from 'react-devtools-shared/src/devtools/views/Profiler/RankedChartBuilder';
25
26
export default class ProfilingCache {
27
_fiberCommits: Map<number, Array<number>> = new Map();
packages/react-devtools-shared/src/devtools/cache.js
+7
-7
@@ -1,6 +1,6 @@
1
// @flow
2
3
-import React, { createContext } from 'react';
3
+import React, {createContext} from 'react';
4
5
// Cache implementation was forked from the React repo:
6
// https://github.com/facebook/react/blob/master/packages/react-cache/src/ReactCache.js
@@ -58,7 +58,7 @@ function readContext(Context, observedBits) {
58
throw new Error(
59
'react-cache: read and preload may only be called from within a ' +
60
"component's render. They are not supported in event handlers or " +
61
- 'lifecycle methods.'
61
+ 'lifecycle methods.',
62
);
63
}
64
return dispatcher.readContext(Context, observedBits);
@@ -72,12 +72,12 @@ type Config = {
72
73
const entries: Map<
74
Resource<any, any, any>,
75
- Map<any, any> | WeakMap<any, any>
75
+ Map<any, any> | WeakMap<any, any>,
76
> = new Map();
77
const resourceConfigs: Map<Resource<any, any, any>, Config> = new Map();
78
79
function getEntriesForResource(
80
- resource: any
80
+ resource: any,
81
): Map<any, any> | WeakMap<any, any> {
82
let entriesForResource = ((entries.get(resource): any): Map<any, any>);
83
if (entriesForResource === undefined) {
@@ -93,7 +93,7 @@ function accessResult<Input, Key, Value>(
93
resource: any,
94
fetch: Input => Thenable<Value>,
95
input: Input,
96
- key: Key
96
+ key: Key,
97
): Result<Value> {
98
const entriesForResource = getEntriesForResource(resource);
99
const entry = entriesForResource.get(key);
@@ -113,7 +113,7 @@ function accessResult<Input, Key, Value>(
113
rejectedResult.status = Rejected;
114
rejectedResult.value = error;
115
}
116
- }
116
+ },
117
);
118
const newResult: PendingResult = {
119
status: Pending,
@@ -129,7 +129,7 @@ function accessResult<Input, Key, Value>(
129
export function createResource<Input, Key, Value>(
130
fetch: Input => Thenable<Value>,
131
hashInput: Input => Key,
132
- config?: Config = {}
132
+ config?: Config = {},
133
): Resource<Input, Key, Value> {
134
const resource = {
135
clear(): void {
packages/react-devtools-shared/src/devtools/index.js
+1
-1
@@ -1,6 +1,6 @@
1
// @flow
2
3
-import type { FrontendBridge } from 'react-devtools-shared/src/bridge';
3
+import type {FrontendBridge} from 'react-devtools-shared/src/bridge';
4
5
type Shell = {|
6
connect: (callback: Function) => void,
packages/react-devtools-shared/src/devtools/store.js
+43
-43
@@ -1,14 +1,14 @@
1
// @flow
2
3
import EventEmitter from 'node-events';
4
-import { inspect } from 'util';
4
+import {inspect} from 'util';
5
import {
6
TREE_OPERATION_ADD,
7
TREE_OPERATION_REMOVE,
8
TREE_OPERATION_REORDER_CHILDREN,
9
TREE_OPERATION_UPDATE_TREE_BASE_DURATION,
10
} from '../constants';
11
-import { ElementTypeRoot } from '../types';
11
+import {ElementTypeRoot} from '../types';
12
import {
13
getSavedComponentFilters,
14
saveComponentFilters,
@@ -16,14 +16,14 @@ import {
16
shallowDiffers,
17
utfDecodeString,
18
} from '../utils';
19
-import { localStorageGetItem, localStorageSetItem } from '../storage';
20
-import { __DEBUG__ } from '../constants';
21
-import { printStore } from './utils';
19
+import {localStorageGetItem, localStorageSetItem} from '../storage';
20
+import {__DEBUG__} from '../constants';
21
+import {printStore} from './utils';
22
import ProfilerStore from './ProfilerStore';
23
24
-import type { Element } from './views/Components/types';
25
-import type { ComponentFilter, ElementType } from '../types';
26
-import type { FrontendBridge } from 'react-devtools-shared/src/bridge';
24
+import type {Element} from './views/Components/types';
25
+import type {ComponentFilter, ElementType} from '../types';
26
+import type {FrontendBridge} from 'react-devtools-shared/src/bridge';
27
28
const debug = (methodName, ...args) => {
29
if (__DEBUG__) {
@@ -31,7 +31,7 @@ const debug = (methodName, ...args) => {
31
`%cStore %c${methodName}`,
32
'color: green; font-weight: bold;',
33
'font-weight: bold;',
34
- ...args
34
+ ...args,
35
);
36
}
37
};
@@ -161,16 +161,16 @@ export default class Store extends EventEmitter<{|
161
bridge.addListener('operations', this.onBridgeOperations);
162
bridge.addListener(
163
'overrideComponentFilters',
164
- this.onBridgeOverrideComponentFilters
164
+ this.onBridgeOverrideComponentFilters,
165
);
166
bridge.addListener('shutdown', this.onBridgeShutdown);
167
bridge.addListener(
168
'isBackendStorageAPISupported',
169
- this.onBridgeStorageSupported
169
+ this.onBridgeStorageSupported,
170
);
171
bridge.addListener(
172
'isNativeStyleEditorSupported',
173
- this.onBridgeNativeStyleEditorSupported
173
+ this.onBridgeNativeStyleEditorSupported,
174
);
175
176
this._profilerStore = new ProfilerStore(bridge, this, isProfiling);
@@ -187,11 +187,11 @@ export default class Store extends EventEmitter<{|
187
// These maps should always be the same size as the number of roots
188
this.assertMapSizeMatchesRootCount(
189
this._rootIDToCapabilities,
190
- '_rootIDToCapabilities'
190
+ '_rootIDToCapabilities',
191
);
192
this.assertMapSizeMatchesRootCount(
193
this._rootIDToRendererID,
194
- '_rootIDToRendererID'
194
+ '_rootIDToRendererID',
195
);
196
}
197
@@ -204,7 +204,7 @@ export default class Store extends EventEmitter<{|
204
map.size
205
} items\n\n${inspect(map, {
206
depth: 20,
207
- })}`
207
+ })}`,
208
);
209
}
210
}
@@ -217,7 +217,7 @@ export default class Store extends EventEmitter<{|
217
218
localStorageSetItem(
219
LOCAL_STORAGE_COLLAPSE_ROOTS_BY_DEFAULT_KEY,
220
- value ? 'true' : 'false'
220
+ value ? 'true' : 'false',
221
);
222
223
this.emit('collapseNodesByDefault');
@@ -236,10 +236,10 @@ export default class Store extends EventEmitter<{|
236
// Filter updates are expensive to apply (since they impact the entire tree).
237
// Let's determine if they've changed and avoid doing this work if they haven't.
238
const prevEnabledComponentFilters = this._componentFilters.filter(
239
- filter => filter.isEnabled
239
+ filter => filter.isEnabled,
240
);
241
const nextEnabledComponentFilters = value.filter(
242
- filter => filter.isEnabled
242
+ filter => filter.isEnabled,
243
);
244
let haveEnabledFiltersChanged =
245
prevEnabledComponentFilters.length !== nextEnabledComponentFilters.length;
@@ -293,7 +293,7 @@ export default class Store extends EventEmitter<{|
293
294
localStorageSetItem(
295
LOCAL_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY,
296
- value ? 'true' : 'false'
296
+ value ? 'true' : 'false',
297
);
298
299
this.emit('recordChangeDescriptions');
@@ -339,7 +339,7 @@ export default class Store extends EventEmitter<{|
339
console.warn(
340
`Invalid index ${index} specified; store contains ${
341
this.numElements
342
- } items.`
342
+ } items.`,
343
);
344
345
return null;
@@ -417,7 +417,7 @@ export default class Store extends EventEmitter<{|
417
while (true) {
418
const current = ((this._idToElement.get(currentID): any): Element);
419
420
- const { children } = current;
420
+ const {children} = current;
421
for (let i = 0; i < children.length; i++) {
422
const childID = children[i];
423
if (childID === previousID) {
@@ -474,7 +474,7 @@ export default class Store extends EventEmitter<{|
474
const sortedIDs = Array.from(unsortedIDs).sort(
475
(idA, idB) =>
476
((this.getIndexOfElementID(idA): any): number) -
477
- ((this.getIndexOfElementID(idB): any): number)
477
+ ((this.getIndexOfElementID(idB): any): number),
478
);
479
480
// Next we need to determine the appropriate depth for each element in the list.
@@ -506,7 +506,7 @@ export default class Store extends EventEmitter<{|
506
throw Error('Invalid owners list');
507
}
508
509
- list.push({ ...element, depth });
509
+ list.push({...element, depth});
510
}
511
});
512
}
@@ -573,7 +573,7 @@ export default class Store extends EventEmitter<{|
573
const weightDelta = 1 - element.weight;
574
575
let parentElement = ((this._idToElement.get(
576
- element.parentID
576
+ element.parentID,
577
): any): Element);
578
while (parentElement != null) {
579
// We don't need to break on a collapsed parent in the same way as the expand case below.
@@ -599,7 +599,7 @@ export default class Store extends EventEmitter<{|
599
const weightDelta = newWeight - oldWeight;
600
601
let parentElement = ((this._idToElement.get(
602
- currentElement.parentID
602
+ currentElement.parentID,
603
): any): Element);
604
while (parentElement != null) {
605
parentElement.weight += weightDelta;
@@ -624,7 +624,7 @@ export default class Store extends EventEmitter<{|
624
if (didMutate) {
625
let weightAcrossRoots = 0;
626
this._roots.forEach(rootID => {
627
- const { weight } = ((this.getElementByID(rootID): any): Element);
627
+ const {weight} = ((this.getElementByID(rootID): any): Element);
628
weightAcrossRoots += weight;
629
});
630
this._weightAcrossRoots = weightAcrossRoots;
@@ -639,7 +639,7 @@ export default class Store extends EventEmitter<{|
639
640
_adjustParentTreeWeight = (
641
parentElement: Element | null,
642
- weightDelta: number
642
+ weightDelta: number,
643
) => {
644
let isInsideCollapsedSubTree = false;
645
@@ -654,7 +654,7 @@ export default class Store extends EventEmitter<{|
654
}
655
656
parentElement = ((this._idToElement.get(
657
- parentElement.parentID
657
+ parentElement.parentID,
658
): any): Element);
659
}
660
@@ -704,7 +704,7 @@ export default class Store extends EventEmitter<{|
704
while (i < stringTableEnd) {
705
const nextLength = operations[i++];
706
const nextString = utfDecodeString(
707
- (operations.slice(i, i + nextLength): any)
707
+ (operations.slice(i, i + nextLength): any),
708
);
709
stringTable.push(nextString);
710
i += nextLength;
@@ -721,7 +721,7 @@ export default class Store extends EventEmitter<{|
721
722
if (this._idToElement.has(id)) {
723
throw Error(
724
- `Cannot add node ${id} because a node with that id is already in the Store.`
724
+ `Cannot add node ${id} because a node with that id is already in the Store.`,
725
);
726
}
727
@@ -778,18 +778,18 @@ export default class Store extends EventEmitter<{|
778
if (__DEBUG__) {
779
debug(
780
'Add',
781
- `node ${id} (${displayName || 'null'}) as child of ${parentID}`
781
+ `node ${id} (${displayName || 'null'}) as child of ${parentID}`,
782
);
783
}
784
785
if (!this._idToElement.has(parentID)) {
786
throw Error(
787
- `Cannot add child ${id} to parent ${parentID} because parent node was not found in the Store.`
787
+ `Cannot add child ${id} to parent ${parentID} because parent node was not found in the Store.`,
788
);
789
}
790
791
const parentElement = ((this._idToElement.get(
792
- parentID
792
+ parentID,
793
): any): Element);
794
parentElement.children.push(id);
795
@@ -836,14 +836,14 @@ export default class Store extends EventEmitter<{|
836
837
if (!this._idToElement.has(id)) {
838
throw Error(
839
- `Cannot remove node ${id} because no matching node was found in the Store.`
839
+ `Cannot remove node ${id} because no matching node was found in the Store.`,
840
);
841
}
842
843
i = i + 1;
844
845
const element = ((this._idToElement.get(id): any): Element);
846
- const { children, ownerID, parentID, weight } = element;
846
+ const {children, ownerID, parentID, weight} = element;
847
if (children.length > 0) {
848
throw new Error(`Node ${id} was removed before its children.`);
849
}
@@ -868,7 +868,7 @@ export default class Store extends EventEmitter<{|
868
parentElement = ((this._idToElement.get(parentID): any): Element);
869
if (parentElement === undefined) {
870
throw Error(
871
- `Cannot remove node ${id} from parent ${parentID} because no matching node was found in the Store.`
871
+ `Cannot remove node ${id} from parent ${parentID} because no matching node was found in the Store.`,
872
);
873
}
874
const index = parentElement.children.indexOf(id);
@@ -895,7 +895,7 @@ export default class Store extends EventEmitter<{|
895
896
if (!this._idToElement.has(id)) {
897
throw Error(
898
- `Cannot reorder children for node ${id} because no matching node was found in the Store.`
898
+ `Cannot reorder children for node ${id} because no matching node was found in the Store.`,
899
);
900
}
901
@@ -903,7 +903,7 @@ export default class Store extends EventEmitter<{|
903
const children = element.children;
904
if (children.length !== numChildren) {
905
throw Error(
906
- `Children cannot be added or removed during a reorder operation.`
906
+ `Children cannot be added or removed during a reorder operation.`,
907
);
908
}
909
@@ -915,7 +915,7 @@ export default class Store extends EventEmitter<{|
915
const childElement = this._idToElement.get(childID);
916
if (childElement == null || childElement.parentID !== id) {
917
console.error(
918
- `Children cannot be added or removed during a reorder operation.`
918
+ `Children cannot be added or removed during a reorder operation.`,
919
);
920
}
921
}
@@ -946,14 +946,14 @@ export default class Store extends EventEmitter<{|
946
this._hasOwnerMetadata = false;
947
this._supportsProfiling = false;
948
this._rootIDToCapabilities.forEach(
949
- ({ hasOwnerMetadata, supportsProfiling }) => {
949
+ ({hasOwnerMetadata, supportsProfiling}) => {
950
if (hasOwnerMetadata) {
951
this._hasOwnerMetadata = true;
952
}
953
if (supportsProfiling) {
954
this._supportsProfiling = true;
955
}
956
- }
956
+ },
957
);
958
959
this.emit('roots');
@@ -977,7 +977,7 @@ export default class Store extends EventEmitter<{|
977
// This action should also override the saved filters too,
978
// else reloading the frontend without reloading the backend would leave things out of sync.
979
onBridgeOverrideComponentFilters = (
980
- componentFilters: Array<ComponentFilter>
980
+ componentFilters: Array<ComponentFilter>,
981
) => {
982
this._componentFilters = componentFilters;
983
@@ -993,7 +993,7 @@ export default class Store extends EventEmitter<{|
993
this._bridge.removeListener('shutdown', this.onBridgeShutdown);
994
this._bridge.removeListener(
995
'isBackendStorageAPISupported',
996
- this.onBridgeStorageSupported
996
+ this.onBridgeStorageSupported,
997
);
998
};
999
packages/react-devtools-shared/src/devtools/utils.js
+8
-5
@@ -1,6 +1,6 @@
1
// @flow
2
3
-import type { Element } from './views/Components/types';
3
+import type {Element} from './views/Components/types';
4
import type Store from './store';
5
6
export function printElement(element: Element, includeWeight: boolean = false) {
@@ -28,7 +28,10 @@ export function printElement(element: Element, includeWeight: boolean = false) {
28
'null'}${key}>${hocs}${suffix}`;
29
}
30
31
-export function printOwnersList(elements: Array<Element>, includeWeight: boolean = false) {
31
+export function printOwnersList(
32
+ elements: Array<Element>,
33
+ includeWeight: boolean = false,
34
+) {
35
return elements
36
.map(element => printElement(element, includeWeight))
37
.join('\n');
@@ -40,7 +43,7 @@ export function printStore(store: Store, includeWeight: boolean = false) {
43
let rootWeight = 0;
44
45
store.roots.forEach(rootID => {
43
- const { weight } = ((store.getElementByID(rootID): any): Element);
46
+ const {weight} = ((store.getElementByID(rootID): any): Element);
47
48
snapshotLines.push('[root]' + (includeWeight ? ` (${weight})` : ''));
49
@@ -62,7 +65,7 @@ export function printStore(store: Store, includeWeight: boolean = false) {
65
throw Error(
66
`Inconsistent Store state. Individual root weights (${rootWeight}) do not match total weight (${
67
store.numElements
65
- })`
68
+ })`,
69
);
70
}
71
@@ -71,4 +74,4 @@ export function printStore(store: Store, includeWeight: boolean = false) {
74
store.assertExpectedRootMapSizes();
75
76
return snapshotLines.join('\n');
74
-}
\ No newline at end of file
77
+}
packages/react-devtools-shared/src/devtools/views/ButtonIcon.js
+2
-3
@@ -36,7 +36,7 @@ type Props = {|
36
type: IconType,
37
|};
38
39
-export default function ButtonIcon({ className = '', type }: Props) {
39
+export default function ButtonIcon({className = '', type}: Props) {
40
let pathData = null;
41
switch (type) {
42
case 'add':
@@ -128,8 +128,7 @@ export default function ButtonIcon({ className = '', type }: Props) {
128
className={`${styles.ButtonIcon} ${className}`}
129
width="24"
130
height="24"
131
- viewBox="0 0 24 24"
132
- >
131
+ viewBox="0 0 24 24">
132
<path d="M0 0h24v24H0z" fill="none" />
133
<path fill="currentColor" d={pathData} />
134
</svg>
packages/react-devtools-shared/src/devtools/views/Components/Badge.js
+7
-4
@@ -1,10 +1,13 @@
1
// @flow
2
3
-import React, { Fragment } from 'react';
4
-import { ElementTypeMemo, ElementTypeForwardRef } from 'react-devtools-shared/src/types';
3
+import React, {Fragment} from 'react';
4
+import {
5
+ ElementTypeMemo,
6
+ ElementTypeForwardRef,
7
+} from 'react-devtools-shared/src/types';
8
import styles from './Badge.css';
9
7
-import type { ElementType } from 'react-devtools-shared/src/types';
10
+import type {ElementType} from 'react-devtools-shared/src/types';
11
12
type Props = {|
13
className?: string,
@@ -12,7 +15,7 @@ type Props = {|
15
type: ElementType,
16
|};
17
15
-export default function Badge({ className, hocDisplayNames, type }: Props) {
18
+export default function Badge({className, hocDisplayNames, type}: Props) {
19
let hocDisplayName = null;
20
let totalBadgeCount = 0;
21
let typeLabel = null;
packages/react-devtools-shared/src/devtools/views/Components/Components.js
+6
-6
@@ -1,15 +1,15 @@
1
// @flow
2
3
-import React, { Suspense } from 'react';
3
+import React, {Suspense} from 'react';
4
import Tree from './Tree';
5
import SelectedElement from './SelectedElement';
6
-import { InspectedElementContextController } from './InspectedElementContext';
7
-import { NativeStyleContextController } from './NativeStyleEditor/context';
8
-import { OwnersListContextController } from './OwnersListContext';
6
+import {InspectedElementContextController} from './InspectedElementContext';
7
+import {NativeStyleContextController} from './NativeStyleEditor/context';
8
+import {OwnersListContextController} from './OwnersListContext';
9
import portaledContent from '../portaledContent';
10
-import { ModalDialog } from '../ModalDialog';
10
+import {ModalDialog} from '../ModalDialog';
11
import SettingsModal from 'react-devtools-shared/src/devtools/views/Settings/SettingsModal';
12
-import { SettingsModalContextController } from 'react-devtools-shared/src/devtools/views/Settings/SettingsModalContext';
12
+import {SettingsModalContextController} from 'react-devtools-shared/src/devtools/views/Settings/SettingsModalContext';
13
14
import styles from './Components.css';
15
packages/react-devtools-shared/src/devtools/views/Components/EditableValue.js
+24
-21
@@ -1,6 +1,6 @@
1
// @flow
2
3
-import React, { Fragment, useCallback, useRef, useState } from 'react';
3
+import React, {Fragment, useCallback, useRef, useState} from 'react';
4
import Button from '../Button';
5
import ButtonIcon from '../ButtonIcon';
6
import styles from './EditableValue.css';
@@ -29,7 +29,7 @@ export default function EditableValue({
29
}
30
31
const handleChange = useCallback(
32
- ({ target }) => {
32
+ ({target}) => {
33
if (dataType === 'boolean') {
34
setEditableValue(target.checked);
35
overrideValueFn(path, target.checked);
@@ -38,24 +38,27 @@ export default function EditableValue({
38
}
39
setHasPendingChanges(true);
40
},
41
- [dataType, overrideValueFn, path]
41
+ [dataType, overrideValueFn, path],
42
);
43
44
- const handleReset = useCallback(() => {
45
- setEditableValue(value);
46
- setHasPendingChanges(false);
44
+ const handleReset = useCallback(
45
+ () => {
46
+ setEditableValue(value);
47
+ setHasPendingChanges(false);
48
48
- if (inputRef.current !== null) {
49
- inputRef.current.focus();
50
- }
51
- }, [value]);
49
+ if (inputRef.current !== null) {
50
+ inputRef.current.focus();
51
+ }
52
+ },
53
+ [value],
54
+ );
55
56
const handleKeyDown = useCallback(
57
event => {
58
// Prevent keydown events from e.g. change selected element in the tree
59
event.stopPropagation();
60
58
- const { key } = event;
61
+ const {key} = event;
62
63
if (key === 'Enter') {
64
if (dataType === 'number') {
@@ -75,7 +78,7 @@ export default function EditableValue({
78
setHasPendingChanges(false);
79
}
80
},
78
- [editableValue, dataType, overrideValueFn, path, value]
81
+ [editableValue, dataType, overrideValueFn, path, value],
82
);
83
84
// Render different input types based on the dataType
@@ -125,15 +128,15 @@ export default function EditableValue({
128
value={inputValue}
129
/>
130
)}
128
- {hasPendingChanges && dataType !== 'boolean' && (
129
- <Button
130
- className={styles.ResetButton}
131
- onClick={handleReset}
132
- title="Reset value"
133
- >
134
- <ButtonIcon type="undo" />
135
- </Button>
136
- )}
131
+ {hasPendingChanges &&
132
+ dataType !== 'boolean' && (
133
+ <Button
134
+ className={styles.ResetButton}
135
+ onClick={handleReset}
136
+ title="Reset value">
137
+ <ButtonIcon type="undo" />
138
+ </Button>
139
+ )}
140
</Fragment>
141
);
142
}
packages/react-devtools-shared/src/devtools/views/Components/Element.js
+27
-31
@@ -1,15 +1,15 @@
1
// @flow
2
3
-import React, { Fragment, useContext, useMemo, useState } from 'react';
3
+import React, {Fragment, useContext, useMemo, useState} from 'react';
4
import Store from 'react-devtools-shared/src/devtools/store';
5
import Badge from './Badge';
6
import ButtonIcon from '../ButtonIcon';
7
-import { createRegExp } from '../utils';
8
-import { TreeDispatcherContext, TreeStateContext } from './TreeContext';
9
-import { StoreContext } from '../context';
7
+import {createRegExp} from '../utils';
8
+import {TreeDispatcherContext, TreeStateContext} from './TreeContext';
9
+import {StoreContext} from '../context';
10
11
-import type { ItemData } from './Tree';
12
-import type { Element } from './types';
11
+import type {ItemData} from './Tree';
12
+import type {Element} from './types';
13
14
import styles from './Element.css';
15
@@ -19,10 +19,10 @@ type Props = {
19
style: Object,
20
};
21
22
-export default function ElementView({ data, index, style }: Props) {
22
+export default function ElementView({data, index, style}: Props) {
23
const store = useContext(StoreContext);
24
- const { ownerFlatTree, ownerID, selectedElementID } = useContext(
25
- TreeStateContext
24
+ const {ownerFlatTree, ownerID, selectedElementID} = useContext(
25
+ TreeStateContext,
26
);
27
const dispatch = useContext(TreeDispatcherContext);
28
@@ -33,17 +33,17 @@ export default function ElementView({ data, index, style }: Props) {
33
34
const [isHovered, setIsHovered] = useState(false);
35
36
- const { isNavigatingWithKeyboard, onElementMouseEnter, treeFocused } = data;
36
+ const {isNavigatingWithKeyboard, onElementMouseEnter, treeFocused} = data;
37
const id = element === null ? null : element.id;
38
const isSelected = selectedElementID === id;
39
40
const handleDoubleClick = () => {
41
if (id !== null) {
42
- dispatch({ type: 'SELECT_OWNER', payload: id });
42
+ dispatch({type: 'SELECT_OWNER', payload: id});
43
}
44
};
45
46
- const handleMouseDown = ({ metaKey }) => {
46
+ const handleMouseDown = ({metaKey}) => {
47
if (id !== null) {
48
dispatch({
49
type: 'SELECT_ELEMENT_BY_ID',
@@ -103,8 +103,7 @@ export default function ElementView({ data, index, style }: Props) {
103
onMouseDown={handleMouseDown}
104
onDoubleClick={handleDoubleClick}
105
style={style}
106
- data-depth={depth}
107
- >
106
+ data-depth={depth}>
107
{/* This wrapper is used by Tree for measurement purposes. */}
108
<div
109
className={styles.Wrapper}
@@ -112,8 +111,7 @@ export default function ElementView({ data, index, style }: Props) {
111
// Left offset presents the appearance of a nested tree structure.
112
// We must use padding rather than margin/left because of the selected background color.
113
transform: `translateX(calc(${depth} * var(--indentation-size)))`,
115
- }}
116
- >
114
+ }}>
115
{ownerID === null ? (
116
<ExpandCollapseToggle element={element} store={store} />
117
) : null}
@@ -124,8 +122,7 @@ export default function ElementView({ data, index, style }: Props) {
122
<span
123
className={styles.KeyValue}
124
title={key}
127
- onDoubleClick={handleKeyDoubleClick}
128
- >
125
+ onDoubleClick={handleKeyDoubleClick}>
126
{key}
127
</span>
128
"
@@ -152,8 +149,8 @@ type ExpandCollapseToggleProps = {|
149
store: Store,
150
|};
151
155
-function ExpandCollapseToggle({ element, store }: ExpandCollapseToggleProps) {
156
- const { children, id, isCollapsed } = element;
152
+function ExpandCollapseToggle({element, store}: ExpandCollapseToggleProps) {
153
+ const {children, id, isCollapsed} = element;
154
155
const toggleCollapsed = event => {
156
event.preventDefault();
@@ -176,8 +173,7 @@ function ExpandCollapseToggle({ element, store }: ExpandCollapseToggleProps) {
173
className={styles.ExpandCollapseToggle}
174
onMouseDown={stopPropagation}
175
onClick={toggleCollapsed}
179
- onDoubleClick={swallowDoubleClick}
180
- >
176
+ onDoubleClick={swallowDoubleClick}>
177
<ButtonIcon type={isCollapsed ? 'collapsed' : 'expanded'} />
178
</div>
179
);
@@ -188,13 +184,14 @@ type DisplayNameProps = {|
184
id: number,
185
|};
186
191
-function DisplayName({ displayName, id }: DisplayNameProps) {
192
- const { searchIndex, searchResults, searchText } = useContext(
193
- TreeStateContext
187
+function DisplayName({displayName, id}: DisplayNameProps) {
188
+ const {searchIndex, searchResults, searchText} = useContext(TreeStateContext);
189
+ const isSearchResult = useMemo(
190
+ () => {
191
+ return searchResults.includes(id);
192
+ },
193
+ [id, searchResults],
194
);
195
- const isSearchResult = useMemo(() => {
196
- return searchResults.includes(id);
197
- }, [id, searchResults]);
195
const isCurrentResult =
196
searchIndex !== null && id === searchResults[searchIndex];
197
@@ -218,10 +215,9 @@ function DisplayName({ displayName, id }: DisplayNameProps) {
215
children.push(
216
<mark
217
key="middle"
221
- className={isCurrentResult ? styles.CurrentHighlight : styles.Highlight}
222
- >
218
+ className={isCurrentResult ? styles.CurrentHighlight : styles.Highlight}>
219
{displayName.slice(startIndex, stopIndex)}
224
- </mark>
220
+ </mark>,
221
);
222
if (stopIndex < displayName.length) {
223
children.push(<span key="end">{displayName.slice(stopIndex)}</span>);
packages/react-devtools-shared/src/devtools/views/Components/ExpandCollapseToggle.js
+1
-2
@@ -19,8 +19,7 @@ export default function ExpandCollapseToggle({
19
<Button
20
className={styles.ExpandCollapseToggle}
21
onClick={() => setIsOpen(prevIsOpen => !prevIsOpen)}
22
- title={`${isOpen ? 'Collapse' : 'Expand'} prop value`}
23
- >
22
+ title={`${isOpen ? 'Collapse' : 'Expand'} prop value`}>
23
<ButtonIcon type={isOpen ? 'expanded' : 'collapsed'} />
24
</Button>
25
);
packages/react-devtools-shared/src/devtools/views/Components/HocBadges.js
+7
-4
@@ -1,17 +1,20 @@
1
// @flow
2
3
import React from 'react';
4
-import { ElementTypeForwardRef, ElementTypeMemo } from 'react-devtools-shared/src/types';
4
+import {
5
+ ElementTypeForwardRef,
6
+ ElementTypeMemo,
7
+} from 'react-devtools-shared/src/types';
8
import styles from './HocBadges.css';
9
7
-import type { Element } from './types';
10
+import type {Element} from './types';
11
12
type Props = {|
13
element: Element,
14
|};
15
13
-export default function HocBadges({ element }: Props) {
14
- const { hocDisplayNames, type } = ((element: any): Element);
16
+export default function HocBadges({element}: Props) {
17
+ const {hocDisplayNames, type} = ((element: any): Element);
18
19
let typeBadge = null;
20
if (type === ElementTypeMemo) {
packages/react-devtools-shared/src/devtools/views/Components/HooksTree.js
+17
-26
@@ -1,20 +1,20 @@
1
// @flow
2
3
-import { copy } from 'clipboard-js';
4
-import React, { useCallback, useContext, useState } from 'react';
5
-import { BridgeContext, StoreContext } from '../context';
3
+import {copy} from 'clipboard-js';
4
+import React, {useCallback, useContext, useState} from 'react';
5
+import {BridgeContext, StoreContext} from '../context';
6
import Button from '../Button';
7
import ButtonIcon from '../ButtonIcon';
8
import EditableValue from './EditableValue';
9
import ExpandCollapseToggle from './ExpandCollapseToggle';
10
-import { InspectedElementContext } from './InspectedElementContext';
10
+import {InspectedElementContext} from './InspectedElementContext';
11
import KeyValue from './KeyValue';
12
-import { serializeHooksForCopy } from '../utils';
12
+import {serializeHooksForCopy} from '../utils';
13
import styles from './HooksTree.css';
14
-import { meta } from '../../../hydration';
14
+import {meta} from '../../../hydration';
15
16
-import type { InspectPath } from './SelectedElement';
17
-import type { HooksNode, HooksTree } from 'react-debug-tools/src/ReactDebugHooks';
16
+import type {InspectPath} from './SelectedElement';
17
+import type {HooksNode, HooksTree} from 'react-debug-tools/src/ReactDebugHooks';
18
19
type HooksTreeViewProps = {|
20
canEditHooks: boolean,
@@ -22,13 +22,13 @@ type HooksTreeViewProps = {|
22
id: number,
23
|};
24
25
-export function HooksTreeView({ canEditHooks, hooks, id }: HooksTreeViewProps) {
26
- const { getInspectedElementPath } = useContext(InspectedElementContext);
25
+export function HooksTreeView({canEditHooks, hooks, id}: HooksTreeViewProps) {
26
+ const {getInspectedElementPath} = useContext(InspectedElementContext);
27
const inspectPath = useCallback(
28
(path: Array<string | number>) => {
29
getInspectedElementPath(id, ['hooks', ...path]);
30
},
31
- [getInspectedElementPath, id]
31
+ [getInspectedElementPath, id],
32
);
33
const handleCopy = useCallback(() => copy(serializeHooksForCopy(hooks)), [
34
hooks,
@@ -93,14 +93,8 @@ type HookViewProps = {|
93
path: Array<string | number>,
94
|};
95
96
-function HookView({
97
- canEditHooks,
98
- hook,
99
- id,
100
- inspectPath,
101
- path,
102
-}: HookViewProps) {
103
- const { name, id: hookID, isStateEditable, subHooks, value } = hook;
96
+function HookView({canEditHooks, hook, id, inspectPath, path}: HookViewProps) {
97
+ const {name, id: hookID, isStateEditable, subHooks, value} = hook;
98
99
const bridge = useContext(BridgeContext);
100
const store = useContext(StoreContext);
@@ -109,7 +103,7 @@ function HookView({
103
104
const toggleIsOpen = useCallback(
105
() => setIsOpen(prevIsOpen => !prevIsOpen),
112
- []
106
+ [],
107
);
108
109
if (hook.hasOwnProperty(meta.inspected)) {
@@ -178,8 +172,7 @@ function HookView({
172
<ExpandCollapseToggle isOpen={isOpen} setIsOpen={setIsOpen} />
173
<span
174
onClick={toggleIsOpen}
181
- className={name !== '' ? styles.Name : styles.NameAnonymous}
182
- >
175
+ className={name !== '' ? styles.Name : styles.NameAnonymous}>
176
{name || 'Anonymous'}
177
</span>
178
</div>
@@ -202,8 +195,7 @@ function HookView({
195
<ExpandCollapseToggle isOpen={isOpen} setIsOpen={setIsOpen} />
196
<span
197
onClick={toggleIsOpen}
205
- className={name !== '' ? styles.Name : styles.NameAnonymous}
206
- >
198
+ className={name !== '' ? styles.Name : styles.NameAnonymous}>
199
{name || 'Anonymous'}
200
</span>{' '}
201
{/* $FlowFixMe */}
@@ -260,8 +252,7 @@ function HookView({
252
typeof overrideValueFn === 'function'
253
? styles.EditableName
254
: styles.Name
263
- }
264
- >
255
+ }>
256
{name}
257
</span>
258
{typeof overrideValueFn === 'function' ? (
packages/react-devtools-shared/src/devtools/views/Components/InspectHostNodesToggle.js
+13
-11
@@ -1,7 +1,7 @@
1
// @flow
2
3
-import React, { useCallback, useContext, useEffect, useState } from 'react';
4
-import { BridgeContext } from '../context';
3
+import React, {useCallback, useContext, useEffect, useState} from 'react';
4
+import {BridgeContext} from '../context';
5
import Toggle from '../Toggle';
6
import ButtonIcon from '../ButtonIcon';
7
@@ -19,22 +19,24 @@ export default function InspectHostNodesToggle() {
19
bridge.send('stopInspectingNative', false);
20
}
21
},
22
- [bridge]
22
+ [bridge],
23
);
24
25
- useEffect(() => {
26
- const onStopInspectingNative = () => setIsInspecting(false);
27
- bridge.addListener('stopInspectingNative', onStopInspectingNative);
28
- return () =>
29
- bridge.removeListener('stopInspectingNative', onStopInspectingNative);
30
- }, [bridge]);
25
+ useEffect(
26
+ () => {
27
+ const onStopInspectingNative = () => setIsInspecting(false);
28
+ bridge.addListener('stopInspectingNative', onStopInspectingNative);
29
+ return () =>
30
+ bridge.removeListener('stopInspectingNative', onStopInspectingNative);
31
+ },
32
+ [bridge],
33
+ );
34
35
return (
36
<Toggle
37
onChange={handleChange}
38
isChecked={isInspecting}
36
- title="Select an element in the page to inspect it"
37
- >
39
+ title="Select an element in the page to inspect it">
40
<ButtonIcon type="search" />
41
</Toggle>
42
);
packages/react-devtools-shared/src/devtools/views/Components/InspectedElementContext.js
+169
-162
@@ -8,12 +8,12 @@ import React, {
8
useMemo,
9
useState,
10
} from 'react';
11
-import { unstable_batchedUpdates as batchedUpdates } from 'react-dom';
12
-import { createResource } from '../../cache';
13
-import { BridgeContext, StoreContext } from '../context';
14
-import { hydrate, fillInPath } from 'react-devtools-shared/src/hydration';
15
-import { TreeStateContext } from './TreeContext';
16
-import { separateDisplayNameAndHOCs } from 'react-devtools-shared/src/utils';
11
+import {unstable_batchedUpdates as batchedUpdates} from 'react-dom';
12
+import {createResource} from '../../cache';
13
+import {BridgeContext, StoreContext} from '../context';
14
+import {hydrate, fillInPath} from 'react-devtools-shared/src/hydration';
15
+import {TreeStateContext} from './TreeContext';
16
+import {separateDisplayNameAndHOCs} from 'react-devtools-shared/src/utils';
17
18
import type {
19
InspectedElement as InspectedElementBackend,
@@ -24,14 +24,14 @@ import type {
24
Element,
25
InspectedElement as InspectedElementFrontend,
26
} from 'react-devtools-shared/src/devtools/views/Components/types';
27
-import type { Resource, Thenable } from '../../cache';
27
+import type {Resource, Thenable} from '../../cache';
28
29
export type GetInspectedElementPath = (
30
id: number,
31
- path: Array<string | number>
31
+ path: Array<string | number>,
32
) => void;
33
export type GetInspectedElement = (
34
- id: number
34
+ id: number,
35
) => InspectedElementFrontend | null;
36
37
type Context = {|
@@ -52,7 +52,7 @@ const inProgressRequests: WeakMap<Element, InProgressRequest> = new WeakMap();
52
const resource: Resource<
53
Element,
54
Element,
55
- InspectedElementFrontend
55
+ InspectedElementFrontend,
56
> = createResource(
57
(element: Element) => {
58
let request = inProgressRequests.get(element);
@@ -65,19 +65,19 @@ const resource: Resource<
65
resolveFn = resolve;
66
});
67
68
- inProgressRequests.set(element, { promise, resolveFn });
68
+ inProgressRequests.set(element, {promise, resolveFn});
69
70
return promise;
71
},
72
(element: Element) => element,
73
- { useWeakMap: true }
73
+ {useWeakMap: true},
74
);
75
76
type Props = {|
77
children: React$Node,
78
|};
79
80
-function InspectedElementContextController({ children }: Props) {
80
+function InspectedElementContextController({children}: Props) {
81
const bridge = useContext(BridgeContext);
82
const store = useContext(StoreContext);
83
@@ -86,10 +86,10 @@ function InspectedElementContextController({ children }: Props) {
86
(id: number, path: Array<string | number>) => {
87
const rendererID = store.getRendererIDForElement(id);
88
if (rendererID !== null) {
89
- bridge.send('inspectElement', { id, path, rendererID });
89
+ bridge.send('inspectElement', {id, path, rendererID});
90
}
91
},
92
- [bridge, store]
92
+ [bridge, store],
93
);
94
95
const getInspectedElement = useCallback<GetInspectedElement>(
@@ -101,13 +101,13 @@ function InspectedElementContextController({ children }: Props) {
101
return null;
102
}
103
},
104
- [store]
104
+ [store],
105
);
106
107
// It's very important that this context consumes selectedElementID and not inspectedElementID.
108
// Otherwise the effect that sends the "inspect" message across the bridge-
109
// would itself be blocked by the same render that suspends (waiting for the data).
110
- const { selectedElementID } = useContext(TreeStateContext);
110
+ const {selectedElementID} = useContext(TreeStateContext);
111
112
const [
113
currentlyInspectedElement,
@@ -115,166 +115,173 @@ function InspectedElementContextController({ children }: Props) {
115
] = useState<InspectedElementFrontend | null>(null);
116
117
// This effect handler invalidates the suspense cache and schedules rendering updates with React.
118
- useEffect(() => {
119
- const onInspectedElement = (data: InspectedElementPayload) => {
120
- const { id } = data;
121
-
122
- let element;
123
-
124
- switch (data.type) {
125
- case 'no-change':
126
- case 'not-found':
127
- // No-op
128
- break;
129
- case 'hydrated-path':
130
- // Merge new data into previous object and invalidate cache
131
- element = store.getElementByID(id);
132
- if (element !== null) {
133
- if (currentlyInspectedElement != null) {
134
- const value = hydrateHelper(data.value, data.path);
135
- const inspectedElement = { ...currentlyInspectedElement };
136
-
137
- fillInPath(inspectedElement, data.path, value);
138
-
139
- resource.write(element, inspectedElement);
140
-
141
- // Schedule update with React if the curently-selected element has been invalidated.
142
- if (id === selectedElementID) {
143
- setCurrentlyInspectedElement(inspectedElement);
144
- }
145
- }
146
- }
147
- break;
148
- case 'full-data':
149
- const {
150
- canEditFunctionProps,
151
- canEditHooks,
152
- canToggleSuspense,
153
- canViewSource,
154
- source,
155
- type,
156
- owners,
157
- context,
158
- hooks,
159
- props,
160
- state,
161
- } = ((data.value: any): InspectedElementBackend);
162
-
163
- const inspectedElement: InspectedElementFrontend = {
164
- canEditFunctionProps,
165
- canEditHooks,
166
- canToggleSuspense,
167
- canViewSource,
168
- id,
169
- source,
170
- type,
171
- owners:
172
- owners === null
173
- ? null
174
- : owners.map(owner => {
175
- const [
176
- displayName,
177
- hocDisplayNames,
178
- ] = separateDisplayNameAndHOCs(
179
- owner.displayName,
180
- owner.type
181
- );
182
- return {
183
- ...owner,
184
- displayName,
185
- hocDisplayNames,
186
- };
187
- }),
188
- context: hydrateHelper(context),
189
- hooks: hydrateHelper(hooks),
190
- props: hydrateHelper(props),
191
- state: hydrateHelper(state),
192
- };
193
-
194
- element = store.getElementByID(id);
195
- if (element !== null) {
196
- const request = inProgressRequests.get(element);
197
- if (request != null) {
198
- inProgressRequests.delete(element);
199
- batchedUpdates(() => {
200
- request.resolveFn(inspectedElement);
201
- setCurrentlyInspectedElement(inspectedElement);
202
- });
203
- } else {
204
- resource.write(element, inspectedElement);
205
-
206
- // Schedule update with React if the curently-selected element has been invalidated.
207
- if (id === selectedElementID) {
208
- setCurrentlyInspectedElement(inspectedElement);
209
- }
210
- }
211
- }
212
- break;
213
- default:
214
- break;
215
- }
216
- };
217
-
218
- bridge.addListener('inspectedElement', onInspectedElement);
219
- return () => bridge.removeListener('inspectedElement', onInspectedElement);
220
- }, [bridge, currentlyInspectedElement, selectedElementID, store]);
221
-
222
- // This effect handler polls for updates on the currently selected element.
223
- useEffect(() => {
224
- if (selectedElementID === null) {
225
- return () => {};
226
- }
118
+ useEffect(
119
+ () => {
120
+ const onInspectedElement = (data: InspectedElementPayload) => {
121
+ const {id} = data;
122
228
- const rendererID = store.getRendererIDForElement(selectedElementID);
123
+ let element;
124
230
- let timeoutID: TimeoutID | null = null;
125
+ switch (data.type) {
126
+ case 'no-change':
127
+ case 'not-found':
128
+ // No-op
129
+ break;
130
+ case 'hydrated-path':
131
+ // Merge new data into previous object and invalidate cache
132
+ element = store.getElementByID(id);
133
+ if (element !== null) {
134
+ if (currentlyInspectedElement != null) {
135
+ const value = hydrateHelper(data.value, data.path);
136
+ const inspectedElement = {...currentlyInspectedElement};
137
232
- const sendRequest = () => {
233
- timeoutID = null;
138
+ fillInPath(inspectedElement, data.path, value);
139
235
- if (rendererID !== null) {
236
- bridge.send('inspectElement', { id: selectedElementID, rendererID });
237
- }
238
- };
239
-
240
- // Send the initial inspection request.
241
- // We'll poll for an update in the response handler below.
242
- sendRequest();
140
+ resource.write(element, inspectedElement);
141
244
- const onInspectedElement = (data: InspectedElementPayload) => {
245
- // If this is the element we requested, wait a little bit and then ask for another update.
246
- if (data.id === selectedElementID) {
247
- switch (data.type) {
248
- case 'no-change':
142
+ // Schedule update with React if the curently-selected element has been invalidated.
143
+ if (id === selectedElementID) {
144
+ setCurrentlyInspectedElement(inspectedElement);
145
+ }
146
+ }
147
+ }
148
+ break;
149
case 'full-data':
250
- case 'hydrated-path':
251
- if (timeoutID !== null) {
252
- clearTimeout(timeoutID);
150
+ const {
151
+ canEditFunctionProps,
152
+ canEditHooks,
153
+ canToggleSuspense,
154
+ canViewSource,
155
+ source,
156
+ type,
157
+ owners,
158
+ context,
159
+ hooks,
160
+ props,
161
+ state,
162
+ } = ((data.value: any): InspectedElementBackend);
163
+
164
+ const inspectedElement: InspectedElementFrontend = {
165
+ canEditFunctionProps,
166
+ canEditHooks,
167
+ canToggleSuspense,
168
+ canViewSource,
169
+ id,
170
+ source,
171
+ type,
172
+ owners:
173
+ owners === null
174
+ ? null
175
+ : owners.map(owner => {
176
+ const [
177
+ displayName,
178
+ hocDisplayNames,
179
+ ] = separateDisplayNameAndHOCs(
180
+ owner.displayName,
181
+ owner.type,
182
+ );
183
+ return {
184
+ ...owner,
185
+ displayName,
186
+ hocDisplayNames,
187
+ };
188
+ }),
189
+ context: hydrateHelper(context),
190
+ hooks: hydrateHelper(hooks),
191
+ props: hydrateHelper(props),
192
+ state: hydrateHelper(state),
193
+ };
194
+
195
+ element = store.getElementByID(id);
196
+ if (element !== null) {
197
+ const request = inProgressRequests.get(element);
198
+ if (request != null) {
199
+ inProgressRequests.delete(element);
200
+ batchedUpdates(() => {
201
+ request.resolveFn(inspectedElement);
202
+ setCurrentlyInspectedElement(inspectedElement);
203
+ });
204
+ } else {
205
+ resource.write(element, inspectedElement);
206
+
207
+ // Schedule update with React if the curently-selected element has been invalidated.
208
+ if (id === selectedElementID) {
209
+ setCurrentlyInspectedElement(inspectedElement);
210
+ }
211
+ }
212
}
254
- timeoutID = setTimeout(sendRequest, 1000);
213
break;
214
default:
215
break;
216
}
217
+ };
218
+
219
+ bridge.addListener('inspectedElement', onInspectedElement);
220
+ return () =>
221
+ bridge.removeListener('inspectedElement', onInspectedElement);
222
+ },
223
+ [bridge, currentlyInspectedElement, selectedElementID, store],
224
+ );
225
+
226
+ // This effect handler polls for updates on the currently selected element.
227
+ useEffect(
228
+ () => {
229
+ if (selectedElementID === null) {
230
+ return () => {};
231
}
260
- };
232
262
- bridge.addListener('inspectedElement', onInspectedElement);
233
+ const rendererID = store.getRendererIDForElement(selectedElementID);
234
264
- return () => {
265
- bridge.removeListener('inspectedElement', onInspectedElement);
235
+ let timeoutID: TimeoutID | null = null;
236
267
- if (timeoutID !== null) {
268
- clearTimeout(timeoutID);
269
- }
270
- };
271
- }, [bridge, selectedElementID, store]);
237
+ const sendRequest = () => {
238
+ timeoutID = null;
239
+
240
+ if (rendererID !== null) {
241
+ bridge.send('inspectElement', {id: selectedElementID, rendererID});
242
+ }
243
+ };
244
+
245
+ // Send the initial inspection request.
246
+ // We'll poll for an update in the response handler below.
247
+ sendRequest();
248
+
249
+ const onInspectedElement = (data: InspectedElementPayload) => {
250
+ // If this is the element we requested, wait a little bit and then ask for another update.
251
+ if (data.id === selectedElementID) {
252
+ switch (data.type) {
253
+ case 'no-change':
254
+ case 'full-data':
255
+ case 'hydrated-path':
256
+ if (timeoutID !== null) {
257
+ clearTimeout(timeoutID);
258
+ }
259
+ timeoutID = setTimeout(sendRequest, 1000);
260
+ break;
261
+ default:
262
+ break;
263
+ }
264
+ }
265
+ };
266
+
267
+ bridge.addListener('inspectedElement', onInspectedElement);
268
+
269
+ return () => {
270
+ bridge.removeListener('inspectedElement', onInspectedElement);
271
+
272
+ if (timeoutID !== null) {
273
+ clearTimeout(timeoutID);
274
+ }
275
+ };
276
+ },
277
+ [bridge, selectedElementID, store],
278
+ );
279
280
const value = useMemo(
274
- () => ({ getInspectedElement, getInspectedElementPath }),
281
+ () => ({getInspectedElement, getInspectedElementPath}),
282
// InspectedElement is used to invalidate the cache and schedule an update with React.
283
// eslint-disable-next-line react-hooks/exhaustive-deps
277
- [currentlyInspectedElement, getInspectedElement, getInspectedElementPath]
284
+ [currentlyInspectedElement, getInspectedElement, getInspectedElementPath],
285
);
286
287
return (
@@ -286,13 +293,13 @@ function InspectedElementContextController({ children }: Props) {
293
294
function hydrateHelper(
295
dehydratedData: any | null,
289
- path?: Array<string | number>
296
+ path?: Array<string | number>,
297
): Object | null {
298
if (dehydratedData !== null) {
292
- let { cleaned, data } = dehydratedData;
299
+ let {cleaned, data} = dehydratedData;
300
301
if (path) {
295
- const { length } = path;
302
+ const {length} = path;
303
if (length > 0) {
304
// Hydration helper requires full paths, but inspection dehydrates with relative paths.
305
// In that event it's important that we adjust the "cleaned" paths to match.
@@ -306,4 +313,4 @@ function hydrateHelper(
313
}
314
}
315
309
-export { InspectedElementContext, InspectedElementContextController };
316
+export {InspectedElementContext, InspectedElementContextController};
packages/react-devtools-shared/src/devtools/views/Components/InspectedElementTree.js
+8
-7
@@ -1,14 +1,14 @@
1
// @flow
2
3
-import { copy } from 'clipboard-js';
4
-import React, { useCallback } from 'react';
3
+import {copy} from 'clipboard-js';
4
+import React, {useCallback} from 'react';
5
import Button from '../Button';
6
import ButtonIcon from '../ButtonIcon';
7
import KeyValue from './KeyValue';
8
-import { serializeDataForCopy } from '../utils';
8
+import {serializeDataForCopy} from '../utils';
9
import styles from './InspectedElementTree.css';
10
11
-import type { InspectPath } from './SelectedElement';
11
+import type {InspectPath} from './SelectedElement';
12
13
type OverrideValueFn = (path: Array<string | number>, value: any) => void;
14
@@ -29,9 +29,10 @@ export default function InspectedElementTree({
29
}: Props) {
30
const isEmpty = data === null || Object.keys(data).length === 0;
31
32
- const handleCopy = useCallback(() => copy(serializeDataForCopy(((data: any): Object))), [
33
- data,
34
- ]);
32
+ const handleCopy = useCallback(
33
+ () => copy(serializeDataForCopy(((data: any): Object))),
34
+ [data],
35
+ );
36
37
if (isEmpty && !showWhenEmpty) {
38
return null;
packages/react-devtools-shared/src/devtools/views/Components/KeyValue.js
+26
-28
@@ -1,14 +1,14 @@
1
// @flow
2
3
-import React, { useEffect, useRef, useState } from 'react';
4
-import type { Element } from 'react';
3
+import React, {useEffect, useRef, useState} from 'react';
4
+import type {Element} from 'react';
5
import EditableValue from './EditableValue';
6
import ExpandCollapseToggle from './ExpandCollapseToggle';
7
-import { getMetaValueLabel } from '../utils';
8
-import { meta } from '../../../hydration';
7
+import {getMetaValueLabel} from '../utils';
8
+import {meta} from '../../../hydration';
9
import styles from './KeyValue.css';
10
11
-import type { InspectPath } from './SelectedElement';
11
+import type {InspectPath} from './SelectedElement';
12
13
type OverrideValueFn = (path: Array<string | number>, value: any) => void;
14
@@ -40,17 +40,20 @@ export default function KeyValue({
40
value[meta.inspectable] &&
41
value[meta.size] !== 0;
42
43
- useEffect(() => {
44
- if (
45
- isInspectable &&
46
- isOpen &&
47
- !prevIsOpenRef.current &&
48
- typeof inspectPath === 'function'
49
- ) {
50
- inspectPath(path);
51
- }
52
- prevIsOpenRef.current = isOpen;
53
- }, [inspectPath, isInspectable, isOpen, path]);
43
+ useEffect(
44
+ () => {
45
+ if (
46
+ isInspectable &&
47
+ isOpen &&
48
+ !prevIsOpenRef.current &&
49
+ typeof inspectPath === 'function'
50
+ ) {
51
+ inspectPath(path);
52
+ }
53
+ prevIsOpenRef.current = isOpen;
54
+ },
55
+ [inspectPath, isInspectable, isOpen, path],
56
+ );
57
58
const toggleIsOpen = () => setIsOpen(prevIsOpen => !prevIsOpen);
59
@@ -107,8 +110,7 @@ export default function KeyValue({
110
)}
111
<span
112
className={styles.Name}
110
- onClick={isInspectable ? toggleIsOpen : undefined}
111
- >
113
+ onClick={isInspectable ? toggleIsOpen : undefined}>
114
{name}
115
</span>
116
<span className={styles.Value}>{getMetaValueLabel(value)}</span>
@@ -135,8 +137,7 @@ export default function KeyValue({
137
key={`${depth}-root`}
138
className={styles.Item}
139
hidden={hidden}
138
- style={style}
139
- >
140
+ style={style}>
141
{hasChildren ? (
142
<ExpandCollapseToggle isOpen={isOpen} setIsOpen={setIsOpen} />
143
) : (
@@ -144,12 +145,11 @@ export default function KeyValue({
145
)}
146
<span
147
className={styles.Name}
147
- onClick={hasChildren ? toggleIsOpen : undefined}
148
- >
148
+ onClick={hasChildren ? toggleIsOpen : undefined}>
149
{name}
150
</span>
151
<span>Array</span>
152
- </div>
152
+ </div>,
153
);
154
} else {
155
const hasChildren = Object.entries(value).length > 0;
@@ -171,8 +171,7 @@ export default function KeyValue({
171
key={`${depth}-root`}
172
className={styles.Item}
173
hidden={hidden}
174
- style={style}
175
- >
174
+ style={style}>
175
{hasChildren ? (
176
<ExpandCollapseToggle isOpen={isOpen} setIsOpen={setIsOpen} />
177
) : (
@@ -180,12 +179,11 @@ export default function KeyValue({
179
)}
180
<span
181
className={styles.Name}
183
- onClick={hasChildren ? toggleIsOpen : undefined}
184
- >
182
+ onClick={hasChildren ? toggleIsOpen : undefined}>
183
{name}
184
</span>
185
<span>Object</span>
188
- </div>
186
+ </div>,
187
);
188
}
189
}
packages/react-devtools-shared/src/devtools/views/Components/NativeStyleEditor/AutoSizeInput.js
+19
-16
@@ -1,6 +1,6 @@
1
// @flow
2
3
-import React, { Fragment, useLayoutEffect, useRef } from 'react';
3
+import React, {Fragment, useLayoutEffect, useRef} from 'react';
4
import styles from './AutoSizeInput.css';
5
6
type Props = {
@@ -58,24 +58,27 @@ export default function AutoSizeInput({
58
}, []);
59
60
// Resize input any time text changes
61
- useLayoutEffect(() => {
62
- if (hiddenDivRef.current === null) {
63
- return;
64
- }
61
+ useLayoutEffect(
62
+ () => {
63
+ if (hiddenDivRef.current === null) {
64
+ return;
65
+ }
66
66
- const scrollWidth = hiddenDivRef.current.getBoundingClientRect().width;
67
- if (!scrollWidth) {
68
- return;
69
- }
67
+ const scrollWidth = hiddenDivRef.current.getBoundingClientRect().width;
68
+ if (!scrollWidth) {
69
+ return;
70
+ }
71
71
- // Adding an extra pixel avoids a slight horizontal scroll when changing text selection/cursor.
72
- // Not sure why this is, but the old DevTools did a similar thing.
73
- const targetWidth = Math.ceil(scrollWidth) + 1;
72
+ // Adding an extra pixel avoids a slight horizontal scroll when changing text selection/cursor.
73
+ // Not sure why this is, but the old DevTools did a similar thing.
74
+ const targetWidth = Math.ceil(scrollWidth) + 1;
75
75
- if (inputRef.current !== null) {
76
- inputRef.current.style.width = `${targetWidth}px`;
77
- }
78
- }, [value]);
76
+ if (inputRef.current !== null) {
77
+ inputRef.current.style.width = `${targetWidth}px`;
78
+ }
79
+ },
80
+ [value],
81
+ );
82
83
const isEmpty = value === '' || value === '""';
84
packages/react-devtools-shared/src/devtools/views/Components/NativeStyleEditor/LayoutViewer.js
+3
-3
@@ -3,15 +3,15 @@
3
import React from 'react';
4
import styles from './LayoutViewer.css';
5
6
-import type { Layout } from './types';
6
+import type {Layout} from './types';
7
8
type Props = {|
9
id: number,
10
layout: Layout,
11
|};
12
13
-export default function LayoutViewer({ id, layout }: Props) {
14
- const { height, margin, padding, y, width, x } = layout;
13
+export default function LayoutViewer({id, layout}: Props) {
14
+ const {height, margin, padding, y, width, x} = layout;
15
16
return (
17
<div className={styles.LayoutViewer}>
packages/react-devtools-shared/src/devtools/views/Components/NativeStyleEditor/StyleEditor.js
+12
-13
@@ -1,16 +1,19 @@
1
// @flow
2
3
-import React, { useContext, useMemo, useRef, useState } from 'react';
4
-import { unstable_batchedUpdates as batchedUpdates } from 'react-dom';
5
-import { copy } from 'clipboard-js';
6
-import { BridgeContext, StoreContext } from 'react-devtools-shared/src/devtools/views/context';
3
+import React, {useContext, useMemo, useRef, useState} from 'react';
4
+import {unstable_batchedUpdates as batchedUpdates} from 'react-dom';
5
+import {copy} from 'clipboard-js';
6
+import {
7
+ BridgeContext,
8
+ StoreContext,
9
+} from 'react-devtools-shared/src/devtools/views/context';
10
import Button from '../../Button';
11
import ButtonIcon from '../../ButtonIcon';
9
-import { serializeDataForCopy } from '../../utils';
12
+import {serializeDataForCopy} from '../../utils';
13
import AutoSizeInput from './AutoSizeInput';
14
import styles from './StyleEditor.css';
15
13
-import type { Style } from './types';
16
+import type {Style} from './types';
17
18
type Props = {|
19
id: number,
@@ -20,7 +23,7 @@ type Props = {|
23
type ChangeAttributeFn = (oldName: string, newName: string, value: any) => void;
24
type ChangeValueFn = (name: string, value: any) => void;
25
23
-export default function StyleEditor({ id, style }: Props) {
26
+export default function StyleEditor({id, style}: Props) {
27
const bridge = useContext(BridgeContext);
28
const store = useContext(StoreContext);
29
@@ -90,11 +93,7 @@ type NewRowProps = {|
93
validAttributes: $ReadOnlyArray<string> | null,
94
|};
95
93
-function NewRow({
94
- changeAttribute,
95
- changeValue,
96
- validAttributes,
97
-}: NewRowProps) {
96
+function NewRow({changeAttribute, changeValue, validAttributes}: NewRowProps) {
97
const [key, setKey] = useState<number>(0);
98
const reset = () => setKey(key + 1);
99
@@ -103,7 +102,7 @@ function NewRow({
102
const changeAttributeWrapper = (
103
oldAttribute: string,
104
newAttribute: string,
106
- value: any
105
+ value: any,
106
) => {
107
// Ignore attribute changes until a value has been specified
108
newAttributeRef.current = newAttribute;
packages/react-devtools-shared/src/devtools/views/Components/NativeStyleEditor/context.js
+98
-86
@@ -8,15 +8,21 @@ import React, {
8
useMemo,
9
useState,
10
} from 'react';
11
-import { unstable_batchedUpdates as batchedUpdates } from 'react-dom';
12
-import { createResource } from 'react-devtools-shared/src/devtools/cache';
13
-import { BridgeContext, StoreContext } from 'react-devtools-shared/src/devtools/views/context';
14
-import { TreeStateContext } from '../TreeContext';
15
-
16
-import type { StyleAndLayout as StyleAndLayoutBackend } from 'react-devtools-shared/src/backend/NativeStyleEditor/types';
17
-import type { StyleAndLayout as StyleAndLayoutFrontend } from './types';
18
-import type { Element } from 'react-devtools-shared/src/devtools/views/Components/types';
19
-import type { Resource, Thenable } from 'react-devtools-shared/src/devtools/cache';
11
+import {unstable_batchedUpdates as batchedUpdates} from 'react-dom';
12
+import {createResource} from 'react-devtools-shared/src/devtools/cache';
13
+import {
14
+ BridgeContext,
15
+ StoreContext,
16
+} from 'react-devtools-shared/src/devtools/views/context';
17
+import {TreeStateContext} from '../TreeContext';
18
+
19
+import type {StyleAndLayout as StyleAndLayoutBackend} from 'react-devtools-shared/src/backend/NativeStyleEditor/types';
20
+import type {StyleAndLayout as StyleAndLayoutFrontend} from './types';
21
+import type {Element} from 'react-devtools-shared/src/devtools/views/Components/types';
22
+import type {
23
+ Resource,
24
+ Thenable,
25
+} from 'react-devtools-shared/src/devtools/cache';
26
27
export type GetStyleAndLayout = (id: number) => StyleAndLayoutFrontend | null;
28
@@ -37,7 +43,7 @@ const inProgressRequests: WeakMap<Element, InProgressRequest> = new WeakMap();
43
const resource: Resource<
44
Element,
45
Element,
40
- StyleAndLayoutFrontend
46
+ StyleAndLayoutFrontend,
47
> = createResource(
48
(element: Element) => {
49
let request = inProgressRequests.get(element);
@@ -50,19 +56,19 @@ const resource: Resource<
56
resolveFn = resolve;
57
});
58
53
- inProgressRequests.set(element, { promise, resolveFn });
59
+ inProgressRequests.set(element, {promise, resolveFn});
60
61
return promise;
62
},
63
(element: Element) => element,
58
- { useWeakMap: true }
64
+ {useWeakMap: true},
65
);
66
67
type Props = {|
68
children: React$Node,
69
|};
70
65
-function NativeStyleContextController({ children }: Props) {
71
+function NativeStyleContextController({children}: Props) {
72
const bridge = useContext(BridgeContext);
73
const store = useContext(StoreContext);
74
@@ -75,13 +81,13 @@ function NativeStyleContextController({ children }: Props) {
81
return null;
82
}
83
},
78
- [store]
84
+ [store],
85
);
86
87
// It's very important that this context consumes selectedElementID and not NativeStyleID.
88
// Otherwise the effect that sends the "inspect" message across the bridge-
89
// would itself be blocked by the same render that suspends (waiting for the data).
84
- const { selectedElementID } = useContext(TreeStateContext);
90
+ const {selectedElementID} = useContext(TreeStateContext);
91
92
const [
93
currentStyleAndLayout,
@@ -89,94 +95,100 @@ function NativeStyleContextController({ children }: Props) {
95
] = useState<StyleAndLayoutFrontend | null>(null);
96
97
// This effect handler invalidates the suspense cache and schedules rendering updates with React.
92
- useEffect(() => {
93
- const onStyleAndLayout = ({ id, layout, style }: StyleAndLayoutBackend) => {
94
- let element = store.getElementByID(id);
95
- if (element !== null) {
96
- const styleAndLayout: StyleAndLayoutFrontend = {
97
- layout,
98
- style,
99
- };
100
- const request = inProgressRequests.get(element);
101
- if (request != null) {
102
- inProgressRequests.delete(element);
103
- batchedUpdates(() => {
104
- request.resolveFn(styleAndLayout);
105
- setCurrentStyleAndLayout(styleAndLayout);
106
- });
107
- } else {
108
- resource.write(element, styleAndLayout);
109
-
110
- // Schedule update with React if the curently-selected element has been invalidated.
111
- if (id === selectedElementID) {
112
- setCurrentStyleAndLayout(styleAndLayout);
98
+ useEffect(
99
+ () => {
100
+ const onStyleAndLayout = ({id, layout, style}: StyleAndLayoutBackend) => {
101
+ let element = store.getElementByID(id);
102
+ if (element !== null) {
103
+ const styleAndLayout: StyleAndLayoutFrontend = {
104
+ layout,
105
+ style,
106
+ };
107
+ const request = inProgressRequests.get(element);
108
+ if (request != null) {
109
+ inProgressRequests.delete(element);
110
+ batchedUpdates(() => {
111
+ request.resolveFn(styleAndLayout);
112
+ setCurrentStyleAndLayout(styleAndLayout);
113
+ });
114
+ } else {
115
+ resource.write(element, styleAndLayout);
116
+
117
+ // Schedule update with React if the curently-selected element has been invalidated.
118
+ if (id === selectedElementID) {
119
+ setCurrentStyleAndLayout(styleAndLayout);
120
+ }
121
}
122
}
115
- }
116
- };
117
-
118
- bridge.addListener('NativeStyleEditor_styleAndLayout', onStyleAndLayout);
119
- return () =>
120
- bridge.removeListener(
121
- 'NativeStyleEditor_styleAndLayout',
122
- onStyleAndLayout
123
- );
124
- }, [bridge, currentStyleAndLayout, selectedElementID, store]);
123
+ };
124
+
125
+ bridge.addListener('NativeStyleEditor_styleAndLayout', onStyleAndLayout);
126
+ return () =>
127
+ bridge.removeListener(
128
+ 'NativeStyleEditor_styleAndLayout',
129
+ onStyleAndLayout,
130
+ );
131
+ },
132
+ [bridge, currentStyleAndLayout, selectedElementID, store],
133
+ );
134
135
// This effect handler polls for updates on the currently selected element.
127
- useEffect(() => {
128
- if (selectedElementID === null) {
129
- return () => {};
130
- }
136
+ useEffect(
137
+ () => {
138
+ if (selectedElementID === null) {
139
+ return () => {};
140
+ }
141
132
- const rendererID = store.getRendererIDForElement(selectedElementID);
142
+ const rendererID = store.getRendererIDForElement(selectedElementID);
143
134
- let timeoutID: TimeoutID | null = null;
144
+ let timeoutID: TimeoutID | null = null;
145
136
- const sendRequest = () => {
137
- timeoutID = null;
146
+ const sendRequest = () => {
147
+ timeoutID = null;
148
139
- if (rendererID !== null) {
140
- bridge.send('NativeStyleEditor_measure', {
141
- id: selectedElementID,
142
- rendererID,
143
- });
144
- }
145
- };
149
+ if (rendererID !== null) {
150
+ bridge.send('NativeStyleEditor_measure', {
151
+ id: selectedElementID,
152
+ rendererID,
153
+ });
154
+ }
155
+ };
156
147
- // Send the initial measurement request.
148
- // We'll poll for an update in the response handler below.
149
- sendRequest();
157
+ // Send the initial measurement request.
158
+ // We'll poll for an update in the response handler below.
159
+ sendRequest();
160
151
- const onStyleAndLayout = ({ id }: StyleAndLayoutBackend) => {
152
- // If this is the element we requested, wait a little bit and then ask for another update.
153
- if (id === selectedElementID) {
154
- if (timeoutID !== null) {
155
- clearTimeout(timeoutID);
161
+ const onStyleAndLayout = ({id}: StyleAndLayoutBackend) => {
162
+ // If this is the element we requested, wait a little bit and then ask for another update.
163
+ if (id === selectedElementID) {
164
+ if (timeoutID !== null) {
165
+ clearTimeout(timeoutID);
166
+ }
167
+ timeoutID = setTimeout(sendRequest, 1000);
168
}
157
- timeoutID = setTimeout(sendRequest, 1000);
158
- }
159
- };
169
+ };
170
161
- bridge.addListener('NativeStyleEditor_styleAndLayout', onStyleAndLayout);
171
+ bridge.addListener('NativeStyleEditor_styleAndLayout', onStyleAndLayout);
172
163
- return () => {
164
- bridge.removeListener(
165
- 'NativeStyleEditor_styleAndLayout',
166
- onStyleAndLayout
167
- );
173
+ return () => {
174
+ bridge.removeListener(
175
+ 'NativeStyleEditor_styleAndLayout',
176
+ onStyleAndLayout,
177
+ );
178
169
- if (timeoutID !== null) {
170
- clearTimeout(timeoutID);
171
- }
172
- };
173
- }, [bridge, selectedElementID, store]);
179
+ if (timeoutID !== null) {
180
+ clearTimeout(timeoutID);
181
+ }
182
+ };
183
+ },
184
+ [bridge, selectedElementID, store],
185
+ );
186
187
const value = useMemo(
176
- () => ({ getStyleAndLayout }),
188
+ () => ({getStyleAndLayout}),
189
// NativeStyle is used to invalidate the cache and schedule an update with React.
190
// eslint-disable-next-line react-hooks/exhaustive-deps
179
- [currentStyleAndLayout, getStyleAndLayout]
191
+ [currentStyleAndLayout, getStyleAndLayout],
192
);
193
194
return (
@@ -186,4 +198,4 @@ function NativeStyleContextController({ children }: Props) {
198
);
199
}
200
189
-export { NativeStyleContext, NativeStyleContextController };
201
+export {NativeStyleContext, NativeStyleContextController};
packages/react-devtools-shared/src/devtools/views/Components/NativeStyleEditor/index.js
+10
-12
@@ -1,13 +1,13 @@
1
// @flow
2
3
-import React, { Fragment, useContext, useMemo } from 'react';
3
+import React, {Fragment, useContext, useMemo} from 'react';
4
import Store from 'react-devtools-shared/src/devtools/store';
5
-import { StoreContext } from 'react-devtools-shared/src/devtools/views/context';
6
-import { useSubscription } from 'react-devtools-shared/src/devtools/views/hooks';
7
-import { NativeStyleContext } from './context';
5
+import {StoreContext} from 'react-devtools-shared/src/devtools/views/context';
6
+import {useSubscription} from 'react-devtools-shared/src/devtools/views/hooks';
7
+import {NativeStyleContext} from './context';
8
import LayoutViewer from './LayoutViewer';
9
import StyleEditor from './StyleEditor';
10
-import { TreeStateContext } from '../TreeContext';
10
+import {TreeStateContext} from '../TreeContext';
11
12
type Props = {||};
13
@@ -24,11 +24,9 @@ export default function NativeStyleEditorWrapper(_: Props) {
24
};
25
},
26
}),
27
- [store]
28
- );
29
- const supportsNativeStyleEditor = useSubscription<boolean>(
30
- subscription
27
+ [store],
28
);
29
+ const supportsNativeStyleEditor = useSubscription<boolean>(subscription);
30
31
if (!supportsNativeStyleEditor) {
32
return null;
@@ -38,9 +36,9 @@ export default function NativeStyleEditorWrapper(_: Props) {
36
}
37
38
function NativeStyleEditor(_: Props) {
41
- const { getStyleAndLayout } = useContext(NativeStyleContext);
39
+ const {getStyleAndLayout} = useContext(NativeStyleContext);
40
43
- const { inspectedElementID } = useContext(TreeStateContext);
41
+ const {inspectedElementID} = useContext(TreeStateContext);
42
if (inspectedElementID === null) {
43
return null;
44
}
@@ -50,7 +48,7 @@ function NativeStyleEditor(_: Props) {
48
return null;
49
}
50
53
- const { layout, style } = maybeStyleAndLayout;
51
+ const {layout, style} = maybeStyleAndLayout;
52
53
return (
54
<Fragment>
packages/react-devtools-shared/src/devtools/views/Components/OwnersListContext.js
+66
-59
@@ -1,19 +1,17 @@
1
// @flow
2
3
-import React, {
4
- createContext,
5
- useCallback,
6
- useContext,
7
- useEffect,
8
-} from 'react';
9
-import { createResource } from '../../cache';
10
-import { BridgeContext, StoreContext } from '../context';
11
-import { TreeStateContext } from './TreeContext';
12
-import { separateDisplayNameAndHOCs } from 'react-devtools-shared/src/utils';
13
-
14
-import type { OwnersList } from 'react-devtools-shared/src/backend/types';
15
-import type { Element, Owner } from 'react-devtools-shared/src/devtools/views/Components/types';
16
-import type { Resource, Thenable } from '../../cache';
3
+import React, {createContext, useCallback, useContext, useEffect} from 'react';
4
+import {createResource} from '../../cache';
5
+import {BridgeContext, StoreContext} from '../context';
6
+import {TreeStateContext} from './TreeContext';
7
+import {separateDisplayNameAndHOCs} from 'react-devtools-shared/src/utils';
8
+
9
+import type {OwnersList} from 'react-devtools-shared/src/backend/types';
10
+import type {
11
+ Element,
12
+ Owner,
13
+} from 'react-devtools-shared/src/devtools/views/Components/types';
14
+import type {Resource, Thenable} from '../../cache';
15
16
type Context = (id: number) => Array<Owner> | null;
17
@@ -39,22 +37,22 @@ const resource: Resource<Element, Element, Array<Owner>> = createResource(
37
resolveFn = resolve;
38
});
39
42
- inProgressRequests.set(element, { promise, resolveFn });
40
+ inProgressRequests.set(element, {promise, resolveFn});
41
42
return promise;
43
},
44
(element: Element) => element,
47
- { useWeakMap: true }
45
+ {useWeakMap: true},
46
);
47
48
type Props = {|
49
children: React$Node,
50
|};
51
54
-function OwnersListContextController({ children }: Props) {
52
+function OwnersListContextController({children}: Props) {
53
const bridge = useContext(BridgeContext);
54
const store = useContext(StoreContext);
57
- const { ownerID } = useContext(TreeStateContext);
55
+ const {ownerID} = useContext(TreeStateContext);
56
57
const read = useCallback(
58
(id: number) => {
@@ -65,54 +63,63 @@ function OwnersListContextController({ children }: Props) {
63
return null;
64
}
65
},
68
- [store]
66
+ [store],
67
);
68
71
- useEffect(() => {
72
- const onOwnersList = (ownersList: OwnersList) => {
73
- const id = ownersList.id;
74
-
75
- const element = store.getElementByID(id);
76
- if (element !== null) {
77
- const request = inProgressRequests.get(element);
78
- if (request != null) {
79
- inProgressRequests.delete(element);
80
-
81
- request.resolveFn(
82
- ownersList.owners === null
83
- ? null
84
- : ownersList.owners.map(owner => {
85
- const [
86
- displayNameWithoutHOCs,
87
- hocDisplayNames,
88
- ] = separateDisplayNameAndHOCs(owner.displayName, owner.type);
89
-
90
- return {
91
- ...owner,
92
- displayName: displayNameWithoutHOCs,
93
- hocDisplayNames,
94
- };
95
- })
96
- );
69
+ useEffect(
70
+ () => {
71
+ const onOwnersList = (ownersList: OwnersList) => {
72
+ const id = ownersList.id;
73
+
74
+ const element = store.getElementByID(id);
75
+ if (element !== null) {
76
+ const request = inProgressRequests.get(element);
77
+ if (request != null) {
78
+ inProgressRequests.delete(element);
79
+
80
+ request.resolveFn(
81
+ ownersList.owners === null
82
+ ? null
83
+ : ownersList.owners.map(owner => {
84
+ const [
85
+ displayNameWithoutHOCs,
86
+ hocDisplayNames,
87
+ ] = separateDisplayNameAndHOCs(
88
+ owner.displayName,
89
+ owner.type,
90
+ );
91
+
92
+ return {
93
+ ...owner,
94
+ displayName: displayNameWithoutHOCs,
95
+ hocDisplayNames,
96
+ };
97
+ }),
98
+ );
99
+ }
100
}
98
- }
99
- };
101
+ };
102
101
- bridge.addListener('ownersList', onOwnersList);
102
- return () => bridge.removeListener('ownersList', onOwnersList);
103
- }, [bridge, store]);
103
+ bridge.addListener('ownersList', onOwnersList);
104
+ return () => bridge.removeListener('ownersList', onOwnersList);
105
+ },
106
+ [bridge, store],
107
+ );
108
109
// This effect requests an updated owners list any time the selected owner changes
106
- useEffect(() => {
107
- if (ownerID !== null) {
108
- const rendererID = store.getRendererIDForElement(ownerID);
109
- if (rendererID !== null) {
110
- bridge.send('getOwnersList', { id: ownerID, rendererID });
110
+ useEffect(
111
+ () => {
112
+ if (ownerID !== null) {
113
+ const rendererID = store.getRendererIDForElement(ownerID);
114
+ if (rendererID !== null) {
115
+ bridge.send('getOwnersList', {id: ownerID, rendererID});
116
+ }
117
}
112
- }
118
114
- return () => {};
115
- }, [bridge, ownerID, store]);
119
+ return () => {};
120
+ },
121
+ [bridge, ownerID, store],
122
+ );
123
124
return (
125
<OwnersListContext.Provider value={read}>
@@ -121,4 +128,4 @@ function OwnersListContextController({ children }: Props) {
128
);
129
}
130
124
-export { OwnersListContext, OwnersListContextController };
131
+export {OwnersListContext, OwnersListContextController};
packages/react-devtools-shared/src/devtools/views/Components/OwnersStack.js
+48
-46
@@ -9,17 +9,17 @@ import React, {
9
useState,
10
} from 'react';
11
import Tooltip from '@reach/tooltip';
12
-import { Menu, MenuList, MenuButton, MenuItem } from '@reach/menu-button';
12
+import {Menu, MenuList, MenuButton, MenuItem} from '@reach/menu-button';
13
import Button from '../Button';
14
import ButtonIcon from '../ButtonIcon';
15
import Toggle from '../Toggle';
16
import Badge from './Badge';
17
-import { OwnersListContext } from './OwnersListContext';
18
-import { TreeDispatcherContext, TreeStateContext } from './TreeContext';
19
-import { useIsOverflowing } from '../hooks';
20
-import { StoreContext } from '../context';
17
+import {OwnersListContext} from './OwnersListContext';
18
+import {TreeDispatcherContext, TreeStateContext} from './TreeContext';
19
+import {useIsOverflowing} from '../hooks';
20
+import {StoreContext} from '../context';
21
22
-import type { Owner } from './types';
22
+import type {Owner} from './types';
23
24
import styles from './OwnersStack.css';
25
@@ -47,7 +47,7 @@ function dialogReducer(state, action) {
47
switch (action.type) {
48
case 'UPDATE_OWNER_ID':
49
const selectedIndex = action.owners.findIndex(
50
- owner => owner.id === action.ownerID
50
+ owner => owner.id === action.ownerID,
51
);
52
return {
53
ownerID: action.ownerID,
@@ -66,7 +66,7 @@ function dialogReducer(state, action) {
66
67
export default function OwnerStack() {
68
const read = useContext(OwnersListContext);
69
- const { ownerID } = useContext(TreeStateContext);
69
+ const {ownerID} = useContext(TreeStateContext);
70
const treeDispatch = useContext(TreeDispatcherContext);
71
72
const [state, dispatch] = useReducer<State, Action>(dialogReducer, {
@@ -93,7 +93,7 @@ export default function OwnerStack() {
93
});
94
}
95
96
- const { owners, selectedIndex } = state;
96
+ const {owners, selectedIndex} = state;
97
98
const selectOwner = useCallback<SelectOwner>(
99
(owner: Owner | null) => {
@@ -103,16 +103,16 @@ export default function OwnerStack() {
103
type: 'UPDATE_SELECTED_INDEX',
104
selectedIndex: index >= 0 ? index : 0,
105
});
106
- treeDispatch({ type: 'SELECT_OWNER', payload: owner.id });
106
+ treeDispatch({type: 'SELECT_OWNER', payload: owner.id});
107
} else {
108
dispatch({
109
type: 'UPDATE_SELECTED_INDEX',
110
selectedIndex: 0,
111
});
112
- treeDispatch({ type: 'RESET_OWNER_STACK' });
112
+ treeDispatch({type: 'RESET_OWNER_STACK'});
113
}
114
},
115
- [owners, treeDispatch]
115
+ [owners, treeDispatch],
116
);
117
118
const [elementsTotalWidth, setElementsTotalWidth] = useState(0);
@@ -121,27 +121,30 @@ export default function OwnerStack() {
121
122
const selectedOwner = owners[selectedIndex];
123
124
- useLayoutEffect(() => {
125
- // If we're already overflowing, then we don't need to re-measure items.
126
- // That's because once the owners stack is open, it can only get larger (by driling in).
127
- // A totally new stack can only be reached by exiting this mode and re-entering it.
128
- if (elementsBarRef.current === null || isOverflowing) {
129
- return () => {};
130
- }
124
+ useLayoutEffect(
125
+ () => {
126
+ // If we're already overflowing, then we don't need to re-measure items.
127
+ // That's because once the owners stack is open, it can only get larger (by driling in).
128
+ // A totally new stack can only be reached by exiting this mode and re-entering it.
129
+ if (elementsBarRef.current === null || isOverflowing) {
130
+ return () => {};
131
+ }
132
132
- let elementsTotalWidth = 0;
133
- for (let i = 0; i < owners.length; i++) {
134
- const element = elementsBarRef.current.children[i];
135
- const computedStyle = getComputedStyle(element);
133
+ let elementsTotalWidth = 0;
134
+ for (let i = 0; i < owners.length; i++) {
135
+ const element = elementsBarRef.current.children[i];
136
+ const computedStyle = getComputedStyle(element);
137
137
- elementsTotalWidth +=
138
- element.offsetWidth +
139
- parseInt(computedStyle.marginLeft, 10) +
140
- parseInt(computedStyle.marginRight, 10);
141
- }
138
+ elementsTotalWidth +=
139
+ element.offsetWidth +
140
+ parseInt(computedStyle.marginLeft, 10) +
141
+ parseInt(computedStyle.marginRight, 10);
142
+ }
143
143
- setElementsTotalWidth(elementsTotalWidth);
144
- }, [elementsBarRef, isOverflowing, owners.length]);
144
+ setElementsTotalWidth(elementsTotalWidth);
145
+ },
146
+ [elementsBarRef, isOverflowing, owners.length],
147
+ );
148
149
return (
150
<div className={styles.OwnerStack}>
@@ -181,8 +184,7 @@ export default function OwnerStack() {
184
<Button
185
className={styles.IconButton}
186
onClick={() => selectOwner(null)}
184
- title="Back to tree view"
185
- >
187
+ title="Back to tree view">
188
<ButtonIcon type="close" />
189
</Button>
190
</div>
@@ -209,8 +211,7 @@ function ElementsDropdown({
211
<MenuItem
212
key={owner.id}
213
className={`${styles.Component} ${isInStore ? '' : styles.NotInStore}`}
212
- onSelect={() => (isInStore ? selectOwner(owner) : null)}
213
- >
214
+ onSelect={() => (isInStore ? selectOwner(owner) : null)}>
215
{owner.displayName}
216
217
<Badge
@@ -218,7 +219,7 @@ function ElementsDropdown({
219
hocDisplayNames={owner.hocDisplayNames}
220
type={owner.type}
221
/>
221
- </MenuItem>
222
+ </MenuItem>,
223
);
224
}
225
@@ -241,24 +242,26 @@ type ElementViewProps = {
242
owner: Owner,
243
selectOwner: SelectOwner,
244
};
244
-function ElementView({ isSelected, owner, selectOwner }: ElementViewProps) {
245
+function ElementView({isSelected, owner, selectOwner}: ElementViewProps) {
246
const store = useContext(StoreContext);
247
247
- const { displayName, hocDisplayNames, type } = owner;
248
+ const {displayName, hocDisplayNames, type} = owner;
249
const isInStore = store.containsElement(owner.id);
250
250
- const handleChange = useCallback(() => {
251
- if (isInStore) {
252
- selectOwner(owner);
253
- }
254
- }, [isInStore, selectOwner, owner]);
251
+ const handleChange = useCallback(
252
+ () => {
253
+ if (isInStore) {
254
+ selectOwner(owner);
255
+ }
256
+ },
257
+ [isInStore, selectOwner, owner],
258
+ );
259
260
return (
261
<Toggle
262
className={`${styles.Component} ${isInStore ? '' : styles.NotInStore}`}
263
isChecked={isSelected}
260
- onChange={handleChange}
261
- >
264
+ onChange={handleChange}>
265
{displayName}
266
267
<Badge
@@ -296,8 +299,7 @@ function BackToOwnerButton({
299
<Button
300
className={isInStore ? undefined : styles.NotInStore}
301
onClick={() => (isInStore ? selectOwner(owner) : null)}
299
- title={`Up to ${owner.displayName || 'owner'}`}
300
- >
302
+ title={`Up to ${owner.displayName || 'owner'}`}>
303
<ButtonIcon type="previous" />
304
</Button>
305
);
packages/react-devtools-shared/src/devtools/views/Components/SearchInput.js
+43
-44
@@ -1,7 +1,7 @@
1
// @flow
2
3
-import React, { useCallback, useContext, useEffect, useRef } from 'react';
4
-import { TreeDispatcherContext, TreeStateContext } from './TreeContext';
3
+import React, {useCallback, useContext, useEffect, useRef} from 'react';
4
+import {TreeDispatcherContext, TreeStateContext} from './TreeContext';
5
import Button from '../Button';
6
import ButtonIcon from '../ButtonIcon';
7
import Icon from '../Icon';
@@ -11,21 +11,19 @@ import styles from './SearchInput.css';
11
type Props = {||};
12
13
export default function SearchInput(props: Props) {
14
- const { searchIndex, searchResults, searchText } = useContext(
15
- TreeStateContext
16
- );
14
+ const {searchIndex, searchResults, searchText} = useContext(TreeStateContext);
15
const dispatch = useContext(TreeDispatcherContext);
16
17
const inputRef = useRef<HTMLInputElement | null>(null);
18
19
const handleTextChange = useCallback(
22
- ({ currentTarget }) =>
23
- dispatch({ type: 'SET_SEARCH_TEXT', payload: currentTarget.value }),
24
- [dispatch]
20
+ ({currentTarget}) =>
21
+ dispatch({type: 'SET_SEARCH_TEXT', payload: currentTarget.value}),
22
+ [dispatch],
23
);
24
const resetSearch = useCallback(
27
- () => dispatch({ type: 'SET_SEARCH_TEXT', payload: '' }),
28
- [dispatch]
25
+ () => dispatch({type: 'SET_SEARCH_TEXT', payload: ''}),
26
+ [dispatch],
27
);
28
29
const handleKeyDown = useCallback(
@@ -33,54 +31,58 @@ export default function SearchInput(props: Props) {
31
// For convenience, let up/down arrow keys change Tree selection.
32
switch (event.key) {
33
case 'ArrowDown':
36
- dispatch({ type: 'SELECT_NEXT_ELEMENT_IN_TREE' });
34
+ dispatch({type: 'SELECT_NEXT_ELEMENT_IN_TREE'});
35
event.preventDefault();
36
break;
37
case 'ArrowUp':
40
- dispatch({ type: 'SELECT_PREVIOUS_ELEMENT_IN_TREE' });
38
+ dispatch({type: 'SELECT_PREVIOUS_ELEMENT_IN_TREE'});
39
event.preventDefault();
40
break;
41
default:
42
break;
43
}
44
},
47
- [dispatch]
45
+ [dispatch],
46
);
47
48
const handleInputKeyPress = useCallback(
51
- ({ key }) => {
49
+ ({key}) => {
50
if (key === 'Enter') {
53
- dispatch({ type: 'GO_TO_NEXT_SEARCH_RESULT' });
51
+ dispatch({type: 'GO_TO_NEXT_SEARCH_RESULT'});
52
}
53
},
56
- [dispatch]
54
+ [dispatch],
55
);
56
57
// Auto-focus search input
60
- useEffect(() => {
61
- if (inputRef.current === null) {
62
- return () => {};
63
- }
58
+ useEffect(
59
+ () => {
60
+ if (inputRef.current === null) {
61
+ return () => {};
62
+ }
63
65
- const handleWindowKey = (event: KeyboardEvent) => {
66
- const { key, metaKey } = event;
67
- if (key === 'f' && metaKey) {
68
- if (inputRef.current !== null) {
69
- inputRef.current.focus();
70
- event.preventDefault();
71
- event.stopPropagation();
64
+ const handleWindowKey = (event: KeyboardEvent) => {
65
+ const {key, metaKey} = event;
66
+ if (key === 'f' && metaKey) {
67
+ if (inputRef.current !== null) {
68
+ inputRef.current.focus();
69
+ event.preventDefault();
70
+ event.stopPropagation();
71
+ }
72
}
73
- }
74
- };
73
+ };
74
76
- // It's important to listen to the ownerDocument to support the browser extension.
77
- // Here we use portals to render individual tabs (e.g. Profiler),
78
- // and the root document might belong to a different window.
79
- const ownerDocument = inputRef.current.ownerDocument;
80
- ownerDocument.addEventListener('keydown', handleWindowKey);
75
+ // It's important to listen to the ownerDocument to support the browser extension.
76
+ // Here we use portals to render individual tabs (e.g. Profiler),
77
+ // and the root document might belong to a different window.
78
+ const ownerDocument = inputRef.current.ownerDocument;
79
+ ownerDocument.addEventListener('keydown', handleWindowKey);
80
82
- return () => ownerDocument.removeEventListener('keydown', handleWindowKey);
83
- }, [inputRef]);
81
+ return () =>
82
+ ownerDocument.removeEventListener('keydown', handleWindowKey);
83
+ },
84
+ [inputRef],
85
+ );
86
87
return (
88
<div className={styles.SearchInput}>
@@ -104,25 +106,22 @@ export default function SearchInput(props: Props) {
106
<Button
107
className={styles.IconButton}
108
disabled={!searchText}
107
- onClick={() => dispatch({ type: 'GO_TO_PREVIOUS_SEARCH_RESULT' })}
108
- title="Scroll to previous search result"
109
- >
109
+ onClick={() => dispatch({type: 'GO_TO_PREVIOUS_SEARCH_RESULT'})}
110
+ title="Scroll to previous search result">
111
<ButtonIcon type="up" />
112
</Button>
113
<Button
114
className={styles.IconButton}
115
disabled={!searchText}
115
- onClick={() => dispatch({ type: 'GO_TO_NEXT_SEARCH_RESULT' })}
116
- title="Scroll to next search result"
117
- >
116
+ onClick={() => dispatch({type: 'GO_TO_NEXT_SEARCH_RESULT'})}
117
+ title="Scroll to next search result">
118
<ButtonIcon type="down" />
119
</Button>
120
<Button
121
className={styles.IconButton}
122
disabled={!searchText}
123
onClick={resetSearch}
124
- title="Reset search"
125
- >
124
+ title="Reset search">
125
<ButtonIcon type="close" />
126
</Button>
127
</div>
packages/react-devtools-shared/src/devtools/views/Components/SelectedElement.js
+137
-130
@@ -1,15 +1,15 @@
1
// @flow
2
3
-import React, { useCallback, useContext } from 'react';
4
-import { TreeDispatcherContext, TreeStateContext } from './TreeContext';
5
-import { BridgeContext, StoreContext } from '../context';
3
+import React, {useCallback, useContext} from 'react';
4
+import {TreeDispatcherContext, TreeStateContext} from './TreeContext';
5
+import {BridgeContext, StoreContext} from '../context';
6
import Button from '../Button';
7
import ButtonIcon from '../ButtonIcon';
8
import HooksTree from './HooksTree';
9
-import { ModalDialogContext } from '../ModalDialog';
9
+import {ModalDialogContext} from '../ModalDialog';
10
import HocBadges from './HocBadges';
11
import InspectedElementTree from './InspectedElementTree';
12
-import { InspectedElementContext } from './InspectedElementContext';
12
+import {InspectedElementContext} from './InspectedElementContext';
13
import ViewElementSourceContext from './ViewElementSourceContext';
14
import NativeStyleEditor from './NativeStyleEditor';
15
import Toggle from '../Toggle';
@@ -25,25 +25,24 @@ import {
25
26
import styles from './SelectedElement.css';
27
28
-import type { GetInspectedElementPath } from './InspectedElementContext';
29
-import type { Element, InspectedElement } from './types';
30
-import type { ElementType } from 'react-devtools-shared/src/types';
28
+import type {GetInspectedElementPath} from './InspectedElementContext';
29
+import type {Element, InspectedElement} from './types';
30
+import type {ElementType} from 'react-devtools-shared/src/types';
31
32
export type Props = {||};
33
34
export default function SelectedElement(_: Props) {
35
- const { inspectedElementID } = useContext(TreeStateContext);
35
+ const {inspectedElementID} = useContext(TreeStateContext);
36
const dispatch = useContext(TreeDispatcherContext);
37
- const {
38
- canViewElementSourceFunction,
39
- viewElementSourceFunction,
40
- } = useContext(ViewElementSourceContext);
37
+ const {canViewElementSourceFunction, viewElementSourceFunction} = useContext(
38
+ ViewElementSourceContext,
39
+ );
40
const bridge = useContext(BridgeContext);
41
const store = useContext(StoreContext);
43
- const { dispatch: modalDialogDispatch } = useContext(ModalDialogContext);
42
+ const {dispatch: modalDialogDispatch} = useContext(ModalDialogContext);
43
45
- const { getInspectedElementPath, getInspectedElement } = useContext(
46
- InspectedElementContext
44
+ const {getInspectedElementPath, getInspectedElement} = useContext(
45
+ InspectedElementContext,
46
);
47
48
const element =
@@ -54,42 +53,51 @@ export default function SelectedElement(_: Props) {
53
const inspectedElement =
54
inspectedElementID != null ? getInspectedElement(inspectedElementID) : null;
55
57
- const highlightElement = useCallback(() => {
58
- if (element !== null && inspectedElementID !== null) {
59
- const rendererID = store.getRendererIDForElement(inspectedElementID);
60
- if (rendererID !== null) {
61
- bridge.send('highlightNativeElement', {
62
- displayName: element.displayName,
63
- hideAfterTimeout: true,
64
- id: inspectedElementID,
65
- openNativeElementsPanel: true,
66
- rendererID,
67
- scrollIntoView: true,
68
- });
56
+ const highlightElement = useCallback(
57
+ () => {
58
+ if (element !== null && inspectedElementID !== null) {
59
+ const rendererID = store.getRendererIDForElement(inspectedElementID);
60
+ if (rendererID !== null) {
61
+ bridge.send('highlightNativeElement', {
62
+ displayName: element.displayName,
63
+ hideAfterTimeout: true,
64
+ id: inspectedElementID,
65
+ openNativeElementsPanel: true,
66
+ rendererID,
67
+ scrollIntoView: true,
68
+ });
69
+ }
70
}
70
- }
71
- }, [bridge, element, inspectedElementID, store]);
71
+ },
72
+ [bridge, element, inspectedElementID, store],
73
+ );
74
73
- const logElement = useCallback(() => {
74
- if (inspectedElementID !== null) {
75
- const rendererID = store.getRendererIDForElement(inspectedElementID);
76
- if (rendererID !== null) {
77
- bridge.send('logElementToConsole', {
78
- id: inspectedElementID,
79
- rendererID,
80
- });
75
+ const logElement = useCallback(
76
+ () => {
77
+ if (inspectedElementID !== null) {
78
+ const rendererID = store.getRendererIDForElement(inspectedElementID);
79
+ if (rendererID !== null) {
80
+ bridge.send('logElementToConsole', {
81
+ id: inspectedElementID,
82
+ rendererID,
83
+ });
84
+ }
85
}
82
- }
83
- }, [bridge, inspectedElementID, store]);
84
-
85
- const viewSource = useCallback(() => {
86
- if (viewElementSourceFunction != null && inspectedElement !== null) {
87
- viewElementSourceFunction(
88
- inspectedElement.id,
89
- ((inspectedElement: any): InspectedElement)
90
- );
91
- }
92
- }, [inspectedElement, viewElementSourceFunction]);
86
+ },
87
+ [bridge, inspectedElementID, store],
88
+ );
89
+
90
+ const viewSource = useCallback(
91
+ () => {
92
+ if (viewElementSourceFunction != null && inspectedElement !== null) {
93
+ viewElementSourceFunction(
94
+ inspectedElement.id,
95
+ ((inspectedElement: any): InspectedElement),
96
+ );
97
+ }
98
+ },
99
+ [inspectedElement, viewElementSourceFunction],
100
+ );
101
102
// In some cases (e.g. FB internal usage) the standalone shell might not be able to view the source.
103
// To detect this case, we defer to an injected helper function (if present).
@@ -110,53 +118,56 @@ export default function SelectedElement(_: Props) {
118
inspectedElement != null && inspectedElement.canToggleSuspense;
119
120
// TODO (suspense toggle) Would be nice to eventually use a two setState pattern here as well.
113
- const toggleSuspended = useCallback(() => {
114
- let nearestSuspenseElement = null;
115
- let currentElement = element;
116
- while (currentElement !== null) {
117
- if (currentElement.type === ElementTypeSuspense) {
118
- nearestSuspenseElement = currentElement;
119
- break;
120
- } else if (currentElement.parentID > 0) {
121
- currentElement = store.getElementByID(currentElement.parentID);
122
- } else {
123
- currentElement = null;
124
- }
125
- }
126
-
127
- // If we didn't find a Suspense ancestor, we can't suspend.
128
- // Instead we can show a warning to the user.
129
- if (nearestSuspenseElement === null) {
130
- modalDialogDispatch({
131
- type: 'SHOW',
132
- content: <CannotSuspendWarningMessage />,
133
- });
134
- } else {
135
- const nearestSuspenseElementID = nearestSuspenseElement.id;
136
-
137
- // If we're suspending from an arbitary (non-Suspense) component, select the nearest Suspense element in the Tree.
138
- // This way when the fallback UI is shown and the current element is hidden, something meaningful is selected.
139
- if (nearestSuspenseElement !== element) {
140
- dispatch({
141
- type: 'SELECT_ELEMENT_BY_ID',
142
- payload: nearestSuspenseElementID,
143
- });
121
+ const toggleSuspended = useCallback(
122
+ () => {
123
+ let nearestSuspenseElement = null;
124
+ let currentElement = element;
125
+ while (currentElement !== null) {
126
+ if (currentElement.type === ElementTypeSuspense) {
127
+ nearestSuspenseElement = currentElement;
128
+ break;
129
+ } else if (currentElement.parentID > 0) {
130
+ currentElement = store.getElementByID(currentElement.parentID);
131
+ } else {
132
+ currentElement = null;
133
+ }
134
}
135
146
- const rendererID = store.getRendererIDForElement(
147
- nearestSuspenseElementID
148
- );
149
-
150
- // Toggle suspended
151
- if (rendererID !== null) {
152
- bridge.send('overrideSuspense', {
153
- id: nearestSuspenseElementID,
154
- rendererID,
155
- forceFallback: !isSuspended,
136
+ // If we didn't find a Suspense ancestor, we can't suspend.
137
+ // Instead we can show a warning to the user.
138
+ if (nearestSuspenseElement === null) {
139
+ modalDialogDispatch({
140
+ type: 'SHOW',
141
+ content: <CannotSuspendWarningMessage />,
142
});
143
+ } else {
144
+ const nearestSuspenseElementID = nearestSuspenseElement.id;
145
+
146
+ // If we're suspending from an arbitary (non-Suspense) component, select the nearest Suspense element in the Tree.
147
+ // This way when the fallback UI is shown and the current element is hidden, something meaningful is selected.
148
+ if (nearestSuspenseElement !== element) {
149
+ dispatch({
150
+ type: 'SELECT_ELEMENT_BY_ID',
151
+ payload: nearestSuspenseElementID,
152
+ });
153
+ }
154
+
155
+ const rendererID = store.getRendererIDForElement(
156
+ nearestSuspenseElementID,
157
+ );
158
+
159
+ // Toggle suspended
160
+ if (rendererID !== null) {
161
+ bridge.send('overrideSuspense', {
162
+ id: nearestSuspenseElementID,
163
+ rendererID,
164
+ forceFallback: !isSuspended,
165
+ });
166
+ }
167
}
158
- }
159
- }, [bridge, dispatch, element, isSuspended, modalDialogDispatch, store]);
168
+ },
169
+ [bridge, dispatch, element, isSuspended, modalDialogDispatch, store],
170
+ );
171
172
if (element === null) {
173
return (
@@ -184,8 +195,7 @@ export default function SelectedElement(_: Props) {
195
isSuspended
196
? 'Unsuspend the selected component'
197
: 'Suspend the selected component'
187
- }
188
- >
198
+ }>
199
<ButtonIcon type="suspend" />
200
</Toggle>
201
)}
@@ -193,24 +203,21 @@ export default function SelectedElement(_: Props) {
203
<Button
204
className={styles.IconButton}
205
onClick={highlightElement}
196
- title="Inspect the matching DOM element"
197
- >
206
+ title="Inspect the matching DOM element">
207
<ButtonIcon type="view-dom" />
208
</Button>
209
)}
210
<Button
211
className={styles.IconButton}
212
onClick={logElement}
204
- title="Log this component data to the console"
205
- >
213
+ title="Log this component data to the console">
214
<ButtonIcon type="log-data" />
215
</Button>
216
<Button
217
className={styles.IconButton}
218
disabled={!canViewSource}
219
onClick={viewSource}
212
- title="View source for this element"
213
- >
220
+ title="View source for this element">
221
<ButtonIcon type="view-source" />
222
</Button>
223
</div>
@@ -248,7 +255,7 @@ function InspectedElementView({
255
getInspectedElementPath,
256
inspectedElement,
257
}: InspectedElementViewProps) {
251
- const { id, type } = element;
258
+ const {id, type} = element;
259
const {
260
canEditFunctionProps,
261
canEditHooks,
@@ -260,7 +267,7 @@ function InspectedElementView({
267
state,
268
} = inspectedElement;
269
263
- const { ownerID } = useContext(TreeStateContext);
270
+ const {ownerID} = useContext(TreeStateContext);
271
const bridge = useContext(BridgeContext);
272
const store = useContext(StoreContext);
273
@@ -268,19 +275,19 @@ function InspectedElementView({
275
(path: Array<string | number>) => {
276
getInspectedElementPath(id, ['context', ...path]);
277
},
271
- [getInspectedElementPath, id]
278
+ [getInspectedElementPath, id],
279
);
280
const inspectPropsPath = useCallback(
281
(path: Array<string | number>) => {
282
getInspectedElementPath(id, ['props', ...path]);
283
},
277
- [getInspectedElementPath, id]
284
+ [getInspectedElementPath, id],
285
);
286
const inspectStatePath = useCallback(
287
(path: Array<string | number>) => {
288
getInspectedElementPath(id, ['state', ...path]);
289
},
283
- [getInspectedElementPath, id]
290
+ [getInspectedElementPath, id],
291
);
292
293
let overrideContextFn = null;
@@ -291,19 +298,19 @@ function InspectedElementView({
298
overrideContextFn = (path: Array<string | number>, value: any) => {
299
const rendererID = store.getRendererIDForElement(id);
300
if (rendererID !== null) {
294
- bridge.send('overrideContext', { id, path, rendererID, value });
301
+ bridge.send('overrideContext', {id, path, rendererID, value});
302
}
303
};
304
overridePropsFn = (path: Array<string | number>, value: any) => {
305
const rendererID = store.getRendererIDForElement(id);
306
if (rendererID !== null) {
300
- bridge.send('overrideProps', { id, path, rendererID, value });
307
+ bridge.send('overrideProps', {id, path, rendererID, value});
308
}
309
};
310
overrideStateFn = (path: Array<string | number>, value: any) => {
311
const rendererID = store.getRendererIDForElement(id);
312
if (rendererID !== null) {
306
- bridge.send('overrideState', { id, path, rendererID, value });
313
+ bridge.send('overrideState', {id, path, rendererID, value});
314
}
315
};
316
} else if (
@@ -315,7 +322,7 @@ function InspectedElementView({
322
overridePropsFn = (path: Array<string | number>, value: any) => {
323
const rendererID = store.getRendererIDForElement(id);
324
if (rendererID !== null) {
318
- bridge.send('overrideProps', { id, path, rendererID, value });
325
+ bridge.send('overrideProps', {id, path, rendererID, value});
326
}
327
};
328
} else if (type === ElementTypeSuspense && canToggleSuspense) {
@@ -370,21 +377,23 @@ function InspectedElementView({
377
378
<NativeStyleEditor />
379
373
- {ownerID === null && owners !== null && owners.length > 0 && (
374
- <div className={styles.Owners}>
375
- <div className={styles.OwnersHeader}>rendered by</div>
376
- {owners.map(owner => (
377
- <OwnerView
378
- key={owner.id}
379
- displayName={owner.displayName || 'Anonymous'}
380
- hocDisplayNames={owner.hocDisplayNames}
381
- id={owner.id}
382
- isInStore={store.containsElement(owner.id)}
383
- type={owner.type}
384
- />
385
- ))}
386
- </div>
387
- )}
380
+ {ownerID === null &&
381
+ owners !== null &&
382
+ owners.length > 0 && (
383
+ <div className={styles.Owners}>
384
+ <div className={styles.OwnersHeader}>rendered by</div>
385
+ {owners.map(owner => (
386
+ <OwnerView
387
+ key={owner.id}
388
+ displayName={owner.displayName || 'Anonymous'}
389
+ hocDisplayNames={owner.hocDisplayNames}
390
+ id={owner.id}
391
+ isInStore={store.containsElement(owner.id)}
392
+ type={owner.type}
393
+ />
394
+ ))}
395
+ </div>
396
+ )}
397
</div>
398
);
399
}
@@ -412,7 +421,7 @@ function OwnerView({
421
type: 'SELECT_ELEMENT_BY_ID',
422
payload: id,
423
}),
415
- [dispatch, id]
424
+ [dispatch, id],
425
);
426
427
return (
@@ -420,12 +429,10 @@ function OwnerView({
429
key={id}
430
className={styles.OwnerButton}
431
disabled={!isInStore}
423
- onClick={handleClick}
424
- >
432
+ onClick={handleClick}>
433
<span
434
className={`${styles.Owner} ${isInStore ? '' : styles.NotInStore}`}
427
- title={displayName}
428
- >
435
+ title={displayName}>
436
{displayName}
437
</span>
438
<Badge hocDisplayNames={hocDisplayNames} type={type} />
@@ -439,7 +446,7 @@ function CannotSuspendWarningMessage() {
446
filter =>
447
filter.type === ComponentFilterElementType &&
448
filter.value === ElementTypeSuspense &&
442
- filter.isEnabled
449
+ filter.isEnabled,
450
);
451
452
// Has the user filted out Suspense nodes from the tree?
packages/react-devtools-shared/src/devtools/views/Components/SelectedTreeHighlight.js
+9
-9
@@ -1,11 +1,11 @@
1
// @flow
2
3
-import React, { useContext, useMemo } from 'react';
4
-import { TreeStateContext } from './TreeContext';
5
-import { SettingsContext } from '../Settings/SettingsContext';
3
+import React, {useContext, useMemo} from 'react';
4
+import {TreeStateContext} from './TreeContext';
5
+import {SettingsContext} from '../Settings/SettingsContext';
6
import TreeFocusedContext from './TreeFocusedContext';
7
-import { StoreContext } from '../context';
8
-import { useSubscription } from '../hooks';
7
+import {StoreContext} from '../context';
8
+import {useSubscription} from '../hooks';
9
import Store from '../../store';
10
11
import styles from './SelectedTreeHighlight.css';
@@ -16,10 +16,10 @@ type Data = {|
16
|};
17
18
export default function SelectedTreeHighlight(_: {||}) {
19
- const { lineHeight } = useContext(SettingsContext);
19
+ const {lineHeight} = useContext(SettingsContext);
20
const store = useContext(StoreContext);
21
const treeFocused = useContext(TreeFocusedContext);
22
- const { ownerID, selectedElementID } = useContext(TreeStateContext);
22
+ const {ownerID, selectedElementID} = useContext(TreeStateContext);
23
24
const subscription = useMemo(
25
() => ({
@@ -74,7 +74,7 @@ export default function SelectedTreeHighlight(_: {||}) {
74
};
75
},
76
}),
77
- [selectedElementID, store]
77
+ [selectedElementID, store],
78
);
79
const data = useSubscription<Data | null>(subscription);
80
@@ -86,7 +86,7 @@ export default function SelectedTreeHighlight(_: {||}) {
86
return null;
87
}
88
89
- const { startIndex, stopIndex } = data;
89
+ const {startIndex, stopIndex} = data;
90
91
return (
92
<div
packages/react-devtools-shared/src/devtools/views/Components/Tree.js
+154
-139
@@ -11,10 +11,10 @@ import React, {
11
useState,
12
} from 'react';
13
import AutoSizer from 'react-virtualized-auto-sizer';
14
-import { FixedSizeList } from 'react-window';
15
-import { TreeDispatcherContext, TreeStateContext } from './TreeContext';
16
-import { SettingsContext } from '../Settings/SettingsContext';
17
-import { BridgeContext, StoreContext } from '../context';
14
+import {FixedSizeList} from 'react-window';
15
+import {TreeDispatcherContext, TreeStateContext} from './TreeContext';
16
+import {SettingsContext} from '../Settings/SettingsContext';
17
+import {BridgeContext, StoreContext} from '../context';
18
import ElementView from './Element';
19
import InspectHostNodesToggle from './InspectHostNodesToggle';
20
import OwnersStack from './OwnersStack';
@@ -31,7 +31,7 @@ const DEFAULT_INDENTATION_SIZE = 12;
31
export type ItemData = {|
32
numElements: number,
33
isNavigatingWithKeyboard: boolean,
34
- lastScrolledIDRef: { current: number | null },
34
+ lastScrolledIDRef: {current: number | null},
35
onElementMouseEnter: (id: number) => void,
36
treeFocused: boolean,
37
|};
@@ -51,14 +51,14 @@ export default function Tree(props: Props) {
51
const bridge = useContext(BridgeContext);
52
const store = useContext(StoreContext);
53
const [isNavigatingWithKeyboard, setIsNavigatingWithKeyboard] = useState(
54
- false
54
+ false,
55
);
56
const treeRef = useRef<HTMLDivElement | null>(null);
57
const focusTargetRef = useRef<HTMLDivElement | null>(null);
58
59
const [treeFocused, setTreeFocused] = useState<boolean>(false);
60
61
- const { lineHeight } = useContext(SettingsContext);
61
+ const {lineHeight} = useContext(SettingsContext);
62
63
// Make sure a newly selected element is visible in the list.
64
// This is helpful for things like the owners list and search.
@@ -77,21 +77,27 @@ export default function Tree(props: Props) {
77
list.scrollToItem(selectedElementIndex, 'smart');
78
}
79
},
80
- [selectedElementIndex]
80
+ [selectedElementIndex],
81
);
82
83
// Picking an element in the inspector should put focus into the tree.
84
// This ensures that keyboard navigation works right after picking a node.
85
- useEffect(() => {
86
- function handleStopInspectingNative(didSelectNode) {
87
- if (didSelectNode && focusTargetRef.current !== null) {
88
- focusTargetRef.current.focus();
85
+ useEffect(
86
+ () => {
87
+ function handleStopInspectingNative(didSelectNode) {
88
+ if (didSelectNode && focusTargetRef.current !== null) {
89
+ focusTargetRef.current.focus();
90
+ }
91
}
90
- }
91
- bridge.addListener('stopInspectingNative', handleStopInspectingNative);
92
- return () =>
93
- bridge.removeListener('stopInspectingNative', handleStopInspectingNative);
94
- }, [bridge]);
92
+ bridge.addListener('stopInspectingNative', handleStopInspectingNative);
93
+ return () =>
94
+ bridge.removeListener(
95
+ 'stopInspectingNative',
96
+ handleStopInspectingNative,
97
+ );
98
+ },
99
+ [bridge],
100
+ );
101
102
// This ref is passed down the context to elements.
103
// It lets them avoid autoscrolling to the same item many times
@@ -99,87 +105,93 @@ export default function Tree(props: Props) {
105
const lastScrolledIDRef = useRef<number | null>(null);
106
107
// Navigate the tree with up/down arrow keys.
102
- useEffect(() => {
103
- if (treeRef.current === null) {
104
- return () => {};
105
- }
106
-
107
- const handleKeyDown = (event: KeyboardEvent) => {
108
- if ((event: any).target.tagName === 'INPUT' || event.defaultPrevented) {
109
- return;
108
+ useEffect(
109
+ () => {
110
+ if (treeRef.current === null) {
111
+ return () => {};
112
}
113
112
- // TODO We should ignore arrow keys if the focus is outside of DevTools.
113
- // Otherwise the inline (embedded) DevTools might change selection unexpectedly,
114
- // e.g. when a text input or a select has focus.
115
-
116
- let element;
117
- switch (event.key) {
118
- case 'ArrowDown':
119
- event.preventDefault();
120
- dispatch({ type: 'SELECT_NEXT_ELEMENT_IN_TREE' });
121
- break;
122
- case 'ArrowLeft':
123
- event.preventDefault();
124
- element =
125
- selectedElementID !== null
126
- ? store.getElementByID(selectedElementID)
127
- : null;
128
- if (element !== null) {
129
- if (element.children.length > 0 && !element.isCollapsed) {
130
- store.toggleIsCollapsed(element.id, true);
131
- } else {
132
- dispatch({ type: 'SELECT_PARENT_ELEMENT_IN_TREE' });
114
+ const handleKeyDown = (event: KeyboardEvent) => {
115
+ if ((event: any).target.tagName === 'INPUT' || event.defaultPrevented) {
116
+ return;
117
+ }
118
+
119
+ // TODO We should ignore arrow keys if the focus is outside of DevTools.
120
+ // Otherwise the inline (embedded) DevTools might change selection unexpectedly,
121
+ // e.g. when a text input or a select has focus.
122
+
123
+ let element;
124
+ switch (event.key) {
125
+ case 'ArrowDown':
126
+ event.preventDefault();
127
+ dispatch({type: 'SELECT_NEXT_ELEMENT_IN_TREE'});
128
+ break;
129
+ case 'ArrowLeft':
130
+ event.preventDefault();
131
+ element =
132
+ selectedElementID !== null
133
+ ? store.getElementByID(selectedElementID)
134
+ : null;
135
+ if (element !== null) {
136
+ if (element.children.length > 0 && !element.isCollapsed) {
137
+ store.toggleIsCollapsed(element.id, true);
138
+ } else {
139
+ dispatch({type: 'SELECT_PARENT_ELEMENT_IN_TREE'});
140
+ }
141
}
134
- }
135
- break;
136
- case 'ArrowRight':
137
- event.preventDefault();
138
- element =
139
- selectedElementID !== null
140
- ? store.getElementByID(selectedElementID)
141
- : null;
142
- if (element !== null) {
143
- if (element.children.length > 0 && element.isCollapsed) {
144
- store.toggleIsCollapsed(element.id, false);
145
- } else {
146
- dispatch({ type: 'SELECT_CHILD_ELEMENT_IN_TREE' });
142
+ break;
143
+ case 'ArrowRight':
144
+ event.preventDefault();
145
+ element =
146
+ selectedElementID !== null
147
+ ? store.getElementByID(selectedElementID)
148
+ : null;
149
+ if (element !== null) {
150
+ if (element.children.length > 0 && element.isCollapsed) {
151
+ store.toggleIsCollapsed(element.id, false);
152
+ } else {
153
+ dispatch({type: 'SELECT_CHILD_ELEMENT_IN_TREE'});
154
+ }
155
}
148
- }
149
- break;
150
- case 'ArrowUp':
151
- event.preventDefault();
152
- dispatch({ type: 'SELECT_PREVIOUS_ELEMENT_IN_TREE' });
153
- break;
154
- default:
155
- return;
156
- }
157
- setIsNavigatingWithKeyboard(true);
158
- };
159
-
160
- // It's important to listen to the ownerDocument to support the browser extension.
161
- // Here we use portals to render individual tabs (e.g. Profiler),
162
- // and the root document might belong to a different window.
163
- const ownerDocument = treeRef.current.ownerDocument;
164
- ownerDocument.addEventListener('keydown', handleKeyDown);
165
-
166
- return () => {
167
- ownerDocument.removeEventListener('keydown', handleKeyDown);
168
- };
169
- }, [dispatch, selectedElementID, store]);
156
+ break;
157
+ case 'ArrowUp':
158
+ event.preventDefault();
159
+ dispatch({type: 'SELECT_PREVIOUS_ELEMENT_IN_TREE'});
160
+ break;
161
+ default:
162
+ return;
163
+ }
164
+ setIsNavigatingWithKeyboard(true);
165
+ };
166
+
167
+ // It's important to listen to the ownerDocument to support the browser extension.
168
+ // Here we use portals to render individual tabs (e.g. Profiler),
169
+ // and the root document might belong to a different window.
170
+ const ownerDocument = treeRef.current.ownerDocument;
171
+ ownerDocument.addEventListener('keydown', handleKeyDown);
172
+
173
+ return () => {
174
+ ownerDocument.removeEventListener('keydown', handleKeyDown);
175
+ };
176
+ },
177
+ [dispatch, selectedElementID, store],
178
+ );
179
180
// Focus management.
181
const handleBlur = useCallback(() => setTreeFocused(false), []);
173
- const handleFocus = useCallback(() => {
174
- setTreeFocused(true);
175
-
176
- if (selectedElementIndex === null && numElements > 0) {
177
- dispatch({
178
- type: 'SELECT_ELEMENT_AT_INDEX',
179
- payload: 0,
180
- });
181
- }
182
- }, [dispatch, numElements, selectedElementIndex]);
182
+ const handleFocus = useCallback(
183
+ () => {
184
+ setTreeFocused(true);
185
+
186
+ if (selectedElementIndex === null && numElements > 0) {
187
+ dispatch({
188
+ type: 'SELECT_ELEMENT_AT_INDEX',
189
+ payload: 0,
190
+ });
191
+ }
192
+ },
193
+ [dispatch, numElements, selectedElementIndex],
194
+ );
195
196
const handleKeyPress = useCallback(
197
event => {
@@ -187,14 +199,14 @@ export default function Tree(props: Props) {
199
case 'Enter':
200
case ' ':
201
if (selectedElementID !== null) {
190
- dispatch({ type: 'SELECT_OWNER', payload: selectedElementID });
202
+ dispatch({type: 'SELECT_OWNER', payload: selectedElementID});
203
}
204
break;
205
default:
206
break;
207
}
208
},
197
- [dispatch, selectedElementID]
209
+ [dispatch, selectedElementID],
210
);
211
212
const highlightNativeElement = useCallback(
@@ -212,37 +224,40 @@ export default function Tree(props: Props) {
224
});
225
}
226
},
215
- [store, bridge]
227
+ [store, bridge],
228
);
229
230
// If we switch the selected element while using the keyboard,
231
// start highlighting it in the DOM instead of the last hovered node.
220
- const searchRef = useRef({ searchIndex, searchResults });
221
- useEffect(() => {
222
- let didSelectNewSearchResult = false;
223
- if (
224
- searchRef.current.searchIndex !== searchIndex ||
225
- searchRef.current.searchResults !== searchResults
226
- ) {
227
- searchRef.current.searchIndex = searchIndex;
228
- searchRef.current.searchResults = searchResults;
229
- didSelectNewSearchResult = true;
230
- }
231
- if (isNavigatingWithKeyboard || didSelectNewSearchResult) {
232
- if (selectedElementID !== null) {
233
- highlightNativeElement(selectedElementID);
234
- } else {
235
- bridge.send('clearNativeElementHighlight');
232
+ const searchRef = useRef({searchIndex, searchResults});
233
+ useEffect(
234
+ () => {
235
+ let didSelectNewSearchResult = false;
236
+ if (
237
+ searchRef.current.searchIndex !== searchIndex ||
238
+ searchRef.current.searchResults !== searchResults
239
+ ) {
240
+ searchRef.current.searchIndex = searchIndex;
241
+ searchRef.current.searchResults = searchResults;
242
+ didSelectNewSearchResult = true;
243
}
237
- }
238
- }, [
239
- bridge,
240
- isNavigatingWithKeyboard,
241
- highlightNativeElement,
242
- searchIndex,
243
- searchResults,
244
- selectedElementID,
245
- ]);
244
+ if (isNavigatingWithKeyboard || didSelectNewSearchResult) {
245
+ if (selectedElementID !== null) {
246
+ highlightNativeElement(selectedElementID);
247
+ } else {
248
+ bridge.send('clearNativeElementHighlight');
249
+ }
250
+ }
251
+ },
252
+ [
253
+ bridge,
254
+ isNavigatingWithKeyboard,
255
+ highlightNativeElement,
256
+ searchIndex,
257
+ searchResults,
258
+ selectedElementID,
259
+ ],
260
+ );
261
262
// Highlight last hovered element.
263
const handleElementMouseEnter = useCallback(
@@ -253,7 +268,7 @@ export default function Tree(props: Props) {
268
highlightNativeElement(id);
269
}
270
},
256
- [isNavigatingWithKeyboard, highlightNativeElement]
271
+ [isNavigatingWithKeyboard, highlightNativeElement],
272
);
273
274
const handleMouseMove = useCallback(() => {
@@ -262,9 +277,12 @@ export default function Tree(props: Props) {
277
setIsNavigatingWithKeyboard(false);
278
}, []);
279
265
- const handleMouseLeave = useCallback(() => {
266
- bridge.send('clearNativeElementHighlight');
267
- }, [bridge]);
280
+ const handleMouseLeave = useCallback(
281
+ () => {
282
+ bridge.send('clearNativeElementHighlight');
283
+ },
284
+ [bridge],
285
+ );
286
287
// Let react-window know to re-render any time the underlying tree data changes.
288
// This includes the owner context, since it controls a filtered view of the tree.
@@ -282,12 +300,12 @@ export default function Tree(props: Props) {
300
handleElementMouseEnter,
301
lastScrolledIDRef,
302
treeFocused,
285
- ]
303
+ ],
304
);
305
306
const itemKey = useCallback(
307
(index: number) => store.getElementIDAtIndex(index),
290
- [store]
308
+ [store],
309
);
310
311
return (
@@ -314,10 +332,9 @@ export default function Tree(props: Props) {
332
onMouseMove={handleMouseMove}
333
onMouseLeave={handleMouseLeave}
334
ref={focusTargetRef}
317
- tabIndex={0}
318
- >
335
+ tabIndex={0}>
336
<AutoSizer>
320
- {({ height, width }) => (
337
+ {({height, width}) => (
338
// $FlowFixMe https://github.com/facebook/flow/issues/7341
339
<FixedSizeList
340
className={styles.List}
@@ -328,8 +345,7 @@ export default function Tree(props: Props) {
345
itemKey={itemKey}
346
itemSize={lineHeight}
347
ref={listCallbackRef}
331
- width={width}
332
- >
348
+ width={width}>
349
{ElementView}
350
</FixedSizeList>
351
)}
@@ -383,8 +399,8 @@ export default function Tree(props: Props) {
399
function updateIndentationSizeVar(
400
innerDiv: HTMLDivElement,
401
cachedChildWidths: WeakMap<HTMLElement, number>,
386
- indentationSizeRef: {| current: number |},
387
- prevListWidthRef: {| current: number |}
402
+ indentationSizeRef: {|current: number|},
403
+ prevListWidthRef: {|current: number|},
404
): void {
405
const list = ((innerDiv.parentElement: any): HTMLDivElement);
406
const listWidth = list.clientWidth;
@@ -411,7 +427,7 @@ function updateIndentationSizeVar(
427
if (cachedChildWidth != null) {
428
childWidth = cachedChildWidth;
429
} else {
414
- const { firstElementChild } = child;
430
+ const {firstElementChild} = child;
431
432
// Skip over e.g. the guideline element
433
if (firstElementChild != null) {
@@ -430,12 +446,12 @@ function updateIndentationSizeVar(
446
list.style.setProperty('--indentation-size', `${maxIndentationSize}px`);
447
}
448
433
-function InnerElementType({ children, style, ...rest }) {
434
- const { ownerID } = useContext(TreeStateContext);
449
+function InnerElementType({children, style, ...rest}) {
450
+ const {ownerID} = useContext(TreeStateContext);
451
452
const cachedChildWidths = useMemo<WeakMap<HTMLElement, number>>(
453
() => new WeakMap(),
438
- []
454
+ [],
455
);
456
457
// This ref tracks the current indentation size.
@@ -468,7 +484,7 @@ function InnerElementType({ children, style, ...rest }) {
484
divRef.current,
485
cachedChildWidths,
486
indentationSizeRef,
471
- prevListWidthRef
487
+ prevListWidthRef,
488
);
489
}
490
});
@@ -482,8 +498,7 @@ function InnerElementType({ children, style, ...rest }) {
498
className={styles.InnerElementType}
499
ref={divRef}
500
style={style}
485
- {...rest}
486
- >
501
+ {...rest}>
502
<SelectedTreeHighlight />
503
{children}
504
</div>
packages/react-devtools-shared/src/devtools/views/Components/TreeContext.js
+79
-70
@@ -32,11 +32,11 @@ import {
32
unstable_runWithPriority as runWithPriority,
33
unstable_UserBlockingPriority as UserBlockingPriority,
34
} from 'scheduler';
35
-import { createRegExp } from '../utils';
36
-import { BridgeContext, StoreContext } from '../context';
35
+import {createRegExp} from '../utils';
36
+import {BridgeContext, StoreContext} from '../context';
37
import Store from '../../store';
38
39
-import type { Element } from './types';
39
+import type {Element} from './types';
40
41
export type StateContext = {|
42
// Tree
@@ -120,12 +120,12 @@ type Action =
120
export type DispatcherContext = (action: Action) => void;
121
122
const TreeStateContext = createContext<StateContext>(
123
- ((null: any): StateContext)
123
+ ((null: any): StateContext),
124
);
125
TreeStateContext.displayName = 'TreeStateContext';
126
127
const TreeDispatcherContext = createContext<DispatcherContext>(
128
- ((null: any): DispatcherContext)
128
+ ((null: any): DispatcherContext),
129
);
130
TreeDispatcherContext.displayName = 'TreeDispatcherContext';
131
@@ -149,7 +149,7 @@ type State = {|
149
|};
150
151
function reduceTreeState(store: Store, state: State, action: Action): State {
152
- let { numElements, ownerID, selectedElementIndex, selectedElementID } = state;
152
+ let {numElements, ownerID, selectedElementIndex, selectedElementID} = state;
153
154
let lookupIDForIndex = true;
155
@@ -169,7 +169,7 @@ function reduceTreeState(store: Store, state: State, action: Action): State {
169
removedIDs.has(selectedElementID)
170
) {
171
selectedElementID = ((removedIDs.get(
172
- selectedElementID
172
+ selectedElementID,
173
): any): number);
174
}
175
if (selectedElementID === 0) {
@@ -180,7 +180,7 @@ function reduceTreeState(store: Store, state: State, action: Action): State {
180
case 'SELECT_CHILD_ELEMENT_IN_TREE':
181
if (selectedElementIndex !== null) {
182
const selectedElement = store.getElementAtIndex(
183
- ((selectedElementIndex: any): number)
183
+ ((selectedElementIndex: any): number),
184
);
185
if (
186
selectedElement !== null &&
@@ -222,11 +222,11 @@ function reduceTreeState(store: Store, state: State, action: Action): State {
222
case 'SELECT_PARENT_ELEMENT_IN_TREE':
223
if (selectedElementIndex !== null) {
224
const selectedElement = store.getElementAtIndex(
225
- ((selectedElementIndex: any): number)
225
+ ((selectedElementIndex: any): number),
226
);
227
if (selectedElement !== null && selectedElement.parentID !== null) {
228
const parentIndex = store.getIndexOfElementID(
229
- selectedElement.parentID
229
+ selectedElement.parentID,
230
);
231
if (parentIndex !== null) {
232
selectedElementIndex = parentIndex;
@@ -253,7 +253,7 @@ function reduceTreeState(store: Store, state: State, action: Action): State {
253
selectedElementID = null;
254
} else {
255
selectedElementID = store.getElementIDAtIndex(
256
- ((selectedElementIndex: any): number)
256
+ ((selectedElementIndex: any): number),
257
);
258
}
259
}
@@ -336,13 +336,13 @@ function reduceSearchState(store: Store, state: State, action: Action): State {
336
// It's possible that multiple tree operations will fire before this action has run.
337
// So it's important to check for elements that may have been added and then removed.
338
if (element !== null) {
339
- const { displayName } = element;
339
+ const {displayName} = element;
340
341
// Add this item to the search results if it matches.
342
const regExp = createRegExp(searchText);
343
if (displayName !== null && regExp.test(displayName)) {
344
const newElementIndex = ((store.getIndexOfElementID(
345
- id
345
+ id,
346
): any): number);
347
348
let foundMatch = false;
@@ -386,7 +386,7 @@ function reduceSearchState(store: Store, state: State, action: Action): State {
386
searchIndex = getNearestResultIndex(
387
store,
388
searchResults,
389
- selectedElementIndex
389
+ selectedElementIndex,
390
);
391
} else {
392
searchIndex = 0;
@@ -394,7 +394,7 @@ function reduceSearchState(store: Store, state: State, action: Action): State {
394
} else {
395
searchIndex = Math.min(
396
((prevSearchIndex: any): number),
397
- searchResults.length - 1
397
+ searchResults.length - 1,
398
);
399
}
400
}
@@ -421,7 +421,7 @@ function reduceSearchState(store: Store, state: State, action: Action): State {
421
if (didRequestSearch && searchIndex !== null) {
422
selectedElementID = ((searchResults[searchIndex]: any): number);
423
selectedElementIndex = store.getIndexOfElementID(
424
- ((selectedElementID: any): number)
424
+ ((selectedElementID: any): number),
425
);
426
}
427
@@ -463,7 +463,7 @@ function reduceOwnersState(store: Store, state: State, action: Action): State {
463
if (selectedElementID !== null) {
464
// Mutation might have caused the index of this ID to shift.
465
selectedElementIndex = ownerFlatTree.findIndex(
466
- element => element.id === selectedElementID
466
+ element => element.id === selectedElementID,
467
);
468
}
469
}
@@ -499,7 +499,7 @@ function reduceOwnersState(store: Store, state: State, action: Action): State {
499
selectedElementIndex = null;
500
} else {
501
selectedElementIndex = ownerFlatTree.findIndex(
502
- element => element.id === payload
502
+ element => element.id === payload,
503
);
504
505
// If the selected element is outside of the current owners list,
@@ -588,9 +588,9 @@ function reduceOwnersState(store: Store, state: State, action: Action): State {
588
function reduceSuspenseState(
589
store: Store,
590
state: State,
591
- action: Action
591
+ action: Action,
592
): State {
593
- const { type } = action;
593
+ const {type} = action;
594
switch (type) {
595
case 'UPDATE_INSPECTED_ELEMENT_ID':
596
if (state.inspectedElementID !== state.selectedElementID) {
@@ -634,7 +634,7 @@ function TreeContextController({
634
// so it's okay for the reducer to have an empty dependencies array.
635
const reducer = useMemo(
636
() => (state: State, action: Action): State => {
637
- const { type } = action;
637
+ const {type} = action;
638
switch (type) {
639
case 'GO_TO_NEXT_SEARCH_RESULT':
640
case 'GO_TO_PREVIOUS_SEARCH_RESULT':
@@ -672,7 +672,7 @@ function TreeContextController({
672
throw new Error(`Unrecognized action "${type}"`);
673
}
674
},
675
- [store]
675
+ [store],
676
);
677
678
const [state, dispatch] = useReducer(reducer, {
@@ -702,62 +702,71 @@ function TreeContextController({
702
// In this case, the current (and "next") priorities would both be "normal",
703
// and suspense would potentially block both updates.
704
runWithPriority(UserBlockingPriority, () => dispatch(action));
705
- next(() => dispatch({ type: 'UPDATE_INSPECTED_ELEMENT_ID' }));
705
+ next(() => dispatch({type: 'UPDATE_INSPECTED_ELEMENT_ID'}));
706
},
707
- [dispatch]
707
+ [dispatch],
708
);
709
710
// Listen for host element selections.
711
- useEffect(() => {
712
- const handleSelectFiber = (id: number) =>
713
- dispatchWrapper({ type: 'SELECT_ELEMENT_BY_ID', payload: id });
714
- bridge.addListener('selectFiber', handleSelectFiber);
715
- return () => bridge.removeListener('selectFiber', handleSelectFiber);
716
- }, [bridge, dispatchWrapper]);
711
+ useEffect(
712
+ () => {
713
+ const handleSelectFiber = (id: number) =>
714
+ dispatchWrapper({type: 'SELECT_ELEMENT_BY_ID', payload: id});
715
+ bridge.addListener('selectFiber', handleSelectFiber);
716
+ return () => bridge.removeListener('selectFiber', handleSelectFiber);
717
+ },
718
+ [bridge, dispatchWrapper],
719
+ );
720
721
// If a newly-selected search result or inspection selection is inside of a collapsed subtree, auto expand it.
722
// This needs to be a layout effect to avoid temporarily flashing an incorrect selection.
723
const prevSelectedElementID = useRef<number | null>(null);
721
- useLayoutEffect(() => {
722
- if (state.selectedElementID !== prevSelectedElementID.current) {
723
- prevSelectedElementID.current = state.selectedElementID;
724
-
725
- if (state.selectedElementID !== null) {
726
- let element = store.getElementByID(state.selectedElementID);
727
- if (element !== null && element.parentID > 0) {
728
- store.toggleIsCollapsed(element.parentID, false);
724
+ useLayoutEffect(
725
+ () => {
726
+ if (state.selectedElementID !== prevSelectedElementID.current) {
727
+ prevSelectedElementID.current = state.selectedElementID;
728
+
729
+ if (state.selectedElementID !== null) {
730
+ let element = store.getElementByID(state.selectedElementID);
731
+ if (element !== null && element.parentID > 0) {
732
+ store.toggleIsCollapsed(element.parentID, false);
733
+ }
734
}
735
}
731
- }
732
- }, [state.selectedElementID, store]);
736
+ },
737
+ [state.selectedElementID, store],
738
+ );
739
740
// Mutations to the underlying tree may impact this context (e.g. search results, selection state).
735
- useEffect(() => {
736
- const handleStoreMutated = ([addedElementIDs, removedElementIDs]: [
737
- Array<number>,
738
- Map<number, number>,
739
- ]) => {
740
- dispatchWrapper({
741
- type: 'HANDLE_STORE_MUTATION',
742
- payload: [addedElementIDs, removedElementIDs],
743
- });
744
- };
745
-
746
- // Since this is a passive effect, the tree may have been mutated before our initial subscription.
747
- if (store.revision !== initialRevision) {
748
- // At the moment, we can treat this as a mutation.
749
- // We don't know which Elements were newly added/removed, but that should be okay in this case.
750
- // It would only impact the search state, which is unlikely to exist yet at this point.
751
- dispatchWrapper({
752
- type: 'HANDLE_STORE_MUTATION',
753
- payload: [[], new Map()],
754
- });
755
- }
741
+ useEffect(
742
+ () => {
743
+ const handleStoreMutated = ([addedElementIDs, removedElementIDs]: [
744
+ Array<number>,
745
+ Map<number, number>,
746
+ ]) => {
747
+ dispatchWrapper({
748
+ type: 'HANDLE_STORE_MUTATION',
749
+ payload: [addedElementIDs, removedElementIDs],
750
+ });
751
+ };
752
+
753
+ // Since this is a passive effect, the tree may have been mutated before our initial subscription.
754
+ if (store.revision !== initialRevision) {
755
+ // At the moment, we can treat this as a mutation.
756
+ // We don't know which Elements were newly added/removed, but that should be okay in this case.
757
+ // It would only impact the search state, which is unlikely to exist yet at this point.
758
+ dispatchWrapper({
759
+ type: 'HANDLE_STORE_MUTATION',
760
+ payload: [[], new Map()],
761
+ });
762
+ }
763
757
- store.addListener('mutated', handleStoreMutated);
764
+ store.addListener('mutated', handleStoreMutated);
765
759
- return () => store.removeListener('mutated', handleStoreMutated);
760
- }, [dispatchWrapper, initialRevision, store]);
766
+ return () => store.removeListener('mutated', handleStoreMutated);
767
+ },
768
+ [dispatchWrapper, initialRevision, store],
769
+ );
770
771
return (
772
<TreeStateContext.Provider value={state}>
@@ -771,10 +780,10 @@ function recursivelySearchTree(
780
store: Store,
781
elementID: number,
782
regExp: RegExp,
774
- searchResults: Array<number>
783
+ searchResults: Array<number>,
784
): void {
776
- const { children, displayName, hocDisplayNames } = ((store.getElementByID(
777
- elementID
785
+ const {children, displayName, hocDisplayNames} = ((store.getElementByID(
786
+ elementID,
787
): any): Element);
788
789
if (displayName != null && regExp.test(displayName) === true) {
@@ -788,14 +797,14 @@ function recursivelySearchTree(
797
}
798
799
children.forEach(childID =>
791
- recursivelySearchTree(store, childID, regExp, searchResults)
800
+ recursivelySearchTree(store, childID, regExp, searchResults),
801
);
802
}
803
804
function getNearestResultIndex(
805
store: Store,
806
searchResults: Array<number>,
798
- selectedElementIndex: number
807
+ selectedElementIndex: number,
808
): number {
809
const index = searchResults.findIndex(id => {
810
const index = store.getIndexOfElementID(id);
@@ -805,4 +814,4 @@ function getNearestResultIndex(
814
return index === -1 ? 0 : index;
815
}
816
808
-export { TreeDispatcherContext, TreeStateContext, TreeContextController };
817
+export {TreeDispatcherContext, TreeStateContext, TreeContextController};
packages/react-devtools-shared/src/devtools/views/Components/TreeFocusedContext.js
+1
-1
@@ -1,6 +1,6 @@
1
// @flow
2
3
-import { createContext } from 'react';
3
+import {createContext} from 'react';
4
5
const TreeFocusedContext = createContext<boolean>(false);
6
packages/react-devtools-shared/src/devtools/views/Components/ViewElementSourceContext.js
+1
-1
@@ -1,6 +1,6 @@
1
// @flow
2
3
-import { createContext } from 'react';
3
+import {createContext} from 'react';
4
5
import type {
6
CanViewElementSource,
packages/react-devtools-shared/src/devtools/views/Components/types.js
+7
-3
@@ -1,7 +1,7 @@
1
// @flow
2
3
-import type { Dehydrated } from 'react-devtools-shared/src/hydration';
4
-import type { ElementType } from 'react-devtools-shared/src/types';
3
+import type {Dehydrated} from 'react-devtools-shared/src/hydration';
4
+import type {ElementType} from 'react-devtools-shared/src/types';
5
6
// Each element on the frontend corresponds to a Fiber on the backend.
7
// Some of its information (e.g. id, type, displayName) come from the backend.
@@ -84,5 +84,9 @@ export type InspectedElement = {|
84
85
export type DehydratedData = {|
86
cleaned: Array<Array<string | number>>,
87
- data: string | Dehydrated | Array<Dehydrated> | { [key: string]: string | Dehydrated },
87
+ data:
88
+ | string
89
+ | Dehydrated
90
+ | Array<Dehydrated>
91
+ | {[key: string]: string | Dehydrated},
92
|};
packages/react-devtools-shared/src/devtools/views/DevTools.js
+14
-17
@@ -5,17 +5,17 @@
5
import '@reach/menu-button/styles.css';
6
import '@reach/tooltip/styles.css';
7
8
-import React, { useMemo, useState } from 'react';
8
+import React, {useMemo, useState} from 'react';
9
import Store from '../store';
10
-import { BridgeContext, StoreContext } from './context';
10
+import {BridgeContext, StoreContext} from './context';
11
import Components from './Components/Components';
12
import Profiler from './Profiler/Profiler';
13
import TabBar from './TabBar';
14
-import { SettingsContextController } from './Settings/SettingsContext';
15
-import { TreeContextController } from './Components/TreeContext';
14
+import {SettingsContextController} from './Settings/SettingsContext';
15
+import {TreeContextController} from './Components/TreeContext';
16
import ViewElementSourceContext from './Components/ViewElementSourceContext';
17
-import { ProfilerContextController } from './Profiler/ProfilerContext';
18
-import { ModalDialogContextController } from './ModalDialog';
17
+import {ProfilerContextController} from './Profiler/ProfilerContext';
18
+import {ModalDialogContextController} from './ModalDialog';
19
import ReactLogo from './ReactLogo';
20
import WarnIfLegacyBackendDetected from './WarnIfLegacyBackendDetected';
21
import ShowWelcomeToTheNewDevToolsDialog from './ShowWelcomeToTheNewDevToolsDialog';
@@ -24,17 +24,17 @@ import styles from './DevTools.css';
24
25
import './root.css';
26
27
-import type { InspectedElement } from 'react-devtools-shared/src/devtools/views/Components/types';
28
-import type { FrontendBridge } from 'react-devtools-shared/src/bridge';
27
+import type {InspectedElement} from 'react-devtools-shared/src/devtools/views/Components/types';
28
+import type {FrontendBridge} from 'react-devtools-shared/src/bridge';
29
30
export type BrowserTheme = 'dark' | 'light';
31
export type TabID = 'components' | 'profiler';
32
export type ViewElementSource = (
33
id: number,
34
- inspectedElement: InspectedElement
34
+ inspectedElement: InspectedElement,
35
) => void;
36
export type CanViewElementSource = (
37
- inspectedElement: InspectedElement
37
+ inspectedElement: InspectedElement,
38
) => boolean;
39
40
export type Props = {|
@@ -100,7 +100,7 @@ export default function DevTools({
100
canViewElementSourceFunction,
101
viewElementSourceFunction,
102
}),
103
- [canViewElementSourceFunction, viewElementSourceFunction]
103
+ [canViewElementSourceFunction, viewElementSourceFunction],
104
);
105
106
return (
@@ -110,8 +110,7 @@ export default function DevTools({
110
<SettingsContextController
111
browserTheme={browserTheme}
112
componentsPortalContainer={componentsPortalContainer}
113
- profilerPortalContainer={profilerPortalContainer}
114
- >
113
+ profilerPortalContainer={profilerPortalContainer}>
114
<ViewElementSourceContext.Provider value={viewElementSource}>
115
<TreeContextController>
116
<ProfilerContextController>
@@ -134,14 +133,12 @@ export default function DevTools({
133
)}
134
<div
135
className={styles.TabContent}
137
- hidden={tab !== 'components'}
138
- >
136
+ hidden={tab !== 'components'}>
137
<Components portalContainer={componentsPortalContainer} />
138
</div>
139
<div
140
className={styles.TabContent}
143
- hidden={tab !== 'profiler'}
144
- >
141
+ hidden={tab !== 'profiler'}>
142
<Profiler portalContainer={profilerPortalContainer} />
143
</div>
144
</div>
packages/react-devtools-shared/src/devtools/views/ErrorBoundary.js
+6
-7
@@ -1,6 +1,6 @@
1
// @flow
2
3
-import React, { Component } from 'react';
3
+import React, {Component} from 'react';
4
import styles from './ErrorBoundary.css';
5
6
type Props = {|
@@ -22,7 +22,7 @@ export default class ErrorBoundary extends Component<Props, State> {
22
hasError: false,
23
};
24
25
- componentDidCatch(error: any, { componentStack }: any) {
25
+ componentDidCatch(error: any, {componentStack}: any) {
26
const errorMessage =
27
typeof error === 'object' && error.hasOwnProperty('message')
28
? error.message
@@ -45,8 +45,8 @@ export default class ErrorBoundary extends Component<Props, State> {
45
}
46
47
render() {
48
- const { children } = this.props;
49
- const { callStack, componentStack, errorMessage, hasError } = this.state;
48
+ const {children} = this.props;
49
+ const {callStack, componentStack, errorMessage, hasError} = this.state;
50
51
let bugURL = process.env.GITHUB_URL;
52
if (bugURL) {
@@ -66,7 +66,7 @@ export default class ErrorBoundary extends Component<Props, State> {
66
}
67
68
bugURL += `/issues/new?labels=${encodeURI(label)}&title=${encodeURI(
69
- title
69
+ title,
70
)}&body=${encodeURI(body)}`;
71
}
72
@@ -81,8 +81,7 @@ export default class ErrorBoundary extends Component<Props, State> {
81
href={bugURL}
82
rel="noopener noreferrer"
83
target="_blank"
84
- title="Report bug"
85
- >
84
+ title="Report bug">
85
Report this issue
86
</a>
87
)}
packages/react-devtools-shared/src/devtools/views/Icon.js
+2
-3
@@ -18,7 +18,7 @@ type Props = {|
18
type: IconType,
19
|};
20
21
-export default function Icon({ className = '', type }: Props) {
21
+export default function Icon({className = '', type}: Props) {
22
let pathData = null;
23
switch (type) {
24
case 'arrow':
@@ -56,8 +56,7 @@ export default function Icon({ className = '', type }: Props) {
56
className={`${styles.Icon} ${className}`}
57
width="24"
58
height="24"
59
- viewBox="0 0 24 24"
60
- >
59
+ viewBox="0 0 24 24">
60
<path d="M0 0h24v24H0z" fill="none" />
61
<path fill="currentColor" d={pathData} />
62
</svg>
packages/react-devtools-shared/src/devtools/views/ModalDialog.js
+17
-15
@@ -9,7 +9,7 @@ import React, {
9
useRef,
10
} from 'react';
11
import Button from './Button';
12
-import { useModalDismissSignal } from './hooks';
12
+import {useModalDismissSignal} from './hooks';
13
14
import styles from './ModalDialog.css';
15
@@ -40,7 +40,7 @@ type ModalDialogContextType = {|
40
|};
41
42
const ModalDialogContext = createContext<ModalDialogContextType>(
43
- ((null: any): ModalDialogContextType)
43
+ ((null: any): ModalDialogContextType),
44
);
45
ModalDialogContext.displayName = 'ModalDialogContext';
46
@@ -69,7 +69,7 @@ type Props = {|
69
children: React$Node,
70
|};
71
72
-function ModalDialogContextController({ children }: Props) {
72
+function ModalDialogContextController({children}: Props) {
73
const [state, dispatch] = useReducer<State, Action>(dialogReducer, {
74
canBeDismissed: true,
75
content: null,
@@ -85,7 +85,7 @@ function ModalDialogContextController({ children }: Props) {
85
title: state.title,
86
dispatch,
87
}),
88
- [state, dispatch]
88
+ [state, dispatch],
89
);
90
91
return (
@@ -96,19 +96,22 @@ function ModalDialogContextController({ children }: Props) {
96
}
97
98
function ModalDialog(_: {||}) {
99
- const { isVisible } = useContext(ModalDialogContext);
99
+ const {isVisible} = useContext(ModalDialogContext);
100
return isVisible ? <ModalDialogImpl /> : null;
101
}
102
103
function ModalDialogImpl(_: {||}) {
104
- const { canBeDismissed, content, dispatch, title } = useContext(
105
- ModalDialogContext
104
+ const {canBeDismissed, content, dispatch, title} = useContext(
105
+ ModalDialogContext,
106
+ );
107
+ const dismissModal = useCallback(
108
+ () => {
109
+ if (canBeDismissed) {
110
+ dispatch({type: 'HIDE'});
111
+ }
112
+ },
113
+ [canBeDismissed, dispatch],
114
);
107
- const dismissModal = useCallback(() => {
108
- if (canBeDismissed) {
109
- dispatch({ type: 'HIDE' });
110
- }
111
- }, [canBeDismissed, dispatch]);
115
const dialogRef = useRef<HTMLDivElement | null>(null);
116
117
// It's important to trap click events within the dialog,
@@ -131,8 +134,7 @@ function ModalDialogImpl(_: {||}) {
134
<div
135
ref={dialogRef}
136
className={styles.Dialog}
134
- onClick={handleDialogClick}
135
- >
137
+ onClick={handleDialogClick}>
138
{title !== null && <div className={styles.Title}>{title}</div>}
139
{content}
140
{canBeDismissed && (
@@ -147,4 +149,4 @@ function ModalDialogImpl(_: {||}) {
149
);
150
}
151
150
-export { ModalDialog, ModalDialogContext, ModalDialogContextController };
152
+export {ModalDialog, ModalDialogContext, ModalDialogContextController};
packages/react-devtools-shared/src/devtools/views/Profiler/ChartNode.js
+1
-2
@@ -56,8 +56,7 @@ export default function ChartNode({
56
opacity: isDimmed ? 0.75 : 1,
57
display: width < minWidthToDisplay ? 'none' : 'block',
58
}}
59
- y={0}
60
- >
59
+ y={0}>
60
<div className={styles.Div} style={textStyle}>
61
{label}
62
</div>
packages/react-devtools-shared/src/devtools/views/Profiler/ClearProfilingDataButton.js
+6
-7
@@ -1,15 +1,15 @@
1
// @flow
2
3
-import React, { useCallback, useContext } from 'react';
4
-import { ProfilerContext } from './ProfilerContext';
3
+import React, {useCallback, useContext} from 'react';
4
+import {ProfilerContext} from './ProfilerContext';
5
import Button from '../Button';
6
import ButtonIcon from '../ButtonIcon';
7
-import { StoreContext } from '../context';
7
+import {StoreContext} from '../context';
8
9
export default function ClearProfilingDataButton() {
10
const store = useContext(StoreContext);
11
- const { didRecordCommits, isProfiling } = useContext(ProfilerContext);
12
- const { profilerStore } = store;
11
+ const {didRecordCommits, isProfiling} = useContext(ProfilerContext);
12
+ const {profilerStore} = store;
13
14
const clear = useCallback(() => profilerStore.clear(), [profilerStore]);
15
@@ -17,8 +17,7 @@ export default function ClearProfilingDataButton() {
17
<Button
18
disabled={isProfiling || !didRecordCommits}
19
onClick={clear}
20
- title="Clear profiling data"
21
- >
20
+ title="Clear profiling data">
21
<ButtonIcon type="clear" />
22
</Button>
23
);
packages/react-devtools-shared/src/devtools/views/Profiler/CommitFlamegraph.js
+51
-47
@@ -1,19 +1,19 @@
1
// @flow
2
3
-import React, { forwardRef, useCallback, useContext, useMemo } from 'react';
3
+import React, {forwardRef, useCallback, useContext, useMemo} from 'react';
4
import AutoSizer from 'react-virtualized-auto-sizer';
5
-import { FixedSizeList } from 'react-window';
6
-import { ProfilerContext } from './ProfilerContext';
5
+import {FixedSizeList} from 'react-window';
6
+import {ProfilerContext} from './ProfilerContext';
7
import NoCommitData from './NoCommitData';
8
import CommitFlamegraphListItem from './CommitFlamegraphListItem';
9
-import { scale } from './utils';
10
-import { StoreContext } from '../context';
11
-import { SettingsContext } from '../Settings/SettingsContext';
9
+import {scale} from './utils';
10
+import {StoreContext} from '../context';
11
+import {SettingsContext} from '../Settings/SettingsContext';
12
13
import styles from './CommitFlamegraph.css';
14
15
-import type { ChartData, ChartNode } from './FlamegraphChartBuilder';
16
-import type { CommitTree } from './types';
15
+import type {ChartData, ChartNode} from './FlamegraphChartBuilder';
16
+import type {CommitTree} from './types';
17
18
export type ItemData = {|
19
chartData: ChartData,
@@ -25,18 +25,18 @@ export type ItemData = {|
25
|};
26
27
export default function CommitFlamegraphAutoSizer(_: {||}) {
28
- const { profilerStore } = useContext(StoreContext);
29
- const { rootID, selectedCommitIndex, selectFiber } = useContext(
30
- ProfilerContext
28
+ const {profilerStore} = useContext(StoreContext);
29
+ const {rootID, selectedCommitIndex, selectFiber} = useContext(
30
+ ProfilerContext,
31
);
32
- const { profilingCache } = profilerStore;
32
+ const {profilingCache} = profilerStore;
33
34
const deselectCurrentFiber = useCallback(
35
event => {
36
event.stopPropagation();
37
selectFiber(null, null);
38
},
39
- [selectFiber]
39
+ [selectFiber],
40
);
41
42
let commitTree: CommitTree | null = null;
@@ -58,7 +58,7 @@ export default function CommitFlamegraphAutoSizer(_: {||}) {
58
return (
59
<div className={styles.Container} onClick={deselectCurrentFiber}>
60
<AutoSizer>
61
- {({ height, width }) => (
61
+ {({height, width}) => (
62
// Force Flow types to avoid checking for `null` here because there's no static proof that
63
// by the time this render prop function is called, the values of the `let` variables have not changed.
64
<CommitFlamegraph
@@ -83,33 +83,39 @@ type Props = {|
83
width: number,
84
|};
85
86
-function CommitFlamegraph({ chartData, commitTree, height, width }: Props) {
87
- const { lineHeight } = useContext(SettingsContext);
88
- const { selectFiber, selectedFiberID } = useContext(ProfilerContext);
89
-
90
- const selectedChartNodeIndex = useMemo<number>(() => {
91
- if (selectedFiberID === null) {
92
- return 0;
93
- }
94
- // The selected node might not be in the tree for this commit,
95
- // so it's important that we have a fallback plan.
96
- const depth = chartData.idToDepthMap.get(selectedFiberID);
97
- return depth !== undefined ? depth - 1 : 0;
98
- }, [chartData, selectedFiberID]);
99
-
100
- const selectedChartNode = useMemo(() => {
101
- let chartNode = null;
102
- if (selectedFiberID !== null) {
103
- const foundChartNode = chartData.rows[selectedChartNodeIndex].find(
104
- chartNode => chartNode.id === selectedFiberID
105
- );
106
-
107
- if (foundChartNode !== undefined) {
108
- chartNode = foundChartNode;
86
+function CommitFlamegraph({chartData, commitTree, height, width}: Props) {
87
+ const {lineHeight} = useContext(SettingsContext);
88
+ const {selectFiber, selectedFiberID} = useContext(ProfilerContext);
89
+
90
+ const selectedChartNodeIndex = useMemo<number>(
91
+ () => {
92
+ if (selectedFiberID === null) {
93
+ return 0;
94
}
110
- }
111
- return chartNode;
112
- }, [chartData, selectedFiberID, selectedChartNodeIndex]);
95
+ // The selected node might not be in the tree for this commit,
96
+ // so it's important that we have a fallback plan.
97
+ const depth = chartData.idToDepthMap.get(selectedFiberID);
98
+ return depth !== undefined ? depth - 1 : 0;
99
+ },
100
+ [chartData, selectedFiberID],
101
+ );
102
+
103
+ const selectedChartNode = useMemo(
104
+ () => {
105
+ let chartNode = null;
106
+ if (selectedFiberID !== null) {
107
+ const foundChartNode = chartData.rows[selectedChartNodeIndex].find(
108
+ chartNode => chartNode.id === selectedFiberID,
109
+ );
110
+
111
+ if (foundChartNode !== undefined) {
112
+ chartNode = foundChartNode;
113
+ }
114
+ }
115
+ return chartNode;
116
+ },
117
+ [chartData, selectedFiberID, selectedChartNodeIndex],
118
+ );
119
120
const itemData = useMemo<ItemData>(
121
() => ({
@@ -120,14 +126,14 @@ function CommitFlamegraph({ chartData, commitTree, height, width }: Props) {
126
? selectedChartNode.treeBaseDuration
127
: chartData.baseDuration,
128
0,
123
- width
129
+ width,
130
),
131
selectedChartNode,
132
selectedChartNodeIndex,
133
selectFiber,
134
width,
135
}),
130
- [chartData, selectedChartNode, selectedChartNodeIndex, selectFiber, width]
136
+ [chartData, selectedChartNode, selectedChartNodeIndex, selectFiber, width],
137
);
138
139
return (
@@ -137,22 +143,20 @@ function CommitFlamegraph({ chartData, commitTree, height, width }: Props) {
143
itemCount={chartData.depth}
144
itemData={itemData}
145
itemSize={lineHeight}
140
- width={width}
141
- >
146
+ width={width}>
147
{CommitFlamegraphListItem}
148
</FixedSizeList>
149
);
150
}
151
147
-const InnerElementType = forwardRef(({ children, ...rest }, ref) => (
152
+const InnerElementType = forwardRef(({children, ...rest}, ref) => (
153
<svg ref={ref} {...rest}>
154
<defs>
155
<pattern
156
id="didNotRenderPattern"
157
patternUnits="userSpaceOnUse"
158
width="4"
154
- height="4"
155
- >
159
+ height="4">
160
<path
161
d="M-1,1 l2,-2 M0,4 l4,-4 M3,5 l2,-2"
162
className={styles.PatternPath}
packages/react-devtools-shared/src/devtools/views/Profiler/CommitFlamegraphListItem.js
+12
-12
@@ -1,13 +1,13 @@
1
// @flow
2
3
-import React, { Fragment, memo, useCallback, useContext } from 'react';
4
-import { areEqual } from 'react-window';
5
-import { barWidthThreshold } from './constants';
6
-import { getGradientColor } from './utils';
3
+import React, {Fragment, memo, useCallback, useContext} from 'react';
4
+import {areEqual} from 'react-window';
5
+import {barWidthThreshold} from './constants';
6
+import {getGradientColor} from './utils';
7
import ChartNode from './ChartNode';
8
-import { SettingsContext } from '../Settings/SettingsContext';
8
+import {SettingsContext} from '../Settings/SettingsContext';
9
10
-import type { ItemData } from './CommitFlamegraph';
10
+import type {ItemData} from './CommitFlamegraph';
11
12
type Props = {
13
data: ItemData,
@@ -15,7 +15,7 @@ type Props = {
15
style: Object,
16
};
17
18
-function CommitFlamegraphListItem({ data, index, style }: Props) {
18
+function CommitFlamegraphListItem({data, index, style}: Props) {
19
const {
20
chartData,
21
scaleX,
@@ -24,15 +24,15 @@ function CommitFlamegraphListItem({ data, index, style }: Props) {
24
selectFiber,
25
width,
26
} = data;
27
- const { renderPathNodes, maxSelfDuration, rows } = chartData;
27
+ const {renderPathNodes, maxSelfDuration, rows} = chartData;
28
29
- const { lineHeight } = useContext(SettingsContext);
29
+ const {lineHeight} = useContext(SettingsContext);
30
const handleClick = useCallback(
31
(event: SyntheticMouseEvent<*>, id: number, name: string) => {
32
event.stopPropagation();
33
selectFiber(id, name);
34
},
35
- [selectFiber]
35
+ [selectFiber],
36
);
37
38
// List items are absolutely positioned using the CSS "top" attribute.
@@ -45,7 +45,7 @@ function CommitFlamegraphListItem({ data, index, style }: Props) {
45
46
let selectedNodeOffset = scaleX(
47
selectedChartNode !== null ? selectedChartNode.offset : 0,
48
- width
48
+ width,
49
);
50
51
return (
@@ -96,7 +96,7 @@ function CommitFlamegraphListItem({ data, index, style }: Props) {
96
key={id}
97
label={label}
98
onClick={event => handleClick(event, id, name)}
99
- textStyle={{ color: textColor }}
99
+ textStyle={{color: textColor}}
100
width={nodeWidth}
101
x={nodeOffset - selectedNodeOffset}
102
y={top}
packages/react-devtools-shared/src/devtools/views/Profiler/CommitRanked.js
+21
-22
@@ -1,19 +1,19 @@
1
// @flow
2
3
-import React, { useCallback, useContext, useMemo } from 'react';
3
+import React, {useCallback, useContext, useMemo} from 'react';
4
import AutoSizer from 'react-virtualized-auto-sizer';
5
-import { FixedSizeList } from 'react-window';
6
-import { ProfilerContext } from './ProfilerContext';
5
+import {FixedSizeList} from 'react-window';
6
+import {ProfilerContext} from './ProfilerContext';
7
import NoCommitData from './NoCommitData';
8
import CommitRankedListItem from './CommitRankedListItem';
9
-import { scale } from './utils';
10
-import { StoreContext } from '../context';
11
-import { SettingsContext } from '../Settings/SettingsContext';
9
+import {scale} from './utils';
10
+import {StoreContext} from '../context';
11
+import {SettingsContext} from '../Settings/SettingsContext';
12
13
import styles from './CommitRanked.css';
14
15
-import type { ChartData } from './RankedChartBuilder';
16
-import type { CommitTree } from './types';
15
+import type {ChartData} from './RankedChartBuilder';
16
+import type {CommitTree} from './types';
17
18
export type ItemData = {|
19
chartData: ChartData,
@@ -25,18 +25,18 @@ export type ItemData = {|
25
|};
26
27
export default function CommitRankedAutoSizer(_: {||}) {
28
- const { profilerStore } = useContext(StoreContext);
29
- const { rootID, selectedCommitIndex, selectFiber } = useContext(
30
- ProfilerContext
28
+ const {profilerStore} = useContext(StoreContext);
29
+ const {rootID, selectedCommitIndex, selectFiber} = useContext(
30
+ ProfilerContext,
31
);
32
- const { profilingCache } = profilerStore;
32
+ const {profilingCache} = profilerStore;
33
34
const deselectCurrentFiber = useCallback(
35
event => {
36
event.stopPropagation();
37
selectFiber(null, null);
38
},
39
- [selectFiber]
39
+ [selectFiber],
40
);
41
42
let commitTree: CommitTree | null = null;
@@ -58,7 +58,7 @@ export default function CommitRankedAutoSizer(_: {||}) {
58
return (
59
<div className={styles.Container} onClick={deselectCurrentFiber}>
60
<AutoSizer>
61
- {({ height, width }) => (
61
+ {({height, width}) => (
62
<CommitRanked
63
chartData={((chartData: any): ChartData)}
64
commitTree={((commitTree: any): CommitTree)}
@@ -81,13 +81,13 @@ type Props = {|
81
width: number,
82
|};
83
84
-function CommitRanked({ chartData, commitTree, height, width }: Props) {
85
- const { lineHeight } = useContext(SettingsContext);
86
- const { selectedFiberID, selectFiber } = useContext(ProfilerContext);
84
+function CommitRanked({chartData, commitTree, height, width}: Props) {
85
+ const {lineHeight} = useContext(SettingsContext);
86
+ const {selectedFiberID, selectFiber} = useContext(ProfilerContext);
87
88
const selectedFiberIndex = useMemo(
89
() => getNodeIndex(chartData, selectedFiberID),
90
- [chartData, selectedFiberID]
90
+ [chartData, selectedFiberID],
91
);
92
93
const itemData = useMemo<ItemData>(
@@ -99,7 +99,7 @@ function CommitRanked({ chartData, commitTree, height, width }: Props) {
99
selectFiber,
100
width,
101
}),
102
- [chartData, selectedFiberID, selectedFiberIndex, selectFiber, width]
102
+ [chartData, selectedFiberID, selectedFiberIndex, selectFiber, width],
103
);
104
105
return (
@@ -109,8 +109,7 @@ function CommitRanked({ chartData, commitTree, height, width }: Props) {
109
itemCount={chartData.nodes.length}
110
itemData={itemData}
111
itemSize={lineHeight}
112
- width={width}
113
- >
112
+ width={width}>
113
{CommitRankedListItem}
114
</FixedSizeList>
115
);
@@ -120,7 +119,7 @@ const getNodeIndex = (chartData: ChartData, id: number | null): number => {
119
if (id === null) {
120
return 0;
121
}
123
- const { nodes } = chartData;
122
+ const {nodes} = chartData;
123
for (let index = 0; index < nodes.length; index++) {
124
if (nodes[index].id === id) {
125
return index;
packages/react-devtools-shared/src/devtools/views/Profiler/CommitRankedListItem.js
+10
-10
@@ -1,13 +1,13 @@
1
// @flow
2
3
-import React, { memo, useCallback, useContext } from 'react';
4
-import { areEqual } from 'react-window';
5
-import { minBarWidth } from './constants';
6
-import { getGradientColor } from './utils';
3
+import React, {memo, useCallback, useContext} from 'react';
4
+import {areEqual} from 'react-window';
5
+import {minBarWidth} from './constants';
6
+import {getGradientColor} from './utils';
7
import ChartNode from './ChartNode';
8
-import { SettingsContext } from '../Settings/SettingsContext';
8
+import {SettingsContext} from '../Settings/SettingsContext';
9
10
-import type { ItemData } from './CommitRanked';
10
+import type {ItemData} from './CommitRanked';
11
12
type Props = {
13
data: ItemData,
@@ -15,19 +15,19 @@ type Props = {
15
style: Object,
16
};
17
18
-function CommitRankedListItem({ data, index, style }: Props) {
19
- const { chartData, scaleX, selectedFiberIndex, selectFiber, width } = data;
18
+function CommitRankedListItem({data, index, style}: Props) {
19
+ const {chartData, scaleX, selectedFiberIndex, selectFiber, width} = data;
20
21
const node = chartData.nodes[index];
22
23
- const { lineHeight } = useContext(SettingsContext);
23
+ const {lineHeight} = useContext(SettingsContext);
24
25
const handleClick = useCallback(
26
event => {
27
event.stopPropagation();
28
selectFiber(node.id, node.name);
29
},
30
- [node, selectFiber]
30
+ [node, selectFiber],
31
);
32
33
// List items are absolutely positioned using the CSS "top" attribute.
packages/react-devtools-shared/src/devtools/views/Profiler/CommitTreeBuilder.js
+26
-26
@@ -7,11 +7,11 @@ import {
7
TREE_OPERATION_REORDER_CHILDREN,
8
TREE_OPERATION_UPDATE_TREE_BASE_DURATION,
9
} from 'react-devtools-shared/src/constants';
10
-import { utfDecodeString } from 'react-devtools-shared/src/utils';
11
-import { ElementTypeRoot } from 'react-devtools-shared/src/types';
10
+import {utfDecodeString} from 'react-devtools-shared/src/utils';
11
+import {ElementTypeRoot} from 'react-devtools-shared/src/types';
12
import ProfilerStore from 'react-devtools-shared/src/devtools/ProfilerStore';
13
14
-import type { ElementType } from 'react-devtools-shared/src/types';
14
+import type {ElementType} from 'react-devtools-shared/src/types';
15
import type {
16
CommitTree,
17
CommitTreeNode,
@@ -24,7 +24,7 @@ const debug = (methodName, ...args) => {
24
`%cCommitTreeBuilder %c${methodName}`,
25
'color: pink; font-weight: bold;',
26
'font-weight: bold;',
27
- ...args
27
+ ...args,
28
);
29
}
30
};
@@ -44,15 +44,15 @@ export function getCommitTree({
44
rootToCommitTreeMap.set(rootID, []);
45
}
46
47
- const commitTrees = ((rootToCommitTreeMap.get(
48
- rootID
49
- ): any): Array<CommitTree>);
47
+ const commitTrees = ((rootToCommitTreeMap.get(rootID): any): Array<
48
+ CommitTree,
49
+ >);
50
51
if (commitIndex < commitTrees.length) {
52
return commitTrees[commitIndex];
53
}
54
55
- const { profilingData } = profilerStore;
55
+ const {profilingData} = profilerStore;
56
if (profilingData === null) {
57
throw Error(`No profiling data available`);
58
}
@@ -62,7 +62,7 @@ export function getCommitTree({
62
throw Error(`Could not find profiling data for root "${rootID}"`);
63
}
64
65
- const { operations } = dataForRoot;
65
+ const {operations} = dataForRoot;
66
67
// Commits are generated sequentially and cached.
68
// If this is the very first commit, start with the cached snapshot and apply the first mutation.
@@ -75,7 +75,7 @@ export function getCommitTree({
75
76
// Mutate the tree
77
if (operations != null && commitIndex < operations.length) {
78
- const commitTree = updateTree({ nodes, rootID }, operations[commitIndex]);
78
+ const commitTree = updateTree({nodes, rootID}, operations[commitIndex]);
79
80
if (__DEBUG__) {
81
__printTree(commitTree);
@@ -94,7 +94,7 @@ export function getCommitTree({
94
if (operations != null && commitIndex < operations.length) {
95
const commitTree = updateTree(
96
previousCommitTree,
97
- operations[commitIndex]
97
+ operations[commitIndex],
98
);
99
100
if (__DEBUG__) {
@@ -107,7 +107,7 @@ export function getCommitTree({
107
}
108
109
throw Error(
110
- `getCommitTree(): Unable to reconstruct tree for root "${rootID}" and commit ${commitIndex}`
110
+ `getCommitTree(): Unable to reconstruct tree for root "${rootID}" and commit ${commitIndex}`,
111
);
112
}
113
@@ -115,7 +115,7 @@ function recursivelyInitializeTree(
115
id: number,
116
parentID: number,
117
nodes: Map<number, CommitTreeNode>,
118
- dataForRoot: ProfilingDataForRootFrontend
118
+ dataForRoot: ProfilingDataForRootFrontend,
119
): void {
120
const node = dataForRoot.snapshots.get(id);
121
if (node != null) {
@@ -126,20 +126,20 @@ function recursivelyInitializeTree(
126
key: node.key,
127
parentID,
128
treeBaseDuration: ((dataForRoot.initialTreeBaseDurations.get(
129
- id
129
+ id,
130
): any): number),
131
type: node.type,
132
});
133
134
node.children.forEach(childID =>
135
- recursivelyInitializeTree(childID, id, nodes, dataForRoot)
135
+ recursivelyInitializeTree(childID, id, nodes, dataForRoot),
136
);
137
}
138
}
139
140
function updateTree(
141
commitTree: CommitTree,
142
- operations: Array<number>
142
+ operations: Array<number>,
143
): CommitTree {
144
// Clone the original tree so edits don't affect it.
145
const nodes = new Map(commitTree.nodes);
@@ -148,7 +148,7 @@ function updateTree(
148
const getClonedNode = (id: number): CommitTreeNode => {
149
const clonedNode = ((Object.assign(
150
{},
151
- nodes.get(id)
151
+ nodes.get(id),
152
): any): CommitTreeNode);
153
nodes.set(id, clonedNode);
154
return clonedNode;
@@ -165,7 +165,7 @@ function updateTree(
165
while (i < stringTableEnd) {
166
const nextLength = operations[i++];
167
const nextString = utfDecodeString(
168
- (operations.slice(i, i + nextLength): any)
168
+ (operations.slice(i, i + nextLength): any),
169
);
170
stringTable.push(nextString);
171
i += nextLength;
@@ -185,7 +185,7 @@ function updateTree(
185
throw new Error(
186
'Commit tree already contains fiber ' +
187
id +
188
- '. This is a bug in React DevTools.'
188
+ '. This is a bug in React DevTools.',
189
);
190
}
191
@@ -225,7 +225,7 @@ function updateTree(
225
if (__DEBUG__) {
226
debug(
227
'Add',
228
- `fiber ${id} (${displayName || 'null'}) as child of ${parentID}`
228
+ `fiber ${id} (${displayName || 'null'}) as child of ${parentID}`,
229
);
230
}
231
@@ -258,7 +258,7 @@ function updateTree(
258
throw new Error(
259
'Commit tree does not contain fiber ' +
260
id +
261
- '. This is a bug in React DevTools.'
261
+ '. This is a bug in React DevTools.',
262
);
263
}
264
@@ -277,7 +277,7 @@ function updateTree(
277
}
278
279
parentNode.children = parentNode.children.filter(
280
- childID => childID !== id
280
+ childID => childID !== id,
281
);
282
}
283
}
@@ -288,7 +288,7 @@ function updateTree(
288
const numChildren = ((operations[i + 2]: any): number);
289
const children = ((operations.slice(
290
i + 3,
291
- i + 3 + numChildren
291
+ i + 3 + numChildren,
292
): any): Array<number>);
293
294
i = i + 3 + numChildren;
@@ -311,7 +311,7 @@ function updateTree(
311
if (__DEBUG__) {
312
debug(
313
'Update',
314
- `fiber ${id} treeBaseDuration to ${node.treeBaseDuration}`
314
+ `fiber ${id} treeBaseDuration to ${node.treeBaseDuration}`,
315
);
316
}
317
@@ -336,7 +336,7 @@ export function invalidateCommitTrees(): void {
336
// DEBUG
337
const __printTree = (commitTree: CommitTree) => {
338
if (__DEBUG__) {
339
- const { nodes, rootID } = commitTree;
339
+ const {nodes, rootID} = commitTree;
340
console.group('__printTree()');
341
const queue = [rootID, 0];
342
while (queue.length > 0) {
@@ -351,7 +351,7 @@ const __printTree = (commitTree: CommitTree) => {
351
console.log(
352
`${'•'.repeat(depth)}${node.id}:${node.displayName || ''} ${
353
node.key ? `key:"${node.key}"` : ''
354
- } (${node.treeBaseDuration})`
354
+ } (${node.treeBaseDuration})`,
355
);
356
357
node.children.forEach(childID => {
packages/react-devtools-shared/src/devtools/views/Profiler/FlamegraphChartBuilder.js
+11
-8
@@ -1,10 +1,13 @@
1
// @flow
2
3
-import { ElementTypeForwardRef, ElementTypeMemo } from 'react-devtools-shared/src/types';
4
-import { formatDuration } from './utils';
3
+import {
4
+ ElementTypeForwardRef,
5
+ ElementTypeMemo,
6
+} from 'react-devtools-shared/src/types';
7
+import {formatDuration} from './utils';
8
import ProfilerStore from 'react-devtools-shared/src/devtools/ProfilerStore';
9
7
-import type { CommitTree } from './types';
10
+import type {CommitTree} from './types';
11
12
export type ChartNode = {|
13
actualDuration: number,
@@ -41,8 +44,8 @@ export function getChartData({
44
|}): ChartData {
45
const commitDatum = profilerStore.getCommitData(rootID, commitIndex);
46
44
- const { fiberActualDurations, fiberSelfDurations } = commitDatum;
45
- const { nodes } = commitTree;
47
+ const {fiberActualDurations, fiberSelfDurations} = commitDatum;
48
+ const {nodes} = commitTree;
49
50
const key = `${rootID}-${commitIndex}`;
51
if (cachedChartData.has(key)) {
@@ -65,7 +68,7 @@ export function getChartData({
68
throw Error(`Could not find node with id "${id}" in commit tree`);
69
}
70
68
- const { children, displayName, key, treeBaseDuration, type } = node;
71
+ const {children, displayName, key, treeBaseDuration, type} = node;
72
73
const actualDuration = fiberActualDurations.get(id) || 0;
74
const selfDuration = fiberSelfDurations.get(id) || 0;
@@ -84,7 +87,7 @@ export function getChartData({
87
let label = `${name}${maybeBadge}${maybeKey}`;
88
if (didRender) {
89
label += ` (${formatDuration(selfDuration)}ms of ${formatDuration(
87
- actualDuration
90
+ actualDuration,
91
)}ms)`;
92
}
93
@@ -125,7 +128,7 @@ export function getChartData({
128
const root = nodes.get(rootID);
129
if (root == null) {
130
throw Error(
128
- `Could not find root node with id "${rootID}" in commit tree`
131
+ `Could not find root node with id "${rootID}" in commit tree`,
132
);
133
}
134
packages/react-devtools-shared/src/devtools/views/Profiler/InteractionListItem.js
+19
-18
@@ -1,12 +1,12 @@
1
// @flow
2
3
-import React, { memo, useCallback } from 'react';
4
-import { areEqual } from 'react-window';
5
-import { getGradientColor } from './utils';
3
+import React, {memo, useCallback} from 'react';
4
+import {areEqual} from 'react-window';
5
+import {getGradientColor} from './utils';
6
7
import styles from './InteractionListItem.css';
8
9
-import type { ItemData } from './Interactions';
9
+import type {ItemData} from './Interactions';
10
11
type Props = {
12
data: ItemData,
@@ -14,7 +14,7 @@ type Props = {
14
style: Object,
15
};
16
17
-function InteractionListItem({ data: itemData, index, style }: Props) {
17
+function InteractionListItem({data: itemData, index, style}: Props) {
18
const {
19
chartData,
20
dataForRoot,
@@ -26,17 +26,20 @@ function InteractionListItem({ data: itemData, index, style }: Props) {
26
selectTab,
27
} = itemData;
28
29
- const { commitData, interactionCommits } = dataForRoot;
30
- const { interactions, lastInteractionTime, maxCommitDuration } = chartData;
29
+ const {commitData, interactionCommits} = dataForRoot;
30
+ const {interactions, lastInteractionTime, maxCommitDuration} = chartData;
31
32
const interaction = interactions[index];
33
if (interaction == null) {
34
throw Error(`Could not find interaction #${index}`);
35
}
36
37
- const handleClick = useCallback(() => {
38
- selectInteraction(interaction.id);
39
- }, [interaction, selectInteraction]);
37
+ const handleClick = useCallback(
38
+ () => {
39
+ selectInteraction(interaction.id);
40
+ },
41
+ [interaction, selectInteraction],
42
+ );
43
44
const commits = interactionCommits.get(interaction.id) || [];
45
@@ -56,13 +59,11 @@ function InteractionListItem({ data: itemData, index, style }: Props) {
59
: styles.Interaction
60
}
61
onClick={handleClick}
59
- style={style}
60
- >
62
+ style={style}>
63
<div
64
className={styles.Name}
63
- style={{ maxWidth: labelWidth }}
64
- title={interaction.name}
65
- >
65
+ style={{maxWidth: labelWidth}}
66
+ title={interaction.name}>
67
{interaction.name}
68
</div>
69
<div
@@ -83,9 +84,9 @@ function InteractionListItem({ data: itemData, index, style }: Props) {
84
1,
85
Math.max(
86
0,
86
- commitData[commitIndex].duration / maxCommitDuration
87
- )
88
- ) || 0
87
+ commitData[commitIndex].duration / maxCommitDuration,
88
+ ),
89
+ ) || 0,
90
),
91
left: labelWidth + scaleX(commitData[commitIndex].timestamp, 0),
92
}}
packages/react-devtools-shared/src/devtools/views/Profiler/Interactions.js
+48
-46
@@ -1,19 +1,19 @@
1
// @flow
2
3
-import React, { useCallback, useContext, useMemo } from 'react';
3
+import React, {useCallback, useContext, useMemo} from 'react';
4
import AutoSizer from 'react-virtualized-auto-sizer';
5
-import { FixedSizeList } from 'react-window';
6
-import { ProfilerContext } from './ProfilerContext';
5
+import {FixedSizeList} from 'react-window';
6
+import {ProfilerContext} from './ProfilerContext';
7
import InteractionListItem from './InteractionListItem';
8
import NoInteractions from './NoInteractions';
9
-import { StoreContext } from '../context';
10
-import { scale } from './utils';
9
+import {StoreContext} from '../context';
10
+import {scale} from './utils';
11
12
import styles from './Interactions.css';
13
14
-import type { ProfilingDataForRootFrontend } from './types';
15
-import type { ChartData } from './InteractionsChartBuilder';
16
-import type { TabID } from './ProfilerContext';
14
+import type {ProfilingDataForRootFrontend} from './types';
15
+import type {ChartData} from './InteractionsChartBuilder';
16
+import type {TabID} from './ProfilerContext';
17
18
export type ItemData = {|
19
chartData: ChartData,
@@ -30,13 +30,13 @@ export default function InteractionsAutoSizer(_: {||}) {
30
return (
31
<div className={styles.Container}>
32
<AutoSizer>
33
- {({ height, width }) => <Interactions height={height} width={width} />}
33
+ {({height, width}) => <Interactions height={height} width={width} />}
34
</AutoSizer>
35
</div>
36
);
37
}
38
39
-function Interactions({ height, width }: {| height: number, width: number |}) {
39
+function Interactions({height, width}: {|height: number, width: number|}) {
40
const {
41
rootID,
42
selectedInteractionID,
@@ -44,8 +44,8 @@ function Interactions({ height, width }: {| height: number, width: number |}) {
44
selectCommitIndex,
45
selectTab,
46
} = useContext(ProfilerContext);
47
- const { profilerStore } = useContext(StoreContext);
48
- const { profilingCache } = profilerStore;
47
+ const {profilerStore} = useContext(StoreContext);
48
+ const {profilingCache} = profilerStore;
49
50
const dataForRoot = profilerStore.getDataForRoot(((rootID: any): number));
51
@@ -53,7 +53,7 @@ function Interactions({ height, width }: {| height: number, width: number |}) {
53
rootID: ((rootID: any): number),
54
});
55
56
- const { interactions } = chartData;
56
+ const {interactions} = chartData;
57
58
const handleKeyDown = useCallback(
59
event => {
@@ -61,14 +61,14 @@ function Interactions({ height, width }: {| height: number, width: number |}) {
61
switch (event.key) {
62
case 'ArrowDown':
63
index = interactions.findIndex(
64
- interaction => interaction.id === selectedInteractionID
64
+ interaction => interaction.id === selectedInteractionID,
65
);
66
selectInteraction(Math.min(interactions.length - 1, index + 1));
67
event.stopPropagation();
68
break;
69
case 'ArrowUp':
70
index = interactions.findIndex(
71
- interaction => interaction.id === selectedInteractionID
71
+ interaction => interaction.id === selectedInteractionID,
72
);
73
selectInteraction(Math.max(0, index - 1));
74
event.stopPropagation();
@@ -77,45 +77,48 @@ function Interactions({ height, width }: {| height: number, width: number |}) {
77
break;
78
}
79
},
80
- [interactions, selectedInteractionID, selectInteraction]
80
+ [interactions, selectedInteractionID, selectInteraction],
81
);
82
83
- const itemData = useMemo<ItemData>(() => {
84
- const interactionCommitSize = parseInt(
85
- getComputedStyle((document.body: any)).getPropertyValue(
86
- '--interaction-commit-size'
87
- ),
88
- 10
89
- );
90
- const interactionLabelWidth = parseInt(
91
- getComputedStyle((document.body: any)).getPropertyValue(
92
- '--interaction-label-width'
93
- ),
94
- 10
95
- );
83
+ const itemData = useMemo<ItemData>(
84
+ () => {
85
+ const interactionCommitSize = parseInt(
86
+ getComputedStyle((document.body: any)).getPropertyValue(
87
+ '--interaction-commit-size',
88
+ ),
89
+ 10,
90
+ );
91
+ const interactionLabelWidth = parseInt(
92
+ getComputedStyle((document.body: any)).getPropertyValue(
93
+ '--interaction-label-width',
94
+ ),
95
+ 10,
96
+ );
97
97
- const labelWidth = Math.min(interactionLabelWidth, width / 5);
98
- const timelineWidth = width - labelWidth - interactionCommitSize;
98
+ const labelWidth = Math.min(interactionLabelWidth, width / 5);
99
+ const timelineWidth = width - labelWidth - interactionCommitSize;
100
100
- return {
101
+ return {
102
+ chartData,
103
+ dataForRoot,
104
+ labelWidth,
105
+ scaleX: scale(0, chartData.lastInteractionTime, 0, timelineWidth),
106
+ selectedInteractionID,
107
+ selectCommitIndex,
108
+ selectInteraction,
109
+ selectTab,
110
+ };
111
+ },
112
+ [
113
chartData,
114
dataForRoot,
103
- labelWidth,
104
- scaleX: scale(0, chartData.lastInteractionTime, 0, timelineWidth),
115
selectedInteractionID,
116
selectCommitIndex,
117
selectInteraction,
118
selectTab,
109
- };
110
- }, [
111
- chartData,
112
- dataForRoot,
113
- selectedInteractionID,
114
- selectCommitIndex,
115
- selectInteraction,
116
- selectTab,
117
- width,
118
- ]);
119
+ width,
120
+ ],
121
+ );
122
123
// If a commit contains no fibers with an actualDuration > 0,
124
// Display a fallback message.
@@ -130,8 +133,7 @@ function Interactions({ height, width }: {| height: number, width: number |}) {
133
itemCount={interactions.length}
134
itemData={itemData}
135
itemSize={30}
133
- width={width}
134
- >
136
+ width={width}>
137
{InteractionListItem}
138
</FixedSizeList>
139
</div>
packages/react-devtools-shared/src/devtools/views/Profiler/InteractionsChartBuilder.js
+2
-2
@@ -2,7 +2,7 @@
2
3
import ProfilerStore from 'react-devtools-shared/src/devtools/ProfilerStore';
4
5
-import type { Interaction } from './types';
5
+import type {Interaction} from './types';
6
7
export type ChartData = {|
8
interactions: Array<Interaction>,
@@ -28,7 +28,7 @@ export function getChartData({
28
throw Error(`Could not find profiling data for root "${rootID}"`);
29
}
30
31
- const { commitData, interactions } = dataForRoot;
31
+ const {commitData, interactions} = dataForRoot;
32
33
const lastInteractionTime =
34
commitData.length > 0 ? commitData[commitData.length - 1].timestamp : 0;
packages/react-devtools-shared/src/devtools/views/Profiler/NoInteractions.js
+2
-3
@@ -12,15 +12,14 @@ export default function NoInteractions({
12
width: number,
13
|}) {
14
return (
15
- <div className={styles.NoInteractions} style={{ height, width }}>
15
+ <div className={styles.NoInteractions} style={{height, width}}>
16
<p className={styles.Header}>No interactions were recorded.</p>
17
<p>
18
<a
19
className={styles.Link}
20
href="http://fb.me/react-interaction-tracing"
21
rel="noopener noreferrer"
22
- target="_blank"
23
- >
22
+ target="_blank">
23
Learn more about the interaction tracing API here.
24
</a>
25
</p>
packages/react-devtools-shared/src/devtools/views/Profiler/Profiler.js
+5
-6
@@ -1,8 +1,8 @@
1
// @flow
2
3
-import React, { Fragment, useContext } from 'react';
4
-import { ModalDialog } from '../ModalDialog';
5
-import { ProfilerContext } from './ProfilerContext';
3
+import React, {Fragment, useContext} from 'react';
4
+import {ModalDialog} from '../ModalDialog';
5
+import {ProfilerContext} from './ProfilerContext';
6
import TabBar from '../TabBar';
7
import ClearProfilingDataButton from './ClearProfilingDataButton';
8
import CommitFlamegraph from './CommitFlamegraph';
@@ -18,7 +18,7 @@ import SidebarInteractions from './SidebarInteractions';
18
import SidebarSelectedFiberInfo from './SidebarSelectedFiberInfo';
19
import SettingsModal from 'react-devtools-shared/src/devtools/views/Settings/SettingsModal';
20
import SettingsModalContextToggle from 'react-devtools-shared/src/devtools/views/Settings/SettingsModalContextToggle';
21
-import { SettingsModalContextController } from 'react-devtools-shared/src/devtools/views/Settings/SettingsModalContext';
21
+import {SettingsModalContextController} from 'react-devtools-shared/src/devtools/views/Settings/SettingsModalContext';
22
import portaledContent from '../portaledContent';
23
24
import styles from './Profiler.css';
@@ -160,8 +160,7 @@ const ProfilingNotSupported = () => (
160
className={styles.Link}
161
href="https://fb.me/react-profiling"
162
rel="noopener noreferrer"
163
- target="_blank"
164
- >
163
+ target="_blank">
164
fb.me/react-profiling
165
</a>
166
.
packages/react-devtools-shared/src/devtools/views/Profiler/ProfilerContext.js
+18
-19
@@ -7,16 +7,16 @@ import React, {
7
useMemo,
8
useState,
9
} from 'react';
10
-import { unstable_batchedUpdates as batchedUpdates } from 'react-dom';
11
-import { useLocalStorage, useSubscription } from '../hooks';
10
+import {unstable_batchedUpdates as batchedUpdates} from 'react-dom';
11
+import {useLocalStorage, useSubscription} from '../hooks';
12
import {
13
TreeDispatcherContext,
14
TreeStateContext,
15
} from '../Components/TreeContext';
16
-import { StoreContext } from '../context';
16
+import {StoreContext} from '../context';
17
import Store from '../../store';
18
19
-import type { ProfilingDataFrontend } from './types';
19
+import type {ProfilingDataFrontend} from './types';
20
21
export type TabID = 'flame-chart' | 'ranked-chart' | 'interactions';
22
@@ -84,12 +84,12 @@ type Props = {|
84
children: React$Node,
85
|};
86
87
-function ProfilerContextController({ children }: Props) {
87
+function ProfilerContextController({children}: Props) {
88
const store = useContext(StoreContext);
89
- const { selectedElementID } = useContext(TreeStateContext);
89
+ const {selectedElementID} = useContext(TreeStateContext);
90
const dispatch = useContext(TreeDispatcherContext);
91
92
- const { profilerStore } = store;
92
+ const {profilerStore} = store;
93
94
const subscription = useMemo(
95
() => ({
@@ -113,7 +113,7 @@ function ProfilerContextController({ children }: Props) {
113
};
114
},
115
}),
116
- [profilerStore, store]
116
+ [profilerStore, store],
117
);
118
const {
119
didRecordCommits,
@@ -153,29 +153,28 @@ function ProfilerContextController({ children }: Props) {
153
154
const startProfiling = useCallback(
155
() => store.profilerStore.startProfiling(),
156
- [store]
156
+ [store],
157
);
158
const stopProfiling = useCallback(() => store.profilerStore.stopProfiling(), [
159
store,
160
]);
161
162
- const [
163
- isCommitFilterEnabled,
164
- setIsCommitFilterEnabled,
165
- ] = useLocalStorage<boolean>('React::DevTools::isCommitFilterEnabled', false);
162
+ const [isCommitFilterEnabled, setIsCommitFilterEnabled] = useLocalStorage<
163
+ boolean,
164
+ >('React::DevTools::isCommitFilterEnabled', false);
165
const [minCommitDuration, setMinCommitDuration] = useLocalStorage<number>(
166
'minCommitDuration',
168
- 0
167
+ 0,
168
);
169
170
const [selectedCommitIndex, selectCommitIndex] = useState<number | null>(
172
- null
171
+ null,
172
);
173
const [selectedTabID, selectTab] = useState<TabID>('flame-chart');
174
const [selectedFiberID, selectFiberID] = useState<number | null>(null);
175
const [selectedFiberName, selectFiberName] = useState<string | null>(null);
176
const [selectedInteractionID, selectInteraction] = useState<number | null>(
178
- null
177
+ null,
178
);
179
180
const selectFiber = useCallback(
@@ -197,7 +196,7 @@ function ProfilerContextController({ children }: Props) {
196
}
197
}
198
},
200
- [dispatch, selectFiberID, selectFiberName, store]
199
+ [dispatch, selectFiberID, selectFiberName, store],
200
);
201
202
if (isProfiling) {
@@ -275,7 +274,7 @@ function ProfilerContextController({ children }: Props) {
274
275
selectedInteractionID,
276
selectInteraction,
278
- ]
277
+ ],
278
);
279
280
return (
@@ -285,4 +284,4 @@ function ProfilerContextController({ children }: Props) {
284
);
285
}
286
288
-export { ProfilerContext, ProfilerContextController };
287
+export {ProfilerContext, ProfilerContextController};
packages/react-devtools-shared/src/devtools/views/Profiler/ProfilingImportExportButtons.js
+74
-70
@@ -1,56 +1,59 @@
1
// @flow
2
3
-import React, { Fragment, useContext, useCallback, useRef } from 'react';
4
-import { ProfilerContext } from './ProfilerContext';
5
-import { ModalDialogContext } from '../ModalDialog';
3
+import React, {Fragment, useContext, useCallback, useRef} from 'react';
4
+import {ProfilerContext} from './ProfilerContext';
5
+import {ModalDialogContext} from '../ModalDialog';
6
import Button from '../Button';
7
import ButtonIcon from '../ButtonIcon';
8
-import { StoreContext } from '../context';
8
+import {StoreContext} from '../context';
9
import {
10
prepareProfilingDataExport,
11
prepareProfilingDataFrontendFromExport,
12
} from './utils';
13
-import { downloadFile } from '../utils';
13
+import {downloadFile} from '../utils';
14
15
import styles from './ProfilingImportExportButtons.css';
16
17
-import type { ProfilingDataExport } from './types';
17
+import type {ProfilingDataExport} from './types';
18
19
export default function ProfilingImportExportButtons() {
20
- const { isProfiling, profilingData, rootID } = useContext(ProfilerContext);
20
+ const {isProfiling, profilingData, rootID} = useContext(ProfilerContext);
21
const store = useContext(StoreContext);
22
- const { profilerStore } = store;
22
+ const {profilerStore} = store;
23
24
const inputRef = useRef<HTMLInputElement | null>(null);
25
26
- const { dispatch: modalDialogDispatch } = useContext(ModalDialogContext);
26
+ const {dispatch: modalDialogDispatch} = useContext(ModalDialogContext);
27
28
- const downloadData = useCallback(() => {
29
- if (rootID === null) {
30
- return;
31
- }
28
+ const downloadData = useCallback(
29
+ () => {
30
+ if (rootID === null) {
31
+ return;
32
+ }
33
33
- if (profilingData !== null) {
34
- const profilingDataExport = prepareProfilingDataExport(profilingData);
35
- const date = new Date();
36
- const dateString = date
37
- .toLocaleDateString(undefined, {
38
- year: 'numeric',
39
- month: '2-digit',
40
- day: '2-digit',
41
- })
42
- .replace(/\//g, '-');
43
- const timeString = date
44
- .toLocaleTimeString(undefined, {
45
- hour12: false,
46
- })
47
- .replace(/:/g, '-');
48
- downloadFile(
49
- `profiling-data.${dateString}.${timeString}.json`,
50
- JSON.stringify(profilingDataExport, null, 2)
51
- );
52
- }
53
- }, [rootID, profilingData]);
34
+ if (profilingData !== null) {
35
+ const profilingDataExport = prepareProfilingDataExport(profilingData);
36
+ const date = new Date();
37
+ const dateString = date
38
+ .toLocaleDateString(undefined, {
39
+ year: 'numeric',
40
+ month: '2-digit',
41
+ day: '2-digit',
42
+ })
43
+ .replace(/\//g, '-');
44
+ const timeString = date
45
+ .toLocaleTimeString(undefined, {
46
+ hour12: false,
47
+ })
48
+ .replace(/:/g, '-');
49
+ downloadFile(
50
+ `profiling-data.${dateString}.${timeString}.json`,
51
+ JSON.stringify(profilingDataExport, null, 2),
52
+ );
53
+ }
54
+ },
55
+ [rootID, profilingData],
56
+ );
57
58
const uploadData = useCallback(() => {
59
if (inputRef.current !== null) {
@@ -58,38 +61,41 @@ export default function ProfilingImportExportButtons() {
61
}
62
}, []);
63
61
- const handleFiles = useCallback(() => {
62
- const input = inputRef.current;
63
- if (input !== null && input.files.length > 0) {
64
- const fileReader = new FileReader();
65
- fileReader.addEventListener('load', () => {
66
- try {
67
- const raw = ((fileReader.result: any): string);
68
- const profilingDataExport = ((JSON.parse(
69
- raw
70
- ): any): ProfilingDataExport);
71
- profilerStore.profilingData = prepareProfilingDataFrontendFromExport(
72
- profilingDataExport
73
- );
74
- } catch (error) {
75
- modalDialogDispatch({
76
- type: 'SHOW',
77
- title: 'Import failed',
78
- content: (
79
- <Fragment>
80
- <div>The profiling data you selected cannot be imported.</div>
81
- {error !== null && (
82
- <div className={styles.ErrorMessage}>{error.message}</div>
83
- )}
84
- </Fragment>
85
- ),
86
- });
87
- }
88
- });
89
- // TODO (profiling) Handle fileReader errors.
90
- fileReader.readAsText(input.files[0]);
91
- }
92
- }, [modalDialogDispatch, profilerStore]);
64
+ const handleFiles = useCallback(
65
+ () => {
66
+ const input = inputRef.current;
67
+ if (input !== null && input.files.length > 0) {
68
+ const fileReader = new FileReader();
69
+ fileReader.addEventListener('load', () => {
70
+ try {
71
+ const raw = ((fileReader.result: any): string);
72
+ const profilingDataExport = ((JSON.parse(
73
+ raw,
74
+ ): any): ProfilingDataExport);
75
+ profilerStore.profilingData = prepareProfilingDataFrontendFromExport(
76
+ profilingDataExport,
77
+ );
78
+ } catch (error) {
79
+ modalDialogDispatch({
80
+ type: 'SHOW',
81
+ title: 'Import failed',
82
+ content: (
83
+ <Fragment>
84
+ <div>The profiling data you selected cannot be imported.</div>
85
+ {error !== null && (
86
+ <div className={styles.ErrorMessage}>{error.message}</div>
87
+ )}
88
+ </Fragment>
89
+ ),
90
+ });
91
+ }
92
+ });
93
+ // TODO (profiling) Handle fileReader errors.
94
+ fileReader.readAsText(input.files[0]);
95
+ }
96
+ },
97
+ [modalDialogDispatch, profilerStore],
98
+ );
99
100
return (
101
<Fragment>
@@ -104,15 +110,13 @@ export default function ProfilingImportExportButtons() {
110
<Button
111
disabled={isProfiling}
112
onClick={uploadData}
107
- title="Load profile..."
108
- >
113
+ title="Load profile...">
114
<ButtonIcon type="import" />
115
</Button>
116
<Button
117
disabled={isProfiling || !profilerStore.didRecordCommits}
118
onClick={downloadData}
114
- title="Save profile..."
115
- >
119
+ title="Save profile...">
120
<ButtonIcon type="export" />
121
</Button>
122
</Fragment>
packages/react-devtools-shared/src/devtools/views/Profiler/RankedChartBuilder.js
+10
-7
@@ -1,10 +1,13 @@
1
// @flow
2
3
-import { ElementTypeForwardRef, ElementTypeMemo } from 'react-devtools-shared/src/types';
4
-import { formatDuration } from './utils';
3
+import {
4
+ ElementTypeForwardRef,
5
+ ElementTypeMemo,
6
+} from 'react-devtools-shared/src/types';
7
+import {formatDuration} from './utils';
8
import ProfilerStore from 'react-devtools-shared/src/devtools/ProfilerStore';
9
7
-import type { CommitTree } from './types';
10
+import type {CommitTree} from './types';
11
12
export type ChartNode = {|
13
id: number,
@@ -33,8 +36,8 @@ export function getChartData({
36
|}): ChartData {
37
const commitDatum = profilerStore.getCommitData(rootID, commitIndex);
38
36
- const { fiberActualDurations, fiberSelfDurations } = commitDatum;
37
- const { nodes } = commitTree;
39
+ const {fiberActualDurations, fiberSelfDurations} = commitDatum;
40
+ const {nodes} = commitTree;
41
42
const key = `${rootID}-${commitIndex}`;
43
if (cachedChartData.has(key)) {
@@ -51,7 +54,7 @@ export function getChartData({
54
throw Error(`Could not find node with id "${id}" in commit tree`);
55
}
56
54
- const { displayName, key, parentID, type } = node;
57
+ const {displayName, key, parentID, type} = node;
58
59
// Don't show the root node in this chart.
60
if (parentID === 0) {
@@ -71,7 +74,7 @@ export function getChartData({
74
}
75
76
const label = `${name}${maybeBadge}${maybeKey} (${formatDuration(
74
- selfDuration
77
+ selfDuration,
78
)}ms)`;
79
chartNodes.push({
80
id,
packages/react-devtools-shared/src/devtools/views/Profiler/RecordToggle.js
+6
-7
@@ -1,9 +1,9 @@
1
// @flow
2
3
-import React, { useContext } from 'react';
3
+import React, {useContext} from 'react';
4
import Button from '../Button';
5
import ButtonIcon from '../ButtonIcon';
6
-import { ProfilerContext } from './ProfilerContext';
6
+import {ProfilerContext} from './ProfilerContext';
7
8
import styles from './RecordToggle.css';
9
@@ -11,9 +11,9 @@ export type Props = {|
11
disabled?: boolean,
12
|};
13
14
-export default function RecordToggle({ disabled }: Props) {
15
- const { isProfiling, startProfiling, stopProfiling } = useContext(
16
- ProfilerContext
14
+export default function RecordToggle({disabled}: Props) {
15
+ const {isProfiling, startProfiling, stopProfiling} = useContext(
16
+ ProfilerContext,
17
);
18
19
let className = styles.InactiveRecordToggle;
@@ -28,8 +28,7 @@ export default function RecordToggle({ disabled }: Props) {
28
className={className}
29
disabled={disabled}
30
onClick={isProfiling ? stopProfiling : startProfiling}
31
- title={isProfiling ? 'Stop profiling' : 'Start profiling'}
32
- >
31
+ title={isProfiling ? 'Stop profiling' : 'Start profiling'}>
32
<ButtonIcon type="record" />
33
</Button>
34
);
packages/react-devtools-shared/src/devtools/views/Profiler/ReloadAndProfileButton.js
+19
-18
@@ -1,10 +1,10 @@
1
// @flow
2
3
-import React, { useCallback, useContext, useMemo } from 'react';
3
+import React, {useCallback, useContext, useMemo} from 'react';
4
import Button from '../Button';
5
import ButtonIcon from '../ButtonIcon';
6
-import { BridgeContext, StoreContext } from '../context';
7
-import { useSubscription } from '../hooks';
6
+import {BridgeContext, StoreContext} from '../context';
7
+import {useSubscription} from '../hooks';
8
import Store from 'react-devtools-shared/src/devtools/store';
9
10
type SubscriptionData = {|
@@ -31,22 +31,24 @@ export default function ReloadAndProfileButton() {
31
};
32
},
33
}),
34
- [store]
34
+ [store],
35
);
36
- const {
37
- recordChangeDescriptions,
38
- supportsReloadAndProfile,
39
- } = useSubscription<SubscriptionData>(subscription);
36
+ const {recordChangeDescriptions, supportsReloadAndProfile} = useSubscription<
37
+ SubscriptionData,
38
+ >(subscription);
39
41
- const reloadAndProfile = useCallback(() => {
42
- // TODO If we want to support reload-and-profile for e.g. React Native,
43
- // we might need to also start profiling here before reloading the app (since DevTools itself isn't reloaded).
44
- // We'd probably want to do this before reloading though, to avoid sending a message on a disconnected port in the browser.
45
- // For now, let's just skip doing it entirely to avoid paying snapshot costs for data we don't need.
46
- // startProfiling();
40
+ const reloadAndProfile = useCallback(
41
+ () => {
42
+ // TODO If we want to support reload-and-profile for e.g. React Native,
43
+ // we might need to also start profiling here before reloading the app (since DevTools itself isn't reloaded).
44
+ // We'd probably want to do this before reloading though, to avoid sending a message on a disconnected port in the browser.
45
+ // For now, let's just skip doing it entirely to avoid paying snapshot costs for data we don't need.
46
+ // startProfiling();
47
48
- bridge.send('reloadAndProfile', recordChangeDescriptions);
49
- }, [bridge, recordChangeDescriptions]);
48
+ bridge.send('reloadAndProfile', recordChangeDescriptions);
49
+ },
50
+ [bridge, recordChangeDescriptions],
51
+ );
52
53
if (!supportsReloadAndProfile) {
54
return null;
@@ -56,8 +58,7 @@ export default function ReloadAndProfileButton() {
58
<Button
59
disabled={!store.supportsProfiling}
60
onClick={reloadAndProfile}
59
- title="Reload and start profiling"
60
- >
61
+ title="Reload and start profiling">
62
<ButtonIcon type="reload" />
63
</Button>
64
);
packages/react-devtools-shared/src/devtools/views/Profiler/RootSelector.js
+6
-6
@@ -1,12 +1,12 @@
1
// @flow
2
3
-import React, { Fragment, useCallback, useContext } from 'react';
4
-import { ProfilerContext } from './ProfilerContext';
3
+import React, {Fragment, useCallback, useContext} from 'react';
4
+import {ProfilerContext} from './ProfilerContext';
5
6
import styles from './RootSelector.css';
7
8
export default function RootSelector(_: {||}) {
9
- const { profilingData, rootID, setRootID } = useContext(ProfilerContext);
9
+ const {profilingData, rootID, setRootID} = useContext(ProfilerContext);
10
11
const options = [];
12
if (profilingData !== null) {
@@ -14,16 +14,16 @@ export default function RootSelector(_: {||}) {
14
options.push(
15
<option key={rootID} value={rootID}>
16
{dataForRoot.displayName}
17
- </option>
17
+ </option>,
18
);
19
});
20
}
21
22
const handleChange = useCallback(
23
- ({ currentTarget }) => {
23
+ ({currentTarget}) => {
24
setRootID(parseInt(currentTarget.value, 10));
25
},
26
- [setRootID]
26
+ [setRootID],
27
);
28
29
if (profilingData === null || profilingData.dataForRoots.size <= 1) {
packages/react-devtools-shared/src/devtools/views/Profiler/SidebarCommitInfo.js
+7
-8
@@ -1,9 +1,9 @@
1
// @flow
2
3
-import React, { Fragment, useContext } from 'react';
4
-import { ProfilerContext } from './ProfilerContext';
5
-import { formatDuration, formatTime } from './utils';
6
-import { StoreContext } from '../context';
3
+import React, {Fragment, useContext} from 'react';
4
+import {ProfilerContext} from './ProfilerContext';
5
+import {formatDuration, formatTime} from './utils';
6
+import {StoreContext} from '../context';
7
8
import styles from './SidebarCommitInfo.css';
9
@@ -17,13 +17,13 @@ export default function SidebarCommitInfo(_: Props) {
17
selectTab,
18
} = useContext(ProfilerContext);
19
20
- const { profilerStore } = useContext(StoreContext);
20
+ const {profilerStore} = useContext(StoreContext);
21
22
if (rootID === null || selectedCommitIndex === null) {
23
return <div className={styles.NothingSelected}>Nothing selected</div>;
24
}
25
26
- const { interactions } = profilerStore.getDataForRoot(rootID);
26
+ const {interactions} = profilerStore.getDataForRoot(rootID);
27
const {
28
duration,
29
interactionIDs,
@@ -70,8 +70,7 @@ export default function SidebarCommitInfo(_: Props) {
70
<button
71
key={interactionID}
72
className={styles.Interaction}
73
- onClick={() => viewInteraction(interactionID)}
74
- >
73
+ onClick={() => viewInteraction(interactionID)}>
74
{interaction.name}
75
</button>
76
);
packages/react-devtools-shared/src/devtools/views/Profiler/SidebarInteractions.js
+16
-17
@@ -1,10 +1,10 @@
1
// @flow
2
3
-import React, { Fragment, useContext } from 'react';
4
-import { ProfilerContext } from './ProfilerContext';
5
-import { formatDuration, formatTime } from './utils';
6
-import { StoreContext } from '../context';
7
-import { getGradientColor } from './utils';
3
+import React, {Fragment, useContext} from 'react';
4
+import {ProfilerContext} from './ProfilerContext';
5
+import {formatDuration, formatTime} from './utils';
6
+import {StoreContext} from '../context';
7
+import {getGradientColor} from './utils';
8
9
import styles from './SidebarInteractions.css';
10
@@ -18,24 +18,24 @@ export default function SidebarInteractions(_: Props) {
18
selectTab,
19
} = useContext(ProfilerContext);
20
21
- const { profilerStore } = useContext(StoreContext);
22
- const { profilingCache } = profilerStore;
21
+ const {profilerStore} = useContext(StoreContext);
22
+ const {profilingCache} = profilerStore;
23
24
if (selectedInteractionID === null) {
25
return <div className={styles.NothingSelected}>Nothing selected</div>;
26
}
27
28
- const { interactionCommits, interactions } = profilerStore.getDataForRoot(
29
- ((rootID: any): number)
28
+ const {interactionCommits, interactions} = profilerStore.getDataForRoot(
29
+ ((rootID: any): number),
30
);
31
const interaction = interactions.get(selectedInteractionID);
32
if (interaction == null) {
33
throw Error(
34
- `Could not find interaction by selected interaction id "${selectedInteractionID}"`
34
+ `Could not find interaction by selected interaction id "${selectedInteractionID}"`,
35
);
36
}
37
38
- const { maxCommitDuration } = profilingCache.getInteractionsChartData({
38
+ const {maxCommitDuration} = profilingCache.getInteractionsChartData({
39
rootID: ((rootID: any): number),
40
});
41
@@ -48,22 +48,21 @@ export default function SidebarInteractions(_: Props) {
48
const commitIndices = interactionCommits.get(selectedInteractionID);
49
if (commitIndices != null) {
50
commitIndices.forEach(commitIndex => {
51
- const { duration, timestamp } = profilerStore.getCommitData(
51
+ const {duration, timestamp} = profilerStore.getCommitData(
52
((rootID: any): number),
53
- commitIndex
53
+ commitIndex,
54
);
55
56
listItems.push(
57
<li
58
key={commitIndex}
59
className={styles.ListItem}
60
- onClick={() => viewCommit(commitIndex)}
61
- >
60
+ onClick={() => viewCommit(commitIndex)}>
61
<div
62
className={styles.CommitBox}
63
style={{
64
backgroundColor: getGradientColor(
66
- Math.min(1, Math.max(0, duration / maxCommitDuration)) || 0
65
+ Math.min(1, Math.max(0, duration / maxCommitDuration)) || 0,
66
),
67
}}
68
/>
@@ -72,7 +71,7 @@ export default function SidebarInteractions(_: Props) {
71
<br />
72
duration: {formatDuration(duration)}ms
73
</div>
75
- </li>
74
+ </li>,
75
);
76
});
77
}
packages/react-devtools-shared/src/devtools/views/Profiler/SidebarSelectedFiberInfo.js
+19
-21
@@ -1,10 +1,10 @@
1
// @flow
2
3
-import React, { Fragment, useContext } from 'react';
3
+import React, {Fragment, useContext} from 'react';
4
import ProfilerStore from 'react-devtools-shared/src/devtools/ProfilerStore';
5
-import { ProfilerContext } from './ProfilerContext';
6
-import { formatDuration, formatTime } from './utils';
7
-import { StoreContext } from '../context';
5
+import {ProfilerContext} from './ProfilerContext';
6
+import {formatDuration, formatTime} from './utils';
7
+import {StoreContext} from '../context';
8
import Button from '../Button';
9
import ButtonIcon from '../ButtonIcon';
10
@@ -13,7 +13,7 @@ import styles from './SidebarSelectedFiberInfo.css';
13
export type Props = {||};
14
15
export default function SidebarSelectedFiberInfo(_: Props) {
16
- const { profilerStore } = useContext(StoreContext);
16
+ const {profilerStore} = useContext(StoreContext);
17
const {
18
rootID,
19
selectCommitIndex,
@@ -22,7 +22,7 @@ export default function SidebarSelectedFiberInfo(_: Props) {
22
selectedFiberName,
23
selectFiber,
24
} = useContext(ProfilerContext);
25
- const { profilingCache } = profilerStore;
25
+ const {profilingCache} = profilerStore;
26
27
const commitIndices = profilingCache.getFiberCommits({
28
fiberID: ((selectedFiberID: any): number),
@@ -33,9 +33,9 @@ export default function SidebarSelectedFiberInfo(_: Props) {
33
for (let i = 0; i < commitIndices.length; i++) {
34
const commitIndex = commitIndices[i];
35
36
- const { duration, timestamp } = profilerStore.getCommitData(
36
+ const {duration, timestamp} = profilerStore.getCommitData(
37
((rootID: any): number),
38
- commitIndex
38
+ commitIndex,
39
);
40
41
listItems.push(
@@ -46,10 +46,9 @@ export default function SidebarSelectedFiberInfo(_: Props) {
46
? styles.CurrentCommit
47
: styles.Commit
48
}
49
- onClick={() => selectCommitIndex(commitIndex)}
50
- >
49
+ onClick={() => selectCommitIndex(commitIndex)}>
50
{formatTime(timestamp)}s for {formatDuration(duration)}ms
52
- </button>
51
+ </button>,
52
);
53
}
54
@@ -63,8 +62,7 @@ export default function SidebarSelectedFiberInfo(_: Props) {
62
<Button
63
className={styles.IconButton}
64
onClick={() => selectFiber(null, null)}
66
- title="Back to commit view"
67
- >
65
+ title="Back to commit view">
66
<ButtonIcon type="close" />
67
</Button>
68
</div>
@@ -101,9 +99,9 @@ function WhatChanged({
99
profilerStore,
100
rootID,
101
}: WhatChangedProps) {
104
- const { changeDescriptions } = profilerStore.getCommitData(
102
+ const {changeDescriptions} = profilerStore.getCommitData(
103
((rootID: any): number),
106
- commitIndex
104
+ commitIndex,
105
);
106
if (changeDescriptions === null) {
107
return null;
@@ -131,7 +129,7 @@ function WhatChanged({
129
changes.push(
130
<div key="context" className={styles.WhatChangedItem}>
131
• Context changed
134
- </div>
132
+ </div>,
133
);
134
} else if (
135
typeof changeDescription.context === 'object' &&
@@ -146,7 +144,7 @@ function WhatChanged({
144
{key}
145
</span>
146
))}
149
- </div>
147
+ </div>,
148
);
149
}
150
@@ -154,7 +152,7 @@ function WhatChanged({
152
changes.push(
153
<div key="hooks" className={styles.WhatChangedItem}>
154
• Hooks changed
157
- </div>
155
+ </div>,
156
);
157
}
158
@@ -170,7 +168,7 @@ function WhatChanged({
168
{key}
169
</span>
170
))}
173
- </div>
171
+ </div>,
172
);
173
}
174
@@ -186,7 +184,7 @@ function WhatChanged({
184
{key}
185
</span>
186
))}
189
- </div>
187
+ </div>,
188
);
189
}
190
@@ -194,7 +192,7 @@ function WhatChanged({
192
changes.push(
193
<div key="nothing" className={styles.WhatChangedItem}>
194
The parent component rendered.
197
- </div>
195
+ </div>,
196
);
197
}
198
packages/react-devtools-shared/src/devtools/views/Profiler/SnapshotCommitList.js
+34
-36
@@ -1,16 +1,10 @@
1
// @flow
2
3
-import React, {
4
- useCallback,
5
- useEffect,
6
- useMemo,
7
- useRef,
8
- useState,
9
-} from 'react';
3
+import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
4
import AutoSizer from 'react-virtualized-auto-sizer';
11
-import { FixedSizeList } from 'react-window';
5
+import {FixedSizeList} from 'react-window';
6
import SnapshotCommitListItem from './SnapshotCommitListItem';
13
-import { minBarWidth } from './constants';
7
+import {minBarWidth} from './constants';
8
9
import styles from './SnapshotCommitList.css';
10
@@ -44,7 +38,7 @@ export default function SnapshotCommitList({
38
}: Props) {
39
return (
40
<AutoSizer>
47
- {({ height, width }) => (
41
+ {({height, width}) => (
42
<List
43
commitDurations={commitDurations}
44
commitTimes={commitTimes}
@@ -86,14 +80,17 @@ function List({
80
const prevCommitIndexRef = useRef<number | null>(null);
81
82
// Make sure a newly selected snapshot is fully visible within the list.
89
- useEffect(() => {
90
- if (selectedFilteredCommitIndex !== prevCommitIndexRef.current) {
91
- prevCommitIndexRef.current = selectedFilteredCommitIndex;
92
- if (selectedFilteredCommitIndex !== null && listRef.current !== null) {
93
- listRef.current.scrollToItem(selectedFilteredCommitIndex);
83
+ useEffect(
84
+ () => {
85
+ if (selectedFilteredCommitIndex !== prevCommitIndexRef.current) {
86
+ prevCommitIndexRef.current = selectedFilteredCommitIndex;
87
+ if (selectedFilteredCommitIndex !== null && listRef.current !== null) {
88
+ listRef.current.scrollToItem(selectedFilteredCommitIndex);
89
+ }
90
}
95
- }
96
- }, [listRef, selectedFilteredCommitIndex]);
91
+ },
92
+ [listRef, selectedFilteredCommitIndex],
93
+ );
94
95
// When the mouse is down, dragging over a commit should auto-select it.
96
// This provides a nice way for users to swipe across a range of commits to compare them.
@@ -104,30 +101,33 @@ function List({
101
const handleMouseUp = useCallback(() => {
102
setIsMouseDown(false);
103
}, []);
107
- useEffect(() => {
108
- if (divRef.current === null) {
109
- return () => {};
110
- }
104
+ useEffect(
105
+ () => {
106
+ if (divRef.current === null) {
107
+ return () => {};
108
+ }
109
112
- // It's important to listen to the ownerDocument to support the browser extension.
113
- // Here we use portals to render individual tabs (e.g. Profiler),
114
- // and the root document might belong to a different window.
115
- const ownerDocument = divRef.current.ownerDocument;
116
- ownerDocument.addEventListener('mouseup', handleMouseUp);
117
- return () => ownerDocument.removeEventListener('mouseup', handleMouseUp);
118
- }, [divRef, handleMouseUp]);
110
+ // It's important to listen to the ownerDocument to support the browser extension.
111
+ // Here we use portals to render individual tabs (e.g. Profiler),
112
+ // and the root document might belong to a different window.
113
+ const ownerDocument = divRef.current.ownerDocument;
114
+ ownerDocument.addEventListener('mouseup', handleMouseUp);
115
+ return () => ownerDocument.removeEventListener('mouseup', handleMouseUp);
116
+ },
117
+ [divRef, handleMouseUp],
118
+ );
119
120
const itemSize = useMemo(
121
() => Math.max(minBarWidth, width / filteredCommitIndices.length),
122
- [filteredCommitIndices, width]
122
+ [filteredCommitIndices, width],
123
);
124
const maxDuration = useMemo(
125
() =>
126
commitDurations.reduce(
127
(maxDuration, duration) => Math.max(maxDuration, duration),
128
- 0
128
+ 0,
129
),
130
- [commitDurations]
130
+ [commitDurations],
131
);
132
133
// Pass required contextual data down to the ListItem renderer.
@@ -151,7 +151,7 @@ function List({
151
selectedCommitIndex,
152
selectedFilteredCommitIndex,
153
selectCommitIndex,
154
- ]
154
+ ],
155
);
156
157
return (
@@ -159,8 +159,7 @@ function List({
159
onMouseDown={handleMouseDown}
160
onMouseUp={handleMouseUp}
161
ref={divRef}
162
- style={{ height, width }}
163
- >
162
+ style={{height, width}}>
163
<FixedSizeList
164
className={styles.List}
165
layout="horizontal"
@@ -169,8 +168,7 @@ function List({
168
itemData={itemData}
169
itemSize={itemSize}
170
ref={(listRef: any) /* Flow bug? */}
172
- width={width}
173
- >
171
+ width={width}>
172
{SnapshotCommitListItem}
173
</FixedSizeList>
174
</div>
packages/react-devtools-shared/src/devtools/views/Profiler/SnapshotCommitListItem.js
+7
-8
@@ -1,12 +1,12 @@
1
// @flow
2
3
-import React, { memo, useCallback } from 'react';
4
-import { areEqual } from 'react-window';
5
-import { getGradientColor, formatDuration, formatTime } from './utils';
3
+import React, {memo, useCallback} from 'react';
4
+import {areEqual} from 'react-window';
5
+import {getGradientColor, formatDuration, formatTime} from './utils';
6
7
import styles from './SnapshotCommitListItem.css';
8
9
-import type { ItemData } from './SnapshotCommitList';
9
+import type {ItemData} from './SnapshotCommitList';
10
11
type Props = {
12
data: ItemData,
@@ -14,7 +14,7 @@ type Props = {
14
style: Object,
15
};
16
17
-function SnapshotCommitListItem({ data: itemData, index, style }: Props) {
17
+function SnapshotCommitListItem({data: itemData, index, style}: Props) {
18
const {
19
commitDurations,
20
commitTimes,
@@ -56,9 +56,8 @@ function SnapshotCommitListItem({ data: itemData, index, style }: Props) {
56
: undefined,
57
}}
58
title={`Duration ${formatDuration(commitDuration)}ms at ${formatTime(
59
- commitTime
60
- )}s`}
61
- >
59
+ commitTime,
60
+ )}s`}>
61
<div
62
className={styles.Inner}
63
style={{
packages/react-devtools-shared/src/devtools/views/Profiler/SnapshotSelector.js
+43
-37
@@ -1,12 +1,12 @@
1
// @flow
2
3
-import React, { Fragment, useCallback, useContext, useMemo } from 'react';
3
+import React, {Fragment, useCallback, useContext, useMemo} from 'react';
4
import Button from '../Button';
5
import ButtonIcon from '../ButtonIcon';
6
-import { ProfilerContext } from './ProfilerContext';
6
+import {ProfilerContext} from './ProfilerContext';
7
import SnapshotCommitList from './SnapshotCommitList';
8
-import { maxBarWidth } from './constants';
9
-import { StoreContext } from '../context';
8
+import {maxBarWidth} from './constants';
9
+import {StoreContext} from '../context';
10
11
import styles from './SnapshotSelector.css';
12
@@ -21,8 +21,8 @@ export default function SnapshotSelector(_: Props) {
21
selectCommitIndex,
22
} = useContext(ProfilerContext);
23
24
- const { profilerStore } = useContext(StoreContext);
25
- const { commitData } = profilerStore.getDataForRoot(((rootID: any): number));
24
+ const {profilerStore} = useContext(StoreContext);
25
+ const {commitData} = profilerStore.getDataForRoot(((rootID: any): number));
26
27
const commitDurations: Array<number> = [];
28
const commitTimes: Array<number> = [];
@@ -42,22 +42,25 @@ export default function SnapshotSelector(_: Props) {
42
}
43
return reduced;
44
}, []),
45
- [commitData, isCommitFilterEnabled, minCommitDuration]
45
+ [commitData, isCommitFilterEnabled, minCommitDuration],
46
);
47
48
const numFilteredCommits = filteredCommitIndices.length;
49
50
// Map the (unfiltered) selected commit index to an index within the filtered data.
51
- const selectedFilteredCommitIndex = useMemo(() => {
52
- if (selectedCommitIndex !== null) {
53
- for (let i = 0; i < filteredCommitIndices.length; i++) {
54
- if (filteredCommitIndices[i] === selectedCommitIndex) {
55
- return i;
51
+ const selectedFilteredCommitIndex = useMemo(
52
+ () => {
53
+ if (selectedCommitIndex !== null) {
54
+ for (let i = 0; i < filteredCommitIndices.length; i++) {
55
+ if (filteredCommitIndices[i] === selectedCommitIndex) {
56
+ return i;
57
+ }
58
}
59
}
58
- }
59
- return null;
60
- }, [filteredCommitIndices, selectedCommitIndex]);
60
+ return null;
61
+ },
62
+ [filteredCommitIndices, selectedCommitIndex],
63
+ );
64
65
// TODO (profiling) This should be managed by the context controller (reducer).
66
// It doesn't currently know about the filtered commits though (since it doesn't suspend).
@@ -77,26 +80,32 @@ export default function SnapshotSelector(_: Props) {
80
label =
81
`${selectedFilteredCommitIndex + 1}`.padStart(
82
`${numFilteredCommits}`.length,
80
- '0'
83
+ '0',
84
) +
85
' / ' +
86
numFilteredCommits;
87
}
88
86
- const viewNextCommit = useCallback(() => {
87
- const nextCommitIndex = Math.min(
88
- ((selectedFilteredCommitIndex: any): number) + 1,
89
- filteredCommitIndices.length - 1
90
- );
91
- selectCommitIndex(filteredCommitIndices[nextCommitIndex]);
92
- }, [selectedFilteredCommitIndex, filteredCommitIndices, selectCommitIndex]);
93
- const viewPrevCommit = useCallback(() => {
94
- const nextCommitIndex = Math.max(
95
- ((selectedFilteredCommitIndex: any): number) - 1,
96
- 0
97
- );
98
- selectCommitIndex(filteredCommitIndices[nextCommitIndex]);
99
- }, [selectedFilteredCommitIndex, filteredCommitIndices, selectCommitIndex]);
89
+ const viewNextCommit = useCallback(
90
+ () => {
91
+ const nextCommitIndex = Math.min(
92
+ ((selectedFilteredCommitIndex: any): number) + 1,
93
+ filteredCommitIndices.length - 1,
94
+ );
95
+ selectCommitIndex(filteredCommitIndices[nextCommitIndex]);
96
+ },
97
+ [selectedFilteredCommitIndex, filteredCommitIndices, selectCommitIndex],
98
+ );
99
+ const viewPrevCommit = useCallback(
100
+ () => {
101
+ const nextCommitIndex = Math.max(
102
+ ((selectedFilteredCommitIndex: any): number) - 1,
103
+ 0,
104
+ );
105
+ selectCommitIndex(filteredCommitIndices[nextCommitIndex]);
106
+ },
107
+ [selectedFilteredCommitIndex, filteredCommitIndices, selectCommitIndex],
108
+ );
109
110
const handleKeyDown = useCallback(
111
event => {
@@ -113,7 +122,7 @@ export default function SnapshotSelector(_: Props) {
122
break;
123
}
124
},
116
- [viewNextCommit, viewPrevCommit]
125
+ [viewNextCommit, viewPrevCommit],
126
);
127
128
if (commitData.length === 0) {
@@ -127,8 +136,7 @@ export default function SnapshotSelector(_: Props) {
136
className={styles.Button}
137
disabled={selectedFilteredCommitIndex === 0 || numFilteredCommits === 0}
138
onClick={viewPrevCommit}
130
- title="Select previous commit"
131
- >
139
+ title="Select previous commit">
140
<ButtonIcon type="previous" />
141
</Button>
142
<div
@@ -141,8 +149,7 @@ export default function SnapshotSelector(_: Props) {
149
? numFilteredCommits * maxBarWidth
150
: undefined,
151
}}
144
- tabIndex={0}
145
- >
152
+ tabIndex={0}>
153
{numFilteredCommits > 0 && (
154
<SnapshotCommitList
155
commitDurations={commitDurations}
@@ -164,8 +171,7 @@ export default function SnapshotSelector(_: Props) {
171
selectedFilteredCommitIndex >= numFilteredCommits - 1
172
}
173
onClick={viewNextCommit}
167
- title="Select next commit"
168
- >
174
+ title="Select next commit">
175
<ButtonIcon type="next" />
176
</Button>
177
</Fragment>
packages/react-devtools-shared/src/devtools/views/Profiler/types.js
+1
-1
@@ -1,6 +1,6 @@
1
// @flow
2
3
-import type { ElementType } from 'react-devtools-shared/src/types';
3
+import type {ElementType} from 'react-devtools-shared/src/types';
4
5
export type CommitTreeNode = {|
6
id: number,
packages/react-devtools-shared/src/devtools/views/Profiler/utils.js
+16
-16
@@ -1,8 +1,8 @@
1
// @flow
2
3
-import { PROFILER_EXPORT_VERSION } from 'react-devtools-shared/src/constants';
3
+import {PROFILER_EXPORT_VERSION} from 'react-devtools-shared/src/constants';
4
5
-import type { ProfilingDataBackend } from 'react-devtools-shared/src/backend/types';
5
+import type {ProfilingDataBackend} from 'react-devtools-shared/src/backend/types';
6
import type {
7
ProfilingDataExport,
8
ProfilingDataForRootExport,
@@ -29,7 +29,7 @@ const commitGradient = [
29
export function prepareProfilingDataFrontendFromBackendAndStore(
30
dataBackends: Array<ProfilingDataBackend>,
31
operationsByRootID: Map<number, Array<Array<number>>>,
32
- snapshotsByRootID: Map<number, Map<number, SnapshotNode>>
32
+ snapshotsByRootID: Map<number, Map<number, SnapshotNode>>,
33
): ProfilingDataFrontend {
34
const dataForRoots: Map<number, ProfilingDataForRootFrontend> = new Map();
35
@@ -61,7 +61,7 @@ export function prepareProfilingDataFrontendFromBackendAndStore(
61
: null,
62
duration: commitDataBackend.duration,
63
fiberActualDurations: new Map(
64
- commitDataBackend.fiberActualDurations
64
+ commitDataBackend.fiberActualDurations,
65
),
66
fiberSelfDurations: new Map(commitDataBackend.fiberSelfDurations),
67
interactionIDs: commitDataBackend.interactionIDs,
@@ -76,18 +76,18 @@ export function prepareProfilingDataFrontendFromBackendAndStore(
76
rootID,
77
snapshots,
78
});
79
- }
79
+ },
80
);
81
});
82
83
- return { dataForRoots };
83
+ return {dataForRoots};
84
}
85
86
// Converts a Profiling data export into the format required by the Store.
87
export function prepareProfilingDataFrontendFromExport(
88
- profilingDataExport: ProfilingDataExport
88
+ profilingDataExport: ProfilingDataExport,
89
): ProfilingDataFrontend {
90
- const { version } = profilingDataExport;
90
+ const {version} = profilingDataExport;
91
92
if (version !== PROFILER_EXPORT_VERSION) {
93
throw Error(`Unsupported profiler export version "${version}"`);
@@ -124,7 +124,7 @@ export function prepareProfilingDataFrontendFromExport(
124
interactionIDs,
125
priorityLevel,
126
timestamp,
127
- })
127
+ }),
128
),
129
displayName,
130
initialTreeBaseDurations: new Map(initialTreeBaseDurations),
@@ -134,15 +134,15 @@ export function prepareProfilingDataFrontendFromExport(
134
rootID,
135
snapshots: new Map(snapshots),
136
});
137
- }
137
+ },
138
);
139
140
- return { dataForRoots };
140
+ return {dataForRoots};
141
}
142
143
// Converts a Store Profiling data into a format that can be safely (JSON) serialized for export.
144
export function prepareProfilingDataExport(
145
- profilingDataFrontend: ProfilingDataFrontend
145
+ profilingDataFrontend: ProfilingDataFrontend,
146
): ProfilingDataExport {
147
const dataForRoots: Array<ProfilingDataForRootExport> = [];
148
profilingDataFrontend.dataForRoots.forEach(
@@ -177,11 +177,11 @@ export function prepareProfilingDataExport(
177
interactionIDs,
178
priorityLevel,
179
timestamp,
180
- })
180
+ }),
181
),
182
displayName,
183
initialTreeBaseDurations: Array.from(
184
- initialTreeBaseDurations.entries()
184
+ initialTreeBaseDurations.entries(),
185
),
186
interactionCommits: Array.from(interactionCommits.entries()),
187
interactions: Array.from(interactions.entries()),
@@ -189,7 +189,7 @@ export function prepareProfilingDataExport(
189
rootID,
190
snapshots: Array.from(snapshots.entries()),
191
});
192
- }
192
+ },
193
);
194
195
return {
@@ -222,7 +222,7 @@ export const scale = (
222
minValue: number,
223
maxValue: number,
224
minRange: number,
225
- maxRange: number
225
+ maxRange: number,
226
) => (value: number, fallbackValue: number) =>
227
maxValue - minValue === 0
228
? fallbackValue
packages/react-devtools-shared/src/devtools/views/ReactLogo.js
+2
-3
@@ -8,13 +8,12 @@ type Props = {|
8
className?: string,
9
|};
10
11
-export default function ReactLogo({ className }: Props) {
11
+export default function ReactLogo({className}: Props) {
12
return (
13
<svg
14
xmlns="http://www.w3.org/2000/svg"
15
className={`${styles.ReactLogo} ${className || ''}`}
16
- viewBox="-11.5 -10.23174 23 20.46348"
17
- >
16
+ viewBox="-11.5 -10.23174 23 20.46348">
17
<circle cx="0" cy="0" r="2.05" fill="currentColor" />
18
<g stroke="currentColor" strokeWidth="1" fill="none">
19
<ellipse rx="11" ry="4.2" />
packages/react-devtools-shared/src/devtools/views/Settings/ComponentsSettings.js
+33
-34
@@ -8,8 +8,8 @@ import React, {
8
useRef,
9
useState,
10
} from 'react';
11
-import { useSubscription } from '../hooks';
12
-import { StoreContext } from '../context';
11
+import {useSubscription} from '../hooks';
12
+import {StoreContext} from '../context';
13
import Store from 'react-devtools-shared/src/devtools/store';
14
import Button from '../Button';
15
import ButtonIcon from '../ButtonIcon';
@@ -52,21 +52,21 @@ export default function ComponentsSettings(_: {||}) {
52
return () => store.removeListener('collapseNodesByDefault', callback);
53
},
54
}),
55
- [store]
55
+ [store],
56
);
57
const collapseNodesByDefault = useSubscription<boolean>(
58
- collapseNodesByDefaultSubscription
58
+ collapseNodesByDefaultSubscription,
59
);
60
61
const updateCollapseNodesByDefault = useCallback(
62
- ({ currentTarget }) => {
62
+ ({currentTarget}) => {
63
store.collapseNodesByDefault = !currentTarget.checked;
64
},
65
- [store]
65
+ [store],
66
);
67
68
const [componentFilters, setComponentFilters] = useState<
69
- Array<ComponentFilter>
69
+ Array<ComponentFilter>,
70
>(() => [...store.componentFilters]);
71
72
const addFilter = useCallback(() => {
@@ -119,7 +119,7 @@ export default function ComponentsSettings(_: {||}) {
119
return cloned;
120
});
121
},
122
- []
122
+ [],
123
);
124
125
const updateFilterValueElementType = useCallback(
@@ -142,7 +142,7 @@ export default function ComponentsSettings(_: {||}) {
142
return cloned;
143
});
144
},
145
- []
145
+ [],
146
);
147
148
const updateFilterValueRegExp = useCallback(
@@ -175,7 +175,7 @@ export default function ComponentsSettings(_: {||}) {
175
return cloned;
176
});
177
},
178
- []
178
+ [],
179
);
180
181
const removeFilter = useCallback((index: number) => {
@@ -215,7 +215,7 @@ export default function ComponentsSettings(_: {||}) {
215
return cloned;
216
});
217
},
218
- []
218
+ [],
219
);
220
221
// Filter updates are expensive to apply (since they impact the entire tree).
@@ -223,15 +223,18 @@ export default function ComponentsSettings(_: {||}) {
223
// The Store will avoid doing any expensive work unless they've changed.
224
// We just want to batch the work in the event that they do change.
225
const componentFiltersRef = useRef<Array<ComponentFilter>>(componentFilters);
226
- useEffect(() => {
227
- componentFiltersRef.current = componentFilters;
228
- return () => {};
229
- }, [componentFilters]);
226
+ useEffect(
227
+ () => {
228
+ componentFiltersRef.current = componentFilters;
229
+ return () => {};
230
+ },
231
+ [componentFilters],
232
+ );
233
useEffect(
234
() => () => {
235
store.componentFilters = [...componentFiltersRef.current];
236
},
234
- [store]
237
+ [store],
238
);
239
240
return (
@@ -273,10 +276,9 @@ export default function ComponentsSettings(_: {||}) {
276
componentFilter.isValid === false
277
? 'Filter invalid'
278
: componentFilter.isEnabled
276
- ? 'Filter enabled'
277
- : 'Filter disabled'
278
- }
279
- >
279
+ ? 'Filter enabled'
280
+ : 'Filter disabled'
281
+ }>
282
<ToggleIcon
283
isEnabled={componentFilter.isEnabled}
284
isValid={
@@ -290,16 +292,15 @@ export default function ComponentsSettings(_: {||}) {
292
<select
293
className={styles.Select}
294
value={componentFilter.type}
293
- onChange={({ currentTarget }) =>
295
+ onChange={({currentTarget}) =>
296
changeFilterType(
297
componentFilter,
298
((parseInt(
299
currentTarget.value,
298
- 10
299
- ): any): ComponentFilterType)
300
+ 10,
301
+ ): any): ComponentFilterType),
302
)
301
- }
302
- >
303
+ }>
304
<option value={ComponentFilterLocation}>location</option>
305
<option value={ComponentFilterDisplayName}>name</option>
306
<option value={ComponentFilterElementType}>type</option>
@@ -318,13 +319,12 @@ export default function ComponentsSettings(_: {||}) {
319
<select
320
className={styles.Select}
321
value={componentFilter.value}
321
- onChange={({ currentTarget }) =>
322
+ onChange={({currentTarget}) =>
323
updateFilterValueElementType(
324
componentFilter,
324
- ((parseInt(currentTarget.value, 10): any): ElementType)
325
+ ((parseInt(currentTarget.value, 10): any): ElementType),
326
)
326
- }
327
- >
327
+ }>
328
<option value={ElementTypeClass}>class</option>
329
<option value={ElementTypeContext}>context</option>
330
<option value={ElementTypeFunction}>function</option>
@@ -344,10 +344,10 @@ export default function ComponentsSettings(_: {||}) {
344
className={styles.Input}
345
type="text"
346
placeholder="Regular expression"
347
- onChange={({ currentTarget }) =>
347
+ onChange={({currentTarget}) =>
348
updateFilterValueRegExp(
349
componentFilter,
350
- currentTarget.value
350
+ currentTarget.value,
351
)
352
}
353
value={componentFilter.value}
@@ -357,8 +357,7 @@ export default function ComponentsSettings(_: {||}) {
357
<td className={styles.TableCell}>
358
<Button
359
onClick={() => removeFilter(index)}
360
- title="Delete filter"
361
- >
360
+ title="Delete filter">
361
<ButtonIcon type="delete" />
362
</Button>
363
</td>
@@ -379,7 +378,7 @@ type ToggleIconProps = {|
378
isEnabled: boolean,
379
isValid: boolean,
380
|};
382
-function ToggleIcon({ isEnabled, isValid }: ToggleIconProps) {
381
+function ToggleIcon({isEnabled, isValid}: ToggleIconProps) {
382
let className;
383
if (isValid) {
384
className = isEnabled ? styles.ToggleOn : styles.ToggleOff;
packages/react-devtools-shared/src/devtools/views/Settings/GeneralSettings.js
+8
-10
@@ -1,8 +1,8 @@
1
// @flow
2
3
-import React, { useContext } from 'react';
4
-import { SettingsContext } from './SettingsContext';
5
-import { CHANGE_LOG_URL } from 'react-devtools-shared/src/constants';
3
+import React, {useContext} from 'react';
4
+import {SettingsContext} from './SettingsContext';
5
+import {CHANGE_LOG_URL} from 'react-devtools-shared/src/constants';
6
7
import styles from './SettingsShared.css';
8
@@ -16,10 +16,10 @@ export default function GeneralSettings(_: {||}) {
16
setAppendComponentStack,
17
} = useContext(SettingsContext);
18
19
- const updateDisplayDensity = ({ currentTarget }) =>
19
+ const updateDisplayDensity = ({currentTarget}) =>
20
setDisplayDensity(currentTarget.value);
21
- const updateTheme = ({ currentTarget }) => setTheme(currentTarget.value);
22
- const updateappendComponentStack = ({ currentTarget }) =>
21
+ const updateTheme = ({currentTarget}) => setTheme(currentTarget.value);
22
+ const updateappendComponentStack = ({currentTarget}) =>
23
setAppendComponentStack(currentTarget.checked);
24
25
return (
@@ -38,8 +38,7 @@ export default function GeneralSettings(_: {||}) {
38
<select
39
className={styles.Select}
40
value={displayDensity}
41
- onChange={updateDisplayDensity}
42
- >
41
+ onChange={updateDisplayDensity}>
42
<option value="compact">Compact</option>
43
<option value="comfortable">Comfortable</option>
44
</select>
@@ -61,8 +60,7 @@ export default function GeneralSettings(_: {||}) {
60
className={styles.ReleaseNotesLink}
61
target="_blank"
62
rel="noopener noreferrer"
64
- href={CHANGE_LOG_URL}
65
- >
63
+ href={CHANGE_LOG_URL}>
64
View release notes
65
</a>{' '}
66
for DevTools version {process.env.DEVTOOLS_VERSION}
packages/react-devtools-shared/src/devtools/views/Settings/ProfilerSettings.js
+11
-11
@@ -1,9 +1,9 @@
1
// @flow
2
3
-import React, { useCallback, useContext, useMemo, useRef } from 'react';
4
-import { useSubscription } from '../hooks';
5
-import { StoreContext } from '../context';
6
-import { ProfilerContext } from 'react-devtools-shared/src/devtools/views/Profiler/ProfilerContext';
3
+import React, {useCallback, useContext, useMemo, useRef} from 'react';
4
+import {useSubscription} from '../hooks';
5
+import {StoreContext} from '../context';
6
+import {ProfilerContext} from 'react-devtools-shared/src/devtools/views/Profiler/ProfilerContext';
7
import Store from 'react-devtools-shared/src/devtools/store';
8
9
import styles from './SettingsShared.css';
@@ -25,26 +25,26 @@ export default function ProfilerSettings(_: {||}) {
25
return () => store.removeListener('recordChangeDescriptions', callback);
26
},
27
}),
28
- [store]
28
+ [store],
29
);
30
const recordChangeDescriptions = useSubscription<boolean>(
31
- recordChangeDescriptionsSubscription
31
+ recordChangeDescriptionsSubscription,
32
);
33
34
const updateRecordChangeDescriptions = useCallback(
35
- ({ currentTarget }) => {
35
+ ({currentTarget}) => {
36
store.recordChangeDescriptions = currentTarget.checked;
37
},
38
- [store]
38
+ [store],
39
);
40
const updateMinCommitDuration = useCallback(
41
(event: SyntheticEvent<HTMLInputElement>) => {
42
const newValue = parseFloat(event.currentTarget.value);
43
setMinCommitDuration(
44
- Number.isNaN(newValue) || newValue <= 0 ? 0 : newValue
44
+ Number.isNaN(newValue) || newValue <= 0 ? 0 : newValue,
45
);
46
},
47
- [setMinCommitDuration]
47
+ [setMinCommitDuration],
48
);
49
const updateIsCommitFilterEnabled = useCallback(
50
(event: SyntheticEvent<HTMLInputElement>) => {
@@ -56,7 +56,7 @@ export default function ProfilerSettings(_: {||}) {
56
}
57
}
58
},
59
- [setIsCommitFilterEnabled]
59
+ [setIsCommitFilterEnabled],
60
);
61
62
const minCommitDurationInputRef = useRef<HTMLInputElement | null>(null);
packages/react-devtools-shared/src/devtools/views/Settings/SettingsContext.js
+89
-78
@@ -12,10 +12,10 @@ import {
12
COMPACT_LINE_HEIGHT,
13
LOCAL_STORAGE_SHOULD_PATCH_CONSOLE_KEY,
14
} from 'react-devtools-shared/src/constants';
15
-import { useLocalStorage } from '../hooks';
16
-import { BridgeContext } from '../context';
15
+import {useLocalStorage} from '../hooks';
16
+import {BridgeContext} from '../context';
17
18
-import type { BrowserTheme } from '../DevTools';
18
+import type {BrowserTheme} from '../DevTools';
19
20
export type DisplayDensity = 'comfortable' | 'compact';
21
export type Theme = 'auto' | 'light' | 'dark';
@@ -57,68 +57,79 @@ function SettingsContextController({
57
58
const [displayDensity, setDisplayDensity] = useLocalStorage<DisplayDensity>(
59
'React::DevTools::displayDensity',
60
- 'compact'
60
+ 'compact',
61
);
62
const [theme, setTheme] = useLocalStorage<Theme>(
63
'React::DevTools::theme',
64
- 'auto'
64
+ 'auto',
65
);
66
- const [
67
- appendComponentStack,
68
- setAppendComponentStack,
69
- ] = useLocalStorage<boolean>(LOCAL_STORAGE_SHOULD_PATCH_CONSOLE_KEY, true);
66
+ const [appendComponentStack, setAppendComponentStack] = useLocalStorage<
67
+ boolean,
68
+ >(LOCAL_STORAGE_SHOULD_PATCH_CONSOLE_KEY, true);
69
71
- const documentElements = useMemo<DocumentElements>(() => {
72
- const array: Array<HTMLElement> = [
73
- ((document.documentElement: any): HTMLElement),
74
- ];
75
- if (componentsPortalContainer != null) {
76
- array.push(
77
- ((componentsPortalContainer.ownerDocument
78
- .documentElement: any): HTMLElement)
79
- );
80
- }
81
- if (profilerPortalContainer != null) {
82
- array.push(
83
- ((profilerPortalContainer.ownerDocument
84
- .documentElement: any): HTMLElement)
85
- );
86
- }
87
- return array;
88
- }, [componentsPortalContainer, profilerPortalContainer]);
70
+ const documentElements = useMemo<DocumentElements>(
71
+ () => {
72
+ const array: Array<HTMLElement> = [
73
+ ((document.documentElement: any): HTMLElement),
74
+ ];
75
+ if (componentsPortalContainer != null) {
76
+ array.push(
77
+ ((componentsPortalContainer.ownerDocument
78
+ .documentElement: any): HTMLElement),
79
+ );
80
+ }
81
+ if (profilerPortalContainer != null) {
82
+ array.push(
83
+ ((profilerPortalContainer.ownerDocument
84
+ .documentElement: any): HTMLElement),
85
+ );
86
+ }
87
+ return array;
88
+ },
89
+ [componentsPortalContainer, profilerPortalContainer],
90
+ );
91
90
- useLayoutEffect(() => {
91
- switch (displayDensity) {
92
- case 'comfortable':
93
- updateDisplayDensity('comfortable', documentElements);
94
- break;
95
- case 'compact':
96
- updateDisplayDensity('compact', documentElements);
97
- break;
98
- default:
99
- throw Error(`Unsupported displayDensity value "${displayDensity}"`);
100
- }
101
- }, [displayDensity, documentElements]);
92
+ useLayoutEffect(
93
+ () => {
94
+ switch (displayDensity) {
95
+ case 'comfortable':
96
+ updateDisplayDensity('comfortable', documentElements);
97
+ break;
98
+ case 'compact':
99
+ updateDisplayDensity('compact', documentElements);
100
+ break;
101
+ default:
102
+ throw Error(`Unsupported displayDensity value "${displayDensity}"`);
103
+ }
104
+ },
105
+ [displayDensity, documentElements],
106
+ );
107
103
- useLayoutEffect(() => {
104
- switch (theme) {
105
- case 'light':
106
- updateThemeVariables('light', documentElements);
107
- break;
108
- case 'dark':
109
- updateThemeVariables('dark', documentElements);
110
- break;
111
- case 'auto':
112
- updateThemeVariables(browserTheme, documentElements);
113
- break;
114
- default:
115
- throw Error(`Unsupported theme value "${theme}"`);
116
- }
117
- }, [browserTheme, theme, documentElements]);
108
+ useLayoutEffect(
109
+ () => {
110
+ switch (theme) {
111
+ case 'light':
112
+ updateThemeVariables('light', documentElements);
113
+ break;
114
+ case 'dark':
115
+ updateThemeVariables('dark', documentElements);
116
+ break;
117
+ case 'auto':
118
+ updateThemeVariables(browserTheme, documentElements);
119
+ break;
120
+ default:
121
+ throw Error(`Unsupported theme value "${theme}"`);
122
+ }
123
+ },
124
+ [browserTheme, theme, documentElements],
125
+ );
126
119
- useEffect(() => {
120
- bridge.send('updateAppendComponentStack', appendComponentStack);
121
- }, [bridge, appendComponentStack]);
127
+ useEffect(
128
+ () => {
129
+ bridge.send('updateAppendComponentStack', appendComponentStack);
130
+ },
131
+ [bridge, appendComponentStack],
132
+ );
133
134
const value = useMemo(
135
() => ({
@@ -140,7 +151,7 @@ function SettingsContextController({
151
appendComponentStack,
152
setAppendComponentStack,
153
theme,
143
- ]
154
+ ],
155
);
156
157
return (
@@ -153,43 +164,43 @@ function SettingsContextController({
164
function setStyleVariable(
165
name: string,
166
value: string,
156
- documentElements: DocumentElements
167
+ documentElements: DocumentElements,
168
) {
169
documentElements.forEach(documentElement =>
159
- documentElement.style.setProperty(name, value)
170
+ documentElement.style.setProperty(name, value),
171
);
172
}
173
174
function updateStyleHelper(
175
themeKey: string,
176
style: string,
166
- documentElements: DocumentElements
177
+ documentElements: DocumentElements,
178
) {
179
setStyleVariable(
180
`--${style}`,
181
`var(--${themeKey}-${style})`,
171
- documentElements
182
+ documentElements,
183
);
184
}
185
186
function updateDisplayDensity(
187
displayDensity: DisplayDensity,
177
- documentElements: DocumentElements
188
+ documentElements: DocumentElements,
189
): void {
190
updateStyleHelper(
191
displayDensity,
192
'font-size-monospace-normal',
182
- documentElements
193
+ documentElements,
194
);
195
updateStyleHelper(
196
displayDensity,
197
'font-size-monospace-large',
187
- documentElements
198
+ documentElements,
199
);
200
updateStyleHelper(
201
displayDensity,
202
'font-size-monospace-small',
192
- documentElements
203
+ documentElements,
204
);
205
updateStyleHelper(displayDensity, 'font-size-sans-normal', documentElements);
206
updateStyleHelper(displayDensity, 'font-size-sans-large', documentElements);
@@ -200,7 +211,7 @@ function updateDisplayDensity(
211
// so update the root font-size as well when the display preference changes.
212
const computedStyle = getComputedStyle((document.body: any));
213
const fontSize = computedStyle.getPropertyValue(
203
- `--${displayDensity}-root-font-size`
214
+ `--${displayDensity}-root-font-size`,
215
);
216
const root = ((document.querySelector(':root'): any): HTMLElement);
217
root.style.fontSize = fontSize;
@@ -208,7 +219,7 @@ function updateDisplayDensity(
219
220
function updateThemeVariables(
221
theme: Theme,
211
- documentElements: DocumentElements
222
+ documentElements: DocumentElements,
223
): void {
224
updateStyleHelper(theme, 'color-attribute-name', documentElements);
225
updateStyleHelper(theme, 'color-attribute-name-inverted', documentElements);
@@ -231,22 +242,22 @@ function updateThemeVariables(
242
updateStyleHelper(
243
theme,
244
'color-commit-did-not-render-fill',
234
- documentElements
245
+ documentElements,
246
);
247
updateStyleHelper(
248
theme,
249
'color-commit-did-not-render-fill-text',
239
- documentElements
250
+ documentElements,
251
);
252
updateStyleHelper(
253
theme,
254
'color-commit-did-not-render-pattern',
244
- documentElements
255
+ documentElements,
256
);
257
updateStyleHelper(
258
theme,
259
'color-commit-did-not-render-pattern-text',
249
- documentElements
260
+ documentElements,
261
);
262
updateStyleHelper(theme, 'color-commit-gradient-0', documentElements);
263
updateStyleHelper(theme, 'color-commit-gradient-1', documentElements);
@@ -264,18 +275,18 @@ function updateThemeVariables(
275
updateStyleHelper(
276
theme,
277
'color-component-badge-background',
267
- documentElements
278
+ documentElements,
279
);
280
updateStyleHelper(
281
theme,
282
'color-component-badge-background-inverted',
272
- documentElements
283
+ documentElements,
284
);
285
updateStyleHelper(theme, 'color-component-badge-count', documentElements);
286
updateStyleHelper(
287
theme,
288
'color-component-badge-count-inverted',
278
- documentElements
289
+ documentElements,
290
);
291
updateStyleHelper(theme, 'color-dim', documentElements);
292
updateStyleHelper(theme, 'color-dimmer', documentElements);
@@ -293,12 +304,12 @@ function updateThemeVariables(
304
updateStyleHelper(
305
theme,
306
'color-selected-tree-highlight-active',
296
- documentElements
307
+ documentElements,
308
);
309
updateStyleHelper(
310
theme,
311
'color-selected-tree-highlight-inactive',
301
- documentElements
312
+ documentElements,
313
);
314
updateStyleHelper(theme, 'color-tab-selected-border', documentElements);
315
updateStyleHelper(theme, 'color-text', documentElements);
@@ -324,4 +335,4 @@ function updateThemeVariables(
335
});
336
}
337
327
-export { SettingsContext, SettingsContextController };
338
+export {SettingsContext, SettingsContextController};
packages/react-devtools-shared/src/devtools/views/Settings/SettingsModal.js
+15
-14
@@ -7,12 +7,12 @@ import React, {
7
useMemo,
8
useRef,
9
} from 'react';
10
-import { SettingsModalContext } from './SettingsModalContext';
10
+import {SettingsModalContext} from './SettingsModalContext';
11
import Store from 'react-devtools-shared/src/devtools/store';
12
import Button from '../Button';
13
import ButtonIcon from '../ButtonIcon';
14
import TabBar from '../TabBar';
15
-import { StoreContext } from '../context';
15
+import {StoreContext} from '../context';
16
import {
17
useLocalStorage,
18
useModalDismissSignal,
@@ -27,11 +27,9 @@ import styles from './SettingsModal.css';
27
type TabID = 'general' | 'components' | 'profiler';
28
29
export default function SettingsModal(_: {||}) {
30
- const { isModalShowing, setIsModalShowing } = useContext(
31
- SettingsModalContext
32
- );
30
+ const {isModalShowing, setIsModalShowing} = useContext(SettingsModalContext);
31
const store = useContext(StoreContext);
34
- const { profilerStore } = store;
32
+ const {profilerStore} = store;
33
34
// Updating preferences while profiling is in progress could break things (e.g. filtering)
35
// Explicitly disallow it for now.
@@ -43,7 +41,7 @@ export default function SettingsModal(_: {||}) {
41
return () => profilerStore.removeListener('isProfiling', callback);
42
},
43
}),
46
- [profilerStore]
44
+ [profilerStore],
45
);
46
const isProfiling = useSubscription<boolean>(isProfilingSubscription);
47
if (isProfiling && isModalShowing) {
@@ -58,24 +56,27 @@ export default function SettingsModal(_: {||}) {
56
}
57
58
function SettingsModalImpl(_: {||}) {
61
- const { setIsModalShowing } = useContext(SettingsModalContext);
59
+ const {setIsModalShowing} = useContext(SettingsModalContext);
60
const dismissModal = useCallback(() => setIsModalShowing(false), [
61
setIsModalShowing,
62
]);
63
64
const [selectedTabID, selectTab] = useLocalStorage<TabID>(
65
'React::DevTools::selectedSettingsTabID',
68
- 'general'
66
+ 'general',
67
);
68
69
const modalRef = useRef<HTMLDivElement | null>(null);
70
useModalDismissSignal(modalRef, dismissModal);
71
74
- useEffect(() => {
75
- if (modalRef.current !== null) {
76
- modalRef.current.focus();
77
- }
78
- }, [modalRef]);
72
+ useEffect(
73
+ () => {
74
+ if (modalRef.current !== null) {
75
+ modalRef.current.focus();
76
+ }
77
+ },
78
+ [modalRef],
79
+ );
80
81
let view = null;
82
switch (selectedTabID) {
packages/react-devtools-shared/src/devtools/views/Settings/SettingsModalContext.js
+4
-8
@@ -1,6 +1,6 @@
1
// @flow
2
3
-import React, { createContext, useMemo, useState } from 'react';
3
+import React, {createContext, useMemo, useState} from 'react';
4
5
export type DisplayDensity = 'comfortable' | 'compact';
6
export type Theme = 'auto' | 'light' | 'dark';
@@ -13,14 +13,10 @@ type Context = {
13
const SettingsModalContext = createContext<Context>(((null: any): Context));
14
SettingsModalContext.displayName = 'SettingsModalContext';
15
16
-function SettingsModalContextController({
17
- children,
18
-}: {|
19
- children: React$Node,
20
-|}) {
16
+function SettingsModalContextController({children}: {|children: React$Node|}) {
17
const [isModalShowing, setIsModalShowing] = useState<boolean>(false);
18
23
- const value = useMemo(() => ({ isModalShowing, setIsModalShowing }), [
19
+ const value = useMemo(() => ({isModalShowing, setIsModalShowing}), [
20
isModalShowing,
21
setIsModalShowing,
22
]);
@@ -32,4 +28,4 @@ function SettingsModalContextController({
28
);
29
}
30
35
-export { SettingsModalContext, SettingsModalContextController };
31
+export {SettingsModalContext, SettingsModalContextController};
packages/react-devtools-shared/src/devtools/views/Settings/SettingsModalContextToggle.js
+8
-9
@@ -1,17 +1,17 @@
1
// @flow
2
3
-import React, { useCallback, useContext, useMemo } from 'react';
4
-import { SettingsModalContext } from './SettingsModalContext';
3
+import React, {useCallback, useContext, useMemo} from 'react';
4
+import {SettingsModalContext} from './SettingsModalContext';
5
import Button from '../Button';
6
import ButtonIcon from '../ButtonIcon';
7
-import { StoreContext } from '../context';
8
-import { useSubscription } from '../hooks';
7
+import {StoreContext} from '../context';
8
+import {useSubscription} from '../hooks';
9
import Store from 'react-devtools-shared/src/devtools/store';
10
11
export default function SettingsModalContextToggle() {
12
- const { setIsModalShowing } = useContext(SettingsModalContext);
12
+ const {setIsModalShowing} = useContext(SettingsModalContext);
13
const store = useContext(StoreContext);
14
- const { profilerStore } = store;
14
+ const {profilerStore} = store;
15
16
const showFilterModal = useCallback(() => setIsModalShowing(true), [
17
setIsModalShowing,
@@ -27,7 +27,7 @@ export default function SettingsModalContextToggle() {
27
return () => profilerStore.removeListener('isProfiling', callback);
28
},
29
}),
30
- [profilerStore]
30
+ [profilerStore],
31
);
32
const isProfiling = useSubscription<boolean>(isProfilingSubscription);
33
@@ -35,8 +35,7 @@ export default function SettingsModalContextToggle() {
35
<Button
36
disabled={isProfiling}
37
onClick={showFilterModal}
38
- title="View settings"
39
- >
38
+ title="View settings">
39
<ButtonIcon type="settings" />
40
</Button>
41
);
packages/react-devtools-shared/src/devtools/views/ShowWelcomeToTheNewDevToolsDialog.js
+25
-23
@@ -1,11 +1,11 @@
1
// @flow
2
3
-import React, { Fragment, useContext, useEffect } from 'react';
4
-import { unstable_batchedUpdates as batchedUpdates } from 'react-dom';
5
-import { useLocalStorage } from './hooks';
6
-import { ModalDialogContext } from './ModalDialog';
3
+import React, {Fragment, useContext, useEffect} from 'react';
4
+import {unstable_batchedUpdates as batchedUpdates} from 'react-dom';
5
+import {useLocalStorage} from './hooks';
6
+import {ModalDialogContext} from './ModalDialog';
7
import ReactLogo from './ReactLogo';
8
-import { CHANGE_LOG_URL } from 'react-devtools-shared/src/constants';
8
+import {CHANGE_LOG_URL} from 'react-devtools-shared/src/constants';
9
10
import styles from './ShowWelcomeToTheNewDevToolsDialog.css';
11
@@ -13,28 +13,31 @@ const LOCAL_STORAGE_KEY =
13
'React::DevTools::hasShownWelcomeToTheNewDevToolsDialog';
14
15
export default function ShowWelcomeToTheNewDevToolsDialog(_: {||}) {
16
- const { dispatch } = useContext(ModalDialogContext);
16
+ const {dispatch} = useContext(ModalDialogContext);
17
const [
18
hasShownWelcomeToTheNewDevToolsDialog,
19
setHasShownWelcomeToTheNewDevToolsDialog,
20
] = useLocalStorage<boolean>(LOCAL_STORAGE_KEY, false);
21
22
- useEffect(() => {
23
- if (!hasShownWelcomeToTheNewDevToolsDialog) {
24
- batchedUpdates(() => {
25
- setHasShownWelcomeToTheNewDevToolsDialog(true);
26
- dispatch({
27
- canBeDismissed: true,
28
- type: 'SHOW',
29
- content: <DialogContent />,
22
+ useEffect(
23
+ () => {
24
+ if (!hasShownWelcomeToTheNewDevToolsDialog) {
25
+ batchedUpdates(() => {
26
+ setHasShownWelcomeToTheNewDevToolsDialog(true);
27
+ dispatch({
28
+ canBeDismissed: true,
29
+ type: 'SHOW',
30
+ content: <DialogContent />,
31
+ });
32
});
31
- });
32
- }
33
- }, [
34
- dispatch,
35
- hasShownWelcomeToTheNewDevToolsDialog,
36
- setHasShownWelcomeToTheNewDevToolsDialog,
37
- ]);
33
+ }
34
+ },
35
+ [
36
+ dispatch,
37
+ hasShownWelcomeToTheNewDevToolsDialog,
38
+ setHasShownWelcomeToTheNewDevToolsDialog,
39
+ ],
40
+ );
41
42
return null;
43
}
@@ -51,8 +54,7 @@ function DialogContent(_: {||}) {
54
className={styles.ReleaseNotesLink}
55
target="_blank"
56
rel="noopener noreferrer"
54
- href={CHANGE_LOG_URL}
55
- >
57
+ href={CHANGE_LOG_URL}>
58
Learn more
59
</a>{' '}
60
about changes in this version.
packages/react-devtools-shared/src/devtools/views/TabBar.js
+7
-8
@@ -1,13 +1,13 @@
1
// @flow
2
3
-import React, { Fragment, useCallback } from 'react';
3
+import React, {Fragment, useCallback} from 'react';
4
import Tooltip from '@reach/tooltip';
5
import Icon from './Icon';
6
7
import styles from './TabBar.css';
8
import tooltipStyles from './Tooltip.css';
9
10
-import type { IconType } from './Icon';
10
+import type {IconType} from './Icon';
11
12
type TabInfo = {|
13
icon: IconType,
@@ -38,8 +38,8 @@ export default function TabBar({
38
}
39
40
const onChange = useCallback(
41
- ({ currentTarget }) => selectTab(currentTarget.value),
42
- [selectTab]
41
+ ({currentTarget}) => selectTab(currentTarget.value),
42
+ [selectTab],
43
);
44
45
const handleKeyDown = useCallback(event => {
@@ -80,18 +80,17 @@ export default function TabBar({
80
81
return (
82
<Fragment>
83
- {tabs.map(({ icon, id, label, title }) => {
83
+ {tabs.map(({icon, id, label, title}) => {
84
let button = (
85
<label
86
className={[
87
tabSizeClassName,
88
disabled ? styles.TabDisabled : styles.Tab,
89
- !disabled && currentTab === id ? styles.TabCurrent : ''
89
+ !disabled && currentTab === id ? styles.TabCurrent : '',
90
].join(' ')}
91
key={id}
92
onKeyDown={handleKeyDown}
93
- onMouseDown={() => selectTab(id)}
94
- >
93
+ onMouseDown={() => selectTab(id)}>
94
<input
95
type="radio"
96
className={styles.Input}
packages/react-devtools-shared/src/devtools/views/Toggle.js
+2
-3
@@ -1,6 +1,6 @@
1
// @flow
2
3
-import React, { useCallback } from 'react';
3
+import React, {useCallback} from 'react';
4
import Tooltip from '@reach/tooltip';
5
6
import styles from './Toggle.css';
@@ -41,8 +41,7 @@ export default function Toggle({
41
<button
42
className={`${defaultClassName} ${className}`}
43
disabled={isDisabled}
44
- onClick={handleClick}
45
- >
44
+ onClick={handleClick}>
45
<span className={styles.ToggleContent} tabIndex={-1}>
46
{children}
47
</span>
packages/react-devtools-shared/src/devtools/views/WarnIfLegacyBackendDetected.js
+53
-50
@@ -1,67 +1,70 @@
1
// @flow
2
3
-import React, { Fragment, useContext, useEffect } from 'react';
4
-import { BridgeContext } from './context';
5
-import { ModalDialogContext } from './ModalDialog';
3
+import React, {Fragment, useContext, useEffect} from 'react';
4
+import {BridgeContext} from './context';
5
+import {ModalDialogContext} from './ModalDialog';
6
7
import styles from './WarnIfLegacyBackendDetected.css';
8
9
export default function WarnIfLegacyBackendDetected(_: {||}) {
10
const bridge = useContext(BridgeContext);
11
- const { dispatch } = useContext(ModalDialogContext);
11
+ const {dispatch} = useContext(ModalDialogContext);
12
13
// Detect pairing with legacy v3 backend.
14
// We do this by listening to a message that it broadcasts but the v4 backend doesn't.
15
// In this case the frontend should show upgrade instructions.
16
- useEffect(() => {
17
- // Wall.listen returns a cleanup function
18
- let unlisten = bridge.wall.listen(message => {
19
- switch (message.type) {
20
- case 'call':
21
- case 'event':
22
- case 'many-events':
23
- // Any of these types indicate the v3 backend.
24
- dispatch({
25
- canBeDismissed: false,
26
- type: 'SHOW',
27
- title: 'DevTools v4 is incompatible with this version of React',
28
- content: <InvalidBackendDetected />,
29
- });
16
+ useEffect(
17
+ () => {
18
+ // Wall.listen returns a cleanup function
19
+ let unlisten = bridge.wall.listen(message => {
20
+ switch (message.type) {
21
+ case 'call':
22
+ case 'event':
23
+ case 'many-events':
24
+ // Any of these types indicate the v3 backend.
25
+ dispatch({
26
+ canBeDismissed: false,
27
+ type: 'SHOW',
28
+ title: 'DevTools v4 is incompatible with this version of React',
29
+ content: <InvalidBackendDetected />,
30
+ });
31
31
- // Once we've identified the backend version, it's safe to unsubscribe.
32
- if (typeof unlisten === 'function') {
33
- unlisten();
34
- unlisten = null;
35
- }
36
- break;
37
- default:
38
- break;
39
- }
32
+ // Once we've identified the backend version, it's safe to unsubscribe.
33
+ if (typeof unlisten === 'function') {
34
+ unlisten();
35
+ unlisten = null;
36
+ }
37
+ break;
38
+ default:
39
+ break;
40
+ }
41
41
- switch (message.event) {
42
- case 'isBackendStorageAPISupported':
43
- case 'isNativeStyleEditorSupported':
44
- case 'operations':
45
- case 'overrideComponentFilters':
46
- // Any of these is sufficient to indicate a v4 backend.
47
- // Once we've identified the backend version, it's safe to unsubscribe.
48
- if (typeof unlisten === 'function') {
49
- unlisten();
50
- unlisten = null;
51
- }
52
- break;
53
- default:
54
- break;
55
- }
56
- });
42
+ switch (message.event) {
43
+ case 'isBackendStorageAPISupported':
44
+ case 'isNativeStyleEditorSupported':
45
+ case 'operations':
46
+ case 'overrideComponentFilters':
47
+ // Any of these is sufficient to indicate a v4 backend.
48
+ // Once we've identified the backend version, it's safe to unsubscribe.
49
+ if (typeof unlisten === 'function') {
50
+ unlisten();
51
+ unlisten = null;
52
+ }
53
+ break;
54
+ default:
55
+ break;
56
+ }
57
+ });
58
58
- return () => {
59
- if (typeof unlisten === 'function') {
60
- unlisten();
61
- unlisten = null;
62
- }
63
- };
64
- }, [bridge, dispatch]);
59
+ return () => {
60
+ if (typeof unlisten === 'function') {
61
+ unlisten();
62
+ unlisten = null;
63
+ }
64
+ };
65
+ },
66
+ [bridge, dispatch],
67
+ );
68
69
return null;
70
}
packages/react-devtools-shared/src/devtools/views/context.js
+3
-3
@@ -1,12 +1,12 @@
1
// @flow
2
3
-import { createContext } from 'react';
3
+import {createContext} from 'react';
4
import Store from '../store';
5
6
-import type { FrontendBridge } from 'react-devtools-shared/src/bridge';
6
+import type {FrontendBridge} from 'react-devtools-shared/src/bridge';
7
8
export const BridgeContext = createContext<FrontendBridge>(
9
- ((null: any): FrontendBridge)
9
+ ((null: any): FrontendBridge),
10
);
11
BridgeContext.displayName = 'BridgeContext';
12
packages/react-devtools-shared/src/devtools/views/hooks.js
+135
-117
@@ -1,37 +1,43 @@
1
// @flow
2
3
import throttle from 'lodash.throttle';
4
-import { useCallback, useEffect, useLayoutEffect, useState } from 'react';
5
-import { localStorageGetItem, localStorageSetItem } from 'react-devtools-shared/src/storage';
4
+import {useCallback, useEffect, useLayoutEffect, useState} from 'react';
5
+import {
6
+ localStorageGetItem,
7
+ localStorageSetItem,
8
+} from 'react-devtools-shared/src/storage';
9
10
export function useIsOverflowing(
8
- containerRef: { current: HTMLDivElement | null },
9
- totalChildWidth: number
11
+ containerRef: {current: HTMLDivElement | null},
12
+ totalChildWidth: number,
13
): boolean {
14
const [isOverflowing, setIsOverflowing] = useState<boolean>(false);
15
16
// It's important to use a layout effect, so that we avoid showing a flash of overflowed content.
14
- useLayoutEffect(() => {
15
- if (containerRef.current === null) {
16
- return () => {};
17
- }
17
+ useLayoutEffect(
18
+ () => {
19
+ if (containerRef.current === null) {
20
+ return () => {};
21
+ }
22
19
- const container = ((containerRef.current: any): HTMLDivElement);
23
+ const container = ((containerRef.current: any): HTMLDivElement);
24
21
- const handleResize = throttle(
22
- () => setIsOverflowing(container.clientWidth <= totalChildWidth),
23
- 100
24
- );
25
+ const handleResize = throttle(
26
+ () => setIsOverflowing(container.clientWidth <= totalChildWidth),
27
+ 100,
28
+ );
29
26
- handleResize();
30
+ handleResize();
31
28
- // It's important to listen to the ownerDocument.defaultView to support the browser extension.
29
- // Here we use portals to render individual tabs (e.g. Profiler),
30
- // and the root document might belong to a different window.
31
- const ownerWindow = container.ownerDocument.defaultView;
32
- ownerWindow.addEventListener('resize', handleResize);
33
- return () => ownerWindow.removeEventListener('resize', handleResize);
34
- }, [containerRef, totalChildWidth]);
32
+ // It's important to listen to the ownerDocument.defaultView to support the browser extension.
33
+ // Here we use portals to render individual tabs (e.g. Profiler),
34
+ // and the root document might belong to a different window.
35
+ const ownerWindow = container.ownerDocument.defaultView;
36
+ ownerWindow.addEventListener('resize', handleResize);
37
+ return () => ownerWindow.removeEventListener('resize', handleResize);
38
+ },
39
+ [containerRef, totalChildWidth],
40
+ );
41
42
return isOverflowing;
43
}
@@ -39,23 +45,26 @@ export function useIsOverflowing(
45
// Forked from https://usehooks.com/useLocalStorage/
46
export function useLocalStorage<T>(
47
key: string,
42
- initialValue: T | (() => T)
48
+ initialValue: T | (() => T),
49
): [T, (value: T | (() => T)) => void] {
44
- const getValueFromLocalStorage = useCallback(() => {
45
- try {
46
- const item = localStorageGetItem(key);
47
- if (item != null) {
48
- return JSON.parse(item);
50
+ const getValueFromLocalStorage = useCallback(
51
+ () => {
52
+ try {
53
+ const item = localStorageGetItem(key);
54
+ if (item != null) {
55
+ return JSON.parse(item);
56
+ }
57
+ } catch (error) {
58
+ console.log(error);
59
}
50
- } catch (error) {
51
- console.log(error);
52
- }
53
- if (typeof initialValue === 'function') {
54
- return ((initialValue: any): () => T)();
55
- } else {
56
- return initialValue;
57
- }
58
- }, [initialValue, key]);
60
+ if (typeof initialValue === 'function') {
61
+ return ((initialValue: any): () => T)();
62
+ } else {
63
+ return initialValue;
64
+ }
65
+ },
66
+ [initialValue, key],
67
+ );
68
69
const [storedValue, setStoredValue] = useState(getValueFromLocalStorage);
70
@@ -70,72 +79,78 @@ export function useLocalStorage<T>(
79
console.log(error);
80
}
81
},
73
- [key, storedValue]
82
+ [key, storedValue],
83
);
84
85
// Listen for changes to this local storage value made from other windows.
86
// This enables the e.g. "⚛️ Elements" tab to update in response to changes from "⚛️ Settings".
78
- useLayoutEffect(() => {
79
- const onStorage = event => {
80
- const newValue = getValueFromLocalStorage();
81
- if (key === event.key && storedValue !== newValue) {
82
- setValue(newValue);
83
- }
84
- };
87
+ useLayoutEffect(
88
+ () => {
89
+ const onStorage = event => {
90
+ const newValue = getValueFromLocalStorage();
91
+ if (key === event.key && storedValue !== newValue) {
92
+ setValue(newValue);
93
+ }
94
+ };
95
86
- window.addEventListener('storage', onStorage);
96
+ window.addEventListener('storage', onStorage);
97
88
- return () => {
89
- window.removeEventListener('storage', onStorage);
90
- };
91
- }, [getValueFromLocalStorage, key, storedValue, setValue]);
98
+ return () => {
99
+ window.removeEventListener('storage', onStorage);
100
+ };
101
+ },
102
+ [getValueFromLocalStorage, key, storedValue, setValue],
103
+ );
104
105
return [storedValue, setValue];
106
}
107
108
export function useModalDismissSignal(
97
- modalRef: { current: HTMLDivElement | null },
109
+ modalRef: {current: HTMLDivElement | null},
110
dismissCallback: () => void,
99
- dismissOnClickOutside?: boolean = true
111
+ dismissOnClickOutside?: boolean = true,
112
): void {
101
- useEffect(() => {
102
- if (modalRef.current === null) {
103
- return () => {};
104
- }
105
-
106
- const handleDocumentKeyDown = ({ key }: any) => {
107
- if (key === 'Escape') {
108
- dismissCallback();
113
+ useEffect(
114
+ () => {
115
+ if (modalRef.current === null) {
116
+ return () => {};
117
}
110
- };
111
-
112
- const handleDocumentClick = (event: any) => {
113
- // $FlowFixMe
114
- if (
115
- modalRef.current !== null &&
116
- !modalRef.current.contains(event.target)
117
- ) {
118
- event.stopPropagation();
119
- event.preventDefault();
120
-
121
- dismissCallback();
118
+
119
+ const handleDocumentKeyDown = ({key}: any) => {
120
+ if (key === 'Escape') {
121
+ dismissCallback();
122
+ }
123
+ };
124
+
125
+ const handleDocumentClick = (event: any) => {
126
+ // $FlowFixMe
127
+ if (
128
+ modalRef.current !== null &&
129
+ !modalRef.current.contains(event.target)
130
+ ) {
131
+ event.stopPropagation();
132
+ event.preventDefault();
133
+
134
+ dismissCallback();
135
+ }
136
+ };
137
+
138
+ // It's important to listen to the ownerDocument to support the browser extension.
139
+ // Here we use portals to render individual tabs (e.g. Profiler),
140
+ // and the root document might belong to a different window.
141
+ const ownerDocument = modalRef.current.ownerDocument;
142
+ ownerDocument.addEventListener('keydown', handleDocumentKeyDown);
143
+ if (dismissOnClickOutside) {
144
+ ownerDocument.addEventListener('click', handleDocumentClick);
145
}
123
- };
124
-
125
- // It's important to listen to the ownerDocument to support the browser extension.
126
- // Here we use portals to render individual tabs (e.g. Profiler),
127
- // and the root document might belong to a different window.
128
- const ownerDocument = modalRef.current.ownerDocument;
129
- ownerDocument.addEventListener('keydown', handleDocumentKeyDown);
130
- if (dismissOnClickOutside) {
131
- ownerDocument.addEventListener('click', handleDocumentClick);
132
- }
133
-
134
- return () => {
135
- ownerDocument.removeEventListener('keydown', handleDocumentKeyDown);
136
- ownerDocument.removeEventListener('click', handleDocumentClick);
137
- };
138
- }, [modalRef, dismissCallback, dismissOnClickOutside]);
146
+
147
+ return () => {
148
+ ownerDocument.removeEventListener('keydown', handleDocumentKeyDown);
149
+ ownerDocument.removeEventListener('click', handleDocumentClick);
150
+ };
151
+ },
152
+ [modalRef, dismissCallback, dismissOnClickOutside],
153
+ );
154
}
155
156
// Copied from https://github.com/facebook/react/pull/15022
@@ -163,39 +178,42 @@ export function useSubscription<Value>({
178
});
179
}
180
166
- useEffect(() => {
167
- let didUnsubscribe = false;
168
-
169
- const checkForUpdates = () => {
170
- if (didUnsubscribe) {
171
- return;
172
- }
181
+ useEffect(
182
+ () => {
183
+ let didUnsubscribe = false;
184
174
- setState(prevState => {
175
- if (
176
- prevState.getCurrentValue !== getCurrentValue ||
177
- prevState.subscribe !== subscribe
178
- ) {
179
- return prevState;
180
- }
181
-
182
- const value = getCurrentValue();
183
- if (prevState.value === value) {
184
- return prevState;
185
+ const checkForUpdates = () => {
186
+ if (didUnsubscribe) {
187
+ return;
188
}
189
187
- return { ...prevState, value };
188
- });
189
- };
190
- const unsubscribe = subscribe(checkForUpdates);
191
-
192
- checkForUpdates();
193
-
194
- return () => {
195
- didUnsubscribe = true;
196
- unsubscribe();
197
- };
198
- }, [getCurrentValue, subscribe]);
190
+ setState(prevState => {
191
+ if (
192
+ prevState.getCurrentValue !== getCurrentValue ||
193
+ prevState.subscribe !== subscribe
194
+ ) {
195
+ return prevState;
196
+ }
197
+
198
+ const value = getCurrentValue();
199
+ if (prevState.value === value) {
200
+ return prevState;
201
+ }
202
+
203
+ return {...prevState, value};
204
+ });
205
+ };
206
+ const unsubscribe = subscribe(checkForUpdates);
207
+
208
+ checkForUpdates();
209
+
210
+ return () => {
211
+ didUnsubscribe = true;
212
+ unsubscribe();
213
+ };
214
+ },
215
+ [getCurrentValue, subscribe],
216
+ );
217
218
return state.value;
219
}
packages/react-devtools-shared/src/devtools/views/portaledContent.js
+3
-3
@@ -1,7 +1,7 @@
1
// @flow
2
3
import React from 'react';
4
-import { createPortal } from 'react-dom';
4
+import {createPortal} from 'react-dom';
5
import ErrorBoundary from './ErrorBoundary';
6
7
export type Props = {
@@ -9,9 +9,9 @@ export type Props = {
9
};
10
11
export default function portaledContent(
12
- Component: React$StatelessFunctionalComponent<any>
12
+ Component: React$StatelessFunctionalComponent<any>,
13
): React$StatelessFunctionalComponent<any> {
14
- return function PortaledContent({ portalContainer, ...rest }: Props) {
14
+ return function PortaledContent({portalContainer, ...rest}: Props) {
15
const children = (
16
<ErrorBoundary>
17
<Component {...rest} />
packages/react-devtools-shared/src/devtools/views/utils.js
+5
-5
@@ -1,9 +1,9 @@
1
// @flow
2
3
import escapeStringRegExp from 'escape-string-regexp';
4
-import { meta } from '../../hydration';
4
+import {meta} from '../../hydration';
5
6
-import type { HooksTree } from 'react-debug-tools/src/ReactDebugHooks';
6
+import type {HooksTree} from 'react-debug-tools/src/ReactDebugHooks';
7
8
export function createRegExp(string: string): RegExp {
9
// Allow /regex/ syntax with optional last /
@@ -65,7 +65,7 @@ export function createRegExp(string: string): RegExp {
65
'|' +
66
firstChar.toUpperCase() +
67
')' +
68
- restRegex
68
+ restRegex,
69
);
70
}
71
@@ -157,7 +157,7 @@ export function serializeHooksForCopy(hooks: HooksTree | null): string {
157
let downloadUrl = null;
158
159
export function downloadFile(filename: string, text: string): void {
160
- const blob = new Blob([text], { type: 'text/plain;charset=utf-8' });
160
+ const blob = new Blob([text], {type: 'text/plain;charset=utf-8'});
161
162
if (downloadUrl !== null) {
163
URL.revokeObjectURL(downloadUrl);
@@ -177,7 +177,7 @@ export function downloadFile(filename: string, text: string): void {
177
}
178
179
export function truncateText(text: string, maxLength: number): string {
180
- const { length } = text;
180
+ const {length} = text;
181
if (length > maxLength) {
182
return (
183
text.substr(0, Math.floor(maxLength / 2)) +
packages/react-devtools-shared/src/hook.js
+5
-5
@@ -12,7 +12,7 @@ import {
12
registerRenderer as registerRendererWithConsole,
13
} from './backend/console';
14
15
-import type { DevToolsHook } from 'react-devtools-shared/src/backend/types';
15
+import type {DevToolsHook} from 'react-devtools-shared/src/backend/types';
16
17
declare var window: any;
18
@@ -44,7 +44,7 @@ export function installHook(target: any): DevToolsHook | null {
44
if (renderer.Mount && renderer.Mount._renderNewRootComponent) {
45
// React DOM Stack
46
const renderRootCode = toString.call(
47
- renderer.Mount._renderNewRootComponent
47
+ renderer.Mount._renderNewRootComponent,
48
);
49
// Filter out bad results (if that is even possible):
50
if (renderRootCode.indexOf('function') !== 0) {
@@ -143,7 +143,7 @@ export function installHook(target: any): DevToolsHook | null {
143
'React is running in production mode, but dead code ' +
144
'elimination has not been applied. Read how to correctly ' +
145
'configure React for production: ' +
146
- 'https://fb.me/react-perf-use-the-production-build'
146
+ 'https://fb.me/react-perf-use-the-production-build',
147
);
148
});
149
}
@@ -194,7 +194,7 @@ export function installHook(target: any): DevToolsHook | null {
194
hook.rendererInterfaces.set(id, rendererInterface);
195
}
196
197
- hook.emit('renderer', { id, renderer, reactBuildType });
197
+ hook.emit('renderer', {id, renderer, reactBuildType});
198
199
return id;
200
}
@@ -305,7 +305,7 @@ export function installHook(target: any): DevToolsHook | null {
305
get() {
306
return hook;
307
},
308
- }: Object)
308
+ }: Object),
309
);
310
311
return hook;
packages/react-devtools-shared/src/hydration.js
+16
-12
@@ -16,7 +16,7 @@ import {
16
StrictMode,
17
Suspense,
18
} from 'react-is';
19
-import { getDisplayName, getInObject, setInObject } from './utils';
19
+import {getDisplayName, getInObject, setInObject} from './utils';
20
21
export const meta = {
22
inspectable: Symbol('inspectable'),
@@ -126,7 +126,7 @@ function createDehydrated(
126
inspectable: boolean,
127
data: Object,
128
cleaned: Array<Array<string | number>>,
129
- path: Array<string | number>
129
+ path: Array<string | number>,
130
): Dehydrated {
131
cleaned.push(path);
132
@@ -175,8 +175,12 @@ export function dehydrate(
175
cleaned: Array<Array<string | number>>,
176
path: Array<string | number>,
177
isPathWhitelisted: (path: Array<string | number>) => boolean,
178
- level?: number = 0
179
-): string | Dehydrated | Array<Dehydrated> | { [key: string]: string | Dehydrated } {
178
+ level?: number = 0,
179
+):
180
+ | string
181
+ | Dehydrated
182
+ | Array<Dehydrated>
183
+ | {[key: string]: string | Dehydrated} {
184
const type = getDataType(data);
185
186
switch (type) {
@@ -239,8 +243,8 @@ export function dehydrate(
243
cleaned,
244
path.concat([i]),
245
isPathWhitelisted,
242
- arrayPathCheck ? 1 : level + 1
243
- )
246
+ arrayPathCheck ? 1 : level + 1,
247
+ ),
248
);
249
250
case 'typed_array':
@@ -267,7 +271,7 @@ export function dehydrate(
271
cleaned,
272
path.concat([name]),
273
isPathWhitelisted,
270
- objectPathCheck ? 1 : level + 1
274
+ objectPathCheck ? 1 : level + 1,
275
);
276
}
277
return object;
@@ -291,7 +295,7 @@ export function dehydrate(
295
export function fillInPath(
296
object: Object,
297
path: Array<string | number>,
294
- value: any
298
+ value: any,
299
) {
300
const target = getInObject(object, path);
301
if (target != null) {
@@ -307,7 +311,7 @@ export function fillInPath(
311
312
export function hydrate(
313
object: Object,
310
- cleaned: Array<Array<string | number>>
314
+ cleaned: Array<Array<string | number>>,
315
): Object {
316
cleaned.forEach((path: Array<string | number>) => {
317
const length = path.length;
@@ -327,7 +331,7 @@ export function hydrate(
331
parent[last] = undefined;
332
} else {
333
// Replace the string keys with Symbols so they're non-enumerable.
330
- const replaced: { [key: Symbol]: boolean | string } = {};
334
+ const replaced: {[key: Symbol]: boolean | string} = {};
335
replaced[meta.inspectable] = !!value.inspectable;
336
replaced[meta.inspected] = false;
337
replaced[meta.name] = value.name;
@@ -342,7 +346,7 @@ export function hydrate(
346
}
347
348
export function getDisplayNameForReactElement(
345
- element: React$Element<any>
349
+ element: React$Element<any>,
350
): string | null {
351
const elementType = typeOf(element);
352
switch (elementType) {
@@ -370,7 +374,7 @@ export function getDisplayNameForReactElement(
374
case Suspense:
375
return 'Suspense';
376
default:
373
- const { type } = element;
377
+ const {type} = element;
378
if (typeof type === 'string') {
379
return type;
380
} else if (type != null) {
packages/react-devtools-shared/src/utils.js
+13
-13
@@ -7,31 +7,31 @@ import {
7
TREE_OPERATION_REORDER_CHILDREN,
8
TREE_OPERATION_UPDATE_TREE_BASE_DURATION,
9
} from './constants';
10
-import { ElementTypeRoot } from 'react-devtools-shared/src/types';
10
+import {ElementTypeRoot} from 'react-devtools-shared/src/types';
11
import {
12
LOCAL_STORAGE_FILTER_PREFERENCES_KEY,
13
LOCAL_STORAGE_SHOULD_PATCH_CONSOLE_KEY,
14
} from './constants';
15
-import { ComponentFilterElementType, ElementTypeHostComponent } from './types';
15
+import {ComponentFilterElementType, ElementTypeHostComponent} from './types';
16
import {
17
ElementTypeClass,
18
ElementTypeForwardRef,
19
ElementTypeFunction,
20
ElementTypeMemo,
21
} from 'react-devtools-shared/src/types';
22
-import { localStorageGetItem, localStorageSetItem } from './storage';
22
+import {localStorageGetItem, localStorageSetItem} from './storage';
23
24
-import type { ComponentFilter, ElementType } from './types';
24
+import type {ComponentFilter, ElementType} from './types';
25
26
const cachedDisplayNames: WeakMap<Function, string> = new WeakMap();
27
28
// On large trees, encoding takes significant time.
29
// Try to reuse the already encoded strings.
30
-let encodedStringCache = new LRU({ max: 1000 });
30
+let encodedStringCache = new LRU({max: 1000});
31
32
export function getDisplayName(
33
type: Function,
34
- fallbackName: string = 'Anonymous'
34
+ fallbackName: string = 'Anonymous',
35
): string {
36
const nameFromCache = cachedDisplayNames.get(type);
37
if (nameFromCache != null) {
@@ -97,7 +97,7 @@ export function printOperationsArray(operations: Array<number>) {
97
while (i < stringTableEnd) {
98
const nextLength = operations[i++];
99
const nextString = utfDecodeString(
100
- (operations.slice(i, i + nextLength): any)
100
+ (operations.slice(i, i + nextLength): any),
101
);
102
stringTable.push(nextString);
103
i += nextLength;
@@ -131,7 +131,7 @@ export function printOperationsArray(operations: Array<number>) {
131
i++; // key
132
133
logs.push(
134
- `Add node ${id} (${displayName || 'null'}) as child of ${parentID}`
134
+ `Add node ${id} (${displayName || 'null'}) as child of ${parentID}`,
135
);
136
}
137
break;
@@ -193,11 +193,11 @@ export function getSavedComponentFilters(): Array<ComponentFilter> {
193
}
194
195
export function saveComponentFilters(
196
- componentFilters: Array<ComponentFilter>
196
+ componentFilters: Array<ComponentFilter>,
197
): void {
198
localStorageSetItem(
199
LOCAL_STORAGE_FILTER_PREFERENCES_KEY,
200
- JSON.stringify(componentFilters)
200
+ JSON.stringify(componentFilters),
201
);
202
}
203
@@ -214,13 +214,13 @@ export function getAppendComponentStack(): boolean {
214
export function setAppendComponentStack(value: boolean): void {
215
localStorageSetItem(
216
LOCAL_STORAGE_SHOULD_PATCH_CONSOLE_KEY,
217
- JSON.stringify(value)
217
+ JSON.stringify(value),
218
);
219
}
220
221
export function separateDisplayNameAndHOCs(
222
displayName: string | null,
223
- type: ElementType
223
+ type: ElementType,
224
): [string | null, Array<string> | null] {
225
if (displayName === null) {
226
return [null, null];
@@ -279,7 +279,7 @@ export function getInObject(object: Object, path: Array<string | number>): any {
279
export function setInObject(
280
object: Object,
281
path: Array<string | number>,
282
- value: any
282
+ value: any,
283
) {
284
const length = path.length;
285
const last = path[length - 1];
packages/react-devtools/app.js
+3
-3
@@ -1,7 +1,7 @@
1
// @flow
2
3
-const { app, BrowserWindow } = require('electron'); // Module to create native browser window.
4
-const { join } = require('path');
3
+const {app, BrowserWindow} = require('electron'); // Module to create native browser window.
4
+const {join} = require('path');
5
6
const argv = require('minimist')(process.argv.slice(2));
7
const projectRoots = argv._;
@@ -31,7 +31,7 @@ app.on('ready', function() {
31
// We use this so that RN can keep relative JSX __source filenames
32
// but "click to open in editor" still works. js1 passes project roots
33
// as the argument to DevTools.
34
- 'window.devtools.setProjectRoots(' + JSON.stringify(projectRoots) + ')'
34
+ 'window.devtools.setProjectRoots(' + JSON.stringify(projectRoots) + ')',
35
);
36
37
// Emitted when the window is closed.
packages/react-devtools/bin.js
+1
-1
@@ -9,7 +9,7 @@ const pkg = require('./package.json');
9
const updateNotifier = require('update-notifier');
10
11
// notify if there's an update
12
-updateNotifier({ pkg }).notify({ defer: false });
12
+updateNotifier({pkg}).notify({defer: false});
13
14
const result = spawn.sync(electron, [require.resolve('./app')].concat(argv), {
15
stdio: 'ignore',
packages/react-devtools/index.js
+1
-1
@@ -1,6 +1,6 @@
1
// @flow
2
3
-const { connectToDevTools } = require('react-devtools-core/backend');
3
+const {connectToDevTools} = require('react-devtools-core/backend');
4
5
// Connect immediately with default options.
6
// If you need more control, use `react-devtools-core` directly instead of `react-devtools`.