Run prettier
Sebastian Markbage committed
Mar 13, 2017 at 17:05 UTC
1843f8716803d380df34a7362d80022352853931
325 files changed
+12714
-11413
src/__mocks__/InitializeCore.js
+1
@@ -12,3 +12,4 @@
12
// Noop
13
14
// TODO #10932517: Move all initialization callers back into react-native
15
+
src/__mocks__/deepDiffer.js
+3
-3
@@ -16,15 +16,15 @@ var deepDiffer = function(one: any, two: any): boolean {
16
// Short circuit on identical object references instead of traversing them.
17
return false;
18
}
19
- if ((typeof one === 'function') && (typeof two === 'function')) {
19
+ if (typeof one === 'function' && typeof two === 'function') {
20
// We consider all functions equal
21
return false;
22
}
23
- if ((typeof one !== 'object') || (one === null)) {
23
+ if (typeof one !== 'object' || one === null) {
24
// Primitives can be directly compared
25
return one !== two;
26
}
27
- if ((typeof two !== 'object') || (two === null)) {
27
+ if (typeof two !== 'object' || two === null) {
28
// We know they are different because the previous case would have triggered
29
// otherwise.
30
return true;
src/__mocks__/deepFreezeAndThrowOnMutationInDev.js
+1
-1
@@ -11,6 +11,6 @@
11
12
// TODO: move into react or fbjs
13
14
-var deepFreezeAndThrowOnMutationInDev = function() { };
14
+var deepFreezeAndThrowOnMutationInDev = function() {};
15
16
module.exports = deepFreezeAndThrowOnMutationInDev;
src/__mocks__/flattenStyle.js
+1
-1
@@ -11,6 +11,6 @@
11
12
// TODO: Move flattenStyle into react
13
14
-var flattenStyle = function() { };
14
+var flattenStyle = function() {};
15
16
module.exports = flattenStyle;
src/addons/ReactFragment.js
+5
-5
@@ -41,7 +41,7 @@ var ReactFragment = {
41
warning(
42
false,
43
'React.addons.createFragment only accepts a single object. Got: %s',
44
- object
44
+ object,
45
);
46
return object;
47
}
@@ -49,7 +49,7 @@ var ReactFragment = {
49
warning(
50
false,
51
'React.addons.createFragment does not accept a ReactElement ' +
52
- 'without a wrapper object.'
52
+ 'without a wrapper object.',
53
);
54
return object;
55
}
@@ -57,7 +57,7 @@ var ReactFragment = {
57
invariant(
58
object.nodeType !== 1,
59
'React.addons.createFragment(...): Encountered an invalid child; DOM ' +
60
- 'elements are not valid children of React components.'
60
+ 'elements are not valid children of React components.',
61
);
62
63
var result = [];
@@ -68,7 +68,7 @@ var ReactFragment = {
68
warning(
69
false,
70
'React.addons.createFragment(...): Child objects should have ' +
71
- 'non-numeric keys so ordering is preserved.'
71
+ 'non-numeric keys so ordering is preserved.',
72
);
73
warnedAboutNumeric = true;
74
}
@@ -77,7 +77,7 @@ var ReactFragment = {
77
object[key],
78
result,
79
key,
80
- emptyFunction.thatReturnsArgument
80
+ emptyFunction.thatReturnsArgument,
81
);
82
}
83
src/addons/ReactWithAddons.js
+1
-2
@@ -13,8 +13,7 @@
13
14
var React = require('react');
15
var ReactAddonsDOMDependencies = require('ReactAddonsDOMDependencies');
16
-var ReactComponentWithPureRenderMixin =
17
- require('ReactComponentWithPureRenderMixin');
16
+var ReactComponentWithPureRenderMixin = require('ReactComponentWithPureRenderMixin');
17
var ReactCSSTransitionGroup = require('ReactCSSTransitionGroup');
18
var ReactFragment = require('ReactFragment');
19
var ReactTransitionGroup = require('ReactTransitionGroup');
src/addons/__tests__/ReactComponentWithPureRenderMixin-test.js
+2
-10
@@ -16,11 +16,9 @@ var ReactComponentWithPureRenderMixin;
16
var ReactTestUtils;
17
18
describe('ReactComponentWithPureRenderMixin', () => {
19
-
19
beforeEach(() => {
20
React = require('react');
22
- ReactComponentWithPureRenderMixin =
23
- require('ReactComponentWithPureRenderMixin');
21
+ ReactComponentWithPureRenderMixin = require('ReactComponentWithPureRenderMixin');
22
ReactTestUtils = require('ReactTestUtils');
23
});
24
@@ -35,12 +33,7 @@ describe('ReactComponentWithPureRenderMixin', () => {
33
}
34
35
render() {
38
- return (
39
- <Apple
40
- color={this.state.color}
41
- ref="apple"
42
- />
43
- );
36
+ return <Apple color={this.state.color} ref="apple" />;
37
}
38
}
39
@@ -141,5 +134,4 @@ describe('ReactComponentWithPureRenderMixin', () => {
134
instance.setState(getInitialState());
135
expect(renderCalls).toBe(3);
136
});
144
-
137
});
src/addons/__tests__/ReactFragment-test.js
+10
-12
@@ -16,7 +16,6 @@ var ReactDOM;
16
var ReactFragment;
17
18
describe('ReactFragment', () => {
19
-
19
beforeEach(() => {
20
React = require('react');
21
ReactDOM = require('react-dom');
@@ -33,9 +32,9 @@ describe('ReactFragment', () => {
32
var container = document.createElement('div');
33
expect(() => ReactDOM.render(element, container)).toThrowError(
34
'Objects are not valid as a React child (found: object with keys ' +
36
- '{x, y, z}). If you meant to render a collection of children, use an ' +
37
- 'array instead or wrap the object using createFragment(object) from ' +
38
- 'the React add-ons.'
35
+ '{x, y, z}). If you meant to render a collection of children, use an ' +
36
+ 'array instead or wrap the object using createFragment(object) from ' +
37
+ 'the React add-ons.',
38
);
39
});
40
@@ -53,9 +52,9 @@ describe('ReactFragment', () => {
52
var container = document.createElement('div');
53
expect(() => ReactDOM.render(<Foo />, container)).toThrowError(
54
'Objects are not valid as a React child (found: object with keys ' +
56
- '{a, b, c}). If you meant to render a collection of children, use an ' +
57
- 'array instead or wrap the object using createFragment(object) from ' +
58
- 'the React add-ons.\n\nCheck the render method of `Foo`.'
55
+ '{a, b, c}). If you meant to render a collection of children, use an ' +
56
+ 'array instead or wrap the object using createFragment(object) from ' +
57
+ 'the React add-ons.\n\nCheck the render method of `Foo`.',
58
);
59
});
60
@@ -66,7 +65,7 @@ describe('ReactFragment', () => {
65
66
expectDev(console.error.calls.count()).toBe(1);
67
expectDev(console.error.calls.argsFor(0)[0]).toContain(
69
- 'Child objects should have non-numeric keys so ordering is preserved.'
68
+ 'Child objects should have non-numeric keys so ordering is preserved.',
69
);
70
});
71
@@ -75,7 +74,7 @@ describe('ReactFragment', () => {
74
ReactFragment.create(null);
75
expectDev(console.error.calls.count()).toBe(1);
76
expectDev(console.error.calls.argsFor(0)[0]).toContain(
78
- 'React.addons.createFragment only accepts a single object.'
77
+ 'React.addons.createFragment only accepts a single object.',
78
);
79
});
80
@@ -84,7 +83,7 @@ describe('ReactFragment', () => {
83
ReactFragment.create([]);
84
expectDev(console.error.calls.count()).toBe(1);
85
expectDev(console.error.calls.argsFor(0)[0]).toContain(
87
- 'React.addons.createFragment only accepts a single object.'
86
+ 'React.addons.createFragment only accepts a single object.',
87
);
88
});
89
@@ -94,8 +93,7 @@ describe('ReactFragment', () => {
93
expectDev(console.error.calls.count()).toBe(1);
94
expectDev(console.error.calls.argsFor(0)[0]).toContain(
95
'React.addons.createFragment does not accept a ReactElement without a ' +
97
- 'wrapper object.'
96
+ 'wrapper object.',
97
);
98
});
100
-
99
});
src/addons/__tests__/renderSubtreeIntoContainer-test.js
+5
-5
@@ -17,7 +17,6 @@ var ReactTestUtils = require('ReactTestUtils');
17
var renderSubtreeIntoContainer = require('renderSubtreeIntoContainer');
18
19
describe('renderSubtreeIntoContainer', () => {
20
-
20
it('should pass context when rendering subtree elsewhere', () => {
21
var portal = document.createElement('div');
22
@@ -47,9 +46,11 @@ describe('renderSubtreeIntoContainer', () => {
46
}
47
48
componentDidMount() {
50
- expect(function() {
51
- renderSubtreeIntoContainer(this, <Component />, portal);
52
- }.bind(this)).not.toThrow();
49
+ expect(
50
+ function() {
51
+ renderSubtreeIntoContainer(this, <Component />, portal);
52
+ }.bind(this),
53
+ ).not.toThrow();
54
}
55
}
56
@@ -296,5 +297,4 @@ describe('renderSubtreeIntoContainer', () => {
297
ReactDOM.render(<Parent value="foo" />, container);
298
expect(portal2.textContent).toBe('foo');
299
});
299
-
300
});
src/addons/__tests__/update-test.js
+39
-35
@@ -14,7 +14,6 @@
14
var update = require('update');
15
16
describe('update', () => {
17
-
17
describe('$push', () => {
18
it('pushes', () => {
19
expect(update([1], {$push: [7]})).toEqual([1, 7]);
@@ -27,12 +26,12 @@ describe('update', () => {
26
it('only pushes an array', () => {
27
expect(update.bind(null, [], {$push: 7})).toThrowError(
28
'update(): expected spec of $push to be an array; got 7. Did you ' +
30
- 'forget to wrap your parameter in an array?'
29
+ 'forget to wrap your parameter in an array?',
30
);
31
});
32
it('only pushes unto an array', () => {
33
expect(update.bind(null, 1, {$push: 7})).toThrowError(
35
- 'update(): expected target of $push to be an array; got 1.'
34
+ 'update(): expected target of $push to be an array; got 1.',
35
);
36
});
37
});
@@ -49,12 +48,12 @@ describe('update', () => {
48
it('only unshifts an array', () => {
49
expect(update.bind(null, [], {$unshift: 7})).toThrowError(
50
'update(): expected spec of $unshift to be an array; got 7. Did you ' +
52
- 'forget to wrap your parameter in an array?'
51
+ 'forget to wrap your parameter in an array?',
52
);
53
});
54
it('only unshifts unto an array', () => {
55
expect(update.bind(null, 1, {$unshift: 7})).toThrowError(
57
- 'update(): expected target of $unshift to be an array; got 1.'
56
+ 'update(): expected target of $unshift to be an array; got 1.',
57
);
58
});
59
});
@@ -71,16 +70,16 @@ describe('update', () => {
70
it('only splices an array of arrays', () => {
71
expect(update.bind(null, [], {$splice: 1})).toThrowError(
72
'update(): expected spec of $splice to be an array of arrays; got 1. ' +
74
- 'Did you forget to wrap your parameters in an array?'
73
+ 'Did you forget to wrap your parameters in an array?',
74
);
75
expect(update.bind(null, [], {$splice: [1]})).toThrowError(
76
'update(): expected spec of $splice to be an array of arrays; got 1. ' +
78
- 'Did you forget to wrap your parameters in an array?'
77
+ 'Did you forget to wrap your parameters in an array?',
78
);
79
});
80
it('only splices unto an array', () => {
81
expect(update.bind(null, 1, {$splice: 7})).toThrowError(
83
- 'Expected $splice target to be an array; got 1'
82
+ 'Expected $splice target to be an array; got 1',
83
);
84
});
85
});
@@ -96,12 +95,12 @@ describe('update', () => {
95
});
96
it('only merges with an object', () => {
97
expect(update.bind(null, {}, {$merge: 7})).toThrowError(
99
- 'update(): $merge expects a spec of type \'object\'; got 7'
98
+ "update(): $merge expects a spec of type 'object'; got 7",
99
);
100
});
101
it('only merges with an object', () => {
102
expect(update.bind(null, 7, {$merge: {a: 'b'}})).toThrowError(
104
- 'update(): $merge expects a target of type \'object\'; got 7'
103
+ "update(): $merge expects a target of type 'object'; got 7",
104
);
105
});
106
});
@@ -131,32 +130,37 @@ describe('update', () => {
130
});
131
it('only applies a function', () => {
132
expect(update.bind(null, 2, {$apply: 123})).toThrowError(
134
- 'update(): expected spec of $apply to be a function; got 123.'
133
+ 'update(): expected spec of $apply to be a function; got 123.',
134
);
135
});
136
});
137
138
it('should support deep updates', () => {
140
- expect(update({
141
- a: 'b',
142
- c: {
143
- d: 'e',
144
- f: [1],
145
- g: [2],
146
- h: [3],
147
- i: {j: 'k'},
148
- l: 4,
149
- },
150
- }, {
151
- c: {
152
- d: {$set: 'm'},
153
- f: {$push: [5]},
154
- g: {$unshift: [6]},
155
- h: {$splice: [[0, 1, 7]]},
156
- i: {$merge: {n: 'o'}},
157
- l: {$apply: (x) => x * 2},
158
- },
159
- })).toEqual({
139
+ expect(
140
+ update(
141
+ {
142
+ a: 'b',
143
+ c: {
144
+ d: 'e',
145
+ f: [1],
146
+ g: [2],
147
+ h: [3],
148
+ i: {j: 'k'},
149
+ l: 4,
150
+ },
151
+ },
152
+ {
153
+ c: {
154
+ d: {$set: 'm'},
155
+ f: {$push: [5]},
156
+ g: {$unshift: [6]},
157
+ h: {$splice: [[0, 1, 7]]},
158
+ i: {$merge: {n: 'o'}},
159
+ l: {$apply: x => x * 2},
160
+ },
161
+ },
162
+ ),
163
+ ).toEqual({
164
a: 'b',
165
c: {
166
d: 'm',
@@ -172,14 +176,14 @@ describe('update', () => {
176
it('should require a command', () => {
177
expect(update.bind(null, {a: 'b'}, {a: 'c'})).toThrowError(
178
'update(): You provided a key path to update() that did not contain ' +
175
- 'one of $push, $unshift, $splice, $set, $merge, $apply. Did you ' +
176
- 'forget to include {$set: ...}?'
179
+ 'one of $push, $unshift, $splice, $set, $merge, $apply. Did you ' +
180
+ 'forget to include {$set: ...}?',
181
);
182
});
183
184
it('should perform safe hasOwnProperty check', () => {
181
- expect(update({}, {'hasOwnProperty': {$set: 'a'}})).toEqual({
182
- 'hasOwnProperty': 'a',
185
+ expect(update({}, {hasOwnProperty: {$set: 'a'}})).toEqual({
186
+ hasOwnProperty: 'a',
187
});
188
});
189
});
src/addons/shallowCompare.js
+2
-4
@@ -19,10 +19,8 @@ var shallowEqual = require('fbjs/lib/shallowEqual');
19
* See also https://facebook.github.io/react/docs/shallow-compare.html
20
*/
21
function shallowCompare(instance, nextProps, nextState) {
22
- return (
23
- !shallowEqual(instance.props, nextProps) ||
24
- !shallowEqual(instance.state, nextState)
25
- );
22
+ return !shallowEqual(instance.props, nextProps) ||
23
+ !shallowEqual(instance.state, nextState);
24
}
25
26
module.exports = shallowCompare;
src/addons/transitions/ReactCSSTransitionGroup.js
+13
-10
@@ -26,16 +26,19 @@ function createTransitionTimeoutPropValidator(transitionType) {
26
// If no timeout duration is provided
27
if (props[timeoutPropName] == null) {
28
return new Error(
29
- timeoutPropName + ' wasn\'t supplied to ReactCSSTransitionGroup: ' +
30
- 'this can cause unreliable animations and won\'t be supported in ' +
31
- 'a future version of React. See ' +
32
- 'https://fb.me/react-animation-transition-group-timeout for more ' +
33
- 'information.'
29
+ timeoutPropName +
30
+ " wasn't supplied to ReactCSSTransitionGroup: " +
31
+ "this can cause unreliable animations and won't be supported in " +
32
+ 'a future version of React. See ' +
33
+ 'https://fb.me/react-animation-transition-group-timeout for more ' +
34
+ 'information.',
35
);
36
36
- // If the duration isn't a number
37
+ // If the duration isn't a number
38
} else if (typeof props[timeoutPropName] !== 'number') {
38
- return new Error(timeoutPropName + ' must be a number (in milliseconds)');
39
+ return new Error(
40
+ timeoutPropName + ' must be a number (in milliseconds)',
41
+ );
42
}
43
}
44
};
@@ -66,7 +69,7 @@ class ReactCSSTransitionGroup extends React.Component {
69
transitionLeave: true,
70
};
71
69
- _wrapChild = (child) => {
72
+ _wrapChild = child => {
73
// We need to provide this childFactory so that
74
// ReactCSSTransitionGroupChild can receive updates to name, enter, and
75
// leave while it is leaving.
@@ -81,14 +84,14 @@ class ReactCSSTransitionGroup extends React.Component {
84
enterTimeout: this.props.transitionEnterTimeout,
85
leaveTimeout: this.props.transitionLeaveTimeout,
86
},
84
- child
87
+ child,
88
);
89
};
90
91
render() {
92
return React.createElement(
93
ReactTransitionGroup,
91
- Object.assign({}, this.props, {childFactory: this._wrapChild})
94
+ Object.assign({}, this.props, {childFactory: this._wrapChild}),
95
);
96
}
97
}
src/addons/transitions/ReactCSSTransitionGroupChild.js
+4
-2
@@ -63,8 +63,10 @@ var ReactCSSTransitionGroupChild = React.createClass({
63
return;
64
}
65
66
- var className = this.props.name[animationType] || this.props.name + '-' + animationType;
67
- var activeClassName = this.props.name[animationType + 'Active'] || className + '-active';
66
+ var className = this.props.name[animationType] ||
67
+ this.props.name + '-' + animationType;
68
+ var activeClassName = this.props.name[animationType + 'Active'] ||
69
+ className + '-active';
70
var timeout = null;
71
72
var endListener = function(e) {
src/addons/transitions/ReactTransitionChildMapping.js
+1
-1
@@ -86,7 +86,7 @@ var ReactTransitionChildMapping = {
86
for (i = 0; i < nextKeysPending[nextKey].length; i++) {
87
var pendingNextKey = nextKeysPending[nextKey][i];
88
childMapping[nextKeysPending[nextKey][i]] = getValueForKey(
89
- pendingNextKey
89
+ pendingNextKey,
90
);
91
}
92
}
src/addons/transitions/ReactTransitionGroup.js
+30
-30
@@ -56,14 +56,14 @@ class ReactTransitionGroup extends React.Component {
56
57
componentWillReceiveProps(nextProps) {
58
var nextChildMapping = ReactTransitionChildMapping.getChildMapping(
59
- nextProps.children
59
+ nextProps.children,
60
);
61
var prevChildMapping = this.state.children;
62
63
this.setState({
64
children: ReactTransitionChildMapping.mergeChildMappings(
65
prevChildMapping,
66
- nextChildMapping
66
+ nextChildMapping,
67
),
68
});
69
@@ -71,16 +71,22 @@ class ReactTransitionGroup extends React.Component {
71
72
for (key in nextChildMapping) {
73
var hasPrev = prevChildMapping && prevChildMapping.hasOwnProperty(key);
74
- if (nextChildMapping[key] && !hasPrev &&
75
- !this.currentlyTransitioningKeys[key]) {
74
+ if (
75
+ nextChildMapping[key] &&
76
+ !hasPrev &&
77
+ !this.currentlyTransitioningKeys[key]
78
+ ) {
79
this.keysToEnter.push(key);
80
}
81
}
82
83
for (key in prevChildMapping) {
84
var hasNext = nextChildMapping && nextChildMapping.hasOwnProperty(key);
82
- if (prevChildMapping[key] && !hasNext &&
83
- !this.currentlyTransitioningKeys[key]) {
85
+ if (
86
+ prevChildMapping[key] &&
87
+ !hasNext &&
88
+ !this.currentlyTransitioningKeys[key]
89
+ ) {
90
this.keysToLeave.push(key);
91
}
92
}
@@ -98,21 +104,19 @@ class ReactTransitionGroup extends React.Component {
104
keysToLeave.forEach(this.performLeave);
105
}
106
101
- performAppear = (key) => {
107
+ performAppear = key => {
108
this.currentlyTransitioningKeys[key] = true;
109
110
var component = this.refs[key];
111
112
if (component.componentWillAppear) {
107
- component.componentWillAppear(
108
- this._handleDoneAppearing.bind(this, key)
109
- );
113
+ component.componentWillAppear(this._handleDoneAppearing.bind(this, key));
114
} else {
115
this._handleDoneAppearing(key);
116
}
117
};
118
115
- _handleDoneAppearing = (key) => {
119
+ _handleDoneAppearing = key => {
120
var component = this.refs[key];
121
if (component.componentDidAppear) {
122
component.componentDidAppear();
@@ -121,7 +125,7 @@ class ReactTransitionGroup extends React.Component {
125
delete this.currentlyTransitioningKeys[key];
126
127
var currentChildMapping = ReactTransitionChildMapping.getChildMapping(
124
- this.props.children
128
+ this.props.children,
129
);
130
131
if (!currentChildMapping || !currentChildMapping.hasOwnProperty(key)) {
@@ -130,21 +134,19 @@ class ReactTransitionGroup extends React.Component {
134
}
135
};
136
133
- performEnter = (key) => {
137
+ performEnter = key => {
138
this.currentlyTransitioningKeys[key] = true;
139
140
var component = this.refs[key];
141
142
if (component.componentWillEnter) {
139
- component.componentWillEnter(
140
- this._handleDoneEntering.bind(this, key)
141
- );
143
+ component.componentWillEnter(this._handleDoneEntering.bind(this, key));
144
} else {
145
this._handleDoneEntering(key);
146
}
147
};
148
147
- _handleDoneEntering = (key) => {
149
+ _handleDoneEntering = key => {
150
var component = this.refs[key];
151
if (component.componentDidEnter) {
152
component.componentDidEnter();
@@ -153,7 +155,7 @@ class ReactTransitionGroup extends React.Component {
155
delete this.currentlyTransitioningKeys[key];
156
157
var currentChildMapping = ReactTransitionChildMapping.getChildMapping(
156
- this.props.children
158
+ this.props.children,
159
);
160
161
if (!currentChildMapping || !currentChildMapping.hasOwnProperty(key)) {
@@ -162,7 +164,7 @@ class ReactTransitionGroup extends React.Component {
164
}
165
};
166
165
- performLeave = (key) => {
167
+ performLeave = key => {
168
this.currentlyTransitioningKeys[key] = true;
169
170
var component = this.refs[key];
@@ -176,7 +178,7 @@ class ReactTransitionGroup extends React.Component {
178
}
179
};
180
179
- _handleDoneLeaving = (key) => {
181
+ _handleDoneLeaving = key => {
182
var component = this.refs[key];
183
184
if (component.componentDidLeave) {
@@ -186,7 +188,7 @@ class ReactTransitionGroup extends React.Component {
188
delete this.currentlyTransitioningKeys[key];
189
190
var currentChildMapping = ReactTransitionChildMapping.getChildMapping(
189
- this.props.children
191
+ this.props.children,
192
);
193
194
if (currentChildMapping && currentChildMapping.hasOwnProperty(key)) {
@@ -213,10 +215,12 @@ class ReactTransitionGroup extends React.Component {
215
// already been removed. In case you need this behavior you can provide
216
// a childFactory function to wrap every child, even the ones that are
217
// leaving.
216
- childrenToRender.push(React.cloneElement(
217
- this.props.childFactory(child),
218
- {ref: key, key: key}
219
- ));
218
+ childrenToRender.push(
219
+ React.cloneElement(this.props.childFactory(child), {
220
+ ref: key,
221
+ key: key,
222
+ }),
223
+ );
224
}
225
}
226
@@ -232,11 +236,7 @@ class ReactTransitionGroup extends React.Component {
236
delete props.transitionAppearTimeout;
237
delete props.component;
238
235
- return React.createElement(
236
- this.props.component,
237
- props,
238
- childrenToRender
239
- );
239
+ return React.createElement(this.props.component, props, childrenToRender);
240
}
241
}
242
src/addons/transitions/__tests__/ReactCSSTransitionGroup-test.js
+43
-48
@@ -32,16 +32,15 @@ describe('ReactCSSTransitionGroup', () => {
32
spyOn(console, 'error');
33
});
34
35
- it('should warn if timeouts aren\'t specified', () => {
35
+ it("should warn if timeouts aren't specified", () => {
36
ReactDOM.render(
37
<ReactCSSTransitionGroup
38
transitionName="yolo"
39
transitionEnter={false}
40
- transitionLeave={true}
41
- >
40
+ transitionLeave={true}>
41
<span key="one" id="one" />
42
</ReactCSSTransitionGroup>,
44
- container
43
+ container,
44
);
45
46
// Warning about the missing transitionLeaveTimeout prop
@@ -54,11 +53,10 @@ describe('ReactCSSTransitionGroup', () => {
53
transitionName="yolo"
54
transitionEnter={false}
55
transitionLeave={true}
57
- transitionLeaveTimeout={0}
58
- >
56
+ transitionLeaveTimeout={0}>
57
<span key="one" id="one" />
58
</ReactCSSTransitionGroup>,
61
- container
59
+ container,
60
);
61
62
expectDev(console.error.calls.count()).toBe(0);
@@ -69,11 +67,10 @@ describe('ReactCSSTransitionGroup', () => {
67
<ReactCSSTransitionGroup
68
transitionName="yolo"
69
transitionEnter={false}
72
- transitionLeaveTimeout={200}
73
- >
70
+ transitionLeaveTimeout={200}>
71
<span key="one" id="one" />
72
</ReactCSSTransitionGroup>,
76
- container
73
+ container,
74
);
75
expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(1);
76
@@ -83,11 +80,10 @@ describe('ReactCSSTransitionGroup', () => {
80
<ReactCSSTransitionGroup
81
transitionName="yolo"
82
transitionEnter={false}
86
- transitionLeaveTimeout={200}
87
- >
83
+ transitionLeaveTimeout={200}>
84
<span key="two" id="two" />
85
</ReactCSSTransitionGroup>,
90
- container
86
+ container,
87
);
88
expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(2);
89
expect(ReactDOM.findDOMNode(a).childNodes[0].id).toBe('two');
@@ -115,14 +111,14 @@ describe('ReactCSSTransitionGroup', () => {
111
<ReactCSSTransitionGroup transitionName="yolo">
112
<span key="one" id="one" />
113
</ReactCSSTransitionGroup>,
118
- container
114
+ container,
115
);
116
expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(1);
117
ReactDOM.render(
118
<ReactCSSTransitionGroup transitionName="yolo">
119
<span key="two" id="two" />
120
</ReactCSSTransitionGroup>,
125
- container
121
+ container,
122
);
123
expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(2);
124
expect(ReactDOM.findDOMNode(a).childNodes[0].id).toBe('two');
@@ -132,32 +128,32 @@ describe('ReactCSSTransitionGroup', () => {
128
it('should switch transitionLeave from false to true', () => {
129
var a = ReactDOM.render(
130
<ReactCSSTransitionGroup
135
- transitionName="yolo"
136
- transitionEnter={false}
137
- transitionLeave={false}>
131
+ transitionName="yolo"
132
+ transitionEnter={false}
133
+ transitionLeave={false}>
134
<span key="one" id="one" />
135
</ReactCSSTransitionGroup>,
140
- container
136
+ container,
137
);
138
expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(1);
139
ReactDOM.render(
140
<ReactCSSTransitionGroup
145
- transitionName="yolo"
146
- transitionEnter={false}
147
- transitionLeave={false}>
141
+ transitionName="yolo"
142
+ transitionEnter={false}
143
+ transitionLeave={false}>
144
<span key="two" id="two" />
145
</ReactCSSTransitionGroup>,
150
- container
146
+ container,
147
);
148
expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(1);
149
ReactDOM.render(
150
<ReactCSSTransitionGroup
155
- transitionName="yolo"
156
- transitionEnter={false}
157
- transitionLeave={true}>
151
+ transitionName="yolo"
152
+ transitionEnter={false}
153
+ transitionLeave={true}>
154
<span key="three" id="three" />
155
</ReactCSSTransitionGroup>,
160
- container
156
+ container,
157
);
158
expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(2);
159
expect(ReactDOM.findDOMNode(a).childNodes[0].id).toBe('three');
@@ -167,7 +163,7 @@ describe('ReactCSSTransitionGroup', () => {
163
it('should work with no children', () => {
164
ReactDOM.render(
165
<ReactCSSTransitionGroup transitionName="yolo" />,
170
- container
166
+ container,
167
);
168
});
169
@@ -176,7 +172,7 @@ describe('ReactCSSTransitionGroup', () => {
172
<ReactCSSTransitionGroup transitionName="yolo">
173
{[null]}
174
</ReactCSSTransitionGroup>,
179
- container
175
+ container,
176
);
177
});
178
@@ -185,14 +181,14 @@ describe('ReactCSSTransitionGroup', () => {
181
<ReactCSSTransitionGroup transitionName="yolo">
182
<span key="one" id="one" />
183
</ReactCSSTransitionGroup>,
188
- container
184
+ container,
185
);
186
expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(1);
187
ReactDOM.render(
188
<ReactCSSTransitionGroup transitionName="yolo">
189
{null}
190
</ReactCSSTransitionGroup>,
195
- container
191
+ container,
192
);
193
// (Here, we expect the original child to stick around but test that no
194
// exception is thrown)
@@ -205,20 +201,20 @@ describe('ReactCSSTransitionGroup', () => {
201
<ReactCSSTransitionGroup transitionName="yolo">
202
{false}
203
</ReactCSSTransitionGroup>,
208
- container
204
+ container,
205
);
206
expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(0);
207
ReactDOM.render(
208
<ReactCSSTransitionGroup transitionName="yolo">
209
<span key="one" id="one" />
210
</ReactCSSTransitionGroup>,
215
- container
211
+ container,
212
);
213
expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(1);
214
expect(ReactDOM.findDOMNode(a).childNodes[0].id).toBe('one');
215
});
216
221
- it('should use transition-type specific names when they\'re provided', () => {
217
+ it("should use transition-type specific names when they're provided", () => {
218
var customTransitionNames = {
219
enter: 'custom-entering',
220
leave: 'custom-leaving',
@@ -228,11 +224,10 @@ describe('ReactCSSTransitionGroup', () => {
224
<ReactCSSTransitionGroup
225
transitionName={customTransitionNames}
226
transitionEnterTimeout={1}
231
- transitionLeaveTimeout={1}
232
- >
227
+ transitionLeaveTimeout={1}>
228
<span key="one" id="one" />
229
</ReactCSSTransitionGroup>,
235
- container
230
+ container,
231
);
232
expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(1);
233
@@ -241,12 +236,11 @@ describe('ReactCSSTransitionGroup', () => {
236
<ReactCSSTransitionGroup
237
transitionName={customTransitionNames}
238
transitionEnterTimeout={1}
244
- transitionLeaveTimeout={1}
245
- >
239
+ transitionLeaveTimeout={1}>
240
<span key="one" id="one" />
241
<span key="two" id="two" />
242
</ReactCSSTransitionGroup>,
249
- container
243
+ container,
244
);
245
expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(2);
246
@@ -258,11 +252,10 @@ describe('ReactCSSTransitionGroup', () => {
252
<ReactCSSTransitionGroup
253
transitionName={customTransitionNames}
254
transitionEnterTimeout={1}
261
- transitionLeaveTimeout={1}
262
- >
255
+ transitionLeaveTimeout={1}>
256
<span key="two" id="two" />
257
</ReactCSSTransitionGroup>,
265
- container
258
+ container,
259
);
260
expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(2);
261
@@ -284,7 +277,10 @@ describe('ReactCSSTransitionGroup', () => {
277
}
278
279
ReactDOM.render(<Component />, container);
287
- ReactDOM.render(<Component><span key="yolo" id="yolo" /></Component>, container);
280
+ ReactDOM.render(
281
+ <Component><span key="yolo" id="yolo" /></Component>,
282
+ container,
283
+ );
284
285
ReactDOM.unmountComponentAtNode(container);
286
@@ -303,10 +299,10 @@ describe('ReactCSSTransitionGroup', () => {
299
}
300
301
class Component extends React.Component {
306
- state = { showChild: true };
302
+ state = {showChild: true};
303
304
componentDidMount() {
309
- this.setState({ showChild: false });
305
+ this.setState({showChild: false});
306
}
307
308
render() {
@@ -314,8 +310,7 @@ describe('ReactCSSTransitionGroup', () => {
310
<ReactCSSTransitionGroup
311
transitionName="yolo"
312
transitionAppear={true}
317
- transitionAppearTimeout={0}
318
- >
313
+ transitionAppearTimeout={0}>
314
<Child show={this.state.showChild} />
315
</ReactCSSTransitionGroup>
316
);
src/addons/transitions/__tests__/ReactTransitionChildMapping-test.js
+1
-1
@@ -27,7 +27,7 @@ describe('ReactTransitionChildMapping', () => {
27
var two = <div key="two" />;
28
var component = <div>{one}{two}</div>;
29
expect(
30
- ReactTransitionChildMapping.getChildMapping(component.props.children)
30
+ ReactTransitionChildMapping.getChildMapping(component.props.children),
31
).toEqual({
32
'.$one': one,
33
'.$two': two,
src/addons/transitions/__tests__/ReactTransitionGroup-test.js
+38
-25
@@ -28,7 +28,6 @@ describe('ReactTransitionGroup', () => {
28
container = document.createElement('div');
29
});
30
31
-
31
it('should handle willEnter correctly', () => {
32
var log = [];
33
@@ -37,7 +36,7 @@ describe('ReactTransitionGroup', () => {
36
log.push('didMount');
37
}
38
40
- componentWillAppear = (cb) => {
39
+ componentWillAppear = cb => {
40
log.push('willAppear');
41
cb();
42
};
@@ -46,7 +45,7 @@ describe('ReactTransitionGroup', () => {
45
log.push('didAppear');
46
};
47
49
- componentWillEnter = (cb) => {
48
+ componentWillEnter = cb => {
49
log.push('willEnter');
50
cb();
51
};
@@ -55,7 +54,7 @@ describe('ReactTransitionGroup', () => {
54
log.push('didEnter');
55
};
56
58
- componentWillLeave = (cb) => {
57
+ componentWillLeave = cb => {
58
log.push('willLeave');
59
cb();
60
};
@@ -108,7 +107,7 @@ describe('ReactTransitionGroup', () => {
107
log.push('didMount');
108
}
109
111
- componentWillEnter = (cb) => {
110
+ componentWillEnter = cb => {
111
log.push('willEnter');
112
willEnterCb = cb;
113
};
@@ -117,7 +116,7 @@ describe('ReactTransitionGroup', () => {
116
log.push('didEnter');
117
};
118
120
- componentWillLeave = (cb) => {
119
+ componentWillLeave = cb => {
120
log.push('willLeave');
121
cb();
122
};
@@ -159,8 +158,13 @@ describe('ReactTransitionGroup', () => {
158
// other animations are blocked until willEnterCb is called
159
willEnterCb();
160
expect(log).toEqual([
162
- 'didMount', 'didMount', 'willEnter',
163
- 'didEnter', 'willLeave', 'didLeave', 'willUnmount',
161
+ 'didMount',
162
+ 'didMount',
163
+ 'willEnter',
164
+ 'didEnter',
165
+ 'willLeave',
166
+ 'didLeave',
167
+ 'willUnmount',
168
]);
169
});
170
@@ -173,7 +177,7 @@ describe('ReactTransitionGroup', () => {
177
log.push('didMount');
178
}
179
176
- componentWillEnter = (cb) => {
180
+ componentWillEnter = cb => {
181
log.push('willEnter');
182
willEnterCb = cb;
183
};
@@ -182,7 +186,7 @@ describe('ReactTransitionGroup', () => {
186
log.push('didEnter');
187
};
188
185
- componentWillLeave = (cb) => {
189
+ componentWillLeave = cb => {
190
log.push('willLeave');
191
cb();
192
};
@@ -222,9 +226,7 @@ describe('ReactTransitionGroup', () => {
226
instance.setState({count: 2});
227
}
228
willEnterCb();
225
- expect(log).toEqual([
226
- 'didMount', 'didMount', 'willEnter', 'didEnter',
227
- ]);
229
+ expect(log).toEqual(['didMount', 'didMount', 'willEnter', 'didEnter']);
230
});
231
232
it('should handle entering/leaving several elements at once', () => {
@@ -235,7 +237,7 @@ describe('ReactTransitionGroup', () => {
237
log.push('didMount' + this.props.id);
238
}
239
238
- componentWillEnter = (cb) => {
240
+ componentWillEnter = cb => {
241
log.push('willEnter' + this.props.id);
242
cb();
243
};
@@ -244,7 +246,7 @@ describe('ReactTransitionGroup', () => {
246
log.push('didEnter' + this.props.id);
247
};
248
247
- componentWillLeave = (cb) => {
249
+ componentWillLeave = cb => {
250
log.push('willLeave' + this.props.id);
251
cb();
252
};
@@ -280,15 +282,26 @@ describe('ReactTransitionGroup', () => {
282
283
instance.setState({count: 3});
284
expect(log).toEqual([
283
- 'didMount1', 'didMount2', 'willEnter1', 'didEnter1',
284
- 'willEnter2', 'didEnter2',
285
+ 'didMount1',
286
+ 'didMount2',
287
+ 'willEnter1',
288
+ 'didEnter1',
289
+ 'willEnter2',
290
+ 'didEnter2',
291
]);
292
log = [];
293
294
instance.setState({count: 0});
295
expect(log).toEqual([
290
- 'willLeave0', 'didLeave0', 'willLeave1', 'didLeave1',
291
- 'willLeave2', 'didLeave2', 'willUnmount0', 'willUnmount1', 'willUnmount2',
296
+ 'willLeave0',
297
+ 'didLeave0',
298
+ 'willLeave1',
299
+ 'didLeave1',
300
+ 'willLeave2',
301
+ 'didLeave2',
302
+ 'willUnmount0',
303
+ 'willUnmount1',
304
+ 'willUnmount2',
305
]);
306
});
307
@@ -307,15 +320,15 @@ describe('ReactTransitionGroup', () => {
320
expectDev(console.error.calls.count()).toBe(2);
321
expectDev(console.error.calls.argsFor(0)[0]).toBe(
322
'Warning: flattenChildren(...): ' +
310
- 'Encountered two children with the same key, `1`. ' +
311
- 'Child keys must be unique; when two children share a key, ' +
312
- 'only the first child will be used.'
323
+ 'Encountered two children with the same key, `1`. ' +
324
+ 'Child keys must be unique; when two children share a key, ' +
325
+ 'only the first child will be used.',
326
);
327
expectDev(console.error.calls.argsFor(1)[0]).toBe(
328
'Warning: flattenChildren(...): ' +
316
- 'Encountered two children with the same key, `1`. ' +
317
- 'Child keys must be unique; when two children share a key, ' +
318
- 'only the first child will be used.'
329
+ 'Encountered two children with the same key, `1`. ' +
330
+ 'Child keys must be unique; when two children share a key, ' +
331
+ 'only the first child will be used.',
332
);
333
});
334
});
src/addons/update.js
+17
-17
@@ -9,7 +9,7 @@
9
* @providesModule update
10
*/
11
12
- /* global hasOwnProperty:true */
12
+/* global hasOwnProperty:true */
13
14
'use strict';
15
@@ -53,15 +53,15 @@ function invariantArrayCase(value, spec, command) {
53
Array.isArray(value),
54
'update(): expected target of %s to be an array; got %s.',
55
command,
56
- value
56
+ value,
57
);
58
var specValue = spec[command];
59
invariant(
60
Array.isArray(specValue),
61
'update(): expected spec of %s to be an array; got %s. ' +
62
- 'Did you forget to wrap your parameter in an array?',
62
+ 'Did you forget to wrap your parameter in an array?',
63
command,
64
- specValue
64
+ specValue,
65
);
66
}
67
@@ -73,16 +73,16 @@ function update(value, spec) {
73
invariant(
74
typeof spec === 'object',
75
'update(): You provided a key path to update() that did not contain one ' +
76
- 'of %s. Did you forget to include {%s: ...}?',
76
+ 'of %s. Did you forget to include {%s: ...}?',
77
ALL_COMMANDS_LIST.join(', '),
78
- COMMAND_SET
78
+ COMMAND_SET,
79
);
80
81
if (hasOwnProperty.call(spec, COMMAND_SET)) {
82
invariant(
83
Object.keys(spec).length === 1,
84
'Cannot have more than one key in an object with %s',
85
- COMMAND_SET
85
+ COMMAND_SET,
86
);
87
88
return spec[COMMAND_SET];
@@ -94,15 +94,15 @@ function update(value, spec) {
94
var mergeObj = spec[COMMAND_MERGE];
95
invariant(
96
mergeObj && typeof mergeObj === 'object',
97
- 'update(): %s expects a spec of type \'object\'; got %s',
97
+ "update(): %s expects a spec of type 'object'; got %s",
98
COMMAND_MERGE,
99
- mergeObj
99
+ mergeObj,
100
);
101
invariant(
102
nextValue && typeof nextValue === 'object',
103
- 'update(): %s expects a target of type \'object\'; got %s',
103
+ "update(): %s expects a target of type 'object'; got %s",
104
COMMAND_MERGE,
105
- nextValue
105
+ nextValue,
106
);
107
Object.assign(nextValue, spec[COMMAND_MERGE]);
108
}
@@ -126,22 +126,22 @@ function update(value, spec) {
126
Array.isArray(value),
127
'Expected %s target to be an array; got %s',
128
COMMAND_SPLICE,
129
- value
129
+ value,
130
);
131
invariant(
132
Array.isArray(spec[COMMAND_SPLICE]),
133
'update(): expected spec of %s to be an array of arrays; got %s. ' +
134
- 'Did you forget to wrap your parameters in an array?',
134
+ 'Did you forget to wrap your parameters in an array?',
135
COMMAND_SPLICE,
136
- spec[COMMAND_SPLICE]
136
+ spec[COMMAND_SPLICE],
137
);
138
spec[COMMAND_SPLICE].forEach(function(args) {
139
invariant(
140
Array.isArray(args),
141
'update(): expected spec of %s to be an array of arrays; got %s. ' +
142
- 'Did you forget to wrap your parameters in an array?',
142
+ 'Did you forget to wrap your parameters in an array?',
143
COMMAND_SPLICE,
144
- spec[COMMAND_SPLICE]
144
+ spec[COMMAND_SPLICE],
145
);
146
nextValue.splice.apply(nextValue, args);
147
});
@@ -152,7 +152,7 @@ function update(value, spec) {
152
typeof spec[COMMAND_APPLY] === 'function',
153
'update(): expected spec of %s to be a function; got %s.',
154
COMMAND_APPLY,
155
- spec[COMMAND_APPLY]
155
+ spec[COMMAND_APPLY],
156
);
157
nextValue = spec[COMMAND_APPLY](nextValue);
158
}
src/isomorphic/React.js
+1
-4
@@ -45,16 +45,14 @@ if (__DEV__) {
45
warning(
46
warnedForCreateMixin,
47
'React.createMixin is deprecated and should not be used. You ' +
48
- 'can use this mixin directly instead.'
48
+ 'can use this mixin directly instead.',
49
);
50
warnedForCreateMixin = true;
51
return mixin;
52
};
53
-
53
}
54
55
var React = {
57
-
56
// Modern
57
58
Children: {
@@ -86,7 +84,6 @@ var React = {
84
DOM: ReactDOMFactories,
85
86
version: ReactVersion,
89
-
87
};
88
89
module.exports = React;
src/isomorphic/__tests__/React-test.js
+1
-3
@@ -12,7 +12,6 @@
12
'use strict';
13
14
describe('React', () => {
15
-
15
var React;
16
17
beforeEach(() => {
@@ -25,8 +24,7 @@ describe('React', () => {
24
React.createMixin();
25
expectDev(console.error.calls.count()).toBe(1);
26
expectDev(console.error.calls.argsFor(0)[0]).toContain(
28
- 'React.createMixin is deprecated and should not be used'
27
+ 'React.createMixin is deprecated and should not be used',
28
);
29
});
31
-
30
});
src/isomorphic/children/ReactChildren.js
+11
-18
@@ -20,13 +20,11 @@ var traverseAllChildren = require('traverseAllChildren');
20
var twoArgumentPooler = PooledClass.twoArgumentPooler;
21
var fourArgumentPooler = PooledClass.fourArgumentPooler;
22
23
-
23
var userProvidedKeyEscapeRegex = /\/+/g;
24
function escapeUserProvidedKey(text) {
25
return ('' + text).replace(userProvidedKeyEscapeRegex, '$&/');
26
}
27
29
-
28
/**
29
* PooledClass representing the bookkeeping associated with performing a child
30
* traversal. Allows avoiding binding callbacks.
@@ -68,13 +66,14 @@ function forEachChildren(children, forEachFunc, forEachContext) {
66
if (children == null) {
67
return children;
68
}
71
- var traverseContext =
72
- ForEachBookKeeping.getPooled(forEachFunc, forEachContext);
69
+ var traverseContext = ForEachBookKeeping.getPooled(
70
+ forEachFunc,
71
+ forEachContext,
72
+ );
73
traverseAllChildren(children, forEachSingleChild, traverseContext);
74
ForEachBookKeeping.release(traverseContext);
75
}
76
77
-
77
/**
78
* PooledClass representing the bookkeeping associated with performing a child
79
* mapping. Allows avoiding binding callbacks.
@@ -109,7 +108,7 @@ function mapSingleChildIntoContext(bookKeeping, child, childKey) {
108
mappedChild,
109
result,
110
childKey,
112
- emptyFunction.thatReturnsArgument
111
+ emptyFunction.thatReturnsArgument,
112
);
113
} else if (mappedChild != null) {
114
if (ReactElement.isValidElement(mappedChild)) {
@@ -118,12 +117,10 @@ function mapSingleChildIntoContext(bookKeeping, child, childKey) {
117
// Keep both the (mapped) and old keys if they differ, just as
118
// traverseAllChildren used to do for objects as children
119
keyPrefix +
121
- (
122
- (mappedChild.key && (!child || (child.key !== mappedChild.key))) ?
123
- escapeUserProvidedKey(mappedChild.key) + '/' :
124
- ''
125
- ) +
126
- childKey
120
+ (mappedChild.key && (!child || child.key !== mappedChild.key)
121
+ ? escapeUserProvidedKey(mappedChild.key) + '/'
122
+ : '') +
123
+ childKey,
124
);
125
}
126
result.push(mappedChild);
@@ -139,7 +136,7 @@ function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) {
136
array,
137
escapedPrefix,
138
func,
142
- context
139
+ context,
140
);
141
traverseAllChildren(children, mapSingleChildIntoContext, traverseContext);
142
MapBookKeeping.release(traverseContext);
@@ -167,8 +164,6 @@ function mapChildren(children, func, context) {
164
return result;
165
}
166
170
-
171
-
167
function forEachSingleChildDummy(traverseContext, child, name) {
168
return null;
169
}
@@ -186,7 +181,6 @@ function countChildren(children, context) {
181
return traverseAllChildren(children, forEachSingleChildDummy, null);
182
}
183
189
-
184
/**
185
* Flatten a children object (typically specified as `props.children`) and
186
* return an array with appropriately re-keyed children.
@@ -199,12 +193,11 @@ function toArray(children) {
193
children,
194
result,
195
null,
202
- emptyFunction.thatReturnsArgument
196
+ emptyFunction.thatReturnsArgument,
197
);
198
return result;
199
}
200
207
-
201
var ReactChildren = {
202
forEach: forEachChildren,
203
map: mapChildren,
src/isomorphic/children/__tests__/ReactChildren-test.js
+164
-116
@@ -37,7 +37,11 @@ describe('ReactChildren', () => {
37
React.Children.forEach(instance.props.children, callback, context);
38
expect(callback).toHaveBeenCalledWith(simpleKid, 0);
39
callback.calls.reset();
40
- var mappedChildren = React.Children.map(instance.props.children, callback, context);
40
+ var mappedChildren = React.Children.map(
41
+ instance.props.children,
42
+ callback,
43
+ context,
44
+ );
45
expect(callback).toHaveBeenCalledWith(simpleKid, 0);
46
expect(mappedChildren[0]).toEqual(<span key=".$simple" />);
47
});
@@ -54,7 +58,11 @@ describe('ReactChildren', () => {
58
React.Children.forEach(instance.props.children, callback, context);
59
expect(callback).toHaveBeenCalledWith(simpleKid, 0);
60
callback.calls.reset();
57
- var mappedChildren = React.Children.map(instance.props.children, callback, context);
61
+ var mappedChildren = React.Children.map(
62
+ instance.props.children,
63
+ callback,
64
+ context,
65
+ );
66
expect(callback).toHaveBeenCalledWith(simpleKid, 0);
67
expect(mappedChildren[0]).toEqual(<span key=".0" />);
68
});
@@ -71,7 +79,11 @@ describe('ReactChildren', () => {
79
React.Children.forEach(instance.props.children, callback, context);
80
expect(callback).toHaveBeenCalledWith(simpleKid, 0);
81
callback.calls.reset();
74
- var mappedChildren = React.Children.map(instance.props.children, callback, context);
82
+ var mappedChildren = React.Children.map(
83
+ instance.props.children,
84
+ callback,
85
+ context,
86
+ );
87
expect(callback).toHaveBeenCalledWith(simpleKid, 0);
88
expect(mappedChildren[0]).toEqual(<span key=".$simple" />);
89
});
@@ -84,11 +96,10 @@ describe('ReactChildren', () => {
96
var four = <div key="keyFour" />;
97
var context = {};
98
87
- var callback =
88
- jasmine.createSpy().and.callFake(function(kid) {
89
- expect(this).toBe(context);
90
- return kid;
91
- });
99
+ var callback = jasmine.createSpy().and.callFake(function(kid) {
100
+ expect(this).toBe(context);
101
+ return kid;
102
+ });
103
104
var instance = (
105
<div>
@@ -112,7 +123,11 @@ describe('ReactChildren', () => {
123
React.Children.forEach(instance.props.children, callback, context);
124
assertCalls();
125
115
- var mappedChildren = React.Children.map(instance.props.children, callback, context);
126
+ var mappedChildren = React.Children.map(
127
+ instance.props.children,
128
+ callback,
129
+ context,
130
+ );
131
assertCalls();
132
expect(mappedChildren).toEqual([
133
<div key=".$keyZero" />,
@@ -127,11 +142,10 @@ describe('ReactChildren', () => {
142
var a = <a key="aNode" />;
143
144
var context = {};
130
- var callback =
131
- jasmine.createSpy().and.callFake(function(kid) {
132
- expect(this).toBe(context);
133
- return kid;
134
- });
145
+ var callback = jasmine.createSpy().and.callFake(function(kid) {
146
+ expect(this).toBe(context);
147
+ return kid;
148
+ });
149
150
var instance = (
151
<div>
@@ -164,7 +178,11 @@ describe('ReactChildren', () => {
178
React.Children.forEach(instance.props.children, callback, context);
179
assertCalls();
180
167
- var mappedChildren = React.Children.map(instance.props.children, callback, context);
181
+ var mappedChildren = React.Children.map(
182
+ instance.props.children,
183
+ callback,
184
+ context,
185
+ );
186
assertCalls();
187
expect(mappedChildren).toEqual([
188
<div key=".$divNode" />,
@@ -189,34 +207,51 @@ describe('ReactChildren', () => {
207
// 2. If grouped in an Array, the `key` prop, falling back to array index
208
209
var context = {};
192
- var callback =
193
- jasmine.createSpy().and.callFake(function(kid) {
194
- return kid;
195
- });
210
+ var callback = jasmine.createSpy().and.callFake(function(kid) {
211
+ return kid;
212
+ });
213
214
var instance = (
198
- <div>{[
199
- ReactFragment.create({
200
- firstHalfKey: [zero, one, two],
201
- secondHalfKey: [three, four],
202
- keyFive: five,
203
- }),
204
- ]}</div>
215
+ <div>
216
+ {[
217
+ ReactFragment.create({
218
+ firstHalfKey: [zero, one, two],
219
+ secondHalfKey: [three, four],
220
+ keyFive: five,
221
+ }),
222
+ ]}
223
+ </div>
224
);
225
226
function assertCalls() {
227
expect(callback.calls.count()).toBe(4);
209
- expect(callback).toHaveBeenCalledWith(<div key="firstHalfKey/.$keyZero" />, 0);
210
- expect(callback).toHaveBeenCalledWith(<div key="firstHalfKey/.$keyTwo" />, 1);
211
- expect(callback).toHaveBeenCalledWith(<div key="secondHalfKey/.$keyFour" />, 2);
212
- expect(callback).toHaveBeenCalledWith(<div key="keyFive/.$keyFiveInner" />, 3);
228
+ expect(callback).toHaveBeenCalledWith(
229
+ <div key="firstHalfKey/.$keyZero" />,
230
+ 0,
231
+ );
232
+ expect(callback).toHaveBeenCalledWith(
233
+ <div key="firstHalfKey/.$keyTwo" />,
234
+ 1,
235
+ );
236
+ expect(callback).toHaveBeenCalledWith(
237
+ <div key="secondHalfKey/.$keyFour" />,
238
+ 2,
239
+ );
240
+ expect(callback).toHaveBeenCalledWith(
241
+ <div key="keyFive/.$keyFiveInner" />,
242
+ 3,
243
+ );
244
callback.calls.reset();
245
}
246
247
React.Children.forEach(instance.props.children, callback, context);
248
assertCalls();
249
219
- var mappedChildren = React.Children.map(instance.props.children, callback, context);
250
+ var mappedChildren = React.Children.map(
251
+ instance.props.children,
252
+ callback,
253
+ context,
254
+ );
255
assertCalls();
256
expect(mappedChildren).toEqual([
257
<div key=".0:$firstHalfKey/.$keyZero" />,
@@ -230,11 +265,10 @@ describe('ReactChildren', () => {
265
var zeroForceKey = <div key="keyZero" />;
266
var oneForceKey = <div key="keyOne" />;
267
var context = {};
233
- var callback =
234
- jasmine.createSpy().and.callFake(function(kid) {
235
- expect(this).toBe(context);
236
- return kid;
237
- });
268
+ var callback = jasmine.createSpy().and.callFake(function(kid) {
269
+ expect(this).toBe(context);
270
+ return kid;
271
+ });
272
273
var forcedKeys = (
274
<div>
@@ -252,7 +286,11 @@ describe('ReactChildren', () => {
286
React.Children.forEach(forcedKeys.props.children, callback, context);
287
assertCalls();
288
255
- var mappedChildren = React.Children.map(forcedKeys.props.children, callback, context);
289
+ var mappedChildren = React.Children.map(
290
+ forcedKeys.props.children,
291
+ callback,
292
+ context,
293
+ );
294
assertCalls();
295
expect(mappedChildren).toEqual([
296
<div key=".$keyZero" />,
@@ -278,11 +316,10 @@ describe('ReactChildren', () => {
316
};
317
318
var context = {};
281
- var callback =
282
- jasmine.createSpy().and.callFake(function(kid) {
283
- expect(this).toBe(context);
284
- return kid;
285
- });
319
+ var callback = jasmine.createSpy().and.callFake(function(kid) {
320
+ expect(this).toBe(context);
321
+ return kid;
322
+ });
323
324
var instance = (
325
<div>
@@ -302,11 +339,15 @@ describe('ReactChildren', () => {
339
assertCalls();
340
expectDev(console.error.calls.count()).toBe(1);
341
expectDev(console.error.calls.argsFor(0)[0]).toContain(
305
- 'Warning: Each child in an array or iterator should have a unique "key" prop.'
342
+ 'Warning: Each child in an array or iterator should have a unique "key" prop.',
343
);
344
console.error.calls.reset();
345
309
- var mappedChildren = React.Children.map(instance.props.children, callback, context);
346
+ var mappedChildren = React.Children.map(
347
+ instance.props.children,
348
+ callback,
349
+ context,
350
+ );
351
assertCalls();
352
expectDev(console.error.calls.count()).toBe(0);
353
expect(mappedChildren).toEqual([
@@ -333,11 +374,10 @@ describe('ReactChildren', () => {
374
};
375
376
var context = {};
336
- var callback =
337
- jasmine.createSpy().and.callFake(function(kid) {
338
- expect(this).toBe(context);
339
- return kid;
340
- });
377
+ var callback = jasmine.createSpy().and.callFake(function(kid) {
378
+ expect(this).toBe(context);
379
+ return kid;
380
+ });
381
382
var instance = (
383
<div>
@@ -356,7 +396,11 @@ describe('ReactChildren', () => {
396
React.Children.forEach(instance.props.children, callback, context);
397
assertCalls();
398
359
- var mappedChildren = React.Children.map(instance.props.children, callback, context);
399
+ var mappedChildren = React.Children.map(
400
+ instance.props.children,
401
+ callback,
402
+ context,
403
+ );
404
assertCalls();
405
expect(mappedChildren).toEqual([
406
<div key=".$#1" />,
@@ -398,7 +442,11 @@ describe('ReactChildren', () => {
442
React.Children.forEach(instance.props.children, callback, context);
443
assertCalls();
444
401
- var mappedChildren = React.Children.map(instance.props.children, callback, context);
445
+ var mappedChildren = React.Children.map(
446
+ instance.props.children,
447
+ callback,
448
+ context,
449
+ );
450
assertCalls();
451
expect(mappedChildren).toEqual([5, 12, 13]);
452
} finally {
@@ -435,12 +483,13 @@ describe('ReactChildren', () => {
483
React.Children.forEach(instance.props.children, callback, context);
484
assertCalls();
485
438
- var mappedChildren = React.Children.map(instance.props.children, callback, context);
486
+ var mappedChildren = React.Children.map(
487
+ instance.props.children,
488
+ callback,
489
+ context,
490
+ );
491
assertCalls();
440
- expect(mappedChildren).toEqual([
441
- 'a',
442
- 13,
443
- ]);
492
+ expect(mappedChildren).toEqual(['a', 13]);
493
494
delete String.prototype.key;
495
delete Number.prototype.key;
@@ -477,8 +526,11 @@ describe('ReactChildren', () => {
526
React.Children.forEach(instance.props.children, callback, scopeTester);
527
expect(lastContext).toBe(scopeTester);
528
480
- var mappedChildren =
481
- React.Children.map(instance.props.children, callback, scopeTester);
529
+ var mappedChildren = React.Children.map(
530
+ instance.props.children,
531
+ callback,
532
+ scopeTester,
533
+ );
534
535
expect(React.Children.count(mappedChildren)).toBe(1);
536
expect(mappedChildren[0]).toBe(scopeTester);
@@ -492,9 +544,9 @@ describe('ReactChildren', () => {
544
var four = <div key="keyFour" />;
545
546
var mapped = [
495
- <div key="giraffe" />, // Key should be joined to obj key
496
- null, // Key should be added even if we don't supply it!
497
- <div />, // Key should be added even if not supplied!
547
+ <div key="giraffe" />, // Key should be joined to obj key
548
+ null, // Key should be added even if we don't supply it!
549
+ <div />, // Key should be added even if not supplied!
550
<span />, // Map from null to something.
551
<div key="keyFour" />,
552
];
@@ -520,8 +572,7 @@ describe('ReactChildren', () => {
572
expect(callback).toHaveBeenCalledWith(four, 4);
573
callback.calls.reset();
574
523
- var mappedChildren =
524
- React.Children.map(instance.props.children, callback);
575
+ var mappedChildren = React.Children.map(instance.props.children, callback);
576
expect(callback.calls.count()).toBe(5);
577
expect(React.Children.count(mappedChildren)).toBe(4);
578
// Keys default to indices.
@@ -530,9 +581,7 @@ describe('ReactChildren', () => {
581
mappedChildren[1].key,
582
mappedChildren[2].key,
583
mappedChildren[3].key,
533
- ]).toEqual(
534
- ['giraffe/.$keyZero', '.$keyTwo', '.3', '.$keyFour']
535
- );
584
+ ]).toEqual(['giraffe/.$keyZero', '.$keyTwo', '.3', '.$keyFour']);
585
586
expect(callback).toHaveBeenCalledWith(zero, 0);
587
expect(callback).toHaveBeenCalledWith(one, 1);
@@ -559,15 +608,15 @@ describe('ReactChildren', () => {
608
// 1. If grouped in an Object, the object key combined with `key` prop
609
// 2. If grouped in an Array, the `key` prop, falling back to array index
610
562
- var zeroMapped = <div key="giraffe" />; // Key should be overridden
563
- var twoMapped = <div />; // Key should be added even if not supplied!
611
+ var zeroMapped = <div key="giraffe" />; // Key should be overridden
612
+ var twoMapped = <div />; // Key should be added even if not supplied!
613
var fourMapped = <div key="keyFour" />;
614
var fiveMapped = <div />;
615
616
var callback = jasmine.createSpy().and.callFake(function(kid, index) {
568
- return index === 0 ? zeroMapped :
569
- index === 1 ? twoMapped :
570
- index === 2 ? fourMapped : fiveMapped;
617
+ return index === 0
618
+ ? zeroMapped
619
+ : index === 1 ? twoMapped : index === 2 ? fourMapped : fiveMapped;
620
});
621
622
var frag = ReactFragment.create({
@@ -577,12 +626,7 @@ describe('ReactChildren', () => {
626
});
627
var instance = <div>{[frag]}</div>;
628
580
- expect([
581
- frag[0].key,
582
- frag[1].key,
583
- frag[2].key,
584
- frag[3].key,
585
- ]).toEqual([
629
+ expect([frag[0].key, frag[1].key, frag[2].key, frag[3].key]).toEqual([
630
'firstHalfKey/.$keyZero',
631
'firstHalfKey/.$keyTwo',
632
'secondHalfKey/.$keyFour',
@@ -618,9 +662,13 @@ describe('ReactChildren', () => {
662
'.0:$keyFive/.$keyFiveInner',
663
]);
664
621
- expect(mappedChildren[0]).toEqual(<div key="giraffe/.0:$firstHalfKey/.$keyZero" />);
665
+ expect(mappedChildren[0]).toEqual(
666
+ <div key="giraffe/.0:$firstHalfKey/.$keyZero" />,
667
+ );
668
expect(mappedChildren[1]).toEqual(<div key=".0:$firstHalfKey/.$keyTwo" />);
623
- expect(mappedChildren[2]).toEqual(<div key="keyFour/.0:$secondHalfKey/.$keyFour" />);
669
+ expect(mappedChildren[2]).toEqual(
670
+ <div key="keyFour/.0:$secondHalfKey/.$keyFour" />,
671
+ );
672
expect(mappedChildren[3]).toEqual(<div key=".0:$keyFive/.$keyFiveInner" />);
673
});
674
@@ -645,21 +693,24 @@ describe('ReactChildren', () => {
693
);
694
695
var expectedForcedKeys = ['giraffe/.$keyZero', '.$keyOne'];
648
- var mappedChildrenForcedKeys =
649
- React.Children.map(forcedKeys.props.children, mapFn);
650
- var mappedForcedKeys = mappedChildrenForcedKeys.map((c) => c.key);
696
+ var mappedChildrenForcedKeys = React.Children.map(
697
+ forcedKeys.props.children,
698
+ mapFn,
699
+ );
700
+ var mappedForcedKeys = mappedChildrenForcedKeys.map(c => c.key);
701
expect(mappedForcedKeys).toEqual(expectedForcedKeys);
702
703
var expectedRemappedForcedKeys = [
704
'giraffe/.$giraffe/.$keyZero',
705
'.$.$keyOne',
706
];
657
- var remappedChildrenForcedKeys =
658
- React.Children.map(mappedChildrenForcedKeys, mapFn);
659
- expect(
660
- remappedChildrenForcedKeys.map((c) => c.key)
661
- ).toEqual(expectedRemappedForcedKeys);
662
-
707
+ var remappedChildrenForcedKeys = React.Children.map(
708
+ mappedChildrenForcedKeys,
709
+ mapFn,
710
+ );
711
+ expect(remappedChildrenForcedKeys.map(c => c.key)).toEqual(
712
+ expectedRemappedForcedKeys,
713
+ );
714
});
715
716
it('should not throw if key provided is a dupe with array key', () => {
@@ -694,10 +745,8 @@ describe('ReactChildren', () => {
745
element => element,
746
);
747
697
- var mappedWithClone = React.Children.map(
698
- instance.props.children,
699
- element => React.cloneElement(element),
700
- );
748
+ var mappedWithClone = React.Children.map(instance.props.children, element =>
749
+ React.cloneElement(element));
750
751
expect(mapped[0].key).toBe(mappedWithClone[0].key);
752
});
@@ -714,10 +763,8 @@ describe('ReactChildren', () => {
763
element => element,
764
);
765
717
- var mappedWithClone = React.Children.map(
718
- instance.props.children,
719
- element => React.cloneElement(element, {key: 'unique'}),
720
- );
766
+ var mappedWithClone = React.Children.map(instance.props.children, element =>
767
+ React.cloneElement(element, {key: 'unique'}));
768
769
expect(mapped[0].key).toBe(mappedWithClone[0].key);
770
});
@@ -773,14 +820,16 @@ describe('ReactChildren', () => {
820
// 2. If grouped in an Array, the `key` prop, falling back to array index
821
822
var instance = (
776
- <div>{[
777
- ReactFragment.create({
778
- firstHalfKey: [zero, one, two],
779
- secondHalfKey: [three, four],
780
- keyFive: five,
781
- }),
782
- null,
783
- ]}</div>
823
+ <div>
824
+ {[
825
+ ReactFragment.create({
826
+ firstHalfKey: [zero, one, two],
827
+ secondHalfKey: [three, four],
828
+ keyFive: five,
829
+ }),
830
+ null,
831
+ ]}
832
+ </div>
833
);
834
var numberOfChildren = React.Children.count(instance.props.children);
835
expect(numberOfChildren).toBe(5);
@@ -792,10 +841,8 @@ describe('ReactChildren', () => {
841
842
expect(React.Children.toArray(<div />).length).toBe(1);
843
expect(React.Children.toArray([<div />]).length).toBe(1);
795
- expect(
796
- React.Children.toArray(<div />)[0].key
797
- ).toBe(
798
- React.Children.toArray([<div />])[0].key
844
+ expect(React.Children.toArray(<div />)[0].key).toBe(
845
+ React.Children.toArray([<div />])[0].key,
846
);
847
848
var flattened = React.Children.toArray([
@@ -819,9 +866,10 @@ describe('ReactChildren', () => {
866
expect(flattened[5].key).toBe(reversed[3].key);
867
868
// null/undefined/bool are all omitted
822
- expect(React.Children.toArray([1, 'two', null, undefined, true])).toEqual(
823
- [1, 'two']
824
- );
869
+ expect(React.Children.toArray([1, 'two', null, undefined, true])).toEqual([
870
+ 1,
871
+ 'two',
872
+ ]);
873
});
874
875
it('should throw on object', () => {
@@ -829,9 +877,9 @@ describe('ReactChildren', () => {
877
React.Children.forEach({a: 1, b: 2}, function() {}, null);
878
}).toThrowError(
879
'Objects are not valid as a React child (found: object with keys ' +
832
- '{a, b}). If you meant to render a collection of children, use an ' +
833
- 'array instead or wrap the object using createFragment(object) from ' +
834
- 'the React add-ons.'
880
+ '{a, b}). If you meant to render a collection of children, use an ' +
881
+ 'array instead or wrap the object using createFragment(object) from ' +
882
+ 'the React add-ons.',
883
);
884
});
885
@@ -842,8 +890,8 @@ describe('ReactChildren', () => {
890
React.Children.forEach(/abc/, function() {}, null);
891
}).toThrowError(
892
'Objects are not valid as a React child (found: /abc/). If you meant ' +
845
- 'to render a collection of children, use an array instead or wrap the ' +
846
- 'object using createFragment(object) from the React add-ons.'
893
+ 'to render a collection of children, use an array instead or wrap the ' +
894
+ 'object using createFragment(object) from the React add-ons.',
895
);
896
});
897
});
src/isomorphic/children/__tests__/onlyChild-test.js
+18
-15
@@ -12,7 +12,6 @@
12
'use strict';
13
14
describe('onlyChild', () => {
15
-
15
var React;
16
var ReactFragment;
17
var onlyChild;
@@ -35,60 +34,64 @@ describe('onlyChild', () => {
34
35
it('should fail when passed two children', () => {
36
expect(function() {
38
- var instance =
37
+ var instance = (
38
<WrapComponent>
39
<div />
40
<span />
42
- </WrapComponent>;
41
+ </WrapComponent>
42
+ );
43
onlyChild(instance.props.children);
44
}).toThrow();
45
});
46
47
it('should fail when passed nully values', () => {
48
expect(function() {
49
- var instance =
49
+ var instance = (
50
<WrapComponent>
51
{null}
52
- </WrapComponent>;
52
+ </WrapComponent>
53
+ );
54
onlyChild(instance.props.children);
55
}).toThrow();
56
57
expect(function() {
57
- var instance =
58
+ var instance = (
59
<WrapComponent>
60
{undefined}
60
- </WrapComponent>;
61
+ </WrapComponent>
62
+ );
63
onlyChild(instance.props.children);
64
}).toThrow();
65
});
66
67
it('should fail when key/value objects', () => {
68
expect(function() {
67
- var instance =
69
+ var instance = (
70
<WrapComponent>
71
{ReactFragment.create({oneThing: <span />})}
70
- </WrapComponent>;
72
+ </WrapComponent>
73
+ );
74
onlyChild(instance.props.children);
75
}).toThrow();
76
});
77
75
-
78
it('should not fail when passed interpolated single child', () => {
79
expect(function() {
78
- var instance =
80
+ var instance = (
81
<WrapComponent>
82
{<span />}
81
- </WrapComponent>;
83
+ </WrapComponent>
84
+ );
85
onlyChild(instance.props.children);
86
}).not.toThrow();
87
});
88
89
it('should return the only child', () => {
87
- var instance =
90
+ var instance = (
91
<WrapComponent>
92
<span />
90
- </WrapComponent>;
93
+ </WrapComponent>
94
+ );
95
expect(onlyChild(instance.props.children)).toEqual(<span />);
96
});
93
-
97
});
src/isomorphic/children/onlyChild.js
+1
-1
@@ -31,7 +31,7 @@ var invariant = require('fbjs/lib/invariant');
31
function onlyChild(children) {
32
invariant(
33
ReactElement.isValidElement(children),
34
- 'React.Children.only expected to receive a single React element child.'
34
+ 'React.Children.only expected to receive a single React element child.',
35
);
36
return children;
37
}
src/isomorphic/classic/__tests__/ReactContextValidator-test.js
+26
-25
@@ -66,7 +66,9 @@ describe('ReactContextValidator', () => {
66
},
67
});
68
69
- var instance = ReactTestUtils.renderIntoDocument(<ComponentInFooBarContext />);
69
+ var instance = ReactTestUtils.renderIntoDocument(
70
+ <ComponentInFooBarContext />,
71
+ );
72
expect(instance.refs.child.context).toEqual({foo: 'abc'});
73
});
74
@@ -184,9 +186,9 @@ describe('ReactContextValidator', () => {
186
expectDev(console.error.calls.count()).toBe(1);
187
expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
188
'Warning: Failed context type: ' +
187
- 'The context `foo` is marked as required in `Component`, but its value ' +
188
- 'is `undefined`.\n' +
189
- ' in Component (at **)'
189
+ 'The context `foo` is marked as required in `Component`, but its value ' +
190
+ 'is `undefined`.\n' +
191
+ ' in Component (at **)',
192
);
193
194
var ComponentInFooStringContext = React.createClass({
@@ -206,7 +208,7 @@ describe('ReactContextValidator', () => {
208
});
209
210
ReactTestUtils.renderIntoDocument(
209
- <ComponentInFooStringContext fooValue={'bar'} />
211
+ <ComponentInFooStringContext fooValue={'bar'} />,
212
);
213
214
// Previous call should not error
@@ -228,15 +230,17 @@ describe('ReactContextValidator', () => {
230
},
231
});
232
231
- ReactTestUtils.renderIntoDocument(<ComponentInFooNumberContext fooValue={123} />);
233
+ ReactTestUtils.renderIntoDocument(
234
+ <ComponentInFooNumberContext fooValue={123} />,
235
+ );
236
237
expectDev(console.error.calls.count()).toBe(2);
238
expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(1)[0])).toBe(
239
'Warning: Failed context type: ' +
236
- 'Invalid context `foo` of type `number` supplied ' +
237
- 'to `Component`, expected `string`.\n' +
238
- ' in Component (at **)\n' +
239
- ' in ComponentInFooNumberContext (at **)'
240
+ 'Invalid context `foo` of type `number` supplied ' +
241
+ 'to `Component`, expected `string`.\n' +
242
+ ' in Component (at **)\n' +
243
+ ' in ComponentInFooNumberContext (at **)',
244
);
245
});
246
@@ -262,9 +266,9 @@ describe('ReactContextValidator', () => {
266
expectDev(console.error.calls.count()).toBe(1);
267
expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
268
'Warning: Failed child context type: ' +
265
- 'The child context `foo` is marked as required in `Component`, but its ' +
266
- 'value is `undefined`.\n' +
267
- ' in Component (at **)'
269
+ 'The child context `foo` is marked as required in `Component`, but its ' +
270
+ 'value is `undefined`.\n' +
271
+ ' in Component (at **)',
272
);
273
274
ReactTestUtils.renderIntoDocument(<Component testContext={{foo: 123}} />);
@@ -272,18 +276,16 @@ describe('ReactContextValidator', () => {
276
expectDev(console.error.calls.count()).toBe(2);
277
expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(1)[0])).toBe(
278
'Warning: Failed child context type: ' +
275
- 'Invalid child context `foo` of type `number` ' +
276
- 'supplied to `Component`, expected `string`.\n' +
277
- ' in Component (at **)'
279
+ 'Invalid child context `foo` of type `number` ' +
280
+ 'supplied to `Component`, expected `string`.\n' +
281
+ ' in Component (at **)',
282
);
283
284
ReactTestUtils.renderIntoDocument(
281
- <Component testContext={{foo: 'foo', bar: 123}} />
285
+ <Component testContext={{foo: 'foo', bar: 123}} />,
286
);
287
284
- ReactTestUtils.renderIntoDocument(
285
- <Component testContext={{foo: 'foo'}} />
286
- );
288
+ ReactTestUtils.renderIntoDocument(<Component testContext={{foo: 'foo'}} />);
289
290
// Previous calls should not log errors
291
expectDev(console.error.calls.count()).toBe(2);
@@ -315,8 +317,8 @@ describe('ReactContextValidator', () => {
317
expectDev(console.error.calls.count()).toBe(1);
318
expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
319
'Warning: ComponentA.childContextTypes is specified but there is no ' +
318
- 'getChildContext() method on the instance. You can either define ' +
319
- 'getChildContext() on ComponentA or remove childContextTypes from it.'
320
+ 'getChildContext() method on the instance. You can either define ' +
321
+ 'getChildContext() on ComponentA or remove childContextTypes from it.',
322
);
323
324
// Warnings should be deduped by component type
@@ -326,8 +328,8 @@ describe('ReactContextValidator', () => {
328
expectDev(console.error.calls.count()).toBe(2);
329
expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(1)[0])).toBe(
330
'Warning: ComponentB.childContextTypes is specified but there is no ' +
329
- 'getChildContext() method on the instance. You can either define ' +
330
- 'getChildContext() on ComponentB or remove childContextTypes from it.'
331
+ 'getChildContext() method on the instance. You can either define ' +
332
+ 'getChildContext() on ComponentB or remove childContextTypes from it.',
333
);
334
});
335
@@ -375,5 +377,4 @@ describe('ReactContextValidator', () => {
377
expect(childContext.bar).toBeUndefined();
378
expect(childContext.foo).toBe('FOO');
379
});
378
-
380
});
src/isomorphic/classic/class/ReactClass.js
+75
-111
@@ -36,24 +36,23 @@ type SpecPolicy =
36
/**
37
* These methods may be defined only once by the class specification or mixin.
38
*/
39
- 'DEFINE_ONCE' |
40
- /**
39
+ | 'DEFINE_ONCE'
40
+ | /**
41
* These methods may be defined by both the class specification and mixins.
42
* Subsequent definitions will be chained. These methods must return void.
43
*/
44
- 'DEFINE_MANY' |
45
- /**
44
+ 'DEFINE_MANY'
45
+ | /**
46
* These methods are overriding the base class.
47
*/
48
- 'OVERRIDE_BASE' |
49
- /**
48
+ 'OVERRIDE_BASE'
49
+ | /**
50
* These methods are similar to DEFINE_MANY, except we assume they return
51
* objects. We try to merge the keys of the return values of all the mixed in
52
* functions. If there is a key conflict we throw.
53
*/
54
'DEFINE_MANY_MERGED';
55
56
-
56
/**
57
* Composite components are higher-level components that compose other composite
58
* or host components.
@@ -77,7 +76,6 @@ type SpecPolicy =
76
* @internal
77
*/
78
var ReactClassInterface: {[key: string]: SpecPolicy} = {
80
-
79
/**
80
* An array of Mixin objects to include when defining your component.
81
*
@@ -172,8 +170,6 @@ var ReactClassInterface: {[key: string]: SpecPolicy} = {
170
*/
171
render: 'DEFINE_ONCE',
172
175
-
176
-
173
// ==== Delegate methods ====
174
175
/**
@@ -284,8 +280,6 @@ var ReactClassInterface: {[key: string]: SpecPolicy} = {
280
*/
281
componentWillUnmount: 'DEFINE_MANY',
282
287
-
288
-
283
// ==== Advanced methods ====
284
285
/**
@@ -299,7 +293,6 @@ var ReactClassInterface: {[key: string]: SpecPolicy} = {
293
* @overridable
294
*/
295
updateComponent: 'OVERRIDE_BASE',
302
-
296
};
297
298
/**
@@ -324,30 +317,22 @@ var RESERVED_SPEC_KEYS = {
317
},
318
childContextTypes: function(Constructor, childContextTypes) {
319
if (__DEV__) {
327
- validateTypeDef(
328
- Constructor,
329
- childContextTypes,
330
- 'child context'
331
- );
320
+ validateTypeDef(Constructor, childContextTypes, 'child context');
321
}
322
Constructor.childContextTypes = Object.assign(
323
{},
324
Constructor.childContextTypes,
336
- childContextTypes
325
+ childContextTypes,
326
);
327
},
328
contextTypes: function(Constructor, contextTypes) {
329
if (__DEV__) {
341
- validateTypeDef(
342
- Constructor,
343
- contextTypes,
344
- 'context'
345
- );
330
+ validateTypeDef(Constructor, contextTypes, 'context');
331
}
332
Constructor.contextTypes = Object.assign(
333
{},
334
Constructor.contextTypes,
350
- contextTypes
335
+ contextTypes,
336
);
337
},
338
/**
@@ -358,7 +343,7 @@ var RESERVED_SPEC_KEYS = {
343
if (Constructor.getDefaultProps) {
344
Constructor.getDefaultProps = createMergedResultFunction(
345
Constructor.getDefaultProps,
361
- getDefaultProps
346
+ getDefaultProps,
347
);
348
} else {
349
Constructor.getDefaultProps = getDefaultProps;
@@ -366,17 +351,9 @@ var RESERVED_SPEC_KEYS = {
351
},
352
propTypes: function(Constructor, propTypes) {
353
if (__DEV__) {
369
- validateTypeDef(
370
- Constructor,
371
- propTypes,
372
- 'prop'
373
- );
354
+ validateTypeDef(Constructor, propTypes, 'prop');
355
}
375
- Constructor.propTypes = Object.assign(
376
- {},
377
- Constructor.propTypes,
378
- propTypes
379
- );
356
+ Constructor.propTypes = Object.assign({}, Constructor.propTypes, propTypes);
357
},
358
statics: function(Constructor, statics) {
359
mixStaticSpecIntoComponent(Constructor, statics);
@@ -384,11 +361,7 @@ var RESERVED_SPEC_KEYS = {
361
autobind: function() {}, // noop
362
};
363
387
-function validateTypeDef(
388
- Constructor,
389
- typeDef,
390
- location: string,
391
-) {
364
+function validateTypeDef(Constructor, typeDef, location: string) {
365
for (var propName in typeDef) {
366
if (typeDef.hasOwnProperty(propName)) {
367
// use a warning instead of an invariant so components
@@ -396,40 +369,39 @@ function validateTypeDef(
369
warning(
370
typeof typeDef[propName] === 'function',
371
'%s: %s type `%s` is invalid; it must be a function, usually from ' +
399
- 'React.PropTypes.',
372
+ 'React.PropTypes.',
373
Constructor.displayName || 'ReactClass',
374
location,
402
- propName
375
+ propName,
376
);
377
}
378
}
379
}
380
381
function validateMethodOverride(isAlreadyDefined, name) {
409
- var specPolicy = ReactClassInterface.hasOwnProperty(name) ?
410
- ReactClassInterface[name] :
411
- null;
382
+ var specPolicy = ReactClassInterface.hasOwnProperty(name)
383
+ ? ReactClassInterface[name]
384
+ : null;
385
386
// Disallow overriding of base class methods unless explicitly allowed.
387
if (ReactClassMixin.hasOwnProperty(name)) {
388
invariant(
389
specPolicy === 'OVERRIDE_BASE',
390
'ReactClassInterface: You are attempting to override ' +
418
- '`%s` from your class specification. Ensure that your method names ' +
419
- 'do not overlap with React methods.',
420
- name
391
+ '`%s` from your class specification. Ensure that your method names ' +
392
+ 'do not overlap with React methods.',
393
+ name,
394
);
395
}
396
397
// Disallow defining methods more than once unless explicitly allowed.
398
if (isAlreadyDefined) {
399
invariant(
427
- specPolicy === 'DEFINE_MANY' ||
428
- specPolicy === 'DEFINE_MANY_MERGED',
400
+ specPolicy === 'DEFINE_MANY' || specPolicy === 'DEFINE_MANY_MERGED',
401
'ReactClassInterface: You are attempting to define ' +
430
- '`%s` on your component more than once. This conflict may be due ' +
431
- 'to a mixin.',
432
- name
402
+ '`%s` on your component more than once. This conflict may be due ' +
403
+ 'to a mixin.',
404
+ name,
405
);
406
}
407
}
@@ -446,12 +418,12 @@ function mixSpecIntoComponent(Constructor, spec) {
418
419
warning(
420
isMixinValid,
449
- '%s: You\'re attempting to include a mixin that is either null ' +
450
- 'or not an object. Check the mixins included by the component, ' +
451
- 'as well as any mixins they include themselves. ' +
452
- 'Expected object but got %s.',
421
+ "%s: You're attempting to include a mixin that is either null " +
422
+ 'or not an object. Check the mixins included by the component, ' +
423
+ 'as well as any mixins they include themselves. ' +
424
+ 'Expected object but got %s.',
425
Constructor.displayName || 'ReactClass',
454
- spec === null ? null : typeofSpec
426
+ spec === null ? null : typeofSpec,
427
);
428
}
429
@@ -460,14 +432,14 @@ function mixSpecIntoComponent(Constructor, spec) {
432
433
invariant(
434
typeof spec !== 'function',
463
- 'ReactClass: You\'re attempting to ' +
464
- 'use a component class or function as a mixin. Instead, just use a ' +
465
- 'regular object.'
435
+ "ReactClass: You're attempting to " +
436
+ 'use a component class or function as a mixin. Instead, just use a ' +
437
+ 'regular object.',
438
);
439
invariant(
440
!ReactElement.isValidElement(spec),
469
- 'ReactClass: You\'re attempting to ' +
470
- 'use a component as a mixin. Instead, just use a regular object.'
441
+ "ReactClass: You're attempting to " +
442
+ 'use a component as a mixin. Instead, just use a regular object.',
443
);
444
445
var proto = Constructor.prototype;
@@ -501,11 +473,9 @@ function mixSpecIntoComponent(Constructor, spec) {
473
// The following member methods should not be automatically bound:
474
// 1. Expected ReactClass methods (in the "interface").
475
// 2. Overridden methods (that were mixed in).
504
- var isReactClassMethod =
505
- ReactClassInterface.hasOwnProperty(name);
476
+ var isReactClassMethod = ReactClassInterface.hasOwnProperty(name);
477
var isFunction = typeof property === 'function';
507
- var shouldAutoBind =
508
- isFunction &&
478
+ var shouldAutoBind = isFunction &&
479
!isReactClassMethod &&
480
!isAlreadyDefined &&
481
spec.autobind !== false;
@@ -519,14 +489,13 @@ function mixSpecIntoComponent(Constructor, spec) {
489
490
// These cases should already be caught by validateMethodOverride.
491
invariant(
522
- isReactClassMethod && (
523
- specPolicy === 'DEFINE_MANY_MERGED' ||
524
- specPolicy === 'DEFINE_MANY'
525
- ),
492
+ isReactClassMethod &&
493
+ (specPolicy === 'DEFINE_MANY_MERGED' ||
494
+ specPolicy === 'DEFINE_MANY'),
495
'ReactClass: Unexpected spec policy %s for key %s ' +
527
- 'when mixing in component specs.',
496
+ 'when mixing in component specs.',
497
specPolicy,
529
- name
498
+ name,
499
);
500
501
// For methods which are defined more than once, call the existing
@@ -565,19 +534,19 @@ function mixStaticSpecIntoComponent(Constructor, statics) {
534
invariant(
535
!isReserved,
536
'ReactClass: You are attempting to define a reserved ' +
568
- 'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' +
569
- 'as an instance property instead; it will still be accessible on the ' +
570
- 'constructor.',
571
- name
537
+ 'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' +
538
+ 'as an instance property instead; it will still be accessible on the ' +
539
+ 'constructor.',
540
+ name,
541
);
542
543
var isInherited = name in Constructor;
544
invariant(
545
!isInherited,
546
'ReactClass: You are attempting to define ' +
578
- '`%s` on your component more than once. This conflict may be ' +
579
- 'due to a mixin.',
580
- name
547
+ '`%s` on your component more than once. This conflict may be ' +
548
+ 'due to a mixin.',
549
+ name,
550
);
551
Constructor[name] = property;
552
}
@@ -593,7 +562,7 @@ function mixStaticSpecIntoComponent(Constructor, statics) {
562
function mergeIntoWithNoDuplicateKeys(one, two) {
563
invariant(
564
one && two && typeof one === 'object' && typeof two === 'object',
596
- 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.'
565
+ 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.',
566
);
567
568
for (var key in two) {
@@ -601,11 +570,11 @@ function mergeIntoWithNoDuplicateKeys(one, two) {
570
invariant(
571
one[key] === undefined,
572
'mergeIntoWithNoDuplicateKeys(): ' +
604
- 'Tried to merge two objects with the same key: `%s`. This conflict ' +
605
- 'may be due to a mixin; in particular, this may be caused by two ' +
606
- 'getInitialState() or getDefaultProps() methods returning objects ' +
607
- 'with clashing keys.',
608
- key
573
+ 'Tried to merge two objects with the same key: `%s`. This conflict ' +
574
+ 'may be due to a mixin; in particular, this may be caused by two ' +
575
+ 'getInitialState() or getDefaultProps() methods returning objects ' +
576
+ 'with clashing keys.',
577
+ key,
578
);
579
one[key] = two[key];
580
}
@@ -675,16 +644,16 @@ function bindAutoBindMethod(component, method) {
644
warning(
645
false,
646
'bind(): React component methods may only be bound to the ' +
678
- 'component instance.\n\nSee %s',
679
- componentName
647
+ 'component instance.\n\nSee %s',
648
+ componentName,
649
);
650
} else if (!args.length) {
651
warning(
652
false,
653
'bind(): You are binding a component method to the component. ' +
685
- 'React does this for you automatically in a high-performance ' +
686
- 'way, so you can safely remove this call.\n\nSee %s',
687
- componentName
654
+ 'React does this for you automatically in a high-performance ' +
655
+ 'way, so you can safely remove this call.\n\nSee %s',
656
+ componentName,
657
);
658
return boundMethod;
659
}
@@ -708,10 +677,7 @@ function bindAutoBindMethods(component) {
677
for (var i = 0; i < pairs.length; i += 2) {
678
var autoBindKey = pairs[i];
679
var method = pairs[i + 1];
711
- component[autoBindKey] = bindAutoBindMethod(
712
- component,
713
- method
714
- );
680
+ component[autoBindKey] = bindAutoBindMethod(component, method);
681
}
682
}
683
@@ -720,7 +686,6 @@ function bindAutoBindMethods(component) {
686
* therefore not already part of the modern ReactComponent.
687
*/
688
var ReactClassMixin = {
723
-
689
/**
690
* TODO: This will be deprecated because state should always keep a consistent
691
* type signature and the only use case for this, is to avoid that.
@@ -744,7 +709,7 @@ var ReactClassComponent = function() {};
709
Object.assign(
710
ReactClassComponent.prototype,
711
ReactComponent.prototype,
747
- ReactClassMixin
712
+ ReactClassMixin,
713
);
714
715
/**
@@ -753,7 +718,6 @@ Object.assign(
718
* @class ReactClass
719
*/
720
var ReactClass = {
756
-
721
/**
722
* Creates a composite component class given a class specification.
723
* See https://facebook.github.io/react/docs/react-api.html#createclass
@@ -774,7 +738,7 @@ var ReactClass = {
738
warning(
739
this instanceof Constructor,
740
'Something is calling a React component directly. Use a factory or ' +
777
- 'JSX instead. See: https://fb.me/react-legacyfactory'
741
+ 'JSX instead. See: https://fb.me/react-legacyfactory',
742
);
743
}
744
@@ -796,8 +760,9 @@ var ReactClass = {
760
var initialState = this.getInitialState ? this.getInitialState() : null;
761
if (__DEV__) {
762
// We allow auto-mocks to proceed as if they're returning null.
799
- if (initialState === undefined &&
800
- this.getInitialState._isMockFunction) {
763
+ if (
764
+ initialState === undefined && this.getInitialState._isMockFunction
765
+ ) {
766
// This is probably bad practice. Consider warning here and
767
// deprecating this convenience.
768
initialState = null;
@@ -806,7 +771,7 @@ var ReactClass = {
771
invariant(
772
typeof initialState === 'object' && !Array.isArray(initialState),
773
'%s.getInitialState(): must return an object or null',
809
- Constructor.displayName || 'ReactCompositeComponent'
774
+ Constructor.displayName || 'ReactCompositeComponent',
775
);
776
777
this.state = initialState;
@@ -837,23 +802,23 @@ var ReactClass = {
802
803
invariant(
804
Constructor.prototype.render,
840
- 'createClass(...): Class specification must implement a `render` method.'
805
+ 'createClass(...): Class specification must implement a `render` method.',
806
);
807
808
if (__DEV__) {
809
warning(
810
!Constructor.prototype.componentShouldUpdate,
811
'%s has a method called ' +
847
- 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' +
848
- 'The name is phrased as a question because the function is ' +
849
- 'expected to return a value.',
850
- spec.displayName || 'A component'
812
+ 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' +
813
+ 'The name is phrased as a question because the function is ' +
814
+ 'expected to return a value.',
815
+ spec.displayName || 'A component',
816
);
817
warning(
818
!Constructor.prototype.componentWillRecieveProps,
819
'%s has a method called ' +
855
- 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?',
856
- spec.displayName || 'A component'
820
+ 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?',
821
+ spec.displayName || 'A component',
822
);
823
}
824
@@ -866,7 +831,6 @@ var ReactClass = {
831
832
return Constructor;
833
},
869
-
834
};
835
836
module.exports = ReactClass;
src/isomorphic/classic/class/__tests__/ReactBind-test.js
+4
-9
@@ -16,9 +16,7 @@ var ReactTestUtils = require('ReactTestUtils');
16
17
// TODO: Test render and all stock methods.
18
describe('autobinding', () => {
19
-
19
it('Holds reference to instance', () => {
21
-
20
var mouseDidEnter = jest.fn();
21
var mouseDidLeave = jest.fn();
22
var mouseDidClick = jest.fn();
@@ -115,7 +113,7 @@ describe('autobinding', () => {
113
spyOn(console, 'error');
114
115
var TestBindComponent = React.createClass({
118
- handleClick: function() { },
116
+ handleClick: function() {},
117
render: function() {
118
return <div onClick={this.handleClick.bind(this)} />;
119
},
@@ -126,8 +124,8 @@ describe('autobinding', () => {
124
expectDev(console.error.calls.count()).toBe(1);
125
expectDev(console.error.calls.argsFor(0)[0]).toBe(
126
'Warning: bind(): You are binding a component method to the component. ' +
129
- 'React does this for you automatically in a high-performance ' +
130
- 'way, so you can safely remove this call.\n\nSee TestBindComponent'
127
+ 'React does this for you automatically in a high-performance ' +
128
+ 'way, so you can safely remove this call.\n\nSee TestBindComponent',
129
);
130
});
131
@@ -141,9 +139,7 @@ describe('autobinding', () => {
139
componentDidMount: function() {
140
this.setState({foo: 2}, this.handleUpdate);
141
},
144
- handleUpdate: function() {
145
-
146
- },
142
+ handleUpdate: function() {},
143
render: function() {
144
return <div onClick={this.handleClick} />;
145
},
@@ -153,5 +149,4 @@ describe('autobinding', () => {
149
150
expectDev(console.error.calls.count()).toBe(0);
151
});
156
-
152
});
src/isomorphic/classic/class/__tests__/ReactBindOptout-test.js
+4
-14
@@ -16,9 +16,7 @@ var ReactTestUtils = require('ReactTestUtils');
16
17
// TODO: Test render and all stock methods.
18
describe('autobind optout', () => {
19
-
19
it('should work with manual binding', () => {
21
-
20
var mouseDidEnter = jest.fn();
21
var mouseDidLeave = jest.fn();
22
var mouseDidClick = jest.fn();
@@ -39,7 +37,7 @@ describe('autobind optout', () => {
37
onMouseOver={this.onMouseEnter.bind(this)}
38
onMouseOut={this.onMouseLeave.bind(this)}
39
onClick={this.onClick.bind(this)}
42
- />
40
+ />
41
);
42
},
43
});
@@ -95,12 +93,7 @@ describe('autobind optout', () => {
93
},
94
95
render: function() {
98
- return (
99
- <div
100
- ref="child"
101
- onClick={this.onClick}
102
- />
103
- );
96
+ return <div ref="child" onClick={this.onClick} />;
97
},
98
});
99
@@ -178,7 +171,7 @@ describe('autobind optout', () => {
171
172
var TestBindComponent = React.createClass({
173
autobind: false,
181
- handleClick: function() { },
174
+ handleClick: function() {},
175
render: function() {
176
return <div onClick={this.handleClick.bind(this)} />;
177
},
@@ -200,9 +193,7 @@ describe('autobind optout', () => {
193
componentDidMount: function() {
194
this.setState({foo: 2}, this.handleUpdate.bind(this));
195
},
203
- handleUpdate: function() {
204
-
205
- },
196
+ handleUpdate: function() {},
197
render: function() {
198
return <div />;
199
},
@@ -212,5 +203,4 @@ describe('autobind optout', () => {
203
204
expectDev(console.error.calls.count()).toBe(0);
205
});
215
-
206
});
src/isomorphic/classic/class/__tests__/ReactClass-test.js
+22
-27
@@ -16,7 +16,6 @@ var ReactDOM;
16
var ReactTestUtils;
17
18
describe('ReactClass-spec', () => {
19
-
19
beforeEach(() => {
20
React = require('react');
21
ReactDOM = require('react-dom');
@@ -27,7 +26,7 @@ describe('ReactClass-spec', () => {
26
expect(function() {
27
React.createClass({});
28
}).toThrowError(
30
- 'createClass(...): Class specification must implement a `render` method.'
29
+ 'createClass(...): Class specification must implement a `render` method.',
30
);
31
});
32
@@ -38,8 +37,7 @@ describe('ReactClass-spec', () => {
37
},
38
});
39
41
- expect(TestComponent.displayName)
42
- .toBe('TestComponent');
40
+ expect(TestComponent.displayName).toBe('TestComponent');
41
});
42
43
it('should copy prop types onto the Constructor', () => {
@@ -54,8 +52,7 @@ describe('ReactClass-spec', () => {
52
});
53
54
expect(TestComponent.propTypes).toBeDefined();
57
- expect(TestComponent.propTypes.value)
58
- .toBe(propValidator);
55
+ expect(TestComponent.propTypes.value).toBe(propValidator);
56
});
57
58
it('should warn on invalid prop types', () => {
@@ -72,7 +69,7 @@ describe('ReactClass-spec', () => {
69
expectDev(console.error.calls.count()).toBe(1);
70
expectDev(console.error.calls.argsFor(0)[0]).toBe(
71
'Warning: Component: prop type `prop` is invalid; ' +
75
- 'it must be a function, usually from React.PropTypes.'
72
+ 'it must be a function, usually from React.PropTypes.',
73
);
74
});
75
@@ -90,7 +87,7 @@ describe('ReactClass-spec', () => {
87
expectDev(console.error.calls.count()).toBe(1);
88
expectDev(console.error.calls.argsFor(0)[0]).toBe(
89
'Warning: Component: context type `prop` is invalid; ' +
93
- 'it must be a function, usually from React.PropTypes.'
90
+ 'it must be a function, usually from React.PropTypes.',
91
);
92
});
93
@@ -108,7 +105,7 @@ describe('ReactClass-spec', () => {
105
expectDev(console.error.calls.count()).toBe(1);
106
expectDev(console.error.calls.argsFor(0)[0]).toBe(
107
'Warning: Component: child context type `prop` is invalid; ' +
111
- 'it must be a function, usually from React.PropTypes.'
108
+ 'it must be a function, usually from React.PropTypes.',
109
);
110
});
111
@@ -126,8 +123,8 @@ describe('ReactClass-spec', () => {
123
expectDev(console.error.calls.count()).toBe(1);
124
expectDev(console.error.calls.argsFor(0)[0]).toBe(
125
'Warning: A component has a method called componentShouldUpdate(). Did you ' +
129
- 'mean shouldComponentUpdate()? The name is phrased as a question ' +
130
- 'because the function is expected to return a value.'
126
+ 'mean shouldComponentUpdate()? The name is phrased as a question ' +
127
+ 'because the function is expected to return a value.',
128
);
129
130
React.createClass({
@@ -142,8 +139,8 @@ describe('ReactClass-spec', () => {
139
expectDev(console.error.calls.count()).toBe(2);
140
expectDev(console.error.calls.argsFor(1)[0]).toBe(
141
'Warning: NamedComponent has a method called componentShouldUpdate(). Did you ' +
145
- 'mean shouldComponentUpdate()? The name is phrased as a question ' +
146
- 'because the function is expected to return a value.'
142
+ 'mean shouldComponentUpdate()? The name is phrased as a question ' +
143
+ 'because the function is expected to return a value.',
144
);
145
});
146
@@ -160,7 +157,7 @@ describe('ReactClass-spec', () => {
157
expectDev(console.error.calls.count()).toBe(1);
158
expectDev(console.error.calls.argsFor(0)[0]).toBe(
159
'Warning: A component has a method called componentWillRecieveProps(). Did you ' +
163
- 'mean componentWillReceiveProps()?'
160
+ 'mean componentWillReceiveProps()?',
161
);
162
});
163
@@ -181,9 +178,9 @@ describe('ReactClass-spec', () => {
178
});
179
}).toThrowError(
180
'ReactClass: You are attempting to define a reserved property, ' +
184
- '`getDefaultProps`, that shouldn\'t be on the "statics" key. Define ' +
185
- 'it as an instance property instead; it will still be accessible on ' +
186
- 'the constructor.'
181
+ '`getDefaultProps`, that shouldn\'t be on the "statics" key. Define ' +
182
+ 'it as an instance property instead; it will still be accessible on ' +
183
+ 'the constructor.',
184
);
185
});
186
@@ -209,19 +206,19 @@ describe('ReactClass-spec', () => {
206
expectDev(console.error.calls.count()).toBe(4);
207
expectDev(console.error.calls.argsFor(0)[0]).toBe(
208
'createClass(...): `mixins` is now a static property and should ' +
212
- 'be defined inside "statics".'
209
+ 'be defined inside "statics".',
210
);
211
expectDev(console.error.calls.argsFor(1)[0]).toBe(
212
'createClass(...): `propTypes` is now a static property and should ' +
216
- 'be defined inside "statics".'
213
+ 'be defined inside "statics".',
214
);
215
expectDev(console.error.calls.argsFor(2)[0]).toBe(
216
'createClass(...): `contextTypes` is now a static property and ' +
220
- 'should be defined inside "statics".'
217
+ 'should be defined inside "statics".',
218
);
219
expectDev(console.error.calls.argsFor(3)[0]).toBe(
220
'createClass(...): `childContextTypes` is now a static property and ' +
224
- 'should be defined inside "statics".'
221
+ 'should be defined inside "statics".',
222
);
223
});
224
@@ -315,7 +312,7 @@ describe('ReactClass-spec', () => {
312
expect(function() {
313
instance = ReactTestUtils.renderIntoDocument(instance);
314
}).toThrowError(
318
- 'Component.getInitialState(): must return an object or null'
315
+ 'Component.getInitialState(): must return an object or null',
316
);
317
});
318
});
@@ -329,9 +326,8 @@ describe('ReactClass-spec', () => {
326
return <span />;
327
},
328
});
332
- expect(
333
- () => ReactTestUtils.renderIntoDocument(<Component />)
334
- ).not.toThrow();
329
+ expect(() =>
330
+ ReactTestUtils.renderIntoDocument(<Component />)).not.toThrow();
331
});
332
333
it('should throw when using legacy factories', () => {
@@ -346,8 +342,7 @@ describe('ReactClass-spec', () => {
342
expectDev(console.error.calls.count()).toBe(1);
343
expectDev(console.error.calls.argsFor(0)[0]).toBe(
344
'Warning: Something is calling a React component directly. Use a ' +
349
- 'factory or JSX instead. See: https://fb.me/react-legacyfactory'
345
+ 'factory or JSX instead. See: https://fb.me/react-legacyfactory',
346
);
347
});
352
-
348
});
src/isomorphic/classic/class/__tests__/ReactClassMixin-test.js
+39
-45
@@ -21,7 +21,6 @@ var mixinPropValidator;
21
var componentPropValidator;
22
23
describe('ReactClass-mixin', () => {
24
-
24
beforeEach(() => {
25
React = require('react');
26
ReactTestUtils = require('ReactTestUtils');
@@ -149,23 +148,22 @@ describe('ReactClass-mixin', () => {
148
149
it('should validate prop types via mixins', () => {
150
expect(TestComponent.propTypes).toBeDefined();
152
- expect(TestComponent.propTypes.value)
153
- .toBe(mixinPropValidator);
151
+ expect(TestComponent.propTypes.value).toBe(mixinPropValidator);
152
});
153
154
it('should override mixin prop types with class prop types', () => {
155
// Sanity check...
156
expect(componentPropValidator).not.toBe(mixinPropValidator);
157
// Actually check...
160
- expect(TestComponentWithPropTypes.propTypes)
161
- .toBeDefined();
162
- expect(TestComponentWithPropTypes.propTypes.value)
163
- .not.toBe(mixinPropValidator);
164
- expect(TestComponentWithPropTypes.propTypes.value)
165
- .toBe(componentPropValidator);
158
+ expect(TestComponentWithPropTypes.propTypes).toBeDefined();
159
+ expect(TestComponentWithPropTypes.propTypes.value).not.toBe(
160
+ mixinPropValidator,
161
+ );
162
+ expect(TestComponentWithPropTypes.propTypes.value).toBe(
163
+ componentPropValidator,
164
+ );
165
});
166
168
-
167
it('should support mixins with getInitialState()', () => {
168
var Mixin = {
169
getInitialState: function() {
@@ -205,9 +203,9 @@ describe('ReactClass-mixin', () => {
203
ReactTestUtils.renderIntoDocument(<Component />);
204
}).toThrowError(
205
'mergeIntoWithNoDuplicateKeys(): Tried to merge two objects with the ' +
208
- 'same key: `x`. This conflict may be due to a mixin; in particular, ' +
209
- 'this may be caused by two getInitialState() or getDefaultProps() ' +
210
- 'methods returning objects with clashing keys.'
206
+ 'same key: `x`. This conflict may be due to a mixin; in particular, ' +
207
+ 'this may be caused by two getInitialState() or getDefaultProps() ' +
208
+ 'methods returning objects with clashing keys.',
209
);
210
});
211
@@ -276,7 +274,7 @@ describe('ReactClass-mixin', () => {
274
});
275
}).toThrowError(
276
'ReactClass: You are attempting to define `abc` on your component more ' +
279
- 'than once. This conflict may be due to a mixin.'
277
+ 'than once. This conflict may be due to a mixin.',
278
);
279
});
280
@@ -304,7 +302,7 @@ describe('ReactClass-mixin', () => {
302
});
303
}).toThrowError(
304
'ReactClass: You are attempting to define `abc` on your component ' +
307
- 'more than once. This conflict may be due to a mixin.'
305
+ 'more than once. This conflict may be due to a mixin.',
306
);
307
});
308
@@ -321,10 +319,10 @@ describe('ReactClass-mixin', () => {
319
320
expectDev(console.error.calls.count()).toBe(1);
321
expectDev(console.error.calls.argsFor(0)[0]).toBe(
324
- 'Warning: ReactClass: You\'re attempting to include a mixin that is ' +
325
- 'either null or not an object. Check the mixins included by the ' +
326
- 'component, as well as any mixins they include themselves. ' +
327
- 'Expected object but got undefined.'
322
+ "Warning: ReactClass: You're attempting to include a mixin that is " +
323
+ 'either null or not an object. Check the mixins included by the ' +
324
+ 'component, as well as any mixins they include themselves. ' +
325
+ 'Expected object but got undefined.',
326
);
327
});
328
@@ -341,10 +339,10 @@ describe('ReactClass-mixin', () => {
339
340
expectDev(console.error.calls.count()).toBe(1);
341
expectDev(console.error.calls.argsFor(0)[0]).toBe(
344
- 'Warning: ReactClass: You\'re attempting to include a mixin that is ' +
345
- 'either null or not an object. Check the mixins included by the ' +
346
- 'component, as well as any mixins they include themselves. ' +
347
- 'Expected object but got null.'
342
+ "Warning: ReactClass: You're attempting to include a mixin that is " +
343
+ 'either null or not an object. Check the mixins included by the ' +
344
+ 'component, as well as any mixins they include themselves. ' +
345
+ 'Expected object but got null.',
346
);
347
});
348
@@ -365,10 +363,10 @@ describe('ReactClass-mixin', () => {
363
364
expectDev(console.error.calls.count()).toBe(1);
365
expectDev(console.error.calls.argsFor(0)[0]).toBe(
368
- 'Warning: ReactClass: You\'re attempting to include a mixin that is ' +
369
- 'either null or not an object. Check the mixins included by the ' +
370
- 'component, as well as any mixins they include themselves. ' +
371
- 'Expected object but got undefined.'
366
+ "Warning: ReactClass: You're attempting to include a mixin that is " +
367
+ 'either null or not an object. Check the mixins included by the ' +
368
+ 'component, as well as any mixins they include themselves. ' +
369
+ 'Expected object but got undefined.',
370
);
371
});
372
@@ -389,10 +387,10 @@ describe('ReactClass-mixin', () => {
387
388
expectDev(console.error.calls.count()).toBe(1);
389
expectDev(console.error.calls.argsFor(0)[0]).toBe(
392
- 'Warning: ReactClass: You\'re attempting to include a mixin that is ' +
393
- 'either null or not an object. Check the mixins included by the ' +
394
- 'component, as well as any mixins they include themselves. ' +
395
- 'Expected object but got null.'
390
+ "Warning: ReactClass: You're attempting to include a mixin that is " +
391
+ 'either null or not an object. Check the mixins included by the ' +
392
+ 'component, as well as any mixins they include themselves. ' +
393
+ 'Expected object but got null.',
394
);
395
});
396
@@ -406,8 +404,8 @@ describe('ReactClass-mixin', () => {
404
},
405
});
406
}).toThrowError(
409
- 'ReactClass: You\'re attempting to use a component as a mixin. ' +
410
- 'Instead, just use a regular object.'
407
+ "ReactClass: You're attempting to use a component as a mixin. " +
408
+ 'Instead, just use a regular object.',
409
);
410
});
411
@@ -427,8 +425,8 @@ describe('ReactClass-mixin', () => {
425
},
426
});
427
}).toThrowError(
430
- 'ReactClass: You\'re attempting to use a component class or function ' +
431
- 'as a mixin. Instead, just use a regular object.'
428
+ "ReactClass: You're attempting to use a component class or function " +
429
+ 'as a mixin. Instead, just use a regular object.',
430
);
431
});
432
@@ -488,9 +486,8 @@ describe('ReactClass-mixin', () => {
486
return <span />;
487
},
488
});
491
- expect(
492
- () => ReactTestUtils.renderIntoDocument(<Component />)
493
- ).not.toThrow();
489
+ expect(() =>
490
+ ReactTestUtils.renderIntoDocument(<Component />)).not.toThrow();
491
492
instance = ReactTestUtils.renderIntoDocument(<Component />);
493
expect(instance.state).toEqual({foo: 'bar'});
@@ -510,9 +507,8 @@ describe('ReactClass-mixin', () => {
507
return <span />;
508
},
509
});
513
- expect(
514
- () => ReactTestUtils.renderIntoDocument(<Component />)
515
- ).not.toThrow();
510
+ expect(() =>
511
+ ReactTestUtils.renderIntoDocument(<Component />)).not.toThrow();
512
513
instance = ReactTestUtils.renderIntoDocument(<Component />);
514
expect(instance.state).toEqual({foo: 'bar'});
@@ -527,12 +523,10 @@ describe('ReactClass-mixin', () => {
523
return <span />;
524
},
525
});
530
- expect(
531
- () => ReactTestUtils.renderIntoDocument(<Component />)
532
- ).not.toThrow();
526
+ expect(() =>
527
+ ReactTestUtils.renderIntoDocument(<Component />)).not.toThrow();
528
529
instance = ReactTestUtils.renderIntoDocument(<Component />);
530
expect(instance.state).toEqual({foo: 'bar', x: true});
531
});
537
-
532
});
src/isomorphic/classic/element/ReactCurrentOwner.js
+2
-4
@@ -12,8 +12,8 @@
12
13
'use strict';
14
15
-import type { ReactInstance } from 'ReactInstanceType';
16
-import type { Fiber } from 'ReactFiber';
15
+import type {ReactInstance} from 'ReactInstanceType';
16
+import type {Fiber} from 'ReactFiber';
17
18
/**
19
* Keeps track of the current owner.
@@ -22,13 +22,11 @@ import type { Fiber } from 'ReactFiber';
22
* currently being constructed.
23
*/
24
var ReactCurrentOwner = {
25
-
25
/**
26
* @internal
27
* @type {ReactComponent}
28
*/
29
current: (null: null | ReactInstance | Fiber),
31
-
30
};
31
32
module.exports = ReactCurrentOwner;
src/isomorphic/classic/element/ReactDOMFactories.js
+1
-1
@@ -141,7 +141,7 @@ var ReactDOMFactories = {
141
track: createDOMFactory('track'),
142
u: createDOMFactory('u'),
143
ul: createDOMFactory('ul'),
144
- 'var': createDOMFactory('var'),
144
+ var: createDOMFactory('var'),
145
video: createDOMFactory('video'),
146
wbr: createDOMFactory('wbr'),
147
src/isomorphic/classic/element/ReactDebugCurrentFrame.js
+5
-5
@@ -12,8 +12,8 @@
12
13
'use strict';
14
15
-import type { Fiber } from 'ReactFiber';
16
-import type { DebugID } from 'ReactInstanceType';
15
+import type {Fiber} from 'ReactFiber';
16
+import type {DebugID} from 'ReactInstanceType';
17
18
const ReactDebugCurrentFrame = {};
19
@@ -27,12 +27,12 @@ if (__DEV__) {
27
} = require('ReactFiberComponentTreeHook');
28
29
// Component that is being worked on
30
- ReactDebugCurrentFrame.current = (null : Fiber | DebugID | null);
30
+ ReactDebugCurrentFrame.current = (null: Fiber | DebugID | null);
31
32
// Element that is being cloned or created
33
- ReactDebugCurrentFrame.element = (null : *);
33
+ ReactDebugCurrentFrame.element = (null: *);
34
35
- ReactDebugCurrentFrame.getStackAddendum = function() : string | null {
35
+ ReactDebugCurrentFrame.getStackAddendum = function(): string | null {
36
let stack = null;
37
const current = ReactDebugCurrentFrame.current;
38
const element = ReactDebugCurrentFrame.element;
src/isomorphic/classic/element/ReactElement.js
+28
-32
@@ -59,10 +59,10 @@ function defineKeyPropWarningGetter(props, displayName) {
59
warning(
60
false,
61
'%s: `key` is not a prop. Trying to access it will result ' +
62
- 'in `undefined` being returned. If you need to access the same ' +
63
- 'value within the child component, you should pass it as a different ' +
64
- 'prop. (https://fb.me/react-special-props)',
65
- displayName
62
+ 'in `undefined` being returned. If you need to access the same ' +
63
+ 'value within the child component, you should pass it as a different ' +
64
+ 'prop. (https://fb.me/react-special-props)',
65
+ displayName,
66
);
67
}
68
};
@@ -80,10 +80,10 @@ function defineRefPropWarningGetter(props, displayName) {
80
warning(
81
false,
82
'%s: `ref` is not a prop. Trying to access it will result ' +
83
- 'in `undefined` being returned. If you need to access the same ' +
84
- 'value within the child component, you should pass it as a different ' +
85
- 'prop. (https://fb.me/react-special-props)',
86
- displayName
83
+ 'in `undefined` being returned. If you need to access the same ' +
84
+ 'value within the child component, you should pass it as a different ' +
85
+ 'prop. (https://fb.me/react-special-props)',
86
+ displayName,
87
);
88
}
89
};
@@ -203,8 +203,10 @@ ReactElement.createElement = function(type, config, children) {
203
source = config.__source === undefined ? null : config.__source;
204
// Remaining properties are added to a new props object
205
for (propName in config) {
206
- if (hasOwnProperty.call(config, propName) &&
207
- !RESERVED_PROPS.hasOwnProperty(propName)) {
206
+ if (
207
+ hasOwnProperty.call(config, propName) &&
208
+ !RESERVED_PROPS.hasOwnProperty(propName)
209
+ ) {
210
props[propName] = config[propName];
211
}
212
}
@@ -239,11 +241,13 @@ ReactElement.createElement = function(type, config, children) {
241
}
242
if (__DEV__) {
243
if (key || ref) {
242
- if (typeof props.$$typeof === 'undefined' ||
243
- props.$$typeof !== REACT_ELEMENT_TYPE) {
244
- var displayName = typeof type === 'function' ?
245
- (type.displayName || type.name || 'Unknown') :
246
- type;
244
+ if (
245
+ typeof props.$$typeof === 'undefined' ||
246
+ props.$$typeof !== REACT_ELEMENT_TYPE
247
+ ) {
248
+ var displayName = typeof type === 'function'
249
+ ? type.displayName || type.name || 'Unknown'
250
+ : type;
251
if (key) {
252
defineKeyPropWarningGetter(props, displayName);
253
}
@@ -260,7 +264,7 @@ ReactElement.createElement = function(type, config, children) {
264
self,
265
source,
266
ReactCurrentOwner.current,
263
- props
267
+ props,
268
);
269
};
270
@@ -287,7 +291,7 @@ ReactElement.cloneAndReplaceKey = function(oldElement, newKey) {
291
oldElement._self,
292
oldElement._source,
293
oldElement._owner,
290
- oldElement.props
294
+ oldElement.props,
295
);
296
297
return newElement;
@@ -332,8 +336,10 @@ ReactElement.cloneElement = function(element, config, children) {
336
defaultProps = element.type.defaultProps;
337
}
338
for (propName in config) {
335
- if (hasOwnProperty.call(config, propName) &&
336
- !RESERVED_PROPS.hasOwnProperty(propName)) {
339
+ if (
340
+ hasOwnProperty.call(config, propName) &&
341
+ !RESERVED_PROPS.hasOwnProperty(propName)
342
+ ) {
343
if (config[propName] === undefined && defaultProps !== undefined) {
344
// Resolve default props
345
props[propName] = defaultProps[propName];
@@ -357,15 +363,7 @@ ReactElement.cloneElement = function(element, config, children) {
363
props.children = childArray;
364
}
365
360
- return ReactElement(
361
- element.type,
362
- key,
363
- ref,
364
- self,
365
- source,
366
- owner,
367
- props
368
- );
366
+ return ReactElement(element.type, key, ref, self, source, owner, props);
367
};
368
369
/**
@@ -376,11 +374,9 @@ ReactElement.cloneElement = function(element, config, children) {
374
* @final
375
*/
376
ReactElement.isValidElement = function(object) {
379
- return (
380
- typeof object === 'object' &&
377
+ return typeof object === 'object' &&
378
object !== null &&
382
- object.$$typeof === REACT_ELEMENT_TYPE
383
- );
379
+ object.$$typeof === REACT_ELEMENT_TYPE;
380
};
381
382
module.exports = ReactElement;
src/isomorphic/classic/element/ReactElementValidator.js
+38
-57
@@ -30,8 +30,8 @@ var getIteratorFn = require('getIteratorFn');
30
if (__DEV__) {
31
var warning = require('fbjs/lib/warning');
32
var ReactDebugCurrentFrame = require('ReactDebugCurrentFrame');
33
- var {
34
- getCurrentStackAddendum,
33
+ var {
34
+ getCurrentStackAddendum,
35
} = require('ReactComponentTreeHook');
36
}
37
@@ -70,8 +70,9 @@ function getCurrentComponentErrorInfo(parentType) {
70
var info = getDeclarationErrorAddendum();
71
72
if (!info) {
73
- var parentName = typeof parentType === 'string' ?
74
- parentType : parentType.displayName || parentType.name;
73
+ var parentName = typeof parentType === 'string'
74
+ ? parentType
75
+ : parentType.displayName || parentType.name;
76
if (parentName) {
77
info = `\n\nCheck the top-level render call using <${parentName}>.`;
78
}
@@ -96,9 +97,8 @@ function validateExplicitKey(element, parentType) {
97
}
98
element._store.validated = true;
99
99
- var memoizer = ownerHasKeyUseWarning.uniqueKey || (
100
- ownerHasKeyUseWarning.uniqueKey = {}
101
- );
100
+ var memoizer = ownerHasKeyUseWarning.uniqueKey ||
101
+ (ownerHasKeyUseWarning.uniqueKey = {});
102
103
var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
104
if (memoizer[currentComponentErrorInfo]) {
@@ -110,21 +110,20 @@ function validateExplicitKey(element, parentType) {
110
// property, it may be the creator of the child that's responsible for
111
// assigning it a key.
112
var childOwner = '';
113
- if (element &&
114
- element._owner &&
115
- element._owner !== ReactCurrentOwner.current) {
113
+ if (
114
+ element && element._owner && element._owner !== ReactCurrentOwner.current
115
+ ) {
116
// Give the component that originally created this child.
117
- childOwner =
118
- ` It was passed a child from ${getComponentName(element._owner)}.`;
117
+ childOwner = ` It was passed a child from ${getComponentName(element._owner)}.`;
118
}
119
120
warning(
121
false,
122
'Each child in an array or iterator should have a unique "key" prop.' +
124
- '%s%s See https://fb.me/react-warning-keys for more information.%s',
123
+ '%s%s See https://fb.me/react-warning-keys for more information.%s',
124
currentComponentErrorInfo,
125
childOwner,
127
- getCurrentStackAddendum(element)
126
+ getCurrentStackAddendum(element),
127
);
128
}
129
@@ -183,41 +182,32 @@ function validatePropTypes(element) {
182
}
183
var name = componentClass.displayName || componentClass.name;
184
if (componentClass.propTypes) {
186
- checkReactTypeSpec(
187
- componentClass.propTypes,
188
- element.props,
189
- 'prop',
190
- name
191
- );
185
+ checkReactTypeSpec(componentClass.propTypes, element.props, 'prop', name);
186
}
187
if (typeof componentClass.getDefaultProps === 'function') {
188
warning(
189
componentClass.getDefaultProps.isReactClassApproved,
190
'getDefaultProps is only used on classic React.createClass ' +
197
- 'definitions. Use a static property named `defaultProps` instead.'
191
+ 'definitions. Use a static property named `defaultProps` instead.',
192
);
193
}
194
}
195
196
var ReactElementValidator = {
203
-
197
createElement: function(type, props, children) {
205
- var validType =
206
- typeof type === 'string' ||
207
- typeof type === 'function';
198
+ var validType = typeof type === 'string' || typeof type === 'function';
199
// We warn in this case but don't throw. We expect the element creation to
200
// succeed and there will likely be errors in render.
201
if (!validType) {
202
var info = '';
203
if (
204
type === undefined ||
214
- typeof type === 'object' &&
215
- type !== null &&
216
- Object.keys(type).length === 0
205
+ (typeof type === 'object' &&
206
+ type !== null &&
207
+ Object.keys(type).length === 0)
208
) {
218
- info +=
219
- ' You likely forgot to export your component from the file ' +
220
- 'it\'s defined in.';
209
+ info += ' You likely forgot to export your component from the file ' +
210
+ "it's defined in.";
211
}
212
213
var sourceInfo = getSourceInfoErrorAddendum(props);
@@ -232,8 +222,8 @@ var ReactElementValidator = {
222
warning(
223
false,
224
'React.createElement: type is invalid -- expected a string (for ' +
235
- 'built-in components) or a class/function (for composite ' +
236
- 'components) but got: %s.%s',
225
+ 'built-in components) or a class/function (for composite ' +
226
+ 'components) but got: %s.%s',
227
type == null ? type : typeof type,
228
info,
229
);
@@ -272,37 +262,29 @@ var ReactElementValidator = {
262
},
263
264
createFactory: function(type) {
275
- var validatedFactory = ReactElementValidator.createElement.bind(
276
- null,
277
- type
278
- );
265
+ var validatedFactory = ReactElementValidator.createElement.bind(null, type);
266
// Legacy hook TODO: Warn if this is accessed
267
validatedFactory.type = type;
268
269
if (__DEV__) {
270
if (canDefineProperty) {
284
- Object.defineProperty(
285
- validatedFactory,
286
- 'type',
287
- {
288
- enumerable: false,
289
- get: function() {
290
- warning(
291
- false,
292
- 'Factory.type is deprecated. Access the class directly ' +
293
- 'before passing it to createFactory.'
294
- );
295
- Object.defineProperty(this, 'type', {
296
- value: type,
297
- });
298
- return type;
299
- },
300
- }
301
- );
271
+ Object.defineProperty(validatedFactory, 'type', {
272
+ enumerable: false,
273
+ get: function() {
274
+ warning(
275
+ false,
276
+ 'Factory.type is deprecated. Access the class directly ' +
277
+ 'before passing it to createFactory.',
278
+ );
279
+ Object.defineProperty(this, 'type', {
280
+ value: type,
281
+ });
282
+ return type;
283
+ },
284
+ });
285
}
286
}
287
305
-
288
return validatedFactory;
289
},
290
@@ -320,7 +302,6 @@ var ReactElementValidator = {
302
}
303
return newElement;
304
},
323
-
305
};
306
307
module.exports = ReactElementValidator;
src/isomorphic/classic/element/__tests__/ReactElement-test.js
+70
-43
@@ -83,9 +83,9 @@ describe('ReactElement', () => {
83
expectDev(console.error.calls.count()).toBe(1);
84
expectDev(console.error.calls.argsFor(0)[0]).toContain(
85
'Child: `key` is not a prop. Trying to access it will result ' +
86
- 'in `undefined` being returned. If you need to access the same ' +
87
- 'value within the child component, you should pass it as a different ' +
88
- 'prop. (https://fb.me/react-special-props)'
86
+ 'in `undefined` being returned. If you need to access the same ' +
87
+ 'value within the child component, you should pass it as a different ' +
88
+ 'prop. (https://fb.me/react-special-props)',
89
);
90
});
91
@@ -113,9 +113,9 @@ describe('ReactElement', () => {
113
expectDev(console.error.calls.count()).toBe(1);
114
expectDev(console.error.calls.argsFor(0)[0]).toContain(
115
'Child: `key` is not a prop. Trying to access it will result ' +
116
- 'in `undefined` being returned. If you need to access the same ' +
117
- 'value within the child component, you should pass it as a different ' +
118
- 'prop. (https://fb.me/react-special-props)'
116
+ 'in `undefined` being returned. If you need to access the same ' +
117
+ 'value within the child component, you should pass it as a different ' +
118
+ 'prop. (https://fb.me/react-special-props)',
119
);
120
});
121
@@ -127,9 +127,9 @@ describe('ReactElement', () => {
127
expectDev(console.error.calls.count()).toBe(1);
128
expectDev(console.error.calls.argsFor(0)[0]).toContain(
129
'div: `key` is not a prop. Trying to access it will result ' +
130
- 'in `undefined` being returned. If you need to access the same ' +
131
- 'value within the child component, you should pass it as a different ' +
132
- 'prop. (https://fb.me/react-special-props)'
130
+ 'in `undefined` being returned. If you need to access the same ' +
131
+ 'value within the child component, you should pass it as a different ' +
132
+ 'prop. (https://fb.me/react-special-props)',
133
);
134
});
135
@@ -155,9 +155,9 @@ describe('ReactElement', () => {
155
expectDev(console.error.calls.count()).toBe(1);
156
expectDev(console.error.calls.argsFor(0)[0]).toContain(
157
'Child: `ref` is not a prop. Trying to access it will result ' +
158
- 'in `undefined` being returned. If you need to access the same ' +
159
- 'value within the child component, you should pass it as a different ' +
160
- 'prop. (https://fb.me/react-special-props)'
158
+ 'in `undefined` being returned. If you need to access the same ' +
159
+ 'value within the child component, you should pass it as a different ' +
160
+ 'prop. (https://fb.me/react-special-props)',
161
);
162
});
163
@@ -265,7 +265,7 @@ describe('ReactElement', () => {
265
});
266
267
var instance = ReactTestUtils.renderIntoDocument(
268
- React.createElement(Wrapper)
268
+ React.createElement(Wrapper),
269
);
270
271
if (ReactDOMFeatureFlags.useFiber) {
@@ -278,9 +278,12 @@ describe('ReactElement', () => {
278
it('merges an additional argument onto the children prop', () => {
279
spyOn(console, 'error');
280
var a = 1;
281
- var element = React.createFactory(ComponentClass)({
282
- children: 'text',
283
- }, a);
281
+ var element = React.createFactory(ComponentClass)(
282
+ {
283
+ children: 'text',
284
+ },
285
+ a,
286
+ );
287
expect(element.props.children).toBe(a);
288
expectDev(console.error.calls.count()).toBe(0);
289
});
@@ -296,9 +299,12 @@ describe('ReactElement', () => {
299
300
it('overrides children if null is provided as an argument', () => {
301
spyOn(console, 'error');
299
- var element = React.createFactory(ComponentClass)({
300
- children: 'text',
301
- }, null);
302
+ var element = React.createFactory(ComponentClass)(
303
+ {
304
+ children: 'text',
305
+ },
306
+ null,
307
+ );
308
expect(element.props.children).toBe(null);
309
expectDev(console.error.calls.count()).toBe(0);
310
});
@@ -346,10 +352,8 @@ describe('ReactElement', () => {
352
},
353
});
354
349
- expect(React.isValidElement(React.createElement('div')))
350
- .toEqual(true);
351
- expect(React.isValidElement(React.createElement(Component)))
352
- .toEqual(true);
355
+ expect(React.isValidElement(React.createElement('div'))).toEqual(true);
356
+ expect(React.isValidElement(React.createElement(Component))).toEqual(true);
357
358
expect(React.isValidElement(null)).toEqual(false);
359
expect(React.isValidElement(true)).toEqual(false);
@@ -357,7 +361,7 @@ describe('ReactElement', () => {
361
expect(React.isValidElement('string')).toEqual(false);
362
expect(React.isValidElement(React.DOM.div)).toEqual(false);
363
expect(React.isValidElement(Component)).toEqual(false);
360
- expect(React.isValidElement({ type: 'div', props: {} })).toEqual(false);
364
+ expect(React.isValidElement({type: 'div', props: {}})).toEqual(false);
365
366
var jsonElement = JSON.stringify(React.createElement('div'));
367
expect(React.isValidElement(JSON.parse(jsonElement))).toBe(true);
@@ -401,7 +405,7 @@ describe('ReactElement', () => {
405
var container = document.createElement('div');
406
var instance = ReactDOM.render(
407
React.createElement(Component, {fruit: 'mango'}),
404
- container
408
+ container,
409
);
410
expect(instance.props.fruit).toBe('mango');
411
@@ -422,12 +426,12 @@ describe('ReactElement', () => {
426
});
427
428
var instance = ReactTestUtils.renderIntoDocument(
425
- React.createElement(Component)
429
+ React.createElement(Component),
430
);
431
expect(instance.props.prop).toBe('testKey');
432
433
var inst2 = ReactTestUtils.renderIntoDocument(
430
- React.createElement(Component, {prop: null})
434
+ React.createElement(Component, {prop: null}),
435
);
436
expect(inst2.props.prop).toBe(null);
437
});
@@ -510,10 +514,8 @@ describe('ReactElement', () => {
514
},
515
});
516
513
- expect(React.isValidElement(React.createElement('div')))
514
- .toEqual(true);
515
- expect(React.isValidElement(React.createElement(Component)))
516
- .toEqual(true);
517
+ expect(React.isValidElement(React.createElement('div'))).toEqual(true);
518
+ expect(React.isValidElement(React.createElement(Component))).toEqual(true);
519
520
expect(React.isValidElement(null)).toEqual(false);
521
expect(React.isValidElement(true)).toEqual(false);
@@ -521,12 +523,11 @@ describe('ReactElement', () => {
523
expect(React.isValidElement('string')).toEqual(false);
524
expect(React.isValidElement(React.DOM.div)).toEqual(false);
525
expect(React.isValidElement(Component)).toEqual(false);
524
- expect(React.isValidElement({ type: 'div', props: {} })).toEqual(false);
526
+ expect(React.isValidElement({type: 'div', props: {}})).toEqual(false);
527
528
var jsonElement = JSON.stringify(React.createElement('div'));
529
expect(React.isValidElement(JSON.parse(jsonElement))).toBe(false);
530
});
529
-
531
});
532
533
describe('comparing jsx vs .createFactory() vs .createElement()', () => {
@@ -540,7 +541,6 @@ describe('comparing jsx vs .createFactory() vs .createElement()', () => {
541
Child = jest.genMockFromModule('ReactElementTestChild');
542
});
543
543
-
544
describe('when using jsx only', () => {
545
var Parent, instance;
546
beforeEach(() => {
@@ -557,7 +557,10 @@ describe('comparing jsx vs .createFactory() vs .createElement()', () => {
557
});
558
559
it('should scry children but cannot', () => {
560
- var children = ReactTestUtils.scryRenderedComponentsWithType(instance, Child);
560
+ var children = ReactTestUtils.scryRenderedComponentsWithType(
561
+ instance,
562
+ Child,
563
+ );
564
expect(children.length).toBe(1);
565
});
566
@@ -566,7 +569,10 @@ describe('comparing jsx vs .createFactory() vs .createElement()', () => {
569
});
570
571
it('can capture Child instantiation calls', () => {
569
- expect(Child.mock.calls[0][0]).toEqual({ foo: 'foo value', children: 'children value' });
572
+ expect(Child.mock.calls[0][0]).toEqual({
573
+ foo: 'foo value',
574
+ children: 'children value',
575
+ });
576
});
577
});
578
@@ -576,7 +582,10 @@ describe('comparing jsx vs .createFactory() vs .createElement()', () => {
582
var childFactory = React.createFactory(Child);
583
var Parent = React.createClass({
584
render: function() {
579
- return React.DOM.div({}, childFactory({ ref: 'child', foo: 'foo value' }, 'children value'));
585
+ return React.DOM.div(
586
+ {},
587
+ childFactory({ref: 'child', foo: 'foo value'}, 'children value'),
588
+ );
589
},
590
});
591
factory = React.createFactory(Parent);
@@ -584,7 +593,10 @@ describe('comparing jsx vs .createFactory() vs .createElement()', () => {
593
});
594
595
it('can properly scry children', () => {
587
- var children = ReactTestUtils.scryRenderedComponentsWithType(instance, Child);
596
+ var children = ReactTestUtils.scryRenderedComponentsWithType(
597
+ instance,
598
+ Child,
599
+ );
600
expect(children.length).toBe(1);
601
});
602
@@ -593,7 +605,10 @@ describe('comparing jsx vs .createFactory() vs .createElement()', () => {
605
});
606
607
it('can capture Child instantiation calls', () => {
596
- expect(Child.mock.calls[0][0]).toEqual({ foo: 'foo value', children: 'children value' });
608
+ expect(Child.mock.calls[0][0]).toEqual({
609
+ foo: 'foo value',
610
+ children: 'children value',
611
+ });
612
});
613
});
614
@@ -602,7 +617,14 @@ describe('comparing jsx vs .createFactory() vs .createElement()', () => {
617
beforeEach(() => {
618
var Parent = React.createClass({
619
render: function() {
605
- return React.DOM.div({}, React.createElement(Child, { ref: 'child', foo: 'foo value' }, 'children value'));
620
+ return React.DOM.div(
621
+ {},
622
+ React.createElement(
623
+ Child,
624
+ {ref: 'child', foo: 'foo value'},
625
+ 'children value',
626
+ ),
627
+ );
628
},
629
});
630
factory = React.createFactory(Parent);
@@ -610,7 +632,10 @@ describe('comparing jsx vs .createFactory() vs .createElement()', () => {
632
});
633
634
it('should scry children but cannot', () => {
613
- var children = ReactTestUtils.scryRenderedComponentsWithType(instance, Child);
635
+ var children = ReactTestUtils.scryRenderedComponentsWithType(
636
+ instance,
637
+ Child,
638
+ );
639
expect(children.length).toBe(1);
640
});
641
@@ -619,8 +644,10 @@ describe('comparing jsx vs .createFactory() vs .createElement()', () => {
644
});
645
646
it('can capture Child instantiation calls', () => {
622
- expect(Child.mock.calls[0][0]).toEqual({ foo: 'foo value', children: 'children value' });
647
+ expect(Child.mock.calls[0][0]).toEqual({
648
+ foo: 'foo value',
649
+ children: 'children value',
650
+ });
651
});
652
});
625
-
653
});
src/isomorphic/classic/element/__tests__/ReactElementClone-test.js
+36
-31
@@ -42,7 +42,7 @@ describe('ReactElementClone', () => {
42
render: function() {
43
return (
44
<div className="parent">
45
- {React.cloneElement(this.props.child, { className: 'xyz' })}
45
+ {React.cloneElement(this.props.child, {className: 'xyz'})}
46
</div>
47
);
48
},
@@ -66,7 +66,7 @@ describe('ReactElementClone', () => {
66
render: function() {
67
return (
68
<div className="parent">
69
- {React.cloneElement(this.props.child, { className: 'xyz' })}
69
+ {React.cloneElement(this.props.child, {className: 'xyz'})}
70
</div>
71
);
72
},
@@ -91,7 +91,7 @@ describe('ReactElementClone', () => {
91
render: function() {
92
return (
93
<div>
94
- {React.cloneElement(this.props.child, { className: 'xyz' })}
94
+ {React.cloneElement(this.props.child, {className: 'xyz'})}
95
</div>
96
);
97
},
@@ -120,7 +120,7 @@ describe('ReactElementClone', () => {
120
});
121
122
ReactTestUtils.renderIntoDocument(
123
- React.cloneElement(<Component />, {children: 'xyz'})
123
+ React.cloneElement(<Component />, {children: 'xyz'}),
124
);
125
});
126
@@ -133,7 +133,7 @@ describe('ReactElementClone', () => {
133
});
134
135
ReactTestUtils.renderIntoDocument(
136
- React.cloneElement(<Component>xyz</Component>, {})
136
+ React.cloneElement(<Component>xyz</Component>, {}),
137
);
138
});
139
@@ -146,34 +146,41 @@ describe('ReactElementClone', () => {
146
147
var clone = React.cloneElement(
148
<Component>xyz</Component>,
149
- { children: <Component /> },
149
+ {children: <Component />},
150
<div />,
151
- <span />
151
+ <span />,
152
);
153
154
- expect(clone.props.children).toEqual([
155
- <div />,
156
- <span />,
157
- ]);
154
+ expect(clone.props.children).toEqual([<div />, <span />]);
155
});
156
157
it('should override children if undefined is provided as an argument', () => {
161
- var element = React.createElement(ComponentClass, {
162
- children: 'text',
163
- }, undefined);
158
+ var element = React.createElement(
159
+ ComponentClass,
160
+ {
161
+ children: 'text',
162
+ },
163
+ undefined,
164
+ );
165
expect(element.props.children).toBe(undefined);
166
166
- var element2 = React.cloneElement(React.createElement(ComponentClass, {
167
- children: 'text',
168
- }), {}, undefined);
167
+ var element2 = React.cloneElement(
168
+ React.createElement(ComponentClass, {
169
+ children: 'text',
170
+ }),
171
+ {},
172
+ undefined,
173
+ );
174
expect(element2.props.children).toBe(undefined);
175
});
176
177
it('should support keys and refs', () => {
178
var Parent = React.createClass({
179
render: function() {
175
- var clone =
176
- React.cloneElement(this.props.children, {key: 'xyz', ref: 'xyz'});
180
+ var clone = React.cloneElement(this.props.children, {
181
+ key: 'xyz',
182
+ ref: 'xyz',
183
+ });
184
expect(clone.key).toBe('xyz');
185
expect(clone.ref).toBe('xyz');
186
return <div>{clone}</div>;
@@ -218,7 +225,7 @@ describe('ReactElementClone', () => {
225
});
226
227
ReactTestUtils.renderIntoDocument(
221
- React.cloneElement(<Component myprop="abc" />, {myprop: 'xyz'})
228
+ React.cloneElement(<Component myprop="abc" />, {myprop: 'xyz'}),
229
);
230
});
231
@@ -252,7 +259,7 @@ describe('ReactElementClone', () => {
259
260
expectDev(console.error.calls.count()).toBe(1);
261
expectDev(console.error.calls.argsFor(0)[0]).toContain(
255
- 'Each child in an array or iterator should have a unique "key" prop.'
262
+ 'Each child in an array or iterator should have a unique "key" prop.',
263
);
264
});
265
@@ -297,21 +304,20 @@ describe('ReactElementClone', () => {
304
});
305
var GrandParent = React.createClass({
306
render: function() {
300
- return React.createElement(
301
- Parent,
302
- { child: React.createElement(Component, {color: 'red'}) }
303
- );
307
+ return React.createElement(Parent, {
308
+ child: React.createElement(Component, {color: 'red'}),
309
+ });
310
},
311
});
312
ReactTestUtils.renderIntoDocument(React.createElement(GrandParent));
313
expectDev(console.error.calls.count()).toBe(1);
314
expectDev(console.error.calls.argsFor(0)[0]).toBe(
315
'Warning: Failed prop type: ' +
310
- 'Invalid prop `color` of type `number` supplied to `Component`, ' +
311
- 'expected `string`.\n' +
312
- ' in Component (created by GrandParent)\n' +
313
- ' in Parent (created by GrandParent)\n' +
314
- ' in GrandParent'
316
+ 'Invalid prop `color` of type `number` supplied to `Component`, ' +
317
+ 'expected `string`.\n' +
318
+ ' in Component (created by GrandParent)\n' +
319
+ ' in Parent (created by GrandParent)\n' +
320
+ ' in GrandParent',
321
);
322
});
323
@@ -361,5 +367,4 @@ describe('ReactElementClone', () => {
367
expect(Object.isFrozen(element.props)).toBe(true);
368
expect(clone.props).toEqual({foo: 'ef'});
369
});
364
-
370
});
src/isomorphic/classic/element/__tests__/ReactElementValidator-test.js
+67
-78
@@ -46,7 +46,7 @@ describe('ReactElementValidator', () => {
46
47
expectDev(console.error.calls.count()).toBe(1);
48
expectDev(console.error.calls.argsFor(0)[0]).toContain(
49
- 'Each child in an array or iterator should have a unique "key" prop.'
49
+ 'Each child in an array or iterator should have a unique "key" prop.',
50
);
51
});
52
@@ -66,19 +66,17 @@ describe('ReactElementValidator', () => {
66
var ComponentWrapper = React.createClass({
67
displayName: 'ComponentWrapper',
68
render: function() {
69
- return InnerComponent({childSet: [Component(), Component()] });
69
+ return InnerComponent({childSet: [Component(), Component()]});
70
},
71
});
72
73
- ReactTestUtils.renderIntoDocument(
74
- React.createElement(ComponentWrapper)
75
- );
73
+ ReactTestUtils.renderIntoDocument(React.createElement(ComponentWrapper));
74
75
expectDev(console.error.calls.count()).toBe(1);
76
expectDev(console.error.calls.argsFor(0)[0]).toContain(
77
'Each child in an array or iterator should have a unique "key" prop.' +
80
- '\n\nCheck the render method of `InnerClass`. ' +
81
- 'It was passed a child from ComponentWrapper. '
78
+ '\n\nCheck the render method of `InnerClass`. ' +
79
+ 'It was passed a child from ComponentWrapper. ',
80
);
81
});
82
@@ -92,35 +90,29 @@ describe('ReactElementValidator', () => {
90
},
91
});
92
95
- var divs = [
96
- <div />,
97
- <div />,
98
- ];
93
+ var divs = [<div />, <div />];
94
ReactTestUtils.renderIntoDocument(<Anonymous>{divs}</Anonymous>);
95
96
expectDev(console.error.calls.count()).toBe(1);
97
expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
98
'Warning: Each child in an array or iterator should have a unique ' +
104
- '"key" prop. See https://fb.me/react-warning-keys for more information.\n' +
105
- ' in div (at **)'
99
+ '"key" prop. See https://fb.me/react-warning-keys for more information.\n' +
100
+ ' in div (at **)',
101
);
102
});
103
104
it('warns for keys for arrays of elements with no owner info', () => {
105
spyOn(console, 'error');
106
112
- var divs = [
113
- <div />,
114
- <div />,
115
- ];
107
+ var divs = [<div />, <div />];
108
ReactTestUtils.renderIntoDocument(<div>{divs}</div>);
109
110
expectDev(console.error.calls.count()).toBe(1);
111
expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
112
'Warning: Each child in an array or iterator should have a unique ' +
121
- '"key" prop.\n\nCheck the top-level render call using <div>. See ' +
122
- 'https://fb.me/react-warning-keys for more information.\n' +
123
- ' in div (at **)'
113
+ '"key" prop.\n\nCheck the top-level render call using <div>. See ' +
114
+ 'https://fb.me/react-warning-keys for more information.\n' +
115
+ ' in div (at **)',
116
);
117
});
118
@@ -150,12 +142,12 @@ describe('ReactElementValidator', () => {
142
expectDev(console.error.calls.count()).toBe(1);
143
expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
144
'Warning: Each child in an array or iterator should have a unique ' +
153
- '"key" prop.\n\nCheck the render method of `Component`. See ' +
154
- 'https://fb.me/react-warning-keys for more information.\n' +
155
- ' in div (at **)\n' +
156
- ' in Component (at **)\n' +
157
- ' in Parent (at **)\n' +
158
- ' in GrandParent (at **)'
145
+ '"key" prop.\n\nCheck the render method of `Component`. See ' +
146
+ 'https://fb.me/react-warning-keys for more information.\n' +
147
+ ' in div (at **)\n' +
148
+ ' in Component (at **)\n' +
149
+ ' in Parent (at **)\n' +
150
+ ' in GrandParent (at **)',
151
);
152
});
153
@@ -177,7 +169,7 @@ describe('ReactElementValidator', () => {
169
<Wrapper>
170
<span />
171
<span />
180
- </Wrapper>
172
+ </Wrapper>,
173
);
174
175
expectDev(console.error.calls.count()).toBe(0);
@@ -203,7 +195,7 @@ describe('ReactElementValidator', () => {
195
196
expectDev(console.error.calls.count()).toBe(1);
197
expectDev(console.error.calls.argsFor(0)[0]).toContain(
206
- 'Each child in an array or iterator should have a unique "key" prop.'
198
+ 'Each child in an array or iterator should have a unique "key" prop.',
199
);
200
});
201
@@ -279,10 +271,10 @@ describe('ReactElementValidator', () => {
271
ReactTestUtils.renderIntoDocument(React.createElement(ParentComp));
272
expectDev(console.error.calls.argsFor(0)[0]).toBe(
273
'Warning: Failed prop type: ' +
282
- 'Invalid prop `color` of type `number` supplied to `MyComp`, ' +
283
- 'expected `string`.\n' +
284
- ' in MyComp (created by ParentComp)\n' +
285
- ' in ParentComp'
274
+ 'Invalid prop `color` of type `number` supplied to `MyComp`, ' +
275
+ 'expected `string`.\n' +
276
+ ' in MyComp (created by ParentComp)\n' +
277
+ ' in ParentComp',
278
);
279
});
280
@@ -297,35 +289,35 @@ describe('ReactElementValidator', () => {
289
expectDev(console.error.calls.count()).toBe(6);
290
expectDev(console.error.calls.argsFor(0)[0]).toBe(
291
'Warning: React.createElement: type is invalid -- expected a string ' +
300
- '(for built-in components) or a class/function (for composite ' +
301
- 'components) but got: undefined. You likely forgot to export your ' +
302
- 'component from the file it\'s defined in.'
292
+ '(for built-in components) or a class/function (for composite ' +
293
+ 'components) but got: undefined. You likely forgot to export your ' +
294
+ "component from the file it's defined in.",
295
);
296
expectDev(console.error.calls.argsFor(1)[0]).toBe(
297
'Warning: React.createElement: type is invalid -- expected a string ' +
306
- '(for built-in components) or a class/function (for composite ' +
307
- 'components) but got: null.'
298
+ '(for built-in components) or a class/function (for composite ' +
299
+ 'components) but got: null.',
300
);
301
expectDev(console.error.calls.argsFor(2)[0]).toBe(
302
'Warning: React.createElement: type is invalid -- expected a string ' +
311
- '(for built-in components) or a class/function (for composite ' +
312
- 'components) but got: boolean.'
303
+ '(for built-in components) or a class/function (for composite ' +
304
+ 'components) but got: boolean.',
305
);
306
expectDev(console.error.calls.argsFor(3)[0]).toBe(
307
'Warning: React.createElement: type is invalid -- expected a string ' +
316
- '(for built-in components) or a class/function (for composite ' +
317
- 'components) but got: number.'
308
+ '(for built-in components) or a class/function (for composite ' +
309
+ 'components) but got: number.',
310
);
311
expectDev(console.error.calls.argsFor(4)[0]).toBe(
312
'Warning: React.createElement: type is invalid -- expected a string ' +
321
- '(for built-in components) or a class/function (for composite ' +
322
- 'components) but got: object.'
313
+ '(for built-in components) or a class/function (for composite ' +
314
+ 'components) but got: object.',
315
);
316
expectDev(console.error.calls.argsFor(5)[0]).toBe(
317
'Warning: React.createElement: type is invalid -- expected a string ' +
326
- '(for built-in components) or a class/function (for composite ' +
327
- 'components) but got: object. You likely forgot to export your ' +
328
- 'component from the file it\'s defined in.'
318
+ '(for built-in components) or a class/function (for composite ' +
319
+ 'components) but got: object. You likely forgot to export your ' +
320
+ "component from the file it's defined in.",
321
);
322
React.createElement('div');
323
expectDev(console.error.calls.count()).toBe(6);
@@ -342,15 +334,15 @@ describe('ReactElementValidator', () => {
334
ReactTestUtils.renderIntoDocument(React.createElement(ParentComp));
335
}).toThrowError(
336
'Element type is invalid: expected a string (for built-in components) ' +
345
- 'or a class/function (for composite components) but got: null.\n\nCheck ' +
346
- 'the render method of `ParentComp`.'
337
+ 'or a class/function (for composite components) but got: null.\n\nCheck ' +
338
+ 'the render method of `ParentComp`.',
339
);
340
expectDev(console.error.calls.count()).toBe(1);
341
expectDev(console.error.calls.argsFor(0)[0]).toBe(
342
'Warning: React.createElement: type is invalid -- expected a string ' +
351
- '(for built-in components) or a class/function (for composite ' +
352
- 'components) but got: null.\n\nCheck the render method of `ParentComp`.' +
353
- '\n in ParentComp'
343
+ '(for built-in components) or a class/function (for composite ' +
344
+ 'components) but got: null.\n\nCheck the render method of `ParentComp`.' +
345
+ '\n in ParentComp',
346
);
347
});
348
@@ -372,8 +364,8 @@ describe('ReactElementValidator', () => {
364
expectDev(console.error.calls.count()).toBe(1);
365
expectDev(console.error.calls.argsFor(0)[0]).toBe(
366
'Warning: Failed prop type: The prop `prop` is marked as required in ' +
375
- '`Component`, but its value is `null`.\n' +
376
- ' in Component'
367
+ '`Component`, but its value is `null`.\n' +
368
+ ' in Component',
369
);
370
});
371
@@ -391,14 +383,14 @@ describe('ReactElementValidator', () => {
383
});
384
385
ReactTestUtils.renderIntoDocument(
394
- React.createElement(Component, {prop:null})
386
+ React.createElement(Component, {prop: null}),
387
);
388
389
expectDev(console.error.calls.count()).toBe(1);
390
expectDev(console.error.calls.argsFor(0)[0]).toBe(
391
'Warning: Failed prop type: The prop `prop` is marked as required in ' +
400
- '`Component`, but its value is `null`.\n' +
401
- ' in Component'
392
+ '`Component`, but its value is `null`.\n' +
393
+ ' in Component',
394
);
395
});
396
@@ -414,30 +406,28 @@ describe('ReactElementValidator', () => {
406
},
407
});
408
409
+ ReactTestUtils.renderIntoDocument(React.createElement(Component));
410
ReactTestUtils.renderIntoDocument(
418
- React.createElement(Component)
419
- );
420
- ReactTestUtils.renderIntoDocument(
421
- React.createElement(Component, {prop: 42})
411
+ React.createElement(Component, {prop: 42}),
412
);
413
414
expectDev(console.error.calls.count()).toBe(2);
415
expectDev(console.error.calls.argsFor(0)[0]).toBe(
416
'Warning: Failed prop type: ' +
427
- 'The prop `prop` is marked as required in `Component`, but its value ' +
428
- 'is `undefined`.\n' +
429
- ' in Component'
417
+ 'The prop `prop` is marked as required in `Component`, but its value ' +
418
+ 'is `undefined`.\n' +
419
+ ' in Component',
420
);
421
422
expectDev(console.error.calls.argsFor(1)[0]).toBe(
423
'Warning: Failed prop type: ' +
434
- 'Invalid prop `prop` of type `number` supplied to ' +
435
- '`Component`, expected `string`.\n' +
436
- ' in Component'
424
+ 'Invalid prop `prop` of type `number` supplied to ' +
425
+ '`Component`, expected `string`.\n' +
426
+ ' in Component',
427
);
428
429
ReactTestUtils.renderIntoDocument(
440
- React.createElement(Component, {prop: 'string'})
430
+ React.createElement(Component, {prop: 'string'}),
431
);
432
433
// Should not error for strings
@@ -457,16 +447,16 @@ describe('ReactElementValidator', () => {
447
});
448
449
ReactTestUtils.renderIntoDocument(
460
- React.createElement(Component, {myProp: {value: 'hi'}})
450
+ React.createElement(Component, {myProp: {value: 'hi'}}),
451
);
452
453
expectDev(console.error.calls.count()).toBe(1);
454
expectDev(console.error.calls.argsFor(0)[0]).toBe(
455
'Warning: Component: type specification of prop `myProp` is invalid; ' +
466
- 'the type checker function must return `null` or an `Error` but ' +
467
- 'returned a function. You may have forgotten to pass an argument to ' +
468
- 'the type checker creator (arrayOf, instanceOf, objectOf, oneOf, ' +
469
- 'oneOfType, and shape all require an argument).'
456
+ 'the type checker function must return `null` or an `Error` but ' +
457
+ 'returned a function. You may have forgotten to pass an argument to ' +
458
+ 'the type checker creator (arrayOf, instanceOf, objectOf, oneOf, ' +
459
+ 'oneOfType, and shape all require an argument).',
460
);
461
});
462
@@ -482,7 +472,7 @@ describe('ReactElementValidator', () => {
472
expectDev(console.error.calls.count()).toBe(1);
473
expectDev(console.error.calls.argsFor(0)[0]).toBe(
474
'Warning: Factory.type is deprecated. Access the class directly before ' +
485
- 'passing it to createFactory.'
475
+ 'passing it to createFactory.',
476
);
477
// Warn once, not again
478
expect(TestFactory.type).toBe(TestComponent);
@@ -531,7 +521,7 @@ describe('ReactElementValidator', () => {
521
// shouldn't blow up either.
522
523
var child = {
534
- $$typeof: (<div />).$$typeof,
524
+ $$typeof: <div />.$$typeof,
525
type: 'span',
526
key: null,
527
ref: null,
@@ -549,10 +539,9 @@ describe('ReactElementValidator', () => {
539
expectDev(console.error.calls.count()).toBe(1);
540
expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
541
'Warning: React.createElement: type is invalid -- expected a string ' +
552
- '(for built-in components) or a class/function (for composite ' +
553
- 'components) but got: undefined. You likely forgot to export your ' +
554
- 'component from the file it\'s defined in.\n\nCheck your code at **.'
542
+ '(for built-in components) or a class/function (for composite ' +
543
+ 'components) but got: undefined. You likely forgot to export your ' +
544
+ "component from the file it's defined in.\n\nCheck your code at **.",
545
);
546
});
557
-
547
});
src/isomorphic/classic/types/ReactPropTypes.js
+40
-43
@@ -95,7 +95,7 @@ if (__DEV__) {
95
var productionTypeChecker = function() {
96
invariant(
97
false,
98
- 'React.PropTypes type checking code is stripped in production.'
98
+ 'React.PropTypes type checking code is stripped in production.',
99
);
100
};
101
productionTypeChecker.isRequired = productionTypeChecker;
@@ -122,7 +122,6 @@ if (__DEV__) {
122
};
123
}
124
125
-
125
/**
126
* inlined Object.is polyfill to avoid requiring consumers ship their own
127
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
@@ -130,7 +129,8 @@ if (__DEV__) {
129
/*eslint-disable no-self-compare*/
130
function is(x, y) {
131
// SameValue algorithm
133
- if (x === y) { // Steps 1-5, 7-10
132
+ if (x === y) {
133
+ // Steps 1-5, 7-10
134
// Steps 6.b-6.e: +0 != -0
135
return x !== 0 || 1 / x === 1 / y;
136
} else {
@@ -165,27 +165,24 @@ function createChainableTypeChecker(validate) {
165
componentName,
166
location,
167
propFullName,
168
- secret
168
+ secret,
169
) {
170
componentName = componentName || ANONYMOUS;
171
propFullName = propFullName || propName;
172
if (__DEV__) {
173
- if (
174
- secret !== ReactPropTypesSecret &&
175
- typeof console !== 'undefined'
176
- ) {
173
+ if (secret !== ReactPropTypesSecret && typeof console !== 'undefined') {
174
var cacheKey = `${componentName}:${propName}`;
175
if (!manualPropTypeCallCache[cacheKey]) {
176
warning(
177
false,
178
'You are manually calling a React.PropTypes validation ' +
182
- 'function for the `%s` prop on `%s`. This is deprecated ' +
183
- 'and will not work in production with the next major version. ' +
184
- 'You may be seeing this warning due to a third-party PropTypes ' +
185
- 'library. See https://fb.me/react-warning-dont-call-proptypes ' +
186
- 'for details.',
179
+ 'function for the `%s` prop on `%s`. This is deprecated ' +
180
+ 'and will not work in production with the next major version. ' +
181
+ 'You may be seeing this warning due to a third-party PropTypes ' +
182
+ 'library. See https://fb.me/react-warning-dont-call-proptypes ' +
183
+ 'for details.',
184
propFullName,
188
- componentName
185
+ componentName,
186
);
187
manualPropTypeCallCache[cacheKey] = true;
188
}
@@ -196,23 +193,17 @@ function createChainableTypeChecker(validate) {
193
if (props[propName] === null) {
194
return new PropTypeError(
195
`The ${location} \`${propFullName}\` is marked as required ` +
199
- `in \`${componentName}\`, but its value is \`null\`.`
196
+ `in \`${componentName}\`, but its value is \`null\`.`,
197
);
198
}
199
return new PropTypeError(
200
`The ${location} \`${propFullName}\` is marked as required in ` +
204
- `\`${componentName}\`, but its value is \`undefined\`.`
201
+ `\`${componentName}\`, but its value is \`undefined\`.`,
202
);
203
}
204
return null;
205
} else {
209
- return validate(
210
- props,
211
- propName,
212
- componentName,
213
- location,
214
- propFullName,
215
- );
206
+ return validate(props, propName, componentName, location, propFullName);
207
}
208
}
209
@@ -229,7 +220,7 @@ function createPrimitiveTypeChecker(expectedType) {
220
componentName,
221
location,
222
propFullName,
232
- secret
223
+ secret,
224
) {
225
var propValue = props[propName];
226
var propType = getPropType(propValue);
@@ -241,8 +232,8 @@ function createPrimitiveTypeChecker(expectedType) {
232
233
return new PropTypeError(
234
`Invalid ${location} \`${propFullName}\` of type ` +
244
- `\`${preciseType}\` supplied to \`${componentName}\`, expected ` +
245
- `\`${expectedType}\`.`
235
+ `\`${preciseType}\` supplied to \`${componentName}\`, expected ` +
236
+ `\`${expectedType}\`.`,
237
);
238
}
239
return null;
@@ -258,7 +249,7 @@ function createArrayOfTypeChecker(typeChecker) {
249
function validate(props, propName, componentName, location, propFullName) {
250
if (typeof typeChecker !== 'function') {
251
return new PropTypeError(
261
- `Property \`${propFullName}\` of component \`${componentName}\` has invalid PropType notation inside arrayOf.`
252
+ `Property \`${propFullName}\` of component \`${componentName}\` has invalid PropType notation inside arrayOf.`,
253
);
254
}
255
var propValue = props[propName];
@@ -266,7 +257,7 @@ function createArrayOfTypeChecker(typeChecker) {
257
var propType = getPropType(propValue);
258
return new PropTypeError(
259
`Invalid ${location} \`${propFullName}\` of type ` +
269
- `\`${propType}\` supplied to \`${componentName}\`, expected an array.`
260
+ `\`${propType}\` supplied to \`${componentName}\`, expected an array.`,
261
);
262
}
263
for (var i = 0; i < propValue.length; i++) {
@@ -276,7 +267,7 @@ function createArrayOfTypeChecker(typeChecker) {
267
componentName,
268
location,
269
`${propFullName}[${i}]`,
279
- ReactPropTypesSecret
270
+ ReactPropTypesSecret,
271
);
272
if (error instanceof Error) {
273
return error;
@@ -294,7 +285,7 @@ function createElementTypeChecker() {
285
var propType = getPropType(propValue);
286
return new PropTypeError(
287
`Invalid ${location} \`${propFullName}\` of type ` +
297
- `\`${propType}\` supplied to \`${componentName}\`, expected a single ReactElement.`
288
+ `\`${propType}\` supplied to \`${componentName}\`, expected a single ReactElement.`,
289
);
290
}
291
return null;
@@ -309,8 +300,8 @@ function createInstanceTypeChecker(expectedClass) {
300
var actualClassName = getClassName(props[propName]);
301
return new PropTypeError(
302
`Invalid ${location} \`${propFullName}\` of type ` +
312
- `\`${actualClassName}\` supplied to \`${componentName}\`, expected ` +
313
- `instance of \`${expectedClassName}\`.`
303
+ `\`${actualClassName}\` supplied to \`${componentName}\`, expected ` +
304
+ `instance of \`${expectedClassName}\`.`,
305
);
306
}
307
return null;
@@ -320,7 +311,10 @@ function createInstanceTypeChecker(expectedClass) {
311
312
function createEnumTypeChecker(expectedValues) {
313
if (!Array.isArray(expectedValues)) {
323
- warning(false, 'Invalid argument supplied to oneOf, expected an instance of array.');
314
+ warning(
315
+ false,
316
+ 'Invalid argument supplied to oneOf, expected an instance of array.',
317
+ );
318
return emptyFunction.thatReturnsNull;
319
}
320
@@ -335,7 +329,7 @@ function createEnumTypeChecker(expectedValues) {
329
var valuesString = JSON.stringify(expectedValues);
330
return new PropTypeError(
331
`Invalid ${location} \`${propFullName}\` of value \`${propValue}\` ` +
338
- `supplied to \`${componentName}\`, expected one of ${valuesString}.`
332
+ `supplied to \`${componentName}\`, expected one of ${valuesString}.`,
333
);
334
}
335
return createChainableTypeChecker(validate);
@@ -345,7 +339,7 @@ function createObjectOfTypeChecker(typeChecker) {
339
function validate(props, propName, componentName, location, propFullName) {
340
if (typeof typeChecker !== 'function') {
341
return new PropTypeError(
348
- `Property \`${propFullName}\` of component \`${componentName}\` has invalid PropType notation inside objectOf.`
342
+ `Property \`${propFullName}\` of component \`${componentName}\` has invalid PropType notation inside objectOf.`,
343
);
344
}
345
var propValue = props[propName];
@@ -353,7 +347,7 @@ function createObjectOfTypeChecker(typeChecker) {
347
if (propType !== 'object') {
348
return new PropTypeError(
349
`Invalid ${location} \`${propFullName}\` of type ` +
356
- `\`${propType}\` supplied to \`${componentName}\`, expected an object.`
350
+ `\`${propType}\` supplied to \`${componentName}\`, expected an object.`,
351
);
352
}
353
for (var key in propValue) {
@@ -364,7 +358,7 @@ function createObjectOfTypeChecker(typeChecker) {
358
componentName,
359
location,
360
`${propFullName}.${key}`,
367
- ReactPropTypesSecret
361
+ ReactPropTypesSecret,
362
);
363
if (error instanceof Error) {
364
return error;
@@ -378,7 +372,10 @@ function createObjectOfTypeChecker(typeChecker) {
372
373
function createUnionTypeChecker(arrayOfTypeCheckers) {
374
if (!Array.isArray(arrayOfTypeCheckers)) {
381
- warning(false, 'Invalid argument supplied to oneOfType, expected an instance of array.');
375
+ warning(
376
+ false,
377
+ 'Invalid argument supplied to oneOfType, expected an instance of array.',
378
+ );
379
return emptyFunction.thatReturnsNull;
380
}
381
@@ -392,7 +389,7 @@ function createUnionTypeChecker(arrayOfTypeCheckers) {
389
componentName,
390
location,
391
propFullName,
395
- ReactPropTypesSecret
392
+ ReactPropTypesSecret,
393
) == null
394
) {
395
return null;
@@ -401,7 +398,7 @@ function createUnionTypeChecker(arrayOfTypeCheckers) {
398
399
return new PropTypeError(
400
`Invalid ${location} \`${propFullName}\` supplied to ` +
404
- `\`${componentName}\`.`
401
+ `\`${componentName}\`.`,
402
);
403
}
404
return createChainableTypeChecker(validate);
@@ -412,7 +409,7 @@ function createNodeChecker() {
409
if (!isNode(props[propName])) {
410
return new PropTypeError(
411
`Invalid ${location} \`${propFullName}\` supplied to ` +
415
- `\`${componentName}\`, expected a ReactNode.`
412
+ `\`${componentName}\`, expected a ReactNode.`,
413
);
414
}
415
return null;
@@ -427,7 +424,7 @@ function createShapeTypeChecker(shapeTypes) {
424
if (propType !== 'object') {
425
return new PropTypeError(
426
`Invalid ${location} \`${propFullName}\` of type \`${propType}\` ` +
430
- `supplied to \`${componentName}\`, expected \`object\`.`
427
+ `supplied to \`${componentName}\`, expected \`object\`.`,
428
);
429
}
430
for (var key in shapeTypes) {
@@ -441,7 +438,7 @@ function createShapeTypeChecker(shapeTypes) {
438
componentName,
439
location,
440
`${propFullName}.${key}`,
444
- ReactPropTypesSecret
441
+ ReactPropTypesSecret,
442
);
443
if (error) {
444
return error;
src/isomorphic/classic/types/__tests__/ReactPropTypes-test.js
+223
-170
@@ -62,14 +62,22 @@ function typeCheckFailRequiredValues(declaration) {
62
var unspecifiedMsg = 'The prop `testProp` is marked as required in ' +
63
'`testComponent`, but its value is \`undefined\`.';
64
65
- var propTypes = { testProp: declaration };
65
+ var propTypes = {testProp: declaration};
66
67
// Required prop is null
68
- var message1 = getPropTypeWarningMessage(propTypes, { testProp: null }, 'testComponent');
68
+ var message1 = getPropTypeWarningMessage(
69
+ propTypes,
70
+ {testProp: null},
71
+ 'testComponent',
72
+ );
73
expect(message1).toContain(specifiedButIsNullMsg);
74
75
// Required prop is undefined
72
- var message2 = getPropTypeWarningMessage(propTypes, { testProp: undefined }, 'testComponent');
76
+ var message2 = getPropTypeWarningMessage(
77
+ propTypes,
78
+ {testProp: undefined},
79
+ 'testComponent',
80
+ );
81
expect(message2).toContain(unspecifiedMsg);
82
83
// Required prop is not a member of props object
@@ -93,16 +101,11 @@ function expectWarningInDevelopment(declaration, value) {
101
var propName = 'testProp' + Math.random().toString();
102
var componentName = 'testComponent' + Math.random().toString();
103
for (var i = 0; i < 3; i++) {
96
- declaration(
97
- props,
98
- propName,
99
- componentName,
100
- 'prop'
101
- );
104
+ declaration(props, propName, componentName, 'prop');
105
}
106
expect(console.error.calls.count()).toBe(1);
107
expect(console.error.calls.argsFor(0)[0]).toContain(
105
- 'You are manually calling a React.PropTypes validation '
108
+ 'You are manually calling a React.PropTypes validation ',
109
);
110
console.error.calls.reset();
111
}
@@ -124,8 +127,14 @@ describe('ReactPropTypes', () => {
127
return new Error('some error');
128
},
129
};
127
- const props = { foo: 'foo' };
128
- const returnValue = checkPropTypes(propTypes, props, 'prop', 'testComponent', null);
130
+ const props = {foo: 'foo'};
131
+ const returnValue = checkPropTypes(
132
+ propTypes,
133
+ props,
134
+ 'prop',
135
+ 'testComponent',
136
+ null,
137
+ );
138
expect(console.error.calls.argsFor(0)[0]).toContain('some error');
139
expect(returnValue).toBe(undefined);
140
});
@@ -137,8 +146,14 @@ describe('ReactPropTypes', () => {
146
throw new Error('some error');
147
},
148
};
140
- const props = { foo: 'foo' };
141
- const returnValue = checkPropTypes(propTypes, props, 'prop', 'testComponent', null);
149
+ const props = {foo: 'foo'};
150
+ const returnValue = checkPropTypes(
151
+ propTypes,
152
+ props,
153
+ 'prop',
154
+ 'testComponent',
155
+ null,
156
+ );
157
expect(console.error.calls.argsFor(0)[0]).toContain('some error');
158
expect(returnValue).toBe(undefined);
159
});
@@ -150,31 +165,31 @@ describe('ReactPropTypes', () => {
165
PropTypes.string,
166
[],
167
'Invalid prop `testProp` of type `array` supplied to ' +
153
- '`testComponent`, expected `string`.'
168
+ '`testComponent`, expected `string`.',
169
);
170
typeCheckFail(
171
PropTypes.string,
172
false,
173
'Invalid prop `testProp` of type `boolean` supplied to ' +
159
- '`testComponent`, expected `string`.'
174
+ '`testComponent`, expected `string`.',
175
);
176
typeCheckFail(
177
PropTypes.string,
178
0,
179
'Invalid prop `testProp` of type `number` supplied to ' +
165
- '`testComponent`, expected `string`.'
180
+ '`testComponent`, expected `string`.',
181
);
182
typeCheckFail(
183
PropTypes.string,
184
{},
185
'Invalid prop `testProp` of type `object` supplied to ' +
171
- '`testComponent`, expected `string`.'
186
+ '`testComponent`, expected `string`.',
187
);
188
typeCheckFail(
189
PropTypes.string,
190
Symbol(),
191
'Invalid prop `testProp` of type `symbol` supplied to ' +
177
- '`testComponent`, expected `string`.'
192
+ '`testComponent`, expected `string`.',
193
);
194
});
195
@@ -183,13 +198,13 @@ describe('ReactPropTypes', () => {
198
PropTypes.string,
199
new Date(),
200
'Invalid prop `testProp` of type `date` supplied to ' +
186
- '`testComponent`, expected `string`.'
201
+ '`testComponent`, expected `string`.',
202
);
203
typeCheckFail(
204
PropTypes.string,
205
/please/,
206
'Invalid prop `testProp` of type `regexp` supplied to ' +
192
- '`testComponent`, expected `string`.'
207
+ '`testComponent`, expected `string`.',
208
);
209
});
210
@@ -289,9 +304,9 @@ describe('ReactPropTypes', () => {
304
describe('ArrayOf Type', () => {
305
it('should fail for invalid argument', () => {
306
typeCheckFail(
292
- PropTypes.arrayOf({ foo: PropTypes.string }),
293
- { foo: 'bar' },
294
- 'Property `testProp` of component `testComponent` has invalid PropType notation inside arrayOf.'
307
+ PropTypes.arrayOf({foo: PropTypes.string}),
308
+ {foo: 'bar'},
309
+ 'Property `testProp` of component `testComponent` has invalid PropType notation inside arrayOf.',
310
);
311
});
312
@@ -305,14 +320,14 @@ describe('ReactPropTypes', () => {
320
it('should support arrayOf with complex types', () => {
321
typeCheckPass(
322
PropTypes.arrayOf(PropTypes.shape({a: PropTypes.number.isRequired})),
308
- [{a: 1}, {a: 2}]
323
+ [{a: 1}, {a: 2}],
324
);
325
326
function Thing() {}
312
- typeCheckPass(
313
- PropTypes.arrayOf(PropTypes.instanceOf(Thing)),
314
- [new Thing(), new Thing()]
315
- );
327
+ typeCheckPass(PropTypes.arrayOf(PropTypes.instanceOf(Thing)), [
328
+ new Thing(),
329
+ new Thing(),
330
+ ]);
331
});
332
333
it('should warn with invalid items in the array', () => {
@@ -320,7 +335,7 @@ describe('ReactPropTypes', () => {
335
PropTypes.arrayOf(PropTypes.number),
336
[1, 2, 'b'],
337
'Invalid prop `testProp[2]` of type `string` supplied to ' +
323
- '`testComponent`, expected `number`.'
338
+ '`testComponent`, expected `number`.',
339
);
340
});
341
@@ -332,7 +347,9 @@ describe('ReactPropTypes', () => {
347
PropTypes.arrayOf(PropTypes.instanceOf(Thing)),
348
[new Thing(), 'xyz'],
349
'Invalid prop `testProp[1]` of type `String` supplied to ' +
335
- '`testComponent`, expected instance of `' + name + '`.'
350
+ '`testComponent`, expected instance of `' +
351
+ name +
352
+ '`.',
353
);
354
});
355
@@ -341,19 +358,19 @@ describe('ReactPropTypes', () => {
358
PropTypes.arrayOf(PropTypes.number),
359
{'0': 'maybe-array', length: 1},
360
'Invalid prop `testProp` of type `object` supplied to ' +
344
- '`testComponent`, expected an array.'
361
+ '`testComponent`, expected an array.',
362
);
363
typeCheckFail(
364
PropTypes.arrayOf(PropTypes.number),
365
123,
366
'Invalid prop `testProp` of type `number` supplied to ' +
350
- '`testComponent`, expected an array.'
367
+ '`testComponent`, expected an array.',
368
);
369
typeCheckFail(
370
PropTypes.arrayOf(PropTypes.number),
371
'string',
372
'Invalid prop `testProp` of type `string` supplied to ' +
356
- '`testComponent`, expected an array.'
373
+ '`testComponent`, expected an array.',
374
);
375
});
376
@@ -368,26 +385,32 @@ describe('ReactPropTypes', () => {
385
386
it('should warn for missing required values', () => {
387
typeCheckFailRequiredValues(
371
- PropTypes.arrayOf(PropTypes.number).isRequired
388
+ PropTypes.arrayOf(PropTypes.number).isRequired,
389
);
390
});
391
392
it('should warn if called manually in development', () => {
393
spyOn(console, 'error');
394
+ expectWarningInDevelopment(PropTypes.arrayOf({foo: PropTypes.string}), {
395
+ foo: 'bar',
396
+ });
397
+ expectWarningInDevelopment(PropTypes.arrayOf(PropTypes.number), [
398
+ 1,
399
+ 2,
400
+ 'b',
401
+ ]);
402
+ expectWarningInDevelopment(PropTypes.arrayOf(PropTypes.number), {
403
+ '0': 'maybe-array',
404
+ length: 1,
405
+ });
406
expectWarningInDevelopment(
378
- PropTypes.arrayOf({ foo: PropTypes.string }),
379
- { foo: 'bar' }
380
- );
381
- expectWarningInDevelopment(
382
- PropTypes.arrayOf(PropTypes.number),
383
- [1, 2, 'b']
407
+ PropTypes.arrayOf(PropTypes.number).isRequired,
408
+ null,
409
);
410
expectWarningInDevelopment(
386
- PropTypes.arrayOf(PropTypes.number),
387
- {'0': 'maybe-array', length: 1}
411
+ PropTypes.arrayOf(PropTypes.number).isRequired,
412
+ undefined,
413
);
389
- expectWarningInDevelopment(PropTypes.arrayOf(PropTypes.number).isRequired, null);
390
- expectWarningInDevelopment(PropTypes.arrayOf(PropTypes.number).isRequired, undefined);
414
});
415
});
416
@@ -413,25 +436,25 @@ describe('ReactPropTypes', () => {
436
PropTypes.element,
437
[<div />, <div />],
438
'Invalid prop `testProp` of type `array` supplied to `testComponent`, ' +
416
- 'expected a single ReactElement.'
439
+ 'expected a single ReactElement.',
440
);
441
typeCheckFail(
442
PropTypes.element,
443
123,
444
'Invalid prop `testProp` of type `number` supplied to `testComponent`, ' +
422
- 'expected a single ReactElement.'
445
+ 'expected a single ReactElement.',
446
);
447
typeCheckFail(
448
PropTypes.element,
449
'foo',
450
'Invalid prop `testProp` of type `string` supplied to `testComponent`, ' +
428
- 'expected a single ReactElement.'
451
+ 'expected a single ReactElement.',
452
);
453
typeCheckFail(
454
PropTypes.element,
455
false,
456
'Invalid prop `testProp` of type `boolean` supplied to `testComponent`, ' +
434
- 'expected a single ReactElement.'
457
+ 'expected a single ReactElement.',
458
);
459
});
460
@@ -472,7 +495,6 @@ describe('ReactPropTypes', () => {
495
expectWarningInDevelopment(PropTypes.element.isRequired, null);
496
expectWarningInDevelopment(PropTypes.element.isRequired, undefined);
497
});
475
-
498
});
499
500
describe('Instance Types', () => {
@@ -487,43 +509,57 @@ describe('ReactPropTypes', () => {
509
PropTypes.instanceOf(Person),
510
false,
511
'Invalid prop `testProp` of type `Boolean` supplied to ' +
490
- '`testComponent`, expected instance of `' + personName + '`.'
512
+ '`testComponent`, expected instance of `' +
513
+ personName +
514
+ '`.',
515
);
516
typeCheckFail(
517
PropTypes.instanceOf(Person),
518
{},
519
'Invalid prop `testProp` of type `Object` supplied to ' +
496
- '`testComponent`, expected instance of `' + personName + '`.'
520
+ '`testComponent`, expected instance of `' +
521
+ personName +
522
+ '`.',
523
);
524
typeCheckFail(
525
PropTypes.instanceOf(Person),
526
'',
527
'Invalid prop `testProp` of type `String` supplied to ' +
502
- '`testComponent`, expected instance of `' + personName + '`.'
528
+ '`testComponent`, expected instance of `' +
529
+ personName +
530
+ '`.',
531
);
532
typeCheckFail(
533
PropTypes.instanceOf(Date),
534
{},
535
'Invalid prop `testProp` of type `Object` supplied to ' +
508
- '`testComponent`, expected instance of `' + dateName + '`.'
536
+ '`testComponent`, expected instance of `' +
537
+ dateName +
538
+ '`.',
539
);
540
typeCheckFail(
541
PropTypes.instanceOf(RegExp),
542
{},
543
'Invalid prop `testProp` of type `Object` supplied to ' +
514
- '`testComponent`, expected instance of `' + regExpName + '`.'
544
+ '`testComponent`, expected instance of `' +
545
+ regExpName +
546
+ '`.',
547
);
548
typeCheckFail(
549
PropTypes.instanceOf(Person),
550
new Cat(),
551
'Invalid prop `testProp` of type `Cat` supplied to ' +
520
- '`testComponent`, expected instance of `' + personName + '`.'
552
+ '`testComponent`, expected instance of `' +
553
+ personName +
554
+ '`.',
555
);
556
typeCheckFail(
557
PropTypes.instanceOf(Person),
558
Object.create(null),
559
'Invalid prop `testProp` of type `<<anonymous>>` supplied to ' +
526
- '`testComponent`, expected instance of `' + personName + '`.'
560
+ '`testComponent`, expected instance of `' +
561
+ personName +
562
+ '`.',
563
);
564
});
565
@@ -553,9 +589,11 @@ describe('ReactPropTypes', () => {
589
expectWarningInDevelopment(PropTypes.instanceOf(Date), {});
590
expectWarningInDevelopment(PropTypes.instanceOf(Date), new Date());
591
expectWarningInDevelopment(PropTypes.instanceOf(Date).isRequired, {});
556
- expectWarningInDevelopment(PropTypes.instanceOf(Date).isRequired, new Date());
592
+ expectWarningInDevelopment(
593
+ PropTypes.instanceOf(Date).isRequired,
594
+ new Date(),
595
+ );
596
});
558
-
597
});
598
599
describe('React Component Types', () => {
@@ -594,18 +632,21 @@ describe('ReactPropTypes', () => {
632
633
// Object of renderable things
634
var frag = ReactFragment.create;
597
- typeCheckPass(PropTypes.node, frag({
598
- k0: 123,
599
- k1: 'Some string',
600
- k2: <div />,
601
- k3: frag({
602
- k30: <MyComponent />,
603
- k31: frag({k310: <a />}),
604
- k32: 'Another string',
635
+ typeCheckPass(
636
+ PropTypes.node,
637
+ frag({
638
+ k0: 123,
639
+ k1: 'Some string',
640
+ k2: <div />,
641
+ k3: frag({
642
+ k30: <MyComponent />,
643
+ k31: frag({k310: <a />}),
644
+ k32: 'Another string',
645
+ }),
646
+ k4: null,
647
+ k5: undefined,
648
}),
606
- k4: null,
607
- k5: undefined,
608
- }));
649
+ );
650
expectDev(console.error.calls.count()).toBe(0);
651
});
652
@@ -632,7 +673,10 @@ describe('ReactPropTypes', () => {
673
return {
674
next: function() {
675
var done = ++i > 2;
635
- return {value: done ? undefined : ['#' + i, <MyComponent />], done: done};
676
+ return {
677
+ value: done ? undefined : ['#' + i, <MyComponent />],
678
+ done: done,
679
+ };
680
},
681
};
682
},
@@ -663,45 +707,46 @@ describe('ReactPropTypes', () => {
707
expectWarningInDevelopment(PropTypes.node.isRequired, undefined);
708
expectWarningInDevelopment(PropTypes.node.isRequired, undefined);
709
});
666
-
710
});
711
712
describe('ObjectOf Type', () => {
713
it('should fail for invalid argument', () => {
714
typeCheckFail(
672
- PropTypes.objectOf({ foo: PropTypes.string }),
673
- { foo: 'bar' },
674
- 'Property `testProp` of component `testComponent` has invalid PropType notation inside objectOf.'
715
+ PropTypes.objectOf({foo: PropTypes.string}),
716
+ {foo: 'bar'},
717
+ 'Property `testProp` of component `testComponent` has invalid PropType notation inside objectOf.',
718
);
719
});
720
721
it('should support the objectOf propTypes', () => {
722
typeCheckPass(PropTypes.objectOf(PropTypes.number), {a: 1, b: 2, c: 3});
680
- typeCheckPass(
681
- PropTypes.objectOf(PropTypes.string),
682
- {a: 'a', b: 'b', c: 'c'}
683
- );
684
- typeCheckPass(
685
- PropTypes.objectOf(PropTypes.oneOf(['a', 'b'])),
686
- {a: 'a', b: 'b'}
687
- );
688
- typeCheckPass(
689
- PropTypes.objectOf(PropTypes.symbol),
690
- {a: Symbol(), b: Symbol(), c: Symbol()}
691
- );
723
+ typeCheckPass(PropTypes.objectOf(PropTypes.string), {
724
+ a: 'a',
725
+ b: 'b',
726
+ c: 'c',
727
+ });
728
+ typeCheckPass(PropTypes.objectOf(PropTypes.oneOf(['a', 'b'])), {
729
+ a: 'a',
730
+ b: 'b',
731
+ });
732
+ typeCheckPass(PropTypes.objectOf(PropTypes.symbol), {
733
+ a: Symbol(),
734
+ b: Symbol(),
735
+ c: Symbol(),
736
+ });
737
});
738
739
it('should support objectOf with complex types', () => {
740
typeCheckPass(
741
PropTypes.objectOf(PropTypes.shape({a: PropTypes.number.isRequired})),
697
- {a: {a: 1}, b: {a: 2}}
742
+ {a: {a: 1}, b: {a: 2}},
743
);
744
745
function Thing() {}
701
- typeCheckPass(
702
- PropTypes.objectOf(PropTypes.instanceOf(Thing)),
703
- {a: new Thing(), b: new Thing()}
704
- );
746
+ typeCheckPass(PropTypes.objectOf(PropTypes.instanceOf(Thing)), {
747
+ a: new Thing(),
748
+ b: new Thing(),
749
+ });
750
});
751
752
it('should warn with invalid items in the object', () => {
@@ -709,7 +754,7 @@ describe('ReactPropTypes', () => {
754
PropTypes.objectOf(PropTypes.number),
755
{a: 1, b: 2, c: 'b'},
756
'Invalid prop `testProp.c` of type `string` supplied to `testComponent`, ' +
712
- 'expected `number`.'
757
+ 'expected `number`.',
758
);
759
});
760
@@ -721,7 +766,9 @@ describe('ReactPropTypes', () => {
766
PropTypes.objectOf(PropTypes.instanceOf(Thing)),
767
{a: new Thing(), b: 'xyz'},
768
'Invalid prop `testProp.b` of type `String` supplied to ' +
724
- '`testComponent`, expected instance of `' + name + '`.'
769
+ '`testComponent`, expected instance of `' +
770
+ name +
771
+ '`.',
772
);
773
});
774
@@ -730,25 +777,25 @@ describe('ReactPropTypes', () => {
777
PropTypes.objectOf(PropTypes.number),
778
[1, 2],
779
'Invalid prop `testProp` of type `array` supplied to ' +
733
- '`testComponent`, expected an object.'
780
+ '`testComponent`, expected an object.',
781
);
782
typeCheckFail(
783
PropTypes.objectOf(PropTypes.number),
784
123,
785
'Invalid prop `testProp` of type `number` supplied to ' +
739
- '`testComponent`, expected an object.'
786
+ '`testComponent`, expected an object.',
787
);
788
typeCheckFail(
789
PropTypes.objectOf(PropTypes.number),
790
'string',
791
'Invalid prop `testProp` of type `string` supplied to ' +
745
- '`testComponent`, expected an object.'
792
+ '`testComponent`, expected an object.',
793
);
794
typeCheckFail(
795
PropTypes.objectOf(PropTypes.symbol),
796
Symbol(),
797
'Invalid prop `testProp` of type `symbol` supplied to ' +
751
- '`testComponent`, expected an object.'
798
+ '`testComponent`, expected an object.',
799
);
800
});
801
@@ -763,23 +810,26 @@ describe('ReactPropTypes', () => {
810
811
it('should warn for missing required values', () => {
812
typeCheckFailRequiredValues(
766
- PropTypes.objectOf(PropTypes.number).isRequired
813
+ PropTypes.objectOf(PropTypes.number).isRequired,
814
);
815
});
816
817
it('should warn if called manually in development', () => {
818
spyOn(console, 'error');
772
- expectWarningInDevelopment(
773
- PropTypes.objectOf({ foo: PropTypes.string }),
774
- { foo: 'bar' }
775
- );
819
+ expectWarningInDevelopment(PropTypes.objectOf({foo: PropTypes.string}), {
820
+ foo: 'bar',
821
+ });
822
+ expectWarningInDevelopment(PropTypes.objectOf(PropTypes.number), {
823
+ a: 1,
824
+ b: 2,
825
+ c: 'b',
826
+ });
827
+ expectWarningInDevelopment(PropTypes.objectOf(PropTypes.number), [1, 2]);
828
+ expectWarningInDevelopment(PropTypes.objectOf(PropTypes.number), null);
829
expectWarningInDevelopment(
830
PropTypes.objectOf(PropTypes.number),
778
- {a: 1, b: 2, c: 'b'}
831
+ undefined,
832
);
780
- expectWarningInDevelopment(PropTypes.objectOf(PropTypes.number), [1, 2]);
781
- expectWarningInDevelopment(PropTypes.objectOf(PropTypes.number), null);
782
- expectWarningInDevelopment(PropTypes.objectOf(PropTypes.number), undefined);
833
});
834
});
835
@@ -790,8 +840,9 @@ describe('ReactPropTypes', () => {
840
PropTypes.oneOf('red', 'blue');
841
842
expectDev(console.error).toHaveBeenCalled();
793
- expectDev(console.error.calls.argsFor(0)[0])
794
- .toContain('Invalid argument supplied to oneOf, expected an instance of array.');
843
+ expectDev(console.error.calls.argsFor(0)[0]).toContain(
844
+ 'Invalid argument supplied to oneOf, expected an instance of array.',
845
+ );
846
847
typeCheckPass(PropTypes.oneOf('red', 'blue'), 'red');
848
});
@@ -801,25 +852,25 @@ describe('ReactPropTypes', () => {
852
PropTypes.oneOf(['red', 'blue']),
853
true,
854
'Invalid prop `testProp` of value `true` supplied to ' +
804
- '`testComponent`, expected one of ["red","blue"].'
855
+ '`testComponent`, expected one of ["red","blue"].',
856
);
857
typeCheckFail(
858
PropTypes.oneOf(['red', 'blue']),
859
[],
860
'Invalid prop `testProp` of value `` supplied to `testComponent`, ' +
810
- 'expected one of ["red","blue"].'
861
+ 'expected one of ["red","blue"].',
862
);
863
typeCheckFail(
864
PropTypes.oneOf(['red', 'blue']),
865
'',
866
'Invalid prop `testProp` of value `` supplied to `testComponent`, ' +
816
- 'expected one of ["red","blue"].'
867
+ 'expected one of ["red","blue"].',
868
);
869
typeCheckFail(
870
PropTypes.oneOf([0, 'false']),
871
false,
872
'Invalid prop `testProp` of value `false` supplied to ' +
822
- '`testComponent`, expected one of [0,"false"].'
873
+ '`testComponent`, expected one of [0,"false"].',
874
);
875
});
876
@@ -853,8 +904,9 @@ describe('ReactPropTypes', () => {
904
PropTypes.oneOfType(PropTypes.string, PropTypes.number);
905
906
expectDev(console.error).toHaveBeenCalled();
856
- expectDev(console.error.calls.argsFor(0)[0])
857
- .toContain('Invalid argument supplied to oneOfType, expected an instance of array.');
907
+ expectDev(console.error.calls.argsFor(0)[0]).toContain(
908
+ 'Invalid argument supplied to oneOfType, expected an instance of array.',
909
+ );
910
911
typeCheckPass(PropTypes.oneOf(PropTypes.string, PropTypes.number), []);
912
});
@@ -863,7 +915,7 @@ describe('ReactPropTypes', () => {
915
typeCheckFail(
916
PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
917
[],
866
- 'Invalid prop `testProp` supplied to `testComponent`.'
918
+ 'Invalid prop `testProp` supplied to `testComponent`.',
919
);
920
921
var checker = PropTypes.oneOfType([
@@ -873,15 +925,12 @@ describe('ReactPropTypes', () => {
925
typeCheckFail(
926
checker,
927
{c: 1},
876
- 'Invalid prop `testProp` supplied to `testComponent`.'
928
+ 'Invalid prop `testProp` supplied to `testComponent`.',
929
);
930
});
931
932
it('should not warn if one of the types are valid', () => {
881
- var checker = PropTypes.oneOfType([
882
- PropTypes.string,
883
- PropTypes.number,
884
- ]);
933
+ var checker = PropTypes.oneOfType([PropTypes.string, PropTypes.number]);
934
typeCheckPass(checker, null);
935
typeCheckPass(checker, 'foo');
936
typeCheckPass(checker, 123);
@@ -896,16 +945,18 @@ describe('ReactPropTypes', () => {
945
946
it('should be implicitly optional and not warn without values', () => {
947
typeCheckPass(
899
- PropTypes.oneOfType([PropTypes.string, PropTypes.number]), null
948
+ PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
949
+ null,
950
);
951
typeCheckPass(
902
- PropTypes.oneOfType([PropTypes.string, PropTypes.number]), undefined
952
+ PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
953
+ undefined,
954
);
955
});
956
957
it('should warn for missing required values', () => {
958
typeCheckFailRequiredValues(
908
- PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired
959
+ PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
960
);
961
});
962
@@ -913,18 +964,17 @@ describe('ReactPropTypes', () => {
964
spyOn(console, 'error');
965
expectWarningInDevelopment(
966
PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
916
- []
967
+ [],
968
);
969
expectWarningInDevelopment(
970
PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
920
- null
971
+ null,
972
);
973
expectWarningInDevelopment(
974
PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
924
- undefined
975
+ undefined,
976
);
977
});
927
-
978
});
979
980
describe('Shape Types', () => {
@@ -933,13 +983,13 @@ describe('ReactPropTypes', () => {
983
PropTypes.shape({}),
984
'some string',
985
'Invalid prop `testProp` of type `string` supplied to ' +
936
- '`testComponent`, expected `object`.'
986
+ '`testComponent`, expected `object`.',
987
);
988
typeCheckFail(
989
PropTypes.shape({}),
990
['array'],
991
'Invalid prop `testProp` of type `array` supplied to ' +
942
- '`testComponent`, expected `object`.'
992
+ '`testComponent`, expected `object`.',
993
);
994
});
995
@@ -966,7 +1016,7 @@ describe('ReactPropTypes', () => {
1016
PropTypes.shape({key: PropTypes.number.isRequired}),
1017
{},
1018
'The prop `testProp.key` is marked as required in `testComponent`, ' +
969
- 'but its value is `undefined`.'
1019
+ 'but its value is `undefined`.',
1020
);
1021
});
1022
@@ -978,44 +1028,49 @@ describe('ReactPropTypes', () => {
1028
}),
1029
{},
1030
'The prop `testProp.key` is marked as required in `testComponent`, ' +
981
- 'but its value is `undefined`.'
1031
+ 'but its value is `undefined`.',
1032
);
1033
});
1034
1035
it('should warn for invalid key types', () => {
986
- typeCheckFail(PropTypes.shape({key: PropTypes.number}),
1036
+ typeCheckFail(
1037
+ PropTypes.shape({key: PropTypes.number}),
1038
{key: 'abc'},
1039
'Invalid prop `testProp.key` of type `string` supplied to `testComponent`, ' +
989
- 'expected `number`.'
1040
+ 'expected `number`.',
1041
);
1042
});
1043
1044
it('should be implicitly optional and not warn without values', () => {
1045
typeCheckPass(
995
- PropTypes.shape(PropTypes.shape({key: PropTypes.number})), null
1046
+ PropTypes.shape(PropTypes.shape({key: PropTypes.number})),
1047
+ null,
1048
);
1049
typeCheckPass(
998
- PropTypes.shape(PropTypes.shape({key: PropTypes.number})), undefined
1050
+ PropTypes.shape(PropTypes.shape({key: PropTypes.number})),
1051
+ undefined,
1052
);
1053
});
1054
1055
it('should warn for missing required values', () => {
1056
typeCheckFailRequiredValues(
1004
- PropTypes.shape({key: PropTypes.number}).isRequired
1057
+ PropTypes.shape({key: PropTypes.number}).isRequired,
1058
);
1059
});
1060
1061
it('should warn if called manually in development', () => {
1062
spyOn(console, 'error');
1063
expectWarningInDevelopment(PropTypes.shape({}), 'some string');
1011
- expectWarningInDevelopment(PropTypes.shape({ foo: PropTypes.number }), { foo: 42 });
1064
+ expectWarningInDevelopment(PropTypes.shape({foo: PropTypes.number}), {
1065
+ foo: 42,
1066
+ });
1067
expectWarningInDevelopment(
1068
PropTypes.shape({key: PropTypes.number}).isRequired,
1014
- null
1069
+ null,
1070
);
1071
expectWarningInDevelopment(
1072
PropTypes.shape({key: PropTypes.number}).isRequired,
1018
- undefined
1073
+ undefined,
1074
);
1075
expectWarningInDevelopment(PropTypes.element, <div />);
1076
});
@@ -1027,13 +1082,13 @@ describe('ReactPropTypes', () => {
1082
PropTypes.symbol,
1083
'hello',
1084
'Invalid prop `testProp` of type `string` supplied to ' +
1030
- '`testComponent`, expected `symbol`.'
1085
+ '`testComponent`, expected `symbol`.',
1086
);
1087
typeCheckFail(
1088
PropTypes.symbol,
1034
- function() { },
1089
+ function() {},
1090
'Invalid prop `testProp` of type `function` supplied to ' +
1036
- '`testComponent`, expected `symbol`.'
1091
+ '`testComponent`, expected `symbol`.',
1092
);
1093
typeCheckFail(
1094
PropTypes.symbol,
@@ -1041,7 +1096,7 @@ describe('ReactPropTypes', () => {
1096
'@@toStringTag': 'Katana',
1097
},
1098
'Invalid prop `testProp` of type `object` supplied to ' +
1044
- '`testComponent`, expected `symbol`.'
1099
+ '`testComponent`, expected `symbol`.',
1100
);
1101
});
1102
@@ -1090,15 +1145,15 @@ describe('ReactPropTypes', () => {
1145
expect(spy.calls.argsFor(0)[1]).toBe('num');
1146
});
1147
1093
- it('should have received the validator\'s return value', () => {
1148
+ it("should have received the validator's return value", () => {
1149
spyOn(console, 'error');
1095
- var spy = jasmine.createSpy().and.callFake(
1096
- function(props, propName, componentName) {
1150
+ var spy = jasmine
1151
+ .createSpy()
1152
+ .and.callFake(function(props, propName, componentName) {
1153
if (props[propName] !== 5) {
1154
return new Error('num must be 5!');
1155
}
1100
- }
1101
- );
1156
+ });
1157
Component = class extends React.Component {
1158
static propTypes = {num: spy};
1159
@@ -1111,33 +1166,31 @@ describe('ReactPropTypes', () => {
1166
ReactDOM.render(<Component num={6} />, container);
1167
expectDev(console.error.calls.count()).toBe(1);
1168
expect(
1114
- console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)')
1169
+ console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)'),
1170
).toBe(
1171
'Warning: Failed prop type: num must be 5!\n' +
1117
- ' in Component (at **)'
1172
+ ' in Component (at **)',
1173
);
1174
});
1175
1121
- it('should not warn if the validator returned null',
1122
- () => {
1123
- spyOn(console, 'error');
1124
- var spy = jasmine.createSpy().and.callFake(
1125
- function(props, propName, componentName) {
1126
- return null;
1127
- }
1128
- );
1129
- Component = class extends React.Component {
1130
- static propTypes = {num: spy};
1176
+ it('should not warn if the validator returned null', () => {
1177
+ spyOn(console, 'error');
1178
+ var spy = jasmine
1179
+ .createSpy()
1180
+ .and.callFake(function(props, propName, componentName) {
1181
+ return null;
1182
+ });
1183
+ Component = class extends React.Component {
1184
+ static propTypes = {num: spy};
1185
1132
- render() {
1133
- return <div />;
1134
- }
1135
- };
1186
+ render() {
1187
+ return <div />;
1188
+ }
1189
+ };
1190
1137
- var container = document.createElement('div');
1138
- ReactDOM.render(<Component num={5} />, container);
1139
- expectDev(console.error.calls.count()).toBe(0);
1140
- }
1141
- );
1191
+ var container = document.createElement('div');
1192
+ ReactDOM.render(<Component num={5} />, container);
1193
+ expectDev(console.error.calls.count()).toBe(0);
1194
+ });
1195
});
1196
});
src/isomorphic/classic/types/__tests__/ReactPropTypesProduction-test.js
+32
-33
@@ -42,15 +42,8 @@ describe('ReactPropTypesProduction', function() {
42
function expectThrowsInProduction(declaration, value) {
43
var props = {testProp: value};
44
expect(() => {
45
- declaration(
46
- props,
47
- 'testProp',
48
- 'testComponent',
49
- 'prop'
50
- );
51
- }).toThrowError(
52
- 'Minified React error #144'
53
- );
45
+ declaration(props, 'testProp', 'testComponent', 'prop');
46
+ }).toThrowError('Minified React error #144');
47
}
48
49
describe('Primitive Types', function() {
@@ -96,20 +89,26 @@ describe('ReactPropTypesProduction', function() {
89
90
describe('ArrayOf Type', function() {
91
it('should be a no-op', function() {
92
+ expectThrowsInProduction(PropTypes.arrayOf({foo: PropTypes.string}), {
93
+ foo: 'bar',
94
+ });
95
+ expectThrowsInProduction(PropTypes.arrayOf(PropTypes.number), [
96
+ 1,
97
+ 2,
98
+ 'b',
99
+ ]);
100
+ expectThrowsInProduction(PropTypes.arrayOf(PropTypes.number), {
101
+ '0': 'maybe-array',
102
+ length: 1,
103
+ });
104
expectThrowsInProduction(
100
- PropTypes.arrayOf({ foo: PropTypes.string }),
101
- { foo: 'bar' }
102
- );
103
- expectThrowsInProduction(
104
- PropTypes.arrayOf(PropTypes.number),
105
- [1, 2, 'b']
105
+ PropTypes.arrayOf(PropTypes.number).isRequired,
106
+ null,
107
);
108
expectThrowsInProduction(
108
- PropTypes.arrayOf(PropTypes.number),
109
- {'0': 'maybe-array', length: 1}
109
+ PropTypes.arrayOf(PropTypes.number).isRequired,
110
+ undefined,
111
);
111
- expectThrowsInProduction(PropTypes.arrayOf(PropTypes.number).isRequired, null);
112
- expectThrowsInProduction(PropTypes.arrayOf(PropTypes.number).isRequired, undefined);
112
});
113
});
114
@@ -141,14 +140,14 @@ describe('ReactPropTypesProduction', function() {
140
141
describe('ObjectOf Type', function() {
142
it('should be a no-op', function() {
144
- expectThrowsInProduction(
145
- PropTypes.objectOf({ foo: PropTypes.string }),
146
- { foo: 'bar' }
147
- );
148
- expectThrowsInProduction(
149
- PropTypes.objectOf(PropTypes.number),
150
- {a: 1, b: 2, c: 'b'}
151
- );
143
+ expectThrowsInProduction(PropTypes.objectOf({foo: PropTypes.string}), {
144
+ foo: 'bar',
145
+ });
146
+ expectThrowsInProduction(PropTypes.objectOf(PropTypes.number), {
147
+ a: 1,
148
+ b: 2,
149
+ c: 'b',
150
+ });
151
expectThrowsInProduction(PropTypes.objectOf(PropTypes.number), [1, 2]);
152
expectThrowsInProduction(PropTypes.objectOf(PropTypes.number), null);
153
expectThrowsInProduction(PropTypes.objectOf(PropTypes.number), undefined);
@@ -168,19 +167,19 @@ describe('ReactPropTypesProduction', function() {
167
it('should be a no-op', function() {
168
expectThrowsInProduction(
169
PropTypes.oneOfType(PropTypes.string, PropTypes.number),
171
- 'red'
170
+ 'red',
171
);
172
expectThrowsInProduction(
173
PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
175
- []
174
+ [],
175
);
176
expectThrowsInProduction(
177
PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
179
- null
178
+ null,
179
);
180
expectThrowsInProduction(
181
PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
183
- undefined
182
+ undefined,
183
);
184
});
185
});
@@ -190,11 +189,11 @@ describe('ReactPropTypesProduction', function() {
189
expectThrowsInProduction(PropTypes.shape({}), 'some string');
190
expectThrowsInProduction(
191
PropTypes.shape({key: PropTypes.number}).isRequired,
193
- null
192
+ null,
193
);
194
expectThrowsInProduction(
195
PropTypes.shape({key: PropTypes.number}).isRequired,
197
- undefined
196
+ undefined,
197
);
198
});
199
});
src/isomorphic/classic/types/checkPropTypes.js
+15
-8
@@ -43,26 +43,33 @@ function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
43
invariant(
44
typeof typeSpecs[typeSpecName] === 'function',
45
'%s: %s type `%s` is invalid; it must be a function, usually from ' +
46
- 'React.PropTypes.',
46
+ 'React.PropTypes.',
47
componentName || 'React class',
48
location,
49
- typeSpecName
49
+ typeSpecName,
50
+ );
51
+ error = typeSpecs[typeSpecName](
52
+ values,
53
+ typeSpecName,
54
+ componentName,
55
+ location,
56
+ null,
57
+ ReactPropTypesSecret,
58
);
51
- error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
59
} catch (ex) {
60
error = ex;
61
}
62
warning(
63
!error || error instanceof Error,
64
'%s: type specification of %s `%s` is invalid; the type checker ' +
58
- 'function must return `null` or an `Error` but returned a %s. ' +
59
- 'You may have forgotten to pass an argument to the type checker ' +
60
- 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +
61
- 'shape all require an argument).',
65
+ 'function must return `null` or an `Error` but returned a %s. ' +
66
+ 'You may have forgotten to pass an argument to the type checker ' +
67
+ 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +
68
+ 'shape all require an argument).',
69
componentName || 'React class',
70
location,
71
typeSpecName,
65
- typeof error
72
+ typeof error,
73
);
74
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
75
// Only monitor this failure once because there tends to be a lot of the
src/isomorphic/hooks/ReactComponentTreeHook.js
+42
-31
@@ -21,24 +21,27 @@ var invariant = require('fbjs/lib/invariant');
21
var warning = require('fbjs/lib/warning');
22
var getComponentName = require('getComponentName');
23
24
-import type { ReactElement, Source } from 'ReactElementType';
25
-import type { DebugID } from 'ReactInstanceType';
26
-import type { Fiber } from 'ReactFiber';
24
+import type {ReactElement, Source} from 'ReactElementType';
25
+import type {DebugID} from 'ReactInstanceType';
26
+import type {Fiber} from 'ReactFiber';
27
28
function isNative(fn) {
29
// Based on isNative() from Lodash
30
var funcToString = Function.prototype.toString;
31
var hasOwnProperty = Object.prototype.hasOwnProperty;
32
- var reIsNative = RegExp('^' + funcToString
33
- // Take an example native function source for comparison
34
- .call(hasOwnProperty)
35
- // Strip regex characters so we can use it for regex
36
- .replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
37
- // Remove hasOwnProperty from the template to make it generic
38
- .replace(
39
- /hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,
40
- '$1.*?'
41
- ) + '$'
32
+ var reIsNative = RegExp(
33
+ '^' +
34
+ funcToString
35
+ // Take an example native function source for comparison
36
+ .call(hasOwnProperty)
37
+ // Strip regex characters so we can use it for regex
38
+ .replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
39
+ // Remove hasOwnProperty from the template to make it generic
40
+ .replace(
41
+ /hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,
42
+ '$1.*?',
43
+ ) +
44
+ '$',
45
);
46
try {
47
var source = funcToString.call(fn);
@@ -48,7 +51,7 @@ function isNative(fn) {
51
}
52
}
53
51
-var canUseCollections = (
54
+var canUseCollections =
55
// Array.from
56
typeof Array.from === 'function' &&
57
// Map
@@ -64,8 +67,7 @@ var canUseCollections = (
67
// Set.prototype.keys
68
Set.prototype != null &&
69
typeof Set.prototype.keys === 'function' &&
67
- isNative(Set.prototype.keys)
68
-);
70
+ isNative(Set.prototype.keys);
71
72
var setItem;
73
var getItem;
@@ -101,7 +103,6 @@ if (canUseCollections) {
103
getRootIDs = function() {
104
return Array.from(rootIDSet.keys());
105
};
104
-
106
} else {
107
var itemByKey = {};
108
var rootByKey = {};
@@ -179,10 +180,14 @@ function describeID(id: DebugID): string {
180
warning(
181
element,
182
'ReactComponentTreeHook: Missing React element for debugID %s when ' +
182
- 'building stack',
183
- id
183
+ 'building stack',
184
+ id,
185
+ );
186
+ return describeComponentFrame(
187
+ name || '',
188
+ element && element._source,
189
+ ownerName || '',
190
);
185
- return describeComponentFrame(name || '', element && element._source, ownerName || '');
191
}
192
193
var ReactComponentTreeHook = {
@@ -197,19 +202,19 @@ var ReactComponentTreeHook = {
202
invariant(
203
nextChild,
204
'Expected hook events to fire for the child ' +
200
- 'before its parent includes it in onSetChildren().'
205
+ 'before its parent includes it in onSetChildren().',
206
);
207
invariant(
208
nextChild.childIDs != null ||
204
- typeof nextChild.element !== 'object' ||
205
- nextChild.element == null,
209
+ typeof nextChild.element !== 'object' ||
210
+ nextChild.element == null,
211
'Expected onSetChildren() to fire for a container child ' +
207
- 'before its parent includes it in onSetChildren().'
212
+ 'before its parent includes it in onSetChildren().',
213
);
214
invariant(
215
nextChild.isMounted,
216
'Expected onMountComponent() to fire for the child ' +
212
- 'before its parent includes it in onSetChildren().'
217
+ 'before its parent includes it in onSetChildren().',
218
);
219
if (nextChild.parentID == null) {
220
nextChild.parentID = id;
@@ -220,15 +225,19 @@ var ReactComponentTreeHook = {
225
invariant(
226
nextChild.parentID === id,
227
'Expected onBeforeMountComponent() parent and onSetChildren() to ' +
223
- 'be consistent (%s has parents %s and %s).',
228
+ 'be consistent (%s has parents %s and %s).',
229
nextChildID,
230
nextChild.parentID,
226
- id
231
+ id,
232
);
233
}
234
},
235
231
- onBeforeMountComponent(id: DebugID, element: ReactElement, parentID: DebugID): void {
236
+ onBeforeMountComponent(
237
+ id: DebugID,
238
+ element: ReactElement,
239
+ parentID: DebugID,
240
+ ): void {
241
var item = {
242
element,
243
parentID,
@@ -313,19 +322,21 @@ var ReactComponentTreeHook = {
322
info += describeComponentFrame(
323
name,
324
topElement._source,
316
- owner && getComponentName(owner)
325
+ owner && getComponentName(owner),
326
);
327
}
328
329
var currentOwner = ReactCurrentOwner.current;
330
if (currentOwner) {
331
if (typeof currentOwner.tag === 'number') {
323
- const workInProgress = ((currentOwner : any) : Fiber);
332
+ const workInProgress = ((currentOwner: any): Fiber);
333
// Safe because if current owner exists, we are reconciling,
334
// and it is guaranteed to be the work-in-progress version.
335
info += getStackAddendumByWorkInProgressFiber(workInProgress);
336
} else if (typeof currentOwner._debugID === 'number') {
328
- info += ReactComponentTreeHook.getStackAddendumByID(currentOwner._debugID);
337
+ info += ReactComponentTreeHook.getStackAddendumByID(
338
+ currentOwner._debugID,
339
+ );
340
}
341
}
342
return info;
src/isomorphic/modern/class/ReactBaseClasses.js
+6
-6
@@ -60,10 +60,10 @@ ReactComponent.prototype.isReactComponent = {};
60
ReactComponent.prototype.setState = function(partialState, callback) {
61
invariant(
62
typeof partialState === 'object' ||
63
- typeof partialState === 'function' ||
64
- partialState == null,
63
+ typeof partialState === 'function' ||
64
+ partialState == null,
65
'setState(...): takes an object of state variables to update or a ' +
66
- 'function which returns an object of state variables.'
66
+ 'function which returns an object of state variables.',
67
);
68
this.updater.enqueueSetState(this, partialState, callback, 'setState');
69
};
@@ -96,12 +96,12 @@ if (__DEV__) {
96
isMounted: [
97
'isMounted',
98
'Instead, make sure to clean up subscriptions and pending requests in ' +
99
- 'componentWillUnmount to prevent memory leaks.',
99
+ 'componentWillUnmount to prevent memory leaks.',
100
],
101
replaceState: [
102
'replaceState',
103
'Refactor your code to use setState instead (see ' +
104
- 'https://github.com/facebook/react/issues/3236).',
104
+ 'https://github.com/facebook/react/issues/3236).',
105
],
106
};
107
var defineDeprecationWarning = function(methodName, info) {
@@ -112,7 +112,7 @@ if (__DEV__) {
112
false,
113
'%s(...) is deprecated in plain JavaScript React classes. %s',
114
info[0],
115
- info[1]
115
+ info[1],
116
);
117
return undefined;
118
},
src/isomorphic/modern/class/ReactNoopUpdateQueue.js
+16
-6
@@ -19,11 +19,12 @@ function warnNoop(publicInstance, callerName) {
19
warning(
20
false,
21
'%s(...): Can only update a mounted or mounting component. ' +
22
- 'This usually means you called %s() on an unmounted component. ' +
23
- 'This is a no-op.\n\nPlease check the code for the %s component.',
22
+ 'This usually means you called %s() on an unmounted component. ' +
23
+ 'This is a no-op.\n\nPlease check the code for the %s component.',
24
callerName,
25
callerName,
26
- constructor && (constructor.displayName || constructor.name) || 'ReactClass'
26
+ (constructor && (constructor.displayName || constructor.name)) ||
27
+ 'ReactClass',
28
);
29
}
30
}
@@ -32,7 +33,6 @@ function warnNoop(publicInstance, callerName) {
33
* This is the abstract API for an update queue.
34
*/
35
var ReactNoopUpdateQueue = {
35
-
36
/**
37
* Checks whether or not this composite component is mounted.
38
* @param {ReactClass} publicInstance The instance we want to test.
@@ -76,7 +76,12 @@ var ReactNoopUpdateQueue = {
76
* @param {?string} Name of the calling function in the public API.
77
* @internal
78
*/
79
- enqueueReplaceState: function(publicInstance, completeState, callback, callerName) {
79
+ enqueueReplaceState: function(
80
+ publicInstance,
81
+ completeState,
82
+ callback,
83
+ callerName,
84
+ ) {
85
warnNoop(publicInstance, 'replaceState');
86
},
87
@@ -92,7 +97,12 @@ var ReactNoopUpdateQueue = {
97
* @param {?string} Name of the calling function in the public API.
98
* @internal
99
*/
95
- enqueueSetState: function(publicInstance, partialState, callback, callerName) {
100
+ enqueueSetState: function(
101
+ publicInstance,
102
+ partialState,
103
+ callback,
104
+ callerName,
105
+ ) {
106
warnNoop(publicInstance, 'setState');
107
},
108
};
src/isomorphic/modern/class/__tests__/ReactClassEquivalence-test.js
+12
-13
@@ -26,7 +26,6 @@ describe('ReactClassEquivalence', () => {
26
var result2 = runJest('ReactES6Class-test.js');
27
compareResults(result1, result2);
28
});
29
-
29
});
30
31
function runJest(testFile) {
@@ -36,13 +35,13 @@ function runJest(testFile) {
35
var setupFile = path.resolve(
36
'scripts',
37
'jest',
39
- 'setupSpecEquivalenceReporter.js'
38
+ 'setupSpecEquivalenceReporter.js',
39
+ );
40
+ var result = spawnSync(
41
+ jestBin,
42
+ [testFile, '--setupTestFrameworkScriptFile', setupFile],
43
+ {cwd},
44
);
41
- var result = spawnSync(jestBin, [
42
- testFile,
43
- '--setupTestFrameworkScriptFile',
44
- setupFile,
45
- ], {cwd});
45
46
if (result.error) {
47
throw result.error;
@@ -51,12 +50,12 @@ function runJest(testFile) {
50
if (result.status !== 0) {
51
throw new Error(
52
'jest process exited with: ' +
54
- result.status +
55
- '\n' +
56
- 'stdout: ' +
57
- result.stdout.toString() +
58
- 'stderr: ' +
59
- result.stderr.toString()
53
+ result.status +
54
+ '\n' +
55
+ 'stdout: ' +
56
+ result.stdout.toString() +
57
+ 'stderr: ' +
58
+ result.stderr.toString(),
59
);
60
}
61
src/isomorphic/modern/class/__tests__/ReactES6Class-test.js
+19
-34
@@ -15,7 +15,6 @@ var React;
15
var ReactDOM;
16
17
describe('ReactES6Class', () => {
18
-
18
var container;
19
var freeze = function(expectation) {
20
Object.freeze(expectation);
@@ -52,19 +51,19 @@ describe('ReactES6Class', () => {
51
}
52
53
it('preserves the name of the class for use in error messages', () => {
55
- class Foo extends React.Component { }
54
+ class Foo extends React.Component {}
55
expect(Foo.name).toBe('Foo');
56
});
57
58
it('throws if no render function is defined', () => {
59
spyOn(console, 'error');
61
- class Foo extends React.Component { }
60
+ class Foo extends React.Component {}
61
expect(() => ReactDOM.render(<Foo />, container)).toThrow();
62
63
expect(console.error.calls.count()).toBe(1);
64
expect(console.error.calls.argsFor(0)[0]).toBe(
65
'Warning: Foo(...): No `render` method found on the returned component ' +
67
- 'instance: you may have forgotten to define `render`.'
66
+ 'instance: you may have forgotten to define `render`.',
67
);
68
});
69
@@ -174,7 +173,7 @@ describe('ReactES6Class', () => {
173
}
174
}
175
expect(() => test(<Foo />, 'span', '')).toThrowError(
177
- 'Foo.state: must be set to an object or null'
176
+ 'Foo.state: must be set to an object or null',
177
);
178
});
179
});
@@ -203,10 +202,7 @@ describe('ReactES6Class', () => {
202
}
203
render() {
204
return (
206
- <Inner
207
- name={this.state.bar}
208
- onClick={this.handleClick.bind(this)}
209
- />
205
+ <Inner name={this.state.bar} onClick={this.handleClick.bind(this)} />
206
);
207
}
208
}
@@ -225,12 +221,7 @@ describe('ReactES6Class', () => {
221
this.setState({bar: 'bar'});
222
}
223
render() {
228
- return (
229
- <Inner
230
- name={this.state.bar}
231
- onClick={this.handleClick}
232
- />
233
- );
224
+ return <Inner name={this.state.bar} onClick={this.handleClick} />;
225
}
226
}
227
test(<Foo initialValue="foo" />, 'DIV', 'foo');
@@ -295,10 +286,7 @@ describe('ReactES6Class', () => {
286
}
287
}
288
test(<Foo value="foo" />, 'SPAN', 'foo');
298
- expect(lifeCycles).toEqual([
299
- 'will-mount',
300
- 'did-mount',
301
- ]);
289
+ expect(lifeCycles).toEqual(['will-mount', 'did-mount']);
290
lifeCycles = []; // reset
291
test(<Foo value="bar" />, 'SPAN', 'bar');
292
// prettier-ignore
@@ -310,9 +298,7 @@ describe('ReactES6Class', () => {
298
]);
299
lifeCycles = []; // reset
300
ReactDOM.unmountComponentAtNode(container);
313
- expect(lifeCycles).toEqual([
314
- 'will-unmount',
315
- ]);
301
+ expect(lifeCycles).toEqual(['will-unmount']);
302
});
303
304
it('warns when classic properties are defined on the instance, but does not invoke them.', () => {
@@ -342,16 +328,16 @@ describe('ReactES6Class', () => {
328
expect(getDefaultPropsWasCalled).toBe(false);
329
expect(console.error.calls.count()).toBe(4);
330
expect(console.error.calls.argsFor(0)[0]).toContain(
345
- 'getInitialState was defined on Foo, a plain JavaScript class.'
331
+ 'getInitialState was defined on Foo, a plain JavaScript class.',
332
);
333
expect(console.error.calls.argsFor(1)[0]).toContain(
348
- 'getDefaultProps was defined on Foo, a plain JavaScript class.'
334
+ 'getDefaultProps was defined on Foo, a plain JavaScript class.',
335
);
336
expect(console.error.calls.argsFor(2)[0]).toContain(
351
- 'propTypes was defined as an instance property on Foo.'
337
+ 'propTypes was defined as an instance property on Foo.',
338
);
339
expect(console.error.calls.argsFor(3)[0]).toContain(
354
- 'contextTypes was defined as an instance property on Foo.'
340
+ 'contextTypes was defined as an instance property on Foo.',
341
);
342
});
343
@@ -386,9 +372,9 @@ describe('ReactES6Class', () => {
372
expect(console.error.calls.count()).toBe(1);
373
expect(console.error.calls.argsFor(0)[0]).toBe(
374
'Warning: ' +
389
- 'NamedComponent has a method called componentShouldUpdate(). Did you ' +
390
- 'mean shouldComponentUpdate()? The name is phrased as a question ' +
391
- 'because the function is expected to return a value.'
375
+ 'NamedComponent has a method called componentShouldUpdate(). Did you ' +
376
+ 'mean shouldComponentUpdate()? The name is phrased as a question ' +
377
+ 'because the function is expected to return a value.',
378
);
379
});
380
@@ -408,8 +394,8 @@ describe('ReactES6Class', () => {
394
expect(console.error.calls.count()).toBe(1);
395
expect(console.error.calls.argsFor(0)[0]).toBe(
396
'Warning: ' +
411
- 'NamedComponent has a method called componentWillRecieveProps(). Did ' +
412
- 'you mean componentWillReceiveProps()?'
397
+ 'NamedComponent has a method called componentWillRecieveProps(). Did ' +
398
+ 'you mean componentWillReceiveProps()?',
399
);
400
});
401
@@ -420,10 +406,10 @@ describe('ReactES6Class', () => {
406
expect(() => instance.isMounted()).toThrow();
407
expect(console.error.calls.count()).toBe(2);
408
expect(console.error.calls.argsFor(0)[0]).toContain(
423
- 'replaceState(...) is deprecated in plain JavaScript React classes'
409
+ 'replaceState(...) is deprecated in plain JavaScript React classes',
410
);
411
expect(console.error.calls.argsFor(1)[0]).toContain(
426
- 'isMounted(...) is deprecated in plain JavaScript React classes'
412
+ 'isMounted(...) is deprecated in plain JavaScript React classes',
413
);
414
});
415
@@ -461,5 +447,4 @@ describe('ReactES6Class', () => {
447
var node = ReactDOM.findDOMNode(instance);
448
expect(node).toBe(container.firstChild);
449
});
464
-
450
});
src/isomorphic/modern/class/__tests__/ReactPureComponent-test.js
-1
@@ -93,5 +93,4 @@ describe('ReactPureComponent', () => {
93
ReactDOM.render(<Component />, document.createElement('div'));
94
expect(renders).toBe(1);
95
});
96
-
96
});
src/isomorphic/modern/element/__tests__/ReactJSXElement-test.js
+8
-11
@@ -80,7 +80,7 @@ describe('ReactJSXElement', () => {
80
expect(element.type).toBe(Component);
81
expect(element.key).toBe('12');
82
expect(element.ref).toBe('34');
83
- var expectation = {foo:'56'};
83
+ var expectation = {foo: '56'};
84
Object.freeze(expectation);
85
expect(element.props).toEqual(expectation);
86
});
@@ -90,7 +90,7 @@ describe('ReactJSXElement', () => {
90
expect(element.type).toBe(Component);
91
expect(element.key).toBe('12');
92
expect(element.ref).toBe(null);
93
- var expectation = {foo:'56'};
93
+ var expectation = {foo: '56'};
94
Object.freeze(expectation);
95
expect(element.props).toEqual(expectation);
96
});
@@ -124,7 +124,7 @@ describe('ReactJSXElement', () => {
124
var element2 = React.cloneElement(
125
<Component children="text" />,
126
{},
127
- undefined
127
+ undefined,
128
);
129
expect(element2.props.children).toBe(undefined);
130
});
@@ -165,7 +165,7 @@ describe('ReactJSXElement', () => {
165
expect(React.isValidElement({})).toEqual(false);
166
expect(React.isValidElement('string')).toEqual(false);
167
expect(React.isValidElement(Component)).toEqual(false);
168
- expect(React.isValidElement({ type: 'div', props: {} })).toEqual(false);
168
+ expect(React.isValidElement({type: 'div', props: {}})).toEqual(false);
169
});
170
171
it('is indistinguishable from a plain object', () => {
@@ -178,10 +178,7 @@ describe('ReactJSXElement', () => {
178
Component.defaultProps = {fruit: 'persimmon'};
179
180
var container = document.createElement('div');
181
- var instance = ReactDOM.render(
182
- <Component fruit="mango" />,
183
- container
184
- );
181
+ var instance = ReactDOM.render(<Component fruit="mango" />, container);
182
expect(instance.props.fruit).toBe('mango');
183
184
ReactDOM.render(<Component />, container);
@@ -199,9 +196,9 @@ describe('ReactJSXElement', () => {
196
var instance = ReactTestUtils.renderIntoDocument(<NormalizingComponent />);
197
expect(instance.props.prop).toBe('testKey');
198
202
- var inst2 =
203
- ReactTestUtils.renderIntoDocument(<NormalizingComponent prop={null} />);
199
+ var inst2 = ReactTestUtils.renderIntoDocument(
200
+ <NormalizingComponent prop={null} />,
201
+ );
202
expect(inst2.props.prop).toBe(null);
203
});
206
-
204
});
src/isomorphic/modern/element/__tests__/ReactJSXElementValidator-test.js
+43
-46
@@ -55,7 +55,7 @@ describe('ReactJSXElementValidator', () => {
55
56
expectDev(console.error.calls.count()).toBe(1);
57
expectDev(console.error.calls.argsFor(0)[0]).toContain(
58
- 'Each child in an array or iterator should have a unique "key" prop.'
58
+ 'Each child in an array or iterator should have a unique "key" prop.',
59
);
60
});
61
@@ -70,11 +70,7 @@ describe('ReactJSXElementValidator', () => {
70
71
class ComponentWrapper extends React.Component {
72
render() {
73
- return (
74
- <InnerComponent
75
- childSet={[<Component />, <Component />]}
76
- />
77
- );
73
+ return <InnerComponent childSet={[<Component />, <Component />]} />;
74
}
75
}
76
@@ -83,8 +79,8 @@ describe('ReactJSXElementValidator', () => {
79
expectDev(console.error.calls.count()).toBe(1);
80
expectDev(console.error.calls.argsFor(0)[0]).toContain(
81
'Each child in an array or iterator should have a unique "key" prop.' +
86
- '\n\nCheck the render method of `InnerComponent`. ' +
87
- 'It was passed a child from ComponentWrapper. '
82
+ '\n\nCheck the render method of `InnerComponent`. ' +
83
+ 'It was passed a child from ComponentWrapper. ',
84
);
85
});
86
@@ -107,14 +103,16 @@ describe('ReactJSXElementValidator', () => {
103
104
expectDev(console.error.calls.count()).toBe(1);
105
expectDev(console.error.calls.argsFor(0)[0]).toContain(
110
- 'Each child in an array or iterator should have a unique "key" prop.'
106
+ 'Each child in an array or iterator should have a unique "key" prop.',
107
);
108
});
109
110
it('does not warns for arrays of elements with keys', () => {
111
spyOn(console, 'error');
112
117
- void <Component>{[<Component key="#1" />, <Component key="#2" />]}</Component>;
113
+ void (
114
+ <Component>{[<Component key="#1" />, <Component key="#2" />]}</Component>
115
+ );
116
117
expectDev(console.error.calls.count()).toBe(0);
118
});
@@ -200,10 +198,10 @@ describe('ReactJSXElementValidator', () => {
198
ReactTestUtils.renderIntoDocument(<ParentComp />);
199
expect(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
200
'Warning: Failed prop type: ' +
203
- 'Invalid prop `color` of type `number` supplied to `MyComp`, ' +
204
- 'expected `string`.\n' +
205
- ' in MyComp (at **)\n' +
206
- ' in ParentComp (at **)'
201
+ 'Invalid prop `color` of type `number` supplied to `MyComp`, ' +
202
+ 'expected `string`.\n' +
203
+ ' in MyComp (at **)\n' +
204
+ ' in ParentComp (at **)',
205
);
206
});
207
@@ -236,11 +234,11 @@ describe('ReactJSXElementValidator', () => {
234
// If it doesn't, it means we're using information from the old element.
235
expect(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
236
'Warning: Failed prop type: ' +
239
- 'Invalid prop `color` of type `number` supplied to `MyComp`, ' +
240
- 'expected `string`.\n' +
241
- ' in MyComp (at **)\n' +
242
- ' in MiddleComp (at **)\n' +
243
- ' in ParentComp (at **)'
237
+ 'Invalid prop `color` of type `number` supplied to `MyComp`, ' +
238
+ 'expected `string`.\n' +
239
+ ' in MyComp (at **)\n' +
240
+ ' in MiddleComp (at **)\n' +
241
+ ' in ParentComp (at **)',
242
);
243
});
244
@@ -258,28 +256,28 @@ describe('ReactJSXElementValidator', () => {
256
expectDev(console.error.calls.count()).toBe(4);
257
expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
258
'Warning: React.createElement: type is invalid -- expected a string ' +
261
- '(for built-in components) or a class/function (for composite ' +
262
- 'components) but got: undefined. You likely forgot to export your ' +
263
- 'component from the file it\'s defined in.' +
264
- '\n\nCheck your code at **.'
259
+ '(for built-in components) or a class/function (for composite ' +
260
+ 'components) but got: undefined. You likely forgot to export your ' +
261
+ "component from the file it's defined in." +
262
+ '\n\nCheck your code at **.',
263
);
264
expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(1)[0])).toBe(
265
'Warning: React.createElement: type is invalid -- expected a string ' +
268
- '(for built-in components) or a class/function (for composite ' +
269
- 'components) but got: null.' +
270
- '\n\nCheck your code at **.'
266
+ '(for built-in components) or a class/function (for composite ' +
267
+ 'components) but got: null.' +
268
+ '\n\nCheck your code at **.',
269
);
270
expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(2)[0])).toBe(
271
'Warning: React.createElement: type is invalid -- expected a string ' +
274
- '(for built-in components) or a class/function (for composite ' +
275
- 'components) but got: boolean.' +
276
- '\n\nCheck your code at **.'
272
+ '(for built-in components) or a class/function (for composite ' +
273
+ 'components) but got: boolean.' +
274
+ '\n\nCheck your code at **.',
275
);
276
expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(3)[0])).toBe(
277
'Warning: React.createElement: type is invalid -- expected a string ' +
280
- '(for built-in components) or a class/function (for composite ' +
281
- 'components) but got: number.' +
282
- '\n\nCheck your code at **.'
278
+ '(for built-in components) or a class/function (for composite ' +
279
+ 'components) but got: number.' +
280
+ '\n\nCheck your code at **.',
281
);
282
void <Div />;
283
expectDev(console.error.calls.count()).toBe(4);
@@ -295,8 +293,8 @@ describe('ReactJSXElementValidator', () => {
293
expectDev(console.error.calls.count()).toBe(1);
294
expect(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
295
'Warning: Failed prop type: The prop `prop` is marked as required in ' +
298
- '`RequiredPropComponent`, but its value is `null`.\n' +
299
- ' in RequiredPropComponent (at **)'
296
+ '`RequiredPropComponent`, but its value is `null`.\n' +
297
+ ' in RequiredPropComponent (at **)',
298
);
299
});
300
@@ -308,8 +306,8 @@ describe('ReactJSXElementValidator', () => {
306
expectDev(console.error.calls.count()).toBe(1);
307
expect(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
308
'Warning: Failed prop type: The prop `prop` is marked as required in ' +
311
- '`RequiredPropComponent`, but its value is `null`.\n' +
312
- ' in RequiredPropComponent (at **)'
309
+ '`RequiredPropComponent`, but its value is `null`.\n' +
310
+ ' in RequiredPropComponent (at **)',
311
);
312
});
313
@@ -322,16 +320,16 @@ describe('ReactJSXElementValidator', () => {
320
expectDev(console.error.calls.count()).toBe(2);
321
expect(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
322
'Warning: Failed prop type: ' +
325
- 'The prop `prop` is marked as required in `RequiredPropComponent`, but ' +
326
- 'its value is `undefined`.\n' +
327
- ' in RequiredPropComponent (at **)'
323
+ 'The prop `prop` is marked as required in `RequiredPropComponent`, but ' +
324
+ 'its value is `undefined`.\n' +
325
+ ' in RequiredPropComponent (at **)',
326
);
327
328
expect(normalizeCodeLocInfo(console.error.calls.argsFor(1)[0])).toBe(
329
'Warning: Failed prop type: ' +
332
- 'Invalid prop `prop` of type `number` supplied to ' +
333
- '`RequiredPropComponent`, expected `string`.\n' +
334
- ' in RequiredPropComponent (at **)'
330
+ 'Invalid prop `prop` of type `number` supplied to ' +
331
+ '`RequiredPropComponent`, expected `string`.\n' +
332
+ ' in RequiredPropComponent (at **)',
333
);
334
335
ReactTestUtils.renderIntoDocument(<RequiredPropComponent prop="string" />);
@@ -358,7 +356,7 @@ describe('ReactJSXElementValidator', () => {
356
expectDev(console.error.calls.count()).toBe(1);
357
expectDev(console.error.calls.argsFor(0)[0]).toContain(
358
'NullPropTypeComponent: prop type `prop` is invalid; it must be a ' +
361
- 'function, usually from React.PropTypes.'
359
+ 'function, usually from React.PropTypes.',
360
);
361
});
362
@@ -376,7 +374,7 @@ describe('ReactJSXElementValidator', () => {
374
expectDev(console.error.calls.count()).toBe(1);
375
expectDev(console.error.calls.argsFor(0)[0]).toContain(
376
'NullContextTypeComponent: context type `prop` is invalid; it must ' +
379
- 'be a function, usually from React.PropTypes.'
377
+ 'be a function, usually from React.PropTypes.',
378
);
379
});
380
@@ -394,8 +392,7 @@ describe('ReactJSXElementValidator', () => {
392
expectDev(console.error.calls.count()).toBe(1);
393
expectDev(console.error.calls.argsFor(0)[0]).toContain(
394
'getDefaultProps is only used on classic React.createClass definitions.' +
397
- ' Use a static property named `defaultProps` instead.'
395
+ ' Use a static property named `defaultProps` instead.',
396
);
397
});
400
-
398
});
src/renderers/__tests__/EventPluginHub-test.js
+3
-6
@@ -25,22 +25,19 @@ describe('EventPluginHub', () => {
25
26
it('should prevent non-function listeners, at dispatch', () => {
27
var node = ReactTestUtils.renderIntoDocument(
28
- <div onClick="not a function" />
28
+ <div onClick="not a function" />,
29
);
30
expect(function() {
31
ReactTestUtils.SimulateNative.click(node);
32
}).toThrowError(
33
- 'Expected onClick listener to be a function, instead got type string'
33
+ 'Expected onClick listener to be a function, instead got type string',
34
);
35
});
36
37
it('should not prevent null listeners, at dispatch', () => {
38
- var node = ReactTestUtils.renderIntoDocument(
39
- <div onClick={null} />
40
- );
38
+ var node = ReactTestUtils.renderIntoDocument(<div onClick={null} />);
39
expect(function() {
40
ReactTestUtils.SimulateNative.click(node);
41
}).not.toThrow();
42
});
45
-
43
});
src/renderers/__tests__/ReactChildReconciler-test.js
+20
-16
@@ -60,7 +60,7 @@ describe('ReactChildReconciler', () => {
60
61
expectDev(console.error.calls.count()).toBe(1);
62
expectDev(console.error.calls.argsFor(0)[0]).toContain(
63
- 'Child keys must be unique; when two children share a key, only the first child will be used.'
63
+ 'Child keys must be unique; when two children share a key, only the first child will be used.',
64
);
65
});
66
@@ -88,14 +88,16 @@ describe('ReactChildReconciler', () => {
88
ReactTestUtils.renderIntoDocument(<GrandParent />);
89
90
expectDev(console.error.calls.count()).toBe(1);
91
- expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toContain(
91
+ expectDev(
92
+ normalizeCodeLocInfo(console.error.calls.argsFor(0)[0]),
93
+ ).toContain(
94
'Encountered two children with the same key, `1`. ' +
93
- 'Child keys must be unique; when two children share a key, ' +
94
- 'only the first child will be used.\n' +
95
- ' in div (at **)\n' +
96
- ' in Component (at **)\n' +
97
- ' in Parent (at **)\n' +
98
- ' in GrandParent (at **)'
95
+ 'Child keys must be unique; when two children share a key, ' +
96
+ 'only the first child will be used.\n' +
97
+ ' in div (at **)\n' +
98
+ ' in Component (at **)\n' +
99
+ ' in Parent (at **)\n' +
100
+ ' in GrandParent (at **)',
101
);
102
});
103
@@ -112,7 +114,7 @@ describe('ReactChildReconciler', () => {
114
115
expectDev(console.error.calls.count()).toBe(1);
116
expectDev(console.error.calls.argsFor(0)[0]).toContain(
115
- 'Child keys must be unique; when two children share a key, only the first child will be used.'
117
+ 'Child keys must be unique; when two children share a key, only the first child will be used.',
118
);
119
});
120
@@ -140,14 +142,16 @@ describe('ReactChildReconciler', () => {
142
ReactTestUtils.renderIntoDocument(<GrandParent />);
143
144
expectDev(console.error.calls.count()).toBe(1);
143
- expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toContain(
145
+ expectDev(
146
+ normalizeCodeLocInfo(console.error.calls.argsFor(0)[0]),
147
+ ).toContain(
148
'Encountered two children with the same key, `1`. ' +
145
- 'Child keys must be unique; when two children share a key, ' +
146
- 'only the first child will be used.\n' +
147
- ' in div (at **)\n' +
148
- ' in Component (at **)\n' +
149
- ' in Parent (at **)\n' +
150
- ' in GrandParent (at **)'
149
+ 'Child keys must be unique; when two children share a key, ' +
150
+ 'only the first child will be used.\n' +
151
+ ' in div (at **)\n' +
152
+ ' in Component (at **)\n' +
153
+ ' in Parent (at **)\n' +
154
+ ' in GrandParent (at **)',
155
);
156
});
157
});
src/renderers/__tests__/ReactComponent-test.js
+61
-58
@@ -29,15 +29,11 @@ describe('ReactComponent', () => {
29
// jQuery objects are basically arrays; people often pass them in by mistake
30
expect(function() {
31
ReactDOM.render(<div />, [container]);
32
- }).toThrowError(
33
- /Target container is not a DOM element./
34
- );
32
+ }).toThrowError(/Target container is not a DOM element./);
33
34
expect(function() {
35
ReactDOM.render(<div />, null);
38
- }).toThrowError(
39
- /Target container is not a DOM element./
40
- );
36
+ }).toThrowError(/Target container is not a DOM element./);
37
});
38
39
it('should throw when supplying a ref outside of render method', () => {
@@ -59,7 +55,7 @@ describe('ReactComponent', () => {
55
<span key={0} />
56
<span key={1} />
57
<span key={2} />
62
- </Wrapper>
58
+ </Wrapper>,
59
);
60
}).toThrowError(/Cannot assign to read only property.*/);
61
});
@@ -84,7 +80,7 @@ describe('ReactComponent', () => {
80
<span key={0} />
81
<span key={1} />
82
<span key={2} />
87
- </Wrapper>
83
+ </Wrapper>,
84
);
85
}).toThrowError(/Cannot assign to read only property.*/);
86
});
@@ -157,9 +153,9 @@ describe('ReactComponent', () => {
153
154
class Component extends React.Component {
155
render() {
160
- var inner = <Wrapper object={innerObj} ref={(c) => this.innerRef = c} />;
156
+ var inner = <Wrapper object={innerObj} ref={c => this.innerRef = c} />;
157
var outer = (
162
- <Wrapper object={outerObj} ref={(c) => this.outerRef = c}>
158
+ <Wrapper object={outerObj} ref={c => this.outerRef = c}>
159
{inner}
160
</Wrapper>
161
);
@@ -194,16 +190,16 @@ describe('ReactComponent', () => {
190
getInner = () => {
191
// (With old-style refs, it's impossible to get a ref to this div
192
// because Wrapper is the current owner when this function is called.)
197
- return <div className="inner" ref={(c) => this.innerRef = c} />;
193
+ return <div className="inner" ref={c => this.innerRef = c} />;
194
};
195
196
render() {
197
return (
198
<Wrapper
199
title="wrapper"
204
- ref={(c) => this.wrapperRef = c}
200
+ ref={c => this.wrapperRef = c}
201
getContent={this.getInner}
206
- />
202
+ />
203
);
204
}
205
@@ -245,12 +241,18 @@ describe('ReactComponent', () => {
241
render() {
242
return (
243
<div>
248
- <Inner id={1} ref={(c) => {
249
- log.push(`ref 1 got ${c ? `instance ${c.props.id}` : 'null'}`);
250
- }} />
251
- <Inner id={2} ref={(c) => {
252
- log.push(`ref 2 got ${c ? `instance ${c.props.id}` : 'null'}`);
253
- }} />
244
+ <Inner
245
+ id={1}
246
+ ref={c => {
247
+ log.push(`ref 1 got ${c ? `instance ${c.props.id}` : 'null'}`);
248
+ }}
249
+ />
250
+ <Inner
251
+ id={2}
252
+ ref={c => {
253
+ log.push(`ref 2 got ${c ? `instance ${c.props.id}` : 'null'}`);
254
+ }}
255
+ />
256
</div>
257
);
258
}
@@ -280,39 +282,41 @@ describe('ReactComponent', () => {
282
/* eslint-disable indent */
283
expect(log).toEqual([
284
'start mount',
283
- 'inner 1 render',
284
- 'inner 2 render',
285
- 'inner 1 componentDidMount',
286
- 'ref 1 got instance 1',
287
- 'inner 2 componentDidMount',
288
- 'ref 2 got instance 2',
289
- 'outer componentDidMount',
285
+ 'inner 1 render',
286
+ 'inner 2 render',
287
+ 'inner 1 componentDidMount',
288
+ 'ref 1 got instance 1',
289
+ 'inner 2 componentDidMount',
290
+ 'ref 2 got instance 2',
291
+ 'outer componentDidMount',
292
'start update',
291
- // Previous (equivalent) refs get cleared
292
- ...(ReactDOMFeatureFlags.useFiber ? [
293
- // Fiber renders first, resets refs later
294
- 'inner 1 render',
295
- 'inner 2 render',
296
- 'ref 1 got null',
297
- 'ref 2 got null',
298
- ] : [
299
- // Stack resets refs before rendering
300
- 'ref 1 got null',
301
- 'inner 1 render',
302
- 'ref 2 got null',
303
- 'inner 2 render',
304
- ]),
305
- 'inner 1 componentDidUpdate',
306
- 'ref 1 got instance 1',
307
- 'inner 2 componentDidUpdate',
308
- 'ref 2 got instance 2',
309
- 'outer componentDidUpdate',
293
+ // Previous (equivalent) refs get cleared
294
+ ...(ReactDOMFeatureFlags.useFiber
295
+ ? [
296
+ // Fiber renders first, resets refs later
297
+ 'inner 1 render',
298
+ 'inner 2 render',
299
+ 'ref 1 got null',
300
+ 'ref 2 got null',
301
+ ]
302
+ : [
303
+ // Stack resets refs before rendering
304
+ 'ref 1 got null',
305
+ 'inner 1 render',
306
+ 'ref 2 got null',
307
+ 'inner 2 render',
308
+ ]),
309
+ 'inner 1 componentDidUpdate',
310
+ 'ref 1 got instance 1',
311
+ 'inner 2 componentDidUpdate',
312
+ 'ref 2 got instance 2',
313
+ 'outer componentDidUpdate',
314
'start unmount',
311
- 'outer componentWillUnmount',
312
- 'ref 1 got null',
313
- 'inner 1 componentWillUnmount',
314
- 'ref 2 got null',
315
- 'inner 2 componentWillUnmount',
315
+ 'outer componentWillUnmount',
316
+ 'ref 1 got null',
317
+ 'inner 1 componentWillUnmount',
318
+ 'ref 2 got null',
319
+ 'inner 2 componentWillUnmount',
320
]);
321
/* eslint-enable indent */
322
});
@@ -334,15 +338,15 @@ describe('ReactComponent', () => {
338
var X = undefined;
339
expect(() => ReactTestUtils.renderIntoDocument(<X />)).toThrowError(
340
'Element type is invalid: expected a string (for built-in components) ' +
337
- 'or a class/function (for composite components) but got: undefined. ' +
338
- 'You likely forgot to export your component from the file it\'s ' +
339
- 'defined in.'
341
+ 'or a class/function (for composite components) but got: undefined. ' +
342
+ "You likely forgot to export your component from the file it's " +
343
+ 'defined in.',
344
);
345
346
var Y = null;
347
expect(() => ReactTestUtils.renderIntoDocument(<Y />)).toThrowError(
348
'Element type is invalid: expected a string (for built-in components) ' +
345
- 'or a class/function (for composite components) but got: null.'
349
+ 'or a class/function (for composite components) but got: null.',
350
);
351
352
// One warning for each element creation
@@ -368,13 +372,12 @@ describe('ReactComponent', () => {
372
373
expect(() => ReactTestUtils.renderIntoDocument(<Foo />)).toThrowError(
374
'Element type is invalid: expected a string (for built-in components) ' +
371
- 'or a class/function (for composite components) but got: undefined. ' +
372
- 'You likely forgot to export your component from the file it\'s ' +
373
- 'defined in.\n\nCheck the render method of `Bar`.'
375
+ 'or a class/function (for composite components) but got: undefined. ' +
376
+ "You likely forgot to export your component from the file it's " +
377
+ 'defined in.\n\nCheck the render method of `Bar`.',
378
);
379
380
// One warning for each element creation
381
expectDev(console.error.calls.count()).toBe(1);
382
});
379
-
383
});
src/renderers/__tests__/ReactComponentLifeCycle-test.js
+52
-80
@@ -19,7 +19,6 @@ var clone = function(o) {
19
return JSON.parse(JSON.stringify(o));
20
};
21
22
-
22
var GET_INIT_STATE_RETURN_VAL = {
23
hasWillMountCompleted: false,
24
hasRenderCompleted: false,
@@ -70,16 +69,14 @@ type ComponentLifeCycle =
69
* Mounted components have a DOM node representation and are capable of
70
* receiving new props.
71
*/
73
- 'MOUNTED' |
74
- /**
72
+ | 'MOUNTED'
73
+ | /**
74
* Unmounted components are inactive and cannot receive new props.
75
*/
76
'UNMOUNTED';
77
78
function getLifeCycleState(instance): ComponentLifeCycle {
80
- return instance.updater.isMounted(instance) ?
81
- 'MOUNTED' :
82
- 'UNMOUNTED';
79
+ return instance.updater.isMounted(instance) ? 'MOUNTED' : 'UNMOUNTED';
80
}
81
82
/**
@@ -104,9 +101,7 @@ describe('ReactComponentLifeCycle', () => {
101
state = {};
102
103
render() {
107
- return (
108
- <div />
109
- );
104
+ return <div />;
105
}
106
}
107
@@ -152,11 +147,9 @@ describe('ReactComponentLifeCycle', () => {
147
148
render() {
149
return (
155
- <div>{
156
- this.state.showHasOnDOMReadyComponent ?
157
- <Child /> :
158
- <div />
159
- }</div>
150
+ <div>
151
+ {this.state.showHasOnDOMReadyComponent ? <Child /> : <div />}
152
+ </div>
153
);
154
}
155
}
@@ -178,9 +171,7 @@ describe('ReactComponentLifeCycle', () => {
171
}
172
173
render() {
181
- return (
182
- <div />
183
- );
174
+ return <div />;
175
}
176
}
177
@@ -197,9 +188,7 @@ describe('ReactComponentLifeCycle', () => {
188
}
189
190
render() {
200
- return (
201
- <div />
202
- );
191
+ return <div />;
192
}
193
}
194
@@ -221,9 +210,7 @@ describe('ReactComponentLifeCycle', () => {
210
}
211
212
render() {
224
- return (
225
- <div />
226
- );
213
+ return <div />;
214
}
215
}
216
@@ -231,9 +218,9 @@ describe('ReactComponentLifeCycle', () => {
218
expectDev(console.error.calls.count()).toBe(1);
219
expectDev(console.error.calls.argsFor(0)[0]).toBe(
220
'Warning: setState(...): Can only update a mounted or ' +
234
- 'mounting component. This usually means you called setState() on an ' +
235
- 'unmounted component. This is a no-op.\n\nPlease check the code for the ' +
236
- 'StatefulComponent component.'
221
+ 'mounting component. This usually means you called setState() on an ' +
222
+ 'unmounted component. This is a no-op.\n\nPlease check the code for the ' +
223
+ 'StatefulComponent component.',
224
);
225
});
226
@@ -259,7 +246,7 @@ describe('ReactComponentLifeCycle', () => {
246
247
expectDev(console.error.calls.count()).toBe(1);
248
expectDev(console.error.calls.argsFor(0)[0]).toContain(
262
- 'Component is accessing isMounted inside its render()'
249
+ 'Component is accessing isMounted inside its render()',
250
);
251
});
252
@@ -285,7 +272,7 @@ describe('ReactComponentLifeCycle', () => {
272
273
expectDev(console.error.calls.count()).toBe(1);
274
expectDev(console.error.calls.argsFor(0)[0]).toContain(
288
- 'Component is accessing isMounted inside its render()'
275
+ 'Component is accessing isMounted inside its render()',
276
);
277
});
278
@@ -326,14 +313,13 @@ describe('ReactComponentLifeCycle', () => {
313
ReactTestUtils.renderIntoDocument(<Component />);
314
expectDev(console.error.calls.count()).toBe(1);
315
expectDev(console.error.calls.argsFor(0)[0]).toContain(
329
- 'Component is accessing findDOMNode inside its render()'
316
+ 'Component is accessing findDOMNode inside its render()',
317
);
318
});
319
320
it('should carry through each of the phases of setup', () => {
321
spyOn(console, 'error');
322
336
-
323
class LifeCycleComponent extends React.Component {
324
constructor(props, context) {
325
super(props, context);
@@ -345,22 +331,21 @@ describe('ReactComponentLifeCycle', () => {
331
hasWillUnmountCompleted: false,
332
};
333
this._testJournal.returnedFromGetInitialState = clone(initState);
348
- this._testJournal.lifeCycleAtStartOfGetInitialState =
349
- getLifeCycleState(this);
334
+ this._testJournal.lifeCycleAtStartOfGetInitialState = getLifeCycleState(
335
+ this,
336
+ );
337
this.state = initState;
338
}
339
340
componentWillMount() {
341
this._testJournal.stateAtStartOfWillMount = clone(this.state);
355
- this._testJournal.lifeCycleAtStartOfWillMount =
356
- getLifeCycleState(this);
342
+ this._testJournal.lifeCycleAtStartOfWillMount = getLifeCycleState(this);
343
this.state.hasWillMountCompleted = true;
344
}
345
346
componentDidMount() {
347
this._testJournal.stateAtStartOfDidMount = clone(this.state);
362
- this._testJournal.lifeCycleAtStartOfDidMount =
363
- getLifeCycleState(this);
348
+ this._testJournal.lifeCycleAtStartOfDidMount = getLifeCycleState(this);
349
this.setState({hasDidMountCompleted: true});
350
}
351
@@ -384,8 +369,9 @@ describe('ReactComponentLifeCycle', () => {
369
370
componentWillUnmount() {
371
this._testJournal.stateAtStartOfWillUnmount = clone(this.state);
387
- this._testJournal.lifeCycleAtStartOfWillUnmount =
388
- getLifeCycleState(this);
372
+ this._testJournal.lifeCycleAtStartOfWillUnmount = getLifeCycleState(
373
+ this,
374
+ );
375
this.state.hasWillUnmountCompleted = true;
376
}
377
}
@@ -398,31 +384,29 @@ describe('ReactComponentLifeCycle', () => {
384
385
// getInitialState
386
expect(instance._testJournal.returnedFromGetInitialState).toEqual(
401
- GET_INIT_STATE_RETURN_VAL
387
+ GET_INIT_STATE_RETURN_VAL,
388
+ );
389
+ expect(instance._testJournal.lifeCycleAtStartOfGetInitialState).toBe(
390
+ 'UNMOUNTED',
391
);
403
- expect(instance._testJournal.lifeCycleAtStartOfGetInitialState)
404
- .toBe('UNMOUNTED');
392
393
// componentWillMount
394
expect(instance._testJournal.stateAtStartOfWillMount).toEqual(
408
- instance._testJournal.returnedFromGetInitialState
395
+ instance._testJournal.returnedFromGetInitialState,
396
);
410
- expect(instance._testJournal.lifeCycleAtStartOfWillMount)
411
- .toBe('UNMOUNTED');
397
+ expect(instance._testJournal.lifeCycleAtStartOfWillMount).toBe('UNMOUNTED');
398
399
// componentDidMount
414
- expect(instance._testJournal.stateAtStartOfDidMount)
415
- .toEqual(DID_MOUNT_STATE);
416
- expect(instance._testJournal.lifeCycleAtStartOfDidMount).toBe(
417
- 'MOUNTED'
400
+ expect(instance._testJournal.stateAtStartOfDidMount).toEqual(
401
+ DID_MOUNT_STATE,
402
);
403
+ expect(instance._testJournal.lifeCycleAtStartOfDidMount).toBe('MOUNTED');
404
405
// initial render
421
- expect(instance._testJournal.stateInInitialRender)
422
- .toEqual(INIT_RENDER_STATE);
423
- expect(instance._testJournal.lifeCycleInInitialRender).toBe(
424
- 'UNMOUNTED'
406
+ expect(instance._testJournal.stateInInitialRender).toEqual(
407
+ INIT_RENDER_STATE,
408
);
409
+ expect(instance._testJournal.lifeCycleInInitialRender).toBe('UNMOUNTED');
410
411
expect(getLifeCycleState(instance)).toBe('MOUNTED');
412
@@ -430,22 +414,18 @@ describe('ReactComponentLifeCycle', () => {
414
instance.forceUpdate();
415
416
// render 2nd time
433
- expect(instance._testJournal.stateInLaterRender)
434
- .toEqual(NEXT_RENDER_STATE);
435
- expect(instance._testJournal.lifeCycleInLaterRender).toBe(
436
- 'MOUNTED'
437
- );
417
+ expect(instance._testJournal.stateInLaterRender).toEqual(NEXT_RENDER_STATE);
418
+ expect(instance._testJournal.lifeCycleInLaterRender).toBe('MOUNTED');
419
420
expect(getLifeCycleState(instance)).toBe('MOUNTED');
421
422
ReactDOM.unmountComponentAtNode(container);
423
443
- expect(instance._testJournal.stateAtStartOfWillUnmount)
444
- .toEqual(WILL_UNMOUNT_STATE);
445
- // componentWillUnmount called right before unmount.
446
- expect(instance._testJournal.lifeCycleAtStartOfWillUnmount).toBe(
447
- 'MOUNTED'
424
+ expect(instance._testJournal.stateAtStartOfWillUnmount).toEqual(
425
+ WILL_UNMOUNT_STATE,
426
);
427
+ // componentWillUnmount called right before unmount.
428
+ expect(instance._testJournal.lifeCycleAtStartOfWillUnmount).toBe('MOUNTED');
429
430
// But the current lifecycle of the component is unmounted.
431
expect(getLifeCycleState(instance)).toBe('UNMOUNTED');
@@ -453,7 +433,7 @@ describe('ReactComponentLifeCycle', () => {
433
434
expectDev(console.error.calls.count()).toBe(1);
435
expectDev(console.error.calls.argsFor(0)[0]).toContain(
456
- 'LifeCycleComponent is accessing isMounted inside its render() function'
436
+ 'LifeCycleComponent is accessing isMounted inside its render() function',
437
);
438
});
439
@@ -482,9 +462,7 @@ describe('ReactComponentLifeCycle', () => {
462
class Component extends React.Component {
463
render() {
464
return (
485
- <Tooltip
486
- ref="tooltip"
487
- tooltip={<div>{this.props.tooltipText}</div>}>
465
+ <Tooltip ref="tooltip" tooltip={<div>{this.props.tooltipText}</div>}>
466
{this.props.text}
467
</Tooltip>
468
);
@@ -492,17 +470,11 @@ describe('ReactComponentLifeCycle', () => {
470
}
471
472
var container = document.createElement('div');
495
- ReactDOM.render(
496
- <Component text="uno" tooltipText="one" />,
497
- container
498
- );
473
+ ReactDOM.render(<Component text="uno" tooltipText="one" />, container);
474
475
// Since `instance` is a root component, we can set its props. This also
476
// makes Tooltip rerender the tooltip component, which shouldn't throw.
502
- ReactDOM.render(
503
- <Component text="dos" tooltipText="two" />,
504
- container
505
- );
477
+ ReactDOM.render(<Component text="dos" tooltipText="two" />, container);
478
});
479
480
it('should allow state updates in componentDidMount', () => {
@@ -519,15 +491,16 @@ describe('ReactComponentLifeCycle', () => {
491
}
492
493
render() {
522
- return (<div />);
494
+ return <div />;
495
}
496
}
497
526
- var instance =
498
+ var instance = (
499
<SetStateInComponentDidMount
500
valueToUseInitially="hello"
501
valueToUseInOnDOMReady="goodbye"
530
- />;
502
+ />
503
+ );
504
instance = ReactTestUtils.renderIntoDocument(instance);
505
expect(instance.state.stateField).toBe('goodbye');
506
});
@@ -566,7 +539,6 @@ describe('ReactComponentLifeCycle', () => {
539
componentWillUnmount: logger('inner componentWillUnmount'),
540
});
541
569
-
542
var container = document.createElement('div');
543
log = [];
544
ReactDOM.render(<Outer x={17} />, container);
@@ -634,8 +606,8 @@ describe('ReactComponentLifeCycle', () => {
606
};
607
608
const div = document.createElement('div');
637
- ReactDOM.render(<Parent ref={(c) => c && log.push('ref')} />, div);
638
- ReactDOM.render(<Parent ref={(c) => c && log.push('ref')} />, div);
609
+ ReactDOM.render(<Parent ref={c => c && log.push('ref')} />, div);
610
+ ReactDOM.render(<Parent ref={c => c && log.push('ref')} />, div);
611
612
expect(log).toEqual([
613
'will mount',
src/renderers/__tests__/ReactComponentTreeHook-test.js
+767
-530
@@ -44,20 +44,12 @@ describe('ReactComponentTreeHook', () => {
44
var Anon = React.createClass({displayName: null, render: () => null});
45
var Orange = React.createClass({render: () => null});
46
47
- expectDev(getAddendum()).toBe(
48
- ''
49
- );
50
- expectDev(getAddendum(<div />)).toBe(
51
- '\n in div (at **)'
52
- );
53
- expectDev(getAddendum(<Anon />)).toBe(
54
- '\n in Unknown (at **)'
55
- );
56
- expectDev(getAddendum(<Orange />)).toBe(
57
- '\n in Orange (at **)'
58
- );
47
+ expectDev(getAddendum()).toBe('');
48
+ expectDev(getAddendum(<div />)).toBe('\n in div (at **)');
49
+ expectDev(getAddendum(<Anon />)).toBe('\n in Unknown (at **)');
50
+ expectDev(getAddendum(<Orange />)).toBe('\n in Orange (at **)');
51
expectDev(getAddendum(React.createElement(Orange))).toBe(
60
- '\n in Orange'
52
+ '\n in Orange',
53
);
54
55
var renders = 0;
@@ -78,23 +70,23 @@ describe('ReactComponentTreeHook', () => {
70
render() {
71
expectDev(getAddendum()).toBe(
72
'\n in S (at **)' +
81
- '\n in div (at **)' +
82
- '\n in R (created by Q)' +
83
- '\n in Q (at **)'
73
+ '\n in div (at **)' +
74
+ '\n in R (created by Q)' +
75
+ '\n in Q (at **)',
76
);
77
expectDev(getAddendum(<span />)).toBe(
78
'\n in span (at **)' +
87
- '\n in S (at **)' +
88
- '\n in div (at **)' +
89
- '\n in R (created by Q)' +
90
- '\n in Q (at **)'
79
+ '\n in S (at **)' +
80
+ '\n in div (at **)' +
81
+ '\n in R (created by Q)' +
82
+ '\n in Q (at **)',
83
);
84
expectDev(getAddendum(React.createElement('span'))).toBe(
85
'\n in span (created by S)' +
94
- '\n in S (at **)' +
95
- '\n in div (at **)' +
96
- '\n in R (created by Q)' +
97
- '\n in Q (at **)'
86
+ '\n in S (at **)' +
87
+ '\n in div (at **)' +
88
+ '\n in R (created by Q)' +
89
+ '\n in Q (at **)',
90
);
91
renders++;
92
return null;
@@ -104,9 +96,7 @@ describe('ReactComponentTreeHook', () => {
96
expectDev(renders).toBe(2);
97
98
// Make sure owner is fetched for the top element too.
107
- expectDev(getAddendum(rOwnedByQ)).toBe(
108
- '\n in R (created by Q)'
109
- );
99
+ expectDev(getAddendum(rOwnedByQ)).toBe('\n in R (created by Q)');
100
});
101
102
// These are features and regression tests that only affect
@@ -126,7 +116,7 @@ describe('ReactComponentTreeHook', () => {
116
117
var q = ReactDOM.render(<Q />, document.createElement('div'));
118
expectDev(getAddendum(ReactInstanceMap.get(q)._debugID)).toBe(
129
- '\n in Q (at **)'
119
+ '\n in Q (at **)',
120
);
121
122
spyOn(console, 'error');
@@ -134,7 +124,7 @@ describe('ReactComponentTreeHook', () => {
124
expectDev(console.error.calls.count()).toBe(1);
125
expectDev(console.error.calls.argsFor(0)[0]).toBe(
126
'Warning: ReactComponentTreeHook: Missing React element for ' +
137
- 'debugID -17 when building stack'
127
+ 'debugID -17 when building stack',
128
);
129
});
130
@@ -278,16 +268,20 @@ describe('ReactComponentTreeHook', () => {
268
var element = <div><Foo /><Baz /><Qux /></div>;
269
var tree = {
270
displayName: 'div',
281
- children: [{
282
- displayName: 'Bar',
283
- children: [],
284
- }, {
285
- displayName: 'Baz',
286
- children: [],
287
- }, {
288
- displayName: 'Unknown',
289
- children: [],
290
- }],
271
+ children: [
272
+ {
273
+ displayName: 'Bar',
274
+ children: [],
275
+ },
276
+ {
277
+ displayName: 'Baz',
278
+ children: [],
279
+ },
280
+ {
281
+ displayName: 'Unknown',
282
+ children: [],
283
+ },
284
+ ],
285
};
286
assertTreeMatches([element, tree]);
287
});
@@ -315,17 +309,21 @@ describe('ReactComponentTreeHook', () => {
309
var tree = {
310
displayName: 'div',
311
element,
318
- children: [{
319
- displayName: 'Bar',
320
- children: [],
321
- }, {
322
- displayName: 'Baz',
323
- children: [],
324
- }, {
325
- // Note: Ideally fallback name should be consistent (e.g. "Unknown")
326
- displayName: 'ReactComponent',
327
- children: [],
328
- }],
312
+ children: [
313
+ {
314
+ displayName: 'Bar',
315
+ children: [],
316
+ },
317
+ {
318
+ displayName: 'Baz',
319
+ children: [],
320
+ },
321
+ {
322
+ // Note: Ideally fallback name should be consistent (e.g. "Unknown")
323
+ displayName: 'ReactComponent',
324
+ children: [],
325
+ },
326
+ ],
327
};
328
assertTreeMatches([element, tree]);
329
});
@@ -359,16 +357,20 @@ describe('ReactComponentTreeHook', () => {
357
var tree = {
358
displayName: 'div',
359
element,
362
- children: [{
363
- displayName: 'Bar',
364
- children: [],
365
- }, {
366
- displayName: 'Baz',
367
- children: [],
368
- }, {
369
- displayName: 'Unknown',
370
- children: [],
371
- }],
360
+ children: [
361
+ {
362
+ displayName: 'Bar',
363
+ children: [],
364
+ },
365
+ {
366
+ displayName: 'Baz',
367
+ children: [],
368
+ },
369
+ {
370
+ displayName: 'Unknown',
371
+ children: [],
372
+ },
373
+ ],
374
};
375
assertTreeMatches([element, tree]);
376
});
@@ -390,16 +392,20 @@ describe('ReactComponentTreeHook', () => {
392
var tree = {
393
displayName: 'div',
394
element,
393
- children: [{
394
- displayName: 'Bar',
395
- children: [],
396
- }, {
397
- displayName: 'Baz',
398
- children: [],
399
- }, {
400
- displayName: 'Unknown',
401
- children: [],
402
- }],
395
+ children: [
396
+ {
397
+ displayName: 'Bar',
398
+ children: [],
399
+ },
400
+ {
401
+ displayName: 'Baz',
402
+ children: [],
403
+ },
404
+ {
405
+ displayName: 'Unknown',
406
+ children: [],
407
+ },
408
+ ],
409
};
410
assertTreeMatches([element, tree]);
411
});
@@ -418,23 +424,31 @@ describe('ReactComponentTreeHook', () => {
424
);
425
var tree = {
426
displayName: 'div',
421
- children: [{
422
- displayName: 'p',
423
- children: [{
424
- displayName: 'span',
425
- children: [{
426
- displayName: '#text',
427
- text: 'Hi!',
428
- }],
429
- }, {
430
- displayName: '#text',
431
- text: 'Wow.',
432
- }],
433
- }, {
434
- displayName: 'hr',
435
- element: <hr />,
436
- children: [],
437
- }],
427
+ children: [
428
+ {
429
+ displayName: 'p',
430
+ children: [
431
+ {
432
+ displayName: 'span',
433
+ children: [
434
+ {
435
+ displayName: '#text',
436
+ text: 'Hi!',
437
+ },
438
+ ],
439
+ },
440
+ {
441
+ displayName: '#text',
442
+ text: 'Wow.',
443
+ },
444
+ ],
445
+ },
446
+ {
447
+ displayName: 'hr',
448
+ element: <hr />,
449
+ children: [],
450
+ },
451
+ ],
452
};
453
assertTreeMatches([element, tree]);
454
});
@@ -450,11 +464,13 @@ describe('ReactComponentTreeHook', () => {
464
var tree = {
465
displayName: 'Foo',
466
element,
453
- children: [{
454
- displayName: 'div',
455
- element: <div />,
456
- children: [],
457
- }],
467
+ children: [
468
+ {
469
+ displayName: 'div',
470
+ element: <div />,
471
+ children: [],
472
+ },
473
+ ],
474
};
475
assertTreeMatches([element, tree]);
476
});
@@ -495,42 +511,59 @@ describe('ReactComponentTreeHook', () => {
511
var tree = {
512
displayName: 'Baz',
513
element,
498
- children: [{
499
- displayName: 'div',
500
- children: [{
501
- displayName: 'Foo',
502
- element: <Foo />,
503
- children: [{
504
- displayName: 'Qux',
505
- element: <Qux />,
506
- children: [],
507
- }],
508
- }, {
509
- displayName: 'Bar',
510
- children: [{
511
- displayName: 'h1',
512
- children: [{
513
- displayName: 'span',
514
- children: [{
515
- displayName: '#text',
516
- element: 'Hi,',
517
- text: 'Hi,',
518
- }],
519
- }, {
520
- displayName: '#text',
521
- text: 'Mom',
522
- element: 'Mom',
523
- }],
524
- }],
525
- }, {
526
- displayName: 'a',
527
- children: [{
528
- displayName: '#text',
529
- text: 'Click me.',
530
- element: 'Click me.',
531
- }],
532
- }],
533
- }],
514
+ children: [
515
+ {
516
+ displayName: 'div',
517
+ children: [
518
+ {
519
+ displayName: 'Foo',
520
+ element: <Foo />,
521
+ children: [
522
+ {
523
+ displayName: 'Qux',
524
+ element: <Qux />,
525
+ children: [],
526
+ },
527
+ ],
528
+ },
529
+ {
530
+ displayName: 'Bar',
531
+ children: [
532
+ {
533
+ displayName: 'h1',
534
+ children: [
535
+ {
536
+ displayName: 'span',
537
+ children: [
538
+ {
539
+ displayName: '#text',
540
+ element: 'Hi,',
541
+ text: 'Hi,',
542
+ },
543
+ ],
544
+ },
545
+ {
546
+ displayName: '#text',
547
+ text: 'Mom',
548
+ element: 'Mom',
549
+ },
550
+ ],
551
+ },
552
+ ],
553
+ },
554
+ {
555
+ displayName: 'a',
556
+ children: [
557
+ {
558
+ displayName: '#text',
559
+ text: 'Click me.',
560
+ element: 'Click me.',
561
+ },
562
+ ],
563
+ },
564
+ ],
565
+ },
566
+ ],
567
};
568
assertTreeMatches([element, tree]);
569
});
@@ -568,13 +601,16 @@ describe('ReactComponentTreeHook', () => {
601
var tree = {
602
displayName: 'div',
603
element,
571
- children: [{
572
- displayName: '#text',
573
- text: '1',
574
- }, {
575
- displayName: '#text',
576
- text: '2',
577
- }],
604
+ children: [
605
+ {
606
+ displayName: '#text',
607
+ text: '1',
608
+ },
609
+ {
610
+ displayName: '#text',
611
+ text: '2',
612
+ },
613
+ ],
614
};
615
assertTreeMatches([element, tree]);
616
});
@@ -584,10 +620,12 @@ describe('ReactComponentTreeHook', () => {
620
var tree = {
621
displayName: 'div',
622
element,
587
- children: [{
588
- displayName: '#text',
589
- text: '1',
590
- }],
623
+ children: [
624
+ {
625
+ displayName: '#text',
626
+ text: '1',
627
+ },
628
+ ],
629
};
630
assertTreeMatches([element, tree]);
631
});
@@ -597,10 +635,12 @@ describe('ReactComponentTreeHook', () => {
635
var tree = {
636
displayName: 'div',
637
element,
600
- children: [{
601
- displayName: '#text',
602
- text: '42',
603
- }],
638
+ children: [
639
+ {
640
+ displayName: '#text',
641
+ text: '42',
642
+ },
643
+ ],
644
};
645
assertTreeMatches([element, tree]);
646
});
@@ -610,10 +650,12 @@ describe('ReactComponentTreeHook', () => {
650
var tree = {
651
displayName: 'div',
652
element,
613
- children: [{
614
- displayName: '#text',
615
- text: '0',
616
- }],
653
+ children: [
654
+ {
655
+ displayName: '#text',
656
+ text: '0',
657
+ },
658
+ ],
659
};
660
assertTreeMatches([element, tree]);
661
});
@@ -634,23 +676,29 @@ describe('ReactComponentTreeHook', () => {
676
var tree = {
677
displayName: 'div',
678
element,
637
- children: [{
638
- displayName: '#text',
639
- text: 'hi',
640
- element: 'hi',
641
- }, {
642
- displayName: '#text',
643
- text: '42',
644
- element: 42,
645
- }, {
646
- displayName: 'Foo',
647
- element: <Foo />,
648
- children: [{
649
- displayName: 'div',
650
- element: <div />,
651
- children: [],
652
- }],
653
- }],
679
+ children: [
680
+ {
681
+ displayName: '#text',
682
+ text: 'hi',
683
+ element: 'hi',
684
+ },
685
+ {
686
+ displayName: '#text',
687
+ text: '42',
688
+ element: 42,
689
+ },
690
+ {
691
+ displayName: 'Foo',
692
+ element: <Foo />,
693
+ children: [
694
+ {
695
+ displayName: 'div',
696
+ element: <div />,
697
+ children: [],
698
+ },
699
+ ],
700
+ },
701
+ ],
702
};
703
assertTreeMatches([element, tree]);
704
});
@@ -671,19 +719,23 @@ describe('ReactComponentTreeHook', () => {
719
var elementBefore = <div>Hi.</div>;
720
var treeBefore = {
721
displayName: 'div',
674
- children: [{
675
- displayName: '#text',
676
- text: 'Hi.',
677
- }],
722
+ children: [
723
+ {
724
+ displayName: '#text',
725
+ text: 'Hi.',
726
+ },
727
+ ],
728
};
729
730
var elementAfter = <div>Bye.</div>;
731
var treeAfter = {
732
displayName: 'div',
683
- children: [{
684
- displayName: '#text',
685
- text: 'Bye.',
686
- }],
733
+ children: [
734
+ {
735
+ displayName: '#text',
736
+ text: 'Bye.',
737
+ },
738
+ ],
739
};
740
741
assertTreeMatches([
@@ -702,10 +754,12 @@ describe('ReactComponentTreeHook', () => {
754
var elementAfter = <div>Hi.</div>;
755
var treeAfter = {
756
displayName: 'div',
705
- children: [{
706
- displayName: '#text',
707
- text: 'Hi.',
708
- }],
757
+ children: [
758
+ {
759
+ displayName: '#text',
760
+ text: 'Hi.',
761
+ },
762
+ ],
763
};
764
765
assertTreeMatches([
@@ -718,10 +772,12 @@ describe('ReactComponentTreeHook', () => {
772
var elementBefore = <div>Hi.</div>;
773
var treeBefore = {
774
displayName: 'div',
721
- children: [{
722
- displayName: '#text',
723
- text: 'Hi.',
724
- }],
775
+ children: [
776
+ {
777
+ displayName: '#text',
778
+ text: 'Hi.',
779
+ },
780
+ ],
781
};
782
783
var elementAfter = <div />;
@@ -746,10 +802,12 @@ describe('ReactComponentTreeHook', () => {
802
var elementAfter = <div>Hi.</div>;
803
var treeAfter = {
804
displayName: 'div',
749
- children: [{
750
- displayName: '#text',
751
- text: 'Hi.',
752
- }],
805
+ children: [
806
+ {
807
+ displayName: '#text',
808
+ text: 'Hi.',
809
+ },
810
+ ],
811
};
812
813
assertTreeMatches([
@@ -762,10 +820,12 @@ describe('ReactComponentTreeHook', () => {
820
var elementBefore = <div>Hi.</div>;
821
var treeBefore = {
822
displayName: 'div',
765
- children: [{
766
- displayName: '#text',
767
- text: 'Hi.',
768
- }],
823
+ children: [
824
+ {
825
+ displayName: '#text',
826
+ text: 'Hi.',
827
+ },
828
+ ],
829
};
830
831
var elementAfter = <div dangerouslySetInnerHTML={{__html: 'Hi.'}} />;
@@ -790,13 +850,16 @@ describe('ReactComponentTreeHook', () => {
850
var elementAfter = <div>{'Hi.'}{'Bye.'}</div>;
851
var treeAfter = {
852
displayName: 'div',
793
- children: [{
794
- displayName: '#text',
795
- text: 'Hi.',
796
- }, {
797
- displayName: '#text',
798
- text: 'Bye.',
799
- }],
853
+ children: [
854
+ {
855
+ displayName: '#text',
856
+ text: 'Hi.',
857
+ },
858
+ {
859
+ displayName: '#text',
860
+ text: 'Bye.',
861
+ },
862
+ ],
863
};
864
865
assertTreeMatches([
@@ -809,13 +872,16 @@ describe('ReactComponentTreeHook', () => {
872
var elementBefore = <div>{'Hi.'}{'Bye.'}</div>;
873
var treeBefore = {
874
displayName: 'div',
812
- children: [{
813
- displayName: '#text',
814
- text: 'Hi.',
815
- }, {
816
- displayName: '#text',
817
- text: 'Bye.',
818
- }],
875
+ children: [
876
+ {
877
+ displayName: '#text',
878
+ text: 'Hi.',
879
+ },
880
+ {
881
+ displayName: '#text',
882
+ text: 'Bye.',
883
+ },
884
+ ],
885
};
886
887
var elementAfter = <div />;
@@ -840,13 +906,16 @@ describe('ReactComponentTreeHook', () => {
906
var elementAfter = <div>{'Hi.'}{'Bye.'}</div>;
907
var treeAfter = {
908
displayName: 'div',
843
- children: [{
844
- displayName: '#text',
845
- text: 'Hi.',
846
- }, {
847
- displayName: '#text',
848
- text: 'Bye.',
849
- }],
909
+ children: [
910
+ {
911
+ displayName: '#text',
912
+ text: 'Hi.',
913
+ },
914
+ {
915
+ displayName: '#text',
916
+ text: 'Bye.',
917
+ },
918
+ ],
919
};
920
921
assertTreeMatches([
@@ -859,13 +928,16 @@ describe('ReactComponentTreeHook', () => {
928
var elementBefore = <div>{'Hi.'}{'Bye.'}</div>;
929
var treeBefore = {
930
displayName: 'div',
862
- children: [{
863
- displayName: '#text',
864
- text: 'Hi.',
865
- }, {
866
- displayName: '#text',
867
- text: 'Bye.',
868
- }],
931
+ children: [
932
+ {
933
+ displayName: '#text',
934
+ text: 'Hi.',
935
+ },
936
+ {
937
+ displayName: '#text',
938
+ text: 'Bye.',
939
+ },
940
+ ],
941
};
942
943
var elementAfter = <div dangerouslySetInnerHTML={{__html: 'Hi.'}} />;
@@ -922,22 +994,27 @@ describe('ReactComponentTreeHook', () => {
994
var elementBefore = <div>Hi.</div>;
995
var treeBefore = {
996
displayName: 'div',
925
- children: [{
926
- displayName: '#text',
927
- text: 'Hi.',
928
- }],
997
+ children: [
998
+ {
999
+ displayName: '#text',
1000
+ text: 'Hi.',
1001
+ },
1002
+ ],
1003
};
1004
1005
var elementAfter = <div>{'Hi.'}{'Bye.'}</div>;
1006
var treeAfter = {
1007
displayName: 'div',
934
- children: [{
935
- displayName: '#text',
936
- text: 'Hi.',
937
- }, {
938
- displayName: '#text',
939
- text: 'Bye.',
940
- }],
1008
+ children: [
1009
+ {
1010
+ displayName: '#text',
1011
+ text: 'Hi.',
1012
+ },
1013
+ {
1014
+ displayName: '#text',
1015
+ text: 'Bye.',
1016
+ },
1017
+ ],
1018
};
1019
1020
assertTreeMatches([
@@ -950,22 +1027,27 @@ describe('ReactComponentTreeHook', () => {
1027
var elementBefore = <div>{'Hi.'}{'Bye.'}</div>;
1028
var treeBefore = {
1029
displayName: 'div',
953
- children: [{
954
- displayName: '#text',
955
- text: 'Hi.',
956
- }, {
957
- displayName: '#text',
958
- text: 'Bye.',
959
- }],
1030
+ children: [
1031
+ {
1032
+ displayName: '#text',
1033
+ text: 'Hi.',
1034
+ },
1035
+ {
1036
+ displayName: '#text',
1037
+ text: 'Bye.',
1038
+ },
1039
+ ],
1040
};
1041
1042
var elementAfter = <div>Hi.</div>;
1043
var treeAfter = {
1044
displayName: 'div',
965
- children: [{
966
- displayName: '#text',
967
- text: 'Hi.',
968
- }],
1045
+ children: [
1046
+ {
1047
+ displayName: '#text',
1048
+ text: 'Hi.',
1049
+ },
1050
+ ],
1051
};
1052
assertTreeMatches([
1053
[elementBefore, treeBefore],
@@ -977,25 +1059,31 @@ describe('ReactComponentTreeHook', () => {
1059
var elementBefore = <div>{'Hi.'}{'Bye.'}</div>;
1060
var treeBefore = {
1061
displayName: 'div',
980
- children: [{
981
- displayName: '#text',
982
- text: 'Hi.',
983
- }, {
984
- displayName: '#text',
985
- text: 'Bye.',
986
- }],
1062
+ children: [
1063
+ {
1064
+ displayName: '#text',
1065
+ text: 'Hi.',
1066
+ },
1067
+ {
1068
+ displayName: '#text',
1069
+ text: 'Bye.',
1070
+ },
1071
+ ],
1072
};
1073
1074
var elementAfter = <div>{'Bye.'}{'Hi.'}</div>;
1075
var treeAfter = {
1076
displayName: 'div',
992
- children: [{
993
- displayName: '#text',
994
- text: 'Bye.',
995
- }, {
996
- displayName: '#text',
997
- text: 'Hi.',
998
- }],
1077
+ children: [
1078
+ {
1079
+ displayName: '#text',
1080
+ text: 'Bye.',
1081
+ },
1082
+ {
1083
+ displayName: '#text',
1084
+ text: 'Hi.',
1085
+ },
1086
+ ],
1087
};
1088
assertTreeMatches([
1089
[elementBefore, treeBefore],
@@ -1012,19 +1100,26 @@ describe('ReactComponentTreeHook', () => {
1100
);
1101
var treeBefore = {
1102
displayName: 'div',
1015
- children: [{
1016
- displayName: 'div',
1017
- children: [{
1018
- displayName: '#text',
1019
- text: 'Hi.',
1020
- }],
1021
- }, {
1022
- displayName: 'div',
1023
- children: [{
1024
- displayName: '#text',
1025
- text: 'Bye.',
1026
- }],
1027
- }],
1103
+ children: [
1104
+ {
1105
+ displayName: 'div',
1106
+ children: [
1107
+ {
1108
+ displayName: '#text',
1109
+ text: 'Hi.',
1110
+ },
1111
+ ],
1112
+ },
1113
+ {
1114
+ displayName: 'div',
1115
+ children: [
1116
+ {
1117
+ displayName: '#text',
1118
+ text: 'Bye.',
1119
+ },
1120
+ ],
1121
+ },
1122
+ ],
1123
};
1124
1125
var elementAfter = (
@@ -1035,19 +1130,26 @@ describe('ReactComponentTreeHook', () => {
1130
);
1131
var treeAfter = {
1132
displayName: 'div',
1038
- children: [{
1039
- displayName: 'div',
1040
- children: [{
1041
- displayName: '#text',
1042
- text: 'Bye.',
1043
- }],
1044
- }, {
1045
- displayName: 'div',
1046
- children: [{
1047
- displayName: '#text',
1048
- text: 'Hi.',
1049
- }],
1050
- }],
1133
+ children: [
1134
+ {
1135
+ displayName: 'div',
1136
+ children: [
1137
+ {
1138
+ displayName: '#text',
1139
+ text: 'Bye.',
1140
+ },
1141
+ ],
1142
+ },
1143
+ {
1144
+ displayName: 'div',
1145
+ children: [
1146
+ {
1147
+ displayName: '#text',
1148
+ text: 'Hi.',
1149
+ },
1150
+ ],
1151
+ },
1152
+ ],
1153
};
1154
1155
assertTreeMatches([
@@ -1065,19 +1167,26 @@ describe('ReactComponentTreeHook', () => {
1167
);
1168
var treeBefore = {
1169
displayName: 'div',
1068
- children: [{
1069
- displayName: 'div',
1070
- children: [{
1071
- displayName: '#text',
1072
- text: 'Hi.',
1073
- }],
1074
- }, {
1075
- displayName: 'div',
1076
- children: [{
1077
- displayName: '#text',
1078
- text: 'Bye.',
1079
- }],
1080
- }],
1170
+ children: [
1171
+ {
1172
+ displayName: 'div',
1173
+ children: [
1174
+ {
1175
+ displayName: '#text',
1176
+ text: 'Hi.',
1177
+ },
1178
+ ],
1179
+ },
1180
+ {
1181
+ displayName: 'div',
1182
+ children: [
1183
+ {
1184
+ displayName: '#text',
1185
+ text: 'Bye.',
1186
+ },
1187
+ ],
1188
+ },
1189
+ ],
1190
};
1191
1192
var elementAfter = (
@@ -1088,19 +1197,26 @@ describe('ReactComponentTreeHook', () => {
1197
);
1198
var treeAfter = {
1199
displayName: 'div',
1091
- children: [{
1092
- displayName: 'div',
1093
- children: [{
1094
- displayName: '#text',
1095
- text: 'Bye.',
1096
- }],
1097
- }, {
1098
- displayName: 'div',
1099
- children: [{
1100
- displayName: '#text',
1101
- text: 'Hi.',
1102
- }],
1103
- }],
1200
+ children: [
1201
+ {
1202
+ displayName: 'div',
1203
+ children: [
1204
+ {
1205
+ displayName: '#text',
1206
+ text: 'Bye.',
1207
+ },
1208
+ ],
1209
+ },
1210
+ {
1211
+ displayName: 'div',
1212
+ children: [
1213
+ {
1214
+ displayName: '#text',
1215
+ text: 'Hi.',
1216
+ },
1217
+ ],
1218
+ },
1219
+ ],
1220
};
1221
1222
assertTreeMatches([
@@ -1121,19 +1237,23 @@ describe('ReactComponentTreeHook', () => {
1237
var elementBefore = <div><Foo /></div>;
1238
var treeBefore = {
1239
displayName: 'div',
1124
- children: [{
1125
- displayName: 'Foo',
1126
- children: [],
1127
- }],
1240
+ children: [
1241
+ {
1242
+ displayName: 'Foo',
1243
+ children: [],
1244
+ },
1245
+ ],
1246
};
1247
1248
var elementAfter = <div><Bar /></div>;
1249
var treeAfter = {
1250
displayName: 'div',
1133
- children: [{
1134
- displayName: 'Bar',
1135
- children: [],
1136
- }],
1251
+ children: [
1252
+ {
1253
+ displayName: 'Bar',
1254
+ children: [],
1255
+ },
1256
+ ],
1257
};
1258
1259
assertTreeMatches([
@@ -1143,32 +1263,40 @@ describe('ReactComponentTreeHook', () => {
1263
});
1264
1265
it('updates a single composite child of the same type', () => {
1146
- function Foo({ children }) {
1266
+ function Foo({children}) {
1267
return children;
1268
}
1269
1270
var elementBefore = <div><Foo><div /></Foo></div>;
1271
var treeBefore = {
1272
displayName: 'div',
1153
- children: [{
1154
- displayName: 'Foo',
1155
- children: [{
1156
- displayName: 'div',
1157
- children: [],
1158
- }],
1159
- }],
1273
+ children: [
1274
+ {
1275
+ displayName: 'Foo',
1276
+ children: [
1277
+ {
1278
+ displayName: 'div',
1279
+ children: [],
1280
+ },
1281
+ ],
1282
+ },
1283
+ ],
1284
};
1285
1286
var elementAfter = <div><Foo><span /></Foo></div>;
1287
var treeAfter = {
1288
displayName: 'div',
1165
- children: [{
1166
- displayName: 'Foo',
1167
- children: [{
1168
- displayName: 'span',
1169
- children: [],
1170
- }],
1171
- }],
1289
+ children: [
1290
+ {
1291
+ displayName: 'Foo',
1292
+ children: [
1293
+ {
1294
+ displayName: 'span',
1295
+ children: [],
1296
+ },
1297
+ ],
1298
+ },
1299
+ ],
1300
};
1301
1302
assertTreeMatches([
@@ -1191,10 +1319,12 @@ describe('ReactComponentTreeHook', () => {
1319
var elementAfter = <div><Foo /></div>;
1320
var treeAfter = {
1321
displayName: 'div',
1194
- children: [{
1195
- displayName: 'Foo',
1196
- children: [],
1197
- }],
1322
+ children: [
1323
+ {
1324
+ displayName: 'Foo',
1325
+ children: [],
1326
+ },
1327
+ ],
1328
};
1329
1330
assertTreeMatches([
@@ -1211,10 +1341,12 @@ describe('ReactComponentTreeHook', () => {
1341
var elementBefore = <div><Foo /></div>;
1342
var treeBefore = {
1343
displayName: 'div',
1214
- children: [{
1215
- displayName: 'Foo',
1216
- children: [],
1217
- }],
1344
+ children: [
1345
+ {
1346
+ displayName: 'Foo',
1347
+ children: [],
1348
+ },
1349
+ ],
1350
};
1351
1352
var elementAfter = <div />;
@@ -1244,19 +1376,25 @@ describe('ReactComponentTreeHook', () => {
1376
);
1377
var tree1 = {
1378
displayName: 'div',
1247
- children: [{
1248
- displayName: '#text',
1249
- text: 'hi',
1250
- }, {
1251
- displayName: '#text',
1252
- text: '42',
1253
- }, {
1254
- displayName: 'Foo',
1255
- children: [{
1256
- displayName: 'div',
1257
- children: [],
1258
- }],
1259
- }],
1379
+ children: [
1380
+ {
1381
+ displayName: '#text',
1382
+ text: 'hi',
1383
+ },
1384
+ {
1385
+ displayName: '#text',
1386
+ text: '42',
1387
+ },
1388
+ {
1389
+ displayName: 'Foo',
1390
+ children: [
1391
+ {
1392
+ displayName: 'div',
1393
+ children: [],
1394
+ },
1395
+ ],
1396
+ },
1397
+ ],
1398
};
1399
1400
var element2 = (
@@ -1269,16 +1407,21 @@ describe('ReactComponentTreeHook', () => {
1407
);
1408
var tree2 = {
1409
displayName: 'div',
1272
- children: [{
1273
- displayName: 'Foo',
1274
- children: [{
1275
- displayName: 'div',
1276
- children: [],
1277
- }],
1278
- }, {
1279
- displayName: '#text',
1280
- text: 'hi',
1281
- }],
1410
+ children: [
1411
+ {
1412
+ displayName: 'Foo',
1413
+ children: [
1414
+ {
1415
+ displayName: 'div',
1416
+ children: [],
1417
+ },
1418
+ ],
1419
+ },
1420
+ {
1421
+ displayName: '#text',
1422
+ text: 'hi',
1423
+ },
1424
+ ],
1425
};
1426
1427
var element3 = (
@@ -1288,13 +1431,17 @@ describe('ReactComponentTreeHook', () => {
1431
);
1432
var tree3 = {
1433
displayName: 'div',
1291
- children: [{
1292
- displayName: 'Foo',
1293
- children: [{
1294
- displayName: 'div',
1295
- children: [],
1296
- }],
1297
- }],
1434
+ children: [
1435
+ {
1436
+ displayName: 'Foo',
1437
+ children: [
1438
+ {
1439
+ displayName: 'div',
1440
+ children: [],
1441
+ },
1442
+ ],
1443
+ },
1444
+ ],
1445
};
1446
1447
assertTreeMatches([
@@ -1307,26 +1454,30 @@ describe('ReactComponentTreeHook', () => {
1454
1455
describe('functional component', () => {
1456
it('updates with a host child', () => {
1310
- function Foo({ children }) {
1457
+ function Foo({children}) {
1458
return children;
1459
}
1460
1461
var elementBefore = <Foo><div /></Foo>;
1462
var treeBefore = {
1463
displayName: 'Foo',
1317
- children: [{
1318
- displayName: 'div',
1319
- children: [],
1320
- }],
1464
+ children: [
1465
+ {
1466
+ displayName: 'div',
1467
+ children: [],
1468
+ },
1469
+ ],
1470
};
1471
1472
var elementAfter = <Foo><span /></Foo>;
1473
var treeAfter = {
1474
displayName: 'Foo',
1326
- children: [{
1327
- displayName: 'span',
1328
- children: [],
1329
- }],
1475
+ children: [
1476
+ {
1477
+ displayName: 'span',
1478
+ children: [],
1479
+ },
1480
+ ],
1481
};
1482
1483
assertTreeMatches([
@@ -1336,7 +1487,7 @@ describe('ReactComponentTreeHook', () => {
1487
});
1488
1489
it('updates from null to a host child', () => {
1339
- function Foo({ children }) {
1490
+ function Foo({children}) {
1491
return children;
1492
}
1493
@@ -1349,10 +1500,12 @@ describe('ReactComponentTreeHook', () => {
1500
var elementAfter = <Foo><div /></Foo>;
1501
var treeAfter = {
1502
displayName: 'Foo',
1352
- children: [{
1353
- displayName: 'div',
1354
- children: [],
1355
- }],
1503
+ children: [
1504
+ {
1505
+ displayName: 'div',
1506
+ children: [],
1507
+ },
1508
+ ],
1509
};
1510
1511
assertTreeMatches([
@@ -1362,17 +1515,19 @@ describe('ReactComponentTreeHook', () => {
1515
});
1516
1517
it('updates from a host child to null', () => {
1365
- function Foo({ children }) {
1518
+ function Foo({children}) {
1519
return children;
1520
}
1521
1522
var elementBefore = <Foo><div /></Foo>;
1523
var treeBefore = {
1524
displayName: 'Foo',
1372
- children: [{
1373
- displayName: 'div',
1374
- children: [],
1375
- }],
1525
+ children: [
1526
+ {
1527
+ displayName: 'div',
1528
+ children: [],
1529
+ },
1530
+ ],
1531
};
1532
1533
var elementAfter = <Foo>{null}</Foo>;
@@ -1392,26 +1547,30 @@ describe('ReactComponentTreeHook', () => {
1547
return null;
1548
}
1549
1395
- function Foo({ children }) {
1550
+ function Foo({children}) {
1551
return children;
1552
}
1553
1554
var elementBefore = <Foo><div /></Foo>;
1555
var treeBefore = {
1556
displayName: 'Foo',
1402
- children: [{
1403
- displayName: 'div',
1404
- children: [],
1405
- }],
1557
+ children: [
1558
+ {
1559
+ displayName: 'div',
1560
+ children: [],
1561
+ },
1562
+ ],
1563
};
1564
1565
var elementAfter = <Foo><Bar /></Foo>;
1566
var treeAfter = {
1567
displayName: 'Foo',
1411
- children: [{
1412
- displayName: 'Bar',
1413
- children: [],
1414
- }],
1568
+ children: [
1569
+ {
1570
+ displayName: 'Bar',
1571
+ children: [],
1572
+ },
1573
+ ],
1574
};
1575
1576
assertTreeMatches([
@@ -1425,26 +1584,30 @@ describe('ReactComponentTreeHook', () => {
1584
return null;
1585
}
1586
1428
- function Foo({ children }) {
1587
+ function Foo({children}) {
1588
return children;
1589
}
1590
1591
var elementBefore = <Foo><Bar /></Foo>;
1592
var treeBefore = {
1593
displayName: 'Foo',
1435
- children: [{
1436
- displayName: 'Bar',
1437
- children: [],
1438
- }],
1594
+ children: [
1595
+ {
1596
+ displayName: 'Bar',
1597
+ children: [],
1598
+ },
1599
+ ],
1600
};
1601
1602
var elementAfter = <Foo><div /></Foo>;
1603
var treeAfter = {
1604
displayName: 'Foo',
1444
- children: [{
1445
- displayName: 'div',
1446
- children: [],
1447
- }],
1605
+ children: [
1606
+ {
1607
+ displayName: 'div',
1608
+ children: [],
1609
+ },
1610
+ ],
1611
};
1612
1613
assertTreeMatches([
@@ -1458,7 +1621,7 @@ describe('ReactComponentTreeHook', () => {
1621
return null;
1622
}
1623
1461
- function Foo({ children }) {
1624
+ function Foo({children}) {
1625
return children;
1626
}
1627
@@ -1471,10 +1634,12 @@ describe('ReactComponentTreeHook', () => {
1634
var elementAfter = <Foo><Bar /></Foo>;
1635
var treeAfter = {
1636
displayName: 'Foo',
1474
- children: [{
1475
- displayName: 'Bar',
1476
- children: [],
1477
- }],
1637
+ children: [
1638
+ {
1639
+ displayName: 'Bar',
1640
+ children: [],
1641
+ },
1642
+ ],
1643
};
1644
1645
assertTreeMatches([
@@ -1488,17 +1653,19 @@ describe('ReactComponentTreeHook', () => {
1653
return null;
1654
}
1655
1491
- function Foo({ children }) {
1656
+ function Foo({children}) {
1657
return children;
1658
}
1659
1660
var elementBefore = <Foo><Bar /></Foo>;
1661
var treeBefore = {
1662
displayName: 'Foo',
1498
- children: [{
1499
- displayName: 'Bar',
1500
- children: [],
1501
- }],
1663
+ children: [
1664
+ {
1665
+ displayName: 'Bar',
1666
+ children: [],
1667
+ },
1668
+ ],
1669
};
1670
1671
var elementAfter = <Foo>{null}</Foo>;
@@ -1525,19 +1692,23 @@ describe('ReactComponentTreeHook', () => {
1692
var elementBefore = <Foo><div /></Foo>;
1693
var treeBefore = {
1694
displayName: 'Foo',
1528
- children: [{
1529
- displayName: 'div',
1530
- children: [],
1531
- }],
1695
+ children: [
1696
+ {
1697
+ displayName: 'div',
1698
+ children: [],
1699
+ },
1700
+ ],
1701
};
1702
1703
var elementAfter = <Foo><span /></Foo>;
1704
var treeAfter = {
1705
displayName: 'Foo',
1537
- children: [{
1538
- displayName: 'span',
1539
- children: [],
1540
- }],
1706
+ children: [
1707
+ {
1708
+ displayName: 'span',
1709
+ children: [],
1710
+ },
1711
+ ],
1712
};
1713
1714
assertTreeMatches([
@@ -1562,10 +1733,12 @@ describe('ReactComponentTreeHook', () => {
1733
var elementAfter = <Foo><div /></Foo>;
1734
var treeAfter = {
1735
displayName: 'Foo',
1565
- children: [{
1566
- displayName: 'div',
1567
- children: [],
1568
- }],
1736
+ children: [
1737
+ {
1738
+ displayName: 'div',
1739
+ children: [],
1740
+ },
1741
+ ],
1742
};
1743
1744
assertTreeMatches([
@@ -1584,10 +1757,12 @@ describe('ReactComponentTreeHook', () => {
1757
var elementBefore = <Foo><div /></Foo>;
1758
var treeBefore = {
1759
displayName: 'Foo',
1587
- children: [{
1588
- displayName: 'div',
1589
- children: [],
1590
- }],
1760
+ children: [
1761
+ {
1762
+ displayName: 'div',
1763
+ children: [],
1764
+ },
1765
+ ],
1766
};
1767
1768
var elementAfter = <Foo>{null}</Foo>;
@@ -1618,19 +1793,23 @@ describe('ReactComponentTreeHook', () => {
1793
var elementBefore = <Foo><div /></Foo>;
1794
var treeBefore = {
1795
displayName: 'Foo',
1621
- children: [{
1622
- displayName: 'div',
1623
- children: [],
1624
- }],
1796
+ children: [
1797
+ {
1798
+ displayName: 'div',
1799
+ children: [],
1800
+ },
1801
+ ],
1802
};
1803
1804
var elementAfter = <Foo><Bar /></Foo>;
1805
var treeAfter = {
1806
displayName: 'Foo',
1630
- children: [{
1631
- displayName: 'Bar',
1632
- children: [],
1633
- }],
1807
+ children: [
1808
+ {
1809
+ displayName: 'Bar',
1810
+ children: [],
1811
+ },
1812
+ ],
1813
};
1814
1815
assertTreeMatches([
@@ -1655,19 +1834,23 @@ describe('ReactComponentTreeHook', () => {
1834
var elementBefore = <Foo><Bar /></Foo>;
1835
var treeBefore = {
1836
displayName: 'Foo',
1658
- children: [{
1659
- displayName: 'Bar',
1660
- children: [],
1661
- }],
1837
+ children: [
1838
+ {
1839
+ displayName: 'Bar',
1840
+ children: [],
1841
+ },
1842
+ ],
1843
};
1844
1845
var elementAfter = <Foo><div /></Foo>;
1846
var treeAfter = {
1847
displayName: 'Foo',
1667
- children: [{
1668
- displayName: 'div',
1669
- children: [],
1670
- }],
1848
+ children: [
1849
+ {
1850
+ displayName: 'div',
1851
+ children: [],
1852
+ },
1853
+ ],
1854
};
1855
1856
assertTreeMatches([
@@ -1698,10 +1881,12 @@ describe('ReactComponentTreeHook', () => {
1881
var elementAfter = <Foo><Bar /></Foo>;
1882
var treeAfter = {
1883
displayName: 'Foo',
1701
- children: [{
1702
- displayName: 'Bar',
1703
- children: [],
1704
- }],
1884
+ children: [
1885
+ {
1886
+ displayName: 'Bar',
1887
+ children: [],
1888
+ },
1889
+ ],
1890
};
1891
1892
assertTreeMatches([
@@ -1726,10 +1911,12 @@ describe('ReactComponentTreeHook', () => {
1911
var elementBefore = <Foo><Bar /></Foo>;
1912
var treeBefore = {
1913
displayName: 'Foo',
1729
- children: [{
1730
- displayName: 'Bar',
1731
- children: [],
1732
- }],
1914
+ children: [
1915
+ {
1916
+ displayName: 'Bar',
1917
+ children: [],
1918
+ },
1919
+ ],
1920
};
1921
1922
var elementAfter = <Foo>{null}</Foo>;
@@ -1762,28 +1949,39 @@ describe('ReactComponentTreeHook', () => {
1949
var element = <article><Foo /></article>;
1950
var tree = {
1951
displayName: 'article',
1765
- children: [{
1766
- displayName: 'Foo',
1767
- children: [{
1768
- displayName: 'Bar',
1769
- ownerDisplayName: 'Foo',
1770
- children: [{
1771
- displayName: 'div',
1772
- ownerDisplayName: 'Bar',
1773
- children: [{
1774
- displayName: 'h1',
1952
+ children: [
1953
+ {
1954
+ displayName: 'Foo',
1955
+ children: [
1956
+ {
1957
+ displayName: 'Bar',
1958
ownerDisplayName: 'Foo',
1776
- children: [{
1777
- displayName: '#text',
1778
- text: 'Hi.',
1779
- }],
1780
- }, {
1781
- displayName: '#text',
1782
- text: ' Mom',
1783
- }],
1784
- }],
1785
- }],
1786
- }],
1959
+ children: [
1960
+ {
1961
+ displayName: 'div',
1962
+ ownerDisplayName: 'Bar',
1963
+ children: [
1964
+ {
1965
+ displayName: 'h1',
1966
+ ownerDisplayName: 'Foo',
1967
+ children: [
1968
+ {
1969
+ displayName: '#text',
1970
+ text: 'Hi.',
1971
+ },
1972
+ ],
1973
+ },
1974
+ {
1975
+ displayName: '#text',
1976
+ text: ' Mom',
1977
+ },
1978
+ ],
1979
+ },
1980
+ ],
1981
+ },
1982
+ ],
1983
+ },
1984
+ ],
1985
};
1986
assertTreeMatches([element, tree]);
1987
});
@@ -1809,28 +2007,40 @@ describe('ReactComponentTreeHook', () => {
2007
}
2008
2009
ReactDOM.render(<Foo />, node);
1812
- ReactComponentTreeTestUtils.expectTree(barInstance._debugID, {
1813
- displayName: 'Bar',
1814
- parentDisplayName: 'Foo',
1815
- parentID: fooInstance._debugID,
1816
- children: [],
1817
- }, 'Foo');
2010
+ ReactComponentTreeTestUtils.expectTree(
2011
+ barInstance._debugID,
2012
+ {
2013
+ displayName: 'Bar',
2014
+ parentDisplayName: 'Foo',
2015
+ parentID: fooInstance._debugID,
2016
+ children: [],
2017
+ },
2018
+ 'Foo',
2019
+ );
2020
2021
renderBar = false;
2022
ReactDOM.render(<Foo />, node);
2023
ReactDOM.render(<Foo />, node);
1822
- ReactComponentTreeTestUtils.expectTree(barInstance._debugID, {
1823
- displayName: 'Unknown',
1824
- children: [],
1825
- parentID: null,
1826
- }, 'Foo');
2024
+ ReactComponentTreeTestUtils.expectTree(
2025
+ barInstance._debugID,
2026
+ {
2027
+ displayName: 'Unknown',
2028
+ children: [],
2029
+ parentID: null,
2030
+ },
2031
+ 'Foo',
2032
+ );
2033
2034
ReactDOM.unmountComponentAtNode(node);
1829
- ReactComponentTreeTestUtils.expectTree(barInstance._debugID, {
1830
- displayName: 'Unknown',
1831
- children: [],
1832
- parentID: null,
1833
- }, 'Foo');
2035
+ ReactComponentTreeTestUtils.expectTree(
2036
+ barInstance._debugID,
2037
+ {
2038
+ displayName: 'Unknown',
2039
+ children: [],
2040
+ parentID: null,
2041
+ },
2042
+ 'Foo',
2043
+ );
2044
});
2045
2046
it('reports update counts', () => {
@@ -1862,24 +2072,34 @@ describe('ReactComponentTreeHook', () => {
2072
var node = document.createElement('div');
2073
2074
ReactDOM.render(<div className="a" />, node);
1865
- expectDev(ReactComponentTreeTestUtils.getRootDisplayNames()).toEqual(['div']);
2075
+ expectDev(ReactComponentTreeTestUtils.getRootDisplayNames()).toEqual([
2076
+ 'div',
2077
+ ]);
2078
2079
ReactDOM.render(<div className="b" />, node);
1868
- expectDev(ReactComponentTreeTestUtils.getRootDisplayNames()).toEqual(['div']);
2080
+ expectDev(ReactComponentTreeTestUtils.getRootDisplayNames()).toEqual([
2081
+ 'div',
2082
+ ]);
2083
2084
ReactDOM.unmountComponentAtNode(node);
2085
expectDev(ReactComponentTreeTestUtils.getRootDisplayNames()).toEqual([]);
1872
- expectDev(ReactComponentTreeTestUtils.getRegisteredDisplayNames()).toEqual([]);
2086
+ expectDev(
2087
+ ReactComponentTreeTestUtils.getRegisteredDisplayNames(),
2088
+ ).toEqual([]);
2089
});
2090
2091
it('registers inlined text nodes', () => {
2092
var node = document.createElement('div');
2093
2094
ReactDOM.render(<div>hi</div>, node);
1879
- expectDev(ReactComponentTreeTestUtils.getRegisteredDisplayNames()).toEqual(['div', '#text']);
2095
+ expectDev(
2096
+ ReactComponentTreeTestUtils.getRegisteredDisplayNames(),
2097
+ ).toEqual(['div', '#text']);
2098
2099
ReactDOM.unmountComponentAtNode(node);
1882
- expectDev(ReactComponentTreeTestUtils.getRegisteredDisplayNames()).toEqual([]);
2100
+ expectDev(
2101
+ ReactComponentTreeTestUtils.getRegisteredDisplayNames(),
2102
+ ).toEqual([]);
2103
});
2104
});
2105
@@ -1949,42 +2169,59 @@ describe('ReactComponentTreeHook', () => {
2169
var tree = {
2170
displayName: 'Baz',
2171
element,
1952
- children: [{
1953
- displayName: 'div',
1954
- children: [{
1955
- displayName: 'Foo',
1956
- element: <Foo />,
1957
- children: [{
1958
- displayName: 'Qux',
1959
- element: <Qux />,
1960
- children: [],
1961
- }],
1962
- }, {
1963
- displayName: 'Bar',
1964
- children: [{
1965
- displayName: 'h1',
1966
- children: [{
1967
- displayName: 'span',
1968
- children: [{
1969
- displayName: '#text',
1970
- element: 'Hi,',
1971
- text: 'Hi,',
1972
- }],
1973
- }, {
1974
- displayName: '#text',
1975
- text: 'Mom',
1976
- element: 'Mom',
1977
- }],
1978
- }],
1979
- }, {
1980
- displayName: 'a',
1981
- children: [{
1982
- displayName: '#text',
1983
- text: 'Click me.',
1984
- element: 'Click me.',
1985
- }],
1986
- }],
1987
- }],
2172
+ children: [
2173
+ {
2174
+ displayName: 'div',
2175
+ children: [
2176
+ {
2177
+ displayName: 'Foo',
2178
+ element: <Foo />,
2179
+ children: [
2180
+ {
2181
+ displayName: 'Qux',
2182
+ element: <Qux />,
2183
+ children: [],
2184
+ },
2185
+ ],
2186
+ },
2187
+ {
2188
+ displayName: 'Bar',
2189
+ children: [
2190
+ {
2191
+ displayName: 'h1',
2192
+ children: [
2193
+ {
2194
+ displayName: 'span',
2195
+ children: [
2196
+ {
2197
+ displayName: '#text',
2198
+ element: 'Hi,',
2199
+ text: 'Hi,',
2200
+ },
2201
+ ],
2202
+ },
2203
+ {
2204
+ displayName: '#text',
2205
+ text: 'Mom',
2206
+ element: 'Mom',
2207
+ },
2208
+ ],
2209
+ },
2210
+ ],
2211
+ },
2212
+ {
2213
+ displayName: 'a',
2214
+ children: [
2215
+ {
2216
+ displayName: '#text',
2217
+ text: 'Click me.',
2218
+ element: 'Click me.',
2219
+ },
2220
+ ],
2221
+ },
2222
+ ],
2223
+ },
2224
+ ],
2225
};
2226
assertTreeMatches([element, tree]);
2227
});
src/renderers/__tests__/ReactComponentTreeHook-test.native.js
+846
-556
@@ -157,16 +157,20 @@ describeStack('ReactComponentTreeHook', () => {
157
var tree = {
158
displayName: 'View',
159
element,
160
- children: [{
161
- displayName: 'Bar',
162
- children: [],
163
- }, {
164
- displayName: 'Baz',
165
- children: [],
166
- }, {
167
- displayName: 'Unknown',
168
- children: [],
169
- }],
160
+ children: [
161
+ {
162
+ displayName: 'Bar',
163
+ children: [],
164
+ },
165
+ {
166
+ displayName: 'Baz',
167
+ children: [],
168
+ },
169
+ {
170
+ displayName: 'Unknown',
171
+ children: [],
172
+ },
173
+ ],
174
};
175
assertTreeMatches([element, tree]);
176
});
@@ -193,17 +197,21 @@ describeStack('ReactComponentTreeHook', () => {
197
var element = <View><Foo /><Baz /><Qux /></View>;
198
var tree = {
199
displayName: 'View',
196
- children: [{
197
- displayName: 'Bar',
198
- children: [],
199
- }, {
200
- displayName: 'Baz',
201
- children: [],
202
- }, {
203
- // Note: Ideally fallback name should be consistent (e.g. "Unknown")
204
- displayName: 'ReactComponent',
205
- children: [],
206
- }],
200
+ children: [
201
+ {
202
+ displayName: 'Bar',
203
+ children: [],
204
+ },
205
+ {
206
+ displayName: 'Baz',
207
+ children: [],
208
+ },
209
+ {
210
+ // Note: Ideally fallback name should be consistent (e.g. "Unknown")
211
+ displayName: 'ReactComponent',
212
+ children: [],
213
+ },
214
+ ],
215
};
216
assertTreeMatches([element, tree]);
217
});
@@ -236,16 +244,20 @@ describeStack('ReactComponentTreeHook', () => {
244
var element = <View><Foo /><Baz /><Qux /></View>;
245
var tree = {
246
displayName: 'View',
239
- children: [{
240
- displayName: 'Bar',
241
- children: [],
242
- }, {
243
- displayName: 'Baz',
244
- children: [],
245
- }, {
246
- displayName: 'Unknown',
247
- children: [],
248
- }],
247
+ children: [
248
+ {
249
+ displayName: 'Bar',
250
+ children: [],
251
+ },
252
+ {
253
+ displayName: 'Baz',
254
+ children: [],
255
+ },
256
+ {
257
+ displayName: 'Unknown',
258
+ children: [],
259
+ },
260
+ ],
261
};
262
assertTreeMatches([element, tree]);
263
});
@@ -266,16 +278,20 @@ describeStack('ReactComponentTreeHook', () => {
278
var element = <View><Foo /><Baz /><Qux /></View>;
279
var tree = {
280
displayName: 'View',
269
- children: [{
270
- displayName: 'Bar',
271
- children: [],
272
- }, {
273
- displayName: 'Baz',
274
- children: [],
275
- }, {
276
- displayName: 'Unknown',
277
- children: [],
278
- }],
281
+ children: [
282
+ {
283
+ displayName: 'Bar',
284
+ children: [],
285
+ },
286
+ {
287
+ displayName: 'Baz',
288
+ children: [],
289
+ },
290
+ {
291
+ displayName: 'Unknown',
292
+ children: [],
293
+ },
294
+ ],
295
};
296
assertTreeMatches([element, tree]);
297
});
@@ -294,24 +310,33 @@ describeStack('ReactComponentTreeHook', () => {
310
var tree = {
311
displayName: 'View',
312
element,
297
- children: [{
298
- displayName: 'View',
299
- children: [{
300
- displayName: 'Text',
301
- children: [{
302
- displayName: 'RCText',
303
- children: [{
304
- displayName: '#text',
305
- element: 'Hi!',
306
- text: 'Hi!',
307
- }],
308
- }],
309
- }],
310
- }, {
311
- displayName: 'Image',
312
- element: <Image />,
313
- children: [],
314
- }],
313
+ children: [
314
+ {
315
+ displayName: 'View',
316
+ children: [
317
+ {
318
+ displayName: 'Text',
319
+ children: [
320
+ {
321
+ displayName: 'RCText',
322
+ children: [
323
+ {
324
+ displayName: '#text',
325
+ element: 'Hi!',
326
+ text: 'Hi!',
327
+ },
328
+ ],
329
+ },
330
+ ],
331
+ },
332
+ ],
333
+ },
334
+ {
335
+ displayName: 'Image',
336
+ element: <Image />,
337
+ children: [],
338
+ },
339
+ ],
340
};
341
assertTreeMatches([element, tree]);
342
});
@@ -327,11 +352,13 @@ describeStack('ReactComponentTreeHook', () => {
352
var tree = {
353
displayName: 'Foo',
354
element,
330
- children: [{
331
- displayName: 'Image',
332
- element: <Image />,
333
- children: [],
334
- }],
355
+ children: [
356
+ {
357
+ displayName: 'Image',
358
+ element: <Image />,
359
+ children: [],
360
+ },
361
+ ],
362
};
363
assertTreeMatches([element, tree]);
364
});
@@ -371,38 +398,54 @@ describeStack('ReactComponentTreeHook', () => {
398
var tree = {
399
displayName: 'Baz',
400
element,
374
- children: [{
375
- displayName: 'View',
376
- children: [{
377
- displayName: 'Foo',
378
- element: <Foo />,
379
- children: [{
380
- displayName: 'Qux',
381
- element: <Qux />,
382
- children: [],
383
- }],
384
- }, {
385
- displayName: 'Bar',
386
- children: [{
387
- displayName: 'View',
388
- children: [{
389
- displayName: 'Text',
390
- children: [{
391
- displayName: 'RCText',
392
- children: [{
393
- displayName: '#text',
394
- element: 'Hi,',
395
- text: 'Hi,',
396
- }],
397
- }],
398
- }],
399
- }],
400
- }, {
401
- displayName: 'Image',
402
- element: <Image />,
403
- children: [],
404
- }],
405
- }],
401
+ children: [
402
+ {
403
+ displayName: 'View',
404
+ children: [
405
+ {
406
+ displayName: 'Foo',
407
+ element: <Foo />,
408
+ children: [
409
+ {
410
+ displayName: 'Qux',
411
+ element: <Qux />,
412
+ children: [],
413
+ },
414
+ ],
415
+ },
416
+ {
417
+ displayName: 'Bar',
418
+ children: [
419
+ {
420
+ displayName: 'View',
421
+ children: [
422
+ {
423
+ displayName: 'Text',
424
+ children: [
425
+ {
426
+ displayName: 'RCText',
427
+ children: [
428
+ {
429
+ displayName: '#text',
430
+ element: 'Hi,',
431
+ text: 'Hi,',
432
+ },
433
+ ],
434
+ },
435
+ ],
436
+ },
437
+ ],
438
+ },
439
+ ],
440
+ },
441
+ {
442
+ displayName: 'Image',
443
+ element: <Image />,
444
+ children: [],
445
+ },
446
+ ],
447
+ },
448
+ ],
449
};
450
assertTreeMatches([element, tree]);
451
});
@@ -439,16 +482,21 @@ describeStack('ReactComponentTreeHook', () => {
482
var element = <Text>{'1'}{2}</Text>;
483
var tree = {
484
displayName: 'Text',
442
- children: [{
443
- displayName: 'RCText',
444
- children: [{
445
- displayName: '#text',
446
- text: '1',
447
- }, {
448
- displayName: '#text',
449
- text: '2',
450
- }],
451
- }],
485
+ children: [
486
+ {
487
+ displayName: 'RCText',
488
+ children: [
489
+ {
490
+ displayName: '#text',
491
+ text: '1',
492
+ },
493
+ {
494
+ displayName: '#text',
495
+ text: '2',
496
+ },
497
+ ],
498
+ },
499
+ ],
500
};
501
assertTreeMatches([element, tree]);
502
});
@@ -457,13 +505,17 @@ describeStack('ReactComponentTreeHook', () => {
505
var element = <Text>{'1'}</Text>;
506
var tree = {
507
displayName: 'Text',
460
- children: [{
461
- displayName: 'RCText',
462
- children: [{
463
- displayName: '#text',
464
- text: '1',
465
- }],
466
- }],
508
+ children: [
509
+ {
510
+ displayName: 'RCText',
511
+ children: [
512
+ {
513
+ displayName: '#text',
514
+ text: '1',
515
+ },
516
+ ],
517
+ },
518
+ ],
519
};
520
assertTreeMatches([element, tree]);
521
});
@@ -472,13 +524,17 @@ describeStack('ReactComponentTreeHook', () => {
524
var element = <Text>{42}</Text>;
525
var tree = {
526
displayName: 'Text',
475
- children: [{
476
- displayName: 'RCText',
477
- children: [{
478
- displayName: '#text',
479
- text: '42',
480
- }],
481
- }],
527
+ children: [
528
+ {
529
+ displayName: 'RCText',
530
+ children: [
531
+ {
532
+ displayName: '#text',
533
+ text: '42',
534
+ },
535
+ ],
536
+ },
537
+ ],
538
};
539
assertTreeMatches([element, tree]);
540
});
@@ -487,13 +543,17 @@ describeStack('ReactComponentTreeHook', () => {
543
var element = <Text>{0}</Text>;
544
var tree = {
545
displayName: 'Text',
490
- children: [{
491
- displayName: 'RCText',
492
- children: [{
493
- displayName: '#text',
494
- text: '0',
495
- }],
496
- }],
546
+ children: [
547
+ {
548
+ displayName: 'RCText',
549
+ children: [
550
+ {
551
+ displayName: '#text',
552
+ text: '0',
553
+ },
554
+ ],
555
+ },
556
+ ],
557
};
558
assertTreeMatches([element, tree]);
559
});
@@ -513,23 +573,30 @@ describeStack('ReactComponentTreeHook', () => {
573
var tree = {
574
displayName: 'View',
575
element,
516
- children: [{
517
- displayName: 'Foo',
518
- element: <Foo />,
519
- children: [{
520
- displayName: 'Image',
521
- element: <Image />,
522
- children: [],
523
- }],
524
- }, {
525
- displayName: 'Foo',
526
- element: <Foo />,
527
- children: [{
528
- displayName: 'Image',
529
- element: <Image />,
530
- children: [],
531
- }],
532
- }],
576
+ children: [
577
+ {
578
+ displayName: 'Foo',
579
+ element: <Foo />,
580
+ children: [
581
+ {
582
+ displayName: 'Image',
583
+ element: <Image />,
584
+ children: [],
585
+ },
586
+ ],
587
+ },
588
+ {
589
+ displayName: 'Foo',
590
+ element: <Foo />,
591
+ children: [
592
+ {
593
+ displayName: 'Image',
594
+ element: <Image />,
595
+ children: [],
596
+ },
597
+ ],
598
+ },
599
+ ],
600
};
601
assertTreeMatches([element, tree]);
602
});
@@ -541,25 +608,33 @@ describeStack('ReactComponentTreeHook', () => {
608
var elementBefore = <Text>Hi.</Text>;
609
var treeBefore = {
610
displayName: 'Text',
544
- children: [{
545
- displayName: 'RCText',
546
- children: [{
547
- displayName: '#text',
548
- text: 'Hi.',
549
- }],
550
- }],
611
+ children: [
612
+ {
613
+ displayName: 'RCText',
614
+ children: [
615
+ {
616
+ displayName: '#text',
617
+ text: 'Hi.',
618
+ },
619
+ ],
620
+ },
621
+ ],
622
};
623
624
var elementAfter = <Text>Bye.</Text>;
625
var treeAfter = {
626
displayName: 'Text',
556
- children: [{
557
- displayName: 'RCText',
558
- children: [{
559
- displayName: '#text',
560
- text: 'Bye.',
561
- }],
562
- }],
627
+ children: [
628
+ {
629
+ displayName: 'RCText',
630
+ children: [
631
+ {
632
+ displayName: '#text',
633
+ text: 'Bye.',
634
+ },
635
+ ],
636
+ },
637
+ ],
638
};
639
640
assertTreeMatches([
@@ -572,22 +647,28 @@ describeStack('ReactComponentTreeHook', () => {
647
var elementBefore = <Text />;
648
var treeBefore = {
649
displayName: 'Text',
575
- children: [{
576
- displayName: 'RCText',
577
- children: [],
578
- }],
650
+ children: [
651
+ {
652
+ displayName: 'RCText',
653
+ children: [],
654
+ },
655
+ ],
656
};
657
658
var elementAfter = <Text>Hi.</Text>;
659
var treeAfter = {
660
displayName: 'Text',
584
- children: [{
585
- displayName: 'RCText',
586
- children: [{
587
- displayName: '#text',
588
- text: 'Hi.',
589
- }],
590
- }],
661
+ children: [
662
+ {
663
+ displayName: 'RCText',
664
+ children: [
665
+ {
666
+ displayName: '#text',
667
+ text: 'Hi.',
668
+ },
669
+ ],
670
+ },
671
+ ],
672
};
673
674
assertTreeMatches([
@@ -600,22 +681,28 @@ describeStack('ReactComponentTreeHook', () => {
681
var elementBefore = <Text>Hi.</Text>;
682
var treeBefore = {
683
displayName: 'Text',
603
- children: [{
604
- displayName: 'RCText',
605
- children: [{
606
- displayName: '#text',
607
- text: 'Hi.',
608
- }],
609
- }],
684
+ children: [
685
+ {
686
+ displayName: 'RCText',
687
+ children: [
688
+ {
689
+ displayName: '#text',
690
+ text: 'Hi.',
691
+ },
692
+ ],
693
+ },
694
+ ],
695
};
696
697
var elementAfter = <Text />;
698
var treeAfter = {
699
displayName: 'Text',
615
- children: [{
616
- displayName: 'RCText',
617
- children: [],
618
- }],
700
+ children: [
701
+ {
702
+ displayName: 'RCText',
703
+ children: [],
704
+ },
705
+ ],
706
};
707
708
assertTreeMatches([
@@ -628,25 +715,32 @@ describeStack('ReactComponentTreeHook', () => {
715
var elementBefore = <Text />;
716
var treeBefore = {
717
displayName: 'Text',
631
- children: [{
632
- displayName: 'RCText',
633
- children: [],
634
- }],
718
+ children: [
719
+ {
720
+ displayName: 'RCText',
721
+ children: [],
722
+ },
723
+ ],
724
};
725
726
var elementAfter = <Text>{'Hi.'}{'Bye.'}</Text>;
727
var treeAfter = {
728
displayName: 'Text',
640
- children: [{
641
- displayName: 'RCText',
642
- children: [{
643
- displayName: '#text',
644
- text: 'Hi.',
645
- }, {
646
- displayName: '#text',
647
- text: 'Bye.',
648
- }],
649
- }],
729
+ children: [
730
+ {
731
+ displayName: 'RCText',
732
+ children: [
733
+ {
734
+ displayName: '#text',
735
+ text: 'Hi.',
736
+ },
737
+ {
738
+ displayName: '#text',
739
+ text: 'Bye.',
740
+ },
741
+ ],
742
+ },
743
+ ],
744
};
745
746
assertTreeMatches([
@@ -659,25 +753,32 @@ describeStack('ReactComponentTreeHook', () => {
753
var elementBefore = <Text>{'Hi.'}{'Bye.'}</Text>;
754
var treeBefore = {
755
displayName: 'Text',
662
- children: [{
663
- displayName: 'RCText',
664
- children: [{
665
- displayName: '#text',
666
- text: 'Hi.',
667
- }, {
668
- displayName: '#text',
669
- text: 'Bye.',
670
- }],
671
- }],
756
+ children: [
757
+ {
758
+ displayName: 'RCText',
759
+ children: [
760
+ {
761
+ displayName: '#text',
762
+ text: 'Hi.',
763
+ },
764
+ {
765
+ displayName: '#text',
766
+ text: 'Bye.',
767
+ },
768
+ ],
769
+ },
770
+ ],
771
};
772
773
var elementAfter = <Text />;
774
var treeAfter = {
775
displayName: 'Text',
677
- children: [{
678
- displayName: 'RCText',
679
- children: [],
680
- }],
776
+ children: [
777
+ {
778
+ displayName: 'RCText',
779
+ children: [],
780
+ },
781
+ ],
782
};
783
assertTreeMatches([
784
[elementBefore, treeBefore],
@@ -689,28 +790,37 @@ describeStack('ReactComponentTreeHook', () => {
790
var elementBefore = <Text>Hi.</Text>;
791
var treeBefore = {
792
displayName: 'Text',
692
- children: [{
693
- displayName: 'RCText',
694
- children: [{
695
- displayName: '#text',
696
- text: 'Hi.',
697
- }],
698
- }],
793
+ children: [
794
+ {
795
+ displayName: 'RCText',
796
+ children: [
797
+ {
798
+ displayName: '#text',
799
+ text: 'Hi.',
800
+ },
801
+ ],
802
+ },
803
+ ],
804
};
805
806
var elementAfter = <Text>{'Hi.'}{'Bye.'}</Text>;
807
var treeAfter = {
808
displayName: 'Text',
704
- children: [{
705
- displayName: 'RCText',
706
- children: [{
707
- displayName: '#text',
708
- text: 'Hi.',
709
- }, {
710
- displayName: '#text',
711
- text: 'Bye.',
712
- }],
713
- }],
809
+ children: [
810
+ {
811
+ displayName: 'RCText',
812
+ children: [
813
+ {
814
+ displayName: '#text',
815
+ text: 'Hi.',
816
+ },
817
+ {
818
+ displayName: '#text',
819
+ text: 'Bye.',
820
+ },
821
+ ],
822
+ },
823
+ ],
824
};
825
826
assertTreeMatches([
@@ -723,28 +833,37 @@ describeStack('ReactComponentTreeHook', () => {
833
var elementBefore = <Text>{'Hi.'}{'Bye.'}</Text>;
834
var treeBefore = {
835
displayName: 'Text',
726
- children: [{
727
- displayName: 'RCText',
728
- children: [{
729
- displayName: '#text',
730
- text: 'Hi.',
731
- }, {
732
- displayName: '#text',
733
- text: 'Bye.',
734
- }],
735
- }],
836
+ children: [
837
+ {
838
+ displayName: 'RCText',
839
+ children: [
840
+ {
841
+ displayName: '#text',
842
+ text: 'Hi.',
843
+ },
844
+ {
845
+ displayName: '#text',
846
+ text: 'Bye.',
847
+ },
848
+ ],
849
+ },
850
+ ],
851
};
852
853
var elementAfter = <Text>Hi.</Text>;
854
var treeAfter = {
855
displayName: 'Text',
741
- children: [{
742
- displayName: 'RCText',
743
- children: [{
744
- displayName: '#text',
745
- text: 'Hi.',
746
- }],
747
- }],
856
+ children: [
857
+ {
858
+ displayName: 'RCText',
859
+ children: [
860
+ {
861
+ displayName: '#text',
862
+ text: 'Hi.',
863
+ },
864
+ ],
865
+ },
866
+ ],
867
};
868
assertTreeMatches([
869
[elementBefore, treeBefore],
@@ -756,31 +875,41 @@ describeStack('ReactComponentTreeHook', () => {
875
var elementBefore = <Text>{'Hi.'}{'Bye.'}</Text>;
876
var treeBefore = {
877
displayName: 'Text',
759
- children: [{
760
- displayName: 'RCText',
761
- children: [{
762
- displayName: '#text',
763
- text: 'Hi.',
764
- }, {
765
- displayName: '#text',
766
- text: 'Bye.',
767
- }],
768
- }],
878
+ children: [
879
+ {
880
+ displayName: 'RCText',
881
+ children: [
882
+ {
883
+ displayName: '#text',
884
+ text: 'Hi.',
885
+ },
886
+ {
887
+ displayName: '#text',
888
+ text: 'Bye.',
889
+ },
890
+ ],
891
+ },
892
+ ],
893
};
894
895
var elementAfter = <Text>{'Bye.'}{'Hi.'}</Text>;
896
var treeAfter = {
897
displayName: 'Text',
774
- children: [{
775
- displayName: 'RCText',
776
- children: [{
777
- displayName: '#text',
778
- text: 'Bye.',
779
- }, {
780
- displayName: '#text',
781
- text: 'Hi.',
782
- }],
783
- }],
898
+ children: [
899
+ {
900
+ displayName: 'RCText',
901
+ children: [
902
+ {
903
+ displayName: '#text',
904
+ text: 'Bye.',
905
+ },
906
+ {
907
+ displayName: '#text',
908
+ text: 'Hi.',
909
+ },
910
+ ],
911
+ },
912
+ ],
913
};
914
assertTreeMatches([
915
[elementBefore, treeBefore],
@@ -797,25 +926,36 @@ describeStack('ReactComponentTreeHook', () => {
926
);
927
var treeBefore = {
928
displayName: 'View',
800
- children: [{
801
- displayName: 'Text',
802
- children: [{
803
- displayName: 'RCText',
804
- children: [{
805
- displayName: '#text',
806
- text: 'Hi.',
807
- }],
808
- }],
809
- }, {
810
- displayName: 'Text',
811
- children: [{
812
- displayName: 'RCText',
813
- children: [{
814
- displayName: '#text',
815
- text: 'Bye.',
816
- }],
817
- }],
818
- }],
929
+ children: [
930
+ {
931
+ displayName: 'Text',
932
+ children: [
933
+ {
934
+ displayName: 'RCText',
935
+ children: [
936
+ {
937
+ displayName: '#text',
938
+ text: 'Hi.',
939
+ },
940
+ ],
941
+ },
942
+ ],
943
+ },
944
+ {
945
+ displayName: 'Text',
946
+ children: [
947
+ {
948
+ displayName: 'RCText',
949
+ children: [
950
+ {
951
+ displayName: '#text',
952
+ text: 'Bye.',
953
+ },
954
+ ],
955
+ },
956
+ ],
957
+ },
958
+ ],
959
};
960
961
var elementAfter = (
@@ -826,25 +966,36 @@ describeStack('ReactComponentTreeHook', () => {
966
);
967
var treeAfter = {
968
displayName: 'View',
829
- children: [{
830
- displayName: 'Text',
831
- children: [{
832
- displayName: 'RCText',
833
- children: [{
834
- displayName: '#text',
835
- text: 'Bye.',
836
- }],
837
- }],
838
- }, {
839
- displayName: 'Text',
840
- children: [{
841
- displayName: 'RCText',
842
- children: [{
843
- displayName: '#text',
844
- text: 'Hi.',
845
- }],
846
- }],
847
- }],
969
+ children: [
970
+ {
971
+ displayName: 'Text',
972
+ children: [
973
+ {
974
+ displayName: 'RCText',
975
+ children: [
976
+ {
977
+ displayName: '#text',
978
+ text: 'Bye.',
979
+ },
980
+ ],
981
+ },
982
+ ],
983
+ },
984
+ {
985
+ displayName: 'Text',
986
+ children: [
987
+ {
988
+ displayName: 'RCText',
989
+ children: [
990
+ {
991
+ displayName: '#text',
992
+ text: 'Hi.',
993
+ },
994
+ ],
995
+ },
996
+ ],
997
+ },
998
+ ],
999
};
1000
1001
assertTreeMatches([
@@ -862,25 +1013,36 @@ describeStack('ReactComponentTreeHook', () => {
1013
);
1014
var treeBefore = {
1015
displayName: 'View',
865
- children: [{
866
- displayName: 'Text',
867
- children: [{
868
- displayName: 'RCText',
869
- children: [{
870
- displayName: '#text',
871
- text: 'Hi.',
872
- }],
873
- }],
874
- }, {
875
- displayName: 'Text',
876
- children: [{
877
- displayName: 'RCText',
878
- children: [{
879
- displayName: '#text',
880
- text: 'Bye.',
881
- }],
882
- }],
883
- }],
1016
+ children: [
1017
+ {
1018
+ displayName: 'Text',
1019
+ children: [
1020
+ {
1021
+ displayName: 'RCText',
1022
+ children: [
1023
+ {
1024
+ displayName: '#text',
1025
+ text: 'Hi.',
1026
+ },
1027
+ ],
1028
+ },
1029
+ ],
1030
+ },
1031
+ {
1032
+ displayName: 'Text',
1033
+ children: [
1034
+ {
1035
+ displayName: 'RCText',
1036
+ children: [
1037
+ {
1038
+ displayName: '#text',
1039
+ text: 'Bye.',
1040
+ },
1041
+ ],
1042
+ },
1043
+ ],
1044
+ },
1045
+ ],
1046
};
1047
1048
var elementAfter = (
@@ -891,25 +1053,36 @@ describeStack('ReactComponentTreeHook', () => {
1053
);
1054
var treeAfter = {
1055
displayName: 'View',
894
- children: [{
895
- displayName: 'Text',
896
- children: [{
897
- displayName: 'RCText',
898
- children: [{
899
- displayName: '#text',
900
- text: 'Bye.',
901
- }],
902
- }],
903
- }, {
904
- displayName: 'Text',
905
- children: [{
906
- displayName: 'RCText',
907
- children: [{
908
- displayName: '#text',
909
- text: 'Hi.',
910
- }],
911
- }],
912
- }],
1056
+ children: [
1057
+ {
1058
+ displayName: 'Text',
1059
+ children: [
1060
+ {
1061
+ displayName: 'RCText',
1062
+ children: [
1063
+ {
1064
+ displayName: '#text',
1065
+ text: 'Bye.',
1066
+ },
1067
+ ],
1068
+ },
1069
+ ],
1070
+ },
1071
+ {
1072
+ displayName: 'Text',
1073
+ children: [
1074
+ {
1075
+ displayName: 'RCText',
1076
+ children: [
1077
+ {
1078
+ displayName: '#text',
1079
+ text: 'Hi.',
1080
+ },
1081
+ ],
1082
+ },
1083
+ ],
1084
+ },
1085
+ ],
1086
};
1087
1088
assertTreeMatches([
@@ -930,19 +1103,23 @@ describeStack('ReactComponentTreeHook', () => {
1103
var elementBefore = <View><Foo /></View>;
1104
var treeBefore = {
1105
displayName: 'View',
933
- children: [{
934
- displayName: 'Foo',
935
- children: [],
936
- }],
1106
+ children: [
1107
+ {
1108
+ displayName: 'Foo',
1109
+ children: [],
1110
+ },
1111
+ ],
1112
};
1113
1114
var elementAfter = <View><Bar /></View>;
1115
var treeAfter = {
1116
displayName: 'View',
942
- children: [{
943
- displayName: 'Bar',
944
- children: [],
945
- }],
1117
+ children: [
1118
+ {
1119
+ displayName: 'Bar',
1120
+ children: [],
1121
+ },
1122
+ ],
1123
};
1124
1125
assertTreeMatches([
@@ -952,32 +1129,40 @@ describeStack('ReactComponentTreeHook', () => {
1129
});
1130
1131
it('updates a single composite child of the same type', () => {
955
- function Foo({ children }) {
1132
+ function Foo({children}) {
1133
return children;
1134
}
1135
1136
var elementBefore = <View><Foo><View /></Foo></View>;
1137
var treeBefore = {
1138
displayName: 'View',
962
- children: [{
963
- displayName: 'Foo',
964
- children: [{
965
- displayName: 'View',
966
- children: [],
967
- }],
968
- }],
1139
+ children: [
1140
+ {
1141
+ displayName: 'Foo',
1142
+ children: [
1143
+ {
1144
+ displayName: 'View',
1145
+ children: [],
1146
+ },
1147
+ ],
1148
+ },
1149
+ ],
1150
};
1151
1152
var elementAfter = <View><Foo><Image /></Foo></View>;
1153
var treeAfter = {
1154
displayName: 'View',
974
- children: [{
975
- displayName: 'Foo',
976
- children: [{
977
- displayName: 'Image',
978
- children: [],
979
- }],
980
- }],
1155
+ children: [
1156
+ {
1157
+ displayName: 'Foo',
1158
+ children: [
1159
+ {
1160
+ displayName: 'Image',
1161
+ children: [],
1162
+ },
1163
+ ],
1164
+ },
1165
+ ],
1166
};
1167
1168
assertTreeMatches([
@@ -1000,10 +1185,12 @@ describeStack('ReactComponentTreeHook', () => {
1185
var elementAfter = <View><Foo /></View>;
1186
var treeAfter = {
1187
displayName: 'View',
1003
- children: [{
1004
- displayName: 'Foo',
1005
- children: [],
1006
- }],
1188
+ children: [
1189
+ {
1190
+ displayName: 'Foo',
1191
+ children: [],
1192
+ },
1193
+ ],
1194
};
1195
1196
assertTreeMatches([
@@ -1020,10 +1207,12 @@ describeStack('ReactComponentTreeHook', () => {
1207
var elementBefore = <View><Foo /></View>;
1208
var treeBefore = {
1209
displayName: 'View',
1023
- children: [{
1024
- displayName: 'Foo',
1025
- children: [],
1026
- }],
1210
+ children: [
1211
+ {
1212
+ displayName: 'Foo',
1213
+ children: [],
1214
+ },
1215
+ ],
1216
};
1217
1218
var elementAfter = <View />;
@@ -1053,31 +1242,45 @@ describeStack('ReactComponentTreeHook', () => {
1242
);
1243
var tree1 = {
1244
displayName: 'View',
1056
- children: [{
1057
- displayName: 'Text',
1058
- children: [{
1059
- displayName: 'RCText',
1060
- children: [{
1061
- displayName: '#text',
1062
- text: 'hi',
1063
- }],
1064
- }],
1065
- }, {
1066
- displayName: 'Text',
1067
- children: [{
1068
- displayName: 'RCText',
1069
- children: [{
1070
- displayName: '#text',
1071
- text: '42',
1072
- }],
1073
- }],
1074
- }, {
1075
- displayName: 'Foo',
1076
- children: [{
1077
- displayName: 'View',
1078
- children: [],
1079
- }],
1080
- }],
1245
+ children: [
1246
+ {
1247
+ displayName: 'Text',
1248
+ children: [
1249
+ {
1250
+ displayName: 'RCText',
1251
+ children: [
1252
+ {
1253
+ displayName: '#text',
1254
+ text: 'hi',
1255
+ },
1256
+ ],
1257
+ },
1258
+ ],
1259
+ },
1260
+ {
1261
+ displayName: 'Text',
1262
+ children: [
1263
+ {
1264
+ displayName: 'RCText',
1265
+ children: [
1266
+ {
1267
+ displayName: '#text',
1268
+ text: '42',
1269
+ },
1270
+ ],
1271
+ },
1272
+ ],
1273
+ },
1274
+ {
1275
+ displayName: 'Foo',
1276
+ children: [
1277
+ {
1278
+ displayName: 'View',
1279
+ children: [],
1280
+ },
1281
+ ],
1282
+ },
1283
+ ],
1284
};
1285
1286
var element2 = (
@@ -1090,22 +1293,31 @@ describeStack('ReactComponentTreeHook', () => {
1293
);
1294
var tree2 = {
1295
displayName: 'View',
1093
- children: [{
1094
- displayName: 'Foo',
1095
- children: [{
1096
- displayName: 'View',
1097
- children: [],
1098
- }],
1099
- }, {
1100
- displayName: 'Text',
1101
- children: [{
1102
- displayName: 'RCText',
1103
- children: [{
1104
- displayName: '#text',
1105
- text: 'hi',
1106
- }],
1107
- }],
1108
- }],
1296
+ children: [
1297
+ {
1298
+ displayName: 'Foo',
1299
+ children: [
1300
+ {
1301
+ displayName: 'View',
1302
+ children: [],
1303
+ },
1304
+ ],
1305
+ },
1306
+ {
1307
+ displayName: 'Text',
1308
+ children: [
1309
+ {
1310
+ displayName: 'RCText',
1311
+ children: [
1312
+ {
1313
+ displayName: '#text',
1314
+ text: 'hi',
1315
+ },
1316
+ ],
1317
+ },
1318
+ ],
1319
+ },
1320
+ ],
1321
};
1322
1323
var element3 = (
@@ -1115,13 +1327,17 @@ describeStack('ReactComponentTreeHook', () => {
1327
);
1328
var tree3 = {
1329
displayName: 'View',
1118
- children: [{
1119
- displayName: 'Foo',
1120
- children: [{
1121
- displayName: 'View',
1122
- children: [],
1123
- }],
1124
- }],
1330
+ children: [
1331
+ {
1332
+ displayName: 'Foo',
1333
+ children: [
1334
+ {
1335
+ displayName: 'View',
1336
+ children: [],
1337
+ },
1338
+ ],
1339
+ },
1340
+ ],
1341
};
1342
1343
assertTreeMatches([
@@ -1134,26 +1350,30 @@ describeStack('ReactComponentTreeHook', () => {
1350
1351
describe('functional component', () => {
1352
it('updates with a host child', () => {
1137
- function Foo({ children }) {
1353
+ function Foo({children}) {
1354
return children;
1355
}
1356
1357
var elementBefore = <Foo><View /></Foo>;
1358
var treeBefore = {
1359
displayName: 'Foo',
1144
- children: [{
1145
- displayName: 'View',
1146
- children: [],
1147
- }],
1360
+ children: [
1361
+ {
1362
+ displayName: 'View',
1363
+ children: [],
1364
+ },
1365
+ ],
1366
};
1367
1368
var elementAfter = <Foo><Image /></Foo>;
1369
var treeAfter = {
1370
displayName: 'Foo',
1153
- children: [{
1154
- displayName: 'Image',
1155
- children: [],
1156
- }],
1371
+ children: [
1372
+ {
1373
+ displayName: 'Image',
1374
+ children: [],
1375
+ },
1376
+ ],
1377
};
1378
1379
assertTreeMatches([
@@ -1163,7 +1383,7 @@ describeStack('ReactComponentTreeHook', () => {
1383
});
1384
1385
it('updates from null to a host child', () => {
1166
- function Foo({ children }) {
1386
+ function Foo({children}) {
1387
return children;
1388
}
1389
@@ -1176,10 +1396,12 @@ describeStack('ReactComponentTreeHook', () => {
1396
var elementAfter = <Foo><View /></Foo>;
1397
var treeAfter = {
1398
displayName: 'Foo',
1179
- children: [{
1180
- displayName: 'View',
1181
- children: [],
1182
- }],
1399
+ children: [
1400
+ {
1401
+ displayName: 'View',
1402
+ children: [],
1403
+ },
1404
+ ],
1405
};
1406
1407
assertTreeMatches([
@@ -1189,17 +1411,19 @@ describeStack('ReactComponentTreeHook', () => {
1411
});
1412
1413
it('updates from a host child to null', () => {
1192
- function Foo({ children }) {
1414
+ function Foo({children}) {
1415
return children;
1416
}
1417
1418
var elementBefore = <Foo><View /></Foo>;
1419
var treeBefore = {
1420
displayName: 'Foo',
1199
- children: [{
1200
- displayName: 'View',
1201
- children: [],
1202
- }],
1421
+ children: [
1422
+ {
1423
+ displayName: 'View',
1424
+ children: [],
1425
+ },
1426
+ ],
1427
};
1428
1429
var elementAfter = <Foo>{null}</Foo>;
@@ -1219,26 +1443,30 @@ describeStack('ReactComponentTreeHook', () => {
1443
return null;
1444
}
1445
1222
- function Foo({ children }) {
1446
+ function Foo({children}) {
1447
return children;
1448
}
1449
1450
var elementBefore = <Foo><View /></Foo>;
1451
var treeBefore = {
1452
displayName: 'Foo',
1229
- children: [{
1230
- displayName: 'View',
1231
- children: [],
1232
- }],
1453
+ children: [
1454
+ {
1455
+ displayName: 'View',
1456
+ children: [],
1457
+ },
1458
+ ],
1459
};
1460
1461
var elementAfter = <Foo><Bar /></Foo>;
1462
var treeAfter = {
1463
displayName: 'Foo',
1238
- children: [{
1239
- displayName: 'Bar',
1240
- children: [],
1241
- }],
1464
+ children: [
1465
+ {
1466
+ displayName: 'Bar',
1467
+ children: [],
1468
+ },
1469
+ ],
1470
};
1471
1472
assertTreeMatches([
@@ -1252,26 +1480,30 @@ describeStack('ReactComponentTreeHook', () => {
1480
return null;
1481
}
1482
1255
- function Foo({ children }) {
1483
+ function Foo({children}) {
1484
return children;
1485
}
1486
1487
var elementBefore = <Foo><Bar /></Foo>;
1488
var treeBefore = {
1489
displayName: 'Foo',
1262
- children: [{
1263
- displayName: 'Bar',
1264
- children: [],
1265
- }],
1490
+ children: [
1491
+ {
1492
+ displayName: 'Bar',
1493
+ children: [],
1494
+ },
1495
+ ],
1496
};
1497
1498
var elementAfter = <Foo><View /></Foo>;
1499
var treeAfter = {
1500
displayName: 'Foo',
1271
- children: [{
1272
- displayName: 'View',
1273
- children: [],
1274
- }],
1501
+ children: [
1502
+ {
1503
+ displayName: 'View',
1504
+ children: [],
1505
+ },
1506
+ ],
1507
};
1508
1509
assertTreeMatches([
@@ -1285,7 +1517,7 @@ describeStack('ReactComponentTreeHook', () => {
1517
return null;
1518
}
1519
1288
- function Foo({ children }) {
1520
+ function Foo({children}) {
1521
return children;
1522
}
1523
@@ -1298,10 +1530,12 @@ describeStack('ReactComponentTreeHook', () => {
1530
var elementAfter = <Foo><Bar /></Foo>;
1531
var treeAfter = {
1532
displayName: 'Foo',
1301
- children: [{
1302
- displayName: 'Bar',
1303
- children: [],
1304
- }],
1533
+ children: [
1534
+ {
1535
+ displayName: 'Bar',
1536
+ children: [],
1537
+ },
1538
+ ],
1539
};
1540
1541
assertTreeMatches([
@@ -1315,17 +1549,19 @@ describeStack('ReactComponentTreeHook', () => {
1549
return null;
1550
}
1551
1318
- function Foo({ children }) {
1552
+ function Foo({children}) {
1553
return children;
1554
}
1555
1556
var elementBefore = <Foo><Bar /></Foo>;
1557
var treeBefore = {
1558
displayName: 'Foo',
1325
- children: [{
1326
- displayName: 'Bar',
1327
- children: [],
1328
- }],
1559
+ children: [
1560
+ {
1561
+ displayName: 'Bar',
1562
+ children: [],
1563
+ },
1564
+ ],
1565
};
1566
1567
var elementAfter = <Foo>{null}</Foo>;
@@ -1352,19 +1588,23 @@ describeStack('ReactComponentTreeHook', () => {
1588
var elementBefore = <Foo><View /></Foo>;
1589
var treeBefore = {
1590
displayName: 'Foo',
1355
- children: [{
1356
- displayName: 'View',
1357
- children: [],
1358
- }],
1591
+ children: [
1592
+ {
1593
+ displayName: 'View',
1594
+ children: [],
1595
+ },
1596
+ ],
1597
};
1598
1599
var elementAfter = <Foo><Image /></Foo>;
1600
var treeAfter = {
1601
displayName: 'Foo',
1364
- children: [{
1365
- displayName: 'Image',
1366
- children: [],
1367
- }],
1602
+ children: [
1603
+ {
1604
+ displayName: 'Image',
1605
+ children: [],
1606
+ },
1607
+ ],
1608
};
1609
1610
assertTreeMatches([
@@ -1389,10 +1629,12 @@ describeStack('ReactComponentTreeHook', () => {
1629
var elementAfter = <Foo><View /></Foo>;
1630
var treeAfter = {
1631
displayName: 'Foo',
1392
- children: [{
1393
- displayName: 'View',
1394
- children: [],
1395
- }],
1632
+ children: [
1633
+ {
1634
+ displayName: 'View',
1635
+ children: [],
1636
+ },
1637
+ ],
1638
};
1639
1640
assertTreeMatches([
@@ -1411,10 +1653,12 @@ describeStack('ReactComponentTreeHook', () => {
1653
var elementBefore = <Foo><View /></Foo>;
1654
var treeBefore = {
1655
displayName: 'Foo',
1414
- children: [{
1415
- displayName: 'View',
1416
- children: [],
1417
- }],
1656
+ children: [
1657
+ {
1658
+ displayName: 'View',
1659
+ children: [],
1660
+ },
1661
+ ],
1662
};
1663
1664
var elementAfter = <Foo>{null}</Foo>;
@@ -1445,19 +1689,23 @@ describeStack('ReactComponentTreeHook', () => {
1689
var elementBefore = <Foo><View /></Foo>;
1690
var treeBefore = {
1691
displayName: 'Foo',
1448
- children: [{
1449
- displayName: 'View',
1450
- children: [],
1451
- }],
1692
+ children: [
1693
+ {
1694
+ displayName: 'View',
1695
+ children: [],
1696
+ },
1697
+ ],
1698
};
1699
1700
var elementAfter = <Foo><Bar /></Foo>;
1701
var treeAfter = {
1702
displayName: 'Foo',
1457
- children: [{
1458
- displayName: 'Bar',
1459
- children: [],
1460
- }],
1703
+ children: [
1704
+ {
1705
+ displayName: 'Bar',
1706
+ children: [],
1707
+ },
1708
+ ],
1709
};
1710
1711
assertTreeMatches([
@@ -1482,19 +1730,23 @@ describeStack('ReactComponentTreeHook', () => {
1730
var elementBefore = <Foo><Bar /></Foo>;
1731
var treeBefore = {
1732
displayName: 'Foo',
1485
- children: [{
1486
- displayName: 'Bar',
1487
- children: [],
1488
- }],
1733
+ children: [
1734
+ {
1735
+ displayName: 'Bar',
1736
+ children: [],
1737
+ },
1738
+ ],
1739
};
1740
1741
var elementAfter = <Foo><View /></Foo>;
1742
var treeAfter = {
1743
displayName: 'Foo',
1494
- children: [{
1495
- displayName: 'View',
1496
- children: [],
1497
- }],
1744
+ children: [
1745
+ {
1746
+ displayName: 'View',
1747
+ children: [],
1748
+ },
1749
+ ],
1750
};
1751
1752
assertTreeMatches([
@@ -1525,10 +1777,12 @@ describeStack('ReactComponentTreeHook', () => {
1777
var elementAfter = <Foo><Bar /></Foo>;
1778
var treeAfter = {
1779
displayName: 'Foo',
1528
- children: [{
1529
- displayName: 'Bar',
1530
- children: [],
1531
- }],
1780
+ children: [
1781
+ {
1782
+ displayName: 'Bar',
1783
+ children: [],
1784
+ },
1785
+ ],
1786
};
1787
1788
assertTreeMatches([
@@ -1553,10 +1807,12 @@ describeStack('ReactComponentTreeHook', () => {
1807
var elementBefore = <Foo><Bar /></Foo>;
1808
var treeBefore = {
1809
displayName: 'Foo',
1556
- children: [{
1557
- displayName: 'Bar',
1558
- children: [],
1559
- }],
1810
+ children: [
1811
+ {
1812
+ displayName: 'Bar',
1813
+ children: [],
1814
+ },
1815
+ ],
1816
};
1817
1818
var elementAfter = <Foo>{null}</Foo>;
@@ -1588,40 +1844,57 @@ describeStack('ReactComponentTreeHook', () => {
1844
var element = <View><Foo /></View>;
1845
var tree = {
1846
displayName: 'View',
1591
- children: [{
1592
- displayName: 'Foo',
1593
- children: [{
1594
- displayName: 'Bar',
1595
- ownerDisplayName: 'Foo',
1596
- children: [{
1597
- displayName: 'View',
1598
- ownerDisplayName: 'Bar',
1599
- children: [{
1600
- displayName: 'Text',
1847
+ children: [
1848
+ {
1849
+ displayName: 'Foo',
1850
+ children: [
1851
+ {
1852
+ displayName: 'Bar',
1853
ownerDisplayName: 'Foo',
1602
- children: [{
1603
- displayName: 'RCText',
1604
- ownerDisplayName: 'Text',
1605
- children: [{
1606
- displayName: '#text',
1607
- text: 'Hi.',
1608
- }],
1609
- }],
1610
- }, {
1611
- displayName: 'Text',
1612
- ownerDisplayName: 'Bar',
1613
- children: [{
1614
- displayName: 'RCText',
1615
- ownerDisplayName: 'Text',
1616
- children: [{
1617
- displayName: '#text',
1618
- text: 'Mom',
1619
- }],
1620
- }],
1621
- }],
1622
- }],
1623
- }],
1624
- }],
1854
+ children: [
1855
+ {
1856
+ displayName: 'View',
1857
+ ownerDisplayName: 'Bar',
1858
+ children: [
1859
+ {
1860
+ displayName: 'Text',
1861
+ ownerDisplayName: 'Foo',
1862
+ children: [
1863
+ {
1864
+ displayName: 'RCText',
1865
+ ownerDisplayName: 'Text',
1866
+ children: [
1867
+ {
1868
+ displayName: '#text',
1869
+ text: 'Hi.',
1870
+ },
1871
+ ],
1872
+ },
1873
+ ],
1874
+ },
1875
+ {
1876
+ displayName: 'Text',
1877
+ ownerDisplayName: 'Bar',
1878
+ children: [
1879
+ {
1880
+ displayName: 'RCText',
1881
+ ownerDisplayName: 'Text',
1882
+ children: [
1883
+ {
1884
+ displayName: '#text',
1885
+ text: 'Mom',
1886
+ },
1887
+ ],
1888
+ },
1889
+ ],
1890
+ },
1891
+ ],
1892
+ },
1893
+ ],
1894
+ },
1895
+ ],
1896
+ },
1897
+ ],
1898
};
1899
assertTreeMatches([element, tree], {includeOwnerDisplayName: true});
1900
});
@@ -1646,27 +1919,39 @@ describeStack('ReactComponentTreeHook', () => {
1919
}
1920
1921
ReactNative.render(<Foo />, 1);
1649
- ReactComponentTreeTestUtils.expectTree(barInstance._debugID, {
1650
- displayName: 'Bar',
1651
- parentDisplayName: 'Foo',
1652
- parentID: fooInstance._debugID,
1653
- children: [],
1654
- }, 'Foo');
1922
+ ReactComponentTreeTestUtils.expectTree(
1923
+ barInstance._debugID,
1924
+ {
1925
+ displayName: 'Bar',
1926
+ parentDisplayName: 'Foo',
1927
+ parentID: fooInstance._debugID,
1928
+ children: [],
1929
+ },
1930
+ 'Foo',
1931
+ );
1932
1933
renderBar = false;
1934
ReactNative.render(<Foo />, 1);
1658
- ReactComponentTreeTestUtils.expectTree(barInstance._debugID, {
1659
- displayName: 'Unknown',
1660
- children: [],
1661
- parentID: null,
1662
- }, 'Foo');
1935
+ ReactComponentTreeTestUtils.expectTree(
1936
+ barInstance._debugID,
1937
+ {
1938
+ displayName: 'Unknown',
1939
+ children: [],
1940
+ parentID: null,
1941
+ },
1942
+ 'Foo',
1943
+ );
1944
1945
ReactNative.unmountComponentAtNode(1);
1665
- ReactComponentTreeTestUtils.expectTree(barInstance._debugID, {
1666
- displayName: 'Unknown',
1667
- children: [],
1668
- parentID: null,
1669
- }, 'Foo');
1946
+ ReactComponentTreeTestUtils.expectTree(
1947
+ barInstance._debugID,
1948
+ {
1949
+ displayName: 'Unknown',
1950
+ children: [],
1951
+ parentID: null,
1952
+ },
1953
+ 'Foo',
1954
+ );
1955
});
1956
1957
it('reports update counts', () => {
@@ -1694,13 +1979,18 @@ describeStack('ReactComponentTreeHook', () => {
1979
1980
it('does not report top-level wrapper as a root', () => {
1981
ReactNative.render(<View><Image /></View>, 1);
1697
- expectDev(ReactComponentTreeTestUtils.getRootDisplayNames()).toEqual(['View']);
1982
+ expectDev(ReactComponentTreeTestUtils.getRootDisplayNames()).toEqual([
1983
+ 'View',
1984
+ ]);
1985
1986
ReactNative.render(<View><Text /></View>, 1);
1700
- expectDev(ReactComponentTreeTestUtils.getRootDisplayNames()).toEqual(['View']);
1987
+ expectDev(ReactComponentTreeTestUtils.getRootDisplayNames()).toEqual([
1988
+ 'View',
1989
+ ]);
1990
1991
ReactNative.unmountComponentAtNode(1);
1992
expectDev(ReactComponentTreeTestUtils.getRootDisplayNames()).toEqual([]);
1704
- expectDev(ReactComponentTreeTestUtils.getRegisteredDisplayNames()).toEqual([]);
1993
+ expectDev(ReactComponentTreeTestUtils.getRegisteredDisplayNames()).toEqual([
1994
+ ]);
1995
});
1996
});
src/renderers/__tests__/ReactCompositeComponent-test.js
+48
-50
@@ -22,7 +22,6 @@ var ReactPropTypes;
22
var ReactTestUtils;
23
24
describe('ReactCompositeComponent', () => {
25
-
25
beforeEach(() => {
26
jest.resetModules();
27
React = require('react');
@@ -42,9 +41,9 @@ describe('ReactCompositeComponent', () => {
41
42
render() {
43
var toggleActivatedState = this._toggleActivatedState;
45
- return !this.state.activated ?
46
- <a ref="x" onClick={toggleActivatedState} /> :
47
- <b ref="x" onClick={toggleActivatedState} />;
44
+ return !this.state.activated
45
+ ? <a ref="x" onClick={toggleActivatedState} />
46
+ : <b ref="x" onClick={toggleActivatedState} />;
47
}
48
};
49
@@ -59,9 +58,9 @@ describe('ReactCompositeComponent', () => {
58
59
render() {
60
var className = this.props.anchorClassOn ? 'anchorClass' : '';
62
- return this.props.renderAnchor ?
63
- <a ref="anch" className={className} /> :
64
- <b />;
61
+ return this.props.renderAnchor
62
+ ? <a ref="anch" className={className} />
63
+ : <b />;
64
}
65
};
66
});
@@ -139,19 +138,22 @@ describe('ReactCompositeComponent', () => {
138
var container = document.createElement('div');
139
var instance = ReactDOM.render(
140
<ChildUpdates renderAnchor={true} anchorClassOn={false} />,
142
- container
141
+ container,
142
);
144
- ReactDOM.render( // Warm any cache
143
+ ReactDOM.render(
144
+ // Warm any cache
145
<ChildUpdates renderAnchor={true} anchorClassOn={true} />,
146
- container
146
+ container,
147
);
148
- ReactDOM.render( // Clear out the anchor
148
+ ReactDOM.render(
149
+ // Clear out the anchor
150
<ChildUpdates renderAnchor={false} anchorClassOn={true} />,
150
- container
151
+ container,
152
);
152
- ReactDOM.render( // rerender
153
+ ReactDOM.render(
154
+ // rerender
155
<ChildUpdates renderAnchor={true} anchorClassOn={false} />,
154
- container
156
+ container,
157
);
158
expect(instance.getAnchor().className).toBe('');
159
});
@@ -188,7 +190,7 @@ describe('ReactCompositeComponent', () => {
190
191
expectDev(console.error.calls.count()).toBe(1);
192
var explicitlyBound = mountedInstance.methodToBeExplicitlyBound.bind(
191
- mountedInstance
193
+ mountedInstance,
194
);
195
expectDev(console.error.calls.count()).toBe(2);
196
var autoBound = mountedInstance.methodAutoBound;
@@ -199,7 +201,6 @@ describe('ReactCompositeComponent', () => {
201
202
expect(explicitlyBound.call(mountedInstance)).toBe(mountedInstance);
203
expect(autoBound.call(mountedInstance)).toBe(mountedInstance);
202
-
204
});
205
206
it('should not pass this to getDefaultProps', () => {
@@ -227,10 +228,14 @@ describe('ReactCompositeComponent', () => {
228
var instance1 = ReactTestUtils.renderIntoDocument(<Component />);
229
expect(instance1.props).toEqual({prop: 'testKey'});
230
230
- var instance2 = ReactTestUtils.renderIntoDocument(<Component prop={undefined} />);
231
+ var instance2 = ReactTestUtils.renderIntoDocument(
232
+ <Component prop={undefined} />,
233
+ );
234
expect(instance2.props).toEqual({prop: 'testKey'});
235
233
- var instance3 = ReactTestUtils.renderIntoDocument(<Component prop={null} />);
236
+ var instance3 = ReactTestUtils.renderIntoDocument(
237
+ <Component prop={null} />,
238
+ );
239
expect(instance3.props).toEqual({prop: null});
240
});
241
@@ -279,9 +284,9 @@ describe('ReactCompositeComponent', () => {
284
expectDev(console.error.calls.count()).toBe(1);
285
expectDev(console.error.calls.argsFor(0)[0]).toContain(
286
'Can only update a mounted or mounting component. This usually means ' +
282
- 'you called setState, replaceState, or forceUpdate on an unmounted ' +
283
- 'component. This is a no-op.\n\nPlease check the code for the ' +
284
- 'Component component.'
287
+ 'you called setState, replaceState, or forceUpdate on an unmounted ' +
288
+ 'component. This is a no-op.\n\nPlease check the code for the ' +
289
+ 'Component component.',
290
);
291
});
292
@@ -323,9 +328,9 @@ describe('ReactCompositeComponent', () => {
328
expectDev(console.error.calls.count()).toBe(1);
329
expectDev(console.error.calls.argsFor(0)[0]).toContain(
330
'Can only update a mounted or mounting component. This usually means ' +
326
- 'you called setState, replaceState, or forceUpdate on an unmounted ' +
327
- 'component. This is a no-op.\n\nPlease check the code for the ' +
328
- 'Component component.'
331
+ 'you called setState, replaceState, or forceUpdate on an unmounted ' +
332
+ 'component. This is a no-op.\n\nPlease check the code for the ' +
333
+ 'Component component.',
334
);
335
});
336
@@ -357,7 +362,6 @@ describe('ReactCompositeComponent', () => {
362
expect(cbCalled).toBe(false);
363
});
364
360
-
365
it('should warn about `setState` in render', () => {
366
spyOn(console, 'error');
367
@@ -373,7 +377,7 @@ describe('ReactCompositeComponent', () => {
377
renderPasses++;
378
renderedState = this.state.value;
379
if (this.state.value === 0) {
376
- this.setState({ value: 1 });
380
+ this.setState({value: 1});
381
}
382
return <div />;
383
}
@@ -386,9 +390,9 @@ describe('ReactCompositeComponent', () => {
390
expectDev(console.error.calls.count()).toBe(1);
391
expectDev(console.error.calls.argsFor(0)[0]).toContain(
392
'Cannot update during an existing state transition (such as within ' +
389
- '`render` or another component\'s constructor). Render methods should ' +
390
- 'be a pure function of props and state; constructor side-effects are ' +
391
- 'an anti-pattern, but can be moved to `componentWillMount`.'
393
+ "`render` or another component's constructor). Render methods should " +
394
+ 'be a pure function of props and state; constructor side-effects are ' +
395
+ 'an anti-pattern, but can be moved to `componentWillMount`.',
396
);
397
398
// The setState call is queued and then executed as a second pass. This
@@ -417,7 +421,7 @@ describe('ReactCompositeComponent', () => {
421
422
getChildContext() {
423
if (this.state.value === 0) {
420
- this.setState({ value: 1 });
424
+ this.setState({value: 1});
425
}
426
}
427
@@ -434,7 +438,7 @@ describe('ReactCompositeComponent', () => {
438
expect(instance.state.value).toBe(1);
439
expectDev(console.error.calls.count()).toBe(1);
440
expectDev(console.error.calls.argsFor(0)[0]).toBe(
437
- 'Warning: setState(...): Cannot call setState() inside getChildContext()'
441
+ 'Warning: setState(...): Cannot call setState() inside getChildContext()',
442
);
443
});
444
@@ -507,7 +511,7 @@ describe('ReactCompositeComponent', () => {
511
expectDev(console.error.calls.count()).toBe(1);
512
expectDev(console.error.calls.argsFor(0)[0]).toBe(
513
'Warning: Component.shouldComponentUpdate(): Returned undefined instead of a ' +
510
- 'boolean value. Make sure to return true or false.'
514
+ 'boolean value. Make sure to return true or false.',
515
);
516
});
517
@@ -515,8 +519,7 @@ describe('ReactCompositeComponent', () => {
519
spyOn(console, 'error');
520
521
class Component extends React.Component {
518
- componentDidUnmount = () => {
519
- };
522
+ componentDidUnmount = () => {};
523
524
render() {
525
return <div />;
@@ -528,8 +531,8 @@ describe('ReactCompositeComponent', () => {
531
expectDev(console.error.calls.count()).toBe(1);
532
expectDev(console.error.calls.argsFor(0)[0]).toBe(
533
'Warning: Component has a method called ' +
531
- 'componentDidUnmount(). But there is no such lifecycle method. ' +
532
- 'Did you mean componentWillUnmount()?'
534
+ 'componentDidUnmount(). But there is no such lifecycle method. ' +
535
+ 'Did you mean componentWillUnmount()?',
536
);
537
});
538
@@ -639,7 +642,7 @@ describe('ReactCompositeComponent', () => {
642
}
643
644
parentInstance = ReactTestUtils.renderIntoDocument(
642
- <Parent><Middle><Child /></Middle></Parent>
645
+ <Parent><Middle><Child /></Middle></Parent>,
646
);
647
648
expect(parentInstance.state.flag).toBe(false);
@@ -691,10 +694,7 @@ describe('ReactCompositeComponent', () => {
694
}
695
}
696
694
-
695
- var wrapper = ReactTestUtils.renderIntoDocument(
696
- <Wrapper />
697
- );
697
+ var wrapper = ReactTestUtils.renderIntoDocument(<Wrapper />);
698
699
expect(wrapper.refs.parent.state.flag).toEqual(true);
700
expect(wrapper.refs.child.context).toEqual({flag: true});
@@ -999,7 +999,7 @@ describe('ReactCompositeComponent', () => {
999
<GrandChild>B2</GrandChild>
1000
</ChildWithContext>
1001
</Parent>,
1002
- div
1002
+ div,
1003
);
1004
1005
parentInstance.setState({
@@ -1030,9 +1030,9 @@ describe('ReactCompositeComponent', () => {
1030
expectDev(console.error.calls.count()).toBe(1);
1031
expectDev(console.error.calls.argsFor(0)[0]).toMatch(
1032
'Render methods should be a pure function of props and state; ' +
1033
- 'triggering nested component updates from render is not allowed. If ' +
1034
- 'necessary, trigger nested updates in componentDidUpdate.\n\nCheck the ' +
1035
- 'render method of Outer.'
1033
+ 'triggering nested component updates from render is not allowed. If ' +
1034
+ 'necessary, trigger nested updates in componentDidUpdate.\n\nCheck the ' +
1035
+ 'render method of Outer.',
1036
);
1037
});
1038
@@ -1295,7 +1295,7 @@ describe('ReactCompositeComponent', () => {
1295
1296
class Foo extends React.Component {
1297
constructor(props) {
1298
- var _props = { idx: props.idx + '!' };
1298
+ var _props = {idx: props.idx + '!'};
1299
super(_props);
1300
}
1301
@@ -1311,9 +1311,8 @@ describe('ReactCompositeComponent', () => {
1311
expectDev(console.error.calls.count()).toBe(1);
1312
expectDev(console.error.calls.argsFor(0)[0]).toContain(
1313
'Foo(...): When calling super() in `Foo`, make sure to pass ' +
1314
- 'up the same props that your component\'s constructor was passed.'
1314
+ "up the same props that your component's constructor was passed.",
1315
);
1316
-
1316
});
1317
1318
it('should only call componentWillUnmount once', () => {
@@ -1344,7 +1343,7 @@ describe('ReactCompositeComponent', () => {
1343
1344
var container = document.createElement('div');
1345
1347
- var setRef = (ref) => {
1346
+ var setRef = ref => {
1347
if (ref) {
1348
app = ref;
1349
}
@@ -1397,5 +1396,4 @@ describe('ReactCompositeComponent', () => {
1396
'B componentDidMount',
1397
]);
1398
});
1400
-
1399
});
src/renderers/__tests__/ReactCompositeComponentDOMMinimalism-test.js
-2
@@ -28,7 +28,6 @@ var expectSingleChildlessDiv;
28
* nodes.
29
*/
30
describe('ReactCompositeComponentDOMMinimalism', () => {
31
-
31
beforeEach(() => {
32
React = require('react');
33
ReactDOM = require('react-dom');
@@ -96,5 +95,4 @@ describe('ReactCompositeComponentDOMMinimalism', () => {
95
expect(el.children[0].tagName).toBe('UL');
96
expect(el.children[0].children.length).toBe(0);
97
});
99
-
98
});
src/renderers/__tests__/ReactCompositeComponentNestedState-test.js
+21
-16
@@ -16,7 +16,6 @@ var ReactDOM;
16
var ReactTestUtils;
17
18
describe('ReactCompositeComponentNestedState-state', () => {
19
-
19
beforeEach(() => {
20
React = require('react');
21
ReactDOM = require('react-dom');
@@ -27,7 +26,7 @@ describe('ReactCompositeComponentNestedState-state', () => {
26
class ParentComponent extends React.Component {
27
state = {color: 'blue'};
28
30
- handleColor = (color) => {
29
+ handleColor = color => {
30
this.props.logger('parent-handleColor', this.state.color);
31
this.setState({color: color}, function() {
32
this.props.logger('parent-after-setState', this.state.color);
@@ -56,13 +55,24 @@ describe('ReactCompositeComponentNestedState-state', () => {
55
handleHue = (shade, color) => {
56
this.props.logger('handleHue', this.state.hue, this.props.color);
57
this.props.onSelectColor(color);
59
- this.setState(function(state, props) {
60
- this.props.logger('setState-this', this.state.hue, this.props.color);
61
- this.props.logger('setState-args', state.hue, props.color);
62
- return {hue: shade + ' ' + props.color};
63
- }, function() {
64
- this.props.logger('after-setState', this.state.hue, this.props.color);
65
- });
58
+ this.setState(
59
+ function(state, props) {
60
+ this.props.logger(
61
+ 'setState-this',
62
+ this.state.hue,
63
+ this.props.color,
64
+ );
65
+ this.props.logger('setState-args', state.hue, props.color);
66
+ return {hue: shade + ' ' + props.color};
67
+ },
68
+ function() {
69
+ this.props.logger(
70
+ 'after-setState',
71
+ this.state.hue,
72
+ this.props.color,
73
+ );
74
+ },
75
+ );
76
};
77
78
render() {
@@ -91,15 +101,10 @@ describe('ReactCompositeComponentNestedState-state', () => {
101
102
var logger = jest.fn();
103
94
- void ReactDOM.render(
95
- <ParentComponent logger={logger} />,
96
- container
97
- );
104
+ void ReactDOM.render(<ParentComponent logger={logger} />, container);
105
106
// click "light green"
100
- ReactTestUtils.Simulate.click(
101
- container.childNodes[0].childNodes[3]
102
- );
107
+ ReactTestUtils.Simulate.click(container.childNodes[0].childNodes[3]);
108
109
expect(logger.mock.calls).toEqual([
110
['parent-render', 'blue'],
src/renderers/__tests__/ReactCompositeComponentState-test.js
+40
-45
@@ -18,7 +18,6 @@ var ReactDOMFeatureFlags;
18
var TestComponent;
19
20
describe('ReactCompositeComponent-state', () => {
21
-
21
beforeEach(() => {
22
React = require('react');
23
@@ -38,7 +37,7 @@ describe('ReactCompositeComponent-state', () => {
37
setFavoriteColor: function(nextColor) {
38
this.setState(
39
{color: nextColor},
41
- this.peekAtCallback('setFavoriteColor')
40
+ this.peekAtCallback('setFavoriteColor'),
41
);
42
},
43
@@ -59,7 +58,7 @@ describe('ReactCompositeComponent-state', () => {
58
});
59
this.setState(
60
{color: 'sunrise'},
62
- this.peekAtCallback('setState-sunrise')
61
+ this.peekAtCallback('setState-sunrise'),
62
);
63
this.setState(function(state) {
64
this.peekAtState('after-setState-sunrise', state);
@@ -67,7 +66,7 @@ describe('ReactCompositeComponent-state', () => {
66
this.peekAtState('componentWillMount-after-sunrise');
67
this.setState(
68
{color: 'orange'},
70
- this.peekAtCallback('setState-orange')
69
+ this.peekAtCallback('setState-orange'),
70
);
71
this.setState(function(state) {
72
this.peekAtState('after-setState-orange', state);
@@ -79,7 +78,7 @@ describe('ReactCompositeComponent-state', () => {
78
this.peekAtState('componentDidMount-start');
79
this.setState(
80
{color: 'yellow'},
82
- this.peekAtCallback('setState-yellow')
81
+ this.peekAtCallback('setState-yellow'),
82
);
83
this.peekAtState('componentDidMount-end');
84
},
@@ -97,7 +96,7 @@ describe('ReactCompositeComponent-state', () => {
96
this.peekAtState('before-setState-again-receiveProps', state);
97
return {color: newProps.nextColor};
98
},
100
- this.peekAtCallback('setState-receiveProps')
99
+ this.peekAtCallback('setState-receiveProps'),
100
);
101
this.setState(function(state) {
102
this.peekAtState('after-setState-receiveProps', state);
@@ -138,12 +137,12 @@ describe('ReactCompositeComponent-state', () => {
137
container,
138
function peekAtInitialCallback() {
139
this.peekAtState('initial-callback');
141
- }
140
+ },
141
);
142
ReactDOM.render(
143
<TestComponent stateListener={stateListener} nextColor="green" />,
144
container,
146
- instance.peekAtCallback('setProps')
145
+ instance.peekAtCallback('setProps'),
146
);
147
instance.setFavoriteColor('blue');
148
instance.forceUpdate(instance.peekAtCallback('forceUpdate'));
@@ -191,9 +190,7 @@ describe('ReactCompositeComponent-state', () => {
190
// from the queue. In Fiber, we keep updates in the queue to support
191
// replaceState(prevState => newState).
192
// TODO: Fix Stack to match Fiber.
194
- expected.push(
195
- ['before-setState-receiveProps', 'yellow'],
196
- );
193
+ expected.push(['before-setState-receiveProps', 'yellow']);
194
}
195
196
expected.push(
@@ -232,7 +229,6 @@ describe('ReactCompositeComponent-state', () => {
229
expect(stateListener.mock.calls.join('\n')).toEqual(expected.join('\n'));
230
});
231
235
-
232
it('should call componentDidUpdate of children first', () => {
233
var container = document.createElement('div');
234
@@ -242,7 +238,7 @@ describe('ReactCompositeComponent-state', () => {
238
var parent = null;
239
240
class Child extends React.Component {
245
- state = {bar:false};
241
+ state = {bar: false};
242
componentDidMount() {
243
child = this;
244
}
@@ -266,7 +262,7 @@ describe('ReactCompositeComponent-state', () => {
262
}
263
264
class Parent extends React.Component {
269
- state = {foo:false};
265
+ state = {foo: false};
266
componentDidMount() {
267
parent = this;
268
}
@@ -281,40 +277,36 @@ describe('ReactCompositeComponent-state', () => {
277
ReactDOM.render(<Parent />, container);
278
279
ReactDOM.unstable_batchedUpdates(() => {
284
- parent.setState({ foo: true });
285
- child.setState({ bar: true });
280
+ parent.setState({foo: true});
281
+ child.setState({bar: true});
282
});
283
// When we render changes top-down in a batch, children's componentDidUpdate
284
// happens before the parent.
289
- expect(ops).toEqual([
290
- 'child did update',
291
- 'parent did update',
292
- ]);
285
+ expect(ops).toEqual(['child did update', 'parent did update']);
286
287
shouldUpdate = false;
288
289
ops = [];
290
291
ReactDOM.unstable_batchedUpdates(() => {
299
- parent.setState({ foo: false });
300
- child.setState({ bar: false });
292
+ parent.setState({foo: false});
293
+ child.setState({bar: false});
294
});
295
// We expect the same thing to happen if we bail out in the middle.
296
expect(ops).toEqual(
297
ReactDOMFeatureFlags.useFiber
298
? [
306
- // Fiber works as expected
307
- 'child did update',
308
- 'parent did update',
309
- ]
299
+ // Fiber works as expected
300
+ 'child did update',
301
+ 'parent did update',
302
+ ]
303
: [
311
- // Stack treats these as two separate updates and therefore the order
312
- // is inverse.
313
- 'parent did update',
314
- 'child did update',
315
- ]
304
+ // Stack treats these as two separate updates and therefore the order
305
+ // is inverse.
306
+ 'parent did update',
307
+ 'child did update',
308
+ ],
309
);
317
-
310
});
311
312
it('should batch unmounts', () => {
@@ -396,8 +388,10 @@ describe('ReactCompositeComponent-state', () => {
388
}
389
shouldComponentUpdate(nextProps, nextState) {
390
log.push(
399
- 'scu from ' + Object.keys(this.state) +
400
- ' to ' + Object.keys(nextState)
391
+ 'scu from ' +
392
+ Object.keys(this.state) +
393
+ ' to ' +
394
+ Object.keys(nextState),
395
);
396
return false;
397
}
@@ -409,10 +403,7 @@ describe('ReactCompositeComponent-state', () => {
403
expect(log.length).toBe(1);
404
test.setState({c: 0});
405
expect(log.length).toBe(2);
412
- expect(log).toEqual([
413
- 'scu from a to a,b',
414
- 'scu from a,b to a,b,c',
415
- ]);
406
+ expect(log).toEqual(['scu from a to a,b', 'scu from a,b to a,b,c']);
407
});
408
409
it('should treat assigning to this.state inside cWRP as a replaceState, with a warning', () => {
@@ -420,17 +411,21 @@ describe('ReactCompositeComponent-state', () => {
411
412
let ops = [];
413
class Test extends React.Component {
423
- state = { step: 1, extra: true };
414
+ state = {step: 1, extra: true};
415
componentWillReceiveProps() {
425
- this.setState({ step: 2 }, () => {
416
+ this.setState({step: 2}, () => {
417
// Tests that earlier setState callbacks are not dropped
427
- ops.push(`callback -- step: ${this.state.step}, extra: ${!!this.state.extra}`);
418
+ ops.push(
419
+ `callback -- step: ${this.state.step}, extra: ${!!this.state.extra}`,
420
+ );
421
});
422
// Treat like replaceState
430
- this.state = { step: 3 };
423
+ this.state = {step: 3};
424
}
425
render() {
433
- ops.push(`render -- step: ${this.state.step}, extra: ${!!this.state.extra}`);
426
+ ops.push(
427
+ `render -- step: ${this.state.step}, extra: ${!!this.state.extra}`,
428
+ );
429
return null;
430
}
431
}
@@ -449,8 +444,8 @@ describe('ReactCompositeComponent-state', () => {
444
expect(console.error.calls.count()).toEqual(1);
445
expect(console.error.calls.argsFor(0)[0]).toEqual(
446
'Warning: Test.componentWillReceiveProps(): Assigning directly to ' +
452
- 'this.state is deprecated (except inside a component\'s constructor). ' +
453
- 'Use setState instead.'
447
+ "this.state is deprecated (except inside a component's constructor). " +
448
+ 'Use setState instead.',
449
);
450
});
451
});
src/renderers/__tests__/ReactEmptyComponent-test.js
+41
-58
@@ -80,21 +80,17 @@ describe('ReactEmptyComponent', () => {
80
ReactTestUtils.renderIntoDocument(<Component />);
81
}).toThrowError(
82
'Component.render(): A valid React element (or null) must be returned. You may ' +
83
- 'have returned undefined, an array or some other invalid object.'
83
+ 'have returned undefined, an array or some other invalid object.',
84
);
85
});
86
87
it('should be able to switch between rendering null and a normal tag', () => {
88
- var instance1 =
89
- <TogglingComponent
90
- firstComponent={null}
91
- secondComponent={'div'}
92
- />;
93
- var instance2 =
94
- <TogglingComponent
95
- firstComponent={'div'}
96
- secondComponent={null}
97
- />;
88
+ var instance1 = (
89
+ <TogglingComponent firstComponent={null} secondComponent={'div'} />
90
+ );
91
+ var instance2 = (
92
+ <TogglingComponent firstComponent={'div'} secondComponent={null} />
93
+ );
94
95
ReactTestUtils.renderIntoDocument(instance1);
96
ReactTestUtils.renderIntoDocument(instance2);
@@ -107,18 +103,16 @@ describe('ReactEmptyComponent', () => {
103
});
104
105
it('should be able to switch in a list of children', () => {
110
- var instance1 =
111
- <TogglingComponent
112
- firstComponent={null}
113
- secondComponent={'div'}
114
- />;
106
+ var instance1 = (
107
+ <TogglingComponent firstComponent={null} secondComponent={'div'} />
108
+ );
109
110
ReactTestUtils.renderIntoDocument(
111
<div>
112
{instance1}
113
{instance1}
114
{instance1}
121
- </div>
115
+ </div>,
116
);
117
118
expect(log.calls.count()).toBe(6);
@@ -130,36 +124,31 @@ describe('ReactEmptyComponent', () => {
124
expect(log.calls.argsFor(5)[0].tagName).toBe('DIV');
125
});
126
133
- it('should distinguish between a script placeholder and an actual script tag',
134
- () => {
135
- var instance1 =
136
- <TogglingComponent
137
- firstComponent={null}
138
- secondComponent={'script'}
139
- />;
140
- var instance2 =
141
- <TogglingComponent
142
- firstComponent={'script'}
143
- secondComponent={null}
144
- />;
127
+ it('should distinguish between a script placeholder and an actual script tag', () => {
128
+ var instance1 = (
129
+ <TogglingComponent firstComponent={null} secondComponent={'script'} />
130
+ );
131
+ var instance2 = (
132
+ <TogglingComponent firstComponent={'script'} secondComponent={null} />
133
+ );
134
146
- expect(function() {
147
- ReactTestUtils.renderIntoDocument(instance1);
148
- }).not.toThrow();
149
- expect(function() {
150
- ReactTestUtils.renderIntoDocument(instance2);
151
- }).not.toThrow();
135
+ expect(function() {
136
+ ReactTestUtils.renderIntoDocument(instance1);
137
+ }).not.toThrow();
138
+ expect(function() {
139
+ ReactTestUtils.renderIntoDocument(instance2);
140
+ }).not.toThrow();
141
153
- expect(log.calls.count()).toBe(4);
154
- expect(log.calls.argsFor(0)[0]).toBe(null);
155
- expect(log.calls.argsFor(1)[0].tagName).toBe('SCRIPT');
156
- expect(log.calls.argsFor(2)[0].tagName).toBe('SCRIPT');
157
- expect(log.calls.argsFor(3)[0]).toBe(null);
158
- }
159
- );
142
+ expect(log.calls.count()).toBe(4);
143
+ expect(log.calls.argsFor(0)[0]).toBe(null);
144
+ expect(log.calls.argsFor(1)[0].tagName).toBe('SCRIPT');
145
+ expect(log.calls.argsFor(2)[0].tagName).toBe('SCRIPT');
146
+ expect(log.calls.argsFor(3)[0]).toBe(null);
147
+ });
148
161
- it('should have findDOMNode return null when multiple layers of composite ' +
162
- 'components render to the same null placeholder',
149
+ it(
150
+ 'should have findDOMNode return null when multiple layers of composite ' +
151
+ 'components render to the same null placeholder',
152
() => {
153
class GrandChild extends React.Component {
154
render() {
@@ -173,16 +162,12 @@ describe('ReactEmptyComponent', () => {
162
}
163
}
164
176
- var instance1 =
177
- <TogglingComponent
178
- firstComponent={'div'}
179
- secondComponent={Child}
180
- />;
181
- var instance2 =
182
- <TogglingComponent
183
- firstComponent={Child}
184
- secondComponent={'div'}
185
- />;
165
+ var instance1 = (
166
+ <TogglingComponent firstComponent={'div'} secondComponent={Child} />
167
+ );
168
+ var instance2 = (
169
+ <TogglingComponent firstComponent={Child} secondComponent={'div'} />
170
+ );
171
172
expect(function() {
173
ReactTestUtils.renderIntoDocument(instance1);
@@ -196,7 +181,7 @@ describe('ReactEmptyComponent', () => {
181
expect(log.calls.argsFor(1)[0]).toBe(null);
182
expect(log.calls.argsFor(2)[0]).toBe(null);
183
expect(log.calls.argsFor(3)[0].tagName).toBe('DIV');
199
- }
184
+ },
185
);
186
187
it('works when switching components', () => {
@@ -259,9 +244,7 @@ describe('ReactEmptyComponent', () => {
244
// Stack does not implement this.
245
expect(function() {
246
ReactDOM.render(null, div);
262
- }).toThrowError(
263
- 'ReactDOM.render(): Invalid component element.'
264
- );
247
+ }).toThrowError('ReactDOM.render(): Invalid component element.');
248
}
249
} finally {
250
ReactFeatureFlags.disableNewFiberFeatures = true;
src/renderers/__tests__/ReactErrorBoundaries-test.js
+489
-485
@@ -148,7 +148,9 @@ describe('ReactErrorBoundaries', () => {
148
log.push('BrokenComponentWillReceiveProps componentDidMount');
149
}
150
componentWillReceiveProps() {
151
- log.push('BrokenComponentWillReceiveProps componentWillReceiveProps [!]');
151
+ log.push(
152
+ 'BrokenComponentWillReceiveProps componentWillReceiveProps [!]',
153
+ );
154
throw new Error('Hello');
155
}
156
componentWillUpdate() {
@@ -273,7 +275,9 @@ describe('ReactErrorBoundaries', () => {
275
return <div>{this.props.children}</div>;
276
}
277
componentWillMount() {
276
- log.push('BrokenComponentWillMountErrorBoundary componentWillMount [!]');
278
+ log.push(
279
+ 'BrokenComponentWillMountErrorBoundary componentWillMount [!]',
280
+ );
281
throw new Error('Hello');
282
}
283
componentDidMount() {
@@ -593,7 +597,7 @@ describe('ReactErrorBoundaries', () => {
597
<ErrorBoundary>
598
<BrokenRender />
599
</ErrorBoundary>,
596
- container3
600
+ container3,
601
);
602
expect(container1.firstChild.textContent).toBe('Before 1');
603
expect(container2.firstChild).toBe(null);
@@ -605,7 +609,7 @@ describe('ReactErrorBoundaries', () => {
609
<ErrorBoundary forceRetry={true}>
610
After 3
611
</ErrorBoundary>,
608
- container3
612
+ container3,
613
);
614
expect(container1.firstChild.textContent).toBe('After 1');
615
expect(container2.firstChild.textContent).toBe('After 2');
@@ -625,11 +629,9 @@ describe('ReactErrorBoundaries', () => {
629
<ErrorBoundary>
630
<BrokenRender />
631
</ErrorBoundary>,
628
- container
629
- );
630
- expect(container.firstChild.textContent).toBe(
631
- 'Caught an error: Hello.'
632
+ container,
633
);
634
+ expect(container.firstChild.textContent).toBe('Caught an error: Hello.');
635
expect(log).toEqual([
636
'ErrorBoundary constructor',
637
'ErrorBoundary componentWillMount',
@@ -637,27 +639,27 @@ describe('ReactErrorBoundaries', () => {
639
'BrokenRender constructor',
640
'BrokenRender componentWillMount',
641
'BrokenRender render [!]',
640
- ...(ReactDOMFeatureFlags.useFiber ? [
641
- // Fiber mounts with null children before capturing error
642
- 'ErrorBoundary componentDidMount',
643
- // Catch and render an error message
644
- 'ErrorBoundary unstable_handleError',
645
- 'ErrorBoundary componentWillUpdate',
646
- 'ErrorBoundary render error',
647
- 'ErrorBoundary componentDidUpdate',
648
- ] : [
649
- // Catch and render an error message
650
- 'ErrorBoundary unstable_handleError',
651
- 'ErrorBoundary render error',
652
- 'ErrorBoundary componentDidMount',
653
- ]),
642
+ ...(ReactDOMFeatureFlags.useFiber
643
+ ? [
644
+ // Fiber mounts with null children before capturing error
645
+ 'ErrorBoundary componentDidMount',
646
+ // Catch and render an error message
647
+ 'ErrorBoundary unstable_handleError',
648
+ 'ErrorBoundary componentWillUpdate',
649
+ 'ErrorBoundary render error',
650
+ 'ErrorBoundary componentDidUpdate',
651
+ ]
652
+ : [
653
+ // Catch and render an error message
654
+ 'ErrorBoundary unstable_handleError',
655
+ 'ErrorBoundary render error',
656
+ 'ErrorBoundary componentDidMount',
657
+ ]),
658
]);
659
660
log.length = 0;
661
ReactDOM.unmountComponentAtNode(container);
658
- expect(log).toEqual([
659
- 'ErrorBoundary componentWillUnmount',
660
- ]);
662
+ expect(log).toEqual(['ErrorBoundary componentWillUnmount']);
663
});
664
665
it('renders an error state if child throws in constructor', () => {
@@ -666,7 +668,7 @@ describe('ReactErrorBoundaries', () => {
668
<ErrorBoundary>
669
<BrokenConstructor />
670
</ErrorBoundary>,
669
- container
671
+ container,
672
);
673
expect(container.firstChild.textContent).toBe('Caught an error: Hello.');
674
expect(log).toEqual([
@@ -674,27 +676,27 @@ describe('ReactErrorBoundaries', () => {
676
'ErrorBoundary componentWillMount',
677
'ErrorBoundary render success',
678
'BrokenConstructor constructor [!]',
677
- ...(ReactDOMFeatureFlags.useFiber ? [
678
- // Fiber mounts with null children before capturing error
679
- 'ErrorBoundary componentDidMount',
680
- // Catch and render an error message
681
- 'ErrorBoundary unstable_handleError',
682
- 'ErrorBoundary componentWillUpdate',
683
- 'ErrorBoundary render error',
684
- 'ErrorBoundary componentDidUpdate',
685
- ] : [
686
- // Catch and render an error message
687
- 'ErrorBoundary unstable_handleError',
688
- 'ErrorBoundary render error',
689
- 'ErrorBoundary componentDidMount',
690
- ]),
679
+ ...(ReactDOMFeatureFlags.useFiber
680
+ ? [
681
+ // Fiber mounts with null children before capturing error
682
+ 'ErrorBoundary componentDidMount',
683
+ // Catch and render an error message
684
+ 'ErrorBoundary unstable_handleError',
685
+ 'ErrorBoundary componentWillUpdate',
686
+ 'ErrorBoundary render error',
687
+ 'ErrorBoundary componentDidUpdate',
688
+ ]
689
+ : [
690
+ // Catch and render an error message
691
+ 'ErrorBoundary unstable_handleError',
692
+ 'ErrorBoundary render error',
693
+ 'ErrorBoundary componentDidMount',
694
+ ]),
695
]);
696
697
log.length = 0;
698
ReactDOM.unmountComponentAtNode(container);
695
- expect(log).toEqual([
696
- 'ErrorBoundary componentWillUnmount',
697
- ]);
699
+ expect(log).toEqual(['ErrorBoundary componentWillUnmount']);
700
});
701
702
it('renders an error state if child throws in componentWillMount', () => {
@@ -703,7 +705,7 @@ describe('ReactErrorBoundaries', () => {
705
<ErrorBoundary>
706
<BrokenComponentWillMount />
707
</ErrorBoundary>,
706
- container
708
+ container,
709
);
710
expect(container.firstChild.textContent).toBe('Caught an error: Hello.');
711
expect(log).toEqual([
@@ -712,25 +714,25 @@ describe('ReactErrorBoundaries', () => {
714
'ErrorBoundary render success',
715
'BrokenComponentWillMount constructor',
716
'BrokenComponentWillMount componentWillMount [!]',
715
- ...(ReactDOMFeatureFlags.useFiber ? [
716
- 'ErrorBoundary componentDidMount',
717
- 'ErrorBoundary unstable_handleError',
718
- 'ErrorBoundary componentWillUpdate',
719
- 'ErrorBoundary render error',
720
- 'ErrorBoundary componentDidUpdate',
721
- ] : [
722
- // Catch and render an error message
723
- 'ErrorBoundary unstable_handleError',
724
- 'ErrorBoundary render error',
725
- 'ErrorBoundary componentDidMount',
726
- ]),
717
+ ...(ReactDOMFeatureFlags.useFiber
718
+ ? [
719
+ 'ErrorBoundary componentDidMount',
720
+ 'ErrorBoundary unstable_handleError',
721
+ 'ErrorBoundary componentWillUpdate',
722
+ 'ErrorBoundary render error',
723
+ 'ErrorBoundary componentDidUpdate',
724
+ ]
725
+ : [
726
+ // Catch and render an error message
727
+ 'ErrorBoundary unstable_handleError',
728
+ 'ErrorBoundary render error',
729
+ 'ErrorBoundary componentDidMount',
730
+ ]),
731
]);
732
733
log.length = 0;
734
ReactDOM.unmountComponentAtNode(container);
731
- expect(log).toEqual([
732
- 'ErrorBoundary componentWillUnmount',
733
- ]);
735
+ expect(log).toEqual(['ErrorBoundary componentWillUnmount']);
736
});
737
738
it('renders an error state if context provider throws in componentWillMount', () => {
@@ -752,7 +754,7 @@ describe('ReactErrorBoundaries', () => {
754
<ErrorBoundary>
755
<BrokenComponentWillMountWithContext />
756
</ErrorBoundary>,
755
- container
757
+ container,
758
);
759
expect(container.firstChild.textContent).toBe('Caught an error: Hello.');
760
});
@@ -780,16 +782,14 @@ describe('ReactErrorBoundaries', () => {
782
<ErrorBoundary>
783
<BrokenComponentWillMountWithContext />
784
</ErrorBoundary>,
783
- container
785
+ container,
786
);
787
expect(container.firstChild.textContent).toBe('Caught an error: Hello.');
788
});
789
790
it('mounts the error message if mounting fails', () => {
791
function renderError(error) {
790
- return (
791
- <ErrorMessage message={error.message} />
792
- );
792
+ return <ErrorMessage message={error.message} />;
793
}
794
795
var container = document.createElement('div');
@@ -797,7 +797,7 @@ describe('ReactErrorBoundaries', () => {
797
<ErrorBoundary renderError={renderError}>
798
<BrokenRender />
799
</ErrorBoundary>,
800
- container
800
+ container,
801
);
802
expect(log).toEqual([
803
'ErrorBoundary constructor',
@@ -806,27 +806,29 @@ describe('ReactErrorBoundaries', () => {
806
'BrokenRender constructor',
807
'BrokenRender componentWillMount',
808
'BrokenRender render [!]',
809
- ...(ReactDOMFeatureFlags.useFiber ? [
810
- 'ErrorBoundary componentDidMount',
811
- 'ErrorBoundary unstable_handleError',
812
- 'ErrorBoundary componentWillUpdate',
813
- 'ErrorBoundary render error',
814
- 'ErrorMessage constructor',
815
- 'ErrorMessage componentWillMount',
816
- 'ErrorMessage render',
817
- 'ErrorMessage componentDidMount',
818
- 'ErrorBoundary componentDidUpdate',
819
- ] : [
820
- // Handle the error:
821
- 'ErrorBoundary unstable_handleError',
822
- 'ErrorBoundary render error',
823
- // Mount the error message:
824
- 'ErrorMessage constructor',
825
- 'ErrorMessage componentWillMount',
826
- 'ErrorMessage render',
827
- 'ErrorMessage componentDidMount',
828
- 'ErrorBoundary componentDidMount',
829
- ]),
809
+ ...(ReactDOMFeatureFlags.useFiber
810
+ ? [
811
+ 'ErrorBoundary componentDidMount',
812
+ 'ErrorBoundary unstable_handleError',
813
+ 'ErrorBoundary componentWillUpdate',
814
+ 'ErrorBoundary render error',
815
+ 'ErrorMessage constructor',
816
+ 'ErrorMessage componentWillMount',
817
+ 'ErrorMessage render',
818
+ 'ErrorMessage componentDidMount',
819
+ 'ErrorBoundary componentDidUpdate',
820
+ ]
821
+ : [
822
+ // Handle the error:
823
+ 'ErrorBoundary unstable_handleError',
824
+ 'ErrorBoundary render error',
825
+ // Mount the error message:
826
+ 'ErrorMessage constructor',
827
+ 'ErrorMessage componentWillMount',
828
+ 'ErrorMessage render',
829
+ 'ErrorMessage componentDidMount',
830
+ 'ErrorBoundary componentDidMount',
831
+ ]),
832
]);
833
834
log.length = 0;
@@ -845,7 +847,7 @@ describe('ReactErrorBoundaries', () => {
847
<BrokenRender />
848
</RetryErrorBoundary>
849
</ErrorBoundary>,
848
- container
850
+ container,
851
);
852
expect(container.firstChild.textContent).toBe('Caught an error: Hello.');
853
expect(log).toEqual([
@@ -858,44 +860,44 @@ describe('ReactErrorBoundaries', () => {
860
'BrokenRender constructor',
861
'BrokenRender componentWillMount',
862
'BrokenRender render [!]',
861
- ...(ReactDOMFeatureFlags.useFiber ? [
862
- // In Fiber, failed error boundaries render null before attempting to recover
863
- 'RetryErrorBoundary componentDidMount',
864
- 'RetryErrorBoundary unstable_handleError [!]',
865
- 'ErrorBoundary componentDidMount',
866
- // Retry
867
- 'RetryErrorBoundary render',
868
- 'BrokenRender constructor',
869
- 'BrokenRender componentWillMount',
870
- 'BrokenRender render [!]',
871
- // This time, the error propagates to the higher boundary
872
- 'RetryErrorBoundary componentWillUnmount',
873
- 'ErrorBoundary unstable_handleError',
874
- // Render the error
875
- 'ErrorBoundary componentWillUpdate',
876
- 'ErrorBoundary render error',
877
- 'ErrorBoundary componentDidUpdate',
878
- ] : [
879
- // The first error boundary catches the error.
880
- // However, it doesn't adjust its state so next render will also fail.
881
- 'RetryErrorBoundary unstable_handleError [*]',
882
- 'RetryErrorBoundary render',
883
- 'BrokenRender constructor',
884
- 'BrokenRender componentWillMount',
885
- 'BrokenRender render [!]',
886
- // This time, the error propagates to the higher boundary
887
- 'ErrorBoundary unstable_handleError',
888
- // Render the error
889
- 'ErrorBoundary render error',
890
- 'ErrorBoundary componentDidMount',
891
- ]),
863
+ ...(ReactDOMFeatureFlags.useFiber
864
+ ? [
865
+ // In Fiber, failed error boundaries render null before attempting to recover
866
+ 'RetryErrorBoundary componentDidMount',
867
+ 'RetryErrorBoundary unstable_handleError [!]',
868
+ 'ErrorBoundary componentDidMount',
869
+ // Retry
870
+ 'RetryErrorBoundary render',
871
+ 'BrokenRender constructor',
872
+ 'BrokenRender componentWillMount',
873
+ 'BrokenRender render [!]',
874
+ // This time, the error propagates to the higher boundary
875
+ 'RetryErrorBoundary componentWillUnmount',
876
+ 'ErrorBoundary unstable_handleError',
877
+ // Render the error
878
+ 'ErrorBoundary componentWillUpdate',
879
+ 'ErrorBoundary render error',
880
+ 'ErrorBoundary componentDidUpdate',
881
+ ]
882
+ : [
883
+ // The first error boundary catches the error.
884
+ // However, it doesn't adjust its state so next render will also fail.
885
+ 'RetryErrorBoundary unstable_handleError [*]',
886
+ 'RetryErrorBoundary render',
887
+ 'BrokenRender constructor',
888
+ 'BrokenRender componentWillMount',
889
+ 'BrokenRender render [!]',
890
+ // This time, the error propagates to the higher boundary
891
+ 'ErrorBoundary unstable_handleError',
892
+ // Render the error
893
+ 'ErrorBoundary render error',
894
+ 'ErrorBoundary componentDidMount',
895
+ ]),
896
]);
897
898
log.length = 0;
899
ReactDOM.unmountComponentAtNode(container);
896
- expect(log).toEqual([
897
- 'ErrorBoundary componentWillUnmount',
898
- ]);
900
+ expect(log).toEqual(['ErrorBoundary componentWillUnmount']);
901
});
902
903
it('propagates errors inside boundary during componentWillMount', () => {
@@ -904,7 +906,7 @@ describe('ReactErrorBoundaries', () => {
906
<ErrorBoundary>
907
<BrokenComponentWillMountErrorBoundary />
908
</ErrorBoundary>,
907
- container
909
+ container,
910
);
911
expect(container.firstChild.textContent).toBe('Caught an error: Hello.');
912
expect(log).toEqual([
@@ -914,25 +916,25 @@ describe('ReactErrorBoundaries', () => {
916
'BrokenComponentWillMountErrorBoundary constructor',
917
'BrokenComponentWillMountErrorBoundary componentWillMount [!]',
918
// The error propagates to the higher boundary
917
- ...(ReactDOMFeatureFlags.useFiber ? [
918
- 'ErrorBoundary componentDidMount',
919
- 'ErrorBoundary unstable_handleError',
920
- 'ErrorBoundary componentWillUpdate',
921
- 'ErrorBoundary render error',
922
- 'ErrorBoundary componentDidUpdate',
923
- ] : [
924
- 'ErrorBoundary unstable_handleError',
925
- // Render the error
926
- 'ErrorBoundary render error',
927
- 'ErrorBoundary componentDidMount',
928
- ]),
919
+ ...(ReactDOMFeatureFlags.useFiber
920
+ ? [
921
+ 'ErrorBoundary componentDidMount',
922
+ 'ErrorBoundary unstable_handleError',
923
+ 'ErrorBoundary componentWillUpdate',
924
+ 'ErrorBoundary render error',
925
+ 'ErrorBoundary componentDidUpdate',
926
+ ]
927
+ : [
928
+ 'ErrorBoundary unstable_handleError',
929
+ // Render the error
930
+ 'ErrorBoundary render error',
931
+ 'ErrorBoundary componentDidMount',
932
+ ]),
933
]);
934
935
log.length = 0;
936
ReactDOM.unmountComponentAtNode(container);
933
- expect(log).toEqual([
934
- 'ErrorBoundary componentWillUnmount',
935
- ]);
937
+ expect(log).toEqual(['ErrorBoundary componentWillUnmount']);
938
});
939
940
it('propagates errors inside boundary while rendering error state', () => {
@@ -943,7 +945,7 @@ describe('ReactErrorBoundaries', () => {
945
<BrokenRender />
946
</BrokenRenderErrorBoundary>
947
</ErrorBoundary>,
946
- container
948
+ container,
949
);
950
expect(container.firstChild.textContent).toBe('Caught an error: Hello.');
951
expect(log).toEqual([
@@ -958,36 +960,36 @@ describe('ReactErrorBoundaries', () => {
960
'BrokenRender render [!]',
961
// The first error boundary catches the error
962
// It adjusts state but throws displaying the message
961
- ...(ReactDOMFeatureFlags.useFiber ? [
962
- // Finish mounting with null children
963
- 'BrokenRenderErrorBoundary componentDidMount',
964
- // Attempt to handle the error
965
- 'BrokenRenderErrorBoundary unstable_handleError',
966
- 'ErrorBoundary componentDidMount',
967
- 'BrokenRenderErrorBoundary render error [!]',
968
- // Boundary fails with new error, propagate to next boundary
969
- 'BrokenRenderErrorBoundary componentWillUnmount',
970
- // Attempt to handle the error again
971
- 'ErrorBoundary unstable_handleError',
972
- 'ErrorBoundary componentWillUpdate',
973
- 'ErrorBoundary render error',
974
- 'ErrorBoundary componentDidUpdate',
975
- ] : [
976
- 'BrokenRenderErrorBoundary unstable_handleError',
977
- 'BrokenRenderErrorBoundary render error [!]',
978
- // The error propagates to the higher boundary
979
- 'ErrorBoundary unstable_handleError',
980
- // Render the error
981
- 'ErrorBoundary render error',
982
- 'ErrorBoundary componentDidMount',
983
- ]),
963
+ ...(ReactDOMFeatureFlags.useFiber
964
+ ? [
965
+ // Finish mounting with null children
966
+ 'BrokenRenderErrorBoundary componentDidMount',
967
+ // Attempt to handle the error
968
+ 'BrokenRenderErrorBoundary unstable_handleError',
969
+ 'ErrorBoundary componentDidMount',
970
+ 'BrokenRenderErrorBoundary render error [!]',
971
+ // Boundary fails with new error, propagate to next boundary
972
+ 'BrokenRenderErrorBoundary componentWillUnmount',
973
+ // Attempt to handle the error again
974
+ 'ErrorBoundary unstable_handleError',
975
+ 'ErrorBoundary componentWillUpdate',
976
+ 'ErrorBoundary render error',
977
+ 'ErrorBoundary componentDidUpdate',
978
+ ]
979
+ : [
980
+ 'BrokenRenderErrorBoundary unstable_handleError',
981
+ 'BrokenRenderErrorBoundary render error [!]',
982
+ // The error propagates to the higher boundary
983
+ 'ErrorBoundary unstable_handleError',
984
+ // Render the error
985
+ 'ErrorBoundary render error',
986
+ 'ErrorBoundary componentDidMount',
987
+ ]),
988
]);
989
990
log.length = 0;
991
ReactDOM.unmountComponentAtNode(container);
988
- expect(log).toEqual([
989
- 'ErrorBoundary componentWillUnmount',
990
- ]);
992
+ expect(log).toEqual(['ErrorBoundary componentWillUnmount']);
993
});
994
995
it('does not call componentWillUnmount when aborting initial mount', () => {
@@ -998,7 +1000,7 @@ describe('ReactErrorBoundaries', () => {
1000
<BrokenRender />
1001
<Normal />
1002
</ErrorBoundary>,
1001
- container
1003
+ container,
1004
);
1005
expect(container.firstChild.textContent).toBe('Caught an error: Hello.');
1006
expect(log).toEqual([
@@ -1013,28 +1015,28 @@ describe('ReactErrorBoundaries', () => {
1015
'BrokenRender constructor',
1016
'BrokenRender componentWillMount',
1017
'BrokenRender render [!]',
1016
- ...(ReactDOMFeatureFlags.useFiber ? [
1017
- // Finish mounting with null children
1018
- 'ErrorBoundary componentDidMount',
1019
- // Handle the error
1020
- 'ErrorBoundary unstable_handleError',
1021
- // Render the error message
1022
- 'ErrorBoundary componentWillUpdate',
1023
- 'ErrorBoundary render error',
1024
- 'ErrorBoundary componentDidUpdate',
1025
- ] : [
1026
- 'ErrorBoundary unstable_handleError',
1027
- // Render the error message
1028
- 'ErrorBoundary render error',
1029
- 'ErrorBoundary componentDidMount',
1030
- ]),
1018
+ ...(ReactDOMFeatureFlags.useFiber
1019
+ ? [
1020
+ // Finish mounting with null children
1021
+ 'ErrorBoundary componentDidMount',
1022
+ // Handle the error
1023
+ 'ErrorBoundary unstable_handleError',
1024
+ // Render the error message
1025
+ 'ErrorBoundary componentWillUpdate',
1026
+ 'ErrorBoundary render error',
1027
+ 'ErrorBoundary componentDidUpdate',
1028
+ ]
1029
+ : [
1030
+ 'ErrorBoundary unstable_handleError',
1031
+ // Render the error message
1032
+ 'ErrorBoundary render error',
1033
+ 'ErrorBoundary componentDidMount',
1034
+ ]),
1035
]);
1036
1037
log.length = 0;
1038
ReactDOM.unmountComponentAtNode(container);
1035
- expect(log).toEqual([
1036
- 'ErrorBoundary componentWillUnmount',
1037
- ]);
1039
+ expect(log).toEqual(['ErrorBoundary componentWillUnmount']);
1040
});
1041
1042
it('resets refs if mounting aborts', () => {
@@ -1051,7 +1053,7 @@ describe('ReactErrorBoundaries', () => {
1053
<div ref={childRef} />
1054
<BrokenRender />
1055
</ErrorBoundary>,
1054
- container
1056
+ container,
1057
);
1058
expect(container.textContent).toBe('Caught an error: Hello.');
1059
expect(log).toEqual([
@@ -1062,26 +1064,28 @@ describe('ReactErrorBoundaries', () => {
1064
'BrokenRender componentWillMount',
1065
'BrokenRender render [!]',
1066
// Handle error:
1065
- ...(ReactDOMFeatureFlags.useFiber ? [
1066
- // Finish mounting with null children
1067
- 'ErrorBoundary componentDidMount',
1068
- // Handle the error
1069
- 'ErrorBoundary unstable_handleError',
1070
- // Render the error message
1071
- 'ErrorBoundary componentWillUpdate',
1072
- 'ErrorBoundary render error',
1073
- 'Error message ref is set to [object HTMLDivElement]',
1074
- 'ErrorBoundary componentDidUpdate',
1075
- ] : [
1076
- 'ErrorBoundary unstable_handleError',
1077
- // Stack reconciler resets ref on update, as it doesn't know ref was never set.
1078
- // This is unnecessary, and Fiber doesn't do it:
1079
- 'Child ref is set to null',
1080
- 'ErrorBoundary render error',
1081
- // Ref to error message should get set:
1082
- 'Error message ref is set to [object HTMLDivElement]',
1083
- 'ErrorBoundary componentDidMount',
1084
- ]),
1067
+ ...(ReactDOMFeatureFlags.useFiber
1068
+ ? [
1069
+ // Finish mounting with null children
1070
+ 'ErrorBoundary componentDidMount',
1071
+ // Handle the error
1072
+ 'ErrorBoundary unstable_handleError',
1073
+ // Render the error message
1074
+ 'ErrorBoundary componentWillUpdate',
1075
+ 'ErrorBoundary render error',
1076
+ 'Error message ref is set to [object HTMLDivElement]',
1077
+ 'ErrorBoundary componentDidUpdate',
1078
+ ]
1079
+ : [
1080
+ 'ErrorBoundary unstable_handleError',
1081
+ // Stack reconciler resets ref on update, as it doesn't know ref was never set.
1082
+ // This is unnecessary, and Fiber doesn't do it:
1083
+ 'Child ref is set to null',
1084
+ 'ErrorBoundary render error',
1085
+ // Ref to error message should get set:
1086
+ 'Error message ref is set to [object HTMLDivElement]',
1087
+ 'ErrorBoundary componentDidMount',
1088
+ ]),
1089
]);
1090
1091
log.length = 0;
@@ -1098,7 +1102,7 @@ describe('ReactErrorBoundaries', () => {
1102
<ErrorBoundary>
1103
<div>Mounted successfully.</div>
1104
</ErrorBoundary>,
1101
- container
1105
+ container,
1106
);
1107
expect(container.firstChild.textContent).toBe('Mounted successfully.');
1108
expect(log).toEqual([
@@ -1110,9 +1114,7 @@ describe('ReactErrorBoundaries', () => {
1114
1115
log.length = 0;
1116
ReactDOM.unmountComponentAtNode(container);
1113
- expect(log).toEqual([
1114
- 'ErrorBoundary componentWillUnmount',
1115
- ]);
1117
+ expect(log).toEqual(['ErrorBoundary componentWillUnmount']);
1118
});
1119
1120
it('catches if child throws in constructor during update', () => {
@@ -1121,7 +1123,7 @@ describe('ReactErrorBoundaries', () => {
1123
<ErrorBoundary>
1124
<Normal />
1125
</ErrorBoundary>,
1124
- container
1126
+ container,
1127
);
1128
1129
log.length = 0;
@@ -1131,7 +1133,7 @@ describe('ReactErrorBoundaries', () => {
1133
<Normal logName="Normal2" />
1134
<BrokenConstructor />
1135
</ErrorBoundary>,
1134
- container
1136
+ container,
1137
);
1138
expect(container.textContent).toBe('Caught an error: Hello.');
1139
expect(log).toEqual([
@@ -1147,31 +1149,31 @@ describe('ReactErrorBoundaries', () => {
1149
'Normal2 render',
1150
// BrokenConstructor will abort rendering:
1151
'BrokenConstructor constructor [!]',
1150
- ...(ReactDOMFeatureFlags.useFiber ? [
1151
- // Finish updating with null children
1152
- 'Normal componentWillUnmount',
1153
- 'ErrorBoundary componentDidUpdate',
1154
- // Handle the error
1155
- 'ErrorBoundary unstable_handleError',
1156
- // Render the error message
1157
- 'ErrorBoundary componentWillUpdate',
1158
- 'ErrorBoundary render error',
1159
- 'ErrorBoundary componentDidUpdate',
1160
- ] : [
1161
- 'ErrorBoundary unstable_handleError',
1162
- // Stack unmounts first, then renders:
1163
- 'Normal componentWillUnmount',
1164
- 'ErrorBoundary render error',
1165
- // Normal2 does not get lifefycle because it was never mounted
1166
- 'ErrorBoundary componentDidUpdate',
1167
- ]),
1152
+ ...(ReactDOMFeatureFlags.useFiber
1153
+ ? [
1154
+ // Finish updating with null children
1155
+ 'Normal componentWillUnmount',
1156
+ 'ErrorBoundary componentDidUpdate',
1157
+ // Handle the error
1158
+ 'ErrorBoundary unstable_handleError',
1159
+ // Render the error message
1160
+ 'ErrorBoundary componentWillUpdate',
1161
+ 'ErrorBoundary render error',
1162
+ 'ErrorBoundary componentDidUpdate',
1163
+ ]
1164
+ : [
1165
+ 'ErrorBoundary unstable_handleError',
1166
+ // Stack unmounts first, then renders:
1167
+ 'Normal componentWillUnmount',
1168
+ 'ErrorBoundary render error',
1169
+ // Normal2 does not get lifefycle because it was never mounted
1170
+ 'ErrorBoundary componentDidUpdate',
1171
+ ]),
1172
]);
1173
1174
log.length = 0;
1175
ReactDOM.unmountComponentAtNode(container);
1172
- expect(log).toEqual([
1173
- 'ErrorBoundary componentWillUnmount',
1174
- ]);
1176
+ expect(log).toEqual(['ErrorBoundary componentWillUnmount']);
1177
});
1178
1179
it('catches if child throws in componentWillMount during update', () => {
@@ -1180,7 +1182,7 @@ describe('ReactErrorBoundaries', () => {
1182
<ErrorBoundary>
1183
<Normal />
1184
</ErrorBoundary>,
1183
- container
1185
+ container,
1186
);
1187
1188
log.length = 0;
@@ -1190,7 +1192,7 @@ describe('ReactErrorBoundaries', () => {
1192
<Normal logName="Normal2" />
1193
<BrokenComponentWillMount />
1194
</ErrorBoundary>,
1193
- container
1195
+ container,
1196
);
1197
expect(container.textContent).toBe('Caught an error: Hello.');
1198
expect(log).toEqual([
@@ -1207,31 +1209,31 @@ describe('ReactErrorBoundaries', () => {
1209
// BrokenComponentWillMount will abort rendering:
1210
'BrokenComponentWillMount constructor',
1211
'BrokenComponentWillMount componentWillMount [!]',
1210
- ...(ReactDOMFeatureFlags.useFiber ? [
1211
- // Finish updating with null children
1212
- 'Normal componentWillUnmount',
1213
- 'ErrorBoundary componentDidUpdate',
1214
- // Handle the error
1215
- 'ErrorBoundary unstable_handleError',
1216
- // Render the error message
1217
- 'ErrorBoundary componentWillUpdate',
1218
- 'ErrorBoundary render error',
1219
- 'ErrorBoundary componentDidUpdate',
1220
- ] : [
1221
- 'ErrorBoundary unstable_handleError',
1222
- // Stack unmounts first, then renders:
1223
- 'Normal componentWillUnmount',
1224
- 'ErrorBoundary render error',
1225
- // Normal2 does not get lifefycle because it was never mounted
1226
- 'ErrorBoundary componentDidUpdate',
1227
- ]),
1212
+ ...(ReactDOMFeatureFlags.useFiber
1213
+ ? [
1214
+ // Finish updating with null children
1215
+ 'Normal componentWillUnmount',
1216
+ 'ErrorBoundary componentDidUpdate',
1217
+ // Handle the error
1218
+ 'ErrorBoundary unstable_handleError',
1219
+ // Render the error message
1220
+ 'ErrorBoundary componentWillUpdate',
1221
+ 'ErrorBoundary render error',
1222
+ 'ErrorBoundary componentDidUpdate',
1223
+ ]
1224
+ : [
1225
+ 'ErrorBoundary unstable_handleError',
1226
+ // Stack unmounts first, then renders:
1227
+ 'Normal componentWillUnmount',
1228
+ 'ErrorBoundary render error',
1229
+ // Normal2 does not get lifefycle because it was never mounted
1230
+ 'ErrorBoundary componentDidUpdate',
1231
+ ]),
1232
]);
1233
1234
log.length = 0;
1235
ReactDOM.unmountComponentAtNode(container);
1232
- expect(log).toEqual([
1233
- 'ErrorBoundary componentWillUnmount',
1234
- ]);
1236
+ expect(log).toEqual(['ErrorBoundary componentWillUnmount']);
1237
});
1238
1239
it('catches if child throws in componentWillReceiveProps during update', () => {
@@ -1241,7 +1243,7 @@ describe('ReactErrorBoundaries', () => {
1243
<Normal />
1244
<BrokenComponentWillReceiveProps />
1245
</ErrorBoundary>,
1244
- container
1246
+ container,
1247
);
1248
1249
log.length = 0;
@@ -1250,7 +1252,7 @@ describe('ReactErrorBoundaries', () => {
1252
<Normal />
1253
<BrokenComponentWillReceiveProps />
1254
</ErrorBoundary>,
1253
- container
1255
+ container,
1256
);
1257
expect(container.textContent).toBe('Caught an error: Hello.');
1258
expect(log).toEqual([
@@ -1262,31 +1264,31 @@ describe('ReactErrorBoundaries', () => {
1264
'Normal render',
1265
// BrokenComponentWillReceiveProps will abort rendering:
1266
'BrokenComponentWillReceiveProps componentWillReceiveProps [!]',
1265
- ...(ReactDOMFeatureFlags.useFiber ? [
1266
- // Finish updating with null children
1267
- 'Normal componentWillUnmount',
1268
- 'BrokenComponentWillReceiveProps componentWillUnmount',
1269
- 'ErrorBoundary componentDidUpdate',
1270
- // Handle the error
1271
- 'ErrorBoundary unstable_handleError',
1272
- 'ErrorBoundary componentWillUpdate',
1273
- 'ErrorBoundary render error',
1274
- 'ErrorBoundary componentDidUpdate',
1275
- ] : [
1276
- 'ErrorBoundary unstable_handleError',
1277
- // Stack unmounts first, then renders:
1278
- 'Normal componentWillUnmount',
1279
- 'BrokenComponentWillReceiveProps componentWillUnmount',
1280
- 'ErrorBoundary render error',
1281
- 'ErrorBoundary componentDidUpdate',
1282
- ]),
1267
+ ...(ReactDOMFeatureFlags.useFiber
1268
+ ? [
1269
+ // Finish updating with null children
1270
+ 'Normal componentWillUnmount',
1271
+ 'BrokenComponentWillReceiveProps componentWillUnmount',
1272
+ 'ErrorBoundary componentDidUpdate',
1273
+ // Handle the error
1274
+ 'ErrorBoundary unstable_handleError',
1275
+ 'ErrorBoundary componentWillUpdate',
1276
+ 'ErrorBoundary render error',
1277
+ 'ErrorBoundary componentDidUpdate',
1278
+ ]
1279
+ : [
1280
+ 'ErrorBoundary unstable_handleError',
1281
+ // Stack unmounts first, then renders:
1282
+ 'Normal componentWillUnmount',
1283
+ 'BrokenComponentWillReceiveProps componentWillUnmount',
1284
+ 'ErrorBoundary render error',
1285
+ 'ErrorBoundary componentDidUpdate',
1286
+ ]),
1287
]);
1288
1289
log.length = 0;
1290
ReactDOM.unmountComponentAtNode(container);
1287
- expect(log).toEqual([
1288
- 'ErrorBoundary componentWillUnmount',
1289
- ]);
1291
+ expect(log).toEqual(['ErrorBoundary componentWillUnmount']);
1292
});
1293
1294
it('catches if child throws in componentWillUpdate during update', () => {
@@ -1296,7 +1298,7 @@ describe('ReactErrorBoundaries', () => {
1298
<Normal />
1299
<BrokenComponentWillUpdate />
1300
</ErrorBoundary>,
1299
- container
1301
+ container,
1302
);
1303
1304
log.length = 0;
@@ -1305,7 +1307,7 @@ describe('ReactErrorBoundaries', () => {
1307
<Normal />
1308
<BrokenComponentWillUpdate />
1309
</ErrorBoundary>,
1308
- container
1310
+ container,
1311
);
1312
expect(container.textContent).toBe('Caught an error: Hello.');
1313
expect(log).toEqual([
@@ -1318,31 +1320,31 @@ describe('ReactErrorBoundaries', () => {
1320
// BrokenComponentWillUpdate will abort rendering:
1321
'BrokenComponentWillUpdate componentWillReceiveProps',
1322
'BrokenComponentWillUpdate componentWillUpdate [!]',
1321
- ...(ReactDOMFeatureFlags.useFiber ? [
1322
- // Finish updating with null children
1323
- 'Normal componentWillUnmount',
1324
- 'BrokenComponentWillUpdate componentWillUnmount',
1325
- 'ErrorBoundary componentDidUpdate',
1326
- // Handle the error
1327
- 'ErrorBoundary unstable_handleError',
1328
- 'ErrorBoundary componentWillUpdate',
1329
- 'ErrorBoundary render error',
1330
- 'ErrorBoundary componentDidUpdate',
1331
- ] : [
1332
- 'ErrorBoundary unstable_handleError',
1333
- // Stack unmounts first, then renders:
1334
- 'Normal componentWillUnmount',
1335
- 'BrokenComponentWillUpdate componentWillUnmount',
1336
- 'ErrorBoundary render error',
1337
- 'ErrorBoundary componentDidUpdate',
1338
- ]),
1323
+ ...(ReactDOMFeatureFlags.useFiber
1324
+ ? [
1325
+ // Finish updating with null children
1326
+ 'Normal componentWillUnmount',
1327
+ 'BrokenComponentWillUpdate componentWillUnmount',
1328
+ 'ErrorBoundary componentDidUpdate',
1329
+ // Handle the error
1330
+ 'ErrorBoundary unstable_handleError',
1331
+ 'ErrorBoundary componentWillUpdate',
1332
+ 'ErrorBoundary render error',
1333
+ 'ErrorBoundary componentDidUpdate',
1334
+ ]
1335
+ : [
1336
+ 'ErrorBoundary unstable_handleError',
1337
+ // Stack unmounts first, then renders:
1338
+ 'Normal componentWillUnmount',
1339
+ 'BrokenComponentWillUpdate componentWillUnmount',
1340
+ 'ErrorBoundary render error',
1341
+ 'ErrorBoundary componentDidUpdate',
1342
+ ]),
1343
]);
1344
1345
log.length = 0;
1346
ReactDOM.unmountComponentAtNode(container);
1343
- expect(log).toEqual([
1344
- 'ErrorBoundary componentWillUnmount',
1345
- ]);
1347
+ expect(log).toEqual(['ErrorBoundary componentWillUnmount']);
1348
});
1349
1350
it('catches if child throws in render during update', () => {
@@ -1351,7 +1353,7 @@ describe('ReactErrorBoundaries', () => {
1353
<ErrorBoundary>
1354
<Normal />
1355
</ErrorBoundary>,
1354
- container
1356
+ container,
1357
);
1358
1359
log.length = 0;
@@ -1361,7 +1363,7 @@ describe('ReactErrorBoundaries', () => {
1363
<Normal logName="Normal2" />
1364
<BrokenRender />
1365
</ErrorBoundary>,
1364
- container
1366
+ container,
1367
);
1368
expect(container.textContent).toBe('Caught an error: Hello.');
1369
expect(log).toEqual([
@@ -1379,30 +1381,30 @@ describe('ReactErrorBoundaries', () => {
1381
'BrokenRender constructor',
1382
'BrokenRender componentWillMount',
1383
'BrokenRender render [!]',
1382
- ...(ReactDOMFeatureFlags.useFiber ? [
1383
- // Finish updating with null children
1384
- 'Normal componentWillUnmount',
1385
- 'ErrorBoundary componentDidUpdate',
1386
- // Handle the error
1387
- 'ErrorBoundary unstable_handleError',
1388
- 'ErrorBoundary componentWillUpdate',
1389
- 'ErrorBoundary render error',
1390
- 'ErrorBoundary componentDidUpdate',
1391
- ] : [
1392
- 'ErrorBoundary unstable_handleError',
1393
- // Stack unmounts first, then renders:
1394
- 'Normal componentWillUnmount',
1395
- 'ErrorBoundary render error',
1396
- // Normal2 does not get lifefycle because it was never mounted
1397
- 'ErrorBoundary componentDidUpdate',
1398
- ]),
1384
+ ...(ReactDOMFeatureFlags.useFiber
1385
+ ? [
1386
+ // Finish updating with null children
1387
+ 'Normal componentWillUnmount',
1388
+ 'ErrorBoundary componentDidUpdate',
1389
+ // Handle the error
1390
+ 'ErrorBoundary unstable_handleError',
1391
+ 'ErrorBoundary componentWillUpdate',
1392
+ 'ErrorBoundary render error',
1393
+ 'ErrorBoundary componentDidUpdate',
1394
+ ]
1395
+ : [
1396
+ 'ErrorBoundary unstable_handleError',
1397
+ // Stack unmounts first, then renders:
1398
+ 'Normal componentWillUnmount',
1399
+ 'ErrorBoundary render error',
1400
+ // Normal2 does not get lifefycle because it was never mounted
1401
+ 'ErrorBoundary componentDidUpdate',
1402
+ ]),
1403
]);
1404
1405
log.length = 0;
1406
ReactDOM.unmountComponentAtNode(container);
1403
- expect(log).toEqual([
1404
- 'ErrorBoundary componentWillUnmount',
1405
- ]);
1407
+ expect(log).toEqual(['ErrorBoundary componentWillUnmount']);
1408
});
1409
1410
it('keeps refs up-to-date during updates', () => {
@@ -1421,7 +1423,7 @@ describe('ReactErrorBoundaries', () => {
1423
<ErrorBoundary errorMessageRef={errorMessageRef}>
1424
<div ref={child1Ref} />
1425
</ErrorBoundary>,
1424
- container
1426
+ container,
1427
);
1428
expect(log).toEqual([
1429
'ErrorBoundary constructor',
@@ -1438,7 +1440,7 @@ describe('ReactErrorBoundaries', () => {
1440
<div ref={child2Ref} />
1441
<BrokenRender />
1442
</ErrorBoundary>,
1441
- container
1443
+ container,
1444
);
1445
expect(container.textContent).toBe('Caught an error: Hello.');
1446
expect(log).toEqual([
@@ -1449,20 +1451,22 @@ describe('ReactErrorBoundaries', () => {
1451
'BrokenRender constructor',
1452
'BrokenRender componentWillMount',
1453
'BrokenRender render [!]',
1452
- ...(ReactDOMFeatureFlags.useFiber ? [
1453
- // Finish updating with null children
1454
- 'Child1 ref is set to null',
1455
- 'ErrorBoundary componentDidUpdate',
1456
- // Handle the error
1457
- 'ErrorBoundary unstable_handleError',
1458
- 'ErrorBoundary componentWillUpdate',
1459
- 'ErrorBoundary render error',
1460
- ] : [
1461
- 'ErrorBoundary unstable_handleError',
1462
- // Stack resets ref first, renders later
1463
- 'Child1 ref is set to null',
1464
- 'ErrorBoundary render error',
1465
- ]),
1454
+ ...(ReactDOMFeatureFlags.useFiber
1455
+ ? [
1456
+ // Finish updating with null children
1457
+ 'Child1 ref is set to null',
1458
+ 'ErrorBoundary componentDidUpdate',
1459
+ // Handle the error
1460
+ 'ErrorBoundary unstable_handleError',
1461
+ 'ErrorBoundary componentWillUpdate',
1462
+ 'ErrorBoundary render error',
1463
+ ]
1464
+ : [
1465
+ 'ErrorBoundary unstable_handleError',
1466
+ // Stack resets ref first, renders later
1467
+ 'Child1 ref is set to null',
1468
+ 'ErrorBoundary render error',
1469
+ ]),
1470
'Error message ref is set to [object HTMLDivElement]',
1471
// Child2 ref is never set because its mounting aborted
1472
'ErrorBoundary componentDidUpdate',
@@ -1484,7 +1488,7 @@ describe('ReactErrorBoundaries', () => {
1488
<BrokenComponentWillUnmount />
1489
<Normal />
1490
</ErrorBoundary>,
1487
- container
1491
+ container,
1492
);
1493
1494
log.length = 0;
@@ -1492,7 +1496,7 @@ describe('ReactErrorBoundaries', () => {
1496
<ErrorBoundary>
1497
<BrokenComponentWillUnmount />
1498
</ErrorBoundary>,
1495
- container
1499
+ container,
1500
);
1501
expect(container.textContent).toBe('Caught an error: Hello.');
1502
expect(log).toEqual([
@@ -1505,40 +1509,40 @@ describe('ReactErrorBoundaries', () => {
1509
'BrokenComponentWillUnmount render',
1510
// Unmounting throws:
1511
'BrokenComponentWillUnmount componentWillUnmount [!]',
1508
- ...(ReactDOMFeatureFlags.useFiber ? [
1509
- // Fiber proceeds with lifecycles despite errors
1510
- 'Normal componentWillUnmount',
1511
- // The components have updated in this phase
1512
- 'BrokenComponentWillUnmount componentDidUpdate',
1513
- 'ErrorBoundary componentDidUpdate',
1514
- // Now that commit phase is done, Fiber unmounts the boundary's children
1515
- 'BrokenComponentWillUnmount componentWillUnmount [!]',
1516
- 'ErrorBoundary unstable_handleError',
1517
- // The initial render was aborted, so
1518
- // Fiber retries from the root.
1519
- 'ErrorBoundary componentWillUpdate',
1520
- // Render an error now (stack will do it later)
1521
- 'ErrorBoundary render error',
1522
- // Attempt to unmount previous child:
1523
- // Done
1524
- 'ErrorBoundary componentDidUpdate',
1525
- ] : [
1526
- // Stack will handle error immediately
1527
- 'ErrorBoundary unstable_handleError',
1528
- // Attempt to unmount previous children:
1529
- 'BrokenComponentWillUnmount componentWillUnmount [!]',
1530
- 'Normal componentWillUnmount',
1531
- // Render an error now (Fiber will do it earlier)
1532
- 'ErrorBoundary render error',
1533
- 'ErrorBoundary componentDidUpdate',
1534
- ]),
1512
+ ...(ReactDOMFeatureFlags.useFiber
1513
+ ? [
1514
+ // Fiber proceeds with lifecycles despite errors
1515
+ 'Normal componentWillUnmount',
1516
+ // The components have updated in this phase
1517
+ 'BrokenComponentWillUnmount componentDidUpdate',
1518
+ 'ErrorBoundary componentDidUpdate',
1519
+ // Now that commit phase is done, Fiber unmounts the boundary's children
1520
+ 'BrokenComponentWillUnmount componentWillUnmount [!]',
1521
+ 'ErrorBoundary unstable_handleError',
1522
+ // The initial render was aborted, so
1523
+ // Fiber retries from the root.
1524
+ 'ErrorBoundary componentWillUpdate',
1525
+ // Render an error now (stack will do it later)
1526
+ 'ErrorBoundary render error',
1527
+ // Attempt to unmount previous child:
1528
+ // Done
1529
+ 'ErrorBoundary componentDidUpdate',
1530
+ ]
1531
+ : [
1532
+ // Stack will handle error immediately
1533
+ 'ErrorBoundary unstable_handleError',
1534
+ // Attempt to unmount previous children:
1535
+ 'BrokenComponentWillUnmount componentWillUnmount [!]',
1536
+ 'Normal componentWillUnmount',
1537
+ // Render an error now (Fiber will do it earlier)
1538
+ 'ErrorBoundary render error',
1539
+ 'ErrorBoundary componentDidUpdate',
1540
+ ]),
1541
]);
1542
1543
log.length = 0;
1544
ReactDOM.unmountComponentAtNode(container);
1539
- expect(log).toEqual([
1540
- 'ErrorBoundary componentWillUnmount',
1541
- ]);
1545
+ expect(log).toEqual(['ErrorBoundary componentWillUnmount']);
1546
});
1547
1548
it('recovers from nested componentWillUnmount errors on update', () => {
@@ -1550,7 +1554,7 @@ describe('ReactErrorBoundaries', () => {
1554
</Normal>
1555
<BrokenComponentWillUnmount />
1556
</ErrorBoundary>,
1553
- container
1557
+ container,
1558
);
1559
1560
log.length = 0;
@@ -1560,7 +1564,7 @@ describe('ReactErrorBoundaries', () => {
1564
<BrokenComponentWillUnmount />
1565
</Normal>
1566
</ErrorBoundary>,
1563
- container
1567
+ container,
1568
);
1569
expect(container.textContent).toBe('Caught an error: Hello.');
1570
expect(log).toEqual([
@@ -1576,38 +1580,38 @@ describe('ReactErrorBoundaries', () => {
1580
'BrokenComponentWillUnmount render',
1581
// Unmounting throws:
1582
'BrokenComponentWillUnmount componentWillUnmount [!]',
1579
- ...(ReactDOMFeatureFlags.useFiber ? [
1580
- // Fiber proceeds with lifecycles despite errors
1581
- 'BrokenComponentWillUnmount componentDidUpdate',
1582
- 'Normal componentDidUpdate',
1583
- 'ErrorBoundary componentDidUpdate',
1584
- 'Normal componentWillUnmount',
1585
- 'BrokenComponentWillUnmount componentWillUnmount [!]',
1586
- // Now that commit phase is done, Fiber handles errors
1587
- 'ErrorBoundary unstable_handleError',
1588
- // The initial render was aborted, so
1589
- // Fiber retries from the root.
1590
- 'ErrorBoundary componentWillUpdate',
1591
- // Render an error now (stack will do it later)
1592
- 'ErrorBoundary render error',
1593
- // Done
1594
- 'ErrorBoundary componentDidUpdate',
1595
- ] : [
1596
- 'ErrorBoundary unstable_handleError',
1597
- // Attempt to unmount previous children:
1598
- 'Normal componentWillUnmount',
1599
- 'BrokenComponentWillUnmount componentWillUnmount [!]',
1600
- // Stack calls lifecycles first, then renders.
1601
- 'ErrorBoundary render error',
1602
- 'ErrorBoundary componentDidUpdate',
1603
- ]),
1583
+ ...(ReactDOMFeatureFlags.useFiber
1584
+ ? [
1585
+ // Fiber proceeds with lifecycles despite errors
1586
+ 'BrokenComponentWillUnmount componentDidUpdate',
1587
+ 'Normal componentDidUpdate',
1588
+ 'ErrorBoundary componentDidUpdate',
1589
+ 'Normal componentWillUnmount',
1590
+ 'BrokenComponentWillUnmount componentWillUnmount [!]',
1591
+ // Now that commit phase is done, Fiber handles errors
1592
+ 'ErrorBoundary unstable_handleError',
1593
+ // The initial render was aborted, so
1594
+ // Fiber retries from the root.
1595
+ 'ErrorBoundary componentWillUpdate',
1596
+ // Render an error now (stack will do it later)
1597
+ 'ErrorBoundary render error',
1598
+ // Done
1599
+ 'ErrorBoundary componentDidUpdate',
1600
+ ]
1601
+ : [
1602
+ 'ErrorBoundary unstable_handleError',
1603
+ // Attempt to unmount previous children:
1604
+ 'Normal componentWillUnmount',
1605
+ 'BrokenComponentWillUnmount componentWillUnmount [!]',
1606
+ // Stack calls lifecycles first, then renders.
1607
+ 'ErrorBoundary render error',
1608
+ 'ErrorBoundary componentDidUpdate',
1609
+ ]),
1610
]);
1611
1612
log.length = 0;
1613
ReactDOM.unmountComponentAtNode(container);
1608
- expect(log).toEqual([
1609
- 'ErrorBoundary componentWillUnmount',
1610
- ]);
1614
+ expect(log).toEqual(['ErrorBoundary componentWillUnmount']);
1615
});
1616
1617
it('picks the right boundary when handling unmounting errors', () => {
@@ -1620,20 +1624,29 @@ describe('ReactErrorBoundaries', () => {
1624
1625
var container = document.createElement('div');
1626
ReactDOM.render(
1623
- <ErrorBoundary logName="OuterErrorBoundary" renderError={renderOuterError}>
1624
- <ErrorBoundary logName="InnerErrorBoundary" renderError={renderInnerError}>
1627
+ <ErrorBoundary
1628
+ logName="OuterErrorBoundary"
1629
+ renderError={renderOuterError}>
1630
+ <ErrorBoundary
1631
+ logName="InnerErrorBoundary"
1632
+ renderError={renderInnerError}>
1633
<BrokenComponentWillUnmount />
1634
</ErrorBoundary>
1635
</ErrorBoundary>,
1628
- container
1636
+ container,
1637
);
1638
1639
log.length = 0;
1640
ReactDOM.render(
1633
- <ErrorBoundary logName="OuterErrorBoundary" renderError={renderOuterError}>
1634
- <ErrorBoundary logName="InnerErrorBoundary" renderError={renderInnerError} />
1641
+ <ErrorBoundary
1642
+ logName="OuterErrorBoundary"
1643
+ renderError={renderOuterError}>
1644
+ <ErrorBoundary
1645
+ logName="InnerErrorBoundary"
1646
+ renderError={renderInnerError}
1647
+ />
1648
</ErrorBoundary>,
1636
- container
1649
+ container,
1650
);
1651
expect(container.textContent).toBe('Caught an inner error: Hello.');
1652
expect(log).toEqual([
@@ -1647,29 +1660,31 @@ describe('ReactErrorBoundaries', () => {
1660
'InnerErrorBoundary render success',
1661
// Try unmounting child
1662
'BrokenComponentWillUnmount componentWillUnmount [!]',
1650
- ...(ReactDOMFeatureFlags.useFiber ? [
1651
- // Fiber proceeds with lifecycles despite errors
1652
- // Inner and outer boundaries have updated in this phase
1653
- 'InnerErrorBoundary componentDidUpdate',
1654
- 'OuterErrorBoundary componentDidUpdate',
1655
- // Now that commit phase is done, Fiber handles errors
1656
- // Only inner boundary receives the error:
1657
- 'InnerErrorBoundary unstable_handleError',
1658
- 'InnerErrorBoundary componentWillUpdate',
1659
- // Render an error now
1660
- 'InnerErrorBoundary render error',
1661
- // In Fiber, this was a local update to the
1662
- // inner boundary so only its hook fires
1663
- 'InnerErrorBoundary componentDidUpdate',
1664
- ] : [
1665
- // Stack will handle error immediately
1666
- 'InnerErrorBoundary unstable_handleError',
1667
- 'InnerErrorBoundary render error',
1668
- // In stack, this was a part of the update to the
1669
- // outer boundary so both lifecycles fire
1670
- 'InnerErrorBoundary componentDidUpdate',
1671
- 'OuterErrorBoundary componentDidUpdate',
1672
- ]),
1663
+ ...(ReactDOMFeatureFlags.useFiber
1664
+ ? [
1665
+ // Fiber proceeds with lifecycles despite errors
1666
+ // Inner and outer boundaries have updated in this phase
1667
+ 'InnerErrorBoundary componentDidUpdate',
1668
+ 'OuterErrorBoundary componentDidUpdate',
1669
+ // Now that commit phase is done, Fiber handles errors
1670
+ // Only inner boundary receives the error:
1671
+ 'InnerErrorBoundary unstable_handleError',
1672
+ 'InnerErrorBoundary componentWillUpdate',
1673
+ // Render an error now
1674
+ 'InnerErrorBoundary render error',
1675
+ // In Fiber, this was a local update to the
1676
+ // inner boundary so only its hook fires
1677
+ 'InnerErrorBoundary componentDidUpdate',
1678
+ ]
1679
+ : [
1680
+ // Stack will handle error immediately
1681
+ 'InnerErrorBoundary unstable_handleError',
1682
+ 'InnerErrorBoundary render error',
1683
+ // In stack, this was a part of the update to the
1684
+ // outer boundary so both lifecycles fire
1685
+ 'InnerErrorBoundary componentDidUpdate',
1686
+ 'OuterErrorBoundary componentDidUpdate',
1687
+ ]),
1688
]);
1689
1690
log.length = 0;
@@ -1686,14 +1701,14 @@ describe('ReactErrorBoundaries', () => {
1701
<ErrorBoundary>
1702
<BrokenRender />
1703
</ErrorBoundary>,
1689
- container
1704
+ container,
1705
);
1706
1707
ReactDOM.render(
1708
<ErrorBoundary>
1709
<Normal />
1710
</ErrorBoundary>,
1696
- container
1711
+ container,
1712
);
1713
// Error boundary doesn't retry by itself:
1714
expect(container.textContent).toBe('Caught an error: Hello.');
@@ -1704,7 +1719,7 @@ describe('ReactErrorBoundaries', () => {
1719
<ErrorBoundary forceRetry={true}>
1720
<Normal />
1721
</ErrorBoundary>,
1707
- container
1722
+ container,
1723
);
1724
expect(container.textContent).not.toContain('Caught an error');
1725
expect(log).toEqual([
@@ -1734,7 +1749,7 @@ describe('ReactErrorBoundaries', () => {
1749
<ErrorBoundary>
1750
<BrokenRender />
1751
</ErrorBoundary>,
1737
- container
1752
+ container,
1753
);
1754
expect(container.textContent).toBe('Caught an error: Hello.');
1755
@@ -1742,7 +1757,7 @@ describe('ReactErrorBoundaries', () => {
1757
<ErrorBoundary>
1758
<BrokenRender />
1759
</ErrorBoundary>,
1745
- container
1760
+ container,
1761
);
1762
expect(container.textContent).toBe('Caught an error: Hello.');
1763
@@ -1752,7 +1767,7 @@ describe('ReactErrorBoundaries', () => {
1767
ReactDOM.unmountComponentAtNode(container);
1768
});
1769
1755
- it('doesn\'t get into inconsistent state during removals', () => {
1770
+ it("doesn't get into inconsistent state during removals", () => {
1771
var container = document.createElement('div');
1772
ReactDOM.render(
1773
<ErrorBoundary>
@@ -1760,7 +1775,7 @@ describe('ReactErrorBoundaries', () => {
1775
<BrokenComponentWillUnmount />
1776
<Normal />
1777
</ErrorBoundary>,
1763
- container
1778
+ container,
1779
);
1780
1781
ReactDOM.render(<ErrorBoundary />, container);
@@ -1768,12 +1783,10 @@ describe('ReactErrorBoundaries', () => {
1783
1784
log.length = 0;
1785
ReactDOM.unmountComponentAtNode(container);
1771
- expect(log).toEqual([
1772
- 'ErrorBoundary componentWillUnmount',
1773
- ]);
1786
+ expect(log).toEqual(['ErrorBoundary componentWillUnmount']);
1787
});
1788
1776
- it('doesn\'t get into inconsistent state during additions', () => {
1789
+ it("doesn't get into inconsistent state during additions", () => {
1790
var container = document.createElement('div');
1791
ReactDOM.render(<ErrorBoundary />, container);
1792
ReactDOM.render(
@@ -1782,18 +1795,16 @@ describe('ReactErrorBoundaries', () => {
1795
<BrokenRender />
1796
<Normal />
1797
</ErrorBoundary>,
1785
- container
1798
+ container,
1799
);
1800
expect(container.textContent).toBe('Caught an error: Hello.');
1801
1802
log.length = 0;
1803
ReactDOM.unmountComponentAtNode(container);
1791
- expect(log).toEqual([
1792
- 'ErrorBoundary componentWillUnmount',
1793
- ]);
1804
+ expect(log).toEqual(['ErrorBoundary componentWillUnmount']);
1805
});
1806
1796
- it('doesn\'t get into inconsistent state during reorders', () => {
1807
+ it("doesn't get into inconsistent state during reorders", () => {
1808
function getAMixOfNormalAndBrokenRenderElements() {
1809
var elements = [];
1810
for (var i = 0; i < 100; i++) {
@@ -1827,7 +1838,7 @@ describe('ReactErrorBoundaries', () => {
1838
<ErrorBoundary>
1839
{getAMixOfNormalAndBrokenRenderElements()}
1840
</ErrorBoundary>,
1830
- container
1841
+ container,
1842
);
1843
expect(container.textContent).not.toContain('Caught an error');
1844
@@ -1836,15 +1847,13 @@ describe('ReactErrorBoundaries', () => {
1847
<ErrorBoundary>
1848
{getAMixOfNormalAndBrokenRenderElements()}
1849
</ErrorBoundary>,
1839
- container
1850
+ container,
1851
);
1852
expect(container.textContent).toBe('Caught an error: Hello.');
1853
1854
log.length = 0;
1855
ReactDOM.unmountComponentAtNode(container);
1845
- expect(log).toEqual([
1846
- 'ErrorBoundary componentWillUnmount',
1847
- ]);
1856
+ expect(log).toEqual(['ErrorBoundary componentWillUnmount']);
1857
});
1858
1859
// The tests below implement new features in Fiber.
@@ -1869,7 +1878,7 @@ describe('ReactErrorBoundaries', () => {
1878
<ErrorBoundary>
1879
<Stateful ref={inst => statefulInst = inst} />
1880
</ErrorBoundary>,
1872
- container
1881
+ container,
1882
);
1883
1884
log.length = 0;
@@ -1888,9 +1897,7 @@ describe('ReactErrorBoundaries', () => {
1897
1898
log.length = 0;
1899
ReactDOM.unmountComponentAtNode(container);
1891
- expect(log).toEqual([
1892
- 'ErrorBoundary componentWillUnmount',
1893
- ]);
1900
+ expect(log).toEqual(['ErrorBoundary componentWillUnmount']);
1901
});
1902
1903
it('catches errors in componentDidMount', () => {
@@ -1903,7 +1910,7 @@ describe('ReactErrorBoundaries', () => {
1910
<BrokenComponentDidMount />
1911
<Normal logName="LastChild" />
1912
</ErrorBoundary>,
1906
- container
1913
+ container,
1914
);
1915
expect(log).toEqual([
1916
'ErrorBoundary constructor',
@@ -1945,9 +1952,7 @@ describe('ReactErrorBoundaries', () => {
1952
1953
log.length = 0;
1954
ReactDOM.unmountComponentAtNode(container);
1948
- expect(log).toEqual([
1949
- 'ErrorBoundary componentWillUnmount',
1950
- ]);
1955
+ expect(log).toEqual(['ErrorBoundary componentWillUnmount']);
1956
});
1957
1958
it('catches errors in componentDidUpdate', () => {
@@ -1956,7 +1961,7 @@ describe('ReactErrorBoundaries', () => {
1961
<ErrorBoundary>
1962
<BrokenComponentDidUpdate />
1963
</ErrorBoundary>,
1959
- container
1964
+ container,
1965
);
1966
1967
log.length = 0;
@@ -1964,7 +1969,7 @@ describe('ReactErrorBoundaries', () => {
1969
<ErrorBoundary>
1970
<BrokenComponentDidUpdate />
1971
</ErrorBoundary>,
1967
- container
1972
+ container,
1973
);
1974
expect(log).toEqual([
1975
'ErrorBoundary componentWillReceiveProps',
@@ -1986,9 +1991,7 @@ describe('ReactErrorBoundaries', () => {
1991
1992
log.length = 0;
1993
ReactDOM.unmountComponentAtNode(container);
1989
- expect(log).toEqual([
1990
- 'ErrorBoundary componentWillUnmount',
1991
- ]);
1994
+ expect(log).toEqual(['ErrorBoundary componentWillUnmount']);
1995
});
1996
1997
it('propagates errors inside boundary during componentDidMount', () => {
@@ -2000,9 +2003,10 @@ describe('ReactErrorBoundaries', () => {
2003
<div>
2004
We should never catch our own error: {error.message}.
2005
</div>
2003
- )} />
2006
+ )}
2007
+ />
2008
</ErrorBoundary>,
2005
- container
2009
+ container,
2010
);
2011
expect(container.firstChild.textContent).toBe('Caught an error: Hello.');
2012
expect(log).toEqual([
@@ -2026,9 +2030,7 @@ describe('ReactErrorBoundaries', () => {
2030
2031
log.length = 0;
2032
ReactDOM.unmountComponentAtNode(container);
2029
- expect(log).toEqual([
2030
- 'ErrorBoundary componentWillUnmount',
2031
- ]);
2033
+ expect(log).toEqual(['ErrorBoundary componentWillUnmount']);
2034
});
2035
2036
it('lets different boundaries catch their own first errors', () => {
@@ -2042,33 +2044,41 @@ describe('ReactErrorBoundaries', () => {
2044
var container = document.createElement('div');
2045
ReactDOM.render(
2046
<ErrorBoundary logName="OuterErrorBoundary">
2045
- <ErrorBoundary logName="InnerUnmountBoundary" renderError={renderUnmountError}>
2047
+ <ErrorBoundary
2048
+ logName="InnerUnmountBoundary"
2049
+ renderError={renderUnmountError}>
2050
<BrokenComponentWillUnmount errorText="E1" />
2051
<BrokenComponentWillUnmount errorText="E2" />
2052
</ErrorBoundary>
2049
- <ErrorBoundary logName="InnerUpdateBoundary" renderError={renderUpdateError}>
2053
+ <ErrorBoundary
2054
+ logName="InnerUpdateBoundary"
2055
+ renderError={renderUpdateError}>
2056
<BrokenComponentDidUpdate errorText="E3" />
2057
<BrokenComponentDidUpdate errorText="E4" />
2058
</ErrorBoundary>
2059
</ErrorBoundary>,
2054
- container
2060
+ container,
2061
);
2062
2063
log.length = 0;
2064
ReactDOM.render(
2065
<ErrorBoundary logName="OuterErrorBoundary">
2060
- <ErrorBoundary logName="InnerUnmountBoundary" renderError={renderUnmountError} />
2061
- <ErrorBoundary logName="InnerUpdateBoundary" renderError={renderUpdateError}>
2066
+ <ErrorBoundary
2067
+ logName="InnerUnmountBoundary"
2068
+ renderError={renderUnmountError}
2069
+ />
2070
+ <ErrorBoundary
2071
+ logName="InnerUpdateBoundary"
2072
+ renderError={renderUpdateError}>
2073
<BrokenComponentDidUpdate errorText="E3" />
2074
<BrokenComponentDidUpdate errorText="E4" />
2075
</ErrorBoundary>
2076
</ErrorBoundary>,
2066
- container
2077
+ container,
2078
);
2079
2080
expect(container.firstChild.textContent).toBe(
2070
- 'Caught an unmounting error: E1.' +
2071
- 'Caught an updating error: E3.'
2081
+ 'Caught an unmounting error: E1.' + 'Caught an updating error: E3.',
2082
);
2083
expect(log).toEqual([
2084
// Begin update phase
@@ -2156,7 +2166,7 @@ describe('ReactErrorBoundaries', () => {
2166
<BrokenRender />
2167
</NoopErrorBoundary>
2168
</div>,
2159
- container
2169
+ container,
2170
);
2171
expect(container.firstChild.textContent).toBe('Sibling');
2172
expect(log).toEqual([
@@ -2174,9 +2184,7 @@ describe('ReactErrorBoundaries', () => {
2184
2185
log.length = 0;
2186
ReactDOM.unmountComponentAtNode(container);
2177
- expect(log).toEqual([
2178
- 'NoopErrorBoundary componentWillUnmount',
2179
- ]);
2187
+ expect(log).toEqual(['NoopErrorBoundary componentWillUnmount']);
2188
});
2189
2190
it('passes first error when two errors happen in commit', () => {
@@ -2213,13 +2221,9 @@ describe('ReactErrorBoundaries', () => {
2221
caughtError = e;
2222
}
2223
2216
- expect(errors).toEqual([
2217
- 'child sad',
2218
- 'parent sad',
2219
- ]);
2224
+ expect(errors).toEqual(['child sad', 'parent sad']);
2225
// Error should be the first thrown
2226
expect(caughtError.message).toBe('child sad');
2227
});
2228
}
2224
-
2229
});
src/renderers/__tests__/ReactHostOperationHistoryHook-test.js
+411
-316
@@ -51,13 +51,15 @@ describeStack('ReactHostOperationHistoryHook', () => {
51
ReactDOM.render(<div><p>Hi.</p></div>, node);
52
53
var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
54
- assertHistoryMatches([{
55
- instanceID: inst._debugID,
56
- type: 'mount',
57
- payload: ReactDOMFeatureFlags.useCreateElement ?
58
- 'DIV' :
59
- '<div data-reactroot="" data-reactid="1"><p data-reactid="2">Hi.</p></div>',
60
- }]);
54
+ assertHistoryMatches([
55
+ {
56
+ instanceID: inst._debugID,
57
+ type: 'mount',
58
+ payload: ReactDOMFeatureFlags.useCreateElement
59
+ ? 'DIV'
60
+ : '<div data-reactroot="" data-reactid="1"><p data-reactid="2">Hi.</p></div>',
61
+ },
62
+ ]);
63
});
64
65
it('gets recorded for composite roots', () => {
@@ -70,14 +72,16 @@ describeStack('ReactHostOperationHistoryHook', () => {
72
ReactDOM.render(<Foo />, node);
73
74
var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
73
- assertHistoryMatches([{
74
- instanceID: inst._debugID,
75
- type: 'mount',
76
- payload: ReactDOMFeatureFlags.useCreateElement ?
77
- 'DIV' :
78
- '<div data-reactroot="" data-reactid="1">' +
79
- '<p data-reactid="2">Hi.</p></div>',
80
- }]);
75
+ assertHistoryMatches([
76
+ {
77
+ instanceID: inst._debugID,
78
+ type: 'mount',
79
+ payload: ReactDOMFeatureFlags.useCreateElement
80
+ ? 'DIV'
81
+ : '<div data-reactroot="" data-reactid="1">' +
82
+ '<p data-reactid="2">Hi.</p></div>',
83
+ },
84
+ ]);
85
});
86
87
it('gets ignored for composite roots that return null', () => {
@@ -111,11 +115,13 @@ describeStack('ReactHostOperationHistoryHook', () => {
115
116
// Since empty components should be invisible to hooks,
117
// we record a "mount" event rather than a "replace with".
114
- assertHistoryMatches([{
115
- instanceID: inst._debugID,
116
- type: 'mount',
117
- payload: 'SPAN',
118
- }]);
118
+ assertHistoryMatches([
119
+ {
120
+ instanceID: inst._debugID,
121
+ type: 'mount',
122
+ payload: 'SPAN',
123
+ },
124
+ ]);
125
});
126
});
127
@@ -124,32 +130,42 @@ describeStack('ReactHostOperationHistoryHook', () => {
130
var node = document.createElement('div');
131
132
ReactHostOperationHistoryHook._preventClearing = true;
127
- ReactDOM.render(<div style={{
128
- color: 'red',
129
- backgroundColor: 'yellow',
130
- }} />, node);
133
+ ReactDOM.render(
134
+ <div
135
+ style={{
136
+ color: 'red',
137
+ backgroundColor: 'yellow',
138
+ }}
139
+ />,
140
+ node,
141
+ );
142
143
var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
144
if (ReactDOMFeatureFlags.useCreateElement) {
134
- assertHistoryMatches([{
135
- instanceID: inst._debugID,
136
- type: 'update styles',
137
- payload: {
138
- color: 'red',
139
- backgroundColor: 'yellow',
145
+ assertHistoryMatches([
146
+ {
147
+ instanceID: inst._debugID,
148
+ type: 'update styles',
149
+ payload: {
150
+ color: 'red',
151
+ backgroundColor: 'yellow',
152
+ },
153
},
141
- }, {
142
- instanceID: inst._debugID,
143
- type: 'mount',
144
- payload: 'DIV',
145
- }]);
154
+ {
155
+ instanceID: inst._debugID,
156
+ type: 'mount',
157
+ payload: 'DIV',
158
+ },
159
+ ]);
160
} else {
147
- assertHistoryMatches([{
148
- instanceID: inst._debugID,
149
- type: 'mount',
150
- payload: '<div style="color:red;background-color:yellow;" ' +
151
- 'data-reactroot="" data-reactid="1"></div>',
152
- }]);
161
+ assertHistoryMatches([
162
+ {
163
+ instanceID: inst._debugID,
164
+ type: 'mount',
165
+ payload: '<div style="color:red;background-color:yellow;" ' +
166
+ 'data-reactroot="" data-reactid="1"></div>',
167
+ },
168
+ ]);
169
}
170
});
171
@@ -159,31 +175,41 @@ describeStack('ReactHostOperationHistoryHook', () => {
175
var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
176
177
ReactHostOperationHistoryHook._preventClearing = true;
162
- ReactDOM.render(<div style={{ color: 'red' }} />, node);
163
- ReactDOM.render(<div style={{
164
- color: 'blue',
165
- backgroundColor: 'yellow',
166
- }} />, node);
167
- ReactDOM.render(<div style={{ backgroundColor: 'green' }} />, node);
178
+ ReactDOM.render(<div style={{color: 'red'}} />, node);
179
+ ReactDOM.render(
180
+ <div
181
+ style={{
182
+ color: 'blue',
183
+ backgroundColor: 'yellow',
184
+ }}
185
+ />,
186
+ node,
187
+ );
188
+ ReactDOM.render(<div style={{backgroundColor: 'green'}} />, node);
189
ReactDOM.render(<div />, node);
190
170
- assertHistoryMatches([{
171
- instanceID: inst._debugID,
172
- type: 'update styles',
173
- payload: { color: 'red' },
174
- }, {
175
- instanceID: inst._debugID,
176
- type: 'update styles',
177
- payload: { color: 'blue', backgroundColor: 'yellow' },
178
- }, {
179
- instanceID: inst._debugID,
180
- type: 'update styles',
181
- payload: { color: '', backgroundColor: 'green' },
182
- }, {
183
- instanceID: inst._debugID,
184
- type: 'update styles',
185
- payload: { backgroundColor: '' },
186
- }]);
191
+ assertHistoryMatches([
192
+ {
193
+ instanceID: inst._debugID,
194
+ type: 'update styles',
195
+ payload: {color: 'red'},
196
+ },
197
+ {
198
+ instanceID: inst._debugID,
199
+ type: 'update styles',
200
+ payload: {color: 'blue', backgroundColor: 'yellow'},
201
+ },
202
+ {
203
+ instanceID: inst._debugID,
204
+ type: 'update styles',
205
+ payload: {color: '', backgroundColor: 'green'},
206
+ },
207
+ {
208
+ instanceID: inst._debugID,
209
+ type: 'update styles',
210
+ payload: {backgroundColor: ''},
211
+ },
212
+ ]);
213
});
214
215
it('gets ignored if the styles are shallowly equal', () => {
@@ -192,23 +218,35 @@ describeStack('ReactHostOperationHistoryHook', () => {
218
var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
219
220
ReactHostOperationHistoryHook._preventClearing = true;
195
- ReactDOM.render(<div style={{
196
- color: 'red',
197
- backgroundColor: 'yellow',
198
- }} />, node);
199
- ReactDOM.render(<div style={{
200
- color: 'red',
201
- backgroundColor: 'yellow',
202
- }} />, node);
203
-
204
- assertHistoryMatches([{
205
- instanceID: inst._debugID,
206
- type: 'update styles',
207
- payload: {
208
- color: 'red',
209
- backgroundColor: 'yellow',
221
+ ReactDOM.render(
222
+ <div
223
+ style={{
224
+ color: 'red',
225
+ backgroundColor: 'yellow',
226
+ }}
227
+ />,
228
+ node,
229
+ );
230
+ ReactDOM.render(
231
+ <div
232
+ style={{
233
+ color: 'red',
234
+ backgroundColor: 'yellow',
235
+ }}
236
+ />,
237
+ node,
238
+ );
239
+
240
+ assertHistoryMatches([
241
+ {
242
+ instanceID: inst._debugID,
243
+ type: 'update styles',
244
+ payload: {
245
+ color: 'red',
246
+ backgroundColor: 'yellow',
247
+ },
248
},
211
- }]);
249
+ ]);
250
});
251
});
252
@@ -222,26 +260,32 @@ describeStack('ReactHostOperationHistoryHook', () => {
260
261
var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
262
if (ReactDOMFeatureFlags.useCreateElement) {
225
- assertHistoryMatches([{
226
- instanceID: inst._debugID,
227
- type: 'update attribute',
228
- payload: { className: 'rad' },
229
- }, {
230
- instanceID: inst._debugID,
231
- type: 'update attribute',
232
- payload: { tabIndex: 42 },
233
- }, {
234
- instanceID: inst._debugID,
235
- type: 'mount',
236
- payload: 'DIV',
237
- }]);
263
+ assertHistoryMatches([
264
+ {
265
+ instanceID: inst._debugID,
266
+ type: 'update attribute',
267
+ payload: {className: 'rad'},
268
+ },
269
+ {
270
+ instanceID: inst._debugID,
271
+ type: 'update attribute',
272
+ payload: {tabIndex: 42},
273
+ },
274
+ {
275
+ instanceID: inst._debugID,
276
+ type: 'mount',
277
+ payload: 'DIV',
278
+ },
279
+ ]);
280
} else {
239
- assertHistoryMatches([{
240
- instanceID: inst._debugID,
241
- type: 'mount',
242
- payload: '<div class="rad" tabindex="42" data-reactroot="" ' +
243
- 'data-reactid="1"></div>',
244
- }]);
281
+ assertHistoryMatches([
282
+ {
283
+ instanceID: inst._debugID,
284
+ type: 'mount',
285
+ payload: '<div class="rad" tabindex="42" data-reactroot="" ' +
286
+ 'data-reactid="1"></div>',
287
+ },
288
+ ]);
289
}
290
});
291
@@ -255,27 +299,33 @@ describeStack('ReactHostOperationHistoryHook', () => {
299
ReactDOM.render(<div className="mad" tabIndex={42} />, node);
300
ReactDOM.render(<div tabIndex={43} />, node);
301
258
- assertHistoryMatches([{
259
- instanceID: inst._debugID,
260
- type: 'update attribute',
261
- payload: { className: 'rad' },
262
- }, {
263
- instanceID: inst._debugID,
264
- type: 'update attribute',
265
- payload: { className: 'mad' },
266
- }, {
267
- instanceID: inst._debugID,
268
- type: 'update attribute',
269
- payload: { tabIndex: 42 },
270
- }, {
271
- instanceID: inst._debugID,
272
- type: 'remove attribute',
273
- payload: 'className',
274
- }, {
275
- instanceID: inst._debugID,
276
- type: 'update attribute',
277
- payload: { tabIndex: 43 },
278
- }]);
302
+ assertHistoryMatches([
303
+ {
304
+ instanceID: inst._debugID,
305
+ type: 'update attribute',
306
+ payload: {className: 'rad'},
307
+ },
308
+ {
309
+ instanceID: inst._debugID,
310
+ type: 'update attribute',
311
+ payload: {className: 'mad'},
312
+ },
313
+ {
314
+ instanceID: inst._debugID,
315
+ type: 'update attribute',
316
+ payload: {tabIndex: 42},
317
+ },
318
+ {
319
+ instanceID: inst._debugID,
320
+ type: 'remove attribute',
321
+ payload: 'className',
322
+ },
323
+ {
324
+ instanceID: inst._debugID,
325
+ type: 'update attribute',
326
+ payload: {tabIndex: 43},
327
+ },
328
+ ]);
329
});
330
});
331
@@ -289,15 +339,18 @@ describeStack('ReactHostOperationHistoryHook', () => {
339
ReactDOM.render(<div disabled={true} />, node);
340
ReactDOM.render(<div disabled={false} />, node);
341
292
- assertHistoryMatches([{
293
- instanceID: inst._debugID,
294
- type: 'update attribute',
295
- payload: { disabled: true },
296
- }, {
297
- instanceID: inst._debugID,
298
- type: 'remove attribute',
299
- payload: 'disabled',
300
- }]);
342
+ assertHistoryMatches([
343
+ {
344
+ instanceID: inst._debugID,
345
+ type: 'update attribute',
346
+ payload: {disabled: true},
347
+ },
348
+ {
349
+ instanceID: inst._debugID,
350
+ type: 'remove attribute',
351
+ payload: 'disabled',
352
+ },
353
+ ]);
354
});
355
});
356
@@ -310,26 +363,32 @@ describeStack('ReactHostOperationHistoryHook', () => {
363
364
var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
365
if (ReactDOMFeatureFlags.useCreateElement) {
313
- assertHistoryMatches([{
314
- instanceID: inst._debugID,
315
- type: 'update attribute',
316
- payload: { 'data-x': 'rad' },
317
- }, {
318
- instanceID: inst._debugID,
319
- type: 'update attribute',
320
- payload: { 'data-y': 42 },
321
- }, {
322
- instanceID: inst._debugID,
323
- type: 'mount',
324
- payload: 'DIV',
325
- }]);
366
+ assertHistoryMatches([
367
+ {
368
+ instanceID: inst._debugID,
369
+ type: 'update attribute',
370
+ payload: {'data-x': 'rad'},
371
+ },
372
+ {
373
+ instanceID: inst._debugID,
374
+ type: 'update attribute',
375
+ payload: {'data-y': 42},
376
+ },
377
+ {
378
+ instanceID: inst._debugID,
379
+ type: 'mount',
380
+ payload: 'DIV',
381
+ },
382
+ ]);
383
} else {
327
- assertHistoryMatches([{
328
- instanceID: inst._debugID,
329
- type: 'mount',
330
- payload: '<div data-x="rad" data-y="42" data-reactroot="" ' +
331
- 'data-reactid="1"></div>',
332
- }]);
384
+ assertHistoryMatches([
385
+ {
386
+ instanceID: inst._debugID,
387
+ type: 'mount',
388
+ payload: '<div data-x="rad" data-y="42" data-reactroot="" ' +
389
+ 'data-reactid="1"></div>',
390
+ },
391
+ ]);
392
}
393
});
394
@@ -343,27 +402,33 @@ describeStack('ReactHostOperationHistoryHook', () => {
402
ReactDOM.render(<div data-x="mad" data-y={42} />, node);
403
ReactDOM.render(<div data-y={43} />, node);
404
346
- assertHistoryMatches([{
347
- instanceID: inst._debugID,
348
- type: 'update attribute',
349
- payload: { 'data-x': 'rad' },
350
- }, {
351
- instanceID: inst._debugID,
352
- type: 'update attribute',
353
- payload: { 'data-x': 'mad' },
354
- }, {
355
- instanceID: inst._debugID,
356
- type: 'update attribute',
357
- payload: { 'data-y': 42 },
358
- }, {
359
- instanceID: inst._debugID,
360
- type: 'remove attribute',
361
- payload: 'data-x',
362
- }, {
363
- instanceID: inst._debugID,
364
- type: 'update attribute',
365
- payload: { 'data-y': 43 },
366
- }]);
405
+ assertHistoryMatches([
406
+ {
407
+ instanceID: inst._debugID,
408
+ type: 'update attribute',
409
+ payload: {'data-x': 'rad'},
410
+ },
411
+ {
412
+ instanceID: inst._debugID,
413
+ type: 'update attribute',
414
+ payload: {'data-x': 'mad'},
415
+ },
416
+ {
417
+ instanceID: inst._debugID,
418
+ type: 'update attribute',
419
+ payload: {'data-y': 42},
420
+ },
421
+ {
422
+ instanceID: inst._debugID,
423
+ type: 'remove attribute',
424
+ payload: 'data-x',
425
+ },
426
+ {
427
+ instanceID: inst._debugID,
428
+ type: 'update attribute',
429
+ payload: {'data-y': 43},
430
+ },
431
+ ]);
432
});
433
});
434
@@ -376,26 +441,32 @@ describeStack('ReactHostOperationHistoryHook', () => {
441
442
var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
443
if (ReactDOMFeatureFlags.useCreateElement) {
379
- assertHistoryMatches([{
380
- instanceID: inst._debugID,
381
- type: 'update attribute',
382
- payload: { className: 'rad' },
383
- }, {
384
- instanceID: inst._debugID,
385
- type: 'update attribute',
386
- payload: { tabIndex: 42 },
387
- }, {
388
- instanceID: inst._debugID,
389
- type: 'mount',
390
- payload: 'MY-COMPONENT',
391
- }]);
444
+ assertHistoryMatches([
445
+ {
446
+ instanceID: inst._debugID,
447
+ type: 'update attribute',
448
+ payload: {className: 'rad'},
449
+ },
450
+ {
451
+ instanceID: inst._debugID,
452
+ type: 'update attribute',
453
+ payload: {tabIndex: 42},
454
+ },
455
+ {
456
+ instanceID: inst._debugID,
457
+ type: 'mount',
458
+ payload: 'MY-COMPONENT',
459
+ },
460
+ ]);
461
} else {
393
- assertHistoryMatches([{
394
- instanceID: inst._debugID,
395
- type: 'mount',
396
- payload: '<my-component className="rad" tabIndex="42" ' +
397
- 'data-reactroot="" data-reactid="1"></my-component>',
398
- }]);
462
+ assertHistoryMatches([
463
+ {
464
+ instanceID: inst._debugID,
465
+ type: 'mount',
466
+ payload: '<my-component className="rad" tabIndex="42" ' +
467
+ 'data-reactroot="" data-reactid="1"></my-component>',
468
+ },
469
+ ]);
470
}
471
});
472
@@ -409,27 +480,33 @@ describeStack('ReactHostOperationHistoryHook', () => {
480
ReactDOM.render(<my-component className="mad" tabIndex={42} />, node);
481
ReactDOM.render(<my-component tabIndex={43} />, node);
482
412
- assertHistoryMatches([{
413
- instanceID: inst._debugID,
414
- type: 'update attribute',
415
- payload: { className: 'rad' },
416
- }, {
417
- instanceID: inst._debugID,
418
- type: 'update attribute',
419
- payload: { className: 'mad' },
420
- }, {
421
- instanceID: inst._debugID,
422
- type: 'update attribute',
423
- payload: { tabIndex: 42 },
424
- }, {
425
- instanceID: inst._debugID,
426
- type: 'remove attribute',
427
- payload: 'className',
428
- }, {
429
- instanceID: inst._debugID,
430
- type: 'update attribute',
431
- payload: { tabIndex: 43 },
432
- }]);
483
+ assertHistoryMatches([
484
+ {
485
+ instanceID: inst._debugID,
486
+ type: 'update attribute',
487
+ payload: {className: 'rad'},
488
+ },
489
+ {
490
+ instanceID: inst._debugID,
491
+ type: 'update attribute',
492
+ payload: {className: 'mad'},
493
+ },
494
+ {
495
+ instanceID: inst._debugID,
496
+ type: 'update attribute',
497
+ payload: {tabIndex: 42},
498
+ },
499
+ {
500
+ instanceID: inst._debugID,
501
+ type: 'remove attribute',
502
+ payload: 'className',
503
+ },
504
+ {
505
+ instanceID: inst._debugID,
506
+ type: 'update attribute',
507
+ payload: {tabIndex: 43},
508
+ },
509
+ ]);
510
});
511
});
512
});
@@ -444,26 +521,33 @@ describeStack('ReactHostOperationHistoryHook', () => {
521
ReactHostOperationHistoryHook._preventClearing = true;
522
ReactDOM.render(<div>Bye.</div>, node);
523
447
- assertHistoryMatches([{
448
- instanceID: inst._debugID,
449
- type: 'replace text',
450
- payload: 'Bye.',
451
- }]);
524
+ assertHistoryMatches([
525
+ {
526
+ instanceID: inst._debugID,
527
+ type: 'replace text',
528
+ payload: 'Bye.',
529
+ },
530
+ ]);
531
});
532
533
it('gets recorded during an update from html', () => {
534
var node = document.createElement('div');
456
- ReactDOM.render(<div dangerouslySetInnerHTML={{__html: 'Hi.'}} />, node);
535
+ ReactDOM.render(
536
+ <div dangerouslySetInnerHTML={{__html: 'Hi.'}} />,
537
+ node,
538
+ );
539
var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
540
541
ReactHostOperationHistoryHook._preventClearing = true;
542
ReactDOM.render(<div>Bye.</div>, node);
543
462
- assertHistoryMatches([{
463
- instanceID: inst._debugID,
464
- type: 'replace text',
465
- payload: 'Bye.',
466
- }]);
544
+ assertHistoryMatches([
545
+ {
546
+ instanceID: inst._debugID,
547
+ type: 'replace text',
548
+ payload: 'Bye.',
549
+ },
550
+ ]);
551
});
552
553
it('gets recorded during an update from children', () => {
@@ -474,19 +558,23 @@ describeStack('ReactHostOperationHistoryHook', () => {
558
ReactHostOperationHistoryHook._preventClearing = true;
559
ReactDOM.render(<div>Bye.</div>, node);
560
477
- assertHistoryMatches([{
478
- instanceID: inst._debugID,
479
- type: 'remove child',
480
- payload: {fromIndex: 0},
481
- }, {
482
- instanceID: inst._debugID,
483
- type: 'remove child',
484
- payload: {fromIndex: 1},
485
- }, {
486
- instanceID: inst._debugID,
487
- type: 'replace text',
488
- payload: 'Bye.',
489
- }]);
561
+ assertHistoryMatches([
562
+ {
563
+ instanceID: inst._debugID,
564
+ type: 'remove child',
565
+ payload: {fromIndex: 0},
566
+ },
567
+ {
568
+ instanceID: inst._debugID,
569
+ type: 'remove child',
570
+ payload: {fromIndex: 1},
571
+ },
572
+ {
573
+ instanceID: inst._debugID,
574
+ type: 'replace text',
575
+ payload: 'Bye.',
576
+ },
577
+ ]);
578
});
579
580
it('gets ignored if new text is equal', () => {
@@ -504,21 +592,28 @@ describeStack('ReactHostOperationHistoryHook', () => {
592
it('gets recorded during an update', () => {
593
var node = document.createElement('div');
594
ReactDOM.render(<div>{'Hi.'}{42}</div>, node);
507
- var inst1 = ReactDOMComponentTree.getInstanceFromNode(node.firstChild.childNodes[0]);
508
- var inst2 = ReactDOMComponentTree.getInstanceFromNode(node.firstChild.childNodes[3]);
595
+ var inst1 = ReactDOMComponentTree.getInstanceFromNode(
596
+ node.firstChild.childNodes[0],
597
+ );
598
+ var inst2 = ReactDOMComponentTree.getInstanceFromNode(
599
+ node.firstChild.childNodes[3],
600
+ );
601
602
ReactHostOperationHistoryHook._preventClearing = true;
603
ReactDOM.render(<div>{'Bye.'}{43}</div>, node);
604
513
- assertHistoryMatches([{
514
- instanceID: inst1._debugID,
515
- type: 'replace text',
516
- payload: 'Bye.',
517
- }, {
518
- instanceID: inst2._debugID,
519
- type: 'replace text',
520
- payload: '43',
521
- }]);
605
+ assertHistoryMatches([
606
+ {
607
+ instanceID: inst1._debugID,
608
+ type: 'replace text',
609
+ payload: 'Bye.',
610
+ },
611
+ {
612
+ instanceID: inst2._debugID,
613
+ type: 'replace text',
614
+ payload: '43',
615
+ },
616
+ ]);
617
});
618
619
it('gets ignored if new text is equal', () => {
@@ -550,11 +645,13 @@ describeStack('ReactHostOperationHistoryHook', () => {
645
ReactHostOperationHistoryHook._preventClearing = true;
646
ReactDOM.render(<Foo />, node);
647
553
- assertHistoryMatches([{
554
- instanceID: inst._debugID,
555
- type: 'replace with',
556
- payload: 'SPAN',
557
- }]);
648
+ assertHistoryMatches([
649
+ {
650
+ instanceID: inst._debugID,
651
+ type: 'replace with',
652
+ payload: 'SPAN',
653
+ },
654
+ ]);
655
});
656
657
it('gets recorded when composite renders to null after a native', () => {
@@ -573,11 +670,13 @@ describeStack('ReactHostOperationHistoryHook', () => {
670
ReactHostOperationHistoryHook._preventClearing = true;
671
ReactDOM.render(<Foo />, node);
672
576
- assertHistoryMatches([{
577
- instanceID: inst._debugID,
578
- type: 'replace with',
579
- payload: '#comment',
580
- }]);
673
+ assertHistoryMatches([
674
+ {
675
+ instanceID: inst._debugID,
676
+ type: 'replace with',
677
+ payload: '#comment',
678
+ },
679
+ ]);
680
});
681
682
it('gets ignored if the type has not changed', () => {
@@ -606,37 +705,32 @@ describeStack('ReactHostOperationHistoryHook', () => {
705
var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
706
707
ReactHostOperationHistoryHook._preventClearing = true;
609
- ReactDOM.render(
610
- <div dangerouslySetInnerHTML={{__html: 'Bye.'}} />,
611
- node
612
- );
708
+ ReactDOM.render(<div dangerouslySetInnerHTML={{__html: 'Bye.'}} />, node);
709
614
- assertHistoryMatches([{
615
- instanceID: inst._debugID,
616
- type: 'replace children',
617
- payload: 'Bye.',
618
- }]);
710
+ assertHistoryMatches([
711
+ {
712
+ instanceID: inst._debugID,
713
+ type: 'replace children',
714
+ payload: 'Bye.',
715
+ },
716
+ ]);
717
});
718
719
it('gets recorded during an update from html', () => {
720
var node = document.createElement('div');
623
- ReactDOM.render(
624
- <div dangerouslySetInnerHTML={{__html: 'Hi.'}} />,
625
- node
626
- );
721
+ ReactDOM.render(<div dangerouslySetInnerHTML={{__html: 'Hi.'}} />, node);
722
var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
723
724
ReactHostOperationHistoryHook._preventClearing = true;
630
- ReactDOM.render(
631
- <div dangerouslySetInnerHTML={{__html: 'Bye.'}} />,
632
- node
633
- );
725
+ ReactDOM.render(<div dangerouslySetInnerHTML={{__html: 'Bye.'}} />, node);
726
635
- assertHistoryMatches([{
636
- instanceID: inst._debugID,
637
- type: 'replace children',
638
- payload: 'Bye.',
639
- }]);
727
+ assertHistoryMatches([
728
+ {
729
+ instanceID: inst._debugID,
730
+ type: 'replace children',
731
+ payload: 'Bye.',
732
+ },
733
+ ]);
734
});
735
736
it('gets recorded during an update from children', () => {
@@ -645,38 +739,33 @@ describeStack('ReactHostOperationHistoryHook', () => {
739
var inst = ReactDOMComponentTree.getInstanceFromNode(node.firstChild);
740
741
ReactHostOperationHistoryHook._preventClearing = true;
648
- ReactDOM.render(
649
- <div dangerouslySetInnerHTML={{__html: 'Hi.'}} />,
650
- node
651
- );
742
+ ReactDOM.render(<div dangerouslySetInnerHTML={{__html: 'Hi.'}} />, node);
743
653
- assertHistoryMatches([{
654
- instanceID: inst._debugID,
655
- type: 'remove child',
656
- payload: {fromIndex: 0},
657
- }, {
658
- instanceID: inst._debugID,
659
- type: 'remove child',
660
- payload: {fromIndex: 1},
661
- }, {
662
- instanceID: inst._debugID,
663
- type: 'replace children',
664
- payload: 'Hi.',
665
- }]);
744
+ assertHistoryMatches([
745
+ {
746
+ instanceID: inst._debugID,
747
+ type: 'remove child',
748
+ payload: {fromIndex: 0},
749
+ },
750
+ {
751
+ instanceID: inst._debugID,
752
+ type: 'remove child',
753
+ payload: {fromIndex: 1},
754
+ },
755
+ {
756
+ instanceID: inst._debugID,
757
+ type: 'replace children',
758
+ payload: 'Hi.',
759
+ },
760
+ ]);
761
});
762
763
it('gets ignored if new html is equal', () => {
764
var node = document.createElement('div');
670
- ReactDOM.render(
671
- <div dangerouslySetInnerHTML={{__html: 'Hi.'}} />,
672
- node
673
- );
765
+ ReactDOM.render(<div dangerouslySetInnerHTML={{__html: 'Hi.'}} />, node);
766
767
ReactHostOperationHistoryHook._preventClearing = true;
676
- ReactDOM.render(
677
- <div dangerouslySetInnerHTML={{__html: 'Hi.'}} />,
678
- node
679
- );
768
+ ReactDOM.render(<div dangerouslySetInnerHTML={{__html: 'Hi.'}} />, node);
769
770
assertHistoryMatches([]);
771
});
@@ -691,11 +780,13 @@ describeStack('ReactHostOperationHistoryHook', () => {
780
ReactHostOperationHistoryHook._preventClearing = true;
781
ReactDOM.render(<div><span /><p /></div>, node);
782
694
- assertHistoryMatches([{
695
- instanceID: inst._debugID,
696
- type: 'insert child',
697
- payload: {toIndex: 1, content: 'P'},
698
- }]);
783
+ assertHistoryMatches([
784
+ {
785
+ instanceID: inst._debugID,
786
+ type: 'insert child',
787
+ payload: {toIndex: 1, content: 'P'},
788
+ },
789
+ ]);
790
});
791
});
792
@@ -708,11 +799,13 @@ describeStack('ReactHostOperationHistoryHook', () => {
799
ReactHostOperationHistoryHook._preventClearing = true;
800
ReactDOM.render(<div><p key="b" /><span key="a" /></div>, node);
801
711
- assertHistoryMatches([{
712
- instanceID: inst._debugID,
713
- type: 'move child',
714
- payload: {fromIndex: 0, toIndex: 1},
715
- }]);
802
+ assertHistoryMatches([
803
+ {
804
+ instanceID: inst._debugID,
805
+ type: 'move child',
806
+ payload: {fromIndex: 0, toIndex: 1},
807
+ },
808
+ ]);
809
});
810
});
811
@@ -725,11 +818,13 @@ describeStack('ReactHostOperationHistoryHook', () => {
818
ReactHostOperationHistoryHook._preventClearing = true;
819
ReactDOM.render(<div><span key="a" /></div>, node);
820
728
- assertHistoryMatches([{
729
- instanceID: inst._debugID,
730
- type: 'remove child',
731
- payload: {fromIndex: 1},
732
- }]);
821
+ assertHistoryMatches([
822
+ {
823
+ instanceID: inst._debugID,
824
+ type: 'remove child',
825
+ payload: {fromIndex: 1},
826
+ },
827
+ ]);
828
});
829
});
830
});
src/renderers/__tests__/ReactIdentity-test.js
+14
-28
@@ -17,7 +17,6 @@ var ReactFragment;
17
var ReactTestUtils;
18
19
describe('ReactIdentity', () => {
20
-
20
beforeEach(() => {
21
jest.resetModules();
22
React = require('react');
@@ -32,11 +31,12 @@ describe('ReactIdentity', () => {
31
32
it('should allow key property to express identity', () => {
33
var node;
35
- var Component = (props) =>
36
- <div ref={(c) => node = c}>
34
+ var Component = props => (
35
+ <div ref={c => node = c}>
36
<div key={props.swap ? 'banana' : 'apple'} />
37
<div key={props.swap ? 'apple' : 'banana'} />
39
- </div>;
38
+ </div>
39
+ );
40
41
var container = document.createElement('div');
42
ReactDOM.render(<Component />, container);
@@ -58,12 +58,12 @@ describe('ReactIdentity', () => {
58
var node1;
59
var node2;
60
ReactDOM.render(
61
- <Wrapper key="wrap1"><span ref={(c) => node1 = c} /></Wrapper>,
62
- container
61
+ <Wrapper key="wrap1"><span ref={c => node1 = c} /></Wrapper>,
62
+ container,
63
);
64
ReactDOM.render(
65
- <Wrapper key="wrap2"><span ref={(c) => node2 = c} /></Wrapper>,
66
- container
65
+ <Wrapper key="wrap2"><span ref={c => node2 = c} /></Wrapper>,
66
+ container,
67
);
68
69
expect(node1).not.toBe(node2);
@@ -91,10 +91,7 @@ describe('ReactIdentity', () => {
91
92
it('should allow any character as a key, in a detached parent', () => {
93
var detachedContainer = document.createElement('div');
94
- renderAComponentWithKeyIntoContainer(
95
- "<'WEIRD/&\\key'>",
96
- detachedContainer
97
- );
94
+ renderAComponentWithKeyIntoContainer("<'WEIRD/&\\key'>", detachedContainer);
95
});
96
97
it('should allow any character as a key, in an attached parent', () => {
@@ -103,17 +100,13 @@ describe('ReactIdentity', () => {
100
var attachedContainer = document.createElement('div');
101
document.body.appendChild(attachedContainer);
102
106
- renderAComponentWithKeyIntoContainer(
107
- "<'WEIRD/&\\key'>",
108
- attachedContainer
109
- );
103
+ renderAComponentWithKeyIntoContainer("<'WEIRD/&\\key'>", attachedContainer);
104
105
document.body.removeChild(attachedContainer);
106
});
107
108
it('should not allow scripts in keys to execute', () => {
115
- var h4x0rKey =
116
- '"><script>window[\'YOUVEBEENH4X0RED\']=true;</script><div id="';
109
+ var h4x0rKey = '"><script>window[\'YOUVEBEENH4X0RED\']=true;</script><div id="';
110
111
var attachedContainer = document.createElement('div');
112
document.body.appendChild(attachedContainer);
@@ -150,9 +143,7 @@ describe('ReactIdentity', () => {
143
}
144
145
expect(function() {
153
-
146
ReactTestUtils.renderIntoDocument(<TestContainer />);
155
-
147
}).not.toThrow();
148
});
149
@@ -184,9 +175,7 @@ describe('ReactIdentity', () => {
175
}
176
177
expect(function() {
187
-
178
ReactTestUtils.renderIntoDocument(<TestContainer />);
189
-
179
}).not.toThrow();
180
});
181
@@ -209,9 +198,7 @@ describe('ReactIdentity', () => {
198
}
199
200
expect(function() {
212
-
201
ReactTestUtils.renderIntoDocument(<TestContainer />);
214
-
202
}).not.toThrow();
203
});
204
@@ -258,16 +245,15 @@ describe('ReactIdentity', () => {
245
});
246
247
it('should not allow implicit and explicit keys to collide', () => {
261
- var component =
248
+ var component = (
249
<div>
250
<span />
251
<span key="0" />
265
- </div>;
252
+ </div>
253
+ );
254
255
expect(function() {
256
ReactTestUtils.renderIntoDocument(component);
257
}).not.toThrow();
258
});
271
-
272
-
259
});
src/renderers/__tests__/ReactMockedComponent-test.js
+8
-6
@@ -18,13 +18,16 @@ var AutoMockedComponent;
18
var MockedComponent;
19
20
describe('ReactMockedComponent', () => {
21
-
21
beforeEach(() => {
22
React = require('react');
23
ReactTestUtils = require('ReactTestUtils');
24
26
- AutoMockedComponent = jest.genMockFromModule('ReactMockedComponentTestComponent');
27
- MockedComponent = jest.genMockFromModule('ReactMockedComponentTestComponent');
25
+ AutoMockedComponent = jest.genMockFromModule(
26
+ 'ReactMockedComponentTestComponent',
27
+ );
28
+ MockedComponent = jest.genMockFromModule(
29
+ 'ReactMockedComponentTestComponent',
30
+ );
31
32
ReactTestUtils.mockComponent(MockedComponent);
33
});
@@ -52,7 +55,7 @@ describe('ReactMockedComponent', () => {
55
56
var found = ReactTestUtils.findRenderedComponentWithType(
57
instance,
55
- AutoMockedComponent
58
+ AutoMockedComponent,
59
);
60
expect(typeof found).toBe('object');
61
@@ -85,7 +88,7 @@ describe('ReactMockedComponent', () => {
88
89
var found = ReactTestUtils.findRenderedComponentWithType(
90
instance,
88
- MockedComponent
91
+ MockedComponent,
92
);
93
expect(typeof found).toBe('object');
94
@@ -96,5 +99,4 @@ describe('ReactMockedComponent', () => {
99
var instance = ReactTestUtils.renderIntoDocument(<MockedComponent />);
100
expect(typeof instance.hasCustomMethod).toBe('function');
101
});
99
-
102
});
src/renderers/__tests__/ReactMultiChild-test.js
+35
-39
@@ -119,7 +119,7 @@ describe('ReactMultiChild', () => {
119
120
ReactDOM.render(
121
<WrapperComponent><MockComponent /></WrapperComponent>,
122
- container
122
+ container,
123
);
124
125
expect(mockMount.mock.calls.length).toBe(1);
@@ -177,25 +177,24 @@ describe('ReactMultiChild', () => {
177
}
178
}
179
180
- ReactDOM.render(
181
- <Parent>{[<div key="1" />]}</Parent>,
182
- container
183
- );
180
+ ReactDOM.render(<Parent>{[<div key="1" />]}</Parent>, container);
181
182
ReactDOM.render(
183
<Parent>{[<div key="1" />, <div key="1" />]}</Parent>,
187
- container
184
+ container,
185
);
186
187
expectDev(console.error.calls.count()).toBe(1);
191
- expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toContain(
188
+ expectDev(
189
+ normalizeCodeLocInfo(console.error.calls.argsFor(0)[0]),
190
+ ).toContain(
191
'Encountered two children with the same key, `1`. ' +
193
- 'Child keys must be unique; when two children share a key, ' +
194
- 'only the first child will be used.\n' +
195
- ' in div (at **)\n' +
196
- ' in WrapperComponent (at **)\n' +
197
- ' in div (at **)\n' +
198
- ' in Parent (at **)'
192
+ 'Child keys must be unique; when two children share a key, ' +
193
+ 'only the first child will be used.\n' +
194
+ ' in div (at **)\n' +
195
+ ' in WrapperComponent (at **)\n' +
196
+ ' in div (at **)\n' +
197
+ ' in Parent (at **)',
198
);
199
});
200
@@ -242,23 +241,25 @@ describe('ReactMultiChild', () => {
241
242
ReactDOM.render(
243
<Parent>{createIterable([<div key="1" />])}</Parent>,
245
- container
244
+ container,
245
);
246
247
ReactDOM.render(
248
<Parent>{createIterable([<div key="1" />, <div key="1" />])}</Parent>,
250
- container
249
+ container,
250
);
251
252
expectDev(console.error.calls.count()).toBe(1);
254
- expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toContain(
253
+ expectDev(
254
+ normalizeCodeLocInfo(console.error.calls.argsFor(0)[0]),
255
+ ).toContain(
256
'Encountered two children with the same key, `1`. ' +
256
- 'Child keys must be unique; when two children share a key, ' +
257
- 'only the first child will be used.\n' +
258
- ' in div (at **)\n' +
259
- ' in WrapperComponent (at **)\n' +
260
- ' in div (at **)\n' +
261
- ' in Parent (at **)'
257
+ 'Child keys must be unique; when two children share a key, ' +
258
+ 'only the first child will be used.\n' +
259
+ ' in div (at **)\n' +
260
+ ' in WrapperComponent (at **)\n' +
261
+ ' in div (at **)\n' +
262
+ ' in Parent (at **)',
263
);
264
});
265
});
@@ -267,9 +268,7 @@ describe('ReactMultiChild', () => {
268
spyOn(console, 'error');
269
class Parent extends React.Component {
270
render() {
270
- return (
271
- <div>{new Map([['foo', 0], ['bar', 1]])}</div>
272
- );
271
+ return <div>{new Map([['foo', 0], ['bar', 1]])}</div>;
272
}
273
}
274
var container = document.createElement('div');
@@ -277,8 +276,8 @@ describe('ReactMultiChild', () => {
276
expectDev(console.error.calls.count()).toBe(1);
277
expectDev(console.error.calls.argsFor(0)[0]).toBe(
278
'Warning: Using Maps as children is unsupported and will likely yield ' +
280
- 'unexpected results. Convert it to a sequence/iterable of keyed ' +
281
- 'ReactElements instead.\n\nCheck the render method of `Parent`.'
279
+ 'unexpected results. Convert it to a sequence/iterable of keyed ' +
280
+ 'ReactElements instead.\n\nCheck the render method of `Parent`.',
281
);
282
});
283
@@ -303,7 +302,7 @@ describe('ReactMultiChild', () => {
302
class Letters extends React.Component {
303
render() {
304
const letters = this.props.letters.split('');
306
- return <div>{letters.map((c) => <Letter key={c} char={c} />)}</div>;
305
+ return <div>{letters.map(c => <Letter key={c} char={c} />)}</div>;
306
}
307
}
308
@@ -337,8 +336,8 @@ describe('ReactMultiChild', () => {
336
337
// These are reference-unequal so they will be swapped even if they have
338
// matching keys
340
- var SpyA = (props) => <Spy {...props} />;
341
- var SpyB = (props) => <Spy {...props} />;
339
+ var SpyA = props => <Spy {...props} />;
340
+ var SpyB = props => <Spy {...props} />;
341
342
var container = document.createElement('div');
343
ReactDOM.render(
@@ -346,14 +345,14 @@ describe('ReactMultiChild', () => {
345
<SpyA key="one" name="oneA" />
346
<SpyA key="two" name="twoA" />
347
</div>,
349
- container
348
+ container,
349
);
350
ReactDOM.render(
351
<div>
352
<SpyB key="one" name="oneB" />
353
<SpyB key="two" name="twoB" />
354
</div>,
356
- container
355
+ container,
356
);
357
358
expect(log).toEqual([
@@ -364,9 +363,8 @@ describe('ReactMultiChild', () => {
363
'oneA componentDidMount',
364
'twoA componentDidMount',
365
367
- ...(
368
- ReactDOMFeatureFlags.useFiber
369
- ? [
366
+ ...(ReactDOMFeatureFlags.useFiber
367
+ ? [
368
'oneB componentWillMount',
369
'oneB render',
370
'twoB componentWillMount',
@@ -374,19 +372,17 @@ describe('ReactMultiChild', () => {
372
'oneA componentWillUnmount',
373
'twoA componentWillUnmount',
374
]
377
- : [
375
+ : [
376
'oneB componentWillMount',
377
'oneB render',
378
'oneA componentWillUnmount',
379
'twoB componentWillMount',
380
'twoB render',
381
'twoA componentWillUnmount',
384
- ]
385
- ),
382
+ ]),
383
384
'oneB componentDidMount',
385
'twoB componentDidMount',
386
]);
387
});
391
-
388
});
src/renderers/__tests__/ReactMultiChildReconcile-test.js
+70
-55
@@ -119,14 +119,15 @@ class FriendsStatusDisplay extends React.Component {
119
for (var key in this.props.usernameToStatus) {
120
var status = this.props.usernameToStatus[key];
121
children.push(
122
- !status ? null :
123
- <StatusDisplay
124
- key={key}
125
- ref={key}
126
- contentKey={key}
127
- onFlush={this.verifyPreviousRefsResolved.bind(this, key)}
128
- status={status}
129
- />
122
+ !status
123
+ ? null
124
+ : <StatusDisplay
125
+ key={key}
126
+ ref={key}
127
+ contentKey={key}
128
+ onFlush={this.verifyPreviousRefsResolved.bind(this, key)}
129
+ status={status}
130
+ />,
131
);
132
}
133
var childrenToRender = this.props.prepareChildren(children);
@@ -138,12 +139,14 @@ class FriendsStatusDisplay extends React.Component {
139
}
140
}
141
141
-
142
function getInternalStateByUserName(statusDisplays) {
143
- return Object.keys(statusDisplays).reduce((acc, key) => {
144
- acc[key] = statusDisplays[key].getInternalState();
145
- return acc;
146
- }, {});
143
+ return Object.keys(statusDisplays).reduce(
144
+ (acc, key) => {
145
+ acc[key] = statusDisplays[key].getInternalState();
146
+ return acc;
147
+ },
148
+ {},
149
+ );
150
}
151
152
/**
@@ -155,14 +158,16 @@ function verifyStatuses(statusDisplays, props) {
158
var nonEmptyStatusDisplays = stripEmptyValues(statusDisplays);
159
var nonEmptyStatusProps = stripEmptyValues(props.usernameToStatus);
160
var username;
158
- expect(Object.keys(nonEmptyStatusDisplays).length)
159
- .toEqual(Object.keys(nonEmptyStatusProps).length);
161
+ expect(Object.keys(nonEmptyStatusDisplays).length).toEqual(
162
+ Object.keys(nonEmptyStatusProps).length,
163
+ );
164
for (username in nonEmptyStatusDisplays) {
165
if (!nonEmptyStatusDisplays.hasOwnProperty(username)) {
166
continue;
167
}
164
- expect(nonEmptyStatusDisplays[username].getStatus())
165
- .toEqual(nonEmptyStatusProps[username]);
168
+ expect(nonEmptyStatusDisplays[username].getStatus()).toEqual(
169
+ nonEmptyStatusProps[username],
170
+ );
171
}
172
173
// now go the other way to make sure we got them all.
@@ -170,12 +175,14 @@ function verifyStatuses(statusDisplays, props) {
175
if (!nonEmptyStatusProps.hasOwnProperty(username)) {
176
continue;
177
}
173
- expect(nonEmptyStatusDisplays[username].getStatus())
174
- .toEqual(nonEmptyStatusProps[username]);
178
+ expect(nonEmptyStatusDisplays[username].getStatus()).toEqual(
179
+ nonEmptyStatusProps[username],
180
+ );
181
}
182
177
- expect(Object.keys(nonEmptyStatusDisplays))
178
- .toEqual(Object.keys(nonEmptyStatusProps));
183
+ expect(Object.keys(nonEmptyStatusDisplays)).toEqual(
184
+ Object.keys(nonEmptyStatusProps),
185
+ );
186
}
187
188
/**
@@ -191,13 +198,13 @@ function verifyStatesPreserved(lastInternalStates, statusDisplays) {
198
continue;
199
}
200
if (lastInternalStates[key]) {
194
- expect(lastInternalStates[key])
195
- .toEqual(statusDisplays[key].getInternalState());
201
+ expect(lastInternalStates[key]).toEqual(
202
+ statusDisplays[key].getInternalState(),
203
+ );
204
}
205
}
206
}
207
200
-
208
/**
209
* Verifies that the internal representation of a set of `renderedChildren`
210
* accurately reflects what is in the DOM.
@@ -218,9 +225,7 @@ function verifyDomOrderingAccurate(outerContainer, statusDisplays) {
225
continue;
226
}
227
var statusDisplay = statusDisplays[username];
221
- orderedLogicalKeys.push(
222
- statusDisplay.props.contentKey
223
- );
228
+ orderedLogicalKeys.push(statusDisplay.props.contentKey);
229
}
230
expect(orderedDomKeys).toEqual(orderedLogicalKeys);
231
}
@@ -228,11 +233,8 @@ function verifyDomOrderingAccurate(outerContainer, statusDisplays) {
233
function testPropsSequenceWithPreparedChildren(sequence, prepareChildren) {
234
var container = document.createElement('div');
235
var parentInstance = ReactDOM.render(
231
- <FriendsStatusDisplay
232
- {...sequence[0]}
233
- prepareChildren={prepareChildren}
234
- />,
235
- container
236
+ <FriendsStatusDisplay {...sequence[0]} prepareChildren={prepareChildren} />,
237
+ container,
238
);
239
var statusDisplays = parentInstance.getStatusDisplays();
240
var lastInternalStates = getInternalStateByUserName(statusDisplays);
@@ -244,7 +246,7 @@ function testPropsSequenceWithPreparedChildren(sequence, prepareChildren) {
246
{...sequence[i]}
247
prepareChildren={prepareChildren}
248
/>,
247
- container
249
+ container,
250
);
251
statusDisplays = parentInstance.getStatusDisplays();
252
verifyStatuses(statusDisplays, sequence[i]);
@@ -289,8 +291,11 @@ describe('ReactMultiChildReconcile', () => {
291
292
var container = document.createElement('div');
293
var parentInstance = ReactDOM.render(
292
- <FriendsStatusDisplay {...props} prepareChildren={prepareChildrenArray} />,
293
- container
294
+ <FriendsStatusDisplay
295
+ {...props}
296
+ prepareChildren={prepareChildrenArray}
297
+ />,
298
+ container,
299
);
300
var statusDisplays = parentInstance.getStatusDisplays();
301
var startingInternalState = statusDisplays.jcw.getInternalState();
@@ -298,20 +303,24 @@ describe('ReactMultiChildReconcile', () => {
303
// Now remove the child.
304
ReactDOM.render(
305
<FriendsStatusDisplay prepareChildren={prepareChildrenArray} />,
301
- container
306
+ container,
307
);
308
statusDisplays = parentInstance.getStatusDisplays();
309
expect(statusDisplays.jcw).toBeFalsy();
310
311
// Now reset the props that cause there to be a child
312
ReactDOM.render(
308
- <FriendsStatusDisplay {...props} prepareChildren={prepareChildrenArray} />,
309
- container
313
+ <FriendsStatusDisplay
314
+ {...props}
315
+ prepareChildren={prepareChildrenArray}
316
+ />,
317
+ container,
318
);
319
statusDisplays = parentInstance.getStatusDisplays();
320
expect(statusDisplays.jcw).toBeTruthy();
313
- expect(statusDisplays.jcw.getInternalState())
314
- .not.toBe(startingInternalState);
321
+ expect(statusDisplays.jcw.getInternalState()).not.toBe(
322
+ startingInternalState,
323
+ );
324
});
325
326
it('should reset internal state if removed then readded in an iterable', () => {
@@ -324,8 +333,11 @@ describe('ReactMultiChildReconcile', () => {
333
334
var container = document.createElement('div');
335
var parentInstance = ReactDOM.render(
327
- <FriendsStatusDisplay {...props} prepareChildren={prepareChildrenIterable} />,
328
- container
336
+ <FriendsStatusDisplay
337
+ {...props}
338
+ prepareChildren={prepareChildrenIterable}
339
+ />,
340
+ container,
341
);
342
var statusDisplays = parentInstance.getStatusDisplays();
343
var startingInternalState = statusDisplays.jcw.getInternalState();
@@ -333,20 +345,24 @@ describe('ReactMultiChildReconcile', () => {
345
// Now remove the child.
346
ReactDOM.render(
347
<FriendsStatusDisplay prepareChildren={prepareChildrenIterable} />,
336
- container
348
+ container,
349
);
350
statusDisplays = parentInstance.getStatusDisplays();
351
expect(statusDisplays.jcw).toBeFalsy();
352
353
// Now reset the props that cause there to be a child
354
ReactDOM.render(
343
- <FriendsStatusDisplay {...props} prepareChildren={prepareChildrenIterable} />,
344
- container
355
+ <FriendsStatusDisplay
356
+ {...props}
357
+ prepareChildren={prepareChildrenIterable}
358
+ />,
359
+ container,
360
);
361
statusDisplays = parentInstance.getStatusDisplays();
362
expect(statusDisplays.jcw).toBeTruthy();
348
- expect(statusDisplays.jcw.getInternalState())
349
- .not.toBe(startingInternalState);
363
+ expect(statusDisplays.jcw.getInternalState()).not.toBe(
364
+ startingInternalState,
365
+ );
366
});
367
368
it('should create unique identity', () => {
@@ -380,7 +396,7 @@ describe('ReactMultiChildReconcile', () => {
396
397
it('should transition from zero to one children correctly', () => {
398
var PROPS_SEQUENCE = [
383
- {usernameToStatus: {} },
399
+ {usernameToStatus: {}},
400
{
401
usernameToStatus: {
402
first: 'firstStatus',
@@ -397,7 +413,7 @@ describe('ReactMultiChildReconcile', () => {
413
first: 'firstStatus',
414
},
415
},
400
- {usernameToStatus: {} },
416
+ {usernameToStatus: {}},
417
];
418
testPropsSequence(PROPS_SEQUENCE);
419
});
@@ -442,8 +458,6 @@ describe('ReactMultiChildReconcile', () => {
458
]);
459
});
460
445
-
446
-
461
/**
462
* `FriendsStatusDisplay` renders nulls as empty children (it's a convention
463
* of `FriendsStatusDisplay`, nothing related to React or these test cases.
@@ -557,7 +571,8 @@ describe('ReactMultiChildReconcile', () => {
571
},
572
},
573
{
560
- usernameToStatus: { // Full circle!
574
+ usernameToStatus: {
575
+ // Full circle!
576
userOne: 'userOneStatus',
577
userTwo: 'userTwoStatus',
578
userThree: 'userThreeStatus',
@@ -603,7 +618,8 @@ describe('ReactMultiChildReconcile', () => {
618
},
619
},
620
{
606
- usernameToStatus: { // Full circle!
621
+ usernameToStatus: {
622
+ // Full circle!
623
userOne: 'userOneStatus',
624
userTwo: 'userTwoStatus',
625
userThree: 'userThreeStatus',
@@ -614,7 +630,6 @@ describe('ReactMultiChildReconcile', () => {
630
testPropsSequence(PROPS_SEQUENCE);
631
});
632
617
-
633
it('should remove nulled out children and ignore new null children', () => {
634
var PROPS_SEQUENCE = [
635
{
@@ -640,7 +655,7 @@ describe('ReactMultiChildReconcile', () => {
655
usernameToStatus: {
656
jcw: 'jcwStatus',
657
jordanjcw: 'jordanjcwStatus',
643
- john: 'johnStatus', // john will go away
658
+ john: 'johnStatus', // john will go away
659
joe: 'joeStatus',
660
},
661
},
src/renderers/__tests__/ReactMultiChildText-test.js
+2
-3
@@ -96,7 +96,6 @@ var expectChildren = function(container, children) {
96
}
97
};
98
99
-
99
/**
100
* ReactMultiChild DOM integration test. In ReactDOM components, we make sure
101
* that single children that are strings are treated as "content" which is much
@@ -194,14 +193,14 @@ describe('ReactMultiChildText', () => {
193
]);
194
expectDev(console.error.calls.count()).toBe(1);
195
expectDev(console.error.calls.argsFor(0)[0]).toContain(
197
- 'Warning: Each child in an array or iterator should have a unique "key" prop.'
196
+ 'Warning: Each child in an array or iterator should have a unique "key" prop.',
197
);
198
});
199
200
it('should throw if rendering both HTML and children', () => {
201
expect(function() {
202
ReactTestUtils.renderIntoDocument(
204
- <div dangerouslySetInnerHTML={{__html: 'abcdef'}}>ghjkl</div>
203
+ <div dangerouslySetInnerHTML={{__html: 'abcdef'}}>ghjkl</div>,
204
);
205
}).toThrow();
206
});
src/renderers/__tests__/ReactPerf-test.js
+136
-118
@@ -104,17 +104,20 @@ describeStack('ReactPerf', () => {
104
});
105
106
var summary = ReactPerf.getWasted(measurements);
107
- expect(summary).toEqual([{
108
- key: 'App',
109
- instanceCount: 1,
110
- inclusiveRenderDuration: 3,
111
- renderCount: 1,
112
- }, {
113
- key: 'App > Box',
114
- instanceCount: 2,
115
- inclusiveRenderDuration: 2,
116
- renderCount: 2,
117
- }]);
107
+ expect(summary).toEqual([
108
+ {
109
+ key: 'App',
110
+ instanceCount: 1,
111
+ inclusiveRenderDuration: 3,
112
+ renderCount: 1,
113
+ },
114
+ {
115
+ key: 'App > Box',
116
+ instanceCount: 2,
117
+ inclusiveRenderDuration: 2,
118
+ renderCount: 2,
119
+ },
120
+ ]);
121
});
122
123
it('should count no-op update in child as waste', () => {
@@ -128,12 +131,14 @@ describeStack('ReactPerf', () => {
131
});
132
133
var summary = ReactPerf.getWasted(measurements);
131
- expect(summary).toEqual([{
132
- key: 'App > Box',
133
- instanceCount: 1,
134
- inclusiveRenderDuration: 1,
135
- renderCount: 1,
136
- }]);
134
+ expect(summary).toEqual([
135
+ {
136
+ key: 'App > Box',
137
+ instanceCount: 1,
138
+ inclusiveRenderDuration: 1,
139
+ renderCount: 1,
140
+ },
141
+ ]);
142
});
143
144
function expectNoWaste(fn) {
@@ -208,12 +213,12 @@ describeStack('ReactPerf', () => {
213
var container = document.createElement('div');
214
ReactDOM.render(
215
<Div dangerouslySetInnerHTML={{__html: 'me'}} />,
211
- container
216
+ container,
217
);
218
expectNoWaste(() => {
219
ReactDOM.render(
220
<Div dangerouslySetInnerHTML={{__html: 'you'}} />,
216
- container
221
+ container,
222
);
223
});
224
});
@@ -266,13 +271,15 @@ describeStack('ReactPerf', () => {
271
ReactDOM.render(<Div><Div key="a" /></Div>, container);
272
ReactDOM.render(<Div><Div key="b" /></Div>, container);
273
});
269
- expect(ReactPerf.getExclusive(measurements)).toEqual([{
270
- key: 'Div',
271
- instanceCount: 3,
272
- counts: { ctor: 3, render: 4 },
273
- durations: { ctor: 3, render: 4 },
274
- totalDuration: 7,
275
- }]);
274
+ expect(ReactPerf.getExclusive(measurements)).toEqual([
275
+ {
276
+ key: 'Div',
277
+ instanceCount: 3,
278
+ counts: {ctor: 3, render: 4},
279
+ durations: {ctor: 3, render: 4},
280
+ totalDuration: 7,
281
+ },
282
+ ]);
283
});
284
285
it('should include lifecycle methods in measurements', () => {
@@ -283,33 +290,35 @@ describeStack('ReactPerf', () => {
290
instance.setState({});
291
ReactDOM.unmountComponentAtNode(container);
292
});
286
- expect(ReactPerf.getExclusive(measurements)).toEqual([{
287
- key: 'LifeCycle',
288
- instanceCount: 1,
289
- totalDuration: 14,
290
- counts: {
291
- ctor: 1,
292
- shouldComponentUpdate: 2,
293
- componentWillMount: 1,
294
- componentDidMount: 1,
295
- componentWillReceiveProps: 1,
296
- componentWillUpdate: 2,
297
- componentDidUpdate: 2,
298
- componentWillUnmount: 1,
299
- render: 3,
300
- },
301
- durations: {
302
- ctor: 1,
303
- shouldComponentUpdate: 2,
304
- componentWillMount: 1,
305
- componentDidMount: 1,
306
- componentWillReceiveProps: 1,
307
- componentWillUpdate: 2,
308
- componentDidUpdate: 2,
309
- componentWillUnmount: 1,
310
- render: 3,
293
+ expect(ReactPerf.getExclusive(measurements)).toEqual([
294
+ {
295
+ key: 'LifeCycle',
296
+ instanceCount: 1,
297
+ totalDuration: 14,
298
+ counts: {
299
+ ctor: 1,
300
+ shouldComponentUpdate: 2,
301
+ componentWillMount: 1,
302
+ componentDidMount: 1,
303
+ componentWillReceiveProps: 1,
304
+ componentWillUpdate: 2,
305
+ componentDidUpdate: 2,
306
+ componentWillUnmount: 1,
307
+ render: 3,
308
+ },
309
+ durations: {
310
+ ctor: 1,
311
+ shouldComponentUpdate: 2,
312
+ componentWillMount: 1,
313
+ componentDidMount: 1,
314
+ componentWillReceiveProps: 1,
315
+ componentWillUpdate: 2,
316
+ componentDidUpdate: 2,
317
+ componentWillUnmount: 1,
318
+ render: 3,
319
+ },
320
},
312
- }]);
321
+ ]);
322
});
323
324
it('should include render time of functional components', () => {
@@ -321,17 +330,19 @@ describeStack('ReactPerf', () => {
330
var measurements = measure(() => {
331
ReactDOM.render(<Foo />, container);
332
});
324
- expect(ReactPerf.getExclusive(measurements)).toEqual([{
325
- key: 'Foo',
326
- instanceCount: 1,
327
- totalDuration: 1,
328
- counts: {
329
- render: 1,
330
- },
331
- durations: {
332
- render: 1,
333
+ expect(ReactPerf.getExclusive(measurements)).toEqual([
334
+ {
335
+ key: 'Foo',
336
+ instanceCount: 1,
337
+ totalDuration: 1,
338
+ counts: {
339
+ render: 1,
340
+ },
341
+ durations: {
342
+ render: 1,
343
+ },
344
},
334
- }]);
345
+ ]);
346
});
347
348
it('should not count time in a portal towards lifecycle method', () => {
@@ -354,40 +365,43 @@ describeStack('ReactPerf', () => {
365
ReactDOM.render(<Portal />, container);
366
});
367
357
- expect(ReactPerf.getExclusive(measurements)).toEqual([{
358
- key: 'Portal',
359
- instanceCount: 1,
360
- totalDuration: 6,
361
- counts: {
362
- ctor: 1,
363
- componentDidMount: 1,
364
- render: 1,
368
+ expect(ReactPerf.getExclusive(measurements)).toEqual([
369
+ {
370
+ key: 'Portal',
371
+ instanceCount: 1,
372
+ totalDuration: 6,
373
+ counts: {
374
+ ctor: 1,
375
+ componentDidMount: 1,
376
+ render: 1,
377
+ },
378
+ durations: {
379
+ ctor: 1,
380
+ // We want to exclude nested imperative ReactDOM.render() from lifecycle hook's own time.
381
+ // Otherwise it would artificially float to the top even though its exclusive time is small.
382
+ // This is how we get 4 as a number with the performanceNow() mock:
383
+ // - we capture the time we enter componentDidMount (n = 0)
384
+ // - we capture the time when we enter a nested flush (n = 1)
385
+ // - in the nested flush, we call it twice: before and after <Foo /> rendering. (n = 3)
386
+ // - we capture the time when we exit a nested flush (n = 4)
387
+ // - we capture the time we exit componentDidMount (n = 5)
388
+ // Time spent in componentDidMount = (5 - 0 - (4 - 3)) = 4.
389
+ componentDidMount: 4,
390
+ render: 1,
391
+ },
392
},
366
- durations: {
367
- ctor: 1,
368
- // We want to exclude nested imperative ReactDOM.render() from lifecycle hook's own time.
369
- // Otherwise it would artificially float to the top even though its exclusive time is small.
370
- // This is how we get 4 as a number with the performanceNow() mock:
371
- // - we capture the time we enter componentDidMount (n = 0)
372
- // - we capture the time when we enter a nested flush (n = 1)
373
- // - in the nested flush, we call it twice: before and after <Foo /> rendering. (n = 3)
374
- // - we capture the time when we exit a nested flush (n = 4)
375
- // - we capture the time we exit componentDidMount (n = 5)
376
- // Time spent in componentDidMount = (5 - 0 - (4 - 3)) = 4.
377
- componentDidMount: 4,
378
- render: 1,
393
+ {
394
+ key: 'Foo',
395
+ instanceCount: 1,
396
+ totalDuration: 1,
397
+ counts: {
398
+ render: 1,
399
+ },
400
+ durations: {
401
+ render: 1,
402
+ },
403
},
380
- }, {
381
- key: 'Foo',
382
- instanceCount: 1,
383
- totalDuration: 1,
384
- counts: {
385
- render: 1,
386
- },
387
- durations: {
388
- render: 1,
389
- },
390
- }]);
404
+ ]);
405
});
406
407
it('warns once when using getMeasurementsSummaryMap', () => {
@@ -397,7 +411,7 @@ describeStack('ReactPerf', () => {
411
expectDev(console.error.calls.count()).toBe(1);
412
expectDev(console.error.calls.argsFor(0)[0]).toContain(
413
'`ReactPerf.getMeasurementsSummaryMap(...)` is deprecated. Use ' +
400
- '`ReactPerf.getWasted(...)` instead.'
414
+ '`ReactPerf.getWasted(...)` instead.',
415
);
416
417
ReactPerf.getMeasurementsSummaryMap(measurements);
@@ -411,7 +425,7 @@ describeStack('ReactPerf', () => {
425
expectDev(console.error.calls.count()).toBe(1);
426
expectDev(console.error.calls.argsFor(0)[0]).toContain(
427
'`ReactPerf.printDOM(...)` is deprecated. Use ' +
414
- '`ReactPerf.printOperations(...)` instead.'
428
+ '`ReactPerf.printOperations(...)` instead.',
429
);
430
431
ReactPerf.printDOM(measurements);
@@ -504,22 +518,26 @@ describeStack('ReactPerf', () => {
518
expect(ReactPerf.getWasted()).toEqual([]);
519
520
ReactDOM.render(<Measurer><App /></Measurer>, container);
507
- expect(ReactPerf.getWasted()).toEqual([{
508
- key: 'Measurer',
509
- instanceCount: 1,
510
- inclusiveRenderDuration: 4,
511
- renderCount: 1,
512
- }, {
513
- key: 'App',
514
- instanceCount: 1,
515
- inclusiveRenderDuration: 3,
516
- renderCount: 1,
517
- }, {
518
- key: 'App > Box',
519
- instanceCount: 2,
520
- inclusiveRenderDuration: 2,
521
- renderCount: 2,
522
- }]);
521
+ expect(ReactPerf.getWasted()).toEqual([
522
+ {
523
+ key: 'Measurer',
524
+ instanceCount: 1,
525
+ inclusiveRenderDuration: 4,
526
+ renderCount: 1,
527
+ },
528
+ {
529
+ key: 'App',
530
+ instanceCount: 1,
531
+ inclusiveRenderDuration: 3,
532
+ renderCount: 1,
533
+ },
534
+ {
535
+ key: 'App > Box',
536
+ instanceCount: 2,
537
+ inclusiveRenderDuration: 2,
538
+ renderCount: 2,
539
+ },
540
+ ]);
541
});
542
543
it('should not print errant warnings if render() throws', () => {
@@ -539,7 +557,7 @@ describeStack('ReactPerf', () => {
557
<LifeCycle />
558
<Evil />
559
</div>,
542
- container
560
+ container,
561
);
562
} catch (err) {
563
if (err !== thrownErr) {
@@ -569,7 +587,7 @@ describeStack('ReactPerf', () => {
587
<LifeCycle />
588
<Evil />
589
</div>,
572
- container
590
+ container,
591
);
592
} catch (err) {
593
if (err !== thrownErr) {
@@ -599,7 +617,7 @@ describeStack('ReactPerf', () => {
617
<LifeCycle />
618
<Evil />
619
</div>,
602
- container
620
+ container,
621
);
622
} catch (err) {
623
if (err !== thrownErr) {
@@ -635,7 +653,7 @@ describeStack('ReactPerf', () => {
653
<LifeCycle />
654
<EvilPortal />
655
</div>,
638
- container
656
+ container,
657
);
658
} catch (err) {
659
if (err !== thrownErr) {
@@ -675,7 +693,7 @@ describeStack('ReactPerf', () => {
693
<LifeCycle />
694
<EvilPortal />
695
</div>,
678
- container
696
+ container,
697
);
698
} catch (err) {
699
if (err !== thrownErr) {
@@ -715,7 +733,7 @@ describeStack('ReactPerf', () => {
733
<LifeCycle />
734
<EvilPortal />
735
</div>,
718
- container
736
+ container,
737
);
738
} catch (err) {
739
if (err !== thrownErr) {
src/renderers/__tests__/ReactStatelessComponent-test.js
+54
-41
@@ -123,19 +123,19 @@ describe('ReactStatelessComponent', () => {
123
expectDev(console.error.calls.count()).toBe(1);
124
expectDev(console.error.calls.argsFor(0)[0]).toContain(
125
'StatelessComponentWithChildContext(...): childContextTypes cannot ' +
126
- 'be defined on a functional component.'
126
+ 'be defined on a functional component.',
127
);
128
} else {
129
expectDev(console.error.calls.count()).toBe(2);
130
expectDev(console.error.calls.argsFor(0)[0]).toContain(
131
'StatelessComponentWithChildContext(...): childContextTypes cannot ' +
132
- 'be defined on a functional component.'
132
+ 'be defined on a functional component.',
133
);
134
expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(1)[0])).toBe(
135
'Warning: StatelessComponentWithChildContext.childContextTypes is specified ' +
136
- 'but there is no getChildContext() method on the instance. You can either ' +
137
- 'define getChildContext() on StatelessComponentWithChildContext or remove ' +
138
- 'childContextTypes from it.'
136
+ 'but there is no getChildContext() method on the instance. You can either ' +
137
+ 'define getChildContext() on StatelessComponentWithChildContext or remove ' +
138
+ 'childContextTypes from it.',
139
);
140
}
141
});
@@ -150,19 +150,18 @@ describe('ReactStatelessComponent', () => {
150
ReactTestUtils.renderIntoDocument(<div><NotAComponent /></div>);
151
}).toThrowError(
152
'NotAComponent(...): A valid React element (or null) must be returned. ' +
153
- 'You may have returned undefined, an array or some other invalid object.'
153
+ 'You may have returned undefined, an array or some other invalid object.',
154
);
155
});
156
}
157
158
it('should throw when stateless component returns undefined', () => {
159
- function NotAComponent() {
160
- }
159
+ function NotAComponent() {}
160
expect(function() {
161
ReactTestUtils.renderIntoDocument(<div><NotAComponent /></div>);
162
}).toThrowError(
163
'NotAComponent(...): A valid React element (or null) must be returned. ' +
165
- 'You may have returned undefined, an array or some other invalid object.'
164
+ 'You may have returned undefined, an array or some other invalid object.',
165
);
166
});
167
@@ -173,9 +172,7 @@ describe('ReactStatelessComponent', () => {
172
173
expect(function() {
174
ReactTestUtils.renderIntoDocument(<Child test="test" />);
176
- }).toThrowError(
177
- 'Stateless function components cannot have refs.'
178
- );
175
+ }).toThrowError('Stateless function components cannot have refs.');
176
});
177
178
it('should warn when given a string ref', () => {
@@ -199,12 +196,12 @@ describe('ReactStatelessComponent', () => {
196
expectDev(console.error.calls.count()).toBe(1);
197
expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
198
'Warning: Stateless function components cannot be given refs. ' +
202
- 'Attempts to access this ref will fail.\n\nCheck the render method ' +
203
- 'of `ParentUsingStringRef`.\n' +
204
- ' in StatelessComponent (at **)\n' +
205
- ' in div (at **)\n' +
206
- ' in Indirection (at **)\n' +
207
- ' in ParentUsingStringRef (at **)'
199
+ 'Attempts to access this ref will fail.\n\nCheck the render method ' +
200
+ 'of `ParentUsingStringRef`.\n' +
201
+ ' in StatelessComponent (at **)\n' +
202
+ ' in div (at **)\n' +
203
+ ' in Indirection (at **)\n' +
204
+ ' in ParentUsingStringRef (at **)',
205
);
206
207
ReactTestUtils.renderIntoDocument(<ParentUsingStringRef />);
@@ -222,9 +219,12 @@ describe('ReactStatelessComponent', () => {
219
render() {
220
return (
221
<Indirection>
225
- <StatelessComponent name="A" ref={(arg) => {
226
- expect(arg).toBe(null);
227
- }} />
222
+ <StatelessComponent
223
+ name="A"
224
+ ref={arg => {
225
+ expect(arg).toBe(null);
226
+ }}
227
+ />
228
</Indirection>
229
);
230
}
@@ -234,12 +234,12 @@ describe('ReactStatelessComponent', () => {
234
expectDev(console.error.calls.count()).toBe(1);
235
expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
236
'Warning: Stateless function components cannot be given refs. ' +
237
- 'Attempts to access this ref will fail.\n\nCheck the render method ' +
238
- 'of `ParentUsingFunctionRef`.\n' +
239
- ' in StatelessComponent (at **)\n' +
240
- ' in div (at **)\n' +
241
- ' in Indirection (at **)\n' +
242
- ' in ParentUsingFunctionRef (at **)'
237
+ 'Attempts to access this ref will fail.\n\nCheck the render method ' +
238
+ 'of `ParentUsingFunctionRef`.\n' +
239
+ ' in StatelessComponent (at **)\n' +
240
+ ' in div (at **)\n' +
241
+ ' in Indirection (at **)\n' +
242
+ ' in ParentUsingFunctionRef (at **)',
243
);
244
245
ReactTestUtils.renderIntoDocument(<ParentUsingFunctionRef />);
@@ -258,10 +258,12 @@ describe('ReactStatelessComponent', () => {
258
return <StatelessComponent name="A" ref={() => {}} />;
259
},
260
});
261
- const instance1 = ReactTestUtils.renderIntoDocument(<AnonymousParentUsingJSX />);
261
+ const instance1 = ReactTestUtils.renderIntoDocument(
262
+ <AnonymousParentUsingJSX />,
263
+ );
264
expectDev(console.error.calls.count()).toBe(1);
265
expectDev(console.error.calls.argsFor(0)[0]).toContain(
264
- 'Warning: Stateless function components cannot be given refs.'
266
+ 'Warning: Stateless function components cannot be given refs.',
267
);
268
// Should be deduped (offending element is on the same line):
269
instance1.forceUpdate();
@@ -273,13 +275,18 @@ describe('ReactStatelessComponent', () => {
275
// When owner doesn't use JSX, and is anonymous, we warn once per internal instance.
276
var AnonymousParentNotUsingJSX = createClassWithoutDisplayName({
277
render() {
276
- return React.createElement(StatelessComponent, {name: 'A', 'ref': () => {}});
278
+ return React.createElement(StatelessComponent, {
279
+ name: 'A',
280
+ ref: () => {},
281
+ });
282
},
283
});
279
- const instance2 = ReactTestUtils.renderIntoDocument(<AnonymousParentNotUsingJSX />);
284
+ const instance2 = ReactTestUtils.renderIntoDocument(
285
+ <AnonymousParentNotUsingJSX />,
286
+ );
287
expectDev(console.error.calls.count()).toBe(1);
288
expectDev(console.error.calls.argsFor(0)[0]).toContain(
282
- 'Warning: Stateless function components cannot be given refs.'
289
+ 'Warning: Stateless function components cannot be given refs.',
290
);
291
// Should be deduped (same internal instance):
292
instance2.forceUpdate();
@@ -288,20 +295,25 @@ describe('ReactStatelessComponent', () => {
295
ReactTestUtils.renderIntoDocument(<AnonymousParentNotUsingJSX />);
296
expectDev(console.error.calls.count()).toBe(2);
297
expectDev(console.error.calls.argsFor(1)[0]).toContain(
291
- 'Warning: Stateless function components cannot be given refs.'
298
+ 'Warning: Stateless function components cannot be given refs.',
299
);
300
console.error.calls.reset();
301
302
// When owner doesn't use JSX, but is named, we warn once per owner name
303
class NamedParentNotUsingJSX extends React.Component {
304
render() {
298
- return React.createElement(StatelessComponent, {name: 'A', 'ref': () => {}});
305
+ return React.createElement(StatelessComponent, {
306
+ name: 'A',
307
+ ref: () => {},
308
+ });
309
}
310
}
301
- const instance3 = ReactTestUtils.renderIntoDocument(<NamedParentNotUsingJSX />);
311
+ const instance3 = ReactTestUtils.renderIntoDocument(
312
+ <NamedParentNotUsingJSX />,
313
+ );
314
expectDev(console.error.calls.count()).toBe(1);
315
expectDev(console.error.calls.argsFor(0)[0]).toContain(
304
- 'Warning: Stateless function components cannot be given refs.'
316
+ 'Warning: Stateless function components cannot be given refs.',
317
);
318
// Should be deduped (same owner name):
319
instance3.forceUpdate();
@@ -329,7 +341,9 @@ describe('ReactStatelessComponent', () => {
341
spyOn(console, 'error');
342
ReactTestUtils.renderIntoDocument(<Child />);
343
expectDev(console.error.calls.count()).toBe(1);
332
- expectDev(console.error.calls.argsFor(0)[0]).toContain('a unique "key" prop');
344
+ expectDev(console.error.calls.argsFor(0)[0]).toContain(
345
+ 'a unique "key" prop',
346
+ );
347
expectDev(console.error.calls.argsFor(0)[0]).toContain('Child');
348
});
349
@@ -344,11 +358,11 @@ describe('ReactStatelessComponent', () => {
358
ReactTestUtils.renderIntoDocument(<Child />);
359
expectDev(console.error.calls.count()).toBe(1);
360
expect(
347
- console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)')
361
+ console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)'),
362
).toBe(
363
'Warning: Failed prop type: Invalid prop `test` of type `number` ' +
350
- 'supplied to `Child`, expected `string`.\n' +
351
- ' in Child (at **)'
364
+ 'supplied to `Child`, expected `string`.\n' +
365
+ ' in Child (at **)',
366
);
367
});
368
@@ -401,5 +415,4 @@ describe('ReactStatelessComponent', () => {
415
}
416
expect(() => ReactTestUtils.renderIntoDocument(<Child />)).not.toThrow();
417
});
404
-
418
});
src/renderers/__tests__/ReactTreeTraversal-test.js
+14
-37
@@ -94,10 +94,7 @@ describe('ReactTreeTraversal', () => {
94
it('should traverse two phase at shallowest node', () => {
95
var parent = renderParentIntoDocument();
96
var target = getInst(parent.refs.P);
97
- var expectedCalls = [
98
- ['P', 'captured', ARG],
99
- ['P', 'bubbled', ARG],
100
- ];
97
+ var expectedCalls = [['P', 'captured', ARG], ['P', 'bubbled', ARG]];
98
ReactTreeTraversal.traverseTwoPhase(target, callback, ARG);
99
expect(mockFn.mock.calls).toEqual(expectedCalls);
100
});
@@ -105,9 +102,7 @@ describe('ReactTreeTraversal', () => {
102
103
describe('traverseEnterLeave', () => {
104
it('should not traverse when enter/leaving outside DOM', () => {
108
- ReactTreeTraversal.traverseEnterLeave(
109
- null, null, callback, ARG, ARG2
110
- );
105
+ ReactTreeTraversal.traverseEnterLeave(null, null, callback, ARG, ARG2);
106
expect(mockFn).not.toHaveBeenCalled();
107
});
108
@@ -115,9 +110,7 @@ describe('ReactTreeTraversal', () => {
110
var parent = renderParentIntoDocument();
111
var leave = getInst(parent.refs.P_P1_C1.refs.DIV_1);
112
var enter = getInst(parent.refs.P_P1_C1.refs.DIV_1);
118
- ReactTreeTraversal.traverseEnterLeave(
119
- leave, enter, callback, ARG, ARG2
120
- );
113
+ ReactTreeTraversal.traverseEnterLeave(leave, enter, callback, ARG, ARG2);
114
expect(mockFn).not.toHaveBeenCalled();
115
});
116
@@ -130,9 +123,7 @@ describe('ReactTreeTraversal', () => {
123
// enter/leave shouldn't fire anything on the parent
124
['P_P1_C1__DIV_2', 'captured', ARG2],
125
];
133
- ReactTreeTraversal.traverseEnterLeave(
134
- leave, enter, callback, ARG, ARG2
135
- );
126
+ ReactTreeTraversal.traverseEnterLeave(leave, enter, callback, ARG, ARG2);
127
expect(mockFn.mock.calls).toEqual(expectedCalls);
128
});
129
@@ -140,12 +131,8 @@ describe('ReactTreeTraversal', () => {
131
var parent = renderParentIntoDocument();
132
var leave = getInst(parent.refs.P_P1_C1.refs.DIV_1);
133
var enter = getInst(parent.refs.P_P1_C1.refs.DIV);
143
- var expectedCalls = [
144
- ['P_P1_C1__DIV_1', 'bubbled', ARG],
145
- ];
146
- ReactTreeTraversal.traverseEnterLeave(
147
- leave, enter, callback, ARG, ARG2
148
- );
134
+ var expectedCalls = [['P_P1_C1__DIV_1', 'bubbled', ARG]];
135
+ ReactTreeTraversal.traverseEnterLeave(leave, enter, callback, ARG, ARG2);
136
expect(mockFn.mock.calls).toEqual(expectedCalls);
137
});
138
@@ -158,9 +145,7 @@ describe('ReactTreeTraversal', () => {
145
['P_P1', 'captured', ARG2],
146
['P_P1_C1__DIV', 'captured', ARG2],
147
];
161
- ReactTreeTraversal.traverseEnterLeave(
162
- leave, enter, callback, ARG, ARG2
163
- );
148
+ ReactTreeTraversal.traverseEnterLeave(leave, enter, callback, ARG, ARG2);
149
expect(mockFn.mock.calls).toEqual(expectedCalls);
150
});
151
@@ -168,12 +153,8 @@ describe('ReactTreeTraversal', () => {
153
var parent = renderParentIntoDocument();
154
var leave = null; // From the window or outside of the React sandbox.
155
var enter = getInst(parent.refs.P);
171
- var expectedCalls = [
172
- ['P', 'captured', ARG2],
173
- ];
174
- ReactTreeTraversal.traverseEnterLeave(
175
- leave, enter, callback, ARG, ARG2
176
- );
156
+ var expectedCalls = [['P', 'captured', ARG2]];
157
+ ReactTreeTraversal.traverseEnterLeave(leave, enter, callback, ARG, ARG2);
158
expect(mockFn.mock.calls).toEqual(expectedCalls);
159
});
160
@@ -186,9 +167,7 @@ describe('ReactTreeTraversal', () => {
167
['P_P1', 'bubbled', ARG],
168
['P', 'bubbled', ARG],
169
];
189
- ReactTreeTraversal.traverseEnterLeave(
190
- leave, enter, callback, ARG, ARG2
191
- );
170
+ ReactTreeTraversal.traverseEnterLeave(leave, enter, callback, ARG, ARG2);
171
expect(mockFn.mock.calls).toEqual(expectedCalls);
172
});
173
@@ -201,9 +180,7 @@ describe('ReactTreeTraversal', () => {
180
['P_P1', 'bubbled', ARG],
181
['P', 'bubbled', ARG],
182
];
204
- ReactTreeTraversal.traverseEnterLeave(
205
- leave, enter, callback, ARG, ARG2
206
- );
183
+ ReactTreeTraversal.traverseEnterLeave(leave, enter, callback, ARG, ARG2);
184
expect(mockFn.mock.calls).toEqual(expectedCalls);
185
});
186
});
@@ -213,7 +190,8 @@ describe('ReactTreeTraversal', () => {
190
var parent = renderParentIntoDocument();
191
var ancestors = [
192
// Common ancestor with self is self.
216
- {one: parent.refs.P_P1_C1.refs.DIV_1,
193
+ {
194
+ one: parent.refs.P_P1_C1.refs.DIV_1,
195
two: parent.refs.P_P1_C1.refs.DIV_1,
196
com: parent.refs.P_P1_C1.refs.DIV_1,
197
},
@@ -255,11 +233,10 @@ describe('ReactTreeTraversal', () => {
233
var plan = ancestors[i];
234
var firstCommon = ReactTreeTraversal.getLowestCommonAncestor(
235
getInst(plan.one),
258
- getInst(plan.two)
236
+ getInst(plan.two),
237
);
238
expect(firstCommon).toBe(getInst(plan.com));
239
}
240
});
241
});
264
-
242
});
src/renderers/__tests__/ReactUpdates-test.js
+52
-52
@@ -487,21 +487,21 @@ describe('ReactUpdates', () => {
487
[root.refs.switcher.refs.box, root.refs.switcher],
488
// Owner-child relationships have inverse will and did
489
['Switcher', 'Box'],
490
- ['Box', 'Switcher']
490
+ ['Box', 'Switcher'],
491
);
492
493
testUpdates(
494
[root.refs.child, root.refs.switcher.refs.box],
495
// Not owner-child so reconcile independently
496
['Box', 'Child'],
497
- ['Box', 'Child']
497
+ ['Box', 'Child'],
498
);
499
500
testUpdates(
501
[root.refs.child, root.refs.switcher],
502
// Switcher owns Box and Child, Box does not own Child
503
['Switcher', 'Box', 'Child'],
504
- ['Box', 'Switcher', 'Child']
504
+ ['Box', 'Switcher', 'Child'],
505
);
506
});
507
@@ -531,7 +531,7 @@ describe('ReactUpdates', () => {
531
if (ReactDOMFeatureFlags.useFiber) {
532
portal = ReactDOM.unstable_createPortal(
533
<B ref={n => b = n} />,
534
- bContainer
534
+ bContainer,
535
);
536
}
537
return <div>A{this.state.x}{portal}</div>;
@@ -607,31 +607,31 @@ describe('ReactUpdates', () => {
607
/* eslint-disable indent */
608
expect(updates).toEqual([
609
'Outer-render-0',
610
- 'Inner-render-0-0',
610
+ 'Inner-render-0-0',
611
612
'Outer-setState-1',
613
- 'Outer-render-1',
614
- 'Inner-render-1-0',
615
- 'Inner-didUpdate-1-0',
616
- 'Outer-didUpdate-1',
617
- // Happens in a batch, so don't re-render yet
618
- 'Inner-setState-1',
619
- 'Outer-callback-1',
620
-
621
- // Happens in a batch
622
- 'Outer-setState-2',
623
-
624
- // Flush batched updates all at once
625
- 'Outer-render-2',
626
- 'Inner-render-2-1',
627
- 'Inner-didUpdate-2-1',
628
- 'Inner-callback-1',
629
- 'Outer-didUpdate-2',
630
- 'Inner-setState-2',
631
- 'Outer-callback-2',
632
- 'Inner-render-2-2',
633
- 'Inner-didUpdate-2-2',
634
- 'Inner-callback-2',
613
+ 'Outer-render-1',
614
+ 'Inner-render-1-0',
615
+ 'Inner-didUpdate-1-0',
616
+ 'Outer-didUpdate-1',
617
+ // Happens in a batch, so don't re-render yet
618
+ 'Inner-setState-1',
619
+ 'Outer-callback-1',
620
+
621
+ // Happens in a batch
622
+ 'Outer-setState-2',
623
+
624
+ // Flush batched updates all at once
625
+ 'Outer-render-2',
626
+ 'Inner-render-2-1',
627
+ 'Inner-didUpdate-2-1',
628
+ 'Inner-callback-1',
629
+ 'Outer-didUpdate-2',
630
+ 'Inner-setState-2',
631
+ 'Outer-callback-2',
632
+ 'Inner-render-2-2',
633
+ 'Inner-didUpdate-2-2',
634
+ 'Inner-callback-2',
635
]);
636
/* eslint-enable indent */
637
});
@@ -654,7 +654,7 @@ describe('ReactUpdates', () => {
654
depth={this.props.depth + 1}
655
count={this.props.count}
656
/>,
657
- ReactDOM.findDOMNode(this)
657
+ ReactDOM.findDOMNode(this),
658
);
659
}
660
}
@@ -761,7 +761,7 @@ describe('ReactUpdates', () => {
761
<div>
762
<A />
763
<B />
764
- </div>
764
+ </div>,
765
);
766
});
767
@@ -886,29 +886,29 @@ describe('ReactUpdates', () => {
886
887
expect(() => component.setState({}, 'no')).toThrowError(
888
'Invalid argument passed as callback. Expected a function. Instead ' +
889
- 'received: no',
889
+ 'received: no',
890
);
891
expectDev(console.error.calls.argsFor(0)[0]).toContain(
892
'setState(...): Expected the last optional `callback` argument to be ' +
893
- 'a function. Instead received: no.'
893
+ 'a function. Instead received: no.',
894
);
895
component = ReactTestUtils.renderIntoDocument(<A />);
896
expect(() => component.setState({}, {foo: 'bar'})).toThrowError(
897
'Invalid argument passed as callback. Expected a function. Instead ' +
898
- 'received: [object Object]',
898
+ 'received: [object Object]',
899
);
900
expectDev(console.error.calls.argsFor(1)[0]).toContain(
901
'setState(...): Expected the last optional `callback` argument to be ' +
902
- 'a function. Instead received: [object Object].'
902
+ 'a function. Instead received: [object Object].',
903
);
904
component = ReactTestUtils.renderIntoDocument(<A />);
905
expect(() => component.setState({}, new Foo())).toThrowError(
906
'Invalid argument passed as callback. Expected a function. Instead ' +
907
- 'received: [object Object]',
907
+ 'received: [object Object]',
908
);
909
expectDev(console.error.calls.argsFor(2)[0]).toContain(
910
'setState(...): Expected the last optional `callback` argument to be ' +
911
- 'a function. Instead received: [object Object].'
911
+ 'a function. Instead received: [object Object].',
912
);
913
expect(console.error.calls.count()).toBe(3);
914
});
@@ -932,29 +932,29 @@ describe('ReactUpdates', () => {
932
933
expect(() => component.replaceState({}, 'no')).toThrowError(
934
'Invalid argument passed as callback. Expected a function. Instead ' +
935
- 'received: no',
935
+ 'received: no',
936
);
937
expectDev(console.error.calls.argsFor(0)[0]).toContain(
938
'replaceState(...): Expected the last optional `callback` argument to be ' +
939
- 'a function. Instead received: no.'
939
+ 'a function. Instead received: no.',
940
);
941
component = ReactTestUtils.renderIntoDocument(<A />);
942
expect(() => component.replaceState({}, {foo: 'bar'})).toThrowError(
943
'Invalid argument passed as callback. Expected a function. Instead ' +
944
- 'received: [object Object]',
944
+ 'received: [object Object]',
945
);
946
expectDev(console.error.calls.argsFor(1)[0]).toContain(
947
'replaceState(...): Expected the last optional `callback` argument to be ' +
948
- 'a function. Instead received: [object Object].'
948
+ 'a function. Instead received: [object Object].',
949
);
950
component = ReactTestUtils.renderIntoDocument(<A />);
951
expect(() => component.replaceState({}, new Foo())).toThrowError(
952
'Invalid argument passed as callback. Expected a function. Instead ' +
953
- 'received: [object Object]',
953
+ 'received: [object Object]',
954
);
955
expectDev(console.error.calls.argsFor(2)[0]).toContain(
956
'replaceState(...): Expected the last optional `callback` argument to be ' +
957
- 'a function. Instead received: [object Object].'
957
+ 'a function. Instead received: [object Object].',
958
);
959
expect(console.error.calls.count()).toBe(3);
960
});
@@ -979,29 +979,29 @@ describe('ReactUpdates', () => {
979
980
expect(() => component.forceUpdate('no')).toThrowError(
981
'Invalid argument passed as callback. Expected a function. Instead ' +
982
- 'received: no',
982
+ 'received: no',
983
);
984
expectDev(console.error.calls.argsFor(0)[0]).toContain(
985
'forceUpdate(...): Expected the last optional `callback` argument to be ' +
986
- 'a function. Instead received: no.'
986
+ 'a function. Instead received: no.',
987
);
988
component = ReactTestUtils.renderIntoDocument(<A />);
989
expect(() => component.forceUpdate({foo: 'bar'})).toThrowError(
990
'Invalid argument passed as callback. Expected a function. Instead ' +
991
- 'received: [object Object]',
991
+ 'received: [object Object]',
992
);
993
expectDev(console.error.calls.argsFor(1)[0]).toContain(
994
'forceUpdate(...): Expected the last optional `callback` argument to be ' +
995
- 'a function. Instead received: [object Object].'
995
+ 'a function. Instead received: [object Object].',
996
);
997
component = ReactTestUtils.renderIntoDocument(<A />);
998
expect(() => component.forceUpdate(new Foo())).toThrowError(
999
'Invalid argument passed as callback. Expected a function. Instead ' +
1000
- 'received: [object Object]',
1000
+ 'received: [object Object]',
1001
);
1002
expectDev(console.error.calls.argsFor(2)[0]).toContain(
1003
'forceUpdate(...): Expected the last optional `callback` argument to be ' +
1004
- 'a function. Instead received: [object Object].'
1004
+ 'a function. Instead received: [object Object].',
1005
);
1006
expect(console.error.calls.count()).toBe(3);
1007
});
@@ -1065,10 +1065,10 @@ describe('ReactUpdates', () => {
1065
class App extends React.Component {
1066
constructor(props) {
1067
super(props);
1068
- this.state = { showChild: true };
1068
+ this.state = {showChild: true};
1069
}
1070
componentDidMount() {
1071
- this.setState({ showChild: false });
1071
+ this.setState({showChild: false});
1072
}
1073
render() {
1074
return (
@@ -1096,7 +1096,7 @@ describe('ReactUpdates', () => {
1096
callbacks.push(this.onChange);
1097
}
1098
componentWillUnmount() {
1099
- callbacks = callbacks.filter((c) => c !== this.onChange);
1099
+ callbacks = callbacks.filter(c => c !== this.onChange);
1100
}
1101
render() {
1102
return <div key={Math.random()} onClick={function() {}} />;
@@ -1142,13 +1142,13 @@ describe('ReactUpdates', () => {
1142
function render() {
1143
ReactDOM.render(
1144
<Editor
1145
- onChange={(newProps) => {
1145
+ onChange={newProps => {
1146
props = {...props, ...newProps};
1147
render();
1148
}}
1149
{...props}
1150
/>,
1151
- container
1151
+ container,
1152
);
1153
}
1154
src/renderers/__tests__/refs-destruction-test.js
+37
-30
@@ -29,11 +29,11 @@ describe('refs-destruction', () => {
29
render() {
30
return (
31
<div>
32
- {this.props.destroy ? null :
33
- <div ref="theInnerDiv">
34
- Lets try to destroy this.
35
- </div>
36
- }
32
+ {this.props.destroy
33
+ ? null
34
+ : <div ref="theInnerDiv">
35
+ Lets try to destroy this.
36
+ </div>}
37
</div>
38
);
39
}
@@ -43,36 +43,38 @@ describe('refs-destruction', () => {
43
it('should remove refs when destroying the parent', () => {
44
var container = document.createElement('div');
45
var testInstance = ReactDOM.render(<TestComponent />, container);
46
- expect(ReactTestUtils.isDOMComponent(testInstance.refs.theInnerDiv))
47
- .toBe(true);
46
+ expect(ReactTestUtils.isDOMComponent(testInstance.refs.theInnerDiv)).toBe(
47
+ true,
48
+ );
49
expect(
49
- Object.keys(testInstance.refs || {})
50
- .filter(key => testInstance.refs[key])
51
- .length
50
+ Object.keys(testInstance.refs || {}).filter(
51
+ key => testInstance.refs[key],
52
+ ).length,
53
).toEqual(1);
54
ReactDOM.unmountComponentAtNode(container);
55
expect(
55
- Object.keys(testInstance.refs || {})
56
- .filter(key => testInstance.refs[key])
57
- .length
56
+ Object.keys(testInstance.refs || {}).filter(
57
+ key => testInstance.refs[key],
58
+ ).length,
59
).toEqual(0);
60
});
61
62
it('should remove refs when destroying the child', () => {
63
var container = document.createElement('div');
64
var testInstance = ReactDOM.render(<TestComponent />, container);
64
- expect(ReactTestUtils.isDOMComponent(testInstance.refs.theInnerDiv))
65
- .toBe(true);
65
+ expect(ReactTestUtils.isDOMComponent(testInstance.refs.theInnerDiv)).toBe(
66
+ true,
67
+ );
68
expect(
67
- Object.keys(testInstance.refs || {})
68
- .filter(key => testInstance.refs[key])
69
- .length
69
+ Object.keys(testInstance.refs || {}).filter(
70
+ key => testInstance.refs[key],
71
+ ).length,
72
).toEqual(1);
73
ReactDOM.render(<TestComponent destroy={true} />, container);
74
expect(
73
- Object.keys(testInstance.refs || {})
74
- .filter(key => testInstance.refs[key])
75
- .length
75
+ Object.keys(testInstance.refs || {}).filter(
76
+ key => testInstance.refs[key],
77
+ ).length,
78
).toEqual(0);
79
});
80
@@ -91,12 +93,15 @@ describe('refs-destruction', () => {
93
componentWillUnmount() {
94
var self = this;
95
// some async animation
94
- setTimeout(function() {
95
- expect(function() {
96
- ReactDOM.unmountComponentAtNode(self.div);
97
- }).not.toThrow();
98
- document.body.removeChild(self.div);
99
- }, 0);
96
+ setTimeout(
97
+ function() {
98
+ expect(function() {
99
+ ReactDOM.unmountComponentAtNode(self.div);
100
+ }).not.toThrow();
101
+ document.body.removeChild(self.div);
102
+ },
103
+ 0,
104
+ );
105
}
106
107
render() {
@@ -106,9 +111,11 @@ describe('refs-destruction', () => {
111
112
class AppModal extends React.Component {
113
render() {
109
- return (<Modal>
110
- <a ref="ref" />
111
- </Modal>);
114
+ return (
115
+ <Modal>
116
+ <a ref="ref" />
117
+ </Modal>
118
+ );
119
}
120
}
121
src/renderers/__tests__/refs-test.js
+32
-26
@@ -39,7 +39,7 @@ class ClickCounter extends React.Component {
39
className="clickLogDiv"
40
key={'clickLog' + i}
41
ref={'clickLog' + i}
42
- />
42
+ />,
43
);
44
}
45
return (
@@ -88,8 +88,9 @@ class TestRefsComponent extends React.Component {
88
* Render a TestRefsComponent and ensure that the main refs are wired up.
89
*/
90
var renderTestRefsComponent = function() {
91
- var testRefsComponent =
92
- ReactTestUtils.renderIntoDocument(<TestRefsComponent />);
91
+ var testRefsComponent = ReactTestUtils.renderIntoDocument(
92
+ <TestRefsComponent />,
93
+ );
94
expect(testRefsComponent instanceof TestRefsComponent).toBe(true);
95
96
var generalContainer = testRefsComponent.refs.myContainer;
@@ -101,10 +102,11 @@ var renderTestRefsComponent = function() {
102
return testRefsComponent;
103
};
104
104
-
105
var expectClickLogsLengthToBe = function(instance, length) {
106
- var clickLogs =
107
- ReactTestUtils.scryRenderedDOMComponentsWithClass(instance, 'clickLogDiv');
106
+ var clickLogs = ReactTestUtils.scryRenderedDOMComponentsWithClass(
107
+ instance,
108
+ 'clickLogDiv',
109
+ );
110
expect(clickLogs.length).toBe(length);
111
expect(Object.keys(instance.refs.myCounter.refs).length).toBe(length);
112
};
@@ -122,11 +124,10 @@ describe('reactiverefs', () => {
124
*/
125
it('Should increase refs with an increase in divs', () => {
126
var testRefsComponent = renderTestRefsComponent();
125
- var clickIncrementer =
126
- ReactTestUtils.findRenderedDOMComponentWithClass(
127
- testRefsComponent,
128
- 'clickIncrementer'
129
- );
127
+ var clickIncrementer = ReactTestUtils.findRenderedDOMComponentWithClass(
128
+ testRefsComponent,
129
+ 'clickIncrementer',
130
+ );
131
132
expectClickLogsLengthToBe(testRefsComponent, 1);
133
@@ -210,12 +211,18 @@ describe('ref swapping', () => {
211
it('Allow refs to hop around children correctly', () => {
212
var refHopsAround = ReactTestUtils.renderIntoDocument(<RefHopsAround />);
213
213
- var firstDiv =
214
- ReactTestUtils.findRenderedDOMComponentWithClass(refHopsAround, 'first');
215
- var secondDiv =
216
- ReactTestUtils.findRenderedDOMComponentWithClass(refHopsAround, 'second');
217
- var thirdDiv =
218
- ReactTestUtils.findRenderedDOMComponentWithClass(refHopsAround, 'third');
214
+ var firstDiv = ReactTestUtils.findRenderedDOMComponentWithClass(
215
+ refHopsAround,
216
+ 'first',
217
+ );
218
+ var secondDiv = ReactTestUtils.findRenderedDOMComponentWithClass(
219
+ refHopsAround,
220
+ 'second',
221
+ );
222
+ var thirdDiv = ReactTestUtils.findRenderedDOMComponentWithClass(
223
+ refHopsAround,
224
+ 'third',
225
+ );
226
227
expect(refHopsAround.refs.hopRef).toEqual(firstDiv);
228
expect(refHopsAround.refs.divTwoRef).toEqual(secondDiv);
@@ -241,7 +248,6 @@ describe('ref swapping', () => {
248
expect(refHopsAround.refs.divThreeRef).toEqual(thirdDiv);
249
});
250
244
-
251
it('always has a value for this.refs', () => {
252
class Component extends React.Component {
253
render() {
@@ -329,11 +335,11 @@ describe('string refs between fiber and stack', () => {
335
ReactDOM.unstable_renderSubtreeIntoContainer(
336
this,
337
span,
332
- this._container = document.createElement('div'),
338
+ (this._container = document.createElement('div')),
339
() => {
340
expect(this.refs.span.nodeName).toBe('SPAN');
341
layerMounted = true;
336
- }
342
+ },
343
);
344
}
345
componentWillUnmount() {
@@ -350,8 +356,8 @@ describe('string refs between fiber and stack', () => {
356
expectDev(console.error.calls.count()).toBe(1);
357
expectDev(console.error.calls.argsFor(0)[0]).toBe(
358
'Warning: You are using React DOM Fiber which is an experimental ' +
353
- 'renderer. It is likely to have bugs, breaking changes and is ' +
354
- 'unsupported.'
359
+ 'renderer. It is likely to have bugs, breaking changes and is ' +
360
+ 'unsupported.',
361
);
362
}
363
});
@@ -376,11 +382,11 @@ describe('string refs between fiber and stack', () => {
382
ReactDOMFiber.unstable_renderSubtreeIntoContainer(
383
this,
384
span,
379
- this._container = document.createElement('div'),
385
+ (this._container = document.createElement('div')),
386
() => {
387
expect(this.refs.span.nodeName).toBe('SPAN');
388
layerMounted = true;
383
- }
389
+ },
390
);
391
}
392
componentWillUnmount() {
@@ -397,8 +403,8 @@ describe('string refs between fiber and stack', () => {
403
expectDev(console.error.calls.count()).toBe(1);
404
expectDev(console.error.calls.argsFor(0)[0]).toBe(
405
'Warning: You are using React DOM Fiber which is an experimental ' +
400
- 'renderer. It is likely to have bugs, breaking changes and is ' +
401
- 'unsupported.'
406
+ 'renderer. It is likely to have bugs, breaking changes and is ' +
407
+ 'unsupported.',
408
);
409
}
410
});
src/renderers/art/ReactARTFiber.js
+22
-56
@@ -23,7 +23,7 @@ const React = require('react');
23
const ReactFiberReconciler = require('ReactFiberReconciler');
24
const ReactDOMFrameScheduling = require('ReactDOMFrameScheduling');
25
26
-const { Component } = React;
26
+const {Component} = React;
27
28
const pooledTransform = new Transform();
29
@@ -133,19 +133,14 @@ function getScaleY(props) {
133
function isSameFont(oldFont, newFont) {
134
if (oldFont === newFont) {
135
return true;
136
- } else if (
137
- typeof newFont === 'string' ||
138
- typeof oldFont === 'string'
139
- ) {
136
+ } else if (typeof newFont === 'string' || typeof oldFont === 'string') {
137
return false;
138
} else {
142
- return (
143
- newFont.fontSize === oldFont.fontSize &&
139
+ return newFont.fontSize === oldFont.fontSize &&
140
newFont.fontStyle === oldFont.fontStyle &&
141
newFont.fontVariant === oldFont.fontVariant &&
142
newFont.fontWeight === oldFont.fontWeight &&
147
- newFont.fontFamily === oldFont.fontFamily
148
- );
143
+ newFont.fontFamily === oldFont.fontFamily;
144
}
145
}
146
@@ -180,24 +175,21 @@ function applyNodeProps(instance, props, prevProps = {}) {
175
}
176
177
if (
183
- instance.xx !== pooledTransform.xx || instance.yx !== pooledTransform.yx ||
184
- instance.xy !== pooledTransform.xy || instance.yy !== pooledTransform.yy ||
185
- instance.x !== pooledTransform.x || instance.y !== pooledTransform.y
178
+ instance.xx !== pooledTransform.xx ||
179
+ instance.yx !== pooledTransform.yx ||
180
+ instance.xy !== pooledTransform.xy ||
181
+ instance.yy !== pooledTransform.yy ||
182
+ instance.x !== pooledTransform.x ||
183
+ instance.y !== pooledTransform.y
184
) {
185
instance.transformTo(pooledTransform);
186
}
187
190
- if (
191
- props.cursor !== prevProps.cursor ||
192
- props.title !== prevProps.title
193
- ) {
188
+ if (props.cursor !== prevProps.cursor || props.title !== prevProps.title) {
189
instance.indicate(props.cursor, props.title);
190
}
191
197
- if (
198
- instance.blend &&
199
- props.opacity !== prevProps.opacity
200
- ) {
192
+ if (instance.blend && props.opacity !== prevProps.opacity) {
193
instance.blend(props.opacity == null ? 1 : props.opacity);
194
}
195
@@ -256,11 +248,7 @@ function applyShapeProps(instance, props, prevProps = {}) {
248
prevProps.height !== props.height ||
249
prevProps.width !== props.width
250
) {
259
- instance.draw(
260
- path,
261
- props.width,
262
- props.height,
263
- );
251
+ instance.draw(path, props.width, props.height);
252
253
instance._prevDelta = path.delta;
254
instance._prevPath = path;
@@ -278,12 +266,7 @@ function applyTextProps(instance, props, prevProps = {}) {
266
props.alignment !== prevProps.alignment ||
267
props.path !== prevProps.path
268
) {
281
- instance.draw(
282
- string,
283
- props.font,
284
- props.alignment,
285
- props.path,
286
- );
269
+ instance.draw(string, props.font, props.alignment, props.path);
270
271
instance._currentString = string;
272
}
@@ -327,33 +310,22 @@ class Pattern {
310
311
class Surface extends Component {
312
componentDidMount() {
330
- const { height, width } = this.props;
313
+ const {height, width} = this.props;
314
315
this._surface = Mode.Surface(+width, +height, this._tagRef);
316
317
this._mountNode = ARTRenderer.createContainer(this._surface);
335
- ARTRenderer.updateContainer(
336
- this.props.children,
337
- this._mountNode,
338
- this,
339
- );
318
+ ARTRenderer.updateContainer(this.props.children, this._mountNode, this);
319
}
320
321
componentDidUpdate(prevProps, prevState) {
322
const props = this.props;
323
345
- if (
346
- props.height !== prevProps.height ||
347
- props.width !== prevProps.width
348
- ) {
324
+ if (props.height !== prevProps.height || props.width !== prevProps.width) {
325
this._surface.resize(+props.width, +props.height);
326
}
327
352
- ARTRenderer.updateContainer(
353
- this.props.children,
354
- this._mountNode,
355
- this,
356
- );
328
+ ARTRenderer.updateContainer(this.props.children, this._mountNode, this);
329
330
if (this._surface.render) {
331
this._surface.render();
@@ -361,11 +333,7 @@ class Surface extends Component {
333
}
334
335
componentWillUnmount() {
364
- ARTRenderer.updateContainer(
365
- null,
366
- this._mountNode,
367
- this,
368
- );
336
+ ARTRenderer.updateContainer(null, this._mountNode, this);
337
}
338
339
render() {
@@ -475,7 +443,7 @@ const ARTRenderer = ReactFiberReconciler({
443
insertBefore(parentInstance, child, beforeChild) {
444
invariant(
445
child !== beforeChild,
478
- 'ReactART: Can not insert node before itself'
446
+ 'ReactART: Can not insert node before itself',
447
);
448
449
child.injectBefore(beforeChild);
@@ -520,10 +488,8 @@ const ARTRenderer = ReactFiberReconciler({
488
scheduleDeferredCallback: ReactDOMFrameScheduling.rIC,
489
490
shouldSetTextContent(props) {
523
- return (
524
- typeof props.children === 'string' ||
525
- typeof props.children === 'number'
526
- );
491
+ return typeof props.children === 'string' ||
492
+ typeof props.children === 'number';
493
},
494
495
useSyncScheduling: true,
src/renderers/art/ReactARTStack.js
+92
-108
@@ -12,7 +12,7 @@
12
'use strict';
13
14
require('art/modes/current').setCurrent(
15
- require('art/modes/fast-noSideEffects') // Flip this to DOM mode for debugging
15
+ require('art/modes/fast-noSideEffects'), // Flip this to DOM mode for debugging
16
);
17
18
const Transform = require('art/core/transform');
@@ -67,8 +67,9 @@ function createComponent(name) {
67
*/
68
function injectAfter(parentNode, referenceNode, node) {
69
let beforeNode;
70
- if (node.parentNode === parentNode &&
71
- node.previousSibling === referenceNode) {
70
+ if (
71
+ node.parentNode === parentNode && node.previousSibling === referenceNode
72
+ ) {
73
return;
74
}
75
if (referenceNode == null) {
@@ -83,7 +84,7 @@ function injectAfter(parentNode, referenceNode, node) {
84
// checks and the behavior isn't well-defined.
85
invariant(
86
node !== beforeNode,
86
- 'ReactART: Can not insert node before itself'
87
+ 'ReactART: Can not insert node before itself',
88
);
89
node.injectBefore(beforeNode);
90
} else if (node.parentNode !== parentNode) {
@@ -94,7 +95,6 @@ function injectAfter(parentNode, referenceNode, node) {
95
// ContainerMixin for components that can hold ART nodes
96
97
const ContainerMixin = assign({}, ReactMultiChild, {
97
-
98
/**
99
* Moves a child component to the supplied index.
100
*
@@ -153,11 +153,7 @@ const ContainerMixin = assign({}, ReactMultiChild, {
153
// Shorthands
154
155
mountAndInjectChildren: function(children, transaction, context) {
156
- const mountedImages = this.mountChildren(
157
- children,
158
- transaction,
159
- context
160
- );
156
+ const mountedImages = this.mountChildren(children, transaction, context);
157
// Each mount image corresponds to one of the flattened children
158
let i = 0;
159
for (let key in this._renderedChildren) {
@@ -168,15 +164,13 @@ const ContainerMixin = assign({}, ReactMultiChild, {
164
i++;
165
}
166
}
171
- }
172
-
167
+ },
168
});
169
170
// Surface is a React DOM Component, not an ART component. It serves as the
171
// entry point into the ART reconciler.
172
173
const Surface = React.createClass({
179
-
174
displayName: 'Surface',
175
176
mixins: [ContainerMixin],
@@ -192,15 +186,16 @@ const Surface = React.createClass({
186
this,
187
this.props.children,
188
transaction,
195
- ReactInstanceMap.get(this)._context
189
+ ReactInstanceMap.get(this)._context,
190
);
191
ReactUpdates.ReactReconcileTransaction.release(transaction);
192
},
193
194
componentDidUpdate: function(oldProps) {
195
const node = this.node;
202
- if (this.props.width != oldProps.width ||
203
- this.props.height != oldProps.height) {
196
+ if (
197
+ this.props.width != oldProps.width || this.props.height != oldProps.height
198
+ ) {
199
node.resize(+this.props.width, +this.props.height);
200
}
201
@@ -210,7 +205,7 @@ const Surface = React.createClass({
205
this,
206
this.props.children,
207
transaction,
213
- ReactInstanceMap.get(this)._context
208
+ ReactInstanceMap.get(this)._context,
209
);
210
ReactUpdates.ReactReconcileTransaction.release(transaction);
211
@@ -243,8 +238,7 @@ const Surface = React.createClass({
238
title={props.title}
239
/>
240
);
246
- }
247
-
241
+ },
242
});
243
244
// Various nodes that can go into a surface
@@ -255,11 +249,10 @@ const EventTypes = {
249
onMouseOut: 'mouseout',
250
onMouseUp: 'mouseup',
251
onMouseDown: 'mousedown',
258
- onClick: 'click'
252
+ onClick: 'click',
253
};
254
255
const NodeMixin = {
262
-
256
construct: function(element) {
257
this._currentElement = element;
258
},
@@ -314,10 +307,12 @@ const NodeMixin = {
307
applyNodeProps: function(oldProps, props) {
308
const node = this.node;
309
317
- const scaleX = props.scaleX != null ? props.scaleX :
318
- props.scale != null ? props.scale : 1;
319
- const scaleY = props.scaleY != null ? props.scaleY :
320
- props.scale != null ? props.scale : 1;
310
+ const scaleX = props.scaleX != null
311
+ ? props.scaleX
312
+ : props.scale != null ? props.scale : 1;
313
+ const scaleY = props.scaleY != null
314
+ ? props.scaleY
315
+ : props.scale != null ? props.scale : 1;
316
317
pooledTransform
318
.transformTo(1, 0, 0, 1, 0, 0)
@@ -329,9 +324,14 @@ const NodeMixin = {
324
pooledTransform.transform(props.transform);
325
}
326
332
- if (node.xx !== pooledTransform.xx || node.yx !== pooledTransform.yx ||
333
- node.xy !== pooledTransform.xy || node.yy !== pooledTransform.yy ||
334
- node.x !== pooledTransform.x || node.y !== pooledTransform.y) {
327
+ if (
328
+ node.xx !== pooledTransform.xx ||
329
+ node.yx !== pooledTransform.yx ||
330
+ node.xy !== pooledTransform.xy ||
331
+ node.yy !== pooledTransform.yy ||
332
+ node.x !== pooledTransform.x ||
333
+ node.y !== pooledTransform.y
334
+ ) {
335
node.transformTo(pooledTransform);
336
}
337
@@ -359,21 +359,19 @@ const NodeMixin = {
359
mountComponentIntoNode: function(rootID, container) {
360
throw new Error(
361
'You cannot render an ART component standalone. ' +
362
- 'You need to wrap it in a Surface.'
362
+ 'You need to wrap it in a Surface.',
363
);
364
- }
365
-
364
+ },
365
};
366
367
// Group
368
369
const Group = createComponent('Group', NodeMixin, ContainerMixin, {
371
-
370
mountComponent: function(
371
transaction,
372
nativeParent,
373
nativeContainerInfo,
376
- context
374
+ context,
375
) {
376
this.node = Mode.Group();
377
const props = this._currentElement.props;
@@ -399,55 +397,54 @@ const Group = createComponent('Group', NodeMixin, ContainerMixin, {
397
unmountComponent: function() {
398
this.destroyEventListeners();
399
this.unmountChildren();
402
- }
403
-
400
+ },
401
});
402
403
// ClippingRectangle
404
const ClippingRectangle = createComponent(
408
- 'ClippingRectangle', NodeMixin, ContainerMixin, {
409
-
410
- mountComponent: function(
411
- transaction,
412
- nativeParent,
413
- nativeContainerInfo,
414
- context
415
- ) {
416
- this.node = Mode.ClippingRectangle();
417
- const props = this._currentElement.props;
418
- this.applyClippingProps(emptyObject, props);
419
- this.mountAndInjectChildren(props.children, transaction, context);
420
- return this.node;
421
- },
422
-
423
- receiveComponent: function(nextComponent, transaction, context) {
424
- const props = nextComponent.props;
425
- const oldProps = this._currentElement.props;
426
- this.applyClippingProps(oldProps, props);
427
- this.updateChildren(props.children, transaction, context);
428
- this._currentElement = nextComponent;
429
- },
430
-
431
- applyClippingProps: function(oldProps, props) {
432
- this.node.width = props.width;
433
- this.node.height = props.height;
434
- this.node.x = props.x;
435
- this.node.y = props.y;
436
- this.applyNodeProps(oldProps, props);
405
+ 'ClippingRectangle',
406
+ NodeMixin,
407
+ ContainerMixin,
408
+ {
409
+ mountComponent: function(
410
+ transaction,
411
+ nativeParent,
412
+ nativeContainerInfo,
413
+ context,
414
+ ) {
415
+ this.node = Mode.ClippingRectangle();
416
+ const props = this._currentElement.props;
417
+ this.applyClippingProps(emptyObject, props);
418
+ this.mountAndInjectChildren(props.children, transaction, context);
419
+ return this.node;
420
+ },
421
+
422
+ receiveComponent: function(nextComponent, transaction, context) {
423
+ const props = nextComponent.props;
424
+ const oldProps = this._currentElement.props;
425
+ this.applyClippingProps(oldProps, props);
426
+ this.updateChildren(props.children, transaction, context);
427
+ this._currentElement = nextComponent;
428
+ },
429
+
430
+ applyClippingProps: function(oldProps, props) {
431
+ this.node.width = props.width;
432
+ this.node.height = props.height;
433
+ this.node.x = props.x;
434
+ this.node.y = props.y;
435
+ this.applyNodeProps(oldProps, props);
436
+ },
437
+
438
+ unmountComponent: function() {
439
+ this.destroyEventListeners();
440
+ this.unmountChildren();
441
+ },
442
},
438
-
439
- unmountComponent: function() {
440
- this.destroyEventListeners();
441
- this.unmountChildren();
442
- }
443
-
444
-});
445
-
443
+);
444
445
// Renderables
446
447
const RenderableMixin = assign({}, NodeMixin, {
450
-
448
applyRenderableProps: function(oldProps, props) {
449
if (oldProps.fill !== props.fill) {
450
if (props.fill && props.fill.applyFill) {
@@ -470,7 +467,7 @@ const RenderableMixin = assign({}, NodeMixin, {
467
props.strokeWidth,
468
props.strokeCap,
469
props.strokeJoin,
473
- props.strokeDash
470
+ props.strokeDash,
471
);
472
}
473
this.applyNodeProps(oldProps, props);
@@ -478,14 +475,12 @@ const RenderableMixin = assign({}, NodeMixin, {
475
476
unmountComponent: function() {
477
this.destroyEventListeners();
481
- }
482
-
478
+ },
479
});
480
481
// Shape
482
483
const Shape = createComponent('Shape', RenderableMixin, {
488
-
484
construct: function(element) {
485
this._currentElement = element;
486
this._oldDelta = null;
@@ -496,7 +491,7 @@ const Shape = createComponent('Shape', RenderableMixin, {
491
transaction,
492
nativeParent,
493
nativeContainerInfo,
499
- context
494
+ context,
495
) {
496
this.node = Mode.Shape();
497
const props = this._currentElement.props;
@@ -516,30 +511,25 @@ const Shape = createComponent('Shape', RenderableMixin, {
511
const oldPath = this._oldPath;
512
const path = props.d || childrenAsString(props.children);
513
519
- if (path.delta !== oldDelta ||
520
- path !== oldPath ||
521
- oldProps.width !== props.width ||
522
- oldProps.height !== props.height) {
523
-
524
- this.node.draw(
525
- path,
526
- props.width,
527
- props.height
528
- );
514
+ if (
515
+ path.delta !== oldDelta ||
516
+ path !== oldPath ||
517
+ oldProps.width !== props.width ||
518
+ oldProps.height !== props.height
519
+ ) {
520
+ this.node.draw(path, props.width, props.height);
521
522
this._oldPath = path;
523
this._oldDelta = path.delta;
524
}
525
526
this.applyRenderableProps(oldProps, props);
535
- }
536
-
527
+ },
528
});
529
530
// Text
531
532
const Text = createComponent('Text', RenderableMixin, {
542
-
533
construct: function(element) {
534
this._currentElement = element;
535
this._oldString = null;
@@ -549,7 +539,7 @@ const Text = createComponent('Text', RenderableMixin, {
539
transaction,
540
nativeParent,
541
nativeContainerInfo,
552
- context
542
+ context,
543
) {
544
const props = this._currentElement.props;
545
const newString = childrenAsString(props.children);
@@ -566,13 +556,11 @@ const Text = createComponent('Text', RenderableMixin, {
556
if (typeof newFont === 'string' || typeof oldFont === 'string') {
557
return false;
558
}
569
- return (
570
- newFont.fontSize === oldFont.fontSize &&
559
+ return newFont.fontSize === oldFont.fontSize &&
560
newFont.fontStyle === oldFont.fontStyle &&
561
newFont.fontVariant === oldFont.fontVariant &&
562
newFont.fontWeight === oldFont.fontWeight &&
574
- newFont.fontFamily === oldFont.fontFamily
575
- );
563
+ newFont.fontFamily === oldFont.fontFamily;
564
},
565
566
receiveComponent: function(nextComponent, transaction, context) {
@@ -582,23 +570,19 @@ const Text = createComponent('Text', RenderableMixin, {
570
const oldString = this._oldString;
571
const newString = childrenAsString(props.children);
572
585
- if (oldString !== newString ||
586
- !this.isSameFont(oldProps.font, props.font) ||
587
- oldProps.alignment !== props.alignment ||
588
- oldProps.path !== props.path) {
589
- this.node.draw(
590
- newString,
591
- props.font,
592
- props.alignment,
593
- props.path
594
- );
573
+ if (
574
+ oldString !== newString ||
575
+ !this.isSameFont(oldProps.font, props.font) ||
576
+ oldProps.alignment !== props.alignment ||
577
+ oldProps.path !== props.path
578
+ ) {
579
+ this.node.draw(newString, props.font, props.alignment, props.path);
580
this._oldString = newString;
581
}
582
583
this.applyRenderableProps(oldProps, props);
584
this._currentElement = nextComponent;
600
- }
601
-
585
+ },
586
});
587
588
// Declarative fill type objects - API design not finalized
src/renderers/art/__tests__/ReactART-test.js
+43
-39
@@ -49,7 +49,6 @@ function testDOMNodeStructure(domNode, expectedStructure) {
49
}
50
51
describe('ReactART', () => {
52
-
52
beforeEach(() => {
53
ARTCurrentMode.setCurrent(ARTSVGMode);
54
@@ -59,29 +58,33 @@ describe('ReactART', () => {
58
59
TestComponent = class extends React.Component {
60
render() {
62
-
63
- var a =
61
+ var a = (
62
<Shape
63
d="M0,0l50,0l0,50l-50,0z"
66
- fill={new ReactART.LinearGradient(["black", "white"])}
64
+ fill={new ReactART.LinearGradient(['black', 'white'])}
65
key="a"
68
- width={50} height={50}
69
- x={50} y={50}
66
+ width={50}
67
+ height={50}
68
+ x={50}
69
+ y={50}
70
opacity={0.1}
71
- />;
71
+ />
72
+ );
73
73
- var b =
74
+ var b = (
75
<Shape
76
fill="#3C5A99"
77
key="b"
78
scale={0.5}
78
- x={50} y={50}
79
+ x={50}
80
+ y={50}
81
title="This is an F"
82
cursor="pointer">
83
M64.564,38.583H54l0.008-5.834c0-3.035,0.293-4.666,4.657-4.666
84
h5.833V16.429h-9.33c-11.213,0-15.159,5.654-15.159,15.16v6.994
85
h-6.99v11.652h6.99v33.815H54V50.235h9.331L64.564,38.583z
84
- </Shape>;
86
+ </Shape>
87
+ );
88
89
var c = <Group key="c" />;
90
@@ -113,22 +116,20 @@ describe('ReactART', () => {
116
width: '150',
117
height: '200',
118
children: [
116
- { nodeName: 'defs' },
119
+ {nodeName: 'defs'},
120
{
121
nodeName: 'g',
122
children: [
123
{
124
nodeName: 'defs',
122
- children: [
123
- { nodeName: 'linearGradient' }
124
- ]
125
+ children: [{nodeName: 'linearGradient'}],
126
},
126
- { nodeName: 'path' },
127
- { nodeName: 'path' },
128
- { nodeName: 'g' }
129
- ]
130
- }
131
- ]
127
+ {nodeName: 'path'},
128
+ {nodeName: 'path'},
129
+ {nodeName: 'g'},
130
+ ],
131
+ },
132
+ ],
133
};
134
135
var realNode = ReactDOM.findDOMNode(instance);
@@ -137,22 +138,25 @@ describe('ReactART', () => {
138
139
it('should be able to reorder components', () => {
140
var container = document.createElement('div');
140
- var instance = ReactDOM.render(<TestComponent flipped={false} />, container);
141
+ var instance = ReactDOM.render(
142
+ <TestComponent flipped={false} />,
143
+ container,
144
+ );
145
146
var expectedStructure = {
147
nodeName: 'svg',
148
children: [
145
- { nodeName: 'defs' },
149
+ {nodeName: 'defs'},
150
{
151
nodeName: 'g',
152
children: [
149
- { nodeName: 'defs' },
150
- { nodeName: 'path', opacity: '0.1' },
151
- { nodeName: 'path', opacity: Missing },
152
- { nodeName: 'g' }
153
- ]
154
- }
155
- ]
153
+ {nodeName: 'defs'},
154
+ {nodeName: 'path', opacity: '0.1'},
155
+ {nodeName: 'path', opacity: Missing},
156
+ {nodeName: 'g'},
157
+ ],
158
+ },
159
+ ],
160
};
161
162
var realNode = ReactDOM.findDOMNode(instance);
@@ -163,17 +167,17 @@ describe('ReactART', () => {
167
var expectedNewStructure = {
168
nodeName: 'svg',
169
children: [
166
- { nodeName: 'defs' },
170
+ {nodeName: 'defs'},
171
{
172
nodeName: 'g',
173
children: [
170
- { nodeName: 'defs' },
171
- { nodeName: 'path', opacity: Missing },
172
- { nodeName: 'path', opacity: '0.1' },
173
- { nodeName: 'g' }
174
- ]
175
- }
176
- ]
174
+ {nodeName: 'defs'},
175
+ {nodeName: 'path', opacity: Missing},
176
+ {nodeName: 'path', opacity: '0.1'},
177
+ {nodeName: 'g'},
178
+ ],
179
+ },
180
+ ],
181
};
182
183
testDOMNodeStructure(realNode, expectedNewStructure);
@@ -187,7 +191,7 @@ describe('ReactART', () => {
191
var chars = this.props.chars.split('');
192
return (
193
<Surface>
190
- {chars.map((text) => <Shape key={text} title={text} />)}
194
+ {chars.map(text => <Shape key={text} title={text} />)}
195
</Surface>
196
);
197
}
@@ -225,7 +229,7 @@ describe('ReactART', () => {
229
<Group>
230
<CustomShape />
231
</Group>
228
- </Surface>
232
+ </Surface>,
233
);
234
expect(mounted).toBe(true);
235
});
src/renderers/dom/ReactDOM.js
+23
-20
@@ -44,11 +44,11 @@ var ReactDOM = {
44
// Allows for debugging when the hook is injected on the page.
45
if (
46
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
47
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') {
47
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function'
48
+) {
49
__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({
50
ComponentTree: {
50
- getClosestInstanceFromNode:
51
- ReactDOMComponentTree.getClosestInstanceFromNode,
51
+ getClosestInstanceFromNode: ReactDOMComponentTree.getClosestInstanceFromNode,
52
getNodeFromInstance: function(inst) {
53
// inst is an internal instance (but could be a composite)
54
if (inst._renderedComponent) {
@@ -69,21 +69,24 @@ if (
69
if (__DEV__) {
70
var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
71
if (ExecutionEnvironment.canUseDOM && window.top === window.self) {
72
-
72
// First check if devtools is not installed
73
if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
74
// If we're in Chrome or Firefox, provide a download link if not installed.
76
- if ((navigator.userAgent.indexOf('Chrome') > -1 &&
75
+ if (
76
+ (navigator.userAgent.indexOf('Chrome') > -1 &&
77
navigator.userAgent.indexOf('Edge') === -1) ||
78
- navigator.userAgent.indexOf('Firefox') > -1) {
78
+ navigator.userAgent.indexOf('Firefox') > -1
79
+ ) {
80
// Firefox does not have the issue with devtools loaded over file://
80
- var showFileUrlMessage = window.location.protocol.indexOf('http') === -1 &&
81
- navigator.userAgent.indexOf('Firefox') === -1;
81
+ var showFileUrlMessage = window.location.protocol.indexOf('http') ===
82
+ -1 && navigator.userAgent.indexOf('Firefox') === -1;
83
console.debug(
84
'Download the React DevTools ' +
84
- (showFileUrlMessage ? 'and use an HTTP server (instead of a file: URL) ' : '') +
85
- 'for a better development experience: ' +
86
- 'https://fb.me/react-devtools'
85
+ (showFileUrlMessage
86
+ ? 'and use an HTTP server (instead of a file: URL) '
87
+ : '') +
88
+ 'for a better development experience: ' +
89
+ 'https://fb.me/react-devtools',
90
);
91
}
92
}
@@ -91,22 +94,22 @@ if (__DEV__) {
94
var testFunc = function testFn() {};
95
warning(
96
(testFunc.name || testFunc.toString()).indexOf('testFn') !== -1,
94
- 'It looks like you\'re using a minified copy of the development build ' +
95
- 'of React. When deploying React apps to production, make sure to use ' +
96
- 'the production build which skips development warnings and is faster. ' +
97
- 'See https://fb.me/react-minification for more details.'
97
+ "It looks like you're using a minified copy of the development build " +
98
+ 'of React. When deploying React apps to production, make sure to use ' +
99
+ 'the production build which skips development warnings and is faster. ' +
100
+ 'See https://fb.me/react-minification for more details.',
101
);
102
103
// If we're in IE8, check to see if we are in compatibility mode and provide
104
// information on preventing compatibility mode
102
- var ieCompatibilityMode =
103
- document.documentMode && document.documentMode < 8;
105
+ var ieCompatibilityMode = document.documentMode &&
106
+ document.documentMode < 8;
107
108
warning(
109
!ieCompatibilityMode,
110
'Internet Explorer is running in compatibility mode; please add the ' +
108
- 'following tag to your HTML to prevent this from happening: ' +
109
- '<meta http-equiv="X-UA-Compatible" content="IE=edge" />'
111
+ 'following tag to your HTML to prevent this from happening: ' +
112
+ '<meta http-equiv="X-UA-Compatible" content="IE=edge" />',
113
);
114
115
var expectedFeatures = [
@@ -127,7 +130,7 @@ if (__DEV__) {
130
warning(
131
false,
132
'One or more ES5 shims expected by React are not available: ' +
130
- 'https://fb.me/react-warning-polyfills'
133
+ 'https://fb.me/react-warning-polyfills',
134
);
135
break;
136
}
src/renderers/dom/__mocks__/ReactDOM.js
+3
-2
@@ -13,5 +13,6 @@ var ReactDOMFeatureFlags = require('ReactDOMFeatureFlags');
13
14
var useFiber = ReactDOMFeatureFlags.useFiber;
15
16
-module.exports =
17
- useFiber ? require('ReactDOMFiber') : require.requireActual('ReactDOM');
16
+module.exports = useFiber
17
+ ? require('ReactDOMFiber')
18
+ : require.requireActual('ReactDOM');
src/renderers/dom/__tests__/ReactDOMProduction-test.js
+13
-26
@@ -69,7 +69,7 @@ describe('ReactDOMProduction', () => {
69
<Component key={2}>B</Component>
70
<Component key={3}>C</Component>
71
</div>,
72
- container
72
+ container,
73
);
74
75
expect(container.firstChild).toBe(inst);
@@ -82,7 +82,7 @@ describe('ReactDOMProduction', () => {
82
<Component key={1}>A</Component>
83
<Component key={3}>C</Component>
84
</div>,
85
- container
85
+ container,
86
);
87
88
expect(inst.className).toBe('red');
@@ -126,10 +126,7 @@ describe('ReactDOMProduction', () => {
126
}
127
128
var container = document.createElement('div');
129
- var inst = ReactDOM.render(
130
- <Component x={1} />,
131
- container
132
- );
129
+ var inst = ReactDOM.render(<Component x={1} />, container);
130
expect(log).toEqual([
131
['componentWillMount'],
132
['render'],
@@ -147,15 +144,10 @@ describe('ReactDOMProduction', () => {
144
log = [];
145
146
inst.setState({y: 2});
150
- expect(log).toEqual([
151
- ['shouldComponentUpdate', {x: 1}, {y: 2}],
152
- ]);
147
+ expect(log).toEqual([['shouldComponentUpdate', {x: 1}, {y: 2}]]);
148
log = [];
149
155
- ReactDOM.render(
156
- <Component x={2} />,
157
- container
158
- );
150
+ ReactDOM.render(<Component x={2} />, container);
151
expect(log).toEqual([
152
['componentWillReceiveProps', {x: 2}],
153
['shouldComponentUpdate', {x: 2}, {y: 2}],
@@ -165,10 +157,7 @@ describe('ReactDOMProduction', () => {
157
]);
158
log = [];
159
168
- ReactDOM.render(
169
- <Component x={2} />,
170
- container
171
- );
160
+ ReactDOM.render(<Component x={2} />, container);
161
expect(log).toEqual([
162
['componentWillReceiveProps', {x: 2}],
163
['shouldComponentUpdate', {x: 2}, {y: 2}],
@@ -176,9 +165,7 @@ describe('ReactDOMProduction', () => {
165
log = [];
166
167
ReactDOM.unmountComponentAtNode(container);
179
- expect(log).toEqual([
180
- ['componentWillUnmount'],
181
- ]);
168
+ expect(log).toEqual([['componentWillUnmount']]);
169
});
170
171
it('should throw with an error code in production', () => {
@@ -193,9 +180,9 @@ describe('ReactDOMProduction', () => {
180
ReactDOM.render(<Component />, container);
181
}).toThrowError(
182
'Minified React error #109; visit ' +
196
- 'http://facebook.github.io/react/docs/error-decoder.html?invariant=109&args[]=Component' +
197
- ' for the full message or use the non-minified dev environment' +
198
- ' for full errors and additional helpful warnings.'
183
+ 'http://facebook.github.io/react/docs/error-decoder.html?invariant=109&args[]=Component' +
184
+ ' for the full message or use the non-minified dev environment' +
185
+ ' for full errors and additional helpful warnings.',
186
);
187
});
188
@@ -232,7 +219,7 @@ describe('ReactDOMProduction', () => {
219
var usePortal = function(tree) {
220
return ReactDOM.unstable_createPortal(
221
tree,
235
- document.createElement('div')
222
+ document.createElement('div'),
223
);
224
};
225
var assertNamespacesMatch = function(tree) {
@@ -266,14 +253,14 @@ describe('ReactDOMProduction', () => {
253
{usePortal(<p {...expectHTML} />)}
254
</svg>
255
<image {...expectSVG} />
269
- </svg>
256
+ </svg>,
257
)}
258
<p {...expectHTML} />
259
</foreignObject>
260
<image {...expectSVG} />
261
</svg>
262
<p {...expectHTML} />
276
- </div>
263
+ </div>,
264
);
265
});
266
}
src/renderers/dom/fiber/ReactDOMFiber.js
+196
-152
@@ -12,8 +12,8 @@
12
13
'use strict';
14
15
-import type { Fiber } from 'ReactFiber';
16
-import type { ReactNodeList } from 'ReactTypes';
15
+import type {Fiber} from 'ReactFiber';
16
+import type {ReactNodeList} from 'ReactTypes';
17
18
var ReactBrowserEventEmitter = require('ReactBrowserEventEmitter');
19
var ReactControlledComponent = require('ReactControlledComponent');
@@ -28,8 +28,8 @@ var ReactFiberReconciler = require('ReactFiberReconciler');
28
var ReactInputSelection = require('ReactInputSelection');
29
var ReactInstanceMap = require('ReactInstanceMap');
30
var ReactPortal = require('ReactPortal');
31
-var { isValidElement } = require('react');
32
-var { injectInternals } = require('ReactFiberDevToolsHook');
31
+var {isValidElement} = require('react');
32
+var {injectInternals} = require('ReactFiberDevToolsHook');
33
34
var findDOMNode = require('findDOMNode');
35
var invariant = require('fbjs/lib/invariant');
@@ -49,40 +49,39 @@ var {
49
50
if (__DEV__) {
51
var validateDOMNesting = require('validateDOMNesting');
52
- var { updatedAncestorInfo } = validateDOMNesting;
52
+ var {updatedAncestorInfo} = validateDOMNesting;
53
}
54
55
-
55
const DOCUMENT_NODE = 9;
56
57
ReactDOMInjection.inject();
58
ReactControlledComponent.injection.injectFiberControlledHostComponent(
60
- ReactDOMFiberComponent
59
+ ReactDOMFiberComponent,
60
);
61
findDOMNode._injectFiber(function(fiber: Fiber) {
62
return DOMRenderer.findHostInstance(fiber);
63
});
64
66
-type DOMContainerElement = Element & { _reactRootContainer: ?Object };
65
+type DOMContainerElement = Element & {_reactRootContainer: ?Object};
66
67
type Container = Element;
68
type Props = {
70
- autoFocus ?: boolean,
71
- children ?: mixed,
72
- hidden ?: boolean,
69
+ autoFocus?: boolean,
70
+ children?: mixed,
71
+ hidden?: boolean,
72
};
73
type Instance = Element;
74
type TextInstance = Text;
75
76
type HostContextDev = {
78
- namespace : string,
79
- ancestorInfo : mixed,
77
+ namespace: string,
78
+ ancestorInfo: mixed,
79
};
80
type HostContextProd = string;
81
type HostContext = HostContextDev | HostContextProd;
82
84
-let eventsEnabled : ?boolean = null;
85
-let selectionInformation : ?mixed = null;
83
+let eventsEnabled: ?boolean = null;
84
+let selectionInformation: ?mixed = null;
85
86
var ELEMENT_NODE_TYPE = 1;
87
var DOC_NODE_TYPE = 9;
@@ -96,11 +95,10 @@ var DOCUMENT_FRAGMENT_NODE_TYPE = 11;
95
* @internal
96
*/
97
function isValidContainer(node) {
99
- return !!(node && (
100
- node.nodeType === ELEMENT_NODE_TYPE ||
101
- node.nodeType === DOC_NODE_TYPE ||
102
- node.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE
103
- ));
98
+ return !!(node &&
99
+ (node.nodeType === ELEMENT_NODE_TYPE ||
100
+ node.nodeType === DOC_NODE_TYPE ||
101
+ node.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE));
102
}
103
104
function validateContainer(container) {
@@ -109,7 +107,7 @@ function validateContainer(container) {
107
}
108
}
109
112
-function getReactRootElementInContainer(container : any) {
110
+function getReactRootElementInContainer(container: any) {
111
if (!container) {
112
return null;
113
}
@@ -121,10 +119,7 @@ function getReactRootElementInContainer(container : any) {
119
}
120
}
121
124
-function shouldAutoFocusHostComponent(
125
- type : string,
126
- props : Props,
127
-) : boolean {
122
+function shouldAutoFocusHostComponent(type: string, props: Props): boolean {
123
switch (type) {
124
case 'button':
125
case 'input':
@@ -136,14 +131,16 @@ function shouldAutoFocusHostComponent(
131
}
132
133
var DOMRenderer = ReactFiberReconciler({
139
-
140
- getRootHostContext(rootContainerInstance : Container) : HostContext {
134
+ getRootHostContext(rootContainerInstance: Container): HostContext {
135
const ownNamespace = rootContainerInstance.namespaceURI || null;
136
const type = rootContainerInstance.tagName;
137
const namespace = getChildNamespace(ownNamespace, type);
138
if (__DEV__) {
145
- const isMountingIntoDocument = rootContainerInstance.ownerDocument.documentElement === rootContainerInstance;
146
- const validatedTag = isMountingIntoDocument ? '#document' : type.toLowerCase();
139
+ const isMountingIntoDocument = rootContainerInstance.ownerDocument.documentElement ===
140
+ rootContainerInstance;
141
+ const validatedTag = isMountingIntoDocument
142
+ ? '#document'
143
+ : type.toLowerCase();
144
const ancestorInfo = updatedAncestorInfo(null, validatedTag, null);
145
return {namespace, ancestorInfo};
146
}
@@ -151,16 +148,20 @@ var DOMRenderer = ReactFiberReconciler({
148
},
149
150
getChildHostContext(
154
- parentHostContext : HostContext,
155
- type : string,
156
- ) : HostContext {
151
+ parentHostContext: HostContext,
152
+ type: string,
153
+ ): HostContext {
154
if (__DEV__) {
158
- const parentHostContextDev = ((parentHostContext : any) : HostContextDev);
155
+ const parentHostContextDev = ((parentHostContext: any): HostContextDev);
156
const namespace = getChildNamespace(parentHostContextDev.namespace, type);
160
- const ancestorInfo = updatedAncestorInfo(parentHostContextDev.ancestorInfo, type, null);
157
+ const ancestorInfo = updatedAncestorInfo(
158
+ parentHostContextDev.ancestorInfo,
159
+ type,
160
+ null,
161
+ );
162
return {namespace, ancestorInfo};
163
}
163
- const parentNamespace = ((parentHostContext : any) : HostContextProd);
164
+ const parentNamespace = ((parentHostContext: any): HostContextProd);
165
return getChildNamespace(parentNamespace, type);
166
},
167
@@ -168,13 +169,13 @@ var DOMRenderer = ReactFiberReconciler({
169
return instance;
170
},
171
171
- prepareForCommit() : void {
172
+ prepareForCommit(): void {
173
eventsEnabled = ReactBrowserEventEmitter.isEnabled();
174
selectionInformation = ReactInputSelection.getSelectionInformation();
175
ReactBrowserEventEmitter.setEnabled(false);
176
},
177
177
- resetAfterCommit() : void {
178
+ resetAfterCommit(): void {
179
ReactInputSelection.restoreSelection(selectionInformation);
180
selectionInformation = null;
181
ReactBrowserEventEmitter.setEnabled(eventsEnabled);
@@ -182,88 +183,114 @@ var DOMRenderer = ReactFiberReconciler({
183
},
184
185
createInstance(
185
- type : string,
186
- props : Props,
187
- rootContainerInstance : Container,
188
- hostContext : HostContext,
189
- internalInstanceHandle : Object,
190
- ) : Instance {
191
- let parentNamespace : string;
186
+ type: string,
187
+ props: Props,
188
+ rootContainerInstance: Container,
189
+ hostContext: HostContext,
190
+ internalInstanceHandle: Object,
191
+ ): Instance {
192
+ let parentNamespace: string;
193
if (__DEV__) {
194
// TODO: take namespace into account when validating.
194
- const hostContextDev = ((hostContext : any) : HostContextDev);
195
+ const hostContextDev = ((hostContext: any): HostContextDev);
196
validateDOMNesting(type, null, null, hostContextDev.ancestorInfo);
197
if (
197
- typeof props.children === 'string' ||
198
- typeof props.children === 'number'
198
+ typeof props.children === 'string' || typeof props.children === 'number'
199
) {
200
const string = '' + props.children;
201
- const ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type, null);
201
+ const ownAncestorInfo = updatedAncestorInfo(
202
+ hostContextDev.ancestorInfo,
203
+ type,
204
+ null,
205
+ );
206
validateDOMNesting(null, string, null, ownAncestorInfo);
207
}
208
parentNamespace = hostContextDev.namespace;
209
} else {
206
- parentNamespace = ((hostContext : any) : HostContextProd);
210
+ parentNamespace = ((hostContext: any): HostContextProd);
211
}
208
- const domElement : Instance = createElement(type, props, rootContainerInstance, parentNamespace);
212
+ const domElement: Instance = createElement(
213
+ type,
214
+ props,
215
+ rootContainerInstance,
216
+ parentNamespace,
217
+ );
218
precacheFiberNode(internalInstanceHandle, domElement);
219
updateFiberProps(domElement, props);
220
return domElement;
221
},
222
214
- appendInitialChild(parentInstance : Instance, child : Instance | TextInstance) : void {
223
+ appendInitialChild(
224
+ parentInstance: Instance,
225
+ child: Instance | TextInstance,
226
+ ): void {
227
parentInstance.appendChild(child);
228
},
229
230
finalizeInitialChildren(
219
- domElement : Instance,
220
- type : string,
221
- props : Props,
222
- rootContainerInstance : Container,
223
- ) : boolean {
231
+ domElement: Instance,
232
+ type: string,
233
+ props: Props,
234
+ rootContainerInstance: Container,
235
+ ): boolean {
236
setInitialProperties(domElement, type, props, rootContainerInstance);
237
return shouldAutoFocusHostComponent(type, props);
238
},
239
240
prepareUpdate(
229
- domElement : Instance,
230
- type : string,
231
- oldProps : Props,
232
- newProps : Props,
233
- rootContainerInstance : Container,
234
- hostContext : HostContext,
235
- ) : null | Array<mixed> {
241
+ domElement: Instance,
242
+ type: string,
243
+ oldProps: Props,
244
+ newProps: Props,
245
+ rootContainerInstance: Container,
246
+ hostContext: HostContext,
247
+ ): null | Array<mixed> {
248
if (__DEV__) {
237
- const hostContextDev = ((hostContext : any) : HostContextDev);
238
- if (typeof newProps.children !== typeof oldProps.children && (
239
- typeof newProps.children === 'string' ||
240
- typeof newProps.children === 'number'
241
- )) {
249
+ const hostContextDev = ((hostContext: any): HostContextDev);
250
+ if (
251
+ typeof newProps.children !== typeof oldProps.children &&
252
+ (typeof newProps.children === 'string' ||
253
+ typeof newProps.children === 'number')
254
+ ) {
255
const string = '' + newProps.children;
243
- const ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type, null);
256
+ const ownAncestorInfo = updatedAncestorInfo(
257
+ hostContextDev.ancestorInfo,
258
+ type,
259
+ null,
260
+ );
261
validateDOMNesting(null, string, null, ownAncestorInfo);
262
}
263
}
247
- return diffProperties(domElement, type, oldProps, newProps, rootContainerInstance);
264
+ return diffProperties(
265
+ domElement,
266
+ type,
267
+ oldProps,
268
+ newProps,
269
+ rootContainerInstance,
270
+ );
271
},
272
273
commitMount(
251
- domElement : Instance,
252
- type : string,
253
- newProps : Props,
254
- internalInstanceHandle : Object,
255
- ) : void {
256
- ((domElement : any) : HTMLButtonElement | HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement).focus();
274
+ domElement: Instance,
275
+ type: string,
276
+ newProps: Props,
277
+ internalInstanceHandle: Object,
278
+ ): void {
279
+ ((domElement: any):
280
+ | HTMLButtonElement
281
+ | HTMLInputElement
282
+ | HTMLSelectElement
283
+ | HTMLTextAreaElement).focus();
284
},
285
286
commitUpdate(
260
- domElement : Instance,
261
- updatePayload : Array<mixed>,
262
- type : string,
263
- oldProps : Props,
264
- newProps : Props,
265
- internalInstanceHandle : Object,
266
- ) : void {
287
+ domElement: Instance,
288
+ updatePayload: Array<mixed>,
289
+ type: string,
290
+ oldProps: Props,
291
+ newProps: Props,
292
+ internalInstanceHandle: Object,
293
+ ): void {
294
// Update the props handle so that we know which props are the ones with
295
// with current event handlers.
296
updateFiberProps(domElement, newProps);
@@ -271,58 +298,64 @@ var DOMRenderer = ReactFiberReconciler({
298
updateProperties(domElement, updatePayload, type, oldProps, newProps);
299
},
300
274
- shouldSetTextContent(props : Props) : boolean {
275
- return (
276
- typeof props.children === 'string' ||
301
+ shouldSetTextContent(props: Props): boolean {
302
+ return typeof props.children === 'string' ||
303
typeof props.children === 'number' ||
278
- (
279
- typeof props.dangerouslySetInnerHTML === 'object' &&
304
+ (typeof props.dangerouslySetInnerHTML === 'object' &&
305
props.dangerouslySetInnerHTML !== null &&
281
- typeof props.dangerouslySetInnerHTML.__html === 'string'
282
- )
283
- );
306
+ typeof props.dangerouslySetInnerHTML.__html === 'string');
307
},
308
286
- resetTextContent(domElement : Instance) : void {
309
+ resetTextContent(domElement: Instance): void {
310
domElement.textContent = '';
311
},
312
290
- shouldDeprioritizeSubtree(type : string, props : Props) : boolean {
313
+ shouldDeprioritizeSubtree(type: string, props: Props): boolean {
314
return !!props.hidden;
315
},
316
317
createTextInstance(
295
- text : string,
296
- rootContainerInstance : Container,
297
- hostContext : HostContext,
298
- internalInstanceHandle : Object
299
- ) : TextInstance {
318
+ text: string,
319
+ rootContainerInstance: Container,
320
+ hostContext: HostContext,
321
+ internalInstanceHandle: Object,
322
+ ): TextInstance {
323
if (__DEV__) {
301
- const hostContextDev = ((hostContext : any) : HostContextDev);
324
+ const hostContextDev = ((hostContext: any): HostContextDev);
325
validateDOMNesting(null, text, null, hostContextDev.ancestorInfo);
326
}
304
- var textNode : TextInstance = document.createTextNode(text);
327
+ var textNode: TextInstance = document.createTextNode(text);
328
precacheFiberNode(internalInstanceHandle, textNode);
329
return textNode;
330
},
331
309
- commitTextUpdate(textInstance : TextInstance, oldText : string, newText : string) : void {
332
+ commitTextUpdate(
333
+ textInstance: TextInstance,
334
+ oldText: string,
335
+ newText: string,
336
+ ): void {
337
textInstance.nodeValue = newText;
338
},
339
313
- appendChild(parentInstance : Instance | Container, child : Instance | TextInstance) : void {
340
+ appendChild(
341
+ parentInstance: Instance | Container,
342
+ child: Instance | TextInstance,
343
+ ): void {
344
parentInstance.appendChild(child);
345
},
346
347
insertBefore(
318
- parentInstance : Instance | Container,
319
- child : Instance | TextInstance,
320
- beforeChild : Instance | TextInstance
321
- ) : void {
348
+ parentInstance: Instance | Container,
349
+ child: Instance | TextInstance,
350
+ beforeChild: Instance | TextInstance,
351
+ ): void {
352
parentInstance.insertBefore(child, beforeChild);
353
},
354
325
- removeChild(parentInstance : Instance | Container, child : Instance | TextInstance) : void {
355
+ removeChild(
356
+ parentInstance: Instance | Container,
357
+ child: Instance | TextInstance,
358
+ ): void {
359
parentInstance.removeChild(child);
360
},
361
@@ -331,10 +364,11 @@ var DOMRenderer = ReactFiberReconciler({
364
scheduleDeferredCallback: ReactDOMFrameScheduling.rIC,
365
366
useSyncScheduling: !ReactDOMFeatureFlags.fiberAsyncScheduling,
334
-
367
});
368
337
-ReactGenericBatching.injection.injectFiberBatchedUpdates(DOMRenderer.batchedUpdates);
369
+ReactGenericBatching.injection.injectFiberBatchedUpdates(
370
+ DOMRenderer.batchedUpdates,
371
+);
372
373
var warned = false;
374
@@ -343,21 +377,22 @@ function warnAboutUnstableUse() {
377
warning(
378
warned || ReactDOMFeatureFlags.useFiber,
379
'You are using React DOM Fiber which is an experimental renderer. ' +
346
- 'It is likely to have bugs, breaking changes and is unsupported.'
380
+ 'It is likely to have bugs, breaking changes and is unsupported.',
381
);
382
warned = true;
383
}
384
385
function renderSubtreeIntoContainer(
352
- parentComponent : ?ReactComponent<any, any, any>,
353
- children : ReactNodeList,
354
- containerNode : DOMContainerElement | Document,
355
- callback: ?Function
386
+ parentComponent: ?ReactComponent<any, any, any>,
387
+ children: ReactNodeList,
388
+ containerNode: DOMContainerElement | Document,
389
+ callback: ?Function,
390
) {
391
validateContainer(containerNode);
392
359
- let container : DOMContainerElement =
360
- containerNode.nodeType === DOCUMENT_NODE ? (containerNode : any).documentElement : (containerNode : any);
393
+ let container: DOMContainerElement = containerNode.nodeType === DOCUMENT_NODE
394
+ ? (containerNode: any).documentElement
395
+ : (containerNode: any);
396
let root = container._reactRootContainer;
397
if (!root) {
398
// First clear any existing content.
@@ -365,7 +400,7 @@ function renderSubtreeIntoContainer(
400
container.removeChild(container.lastChild);
401
}
402
const newRoot = DOMRenderer.createContainer(container);
368
- root = container._reactRootContainer = newRoot;
403
+ root = (container._reactRootContainer = newRoot);
404
// Initial mount should not be batched.
405
DOMRenderer.unbatchedUpdates(() => {
406
DOMRenderer.updateContainer(children, newRoot, parentComponent, callback);
@@ -377,8 +412,11 @@ function renderSubtreeIntoContainer(
412
}
413
414
var ReactDOM = {
380
-
381
- render(element : ReactElement<any>, container : DOMContainerElement, callback: ?Function) {
415
+ render(
416
+ element: ReactElement<any>,
417
+ container: DOMContainerElement,
418
+ callback: ?Function,
419
+ ) {
420
validateContainer(container);
421
422
if (ReactFeatureFlags.disableNewFiberFeatures) {
@@ -390,29 +428,26 @@ var ReactDOM = {
428
invariant(
429
false,
430
'ReactDOM.render(): Invalid component element. Instead of ' +
393
- 'passing a string like \'div\', pass ' +
394
- 'React.createElement(\'div\') or <div />.'
431
+ "passing a string like 'div', pass " +
432
+ "React.createElement('div') or <div />.",
433
);
434
} else if (typeof element === 'function') {
435
invariant(
436
false,
437
'ReactDOM.render(): Invalid component element. Instead of ' +
400
- 'passing a class like Foo, pass React.createElement(Foo) ' +
401
- 'or <Foo />.'
438
+ 'passing a class like Foo, pass React.createElement(Foo) ' +
439
+ 'or <Foo />.',
440
);
441
} else if (element != null && typeof element.props !== 'undefined') {
442
// Check if it quacks like an element
443
invariant(
444
false,
445
'ReactDOM.render(): Invalid component element. This may be ' +
408
- 'caused by unintentionally loading two independent copies ' +
409
- 'of React.'
446
+ 'caused by unintentionally loading two independent copies ' +
447
+ 'of React.',
448
);
449
} else {
412
- invariant(
413
- false,
414
- 'ReactDOM.render(): Invalid component element.'
415
- );
450
+ invariant(false, 'ReactDOM.render(): Invalid component element.');
451
}
452
}
453
}
@@ -420,24 +455,24 @@ var ReactDOM = {
455
if (__DEV__) {
456
const isRootRenderedBySomeReact = !!container._reactRootContainer;
457
const rootEl = getReactRootElementInContainer(container);
423
- const hasNonRootReactChild = !!(rootEl && ReactDOMComponentTree.getInstanceFromNode(rootEl));
458
+ const hasNonRootReactChild = !!(rootEl &&
459
+ ReactDOMComponentTree.getInstanceFromNode(rootEl));
460
461
warning(
426
- !hasNonRootReactChild ||
427
- isRootRenderedBySomeReact,
462
+ !hasNonRootReactChild || isRootRenderedBySomeReact,
463
'render(...): Replacing React-rendered children with a new root ' +
429
- 'component. If you intended to update the children of this node, ' +
430
- 'you should instead have the existing children update their state ' +
431
- 'and render the new components instead of calling ReactDOM.render.'
464
+ 'component. If you intended to update the children of this node, ' +
465
+ 'you should instead have the existing children update their state ' +
466
+ 'and render the new components instead of calling ReactDOM.render.',
467
);
468
469
warning(
470
!container.tagName || container.tagName.toUpperCase() !== 'BODY',
471
'render(): Rendering components directly into document.body is ' +
437
- 'discouraged, since its children are often manipulated by third-party ' +
438
- 'scripts and browser extensions. This may lead to subtle ' +
439
- 'reconciliation issues. Try rendering into a container element created ' +
440
- 'for your app.'
472
+ 'discouraged, since its children are often manipulated by third-party ' +
473
+ 'scripts and browser extensions. This may lead to subtle ' +
474
+ 'reconciliation issues. Try rendering into a container element created ' +
475
+ 'for your app.',
476
);
477
}
478
@@ -445,33 +480,39 @@ var ReactDOM = {
480
},
481
482
unstable_renderSubtreeIntoContainer(
448
- parentComponent : ReactComponent<any, any, any>,
449
- element : ReactElement<any>,
450
- containerNode : DOMContainerElement | Document,
451
- callback: ?Function
483
+ parentComponent: ReactComponent<any, any, any>,
484
+ element: ReactElement<any>,
485
+ containerNode: DOMContainerElement | Document,
486
+ callback: ?Function,
487
) {
488
invariant(
489
parentComponent != null && ReactInstanceMap.has(parentComponent),
455
- 'parentComponent must be a valid React Component'
490
+ 'parentComponent must be a valid React Component',
491
+ );
492
+ return renderSubtreeIntoContainer(
493
+ parentComponent,
494
+ element,
495
+ containerNode,
496
+ callback,
497
);
457
- return renderSubtreeIntoContainer(parentComponent, element, containerNode, callback);
498
},
499
460
- unmountComponentAtNode(container : DOMContainerElement) {
500
+ unmountComponentAtNode(container: DOMContainerElement) {
501
invariant(
502
isValidContainer(container),
463
- 'unmountComponentAtNode(...): Target container is not a DOM element.'
503
+ 'unmountComponentAtNode(...): Target container is not a DOM element.',
504
);
505
warnAboutUnstableUse();
506
507
if (container._reactRootContainer) {
508
if (__DEV__) {
509
const rootEl = getReactRootElementInContainer(container);
470
- const renderedByDifferentReact = rootEl && !ReactDOMComponentTree.getInstanceFromNode(rootEl);
510
+ const renderedByDifferentReact = rootEl &&
511
+ !ReactDOMComponentTree.getInstanceFromNode(rootEl);
512
warning(
513
!renderedByDifferentReact,
473
- 'unmountComponentAtNode(): The node you\'re attempting to unmount ' +
474
- 'was rendered by another copy of React.'
514
+ "unmountComponentAtNode(): The node you're attempting to unmount " +
515
+ 'was rendered by another copy of React.',
516
);
517
}
518
@@ -486,7 +527,11 @@ var ReactDOM = {
527
528
findDOMNode: findDOMNode,
529
489
- unstable_createPortal(children: ReactNodeList, container : DOMContainerElement, key : ?string = null) {
530
+ unstable_createPortal(
531
+ children: ReactNodeList,
532
+ container: DOMContainerElement,
533
+ key: ?string = null,
534
+ ) {
535
// TODO: pass ReactDOM portal implementation as third argument
536
return ReactPortal.createPortal(children, container, null, key);
537
},
@@ -494,7 +539,6 @@ var ReactDOM = {
539
unstable_batchedUpdates: ReactGenericBatching.batchedUpdates,
540
541
unstable_deferredUpdates: DOMRenderer.deferredUpdates,
497
-
542
};
543
544
if (typeof injectInternals === 'function') {
src/renderers/dom/fiber/ReactDOMFiberComponent.js
+173
-191
@@ -24,7 +24,7 @@ var ReactDOMFiberInput = require('ReactDOMFiberInput');
24
var ReactDOMFiberOption = require('ReactDOMFiberOption');
25
var ReactDOMFiberSelect = require('ReactDOMFiberSelect');
26
var ReactDOMFiberTextarea = require('ReactDOMFiberTextarea');
27
-var { getCurrentFiberOwnerName } = require('ReactDebugCurrentFiber');
27
+var {getCurrentFiberOwnerName} = require('ReactDebugCurrentFiber');
28
29
var emptyFunction = require('fbjs/lib/emptyFunction');
30
var invariant = require('fbjs/lib/invariant');
@@ -38,9 +38,13 @@ if (__DEV__) {
38
var ReactDOMInvalidARIAHook = require('ReactDOMInvalidARIAHook');
39
var ReactDOMNullInputValuePropHook = require('ReactDOMNullInputValuePropHook');
40
var ReactDOMUnknownPropertyHook = require('ReactDOMUnknownPropertyHook');
41
- var { validateProperties: validateARIAProperties } = ReactDOMInvalidARIAHook;
42
- var { validateProperties: validateInputPropertes } = ReactDOMNullInputValuePropHook;
43
- var { validateProperties: validateUnknownPropertes } = ReactDOMUnknownPropertyHook;
41
+ var {validateProperties: validateARIAProperties} = ReactDOMInvalidARIAHook;
42
+ var {
43
+ validateProperties: validateInputPropertes,
44
+ } = ReactDOMNullInputValuePropHook;
45
+ var {
46
+ validateProperties: validateUnknownPropertes,
47
+ } = ReactDOMUnknownPropertyHook;
48
}
49
50
var didWarnShadyDOM = false;
@@ -63,7 +67,6 @@ var {
67
// Node type for document fragments (Node.DOCUMENT_FRAGMENT_NODE).
68
var DOC_FRAGMENT_TYPE = 11;
69
66
-
70
function getDeclarationErrorAddendum() {
71
var ownerName = getCurrentFiberOwnerName();
72
if (ownerName) {
@@ -73,7 +76,7 @@ function getDeclarationErrorAddendum() {
76
return '';
77
}
78
76
-function assertValidProps(tag : string, props : ?Object) {
79
+function assertValidProps(tag: string, props: ?Object) {
80
if (!props) {
81
return;
82
}
@@ -82,53 +85,52 @@ function assertValidProps(tag : string, props : ?Object) {
85
invariant(
86
props.children == null && props.dangerouslySetInnerHTML == null,
87
'%s is a void element tag and must neither have `children` nor ' +
85
- 'use `dangerouslySetInnerHTML`.%s',
88
+ 'use `dangerouslySetInnerHTML`.%s',
89
tag,
87
- getDeclarationErrorAddendum()
90
+ getDeclarationErrorAddendum(),
91
);
92
}
93
if (props.dangerouslySetInnerHTML != null) {
94
invariant(
95
props.children == null,
93
- 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'
96
+ 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.',
97
);
98
invariant(
99
typeof props.dangerouslySetInnerHTML === 'object' &&
97
- HTML in props.dangerouslySetInnerHTML,
100
+ HTML in props.dangerouslySetInnerHTML,
101
'`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' +
99
- 'Please visit https://fb.me/react-invariant-dangerously-set-inner-html ' +
100
- 'for more information.'
102
+ 'Please visit https://fb.me/react-invariant-dangerously-set-inner-html ' +
103
+ 'for more information.',
104
);
105
}
106
if (__DEV__) {
107
warning(
108
props.innerHTML == null,
109
'Directly setting property `innerHTML` is not permitted. ' +
107
- 'For more information, lookup documentation on `dangerouslySetInnerHTML`.'
110
+ 'For more information, lookup documentation on `dangerouslySetInnerHTML`.',
111
);
112
warning(
113
props.suppressContentEditableWarning ||
111
- !props.contentEditable ||
112
- props.children == null,
114
+ !props.contentEditable ||
115
+ props.children == null,
116
'A component is `contentEditable` and contains `children` managed by ' +
114
- 'React. It is now your responsibility to guarantee that none of ' +
115
- 'those nodes are unexpectedly modified or duplicated. This is ' +
116
- 'probably not intentional.'
117
+ 'React. It is now your responsibility to guarantee that none of ' +
118
+ 'those nodes are unexpectedly modified or duplicated. This is ' +
119
+ 'probably not intentional.',
120
);
121
warning(
119
- props.onFocusIn == null &&
120
- props.onFocusOut == null,
122
+ props.onFocusIn == null && props.onFocusOut == null,
123
'React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' +
122
- 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' +
123
- 'are not needed/supported by React.'
124
+ 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' +
125
+ 'are not needed/supported by React.',
126
);
127
}
128
invariant(
129
props.style == null || typeof props.style === 'object',
130
'The `style` prop expects a mapping from style properties to values, ' +
129
- 'not a string. For example, style={{marginRight: spacing + \'em\'}} when ' +
130
- 'using JSX.%s',
131
- getDeclarationErrorAddendum()
131
+ "not a string. For example, style={{marginRight: spacing + 'em'}} when " +
132
+ 'using JSX.%s',
133
+ getDeclarationErrorAddendum(),
134
);
135
}
136
@@ -146,11 +148,13 @@ function ensureListeningTo(rootContainerElement, registrationName) {
148
// bubble.
149
warning(
150
registrationName !== 'onScroll' || isEventSupported('scroll', true),
149
- 'This browser doesn\'t support the `onScroll` event'
151
+ "This browser doesn't support the `onScroll` event",
152
);
153
}
154
var isDocumentFragment = rootContainerElement.nodeType === DOC_FRAGMENT_TYPE;
153
- var doc = isDocumentFragment ? rootContainerElement : rootContainerElement.ownerDocument;
155
+ var doc = isDocumentFragment
156
+ ? rootContainerElement
157
+ : rootContainerElement.ownerDocument;
158
listenTo(registrationName, doc);
159
}
160
@@ -182,7 +186,7 @@ var mediaEvents = {
186
topWaiting: 'waiting',
187
};
188
185
-function trapClickOnNonInteractiveElement(node : HTMLElement) {
189
+function trapClickOnNonInteractiveElement(node: HTMLElement) {
190
// Mobile Safari does not fire properly bubble click events on
191
// non-interactive elements, which means delegated click listeners do not
192
// fire. The workaround for this bug involves attaching an empty click
@@ -195,7 +199,7 @@ function trapClickOnNonInteractiveElement(node : HTMLElement) {
199
node.onclick = emptyFunction;
200
}
201
198
-function trapBubbledEventsLocal(node : Element, tag : string) {
202
+function trapBubbledEventsLocal(node: Element, tag: string) {
203
// If a component renders to null or if another component fatals and causes
204
// the state of the tree to be corrupted, `node` here can be null.
205
@@ -205,11 +209,7 @@ function trapBubbledEventsLocal(node : Element, tag : string) {
209
switch (tag) {
210
case 'iframe':
211
case 'object':
208
- ReactBrowserEventEmitter.trapBubbledEvent(
209
- 'topLoad',
210
- 'load',
211
- node
212
- );
212
+ ReactBrowserEventEmitter.trapBubbledEvent('topLoad', 'load', node);
213
break;
214
case 'video':
215
case 'audio':
@@ -219,58 +219,30 @@ function trapBubbledEventsLocal(node : Element, tag : string) {
219
ReactBrowserEventEmitter.trapBubbledEvent(
220
event,
221
mediaEvents[event],
222
- node
222
+ node,
223
);
224
}
225
}
226
break;
227
case 'source':
228
- ReactBrowserEventEmitter.trapBubbledEvent(
229
- 'topError',
230
- 'error',
231
- node
232
- );
228
+ ReactBrowserEventEmitter.trapBubbledEvent('topError', 'error', node);
229
break;
230
case 'img':
231
case 'image':
236
- ReactBrowserEventEmitter.trapBubbledEvent(
237
- 'topError',
238
- 'error',
239
- node
240
- );
241
- ReactBrowserEventEmitter.trapBubbledEvent(
242
- 'topLoad',
243
- 'load',
244
- node
245
- );
232
+ ReactBrowserEventEmitter.trapBubbledEvent('topError', 'error', node);
233
+ ReactBrowserEventEmitter.trapBubbledEvent('topLoad', 'load', node);
234
break;
235
case 'form':
248
- ReactBrowserEventEmitter.trapBubbledEvent(
249
- 'topReset',
250
- 'reset',
251
- node
252
- );
253
- ReactBrowserEventEmitter.trapBubbledEvent(
254
- 'topSubmit',
255
- 'submit',
256
- node
257
- );
236
+ ReactBrowserEventEmitter.trapBubbledEvent('topReset', 'reset', node);
237
+ ReactBrowserEventEmitter.trapBubbledEvent('topSubmit', 'submit', node);
238
break;
239
case 'input':
240
case 'select':
241
case 'textarea':
262
- ReactBrowserEventEmitter.trapBubbledEvent(
263
- 'topInvalid',
264
- 'invalid',
265
- node
266
- );
242
+ ReactBrowserEventEmitter.trapBubbledEvent('topInvalid', 'invalid', node);
243
break;
244
case 'details':
269
- ReactBrowserEventEmitter.trapBubbledEvent(
270
- 'topToggle',
271
- 'toggle',
272
- node
273
- );
245
+ ReactBrowserEventEmitter.trapBubbledEvent('topToggle', 'toggle', node);
246
break;
247
}
248
}
@@ -279,21 +251,21 @@ function trapBubbledEventsLocal(node : Element, tag : string) {
251
// those special-case tags.
252
253
var omittedCloseTags = {
282
- 'area': true,
283
- 'base': true,
284
- 'br': true,
285
- 'col': true,
286
- 'embed': true,
287
- 'hr': true,
288
- 'img': true,
289
- 'input': true,
290
- 'keygen': true,
291
- 'link': true,
292
- 'meta': true,
293
- 'param': true,
294
- 'source': true,
295
- 'track': true,
296
- 'wbr': true,
254
+ area: true,
255
+ base: true,
256
+ br: true,
257
+ col: true,
258
+ embed: true,
259
+ hr: true,
260
+ img: true,
261
+ input: true,
262
+ keygen: true,
263
+ link: true,
264
+ meta: true,
265
+ param: true,
266
+ source: true,
267
+ track: true,
268
+ wbr: true,
269
// NOTE: menuitem's close tag should be omitted, but that causes problems.
270
};
271
@@ -301,7 +273,7 @@ var omittedCloseTags = {
273
// `omittedCloseTags` except that `menuitem` should still have its closing tag.
274
275
var voidElementTags = {
304
- 'menuitem': true,
276
+ menuitem: true,
277
...omittedCloseTags,
278
};
279
@@ -310,11 +282,11 @@ function isCustomComponent(tagName, props) {
282
}
283
284
function setInitialDOMProperties(
313
- domElement : Element,
314
- rootContainerElement : Element,
315
- nextProps : Object,
316
- isCustomComponentTag : boolean,
317
-) : void {
285
+ domElement: Element,
286
+ rootContainerElement: Element,
287
+ nextProps: Object,
288
+ isCustomComponentTag: boolean,
289
+): void {
290
for (var propKey in nextProps) {
291
var nextProp = nextProps[propKey];
292
if (!nextProps.hasOwnProperty(propKey)) {
@@ -330,10 +302,7 @@ function setInitialDOMProperties(
302
}
303
// Relies on `updateStylesByID` not mutating `styleUpdates`.
304
// TODO: call ReactInstrumentation.debugTool.onHostOperation in DEV.
333
- CSSPropertyOperations.setValueForStyles(
334
- domElement,
335
- nextProp,
336
- );
305
+ CSSPropertyOperations.setValueForStyles(domElement, nextProp);
306
} else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
307
var nextHtml = nextProp ? nextProp[HTML] : undefined;
308
if (nextHtml != null) {
@@ -352,40 +321,37 @@ function setInitialDOMProperties(
321
ensureListeningTo(rootContainerElement, propKey);
322
}
323
} else if (isCustomComponentTag) {
355
- DOMPropertyOperations.setValueForAttribute(
356
- domElement,
357
- propKey,
358
- nextProp
359
- );
324
+ DOMPropertyOperations.setValueForAttribute(domElement, propKey, nextProp);
325
} else if (
361
- DOMProperty.properties[propKey] ||
362
- DOMProperty.isCustomAttribute(propKey)) {
326
+ DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)
327
+ ) {
328
// If we're updating to null or undefined, we should remove the property
329
// from the DOM node instead of inadvertently setting to a string. This
330
// brings us in line with the same behavior we have on initial render.
331
if (nextProp != null) {
367
- DOMPropertyOperations.setValueForProperty(domElement, propKey, nextProp);
332
+ DOMPropertyOperations.setValueForProperty(
333
+ domElement,
334
+ propKey,
335
+ nextProp,
336
+ );
337
}
338
}
339
}
340
}
341
342
function updateDOMProperties(
374
- domElement : Element,
375
- updatePayload : Array<any>,
376
- wasCustomComponentTag : boolean,
377
- isCustomComponentTag : boolean,
378
-) : void {
343
+ domElement: Element,
344
+ updatePayload: Array<any>,
345
+ wasCustomComponentTag: boolean,
346
+ isCustomComponentTag: boolean,
347
+): void {
348
// TODO: Handle wasCustomComponentTag
349
for (var i = 0; i < updatePayload.length; i += 2) {
350
var propKey = updatePayload[i];
351
var propValue = updatePayload[i + 1];
352
if (propKey === STYLE) {
353
// TODO: call ReactInstrumentation.debugTool.onHostOperation in DEV.
385
- CSSPropertyOperations.setValueForStyles(
386
- domElement,
387
- propValue,
388
- );
354
+ CSSPropertyOperations.setValueForStyles(domElement, propValue);
355
} else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
356
setInnerHTML(domElement, propValue);
357
} else if (propKey === CHILDREN) {
@@ -395,22 +361,23 @@ function updateDOMProperties(
361
DOMPropertyOperations.setValueForAttribute(
362
domElement,
363
propKey,
398
- propValue
364
+ propValue,
365
);
366
} else {
401
- DOMPropertyOperations.deleteValueForAttribute(
402
- domElement,
403
- propKey
404
- );
367
+ DOMPropertyOperations.deleteValueForAttribute(domElement, propKey);
368
}
369
} else if (
407
- DOMProperty.properties[propKey] ||
408
- DOMProperty.isCustomAttribute(propKey)) {
370
+ DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)
371
+ ) {
372
// If we're updating to null or undefined, we should remove the property
373
// from the DOM node instead of inadvertently setting to a string. This
374
// brings us in line with the same behavior we have on initial render.
375
if (propValue != null) {
413
- DOMPropertyOperations.setValueForProperty(domElement, propKey, propValue);
376
+ DOMPropertyOperations.setValueForProperty(
377
+ domElement,
378
+ propKey,
379
+ propValue,
380
+ );
381
} else {
382
DOMPropertyOperations.deleteValueForProperty(domElement, propKey);
383
}
@@ -419,7 +386,7 @@ function updateDOMProperties(
386
}
387
388
// Assumes there is no parent namespace.
422
-function getIntrinsicNamespace(type : string) : string {
389
+function getIntrinsicNamespace(type: string): string {
390
switch (type) {
391
case 'svg':
392
return SVG_NAMESPACE;
@@ -431,7 +398,7 @@ function getIntrinsicNamespace(type : string) : string {
398
}
399
400
var ReactDOMFiberComponent = {
434
- getChildNamespace(parentNamespace : string | null, type : string) : string {
401
+ getChildNamespace(parentNamespace: string | null, type: string): string {
402
if (parentNamespace == null || parentNamespace === HTML_NAMESPACE) {
403
// No (or default) parent namespace: potential entry point.
404
return getIntrinsicNamespace(type);
@@ -445,15 +412,15 @@ var ReactDOMFiberComponent = {
412
},
413
414
createElement(
448
- type : string,
449
- props : Object,
450
- rootContainerElement : Element,
451
- parentNamespace : string
452
- ) : Element {
415
+ type: string,
416
+ props: Object,
417
+ rootContainerElement: Element,
418
+ parentNamespace: string,
419
+ ): Element {
420
// We create tags in the namespace of their parent container, except HTML
421
// tags get no namespace.
422
var ownerDocument = rootContainerElement.ownerDocument;
456
- var domElement : Element;
423
+ var domElement: Element;
424
var namespaceURI = parentNamespace;
425
if (namespaceURI === HTML_NAMESPACE) {
426
namespaceURI = getIntrinsicNamespace(type);
@@ -461,11 +428,10 @@ var ReactDOMFiberComponent = {
428
if (namespaceURI === HTML_NAMESPACE) {
429
if (__DEV__) {
430
warning(
464
- type === type.toLowerCase() ||
465
- isCustomComponent(type, props),
431
+ type === type.toLowerCase() || isCustomComponent(type, props),
432
'<%s /> is using uppercase HTML. Always use lowercase HTML tags ' +
467
- 'in React.',
468
- type
433
+ 'in React.',
434
+ type,
435
);
436
}
437
@@ -473,9 +439,9 @@ var ReactDOMFiberComponent = {
439
// Create the script via .innerHTML so its "parser-inserted" flag is
440
// set to true and it does not execute
441
var div = ownerDocument.createElement('div');
476
- div.innerHTML = '<script><' + '/script>'; // eslint-disable-line
442
+ div.innerHTML = '<script><' + '/script>'; // eslint-disable-line
443
// This is guaranteed to yield a script element.
478
- var firstChild = ((div.firstChild : any) : HTMLScriptElement);
444
+ var firstChild = ((div.firstChild: any): HTMLScriptElement);
445
domElement = div.removeChild(firstChild);
446
} else if (props.is) {
447
domElement = ownerDocument.createElement(type, props.is);
@@ -486,22 +452,18 @@ var ReactDOMFiberComponent = {
452
domElement = ownerDocument.createElement(type);
453
}
454
} else {
489
- domElement = ownerDocument.createElementNS(
490
- namespaceURI,
491
- type
492
- );
455
+ domElement = ownerDocument.createElementNS(namespaceURI, type);
456
}
457
458
return domElement;
459
},
460
461
setInitialProperties(
499
- domElement : Element,
500
- tag : string,
501
- rawProps : Object,
502
- rootContainerElement : Element
503
- ) : void {
504
-
462
+ domElement: Element,
463
+ tag: string,
464
+ rawProps: Object,
465
+ rootContainerElement: Element,
466
+ ): void {
467
var isCustomComponentTag = isCustomComponent(tag, rawProps);
468
if (__DEV__) {
469
validatePropertiesInDevelopment(tag, rawProps);
@@ -509,14 +471,14 @@ var ReactDOMFiberComponent = {
471
warning(
472
false,
473
'%s is using shady DOM. Using shady DOM with React can ' +
512
- 'cause things to break subtly.',
513
- getCurrentFiberOwnerName() || 'A component'
474
+ 'cause things to break subtly.',
475
+ getCurrentFiberOwnerName() || 'A component',
476
);
477
didWarnShadyDOM = true;
478
}
479
}
480
519
- var props : Object;
481
+ var props: Object;
482
switch (tag) {
483
case 'audio':
484
case 'form':
@@ -569,20 +531,20 @@ var ReactDOMFiberComponent = {
531
domElement,
532
rootContainerElement,
533
props,
572
- isCustomComponentTag
534
+ isCustomComponentTag,
535
);
536
537
switch (tag) {
538
case 'input':
539
// TODO: Make sure we check if this is still unmounted or do any clean
540
// up necessary since we never stop tracking anymore.
579
- inputValueTracking.trackNode((domElement : any));
541
+ inputValueTracking.trackNode((domElement: any));
542
ReactDOMFiberInput.postMountWrapper(domElement, rawProps);
543
break;
544
case 'textarea':
545
// TODO: Make sure we check if this is still unmounted or do any clean
546
// up necessary since we never stop tracking anymore.
585
- inputValueTracking.trackNode((domElement : any));
547
+ inputValueTracking.trackNode((domElement: any));
548
ReactDOMFiberTextarea.postMountWrapper(domElement, rawProps);
549
break;
550
case 'option':
@@ -591,7 +553,7 @@ var ReactDOMFiberComponent = {
553
default:
554
if (typeof props.onClick === 'function') {
555
// TODO: This cast may not be sound for SVG, MathML or custom elements.
594
- trapClickOnNonInteractiveElement(((domElement : any) : HTMLElement));
556
+ trapClickOnNonInteractiveElement(((domElement: any): HTMLElement));
557
}
558
break;
559
}
@@ -599,20 +561,20 @@ var ReactDOMFiberComponent = {
561
562
// Calculate the diff between the two objects.
563
diffProperties(
602
- domElement : Element,
603
- tag : string,
604
- lastRawProps : Object,
605
- nextRawProps : Object,
606
- rootContainerElement : Element,
607
- ) : null | Array<mixed> {
564
+ domElement: Element,
565
+ tag: string,
566
+ lastRawProps: Object,
567
+ nextRawProps: Object,
568
+ rootContainerElement: Element,
569
+ ): null | Array<mixed> {
570
if (__DEV__) {
571
validatePropertiesInDevelopment(tag, nextRawProps);
572
}
573
612
- var updatePayload : null | Array<any> = null;
574
+ var updatePayload: null | Array<any> = null;
575
614
- var lastProps : Object;
615
- var nextProps : Object;
576
+ var lastProps: Object;
577
+ var nextProps: Object;
578
switch (tag) {
579
case 'input':
580
lastProps = ReactDOMFiberInput.getHostProps(domElement, lastRawProps);
@@ -630,17 +592,25 @@ var ReactDOMFiberComponent = {
592
updatePayload = [];
593
break;
594
case 'textarea':
633
- lastProps = ReactDOMFiberTextarea.getHostProps(domElement, lastRawProps);
634
- nextProps = ReactDOMFiberTextarea.getHostProps(domElement, nextRawProps);
595
+ lastProps = ReactDOMFiberTextarea.getHostProps(
596
+ domElement,
597
+ lastRawProps,
598
+ );
599
+ nextProps = ReactDOMFiberTextarea.getHostProps(
600
+ domElement,
601
+ nextRawProps,
602
+ );
603
updatePayload = [];
604
break;
605
default:
606
lastProps = lastRawProps;
607
nextProps = nextRawProps;
640
- if (typeof lastProps.onClick !== 'function' &&
641
- typeof nextProps.onClick === 'function') {
608
+ if (
609
+ typeof lastProps.onClick !== 'function' &&
610
+ typeof nextProps.onClick === 'function'
611
+ ) {
612
// TODO: This cast may not be sound for SVG, MathML or custom elements.
643
- trapClickOnNonInteractiveElement(((domElement : any) : HTMLElement));
613
+ trapClickOnNonInteractiveElement(((domElement: any): HTMLElement));
614
}
615
break;
616
}
@@ -651,9 +621,11 @@ var ReactDOMFiberComponent = {
621
var styleName;
622
var styleUpdates = null;
623
for (propKey in lastProps) {
654
- if (nextProps.hasOwnProperty(propKey) ||
655
- !lastProps.hasOwnProperty(propKey) ||
656
- lastProps[propKey] == null) {
624
+ if (
625
+ nextProps.hasOwnProperty(propKey) ||
626
+ !lastProps.hasOwnProperty(propKey) ||
627
+ lastProps[propKey] == null
628
+ ) {
629
continue;
630
}
631
if (propKey === STYLE) {
@@ -666,8 +638,9 @@ var ReactDOMFiberComponent = {
638
styleUpdates[styleName] = '';
639
}
640
}
669
- } else if (propKey === DANGEROUSLY_SET_INNER_HTML ||
670
- propKey === CHILDREN) {
641
+ } else if (
642
+ propKey === DANGEROUSLY_SET_INNER_HTML || propKey === CHILDREN
643
+ ) {
644
// Noop. This is handled by the clear text mechanism.
645
} else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING) {
646
// Noop
@@ -686,11 +659,12 @@ var ReactDOMFiberComponent = {
659
}
660
for (propKey in nextProps) {
661
var nextProp = nextProps[propKey];
689
- var lastProp =
690
- lastProps != null ? lastProps[propKey] : undefined;
691
- if (!nextProps.hasOwnProperty(propKey) ||
692
- nextProp === lastProp ||
693
- nextProp == null && lastProp == null) {
662
+ var lastProp = lastProps != null ? lastProps[propKey] : undefined;
663
+ if (
664
+ !nextProps.hasOwnProperty(propKey) ||
665
+ nextProp === lastProp ||
666
+ (nextProp == null && lastProp == null)
667
+ ) {
668
continue;
669
}
670
if (propKey === STYLE) {
@@ -704,8 +678,10 @@ var ReactDOMFiberComponent = {
678
if (lastProp) {
679
// Unset styles on `lastProp` but not on `nextProp`.
680
for (styleName in lastProp) {
707
- if (lastProp.hasOwnProperty(styleName) &&
708
- (!nextProp || !nextProp.hasOwnProperty(styleName))) {
681
+ if (
682
+ lastProp.hasOwnProperty(styleName) &&
683
+ (!nextProp || !nextProp.hasOwnProperty(styleName))
684
+ ) {
685
if (!styleUpdates) {
686
styleUpdates = {};
687
}
@@ -714,8 +690,10 @@ var ReactDOMFiberComponent = {
690
}
691
// Update styles that changed since `lastProp`.
692
for (styleName in nextProp) {
717
- if (nextProp.hasOwnProperty(styleName) &&
718
- lastProp[styleName] !== nextProp[styleName]) {
693
+ if (
694
+ nextProp.hasOwnProperty(styleName) &&
695
+ lastProp[styleName] !== nextProp[styleName]
696
+ ) {
697
if (!styleUpdates) {
698
styleUpdates = {};
699
}
@@ -744,9 +722,10 @@ var ReactDOMFiberComponent = {
722
// inserted already.
723
}
724
} else if (propKey === CHILDREN) {
747
- if (lastProp !== nextProp && (
748
- typeof nextProp === 'string' || typeof nextProp === 'number'
749
- )) {
725
+ if (
726
+ lastProp !== nextProp &&
727
+ (typeof nextProp === 'string' || typeof nextProp === 'number')
728
+ ) {
729
(updatePayload = updatePayload || []).push(propKey, '' + nextProp);
730
}
731
} else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING) {
@@ -776,12 +755,12 @@ var ReactDOMFiberComponent = {
755
756
// Apply the diff.
757
updateProperties(
779
- domElement : Element,
780
- updatePayload : Array<any>,
781
- tag : string,
782
- lastRawProps : Object,
783
- nextRawProps : Object
784
- ) : void {
758
+ domElement: Element,
759
+ updatePayload: Array<any>,
760
+ tag: string,
761
+ lastRawProps: Object,
762
+ nextRawProps: Object,
763
+ ): void {
764
var wasCustomComponentTag = isCustomComponent(tag, lastRawProps);
765
var isCustomComponentTag = isCustomComponent(tag, nextRawProps);
766
// Apply the diff.
@@ -789,7 +768,7 @@ var ReactDOMFiberComponent = {
768
domElement,
769
updatePayload,
770
wasCustomComponentTag,
792
- isCustomComponentTag
771
+ isCustomComponentTag,
772
);
773
774
// TODO: Ensure that an update gets scheduled if any of the special props
@@ -812,7 +791,11 @@ var ReactDOMFiberComponent = {
791
}
792
},
793
815
- restoreControlledState(domElement : Element, tag : string, props : Object) : void {
794
+ restoreControlledState(
795
+ domElement: Element,
796
+ tag: string,
797
+ props: Object,
798
+ ): void {
799
switch (tag) {
800
case 'input':
801
ReactDOMFiberInput.restoreControlledState(domElement, props);
@@ -825,7 +808,6 @@ var ReactDOMFiberComponent = {
808
return;
809
}
810
},
828
-
811
};
812
813
module.exports = ReactDOMFiberComponent;
src/renderers/dom/fiber/ReactDOMFrameScheduling.js
+24
-22
@@ -20,18 +20,18 @@
20
// layout, paint and other browser work is counted against the available time.
21
// The frame rate is dynamically adjusted.
22
23
-import type { Deadline } from 'ReactFiberReconciler';
23
+import type {Deadline} from 'ReactFiberReconciler';
24
25
var invariant = require('fbjs/lib/invariant');
26
27
// TODO: There's no way to cancel these, because Fiber doesn't atm.
28
-let rAF : (callback : (time : number) => void) => number;
29
-let rIC : (callback : (deadline : Deadline) => void) => number;
28
+let rAF: (callback: (time: number) => void) => number;
29
+let rIC: (callback: (deadline: Deadline) => void) => number;
30
if (typeof requestAnimationFrame !== 'function') {
31
invariant(
32
false,
33
'React depends on requestAnimationFrame. Make sure that you load a ' +
34
- 'polyfill in older browsers.'
34
+ 'polyfill in older browsers.',
35
);
36
} else if (typeof requestIdleCallback !== 'function') {
37
// Wrap requestAnimationFrame and polyfill requestIdleCallback.
@@ -50,22 +50,21 @@ if (typeof requestAnimationFrame !== 'function') {
50
var activeFrameTime = 33;
51
52
var frameDeadlineObject = {
53
- timeRemaining: (
54
- typeof performance === 'object' &&
55
- typeof performance.now === 'function' ? function() {
56
- // We assume that if we have a performance timer that the rAF callback
57
- // gets a performance timer value. Not sure if this is always true.
58
- return frameDeadline - performance.now();
59
- } : function() {
60
- // As a fallback we use Date.now.
61
- return frameDeadline - Date.now();
62
- }
63
- ),
53
+ timeRemaining: typeof performance === 'object' &&
54
+ typeof performance.now === 'function'
55
+ ? function() {
56
+ // We assume that if we have a performance timer that the rAF callback
57
+ // gets a performance timer value. Not sure if this is always true.
58
+ return frameDeadline - performance.now();
59
+ }
60
+ : function() {
61
+ // As a fallback we use Date.now.
62
+ return frameDeadline - Date.now();
63
+ },
64
};
65
66
// We use the postMessage trick to defer idle work until after the repaint.
67
- var messageKey =
68
- '__reactIdleCallback$' + Math.random().toString(36).slice(2);
67
+ var messageKey = '__reactIdleCallback$' + Math.random().toString(36).slice(2);
68
var idleTick = function(event) {
69
if (event.source !== window || event.data !== messageKey) {
70
return;
@@ -84,7 +83,9 @@ if (typeof requestAnimationFrame !== 'function') {
83
var animationTick = function(rafTime) {
84
isAnimationFrameScheduled = false;
85
var nextFrameTime = rafTime - frameDeadline + activeFrameTime;
87
- if (nextFrameTime < activeFrameTime && previousFrameTime < activeFrameTime) {
86
+ if (
87
+ nextFrameTime < activeFrameTime && previousFrameTime < activeFrameTime
88
+ ) {
89
if (nextFrameTime < 8) {
90
// Defensive coding. We don't support higher frame rates than 120hz.
91
// If we get lower than that, it is probably a bug.
@@ -97,8 +98,9 @@ if (typeof requestAnimationFrame !== 'function') {
98
// running on 120hz display or 90hz VR display.
99
// Take the max of the two in case one of them was an anomaly due to
100
// missed frame deadlines.
100
- activeFrameTime = nextFrameTime < previousFrameTime ?
101
- previousFrameTime : nextFrameTime;
101
+ activeFrameTime = nextFrameTime < previousFrameTime
102
+ ? previousFrameTime
103
+ : nextFrameTime;
104
} else {
105
previousFrameTime = nextFrameTime;
106
}
@@ -114,7 +116,7 @@ if (typeof requestAnimationFrame !== 'function') {
116
}
117
};
118
117
- rAF = function(callback : (time : number) => void) : number {
119
+ rAF = function(callback: (time: number) => void): number {
120
// This assumes that we only schedule one callback at a time because that's
121
// how Fiber uses it.
122
scheduledRAFCallback = callback;
@@ -126,7 +128,7 @@ if (typeof requestAnimationFrame !== 'function') {
128
return 0;
129
};
130
129
- rIC = function(callback : (deadline : Deadline) => void) : number {
131
+ rIC = function(callback: (deadline: Deadline) => void): number {
132
// This assumes that we only schedule one callback at a time because that's
133
// how Fiber uses it.
134
scheduledRICCallback = callback;
src/renderers/dom/fiber/__tests__/ReactDOMFiber-test.js
+149
-229
@@ -34,20 +34,14 @@ describe('ReactDOMFiber', () => {
34
it('should render strings as children', () => {
35
const Box = ({value}) => <div>{value}</div>;
36
37
- ReactDOM.render(
38
- <Box value="foo" />,
39
- container
40
- );
37
+ ReactDOM.render(<Box value="foo" />, container);
38
expect(container.textContent).toEqual('foo');
39
});
40
41
it('should render numbers as children', () => {
42
const Box = ({value}) => <div>{value}</div>;
43
47
- ReactDOM.render(
48
- <Box value={10} />,
49
- container
50
- );
44
+ ReactDOM.render(<Box value={10} />, container);
45
46
expect(container.textContent).toEqual('10');
47
});
@@ -55,20 +49,12 @@ describe('ReactDOMFiber', () => {
49
it('should be called a callback argument', () => {
50
// mounting phase
51
let called = false;
58
- ReactDOM.render(
59
- <div>Foo</div>,
60
- container,
61
- () => called = true
62
- );
52
+ ReactDOM.render(<div>Foo</div>, container, () => called = true);
53
expect(called).toEqual(true);
54
55
// updating phase
56
called = false;
67
- ReactDOM.render(
68
- <div>Foo</div>,
69
- container,
70
- () => called = true
71
- );
57
+ ReactDOM.render(<div>Foo</div>, container, () => called = true);
58
expect(called).toEqual(true);
59
});
60
@@ -82,21 +68,13 @@ describe('ReactDOMFiber', () => {
68
69
// mounting phase
70
let called = false;
85
- ReactDOM.render(
86
- element,
87
- container,
88
- () => called = true
89
- );
71
+ ReactDOM.render(element, container, () => called = true);
72
expect(called).toEqual(true);
73
74
// updating phase
75
called = false;
76
ReactDOM.unstable_batchedUpdates(() => {
95
- ReactDOM.render(
96
- element,
97
- container,
98
- () => called = true
99
- );
77
+ ReactDOM.render(element, container, () => called = true);
78
});
79
expect(called).toEqual(true);
80
});
@@ -105,20 +83,14 @@ describe('ReactDOMFiber', () => {
83
it('should render a component returning strings directly from render', () => {
84
const Text = ({value}) => value;
85
108
- ReactDOM.render(
109
- <Text value="foo" />,
110
- container
111
- );
86
+ ReactDOM.render(<Text value="foo" />, container);
87
expect(container.textContent).toEqual('foo');
88
});
89
90
it('should render a component returning numbers directly from render', () => {
91
const Text = ({value}) => value;
92
118
- ReactDOM.render(
119
- <Text value={10} />,
120
- container
121
- );
93
+ ReactDOM.render(<Text value={10} />, container);
94
95
expect(container.textContent).toEqual('10');
96
});
@@ -133,7 +105,7 @@ describe('ReactDOMFiber', () => {
105
let instance = null;
106
ReactDOM.render(
107
<Text value="foo" ref={ref => instance = ref} />,
136
- container
108
+ container,
109
);
110
111
const textNode = ReactDOM.findDOMNode(instance);
@@ -145,18 +117,12 @@ describe('ReactDOMFiber', () => {
117
it('finds the first child when a component returns a fragment', () => {
118
class Fragment extends React.Component {
119
render() {
148
- return [
149
- <div />,
150
- <span />,
151
- ];
120
+ return [<div />, <span />];
121
}
122
}
123
124
let instance = null;
156
- ReactDOM.render(
157
- <Fragment ref={ref => instance = ref} />,
158
- container
159
- );
125
+ ReactDOM.render(<Fragment ref={ref => instance = ref} />, container);
126
127
expect(container.childNodes.length).toBe(2);
128
@@ -174,18 +140,12 @@ describe('ReactDOMFiber', () => {
140
141
class Fragment extends React.Component {
142
render() {
177
- return [
178
- <Wrapper><div /></Wrapper>,
179
- <span />,
180
- ];
143
+ return [<Wrapper><div /></Wrapper>, <span />];
144
}
145
}
146
147
let instance = null;
185
- ReactDOM.render(
186
- <Fragment ref={ref => instance = ref} />,
187
- container
188
- );
148
+ ReactDOM.render(<Fragment ref={ref => instance = ref} />, container);
149
150
expect(container.childNodes.length).toBe(2);
151
@@ -203,19 +163,12 @@ describe('ReactDOMFiber', () => {
163
164
class Fragment extends React.Component {
165
render() {
206
- return [
207
- <NullComponent />,
208
- <div />,
209
- <span />,
210
- ];
166
+ return [<NullComponent />, <div />, <span />];
167
}
168
}
169
170
let instance = null;
215
- ReactDOM.render(
216
- <Fragment ref={ref => instance = ref} />,
217
- container
218
- );
171
+ ReactDOM.render(<Fragment ref={ref => instance = ref} />, container);
172
173
expect(container.childNodes.length).toBe(2);
174
@@ -234,7 +187,7 @@ describe('ReactDOMFiber', () => {
187
var usePortal = function(tree) {
188
return ReactDOM.unstable_createPortal(
189
tree,
237
- document.createElement('div')
190
+ document.createElement('div'),
191
);
192
};
193
@@ -264,12 +217,9 @@ describe('ReactDOMFiber', () => {
217
218
ReactDOM.render(
219
<div>
267
- {ReactDOM.unstable_createPortal(
268
- <div>portal</div>,
269
- portalContainer
270
- )}
220
+ {ReactDOM.unstable_createPortal(<div>portal</div>, portalContainer)}
221
</div>,
272
- container
222
+ container,
223
);
224
expect(portalContainer.innerHTML).toBe('<div>portal</div>');
225
expect(container.innerHTML).toBe('<div></div>');
@@ -315,7 +265,7 @@ describe('ReactDOMFiber', () => {
265
<Child name={`normal[0]:${step}`} />,
266
ReactDOM.unstable_createPortal(
267
<Child name={`portal1[0]:${step}`} />,
318
- portalContainer1
268
+ portalContainer1,
269
),
270
<Child name={`normal[1]:${step}`} />,
271
ReactDOM.unstable_createPortal(
@@ -323,7 +273,7 @@ describe('ReactDOMFiber', () => {
273
<Child name={`portal2[0]:${step}`} />,
274
<Child name={`portal2[1]:${step}`} />,
275
],
326
- portalContainer2
276
+ portalContainer2,
277
),
278
];
279
}
@@ -331,8 +281,12 @@ describe('ReactDOMFiber', () => {
281
282
ReactDOM.render(<Parent step="a" />, container);
283
expect(portalContainer1.innerHTML).toBe('<div>portal1[0]:a</div>');
334
- expect(portalContainer2.innerHTML).toBe('<div>portal2[0]:a</div><div>portal2[1]:a</div>');
335
- expect(container.innerHTML).toBe('<div>normal[0]:a</div><div>normal[1]:a</div>');
284
+ expect(portalContainer2.innerHTML).toBe(
285
+ '<div>portal2[0]:a</div><div>portal2[1]:a</div>',
286
+ );
287
+ expect(container.innerHTML).toBe(
288
+ '<div>normal[0]:a</div><div>normal[1]:a</div>',
289
+ );
290
expect(ops).toEqual([
291
'normal[0]:a componentDidMount',
292
'portal1[0]:a componentDidMount',
@@ -345,8 +299,12 @@ describe('ReactDOMFiber', () => {
299
ops.length = 0;
300
ReactDOM.render(<Parent step="b" />, container);
301
expect(portalContainer1.innerHTML).toBe('<div>portal1[0]:b</div>');
348
- expect(portalContainer2.innerHTML).toBe('<div>portal2[0]:b</div><div>portal2[1]:b</div>');
349
- expect(container.innerHTML).toBe('<div>normal[0]:b</div><div>normal[1]:b</div>');
302
+ expect(portalContainer2.innerHTML).toBe(
303
+ '<div>portal2[0]:b</div><div>portal2[1]:b</div>',
304
+ );
305
+ expect(container.innerHTML).toBe(
306
+ '<div>normal[0]:b</div><div>normal[1]:b</div>',
307
+ );
308
expect(ops).toEqual([
309
'normal[0]:b componentDidUpdate',
310
'portal1[0]:b componentDidUpdate',
@@ -376,26 +334,36 @@ describe('ReactDOMFiber', () => {
334
var portalContainer2 = document.createElement('div');
335
var portalContainer3 = document.createElement('div');
336
379
- ReactDOM.render([
380
- <div>normal[0]</div>,
381
- ReactDOM.unstable_createPortal([
382
- <div>portal1[0]</div>,
383
- ReactDOM.unstable_createPortal(
384
- <div>portal2[0]</div>,
385
- portalContainer2
386
- ),
337
+ ReactDOM.render(
338
+ [
339
+ <div>normal[0]</div>,
340
ReactDOM.unstable_createPortal(
388
- <div>portal3[0]</div>,
389
- portalContainer3
341
+ [
342
+ <div>portal1[0]</div>,
343
+ ReactDOM.unstable_createPortal(
344
+ <div>portal2[0]</div>,
345
+ portalContainer2,
346
+ ),
347
+ ReactDOM.unstable_createPortal(
348
+ <div>portal3[0]</div>,
349
+ portalContainer3,
350
+ ),
351
+ <div>portal1[1]</div>,
352
+ ],
353
+ portalContainer1,
354
),
391
- <div>portal1[1]</div>,
392
- ], portalContainer1),
393
- <div>normal[1]</div>,
394
- ], container);
395
- expect(portalContainer1.innerHTML).toBe('<div>portal1[0]</div><div>portal1[1]</div>');
355
+ <div>normal[1]</div>,
356
+ ],
357
+ container,
358
+ );
359
+ expect(portalContainer1.innerHTML).toBe(
360
+ '<div>portal1[0]</div><div>portal1[1]</div>',
361
+ );
362
expect(portalContainer2.innerHTML).toBe('<div>portal2[0]</div>');
363
expect(portalContainer3.innerHTML).toBe('<div>portal3[0]</div>');
398
- expect(container.innerHTML).toBe('<div>normal[0]</div><div>normal[1]</div>');
364
+ expect(container.innerHTML).toBe(
365
+ '<div>normal[0]</div><div>normal[1]</div>',
366
+ );
367
368
ReactDOM.unmountComponentAtNode(container);
369
expect(portalContainer1.innerHTML).toBe('');
@@ -409,72 +377,54 @@ describe('ReactDOMFiber', () => {
377
378
ReactDOM.render(
379
<div>
412
- {ReactDOM.unstable_createPortal(
413
- <div>portal:1</div>,
414
- portalContainer
415
- )}
380
+ {ReactDOM.unstable_createPortal(<div>portal:1</div>, portalContainer)}
381
</div>,
417
- container
382
+ container,
383
);
384
expect(portalContainer.innerHTML).toBe('<div>portal:1</div>');
385
expect(container.innerHTML).toBe('<div></div>');
386
387
ReactDOM.render(
388
<div>
424
- {ReactDOM.unstable_createPortal(
425
- <div>portal:2</div>,
426
- portalContainer
427
- )}
389
+ {ReactDOM.unstable_createPortal(<div>portal:2</div>, portalContainer)}
390
</div>,
429
- container
391
+ container,
392
);
393
expect(portalContainer.innerHTML).toBe('<div>portal:2</div>');
394
expect(container.innerHTML).toBe('<div></div>');
395
396
ReactDOM.render(
397
<div>
436
- {ReactDOM.unstable_createPortal(
437
- <p>portal:3</p>,
438
- portalContainer
439
- )}
398
+ {ReactDOM.unstable_createPortal(<p>portal:3</p>, portalContainer)}
399
</div>,
441
- container
400
+ container,
401
);
402
expect(portalContainer.innerHTML).toBe('<p>portal:3</p>');
403
expect(container.innerHTML).toBe('<div></div>');
404
405
ReactDOM.render(
406
<div>
448
- {ReactDOM.unstable_createPortal(
449
- ['Hi', 'Bye'],
450
- portalContainer
451
- )}
407
+ {ReactDOM.unstable_createPortal(['Hi', 'Bye'], portalContainer)}
408
</div>,
453
- container
409
+ container,
410
);
411
expect(portalContainer.innerHTML).toBe('HiBye');
412
expect(container.innerHTML).toBe('<div></div>');
413
414
ReactDOM.render(
415
<div>
460
- {ReactDOM.unstable_createPortal(
461
- ['Bye', 'Hi'],
462
- portalContainer
463
- )}
416
+ {ReactDOM.unstable_createPortal(['Bye', 'Hi'], portalContainer)}
417
</div>,
465
- container
418
+ container,
419
);
420
expect(portalContainer.innerHTML).toBe('ByeHi');
421
expect(container.innerHTML).toBe('<div></div>');
422
423
ReactDOM.render(
424
<div>
472
- {ReactDOM.unstable_createPortal(
473
- null,
474
- portalContainer
475
- )}
425
+ {ReactDOM.unstable_createPortal(null, portalContainer)}
426
</div>,
477
- container
427
+ container,
428
);
429
expect(portalContainer.innerHTML).toBe('');
430
expect(container.innerHTML).toBe('<div></div>');
@@ -484,20 +434,16 @@ describe('ReactDOMFiber', () => {
434
assertNamespacesMatch(
435
<svg {...expectSVG}>
436
<image {...expectSVG} />
487
- {usePortal(
488
- <div {...expectHTML} />
489
- )}
437
+ {usePortal(<div {...expectHTML} />)}
438
<image {...expectSVG} />
491
- </svg>
439
+ </svg>,
440
);
441
assertNamespacesMatch(
442
<math {...expectMath}>
443
<mi {...expectMath} />
496
- {usePortal(
497
- <div {...expectHTML} />
498
- )}
444
+ {usePortal(<div {...expectHTML} />)}
445
<mi {...expectMath} />
500
- </math>
446
+ </math>,
447
);
448
assertNamespacesMatch(
449
<div {...expectHTML}>
@@ -505,10 +451,10 @@ describe('ReactDOMFiber', () => {
451
{usePortal(
452
<svg {...expectSVG}>
453
<image {...expectSVG} />
508
- </svg>
454
+ </svg>,
455
)}
456
<p {...expectHTML} />
511
- </div>
457
+ </div>,
458
);
459
});
460
@@ -516,15 +462,11 @@ describe('ReactDOMFiber', () => {
462
assertNamespacesMatch(
463
<svg {...expectSVG}>
464
<image {...expectSVG} />
519
- {usePortal(
520
- <div {...expectHTML} />
521
- )}
465
+ {usePortal(<div {...expectHTML} />)}
466
<image {...expectSVG} />
523
- {usePortal(
524
- <div {...expectHTML} />
525
- )}
467
+ {usePortal(<div {...expectHTML} />)}
468
<image {...expectSVG} />
527
- </svg>
469
+ </svg>,
470
);
471
assertNamespacesMatch(
472
<div {...expectHTML}>
@@ -533,11 +475,11 @@ describe('ReactDOMFiber', () => {
475
{usePortal(
476
<svg {...expectSVG}>
477
<image {...expectSVG} />
536
- </svg>
478
+ </svg>,
479
)}
480
</math>
481
<p {...expectHTML} />
540
- </div>
482
+ </div>,
483
);
484
assertNamespacesMatch(
485
<math {...expectMath}>
@@ -553,34 +495,30 @@ describe('ReactDOMFiber', () => {
495
<p {...expectHTML} />
496
</foreignObject>
497
<image {...expectSVG} />
556
- </svg>
498
+ </svg>,
499
)}
500
<mi {...expectMath} />
559
- </math>
501
+ </math>,
502
);
503
assertNamespacesMatch(
504
<div {...expectHTML}>
505
{usePortal(
506
<svg {...expectSVG}>
565
- {usePortal(
566
- <div {...expectHTML} />
567
- )}
507
+ {usePortal(<div {...expectHTML} />)}
508
<image {...expectSVG} />
569
- </svg>
509
+ </svg>,
510
)}
511
<p {...expectHTML} />
572
- </div>
512
+ </div>,
513
);
514
assertNamespacesMatch(
515
<svg {...expectSVG}>
516
<svg {...expectSVG}>
577
- {usePortal(
578
- <div {...expectHTML} />
579
- )}
517
+ {usePortal(<div {...expectHTML} />)}
518
<image {...expectSVG} />
519
</svg>
520
<image {...expectSVG} />
583
- </svg>
521
+ </svg>,
522
);
523
});
524
@@ -590,7 +528,7 @@ describe('ReactDOMFiber', () => {
528
{usePortal(
529
<svg {...expectSVG}>
530
<image {...expectSVG} />
593
- </svg>
531
+ </svg>,
532
)}
533
<p {...expectHTML} />
534
<svg {...expectSVG}>
@@ -603,7 +541,7 @@ describe('ReactDOMFiber', () => {
541
<image {...expectSVG} />
542
</svg>
543
<p {...expectHTML} />
606
- </div>
544
+ </div>,
545
);
546
assertNamespacesMatch(
547
<div {...expectHTML}>
@@ -617,7 +555,7 @@ describe('ReactDOMFiber', () => {
555
<image {...expectSVG} />
556
</svg>
557
<image {...expectSVG} />
620
- </svg>
558
+ </svg>,
559
)}
560
<image {...expectSVG} />
561
<foreignObject {...expectSVG}>
@@ -629,7 +567,7 @@ describe('ReactDOMFiber', () => {
567
<image {...expectSVG} />
568
</svg>
569
<p {...expectHTML} />
632
- </div>
570
+ </div>,
571
);
572
assertNamespacesMatch(
573
<div {...expectHTML}>
@@ -647,14 +585,14 @@ describe('ReactDOMFiber', () => {
585
{usePortal(<p {...expectHTML} />)}
586
</svg>
587
<image {...expectSVG} />
650
- </svg>
588
+ </svg>,
589
)}
590
<p {...expectHTML} />
591
</foreignObject>
592
<image {...expectSVG} />
593
</svg>
594
<p {...expectHTML} />
657
- </div>
595
+ </div>,
596
);
597
});
598
@@ -667,12 +605,10 @@ describe('ReactDOMFiber', () => {
605
assertNamespacesMatch(
606
<svg {...expectSVG}>
607
<BrokenRender />
670
- </svg>
608
+ </svg>,
609
);
610
}).toThrow('Hello');
673
- assertNamespacesMatch(
674
- <div {...expectHTML} />
675
- );
611
+ assertNamespacesMatch(<div {...expectHTML} />);
612
});
613
614
it('should unwind namespaces on caught errors', () => {
@@ -703,11 +639,9 @@ describe('ReactDOMFiber', () => {
639
</ErrorBoundary>
640
</foreignObject>
641
<image {...expectSVG} />
706
- </svg>
707
- );
708
- assertNamespacesMatch(
709
- <div {...expectHTML} />
642
+ </svg>,
643
);
644
+ assertNamespacesMatch(<div {...expectHTML} />);
645
});
646
647
it('should unwind namespaces on caught errors in a portal', () => {
@@ -736,13 +670,11 @@ describe('ReactDOMFiber', () => {
670
<math {...expectMath}>
671
<BrokenRender />)
672
</math>
739
- </div>
673
+ </div>,
674
)}
675
</ErrorBoundary>
742
- {usePortal(
743
- <div {...expectHTML} />
744
- )}
745
- </svg>
676
+ {usePortal(<div {...expectHTML} />)}
677
+ </svg>,
678
);
679
});
680
@@ -771,10 +703,7 @@ describe('ReactDOMFiber', () => {
703
}
704
705
render() {
774
- return ReactDOM.unstable_createPortal(
775
- <Component />,
776
- portalContainer
777
- );
706
+ return ReactDOM.unstable_createPortal(<Component />, portalContainer);
707
}
708
}
709
@@ -815,10 +744,7 @@ describe('ReactDOMFiber', () => {
744
}
745
746
render() {
818
- return ReactDOM.unstable_createPortal(
819
- <Component />,
820
- portalContainer
821
- );
747
+ return ReactDOM.unstable_createPortal(<Component />, portalContainer);
748
}
749
}
750
@@ -858,10 +784,7 @@ describe('ReactDOMFiber', () => {
784
}
785
786
render() {
861
- return ReactDOM.unstable_createPortal(
862
- <Component />,
863
- portalContainer
864
- );
787
+ return ReactDOM.unstable_createPortal(<Component />, portalContainer);
788
}
789
}
790
@@ -876,11 +799,9 @@ describe('ReactDOMFiber', () => {
799
it('findDOMNode should find dom element after expanding a fragment', () => {
800
class MyNode extends React.Component {
801
render() {
879
- return (
880
- !this.props.flag ?
881
- [<div key="a" />] :
882
- [<span key="b" />, <div key="a" />]
883
- );
802
+ return !this.props.flag
803
+ ? [<div key="a" />]
804
+ : [<span key="b" />, <div key="a" />];
805
}
806
}
807
@@ -904,13 +825,15 @@ describe('ReactDOMFiber', () => {
825
ReactDOM.render(
826
<div onClick={() => ops.push('parent clicked')}>
827
{ReactDOM.unstable_createPortal(
907
- <div onClick={() => ops.push('portal clicked')} ref={n => portal = n}>
828
+ <div
829
+ onClick={() => ops.push('portal clicked')}
830
+ ref={n => portal = n}>
831
portal
832
</div>,
910
- portalContainer
833
+ portalContainer,
834
)}
835
</div>,
913
- container
836
+ container,
837
);
838
839
expect(portal.tagName).toBe('DIV');
@@ -919,13 +842,10 @@ describe('ReactDOMFiber', () => {
842
ReactTestUtils.simulateNativeEventOnNode(
843
'topClick',
844
portal,
922
- fakeNativeEvent
845
+ fakeNativeEvent,
846
);
847
925
- expect(ops).toEqual([
926
- 'portal clicked',
927
- 'parent clicked',
928
- ]);
848
+ expect(ops).toEqual(['portal clicked', 'parent clicked']);
849
});
850
851
it('should not onMouseLeave when staying in the portal', () => {
@@ -938,24 +858,16 @@ describe('ReactDOMFiber', () => {
858
859
function simulateMouseMove(from, to) {
860
if (from) {
941
- ReactTestUtils.simulateNativeEventOnNode(
942
- 'topMouseOut',
943
- from,
944
- {
945
- target: from,
946
- relatedTarget: to,
947
- }
948
- );
861
+ ReactTestUtils.simulateNativeEventOnNode('topMouseOut', from, {
862
+ target: from,
863
+ relatedTarget: to,
864
+ });
865
}
866
if (to) {
951
- ReactTestUtils.simulateNativeEventOnNode(
952
- 'topMouseOver',
953
- to,
954
- {
955
- target: to,
956
- relatedTarget: from,
957
- }
958
- );
867
+ ReactTestUtils.simulateNativeEventOnNode('topMouseOver', to, {
868
+ target: to,
869
+ relatedTarget: from,
870
+ });
871
}
872
}
873
@@ -972,18 +884,16 @@ describe('ReactDOMFiber', () => {
884
ref={n => secondTarget = n}>
885
portal
886
</div>,
975
- portalContainer
887
+ portalContainer,
888
)}
889
</div>
890
<div ref={n => thirdTarget = n} />
891
</div>,
980
- container
892
+ container,
893
);
894
895
simulateMouseMove(null, firstTarget);
984
- expect(ops).toEqual([
985
- 'enter parent',
986
- ]);
896
+ expect(ops).toEqual(['enter parent']);
897
898
ops = [];
899
@@ -1008,18 +918,16 @@ describe('ReactDOMFiber', () => {
918
const handlerB = () => ops.push('B');
919
920
class Example extends React.Component {
1011
- state = { flip: false, count: 0 };
921
+ state = {flip: false, count: 0};
922
flip() {
1013
- this.setState({ flip: true, count: this.state.count + 1 });
923
+ this.setState({flip: true, count: this.state.count + 1});
924
}
925
tick() {
1016
- this.setState({ count: this.state.count + 1 });
926
+ this.setState({count: this.state.count + 1});
927
}
928
render() {
929
const useB = !this.props.forceA && this.state.flip;
1020
- return (
1021
- <div onClick={useB ? handlerB : handlerA} />
1022
- );
930
+ return <div onClick={useB ? handlerB : handlerA} />;
931
}
932
}
933
@@ -1043,7 +951,7 @@ describe('ReactDOMFiber', () => {
951
ReactTestUtils.simulateNativeEventOnNode(
952
'topClick',
953
target,
1046
- fakeNativeEvent
954
+ fakeNativeEvent,
955
);
956
}
957
@@ -1082,7 +990,6 @@ describe('ReactDOMFiber', () => {
990
// Any click that happens after commit, should invoke A.
991
click(node);
992
expect(ops).toEqual(['A']);
1085
-
993
});
994
995
it('should not crash encountering low-priority tree', () => {
@@ -1090,7 +997,7 @@ describe('ReactDOMFiber', () => {
997
<div hidden={true}>
998
<div />
999
</div>,
1093
- container
1000
+ container,
1001
);
1002
});
1003
}
@@ -1115,11 +1022,17 @@ describe('disableNewFiberFeatures', () => {
1022
it('throws if non-element passed to top-level render', () => {
1023
const message = 'render(): Invalid component element.';
1024
expect(() => ReactDOM.render(null, container)).toThrow(message, container);
1118
- expect(() => ReactDOM.render(undefined, container)).toThrow(message, container);
1025
+ expect(() => ReactDOM.render(undefined, container)).toThrow(
1026
+ message,
1027
+ container,
1028
+ );
1029
expect(() => ReactDOM.render(false, container)).toThrow(message, container);
1030
expect(() => ReactDOM.render('Hi', container)).toThrow(message, container);
1031
expect(() => ReactDOM.render(999, container)).toThrow(message, container);
1122
- expect(() => ReactDOM.render([<div />], container)).toThrow(message, container);
1032
+ expect(() => ReactDOM.render([<div />], container)).toThrow(
1033
+ message,
1034
+ container,
1035
+ );
1036
});
1037
1038
it('throws if something other than false, null, or an element is returned from render', () => {
@@ -1127,9 +1040,16 @@ describe('disableNewFiberFeatures', () => {
1040
return props.children;
1041
}
1042
1130
- expect(() => ReactDOM.render(<Render>Hi</Render>, container)).toThrow(/You may have returned undefined/);
1131
- expect(() => ReactDOM.render(<Render>{999}</Render>, container)).toThrow(/You may have returned undefined/);
1132
- expect(() => ReactDOM.render(<Render>[<div />]</Render>, container)).toThrow(/You may have returned undefined/);
1043
+ expect(() => ReactDOM.render(<Render>Hi</Render>, container)).toThrow(
1044
+ /You may have returned undefined/,
1045
+ );
1046
+ expect(() => ReactDOM.render(<Render>{999}</Render>, container)).toThrow(
1047
+ /You may have returned undefined/,
1048
+ );
1049
+ expect(() =>
1050
+ ReactDOM.render(<Render>[<div />]</Render>, container)).toThrow(
1051
+ /You may have returned undefined/,
1052
+ );
1053
});
1054
1055
it('treats mocked render functions as if they return null', () => {
src/renderers/dom/fiber/wrappers/ReactDOMFiberInput.js
+79
-64
@@ -16,14 +16,14 @@ type InputWithWrapperState = HTMLInputElement & {
16
_wrapperState: {
17
initialValue: ?string,
18
initialChecked: ?boolean,
19
- controlled?: boolean
20
- }
19
+ controlled?: boolean,
20
+ },
21
};
22
23
var DOMPropertyOperations = require('DOMPropertyOperations');
24
var ReactControlledValuePropTypes = require('ReactControlledValuePropTypes');
25
var ReactDOMComponentTree = require('ReactDOMComponentTree');
26
-var { getCurrentFiberOwnerName } = require('ReactDebugCurrentFiber');
26
+var {getCurrentFiberOwnerName} = require('ReactDebugCurrentFiber');
27
28
var invariant = require('fbjs/lib/invariant');
29
var warning = require('fbjs/lib/warning');
@@ -55,38 +55,42 @@ function isControlled(props) {
55
* See http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html
56
*/
57
var ReactDOMInput = {
58
- getHostProps: function(element : Element, props : Object) {
59
- var node = ((element : any) : InputWithWrapperState);
58
+ getHostProps: function(element: Element, props: Object) {
59
+ var node = ((element: any): InputWithWrapperState);
60
var value = props.value;
61
var checked = props.checked;
62
63
- var hostProps = Object.assign({
64
- // Make sure we set .type before any other properties (setting .value
65
- // before .type means .value is lost in IE11 and below)
66
- type: undefined,
67
- // Make sure we set .step before .value (setting .value before .step
68
- // means .value is rounded on mount, based upon step precision)
69
- step: undefined,
70
- // Make sure we set .min & .max before .value (to ensure proper order
71
- // in corner cases such as min or max deriving from value, e.g. Issue #7170)
72
- min: undefined,
73
- max: undefined,
74
- }, props, {
75
- defaultChecked: undefined,
76
- defaultValue: undefined,
77
- value: value != null ? value : node._wrapperState.initialValue,
78
- checked: checked != null ? checked : node._wrapperState.initialChecked,
79
- });
63
+ var hostProps = Object.assign(
64
+ {
65
+ // Make sure we set .type before any other properties (setting .value
66
+ // before .type means .value is lost in IE11 and below)
67
+ type: undefined,
68
+ // Make sure we set .step before .value (setting .value before .step
69
+ // means .value is rounded on mount, based upon step precision)
70
+ step: undefined,
71
+ // Make sure we set .min & .max before .value (to ensure proper order
72
+ // in corner cases such as min or max deriving from value, e.g. Issue #7170)
73
+ min: undefined,
74
+ max: undefined,
75
+ },
76
+ props,
77
+ {
78
+ defaultChecked: undefined,
79
+ defaultValue: undefined,
80
+ value: value != null ? value : node._wrapperState.initialValue,
81
+ checked: checked != null ? checked : node._wrapperState.initialChecked,
82
+ },
83
+ );
84
85
return hostProps;
86
},
87
84
- mountWrapper: function(element : Element, props : Object) {
88
+ mountWrapper: function(element: Element, props: Object) {
89
if (__DEV__) {
90
ReactControlledValuePropTypes.checkPropTypes(
91
'input',
92
props,
89
- getCurrentFiberOwnerName()
93
+ getCurrentFiberOwnerName(),
94
);
95
96
if (
@@ -97,13 +101,13 @@ var ReactDOMInput = {
101
warning(
102
false,
103
'%s contains an input of type %s with both checked and defaultChecked props. ' +
100
- 'Input elements must be either controlled or uncontrolled ' +
101
- '(specify either the checked prop, or the defaultChecked prop, but not ' +
102
- 'both). Decide between using a controlled or uncontrolled input ' +
103
- 'element and remove one of these props. More info: ' +
104
- 'https://fb.me/react-controlled-components',
104
+ 'Input elements must be either controlled or uncontrolled ' +
105
+ '(specify either the checked prop, or the defaultChecked prop, but not ' +
106
+ 'both). Decide between using a controlled or uncontrolled input ' +
107
+ 'element and remove one of these props. More info: ' +
108
+ 'https://fb.me/react-controlled-components',
109
getCurrentFiberOwnerName() || 'A component',
106
- props.type
110
+ props.type,
111
);
112
didWarnCheckedDefaultChecked = true;
113
}
@@ -115,22 +119,24 @@ var ReactDOMInput = {
119
warning(
120
false,
121
'%s contains an input of type %s with both value and defaultValue props. ' +
118
- 'Input elements must be either controlled or uncontrolled ' +
119
- '(specify either the value prop, or the defaultValue prop, but not ' +
120
- 'both). Decide between using a controlled or uncontrolled input ' +
121
- 'element and remove one of these props. More info: ' +
122
- 'https://fb.me/react-controlled-components',
122
+ 'Input elements must be either controlled or uncontrolled ' +
123
+ '(specify either the value prop, or the defaultValue prop, but not ' +
124
+ 'both). Decide between using a controlled or uncontrolled input ' +
125
+ 'element and remove one of these props. More info: ' +
126
+ 'https://fb.me/react-controlled-components',
127
getCurrentFiberOwnerName() || 'A component',
124
- props.type
128
+ props.type,
129
);
130
didWarnValueDefaultValue = true;
131
}
132
}
133
134
var defaultValue = props.defaultValue;
131
- var node = ((element : any) : InputWithWrapperState);
135
+ var node = ((element: any): InputWithWrapperState);
136
node._wrapperState = {
133
- initialChecked: props.checked != null ? props.checked : props.defaultChecked,
137
+ initialChecked: props.checked != null
138
+ ? props.checked
139
+ : props.defaultChecked,
140
initialValue: props.value != null ? props.value : defaultValue,
141
};
142
@@ -139,32 +145,40 @@ var ReactDOMInput = {
145
}
146
},
147
142
- updateWrapper: function(element : Element, props : Object) {
143
- var node = ((element : any) : InputWithWrapperState);
148
+ updateWrapper: function(element: Element, props: Object) {
149
+ var node = ((element: any): InputWithWrapperState);
150
if (__DEV__) {
151
var controlled = isControlled(props);
152
147
- if (!node._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) {
153
+ if (
154
+ !node._wrapperState.controlled &&
155
+ controlled &&
156
+ !didWarnUncontrolledToControlled
157
+ ) {
158
warning(
159
false,
160
'%s is changing an uncontrolled input of type %s to be controlled. ' +
151
- 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
152
- 'Decide between using a controlled or uncontrolled input ' +
153
- 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components',
161
+ 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
162
+ 'Decide between using a controlled or uncontrolled input ' +
163
+ 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components',
164
getCurrentFiberOwnerName() || 'A component',
155
- props.type
165
+ props.type,
166
);
167
didWarnUncontrolledToControlled = true;
168
}
159
- if (node._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) {
169
+ if (
170
+ node._wrapperState.controlled &&
171
+ !controlled &&
172
+ !didWarnControlledToUncontrolled
173
+ ) {
174
warning(
175
false,
176
'%s is changing a controlled input of type %s to be uncontrolled. ' +
163
- 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
164
- 'Decide between using a controlled or uncontrolled input ' +
165
- 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components',
177
+ 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
178
+ 'Decide between using a controlled or uncontrolled input ' +
179
+ 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components',
180
getCurrentFiberOwnerName() || 'A component',
167
- props.type
181
+ props.type,
182
);
183
didWarnControlledToUncontrolled = true;
184
}
@@ -175,13 +189,12 @@ var ReactDOMInput = {
189
DOMPropertyOperations.setValueForProperty(
190
node,
191
'checked',
178
- checked || false
192
+ checked || false,
193
);
194
}
195
196
var value = props.value;
197
if (value != null) {
184
-
198
// Cast `value` to a string to ensure the value is set correctly. While
199
// browsers typically do this as necessary, jsdom doesn't.
200
var newValue = '' + value;
@@ -210,8 +223,8 @@ var ReactDOMInput = {
223
}
224
},
225
213
- postMountWrapper: function(element : Element, props : Object) {
214
- var node = ((element : any) : InputWithWrapperState);
226
+ postMountWrapper: function(element: Element, props: Object) {
227
+ var node = ((element: any): InputWithWrapperState);
228
229
// Detach value from defaultValue. We won't do anything if we're working on
230
// submit or reset inputs as those values & defaultValues are linked. They
@@ -256,8 +269,8 @@ var ReactDOMInput = {
269
}
270
},
271
259
- restoreControlledState: function(element : Element, props : Object) {
260
- var node = ((element : any) : InputWithWrapperState);
272
+ restoreControlledState: function(element: Element, props: Object) {
273
+ var node = ((element: any): InputWithWrapperState);
274
ReactDOMInput.updateWrapper(node, props);
275
updateNamedCousins(node, props);
276
},
@@ -266,10 +279,10 @@ var ReactDOMInput = {
279
function updateNamedCousins(rootNode, props) {
280
var name = props.name;
281
if (props.type === 'radio' && name != null) {
269
- var queryRoot : Element = rootNode;
282
+ var queryRoot: Element = rootNode;
283
284
while (queryRoot.parentNode) {
272
- queryRoot = ((queryRoot.parentNode : any) : Element);
285
+ queryRoot = ((queryRoot.parentNode: any): Element);
286
}
287
288
// If `rootNode.form` was non-null, then we could try `form.elements`,
@@ -280,23 +293,25 @@ function updateNamedCousins(rootNode, props) {
293
// document. Let's just use the local `querySelectorAll` to ensure we don't
294
// miss anything.
295
var group = queryRoot.querySelectorAll(
283
- 'input[name=' + JSON.stringify('' + name) + '][type="radio"]');
296
+ 'input[name=' + JSON.stringify('' + name) + '][type="radio"]',
297
+ );
298
299
for (var i = 0; i < group.length; i++) {
286
- var otherNode = ((group[i] : any) : HTMLInputElement);
287
- if (otherNode === rootNode ||
288
- otherNode.form !== rootNode.form) {
300
+ var otherNode = ((group[i]: any): HTMLInputElement);
301
+ if (otherNode === rootNode || otherNode.form !== rootNode.form) {
302
continue;
303
}
304
// This will throw if radio buttons rendered by different copies of React
305
// and the same name are rendered into the same form (same as #1939).
306
// That's probably okay; we don't support it just as we don't support
307
// mixing React radio buttons with non-React ones.
295
- var otherProps = ReactDOMComponentTree.getFiberCurrentPropsFromNode(otherNode);
308
+ var otherProps = ReactDOMComponentTree.getFiberCurrentPropsFromNode(
309
+ otherNode,
310
+ );
311
invariant(
312
otherProps,
313
'ReactDOMInput: Mixing React and non-React radio inputs with the ' +
299
- 'same `name` is not supported.'
314
+ 'same `name` is not supported.',
315
);
316
// If this is a controlled radio button group, forcing the input that
317
// was previously checked to update will cause it to be come re-checked
src/renderers/dom/fiber/wrappers/ReactDOMFiberOption.js
+4
-5
@@ -39,25 +39,25 @@ function flattenChildren(children) {
39
* Implements an <option> host component that warns when `selected` is set.
40
*/
41
var ReactDOMOption = {
42
- mountWrapper: function(element : Element, props : Object) {
42
+ mountWrapper: function(element: Element, props: Object) {
43
// TODO (yungsters): Remove support for `selected` in <option>.
44
if (__DEV__) {
45
warning(
46
props.selected == null,
47
'Use the `defaultValue` or `value` props on <select> instead of ' +
48
- 'setting `selected` on <option>.'
48
+ 'setting `selected` on <option>.',
49
);
50
}
51
},
52
53
- postMountWrapper: function(element : Element, props : Object) {
53
+ postMountWrapper: function(element: Element, props: Object) {
54
// value="" should make a value attribute (#6219)
55
if (props.value != null) {
56
element.setAttribute('value', props.value);
57
}
58
},
59
60
- getHostProps: function(element : Element, props : Object) {
60
+ getHostProps: function(element: Element, props: Object) {
61
var hostProps = Object.assign({children: undefined}, props);
62
63
var content = flattenChildren(props.children);
@@ -68,7 +68,6 @@ var ReactDOMOption = {
68
69
return hostProps;
70
},
71
-
71
};
72
73
module.exports = ReactDOMOption;
src/renderers/dom/fiber/wrappers/ReactDOMFiberSelect.js
+30
-24
@@ -15,12 +15,12 @@
15
type SelectWithWrapperState = HTMLSelectElement & {
16
_wrapperState: {
17
initialValue: ?string,
18
- wasMultiple: boolean
19
- }
18
+ wasMultiple: boolean,
19
+ },
20
};
21
22
var ReactControlledValuePropTypes = require('ReactControlledValuePropTypes');
23
-var { getCurrentFiberOwnerName } = require('ReactDebugCurrentFiber');
23
+var {getCurrentFiberOwnerName} = require('ReactDebugCurrentFiber');
24
var warning = require('fbjs/lib/warning');
25
26
var didWarnValueDefaultValue = false;
@@ -42,7 +42,7 @@ function checkSelectPropTypes(props) {
42
ReactControlledValuePropTypes.checkPropTypes(
43
'select',
44
props,
45
- getCurrentFiberOwnerName()
45
+ getCurrentFiberOwnerName(),
46
);
47
48
for (var i = 0; i < valuePropNames.length; i++) {
@@ -55,28 +55,34 @@ function checkSelectPropTypes(props) {
55
warning(
56
false,
57
'The `%s` prop supplied to <select> must be an array if ' +
58
- '`multiple` is true.%s',
58
+ '`multiple` is true.%s',
59
propName,
60
- getDeclarationErrorAddendum()
60
+ getDeclarationErrorAddendum(),
61
);
62
} else if (!props.multiple && isArray) {
63
warning(
64
false,
65
'The `%s` prop supplied to <select> must be a scalar ' +
66
- 'value if `multiple` is false.%s',
66
+ 'value if `multiple` is false.%s',
67
propName,
68
- getDeclarationErrorAddendum()
68
+ getDeclarationErrorAddendum(),
69
);
70
}
71
}
72
}
73
74
-function updateOptions(node : HTMLSelectElement, multiple : boolean, propValue : any) {
75
- type IndexableHTMLOptionsCollection = HTMLOptionsCollection & { [key:number]: HTMLOptionElement };
76
- var options : IndexableHTMLOptionsCollection = node.options;
74
+function updateOptions(
75
+ node: HTMLSelectElement,
76
+ multiple: boolean,
77
+ propValue: any,
78
+) {
79
+ type IndexableHTMLOptionsCollection = HTMLOptionsCollection & {
80
+ [key: number]: HTMLOptionElement,
81
+ };
82
+ var options: IndexableHTMLOptionsCollection = node.options;
83
84
if (multiple) {
79
- let selectedValues = (propValue : Array<string>);
85
+ let selectedValues = (propValue: Array<string>);
86
let selectedValue = {};
87
for (let i = 0; i < selectedValues.length; i++) {
88
selectedValue['' + selectedValues[i]] = true;
@@ -90,7 +96,7 @@ function updateOptions(node : HTMLSelectElement, multiple : boolean, propValue :
96
} else {
97
// Do not set `select.value` as exact behavior isn't consistent across all
98
// browsers for all cases.
93
- let selectedValue = '' + (propValue : string);
99
+ let selectedValue = '' + (propValue: string);
100
for (let i = 0; i < options.length; i++) {
101
if (options[i].value === selectedValue) {
102
options[i].selected = true;
@@ -119,14 +125,14 @@ function updateOptions(node : HTMLSelectElement, multiple : boolean, propValue :
125
* selected.
126
*/
127
var ReactDOMSelect = {
122
- getHostProps: function(element : Element, props : Object) {
128
+ getHostProps: function(element: Element, props: Object) {
129
return Object.assign({}, props, {
130
value: undefined,
131
});
132
},
133
128
- mountWrapper: function(element : Element, props : Object) {
129
- var node = ((element : any) : SelectWithWrapperState);
134
+ mountWrapper: function(element: Element, props: Object) {
135
+ var node = ((element: any): SelectWithWrapperState);
136
if (__DEV__) {
137
checkSelectPropTypes(props);
138
}
@@ -145,10 +151,10 @@ var ReactDOMSelect = {
151
warning(
152
false,
153
'Select elements must be either controlled or uncontrolled ' +
148
- '(specify either the value prop, or the defaultValue prop, but not ' +
149
- 'both). Decide between using a controlled or uncontrolled select ' +
150
- 'element and remove one of these props. More info: ' +
151
- 'https://fb.me/react-controlled-components'
154
+ '(specify either the value prop, or the defaultValue prop, but not ' +
155
+ 'both). Decide between using a controlled or uncontrolled select ' +
156
+ 'element and remove one of these props. More info: ' +
157
+ 'https://fb.me/react-controlled-components',
158
);
159
didWarnValueDefaultValue = true;
160
}
@@ -161,8 +167,8 @@ var ReactDOMSelect = {
167
}
168
},
169
164
- postUpdateWrapper: function(element : Element, props : Object) {
165
- var node = ((element : any) : SelectWithWrapperState);
170
+ postUpdateWrapper: function(element: Element, props: Object) {
171
+ var node = ((element: any): SelectWithWrapperState);
172
// After the initial mount, we control selected-ness manually so don't pass
173
// this value down
174
node._wrapperState.initialValue = undefined;
@@ -184,8 +190,8 @@ var ReactDOMSelect = {
190
}
191
},
192
187
- restoreControlledState: function(element : Element, props : Object) {
188
- var node = ((element : any) : SelectWithWrapperState);
193
+ restoreControlledState: function(element: Element, props: Object) {
194
+ var node = ((element: any): SelectWithWrapperState);
195
var value = props.value;
196
197
if (value != null) {
src/renderers/dom/fiber/wrappers/ReactDOMFiberTextarea.js
+20
-22
@@ -15,11 +15,11 @@
15
type TextAreaWithWrapperState = HTMLTextAreaElement & {
16
_wrapperState: {
17
initialValue: string,
18
- }
18
+ },
19
};
20
21
var ReactControlledValuePropTypes = require('ReactControlledValuePropTypes');
22
-var { getCurrentFiberOwnerName } = require('ReactDebugCurrentFiber');
22
+var {getCurrentFiberOwnerName} = require('ReactDebugCurrentFiber');
23
24
var invariant = require('fbjs/lib/invariant');
25
var warning = require('fbjs/lib/warning');
@@ -42,11 +42,11 @@ var didWarnValDefaultVal = false;
42
* `defaultValue` if specified, or the children content (deprecated).
43
*/
44
var ReactDOMTextarea = {
45
- getHostProps: function(element : Element, props : Object) {
46
- var node = ((element : any) : TextAreaWithWrapperState);
45
+ getHostProps: function(element: Element, props: Object) {
46
+ var node = ((element: any): TextAreaWithWrapperState);
47
invariant(
48
props.dangerouslySetInnerHTML == null,
49
- '`dangerouslySetInnerHTML` does not make sense on <textarea>.'
49
+ '`dangerouslySetInnerHTML` does not make sense on <textarea>.',
50
);
51
52
// Always set children to the same thing. In IE9, the selection range will
@@ -63,13 +63,13 @@ var ReactDOMTextarea = {
63
return hostProps;
64
},
65
66
- mountWrapper: function(element : Element, props : Object) {
67
- var node = ((element : any) : TextAreaWithWrapperState);
66
+ mountWrapper: function(element: Element, props: Object) {
67
+ var node = ((element: any): TextAreaWithWrapperState);
68
if (__DEV__) {
69
ReactControlledValuePropTypes.checkPropTypes(
70
'textarea',
71
props,
72
- getCurrentFiberOwnerName()
72
+ getCurrentFiberOwnerName(),
73
);
74
if (
75
props.value !== undefined &&
@@ -79,16 +79,15 @@ var ReactDOMTextarea = {
79
warning(
80
false,
81
'Textarea elements must be either controlled or uncontrolled ' +
82
- '(specify either the value prop, or the defaultValue prop, but not ' +
83
- 'both). Decide between using a controlled or uncontrolled textarea ' +
84
- 'and remove one of these props. More info: ' +
85
- 'https://fb.me/react-controlled-components'
82
+ '(specify either the value prop, or the defaultValue prop, but not ' +
83
+ 'both). Decide between using a controlled or uncontrolled textarea ' +
84
+ 'and remove one of these props. More info: ' +
85
+ 'https://fb.me/react-controlled-components',
86
);
87
didWarnValDefaultVal = true;
88
}
89
}
90
91
-
91
var value = props.value;
92
var initialValue = value;
93
@@ -102,17 +101,17 @@ var ReactDOMTextarea = {
101
warning(
102
false,
103
'Use the `defaultValue` or `value` props instead of setting ' +
105
- 'children on <textarea>.'
104
+ 'children on <textarea>.',
105
);
106
}
107
invariant(
108
defaultValue == null,
110
- 'If you supply `defaultValue` on a <textarea>, do not pass children.'
109
+ 'If you supply `defaultValue` on a <textarea>, do not pass children.',
110
);
111
if (Array.isArray(children)) {
112
invariant(
113
children.length <= 1,
115
- '<textarea> can only have at most one child.'
114
+ '<textarea> can only have at most one child.',
115
);
116
children = children[0];
117
}
@@ -130,8 +129,8 @@ var ReactDOMTextarea = {
129
};
130
},
131
133
- updateWrapper: function(element : Element, props : Object) {
134
- var node = ((element : any) : TextAreaWithWrapperState);
132
+ updateWrapper: function(element: Element, props: Object) {
133
+ var node = ((element: any): TextAreaWithWrapperState);
134
var value = props.value;
135
if (value != null) {
136
// Cast `value` to a string to ensure the value is set correctly. While
@@ -151,8 +150,8 @@ var ReactDOMTextarea = {
150
}
151
},
152
154
- postMountWrapper: function(element : Element, props : Object) {
155
- var node = ((element : any) : TextAreaWithWrapperState);
153
+ postMountWrapper: function(element: Element, props: Object) {
154
+ var node = ((element: any): TextAreaWithWrapperState);
155
// This is in postMount because we need access to the DOM node, which is not
156
// available until after the component has mounted.
157
var textContent = node.textContent;
@@ -166,11 +165,10 @@ var ReactDOMTextarea = {
165
}
166
},
167
169
- restoreControlledState: function(element : Element, props : Object) {
168
+ restoreControlledState: function(element: Element, props: Object) {
169
// DOM component is still mounted; update
170
ReactDOMTextarea.updateWrapper(element, props);
171
},
173
-
172
};
173
174
module.exports = ReactDOMTextarea;
src/renderers/dom/shared/CSSPropertyOperations.js
+11
-14
@@ -22,7 +22,7 @@ var memoizeStringOnly = require('fbjs/lib/memoizeStringOnly');
22
var warning = require('fbjs/lib/warning');
23
24
if (__DEV__) {
25
- var { getCurrentFiberOwnerName } = require('ReactDebugCurrentFiber');
25
+ var {getCurrentFiberOwnerName} = require('ReactDebugCurrentFiber');
26
}
27
28
var processStyleName = memoizeStringOnly(function(styleName) {
@@ -67,7 +67,7 @@ if (__DEV__) {
67
'Unsupported style property %s. Did you mean %s?%s',
68
name,
69
camelizeStyleName(name),
70
- checkRenderMessage(owner)
70
+ checkRenderMessage(owner),
71
);
72
};
73
@@ -82,7 +82,7 @@ if (__DEV__) {
82
'Unsupported vendor-prefixed style property %s. Did you mean %s?%s',
83
name,
84
name.charAt(0).toUpperCase() + name.slice(1),
85
- checkRenderMessage(owner)
85
+ checkRenderMessage(owner),
86
);
87
};
88
@@ -94,11 +94,11 @@ if (__DEV__) {
94
warnedStyleValues[value] = true;
95
warning(
96
false,
97
- 'Style property values shouldn\'t contain a semicolon.%s ' +
98
- 'Try "%s: %s" instead.',
97
+ "Style property values shouldn't contain a semicolon.%s " +
98
+ 'Try "%s: %s" instead.',
99
checkRenderMessage(owner),
100
name,
101
- value.replace(badStyleValueWithSemicolonPattern, '')
101
+ value.replace(badStyleValueWithSemicolonPattern, ''),
102
);
103
};
104
@@ -112,7 +112,7 @@ if (__DEV__) {
112
false,
113
'`NaN` is an invalid value for the `%s` css style property.%s',
114
name,
115
- checkRenderMessage(owner)
115
+ checkRenderMessage(owner),
116
);
117
};
118
@@ -161,7 +161,6 @@ if (__DEV__) {
161
* Operations for dealing with CSS properties.
162
*/
163
var CSSPropertyOperations = {
164
-
164
/**
165
* Serializes a mapping of style properties for use as inline styles:
166
*
@@ -187,8 +186,8 @@ var CSSPropertyOperations = {
186
}
187
if (styleValue != null) {
188
serialized += processStyleName(styleName) + ':';
190
- serialized +=
191
- dangerousStyleValue(styleName, styleValue, component) + ';';
189
+ serialized += dangerousStyleValue(styleName, styleValue, component) +
190
+ ';';
191
}
192
}
193
return serialized || null;
@@ -214,7 +213,7 @@ var CSSPropertyOperations = {
213
var styleValue = dangerousStyleValue(
214
styleName,
215
styles[styleName],
217
- component
216
+ component,
217
);
218
if (styleName === 'float' || styleName === 'cssFloat') {
219
styleName = styleFloatAccessor;
@@ -222,8 +221,7 @@ var CSSPropertyOperations = {
221
if (styleValue) {
222
style[styleName] = styleValue;
223
} else {
225
- var expansion =
226
- hasShorthandPropertyBug &&
224
+ var expansion = hasShorthandPropertyBug &&
225
CSSProperty.shorthandPropertyExpansions[styleName];
226
if (expansion) {
227
// Shorthand property that IE8 won't like unsetting, so unset each
@@ -237,7 +235,6 @@ var CSSPropertyOperations = {
235
}
236
}
237
},
240
-
238
};
239
240
module.exports = CSSPropertyOperations;
src/renderers/dom/shared/DOMProperty.js
+22
-17
@@ -66,18 +66,18 @@ var DOMPropertyInjection = {
66
67
if (domPropertyConfig.isCustomAttribute) {
68
DOMProperty._isCustomAttributeFunctions.push(
69
- domPropertyConfig.isCustomAttribute
69
+ domPropertyConfig.isCustomAttribute,
70
);
71
}
72
73
for (var propName in Properties) {
74
invariant(
75
!DOMProperty.properties.hasOwnProperty(propName),
76
- 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property ' +
77
- '\'%s\' which has already been injected. You may be accidentally ' +
78
- 'injecting the same DOM property config twice, or you may be ' +
79
- 'injecting two configs that have conflicting property names.',
80
- propName
76
+ "injectDOMPropertyConfig(...): You're trying to inject DOM property " +
77
+ "'%s' which has already been injected. You may be accidentally " +
78
+ 'injecting the same DOM property config twice, or you may be ' +
79
+ 'injecting two configs that have conflicting property names.',
80
+ propName,
81
);
82
83
var lowerCased = propName.toLowerCase();
@@ -92,17 +92,23 @@ var DOMPropertyInjection = {
92
mustUseProperty: checkMask(propConfig, Injection.MUST_USE_PROPERTY),
93
hasBooleanValue: checkMask(propConfig, Injection.HAS_BOOLEAN_VALUE),
94
hasNumericValue: checkMask(propConfig, Injection.HAS_NUMERIC_VALUE),
95
- hasPositiveNumericValue:
96
- checkMask(propConfig, Injection.HAS_POSITIVE_NUMERIC_VALUE),
97
- hasOverloadedBooleanValue:
98
- checkMask(propConfig, Injection.HAS_OVERLOADED_BOOLEAN_VALUE),
95
+ hasPositiveNumericValue: checkMask(
96
+ propConfig,
97
+ Injection.HAS_POSITIVE_NUMERIC_VALUE,
98
+ ),
99
+ hasOverloadedBooleanValue: checkMask(
100
+ propConfig,
101
+ Injection.HAS_OVERLOADED_BOOLEAN_VALUE,
102
+ ),
103
};
104
invariant(
101
- propertyInfo.hasBooleanValue + propertyInfo.hasNumericValue +
102
- propertyInfo.hasOverloadedBooleanValue <= 1,
105
+ propertyInfo.hasBooleanValue +
106
+ propertyInfo.hasNumericValue +
107
+ propertyInfo.hasOverloadedBooleanValue <=
108
+ 1,
109
'DOMProperty: Value can be one of boolean, overloaded boolean, or ' +
104
- 'numeric value, but not a combination: %s',
105
- propName
110
+ 'numeric value, but not a combination: %s',
111
+ propName,
112
);
113
114
if (__DEV__) {
@@ -138,7 +144,6 @@ var DOMPropertyInjection = {
144
var ATTRIBUTE_NAME_START_CHAR = ':A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD';
145
/* eslint-enable max-len */
146
141
-
147
/**
148
* DOMProperty exports lookup objects that can be used like functions:
149
*
@@ -153,12 +158,12 @@ var ATTRIBUTE_NAME_START_CHAR = ':A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\
158
* @see http://jsperf.com/key-missing
159
*/
160
var DOMProperty = {
156
-
161
ID_ATTRIBUTE_NAME: 'data-reactid',
162
ROOT_ATTRIBUTE_NAME: 'data-reactroot',
163
164
ATTRIBUTE_NAME_START_CHAR: ATTRIBUTE_NAME_START_CHAR,
161
- ATTRIBUTE_NAME_CHAR: ATTRIBUTE_NAME_START_CHAR + '\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040',
165
+ ATTRIBUTE_NAME_CHAR: ATTRIBUTE_NAME_START_CHAR +
166
+ '\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040',
167
168
/**
169
* Map from property "standard name" to an object with info about how to set
src/renderers/dom/shared/DOMPropertyOperations.js
+26
-20
@@ -19,7 +19,11 @@ var quoteAttributeValueForBrowser = require('quoteAttributeValueForBrowser');
19
var warning = require('fbjs/lib/warning');
20
21
var VALID_ATTRIBUTE_NAME_REGEX = new RegExp(
22
- '^[' + DOMProperty.ATTRIBUTE_NAME_START_CHAR + '][' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$'
22
+ '^[' +
23
+ DOMProperty.ATTRIBUTE_NAME_START_CHAR +
24
+ '][' +
25
+ DOMProperty.ATTRIBUTE_NAME_CHAR +
26
+ ']*$',
27
);
28
var illegalAttributeNameCache = {};
29
var validatedAttributeNameCache = {};
@@ -36,11 +40,7 @@ function isAttributeNameSafe(attributeName) {
40
return true;
41
}
42
illegalAttributeNameCache[attributeName] = true;
39
- warning(
40
- false,
41
- 'Invalid attribute name: `%s`',
42
- attributeName
43
- );
43
+ warning(false, 'Invalid attribute name: `%s`', attributeName);
44
return false;
45
}
46
@@ -48,7 +48,7 @@ function shouldIgnoreValue(propertyInfo, value) {
48
return value == null ||
49
(propertyInfo.hasBooleanValue && !value) ||
50
(propertyInfo.hasNumericValue && isNaN(value)) ||
51
- (propertyInfo.hasPositiveNumericValue && (value < 1)) ||
51
+ (propertyInfo.hasPositiveNumericValue && value < 1) ||
52
(propertyInfo.hasOverloadedBooleanValue && value === false);
53
}
54
@@ -56,7 +56,6 @@ function shouldIgnoreValue(propertyInfo, value) {
56
* Operations for dealing with DOM properties.
57
*/
58
var DOMPropertyOperations = {
59
-
59
/**
60
* Creates markup for the ID property.
61
*
@@ -64,7 +63,8 @@ var DOMPropertyOperations = {
63
* @return {string} Markup string.
64
*/
65
createMarkupForID: function(id) {
67
- return DOMProperty.ID_ATTRIBUTE_NAME + '=' +
66
+ return DOMProperty.ID_ATTRIBUTE_NAME +
67
+ '=' +
68
quoteAttributeValueForBrowser(id);
69
},
70
@@ -88,15 +88,18 @@ var DOMPropertyOperations = {
88
* @return {?string} Markup string, or null if the property was invalid.
89
*/
90
createMarkupForProperty: function(name, value) {
91
- var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ?
92
- DOMProperty.properties[name] : null;
91
+ var propertyInfo = DOMProperty.properties.hasOwnProperty(name)
92
+ ? DOMProperty.properties[name]
93
+ : null;
94
if (propertyInfo) {
95
if (shouldIgnoreValue(propertyInfo, value)) {
96
return '';
97
}
98
var attributeName = propertyInfo.attributeName;
98
- if (propertyInfo.hasBooleanValue ||
99
- (propertyInfo.hasOverloadedBooleanValue && value === true)) {
99
+ if (
100
+ propertyInfo.hasBooleanValue ||
101
+ (propertyInfo.hasOverloadedBooleanValue && value === true)
102
+ ) {
103
return attributeName + '=""';
104
}
105
return attributeName + '=' + quoteAttributeValueForBrowser(value);
@@ -131,8 +134,9 @@ var DOMPropertyOperations = {
134
* @param {*} value
135
*/
136
setValueForProperty: function(node, name, value) {
134
- var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ?
135
- DOMProperty.properties[name] : null;
137
+ var propertyInfo = DOMProperty.properties.hasOwnProperty(name)
138
+ ? DOMProperty.properties[name]
139
+ : null;
140
if (propertyInfo) {
141
var mutationMethod = propertyInfo.mutationMethod;
142
if (mutationMethod) {
@@ -151,8 +155,10 @@ var DOMPropertyOperations = {
155
// ('' + value) makes it output the correct toString()-value.
156
if (namespace) {
157
node.setAttributeNS(namespace, attributeName, '' + value);
154
- } else if (propertyInfo.hasBooleanValue ||
155
- (propertyInfo.hasOverloadedBooleanValue && value === true)) {
158
+ } else if (
159
+ propertyInfo.hasBooleanValue ||
160
+ (propertyInfo.hasOverloadedBooleanValue && value === true)
161
+ ) {
162
node.setAttribute(attributeName, '');
163
} else {
164
node.setAttribute(attributeName, '' + value);
@@ -219,8 +225,9 @@ var DOMPropertyOperations = {
225
* @param {string} name
226
*/
227
deleteValueForProperty: function(node, name) {
222
- var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ?
223
- DOMProperty.properties[name] : null;
228
+ var propertyInfo = DOMProperty.properties.hasOwnProperty(name)
229
+ ? DOMProperty.properties[name]
230
+ : null;
231
if (propertyInfo) {
232
var mutationMethod = propertyInfo.mutationMethod;
233
if (mutationMethod) {
@@ -247,7 +254,6 @@ var DOMPropertyOperations = {
254
});
255
}
256
},
250
-
257
};
258
259
module.exports = DOMPropertyOperations;
src/renderers/dom/shared/HTMLDOMPropertyConfig.js
+4
-7
@@ -16,14 +16,12 @@ var DOMProperty = require('DOMProperty');
16
var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY;
17
var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE;
18
var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE;
19
-var HAS_POSITIVE_NUMERIC_VALUE =
20
- DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE;
21
-var HAS_OVERLOADED_BOOLEAN_VALUE =
22
- DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE;
19
+var HAS_POSITIVE_NUMERIC_VALUE = DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE;
20
+var HAS_OVERLOADED_BOOLEAN_VALUE = DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE;
21
22
var HTMLDOMPropertyConfig = {
23
isCustomAttribute: RegExp.prototype.test.bind(
26
- new RegExp('^(data|aria)-[' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$')
24
+ new RegExp('^(data|aria)-[' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$'),
25
),
26
Properties: {
27
/**
@@ -211,8 +209,7 @@ var HTMLDOMPropertyConfig = {
209
htmlFor: 'for',
210
httpEquiv: 'http-equiv',
211
},
214
- DOMPropertyNames: {
215
- },
212
+ DOMPropertyNames: {},
213
};
214
215
module.exports = HTMLDOMPropertyConfig;
src/renderers/dom/shared/ReactBrowserEventEmitter.js
+36
-40
@@ -84,8 +84,10 @@ var reactTopListenersCounter = 0;
84
var topEventMapping = {
85
topAbort: 'abort',
86
topAnimationEnd: getVendorPrefixedEventName('animationend') || 'animationend',
87
- topAnimationIteration: getVendorPrefixedEventName('animationiteration') || 'animationiteration',
88
- topAnimationStart: getVendorPrefixedEventName('animationstart') || 'animationstart',
87
+ topAnimationIteration: getVendorPrefixedEventName('animationiteration') ||
88
+ 'animationiteration',
89
+ topAnimationStart: getVendorPrefixedEventName('animationstart') ||
90
+ 'animationstart',
91
topBlur: 'blur',
92
topCancel: 'cancel',
93
topCanPlay: 'canplay',
@@ -145,7 +147,8 @@ var topEventMapping = {
147
topTouchEnd: 'touchend',
148
topTouchMove: 'touchmove',
149
topTouchStart: 'touchstart',
148
- topTransitionEnd: getVendorPrefixedEventName('transitionend') || 'transitionend',
150
+ topTransitionEnd: getVendorPrefixedEventName('transitionend') ||
151
+ 'transitionend',
152
topVolumeChange: 'volumechange',
153
topWaiting: 'waiting',
154
topWheel: 'wheel',
@@ -167,7 +170,6 @@ function getListeningForDocument(mountAt) {
170
}
171
172
var ReactBrowserEventEmitter = Object.assign({}, ReactEventEmitterMixin, {
170
-
173
/**
174
* Injectable event backend
175
*/
@@ -179,7 +181,7 @@ var ReactBrowserEventEmitter = Object.assign({}, ReactEventEmitterMixin, {
181
*/
182
injectReactEventListener: function(ReactEventListener) {
183
ReactEventListener.setHandleTopLevel(
182
- ReactBrowserEventEmitter.handleTopLevel
184
+ ReactBrowserEventEmitter.handleTopLevel,
185
);
186
ReactBrowserEventEmitter.ReactEventListener = ReactEventListener;
187
},
@@ -200,10 +202,8 @@ var ReactBrowserEventEmitter = Object.assign({}, ReactEventEmitterMixin, {
202
* @return {boolean} True if callbacks are enabled.
203
*/
204
isEnabled: function() {
203
- return !!(
204
- ReactBrowserEventEmitter.ReactEventListener &&
205
- ReactBrowserEventEmitter.ReactEventListener.isEnabled()
206
- );
205
+ return !!(ReactBrowserEventEmitter.ReactEventListener &&
206
+ ReactBrowserEventEmitter.ReactEventListener.isEnabled());
207
},
208
209
/**
@@ -230,27 +230,27 @@ var ReactBrowserEventEmitter = Object.assign({}, ReactEventEmitterMixin, {
230
listenTo: function(registrationName, contentDocumentHandle) {
231
var mountAt = contentDocumentHandle;
232
var isListening = getListeningForDocument(mountAt);
233
- var dependencies =
234
- EventPluginRegistry.registrationNameDependencies[registrationName];
233
+ var dependencies = EventPluginRegistry.registrationNameDependencies[
234
+ registrationName
235
+ ];
236
237
for (var i = 0; i < dependencies.length; i++) {
238
var dependency = dependencies[i];
238
- if (!(
239
- isListening.hasOwnProperty(dependency) &&
240
- isListening[dependency]
241
- )) {
239
+ if (
240
+ !(isListening.hasOwnProperty(dependency) && isListening[dependency])
241
+ ) {
242
if (dependency === 'topWheel') {
243
if (isEventSupported('wheel')) {
244
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(
245
'topWheel',
246
'wheel',
247
- mountAt
247
+ mountAt,
248
);
249
} else if (isEventSupported('mousewheel')) {
250
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(
251
'topWheel',
252
'mousewheel',
253
- mountAt
253
+ mountAt,
254
);
255
} else {
256
// Firefox needs to capture a different mouse scroll event.
@@ -258,37 +258,34 @@ var ReactBrowserEventEmitter = Object.assign({}, ReactEventEmitterMixin, {
258
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(
259
'topWheel',
260
'DOMMouseScroll',
261
- mountAt
261
+ mountAt,
262
);
263
}
264
} else if (dependency === 'topScroll') {
265
-
265
if (isEventSupported('scroll', true)) {
266
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(
267
'topScroll',
268
'scroll',
270
- mountAt
269
+ mountAt,
270
);
271
} else {
272
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(
273
'topScroll',
274
'scroll',
276
- ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE
275
+ ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE,
276
);
277
}
279
- } else if (dependency === 'topFocus' ||
280
- dependency === 'topBlur') {
281
-
278
+ } else if (dependency === 'topFocus' || dependency === 'topBlur') {
279
if (isEventSupported('focus', true)) {
280
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(
281
'topFocus',
282
'focus',
286
- mountAt
283
+ mountAt,
284
);
285
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(
286
'topBlur',
287
'blur',
291
- mountAt
288
+ mountAt,
289
);
290
} else if (isEventSupported('focusin')) {
291
// IE has `focusin` and `focusout` events which bubble.
@@ -296,12 +293,12 @@ var ReactBrowserEventEmitter = Object.assign({}, ReactEventEmitterMixin, {
293
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(
294
'topFocus',
295
'focusin',
299
- mountAt
296
+ mountAt,
297
);
298
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(
299
'topBlur',
300
'focusout',
304
- mountAt
301
+ mountAt,
302
);
303
}
304
@@ -313,7 +310,7 @@ var ReactBrowserEventEmitter = Object.assign({}, ReactEventEmitterMixin, {
310
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(
311
'topCancel',
312
'cancel',
316
- mountAt
313
+ mountAt,
314
);
315
}
316
isListening.topCancel = true;
@@ -322,7 +319,7 @@ var ReactBrowserEventEmitter = Object.assign({}, ReactEventEmitterMixin, {
319
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(
320
'topClose',
321
'close',
325
- mountAt
322
+ mountAt,
323
);
324
}
325
isListening.topClose = true;
@@ -330,7 +327,7 @@ var ReactBrowserEventEmitter = Object.assign({}, ReactEventEmitterMixin, {
327
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(
328
dependency,
329
topEventMapping[dependency],
333
- mountAt
330
+ mountAt,
331
);
332
}
333
@@ -341,14 +338,14 @@ var ReactBrowserEventEmitter = Object.assign({}, ReactEventEmitterMixin, {
338
339
isListeningToAllDependencies: function(registrationName, mountAt) {
340
var isListening = getListeningForDocument(mountAt);
344
- var dependencies =
345
- EventPluginRegistry.registrationNameDependencies[registrationName];
341
+ var dependencies = EventPluginRegistry.registrationNameDependencies[
342
+ registrationName
343
+ ];
344
for (var i = 0; i < dependencies.length; i++) {
345
var dependency = dependencies[i];
348
- if (!(
349
- isListening.hasOwnProperty(dependency) &&
350
- isListening[dependency]
351
- )) {
346
+ if (
347
+ !(isListening.hasOwnProperty(dependency) && isListening[dependency])
348
+ ) {
349
return false;
350
}
351
}
@@ -359,7 +356,7 @@ var ReactBrowserEventEmitter = Object.assign({}, ReactEventEmitterMixin, {
356
return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(
357
topLevelType,
358
handlerBaseName,
362
- handle
359
+ handle,
360
);
361
},
362
@@ -367,7 +364,7 @@ var ReactBrowserEventEmitter = Object.assign({}, ReactEventEmitterMixin, {
364
return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(
365
topLevelType,
366
handlerBaseName,
370
- handle
367
+ handle,
368
);
369
},
370
@@ -405,7 +402,6 @@ var ReactBrowserEventEmitter = Object.assign({}, ReactEventEmitterMixin, {
402
isMonitoringScrollValue = true;
403
}
404
},
408
-
405
});
406
407
module.exports = ReactBrowserEventEmitter;
src/renderers/dom/shared/ReactDOMComponentTree.js
+7
-8
@@ -13,7 +13,7 @@
13
14
var DOMProperty = require('DOMProperty');
15
var ReactDOMComponentFlags = require('ReactDOMComponentFlags');
16
-var { HostComponent, HostText } = require('ReactTypeOfWork');
16
+var {HostComponent, HostText} = require('ReactTypeOfWork');
17
18
var invariant = require('fbjs/lib/invariant');
19
@@ -31,11 +31,10 @@ var internalEventHandlersKey = '__reactEventHandlers$' + randomKey;
31
*/
32
function shouldPrecacheNode(node, nodeID) {
33
return (node.nodeType === 1 &&
34
- node.getAttribute(ATTR_NAME) === ('' + nodeID)) ||
35
- (node.nodeType === 8 &&
36
- node.nodeValue === ' react-text: ' + nodeID + ' ') ||
37
- (node.nodeType === 8 &&
38
- node.nodeValue === ' react-empty: ' + nodeID + ' ');
34
+ node.getAttribute(ATTR_NAME) === '' + nodeID) ||
35
+ (node.nodeType === 8 &&
36
+ node.nodeValue === ' react-text: ' + nodeID + ' ') ||
37
+ (node.nodeType === 8 && node.nodeValue === ' react-empty: ' + nodeID + ' ');
38
}
39
40
/**
@@ -194,7 +193,7 @@ function getNodeFromInstance(inst) {
193
// invariant for a missing parent, which is super confusing.
194
invariant(
195
inst._hostNode !== undefined,
197
- 'getNodeFromInstance: Invalid argument.'
196
+ 'getNodeFromInstance: Invalid argument.',
197
);
198
199
if (inst._hostNode) {
@@ -207,7 +206,7 @@ function getNodeFromInstance(inst) {
206
parents.push(inst);
207
invariant(
208
inst._hostParent,
210
- 'React DOM tree root should always have a node reference.'
209
+ 'React DOM tree root should always have a node reference.',
210
);
211
inst = inst._hostParent;
212
}
src/renderers/dom/shared/ReactDOMInjection.js
+1
-1
@@ -39,7 +39,7 @@ function inject() {
39
alreadyInjected = true;
40
41
ReactBrowserEventEmitter.injection.injectReactEventListener(
42
- ReactEventListener
42
+ ReactEventListener,
43
);
44
45
/**
src/renderers/dom/shared/ReactDOMSelection.js
+5
-8
@@ -99,7 +99,7 @@ function getModernOffsets(node) {
99
selection.anchorNode,
100
selection.anchorOffset,
101
selection.focusNode,
102
- selection.focusOffset
102
+ selection.focusOffset,
103
);
104
105
var rangeLength = isSelectionCollapsed ? 0 : currentRange.toString().length;
@@ -112,7 +112,7 @@ function getModernOffsets(node) {
112
tempRange.startContainer,
113
tempRange.startOffset,
114
tempRange.endContainer,
115
- tempRange.endOffset
115
+ tempRange.endOffset,
116
);
117
118
var start = isTempRangeCollapsed ? 0 : tempRange.toString().length;
@@ -176,8 +176,7 @@ function setModernOffsets(node, offsets) {
176
var selection = window.getSelection();
177
var length = node[getTextContentAccessor()].length;
178
var start = Math.min(offsets.start, length);
179
- var end = offsets.end === undefined ?
180
- start : Math.min(offsets.end, length);
179
+ var end = offsets.end === undefined ? start : Math.min(offsets.end, length);
180
181
// IE 11 uses modern selection, but doesn't support the extend method.
182
// Flip backward selections, so we can set with a single range.
@@ -205,11 +204,9 @@ function setModernOffsets(node, offsets) {
204
}
205
}
206
208
-var useIEOffsets = (
209
- ExecutionEnvironment.canUseDOM &&
207
+var useIEOffsets = ExecutionEnvironment.canUseDOM &&
208
'selection' in document &&
211
- !('getSelection' in window)
212
-);
209
+ !('getSelection' in window);
210
211
var ReactDOMSelection = {
212
/**
src/renderers/dom/shared/ReactEventListener.js
+8
-11
@@ -21,7 +21,7 @@ var ReactTypeOfWork = require('ReactTypeOfWork');
21
var getEventTarget = require('getEventTarget');
22
var getUnboundedScrollPosition = require('fbjs/lib/getUnboundedScrollPosition');
23
24
-var { HostRoot } = ReactTypeOfWork;
24
+var {HostRoot} = ReactTypeOfWork;
25
26
/**
27
* Find the deepest React component completely containing the root of the
@@ -67,7 +67,7 @@ Object.assign(TopLevelCallbackBookKeeping.prototype, {
67
});
68
PooledClass.addPoolingTo(
69
TopLevelCallbackBookKeeping,
70
- PooledClass.threeArgumentPooler
70
+ PooledClass.threeArgumentPooler,
71
);
72
73
function handleTopLevelImpl(bookKeeping) {
@@ -88,9 +88,7 @@ function handleTopLevelImpl(bookKeeping) {
88
break;
89
}
90
bookKeeping.ancestors.push(ancestor);
91
- ancestor = ReactDOMComponentTree.getClosestInstanceFromNode(
92
- root
93
- );
91
+ ancestor = ReactDOMComponentTree.getClosestInstanceFromNode(root);
92
} while (ancestor);
93
94
for (var i = 0; i < bookKeeping.ancestors.length; i++) {
@@ -99,7 +97,7 @@ function handleTopLevelImpl(bookKeeping) {
97
bookKeeping.topLevelType,
98
targetInst,
99
bookKeeping.nativeEvent,
102
- getEventTarget(bookKeeping.nativeEvent)
100
+ getEventTarget(bookKeeping.nativeEvent),
101
);
102
}
103
}
@@ -127,7 +125,6 @@ var ReactEventListener = {
125
return ReactEventListener._enabled;
126
},
127
130
-
128
/**
129
* Traps top-level events by using event bubbling.
130
*
@@ -145,7 +142,7 @@ var ReactEventListener = {
142
return EventListener.listen(
143
element,
144
handlerBaseName,
148
- ReactEventListener.dispatchEvent.bind(null, topLevelType)
145
+ ReactEventListener.dispatchEvent.bind(null, topLevelType),
146
);
147
},
148
@@ -166,7 +163,7 @@ var ReactEventListener = {
163
return EventListener.capture(
164
element,
165
handlerBaseName,
169
- ReactEventListener.dispatchEvent.bind(null, topLevelType)
166
+ ReactEventListener.dispatchEvent.bind(null, topLevelType),
167
);
168
},
169
@@ -182,13 +179,13 @@ var ReactEventListener = {
179
180
var nativeEventTarget = getEventTarget(nativeEvent);
181
var targetInst = ReactDOMComponentTree.getClosestInstanceFromNode(
185
- nativeEventTarget
182
+ nativeEventTarget,
183
);
184
185
var bookKeeping = TopLevelCallbackBookKeeping.getPooled(
186
topLevelType,
187
nativeEvent,
191
- targetInst
188
+ targetInst,
189
);
190
191
try {
src/renderers/dom/shared/ReactInputSelection.js
+17
-20
@@ -28,24 +28,21 @@ function isInDocument(node) {
28
* Input selection module for React.
29
*/
30
var ReactInputSelection = {
31
-
31
hasSelectionCapabilities: function(elem) {
32
var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
34
- return nodeName && (
35
- (nodeName === 'input' && elem.type === 'text') ||
36
- nodeName === 'textarea' ||
37
- elem.contentEditable === 'true'
38
- );
33
+ return nodeName &&
34
+ ((nodeName === 'input' && elem.type === 'text') ||
35
+ nodeName === 'textarea' ||
36
+ elem.contentEditable === 'true');
37
},
38
39
getSelectionInformation: function() {
40
var focusedElem = getActiveElement();
41
return {
42
focusedElem: focusedElem,
45
- selectionRange:
46
- ReactInputSelection.hasSelectionCapabilities(focusedElem) ?
47
- ReactInputSelection.getSelection(focusedElem) :
48
- null,
43
+ selectionRange: ReactInputSelection.hasSelectionCapabilities(focusedElem)
44
+ ? ReactInputSelection.getSelection(focusedElem)
45
+ : null,
46
};
47
},
48
@@ -58,13 +55,9 @@ var ReactInputSelection = {
55
var curFocusedElem = getActiveElement();
56
var priorFocusedElem = priorSelectionInformation.focusedElem;
57
var priorSelectionRange = priorSelectionInformation.selectionRange;
61
- if (curFocusedElem !== priorFocusedElem &&
62
- isInDocument(priorFocusedElem)) {
58
+ if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {
59
if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) {
64
- ReactInputSelection.setSelection(
65
- priorFocusedElem,
66
- priorSelectionRange
67
- );
60
+ ReactInputSelection.setSelection(priorFocusedElem, priorSelectionRange);
61
}
62
63
// Focusing a node can change the scroll position, which is undesirable
@@ -105,8 +98,10 @@ var ReactInputSelection = {
98
start: input.selectionStart,
99
end: input.selectionEnd,
100
};
108
- } else if (document.selection &&
109
- (input.nodeName && input.nodeName.toLowerCase() === 'input')) {
101
+ } else if (
102
+ document.selection &&
103
+ (input.nodeName && input.nodeName.toLowerCase() === 'input')
104
+ ) {
105
// IE8 input.
106
var range = document.selection.createRange();
107
// There can only be one selection per document in IE, so it must
@@ -141,8 +136,10 @@ var ReactInputSelection = {
136
if ('selectionStart' in input) {
137
input.selectionStart = start;
138
input.selectionEnd = Math.min(end, input.value.length);
144
- } else if (document.selection &&
145
- (input.nodeName && input.nodeName.toLowerCase() === 'input')) {
139
+ } else if (
140
+ document.selection &&
141
+ (input.nodeName && input.nodeName.toLowerCase() === 'input')
142
+ ) {
143
var range = input.createTextRange();
144
range.collapse(true);
145
range.moveStart('character', start);
src/renderers/dom/shared/SVGDOMPropertyConfig.js
+1
-1
@@ -292,7 +292,7 @@ var SVGDOMPropertyConfig = {
292
DOMAttributeNames: {},
293
};
294
295
-Object.keys(ATTRS).forEach((key) => {
295
+Object.keys(ATTRS).forEach(key => {
296
SVGDOMPropertyConfig.Properties[key] = 0;
297
if (ATTRS[key]) {
298
SVGDOMPropertyConfig.DOMAttributeNames[key] = ATTRS[key];
src/renderers/dom/shared/__tests__/CSSProperty-test.js
-1
@@ -27,5 +27,4 @@ describe('CSSProperty', () => {
27
expect(CSSProperty.isUnitlessNumber.msGridRow).toBeTruthy();
28
expect(CSSProperty.isUnitlessNumber.msGridColumn).toBeTruthy();
29
});
30
-
30
});
src/renderers/dom/shared/__tests__/CSSPropertyOperations-test.js
+79
-56
@@ -24,48 +24,60 @@ describe('CSSPropertyOperations', () => {
24
});
25
26
it('should create markup for simple styles', () => {
27
- expect(CSSPropertyOperations.createMarkupForStyles({
28
- backgroundColor: '#3b5998',
29
- display: 'none',
30
- })).toBe('background-color:#3b5998;display:none;');
27
+ expect(
28
+ CSSPropertyOperations.createMarkupForStyles({
29
+ backgroundColor: '#3b5998',
30
+ display: 'none',
31
+ }),
32
+ ).toBe('background-color:#3b5998;display:none;');
33
});
34
35
it('should ignore undefined styles', () => {
34
- expect(CSSPropertyOperations.createMarkupForStyles({
35
- backgroundColor: undefined,
36
- display: 'none',
37
- })).toBe('display:none;');
36
+ expect(
37
+ CSSPropertyOperations.createMarkupForStyles({
38
+ backgroundColor: undefined,
39
+ display: 'none',
40
+ }),
41
+ ).toBe('display:none;');
42
});
43
44
it('should ignore null styles', () => {
41
- expect(CSSPropertyOperations.createMarkupForStyles({
42
- backgroundColor: null,
43
- display: 'none',
44
- })).toBe('display:none;');
45
+ expect(
46
+ CSSPropertyOperations.createMarkupForStyles({
47
+ backgroundColor: null,
48
+ display: 'none',
49
+ }),
50
+ ).toBe('display:none;');
51
});
52
53
it('should return null for no styles', () => {
48
- expect(CSSPropertyOperations.createMarkupForStyles({
49
- backgroundColor: null,
50
- display: null,
51
- })).toBe(null);
54
+ expect(
55
+ CSSPropertyOperations.createMarkupForStyles({
56
+ backgroundColor: null,
57
+ display: null,
58
+ }),
59
+ ).toBe(null);
60
});
61
62
it('should automatically append `px` to relevant styles', () => {
55
- expect(CSSPropertyOperations.createMarkupForStyles({
56
- left: 0,
57
- margin: 16,
58
- opacity: 0.5,
59
- padding: '4px',
60
- })).toBe('left:0;margin:16px;opacity:0.5;padding:4px;');
63
+ expect(
64
+ CSSPropertyOperations.createMarkupForStyles({
65
+ left: 0,
66
+ margin: 16,
67
+ opacity: 0.5,
68
+ padding: '4px',
69
+ }),
70
+ ).toBe('left:0;margin:16px;opacity:0.5;padding:4px;');
71
});
72
73
it('should trim values', () => {
64
- expect(CSSPropertyOperations.createMarkupForStyles({
65
- left: '16 ',
66
- opacity: 0.5,
67
- right: ' 4 ',
68
- })).toBe('left:16;opacity:0.5;right:4;');
74
+ expect(
75
+ CSSPropertyOperations.createMarkupForStyles({
76
+ left: '16 ',
77
+ opacity: 0.5,
78
+ right: ' 4 ',
79
+ }),
80
+ ).toBe('left:16;opacity:0.5;right:4;');
81
});
82
83
it('should not append `px` to styles that might need a number', () => {
@@ -74,16 +86,19 @@ describe('CSSPropertyOperations', () => {
86
unitlessProperties.forEach(function(property) {
87
var styles = {};
88
styles[property] = 1;
77
- expect(CSSPropertyOperations.createMarkupForStyles(styles))
78
- .toMatch(/:1;$/);
89
+ expect(CSSPropertyOperations.createMarkupForStyles(styles)).toMatch(
90
+ /:1;$/,
91
+ );
92
});
93
});
94
95
it('should create vendor-prefixed markup correctly', () => {
83
- expect(CSSPropertyOperations.createMarkupForStyles({
84
- msTransition: 'none',
85
- MozTransition: 'none',
86
- })).toBe('-ms-transition:none;-moz-transition:none;');
96
+ expect(
97
+ CSSPropertyOperations.createMarkupForStyles({
98
+ msTransition: 'none',
99
+ MozTransition: 'none',
100
+ }),
101
+ ).toBe('-ms-transition:none;-moz-transition:none;');
102
});
103
104
it('should set style attribute when styles exist', () => {
@@ -112,7 +127,7 @@ describe('CSSPropertyOperations', () => {
127
static displayName = 'Comp';
128
129
render() {
115
- return <div style={{ 'background-color': 'crimson' }} />;
130
+ return <div style={{'background-color': 'crimson'}} />;
131
}
132
}
133
@@ -122,7 +137,7 @@ describe('CSSPropertyOperations', () => {
137
expectDev(console.error.calls.count()).toBe(1);
138
expectDev(console.error.calls.argsFor(0)[0]).toEqual(
139
'Warning: Unsupported style property background-color. Did you mean backgroundColor?' +
125
- '\n\nCheck the render method of `Comp`.'
140
+ '\n\nCheck the render method of `Comp`.',
141
);
142
});
143
@@ -147,11 +162,11 @@ describe('CSSPropertyOperations', () => {
162
expectDev(console.error.calls.count()).toBe(2);
163
expectDev(console.error.calls.argsFor(0)[0]).toEqual(
164
'Warning: Unsupported style property -ms-transform. Did you mean msTransform?' +
150
- '\n\nCheck the render method of `Comp`.'
165
+ '\n\nCheck the render method of `Comp`.',
166
);
167
expectDev(console.error.calls.argsFor(1)[0]).toEqual(
168
'Warning: Unsupported style property -webkit-transform. Did you mean WebkitTransform?' +
154
- '\n\nCheck the render method of `Comp`.'
169
+ '\n\nCheck the render method of `Comp`.',
170
);
171
});
172
@@ -160,11 +175,15 @@ describe('CSSPropertyOperations', () => {
175
static displayName = 'Comp';
176
177
render() {
163
- return (<div style={{
164
- msTransform: 'translate3d(0, 0, 0)',
165
- oTransform: 'translate3d(0, 0, 0)',
166
- webkitTransform: 'translate3d(0, 0, 0)',
167
- }} />);
178
+ return (
179
+ <div
180
+ style={{
181
+ msTransform: 'translate3d(0, 0, 0)',
182
+ oTransform: 'translate3d(0, 0, 0)',
183
+ webkitTransform: 'translate3d(0, 0, 0)',
184
+ }}
185
+ />
186
+ );
187
}
188
}
189
@@ -175,11 +194,11 @@ describe('CSSPropertyOperations', () => {
194
expectDev(console.error.calls.count()).toBe(2);
195
expectDev(console.error.calls.argsFor(0)[0]).toEqual(
196
'Warning: Unsupported vendor-prefixed style property oTransform. ' +
178
- 'Did you mean OTransform?\n\nCheck the render method of `Comp`.'
197
+ 'Did you mean OTransform?\n\nCheck the render method of `Comp`.',
198
);
199
expectDev(console.error.calls.argsFor(1)[0]).toEqual(
200
'Warning: Unsupported vendor-prefixed style property webkitTransform. ' +
182
- 'Did you mean WebkitTransform?\n\nCheck the render method of `Comp`.'
201
+ 'Did you mean WebkitTransform?\n\nCheck the render method of `Comp`.',
202
);
203
});
204
@@ -188,12 +207,16 @@ describe('CSSPropertyOperations', () => {
207
static displayName = 'Comp';
208
209
render() {
191
- return (<div style={{
192
- fontFamily: 'Helvetica, arial',
193
- backgroundImage: 'url(foo;bar)',
194
- backgroundColor: 'blue;',
195
- color: 'red; ',
196
- }} />);
210
+ return (
211
+ <div
212
+ style={{
213
+ fontFamily: 'Helvetica, arial',
214
+ backgroundImage: 'url(foo;bar)',
215
+ backgroundColor: 'blue;',
216
+ color: 'red; ',
217
+ }}
218
+ />
219
+ );
220
}
221
}
222
@@ -202,12 +225,12 @@ describe('CSSPropertyOperations', () => {
225
ReactDOM.render(<Comp />, root);
226
expectDev(console.error.calls.count()).toBe(2);
227
expectDev(console.error.calls.argsFor(0)[0]).toEqual(
205
- 'Warning: Style property values shouldn\'t contain a semicolon.' +
206
- '\n\nCheck the render method of `Comp`. Try "backgroundColor: blue" instead.',
228
+ "Warning: Style property values shouldn't contain a semicolon." +
229
+ '\n\nCheck the render method of `Comp`. Try "backgroundColor: blue" instead.',
230
);
231
expectDev(console.error.calls.argsFor(1)[0]).toEqual(
209
- 'Warning: Style property values shouldn\'t contain a semicolon.' +
210
- '\n\nCheck the render method of `Comp`. Try "color: red" instead.',
232
+ "Warning: Style property values shouldn't contain a semicolon." +
233
+ '\n\nCheck the render method of `Comp`. Try "color: red" instead.',
234
);
235
});
236
@@ -216,7 +239,7 @@ describe('CSSPropertyOperations', () => {
239
static displayName = 'Comp';
240
241
render() {
219
- return <div style={{ fontSize: NaN }} />;
242
+ return <div style={{fontSize: NaN}} />;
243
}
244
}
245
@@ -227,7 +250,7 @@ describe('CSSPropertyOperations', () => {
250
expectDev(console.error.calls.count()).toBe(1);
251
expectDev(console.error.calls.argsFor(0)[0]).toEqual(
252
'Warning: `NaN` is an invalid value for the `fontSize` css style property.' +
230
- '\n\nCheck the render method of `Comp`.'
253
+ '\n\nCheck the render method of `Comp`.',
254
);
255
});
256
});
src/renderers/dom/shared/__tests__/DOMPropertyOperations-test.js
+136
-195
@@ -27,148 +27,118 @@ describe('DOMPropertyOperations', () => {
27
});
28
29
describe('createMarkupForProperty', () => {
30
-
30
it('should create markup for simple properties', () => {
32
- expect(DOMPropertyOperations.createMarkupForProperty(
33
- 'name',
34
- 'simple'
35
- )).toBe('name="simple"');
36
-
37
- expect(DOMPropertyOperations.createMarkupForProperty(
38
- 'name',
39
- false
40
- )).toBe('name="false"');
41
-
42
- expect(DOMPropertyOperations.createMarkupForProperty(
43
- 'name',
44
- null
45
- )).toBe('');
31
+ expect(
32
+ DOMPropertyOperations.createMarkupForProperty('name', 'simple'),
33
+ ).toBe('name="simple"');
34
+
35
+ expect(DOMPropertyOperations.createMarkupForProperty('name', false)).toBe(
36
+ 'name="false"',
37
+ );
38
+
39
+ expect(DOMPropertyOperations.createMarkupForProperty('name', null)).toBe(
40
+ '',
41
+ );
42
});
43
44
it('should work with the id attribute', () => {
49
- expect(DOMPropertyOperations.createMarkupForProperty(
50
- 'id',
51
- 'simple'
52
- )).toBe('id="simple"');
45
+ expect(
46
+ DOMPropertyOperations.createMarkupForProperty('id', 'simple'),
47
+ ).toBe('id="simple"');
48
});
49
50
it('should create markup for boolean properties', () => {
56
- expect(DOMPropertyOperations.createMarkupForProperty(
57
- 'checked',
58
- 'simple'
59
- )).toBe('checked=""');
60
-
61
- expect(DOMPropertyOperations.createMarkupForProperty(
62
- 'checked',
63
- true
64
- )).toBe('checked=""');
65
-
66
- expect(DOMPropertyOperations.createMarkupForProperty(
67
- 'checked',
68
- false
69
- )).toBe('');
70
-
71
- expect(DOMPropertyOperations.createMarkupForProperty(
72
- 'scoped',
73
- true
74
- )).toBe('scoped=""');
51
+ expect(
52
+ DOMPropertyOperations.createMarkupForProperty('checked', 'simple'),
53
+ ).toBe('checked=""');
54
+
55
+ expect(
56
+ DOMPropertyOperations.createMarkupForProperty('checked', true),
57
+ ).toBe('checked=""');
58
+
59
+ expect(
60
+ DOMPropertyOperations.createMarkupForProperty('checked', false),
61
+ ).toBe('');
62
+
63
+ expect(
64
+ DOMPropertyOperations.createMarkupForProperty('scoped', true),
65
+ ).toBe('scoped=""');
66
});
67
68
it('should create markup for booleanish properties', () => {
78
- expect(DOMPropertyOperations.createMarkupForProperty(
79
- 'download',
80
- 'simple'
81
- )).toBe('download="simple"');
82
-
83
- expect(DOMPropertyOperations.createMarkupForProperty(
84
- 'download',
85
- true
86
- )).toBe('download=""');
87
-
88
- expect(DOMPropertyOperations.createMarkupForProperty(
89
- 'download',
90
- 'true'
91
- )).toBe('download="true"');
92
-
93
- expect(DOMPropertyOperations.createMarkupForProperty(
94
- 'download',
95
- false
96
- )).toBe('');
97
-
98
- expect(DOMPropertyOperations.createMarkupForProperty(
99
- 'download',
100
- 'false'
101
- )).toBe('download="false"');
102
-
103
- expect(DOMPropertyOperations.createMarkupForProperty(
104
- 'download',
105
- undefined
106
- )).toBe('');
107
-
108
- expect(DOMPropertyOperations.createMarkupForProperty(
109
- 'download',
110
- null
111
- )).toBe('');
112
-
113
- expect(DOMPropertyOperations.createMarkupForProperty(
114
- 'download',
115
- 0
116
- )).toBe('download="0"');
69
+ expect(
70
+ DOMPropertyOperations.createMarkupForProperty('download', 'simple'),
71
+ ).toBe('download="simple"');
72
+
73
+ expect(
74
+ DOMPropertyOperations.createMarkupForProperty('download', true),
75
+ ).toBe('download=""');
76
+
77
+ expect(
78
+ DOMPropertyOperations.createMarkupForProperty('download', 'true'),
79
+ ).toBe('download="true"');
80
+
81
+ expect(
82
+ DOMPropertyOperations.createMarkupForProperty('download', false),
83
+ ).toBe('');
84
+
85
+ expect(
86
+ DOMPropertyOperations.createMarkupForProperty('download', 'false'),
87
+ ).toBe('download="false"');
88
+
89
+ expect(
90
+ DOMPropertyOperations.createMarkupForProperty('download', undefined),
91
+ ).toBe('');
92
+
93
+ expect(
94
+ DOMPropertyOperations.createMarkupForProperty('download', null),
95
+ ).toBe('');
96
+
97
+ expect(DOMPropertyOperations.createMarkupForProperty('download', 0)).toBe(
98
+ 'download="0"',
99
+ );
100
});
101
102
it('should create markup for custom attributes', () => {
120
- expect(DOMPropertyOperations.createMarkupForProperty(
121
- 'aria-label',
122
- 'simple'
123
- )).toBe('aria-label="simple"');
124
-
125
- expect(DOMPropertyOperations.createMarkupForProperty(
126
- 'aria-label',
127
- false
128
- )).toBe('aria-label="false"');
129
-
130
- expect(DOMPropertyOperations.createMarkupForProperty(
131
- 'aria-label',
132
- null
133
- )).toBe('');
103
+ expect(
104
+ DOMPropertyOperations.createMarkupForProperty('aria-label', 'simple'),
105
+ ).toBe('aria-label="simple"');
106
+
107
+ expect(
108
+ DOMPropertyOperations.createMarkupForProperty('aria-label', false),
109
+ ).toBe('aria-label="false"');
110
+
111
+ expect(
112
+ DOMPropertyOperations.createMarkupForProperty('aria-label', null),
113
+ ).toBe('');
114
});
115
116
it('should create markup for numeric properties', () => {
137
- expect(DOMPropertyOperations.createMarkupForProperty(
138
- 'start',
139
- 5
140
- )).toBe('start="5"');
141
-
142
- expect(DOMPropertyOperations.createMarkupForProperty(
143
- 'start',
144
- 0
145
- )).toBe('start="0"');
146
-
147
- expect(DOMPropertyOperations.createMarkupForProperty(
148
- 'size',
149
- 0
150
- )).toBe('');
151
-
152
- expect(DOMPropertyOperations.createMarkupForProperty(
153
- 'size',
154
- 1
155
- )).toBe('size="1"');
156
- });
117
+ expect(DOMPropertyOperations.createMarkupForProperty('start', 5)).toBe(
118
+ 'start="5"',
119
+ );
120
+
121
+ expect(DOMPropertyOperations.createMarkupForProperty('start', 0)).toBe(
122
+ 'start="0"',
123
+ );
124
+
125
+ expect(DOMPropertyOperations.createMarkupForProperty('size', 0)).toBe('');
126
127
+ expect(DOMPropertyOperations.createMarkupForProperty('size', 1)).toBe(
128
+ 'size="1"',
129
+ );
130
+ });
131
});
132
133
describe('createMarkupForProperty', () => {
161
-
134
it('should allow custom properties on web components', () => {
163
- expect(DOMPropertyOperations.createMarkupForCustomAttribute(
164
- 'awesomeness',
165
- 5
166
- )).toBe('awesomeness="5"');
167
-
168
- expect(DOMPropertyOperations.createMarkupForCustomAttribute(
169
- 'dev',
170
- 'jim'
171
- )).toBe('dev="jim"');
135
+ expect(
136
+ DOMPropertyOperations.createMarkupForCustomAttribute('awesomeness', 5),
137
+ ).toBe('awesomeness="5"');
138
+
139
+ expect(
140
+ DOMPropertyOperations.createMarkupForCustomAttribute('dev', 'jim'),
141
+ ).toBe('dev="jim"');
142
});
143
});
144
@@ -198,15 +168,22 @@ describe('DOMPropertyOperations', () => {
168
DOMPropertyOperations.setValueForProperty(
169
stubNode,
170
'xlinkHref',
201
- 'about:blank'
171
+ 'about:blank',
172
);
173
expect(stubNode.setAttributeNS.calls.count()).toBe(1);
204
- expect(stubNode.setAttributeNS.calls.argsFor(0))
205
- .toEqual(['http://www.w3.org/1999/xlink', 'xlink:href', 'about:blank']);
174
+ expect(stubNode.setAttributeNS.calls.argsFor(0)).toEqual([
175
+ 'http://www.w3.org/1999/xlink',
176
+ 'xlink:href',
177
+ 'about:blank',
178
+ ]);
179
});
180
181
it('should set values as boolean properties', () => {
209
- DOMPropertyOperations.setValueForProperty(stubNode, 'disabled', 'disabled');
182
+ DOMPropertyOperations.setValueForProperty(
183
+ stubNode,
184
+ 'disabled',
185
+ 'disabled',
186
+ );
187
expect(stubNode.getAttribute('disabled')).toBe('');
188
DOMPropertyOperations.setValueForProperty(stubNode, 'disabled', true);
189
expect(stubNode.getAttribute('disabled')).toBe('');
@@ -240,23 +217,15 @@ describe('DOMPropertyOperations', () => {
217
DOMPropertyOperations.setValueForProperty(
218
stubNode,
219
'allowFullScreen',
243
- false
220
+ false,
221
);
222
expect(stubNode.hasAttribute('allowFullScreen')).toBe(false);
223
});
224
225
it('should remove when setting custom attr to null', () => {
249
- DOMPropertyOperations.setValueForProperty(
250
- stubNode,
251
- 'data-foo',
252
- 'bar'
253
- );
226
+ DOMPropertyOperations.setValueForProperty(stubNode, 'data-foo', 'bar');
227
expect(stubNode.hasAttribute('data-foo')).toBe(true);
255
- DOMPropertyOperations.setValueForProperty(
256
- stubNode,
257
- 'data-foo',
258
- null
259
- );
228
+ DOMPropertyOperations.setValueForProperty(stubNode, 'data-foo', null);
229
expect(stubNode.hasAttribute('data-foo')).toBe(false);
230
});
231
@@ -273,7 +242,7 @@ describe('DOMPropertyOperations', () => {
242
DOMPropertyOperations.setValueForProperty(
243
stubNode,
244
'foobar',
276
- 'cows say moo'
245
+ 'cows say moo',
246
);
247
248
expect(foobarSetter.mock.calls.length).toBe(1);
@@ -285,15 +254,11 @@ describe('DOMPropertyOperations', () => {
254
DOMPropertyOperations.setValueForProperty(
255
stubNode,
256
'className',
288
- 'selected'
257
+ 'selected',
258
);
259
expect(stubNode.className).toBe('selected');
260
292
- DOMPropertyOperations.setValueForProperty(
293
- stubNode,
294
- 'className',
295
- null
296
- );
261
+ DOMPropertyOperations.setValueForProperty(stubNode, 'className', null);
262
// className should be '', not 'null' or null (which becomes 'null' in
263
// some browsers)
264
expect(stubNode.className).toBe('');
@@ -301,18 +266,10 @@ describe('DOMPropertyOperations', () => {
266
});
267
268
it('should remove property properly for boolean properties', () => {
304
- DOMPropertyOperations.setValueForProperty(
305
- stubNode,
306
- 'hidden',
307
- true
308
- );
269
+ DOMPropertyOperations.setValueForProperty(stubNode, 'hidden', true);
270
expect(stubNode.hasAttribute('hidden')).toBe(true);
271
311
- DOMPropertyOperations.setValueForProperty(
312
- stubNode,
313
- 'hidden',
314
- false
315
- );
272
+ DOMPropertyOperations.setValueForProperty(stubNode, 'hidden', false);
273
expect(stubNode.hasAttribute('hidden')).toBe(false);
274
});
275
@@ -329,23 +286,14 @@ describe('DOMPropertyOperations', () => {
286
},
287
});
288
332
- DOMPropertyOperations.setValueForProperty(
333
- stubNode,
334
- 'foobar',
335
- 'selected'
336
- );
289
+ DOMPropertyOperations.setValueForProperty(stubNode, 'foobar', 'selected');
290
expect(stubNode.className).toBe('selected');
291
339
- DOMPropertyOperations.setValueForProperty(
340
- stubNode,
341
- 'foobar',
342
- null
343
- );
292
+ DOMPropertyOperations.setValueForProperty(stubNode, 'foobar', null);
293
// className should be '', not 'null' or null (which becomes 'null' in
294
// some browsers)
295
expect(stubNode.className).toBe('');
296
});
348
-
297
});
298
299
describe('deleteValueForProperty', () => {
@@ -395,26 +343,23 @@ describe('DOMPropertyOperations', () => {
343
expect(stubNode.getAttribute('multiple')).toBe(null);
344
expect(stubNode.multiple).toBe(false);
345
398
- expect(
399
- stubNode.options[0].selected &&
400
- stubNode.options[1].selected
401
- ).toBe(false);
346
+ expect(stubNode.options[0].selected && stubNode.options[1].selected).toBe(
347
+ false,
348
+ );
349
});
350
});
351
352
describe('injectDOMPropertyConfig', () => {
353
it('should support custom attributes', () => {
354
// foobar does not exist yet
408
- expect(DOMPropertyOperations.createMarkupForProperty(
409
- 'foobar',
410
- 'simple'
411
- )).toBe(null);
355
+ expect(
356
+ DOMPropertyOperations.createMarkupForProperty('foobar', 'simple'),
357
+ ).toBe(null);
358
359
// foo-* does not exist yet
414
- expect(DOMPropertyOperations.createMarkupForProperty(
415
- 'foo-xyz',
416
- 'simple'
417
- )).toBe(null);
360
+ expect(
361
+ DOMPropertyOperations.createMarkupForProperty('foo-xyz', 'simple'),
362
+ ).toBe(null);
363
364
// inject foobar DOM property
365
DOMProperty.injection.injectDOMPropertyConfig({
@@ -425,32 +370,28 @@ describe('DOMPropertyOperations', () => {
370
});
371
372
// Ensure old attributes still work
428
- expect(DOMPropertyOperations.createMarkupForProperty(
429
- 'name',
430
- 'simple'
431
- )).toBe('name="simple"');
432
- expect(DOMPropertyOperations.createMarkupForProperty(
433
- 'data-name',
434
- 'simple'
435
- )).toBe('data-name="simple"');
373
+ expect(
374
+ DOMPropertyOperations.createMarkupForProperty('name', 'simple'),
375
+ ).toBe('name="simple"');
376
+ expect(
377
+ DOMPropertyOperations.createMarkupForProperty('data-name', 'simple'),
378
+ ).toBe('data-name="simple"');
379
380
// foobar should work
438
- expect(DOMPropertyOperations.createMarkupForProperty(
439
- 'foobar',
440
- 'simple'
441
- )).toBe('foobar="simple"');
381
+ expect(
382
+ DOMPropertyOperations.createMarkupForProperty('foobar', 'simple'),
383
+ ).toBe('foobar="simple"');
384
385
// foo-* should work
444
- expect(DOMPropertyOperations.createMarkupForProperty(
445
- 'foo-xyz',
446
- 'simple'
447
- )).toBe('foo-xyz="simple"');
386
+ expect(
387
+ DOMPropertyOperations.createMarkupForProperty('foo-xyz', 'simple'),
388
+ ).toBe('foo-xyz="simple"');
389
390
// It should complain about double injections.
391
expect(function() {
451
- DOMProperty.injection.injectDOMPropertyConfig(
452
- {Properties: {foobar: null}}
453
- );
392
+ DOMProperty.injection.injectDOMPropertyConfig({
393
+ Properties: {foobar: null},
394
+ });
395
}).toThrow();
396
});
397
});
src/renderers/dom/shared/__tests__/ReactBrowserEventEmitter-test.js
+76
-219
@@ -76,7 +76,7 @@ describe('ReactBrowserEventEmitter', () => {
76
var CHILD_PROPS = {};
77
78
function Child(props) {
79
- return <div ref={(c) => CHILD = c} {...props} />;
79
+ return <div ref={c => CHILD = c} {...props} />;
80
}
81
82
class ChildWrapper extends React.PureComponent {
@@ -87,12 +87,12 @@ describe('ReactBrowserEventEmitter', () => {
87
88
function renderTree() {
89
ReactDOM.render(
90
- <div ref={(c) => GRANDPARENT = c} {...GRANDPARENT_PROPS}>
91
- <div ref={(c) => PARENT = c} {...PARENT_PROPS}>
90
+ <div ref={c => GRANDPARENT = c} {...GRANDPARENT_PROPS}>
91
+ <div ref={c => PARENT = c} {...PARENT_PROPS}>
92
<ChildWrapper {...CHILD_PROPS} />
93
</div>
94
</div>,
95
- container
95
+ container,
96
);
97
}
98
@@ -100,10 +100,7 @@ describe('ReactBrowserEventEmitter', () => {
100
101
getListener = function(node, eventName) {
102
var inst = ReactDOMComponentTree.getInstanceFromNode(node);
103
- return EventPluginHub.getListener(
104
- inst,
105
- eventName
106
- );
103
+ return EventPluginHub.getListener(inst, eventName);
104
};
105
putListener = function(node, eventName, listener) {
106
switch (node) {
@@ -167,35 +164,20 @@ describe('ReactBrowserEventEmitter', () => {
164
expect(LISTENER.mock.calls.length).toBe(1);
165
});
166
170
- it(
171
- 'should not invoke handlers if ReactBrowserEventEmitter is disabled',
172
- () => {
173
- registerSimpleTestHandler();
174
- ReactBrowserEventEmitter.setEnabled(false);
175
- ReactTestUtils.SimulateNative.click(CHILD);
176
- expect(LISTENER.mock.calls.length).toBe(0);
177
- ReactBrowserEventEmitter.setEnabled(true);
178
- ReactTestUtils.SimulateNative.click(CHILD);
179
- expect(LISTENER.mock.calls.length).toBe(1);
180
- }
181
- );
167
+ it('should not invoke handlers if ReactBrowserEventEmitter is disabled', () => {
168
+ registerSimpleTestHandler();
169
+ ReactBrowserEventEmitter.setEnabled(false);
170
+ ReactTestUtils.SimulateNative.click(CHILD);
171
+ expect(LISTENER.mock.calls.length).toBe(0);
172
+ ReactBrowserEventEmitter.setEnabled(true);
173
+ ReactTestUtils.SimulateNative.click(CHILD);
174
+ expect(LISTENER.mock.calls.length).toBe(1);
175
+ });
176
177
it('should bubble simply', () => {
184
- putListener(
185
- CHILD,
186
- ON_CLICK_KEY,
187
- recordID.bind(null, CHILD)
188
- );
189
- putListener(
190
- PARENT,
191
- ON_CLICK_KEY,
192
- recordID.bind(null, PARENT)
193
- );
194
- putListener(
195
- GRANDPARENT,
196
- ON_CLICK_KEY,
197
- recordID.bind(null, GRANDPARENT)
198
- );
178
+ putListener(CHILD, ON_CLICK_KEY, recordID.bind(null, CHILD));
179
+ putListener(PARENT, ON_CLICK_KEY, recordID.bind(null, PARENT));
180
+ putListener(GRANDPARENT, ON_CLICK_KEY, recordID.bind(null, GRANDPARENT));
181
ReactTestUtils.Simulate.click(CHILD);
182
expect(idCallOrder.length).toBe(3);
183
expect(idCallOrder[0]).toBe(CHILD);
@@ -204,27 +186,11 @@ describe('ReactBrowserEventEmitter', () => {
186
});
187
188
it('should bubble to the right handler after an update', () => {
207
- putListener(
208
- GRANDPARENT,
209
- ON_CLICK_KEY,
210
- recordID.bind(null, 'GRANDPARENT')
211
- );
212
- putListener(
213
- PARENT,
214
- ON_CLICK_KEY,
215
- recordID.bind(null, 'PARENT')
216
- );
217
- putListener(
218
- CHILD,
219
- ON_CLICK_KEY,
220
- recordID.bind(null, 'CHILD')
221
- );
189
+ putListener(GRANDPARENT, ON_CLICK_KEY, recordID.bind(null, 'GRANDPARENT'));
190
+ putListener(PARENT, ON_CLICK_KEY, recordID.bind(null, 'PARENT'));
191
+ putListener(CHILD, ON_CLICK_KEY, recordID.bind(null, 'CHILD'));
192
ReactTestUtils.Simulate.click(CHILD);
223
- expect(idCallOrder).toEqual([
224
- 'CHILD',
225
- 'PARENT',
226
- 'GRANDPARENT',
227
- ]);
193
+ expect(idCallOrder).toEqual(['CHILD', 'PARENT', 'GRANDPARENT']);
194
195
idCallOrder = [];
196
@@ -232,36 +198,20 @@ describe('ReactBrowserEventEmitter', () => {
198
putListener(
199
GRANDPARENT,
200
ON_CLICK_KEY,
235
- recordID.bind(null, 'UPDATED_GRANDPARENT')
201
+ recordID.bind(null, 'UPDATED_GRANDPARENT'),
202
);
203
204
ReactTestUtils.Simulate.click(CHILD);
239
- expect(idCallOrder).toEqual([
240
- 'CHILD',
241
- 'PARENT',
242
- 'UPDATED_GRANDPARENT',
243
- ]);
205
+ expect(idCallOrder).toEqual(['CHILD', 'PARENT', 'UPDATED_GRANDPARENT']);
206
});
207
208
it('should continue bubbling if an error is thrown', () => {
247
- putListener(
248
- CHILD,
249
- ON_CLICK_KEY,
250
- recordID.bind(null, CHILD)
251
- );
252
- putListener(
253
- PARENT,
254
- ON_CLICK_KEY,
255
- function() {
256
- recordID(PARENT);
257
- throw new Error('Handler interrupted');
258
- }
259
- );
260
- putListener(
261
- GRANDPARENT,
262
- ON_CLICK_KEY,
263
- recordID.bind(null, GRANDPARENT)
264
- );
209
+ putListener(CHILD, ON_CLICK_KEY, recordID.bind(null, CHILD));
210
+ putListener(PARENT, ON_CLICK_KEY, function() {
211
+ recordID(PARENT);
212
+ throw new Error('Handler interrupted');
213
+ });
214
+ putListener(GRANDPARENT, ON_CLICK_KEY, recordID.bind(null, GRANDPARENT));
215
expect(function() {
216
ReactTestUtils.Simulate.click(CHILD);
217
}).toThrow();
@@ -272,30 +222,18 @@ describe('ReactBrowserEventEmitter', () => {
222
});
223
224
it('should set currentTarget', () => {
275
- putListener(
276
- CHILD,
277
- ON_CLICK_KEY,
278
- function(event) {
279
- recordID(CHILD);
280
- expect(event.currentTarget).toBe(CHILD);
281
- }
282
- );
283
- putListener(
284
- PARENT,
285
- ON_CLICK_KEY,
286
- function(event) {
287
- recordID(PARENT);
288
- expect(event.currentTarget).toBe(PARENT);
289
- }
290
- );
291
- putListener(
292
- GRANDPARENT,
293
- ON_CLICK_KEY,
294
- function(event) {
295
- recordID(GRANDPARENT);
296
- expect(event.currentTarget).toBe(GRANDPARENT);
297
- }
298
- );
225
+ putListener(CHILD, ON_CLICK_KEY, function(event) {
226
+ recordID(CHILD);
227
+ expect(event.currentTarget).toBe(CHILD);
228
+ });
229
+ putListener(PARENT, ON_CLICK_KEY, function(event) {
230
+ recordID(PARENT);
231
+ expect(event.currentTarget).toBe(PARENT);
232
+ });
233
+ putListener(GRANDPARENT, ON_CLICK_KEY, function(event) {
234
+ recordID(GRANDPARENT);
235
+ expect(event.currentTarget).toBe(GRANDPARENT);
236
+ });
237
ReactTestUtils.Simulate.click(CHILD);
238
expect(idCallOrder.length).toBe(3);
239
expect(idCallOrder[0]).toBe(CHILD);
@@ -304,21 +242,13 @@ describe('ReactBrowserEventEmitter', () => {
242
});
243
244
it('should support stopPropagation()', () => {
307
- putListener(
308
- CHILD,
309
- ON_CLICK_KEY,
310
- recordID.bind(null, CHILD)
311
- );
245
+ putListener(CHILD, ON_CLICK_KEY, recordID.bind(null, CHILD));
246
putListener(
247
PARENT,
248
ON_CLICK_KEY,
315
- recordIDAndStopPropagation.bind(null, PARENT)
316
- );
317
- putListener(
318
- GRANDPARENT,
319
- ON_CLICK_KEY,
320
- recordID.bind(null, GRANDPARENT)
249
+ recordIDAndStopPropagation.bind(null, PARENT),
250
);
251
+ putListener(GRANDPARENT, ON_CLICK_KEY, recordID.bind(null, GRANDPARENT));
252
ReactTestUtils.Simulate.click(CHILD);
253
expect(idCallOrder.length).toBe(2);
254
expect(idCallOrder[0]).toBe(CHILD);
@@ -327,25 +257,13 @@ describe('ReactBrowserEventEmitter', () => {
257
258
it('should support overriding .isPropagationStopped()', () => {
259
// Ew. See D4504876.
330
- putListener(
331
- CHILD,
332
- ON_CLICK_KEY,
333
- recordID.bind(null, CHILD)
334
- );
335
- putListener(
336
- PARENT,
337
- ON_CLICK_KEY,
338
- function(e) {
339
- recordID(PARENT, e);
340
- // This stops React bubbling but avoids touching the native event
341
- e.isPropagationStopped = () => true;
342
- }
343
- );
344
- putListener(
345
- GRANDPARENT,
346
- ON_CLICK_KEY,
347
- recordID.bind(null, GRANDPARENT)
348
- );
260
+ putListener(CHILD, ON_CLICK_KEY, recordID.bind(null, CHILD));
261
+ putListener(PARENT, ON_CLICK_KEY, function(e) {
262
+ recordID(PARENT, e);
263
+ // This stops React bubbling but avoids touching the native event
264
+ e.isPropagationStopped = () => true;
265
+ });
266
+ putListener(GRANDPARENT, ON_CLICK_KEY, recordID.bind(null, GRANDPARENT));
267
ReactTestUtils.Simulate.click(CHILD);
268
expect(idCallOrder.length).toBe(2);
269
expect(idCallOrder[0]).toBe(CHILD);
@@ -356,39 +274,19 @@ describe('ReactBrowserEventEmitter', () => {
274
putListener(
275
CHILD,
276
ON_CLICK_KEY,
359
- recordIDAndStopPropagation.bind(null, CHILD)
360
- );
361
- putListener(
362
- PARENT,
363
- ON_CLICK_KEY,
364
- recordID.bind(null, PARENT)
365
- );
366
- putListener(
367
- GRANDPARENT,
368
- ON_CLICK_KEY,
369
- recordID.bind(null, GRANDPARENT)
277
+ recordIDAndStopPropagation.bind(null, CHILD),
278
);
279
+ putListener(PARENT, ON_CLICK_KEY, recordID.bind(null, PARENT));
280
+ putListener(GRANDPARENT, ON_CLICK_KEY, recordID.bind(null, GRANDPARENT));
281
ReactTestUtils.Simulate.click(CHILD);
282
expect(idCallOrder.length).toBe(1);
283
expect(idCallOrder[0]).toBe(CHILD);
284
});
285
286
it('should not stopPropagation if false is returned', () => {
377
- putListener(
378
- CHILD,
379
- ON_CLICK_KEY,
380
- recordIDAndReturnFalse.bind(null, CHILD)
381
- );
382
- putListener(
383
- PARENT,
384
- ON_CLICK_KEY,
385
- recordID.bind(null, PARENT)
386
- );
387
- putListener(
388
- GRANDPARENT,
389
- ON_CLICK_KEY,
390
- recordID.bind(null, GRANDPARENT)
391
- );
287
+ putListener(CHILD, ON_CLICK_KEY, recordIDAndReturnFalse.bind(null, CHILD));
288
+ putListener(PARENT, ON_CLICK_KEY, recordID.bind(null, PARENT));
289
+ putListener(GRANDPARENT, ON_CLICK_KEY, recordID.bind(null, GRANDPARENT));
290
spyOn(console, 'error');
291
ReactTestUtils.Simulate.click(CHILD);
292
expect(idCallOrder.length).toBe(3);
@@ -412,16 +310,8 @@ describe('ReactBrowserEventEmitter', () => {
310
var handleChildClick = function(event) {
311
deleteAllListeners(PARENT);
312
};
415
- putListener(
416
- CHILD,
417
- ON_CLICK_KEY,
418
- handleChildClick
419
- );
420
- putListener(
421
- PARENT,
422
- ON_CLICK_KEY,
423
- handleParentClick
424
- );
313
+ putListener(CHILD, ON_CLICK_KEY, handleChildClick);
314
+ putListener(PARENT, ON_CLICK_KEY, handleParentClick);
315
ReactTestUtils.Simulate.click(CHILD);
316
expect(handleParentClick.mock.calls.length).toBe(1);
317
});
@@ -429,81 +319,57 @@ describe('ReactBrowserEventEmitter', () => {
319
it('should not invoke newly inserted handlers while bubbling', () => {
320
var handleParentClick = jest.fn();
321
var handleChildClick = function(event) {
432
- putListener(
433
- PARENT,
434
- ON_CLICK_KEY,
435
- handleParentClick
436
- );
322
+ putListener(PARENT, ON_CLICK_KEY, handleParentClick);
323
};
438
- putListener(
439
- CHILD,
440
- ON_CLICK_KEY,
441
- handleChildClick
442
- );
324
+ putListener(CHILD, ON_CLICK_KEY, handleChildClick);
325
ReactTestUtils.Simulate.click(CHILD);
326
expect(handleParentClick.mock.calls.length).toBe(0);
327
});
328
329
it('should have mouse enter simulated by test utils', () => {
448
- putListener(
449
- CHILD,
450
- ON_MOUSE_ENTER_KEY,
451
- recordID.bind(null, CHILD)
452
- );
330
+ putListener(CHILD, ON_MOUSE_ENTER_KEY, recordID.bind(null, CHILD));
331
ReactTestUtils.Simulate.mouseEnter(CHILD);
332
expect(idCallOrder.length).toBe(1);
333
expect(idCallOrder[0]).toBe(CHILD);
334
});
335
336
it('should infer onTouchTap from a touchStart/End', () => {
459
- putListener(
460
- CHILD,
461
- ON_TOUCH_TAP_KEY,
462
- recordID.bind(null, CHILD)
463
- );
337
+ putListener(CHILD, ON_TOUCH_TAP_KEY, recordID.bind(null, CHILD));
338
ReactTestUtils.SimulateNative.touchStart(
339
CHILD,
466
- ReactTestUtils.nativeTouchData(0, 0)
340
+ ReactTestUtils.nativeTouchData(0, 0),
341
);
342
ReactTestUtils.SimulateNative.touchEnd(
343
CHILD,
470
- ReactTestUtils.nativeTouchData(0, 0)
344
+ ReactTestUtils.nativeTouchData(0, 0),
345
);
346
expect(idCallOrder.length).toBe(1);
347
expect(idCallOrder[0]).toBe(CHILD);
348
});
349
350
it('should infer onTouchTap from when dragging below threshold', () => {
477
- putListener(
478
- CHILD,
479
- ON_TOUCH_TAP_KEY,
480
- recordID.bind(null, CHILD)
481
- );
351
+ putListener(CHILD, ON_TOUCH_TAP_KEY, recordID.bind(null, CHILD));
352
ReactTestUtils.SimulateNative.touchStart(
353
CHILD,
484
- ReactTestUtils.nativeTouchData(0, 0)
354
+ ReactTestUtils.nativeTouchData(0, 0),
355
);
356
ReactTestUtils.SimulateNative.touchEnd(
357
CHILD,
488
- ReactTestUtils.nativeTouchData(0, tapMoveThreshold - 1)
358
+ ReactTestUtils.nativeTouchData(0, tapMoveThreshold - 1),
359
);
360
expect(idCallOrder.length).toBe(1);
361
expect(idCallOrder[0]).toBe(CHILD);
362
});
363
364
it('should not onTouchTap from when dragging beyond threshold', () => {
495
- putListener(
496
- CHILD,
497
- ON_TOUCH_TAP_KEY,
498
- recordID.bind(null, CHILD)
499
- );
365
+ putListener(CHILD, ON_TOUCH_TAP_KEY, recordID.bind(null, CHILD));
366
ReactTestUtils.SimulateNative.touchStart(
367
CHILD,
502
- ReactTestUtils.nativeTouchData(0, 0)
368
+ ReactTestUtils.nativeTouchData(0, 0),
369
);
370
ReactTestUtils.SimulateNative.touchEnd(
371
CHILD,
506
- ReactTestUtils.nativeTouchData(0, tapMoveThreshold + 1)
372
+ ReactTestUtils.nativeTouchData(0, tapMoveThreshold + 1),
373
);
374
expect(idCallOrder.length).toBe(0);
375
});
@@ -549,28 +415,20 @@ describe('ReactBrowserEventEmitter', () => {
415
});
416
417
it('should bubble onTouchTap', () => {
552
- putListener(
553
- CHILD,
554
- ON_TOUCH_TAP_KEY,
555
- recordID.bind(null, CHILD)
556
- );
557
- putListener(
558
- PARENT,
559
- ON_TOUCH_TAP_KEY,
560
- recordID.bind(null, PARENT)
561
- );
418
+ putListener(CHILD, ON_TOUCH_TAP_KEY, recordID.bind(null, CHILD));
419
+ putListener(PARENT, ON_TOUCH_TAP_KEY, recordID.bind(null, PARENT));
420
putListener(
421
GRANDPARENT,
422
ON_TOUCH_TAP_KEY,
565
- recordID.bind(null, GRANDPARENT)
423
+ recordID.bind(null, GRANDPARENT),
424
);
425
ReactTestUtils.SimulateNative.touchStart(
426
CHILD,
569
- ReactTestUtils.nativeTouchData(0, 0)
427
+ ReactTestUtils.nativeTouchData(0, 0),
428
);
429
ReactTestUtils.SimulateNative.touchEnd(
430
CHILD,
573
- ReactTestUtils.nativeTouchData(0, 0)
431
+ ReactTestUtils.nativeTouchData(0, 0),
432
);
433
expect(idCallOrder.length).toBe(3);
434
expect(idCallOrder[0] === CHILD).toBe(true);
@@ -593,5 +451,4 @@ describe('ReactBrowserEventEmitter', () => {
451
document.createEvent = originalCreateEvent;
452
}
453
});
596
-
454
});
src/renderers/dom/shared/__tests__/ReactDOM-test.js
+23
-26
@@ -53,7 +53,7 @@ describe('ReactDOM', () => {
53
54
it('should allow children to be passed as an argument', () => {
55
var argDiv = ReactTestUtils.renderIntoDocument(
56
- React.DOM.div(null, 'child')
56
+ React.DOM.div(null, 'child'),
57
);
58
var argNode = ReactDOM.findDOMNode(argDiv);
59
expect(argNode.innerHTML).toBe('child');
@@ -61,7 +61,7 @@ describe('ReactDOM', () => {
61
62
it('should overwrite props.children with children argument', () => {
63
var conflictDiv = ReactTestUtils.renderIntoDocument(
64
- React.DOM.div({children: 'fakechild'}, 'child')
64
+ React.DOM.div({children: 'fakechild'}, 'child'),
65
);
66
var conflictNode = ReactDOM.findDOMNode(conflictDiv);
67
expect(conflictNode.innerHTML).toBe('child');
@@ -76,34 +76,34 @@ describe('ReactDOM', () => {
76
<div>
77
<div key="theDog" className="dog" />,
78
<div key="theBird" className="bird" />
79
- </div>
79
+ </div>,
80
);
81
// Warm the cache with theDog
82
myDiv = ReactTestUtils.renderIntoDocument(
83
<div>
84
<div key="theDog" className="dogbeforedelete" />,
85
<div key="theBird" className="bird" />,
86
- </div>
86
+ </div>,
87
);
88
// Remove theDog - this should purge the cache
89
myDiv = ReactTestUtils.renderIntoDocument(
90
<div>
91
<div key="theBird" className="bird" />,
92
- </div>
92
+ </div>,
93
);
94
// Now, put theDog back. It's now a different DOM node.
95
myDiv = ReactTestUtils.renderIntoDocument(
96
<div>
97
<div key="theDog" className="dog" />,
98
<div key="theBird" className="bird" />,
99
- </div>
99
+ </div>,
100
);
101
// Change the className of theDog. It will use the same element
102
myDiv = ReactTestUtils.renderIntoDocument(
103
<div>
104
<div key="theDog" className="bigdog" />,
105
<div key="theBird" className="bird" />,
106
- </div>
106
+ </div>,
107
);
108
var root = ReactDOM.findDOMNode(myDiv);
109
var dog = root.childNodes[0];
@@ -136,27 +136,27 @@ describe('ReactDOM', () => {
136
var myDiv = document.createElement('div');
137
expect(() => ReactDOM.render(<A />, myDiv, 'no')).toThrowError(
138
'Invalid argument passed as callback. Expected a function. Instead ' +
139
- 'received: no',
139
+ 'received: no',
140
);
141
expectDev(console.error.calls.argsFor(0)[0]).toContain(
142
'render(...): Expected the last optional `callback` argument to be ' +
143
- 'a function. Instead received: no.'
143
+ 'a function. Instead received: no.',
144
);
145
expect(() => ReactDOM.render(<A />, myDiv, {foo: 'bar'})).toThrowError(
146
'Invalid argument passed as callback. Expected a function. Instead ' +
147
- 'received: [object Object]',
147
+ 'received: [object Object]',
148
);
149
expectDev(console.error.calls.argsFor(1)[0]).toContain(
150
'render(...): Expected the last optional `callback` argument to be ' +
151
- 'a function. Instead received: [object Object].'
151
+ 'a function. Instead received: [object Object].',
152
);
153
expect(() => ReactDOM.render(<A />, myDiv, new Foo())).toThrowError(
154
'Invalid argument passed as callback. Expected a function. Instead ' +
155
- 'received: [object Object]',
155
+ 'received: [object Object]',
156
);
157
expectDev(console.error.calls.argsFor(2)[0]).toContain(
158
'render(...): Expected the last optional `callback` argument to be ' +
159
- 'a function. Instead received: [object Object].'
159
+ 'a function. Instead received: [object Object].',
160
);
161
expect(console.error.calls.count()).toBe(3);
162
});
@@ -181,29 +181,29 @@ describe('ReactDOM', () => {
181
ReactDOM.render(<A />, myDiv);
182
expect(() => ReactDOM.render(<A />, myDiv, 'no')).toThrowError(
183
'Invalid argument passed as callback. Expected a function. Instead ' +
184
- 'received: no',
184
+ 'received: no',
185
);
186
expectDev(console.error.calls.argsFor(0)[0]).toContain(
187
'render(...): Expected the last optional `callback` argument to be ' +
188
- 'a function. Instead received: no.'
188
+ 'a function. Instead received: no.',
189
);
190
ReactDOM.render(<A />, myDiv); // Re-mount
191
expect(() => ReactDOM.render(<A />, myDiv, {foo: 'bar'})).toThrowError(
192
'Invalid argument passed as callback. Expected a function. Instead ' +
193
- 'received: [object Object]',
193
+ 'received: [object Object]',
194
);
195
expectDev(console.error.calls.argsFor(1)[0]).toContain(
196
'render(...): Expected the last optional `callback` argument to be ' +
197
- 'a function. Instead received: [object Object].'
197
+ 'a function. Instead received: [object Object].',
198
);
199
ReactDOM.render(<A />, myDiv); // Re-mount
200
expect(() => ReactDOM.render(<A />, myDiv, new Foo())).toThrowError(
201
'Invalid argument passed as callback. Expected a function. Instead ' +
202
- 'received: [object Object]',
202
+ 'received: [object Object]',
203
);
204
expectDev(console.error.calls.argsFor(2)[0]).toContain(
205
'render(...): Expected the last optional `callback` argument to be ' +
206
- 'a function. Instead received: [object Object].'
206
+ 'a function. Instead received: [object Object].',
207
);
208
expect(console.error.calls.count()).toBe(3);
209
});
@@ -215,9 +215,9 @@ describe('ReactDOM', () => {
215
render() {
216
return (
217
<div>
218
- <input id="one" ref={(r) => input = input || r} />
218
+ <input id="one" ref={r => input = input || r} />
219
{this.props.showTwo &&
220
- <input id="two" ref={(r) => input2 = input2 || r} />}
220
+ <input id="two" ref={r => input2 = input2 || r} />}
221
</div>
222
);
223
}
@@ -242,7 +242,7 @@ describe('ReactDOM', () => {
242
// deterministically force without relying intensely on React DOM
243
// implementation details)
244
var div = container.firstChild;
245
- ['appendChild', 'insertBefore'].forEach((name) => {
245
+ ['appendChild', 'insertBefore'].forEach(name => {
246
var mutator = div[name];
247
div[name] = function() {
248
if (input) {
@@ -260,10 +260,7 @@ describe('ReactDOM', () => {
260
// componentDidUpdate focuses input2 and that should make it down to here,
261
// not get overwritten by focus restoration.
262
expect(document.activeElement.id).toBe('two');
263
- expect(log).toEqual([
264
- 'input2 inserted',
265
- 'input2 focused',
266
- ]);
263
+ expect(log).toEqual(['input2 inserted', 'input2 focused']);
264
document.body.removeChild(container);
265
});
266
src/renderers/dom/shared/__tests__/ReactDOMComponent-test.js
+298
-273
@@ -11,7 +11,6 @@
11
12
'use strict';
13
14
-
14
describe('ReactDOMComponent', () => {
15
var React;
16
var ReactTestUtils;
@@ -148,7 +147,7 @@ describe('ReactDOMComponent', () => {
147
expectDev(console.error.calls.count(0)).toBe(1);
148
expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
149
'Warning: Unknown prop `foo` on <div> tag. Remove this prop from the element. ' +
151
- 'For details, see https://fb.me/react-unknown-prop\n in div (at **)'
150
+ 'For details, see https://fb.me/react-unknown-prop\n in div (at **)',
151
);
152
});
153
@@ -159,7 +158,7 @@ describe('ReactDOMComponent', () => {
158
expectDev(console.error.calls.count(0)).toBe(1);
159
expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
160
'Warning: Unknown props `foo`, `baz` on <div> tag. Remove these props from the element. ' +
162
- 'For details, see https://fb.me/react-unknown-prop\n in div (at **)'
161
+ 'For details, see https://fb.me/react-unknown-prop\n in div (at **)',
162
);
163
});
164
@@ -169,7 +168,7 @@ describe('ReactDOMComponent', () => {
168
ReactDOM.render(<div onDblClick={() => {}} />, container);
169
expectDev(console.error.calls.count(0)).toBe(1);
170
expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
172
- 'Warning: Unknown event handler property onDblClick. Did you mean `onDoubleClick`?\n in div (at **)'
171
+ 'Warning: Unknown event handler property onDblClick. Did you mean `onDoubleClick`?\n in div (at **)',
172
);
173
});
174
@@ -242,15 +241,14 @@ describe('ReactDOMComponent', () => {
241
<my-second-component slot="first" />
242
<button slot="second">Hello</button>
243
</my-component>,
245
- container
244
+ container,
245
);
246
247
var lightDOM = container.firstChild.childNodes;
248
249
expect(lightDOM[0].getAttribute('slot')).toBe('first');
250
expect(lightDOM[1].getAttribute('slot')).toBe('second');
252
-
253
- } );
251
+ });
252
253
it('should skip reserved props on web components', () => {
254
var container = document.createElement('div');
@@ -260,11 +258,11 @@ describe('ReactDOMComponent', () => {
258
children={['foo']}
259
suppressContentEditableWarning={true}
260
/>,
263
- container
261
+ container,
262
);
263
expect(container.firstChild.hasAttribute('children')).toBe(false);
264
expect(
267
- container.firstChild.hasAttribute('suppressContentEditableWarning')
265
+ container.firstChild.hasAttribute('suppressContentEditableWarning'),
266
).toBe(false);
267
268
ReactDOM.render(
@@ -272,11 +270,11 @@ describe('ReactDOMComponent', () => {
270
children={['bar']}
271
suppressContentEditableWarning={false}
272
/>,
275
- container
273
+ container,
274
);
275
expect(container.firstChild.hasAttribute('children')).toBe(false);
276
expect(
279
- container.firstChild.hasAttribute('suppressContentEditableWarning')
277
+ container.firstChild.hasAttribute('suppressContentEditableWarning'),
278
).toBe(false);
279
});
280
@@ -285,19 +283,19 @@ describe('ReactDOMComponent', () => {
283
284
ReactDOM.render(
285
<my-component dangerouslySetInnerHTML={{__html: 'hi'}} />,
288
- container
286
+ container,
287
+ );
288
+ expect(container.firstChild.hasAttribute('dangerouslySetInnerHTML')).toBe(
289
+ false,
290
);
290
- expect(
291
- container.firstChild.hasAttribute('dangerouslySetInnerHTML')
292
- ).toBe(false);
291
292
ReactDOM.render(
293
<my-component dangerouslySetInnerHTML={{__html: 'bye'}} />,
296
- container
294
+ container,
295
+ );
296
+ expect(container.firstChild.hasAttribute('dangerouslySetInnerHTML')).toBe(
297
+ false,
298
);
298
- expect(
299
- container.firstChild.hasAttribute('dangerouslySetInnerHTML')
300
- ).toBe(false);
299
});
300
301
it('should render null and undefined as empty but print other falsy values', () => {
@@ -305,37 +303,34 @@ describe('ReactDOMComponent', () => {
303
304
ReactDOM.render(
305
<div dangerouslySetInnerHTML={{__html: 'textContent'}} />,
308
- container
306
+ container,
307
);
308
expect(container.textContent).toEqual('textContent');
309
312
- ReactDOM.render(
313
- <div dangerouslySetInnerHTML={{__html: 0}} />,
314
- container
315
- );
310
+ ReactDOM.render(<div dangerouslySetInnerHTML={{__html: 0}} />, container);
311
expect(container.textContent).toEqual('0');
312
313
ReactDOM.render(
314
<div dangerouslySetInnerHTML={{__html: false}} />,
320
- container
315
+ container,
316
);
317
expect(container.textContent).toEqual('false');
318
319
ReactDOM.render(
320
<div dangerouslySetInnerHTML={{__html: ''}} />,
326
- container
321
+ container,
322
);
323
expect(container.textContent).toEqual('');
324
325
ReactDOM.render(
326
<div dangerouslySetInnerHTML={{__html: null}} />,
332
- container
327
+ container,
328
);
329
expect(container.textContent).toEqual('');
330
331
ReactDOM.render(
332
<div dangerouslySetInnerHTML={{__html: undefined}} />,
338
- container
333
+ container,
334
);
335
expect(container.textContent).toEqual('');
336
});
@@ -387,13 +382,13 @@ describe('ReactDOMComponent', () => {
382
var element = React.createElement(
383
'x-foo-component',
384
{'blah" onclick="beevil" noise="hi': 'selected'},
390
- null
385
+ null,
386
);
387
ReactDOM.render(element, container);
388
}
389
expectDev(console.error.calls.count()).toBe(1);
390
expectDev(console.error.calls.argsFor(0)[0]).toEqual(
396
- 'Warning: Invalid attribute name: `blah" onclick="beevil" noise="hi`'
391
+ 'Warning: Invalid attribute name: `blah" onclick="beevil" noise="hi`',
392
);
393
});
394
@@ -407,13 +402,13 @@ describe('ReactDOMComponent', () => {
402
var afterUpdate = React.createElement(
403
'x-foo-component',
404
{'blah" onclick="beevil" noise="hi': 'selected'},
410
- null
405
+ null,
406
);
407
ReactDOM.render(afterUpdate, container);
408
}
409
expectDev(console.error.calls.count()).toBe(1);
410
expectDev(console.error.calls.argsFor(0)[0]).toEqual(
416
- 'Warning: Invalid attribute name: `blah" onclick="beevil" noise="hi`'
411
+ 'Warning: Invalid attribute name: `blah" onclick="beevil" noise="hi`',
412
);
413
});
414
@@ -463,12 +458,8 @@ describe('ReactDOMComponent', () => {
458
});
459
460
it('should reset innerHTML when switching from a direct text child to an empty child', () => {
466
- const transitionToValues = [
467
- null,
468
- undefined,
469
- false,
470
- ];
471
- transitionToValues.forEach((transitionToValue) => {
461
+ const transitionToValues = [null, undefined, false];
462
+ transitionToValues.forEach(transitionToValue => {
463
var container = document.createElement('div');
464
ReactDOM.render(<div>bonjour</div>, container);
465
expect(container.firstChild.innerHTML).toEqual('bonjour');
@@ -480,7 +471,10 @@ describe('ReactDOMComponent', () => {
471
472
it('should empty element when removing innerHTML', () => {
473
var container = document.createElement('div');
483
- ReactDOM.render(<div dangerouslySetInnerHTML={{__html: ':)'}} />, container);
474
+ ReactDOM.render(
475
+ <div dangerouslySetInnerHTML={{__html: ':)'}} />,
476
+ container,
477
+ );
478
479
expect(container.firstChild.innerHTML).toEqual(':)');
480
ReactDOM.render(<div />, container);
@@ -494,7 +488,7 @@ describe('ReactDOMComponent', () => {
488
expect(container.firstChild.innerHTML).toEqual('hello');
489
ReactDOM.render(
490
<div dangerouslySetInnerHTML={{__html: 'goodbye'}} />,
497
- container
491
+ container,
492
);
493
expect(container.firstChild.innerHTML).toEqual('goodbye');
494
});
@@ -503,7 +497,7 @@ describe('ReactDOMComponent', () => {
497
var container = document.createElement('div');
498
ReactDOM.render(
499
<div dangerouslySetInnerHTML={{__html: 'bonjour'}} />,
506
- container
500
+ container,
501
);
502
503
expect(container.firstChild.innerHTML).toEqual('bonjour');
@@ -515,7 +509,7 @@ describe('ReactDOMComponent', () => {
509
var container = document.createElement('div');
510
ReactDOM.render(
511
<div><div dangerouslySetInnerHTML={{__html: 'bonjour'}} /></div>,
518
- container
512
+ container,
513
);
514
515
expect(container.textContent).toEqual('bonjour');
@@ -530,7 +524,7 @@ describe('ReactDOMComponent', () => {
524
expect(container.textContent).toEqual('adieu');
525
ReactDOM.render(
526
<div><div dangerouslySetInnerHTML={{__html: 'bonjour'}} /></div>,
533
- container
527
+ container,
528
);
529
expect(container.textContent).toEqual('bonjour');
530
});
@@ -672,7 +666,7 @@ describe('ReactDOMComponent', () => {
666
<div key="C">C</div><div key="D">D</div>
667
</div>
668
</div>,
675
- container
669
+ container,
670
);
671
// BADC
672
ReactDOM.render(
@@ -684,7 +678,7 @@ describe('ReactDOMComponent', () => {
678
<div key="D">D</div><div key="C">C</div>
679
</div>
680
</div>,
687
- container
681
+ container,
682
);
683
684
expect(container.textContent).toBe('BADC');
@@ -702,7 +696,7 @@ describe('ReactDOMComponent', () => {
696
if (typeof value !== 'undefined') {
697
re += quoteRegexp(value) + '[\\\'"]';
698
}
705
- return (new RegExp(re)).test(actual);
699
+ return new RegExp(re).test(actual);
700
}
701
702
function genMarkup(props) {
@@ -716,9 +710,14 @@ describe('ReactDOMComponent', () => {
710
});
711
712
it('should escape style names and values', () => {
719
- expect(toHaveAttribute(genMarkup({
720
- style: {'b&ckground': '<3'},
721
- }), ['style', 'b&ckground:<3;']));
713
+ expect(
714
+ toHaveAttribute(
715
+ genMarkup({
716
+ style: {'b&ckground': '<3'},
717
+ }),
718
+ ['style', 'b&ckground:<3;'],
719
+ ),
720
+ );
721
});
722
});
723
@@ -729,17 +728,20 @@ describe('ReactDOMComponent', () => {
728
729
function genMarkup(props) {
730
return ReactDOMServer.renderToString(<div {...props} />);
732
- }
731
+ }
732
733
function toHaveInnerhtml(actual, expected) {
734
var re = '^' + quoteRegexp(expected) + '$';
736
- return (new RegExp(re)).test(actual);
735
+ return new RegExp(re).test(actual);
736
}
737
738
it('should handle dangerouslySetInnerHTML', () => {
739
var innerHTML = {__html: 'testContent'};
740
expect(
742
- toHaveInnerhtml(genMarkup({dangerouslySetInnerHTML: innerHTML}), 'testContent')
741
+ toHaveInnerhtml(
742
+ genMarkup({dangerouslySetInnerHTML: innerHTML}),
743
+ 'testContent',
744
+ ),
745
);
746
});
747
});
@@ -759,9 +761,13 @@ describe('ReactDOMComponent', () => {
761
var container = document.createElement('div');
762
ReactDOM.render(
763
<video>
762
- <source src="http://example.org/video" type="video/mp4" onError={(e) => console.error('onError called')} />
764
+ <source
765
+ src="http://example.org/video"
766
+ type="video/mp4"
767
+ onError={e => console.error('onError called')}
768
+ />
769
</video>,
764
- container
770
+ container,
771
);
772
773
var errorEvent = document.createEvent('Event');
@@ -769,9 +775,7 @@ describe('ReactDOMComponent', () => {
775
container.getElementsByTagName('source')[0].dispatchEvent(errorEvent);
776
777
expectDev(console.error.calls.count()).toBe(1);
772
- expectDev(console.error.calls.argsFor(0)[0]).toContain(
773
- 'onError called'
774
- );
778
+ expectDev(console.error.calls.argsFor(0)[0]).toContain('onError called');
779
});
780
781
it('should not duplicate uppercased selfclosing tags', () => {
@@ -786,24 +790,22 @@ describe('ReactDOMComponent', () => {
790
expect(returnedValue).not.toContain('</BR>');
791
expectDev(console.error.calls.count()).toBe(1);
792
expectDev(console.error.calls.argsFor(0)[0]).toContain(
789
- '<BR /> is using uppercase HTML.'
793
+ '<BR /> is using uppercase HTML.',
794
);
795
});
796
797
it('should warn on upper case HTML tags, not SVG nor custom tags', () => {
798
spyOn(console, 'error');
799
ReactTestUtils.renderIntoDocument(
796
- React.createElement('svg', null, React.createElement('PATH'))
800
+ React.createElement('svg', null, React.createElement('PATH')),
801
);
802
expectDev(console.error.calls.count()).toBe(0);
799
- ReactTestUtils.renderIntoDocument(
800
- React.createElement('CUSTOM-TAG')
801
- );
803
+ ReactTestUtils.renderIntoDocument(React.createElement('CUSTOM-TAG'));
804
expectDev(console.error.calls.count()).toBe(0);
805
ReactTestUtils.renderIntoDocument(React.createElement('IMG'));
806
expectDev(console.error.calls.count()).toBe(1);
807
expectDev(console.error.calls.argsFor(0)[0]).toContain(
806
- '<IMG /> is using uppercase HTML.'
808
+ '<IMG /> is using uppercase HTML.',
809
);
810
});
811
@@ -814,7 +816,7 @@ describe('ReactDOMComponent', () => {
816
ReactDOM.render(<input>children</input>, container);
817
}).toThrowError(
818
'input is a void element tag and must neither have `children` nor ' +
817
- 'use `dangerouslySetInnerHTML`.'
819
+ 'use `dangerouslySetInnerHTML`.',
820
);
821
});
822
@@ -824,11 +826,11 @@ describe('ReactDOMComponent', () => {
826
expect(function() {
827
ReactDOM.render(
828
<input dangerouslySetInnerHTML={{__html: 'content'}} />,
827
- container
829
+ container,
830
);
831
}).toThrowError(
832
'input is a void element tag and must neither have `children` nor use ' +
831
- '`dangerouslySetInnerHTML`.'
833
+ '`dangerouslySetInnerHTML`.',
834
);
835
});
836
@@ -850,13 +852,8 @@ describe('ReactDOMComponent', () => {
852
}
853
854
expect(function() {
853
- ReactDOM.render(
854
- <Owner />,
855
- container
856
- );
857
- }).toThrowError(
858
- '\n\nThis DOM node was rendered by `Owner`.'
859
- );
855
+ ReactDOM.render(<Owner />, container);
856
+ }).toThrowError('\n\nThis DOM node was rendered by `Owner`.');
857
});
858
859
it('should emit a warning once for a named custom component using shady DOM', () => {
@@ -881,11 +878,10 @@ describe('ReactDOMComponent', () => {
878
expectDev(console.error.calls.count()).toBe(1);
879
expectDev(console.error.calls.argsFor(0)[0]).toContain(
880
'ShadyComponent is using shady DOM. Using shady DOM with React can ' +
884
- 'cause things to break subtly.'
881
+ 'cause things to break subtly.',
882
);
883
mountComponent({is: 'custom-shady-div2'});
884
expectDev(console.error.calls.count()).toBe(1);
888
-
885
} finally {
886
document.createElement = defaultCreateElement;
887
}
@@ -909,12 +905,11 @@ describe('ReactDOMComponent', () => {
905
expectDev(console.error.calls.count()).toBe(1);
906
expectDev(console.error.calls.argsFor(0)[0]).toContain(
907
'A component is using shady DOM. Using shady DOM with React can ' +
912
- 'cause things to break subtly.'
908
+ 'cause things to break subtly.',
909
);
910
911
mountComponent({is: 'custom-shady-div2'});
912
expectDev(console.error.calls.count()).toBe(1);
917
-
913
} finally {
914
document.createElement = defaultCreateElement;
915
}
@@ -924,7 +919,9 @@ describe('ReactDOMComponent', () => {
919
it('should treat menuitem as a void element but still create the closing tag', () => {
920
var container = document.createElement('div');
921
927
- var returnedValue = ReactDOMServer.renderToString(<menu><menuitem /></menu>);
922
+ var returnedValue = ReactDOMServer.renderToString(
923
+ <menu><menuitem /></menu>,
924
+ );
925
926
expect(returnedValue).toContain('</menuitem>');
927
@@ -932,26 +929,24 @@ describe('ReactDOMComponent', () => {
929
ReactDOM.render(<menu><menuitem>children</menuitem></menu>, container);
930
}).toThrowError(
931
'menuitem is a void element tag and must neither have `children` nor use ' +
935
- '`dangerouslySetInnerHTML`.'
932
+ '`dangerouslySetInnerHTML`.',
933
);
937
-
934
});
935
936
it('should validate against multiple children props', () => {
937
expect(function() {
938
mountComponent({children: '', dangerouslySetInnerHTML: ''});
939
}).toThrowError(
944
- 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'
940
+ 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.',
941
);
942
});
943
944
it('should validate against use of innerHTML', () => {
949
-
945
spyOn(console, 'error');
946
mountComponent({innerHTML: '<span>Hi Jim!</span>'});
947
expectDev(console.error.calls.count()).toBe(1);
948
expectDev(console.error.calls.argsFor(0)[0]).toContain(
954
- 'Directly setting property `innerHTML` is not permitted. '
949
+ 'Directly setting property `innerHTML` is not permitted. ',
950
);
951
});
952
@@ -960,22 +955,22 @@ describe('ReactDOMComponent', () => {
955
mountComponent({dangerouslySetInnerHTML: '<span>Hi Jim!</span>'});
956
}).toThrowError(
957
'`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' +
963
- 'Please visit https://fb.me/react-invariant-dangerously-set-inner-html for more information.'
958
+ 'Please visit https://fb.me/react-invariant-dangerously-set-inner-html for more information.',
959
);
960
});
961
962
it('should validate use of dangerouslySetInnerHTML', () => {
963
expect(function() {
969
- mountComponent({dangerouslySetInnerHTML: {foo: 'bar'} });
964
+ mountComponent({dangerouslySetInnerHTML: {foo: 'bar'}});
965
}).toThrowError(
966
'`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' +
972
- 'Please visit https://fb.me/react-invariant-dangerously-set-inner-html for more information.'
967
+ 'Please visit https://fb.me/react-invariant-dangerously-set-inner-html for more information.',
968
);
969
});
970
971
it('should allow {__html: null}', () => {
972
expect(function() {
978
- mountComponent({dangerouslySetInnerHTML: {__html: null} });
973
+ mountComponent({dangerouslySetInnerHTML: {__html: null}});
974
}).not.toThrow();
975
});
976
@@ -988,7 +983,11 @@ describe('ReactDOMComponent', () => {
983
984
it('should respect suppressContentEditableWarning', () => {
985
spyOn(console, 'error');
991
- mountComponent({contentEditable: true, children: '', suppressContentEditableWarning: true});
986
+ mountComponent({
987
+ contentEditable: true,
988
+ children: '',
989
+ suppressContentEditableWarning: true,
990
+ });
991
expectDev(console.error.calls.count()).toBe(0);
992
});
993
@@ -997,14 +996,17 @@ describe('ReactDOMComponent', () => {
996
mountComponent({style: 'display: none'});
997
}).toThrowError(
998
'The `style` prop expects a mapping from style properties to values, ' +
1000
- 'not a string. For example, style={{marginRight: spacing + \'em\'}} ' +
1001
- 'when using JSX.'
999
+ "not a string. For example, style={{marginRight: spacing + 'em'}} " +
1000
+ 'when using JSX.',
1001
);
1002
});
1003
1004
it('should track input values', () => {
1005
var container = document.createElement('div');
1007
- var inst = ReactDOM.render(<input type="text" defaultValue="foo" />, container);
1006
+ var inst = ReactDOM.render(
1007
+ <input type="text" defaultValue="foo" />,
1008
+ container,
1009
+ );
1010
1011
var tracker = inputValueTracking._getTrackerFromNode(inst);
1012
@@ -1032,7 +1034,7 @@ describe('ReactDOMComponent', () => {
1034
ReactDOM.render(<X />, container);
1035
}).toThrowError(
1036
'input is a void element tag and must neither have `children` ' +
1035
- 'nor use `dangerouslySetInnerHTML`.\n\nThis DOM node was rendered by `X`.'
1037
+ 'nor use `dangerouslySetInnerHTML`.\n\nThis DOM node was rendered by `X`.',
1038
);
1039
});
1040
@@ -1041,9 +1043,14 @@ describe('ReactDOMComponent', () => {
1043
var container = document.createElement('div');
1044
spyOn(document, 'createElement').and.callThrough();
1045
ReactDOM.render(<div is="custom-div" />, container);
1044
- expect(document.createElement).toHaveBeenCalledWith('div', 'custom-div');
1046
+ expect(document.createElement).toHaveBeenCalledWith(
1047
+ 'div',
1048
+ 'custom-div',
1049
+ );
1050
} else {
1046
- expect(ReactDOMServer.renderToString(<div is="custom-div" />)).toContain('is="custom-div"');
1051
+ expect(
1052
+ ReactDOMServer.renderToString(<div is="custom-div" />),
1053
+ ).toContain('is="custom-div"');
1054
}
1055
});
1056
@@ -1054,11 +1061,11 @@ describe('ReactDOMComponent', () => {
1061
<svg>
1062
<image
1063
xlinkHref="http://example.org/image"
1057
- onError={(e) => console.log('onError called')}
1058
- onLoad={(e) => console.log('onLoad called')}
1064
+ onError={e => console.log('onError called')}
1065
+ onLoad={e => console.log('onLoad called')}
1066
/>
1067
</svg>,
1061
- container
1068
+ container,
1069
);
1070
1071
var loadEvent = document.createEvent('Event');
@@ -1071,12 +1078,8 @@ describe('ReactDOMComponent', () => {
1078
container.getElementsByTagName('image')[0].dispatchEvent(loadEvent);
1079
1080
expectDev(console.log.calls.count()).toBe(2);
1074
- expectDev(console.log.calls.argsFor(0)[0]).toContain(
1075
- 'onError called'
1076
- );
1077
- expectDev(console.log.calls.argsFor(1)[0]).toContain(
1078
- 'onLoad called'
1079
- );
1081
+ expectDev(console.log.calls.argsFor(0)[0]).toContain('onError called');
1082
+ expectDev(console.log.calls.argsFor(1)[0]).toContain('onLoad called');
1083
});
1084
});
1085
@@ -1094,7 +1097,7 @@ describe('ReactDOMComponent', () => {
1097
ReactDOM.render(<input>children</input>, container);
1098
}).toThrowError(
1099
'input is a void element tag and must neither have `children` nor use ' +
1097
- '`dangerouslySetInnerHTML`.'
1100
+ '`dangerouslySetInnerHTML`.',
1101
);
1102
});
1103
@@ -1104,11 +1107,11 @@ describe('ReactDOMComponent', () => {
1107
expect(function() {
1108
ReactDOM.render(
1109
<input dangerouslySetInnerHTML={{__html: 'content'}} />,
1107
- container
1110
+ container,
1111
);
1112
}).toThrowError(
1113
'input is a void element tag and must neither have `children` nor use ' +
1111
- '`dangerouslySetInnerHTML`.'
1114
+ '`dangerouslySetInnerHTML`.',
1115
);
1116
});
1117
@@ -1118,19 +1121,16 @@ describe('ReactDOMComponent', () => {
1121
expect(function() {
1122
ReactDOM.render(
1123
<div children="" dangerouslySetInnerHTML={{__html: ''}} />,
1121
- container
1124
+ container,
1125
);
1126
}).toThrowError(
1124
- 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'
1127
+ 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.',
1128
);
1129
});
1130
1131
it('should warn about contentEditable and children', () => {
1132
spyOn(console, 'error');
1130
- ReactDOM.render(
1131
- <div contentEditable={true}><div /></div>,
1132
- container
1133
- );
1133
+ ReactDOM.render(<div contentEditable={true}><div /></div>, container);
1134
expectDev(console.error.calls.count()).toBe(1);
1135
expectDev(console.error.calls.argsFor(0)[0]).toContain('contentEditable');
1136
});
@@ -1142,8 +1142,8 @@ describe('ReactDOMComponent', () => {
1142
ReactDOM.render(<div style={1} />, container);
1143
}).toThrowError(
1144
'The `style` prop expects a mapping from style properties to values, ' +
1145
- 'not a string. For example, style={{marginRight: spacing + \'em\'}} ' +
1146
- 'when using JSX.'
1145
+ "not a string. For example, style={{marginRight: spacing + 'em'}} " +
1146
+ 'when using JSX.',
1147
);
1148
});
1149
@@ -1158,25 +1158,28 @@ describe('ReactDOMComponent', () => {
1158
ReactDOM.render(<Animal />, container);
1159
}).toThrowError(
1160
'The `style` prop expects a mapping from style properties to values, ' +
1161
- 'not a string. For example, style={{marginRight: spacing + \'em\'}} ' +
1162
- 'when using JSX.\n\nThis DOM node was rendered by `Animal`.'
1161
+ "not a string. For example, style={{marginRight: spacing + 'em'}} " +
1162
+ 'when using JSX.\n\nThis DOM node was rendered by `Animal`.',
1163
);
1164
});
1165
1166
it('should properly escape text content and attributes values', () => {
1167
expect(
1168
ReactDOMServer.renderToStaticMarkup(
1169
- React.DOM.div({
1170
- title: '\'"<>&',
1171
- style: {
1172
- textAlign: '\'"<>&',
1169
+ React.DOM.div(
1170
+ {
1171
+ title: '\'"<>&',
1172
+ style: {
1173
+ textAlign: '\'"<>&',
1174
+ },
1175
},
1174
- }, '\'"<>&')
1175
- )
1176
+ '\'"<>&',
1177
+ ),
1178
+ ),
1179
).toBe(
1180
'<div title="'"<>&" style="text-align:'"<>&;">' +
1181
''"<>&' +
1179
- '</div>'
1182
+ '</div>',
1183
);
1184
});
1185
});
@@ -1186,7 +1189,10 @@ describe('ReactDOMComponent', () => {
1189
if (!ReactDOMFeatureFlags.useFiber) {
1190
it('should clean up input value tracking', () => {
1191
var container = document.createElement('div');
1189
- var node = ReactDOM.render(<input type="text" defaultValue="foo" />, container);
1192
+ var node = ReactDOM.render(
1193
+ <input type="text" defaultValue="foo" />,
1194
+ container,
1195
+ );
1196
var tracker = inputValueTracking._getTrackerFromNode(node);
1197
1198
spyOn(tracker, 'stopTracking');
@@ -1231,8 +1237,7 @@ describe('ReactDOMComponent', () => {
1237
it('should warn about the `onScroll` issue when unsupported (IE8)', () => {
1238
// Mock this here so we can mimic IE8 support. We require isEventSupported
1239
// before React so it's pre-mocked before React would require it.
1234
- jest.resetModules()
1235
- .mock('isEventSupported');
1240
+ jest.resetModules().mock('isEventSupported');
1241
var isEventSupported = require('isEventSupported');
1242
isEventSupported.mockReturnValueOnce(false);
1243
ReactTestUtils = require('ReactTestUtils');
@@ -1241,7 +1246,7 @@ describe('ReactDOMComponent', () => {
1246
ReactTestUtils.renderIntoDocument(<div onScroll={function() {}} />);
1247
expectDev(console.error.calls.count()).toBe(1);
1248
expectDev(console.error.calls.argsFor(0)[0]).toBe(
1244
- 'Warning: This browser doesn\'t support the `onScroll` event'
1249
+ "Warning: This browser doesn't support the `onScroll` event",
1250
);
1251
});
1252
@@ -1255,34 +1260,26 @@ describe('ReactDOMComponent', () => {
1260
describe('tag sanitization', () => {
1261
it('should throw when an invalid tag name is used server-side', () => {
1262
var hackzor = React.createElement('script tag');
1258
- expect(
1259
- () => ReactDOMServer.renderToString(hackzor)
1260
- ).toThrowError(
1261
- 'Invalid tag: script tag'
1263
+ expect(() => ReactDOMServer.renderToString(hackzor)).toThrowError(
1264
+ 'Invalid tag: script tag',
1265
);
1266
});
1267
1268
it('should throw when an attack vector is used server-side', () => {
1269
var hackzor = React.createElement('div><img /><div');
1267
- expect(
1268
- () => ReactDOMServer.renderToString(hackzor)
1269
- ).toThrowError(
1270
- 'Invalid tag: div><img /><div'
1270
+ expect(() => ReactDOMServer.renderToString(hackzor)).toThrowError(
1271
+ 'Invalid tag: div><img /><div',
1272
);
1273
});
1274
1275
it('should throw when an invalid tag name is used', () => {
1276
var hackzor = React.createElement('script tag');
1276
- expect(
1277
- () => ReactTestUtils.renderIntoDocument(hackzor)
1278
- ).toThrow();
1277
+ expect(() => ReactTestUtils.renderIntoDocument(hackzor)).toThrow();
1278
});
1279
1280
it('should throw when an attack vector is used', () => {
1281
var hackzor = React.createElement('div><img /><div');
1283
- expect(
1284
- () => ReactTestUtils.renderIntoDocument(hackzor)
1285
- ).toThrow();
1282
+ expect(() => ReactTestUtils.renderIntoDocument(hackzor)).toThrow();
1283
});
1284
});
1285
@@ -1291,15 +1288,15 @@ describe('ReactDOMComponent', () => {
1288
spyOn(console, 'error');
1289
ReactTestUtils.renderIntoDocument(<div><tr /><tr /></div>);
1290
1294
- var addendum = ReactDOMFeatureFlags.useFiber ?
1295
- '\n in tr (at **)' +
1296
- '\n in div (at **)' :
1297
- ' See div > tr.';
1291
+ var addendum = ReactDOMFeatureFlags.useFiber
1292
+ ? '\n in tr (at **)' + '\n in div (at **)'
1293
+ : ' See div > tr.';
1294
1295
expectDev(console.error.calls.count()).toBe(1);
1296
expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
1297
'Warning: validateDOMNesting(...): <tr> cannot appear as a child of ' +
1302
- '<div>.' + addendum
1298
+ '<div>.' +
1299
+ addendum,
1300
);
1301
});
1302
@@ -1308,16 +1305,16 @@ describe('ReactDOMComponent', () => {
1305
var p = document.createElement('p');
1306
ReactDOM.render(<span><p /></span>, p);
1307
1311
- var addendum = ReactDOMFeatureFlags.useFiber ?
1312
- // There is no outer `p` here because root container is not part of the stack.
1313
- '\n in p (at **)' +
1314
- '\n in span (at **)' :
1315
- ' See p > ... > p.';
1308
+ var addendum = ReactDOMFeatureFlags.useFiber
1309
+ ? // There is no outer `p` here because root container is not part of the stack.
1310
+ '\n in p (at **)' + '\n in span (at **)'
1311
+ : ' See p > ... > p.';
1312
1313
expectDev(console.error.calls.count()).toBe(1);
1314
expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
1315
'Warning: validateDOMNesting(...): <p> cannot appear as a descendant ' +
1320
- 'of <p>.' + addendum
1316
+ 'of <p>.' +
1317
+ addendum,
1318
);
1319
});
1320
@@ -1339,37 +1336,39 @@ describe('ReactDOMComponent', () => {
1336
ReactTestUtils.renderIntoDocument(<Foo />);
1337
expectDev(console.error.calls.count()).toBe(3);
1338
1342
- var addendum1 = ReactDOMFeatureFlags.useFiber ?
1343
- '\n in tr (at **)' +
1344
- '\n in Row (at **)' +
1345
- '\n in table (at **)' +
1346
- '\n in Foo (at **)' :
1347
- ' See Foo > table > Row > tr.';
1339
+ var addendum1 = ReactDOMFeatureFlags.useFiber
1340
+ ? '\n in tr (at **)' +
1341
+ '\n in Row (at **)' +
1342
+ '\n in table (at **)' +
1343
+ '\n in Foo (at **)'
1344
+ : ' See Foo > table > Row > tr.';
1345
expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
1346
'Warning: validateDOMNesting(...): <tr> cannot appear as a child of ' +
1350
- '<table>. Add a <tbody> to your code to match the DOM tree generated ' +
1351
- 'by the browser.' + addendum1
1347
+ '<table>. Add a <tbody> to your code to match the DOM tree generated ' +
1348
+ 'by the browser.' +
1349
+ addendum1,
1350
);
1351
1354
- var addendum2 = ReactDOMFeatureFlags.useFiber ?
1355
- '\n in tr (at **)' +
1356
- '\n in Row (at **)' +
1357
- '\n in table (at **)' +
1358
- '\n in Foo (at **)' :
1359
- ' See Row > tr > #text.';
1352
+ var addendum2 = ReactDOMFeatureFlags.useFiber
1353
+ ? '\n in tr (at **)' +
1354
+ '\n in Row (at **)' +
1355
+ '\n in table (at **)' +
1356
+ '\n in Foo (at **)'
1357
+ : ' See Row > tr > #text.';
1358
expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(1)[0])).toBe(
1359
'Warning: validateDOMNesting(...): Text nodes cannot appear as a ' +
1362
- 'child of <tr>.' + addendum2
1360
+ 'child of <tr>.' +
1361
+ addendum2,
1362
);
1363
1365
- var addendum3 = ReactDOMFeatureFlags.useFiber ?
1366
- '\n in table (at **)' +
1367
- '\n in Foo (at **)' :
1368
- ' See Foo > table > #text.';
1364
+ var addendum3 = ReactDOMFeatureFlags.useFiber
1365
+ ? '\n in table (at **)' + '\n in Foo (at **)'
1366
+ : ' See Foo > table > #text.';
1367
expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(2)[0])).toBe(
1368
'Warning: validateDOMNesting(...): Whitespace text nodes cannot ' +
1371
- 'appear as a child of <table>. Make sure you don\'t have any extra ' +
1372
- 'whitespace between tags on each line of your source code.' + addendum3
1369
+ "appear as a child of <table>. Make sure you don't have any extra " +
1370
+ 'whitespace between tags on each line of your source code.' +
1371
+ addendum3,
1372
);
1373
});
1374
@@ -1402,14 +1401,16 @@ describe('ReactDOMComponent', () => {
1401
});
1402
ReactTestUtils.renderIntoDocument(<App1 />);
1403
expectDev(console.error.calls.count()).toBe(1);
1405
- expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toContain(
1406
- ReactDOMFeatureFlags.useFiber ?
1407
- '\n in tr (at **)' +
1408
- '\n in Row (at **)' +
1409
- '\n in FancyRow (at **)' +
1410
- '\n in table (at **)' +
1411
- '\n in Viz1 (at **)' :
1412
- 'See Viz1 > table > FancyRow > Row > tr.'
1404
+ expectDev(
1405
+ normalizeCodeLocInfo(console.error.calls.argsFor(0)[0]),
1406
+ ).toContain(
1407
+ ReactDOMFeatureFlags.useFiber
1408
+ ? '\n in tr (at **)' +
1409
+ '\n in Row (at **)' +
1410
+ '\n in FancyRow (at **)' +
1411
+ '\n in table (at **)' +
1412
+ '\n in Viz1 (at **)'
1413
+ : 'See Viz1 > table > FancyRow > Row > tr.',
1414
);
1415
1416
var Viz2 = React.createClass({
@@ -1420,51 +1421,59 @@ describe('ReactDOMComponent', () => {
1421
});
1422
ReactTestUtils.renderIntoDocument(<App2 />);
1423
expectDev(console.error.calls.count()).toBe(2);
1423
- expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(1)[0])).toContain(
1424
- ReactDOMFeatureFlags.useFiber ?
1425
- '\n in tr (at **)' +
1426
- '\n in Row (at **)' +
1427
- '\n in FancyRow (at **)' +
1428
- '\n in table (at **)' +
1429
- '\n in Table (at **)' +
1430
- '\n in FancyTable (at **)' +
1431
- '\n in Viz2 (at **)' :
1432
- 'See Viz2 > FancyTable > Table > table > FancyRow > Row > tr.'
1424
+ expectDev(
1425
+ normalizeCodeLocInfo(console.error.calls.argsFor(1)[0]),
1426
+ ).toContain(
1427
+ ReactDOMFeatureFlags.useFiber
1428
+ ? '\n in tr (at **)' +
1429
+ '\n in Row (at **)' +
1430
+ '\n in FancyRow (at **)' +
1431
+ '\n in table (at **)' +
1432
+ '\n in Table (at **)' +
1433
+ '\n in FancyTable (at **)' +
1434
+ '\n in Viz2 (at **)'
1435
+ : 'See Viz2 > FancyTable > Table > table > FancyRow > Row > tr.',
1436
);
1437
1438
ReactTestUtils.renderIntoDocument(<FancyTable><FancyRow /></FancyTable>);
1439
expectDev(console.error.calls.count()).toBe(3);
1437
- expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(2)[0])).toContain(
1438
- ReactDOMFeatureFlags.useFiber ?
1439
- '\n in tr (at **)' +
1440
- '\n in Row (at **)' +
1441
- '\n in FancyRow (at **)' +
1442
- '\n in table (at **)' +
1443
- '\n in Table (at **)' +
1444
- '\n in FancyTable (at **)' :
1445
- 'See FancyTable > Table > table > FancyRow > Row > tr.'
1440
+ expectDev(
1441
+ normalizeCodeLocInfo(console.error.calls.argsFor(2)[0]),
1442
+ ).toContain(
1443
+ ReactDOMFeatureFlags.useFiber
1444
+ ? '\n in tr (at **)' +
1445
+ '\n in Row (at **)' +
1446
+ '\n in FancyRow (at **)' +
1447
+ '\n in table (at **)' +
1448
+ '\n in Table (at **)' +
1449
+ '\n in FancyTable (at **)'
1450
+ : 'See FancyTable > Table > table > FancyRow > Row > tr.',
1451
);
1452
1453
ReactTestUtils.renderIntoDocument(<table><FancyRow /></table>);
1454
expectDev(console.error.calls.count()).toBe(4);
1450
- expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(3)[0])).toContain(
1451
- ReactDOMFeatureFlags.useFiber ?
1452
- '\n in tr (at **)' +
1453
- '\n in Row (at **)' +
1454
- '\n in FancyRow (at **)' +
1455
- '\n in table (at **)' :
1456
- 'See table > FancyRow > Row > tr.'
1455
+ expectDev(
1456
+ normalizeCodeLocInfo(console.error.calls.argsFor(3)[0]),
1457
+ ).toContain(
1458
+ ReactDOMFeatureFlags.useFiber
1459
+ ? '\n in tr (at **)' +
1460
+ '\n in Row (at **)' +
1461
+ '\n in FancyRow (at **)' +
1462
+ '\n in table (at **)'
1463
+ : 'See table > FancyRow > Row > tr.',
1464
);
1465
1466
ReactTestUtils.renderIntoDocument(<FancyTable><tr /></FancyTable>);
1467
expectDev(console.error.calls.count()).toBe(5);
1461
- expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(4)[0])).toContain(
1462
- ReactDOMFeatureFlags.useFiber ?
1463
- '\n in tr (at **)' +
1464
- '\n in table (at **)' +
1465
- '\n in Table (at **)' +
1466
- '\n in FancyTable (at **)' :
1467
- 'See FancyTable > Table > table > tr.'
1468
+ expectDev(
1469
+ normalizeCodeLocInfo(console.error.calls.argsFor(4)[0]),
1470
+ ).toContain(
1471
+ ReactDOMFeatureFlags.useFiber
1472
+ ? '\n in tr (at **)' +
1473
+ '\n in table (at **)' +
1474
+ '\n in Table (at **)' +
1475
+ '\n in FancyTable (at **)'
1476
+ : 'See FancyTable > Table > table > tr.',
1477
);
1478
1479
class Link extends React.Component {
@@ -1475,28 +1484,36 @@ describe('ReactDOMComponent', () => {
1484
1485
ReactTestUtils.renderIntoDocument(<Link><div><Link /></div></Link>);
1486
expectDev(console.error.calls.count()).toBe(6);
1478
- expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(5)[0])).toContain(
1479
- ReactDOMFeatureFlags.useFiber ?
1480
- '\n in a (at **)' +
1481
- '\n in Link (at **)' +
1482
- '\n in div (at **)' +
1483
- '\n in a (at **)' +
1484
- '\n in Link (at **)' :
1485
- 'See Link > a > ... > Link > a.'
1487
+ expectDev(
1488
+ normalizeCodeLocInfo(console.error.calls.argsFor(5)[0]),
1489
+ ).toContain(
1490
+ ReactDOMFeatureFlags.useFiber
1491
+ ? '\n in a (at **)' +
1492
+ '\n in Link (at **)' +
1493
+ '\n in div (at **)' +
1494
+ '\n in a (at **)' +
1495
+ '\n in Link (at **)'
1496
+ : 'See Link > a > ... > Link > a.',
1497
);
1498
});
1499
1500
it('should warn about incorrect casing on properties (ssr)', () => {
1501
spyOn(console, 'error');
1491
- ReactDOMServer.renderToString(React.createElement('input', {type: 'text', tabindex: '1'}));
1502
+ ReactDOMServer.renderToString(
1503
+ React.createElement('input', {type: 'text', tabindex: '1'}),
1504
+ );
1505
expectDev(console.error.calls.count()).toBe(1);
1506
expectDev(console.error.calls.argsFor(0)[0]).toContain('tabIndex');
1507
});
1508
1509
it('should warn about incorrect casing on event handlers (ssr)', () => {
1510
spyOn(console, 'error');
1498
- ReactDOMServer.renderToString(React.createElement('input', {type: 'text', onclick: '1'}));
1499
- ReactDOMServer.renderToString(React.createElement('input', {type: 'text', onKeydown: '1'}));
1511
+ ReactDOMServer.renderToString(
1512
+ React.createElement('input', {type: 'text', onclick: '1'}),
1513
+ );
1514
+ ReactDOMServer.renderToString(
1515
+ React.createElement('input', {type: 'text', onKeydown: '1'}),
1516
+ );
1517
expectDev(console.error.calls.count()).toBe(2);
1518
expectDev(console.error.calls.argsFor(0)[0]).toContain('onClick');
1519
expectDev(console.error.calls.argsFor(1)[0]).toContain('onKeyDown');
@@ -1504,15 +1521,21 @@ describe('ReactDOMComponent', () => {
1521
1522
it('should warn about incorrect casing on properties', () => {
1523
spyOn(console, 'error');
1507
- ReactTestUtils.renderIntoDocument(React.createElement('input', {type: 'text', tabindex: '1'}));
1524
+ ReactTestUtils.renderIntoDocument(
1525
+ React.createElement('input', {type: 'text', tabindex: '1'}),
1526
+ );
1527
expectDev(console.error.calls.count()).toBe(1);
1528
expectDev(console.error.calls.argsFor(0)[0]).toContain('tabIndex');
1529
});
1530
1531
it('should warn about incorrect casing on event handlers', () => {
1532
spyOn(console, 'error');
1514
- ReactTestUtils.renderIntoDocument(React.createElement('input', {type: 'text', onclick: '1'}));
1515
- ReactTestUtils.renderIntoDocument(React.createElement('input', {type: 'text', onKeydown: '1'}));
1533
+ ReactTestUtils.renderIntoDocument(
1534
+ React.createElement('input', {type: 'text', onclick: '1'}),
1535
+ );
1536
+ ReactTestUtils.renderIntoDocument(
1537
+ React.createElement('input', {type: 'text', onKeydown: '1'}),
1538
+ );
1539
expectDev(console.error.calls.count()).toBe(2);
1540
expectDev(console.error.calls.argsFor(0)[0]).toContain('onClick');
1541
expectDev(console.error.calls.argsFor(1)[0]).toContain('onKeyDown');
@@ -1520,14 +1543,18 @@ describe('ReactDOMComponent', () => {
1543
1544
it('should warn about class', () => {
1545
spyOn(console, 'error');
1523
- ReactTestUtils.renderIntoDocument(React.createElement('div', {class: 'muffins'}));
1546
+ ReactTestUtils.renderIntoDocument(
1547
+ React.createElement('div', {class: 'muffins'}),
1548
+ );
1549
expectDev(console.error.calls.count()).toBe(1);
1550
expectDev(console.error.calls.argsFor(0)[0]).toContain('className');
1551
});
1552
1553
it('should warn about class (ssr)', () => {
1554
spyOn(console, 'error');
1530
- ReactDOMServer.renderToString(React.createElement('div', {class: 'muffins'}));
1555
+ ReactDOMServer.renderToString(
1556
+ React.createElement('div', {class: 'muffins'}),
1557
+ );
1558
expectDev(console.error.calls.count()).toBe(1);
1559
expectDev(console.error.calls.argsFor(0)[0]).toContain('className');
1560
});
@@ -1561,16 +1588,12 @@ describe('ReactDOMComponent', () => {
1588
ReactTestUtils.renderIntoDocument(<div class="paladin" />);
1589
ReactTestUtils.renderIntoDocument(<input type="text" onclick="1" />);
1590
expectDev(console.error.calls.count()).toBe(2);
1564
- expect(
1565
- normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])
1566
- ).toBe(
1567
- 'Warning: Unknown DOM property class. Did you mean className?\n in div (at **)'
1591
+ expect(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
1592
+ 'Warning: Unknown DOM property class. Did you mean className?\n in div (at **)',
1593
);
1569
- expect(
1570
- normalizeCodeLocInfo(console.error.calls.argsFor(1)[0])
1571
- ).toBe(
1594
+ expect(normalizeCodeLocInfo(console.error.calls.argsFor(1)[0])).toBe(
1595
'Warning: Unknown event handler property onclick. Did you mean ' +
1573
- '`onClick`?\n in input (at **)'
1596
+ '`onClick`?\n in input (at **)',
1597
);
1598
});
1599
@@ -1579,16 +1602,12 @@ describe('ReactDOMComponent', () => {
1602
ReactDOMServer.renderToString(<div class="paladin" />);
1603
ReactDOMServer.renderToString(<input type="text" onclick="1" />);
1604
expectDev(console.error.calls.count()).toBe(2);
1582
- expect(
1583
- normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])
1584
- ).toBe(
1585
- 'Warning: Unknown DOM property class. Did you mean className?\n in div (at **)'
1605
+ expect(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
1606
+ 'Warning: Unknown DOM property class. Did you mean className?\n in div (at **)',
1607
);
1587
- expect(
1588
- normalizeCodeLocInfo(console.error.calls.argsFor(1)[0])
1589
- ).toBe(
1608
+ expect(normalizeCodeLocInfo(console.error.calls.argsFor(1)[0])).toBe(
1609
'Warning: Unknown event handler property onclick. Did you mean ' +
1591
- '`onClick`?\n in input (at **)'
1610
+ '`onClick`?\n in input (at **)',
1611
);
1612
});
1613
@@ -1601,10 +1620,8 @@ describe('ReactDOMComponent', () => {
1620
1621
ReactTestUtils.renderIntoDocument(<div class="paladin" />, container);
1622
expectDev(console.error.calls.count()).toBe(1);
1604
- expect(
1605
- normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])
1606
- ).toBe(
1607
- 'Warning: Unknown DOM property class. Did you mean className?\n in div (at **)'
1623
+ expect(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
1624
+ 'Warning: Unknown DOM property class. Did you mean className?\n in div (at **)',
1625
);
1626
});
1627
@@ -1613,12 +1630,12 @@ describe('ReactDOMComponent', () => {
1630
1631
ReactTestUtils.renderIntoDocument(
1632
<div className="foo1">
1616
- <div class="foo2" />
1617
- <div onClick="foo3" />
1618
- <div onclick="foo4" />
1619
- <div className="foo5" />
1620
- <div className="foo6" />
1621
- </div>
1633
+ <div class="foo2" />
1634
+ <div onClick="foo3" />
1635
+ <div onclick="foo4" />
1636
+ <div className="foo5" />
1637
+ <div className="foo6" />
1638
+ </div>,
1639
);
1640
1641
expectDev(console.error.calls.count()).toBe(2);
@@ -1641,12 +1658,12 @@ describe('ReactDOMComponent', () => {
1658
1659
ReactDOMServer.renderToString(
1660
<div className="foo1">
1644
- <div class="foo2" />
1645
- <div onClick="foo3" />
1646
- <div onclick="foo4" />
1647
- <div className="foo5" />
1648
- <div className="foo6" />
1649
- </div>
1661
+ <div class="foo2" />
1662
+ <div onClick="foo3" />
1663
+ <div onclick="foo4" />
1664
+ <div className="foo5" />
1665
+ <div className="foo6" />
1666
+ </div>,
1667
);
1668
1669
expectDev(console.error.calls.count()).toBe(2);
@@ -1769,34 +1786,42 @@ describe('ReactDOMComponent', () => {
1786
it('should suggest property name if available', () => {
1787
spyOn(console, 'error');
1788
1772
- ReactTestUtils.renderIntoDocument(React.createElement('label', {for: 'test'}));
1773
- ReactTestUtils.renderIntoDocument(React.createElement('input', {type: 'text', autofocus: true}));
1789
+ ReactTestUtils.renderIntoDocument(
1790
+ React.createElement('label', {for: 'test'}),
1791
+ );
1792
+ ReactTestUtils.renderIntoDocument(
1793
+ React.createElement('input', {type: 'text', autofocus: true}),
1794
+ );
1795
1796
expectDev(console.error.calls.count()).toBe(2);
1797
1798
expectDev(console.error.calls.argsFor(0)[0]).toBe(
1778
- 'Warning: Unknown DOM property for. Did you mean htmlFor?\n in label'
1799
+ 'Warning: Unknown DOM property for. Did you mean htmlFor?\n in label',
1800
);
1801
1802
expectDev(console.error.calls.argsFor(1)[0]).toBe(
1782
- 'Warning: Unknown DOM property autofocus. Did you mean autoFocus?\n in input'
1803
+ 'Warning: Unknown DOM property autofocus. Did you mean autoFocus?\n in input',
1804
);
1805
});
1806
1807
it('should suggest property name if available (ssr)', () => {
1808
spyOn(console, 'error');
1809
1789
- ReactDOMServer.renderToString(React.createElement('label', {for: 'test'}));
1790
- ReactDOMServer.renderToString(React.createElement('input', {type: 'text', autofocus: true}));
1810
+ ReactDOMServer.renderToString(
1811
+ React.createElement('label', {for: 'test'}),
1812
+ );
1813
+ ReactDOMServer.renderToString(
1814
+ React.createElement('input', {type: 'text', autofocus: true}),
1815
+ );
1816
1817
expectDev(console.error.calls.count()).toBe(2);
1818
1819
expectDev(console.error.calls.argsFor(0)[0]).toBe(
1795
- 'Warning: Unknown DOM property for. Did you mean htmlFor?\n in label'
1820
+ 'Warning: Unknown DOM property for. Did you mean htmlFor?\n in label',
1821
);
1822
1823
expectDev(console.error.calls.argsFor(1)[0]).toBe(
1799
- 'Warning: Unknown DOM property autofocus. Did you mean autoFocus?\n in input'
1824
+ 'Warning: Unknown DOM property autofocus. Did you mean autoFocus?\n in input',
1825
);
1826
});
1827
});
@@ -1805,7 +1830,7 @@ describe('ReactDOMComponent', () => {
1830
it('renders innerHTML and preserves whitespace', () => {
1831
const container = document.createElement('div');
1832
const html = '\n \t <span> \n testContent \t </span> \n \t';
1808
- const elem = <div dangerouslySetInnerHTML={{ __html: html }} />;
1833
+ const elem = <div dangerouslySetInnerHTML={{__html: html}} />;
1834
1835
ReactDOM.render(elem, container);
1836
expect(container.firstChild.innerHTML).toBe(html);
@@ -1814,11 +1839,11 @@ describe('ReactDOMComponent', () => {
1839
it('render and then updates innerHTML and preserves whitespace', () => {
1840
const container = document.createElement('div');
1841
const html = '\n \t <span> \n testContent1 \t </span> \n \t';
1817
- const elem = <div dangerouslySetInnerHTML={{ __html: html }} />;
1842
+ const elem = <div dangerouslySetInnerHTML={{__html: html}} />;
1843
ReactDOM.render(elem, container);
1844
1845
const html2 = '\n \t <div> \n testContent2 \t </div> \n \t';
1821
- const elem2 = <div dangerouslySetInnerHTML={{ __html: html2 }} />;
1846
+ const elem2 = <div dangerouslySetInnerHTML={{__html: html2}} />;
1847
ReactDOM.render(elem2, container);
1848
1849
expect(container.firstChild.innerHTML).toBe(html2);
src/renderers/dom/shared/__tests__/ReactDOMComponentTree-test.js
+4
-3
@@ -102,7 +102,7 @@ describe('ReactDOMComponentTree', () => {
102
103
function renderAndGetClosest(sel) {
104
return ReactDOMComponentTree.getClosestInstanceFromNode(
105
- renderAndQuery(sel)
105
+ renderAndQuery(sel),
106
);
107
}
108
@@ -115,11 +115,12 @@ describe('ReactDOMComponentTree', () => {
115
116
// This one's a text component!
117
var root = renderAndQuery(null);
118
- var inst = ReactDOMComponentTree.getInstanceFromNode(root.children[0].childNodes[2]);
118
+ var inst = ReactDOMComponentTree.getInstanceFromNode(
119
+ root.children[0].childNodes[2],
120
+ );
121
expect(getTextOf(inst)).toBe('goodbye.');
122
123
expect(getTypeOf(renderAndGetClosest('b'))).toBe('main');
124
expect(getTypeOf(renderAndGetClosest('img'))).toBe('main');
125
});
124
-
126
});
src/renderers/dom/shared/__tests__/ReactDOMInvalidARIAHook-test.js
+7
-9
@@ -38,21 +38,19 @@ describe('ReactDOMInvalidARIAHook', () => {
38
expectDev(console.error.calls.count()).toBe(1);
39
expectDev(console.error.calls.argsFor(0)[0]).toContain(
40
'Warning: Invalid aria prop `aria-badprop` on <div> tag. ' +
41
- 'For details, see https://fb.me/invalid-aria-prop'
41
+ 'For details, see https://fb.me/invalid-aria-prop',
42
);
43
});
44
it('should warn for many invalid aria-* props', () => {
45
spyOn(console, 'error');
46
- mountComponent(
47
- {
48
- 'aria-badprop': 'Very tall trees',
49
- 'aria-malprop': 'Turbulent seas',
50
- }
51
- );
46
+ mountComponent({
47
+ 'aria-badprop': 'Very tall trees',
48
+ 'aria-malprop': 'Turbulent seas',
49
+ });
50
expectDev(console.error.calls.count()).toBe(1);
51
expectDev(console.error.calls.argsFor(0)[0]).toContain(
52
'Warning: Invalid aria props `aria-badprop`, `aria-malprop` on <div> ' +
55
- 'tag. For details, see https://fb.me/invalid-aria-prop'
53
+ 'tag. For details, see https://fb.me/invalid-aria-prop',
54
);
55
});
56
it('should warn for an improperly cased aria-* prop', () => {
@@ -62,7 +60,7 @@ describe('ReactDOMInvalidARIAHook', () => {
60
expectDev(console.error.calls.count()).toBe(1);
61
expectDev(console.error.calls.argsFor(0)[0]).toContain(
62
'Warning: Unknown ARIA attribute aria-hasPopup. ' +
65
- 'Did you mean aria-haspopup?'
63
+ 'Did you mean aria-haspopup?',
64
);
65
});
66
});
src/renderers/dom/shared/__tests__/ReactDOMSVG-test.js
+69
-29
@@ -17,7 +17,6 @@ var ReactDOMFeatureFlags;
17
var ReactDOMServer;
18
19
describe('ReactDOMSVG', () => {
20
-
20
beforeEach(() => {
21
React = require('react');
22
ReactDOM = require('react-dom');
@@ -29,14 +28,27 @@ describe('ReactDOMSVG', () => {
28
var markup = ReactDOMServer.renderToString(
29
<svg>
30
<image xlinkHref="http://i.imgur.com/w7GCRPb.png" />
32
- </svg>
31
+ </svg>,
32
);
33
expect(markup).toContain('xlink:href="http://i.imgur.com/w7GCRPb.png"');
34
});
35
36
it('creates elements with SVG namespace inside SVG tag during mount', () => {
37
var node = document.createElement('div');
39
- var div, div2, div3, foreignObject, foreignObject2, g, image, image2, image3, p, svg, svg2, svg3, svg4;
38
+ var div,
39
+ div2,
40
+ div3,
41
+ foreignObject,
42
+ foreignObject2,
43
+ g,
44
+ image,
45
+ image2,
46
+ image3,
47
+ p,
48
+ svg,
49
+ svg2,
50
+ svg3,
51
+ svg4;
52
ReactDOM.render(
53
<div>
54
<svg ref={el => svg = el}>
@@ -45,12 +57,18 @@ describe('ReactDOMSVG', () => {
57
<foreignObject ref={el => foreignObject = el}>
58
<svg ref={el => svg3 = el}>
59
<svg ref={el => svg4 = el} />
48
- <image ref={el => image = el} xlinkHref="http://i.imgur.com/w7GCRPb.png" />
60
+ <image
61
+ ref={el => image = el}
62
+ xlinkHref="http://i.imgur.com/w7GCRPb.png"
63
+ />
64
</svg>
65
<div ref={el => div = el} />
66
</foreignObject>
67
</svg>
53
- <image ref={el => image2 = el} xlinkHref="http://i.imgur.com/w7GCRPb.png" />
68
+ <image
69
+ ref={el => image2 = el}
70
+ xlinkHref="http://i.imgur.com/w7GCRPb.png"
71
+ />
72
<foreignObject ref={el => foreignObject2 = el}>
73
<div ref={el => div2 = el} />
74
</foreignObject>
@@ -58,12 +76,15 @@ describe('ReactDOMSVG', () => {
76
</svg>
77
<p ref={el => p = el}>
78
<svg>
61
- <image ref={el => image3 = el} xlinkHref="http://i.imgur.com/w7GCRPb.png" />
79
+ <image
80
+ ref={el => image3 = el}
81
+ xlinkHref="http://i.imgur.com/w7GCRPb.png"
82
+ />
83
</svg>
84
</p>
85
<div ref={el => div3 = el} />
86
</div>,
66
- node
87
+ node,
88
);
89
[svg, svg2, svg3, svg4].forEach(el => {
90
expect(el.namespaceURI).toBe('http://www.w3.org/2000/svg');
@@ -79,9 +100,9 @@ describe('ReactDOMSVG', () => {
100
[image, image2, image3].forEach(el => {
101
expect(el.namespaceURI).toBe('http://www.w3.org/2000/svg');
102
expect(el.tagName).toBe('image');
82
- expect(
83
- el.getAttributeNS('http://www.w3.org/1999/xlink', 'href')
84
- ).toBe('http://i.imgur.com/w7GCRPb.png');
103
+ expect(el.getAttributeNS('http://www.w3.org/1999/xlink', 'href')).toBe(
104
+ 'http://i.imgur.com/w7GCRPb.png',
105
+ );
106
});
107
[foreignObject, foreignObject2].forEach(el => {
108
expect(el.namespaceURI).toBe('http://www.w3.org/2000/svg');
@@ -94,7 +115,18 @@ describe('ReactDOMSVG', () => {
115
});
116
117
it('creates elements with SVG namespace inside SVG tag during update', () => {
97
- var inst, div, div2, foreignObject, foreignObject2, g, image, image2, svg, svg2, svg3, svg4;
118
+ var inst,
119
+ div,
120
+ div2,
121
+ foreignObject,
122
+ foreignObject2,
123
+ g,
124
+ image,
125
+ image2,
126
+ svg,
127
+ svg2,
128
+ svg3,
129
+ svg4;
130
131
class App extends React.Component {
132
state = {step: 0};
@@ -110,12 +142,18 @@ describe('ReactDOMSVG', () => {
142
<foreignObject ref={el => foreignObject = el}>
143
<svg ref={el => svg3 = el}>
144
<svg ref={el => svg4 = el} />
113
- <image ref={el => image = el} xlinkHref="http://i.imgur.com/w7GCRPb.png" />
145
+ <image
146
+ ref={el => image = el}
147
+ xlinkHref="http://i.imgur.com/w7GCRPb.png"
148
+ />
149
</svg>
150
<div ref={el => div = el} />
151
</foreignObject>
152
</svg>
118
- <image ref={el => image2 = el} xlinkHref="http://i.imgur.com/w7GCRPb.png" />
153
+ <image
154
+ ref={el => image2 = el}
155
+ xlinkHref="http://i.imgur.com/w7GCRPb.png"
156
+ />
157
<foreignObject ref={el => foreignObject2 = el}>
158
<div ref={el => div2 = el} />
159
</foreignObject>
@@ -129,7 +167,7 @@ describe('ReactDOMSVG', () => {
167
<svg ref={el => svg = el}>
168
<App />
169
</svg>,
132
- node
170
+ node,
171
);
172
inst.setState({step: 1});
173
@@ -144,9 +182,9 @@ describe('ReactDOMSVG', () => {
182
[image, image2].forEach(el => {
183
expect(el.namespaceURI).toBe('http://www.w3.org/2000/svg');
184
expect(el.tagName).toBe('image');
147
- expect(
148
- el.getAttributeNS('http://www.w3.org/1999/xlink', 'href')
149
- ).toBe('http://i.imgur.com/w7GCRPb.png');
185
+ expect(el.getAttributeNS('http://www.w3.org/1999/xlink', 'href')).toBe(
186
+ 'http://i.imgur.com/w7GCRPb.png',
187
+ );
188
});
189
[foreignObject, foreignObject2].forEach(el => {
190
expect(el.namespaceURI).toBe('http://www.w3.org/2000/svg');
@@ -160,14 +198,14 @@ describe('ReactDOMSVG', () => {
198
});
199
200
it('can render SVG into a non-React SVG tree', () => {
163
- var outerSVGRoot = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
201
+ var outerSVGRoot = document.createElementNS(
202
+ 'http://www.w3.org/2000/svg',
203
+ 'svg',
204
+ );
205
var container = document.createElementNS('http://www.w3.org/2000/svg', 'g');
206
outerSVGRoot.appendChild(container);
207
var image;
167
- ReactDOM.render(
168
- <image ref={el => image = el} />,
169
- container
170
- );
208
+ ReactDOM.render(<image ref={el => image = el} />, container);
209
expect(image.namespaceURI).toBe('http://www.w3.org/2000/svg');
210
expect(image.tagName).toBe('image');
211
});
@@ -182,16 +220,18 @@ describe('ReactDOMSVG', () => {
220
return;
221
}
222
185
- var outerSVGRoot = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
186
- var container = document.createElementNS('http://www.w3.org/2000/svg', 'foreignObject');
223
+ var outerSVGRoot = document.createElementNS(
224
+ 'http://www.w3.org/2000/svg',
225
+ 'svg',
226
+ );
227
+ var container = document.createElementNS(
228
+ 'http://www.w3.org/2000/svg',
229
+ 'foreignObject',
230
+ );
231
outerSVGRoot.appendChild(container);
232
var div;
189
- ReactDOM.render(
190
- <div ref={el => div = el} />,
191
- container
192
- );
233
+ ReactDOM.render(<div ref={el => div = el} />, container);
234
expect(div.namespaceURI).toBe('http://www.w3.org/1999/xhtml');
235
expect(div.tagName).toBe('DIV');
236
});
196
-
237
});
src/renderers/dom/shared/__tests__/ReactDOMServerIntegration-test.js
+16
-13
@@ -34,8 +34,12 @@ async function expectErrors(fn, count) {
34
}
35
36
const result = await fn();
37
- if (console.error.calls.count() !== count && console.error.calls.count() !== 0) {
38
- console.log(`We expected ${count} warning(s), but saw ${console.error.calls.count()} warning(s).`);
37
+ if (
38
+ console.error.calls.count() !== count && console.error.calls.count() !== 0
39
+ ) {
40
+ console.log(
41
+ `We expected ${count} warning(s), but saw ${console.error.calls.count()} warning(s).`,
42
+ );
43
if (console.error.calls.count() > 0) {
44
console.log(`We saw these warnings:`);
45
for (var i = 0; i < console.error.calls.count(); i++) {
@@ -57,7 +61,7 @@ function renderIntoDom(reactElement, domElement, errorCount = 0) {
61
ExecutionEnvironment.canUseDOM = false;
62
return domElement.firstChild;
63
},
60
- errorCount
64
+ errorCount,
65
);
66
}
67
@@ -67,7 +71,7 @@ function renderIntoDom(reactElement, domElement, errorCount = 0) {
71
async function serverRender(reactElement, errorCount = 0) {
72
const markup = await expectErrors(
73
() => Promise.resolve(ReactDOMServer.renderToString(reactElement)),
70
- errorCount
74
+ errorCount,
75
);
76
var domElement = document.createElement('div');
77
domElement.innerHTML = markup;
@@ -107,8 +111,7 @@ const clientRenderOnBadMarkup = (element, errorCount = 0) => {
111
// render; you should not depend on the interactivity of the returned DOM element,
112
// as that will not work in the server string scenario.
113
function itRenders(desc, testFn) {
110
- it(`renders ${desc} with server string render`,
111
- () => testFn(serverRender));
114
+ it(`renders ${desc} with server string render`, () => testFn(serverRender));
115
itClientRenders(desc, testFn);
116
}
117
@@ -124,12 +127,12 @@ function itRenders(desc, testFn) {
127
// Since all of the renders in this function are on the client, you can test interactivity,
128
// unlike with itRenders.
129
function itClientRenders(desc, testFn) {
127
- it(`renders ${desc} with clean client render`,
128
- () => testFn(clientCleanRender));
129
- it(`renders ${desc} with client render on top of good server markup`,
130
- () => testFn(clientRenderOnServerString));
131
- it(`renders ${desc} with client render on top of bad server markup`,
132
- () => testFn(clientRenderOnBadMarkup));
130
+ it(`renders ${desc} with clean client render`, () =>
131
+ testFn(clientCleanRender));
132
+ it(`renders ${desc} with client render on top of good server markup`, () =>
133
+ testFn(clientRenderOnServerString));
134
+ it(`renders ${desc} with client render on top of bad server markup`, () =>
135
+ testFn(clientRenderOnBadMarkup));
136
}
137
138
describe('ReactDOMServerIntegration', () => {
@@ -150,7 +153,7 @@ describe('ReactDOMServerIntegration', () => {
153
});
154
155
itRenders('a div with inline styles', async render => {
153
- const e = await render(<div style={{color:'red', width:'30px'}} />);
156
+ const e = await render(<div style={{color: 'red', width: '30px'}} />);
157
expect(e.style.color).toBe('red');
158
expect(e.style.width).toBe('30px');
159
});
src/renderers/dom/shared/__tests__/ReactDOMTextComponent-test.js
+33
-9
@@ -76,7 +76,10 @@ describe('ReactDOMTextComponent', () => {
76
77
it('can reconcile text merged by Node.normalize() alongside other elements', () => {
78
var el = document.createElement('div');
79
- var inst = ReactDOM.render(<div>{'foo'}{'bar'}{'baz'}<span />{'qux'}</div>, el);
79
+ var inst = ReactDOM.render(
80
+ <div>{'foo'}{'bar'}{'baz'}<span />{'qux'}</div>,
81
+ el,
82
+ );
83
84
var container = ReactDOM.findDOMNode(inst);
85
container.normalize();
@@ -121,8 +124,14 @@ describe('ReactDOMTextComponent', () => {
124
let childNodes = filterOutComments(ReactDOM.findDOMNode(inst).childNodes);
125
let textNode = childNodes[1];
126
textNode.textContent = 'foo';
124
- container.insertBefore(document.createTextNode('bar'), childNodes[1].nextSibling);
125
- container.insertBefore(document.createTextNode('baz'), childNodes[1].nextSibling);
127
+ container.insertBefore(
128
+ document.createTextNode('bar'),
129
+ childNodes[1].nextSibling,
130
+ );
131
+ container.insertBefore(
132
+ document.createTextNode('baz'),
133
+ childNodes[1].nextSibling,
134
+ );
135
136
inst = ReactDOM.render(<div><span />{'barbazqux'}</div>, el);
137
container = ReactDOM.findDOMNode(inst);
@@ -131,19 +140,34 @@ describe('ReactDOMTextComponent', () => {
140
141
it('can reconcile text arbitrarily split into multiple nodes on some substitutions only', () => {
142
var el = document.createElement('div');
134
- var inst = ReactDOM.render(<div><span />{'bar'}<span />{'foobarbaz'}{'foo'}{'barfoo'}<span /></div>, el);
143
+ var inst = ReactDOM.render(
144
+ <div><span />{'bar'}<span />{'foobarbaz'}{'foo'}{'barfoo'}<span /></div>,
145
+ el,
146
+ );
147
148
var container = ReactDOM.findDOMNode(inst);
149
let childNodes = filterOutComments(ReactDOM.findDOMNode(inst).childNodes);
150
let textNode = childNodes[3];
151
textNode.textContent = 'foo';
140
- container.insertBefore(document.createTextNode('bar'), childNodes[3].nextSibling);
141
- container.insertBefore(document.createTextNode('baz'), childNodes[3].nextSibling);
152
+ container.insertBefore(
153
+ document.createTextNode('bar'),
154
+ childNodes[3].nextSibling,
155
+ );
156
+ container.insertBefore(
157
+ document.createTextNode('baz'),
158
+ childNodes[3].nextSibling,
159
+ );
160
let secondTextNode = childNodes[5];
161
secondTextNode.textContent = 'bar';
144
- container.insertBefore(document.createTextNode('foo'), childNodes[5].nextSibling);
145
-
146
- inst = ReactDOM.render(<div><span />{'baz'}<span />{'barbazqux'}{'bar'}{'bazbar'}<span /></div>, el);
162
+ container.insertBefore(
163
+ document.createTextNode('foo'),
164
+ childNodes[5].nextSibling,
165
+ );
166
+
167
+ inst = ReactDOM.render(
168
+ <div><span />{'baz'}<span />{'barbazqux'}{'bar'}{'bazbar'}<span /></div>,
169
+ el,
170
+ );
171
container = ReactDOM.findDOMNode(inst);
172
expect(container.textContent).toBe('bazbarbazquxbarbazbar');
173
});
src/renderers/dom/shared/__tests__/ReactEventIndependence-test.js
+3
-4
@@ -32,7 +32,7 @@ describe('ReactEventIndependence', () => {
32
dangerouslySetInnerHTML={{
33
__html: '<button data-reactid=".z">click me</div>',
34
}}
35
- />
35
+ />,
36
);
37
ReactTestUtils.SimulateNative.click(div.firstChild);
38
expect(clicks).toBe(1);
@@ -44,7 +44,7 @@ describe('ReactEventIndependence', () => {
44
outer.setAttribute('data-reactid', '.z');
45
var inner = ReactDOM.render(
46
<button onClick={() => clicks++}>click me</button>,
47
- outer
47
+ outer,
48
);
49
ReactTestUtils.SimulateNative.click(inner);
50
expect(clicks).toBe(1);
@@ -55,7 +55,7 @@ describe('ReactEventIndependence', () => {
55
var container = document.createElement('div');
56
var button = ReactDOM.render(
57
<button onClick={() => clicks++}>click me</button>,
58
- container
58
+ container,
59
);
60
61
// Now we unmount the component, as if caused by a non-React event handler
@@ -66,5 +66,4 @@ describe('ReactEventIndependence', () => {
66
// Since the tree is unmounted, we don't dispatch the click event.
67
expect(clicks).toBe(0);
68
});
69
-
69
});
src/renderers/dom/shared/__tests__/ReactEventListener-test.js
+50
-51
@@ -11,7 +11,6 @@
11
12
'use strict';
13
14
-
14
var EVENT_TARGET_PARAM = 1;
15
16
describe('ReactEventListener', () => {
@@ -38,19 +37,16 @@ describe('ReactEventListener', () => {
37
var otherNode = document.createElement('h1');
38
var component = ReactDOM.render(<div />, document.createElement('div'));
39
expect(handleTopLevel.mock.calls.length).toBe(0);
41
- ReactEventListener.dispatchEvent(
42
- 'topMouseOut',
43
- {
44
- type: 'mouseout',
45
- fromElement: otherNode,
46
- target: otherNode,
47
- srcElement: otherNode,
48
- toElement: ReactDOM.findDOMNode(component),
49
- relatedTarget: ReactDOM.findDOMNode(component),
50
- view: window,
51
- path: [otherNode, otherNode],
52
- },
53
- );
40
+ ReactEventListener.dispatchEvent('topMouseOut', {
41
+ type: 'mouseout',
42
+ fromElement: otherNode,
43
+ target: otherNode,
44
+ srcElement: otherNode,
45
+ toElement: ReactDOM.findDOMNode(component),
46
+ relatedTarget: ReactDOM.findDOMNode(component),
47
+ view: window,
48
+ path: [otherNode, otherNode],
49
+ });
50
expect(handleTopLevel.mock.calls.length).toBe(1);
51
});
52
@@ -61,8 +57,7 @@ describe('ReactEventListener', () => {
57
var parentContainer = document.createElement('div');
58
var parentControl = <div>Parent</div>;
59
childControl = ReactDOM.render(childControl, childContainer);
64
- parentControl =
65
- ReactDOM.render(parentControl, parentContainer);
60
+ parentControl = ReactDOM.render(parentControl, parentContainer);
61
ReactDOM.findDOMNode(parentControl).appendChild(childContainer);
62
63
var callback = ReactEventListener.dispatchEvent.bind(null, 'test');
@@ -72,10 +67,12 @@ describe('ReactEventListener', () => {
67
68
var calls = handleTopLevel.mock.calls;
69
expect(calls.length).toBe(2);
75
- expect(calls[0][EVENT_TARGET_PARAM])
76
- .toBe(ReactDOMComponentTree.getInstanceFromNode(childControl));
77
- expect(calls[1][EVENT_TARGET_PARAM])
78
- .toBe(ReactDOMComponentTree.getInstanceFromNode(parentControl));
70
+ expect(calls[0][EVENT_TARGET_PARAM]).toBe(
71
+ ReactDOMComponentTree.getInstanceFromNode(childControl),
72
+ );
73
+ expect(calls[1][EVENT_TARGET_PARAM]).toBe(
74
+ ReactDOMComponentTree.getInstanceFromNode(parentControl),
75
+ );
76
});
77
78
it('should propagate events two levels down', () => {
@@ -86,10 +83,11 @@ describe('ReactEventListener', () => {
83
var grandParentContainer = document.createElement('div');
84
var grandParentControl = <div>Parent</div>;
85
childControl = ReactDOM.render(childControl, childContainer);
89
- parentControl =
90
- ReactDOM.render(parentControl, parentContainer);
91
- grandParentControl =
92
- ReactDOM.render(grandParentControl, grandParentContainer);
86
+ parentControl = ReactDOM.render(parentControl, parentContainer);
87
+ grandParentControl = ReactDOM.render(
88
+ grandParentControl,
89
+ grandParentContainer,
90
+ );
91
ReactDOM.findDOMNode(parentControl).appendChild(childContainer);
92
ReactDOM.findDOMNode(grandParentControl).appendChild(parentContainer);
93
@@ -100,12 +98,15 @@ describe('ReactEventListener', () => {
98
99
var calls = handleTopLevel.mock.calls;
100
expect(calls.length).toBe(3);
103
- expect(calls[0][EVENT_TARGET_PARAM])
104
- .toBe(ReactDOMComponentTree.getInstanceFromNode(childControl));
105
- expect(calls[1][EVENT_TARGET_PARAM])
106
- .toBe(ReactDOMComponentTree.getInstanceFromNode(parentControl));
107
- expect(calls[2][EVENT_TARGET_PARAM])
108
- .toBe(ReactDOMComponentTree.getInstanceFromNode(grandParentControl));
101
+ expect(calls[0][EVENT_TARGET_PARAM]).toBe(
102
+ ReactDOMComponentTree.getInstanceFromNode(childControl),
103
+ );
104
+ expect(calls[1][EVENT_TARGET_PARAM]).toBe(
105
+ ReactDOMComponentTree.getInstanceFromNode(parentControl),
106
+ );
107
+ expect(calls[2][EVENT_TARGET_PARAM]).toBe(
108
+ ReactDOMComponentTree.getInstanceFromNode(grandParentControl),
109
+ );
110
});
111
112
it('should not get confused by disappearing elements', () => {
@@ -114,8 +115,7 @@ describe('ReactEventListener', () => {
115
var parentContainer = document.createElement('div');
116
var parentControl = <div>Parent</div>;
117
childControl = ReactDOM.render(childControl, childContainer);
117
- parentControl =
118
- ReactDOM.render(parentControl, parentContainer);
118
+ parentControl = ReactDOM.render(parentControl, parentContainer);
119
ReactDOM.findDOMNode(parentControl).appendChild(childContainer);
120
121
// ReactBrowserEventEmitter.handleTopLevel might remove the
@@ -128,7 +128,7 @@ describe('ReactEventListener', () => {
128
if (topLevelTarget === childNode) {
129
ReactDOM.unmountComponentAtNode(childContainer);
130
}
131
- }
131
+ },
132
);
133
134
var callback = ReactEventListener.dispatchEvent.bind(null, 'test');
@@ -138,23 +138,19 @@ describe('ReactEventListener', () => {
138
139
var calls = handleTopLevel.mock.calls;
140
expect(calls.length).toBe(2);
141
- expect(calls[0][EVENT_TARGET_PARAM])
142
- .toBe(ReactDOMComponentTree.getInstanceFromNode(childNode));
143
- expect(calls[1][EVENT_TARGET_PARAM])
144
- .toBe(ReactDOMComponentTree.getInstanceFromNode(parentControl));
141
+ expect(calls[0][EVENT_TARGET_PARAM]).toBe(
142
+ ReactDOMComponentTree.getInstanceFromNode(childNode),
143
+ );
144
+ expect(calls[1][EVENT_TARGET_PARAM]).toBe(
145
+ ReactDOMComponentTree.getInstanceFromNode(parentControl),
146
+ );
147
});
148
149
it('should batch between handlers from different roots', () => {
150
var childContainer = document.createElement('div');
151
var parentContainer = document.createElement('div');
150
- var childControl = ReactDOM.render(
151
- <div>Child</div>,
152
- childContainer
153
- );
154
- var parentControl = ReactDOM.render(
155
- <div>Parent</div>,
156
- parentContainer
157
- );
152
+ var childControl = ReactDOM.render(<div>Child</div>, childContainer);
153
+ var parentControl = ReactDOM.render(<div>Parent</div>, parentContainer);
154
ReactDOM.findDOMNode(parentControl).appendChild(childContainer);
155
156
// Suppose an event handler in each root enqueues an update to the
@@ -164,15 +160,17 @@ describe('ReactEventListener', () => {
160
function(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) {
161
ReactDOM.render(
162
<div>{topLevelTarget === childNode ? '1' : '2'}</div>,
167
- childContainer
163
+ childContainer,
164
);
165
// Since we're batching, neither update should yet have gone through.
166
expect(childNode.textContent).toBe('Child');
171
- }
167
+ },
168
);
169
174
- var callback =
175
- ReactEventListener.dispatchEvent.bind(ReactEventListener, 'test');
170
+ var callback = ReactEventListener.dispatchEvent.bind(
171
+ ReactEventListener,
172
+ 'test',
173
+ );
174
callback({
175
target: childNode,
176
});
@@ -204,7 +202,8 @@ describe('ReactEventListener', () => {
202
203
var calls = handleTopLevel.mock.calls;
204
expect(calls.length).toBe(1);
207
- expect(calls[0][EVENT_TARGET_PARAM])
208
- .toBe(ReactDOMComponentTree.getInstanceFromNode(instance.getInner()));
205
+ expect(calls[0][EVENT_TARGET_PARAM]).toBe(
206
+ ReactDOMComponentTree.getInstanceFromNode(instance.getInner()),
207
+ );
208
});
209
});
src/renderers/dom/shared/__tests__/ReactMount-test.js
+13
-12
@@ -43,7 +43,7 @@ describe('ReactMount', () => {
43
expect(function() {
44
ReactDOM.unmountComponentAtNode(nodeArray);
45
}).toThrowError(
46
- 'unmountComponentAtNode(...): Target container is not a DOM element.'
46
+ 'unmountComponentAtNode(...): Target container is not a DOM element.',
47
);
48
});
49
});
@@ -53,7 +53,7 @@ describe('ReactMount', () => {
53
ReactTestUtils.renderIntoDocument('div');
54
}).toThrowError(
55
'ReactDOM.render(): Invalid component element. Instead of passing a ' +
56
- 'string like \'div\', pass React.createElement(\'div\') or <div />.'
56
+ "string like 'div', pass React.createElement('div') or <div />.",
57
);
58
});
59
@@ -68,7 +68,7 @@ describe('ReactMount', () => {
68
ReactTestUtils.renderIntoDocument(Component);
69
}).toThrowError(
70
'ReactDOM.render(): Invalid component element. Instead of passing a ' +
71
- 'class like Foo, pass React.createElement(Foo) or <Foo />.'
71
+ 'class like Foo, pass React.createElement(Foo) or <Foo />.',
72
);
73
});
74
@@ -158,25 +158,26 @@ describe('ReactMount', () => {
158
159
expectDev(console.error.calls.count()).toBe(1);
160
expectDev(console.error.calls.argsFor(0)[0]).toContain(
161
- 'Rendering components directly into document.body is discouraged'
161
+ 'Rendering components directly into document.body is discouraged',
162
);
163
});
164
165
it('should account for escaping on a checksum mismatch', () => {
166
var div = document.createElement('div');
167
var markup = ReactDOMServer.renderToString(
168
- <div>This markup contains an nbsp entity: server text</div>);
168
+ <div>This markup contains an nbsp entity: server text</div>,
169
+ );
170
div.innerHTML = markup;
171
172
spyOn(console, 'error');
173
ReactDOM.render(
174
<div>This markup contains an nbsp entity: client text</div>,
174
- div
175
+ div,
176
);
177
expectDev(console.error.calls.count()).toBe(1);
178
expectDev(console.error.calls.argsFor(0)[0]).toContain(
179
' (client) nbsp entity: client text</div>\n' +
179
- ' (server) nbsp entity: server text</div>'
180
+ ' (server) nbsp entity: server text</div>',
181
);
182
});
183
@@ -221,9 +222,9 @@ describe('ReactMount', () => {
222
expectDev(console.error.calls.count()).toBe(1);
223
expectDev(console.error.calls.argsFor(0)[0]).toBe(
224
'Warning: render(...): Replacing React-rendered children with a new ' +
224
- 'root component. If you intended to update the children of this node, ' +
225
- 'you should instead have the existing children update their state and ' +
226
- 'render the new components instead of calling ReactDOM.render.'
225
+ 'root component. If you intended to update the children of this node, ' +
226
+ 'you should instead have the existing children update their state and ' +
227
+ 'render the new components instead of calling ReactDOM.render.',
228
);
229
});
230
@@ -246,8 +247,8 @@ describe('ReactMount', () => {
247
ReactDOMOther.unmountComponentAtNode(container);
248
expectDev(console.error.calls.count()).toBe(1);
249
expectDev(console.error.calls.argsFor(0)[0]).toBe(
249
- 'Warning: unmountComponentAtNode(): The node you\'re attempting to unmount ' +
250
- 'was rendered by another copy of React.'
250
+ "Warning: unmountComponentAtNode(): The node you're attempting to unmount " +
251
+ 'was rendered by another copy of React.',
252
);
253
254
// Don't throw a warning if the correct React copy unmounts the node
src/renderers/dom/shared/__tests__/ReactMountDestruction-test.js
+14
-12
@@ -43,10 +43,11 @@ describe('ReactMount', () => {
43
it('should warn when unmounting a non-container root node', () => {
44
var mainContainerDiv = document.createElement('div');
45
46
- var component =
46
+ var component = (
47
<div>
48
<div />
49
- </div>;
49
+ </div>
50
+ );
51
ReactDOM.render(component, mainContainerDiv);
52
53
// Test that unmounting at a root node gives a helpful warning
@@ -55,22 +56,23 @@ describe('ReactMount', () => {
56
ReactDOM.unmountComponentAtNode(rootDiv);
57
expectDev(console.error.calls.count()).toBe(1);
58
expectDev(console.error.calls.argsFor(0)[0]).toBe(
58
- 'Warning: unmountComponentAtNode(): The node you\'re attempting to ' +
59
- 'unmount was rendered by React and is not a top-level container. You ' +
60
- 'may have accidentally passed in a React root node instead of its ' +
61
- 'container.'
59
+ "Warning: unmountComponentAtNode(): The node you're attempting to " +
60
+ 'unmount was rendered by React and is not a top-level container. You ' +
61
+ 'may have accidentally passed in a React root node instead of its ' +
62
+ 'container.',
63
);
64
});
65
66
it('should warn when unmounting a non-container, non-root node', () => {
67
var mainContainerDiv = document.createElement('div');
68
68
- var component =
69
+ var component = (
70
<div>
71
<div>
72
<div />
73
</div>
73
- </div>;
74
+ </div>
75
+ );
76
ReactDOM.render(component, mainContainerDiv);
77
78
// Test that unmounting at a non-root node gives a different warning
@@ -79,10 +81,10 @@ describe('ReactMount', () => {
81
ReactDOM.unmountComponentAtNode(nonRootDiv);
82
expectDev(console.error.calls.count()).toBe(1);
83
expectDev(console.error.calls.argsFor(0)[0]).toBe(
82
- 'Warning: unmountComponentAtNode(): The node you\'re attempting to ' +
83
- 'unmount was rendered by React and is not a top-level container. ' +
84
- 'Instead, have the parent component update its state and rerender in ' +
85
- 'order to remove this component.'
84
+ "Warning: unmountComponentAtNode(): The node you're attempting to " +
85
+ 'unmount was rendered by React and is not a top-level container. ' +
86
+ 'Instead, have the parent component update its state and rerender in ' +
87
+ 'order to remove this component.',
88
);
89
});
90
});
src/renderers/dom/shared/__tests__/ReactRenderDocument-test.js
+20
-20
@@ -19,8 +19,7 @@ var getTestDocument;
19
20
var testDocument;
21
22
-var UNMOUNT_INVARIANT_MESSAGE =
23
- '<html> tried to unmount. ' +
22
+var UNMOUNT_INVARIANT_MESSAGE = '<html> tried to unmount. ' +
23
'Because of cross-browser quirks it is impossible to unmount some ' +
24
'top-level components (eg <html>, <head>, and <body>) reliably and ' +
25
'efficiently. To fix this, have a single top-level component that ' +
@@ -166,7 +165,7 @@ describe('rendering React components at document', () => {
165
}
166
167
var markup = ReactDOMServer.renderToString(
169
- <Component text="Hello world" />
168
+ <Component text="Hello world" />,
169
);
170
testDocument = getTestDocument(markup);
171
@@ -194,7 +193,7 @@ describe('rendering React components at document', () => {
193
}
194
195
var markup = ReactDOMServer.renderToString(
197
- <Component text="Goodbye world" />
196
+ <Component text="Goodbye world" />,
197
);
198
testDocument = getTestDocument(markup);
199
@@ -202,16 +201,16 @@ describe('rendering React components at document', () => {
201
// Notice the text is different!
202
ReactDOM.render(<Component text="Hello world" />, testDocument);
203
}).toThrowError(
205
- 'You\'re trying to render a component to the document using ' +
206
- 'server rendering but the checksum was invalid. This usually ' +
207
- 'means you rendered a different component type or props on ' +
208
- 'the client from the one on the server, or your render() methods ' +
209
- 'are impure. React cannot handle this case due to cross-browser ' +
210
- 'quirks by rendering at the document root. You should look for ' +
211
- 'environment dependent code in your components and ensure ' +
212
- 'the props are the same client and server side:\n' +
213
- ' (client) dy data-reactid="4">Hello world</body></\n' +
214
- ' (server) dy data-reactid="4">Goodbye world</body>'
204
+ "You're trying to render a component to the document using " +
205
+ 'server rendering but the checksum was invalid. This usually ' +
206
+ 'means you rendered a different component type or props on ' +
207
+ 'the client from the one on the server, or your render() methods ' +
208
+ 'are impure. React cannot handle this case due to cross-browser ' +
209
+ 'quirks by rendering at the document root. You should look for ' +
210
+ 'environment dependent code in your components and ensure ' +
211
+ 'the props are the same client and server side:\n' +
212
+ ' (client) dy data-reactid="4">Hello world</body></\n' +
213
+ ' (server) dy data-reactid="4">Goodbye world</body>',
214
);
215
});
216
@@ -238,15 +237,15 @@ describe('rendering React components at document', () => {
237
expect(function() {
238
ReactDOM.render(<Component />, container);
239
}).toThrowError(
241
- 'You\'re trying to render a component to the document but you didn\'t ' +
242
- 'use server rendering. We can\'t do this without using server ' +
243
- 'rendering due to cross-browser quirks. See ' +
244
- 'ReactDOMServer.renderToString() for server rendering.'
240
+ "You're trying to render a component to the document but you didn't " +
241
+ "use server rendering. We can't do this without using server " +
242
+ 'rendering due to cross-browser quirks. See ' +
243
+ 'ReactDOMServer.renderToString() for server rendering.',
244
);
245
});
246
247
it('supports findDOMNode on full-page components', () => {
249
- var tree =
248
+ var tree = (
249
<html>
250
<head>
251
<title>Hello World</title>
@@ -254,7 +253,8 @@ describe('rendering React components at document', () => {
253
<body>
254
Hello world
255
</body>
257
- </html>;
256
+ </html>
257
+ );
258
259
var markup = ReactDOMServer.renderToString(tree);
260
testDocument = getTestDocument(markup);
src/renderers/dom/shared/__tests__/ReactServerRendering-test.js
+96
-86
@@ -44,36 +44,48 @@ describe('ReactDOMServer', () => {
44
45
describe('renderToString', () => {
46
it('should generate simple markup', () => {
47
- var response = ReactDOMServer.renderToString(
48
- <span>hello world</span>
47
+ var response = ReactDOMServer.renderToString(<span>hello world</span>);
48
+ expect(response).toMatch(
49
+ new RegExp(
50
+ '<span ' +
51
+ ROOT_ATTRIBUTE_NAME +
52
+ '="" ' +
53
+ ID_ATTRIBUTE_NAME +
54
+ '="[^"]+" ' +
55
+ ReactMarkupChecksum.CHECKSUM_ATTR_NAME +
56
+ '="[^"]+">hello world</span>',
57
+ ),
58
);
50
- expect(response).toMatch(new RegExp(
51
- '<span ' + ROOT_ATTRIBUTE_NAME + '="" ' +
52
- ID_ATTRIBUTE_NAME + '="[^"]+" ' +
53
- ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="[^"]+">hello world</span>'
54
- ));
59
});
60
61
it('should generate simple markup for self-closing tags', () => {
58
- var response = ReactDOMServer.renderToString(
59
- <img />
62
+ var response = ReactDOMServer.renderToString(<img />);
63
+ expect(response).toMatch(
64
+ new RegExp(
65
+ '<img ' +
66
+ ROOT_ATTRIBUTE_NAME +
67
+ '="" ' +
68
+ ID_ATTRIBUTE_NAME +
69
+ '="[^"]+" ' +
70
+ ReactMarkupChecksum.CHECKSUM_ATTR_NAME +
71
+ '="[^"]+"/>',
72
+ ),
73
);
61
- expect(response).toMatch(new RegExp(
62
- '<img ' + ROOT_ATTRIBUTE_NAME + '="" ' +
63
- ID_ATTRIBUTE_NAME + '="[^"]+" ' +
64
- ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="[^"]+"/>'
65
- ));
74
});
75
76
it('should generate simple markup for attribute with `>` symbol', () => {
69
- var response = ReactDOMServer.renderToString(
70
- <img data-attr=">" />
77
+ var response = ReactDOMServer.renderToString(<img data-attr=">" />);
78
+ expect(response).toMatch(
79
+ new RegExp(
80
+ '<img data-attr=">" ' +
81
+ ROOT_ATTRIBUTE_NAME +
82
+ '="" ' +
83
+ ID_ATTRIBUTE_NAME +
84
+ '="[^"]+" ' +
85
+ ReactMarkupChecksum.CHECKSUM_ATTR_NAME +
86
+ '="[^"]+"/>',
87
+ ),
88
);
72
- expect(response).toMatch(new RegExp(
73
- '<img data-attr=">" ' + ROOT_ATTRIBUTE_NAME + '="" ' +
74
- ID_ATTRIBUTE_NAME + '="[^"]+" ' +
75
- ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="[^"]+"/>'
76
- ));
89
});
90
91
it('should generate comment markup for component returns null', () => {
@@ -102,19 +114,25 @@ describe('ReactDOMServer', () => {
114
}
115
}
116
105
- var response = ReactDOMServer.renderToString(
106
- <Parent />
107
- );
108
- expect(response).toMatch(new RegExp(
109
- '<div ' + ROOT_ATTRIBUTE_NAME + '="" ' +
110
- ID_ATTRIBUTE_NAME + '="[^"]+" ' +
111
- ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="[^"]+">' +
112
- '<span ' + ID_ATTRIBUTE_NAME + '="[^"]+">' +
117
+ var response = ReactDOMServer.renderToString(<Parent />);
118
+ expect(response).toMatch(
119
+ new RegExp(
120
+ '<div ' +
121
+ ROOT_ATTRIBUTE_NAME +
122
+ '="" ' +
123
+ ID_ATTRIBUTE_NAME +
124
+ '="[^"]+" ' +
125
+ ReactMarkupChecksum.CHECKSUM_ATTR_NAME +
126
+ '="[^"]+">' +
127
+ '<span ' +
128
+ ID_ATTRIBUTE_NAME +
129
+ '="[^"]+">' +
130
'<!-- react-text: [0-9]+ -->My name is <!-- /react-text -->' +
131
'<!-- react-text: [0-9]+ -->child<!-- /react-text -->' +
115
- '</span>' +
116
- '</div>'
117
- ));
132
+ '</span>' +
133
+ '</div>',
134
+ ),
135
+ );
136
});
137
138
it('should only execute certain lifecycle methods', () => {
@@ -162,21 +180,27 @@ describe('ReactDOMServer', () => {
180
}
181
}
182
165
- var response = ReactDOMServer.renderToString(
166
- <TestComponent />
167
- );
168
-
169
- expect(response).toMatch(new RegExp(
170
- '<span ' + ROOT_ATTRIBUTE_NAME + '="" ' +
171
- ID_ATTRIBUTE_NAME + '="[^"]+" ' +
172
- ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="[^"]+">' +
173
- '<!-- react-text: [0-9]+ -->Component name: <!-- /react-text -->' +
174
- '<!-- react-text: [0-9]+ -->TestComponent<!-- /react-text -->' +
175
- '</span>'
176
- ));
177
- expect(lifecycle).toEqual(
178
- ['getInitialState', 'componentWillMount', 'render']
183
+ var response = ReactDOMServer.renderToString(<TestComponent />);
184
+
185
+ expect(response).toMatch(
186
+ new RegExp(
187
+ '<span ' +
188
+ ROOT_ATTRIBUTE_NAME +
189
+ '="" ' +
190
+ ID_ATTRIBUTE_NAME +
191
+ '="[^"]+" ' +
192
+ ReactMarkupChecksum.CHECKSUM_ATTR_NAME +
193
+ '="[^"]+">' +
194
+ '<!-- react-text: [0-9]+ -->Component name: <!-- /react-text -->' +
195
+ '<!-- react-text: [0-9]+ -->TestComponent<!-- /react-text -->' +
196
+ '</span>',
197
+ ),
198
);
199
+ expect(lifecycle).toEqual([
200
+ 'getInitialState',
201
+ 'componentWillMount',
202
+ 'render',
203
+ ]);
204
}
205
206
runTest();
@@ -235,9 +259,7 @@ describe('ReactDOMServer', () => {
259
expect(element.innerHTML).toEqual('');
260
261
ExecutionEnvironment.canUseDOM = false;
238
- lastMarkup = ReactDOMServer.renderToString(
239
- <TestComponent name="x" />
240
- );
262
+ lastMarkup = ReactDOMServer.renderToString(<TestComponent name="x" />);
263
ExecutionEnvironment.canUseDOM = true;
264
element.innerHTML = lastMarkup;
265
@@ -248,8 +270,7 @@ describe('ReactDOMServer', () => {
270
if (ReactDOMFeatureFlags.useFiber) {
271
var reactMetaData = /\s+data-react[a-z-]+="[^"]*"/g;
272
var reactComments = /<!-- \/?react-text(: \d+)? -->/g;
251
- expectedMarkup =
252
- expectedMarkup
273
+ expectedMarkup = expectedMarkup
274
.replace(reactMetaData, '')
275
.replace(reactComments, '');
276
}
@@ -281,13 +302,8 @@ describe('ReactDOMServer', () => {
302
303
it('should throw with silly args', () => {
304
expect(
284
- ReactDOMServer.renderToString.bind(
285
- ReactDOMServer,
286
- 'not a component'
287
- )
288
- ).toThrowError(
289
- 'renderToString(): You must pass a valid ReactElement.'
290
- );
305
+ ReactDOMServer.renderToString.bind(ReactDOMServer, 'not a component'),
306
+ ).toThrowError('renderToString(): You must pass a valid ReactElement.');
307
});
308
});
309
@@ -305,9 +321,7 @@ describe('ReactDOMServer', () => {
321
}
322
}
323
308
- var response = ReactDOMServer.renderToStaticMarkup(
309
- <TestComponent />
310
- );
324
+ var response = ReactDOMServer.renderToStaticMarkup(<TestComponent />);
325
326
expect(response).toBe('<span><div>inner text</div></span>');
327
});
@@ -319,9 +333,7 @@ describe('ReactDOMServer', () => {
333
}
334
}
335
322
- var response = ReactDOMServer.renderToStaticMarkup(
323
- <TestComponent />
324
- );
336
+ var response = ReactDOMServer.renderToStaticMarkup(<TestComponent />);
337
338
expect(response).toBe('<span>hello world</span>');
339
});
@@ -371,14 +383,14 @@ describe('ReactDOMServer', () => {
383
}
384
}
385
374
- var response = ReactDOMServer.renderToStaticMarkup(
375
- <TestComponent />
376
- );
386
+ var response = ReactDOMServer.renderToStaticMarkup(<TestComponent />);
387
388
expect(response).toBe('<span>Component name: TestComponent</span>');
379
- expect(lifecycle).toEqual(
380
- ['getInitialState', 'componentWillMount', 'render']
381
- );
389
+ expect(lifecycle).toEqual([
390
+ 'getInitialState',
391
+ 'componentWillMount',
392
+ 'render',
393
+ ]);
394
}
395
396
runTest();
@@ -392,10 +404,10 @@ describe('ReactDOMServer', () => {
404
expect(
405
ReactDOMServer.renderToStaticMarkup.bind(
406
ReactDOMServer,
395
- 'not a component'
396
- )
407
+ 'not a component',
408
+ ),
409
).toThrowError(
398
- 'renderToStaticMarkup(): You must pass a valid ReactElement.'
410
+ 'renderToStaticMarkup(): You must pass a valid ReactElement.',
411
);
412
});
413
@@ -414,9 +426,7 @@ describe('ReactDOMServer', () => {
426
// We shouldn't ever be calling this on the server
427
throw new Error('Browser reconcile transaction should not be used');
428
};
417
- var markup = ReactDOMServer.renderToString(
418
- <Component />
419
- );
429
+ var markup = ReactDOMServer.renderToString(<Component />);
430
expect(markup.indexOf('hello, world') >= 0).toBe(true);
431
});
432
@@ -426,7 +436,7 @@ describe('ReactDOMServer', () => {
436
const staticContent = ReactDOMServer.renderToStaticMarkup(
437
<div>
438
<img src="foo-bar.jpg" />
429
- </div>
439
+ </div>,
440
);
441
return <div dangerouslySetInnerHTML={{__html: staticContent}} />;
442
}
@@ -448,8 +458,8 @@ describe('ReactDOMServer', () => {
458
<div>
459
<StaticComponent />
460
<Component />
451
- </div>
452
- )
461
+ </div>,
462
+ ),
463
).not.toThrow();
464
});
465
});
@@ -473,8 +483,8 @@ describe('ReactDOMServer', () => {
483
expectDev(console.error.calls.count()).toBe(1);
484
expectDev(console.error.calls.mostRecent().args[0]).toBe(
485
'Warning: setState(...): Can only update a mounting component.' +
476
- ' This usually means you called setState() outside componentWillMount() on the server.' +
477
- ' This is a no-op.\n\nPlease check the code for the Foo component.'
486
+ ' This usually means you called setState() outside componentWillMount() on the server.' +
487
+ ' This is a no-op.\n\nPlease check the code for the Foo component.',
488
);
489
var markup = ReactDOMServer.renderToStaticMarkup(<Foo />);
490
expect(markup).toBe('<div>hello</div>');
@@ -499,8 +509,8 @@ describe('ReactDOMServer', () => {
509
expectDev(console.error.calls.count()).toBe(1);
510
expectDev(console.error.calls.mostRecent().args[0]).toBe(
511
'Warning: replaceState(...): Can only update a mounting component. ' +
502
- 'This usually means you called replaceState() outside componentWillMount() on the server. ' +
503
- 'This is a no-op.\n\nPlease check the code for the Bar component.'
512
+ 'This usually means you called replaceState() outside componentWillMount() on the server. ' +
513
+ 'This is a no-op.\n\nPlease check the code for the Bar component.',
514
);
515
var markup = ReactDOMServer.renderToStaticMarkup(<Bar />);
516
expect(markup).toBe('<div>hello</div>');
@@ -526,8 +536,8 @@ describe('ReactDOMServer', () => {
536
expectDev(console.error.calls.count()).toBe(1);
537
expectDev(console.error.calls.mostRecent().args[0]).toBe(
538
'Warning: forceUpdate(...): Can only update a mounting component. ' +
529
- 'This usually means you called forceUpdate() outside componentWillMount() on the server. ' +
530
- 'This is a no-op.\n\nPlease check the code for the Baz component.'
539
+ 'This usually means you called forceUpdate() outside componentWillMount() on the server. ' +
540
+ 'This is a no-op.\n\nPlease check the code for the Baz component.',
541
);
542
var markup = ReactDOMServer.renderToStaticMarkup(<Baz />);
543
expect(markup).toBe('<div></div>');
@@ -545,7 +555,7 @@ describe('ReactDOMServer', () => {
555
<span key={0} />
556
<span key={1} />
557
<span key={2} />
548
- </Wrapper>
558
+ </Wrapper>,
559
);
560
}).toThrowError(/Cannot assign to read only property.*/);
561
});
src/renderers/dom/shared/__tests__/escapeTextContentForBrowser-test.js
+5
-5
@@ -12,7 +12,6 @@
12
'use strict';
13
14
describe('escapeTextContentForBrowser', () => {
15
-
15
var escapeTextContentForBrowser = require('escapeTextContentForBrowser');
16
17
it('should escape boolean to string', () => {
@@ -35,14 +34,15 @@ describe('escapeTextContentForBrowser', () => {
34
});
35
36
it('should escape string', () => {
38
- var escaped = escapeTextContentForBrowser('<script type=\'\' src=""></script>');
37
+ var escaped = escapeTextContentForBrowser(
38
+ '<script type=\'\' src=""></script>',
39
+ );
40
expect(escaped).not.toContain('<');
41
expect(escaped).not.toContain('>');
41
- expect(escaped).not.toContain('\'');
42
- expect(escaped).not.toContain('\"');
42
+ expect(escaped).not.toContain("'");
43
+ expect(escaped).not.toContain('"');
44
45
escaped = escapeTextContentForBrowser('&');
46
expect(escaped).toBe('&');
47
});
47
-
48
});
src/renderers/dom/shared/__tests__/findDOMNode-test.js
+3
-4
@@ -35,7 +35,7 @@ describe('findDOMNode', () => {
35
});
36
37
it('findDOMNode should find dom element after an update from null', () => {
38
- function Bar({ flag }) {
38
+ function Bar({flag}) {
39
if (flag) {
40
return <span>A</span>;
41
}
@@ -64,7 +64,7 @@ describe('findDOMNode', () => {
64
expect(function() {
65
ReactDOM.findDOMNode({foo: 'bar'});
66
}).toThrowError(
67
- 'Element appears to be neither ReactComponent nor DOMNode. Keys: foo'
67
+ 'Element appears to be neither ReactComponent nor DOMNode. Keys: foo',
68
);
69
});
70
@@ -80,7 +80,7 @@ describe('findDOMNode', () => {
80
ReactDOM.unmountComponentAtNode(container);
81
82
expect(() => ReactDOM.findDOMNode(inst)).toThrowError(
83
- 'Unable to find node on an unmounted component.'
83
+ 'Unable to find node on an unmounted component.',
84
);
85
});
86
@@ -97,5 +97,4 @@ describe('findDOMNode', () => {
97
98
expect(() => ReactTestUtils.renderIntoDocument(<Bar />)).not.toThrow();
99
});
100
-
100
});
src/renderers/dom/shared/__tests__/inputValueTracking-test.js
+17
-24
@@ -22,23 +22,21 @@ describe('inputValueTracking', () => {
22
input.type = 'text';
23
checkbox = document.createElement('input');
24
checkbox.type = 'checkbox';
25
- mockComponent = { _hostNode: input, _wrapperState: {} };
25
+ mockComponent = {_hostNode: input, _wrapperState: {}};
26
});
27
28
it('should attach tracker to wrapper state', () => {
29
inputValueTracking.track(mockComponent);
30
31
- expect(
32
- mockComponent._wrapperState.hasOwnProperty('valueTracker')
33
- ).toBe(true);
31
+ expect(mockComponent._wrapperState.hasOwnProperty('valueTracker')).toBe(
32
+ true,
33
+ );
34
});
35
36
it('should define `value` on the instance node', () => {
37
inputValueTracking.track(mockComponent);
38
39
- expect(
40
- input.hasOwnProperty('value')
41
- ).toBe(true);
39
+ expect(input.hasOwnProperty('value')).toBe(true);
40
});
41
42
it('should define `checked` on the instance node', () => {
@@ -116,15 +114,11 @@ describe('inputValueTracking', () => {
114
115
var tracker = mockComponent._wrapperState.valueTracker;
116
119
- expect(
120
- inputValueTracking.updateValueIfChanged(mockComponent)
121
- ).toBe(false);
117
+ expect(inputValueTracking.updateValueIfChanged(mockComponent)).toBe(false);
118
119
tracker.setValue('bar');
120
125
- expect(
126
- inputValueTracking.updateValueIfChanged(mockComponent)
127
- ).toBe(true);
121
+ expect(inputValueTracking.updateValueIfChanged(mockComponent)).toBe(true);
122
123
expect(tracker.getValue()).toEqual('foo');
124
});
@@ -132,17 +126,16 @@ describe('inputValueTracking', () => {
126
it('should track value and return true when updating untracked instance', () => {
127
input.value = 'foo';
128
135
- expect(
136
- inputValueTracking.updateValueIfChanged(mockComponent)
137
- )
138
- .toBe(true);
129
+ expect(inputValueTracking.updateValueIfChanged(mockComponent)).toBe(true);
130
131
var tracker = mockComponent._wrapperState.valueTracker;
132
expect(tracker.getValue()).toEqual('foo');
133
});
134
135
it('should return tracker from node', () => {
145
- var node = ReactTestUtils.renderIntoDocument(<input type="text" defaultValue="foo" />);
136
+ var node = ReactTestUtils.renderIntoDocument(
137
+ <input type="text" defaultValue="foo" />,
138
+ );
139
var tracker = inputValueTracking._getTrackerFromNode(node);
140
expect(tracker.getValue()).toEqual('foo');
141
});
@@ -150,15 +143,15 @@ describe('inputValueTracking', () => {
143
it('should stop tracking', () => {
144
inputValueTracking.track(mockComponent);
145
153
- expect(
154
- mockComponent._wrapperState.hasOwnProperty('valueTracker')
155
- ).toBe(true);
146
+ expect(mockComponent._wrapperState.hasOwnProperty('valueTracker')).toBe(
147
+ true,
148
+ );
149
150
inputValueTracking.stopTracking(mockComponent);
151
159
- expect(
160
- mockComponent._wrapperState.hasOwnProperty('valueTracker')
161
- ).toBe(false);
152
+ expect(mockComponent._wrapperState.hasOwnProperty('valueTracker')).toBe(
153
+ false,
154
+ );
155
156
expect(input.hasOwnProperty('value')).toBe(false);
157
});
src/renderers/dom/shared/__tests__/quoteAttributeValueForBrowser-test.js
+5
-5
@@ -12,7 +12,6 @@
12
'use strict';
13
14
describe('quoteAttributeValueForBrowser', () => {
15
-
15
var quoteAttributeValueForBrowser = require('quoteAttributeValueForBrowser');
16
17
it('should escape boolean to string', () => {
@@ -35,14 +34,15 @@ describe('quoteAttributeValueForBrowser', () => {
34
});
35
36
it('should escape string', () => {
38
- var escaped = quoteAttributeValueForBrowser('<script type=\'\' src=""></script>');
37
+ var escaped = quoteAttributeValueForBrowser(
38
+ '<script type=\'\' src=""></script>',
39
+ );
40
expect(escaped).not.toContain('<');
41
expect(escaped).not.toContain('>');
41
- expect(escaped).not.toContain('\'');
42
- expect(escaped.substr(1, -1)).not.toContain('\"');
42
+ expect(escaped).not.toContain("'");
43
+ expect(escaped.substr(1, -1)).not.toContain('"');
44
45
escaped = quoteAttributeValueForBrowser('&');
46
expect(escaped).toBe('"&"');
47
});
47
-
48
});
src/renderers/dom/shared/__tests__/validateDOMNesting-test.js
+102
-14
@@ -15,22 +15,107 @@ var validateDOMNesting;
15
16
// https://html.spec.whatwg.org/multipage/syntax.html#special
17
var specialTags = [
18
- 'address', 'applet', 'area', 'article', 'aside', 'base', 'basefont',
19
- 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col',
20
- 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset',
21
- 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2',
22
- 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe',
23
- 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu',
24
- 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol',
25
- 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source',
26
- 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot',
27
- 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp',
18
+ 'address',
19
+ 'applet',
20
+ 'area',
21
+ 'article',
22
+ 'aside',
23
+ 'base',
24
+ 'basefont',
25
+ 'bgsound',
26
+ 'blockquote',
27
+ 'body',
28
+ 'br',
29
+ 'button',
30
+ 'caption',
31
+ 'center',
32
+ 'col',
33
+ 'colgroup',
34
+ 'dd',
35
+ 'details',
36
+ 'dir',
37
+ 'div',
38
+ 'dl',
39
+ 'dt',
40
+ 'embed',
41
+ 'fieldset',
42
+ 'figcaption',
43
+ 'figure',
44
+ 'footer',
45
+ 'form',
46
+ 'frame',
47
+ 'frameset',
48
+ 'h1',
49
+ 'h2',
50
+ 'h3',
51
+ 'h4',
52
+ 'h5',
53
+ 'h6',
54
+ 'head',
55
+ 'header',
56
+ 'hgroup',
57
+ 'hr',
58
+ 'html',
59
+ 'iframe',
60
+ 'img',
61
+ 'input',
62
+ 'isindex',
63
+ 'li',
64
+ 'link',
65
+ 'listing',
66
+ 'main',
67
+ 'marquee',
68
+ 'menu',
69
+ 'menuitem',
70
+ 'meta',
71
+ 'nav',
72
+ 'noembed',
73
+ 'noframes',
74
+ 'noscript',
75
+ 'object',
76
+ 'ol',
77
+ 'p',
78
+ 'param',
79
+ 'plaintext',
80
+ 'pre',
81
+ 'script',
82
+ 'section',
83
+ 'select',
84
+ 'source',
85
+ 'style',
86
+ 'summary',
87
+ 'table',
88
+ 'tbody',
89
+ 'td',
90
+ 'template',
91
+ 'textarea',
92
+ 'tfoot',
93
+ 'th',
94
+ 'thead',
95
+ 'title',
96
+ 'tr',
97
+ 'track',
98
+ 'ul',
99
+ 'wbr',
100
+ 'xmp',
101
];
102
103
// https://html.spec.whatwg.org/multipage/syntax.html#formatting
104
var formattingTags = [
32
- 'a', 'b', 'big', 'code', 'em', 'font', 'i', 'nobr', 's', 'small', 'strike',
33
- 'strong', 'tt', 'u',
105
+ 'a',
106
+ 'b',
107
+ 'big',
108
+ 'code',
109
+ 'em',
110
+ 'font',
111
+ 'i',
112
+ 'nobr',
113
+ 's',
114
+ 'small',
115
+ 'strike',
116
+ 'strong',
117
+ 'tt',
118
+ 'u',
119
];
120
121
function isTagStackValid(stack) {
@@ -39,8 +124,11 @@ function isTagStackValid(stack) {
124
if (!validateDOMNesting.isTagValidInContext(stack[i], ancestorInfo)) {
125
return false;
126
}
42
- ancestorInfo =
43
- validateDOMNesting.updatedAncestorInfo(ancestorInfo, stack[i], null);
127
+ ancestorInfo = validateDOMNesting.updatedAncestorInfo(
128
+ ancestorInfo,
129
+ stack[i],
130
+ null,
131
+ );
132
}
133
return true;
134
}
src/renderers/dom/shared/dangerousStyleValue.js
+5
-2
@@ -41,8 +41,11 @@ function dangerousStyleValue(name, value, component) {
41
return '';
42
}
43
44
- if (typeof value === 'number' && value !== 0 &&
45
- !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])) {
44
+ if (
45
+ typeof value === 'number' &&
46
+ value !== 0 &&
47
+ !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])
48
+ ) {
49
return value + 'px'; // Presumes implicit 'px' suffix for unitless numbers
50
}
51
src/renderers/dom/shared/escapeTextContentForBrowser.js
+2
-5
@@ -74,7 +74,7 @@ function escapeHtml(string) {
74
escape = '&';
75
break;
76
case 39: // '
77
- escape = '''; // modified from escape-html; used to be '''
77
+ escape = '''; // modified from escape-html; used to be '''
78
break;
79
case 60: // <
80
escape = '<';
@@ -94,13 +94,10 @@ function escapeHtml(string) {
94
html += escape;
95
}
96
97
- return lastIndex !== index
98
- ? html + str.substring(lastIndex, index)
99
- : html;
97
+ return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
98
}
99
// end code copied and modified from escape-html
100
103
-
101
/**
102
* Escapes text to prevent scripting attacks.
103
*
src/renderers/dom/shared/eventPlugins/BeforeInputEventPlugin.js
+30
-44
@@ -17,15 +17,13 @@ var FallbackCompositionState = require('FallbackCompositionState');
17
var SyntheticCompositionEvent = require('SyntheticCompositionEvent');
18
var SyntheticInputEvent = require('SyntheticInputEvent');
19
20
-import type { TopLevelTypes } from 'EventConstants';
20
+import type {TopLevelTypes} from 'EventConstants';
21
22
var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space
23
var START_KEYCODE = 229;
24
25
-var canUseCompositionEvent = (
26
- ExecutionEnvironment.canUseDOM &&
27
- 'CompositionEvent' in window
28
-);
25
+var canUseCompositionEvent = ExecutionEnvironment.canUseDOM &&
26
+ 'CompositionEvent' in window;
27
28
var documentMode = null;
29
if (ExecutionEnvironment.canUseDOM && 'documentMode' in document) {
@@ -35,23 +33,17 @@ if (ExecutionEnvironment.canUseDOM && 'documentMode' in document) {
33
// Webkit offers a very useful `textInput` event that can be used to
34
// directly represent `beforeInput`. The IE `textinput` event is not as
35
// useful, so we don't use it.
38
-var canUseTextInputEvent = (
39
- ExecutionEnvironment.canUseDOM &&
36
+var canUseTextInputEvent = ExecutionEnvironment.canUseDOM &&
37
'TextEvent' in window &&
38
!documentMode &&
42
- !isPresto()
43
-);
39
+ !isPresto();
40
41
// In IE9+, we have access to composition events, but the data supplied
42
// by the native compositionend event may be incorrect. Japanese ideographic
43
// spaces, for instance (\u3000) are not recorded correctly.
48
-var useFallbackCompositionData = (
49
- ExecutionEnvironment.canUseDOM &&
50
- (
51
- !canUseCompositionEvent ||
52
- (documentMode && documentMode > 8 && documentMode <= 11)
53
- )
54
-);
44
+var useFallbackCompositionData = ExecutionEnvironment.canUseDOM &&
45
+ (!canUseCompositionEvent ||
46
+ (documentMode && documentMode > 8 && documentMode <= 11));
47
48
/**
49
* Opera <= 12 includes TextEvent in window, but does not fire
@@ -59,11 +51,9 @@ var useFallbackCompositionData = (
51
*/
52
function isPresto() {
53
var opera = window.opera;
62
- return (
63
- typeof opera === 'object' &&
54
+ return typeof opera === 'object' &&
55
typeof opera.version === 'function' &&
65
- parseInt(opera.version(), 10) <= 12
66
- );
56
+ parseInt(opera.version(), 10) <= 12;
57
}
58
59
var SPACEBAR_CODE = 32;
@@ -136,14 +126,11 @@ var hasSpaceKeypress = false;
126
* (cut, copy, select-all, etc.) even though no character is inserted.
127
*/
128
function isKeypressCommand(nativeEvent) {
139
- return (
140
- (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) &&
129
+ return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) &&
130
// ctrlKey && altKey is equivalent to AltGr, and is not a command.
142
- !(nativeEvent.ctrlKey && nativeEvent.altKey)
143
- );
131
+ !(nativeEvent.ctrlKey && nativeEvent.altKey);
132
}
133
146
-
134
/**
135
* Translate native top level events into event types.
136
*
@@ -170,10 +157,7 @@ function getCompositionEventType(topLevelType) {
157
* @return {boolean}
158
*/
159
function isFallbackCompositionStart(topLevelType, nativeEvent) {
173
- return (
174
- topLevelType === 'topKeyDown' &&
175
- nativeEvent.keyCode === START_KEYCODE
176
- );
160
+ return topLevelType === 'topKeyDown' && nativeEvent.keyCode === START_KEYCODE;
161
}
162
163
/**
@@ -187,11 +171,11 @@ function isFallbackCompositionEnd(topLevelType, nativeEvent) {
171
switch (topLevelType) {
172
case 'topKeyUp':
173
// Command keys insert or clear IME input.
190
- return (END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1);
174
+ return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;
175
case 'topKeyDown':
176
// Expect IME keyCode on each keydown. If we get any other
177
// code we must have exited earlier.
194
- return (nativeEvent.keyCode !== START_KEYCODE);
178
+ return nativeEvent.keyCode !== START_KEYCODE;
179
case 'topKeyPress':
180
case 'topMouseDown':
181
case 'topBlur':
@@ -229,7 +213,7 @@ function extractCompositionEvent(
213
topLevelType,
214
targetInst,
215
nativeEvent,
232
- nativeEventTarget
216
+ nativeEventTarget,
217
) {
218
var eventType;
219
var fallbackData;
@@ -252,8 +236,9 @@ function extractCompositionEvent(
236
// The current composition is stored statically and must not be
237
// overwritten while composition continues.
238
if (!currentComposition && eventType === eventTypes.compositionStart) {
255
- currentComposition =
256
- FallbackCompositionState.getPooled(nativeEventTarget);
239
+ currentComposition = FallbackCompositionState.getPooled(
240
+ nativeEventTarget,
241
+ );
242
} else if (eventType === eventTypes.compositionEnd) {
243
if (currentComposition) {
244
fallbackData = currentComposition.getData();
@@ -265,7 +250,7 @@ function extractCompositionEvent(
250
eventType,
251
targetInst,
252
nativeEvent,
268
- nativeEventTarget
253
+ nativeEventTarget,
254
);
255
256
if (fallbackData) {
@@ -348,9 +333,11 @@ function getFallbackBeforeInputChars(topLevelType: TopLevelTypes, nativeEvent) {
333
// If composition event is available, we extract a string only at
334
// compositionevent, otherwise extract it at fallback events.
335
if (currentComposition) {
351
- if (topLevelType === 'topCompositionEnd'
352
- || (!canUseCompositionEvent
353
- && isFallbackCompositionEnd(topLevelType, nativeEvent))) {
336
+ if (
337
+ topLevelType === 'topCompositionEnd' ||
338
+ (!canUseCompositionEvent &&
339
+ isFallbackCompositionEnd(topLevelType, nativeEvent))
340
+ ) {
341
var chars = currentComposition.getData();
342
FallbackCompositionState.release(currentComposition);
343
currentComposition = null;
@@ -402,7 +389,7 @@ function extractBeforeInputEvent(
389
topLevelType,
390
targetInst,
391
nativeEvent,
405
- nativeEventTarget
392
+ nativeEventTarget,
393
) {
394
var chars;
395
@@ -422,7 +409,7 @@ function extractBeforeInputEvent(
409
eventTypes.beforeInput,
410
targetInst,
411
nativeEvent,
425
- nativeEventTarget
412
+ nativeEventTarget,
413
);
414
415
event.data = chars;
@@ -449,27 +436,26 @@ function extractBeforeInputEvent(
436
* `composition` event types.
437
*/
438
var BeforeInputEventPlugin = {
452
-
439
eventTypes: eventTypes,
440
441
extractEvents: function(
442
topLevelType,
443
targetInst,
444
nativeEvent,
459
- nativeEventTarget
445
+ nativeEventTarget,
446
) {
447
return [
448
extractCompositionEvent(
449
topLevelType,
450
targetInst,
451
nativeEvent,
466
- nativeEventTarget
452
+ nativeEventTarget,
453
),
454
extractBeforeInputEvent(
455
topLevelType,
456
targetInst,
457
nativeEvent,
472
- nativeEventTarget
458
+ nativeEventTarget,
459
),
460
];
461
},
src/renderers/dom/shared/eventPlugins/ChangeEventPlugin.js
+29
-65
@@ -48,7 +48,7 @@ function createAndAccumulateChangeEvent(inst, nativeEvent, target) {
48
eventTypes.change,
49
inst,
50
nativeEvent,
51
- target
51
+ target,
52
);
53
event.type = 'change';
54
// Flag this event loop as needing state restore.
@@ -62,32 +62,27 @@ function createAndAccumulateChangeEvent(inst, nativeEvent, target) {
62
var activeElement = null;
63
var activeElementInst = null;
64
65
-
66
-
65
/**
66
* SECTION: handle `change` event
67
*/
68
function shouldUseChangeEvent(elem) {
69
var nodeName = elem.nodeName && elem.nodeName.toLowerCase();
72
- return (
73
- nodeName === 'select' ||
74
- (nodeName === 'input' && elem.type === 'file')
75
- );
70
+ return nodeName === 'select' ||
71
+ (nodeName === 'input' && elem.type === 'file');
72
}
73
74
var doesChangeEventBubble = false;
75
if (ExecutionEnvironment.canUseDOM) {
76
// See `handleChange` comment below
81
- doesChangeEventBubble = isEventSupported('change') && (
82
- !document.documentMode || document.documentMode > 8
83
- );
77
+ doesChangeEventBubble = isEventSupported('change') &&
78
+ (!document.documentMode || document.documentMode > 8);
79
}
80
81
function manualDispatchChangeEvent(nativeEvent) {
82
var event = createAndAccumulateChangeEvent(
83
activeElementInst,
84
nativeEvent,
90
- getEventTarget(nativeEvent)
85
+ getEventTarget(nativeEvent),
86
);
87
88
// If change and propertychange bubbled, we'd just bind to it like all the
@@ -130,20 +125,13 @@ function getInstIfValueChanged(targetInst) {
125
}
126
}
127
133
-function getTargetInstForChangeEvent(
134
- topLevelType,
135
- targetInst
136
-) {
128
+function getTargetInstForChangeEvent(topLevelType, targetInst) {
129
if (topLevelType === 'topChange') {
130
return targetInst;
131
}
132
}
133
142
-function handleEventsForChangeEventIE8(
143
- topLevelType,
144
- target,
145
- targetInst
146
-) {
134
+function handleEventsForChangeEventIE8(topLevelType, target, targetInst) {
135
if (topLevelType === 'topFocus') {
136
// stopWatching() should be a noop here but we call it just in case we
137
// missed a blur event somehow.
@@ -154,7 +142,6 @@ function handleEventsForChangeEventIE8(
142
}
143
}
144
157
-
145
/**
146
* SECTION: handle `input` event
147
*/
@@ -162,12 +149,10 @@ var isInputEventSupported = false;
149
if (ExecutionEnvironment.canUseDOM) {
150
// IE9 claims to support the input event but fails to trigger it when
151
// deleting text, so we ignore its input events.
165
- isInputEventSupported = isEventSupported('input') && (
166
- !document.documentMode || document.documentMode > 9
167
- );
152
+ isInputEventSupported = isEventSupported('input') &&
153
+ (!document.documentMode || document.documentMode > 9);
154
}
155
170
-
156
/**
157
* (For IE <=9) Starts tracking propertychange events on the passed-in element
158
* and override the value property so that we can distinguish user events from
@@ -205,11 +190,7 @@ function handlePropertyChange(nativeEvent) {
190
}
191
}
192
208
-function handleEventsForInputEventPolyfill(
209
- topLevelType,
210
- target,
211
- targetInst
212
-) {
193
+function handleEventsForInputEventPolyfill(topLevelType, target, targetInst) {
194
if (topLevelType === 'topFocus') {
195
// In IE8, we can capture almost all .value changes by adding a
196
// propertychange handler and looking for events with propertyName
@@ -232,13 +213,12 @@ function handleEventsForInputEventPolyfill(
213
}
214
215
// For IE8 and IE9.
235
-function getTargetInstForInputEventPolyfill(
236
- topLevelType,
237
- targetInst
238
-) {
239
- if (topLevelType === 'topSelectionChange' ||
240
- topLevelType === 'topKeyUp' ||
241
- topLevelType === 'topKeyDown') {
216
+function getTargetInstForInputEventPolyfill(topLevelType, targetInst) {
217
+ if (
218
+ topLevelType === 'topSelectionChange' ||
219
+ topLevelType === 'topKeyUp' ||
220
+ topLevelType === 'topKeyDown'
221
+ ) {
222
// On the selectionchange event, the target is just document which isn't
223
// helpful for us so just check activeElement instead.
224
//
@@ -253,7 +233,6 @@ function getTargetInstForInputEventPolyfill(
233
}
234
}
235
256
-
236
/**
237
* SECTION: handle `click` event
238
*/
@@ -262,29 +241,19 @@ function shouldUseClickEvent(elem) {
241
// This approach works across all browsers, whereas `change` does not fire
242
// until `blur` in IE8.
243
var nodeName = elem.nodeName;
265
- return (
266
- (nodeName && nodeName.toLowerCase() === 'input') &&
267
- (elem.type === 'checkbox' || elem.type === 'radio')
268
- );
244
+ return nodeName &&
245
+ nodeName.toLowerCase() === 'input' &&
246
+ (elem.type === 'checkbox' || elem.type === 'radio');
247
}
248
271
-function getTargetInstForClickEvent(
272
- topLevelType,
273
- targetInst
274
-) {
249
+function getTargetInstForClickEvent(topLevelType, targetInst) {
250
if (topLevelType === 'topClick') {
251
return getInstIfValueChanged(targetInst);
252
}
253
}
254
280
-function getTargetInstForInputOrChangeEvent(
281
- topLevelType,
282
- targetInst
283
-) {
284
- if (
285
- topLevelType === 'topInput' ||
286
- topLevelType === 'topChange'
287
- ) {
255
+function getTargetInstForInputOrChangeEvent(topLevelType, targetInst) {
256
+ if (topLevelType === 'topInput' || topLevelType === 'topChange') {
257
return getInstIfValueChanged(targetInst);
258
}
259
}
@@ -300,7 +269,6 @@ function getTargetInstForInputOrChangeEvent(
269
* - select
270
*/
271
var ChangeEventPlugin = {
303
-
272
eventTypes: eventTypes,
273
274
_isInputEventSupported: isInputEventSupported,
@@ -309,10 +277,11 @@ var ChangeEventPlugin = {
277
topLevelType,
278
targetInst,
279
nativeEvent,
312
- nativeEventTarget
280
+ nativeEventTarget,
281
) {
314
- var targetNode = targetInst ?
315
- ReactDOMComponentTree.getNodeFromInstance(targetInst) : window;
282
+ var targetNode = targetInst
283
+ ? ReactDOMComponentTree.getNodeFromInstance(targetInst)
284
+ : window;
285
286
var getTargetInstFunc, handleEventFunc;
287
if (shouldUseChangeEvent(targetNode)) {
@@ -338,21 +307,16 @@ var ChangeEventPlugin = {
307
var event = createAndAccumulateChangeEvent(
308
inst,
309
nativeEvent,
341
- nativeEventTarget
310
+ nativeEventTarget,
311
);
312
return event;
313
}
314
}
315
316
if (handleEventFunc) {
348
- handleEventFunc(
349
- topLevelType,
350
- targetNode,
351
- targetInst
352
- );
317
+ handleEventFunc(topLevelType, targetNode, targetInst);
318
}
319
},
355
-
320
};
321
322
module.exports = ChangeEventPlugin;
src/renderers/dom/shared/eventPlugins/EnterLeaveEventPlugin.js
+19
-23
@@ -18,22 +18,15 @@ var SyntheticMouseEvent = require('SyntheticMouseEvent');
18
var eventTypes = {
19
mouseEnter: {
20
registrationName: 'onMouseEnter',
21
- dependencies: [
22
- 'topMouseOut',
23
- 'topMouseOver',
24
- ],
21
+ dependencies: ['topMouseOut', 'topMouseOver'],
22
},
23
mouseLeave: {
24
registrationName: 'onMouseLeave',
28
- dependencies: [
29
- 'topMouseOut',
30
- 'topMouseOver',
31
- ],
25
+ dependencies: ['topMouseOut', 'topMouseOver'],
26
},
27
};
28
29
var EnterLeaveEventPlugin = {
36
-
30
eventTypes: eventTypes,
31
32
/**
@@ -47,14 +40,15 @@ var EnterLeaveEventPlugin = {
40
topLevelType,
41
targetInst,
42
nativeEvent,
50
- nativeEventTarget
43
+ nativeEventTarget,
44
) {
52
- if (topLevelType === 'topMouseOver' &&
53
- (nativeEvent.relatedTarget || nativeEvent.fromElement)) {
45
+ if (
46
+ topLevelType === 'topMouseOver' &&
47
+ (nativeEvent.relatedTarget || nativeEvent.fromElement)
48
+ ) {
49
return null;
50
}
56
- if (topLevelType !== 'topMouseOut' &&
57
- topLevelType !== 'topMouseOver') {
51
+ if (topLevelType !== 'topMouseOut' && topLevelType !== 'topMouseOver') {
52
// Must not be a mouse in or mouse out - ignoring.
53
return null;
54
}
@@ -78,8 +72,9 @@ var EnterLeaveEventPlugin = {
72
if (topLevelType === 'topMouseOut') {
73
from = targetInst;
74
var related = nativeEvent.relatedTarget || nativeEvent.toElement;
81
- to = related ?
82
- ReactDOMComponentTree.getClosestInstanceFromNode(related) : null;
75
+ to = related
76
+ ? ReactDOMComponentTree.getClosestInstanceFromNode(related)
77
+ : null;
78
} else {
79
// Moving to a node from outside the window.
80
from = null;
@@ -91,16 +86,18 @@ var EnterLeaveEventPlugin = {
86
return null;
87
}
88
94
- var fromNode =
95
- from == null ? win : ReactDOMComponentTree.getNodeFromInstance(from);
96
- var toNode =
97
- to == null ? win : ReactDOMComponentTree.getNodeFromInstance(to);
89
+ var fromNode = from == null
90
+ ? win
91
+ : ReactDOMComponentTree.getNodeFromInstance(from);
92
+ var toNode = to == null
93
+ ? win
94
+ : ReactDOMComponentTree.getNodeFromInstance(to);
95
96
var leave = SyntheticMouseEvent.getPooled(
97
eventTypes.mouseLeave,
98
from,
99
nativeEvent,
103
- nativeEventTarget
100
+ nativeEventTarget,
101
);
102
leave.type = 'mouseleave';
103
leave.target = fromNode;
@@ -110,7 +107,7 @@ var EnterLeaveEventPlugin = {
107
eventTypes.mouseEnter,
108
to,
109
nativeEvent,
113
- nativeEventTarget
110
+ nativeEventTarget,
111
);
112
enter.type = 'mouseenter';
113
enter.target = toNode;
@@ -120,7 +117,6 @@ var EnterLeaveEventPlugin = {
117
118
return [leave, enter];
119
},
123
-
120
};
121
122
module.exports = EnterLeaveEventPlugin;
src/renderers/dom/shared/eventPlugins/SelectEventPlugin.js
+25
-25
@@ -22,11 +22,9 @@ var getActiveElement = require('fbjs/lib/getActiveElement');
22
var isTextInputElement = require('isTextInputElement');
23
var shallowEqual = require('fbjs/lib/shallowEqual');
24
25
-var skipSelectionChangeEvent = (
26
- ExecutionEnvironment.canUseDOM &&
25
+var skipSelectionChangeEvent = ExecutionEnvironment.canUseDOM &&
26
'documentMode' in document &&
28
- document.documentMode <= 11
29
-);
27
+ document.documentMode <= 11;
28
29
var eventTypes = {
30
select: {
@@ -54,8 +52,7 @@ var mouseDown = false;
52
53
// Track whether all listeners exists for this plugin. If none exist, we do
54
// not extract events. See #3639.
57
-var isListeningToAllDependencies =
58
- ReactBrowserEventEmitter.isListeningToAllDependencies;
55
+var isListeningToAllDependencies = ReactBrowserEventEmitter.isListeningToAllDependencies;
56
57
/**
58
* Get an object which is a unique representation of the current selection.
@@ -67,8 +64,10 @@ var isListeningToAllDependencies =
64
* @return {object}
65
*/
66
function getSelection(node) {
70
- if ('selectionStart' in node &&
71
- ReactInputSelection.hasSelectionCapabilities(node)) {
67
+ if (
68
+ 'selectionStart' in node &&
69
+ ReactInputSelection.hasSelectionCapabilities(node)
70
+ ) {
71
return {
72
start: node.selectionStart,
73
end: node.selectionEnd,
@@ -103,9 +102,9 @@ function constructSelectEvent(nativeEvent, nativeEventTarget) {
102
// selection (this matches native `select` event behavior). In HTML5, select
103
// fires only on input and textarea thus if there's no focused element we
104
// won't dispatch.
106
- if (mouseDown ||
107
- activeElement == null ||
108
- activeElement !== getActiveElement()) {
105
+ if (
106
+ mouseDown || activeElement == null || activeElement !== getActiveElement()
107
+ ) {
108
return null;
109
}
110
@@ -118,7 +117,7 @@ function constructSelectEvent(nativeEvent, nativeEventTarget) {
117
eventTypes.select,
118
activeElementInst,
119
nativeEvent,
121
- nativeEventTarget
120
+ nativeEventTarget,
121
);
122
123
syntheticEvent.type = 'select';
@@ -147,32 +146,34 @@ function constructSelectEvent(nativeEvent, nativeEventTarget) {
146
* - Fires after user input.
147
*/
148
var SelectEventPlugin = {
150
-
149
eventTypes: eventTypes,
150
151
extractEvents: function(
152
topLevelType,
153
targetInst,
154
nativeEvent,
157
- nativeEventTarget
155
+ nativeEventTarget,
156
) {
159
- var doc = nativeEventTarget.window === nativeEventTarget ?
160
- nativeEventTarget.document :
161
- nativeEventTarget.nodeType === 9 ?
162
- nativeEventTarget :
163
- nativeEventTarget.ownerDocument;
157
+ var doc = nativeEventTarget.window === nativeEventTarget
158
+ ? nativeEventTarget.document
159
+ : nativeEventTarget.nodeType === 9
160
+ ? nativeEventTarget
161
+ : nativeEventTarget.ownerDocument;
162
if (!doc || !isListeningToAllDependencies('onSelect', doc)) {
163
return null;
164
}
165
168
- var targetNode = targetInst ?
169
- ReactDOMComponentTree.getNodeFromInstance(targetInst) : window;
166
+ var targetNode = targetInst
167
+ ? ReactDOMComponentTree.getNodeFromInstance(targetInst)
168
+ : window;
169
170
switch (topLevelType) {
171
// Track the input node that has focus.
172
case 'topFocus':
174
- if (isTextInputElement(targetNode) ||
175
- targetNode.contentEditable === 'true') {
173
+ if (
174
+ isTextInputElement(targetNode) ||
175
+ targetNode.contentEditable === 'true'
176
+ ) {
177
activeElement = targetNode;
178
activeElementInst = targetInst;
179
lastSelection = null;
@@ -207,7 +208,7 @@ var SelectEventPlugin = {
208
if (skipSelectionChangeEvent) {
209
break;
210
}
210
- // falls through
211
+ // falls through
212
case 'topKeyDown':
213
case 'topKeyUp':
214
return constructSelectEvent(nativeEvent, nativeEventTarget);
@@ -215,7 +216,6 @@ var SelectEventPlugin = {
216
217
return null;
218
},
218
-
219
};
220
221
module.exports = SelectEventPlugin;
src/renderers/dom/shared/eventPlugins/SimpleEventPlugin.js
+7
-12
@@ -34,10 +34,7 @@ import type {
34
ReactSyntheticEvent,
35
} from 'ReactSyntheticEventType';
36
import type {ReactInstance} from 'ReactInstanceType';
37
-import type {
38
- EventTypes,
39
- PluginModule,
40
-} from 'PluginModuleType';
37
+import type {EventTypes, PluginModule} from 'PluginModuleType';
38
39
/**
40
* Turns
@@ -142,7 +139,6 @@ var topLevelEventsToDispatchConfig: {[key: TopLevelTypes]: DispatchConfig} = {};
139
});
140
141
var SimpleEventPlugin: PluginModule<MouseEvent> = {
145
-
142
eventTypes: eventTypes,
143
144
extractEvents: function(
@@ -199,7 +195,7 @@ var SimpleEventPlugin: PluginModule<MouseEvent> = {
195
if (getEventCharCode(nativeEvent) === 0) {
196
return null;
197
}
202
- /* falls through */
198
+ /* falls through */
199
case 'topKeyDown':
200
case 'topKeyUp':
201
EventConstructor = SyntheticKeyboardEvent;
@@ -214,13 +210,13 @@ var SimpleEventPlugin: PluginModule<MouseEvent> = {
210
if (nativeEvent.button === 2) {
211
return null;
212
}
217
- /* falls through */
213
+ /* falls through */
214
case 'topDoubleClick':
215
case 'topMouseDown':
216
case 'topMouseMove':
217
case 'topMouseUp':
222
- // TODO: Disabled elements should not respond to mouse events
223
- /* falls through */
218
+ // TODO: Disabled elements should not respond to mouse events
219
+ /* falls through */
220
case 'topMouseOut':
221
case 'topMouseOver':
222
case 'topContextMenu':
@@ -265,18 +261,17 @@ var SimpleEventPlugin: PluginModule<MouseEvent> = {
261
invariant(
262
EventConstructor,
263
'SimpleEventPlugin: Unhandled event type, `%s`.',
268
- topLevelType
264
+ topLevelType,
265
);
266
var event = EventConstructor.getPooled(
267
dispatchConfig,
268
targetInst,
269
nativeEvent,
274
- nativeEventTarget
270
+ nativeEventTarget,
271
);
272
EventPropagators.accumulateTwoPhaseDispatches(event);
273
return event;
274
},
279
-
275
};
276
277
module.exports = SimpleEventPlugin;
src/renderers/dom/shared/eventPlugins/TapEventPlugin.js
+13
-27
@@ -21,10 +21,7 @@ var ViewportMetrics = require('ViewportMetrics');
21
var isStartish = EventPluginUtils.isStartish;
22
var isEndish = EventPluginUtils.isEndish;
23
24
-import type {
25
- EventTypes,
26
- PluginModule,
27
-} from 'PluginModuleType';
24
+import type {EventTypes, PluginModule} from 'PluginModuleType';
25
import type {ReactInstance} from 'ReactInstanceType';
26
import type {TopLevelTypes} from 'EventConstants';
27
@@ -35,14 +32,10 @@ import type {TopLevelTypes} from 'EventConstants';
32
* "Indexable signature not found in Touch".
33
* See https://github.com/facebook/flow/issues/1323
34
*/
38
-type TouchPropertyKey =
39
- 'clientX' |
40
- 'clientY' |
41
- 'pageX' |
42
- 'pageY';
35
+type TouchPropertyKey = 'clientX' | 'clientY' | 'pageX' | 'pageY';
36
37
declare class _Touch extends Touch {
45
- [key: TouchPropertyKey]: number;
38
+ [key: TouchPropertyKey]: number,
39
}
40
41
type AxisCoordinateData = {
@@ -81,20 +74,17 @@ function getAxisCoordOfEvent(
74
if (singleTouch) {
75
return singleTouch[axis.page];
76
}
84
- return axis.page in nativeEvent ?
85
- nativeEvent[axis.page] :
86
- nativeEvent[axis.client] + ViewportMetrics[axis.envScroll];
77
+ return axis.page in nativeEvent
78
+ ? nativeEvent[axis.page]
79
+ : nativeEvent[axis.client] + ViewportMetrics[axis.envScroll];
80
}
81
89
-function getDistance(
90
- coords: CoordinatesType,
91
- nativeEvent: _Touch,
92
-): number {
82
+function getDistance(coords: CoordinatesType, nativeEvent: _Touch): number {
83
var pageX = getAxisCoordOfEvent(Axis.x, nativeEvent);
84
var pageY = getAxisCoordOfEvent(Axis.y, nativeEvent);
85
return Math.pow(
86
Math.pow(pageX - coords.x, 2) + Math.pow(pageY - coords.y, 2),
97
- 0.5
87
+ 0.5,
88
);
89
}
90
@@ -105,11 +95,9 @@ var touchEvents = [
95
'topTouchMove',
96
];
97
108
-var dependencies = [
109
- 'topMouseDown',
110
- 'topMouseMove',
111
- 'topMouseUp',
112
-].concat(touchEvents);
98
+var dependencies = ['topMouseDown', 'topMouseMove', 'topMouseUp'].concat(
99
+ touchEvents,
100
+);
101
102
var eventTypes: EventTypes = {
103
touchTap: {
@@ -126,7 +114,6 @@ var usedTouchTime = 0;
114
var TOUCH_DELAY = 1000;
115
116
var TapEventPlugin: PluginModule<_Touch> = {
129
-
117
tapMoveThreshold: tapMoveThreshold,
118
119
eventTypes: eventTypes,
@@ -147,7 +134,7 @@ var TapEventPlugin: PluginModule<_Touch> = {
134
usedTouch = true;
135
usedTouchTime = Date.now();
136
} else {
150
- if (usedTouch && (Date.now() - usedTouchTime < TOUCH_DELAY)) {
137
+ if (usedTouch && Date.now() - usedTouchTime < TOUCH_DELAY) {
138
return null;
139
}
140
}
@@ -158,7 +145,7 @@ var TapEventPlugin: PluginModule<_Touch> = {
145
eventTypes.touchTap,
146
targetInst,
147
nativeEvent,
161
- nativeEventTarget
148
+ nativeEventTarget,
149
);
150
}
151
if (isStartish(topLevelType)) {
@@ -171,7 +158,6 @@ var TapEventPlugin: PluginModule<_Touch> = {
158
EventPropagators.accumulateTwoPhaseDispatches(event);
159
return event;
160
},
174
-
161
};
162
163
module.exports = TapEventPlugin;
src/renderers/dom/shared/eventPlugins/__tests__/BeforeInputEventPlugin-test.js
+65
-37
@@ -15,12 +15,12 @@ var React = require('react');
15
var ReactTestUtils = require('ReactTestUtils');
16
17
var EventMapping = {
18
- compositionstart : 'topCompositionStart',
19
- compositionend : 'topCompositionEnd',
20
- keyup : 'topKeyUp',
21
- keydown : 'topKeyDown',
22
- textInput : 'topTextInput',
23
- textinput : null, // Not defined now
18
+ compositionstart: 'topCompositionStart',
19
+ compositionend: 'topCompositionEnd',
20
+ keyup: 'topKeyUp',
21
+ keydown: 'topKeyDown',
22
+ textInput: 'topTextInput',
23
+ textinput: null, // Not defined now
24
};
25
26
describe('BeforeInputEventPlugin', function() {
@@ -62,12 +62,12 @@ describe('BeforeInputEventPlugin', function() {
62
EventMapping[eventType],
63
ModuleCache.ReactDOMComponentTree.getInstanceFromNode(node),
64
evt,
65
- node
65
+ node,
66
);
67
}
68
69
function setElementText(node) {
70
- return (args) => node.innerHTML = args;
70
+ return args => node.innerHTML = args;
71
}
72
73
function accumulateEvents(node, events) {
@@ -94,8 +94,9 @@ describe('BeforeInputEventPlugin', function() {
94
// Both are null. Expected.
95
} else if (actual === null) {
96
throw new EventMismatchError(idx, 'Expected not to be null');
97
- } else if (expected.type === null
98
- || !(actual instanceof expected.type)) {
97
+ } else if (
98
+ expected.type === null || !(actual instanceof expected.type)
99
+ ) {
100
throw new EventMismatchError(idx, 'Unexpected type: ' + actual);
101
} else {
102
// Type match.
@@ -103,8 +104,10 @@ describe('BeforeInputEventPlugin', function() {
104
if (!(expectedKey in actual)) {
105
throw new EventMismatchError(idx, 'KeyNotFound: ' + expectedKey);
106
} else if (actual[expectedKey] !== expected.data[expectedKey]) {
106
- throw new EventMismatchError(idx,
107
- 'ValueMismatch: ' + actual[expectedKey]);
107
+ throw new EventMismatchError(
108
+ idx,
109
+ 'ValueMismatch: ' + actual[expectedKey],
110
+ );
111
}
112
});
113
}
@@ -142,16 +145,26 @@ describe('BeforeInputEventPlugin', function() {
145
// textInput, SyntheticCompositionEvent at composition, and nothing from
146
// keyUp.
147
var Expected_Webkit = () => [
145
- {type: ModuleCache.SyntheticCompositionEvent, data: {}}, {type: null},
146
- {type: null}, {type: ModuleCache.SyntheticInputEvent, data: {data: 'A'}},
147
- {type: null}, {type: null}, // textinput of A
148
- {type: null}, {type: null}, // keyUp of 65
149
- {type: null}, {type: ModuleCache.SyntheticInputEvent, data: {data: 'abc'}},
150
- {type: null}, {type: null}, // textinput of abc
151
- {type: null}, {type: null}, // keyUp of 32
152
- {type: null}, {type: ModuleCache.SyntheticInputEvent, data: {data: 'xyz'}},
153
- {type: null}, {type: null}, // textinput of xyz
154
- {type: null}, {type: null}, // keyUp of 32
148
+ {type: ModuleCache.SyntheticCompositionEvent, data: {}},
149
+ {type: null},
150
+ {type: null},
151
+ {type: ModuleCache.SyntheticInputEvent, data: {data: 'A'}},
152
+ {type: null},
153
+ {type: null}, // textinput of A
154
+ {type: null},
155
+ {type: null}, // keyUp of 65
156
+ {type: null},
157
+ {type: ModuleCache.SyntheticInputEvent, data: {data: 'abc'}},
158
+ {type: null},
159
+ {type: null}, // textinput of abc
160
+ {type: null},
161
+ {type: null}, // keyUp of 32
162
+ {type: null},
163
+ {type: ModuleCache.SyntheticInputEvent, data: {data: 'xyz'}},
164
+ {type: null},
165
+ {type: null}, // textinput of xyz
166
+ {type: null},
167
+ {type: null}, // keyUp of 32
168
{type: ModuleCache.SyntheticCompositionEvent, data: {data: 'Hello'}},
169
{type: null},
170
];
@@ -161,19 +174,29 @@ describe('BeforeInputEventPlugin', function() {
174
// expected to be triggered at compositionend with a text of the target
175
// element, not event data.
176
var Expected_IE11 = () => [
164
- {type: ModuleCache.SyntheticCompositionEvent, data: {}}, {type: null},
165
- {type: null}, {type: null}, // textInput of A
166
- {type: null}, {type: null}, // textinput of A
167
- {type: null}, {type: null}, // keyUp of 65
168
- {type: null}, {type: null}, // textInput of abc
169
- {type: null}, {type: null}, // textinput of abc
177
+ {type: ModuleCache.SyntheticCompositionEvent, data: {}},
178
+ {type: null},
179
+ {type: null},
180
+ {type: null}, // textInput of A
181
+ {type: null},
182
+ {type: null}, // textinput of A
183
+ {type: null},
184
+ {type: null}, // keyUp of 65
185
+ {type: null},
186
+ {type: null}, // textInput of abc
187
+ {type: null},
188
+ {type: null}, // textinput of abc
189
190
// fallbackData should NOT be set at keyUp with any of END_KEYCODES
172
- {type: null}, {type: null}, // keyUp of 32
191
+ {type: null},
192
+ {type: null}, // keyUp of 32
193
174
- {type: null}, {type: null}, // textInput of xyz
175
- {type: null}, {type: null}, // textinput of xyz
176
- {type: null}, {type: null}, // keyUp of 32
194
+ {type: null},
195
+ {type: null}, // textInput of xyz
196
+ {type: null},
197
+ {type: null}, // textinput of xyz
198
+ {type: null},
199
+ {type: null}, // keyUp of 32
200
201
// fallbackData is retrieved from the element, which is XYZ,
202
// at a time of compositionend
@@ -185,25 +208,30 @@ describe('BeforeInputEventPlugin', function() {
208
ModuleCache = new initialize(Emulator);
209
210
var EditableDiv = React.createClass({
188
- render: () => (<div contentEditable="true" />),
211
+ render: () => <div contentEditable="true" />,
212
});
213
var rendered = ReactTestUtils.renderIntoDocument(<EditableDiv />);
214
215
var node = ModuleCache.ReactDOM.findDOMNode(rendered);
216
var events = [];
217
195
- Scenario.forEach((el) =>
196
- el.run.call(this, node, events).apply(this, el.arg));
218
+ Scenario.forEach(el => el.run.call(this, node, events).apply(this, el.arg));
219
verifyEvents(events, ExpectedResult());
220
}
221
222
it('extract onBeforeInput from native textinput events', function() {
223
TestEditableReactComponent(
202
- simulateWebkit, Scenario_Composition, Expected_Webkit);
224
+ simulateWebkit,
225
+ Scenario_Composition,
226
+ Expected_Webkit,
227
+ );
228
});
229
230
it('extract onBeforeInput from fallback objects', function() {
231
TestEditableReactComponent(
207
- simulateIE11, Scenario_Composition, Expected_IE11);
232
+ simulateIE11,
233
+ Scenario_Composition,
234
+ Expected_IE11,
235
+ );
236
});
237
});
src/renderers/dom/shared/eventPlugins/__tests__/ChangeEventPlugin-test.js
+15
-7
@@ -48,7 +48,9 @@ describe('ChangeEventPlugin', () => {
48
expect(e.type).toBe('change');
49
}
50
51
- var input = ReactTestUtils.renderIntoDocument(<input type="checkbox" onChange={cb} />);
51
+ var input = ReactTestUtils.renderIntoDocument(
52
+ <input type="checkbox" onChange={cb} />,
53
+ );
54
55
setUntrackedValue(input, true);
56
ReactTestUtils.SimulateNative.click(input);
@@ -58,7 +60,7 @@ describe('ChangeEventPlugin', () => {
60
61
it('should catch setting the value programmatically', () => {
62
var input = ReactTestUtils.renderIntoDocument(
61
- <input type="text" defaultValue="foo" />
63
+ <input type="text" defaultValue="foo" />,
64
);
65
66
input.value = 'bar';
@@ -74,7 +76,7 @@ describe('ChangeEventPlugin', () => {
76
}
77
78
var input = ReactTestUtils.renderIntoDocument(
77
- <input type="text" onChange={cb} defaultValue="foo" />
79
+ <input type="text" onChange={cb} defaultValue="foo" />,
80
);
81
82
input.value = 'bar';
@@ -96,7 +98,7 @@ describe('ChangeEventPlugin', () => {
98
}
99
100
var input = ReactTestUtils.renderIntoDocument(
99
- <input type="checkbox" onChange={cb} defaultChecked={true} />
101
+ <input type="checkbox" onChange={cb} defaultChecked={true} />,
102
);
103
104
input.checked = true;
@@ -124,7 +126,9 @@ describe('ChangeEventPlugin', () => {
126
called += 1;
127
}
128
127
- var input = ReactTestUtils.renderIntoDocument(<input type="radio" onChange={cb} />);
129
+ var input = ReactTestUtils.renderIntoDocument(
130
+ <input type="radio" onChange={cb} />,
131
+ );
132
setUntrackedValue(input, true);
133
ReactTestUtils.SimulateNative.click(input);
134
ReactTestUtils.SimulateNative.click(input);
@@ -181,7 +185,9 @@ describe('ChangeEventPlugin', () => {
185
return;
186
}
187
184
- var input = ReactTestUtils.renderIntoDocument(<input type="range" onChange={cb} />);
188
+ var input = ReactTestUtils.renderIntoDocument(
189
+ <input type="range" onChange={cb} />,
190
+ );
191
setUntrackedValue(input, 'bar');
192
193
ReactTestUtils.SimulateNative.input(input);
@@ -201,7 +207,9 @@ describe('ChangeEventPlugin', () => {
207
expect(e.type).toBe('change');
208
}
209
204
- var input = ReactTestUtils.renderIntoDocument(<input type="range" onChange={cb} />);
210
+ var input = ReactTestUtils.renderIntoDocument(
211
+ <input type="range" onChange={cb} />,
212
+ );
213
setUntrackedValue(input, '40');
214
ReactTestUtils.SimulateNative.input(input);
215
ReactTestUtils.SimulateNative.change(input);
src/renderers/dom/shared/eventPlugins/__tests__/EnterLeaveEventPlugin-test.js
+6
-3
@@ -33,18 +33,21 @@ describe('EnterLeaveEventPlugin', () => {
33
var iframeDocument = iframe.contentDocument;
34
35
iframeDocument.write(
36
- '<!DOCTYPE html><html><head></head><body><div></div></body></html>'
36
+ '<!DOCTYPE html><html><head></head><body><div></div></body></html>',
37
);
38
iframeDocument.close();
39
40
- var component = ReactDOM.render(<div />, iframeDocument.body.getElementsByTagName('div')[0]);
40
+ var component = ReactDOM.render(
41
+ <div />,
42
+ iframeDocument.body.getElementsByTagName('div')[0],
43
+ );
44
var div = ReactDOM.findDOMNode(component);
45
46
var extracted = EnterLeaveEventPlugin.extractEvents(
47
'topMouseOver',
48
ReactDOMComponentTree.getInstanceFromNode(div),
49
{target: div},
47
- div
50
+ div,
51
);
52
expect(extracted.length).toBe(2);
53
src/renderers/dom/shared/eventPlugins/__tests__/SelectEventPlugin-test.js
+3
-7
@@ -23,7 +23,7 @@ describe('SelectEventPlugin', () => {
23
topLevelEvent,
24
ReactDOMComponentTree.getInstanceFromNode(node),
25
{target: node},
26
- node
26
+ node,
27
);
28
}
29
@@ -50,11 +50,7 @@ describe('SelectEventPlugin', () => {
50
// environment so we need to ensure it gets set for this test to be valid.
51
var fakeNativeEvent = function() {};
52
fakeNativeEvent.target = node;
53
- ReactTestUtils.simulateNativeEventOnNode(
54
- 'topFocus',
55
- node,
56
- fakeNativeEvent
57
- );
53
+ ReactTestUtils.simulateNativeEventOnNode('topFocus', node, fakeNativeEvent);
54
55
var mousedown = extract(node, 'topMouseDown');
56
expect(mousedown).toBe(null);
@@ -73,7 +69,7 @@ describe('SelectEventPlugin', () => {
69
var cb = jest.fn();
70
71
var rendered = ReactTestUtils.renderIntoDocument(
76
- <WithSelect onSelect={cb} />
72
+ <WithSelect onSelect={cb} />,
73
);
74
var node = ReactDOM.findDOMNode(rendered);
75
src/renderers/dom/shared/eventPlugins/__tests__/SimpleEventPlugin-test.js
+20
-24
@@ -11,7 +11,6 @@
11
12
'use strict';
13
14
-
14
describe('SimpleEventPlugin', function() {
15
var React;
16
var ReactDOM;
@@ -43,13 +42,13 @@ describe('SimpleEventPlugin', function() {
42
});
43
44
it('A non-interactive tags click when disabled', function() {
46
- var element = (<div onClick={ onClick } />);
45
+ var element = <div onClick={onClick} />;
46
expectClickThru(mounted(element));
47
});
48
49
it('A non-interactive tags clicks bubble when disabled', function() {
50
var element = ReactTestUtils.renderIntoDocument(
52
- <div onClick={onClick}><div /></div>
51
+ <div onClick={onClick}><div /></div>,
52
);
53
var child = ReactDOM.findDOMNode(element).firstChild;
54
@@ -59,7 +58,7 @@ describe('SimpleEventPlugin', function() {
58
59
it('does not register a click when clicking a child of a disabled element', function() {
60
var element = ReactTestUtils.renderIntoDocument(
62
- <button onClick={onClick} disabled={true}><span /></button>
61
+ <button onClick={onClick} disabled={true}><span /></button>,
62
);
63
var child = ReactDOM.findDOMNode(element).querySelector('span');
64
@@ -69,7 +68,7 @@ describe('SimpleEventPlugin', function() {
68
69
it('triggers click events for children of disabled elements', function() {
70
var element = ReactTestUtils.renderIntoDocument(
72
- <button disabled={true}><span onClick={onClick} /></button>
71
+ <button disabled={true}><span onClick={onClick} /></button>,
72
);
73
var child = ReactDOM.findDOMNode(element).querySelector('span');
74
@@ -81,7 +80,7 @@ describe('SimpleEventPlugin', function() {
80
var element = ReactTestUtils.renderIntoDocument(
81
<div onClickCapture={onClick}>
82
<button disabled={true}><span /></button>
84
- </div>
83
+ </div>,
84
);
85
var child = ReactDOM.findDOMNode(element).querySelector('span');
86
@@ -91,7 +90,7 @@ describe('SimpleEventPlugin', function() {
90
91
it('triggers captured click events for children of disabled elements', function() {
92
var element = ReactTestUtils.renderIntoDocument(
94
- <button disabled={true}><span onClickCapture={onClick} /></button>
93
+ <button disabled={true}><span onClickCapture={onClick} /></button>,
94
);
95
var child = ReactDOM.findDOMNode(element).querySelector('span');
96
@@ -100,9 +99,7 @@ describe('SimpleEventPlugin', function() {
99
});
100
101
['button', 'input', 'select', 'textarea'].forEach(function(tagName) {
103
-
102
describe(tagName, function() {
105
-
103
it('should forward clicks when it starts out not disabled', () => {
104
var element = React.createElement(tagName, {
105
onClick: onClick,
@@ -123,12 +120,12 @@ describe('SimpleEventPlugin', function() {
120
it('should forward clicks when it becomes not disabled', () => {
121
var container = document.createElement('div');
122
var element = ReactDOM.render(
126
- React.createElement(tagName, { onClick: onClick, disabled: true }),
127
- container
123
+ React.createElement(tagName, {onClick: onClick, disabled: true}),
124
+ container,
125
);
126
element = ReactDOM.render(
130
- React.createElement(tagName, { onClick: onClick }),
131
- container
127
+ React.createElement(tagName, {onClick: onClick}),
128
+ container,
129
);
130
expectClickThru(element);
131
});
@@ -136,12 +133,12 @@ describe('SimpleEventPlugin', function() {
133
it('should not forward clicks when it becomes disabled', () => {
134
var container = document.createElement('div');
135
var element = ReactDOM.render(
139
- React.createElement(tagName, { onClick: onClick }),
140
- container
136
+ React.createElement(tagName, {onClick: onClick}),
137
+ container,
138
);
139
element = ReactDOM.render(
143
- React.createElement(tagName, { onClick: onClick, disabled: true }),
144
- container
140
+ React.createElement(tagName, {onClick: onClick, disabled: true}),
141
+ container,
142
);
143
expectNoClickThru(element);
144
});
@@ -149,26 +146,25 @@ describe('SimpleEventPlugin', function() {
146
it('should work correctly if the listener is changed', () => {
147
var container = document.createElement('div');
148
var element = ReactDOM.render(
152
- React.createElement(tagName, { onClick: onClick, disabled: true }),
153
- container
149
+ React.createElement(tagName, {onClick: onClick, disabled: true}),
150
+ container,
151
);
152
element = ReactDOM.render(
156
- React.createElement(tagName, { onClick: onClick, disabled: false }),
157
- container
153
+ React.createElement(tagName, {onClick: onClick, disabled: false}),
154
+ container,
155
);
156
expectClickThru(element);
157
});
158
});
159
});
160
164
-
161
describe('iOS bubbling click fix', function() {
162
// See http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
163
164
it('does not add a local click to interactive elements', function() {
165
var container = document.createElement('div');
166
171
- ReactDOM.render(<button onClick={ onClick } />, container);
167
+ ReactDOM.render(<button onClick={onClick} />, container);
168
169
var node = container.firstChild;
170
@@ -180,7 +176,7 @@ describe('SimpleEventPlugin', function() {
176
it('adds a local click listener to non-interactive elements', function() {
177
var container = document.createElement('div');
178
183
- ReactDOM.render(<div onClick={ onClick } />, container);
179
+ ReactDOM.render(<div onClick={onClick} />, container);
180
181
var node = container.firstChild;
182
src/renderers/dom/shared/findDOMNode.js
+14
-15
@@ -24,22 +24,24 @@ let findStack = function(arg) {
24
invariant(false, 'Missing injection for stack findDOMNode');
25
};
26
27
-const findDOMNode = function(componentOrElement : Element | ?ReactComponent<any, any, any>) : null | Element | Text {
27
+const findDOMNode = function(
28
+ componentOrElement: Element | ?ReactComponent<any, any, any>,
29
+): null | Element | Text {
30
if (__DEV__) {
29
- var owner = (ReactCurrentOwner.current : any);
31
+ var owner = (ReactCurrentOwner.current: any);
32
if (owner !== null) {
33
var isFiber = typeof owner.tag === 'number';
32
- var warnedAboutRefsInRender = isFiber ?
33
- owner.stateNode._warnedAboutRefsInRender :
34
- owner._warnedAboutRefsInRender;
34
+ var warnedAboutRefsInRender = isFiber
35
+ ? owner.stateNode._warnedAboutRefsInRender
36
+ : owner._warnedAboutRefsInRender;
37
warning(
38
warnedAboutRefsInRender,
39
'%s is accessing findDOMNode inside its render(). ' +
38
- 'render() should be a pure function of props and state. It should ' +
39
- 'never access something that requires stale data from the previous ' +
40
- 'render, such as refs. Move this logic to componentDidMount and ' +
41
- 'componentDidUpdate instead.',
42
- getComponentName(owner) || 'A component'
40
+ 'render() should be a pure function of props and state. It should ' +
41
+ 'never access something that requires stale data from the previous ' +
42
+ 'render, such as refs. Move this logic to componentDidMount and ' +
43
+ 'componentDidUpdate instead.',
44
+ getComponentName(owner) || 'A component',
45
);
46
if (isFiber) {
47
owner.stateNode._warnedAboutRefsInRender = true;
@@ -65,15 +67,12 @@ const findDOMNode = function(componentOrElement : Element | ?ReactComponent<any,
67
}
68
69
if (typeof componentOrElement.render === 'function') {
68
- invariant(
69
- false,
70
- 'Unable to find node on an unmounted component.'
71
- );
70
+ invariant(false, 'Unable to find node on an unmounted component.');
71
} else {
72
invariant(
73
false,
74
'Element appears to be neither ReactComponent nor DOMNode. Keys: %s',
76
- Object.keys(componentOrElement)
75
+ Object.keys(componentOrElement),
76
);
77
}
78
};
src/renderers/dom/shared/hooks/ReactDOMInvalidARIAHook.js
+11
-13
@@ -36,19 +36,17 @@ function getStackAddendum(debugID) {
36
}
37
38
function validateProperty(tagName, name, debugID) {
39
- if (
40
- warnedProperties.hasOwnProperty(name)
41
- && warnedProperties[name]
42
- ) {
39
+ if (warnedProperties.hasOwnProperty(name) && warnedProperties[name]) {
40
return true;
41
}
42
43
if (rARIA.test(name)) {
44
var lowerCasedName = name.toLowerCase();
48
- var standardName =
49
- DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ?
50
- DOMProperty.getPossibleStandardName[lowerCasedName] :
51
- null;
45
+ var standardName = DOMProperty.getPossibleStandardName.hasOwnProperty(
46
+ lowerCasedName,
47
+ )
48
+ ? DOMProperty.getPossibleStandardName[lowerCasedName]
49
+ : null;
50
51
// If this is an aria-* attribute, but is not listed in the known DOM
52
// DOM properties, then it is an invalid aria-* attribute.
@@ -63,7 +61,7 @@ function validateProperty(tagName, name, debugID) {
61
'Unknown ARIA attribute %s. Did you mean %s?%s',
62
name,
63
standardName,
66
- getStackAddendum(debugID)
64
+ getStackAddendum(debugID),
65
);
66
warnedProperties[name] = true;
67
return true;
@@ -91,19 +89,19 @@ function warnInvalidARIAProps(type, props, debugID) {
89
warning(
90
false,
91
'Invalid aria prop %s on <%s> tag. ' +
94
- 'For details, see https://fb.me/invalid-aria-prop%s',
92
+ 'For details, see https://fb.me/invalid-aria-prop%s',
93
unknownPropString,
94
type,
97
- getStackAddendum(debugID)
95
+ getStackAddendum(debugID),
96
);
97
} else if (invalidProps.length > 1) {
98
warning(
99
false,
100
'Invalid aria props %s on <%s> tag. ' +
103
- 'For details, see https://fb.me/invalid-aria-prop%s',
101
+ 'For details, see https://fb.me/invalid-aria-prop%s',
102
unknownPropString,
103
type,
106
- getStackAddendum(debugID)
104
+ getStackAddendum(debugID),
105
);
106
}
107
}
src/renderers/dom/shared/hooks/ReactDOMNullInputValuePropHook.js
+3
-3
@@ -40,10 +40,10 @@ function validateProperties(type, props, debugID /* Stack only */) {
40
warning(
41
false,
42
'`value` prop on `%s` should not be null. ' +
43
- 'Consider using the empty string to clear the component or `undefined` ' +
44
- 'for uncontrolled components.%s',
43
+ 'Consider using the empty string to clear the component or `undefined` ' +
44
+ 'for uncontrolled components.%s',
45
type,
46
- getStackAddendum(debugID)
46
+ getStackAddendum(debugID),
47
);
48
49
didWarnValueNull = true;
src/renderers/dom/shared/hooks/ReactDOMUnknownPropertyHook.js
+26
-27
@@ -46,11 +46,16 @@ if (__DEV__) {
46
var warnedProperties = {};
47
48
var validateProperty = function(tagName, name, debugID) {
49
- if (DOMProperty.properties.hasOwnProperty(name) || DOMProperty.isCustomAttribute(name)) {
49
+ if (
50
+ DOMProperty.properties.hasOwnProperty(name) ||
51
+ DOMProperty.isCustomAttribute(name)
52
+ ) {
53
return true;
54
}
52
- if (reactProps.hasOwnProperty(name) && reactProps[name] ||
53
- warnedProperties.hasOwnProperty(name) && warnedProperties[name]) {
55
+ if (
56
+ (reactProps.hasOwnProperty(name) && reactProps[name]) ||
57
+ (warnedProperties.hasOwnProperty(name) && warnedProperties[name])
58
+ ) {
59
return true;
60
}
61
if (EventPluginRegistry.registrationNameModules.hasOwnProperty(name)) {
@@ -60,21 +65,17 @@ if (__DEV__) {
65
var lowerCasedName = name.toLowerCase();
66
67
// data-* attributes should be lowercase; suggest the lowercase version
63
- var standardName = (
64
- DOMProperty.isCustomAttribute(lowerCasedName) ?
65
- lowerCasedName :
66
- DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ?
67
- DOMProperty.getPossibleStandardName[lowerCasedName] :
68
- null
69
- );
70
-
71
- var registrationName = (
72
- EventPluginRegistry.possibleRegistrationNames.hasOwnProperty(
73
- lowerCasedName
74
- ) ?
75
- EventPluginRegistry.possibleRegistrationNames[lowerCasedName] :
76
- null
77
- );
68
+ var standardName = DOMProperty.isCustomAttribute(lowerCasedName)
69
+ ? lowerCasedName
70
+ : DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName)
71
+ ? DOMProperty.getPossibleStandardName[lowerCasedName]
72
+ : null;
73
+
74
+ var registrationName = EventPluginRegistry.possibleRegistrationNames.hasOwnProperty(
75
+ lowerCasedName,
76
+ )
77
+ ? EventPluginRegistry.possibleRegistrationNames[lowerCasedName]
78
+ : null;
79
80
if (standardName != null) {
81
warning(
@@ -82,7 +83,7 @@ if (__DEV__) {
83
'Unknown DOM property %s. Did you mean %s?%s',
84
name,
85
standardName,
85
- getStackAddendum(debugID)
86
+ getStackAddendum(debugID),
87
);
88
return true;
89
} else if (registrationName != null) {
@@ -91,7 +92,7 @@ if (__DEV__) {
92
'Unknown event handler property %s. Did you mean `%s`?%s',
93
name,
94
registrationName,
94
- getStackAddendum(debugID)
95
+ getStackAddendum(debugID),
96
);
97
return true;
98
} else {
@@ -113,27 +114,25 @@ var warnUnknownProperties = function(type, props, debugID) {
114
}
115
}
116
116
- var unknownPropString = unknownProps
117
- .map(prop => '`' + prop + '`')
118
- .join(', ');
117
+ var unknownPropString = unknownProps.map(prop => '`' + prop + '`').join(', ');
118
119
if (unknownProps.length === 1) {
120
warning(
121
false,
122
'Unknown prop %s on <%s> tag. Remove this prop from the element. ' +
124
- 'For details, see https://fb.me/react-unknown-prop%s',
123
+ 'For details, see https://fb.me/react-unknown-prop%s',
124
unknownPropString,
125
type,
127
- getStackAddendum(debugID)
126
+ getStackAddendum(debugID),
127
);
128
} else if (unknownProps.length > 1) {
129
warning(
130
false,
131
'Unknown props %s on <%s> tag. Remove these props from the element. ' +
133
- 'For details, see https://fb.me/react-unknown-prop%s',
132
+ 'For details, see https://fb.me/react-unknown-prop%s',
133
unknownPropString,
134
type,
136
- getStackAddendum(debugID)
135
+ getStackAddendum(debugID),
136
);
137
}
138
};
src/renderers/dom/shared/inputValueTracking.js
+26
-31
@@ -12,59 +12,56 @@
12
13
'use strict';
14
15
-import type { Fiber } from 'ReactFiber';
16
-import type { ReactInstance } from 'ReactInstanceType';
15
+import type {Fiber} from 'ReactFiber';
16
+import type {ReactInstance} from 'ReactInstanceType';
17
18
type ValueTracker = {
19
- getValue() : string,
20
- setValue(value : string) : void,
21
- stopTracking() : void
19
+ getValue(): string,
20
+ setValue(value: string): void,
21
+ stopTracking(): void,
22
};
23
-type WrapperState = { _wrapperState: { valueTracker: ?ValueTracker } };
23
+type WrapperState = {_wrapperState: {valueTracker: ?ValueTracker}};
24
type ElementWithWrapperState = Element & WrapperState;
25
type InstanceWithWrapperState = ReactInstance & WrapperState;
26
27
var ReactDOMComponentTree = require('ReactDOMComponentTree');
28
29
-function isCheckable(elem : any) {
29
+function isCheckable(elem: any) {
30
var type = elem.type;
31
var nodeName = elem.nodeName;
32
- return (
33
- (nodeName && nodeName.toLowerCase() === 'input') &&
34
- (type === 'checkbox' || type === 'radio')
35
- );
32
+ return nodeName &&
33
+ nodeName.toLowerCase() === 'input' &&
34
+ (type === 'checkbox' || type === 'radio');
35
}
36
38
-function getTracker(inst : any) {
37
+function getTracker(inst: any) {
38
if (typeof inst.tag === 'number') {
39
inst = inst.stateNode;
40
}
41
return inst._wrapperState.valueTracker;
42
}
43
45
-function attachTracker(inst : InstanceWithWrapperState, tracker : ?ValueTracker) {
44
+function attachTracker(inst: InstanceWithWrapperState, tracker: ?ValueTracker) {
45
inst._wrapperState.valueTracker = tracker;
46
}
47
49
-function detachTracker(inst : InstanceWithWrapperState) {
48
+function detachTracker(inst: InstanceWithWrapperState) {
49
delete inst._wrapperState.valueTracker;
50
}
51
52
function getValueFromNode(node) {
53
var value;
54
if (node) {
56
- value = isCheckable(node)
57
- ? '' + node.checked
58
- : node.value;
55
+ value = isCheckable(node) ? '' + node.checked : node.value;
56
}
57
return value;
58
}
59
63
-function trackValueOnNode(node : any, inst : any) : ?ValueTracker {
60
+function trackValueOnNode(node: any, inst: any): ?ValueTracker {
61
var valueField = isCheckable(node) ? 'checked' : 'value';
62
var descriptor = Object.getOwnPropertyDescriptor(
63
node.constructor.prototype,
67
- valueField
64
+ valueField,
65
);
66
67
var currentValue = '' + node[valueField];
@@ -110,20 +107,18 @@ function trackValueOnNode(node : any, inst : any) : ?ValueTracker {
107
108
var inputValueTracking = {
109
// exposed for testing
113
- _getTrackerFromNode(node : ElementWithWrapperState) {
114
- return getTracker(
115
- ReactDOMComponentTree.getInstanceFromNode(node)
116
- );
110
+ _getTrackerFromNode(node: ElementWithWrapperState) {
111
+ return getTracker(ReactDOMComponentTree.getInstanceFromNode(node));
112
},
113
119
- trackNode: function(node : ElementWithWrapperState) {
114
+ trackNode: function(node: ElementWithWrapperState) {
115
if (node._wrapperState.valueTracker) {
116
return;
117
}
118
node._wrapperState.valueTracker = trackValueOnNode(node, node);
119
},
120
126
- track: function(inst : InstanceWithWrapperState) {
121
+ track: function(inst: InstanceWithWrapperState) {
122
if (getTracker(inst)) {
123
return;
124
}
@@ -131,24 +126,24 @@ var inputValueTracking = {
126
attachTracker(inst, trackValueOnNode(node, inst));
127
},
128
134
- updateValueIfChanged(inst : InstanceWithWrapperState | Fiber) {
129
+ updateValueIfChanged(inst: InstanceWithWrapperState | Fiber) {
130
if (!inst) {
131
return false;
132
}
133
var tracker = getTracker(inst);
134
135
if (!tracker) {
141
- if (typeof (inst : any).tag === 'number') {
142
- inputValueTracking.trackNode((inst : any).stateNode);
136
+ if (typeof (inst: any).tag === 'number') {
137
+ inputValueTracking.trackNode((inst: any).stateNode);
138
} else {
144
- inputValueTracking.track((inst : any));
139
+ inputValueTracking.track((inst: any));
140
}
141
return true;
142
}
143
144
var lastValue = tracker.getValue();
145
var nextValue = getValueFromNode(
151
- ReactDOMComponentTree.getNodeFromInstance(inst)
146
+ ReactDOMComponentTree.getNodeFromInstance(inst),
147
);
148
149
if (nextValue !== lastValue) {
@@ -159,7 +154,7 @@ var inputValueTracking = {
154
return false;
155
},
156
162
- stopTracking(inst : InstanceWithWrapperState | Fiber) {
157
+ stopTracking(inst: InstanceWithWrapperState | Fiber) {
158
var tracker = getTracker(inst);
159
if (tracker) {
160
tracker.stopTracking();
src/renderers/dom/shared/setInnerHTML.js
+19
-18
@@ -30,23 +30,22 @@ var reusableSVGContainer;
30
* @param {string} html
31
* @internal
32
*/
33
-var setInnerHTML = createMicrosoftUnsafeLocalFunction(
34
- function(node, html) {
35
- // IE does not have innerHTML for SVG nodes, so instead we inject the
36
- // new markup in a temp node and then move the child nodes across into
37
- // the target node
38
- if (node.namespaceURI === DOMNamespaces.svg && !('innerHTML' in node)) {
39
- reusableSVGContainer = reusableSVGContainer || document.createElement('div');
40
- reusableSVGContainer.innerHTML = '<svg>' + html + '</svg>';
41
- var svgNode = reusableSVGContainer.firstChild;
42
- while (svgNode.firstChild) {
43
- node.appendChild(svgNode.firstChild);
44
- }
45
- } else {
46
- node.innerHTML = html;
33
+var setInnerHTML = createMicrosoftUnsafeLocalFunction(function(node, html) {
34
+ // IE does not have innerHTML for SVG nodes, so instead we inject the
35
+ // new markup in a temp node and then move the child nodes across into
36
+ // the target node
37
+ if (node.namespaceURI === DOMNamespaces.svg && !('innerHTML' in node)) {
38
+ reusableSVGContainer = reusableSVGContainer ||
39
+ document.createElement('div');
40
+ reusableSVGContainer.innerHTML = '<svg>' + html + '</svg>';
41
+ var svgNode = reusableSVGContainer.firstChild;
42
+ while (svgNode.firstChild) {
43
+ node.appendChild(svgNode.firstChild);
44
}
45
+ } else {
46
+ node.innerHTML = html;
47
}
49
-);
48
+});
49
50
if (ExecutionEnvironment.canUseDOM) {
51
// IE8: When updating a just created node with innerHTML only leading
@@ -72,15 +71,17 @@ if (ExecutionEnvironment.canUseDOM) {
71
// thin air on IE8, this only happens if there is no visible text
72
// in-front of the non-visible tags. Piggyback on the whitespace fix
73
// and simply check if any non-visible tags appear in the source.
75
- if (WHITESPACE_TEST.test(html) ||
76
- html[0] === '<' && NONVISIBLE_TEST.test(html)) {
74
+ if (
75
+ WHITESPACE_TEST.test(html) ||
76
+ (html[0] === '<' && NONVISIBLE_TEST.test(html))
77
+ ) {
78
// Recover leading whitespace by temporarily prepending any character.
79
// \uFEFF has the potential advantage of being zero-width/invisible.
80
// UglifyJS drops U+FEFF chars when parsing, so use String.fromCharCode
81
// in hopes that this is preserved even if "\uFEFF" is transformed to
82
// the actual Unicode character (by Babel, for example).
83
// https://github.com/mishoo/UglifyJS2/blob/v2.4.20/lib/parse.js#L216
83
- node.innerHTML = String.fromCharCode(0xFEFF) + html;
84
+ node.innerHTML = String.fromCharCode(0xfeff) + html;
85
86
// deleteData leaves an empty `TextNode` which offsets the index of all
87
// children. Definitely want to avoid this.
src/renderers/dom/shared/setTextContent.js
+3
-1
@@ -29,7 +29,9 @@ var setTextContent = function(node, text) {
29
if (text) {
30
var firstChild = node.firstChild;
31
32
- if (firstChild && firstChild === node.lastChild && firstChild.nodeType === 3) {
32
+ if (
33
+ firstChild && firstChild === node.lastChild && firstChild.nodeType === 3
34
+ ) {
35
firstChild.nodeValue = text;
36
return;
37
}
src/renderers/dom/shared/syntheticEvents/SyntheticAnimationEvent.js
+9
-6
@@ -34,14 +34,17 @@ function SyntheticAnimationEvent(
34
dispatchConfig,
35
dispatchMarker,
36
nativeEvent,
37
- nativeEventTarget
37
+ nativeEventTarget,
38
) {
39
- return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
39
+ return SyntheticEvent.call(
40
+ this,
41
+ dispatchConfig,
42
+ dispatchMarker,
43
+ nativeEvent,
44
+ nativeEventTarget,
45
+ );
46
}
47
42
-SyntheticEvent.augmentClass(
43
- SyntheticAnimationEvent,
44
- AnimationEventInterface
45
-);
48
+SyntheticEvent.augmentClass(SyntheticAnimationEvent, AnimationEventInterface);
49
50
module.exports = SyntheticAnimationEvent;
src/renderers/dom/shared/syntheticEvents/SyntheticClipboardEvent.js
+16
-7
@@ -19,11 +19,9 @@ var SyntheticEvent = require('SyntheticEvent');
19
*/
20
var ClipboardEventInterface = {
21
clipboardData: function(event) {
22
- return (
23
- 'clipboardData' in event ?
24
- event.clipboardData :
25
- window.clipboardData
26
- );
22
+ return 'clipboardData' in event
23
+ ? event.clipboardData
24
+ : window.clipboardData;
25
},
26
};
27
@@ -33,8 +31,19 @@ var ClipboardEventInterface = {
31
* @param {object} nativeEvent Native browser event.
32
* @extends {SyntheticUIEvent}
33
*/
36
-function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
37
- return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
34
+function SyntheticClipboardEvent(
35
+ dispatchConfig,
36
+ dispatchMarker,
37
+ nativeEvent,
38
+ nativeEventTarget,
39
+) {
40
+ return SyntheticEvent.call(
41
+ this,
42
+ dispatchConfig,
43
+ dispatchMarker,
44
+ nativeEvent,
45
+ nativeEventTarget,
46
+ );
47
}
48
49
SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface);
src/renderers/dom/shared/syntheticEvents/SyntheticCompositionEvent.js
+9
-3
@@ -31,14 +31,20 @@ function SyntheticCompositionEvent(
31
dispatchConfig,
32
dispatchMarker,
33
nativeEvent,
34
- nativeEventTarget
34
+ nativeEventTarget,
35
) {
36
- return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
36
+ return SyntheticEvent.call(
37
+ this,
38
+ dispatchConfig,
39
+ dispatchMarker,
40
+ nativeEvent,
41
+ nativeEventTarget,
42
+ );
43
}
44
45
SyntheticEvent.augmentClass(
46
SyntheticCompositionEvent,
41
- CompositionEventInterface
47
+ CompositionEventInterface,
48
);
49
50
module.exports = SyntheticCompositionEvent;
src/renderers/dom/shared/syntheticEvents/SyntheticDragEvent.js
+13
-2
@@ -27,8 +27,19 @@ var DragEventInterface = {
27
* @param {object} nativeEvent Native browser event.
28
* @extends {SyntheticUIEvent}
29
*/
30
-function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
31
- return SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
30
+function SyntheticDragEvent(
31
+ dispatchConfig,
32
+ dispatchMarker,
33
+ nativeEvent,
34
+ nativeEventTarget,
35
+) {
36
+ return SyntheticMouseEvent.call(
37
+ this,
38
+ dispatchConfig,
39
+ dispatchMarker,
40
+ nativeEvent,
41
+ nativeEventTarget,
42
+ );
43
}
44
45
SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface);
src/renderers/dom/shared/syntheticEvents/SyntheticFocusEvent.js
+13
-2
@@ -27,8 +27,19 @@ var FocusEventInterface = {
27
* @param {object} nativeEvent Native browser event.
28
* @extends {SyntheticUIEvent}
29
*/
30
-function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
31
- return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
30
+function SyntheticFocusEvent(
31
+ dispatchConfig,
32
+ dispatchMarker,
33
+ nativeEvent,
34
+ nativeEventTarget,
35
+) {
36
+ return SyntheticUIEvent.call(
37
+ this,
38
+ dispatchConfig,
39
+ dispatchMarker,
40
+ nativeEvent,
41
+ nativeEventTarget,
42
+ );
43
}
44
45
SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface);
src/renderers/dom/shared/syntheticEvents/SyntheticInputEvent.js
+9
-6
@@ -32,14 +32,17 @@ function SyntheticInputEvent(
32
dispatchConfig,
33
dispatchMarker,
34
nativeEvent,
35
- nativeEventTarget
35
+ nativeEventTarget,
36
) {
37
- return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
37
+ return SyntheticEvent.call(
38
+ this,
39
+ dispatchConfig,
40
+ dispatchMarker,
41
+ nativeEvent,
42
+ nativeEventTarget,
43
+ );
44
}
45
40
-SyntheticEvent.augmentClass(
41
- SyntheticInputEvent,
42
- InputEventInterface
43
-);
46
+SyntheticEvent.augmentClass(SyntheticInputEvent, InputEventInterface);
47
48
module.exports = SyntheticInputEvent;
src/renderers/dom/shared/syntheticEvents/SyntheticKeyboardEvent.js
+13
-2
@@ -75,8 +75,19 @@ var KeyboardEventInterface = {
75
* @param {object} nativeEvent Native browser event.
76
* @extends {SyntheticUIEvent}
77
*/
78
-function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
79
- return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
78
+function SyntheticKeyboardEvent(
79
+ dispatchConfig,
80
+ dispatchMarker,
81
+ nativeEvent,
82
+ nativeEventTarget,
83
+) {
84
+ return SyntheticUIEvent.call(
85
+ this,
86
+ dispatchConfig,
87
+ dispatchMarker,
88
+ nativeEvent,
89
+ nativeEventTarget,
90
+ );
91
}
92
93
SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface);
src/renderers/dom/shared/syntheticEvents/SyntheticMouseEvent.js
+23
-13
@@ -46,22 +46,21 @@ var MouseEventInterface = {
46
},
47
buttons: null,
48
relatedTarget: function(event) {
49
- return event.relatedTarget || (
50
- event.fromElement === event.srcElement ?
51
- event.toElement :
52
- event.fromElement
53
- );
49
+ return event.relatedTarget ||
50
+ (event.fromElement === event.srcElement
51
+ ? event.toElement
52
+ : event.fromElement);
53
},
54
// "Proprietary" Interface.
55
pageX: function(event) {
57
- return 'pageX' in event ?
58
- event.pageX :
59
- event.clientX + ViewportMetrics.currentScrollLeft;
56
+ return 'pageX' in event
57
+ ? event.pageX
58
+ : event.clientX + ViewportMetrics.currentScrollLeft;
59
},
60
pageY: function(event) {
62
- return 'pageY' in event ?
63
- event.pageY :
64
- event.clientY + ViewportMetrics.currentScrollTop;
61
+ return 'pageY' in event
62
+ ? event.pageY
63
+ : event.clientY + ViewportMetrics.currentScrollTop;
64
},
65
};
66
@@ -71,8 +70,19 @@ var MouseEventInterface = {
70
* @param {object} nativeEvent Native browser event.
71
* @extends {SyntheticUIEvent}
72
*/
74
-function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
75
- return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
73
+function SyntheticMouseEvent(
74
+ dispatchConfig,
75
+ dispatchMarker,
76
+ nativeEvent,
77
+ nativeEventTarget,
78
+) {
79
+ return SyntheticUIEvent.call(
80
+ this,
81
+ dispatchConfig,
82
+ dispatchMarker,
83
+ nativeEvent,
84
+ nativeEventTarget,
85
+ );
86
}
87
88
SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface);
src/renderers/dom/shared/syntheticEvents/SyntheticTouchEvent.js
+13
-2
@@ -36,8 +36,19 @@ var TouchEventInterface = {
36
* @param {object} nativeEvent Native browser event.
37
* @extends {SyntheticUIEvent}
38
*/
39
-function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
40
- return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
39
+function SyntheticTouchEvent(
40
+ dispatchConfig,
41
+ dispatchMarker,
42
+ nativeEvent,
43
+ nativeEventTarget,
44
+) {
45
+ return SyntheticUIEvent.call(
46
+ this,
47
+ dispatchConfig,
48
+ dispatchMarker,
49
+ nativeEvent,
50
+ nativeEventTarget,
51
+ );
52
}
53
54
SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface);
src/renderers/dom/shared/syntheticEvents/SyntheticTransitionEvent.js
+9
-6
@@ -34,14 +34,17 @@ function SyntheticTransitionEvent(
34
dispatchConfig,
35
dispatchMarker,
36
nativeEvent,
37
- nativeEventTarget
37
+ nativeEventTarget,
38
) {
39
- return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
39
+ return SyntheticEvent.call(
40
+ this,
41
+ dispatchConfig,
42
+ dispatchMarker,
43
+ nativeEvent,
44
+ nativeEventTarget,
45
+ );
46
}
47
42
-SyntheticEvent.augmentClass(
43
- SyntheticTransitionEvent,
44
- TransitionEventInterface
45
-);
48
+SyntheticEvent.augmentClass(SyntheticTransitionEvent, TransitionEventInterface);
49
50
module.exports = SyntheticTransitionEvent;
src/renderers/dom/shared/syntheticEvents/SyntheticUIEvent.js
+13
-2
@@ -50,8 +50,19 @@ var UIEventInterface = {
50
* @param {object} nativeEvent Native browser event.
51
* @extends {SyntheticEvent}
52
*/
53
-function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
54
- return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
53
+function SyntheticUIEvent(
54
+ dispatchConfig,
55
+ dispatchMarker,
56
+ nativeEvent,
57
+ nativeEventTarget,
58
+) {
59
+ return SyntheticEvent.call(
60
+ this,
61
+ dispatchConfig,
62
+ dispatchMarker,
63
+ nativeEvent,
64
+ nativeEventTarget,
65
+ );
66
}
67
68
SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface);
src/renderers/dom/shared/syntheticEvents/SyntheticWheelEvent.js
+24
-14
@@ -19,20 +19,19 @@ var SyntheticMouseEvent = require('SyntheticMouseEvent');
19
*/
20
var WheelEventInterface = {
21
deltaX: function(event) {
22
- return (
23
- 'deltaX' in event ? event.deltaX :
24
- // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
25
- 'wheelDeltaX' in event ? -event.wheelDeltaX : 0
26
- );
22
+ return 'deltaX' in event
23
+ ? event.deltaX
24
+ : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
25
+ 'wheelDeltaX' in event ? -event.wheelDeltaX : 0;
26
},
27
deltaY: function(event) {
29
- return (
30
- 'deltaY' in event ? event.deltaY :
31
- // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
32
- 'wheelDeltaY' in event ? -event.wheelDeltaY :
33
- // Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
34
- 'wheelDelta' in event ? -event.wheelDelta : 0
35
- );
28
+ return 'deltaY' in event
29
+ ? event.deltaY
30
+ : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
31
+ 'wheelDeltaY' in event
32
+ ? -event.wheelDeltaY
33
+ : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
34
+ 'wheelDelta' in event ? -event.wheelDelta : 0;
35
},
36
deltaZ: null,
37
@@ -49,8 +48,19 @@ var WheelEventInterface = {
48
* @param {object} nativeEvent Native browser event.
49
* @extends {SyntheticMouseEvent}
50
*/
52
-function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
53
- return SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
51
+function SyntheticWheelEvent(
52
+ dispatchConfig,
53
+ dispatchMarker,
54
+ nativeEvent,
55
+ nativeEventTarget,
56
+) {
57
+ return SyntheticMouseEvent.call(
58
+ this,
59
+ dispatchConfig,
60
+ dispatchMarker,
61
+ nativeEvent,
62
+ nativeEventTarget,
63
+ );
64
}
65
66
SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface);
src/renderers/dom/shared/syntheticEvents/__tests__/SyntheticClipboardEvent-test.js
+8
-5
@@ -29,12 +29,15 @@ describe('SyntheticClipboardEvent', () => {
29
describe('when event has clipboardData', () => {
30
it("returns event's clipboardData", () => {
31
// Mock clipboardData since native implementation doesn't have a constructor
32
- var clipboardData = jasmine.createSpyObj(
33
- 'clipboardData',
34
- ['dropEffect', 'effectAllowed', 'files', 'items', 'types']
35
- );
32
+ var clipboardData = jasmine.createSpyObj('clipboardData', [
33
+ 'dropEffect',
34
+ 'effectAllowed',
35
+ 'files',
36
+ 'items',
37
+ 'types',
38
+ ]);
39
var clipboardEvent = createEvent({clipboardData: clipboardData});
37
-
40
+
41
expect(clipboardEvent.clipboardData).toBe(clipboardData);
42
});
43
});
src/renderers/dom/shared/syntheticEvents/__tests__/SyntheticEvent-test.js
+47
-44
@@ -53,9 +53,9 @@ describe('SyntheticEvent', () => {
53
});
54
55
it('should be prevented if nativeEvent is prevented', () => {
56
- expect(
57
- createEvent({defaultPrevented: true}).isDefaultPrevented()
58
- ).toBe(true);
56
+ expect(createEvent({defaultPrevented: true}).isDefaultPrevented()).toBe(
57
+ true,
58
+ );
59
expect(createEvent({returnValue: false}).isDefaultPrevented()).toBe(true);
60
});
61
@@ -91,10 +91,10 @@ describe('SyntheticEvent', () => {
91
// assert the first warning for accessing `type`
92
expectDev(console.error.calls.argsFor(0)[0]).toBe(
93
'Warning: This synthetic event is reused for performance reasons. If ' +
94
- 'you\'re seeing this, you\'re accessing the property `type` on a ' +
95
- 'released/nullified synthetic event. This is set to null. If you must ' +
96
- 'keep the original synthetic event around, use event.persist(). ' +
97
- 'See https://fb.me/react-event-pooling for more information.'
94
+ "you're seeing this, you're accessing the property `type` on a " +
95
+ 'released/nullified synthetic event. This is set to null. If you must ' +
96
+ 'keep the original synthetic event around, use event.persist(). ' +
97
+ 'See https://fb.me/react-event-pooling for more information.',
98
);
99
});
100
@@ -103,14 +103,14 @@ describe('SyntheticEvent', () => {
103
var target = document.createElement('div');
104
var syntheticEvent = createEvent({srcElement: target});
105
syntheticEvent.destructor();
106
- expect(syntheticEvent.type = 'MouseEvent').toBe('MouseEvent');
106
+ expect((syntheticEvent.type = 'MouseEvent')).toBe('MouseEvent');
107
expectDev(console.error.calls.count()).toBe(1);
108
expectDev(console.error.calls.argsFor(0)[0]).toBe(
109
'Warning: This synthetic event is reused for performance reasons. If ' +
110
- 'you\'re seeing this, you\'re setting the property `type` on a ' +
111
- 'released/nullified synthetic event. This is effectively a no-op. If you must ' +
112
- 'keep the original synthetic event around, use event.persist(). ' +
113
- 'See https://fb.me/react-event-pooling for more information.'
110
+ "you're seeing this, you're setting the property `type` on a " +
111
+ 'released/nullified synthetic event. This is effectively a no-op. If you must ' +
112
+ 'keep the original synthetic event around, use event.persist(). ' +
113
+ 'See https://fb.me/react-event-pooling for more information.',
114
);
115
});
116
@@ -122,10 +122,10 @@ describe('SyntheticEvent', () => {
122
expectDev(console.error.calls.count()).toBe(1);
123
expectDev(console.error.calls.argsFor(0)[0]).toBe(
124
'Warning: This synthetic event is reused for performance reasons. If ' +
125
- 'you\'re seeing this, you\'re accessing the method `preventDefault` on a ' +
126
- 'released/nullified synthetic event. This is a no-op function. If you must ' +
127
- 'keep the original synthetic event around, use event.persist(). ' +
128
- 'See https://fb.me/react-event-pooling for more information.'
125
+ "you're seeing this, you're accessing the method `preventDefault` on a " +
126
+ 'released/nullified synthetic event. This is a no-op function. If you must ' +
127
+ 'keep the original synthetic event around, use event.persist(). ' +
128
+ 'See https://fb.me/react-event-pooling for more information.',
129
);
130
});
131
@@ -137,39 +137,42 @@ describe('SyntheticEvent', () => {
137
expectDev(console.error.calls.count()).toBe(1);
138
expectDev(console.error.calls.argsFor(0)[0]).toBe(
139
'Warning: This synthetic event is reused for performance reasons. If ' +
140
- 'you\'re seeing this, you\'re accessing the method `stopPropagation` on a ' +
141
- 'released/nullified synthetic event. This is a no-op function. If you must ' +
142
- 'keep the original synthetic event around, use event.persist(). ' +
143
- 'See https://fb.me/react-event-pooling for more information.'
140
+ "you're seeing this, you're accessing the method `stopPropagation` on a " +
141
+ 'released/nullified synthetic event. This is a no-op function. If you must ' +
142
+ 'keep the original synthetic event around, use event.persist(). ' +
143
+ 'See https://fb.me/react-event-pooling for more information.',
144
);
145
});
146
147
// TODO: reenable this test. We are currently silencing these warnings when
148
// using TestUtils.Simulate to avoid spurious warnings that result from the
149
// way we simulate events.
150
- xit('should properly log warnings when events simulated with rendered components', () => {
151
- spyOn(console, 'error');
152
- var event;
153
- var element = document.createElement('div');
154
- function assignEvent(e) {
155
- event = e;
156
- }
157
- var instance = ReactDOM.render(<div onClick={assignEvent} />, element);
158
- ReactTestUtils.Simulate.click(ReactDOM.findDOMNode(instance));
159
- expectDev(console.error.calls.count()).toBe(0);
150
+ xit(
151
+ 'should properly log warnings when events simulated with rendered components',
152
+ () => {
153
+ spyOn(console, 'error');
154
+ var event;
155
+ var element = document.createElement('div');
156
+ function assignEvent(e) {
157
+ event = e;
158
+ }
159
+ var instance = ReactDOM.render(<div onClick={assignEvent} />, element);
160
+ ReactTestUtils.Simulate.click(ReactDOM.findDOMNode(instance));
161
+ expectDev(console.error.calls.count()).toBe(0);
162
161
- // access a property to cause the warning
162
- event.nativeEvent; // eslint-disable-line no-unused-expressions
163
+ // access a property to cause the warning
164
+ event.nativeEvent; // eslint-disable-line no-unused-expressions
165
164
- expectDev(console.error.calls.count()).toBe(1);
165
- expectDev(console.error.calls.argsFor(0)[0]).toBe(
166
- 'Warning: This synthetic event is reused for performance reasons. If ' +
167
- 'you\'re seeing this, you\'re accessing the property `nativeEvent` on a ' +
168
- 'released/nullified synthetic event. This is set to null. If you must ' +
169
- 'keep the original synthetic event around, use event.persist(). ' +
170
- 'See https://fb.me/react-event-pooling for more information.'
171
- );
172
- });
166
+ expectDev(console.error.calls.count()).toBe(1);
167
+ expectDev(console.error.calls.argsFor(0)[0]).toBe(
168
+ 'Warning: This synthetic event is reused for performance reasons. If ' +
169
+ "you're seeing this, you're accessing the property `nativeEvent` on a " +
170
+ 'released/nullified synthetic event. This is set to null. If you must ' +
171
+ 'keep the original synthetic event around, use event.persist(). ' +
172
+ 'See https://fb.me/react-event-pooling for more information.',
173
+ );
174
+ },
175
+ );
176
177
it('should warn if Proxy is supported and the synthetic event is added a property', () => {
178
spyOn(console, 'error');
@@ -181,9 +184,9 @@ describe('SyntheticEvent', () => {
184
expectDev(console.error.calls.count()).toBe(1);
185
expectDev(console.error.calls.argsFor(0)[0]).toBe(
186
'Warning: This synthetic event is reused for performance reasons. If ' +
184
- 'you\'re seeing this, you\'re adding a new property in the synthetic ' +
185
- 'event object. The property is never released. ' +
186
- 'See https://fb.me/react-event-pooling for more information.'
187
+ "you're seeing this, you're adding a new property in the synthetic " +
188
+ 'event object. The property is never released. ' +
189
+ 'See https://fb.me/react-event-pooling for more information.',
190
);
191
} else {
192
expectDev(console.error.calls.count()).toBe(0);
src/renderers/dom/shared/syntheticEvents/__tests__/SyntheticWheelEvent-test.js
-1
@@ -67,5 +67,4 @@ describe('SyntheticWheelEvent', () => {
67
syntheticEvent.persist();
68
expect(syntheticEvent.isPersistent()).toBe(true);
69
});
70
-
70
});
src/renderers/dom/shared/utils/ReactControlledValuePropTypes.js
+23
-22
@@ -17,43 +17,44 @@ var ReactPropTypesSecret = require('ReactPropTypesSecret');
17
var warning = require('fbjs/lib/warning');
18
19
var hasReadOnlyValue = {
20
- 'button': true,
21
- 'checkbox': true,
22
- 'image': true,
23
- 'hidden': true,
24
- 'radio': true,
25
- 'reset': true,
26
- 'submit': true,
20
+ button: true,
21
+ checkbox: true,
22
+ image: true,
23
+ hidden: true,
24
+ radio: true,
25
+ reset: true,
26
+ submit: true,
27
};
28
29
var propTypes = {
30
value: function(props, propName, componentName) {
31
- if (!props[propName] ||
32
- hasReadOnlyValue[props.type] ||
33
- props.onChange ||
34
- props.readOnly ||
35
- props.disabled) {
31
+ if (
32
+ !props[propName] ||
33
+ hasReadOnlyValue[props.type] ||
34
+ props.onChange ||
35
+ props.readOnly ||
36
+ props.disabled
37
+ ) {
38
return null;
39
}
40
return new Error(
41
'You provided a `value` prop to a form field without an ' +
40
- '`onChange` handler. This will render a read-only field. If ' +
41
- 'the field should be mutable use `defaultValue`. Otherwise, ' +
42
- 'set either `onChange` or `readOnly`.'
42
+ '`onChange` handler. This will render a read-only field. If ' +
43
+ 'the field should be mutable use `defaultValue`. Otherwise, ' +
44
+ 'set either `onChange` or `readOnly`.',
45
);
46
},
47
checked: function(props, propName, componentName) {
46
- if (!props[propName] ||
47
- props.onChange ||
48
- props.readOnly ||
49
- props.disabled) {
48
+ if (
49
+ !props[propName] || props.onChange || props.readOnly || props.disabled
50
+ ) {
51
return null;
52
}
53
return new Error(
54
'You provided a `checked` prop to a form field without an ' +
54
- '`onChange` handler. This will render a read-only field. If ' +
55
- 'the field should be mutable use `defaultChecked`. Otherwise, ' +
56
- 'set either `onChange` or `readOnly`.'
55
+ '`onChange` handler. This will render a read-only field. If ' +
56
+ 'the field should be mutable use `defaultChecked`. Otherwise, ' +
57
+ 'set either `onChange` or `readOnly`.',
58
);
59
},
60
onChange: React.PropTypes.func,
src/renderers/dom/shared/utils/ViewportMetrics.js
-2
@@ -12,7 +12,6 @@
12
'use strict';
13
14
var ViewportMetrics = {
15
-
15
currentScrollLeft: 0,
16
17
currentScrollTop: 0,
@@ -21,7 +20,6 @@ var ViewportMetrics = {
20
ViewportMetrics.currentScrollLeft = scrollPosition.x;
21
ViewportMetrics.currentScrollTop = scrollPosition.y;
22
},
24
-
23
};
24
25
module.exports = ViewportMetrics;
src/renderers/dom/shared/utils/__tests__/getEventCharCode-test.js
+7
-6
@@ -17,9 +17,10 @@ describe('getEventCharCode', () => {
17
describe('when charCode is present in nativeEvent', () => {
18
describe('when charCode is 0 and keyCode is 13', () => {
19
it('returns 13', () => {
20
- var nativeEvent = new KeyboardEvent(
21
- 'keypress', {charCode: 0, keyCode: 13}
22
- );
20
+ var nativeEvent = new KeyboardEvent('keypress', {
21
+ charCode: 0,
22
+ keyCode: 13,
23
+ });
24
25
expect(getEventCharCode(nativeEvent)).toBe(13);
26
});
@@ -62,7 +63,7 @@ describe('getEventCharCode', () => {
63
describe('when charCode is not present in nativeEvent', () => {
64
describe('when keyCode is 32 or bigger', () => {
65
it('returns keyCode', () => {
65
- var nativeEvent = {'keyCode': 32};
66
+ var nativeEvent = {keyCode: 32};
67
68
expect(getEventCharCode(nativeEvent)).toBe(32);
69
});
@@ -71,7 +72,7 @@ describe('getEventCharCode', () => {
72
describe('when keyCode is smaller than 32', () => {
73
describe('when keyCode is 13', () => {
74
it('returns 13', () => {
74
- var nativeEvent = {'keyCode': 13};
75
+ var nativeEvent = {keyCode: 13};
76
77
expect(getEventCharCode(nativeEvent)).toBe(13);
78
});
@@ -79,7 +80,7 @@ describe('getEventCharCode', () => {
80
81
describe('when keyCode is not 13', () => {
82
it('returns 0', () => {
82
- var nativeEvent = {'keyCode': 31};
83
+ var nativeEvent = {keyCode: 31};
84
85
expect(getEventCharCode(nativeEvent)).toBe(0);
86
});
src/renderers/dom/shared/utils/__tests__/getNodeForCharacterOffset-test.js
+7
-7
@@ -48,16 +48,16 @@ describe('getNodeForCharacterOffset', () => {
48
'<i>' +
49
'<i>1</i>' +
50
'<i>' +
51
- '<i>' +
52
- '<i>2</i>' +
53
- '<i></i>' +
54
- '</i>' +
51
+ '<i>' +
52
+ '<i>2</i>' +
53
+ '<i></i>' +
54
+ '</i>' +
55
'</i>' +
56
'<i>' +
57
- '3' +
58
- '<i>45</i>' +
57
+ '3' +
58
+ '<i>45</i>' +
59
'</i>' +
60
- '</i>'
60
+ '</i>',
61
);
62
63
expectNodeOffset(getNodeForCharacterOffset(node, 3), '3', 1);
src/renderers/dom/shared/utils/__tests__/setInnerHTML-test.js
+6
-2
@@ -37,8 +37,12 @@ describe('setInnerHTML', () => {
37
var html = '<circle></circle><rect></rect>';
38
setInnerHTML(node, html);
39
40
- expect(node.appendChild.calls.argsFor(0)[0].outerHTML).toBe('<circle></circle>');
41
- expect(node.appendChild.calls.argsFor(1)[0].outerHTML).toBe('<rect></rect>');
40
+ expect(node.appendChild.calls.argsFor(0)[0].outerHTML).toBe(
41
+ '<circle></circle>',
42
+ );
43
+ expect(node.appendChild.calls.argsFor(1)[0].outerHTML).toBe(
44
+ '<rect></rect>',
45
+ );
46
});
47
});
48
});
src/renderers/dom/shared/utils/getEventKey.js
+24
-14
@@ -18,18 +18,18 @@ var getEventCharCode = require('getEventCharCode');
18
* @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
19
*/
20
var normalizeKey = {
21
- 'Esc': 'Escape',
22
- 'Spacebar': ' ',
23
- 'Left': 'ArrowLeft',
24
- 'Up': 'ArrowUp',
25
- 'Right': 'ArrowRight',
26
- 'Down': 'ArrowDown',
27
- 'Del': 'Delete',
28
- 'Win': 'OS',
29
- 'Menu': 'ContextMenu',
30
- 'Apps': 'ContextMenu',
31
- 'Scroll': 'ScrollLock',
32
- 'MozPrintableKey': 'Unidentified',
21
+ Esc: 'Escape',
22
+ Spacebar: ' ',
23
+ Left: 'ArrowLeft',
24
+ Up: 'ArrowUp',
25
+ Right: 'ArrowRight',
26
+ Down: 'ArrowDown',
27
+ Del: 'Delete',
28
+ Win: 'OS',
29
+ Menu: 'ContextMenu',
30
+ Apps: 'ContextMenu',
31
+ Scroll: 'ScrollLock',
32
+ MozPrintableKey: 'Unidentified',
33
};
34
35
/**
@@ -59,8 +59,18 @@ var translateToKey = {
59
40: 'ArrowDown',
60
45: 'Insert',
61
46: 'Delete',
62
- 112: 'F1', 113: 'F2', 114: 'F3', 115: 'F4', 116: 'F5', 117: 'F6',
63
- 118: 'F7', 119: 'F8', 120: 'F9', 121: 'F10', 122: 'F11', 123: 'F12',
62
+ 112: 'F1',
63
+ 113: 'F2',
64
+ 114: 'F3',
65
+ 115: 'F4',
66
+ 116: 'F5',
67
+ 117: 'F6',
68
+ 118: 'F7',
69
+ 119: 'F8',
70
+ 120: 'F9',
71
+ 121: 'F10',
72
+ 122: 'F11',
73
+ 123: 'F12',
74
144: 'NumLock',
75
145: 'ScrollLock',
76
224: 'Meta',
src/renderers/dom/shared/utils/getEventModifierState.js
+4
-4
@@ -17,10 +17,10 @@
17
*/
18
19
var modifierKeyToProp = {
20
- 'Alt': 'altKey',
21
- 'Control': 'ctrlKey',
22
- 'Meta': 'metaKey',
23
- 'Shift': 'shiftKey',
20
+ Alt: 'altKey',
21
+ Control: 'ctrlKey',
22
+ Meta: 'metaKey',
23
+ Shift: 'shiftKey',
24
};
25
26
// IE8 does not implement getModifierState so we simply map it to the only
src/renderers/dom/shared/utils/getTextContentAccessor.js
+3
-3
@@ -25,9 +25,9 @@ function getTextContentAccessor() {
25
if (!contentKey && ExecutionEnvironment.canUseDOM) {
26
// Prefer textContent to innerText because many browsers support both but
27
// SVG <text> elements don't support innerText even when <div> does.
28
- contentKey = 'textContent' in document.documentElement ?
29
- 'textContent' :
30
- 'innerText';
28
+ contentKey = 'textContent' in document.documentElement
29
+ ? 'textContent'
30
+ : 'innerText';
31
}
32
return contentKey;
33
}
src/renderers/dom/shared/utils/getVendorPrefixedEventName.js
+1
-2
@@ -83,7 +83,6 @@ if (ExecutionEnvironment.canUseDOM) {
83
function getVendorPrefixedEventName(eventName) {
84
if (prefixedEventNames[eventName]) {
85
return prefixedEventNames[eventName];
86
-
86
} else if (!vendorPrefixes[eventName]) {
87
return eventName;
88
}
@@ -92,7 +91,7 @@ function getVendorPrefixedEventName(eventName) {
91
92
for (var styleProp in prefixMap) {
93
if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) {
95
- return prefixedEventNames[eventName] = prefixMap[styleProp];
94
+ return (prefixedEventNames[eventName] = prefixMap[styleProp]);
95
}
96
}
97
src/renderers/dom/shared/utils/isEventSupported.js
+5
-4
@@ -15,8 +15,7 @@ var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
15
16
var useHasFeature;
17
if (ExecutionEnvironment.canUseDOM) {
18
- useHasFeature =
19
- document.implementation &&
18
+ useHasFeature = document.implementation &&
19
document.implementation.hasFeature &&
20
// always returns true in newer browsers as per the standard.
21
// @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature
@@ -38,8 +37,10 @@ if (ExecutionEnvironment.canUseDOM) {
37
* @license Modernizr 3.0.0pre (Custom Build) | MIT
38
*/
39
function isEventSupported(eventNameSuffix, capture) {
41
- if (!ExecutionEnvironment.canUseDOM ||
42
- capture && !('addEventListener' in document)) {
40
+ if (
41
+ !ExecutionEnvironment.canUseDOM ||
42
+ (capture && !('addEventListener' in document))
43
+ ) {
44
return false;
45
}
46
src/renderers/dom/shared/validateDOMNesting.js
+202
-86
@@ -18,7 +18,7 @@ var warning = require('fbjs/lib/warning');
18
var validateDOMNesting = emptyFunction;
19
20
if (__DEV__) {
21
- var { getCurrentFiberStackAddendum } = require('ReactDebugCurrentFiber');
21
+ var {getCurrentFiberStackAddendum} = require('ReactDebugCurrentFiber');
22
23
// This validation code was written based on the HTML5 parsing spec:
24
// https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
@@ -33,36 +33,125 @@ if (__DEV__) {
33
34
// https://html.spec.whatwg.org/multipage/syntax.html#special
35
var specialTags = [
36
- 'address', 'applet', 'area', 'article', 'aside', 'base', 'basefont',
37
- 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col',
38
- 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset',
39
- 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2',
40
- 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe',
41
- 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee',
42
- 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript',
43
- 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section',
44
- 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template',
45
- 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr',
36
+ 'address',
37
+ 'applet',
38
+ 'area',
39
+ 'article',
40
+ 'aside',
41
+ 'base',
42
+ 'basefont',
43
+ 'bgsound',
44
+ 'blockquote',
45
+ 'body',
46
+ 'br',
47
+ 'button',
48
+ 'caption',
49
+ 'center',
50
+ 'col',
51
+ 'colgroup',
52
+ 'dd',
53
+ 'details',
54
+ 'dir',
55
+ 'div',
56
+ 'dl',
57
+ 'dt',
58
+ 'embed',
59
+ 'fieldset',
60
+ 'figcaption',
61
+ 'figure',
62
+ 'footer',
63
+ 'form',
64
+ 'frame',
65
+ 'frameset',
66
+ 'h1',
67
+ 'h2',
68
+ 'h3',
69
+ 'h4',
70
+ 'h5',
71
+ 'h6',
72
+ 'head',
73
+ 'header',
74
+ 'hgroup',
75
+ 'hr',
76
+ 'html',
77
+ 'iframe',
78
+ 'img',
79
+ 'input',
80
+ 'isindex',
81
+ 'li',
82
+ 'link',
83
+ 'listing',
84
+ 'main',
85
+ 'marquee',
86
+ 'menu',
87
+ 'menuitem',
88
+ 'meta',
89
+ 'nav',
90
+ 'noembed',
91
+ 'noframes',
92
+ 'noscript',
93
+ 'object',
94
+ 'ol',
95
+ 'p',
96
+ 'param',
97
+ 'plaintext',
98
+ 'pre',
99
+ 'script',
100
+ 'section',
101
+ 'select',
102
+ 'source',
103
+ 'style',
104
+ 'summary',
105
+ 'table',
106
+ 'tbody',
107
+ 'td',
108
+ 'template',
109
+ 'textarea',
110
+ 'tfoot',
111
+ 'th',
112
+ 'thead',
113
+ 'title',
114
+ 'tr',
115
+ 'track',
116
+ 'ul',
117
+ 'wbr',
118
'xmp',
119
];
120
121
// https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
122
var inScopeTags = [
51
- 'applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object',
123
+ 'applet',
124
+ 'caption',
125
+ 'html',
126
+ 'table',
127
+ 'td',
128
+ 'th',
129
+ 'marquee',
130
+ 'object',
131
'template',
132
133
// https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
134
// TODO: Distinguish by namespace here -- for <title>, including it here
135
// errs on the side of fewer warnings
57
- 'foreignObject', 'desc', 'title',
136
+ 'foreignObject',
137
+ 'desc',
138
+ 'title',
139
];
140
141
// https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope
142
var buttonScopeTags = inScopeTags.concat(['button']);
143
144
// https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags
64
- var impliedEndTags =
65
- ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt'];
145
+ var impliedEndTags = [
146
+ 'dd',
147
+ 'dt',
148
+ 'li',
149
+ 'option',
150
+ 'optgroup',
151
+ 'p',
152
+ 'rp',
153
+ 'rt',
154
+ ];
155
156
var emptyAncestorInfo = {
157
current: null,
@@ -94,7 +183,9 @@ if (__DEV__) {
183
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
184
if (
185
specialTags.indexOf(tag) !== -1 &&
97
- tag !== 'address' && tag !== 'div' && tag !== 'p'
186
+ tag !== 'address' &&
187
+ tag !== 'div' &&
188
+ tag !== 'p'
189
) {
190
ancestorInfo.listItemTagAutoclosing = null;
191
ancestorInfo.dlItemTagAutoclosing = null;
@@ -150,19 +241,20 @@ if (__DEV__) {
241
242
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr
243
case 'tr':
153
- return (
154
- tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' ||
155
- tag === 'template'
156
- );
244
+ return tag === 'th' ||
245
+ tag === 'td' ||
246
+ tag === 'style' ||
247
+ tag === 'script' ||
248
+ tag === 'template';
249
250
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody
251
case 'tbody':
252
case 'thead':
253
case 'tfoot':
162
- return (
163
- tag === 'tr' || tag === 'style' || tag === 'script' ||
164
- tag === 'template'
165
- );
254
+ return tag === 'tr' ||
255
+ tag === 'style' ||
256
+ tag === 'script' ||
257
+ tag === 'template';
258
259
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup
260
case 'colgroup':
@@ -170,20 +262,28 @@ if (__DEV__) {
262
263
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable
264
case 'table':
173
- return (
174
- tag === 'caption' || tag === 'colgroup' || tag === 'tbody' ||
175
- tag === 'tfoot' || tag === 'thead' || tag === 'style' ||
176
- tag === 'script' || tag === 'template'
177
- );
265
+ return tag === 'caption' ||
266
+ tag === 'colgroup' ||
267
+ tag === 'tbody' ||
268
+ tag === 'tfoot' ||
269
+ tag === 'thead' ||
270
+ tag === 'style' ||
271
+ tag === 'script' ||
272
+ tag === 'template';
273
274
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead
275
case 'head':
181
- return (
182
- tag === 'base' || tag === 'basefont' || tag === 'bgsound' ||
183
- tag === 'link' || tag === 'meta' || tag === 'title' ||
184
- tag === 'noscript' || tag === 'noframes' || tag === 'style' ||
185
- tag === 'script' || tag === 'template'
186
- );
276
+ return tag === 'base' ||
277
+ tag === 'basefont' ||
278
+ tag === 'bgsound' ||
279
+ tag === 'link' ||
280
+ tag === 'meta' ||
281
+ tag === 'title' ||
282
+ tag === 'noscript' ||
283
+ tag === 'noframes' ||
284
+ tag === 'style' ||
285
+ tag === 'script' ||
286
+ tag === 'template';
287
288
// https://html.spec.whatwg.org/multipage/semantics.html#the-html-element
289
case 'html':
@@ -202,10 +302,12 @@ if (__DEV__) {
302
case 'h4':
303
case 'h5':
304
case 'h6':
205
- return (
206
- parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' &&
207
- parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6'
208
- );
305
+ return parentTag !== 'h1' &&
306
+ parentTag !== 'h2' &&
307
+ parentTag !== 'h3' &&
308
+ parentTag !== 'h4' &&
309
+ parentTag !== 'h5' &&
310
+ parentTag !== 'h6';
311
312
case 'rp':
313
case 'rt':
@@ -318,9 +420,16 @@ if (__DEV__) {
420
return stack;
421
};
422
321
- var getOwnerInfo = function(childInstance, childTag, ancestorInstance, ancestorTag, isParent) {
423
+ var getOwnerInfo = function(
424
+ childInstance,
425
+ childTag,
426
+ ancestorInstance,
427
+ ancestorTag,
428
+ isParent,
429
+ ) {
430
var childOwner = childInstance && childInstance._currentElement._owner;
323
- var ancestorOwner = ancestorInstance && ancestorInstance._currentElement._owner;
431
+ var ancestorOwner = ancestorInstance &&
432
+ ancestorInstance._currentElement._owner;
433
434
var childOwners = findOwnerStack(childOwner);
435
var ancestorOwners = findOwnerStack(ancestorOwner);
@@ -338,25 +447,27 @@ if (__DEV__) {
447
}
448
449
var UNKNOWN = '(unknown)';
341
- var childOwnerNames = childOwners.slice(deepestCommon + 1).map(
342
- (inst) => getComponentName(inst) || UNKNOWN
343
- );
344
- var ancestorOwnerNames = ancestorOwners.slice(deepestCommon + 1).map(
345
- (inst) => getComponentName(inst) || UNKNOWN
346
- );
347
- var ownerInfo = [].concat(
348
- // If the parent and child instances have a common owner ancestor, start
349
- // with that -- otherwise we just start with the parent's owners.
350
- deepestCommon !== -1 ?
351
- getComponentName(childOwners[deepestCommon]) || UNKNOWN :
352
- [],
353
- ancestorOwnerNames,
354
- ancestorTag,
355
- // If we're warning about an invalid (non-parent) ancestry, add '...'
356
- isParent ? [] : ['...'],
357
- childOwnerNames,
358
- childTag
359
- ).join(' > ');
450
+ var childOwnerNames = childOwners
451
+ .slice(deepestCommon + 1)
452
+ .map(inst => getComponentName(inst) || UNKNOWN);
453
+ var ancestorOwnerNames = ancestorOwners
454
+ .slice(deepestCommon + 1)
455
+ .map(inst => getComponentName(inst) || UNKNOWN);
456
+ var ownerInfo = []
457
+ .concat(
458
+ // If the parent and child instances have a common owner ancestor, start
459
+ // with that -- otherwise we just start with the parent's owners.
460
+ deepestCommon !== -1
461
+ ? getComponentName(childOwners[deepestCommon]) || UNKNOWN
462
+ : [],
463
+ ancestorOwnerNames,
464
+ ancestorTag,
465
+ // If we're warning about an invalid (non-parent) ancestry, add '...'
466
+ isParent ? [] : ['...'],
467
+ childOwnerNames,
468
+ childTag,
469
+ )
470
+ .join(' > ');
471
472
return ownerInfo;
473
};
@@ -367,7 +478,7 @@ if (__DEV__) {
478
childTag,
479
childText,
480
childInstance,
370
- ancestorInfo
481
+ ancestorInfo,
482
) {
483
ancestorInfo = ancestorInfo || emptyAncestorInfo;
484
var parentInfo = ancestorInfo.current;
@@ -376,15 +487,17 @@ if (__DEV__) {
487
if (childText != null) {
488
warning(
489
childTag == null,
379
- 'validateDOMNesting: when childText is passed, childTag should be null'
490
+ 'validateDOMNesting: when childText is passed, childTag should be null',
491
);
492
childTag = '#text';
493
}
494
384
- var invalidParent =
385
- isTagValidWithParent(childTag, parentTag) ? null : parentInfo;
386
- var invalidAncestor =
387
- invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo);
495
+ var invalidParent = isTagValidWithParent(childTag, parentTag)
496
+ ? null
497
+ : parentInfo;
498
+ var invalidAncestor = invalidParent
499
+ ? null
500
+ : findInvalidAncestorForTag(childTag, ancestorInfo);
501
var invalidParentOrAncestor = invalidParent || invalidAncestor;
502
if (!invalidParentOrAncestor) {
503
return;
@@ -395,19 +508,26 @@ if (__DEV__) {
508
var addendum;
509
510
if (childInstance != null) {
398
- addendum = ' See ' + getOwnerInfo(
399
- childInstance,
400
- childTag,
401
- ancestorInstance,
402
- ancestorTag,
403
- !!invalidParent
404
- ) + '.';
511
+ addendum = ' See ' +
512
+ getOwnerInfo(
513
+ childInstance,
514
+ childTag,
515
+ ancestorInstance,
516
+ ancestorTag,
517
+ !!invalidParent,
518
+ ) +
519
+ '.';
520
} else {
521
addendum = getCurrentFiberStackAddendum();
522
}
523
409
- var warnKey =
410
- !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + addendum;
524
+ var warnKey = !!invalidParent +
525
+ '|' +
526
+ childTag +
527
+ '|' +
528
+ ancestorTag +
529
+ '|' +
530
+ addendum;
531
if (didWarn[warnKey]) {
532
return;
533
}
@@ -420,8 +540,7 @@ if (__DEV__) {
540
tagDisplayName = 'Text nodes';
541
} else {
542
tagDisplayName = 'Whitespace text nodes';
423
- whitespaceInfo =
424
- ' Make sure you don\'t have any extra whitespace between tags on ' +
543
+ whitespaceInfo = " Make sure you don't have any extra whitespace between tags on " +
544
'each line of your source code.';
545
}
546
} else {
@@ -431,8 +550,7 @@ if (__DEV__) {
550
if (invalidParent) {
551
var info = '';
552
if (ancestorTag === 'table' && childTag === 'tr') {
434
- info +=
435
- ' Add a <tbody> to your code to match the DOM tree generated by ' +
553
+ info += ' Add a <tbody> to your code to match the DOM tree generated by ' +
554
'the browser.';
555
}
556
warning(
@@ -442,16 +560,16 @@ if (__DEV__) {
560
ancestorTag,
561
whitespaceInfo,
562
info,
445
- addendum
563
+ addendum,
564
);
565
} else {
566
warning(
567
false,
568
'validateDOMNesting(...): %s cannot appear as a descendant of ' +
451
- '<%s>.%s',
569
+ '<%s>.%s',
570
tagDisplayName,
571
ancestorTag,
454
- addendum
572
+ addendum,
573
);
574
}
575
};
@@ -463,10 +581,8 @@ if (__DEV__) {
581
ancestorInfo = ancestorInfo || emptyAncestorInfo;
582
var parentInfo = ancestorInfo.current;
583
var parentTag = parentInfo && parentInfo.tag;
466
- return (
467
- isTagValidWithParent(tag, parentTag) &&
468
- !findInvalidAncestorForTag(tag, ancestorInfo)
469
- );
584
+ return isTagValidWithParent(tag, parentTag) &&
585
+ !findInvalidAncestorForTag(tag, ancestorInfo);
586
};
587
}
588
src/renderers/dom/shared/wrappers/__tests__/ReactDOMInput-test.js
+179
-133
@@ -11,7 +11,6 @@
11
12
'use strict';
13
14
-
14
var emptyFunction = require('fbjs/lib/emptyFunction');
15
16
describe('ReactDOMInput', () => {
@@ -42,10 +41,7 @@ describe('ReactDOMInput', () => {
41
42
it('should properly control a value even if no event listener exists', () => {
43
var container = document.createElement('div');
45
- var stub = ReactDOM.render(
46
- <input type="text" value="lion" />,
47
- container
48
- );
44
+ var stub = ReactDOM.render(<input type="text" value="lion" />, container);
45
46
document.body.appendChild(container);
47
@@ -77,12 +73,12 @@ describe('ReactDOMInput', () => {
73
changeEvent.initEvent('change', true, true);
74
75
class ControlledInputs extends React.Component {
80
- state = { value: 'lion' };
76
+ state = {value: 'lion'};
77
a = null;
78
b = null;
79
switchedFocus = false;
80
change(newValue) {
85
- this.setState({ value: newValue });
81
+ this.setState({value: newValue});
82
// Calling focus here will blur the text box which causes a native
83
// change event. Ideally we shouldn't have to fire this ourselves.
84
// I don't know how to simulate a change event on a text box.
@@ -93,7 +89,7 @@ describe('ReactDOMInput', () => {
89
this.switchedFocus = true;
90
// currentValue should be 'giraffe' here because we should not have
91
// restored it on the target yet.
96
- this.setState({ value: currentValue });
92
+ this.setState({value: currentValue});
93
}
94
render() {
95
return (
@@ -105,10 +101,7 @@ describe('ReactDOMInput', () => {
101
onChange={e => this.change(e.target.value)}
102
onBlur={e => this.blur(e.target.value)}
103
/>
108
- <input
109
- type="text"
110
- ref={n => this.b = n}
111
- />
104
+ <input type="text" ref={n => this.b = n} />
105
</div>
106
);
107
}
@@ -139,7 +132,7 @@ describe('ReactDOMInput', () => {
132
inputEvent.initEvent('input', true, true);
133
134
class ControlledInputs extends React.Component {
142
- state = { value: 'lion' };
135
+ state = {value: 'lion'};
136
a = null;
137
b = null;
138
change(newValue) {
@@ -158,11 +151,7 @@ describe('ReactDOMInput', () => {
151
value="lion"
152
onChange={e => this.change(e.target.value)}
153
/>
161
- <input
162
- type="checkbox"
163
- ref={n => this.b = n}
164
- checked={true}
165
- />
154
+ <input type="checkbox" ref={n => this.b = n} checked={true} />
155
</div>
156
);
157
}
@@ -198,7 +187,7 @@ describe('ReactDOMInput', () => {
187
it('only assigns defaultValue if it changes', () => {
188
class Test extends React.Component {
189
render() {
201
- return (<input defaultValue="0" />);
190
+ return <input defaultValue="0" />;
191
}
192
}
193
@@ -210,7 +199,9 @@ describe('ReactDOMInput', () => {
199
return '0';
200
},
201
set(value) {
213
- throw new Error(`defaultValue was assigned ${value}, but it did not change!`);
202
+ throw new Error(
203
+ `defaultValue was assigned ${value}, but it did not change!`,
204
+ );
205
},
206
});
207
@@ -236,7 +227,10 @@ describe('ReactDOMInput', () => {
227
it('should update `defaultValue` for uncontrolled input', () => {
228
var container = document.createElement('div');
229
239
- var node = ReactDOM.render(<input type="text" defaultValue="0" />, container);
230
+ var node = ReactDOM.render(
231
+ <input type="text" defaultValue="0" />,
232
+ container,
233
+ );
234
235
expect(node.value).toBe('0');
236
@@ -249,7 +243,10 @@ describe('ReactDOMInput', () => {
243
it('should update `defaultValue` for uncontrolled date/time input', () => {
244
var container = document.createElement('div');
245
252
- var node = ReactDOM.render(<input type="date" defaultValue="1980-01-01" />, container);
246
+ var node = ReactDOM.render(
247
+ <input type="date" defaultValue="1980-01-01" />,
248
+ container,
249
+ );
250
251
expect(node.value).toBe('1980-01-01');
252
@@ -264,7 +261,10 @@ describe('ReactDOMInput', () => {
261
it('should take `defaultValue` when changing to uncontrolled input', () => {
262
var container = document.createElement('div');
263
267
- var node = ReactDOM.render(<input type="text" value="0" readOnly="true" />, container);
264
+ var node = ReactDOM.render(
265
+ <input type="text" value="0" readOnly="true" />,
266
+ container,
267
+ );
268
269
expect(node.value).toBe('0');
270
@@ -274,7 +274,9 @@ describe('ReactDOMInput', () => {
274
});
275
276
it('should render defaultValue for SSR', () => {
277
- var markup = ReactDOMServer.renderToString(<input type="text" defaultValue="1" />);
277
+ var markup = ReactDOMServer.renderToString(
278
+ <input type="text" defaultValue="1" />,
279
+ );
280
var div = document.createElement('div');
281
div.innerHTML = markup;
282
expect(div.firstChild.getAttribute('value')).toBe('1');
@@ -350,7 +352,7 @@ describe('ReactDOMInput', () => {
352
353
stub = ReactDOM.render(
354
<input type="text" value={true} onChange={emptyFunction} />,
353
- container
355
+ container,
356
);
357
expect(node.value).toEqual('true');
358
});
@@ -364,7 +366,7 @@ describe('ReactDOMInput', () => {
366
367
stub = ReactDOM.render(
368
<input type="text" value={false} onChange={emptyFunction} />,
367
- container
369
+ container,
370
);
371
expect(node.value).toEqual('false');
372
});
@@ -383,7 +385,7 @@ describe('ReactDOMInput', () => {
385
};
386
stub = ReactDOM.render(
387
<input type="text" value={objToString} onChange={emptyFunction} />,
386
- container
388
+ container,
389
);
390
expect(node.value).toEqual('foobar');
391
});
@@ -436,11 +438,7 @@ describe('ReactDOMInput', () => {
438
var fakeNativeEvent = function() {};
439
fakeNativeEvent.target = node;
440
fakeNativeEvent.path = [node, container];
439
- ReactTestUtils.simulateNativeEventOnNode(
440
- 'topInput',
441
- node,
442
- fakeNativeEvent
443
- );
441
+ ReactTestUtils.simulateNativeEventOnNode('topInput', node, fakeNativeEvent);
442
443
expect(handled).toBe(true);
444
});
@@ -455,7 +453,7 @@ describe('ReactDOMInput', () => {
453
// report this as not having a `value` attribute at all; IE reports it as
454
// the actual label that the user sees.
455
expect(
458
- !node.hasAttribute('value') || node.getAttribute('value').length > 0
456
+ !node.hasAttribute('value') || node.getAttribute('value').length > 0,
457
).toBe(true);
458
});
459
@@ -470,13 +468,10 @@ describe('ReactDOMInput', () => {
468
name="fruit"
469
checked={true}
470
onChange={emptyFunction}
473
- />A
474
- <input
475
- ref="b"
476
- type="radio"
477
- name="fruit"
478
- onChange={emptyFunction}
479
- />B
471
+ />
472
+ A
473
+ <input ref="b" type="radio" name="fruit" onChange={emptyFunction} />
474
+ B
475
476
<form>
477
<input
@@ -539,19 +534,20 @@ describe('ReactDOMInput', () => {
534
name="fruit"
535
checked={true}
536
onChange={emptyFunction}
542
- />A
537
+ />
538
+ A
539
</div>
540
);
541
}
542
}
543
544
class ComponentB extends React.Component {
549
- state = { changed: false };
545
+ state = {changed: false};
546
handleChange = () => {
547
this.setState({
548
changed: true,
549
});
554
- }
550
+ };
551
componentDidUpdate() {
552
sharedParent.appendChild(container2);
553
}
@@ -564,7 +560,8 @@ describe('ReactDOMInput', () => {
560
name="fruit"
561
checked={false}
562
onChange={this.handleChange}
567
- />B
563
+ />
564
+ B
565
</div>
566
);
567
}
@@ -591,17 +588,16 @@ describe('ReactDOMInput', () => {
588
589
it('should warn with value and no onChange handler and readOnly specified', () => {
590
ReactTestUtils.renderIntoDocument(
594
- <input type="text" value="zoink" readOnly={true} />
591
+ <input type="text" value="zoink" readOnly={true} />,
592
);
593
expectDev(console.error.calls.count()).toBe(0);
594
595
ReactTestUtils.renderIntoDocument(
599
- <input type="text" value="zoink" readOnly={false} />
596
+ <input type="text" value="zoink" readOnly={false} />,
597
);
598
expectDev(console.error.calls.count()).toBe(1);
599
});
600
604
-
601
it('should have a this value of undefined if bind is not used', () => {
602
var unboundInputOnChange = function() {
603
expect(this).toBe(undefined);
@@ -615,12 +611,12 @@ describe('ReactDOMInput', () => {
611
612
it('should warn with checked and no onChange handler with readOnly specified', () => {
613
ReactTestUtils.renderIntoDocument(
618
- <input type="checkbox" checked="false" readOnly={true} />
614
+ <input type="checkbox" checked="false" readOnly={true} />,
615
);
616
expectDev(console.error.calls.count()).toBe(0);
617
618
ReactTestUtils.renderIntoDocument(
623
- <input type="checkbox" checked="false" readOnly={false} />
619
+ <input type="checkbox" checked="false" readOnly={false} />,
620
);
621
expectDev(console.error.calls.count()).toBe(1);
622
});
@@ -636,8 +632,8 @@ describe('ReactDOMInput', () => {
632
ReactTestUtils.renderIntoDocument(<input type="text" value={null} />);
633
expectDev(console.error.calls.argsFor(0)[0]).toContain(
634
'`value` prop on `input` should not be null. ' +
639
- 'Consider using the empty string to clear the component or `undefined` ' +
640
- 'for uncontrolled components.'
635
+ 'Consider using the empty string to clear the component or `undefined` ' +
636
+ 'for uncontrolled components.',
637
);
638
639
ReactTestUtils.renderIntoDocument(<input type="text" value={null} />);
@@ -646,81 +642,100 @@ describe('ReactDOMInput', () => {
642
643
it('should warn if checked and defaultChecked props are specified', () => {
644
ReactTestUtils.renderIntoDocument(
649
- <input type="radio" checked={true} defaultChecked={true} readOnly={true} />
645
+ <input
646
+ type="radio"
647
+ checked={true}
648
+ defaultChecked={true}
649
+ readOnly={true}
650
+ />,
651
);
652
expectDev(console.error.calls.argsFor(0)[0]).toContain(
653
'A component contains an input of type radio with both checked and defaultChecked props. ' +
653
- 'Input elements must be either controlled or uncontrolled ' +
654
- '(specify either the checked prop, or the defaultChecked prop, but not ' +
655
- 'both). Decide between using a controlled or uncontrolled input ' +
656
- 'element and remove one of these props. More info: ' +
657
- 'https://fb.me/react-controlled-components'
654
+ 'Input elements must be either controlled or uncontrolled ' +
655
+ '(specify either the checked prop, or the defaultChecked prop, but not ' +
656
+ 'both). Decide between using a controlled or uncontrolled input ' +
657
+ 'element and remove one of these props. More info: ' +
658
+ 'https://fb.me/react-controlled-components',
659
);
660
661
ReactTestUtils.renderIntoDocument(
661
- <input type="radio" checked={true} defaultChecked={true} readOnly={true} />
662
+ <input
663
+ type="radio"
664
+ checked={true}
665
+ defaultChecked={true}
666
+ readOnly={true}
667
+ />,
668
);
669
expectDev(console.error.calls.count()).toBe(1);
670
});
671
672
it('should warn if value and defaultValue props are specified', () => {
673
ReactTestUtils.renderIntoDocument(
668
- <input type="text" value="foo" defaultValue="bar" readOnly={true} />
674
+ <input type="text" value="foo" defaultValue="bar" readOnly={true} />,
675
);
676
expectDev(console.error.calls.argsFor(0)[0]).toContain(
677
'A component contains an input of type text with both value and defaultValue props. ' +
672
- 'Input elements must be either controlled or uncontrolled ' +
673
- '(specify either the value prop, or the defaultValue prop, but not ' +
674
- 'both). Decide between using a controlled or uncontrolled input ' +
675
- 'element and remove one of these props. More info: ' +
676
- 'https://fb.me/react-controlled-components'
678
+ 'Input elements must be either controlled or uncontrolled ' +
679
+ '(specify either the value prop, or the defaultValue prop, but not ' +
680
+ 'both). Decide between using a controlled or uncontrolled input ' +
681
+ 'element and remove one of these props. More info: ' +
682
+ 'https://fb.me/react-controlled-components',
683
);
684
685
ReactTestUtils.renderIntoDocument(
680
- <input type="text" value="foo" defaultValue="bar" readOnly={true} />
686
+ <input type="text" value="foo" defaultValue="bar" readOnly={true} />,
687
);
688
expectDev(console.error.calls.count()).toBe(1);
689
});
690
691
it('should warn if controlled input switches to uncontrolled (value is undefined)', () => {
686
- var stub = <input type="text" value="controlled" onChange={emptyFunction} />;
692
+ var stub = (
693
+ <input type="text" value="controlled" onChange={emptyFunction} />
694
+ );
695
var container = document.createElement('div');
696
ReactDOM.render(stub, container);
697
ReactDOM.render(<input type="text" />, container);
698
expectDev(console.error.calls.count()).toBe(1);
699
expectDev(console.error.calls.argsFor(0)[0]).toContain(
700
'A component is changing a controlled input of type text to be uncontrolled. ' +
693
- 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
694
- 'Decide between using a controlled or uncontrolled input ' +
695
- 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components'
701
+ 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
702
+ 'Decide between using a controlled or uncontrolled input ' +
703
+ 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components',
704
);
705
});
706
707
it('should warn if controlled input switches to uncontrolled (value is null)', () => {
700
- var stub = <input type="text" value="controlled" onChange={emptyFunction} />;
708
+ var stub = (
709
+ <input type="text" value="controlled" onChange={emptyFunction} />
710
+ );
711
var container = document.createElement('div');
712
ReactDOM.render(stub, container);
713
ReactDOM.render(<input type="text" value={null} />, container);
714
expectDev(console.error.calls.count()).toBeGreaterThan(0);
715
expectDev(console.error.calls.argsFor(1)[0]).toContain(
716
'A component is changing a controlled input of type text to be uncontrolled. ' +
707
- 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
708
- 'Decide between using a controlled or uncontrolled input ' +
709
- 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components'
717
+ 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
718
+ 'Decide between using a controlled or uncontrolled input ' +
719
+ 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components',
720
);
721
});
722
723
it('should warn if controlled input switches to uncontrolled with defaultValue', () => {
714
- var stub = <input type="text" value="controlled" onChange={emptyFunction} />;
724
+ var stub = (
725
+ <input type="text" value="controlled" onChange={emptyFunction} />
726
+ );
727
var container = document.createElement('div');
728
ReactDOM.render(stub, container);
717
- ReactDOM.render(<input type="text" defaultValue="uncontrolled" />, container);
729
+ ReactDOM.render(
730
+ <input type="text" defaultValue="uncontrolled" />,
731
+ container,
732
+ );
733
expectDev(console.error.calls.count()).toBe(1);
734
expectDev(console.error.calls.argsFor(0)[0]).toContain(
735
'A component is changing a controlled input of type text to be uncontrolled. ' +
721
- 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
722
- 'Decide between using a controlled or uncontrolled input ' +
723
- 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components'
736
+ 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
737
+ 'Decide between using a controlled or uncontrolled input ' +
738
+ 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components',
739
);
740
});
741
@@ -732,9 +747,9 @@ describe('ReactDOMInput', () => {
747
expectDev(console.error.calls.count()).toBe(1);
748
expectDev(console.error.calls.argsFor(0)[0]).toContain(
749
'A component is changing an uncontrolled input of type text to be controlled. ' +
735
- 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
736
- 'Decide between using a controlled or uncontrolled input ' +
737
- 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components'
750
+ 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
751
+ 'Decide between using a controlled or uncontrolled input ' +
752
+ 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components',
753
);
754
});
755
@@ -746,51 +761,57 @@ describe('ReactDOMInput', () => {
761
expectDev(console.error.calls.count()).toBeGreaterThan(0);
762
expectDev(console.error.calls.argsFor(1)[0]).toContain(
763
'A component is changing an uncontrolled input of type text to be controlled. ' +
749
- 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
750
- 'Decide between using a controlled or uncontrolled input ' +
751
- 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components'
764
+ 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
765
+ 'Decide between using a controlled or uncontrolled input ' +
766
+ 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components',
767
);
768
});
769
770
it('should warn if controlled checkbox switches to uncontrolled (checked is undefined)', () => {
756
- var stub = <input type="checkbox" checked={true} onChange={emptyFunction} />;
771
+ var stub = (
772
+ <input type="checkbox" checked={true} onChange={emptyFunction} />
773
+ );
774
var container = document.createElement('div');
775
ReactDOM.render(stub, container);
776
ReactDOM.render(<input type="checkbox" />, container);
777
expectDev(console.error.calls.count()).toBe(1);
778
expectDev(console.error.calls.argsFor(0)[0]).toContain(
779
'A component is changing a controlled input of type checkbox to be uncontrolled. ' +
763
- 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
764
- 'Decide between using a controlled or uncontrolled input ' +
765
- 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components'
780
+ 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
781
+ 'Decide between using a controlled or uncontrolled input ' +
782
+ 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components',
783
);
784
});
785
786
it('should warn if controlled checkbox switches to uncontrolled (checked is null)', () => {
770
- var stub = <input type="checkbox" checked={true} onChange={emptyFunction} />;
787
+ var stub = (
788
+ <input type="checkbox" checked={true} onChange={emptyFunction} />
789
+ );
790
var container = document.createElement('div');
791
ReactDOM.render(stub, container);
792
ReactDOM.render(<input type="checkbox" checked={null} />, container);
793
expectDev(console.error.calls.count()).toBe(1);
794
expectDev(console.error.calls.argsFor(0)[0]).toContain(
795
'A component is changing a controlled input of type checkbox to be uncontrolled. ' +
777
- 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
778
- 'Decide between using a controlled or uncontrolled input ' +
779
- 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components'
796
+ 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
797
+ 'Decide between using a controlled or uncontrolled input ' +
798
+ 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components',
799
);
800
});
801
802
it('should warn if controlled checkbox switches to uncontrolled with defaultChecked', () => {
784
- var stub = <input type="checkbox" checked={true} onChange={emptyFunction} />;
803
+ var stub = (
804
+ <input type="checkbox" checked={true} onChange={emptyFunction} />
805
+ );
806
var container = document.createElement('div');
807
ReactDOM.render(stub, container);
808
ReactDOM.render(<input type="checkbox" defaultChecked={true} />, container);
809
expectDev(console.error.calls.count()).toBe(1);
810
expectDev(console.error.calls.argsFor(0)[0]).toContain(
811
'A component is changing a controlled input of type checkbox to be uncontrolled. ' +
791
- 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
792
- 'Decide between using a controlled or uncontrolled input ' +
793
- 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components'
812
+ 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
813
+ 'Decide between using a controlled or uncontrolled input ' +
814
+ 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components',
815
);
816
});
817
@@ -802,9 +823,9 @@ describe('ReactDOMInput', () => {
823
expectDev(console.error.calls.count()).toBe(1);
824
expectDev(console.error.calls.argsFor(0)[0]).toContain(
825
'A component is changing an uncontrolled input of type checkbox to be controlled. ' +
805
- 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
806
- 'Decide between using a controlled or uncontrolled input ' +
807
- 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components'
826
+ 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
827
+ 'Decide between using a controlled or uncontrolled input ' +
828
+ 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components',
829
);
830
});
831
@@ -816,9 +837,9 @@ describe('ReactDOMInput', () => {
837
expectDev(console.error.calls.count()).toBe(1);
838
expectDev(console.error.calls.argsFor(0)[0]).toContain(
839
'A component is changing an uncontrolled input of type checkbox to be controlled. ' +
819
- 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
820
- 'Decide between using a controlled or uncontrolled input ' +
821
- 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components'
840
+ 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
841
+ 'Decide between using a controlled or uncontrolled input ' +
842
+ 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components',
843
);
844
});
845
@@ -830,9 +851,9 @@ describe('ReactDOMInput', () => {
851
expectDev(console.error.calls.count()).toBe(1);
852
expectDev(console.error.calls.argsFor(0)[0]).toContain(
853
'A component is changing a controlled input of type radio to be uncontrolled. ' +
833
- 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
834
- 'Decide between using a controlled or uncontrolled input ' +
835
- 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components'
854
+ 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
855
+ 'Decide between using a controlled or uncontrolled input ' +
856
+ 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components',
857
);
858
});
859
@@ -844,9 +865,9 @@ describe('ReactDOMInput', () => {
865
expectDev(console.error.calls.count()).toBe(1);
866
expectDev(console.error.calls.argsFor(0)[0]).toContain(
867
'A component is changing a controlled input of type radio to be uncontrolled. ' +
847
- 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
848
- 'Decide between using a controlled or uncontrolled input ' +
849
- 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components'
868
+ 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
869
+ 'Decide between using a controlled or uncontrolled input ' +
870
+ 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components',
871
);
872
});
873
@@ -858,9 +879,9 @@ describe('ReactDOMInput', () => {
879
expectDev(console.error.calls.count()).toBe(1);
880
expectDev(console.error.calls.argsFor(0)[0]).toContain(
881
'A component is changing a controlled input of type radio to be uncontrolled. ' +
861
- 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
862
- 'Decide between using a controlled or uncontrolled input ' +
863
- 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components'
882
+ 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
883
+ 'Decide between using a controlled or uncontrolled input ' +
884
+ 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components',
885
);
886
});
887
@@ -872,9 +893,9 @@ describe('ReactDOMInput', () => {
893
expectDev(console.error.calls.count()).toBe(1);
894
expectDev(console.error.calls.argsFor(0)[0]).toContain(
895
'A component is changing an uncontrolled input of type radio to be controlled. ' +
875
- 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
876
- 'Decide between using a controlled or uncontrolled input ' +
877
- 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components'
896
+ 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
897
+ 'Decide between using a controlled or uncontrolled input ' +
898
+ 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components',
899
);
900
});
901
@@ -886,9 +907,9 @@ describe('ReactDOMInput', () => {
907
expectDev(console.error.calls.count()).toBe(1);
908
expectDev(console.error.calls.argsFor(0)[0]).toContain(
909
'A component is changing an uncontrolled input of type radio to be controlled. ' +
889
- 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
890
- 'Decide between using a controlled or uncontrolled input ' +
891
- 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components'
910
+ 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
911
+ 'Decide between using a controlled or uncontrolled input ' +
912
+ 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components',
913
);
914
});
915
@@ -896,15 +917,24 @@ describe('ReactDOMInput', () => {
917
var container = document.createElement('div');
918
ReactDOM.render(<input type="radio" value="value" />, container);
919
ReactDOM.render(<input type="radio" />, container);
899
- ReactDOM.render(<input type="radio" value="value" defaultChecked={true} />, container);
900
- ReactDOM.render(<input type="radio" value="value" onChange={() => null} />, container);
920
+ ReactDOM.render(
921
+ <input type="radio" value="value" defaultChecked={true} />,
922
+ container,
923
+ );
924
+ ReactDOM.render(
925
+ <input type="radio" value="value" onChange={() => null} />,
926
+ container,
927
+ );
928
ReactDOM.render(<input type="radio" />, container);
929
expectDev(console.error.calls.count()).toBe(0);
930
});
931
932
it('should not warn if radio value changes but never becomes uncontrolled', () => {
933
var container = document.createElement('div');
907
- ReactDOM.render(<input type="radio" checked={false} onChange={() => null} />, container);
934
+ ReactDOM.render(
935
+ <input type="radio" checked={false} onChange={() => null} />,
936
+ container,
937
+ );
938
ReactDOM.render(
939
<input
940
type="radio"
@@ -912,19 +942,29 @@ describe('ReactDOMInput', () => {
942
defaultChecked={true}
943
checked={false}
944
onChange={() => null}
915
- />, container);
945
+ />,
946
+ container,
947
+ );
948
expectDev(console.error.calls.count()).toBe(0);
949
});
950
951
it('should warn if radio checked false changes to become uncontrolled', () => {
952
var container = document.createElement('div');
921
- ReactDOM.render(<input type="radio" value="value" checked={false} onChange={() => null} />, container);
953
+ ReactDOM.render(
954
+ <input
955
+ type="radio"
956
+ value="value"
957
+ checked={false}
958
+ onChange={() => null}
959
+ />,
960
+ container,
961
+ );
962
ReactDOM.render(<input type="radio" value="value" />, container);
963
expectDev(console.error.calls.argsFor(0)[0]).toContain(
964
'A component is changing a controlled input of type radio to be uncontrolled. ' +
925
- 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
926
- 'Decide between using a controlled or uncontrolled input ' +
927
- 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components'
965
+ 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
966
+ 'Decide between using a controlled or uncontrolled input ' +
967
+ 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components',
968
);
969
});
970
@@ -950,7 +990,9 @@ describe('ReactDOMInput', () => {
990
return el;
991
});
992
953
- ReactTestUtils.renderIntoDocument(<input value="0" type="range" min="0" max="100" step="1" />);
993
+ ReactTestUtils.renderIntoDocument(
994
+ <input value="0" type="range" min="0" max="100" step="1" />,
995
+ );
996
expect(log).toEqual([
997
...(ReactDOMFeatureFlags.useFiber ? [] : ['set data-reactroot']),
998
'set type',
@@ -966,18 +1008,18 @@ describe('ReactDOMInput', () => {
1008
1009
it('sets value properly with type coming later in props', () => {
1010
var input = ReactTestUtils.renderIntoDocument(
969
- <input value="hi" type="radio" />
1011
+ <input value="hi" type="radio" />,
1012
);
1013
expect(input.value).toBe('hi');
1014
});
1015
1016
it('does not raise a validation warning when it switches types', () => {
1017
class Input extends React.Component {
976
- state = { type: 'number', value: 1000 };
1018
+ state = {type: 'number', value: 1000};
1019
1020
render() {
979
- var { value, type } = this.state;
980
- return (<input onChange={() => {}} type={type} value={value} />);
1021
+ var {value, type} = this.state;
1022
+ return <input onChange={() => {}} type={type} value={value} />;
1023
}
1024
}
1025
@@ -986,7 +1028,7 @@ describe('ReactDOMInput', () => {
1028
1029
// If the value is set before the type, a validation warning will raise and
1030
// the value will not be assigned.
989
- input.setState({ type: 'text', value: 'Test' });
1031
+ input.setState({type: 'text', value: 'Test'});
1032
expect(node.value).toEqual('Test');
1033
});
1034
@@ -1017,9 +1059,13 @@ describe('ReactDOMInput', () => {
1059
return el;
1060
});
1061
1020
- ReactTestUtils.renderIntoDocument(<input type="date" defaultValue="1980-01-01" />);
1062
+ ReactTestUtils.renderIntoDocument(
1063
+ <input type="date" defaultValue="1980-01-01" />,
1064
+ );
1065
expect(log).toEqual([
1022
- ...(ReactDOMFeatureFlags.useFiber ? [] : ['node.setAttribute("data-reactroot", "")']),
1066
+ ...(ReactDOMFeatureFlags.useFiber
1067
+ ? []
1068
+ : ['node.setAttribute("data-reactroot", "")']),
1069
'node.setAttribute("type", "date")',
1070
'node.setAttribute("value", "1980-01-01")',
1071
'node.value = ""',
src/renderers/dom/shared/wrappers/__tests__/ReactDOMOption-test.js
+13
-14
@@ -11,7 +11,6 @@
11
12
'use strict';
13
14
-
14
describe('ReactDOMOption', () => {
15
function normalizeCodeLocInfo(str) {
16
return str && str.replace(/\(at .+?:\d+\)/g, '(at **)');
@@ -45,12 +44,14 @@ describe('ReactDOMOption', () => {
44
ReactTestUtils.renderIntoDocument(el);
45
// only warn once
46
expectDev(console.error.calls.count()).toBe(1);
48
- expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toContain(
49
- ReactDOMFeatureFlags.useFiber ?
50
- '<div> cannot appear as a child of <option>.\n' +
51
- ' in div (at **)\n' +
52
- ' in option (at **)' :
53
- 'Only strings and numbers are supported as <option> children.'
47
+ expectDev(
48
+ normalizeCodeLocInfo(console.error.calls.argsFor(0)[0]),
49
+ ).toContain(
50
+ ReactDOMFeatureFlags.useFiber
51
+ ? '<div> cannot appear as a child of <option>.\n' +
52
+ ' in div (at **)\n' +
53
+ ' in option (at **)'
54
+ : 'Only strings and numbers are supported as <option> children.',
55
);
56
});
57
@@ -66,7 +67,7 @@ describe('ReactDOMOption', () => {
67
});
68
69
it('should be able to use dangerouslySetInnerHTML on option', () => {
69
- var stub = <option dangerouslySetInnerHTML={{ __html: 'foobar' }} />;
70
+ var stub = <option dangerouslySetInnerHTML={{__html: 'foobar'}} />;
71
stub = ReactTestUtils.renderIntoDocument(stub);
72
73
var node = ReactDOM.findDOMNode(stub);
@@ -86,12 +87,13 @@ describe('ReactDOMOption', () => {
87
88
it('should allow ignoring `value` on option', () => {
89
var a = 'a';
89
- var stub =
90
+ var stub = (
91
<select value="giraffe" onChange={() => {}}>
92
<option>monkey</option>
93
<option>gir{a}ffe</option>
94
<option>gorill{a}</option>
94
- </select>;
95
+ </select>
96
+ );
97
var options = stub.props.children;
98
var container = document.createElement('div');
99
stub = ReactDOM.render(stub, container);
@@ -99,10 +101,7 @@ describe('ReactDOMOption', () => {
101
102
expect(node.selectedIndex).toBe(1);
103
102
- ReactDOM.render(
103
- <select value="gorilla">{options}</select>,
104
- container
105
- );
104
+ ReactDOM.render(<select value="gorilla">{options}</select>, container);
105
expect(node.selectedIndex).toEqual(2);
106
});
107
});
src/renderers/dom/shared/wrappers/__tests__/ReactDOMSelect-test.js
+138
-118
@@ -11,7 +11,6 @@
11
12
'use strict';
13
14
-
14
describe('ReactDOMSelect', () => {
15
var React;
16
var ReactDOM;
@@ -28,12 +27,13 @@ describe('ReactDOMSelect', () => {
27
});
28
29
it('should allow setting `defaultValue`', () => {
31
- var stub =
30
+ var stub = (
31
<select defaultValue="giraffe">
32
<option value="monkey">A monkey!</option>
33
<option value="giraffe">A giraffe!</option>
34
<option value="gorilla">A gorilla!</option>
36
- </select>;
35
+ </select>
36
+ );
37
var options = stub.props.children;
38
var container = document.createElement('div');
39
stub = ReactDOM.render(stub, container);
@@ -44,7 +44,7 @@ describe('ReactDOMSelect', () => {
44
// Changing `defaultValue` should do nothing.
45
ReactDOM.render(
46
<select defaultValue="gorilla">{options}</select>,
47
- container
47
+ container,
48
);
49
expect(node.value).toEqual('giraffe');
50
});
@@ -58,12 +58,13 @@ describe('ReactDOMSelect', () => {
58
});
59
60
it('should not control when using `defaultValue`', () => {
61
- var el =
61
+ var el = (
62
<select defaultValue="giraffe">
63
<option value="monkey">A monkey!</option>
64
<option value="giraffe">A giraffe!</option>
65
<option value="gorilla">A gorilla!</option>
66
- </select>;
66
+ </select>
67
+ );
68
var container = document.createElement('div');
69
var stub = ReactDOM.render(el, container);
70
var node = ReactDOM.findDOMNode(stub);
@@ -77,39 +78,41 @@ describe('ReactDOMSelect', () => {
78
});
79
80
it('should allow setting `defaultValue` with multiple', () => {
80
- var stub =
81
+ var stub = (
82
<select multiple={true} defaultValue={['giraffe', 'gorilla']}>
83
<option value="monkey">A monkey!</option>
84
<option value="giraffe">A giraffe!</option>
85
<option value="gorilla">A gorilla!</option>
85
- </select>;
86
+ </select>
87
+ );
88
var options = stub.props.children;
89
var container = document.createElement('div');
90
stub = ReactDOM.render(stub, container);
91
var node = ReactDOM.findDOMNode(stub);
92
91
- expect(node.options[0].selected).toBe(false); // monkey
92
- expect(node.options[1].selected).toBe(true); // giraffe
93
- expect(node.options[2].selected).toBe(true); // gorilla
93
+ expect(node.options[0].selected).toBe(false); // monkey
94
+ expect(node.options[1].selected).toBe(true); // giraffe
95
+ expect(node.options[2].selected).toBe(true); // gorilla
96
97
// Changing `defaultValue` should do nothing.
98
ReactDOM.render(
99
<select multiple={true} defaultValue={['monkey']}>{options}</select>,
98
- container
100
+ container,
101
);
102
101
- expect(node.options[0].selected).toBe(false); // monkey
102
- expect(node.options[1].selected).toBe(true); // giraffe
103
- expect(node.options[2].selected).toBe(true); // gorilla
103
+ expect(node.options[0].selected).toBe(false); // monkey
104
+ expect(node.options[1].selected).toBe(true); // giraffe
105
+ expect(node.options[2].selected).toBe(true); // gorilla
106
});
107
108
it('should allow setting `value`', () => {
107
- var stub =
109
+ var stub = (
110
<select value="giraffe" onChange={noop}>
111
<option value="monkey">A monkey!</option>
112
<option value="giraffe">A giraffe!</option>
113
<option value="gorilla">A gorilla!</option>
112
- </select>;
114
+ </select>
115
+ );
116
var options = stub.props.children;
117
var container = document.createElement('div');
118
stub = ReactDOM.render(stub, container);
@@ -120,7 +123,7 @@ describe('ReactDOMSelect', () => {
123
// Changing the `value` prop should change the selected option.
124
ReactDOM.render(
125
<select value="gorilla" onChange={noop}>{options}</select>,
123
- container
126
+ container,
127
);
128
expect(node.value).toEqual('gorilla');
129
});
@@ -134,47 +137,49 @@ describe('ReactDOMSelect', () => {
137
});
138
139
it('should allow setting `value` with multiple', () => {
137
- var stub =
140
+ var stub = (
141
<select multiple={true} value={['giraffe', 'gorilla']} onChange={noop}>
142
<option value="monkey">A monkey!</option>
143
<option value="giraffe">A giraffe!</option>
144
<option value="gorilla">A gorilla!</option>
142
- </select>;
145
+ </select>
146
+ );
147
var options = stub.props.children;
148
var container = document.createElement('div');
149
stub = ReactDOM.render(stub, container);
150
var node = ReactDOM.findDOMNode(stub);
151
148
- expect(node.options[0].selected).toBe(false); // monkey
149
- expect(node.options[1].selected).toBe(true); // giraffe
150
- expect(node.options[2].selected).toBe(true); // gorilla
152
+ expect(node.options[0].selected).toBe(false); // monkey
153
+ expect(node.options[1].selected).toBe(true); // giraffe
154
+ expect(node.options[2].selected).toBe(true); // gorilla
155
156
// Changing the `value` prop should change the selected options.
157
ReactDOM.render(
158
<select multiple={true} value={['monkey']} onChange={noop}>
159
{options}
160
</select>,
157
- container
161
+ container,
162
);
163
160
- expect(node.options[0].selected).toBe(true); // monkey
161
- expect(node.options[1].selected).toBe(false); // giraffe
162
- expect(node.options[2].selected).toBe(false); // gorilla
164
+ expect(node.options[0].selected).toBe(true); // monkey
165
+ expect(node.options[1].selected).toBe(false); // giraffe
166
+ expect(node.options[2].selected).toBe(false); // gorilla
167
});
168
169
it('should not select other options automatically', () => {
166
- var stub =
170
+ var stub = (
171
<select multiple={true} value={['12']} onChange={noop}>
172
<option value="1">one</option>
173
<option value="2">two</option>
174
<option value="12">twelve</option>
171
- </select>;
175
+ </select>
176
+ );
177
stub = ReactTestUtils.renderIntoDocument(stub);
178
var node = ReactDOM.findDOMNode(stub);
179
175
- expect(node.options[0].selected).toBe(false); // one
176
- expect(node.options[1].selected).toBe(false); // two
177
- expect(node.options[2].selected).toBe(true); // twelve
180
+ expect(node.options[0].selected).toBe(false); // one
181
+ expect(node.options[1].selected).toBe(false); // two
182
+ expect(node.options[2].selected).toBe(true); // twelve
183
});
184
185
it('should reset child options selected when they are changed and `value` is set', () => {
@@ -188,14 +193,14 @@ describe('ReactDOMSelect', () => {
193
<option value="b">b</option>
194
<option value="c">c</option>
195
</select>,
191
- container
196
+ container,
197
);
198
199
var node = ReactDOM.findDOMNode(stub);
200
196
- expect(node.options[0].selected).toBe(true); // a
197
- expect(node.options[1].selected).toBe(true); // b
198
- expect(node.options[2].selected).toBe(false); // c
201
+ expect(node.options[0].selected).toBe(true); // a
202
+ expect(node.options[1].selected).toBe(true); // b
203
+ expect(node.options[2].selected).toBe(false); // c
204
});
205
206
it('should allow setting `value` with `objectToString`', () => {
@@ -206,124 +211,129 @@ describe('ReactDOMSelect', () => {
211
},
212
};
213
209
- var el =
214
+ var el = (
215
<select multiple={true} value={[objectToString]} onChange={noop}>
216
<option value="monkey">A monkey!</option>
217
<option value="giraffe">A giraffe!</option>
218
<option value="gorilla">A gorilla!</option>
214
- </select>;
219
+ </select>
220
+ );
221
var container = document.createElement('div');
222
var stub = ReactDOM.render(el, container);
223
var node = ReactDOM.findDOMNode(stub);
224
219
- expect(node.options[0].selected).toBe(false); // monkey
220
- expect(node.options[1].selected).toBe(true); // giraffe
221
- expect(node.options[2].selected).toBe(false); // gorilla
225
+ expect(node.options[0].selected).toBe(false); // monkey
226
+ expect(node.options[1].selected).toBe(true); // giraffe
227
+ expect(node.options[2].selected).toBe(false); // gorilla
228
229
// Changing the `value` prop should change the selected options.
230
objectToString.animal = 'monkey';
231
226
- var el2 =
232
+ var el2 = (
233
<select multiple={true} value={[objectToString]}>
234
<option value="monkey">A monkey!</option>
235
<option value="giraffe">A giraffe!</option>
236
<option value="gorilla">A gorilla!</option>
231
- </select>;
237
+ </select>
238
+ );
239
ReactDOM.render(el2, container);
240
234
- expect(node.options[0].selected).toBe(true); // monkey
235
- expect(node.options[1].selected).toBe(false); // giraffe
236
- expect(node.options[2].selected).toBe(false); // gorilla
241
+ expect(node.options[0].selected).toBe(true); // monkey
242
+ expect(node.options[1].selected).toBe(false); // giraffe
243
+ expect(node.options[2].selected).toBe(false); // gorilla
244
});
245
246
it('should allow switching to multiple', () => {
240
- var stub =
247
+ var stub = (
248
<select defaultValue="giraffe">
249
<option value="monkey">A monkey!</option>
250
<option value="giraffe">A giraffe!</option>
251
<option value="gorilla">A gorilla!</option>
245
- </select>;
252
+ </select>
253
+ );
254
var options = stub.props.children;
255
var container = document.createElement('div');
256
stub = ReactDOM.render(stub, container);
257
var node = ReactDOM.findDOMNode(stub);
258
251
- expect(node.options[0].selected).toBe(false); // monkey
252
- expect(node.options[1].selected).toBe(true); // giraffe
253
- expect(node.options[2].selected).toBe(false); // gorilla
259
+ expect(node.options[0].selected).toBe(false); // monkey
260
+ expect(node.options[1].selected).toBe(true); // giraffe
261
+ expect(node.options[2].selected).toBe(false); // gorilla
262
263
// When making it multiple, giraffe and gorilla should be selected
264
ReactDOM.render(
265
<select multiple={true} defaultValue={['giraffe', 'gorilla']}>
266
{options}
267
</select>,
260
- container
268
+ container,
269
);
270
263
- expect(node.options[0].selected).toBe(false); // monkey
264
- expect(node.options[1].selected).toBe(true); // giraffe
265
- expect(node.options[2].selected).toBe(true); // gorilla
271
+ expect(node.options[0].selected).toBe(false); // monkey
272
+ expect(node.options[1].selected).toBe(true); // giraffe
273
+ expect(node.options[2].selected).toBe(true); // gorilla
274
});
275
276
it('should allow switching from multiple', () => {
269
- var stub =
277
+ var stub = (
278
<select multiple={true} defaultValue={['giraffe', 'gorilla']}>
279
<option value="monkey">A monkey!</option>
280
<option value="giraffe">A giraffe!</option>
281
<option value="gorilla">A gorilla!</option>
274
- </select>;
282
+ </select>
283
+ );
284
var options = stub.props.children;
285
var container = document.createElement('div');
286
stub = ReactDOM.render(stub, container);
287
var node = ReactDOM.findDOMNode(stub);
288
280
- expect(node.options[0].selected).toBe(false); // monkey
281
- expect(node.options[1].selected).toBe(true); // giraffe
282
- expect(node.options[2].selected).toBe(true); // gorilla
289
+ expect(node.options[0].selected).toBe(false); // monkey
290
+ expect(node.options[1].selected).toBe(true); // giraffe
291
+ expect(node.options[2].selected).toBe(true); // gorilla
292
293
// When removing multiple, defaultValue is applied again, being omitted
294
// means that "monkey" will be selected
295
ReactDOM.render(
296
<select defaultValue="gorilla">{options}</select>,
288
- container
297
+ container,
298
);
299
291
-
292
- expect(node.options[0].selected).toBe(false); // monkey
293
- expect(node.options[1].selected).toBe(false); // giraffe
294
- expect(node.options[2].selected).toBe(true); // gorilla
300
+ expect(node.options[0].selected).toBe(false); // monkey
301
+ expect(node.options[1].selected).toBe(false); // giraffe
302
+ expect(node.options[2].selected).toBe(true); // gorilla
303
});
304
305
it('should remember value when switching to uncontrolled', () => {
298
- var stub =
306
+ var stub = (
307
<select value={'giraffe'} onChange={noop}>
308
<option value="monkey">A monkey!</option>
309
<option value="giraffe">A giraffe!</option>
310
<option value="gorilla">A gorilla!</option>
303
- </select>;
311
+ </select>
312
+ );
313
var options = stub.props.children;
314
var container = document.createElement('div');
315
stub = ReactDOM.render(stub, container);
316
var node = ReactDOM.findDOMNode(stub);
317
309
- expect(node.options[0].selected).toBe(false); // monkey
310
- expect(node.options[1].selected).toBe(true); // giraffe
311
- expect(node.options[2].selected).toBe(false); // gorilla
318
+ expect(node.options[0].selected).toBe(false); // monkey
319
+ expect(node.options[1].selected).toBe(true); // giraffe
320
+ expect(node.options[2].selected).toBe(false); // gorilla
321
322
ReactDOM.render(<select>{options}</select>, container);
323
315
- expect(node.options[0].selected).toBe(false); // monkey
316
- expect(node.options[1].selected).toBe(true); // giraffe
317
- expect(node.options[2].selected).toBe(false); // gorilla
324
+ expect(node.options[0].selected).toBe(false); // monkey
325
+ expect(node.options[1].selected).toBe(true); // giraffe
326
+ expect(node.options[2].selected).toBe(false); // gorilla
327
});
328
329
it('should remember updated value when switching to uncontrolled', () => {
321
- var stub =
330
+ var stub = (
331
<select value={'giraffe'} onChange={noop}>
332
<option value="monkey">A monkey!</option>
333
<option value="giraffe">A giraffe!</option>
334
<option value="gorilla">A gorilla!</option>
326
- </select>;
335
+ </select>
336
+ );
337
var options = stub.props.children;
338
var container = document.createElement('div');
339
stub = ReactDOM.render(stub, container);
@@ -331,27 +341,28 @@ describe('ReactDOMSelect', () => {
341
342
ReactDOM.render(
343
<select value="gorilla" onChange={noop}>{options}</select>,
334
- container
344
+ container,
345
);
346
337
- expect(node.options[0].selected).toBe(false); // monkey
338
- expect(node.options[1].selected).toBe(false); // giraffe
339
- expect(node.options[2].selected).toBe(true); // gorilla
347
+ expect(node.options[0].selected).toBe(false); // monkey
348
+ expect(node.options[1].selected).toBe(false); // giraffe
349
+ expect(node.options[2].selected).toBe(true); // gorilla
350
351
ReactDOM.render(<select>{options}</select>, container);
352
343
- expect(node.options[0].selected).toBe(false); // monkey
344
- expect(node.options[1].selected).toBe(false); // giraffe
345
- expect(node.options[2].selected).toBe(true); // gorilla
353
+ expect(node.options[0].selected).toBe(false); // monkey
354
+ expect(node.options[1].selected).toBe(false); // giraffe
355
+ expect(node.options[2].selected).toBe(true); // gorilla
356
});
357
358
it('should support server-side rendering', () => {
349
- var stub =
359
+ var stub = (
360
<select value="giraffe" onChange={noop}>
361
<option value="monkey">A monkey!</option>
362
<option value="giraffe">A giraffe!</option>
363
<option value="gorilla">A gorilla!</option>
354
- </select>;
364
+ </select>
365
+ );
366
var markup = ReactDOMServer.renderToString(stub);
367
expect(markup).toContain('<option selected="" value="giraffe"');
368
expect(markup).not.toContain('<option selected="" value="monkey"');
@@ -359,12 +370,13 @@ describe('ReactDOMSelect', () => {
370
});
371
372
it('should support server-side rendering with defaultValue', () => {
362
- var stub =
373
+ var stub = (
374
<select defaultValue="giraffe">
375
<option value="monkey">A monkey!</option>
376
<option value="giraffe">A giraffe!</option>
377
<option value="gorilla">A gorilla!</option>
367
- </select>;
378
+ </select>
379
+ );
380
var markup = ReactDOMServer.renderToString(stub);
381
expect(markup).toContain('<option selected="" value="giraffe"');
382
expect(markup).not.toContain('<option selected="" value="monkey"');
@@ -372,12 +384,13 @@ describe('ReactDOMSelect', () => {
384
});
385
386
it('should support server-side rendering with multiple', () => {
375
- var stub =
387
+ var stub = (
388
<select multiple={true} value={['giraffe', 'gorilla']} onChange={noop}>
389
<option value="monkey">A monkey!</option>
390
<option value="giraffe">A giraffe!</option>
391
<option value="gorilla">A gorilla!</option>
380
- </select>;
392
+ </select>
393
+ );
394
var markup = ReactDOMServer.renderToString(stub);
395
expect(markup).toContain('<option selected="" value="giraffe"');
396
expect(markup).toContain('<option selected="" value="gorilla"');
@@ -393,24 +406,24 @@ describe('ReactDOMSelect', () => {
406
<option key="giraffe" value="giraffe">A giraffe!</option>
407
<option key="gorilla" value="gorilla">A gorilla!</option>
408
</select>,
396
- container
409
+ container,
410
);
411
var node = ReactDOM.findDOMNode(select);
412
400
- expect(node.options[0].selected).toBe(false); // monkey
401
- expect(node.options[1].selected).toBe(true); // giraffe
402
- expect(node.options[2].selected).toBe(false); // gorilla
413
+ expect(node.options[0].selected).toBe(false); // monkey
414
+ expect(node.options[1].selected).toBe(true); // giraffe
415
+ expect(node.options[2].selected).toBe(false); // gorilla
416
417
ReactDOM.render(
418
<select multiple={true} defaultValue={['giraffe']}>
419
<option key="monkey" value="monkey">A monkey!</option>
420
<option key="gorilla" value="gorilla">A gorilla!</option>
421
</select>,
409
- container
422
+ container,
423
);
424
412
- expect(node.options[0].selected).toBe(false); // monkey
413
- expect(node.options[1].selected).toBe(false); // gorilla
425
+ expect(node.options[0].selected).toBe(false); // monkey
426
+ expect(node.options[1].selected).toBe(false); // gorilla
427
428
ReactDOM.render(
429
<select multiple={true} defaultValue={['giraffe']}>
@@ -418,35 +431,40 @@ describe('ReactDOMSelect', () => {
431
<option key="giraffe" value="giraffe">A giraffe!</option>
432
<option key="gorilla" value="gorilla">A gorilla!</option>
433
</select>,
421
- container
434
+ container,
435
);
436
424
- expect(node.options[0].selected).toBe(false); // monkey
425
- expect(node.options[1].selected).toBe(false); // giraffe
426
- expect(node.options[2].selected).toBe(false); // gorilla
437
+ expect(node.options[0].selected).toBe(false); // monkey
438
+ expect(node.options[1].selected).toBe(false); // giraffe
439
+ expect(node.options[2].selected).toBe(false); // gorilla
440
});
441
442
it('should warn if value is null', () => {
443
spyOn(console, 'error');
444
432
- ReactTestUtils.renderIntoDocument(<select value={null}><option value="test" /></select>);
445
+ ReactTestUtils.renderIntoDocument(
446
+ <select value={null}><option value="test" /></select>,
447
+ );
448
expectDev(console.error.calls.argsFor(0)[0]).toContain(
449
'`value` prop on `select` should not be null. ' +
435
- 'Consider using the empty string to clear the component or `undefined` ' +
436
- 'for uncontrolled components.'
450
+ 'Consider using the empty string to clear the component or `undefined` ' +
451
+ 'for uncontrolled components.',
452
);
453
439
- ReactTestUtils.renderIntoDocument(<select value={null}><option value="test" /></select>);
454
+ ReactTestUtils.renderIntoDocument(
455
+ <select value={null}><option value="test" /></select>,
456
+ );
457
expectDev(console.error.calls.count()).toBe(1);
458
});
459
460
it('should refresh state on change', () => {
444
- var stub =
461
+ var stub = (
462
<select value="giraffe" onChange={noop}>
463
<option value="monkey">A monkey!</option>
464
<option value="giraffe">A giraffe!</option>
465
<option value="gorilla">A gorilla!</option>
449
- </select>;
466
+ </select>
467
+ );
468
stub = ReactTestUtils.renderIntoDocument(stub);
469
var node = ReactDOM.findDOMNode(stub);
470
@@ -462,14 +480,14 @@ describe('ReactDOMSelect', () => {
480
<option value="monkey">A monkey!</option>
481
<option value="giraffe">A giraffe!</option>
482
<option value="gorilla">A gorilla!</option>
465
- </select>
483
+ </select>,
484
);
485
expectDev(console.error.calls.argsFor(0)[0]).toContain(
486
'Select elements must be either controlled or uncontrolled ' +
469
- '(specify either the value prop, or the defaultValue prop, but not ' +
470
- 'both). Decide between using a controlled or uncontrolled select ' +
471
- 'element and remove one of these props. More info: ' +
472
- 'https://fb.me/react-controlled-components'
487
+ '(specify either the value prop, or the defaultValue prop, but not ' +
488
+ 'both). Decide between using a controlled or uncontrolled select ' +
489
+ 'element and remove one of these props. More info: ' +
490
+ 'https://fb.me/react-controlled-components',
491
);
492
493
ReactTestUtils.renderIntoDocument(
@@ -477,7 +495,7 @@ describe('ReactDOMSelect', () => {
495
<option value="monkey">A monkey!</option>
496
<option value="giraffe">A giraffe!</option>
497
<option value="gorilla">A gorilla!</option>
480
- </select>
498
+ </select>,
499
);
500
expectDev(console.error.calls.count()).toBe(1);
501
});
@@ -488,12 +506,13 @@ describe('ReactDOMSelect', () => {
506
}
507
508
var container = document.createElement('div');
491
- var stub =
509
+ var stub = (
510
<select value="giraffe" onChange={changeView}>
511
<option value="monkey">A monkey!</option>
512
<option value="giraffe">A giraffe!</option>
513
<option value="gorilla">A gorilla!</option>
496
- </select>;
514
+ </select>
515
+ );
516
stub = ReactDOM.render(stub, container);
517
var node = ReactDOM.findDOMNode(stub);
518
@@ -501,19 +520,20 @@ describe('ReactDOMSelect', () => {
520
});
521
522
it('should select grandchild options nested inside an optgroup', () => {
504
- var stub =
523
+ var stub = (
524
<select value="b" onChange={noop}>
525
<optgroup label="group">
526
<option value="a">a</option>
527
<option value="b">b</option>
528
<option value="c">c</option>
529
</optgroup>
511
- </select>;
530
+ </select>
531
+ );
532
var container = document.createElement('div');
533
var node = ReactDOM.render(stub, container);
534
515
- expect(node.options[0].selected).toBe(false); // a
516
- expect(node.options[1].selected).toBe(true); // b
517
- expect(node.options[2].selected).toBe(false); // c
535
+ expect(node.options[0].selected).toBe(false); // a
536
+ expect(node.options[1].selected).toBe(true); // b
537
+ expect(node.options[2].selected).toBe(false); // c
538
});
539
});
src/renderers/dom/shared/wrappers/__tests__/ReactDOMTextarea-test.js
+25
-17
@@ -121,7 +121,7 @@ describe('ReactDOMTextarea', () => {
121
122
stub = ReactDOM.render(
123
<textarea value="gorilla" onChange={emptyFunction} />,
124
- container
124
+ container,
125
);
126
expect(node.value).toEqual('gorilla');
127
});
@@ -152,7 +152,7 @@ describe('ReactDOMTextarea', () => {
152
153
stub = ReactDOM.render(
154
<textarea value={true} onChange={emptyFunction} />,
155
- container
155
+ container,
156
);
157
expect(node.value).toEqual('true');
158
});
@@ -166,7 +166,7 @@ describe('ReactDOMTextarea', () => {
166
167
stub = ReactDOM.render(
168
<textarea value={false} onChange={emptyFunction} />,
169
- container
169
+ container,
170
);
171
expect(node.value).toEqual('false');
172
});
@@ -185,7 +185,7 @@ describe('ReactDOMTextarea', () => {
185
};
186
stub = ReactDOM.render(
187
<textarea value={objToString} onChange={emptyFunction} />,
188
- container
188
+ container,
189
);
190
expect(node.value).toEqual('foo');
191
});
@@ -266,7 +266,10 @@ describe('ReactDOMTextarea', () => {
266
it('should keep value when switching to uncontrolled element if not changed', () => {
267
var container = document.createElement('div');
268
269
- var node = renderTextarea(<textarea value="kitten" onChange={emptyFunction} />, container);
269
+ var node = renderTextarea(
270
+ <textarea value="kitten" onChange={emptyFunction} />,
271
+ container,
272
+ );
273
274
expect(node.value).toBe('kitten');
275
@@ -278,11 +281,17 @@ describe('ReactDOMTextarea', () => {
281
it('should keep value when switching to uncontrolled element if changed', () => {
282
var container = document.createElement('div');
283
281
- var node = renderTextarea(<textarea value="kitten" onChange={emptyFunction} />, container);
284
+ var node = renderTextarea(
285
+ <textarea value="kitten" onChange={emptyFunction} />,
286
+ container,
287
+ );
288
289
expect(node.value).toBe('kitten');
290
285
- ReactDOM.render(<textarea value="puppies" onChange={emptyFunction} />, container);
291
+ ReactDOM.render(
292
+ <textarea value="puppies" onChange={emptyFunction} />,
293
+ container,
294
+ );
295
296
expect(node.value).toBe('puppies');
297
@@ -322,7 +331,7 @@ describe('ReactDOMTextarea', () => {
331
332
expect(function() {
333
ReactTestUtils.renderIntoDocument(
325
- <textarea>{'hello'}{'there'}</textarea>
334
+ <textarea>{'hello'}{'there'}</textarea>,
335
);
336
}).toThrow();
337
@@ -350,8 +359,8 @@ describe('ReactDOMTextarea', () => {
359
ReactTestUtils.renderIntoDocument(<textarea value={null} />);
360
expectDev(console.error.calls.argsFor(0)[0]).toContain(
361
'`value` prop on `textarea` should not be null. ' +
353
- 'Consider using the empty string to clear the component or `undefined` ' +
354
- 'for uncontrolled components.'
362
+ 'Consider using the empty string to clear the component or `undefined` ' +
363
+ 'for uncontrolled components.',
364
);
365
366
ReactTestUtils.renderIntoDocument(<textarea value={null} />);
@@ -361,20 +370,19 @@ describe('ReactDOMTextarea', () => {
370
it('should warn if value and defaultValue are specified', () => {
371
spyOn(console, 'error');
372
ReactTestUtils.renderIntoDocument(
364
- <textarea value="foo" defaultValue="bar" readOnly={true} />
373
+ <textarea value="foo" defaultValue="bar" readOnly={true} />,
374
);
375
expectDev(console.error.calls.argsFor(0)[0]).toContain(
376
'Textarea elements must be either controlled or uncontrolled ' +
368
- '(specify either the value prop, or the defaultValue prop, but not ' +
369
- 'both). Decide between using a controlled or uncontrolled textarea ' +
370
- 'and remove one of these props. More info: ' +
371
- 'https://fb.me/react-controlled-components'
377
+ '(specify either the value prop, or the defaultValue prop, but not ' +
378
+ 'both). Decide between using a controlled or uncontrolled textarea ' +
379
+ 'and remove one of these props. More info: ' +
380
+ 'https://fb.me/react-controlled-components',
381
);
382
383
ReactTestUtils.renderIntoDocument(
375
- <textarea value="foo" defaultValue="bar" readOnly={true} />
384
+ <textarea value="foo" defaultValue="bar" readOnly={true} />,
385
);
386
expectDev(console.error.calls.count()).toBe(1);
387
});
379
-
388
});
src/renderers/dom/stack/client/DOMChildrenOperations.js
+17
-19
@@ -43,7 +43,7 @@ var insertChildAt = createMicrosoftUnsafeLocalFunction(
43
// `appendChild(node)`. (Using `undefined` is not allowed by all browsers so
44
// we are careful to use `null`.)
45
parentNode.insertBefore(childNode, referenceNode);
46
- }
46
+ },
47
);
48
49
function insertLazyTreeChildAt(parentNode, childTree, referenceNode) {
@@ -72,7 +72,7 @@ function moveDelimitedText(
72
parentNode,
73
openingComment,
74
closingComment,
75
- referenceNode
75
+ referenceNode,
76
) {
77
var node = openingComment;
78
while (true) {
@@ -107,7 +107,7 @@ function replaceDelimitedText(openingComment, closingComment, stringText) {
107
insertChildAt(
108
parentNode,
109
document.createTextNode(stringText),
110
- nodeAfterComment
110
+ nodeAfterComment,
111
);
112
}
113
} else {
@@ -123,7 +123,9 @@ function replaceDelimitedText(openingComment, closingComment, stringText) {
123
124
if (__DEV__) {
125
ReactInstrumentation.debugTool.onHostOperation({
126
- instanceID: ReactDOMComponentTree.getInstanceFromNode(openingComment)._debugID,
126
+ instanceID: ReactDOMComponentTree.getInstanceFromNode(
127
+ openingComment,
128
+ )._debugID,
129
type: 'replace text',
130
payload: stringText,
131
});
@@ -157,7 +159,6 @@ if (__DEV__) {
159
* Operations for updating with DOM children.
160
*/
161
var DOMChildrenOperations = {
160
-
162
dangerouslyReplaceNodeWithMarkup: dangerouslyReplaceNodeWithMarkup,
163
164
replaceDelimitedText: replaceDelimitedText,
@@ -171,8 +172,9 @@ var DOMChildrenOperations = {
172
*/
173
processUpdates: function(parentNode, updates) {
174
if (__DEV__) {
174
- var parentNodeDebugID =
175
- ReactDOMComponentTree.getInstanceFromNode(parentNode)._debugID;
175
+ var parentNodeDebugID = ReactDOMComponentTree.getInstanceFromNode(
176
+ parentNode,
177
+ )._debugID;
178
}
179
180
for (var k = 0; k < updates.length; k++) {
@@ -182,13 +184,16 @@ var DOMChildrenOperations = {
184
insertLazyTreeChildAt(
185
parentNode,
186
update.content,
185
- getNodeAfter(parentNode, update.afterNode)
187
+ getNodeAfter(parentNode, update.afterNode),
188
);
189
if (__DEV__) {
190
ReactInstrumentation.debugTool.onHostOperation({
191
instanceID: parentNodeDebugID,
192
type: 'insert child',
191
- payload: {toIndex: update.toIndex, content: update.content.toString()},
193
+ payload: {
194
+ toIndex: update.toIndex,
195
+ content: update.content.toString(),
196
+ },
197
});
198
}
199
break;
@@ -196,7 +201,7 @@ var DOMChildrenOperations = {
201
moveChild(
202
parentNode,
203
update.fromNode,
199
- getNodeAfter(parentNode, update.afterNode)
204
+ getNodeAfter(parentNode, update.afterNode),
205
);
206
if (__DEV__) {
207
ReactInstrumentation.debugTool.onHostOperation({
@@ -207,10 +212,7 @@ var DOMChildrenOperations = {
212
}
213
break;
214
case 'SET_MARKUP':
210
- setInnerHTML(
211
- parentNode,
212
- update.content
213
- );
215
+ setInnerHTML(parentNode, update.content);
216
if (__DEV__) {
217
ReactInstrumentation.debugTool.onHostOperation({
218
instanceID: parentNodeDebugID,
@@ -220,10 +222,7 @@ var DOMChildrenOperations = {
222
}
223
break;
224
case 'TEXT_CONTENT':
223
- setTextContent(
224
- parentNode,
225
- update.content
226
- );
225
+ setTextContent(parentNode, update.content);
226
if (__DEV__) {
227
ReactInstrumentation.debugTool.onHostOperation({
228
instanceID: parentNodeDebugID,
@@ -245,7 +244,6 @@ var DOMChildrenOperations = {
244
}
245
}
246
},
248
-
247
};
248
249
module.exports = DOMChildrenOperations;
src/renderers/dom/stack/client/DOMLazyTree.js
+11
-13
@@ -31,14 +31,11 @@ var DOCUMENT_FRAGMENT_NODE_TYPE = 11;
31
*
32
* See https://github.com/spicyj/innerhtml-vs-createelement-vs-clonenode.
33
*/
34
-var enableLazy = (
35
- typeof document !== 'undefined' &&
36
- typeof document.documentMode === 'number'
37
- ||
38
- typeof navigator !== 'undefined' &&
39
- typeof navigator.userAgent === 'string' &&
40
- /\bEdge\/\d/.test(navigator.userAgent)
41
-);
34
+var enableLazy = (typeof document !== 'undefined' &&
35
+ typeof document.documentMode === 'number') ||
36
+ (typeof navigator !== 'undefined' &&
37
+ typeof navigator.userAgent === 'string' &&
38
+ /\bEdge\/\d/.test(navigator.userAgent));
39
40
function insertTreeChildren(tree) {
41
if (!enableLazy) {
@@ -65,19 +62,20 @@ var insertTreeBefore = createMicrosoftUnsafeLocalFunction(
62
// this level. Also, some <object> plugins (like Flash Player) will read
63
// <param> nodes immediately upon insertion into the DOM, so <object>
64
// must also be populated prior to insertion into the DOM.
68
- if (tree.node.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE
69
- ||
70
- tree.node.nodeType === ELEMENT_NODE_TYPE &&
65
+ if (
66
+ tree.node.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE ||
67
+ (tree.node.nodeType === ELEMENT_NODE_TYPE &&
68
tree.node.nodeName.toLowerCase() === 'object' &&
69
(tree.node.namespaceURI == null ||
73
- tree.node.namespaceURI === DOMNamespaces.html)) {
70
+ tree.node.namespaceURI === DOMNamespaces.html))
71
+ ) {
72
insertTreeChildren(tree);
73
parentNode.insertBefore(tree.node, referenceNode);
74
} else {
75
parentNode.insertBefore(tree.node, referenceNode);
76
insertTreeChildren(tree);
77
}
80
- }
78
+ },
79
);
80
81
function replaceChildWithTree(oldNode, newTree) {
src/renderers/dom/stack/client/Danger.js
+6
-8
@@ -19,7 +19,6 @@ var emptyFunction = require('fbjs/lib/emptyFunction');
19
var invariant = require('fbjs/lib/invariant');
20
21
var Danger = {
22
-
22
/**
23
* Replaces a node with a string of markup at its current position within its
24
* parent. The markup must render into a single root node.
@@ -32,17 +31,17 @@ var Danger = {
31
invariant(
32
ExecutionEnvironment.canUseDOM,
33
'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a ' +
35
- 'worker thread. Make sure `window` and `document` are available ' +
36
- 'globally before requiring React when unit testing or use ' +
37
- 'ReactDOMServer.renderToString() for server rendering.'
34
+ 'worker thread. Make sure `window` and `document` are available ' +
35
+ 'globally before requiring React when unit testing or use ' +
36
+ 'ReactDOMServer.renderToString() for server rendering.',
37
);
38
invariant(markup, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.');
39
invariant(
40
oldChild.nodeName !== 'HTML',
41
'dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the ' +
43
- '<html> node. This is because browser quirks make this unreliable ' +
44
- 'and/or slow. If you want to render to the root you must use ' +
45
- 'server rendering. See ReactDOMServer.renderToString().'
42
+ '<html> node. This is because browser quirks make this unreliable ' +
43
+ 'and/or slow. If you want to render to the root you must use ' +
44
+ 'server rendering. See ReactDOMServer.renderToString().',
45
);
46
47
if (typeof markup === 'string') {
@@ -52,7 +51,6 @@ var Danger = {
51
DOMLazyTree.replaceChildWithTree(oldChild, markup);
52
}
53
},
55
-
54
};
55
56
module.exports = Danger;
src/renderers/dom/stack/client/ReactComponentBrowserEnvironment.js
+2
-6
@@ -20,13 +20,9 @@ var ReactDOMIDOperations = require('ReactDOMIDOperations');
20
* need for this injection.
21
*/
22
var ReactComponentBrowserEnvironment = {
23
+ processChildrenUpdates: ReactDOMIDOperations.dangerouslyProcessChildrenUpdates,
24
24
- processChildrenUpdates:
25
- ReactDOMIDOperations.dangerouslyProcessChildrenUpdates,
26
-
27
- replaceNodeWithMarkup:
28
- DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup,
29
-
25
+ replaceNodeWithMarkup: DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup,
26
};
27
28
module.exports = ReactComponentBrowserEnvironment;
src/renderers/dom/stack/client/ReactDOMComponent.js
+181
-194
@@ -46,7 +46,7 @@ var listenTo = ReactBrowserEventEmitter.listenTo;
46
var registrationNameModules = EventPluginRegistry.registrationNameModules;
47
48
// For quickly matching children type, to test if can be treated as content.
49
-var CONTENT_TYPES = {'string': true, 'number': true};
49
+var CONTENT_TYPES = {string: true, number: true};
50
51
var STYLE = 'style';
52
var HTML = '__html';
@@ -59,7 +59,6 @@ var RESERVED_PROPS = {
59
// Node type for document fragments (Node.DOCUMENT_FRAGMENT_NODE).
60
var DOC_FRAGMENT_TYPE = 11;
61
62
-
62
function getDeclarationErrorAddendum(internalInstance) {
63
if (internalInstance) {
64
var owner = internalInstance._currentElement._owner || null;
@@ -86,53 +85,52 @@ function assertValidProps(component, props) {
85
invariant(
86
props.children == null && props.dangerouslySetInnerHTML == null,
87
'%s is a void element tag and must neither have `children` nor ' +
89
- 'use `dangerouslySetInnerHTML`.%s',
88
+ 'use `dangerouslySetInnerHTML`.%s',
89
component._tag,
91
- getDeclarationErrorAddendum(component)
90
+ getDeclarationErrorAddendum(component),
91
);
92
}
93
if (props.dangerouslySetInnerHTML != null) {
94
invariant(
95
props.children == null,
97
- 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'
96
+ 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.',
97
);
98
invariant(
99
typeof props.dangerouslySetInnerHTML === 'object' &&
101
- HTML in props.dangerouslySetInnerHTML,
100
+ HTML in props.dangerouslySetInnerHTML,
101
'`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' +
103
- 'Please visit https://fb.me/react-invariant-dangerously-set-inner-html ' +
104
- 'for more information.'
102
+ 'Please visit https://fb.me/react-invariant-dangerously-set-inner-html ' +
103
+ 'for more information.',
104
);
105
}
106
if (__DEV__) {
107
warning(
108
props.innerHTML == null,
109
'Directly setting property `innerHTML` is not permitted. ' +
111
- 'For more information, lookup documentation on `dangerouslySetInnerHTML`.'
110
+ 'For more information, lookup documentation on `dangerouslySetInnerHTML`.',
111
);
112
warning(
113
props.suppressContentEditableWarning ||
115
- !props.contentEditable ||
116
- props.children == null,
114
+ !props.contentEditable ||
115
+ props.children == null,
116
'A component is `contentEditable` and contains `children` managed by ' +
118
- 'React. It is now your responsibility to guarantee that none of ' +
119
- 'those nodes are unexpectedly modified or duplicated. This is ' +
120
- 'probably not intentional.'
117
+ 'React. It is now your responsibility to guarantee that none of ' +
118
+ 'those nodes are unexpectedly modified or duplicated. This is ' +
119
+ 'probably not intentional.',
120
);
121
warning(
123
- props.onFocusIn == null &&
124
- props.onFocusOut == null,
122
+ props.onFocusIn == null && props.onFocusOut == null,
123
'React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' +
126
- 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' +
127
- 'are not needed/supported by React.'
124
+ 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' +
125
+ 'are not needed/supported by React.',
126
);
127
}
128
invariant(
129
props.style == null || typeof props.style === 'object',
130
'The `style` prop expects a mapping from style properties to values, ' +
133
- 'not a string. For example, style={{marginRight: spacing + \'em\'}} when ' +
134
- 'using JSX.%s',
135
- getDeclarationErrorAddendum(component)
131
+ "not a string. For example, style={{marginRight: spacing + 'em'}} when " +
132
+ 'using JSX.%s',
133
+ getDeclarationErrorAddendum(component),
134
);
135
}
136
@@ -145,12 +143,15 @@ function ensureListeningTo(inst, registrationName, transaction) {
143
// bubble.
144
warning(
145
registrationName !== 'onScroll' || isEventSupported('scroll', true),
148
- 'This browser doesn\'t support the `onScroll` event'
146
+ "This browser doesn't support the `onScroll` event",
147
);
148
}
149
var containerInfo = inst._hostContainerInfo;
152
- var isDocumentFragment = containerInfo._node && containerInfo._node.nodeType === DOC_FRAGMENT_TYPE;
153
- var doc = isDocumentFragment ? containerInfo._node : containerInfo._ownerDocument;
150
+ var isDocumentFragment = containerInfo._node &&
151
+ containerInfo._node.nodeType === DOC_FRAGMENT_TYPE;
152
+ var doc = isDocumentFragment
153
+ ? containerInfo._node
154
+ : containerInfo._ownerDocument;
155
listenTo(registrationName, doc);
156
}
157
@@ -188,10 +189,17 @@ if (__DEV__) {
189
validateDOMNesting(null, '' + content, this, this._ancestorInfo);
190
this._contentDebugID = contentDebugID;
191
if (hasExistingContent) {
191
- ReactInstrumentation.debugTool.onBeforeUpdateComponent(contentDebugID, content);
192
+ ReactInstrumentation.debugTool.onBeforeUpdateComponent(
193
+ contentDebugID,
194
+ content,
195
+ );
196
ReactInstrumentation.debugTool.onUpdateComponent(contentDebugID);
197
} else {
194
- ReactInstrumentation.debugTool.onBeforeMountComponent(contentDebugID, content, debugID);
198
+ ReactInstrumentation.debugTool.onBeforeMountComponent(
199
+ contentDebugID,
200
+ content,
201
+ debugID,
202
+ );
203
ReactInstrumentation.debugTool.onMountComponent(contentDebugID);
204
ReactInstrumentation.debugTool.onSetChildren(debugID, [contentDebugID]);
205
}
@@ -250,25 +258,17 @@ function trapBubbledEventsLocal() {
258
// the state of the tree to be corrupted, `node` here can be null.
259
invariant(inst._rootNodeID, 'Must be mounted to trap events');
260
var node = getNode(inst);
253
- invariant(
254
- node,
255
- 'trapBubbledEvent(...): Requires node to be rendered.'
256
- );
261
+ invariant(node, 'trapBubbledEvent(...): Requires node to be rendered.');
262
263
switch (inst._tag) {
264
case 'iframe':
265
case 'object':
266
inst._wrapperState.listeners = [
262
- ReactBrowserEventEmitter.trapBubbledEvent(
263
- 'topLoad',
264
- 'load',
265
- node
266
- ),
267
+ ReactBrowserEventEmitter.trapBubbledEvent('topLoad', 'load', node),
268
];
269
break;
270
case 'video':
271
case 'audio':
271
-
272
inst._wrapperState.listeners = [];
273
// Create listener for each media event
274
for (var event in mediaEvents) {
@@ -277,48 +277,28 @@ function trapBubbledEventsLocal() {
277
ReactBrowserEventEmitter.trapBubbledEvent(
278
event,
279
mediaEvents[event],
280
- node
281
- )
280
+ node,
281
+ ),
282
);
283
}
284
}
285
break;
286
case 'source':
287
inst._wrapperState.listeners = [
288
- ReactBrowserEventEmitter.trapBubbledEvent(
289
- 'topError',
290
- 'error',
291
- node
292
- ),
288
+ ReactBrowserEventEmitter.trapBubbledEvent('topError', 'error', node),
289
];
290
break;
291
case 'img':
292
case 'image':
293
inst._wrapperState.listeners = [
298
- ReactBrowserEventEmitter.trapBubbledEvent(
299
- 'topError',
300
- 'error',
301
- node
302
- ),
303
- ReactBrowserEventEmitter.trapBubbledEvent(
304
- 'topLoad',
305
- 'load',
306
- node
307
- ),
294
+ ReactBrowserEventEmitter.trapBubbledEvent('topError', 'error', node),
295
+ ReactBrowserEventEmitter.trapBubbledEvent('topLoad', 'load', node),
296
];
297
break;
298
case 'form':
299
inst._wrapperState.listeners = [
312
- ReactBrowserEventEmitter.trapBubbledEvent(
313
- 'topReset',
314
- 'reset',
315
- node
316
- ),
317
- ReactBrowserEventEmitter.trapBubbledEvent(
318
- 'topSubmit',
319
- 'submit',
320
- node
321
- ),
300
+ ReactBrowserEventEmitter.trapBubbledEvent('topReset', 'reset', node),
301
+ ReactBrowserEventEmitter.trapBubbledEvent('topSubmit', 'submit', node),
302
];
303
break;
304
case 'input':
@@ -328,17 +308,13 @@ function trapBubbledEventsLocal() {
308
ReactBrowserEventEmitter.trapBubbledEvent(
309
'topInvalid',
310
'invalid',
331
- node
311
+ node,
312
),
313
];
314
break;
315
case 'details':
316
inst._wrapperState.listeners = [
337
- ReactBrowserEventEmitter.trapBubbledEvent(
338
- 'topToggle',
339
- 'toggle',
340
- node
341
- ),
317
+ ReactBrowserEventEmitter.trapBubbledEvent('topToggle', 'toggle', node),
318
];
319
break;
320
}
@@ -352,36 +328,39 @@ function postUpdateSelectWrapper() {
328
// those special-case tags.
329
330
var omittedCloseTags = {
355
- 'area': true,
356
- 'base': true,
357
- 'br': true,
358
- 'col': true,
359
- 'embed': true,
360
- 'hr': true,
361
- 'img': true,
362
- 'input': true,
363
- 'keygen': true,
364
- 'link': true,
365
- 'meta': true,
366
- 'param': true,
367
- 'source': true,
368
- 'track': true,
369
- 'wbr': true,
331
+ area: true,
332
+ base: true,
333
+ br: true,
334
+ col: true,
335
+ embed: true,
336
+ hr: true,
337
+ img: true,
338
+ input: true,
339
+ keygen: true,
340
+ link: true,
341
+ meta: true,
342
+ param: true,
343
+ source: true,
344
+ track: true,
345
+ wbr: true,
346
// NOTE: menuitem's close tag should be omitted, but that causes problems.
347
};
348
349
var newlineEatingTags = {
374
- 'listing': true,
375
- 'pre': true,
376
- 'textarea': true,
350
+ listing: true,
351
+ pre: true,
352
+ textarea: true,
353
};
354
355
// For HTML, certain tags cannot have children. This has the same purpose as
356
// `omittedCloseTags` except that `menuitem` should still have its closing tag.
357
382
-var voidElementTags = Object.assign({
383
- 'menuitem': true,
384
-}, omittedCloseTags);
358
+var voidElementTags = Object.assign(
359
+ {
360
+ menuitem: true,
361
+ },
362
+ omittedCloseTags,
363
+);
364
365
// We accept any tag to be rendered but since this gets injected into arbitrary
366
// HTML, we want to make sure that it's a safe tag.
@@ -441,7 +420,6 @@ function ReactDOMComponent(element) {
420
ReactDOMComponent.displayName = 'ReactDOMComponent';
421
422
ReactDOMComponent.Mixin = {
444
-
423
/**
424
* Generates root tag markup then recurses. This method has side effects and
425
* is not idempotent.
@@ -457,7 +435,7 @@ ReactDOMComponent.Mixin = {
435
transaction,
436
hostParent,
437
hostContainerInfo,
460
- context
438
+ context,
439
) {
440
this._rootNodeID = globalIdCounter++;
441
this._domID = hostContainerInfo._idCounter++;
@@ -527,18 +505,20 @@ ReactDOMComponent.Mixin = {
505
namespaceURI = hostContainerInfo._namespaceURI;
506
parentTag = hostContainerInfo._tag;
507
}
530
- if (namespaceURI == null ||
531
- namespaceURI === DOMNamespaces.svg && parentTag === 'foreignobject') {
508
+ if (
509
+ namespaceURI == null ||
510
+ (namespaceURI === DOMNamespaces.svg && parentTag === 'foreignobject')
511
+ ) {
512
namespaceURI = DOMNamespaces.html;
513
}
514
if (namespaceURI === DOMNamespaces.html) {
515
if (__DEV__) {
516
warning(
517
isCustomComponent(this._tag, props) ||
538
- this._tag === this._currentElement.type,
518
+ this._tag === this._currentElement.type,
519
'<%s /> is using uppercase HTML. Always use lowercase HTML tags ' +
540
- 'in React.',
541
- this._currentElement.type
520
+ 'in React.',
521
+ this._currentElement.type,
522
);
523
}
524
if (this._tag === 'svg') {
@@ -561,8 +541,11 @@ ReactDOMComponent.Mixin = {
541
// component when server rendering
542
validateDOMNesting(this._tag, null, this, parentInfo);
543
}
564
- this._ancestorInfo =
565
- validateDOMNesting.updatedAncestorInfo(parentInfo, this._tag, this);
544
+ this._ancestorInfo = validateDOMNesting.updatedAncestorInfo(
545
+ parentInfo,
546
+ this._tag,
547
+ this,
548
+ );
549
}
550
551
var mountImage;
@@ -586,20 +569,17 @@ ReactDOMComponent.Mixin = {
569
el = ownerDocument.createElement(type);
570
}
571
} else {
589
- el = ownerDocument.createElementNS(
590
- namespaceURI,
591
- type
592
- );
572
+ el = ownerDocument.createElementNS(namespaceURI, type);
573
}
574
var isCustomComponentTag = isCustomComponent(this._tag, props);
575
if (__DEV__ && isCustomComponentTag && !didWarnShadyDOM && el.shadyRoot) {
576
var owner = this._currentElement._owner;
597
- var name = owner && owner.getName() || 'A component';
577
+ var name = (owner && owner.getName()) || 'A component';
578
warning(
579
false,
580
'%s is using shady DOM. Using shady DOM with React can ' +
601
- 'cause things to break subtly.',
602
- name
581
+ 'cause things to break subtly.',
582
+ name,
583
);
584
didWarnShadyDOM = true;
585
}
@@ -614,7 +594,10 @@ ReactDOMComponent.Mixin = {
594
mountImage = lazyTree;
595
} else {
596
validateDangerousTag(this._tag);
617
- var tagOpen = this._createOpenTagMarkupAndPutListeners(transaction, props);
597
+ var tagOpen = this._createOpenTagMarkupAndPutListeners(
598
+ transaction,
599
+ props,
600
+ );
601
var tagContent = this._createContentMarkup(transaction, props, context);
602
if (!tagContent && omittedCloseTags[this._tag]) {
603
mountImage = tagOpen + '/>';
@@ -625,57 +608,43 @@ ReactDOMComponent.Mixin = {
608
609
switch (this._tag) {
610
case 'input':
628
- transaction.getReactMountReady().enqueue(
629
- inputPostMount,
630
- this
631
- );
611
+ transaction.getReactMountReady().enqueue(inputPostMount, this);
612
if (props.autoFocus) {
633
- transaction.getReactMountReady().enqueue(
634
- AutoFocusUtils.focusDOMComponent,
635
- this
636
- );
613
+ transaction
614
+ .getReactMountReady()
615
+ .enqueue(AutoFocusUtils.focusDOMComponent, this);
616
}
617
break;
618
case 'textarea':
640
- transaction.getReactMountReady().enqueue(
641
- textareaPostMount,
642
- this
643
- );
619
+ transaction.getReactMountReady().enqueue(textareaPostMount, this);
620
if (props.autoFocus) {
645
- transaction.getReactMountReady().enqueue(
646
- AutoFocusUtils.focusDOMComponent,
647
- this
648
- );
621
+ transaction
622
+ .getReactMountReady()
623
+ .enqueue(AutoFocusUtils.focusDOMComponent, this);
624
}
625
break;
626
case 'select':
627
if (props.autoFocus) {
653
- transaction.getReactMountReady().enqueue(
654
- AutoFocusUtils.focusDOMComponent,
655
- this
656
- );
628
+ transaction
629
+ .getReactMountReady()
630
+ .enqueue(AutoFocusUtils.focusDOMComponent, this);
631
}
632
break;
633
case 'button':
634
if (props.autoFocus) {
661
- transaction.getReactMountReady().enqueue(
662
- AutoFocusUtils.focusDOMComponent,
663
- this
664
- );
635
+ transaction
636
+ .getReactMountReady()
637
+ .enqueue(AutoFocusUtils.focusDOMComponent, this);
638
}
639
break;
640
case 'option':
668
- transaction.getReactMountReady().enqueue(
669
- optionPostMount,
670
- this
671
- );
641
+ transaction.getReactMountReady().enqueue(optionPostMount, this);
642
break;
643
default:
644
if (typeof props.onClick === 'function') {
675
- transaction.getReactMountReady().enqueue(
676
- trapClickOnNonInteractiveElement,
677
- this
678
- );
645
+ transaction
646
+ .getReactMountReady()
647
+ .enqueue(trapClickOnNonInteractiveElement, this);
648
}
649
break;
650
}
@@ -718,15 +687,24 @@ ReactDOMComponent.Mixin = {
687
Object.freeze(propValue);
688
}
689
}
721
- propValue = CSSPropertyOperations.createMarkupForStyles(propValue, this);
690
+ propValue = CSSPropertyOperations.createMarkupForStyles(
691
+ propValue,
692
+ this,
693
+ );
694
}
695
var markup = null;
696
if (this._tag != null && isCustomComponent(this._tag, props)) {
697
if (!RESERVED_PROPS.hasOwnProperty(propKey)) {
726
- markup = DOMPropertyOperations.createMarkupForCustomAttribute(propKey, propValue);
698
+ markup = DOMPropertyOperations.createMarkupForCustomAttribute(
699
+ propKey,
700
+ propValue,
701
+ );
702
}
703
} else {
729
- markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue);
704
+ markup = DOMPropertyOperations.createMarkupForProperty(
705
+ propKey,
706
+ propValue,
707
+ );
708
}
709
if (markup) {
710
ret += ' ' + markup;
@@ -766,8 +744,9 @@ ReactDOMComponent.Mixin = {
744
ret = innerHTML.__html;
745
}
746
} else {
769
- var contentToUse =
770
- CONTENT_TYPES[typeof props.children] ? props.children : null;
747
+ var contentToUse = CONTENT_TYPES[typeof props.children]
748
+ ? props.children
749
+ : null;
750
var childrenToUse = contentToUse != null ? null : props.children;
751
if (contentToUse != null) {
752
// TODO: Validate that text is allowed as a child of this node
@@ -779,7 +758,7 @@ ReactDOMComponent.Mixin = {
758
var mountImages = this.mountChildren(
759
childrenToUse,
760
transaction,
782
- context
761
+ context,
762
);
763
ret = mountImages.join('');
764
}
@@ -810,8 +789,9 @@ ReactDOMComponent.Mixin = {
789
DOMLazyTree.queueHTML(lazyTree, innerHTMLContent);
790
}
791
} else {
813
- var contentToUse =
814
- CONTENT_TYPES[typeof props.children] ? props.children : null;
792
+ var contentToUse = CONTENT_TYPES[typeof props.children]
793
+ ? props.children
794
+ : null;
795
var childrenToUse = contentToUse != null ? null : props.children;
796
// TODO: Validate that text is allowed as a child of this node
797
if (contentToUse != null) {
@@ -829,7 +809,7 @@ ReactDOMComponent.Mixin = {
809
var mountImages = this.mountChildren(
810
childrenToUse,
811
transaction,
832
- context
812
+ context,
813
);
814
for (var i = 0; i < mountImages.length; i++) {
815
DOMLazyTree.queueChild(lazyTree, mountImages[i]);
@@ -884,25 +864,26 @@ ReactDOMComponent.Mixin = {
864
nextProps = ReactDOMTextarea.getHostProps(this, nextProps);
865
break;
866
default:
887
- if (typeof lastProps.onClick !== 'function' &&
888
- typeof nextProps.onClick === 'function') {
889
- transaction.getReactMountReady().enqueue(
890
- trapClickOnNonInteractiveElement,
891
- this
892
- );
867
+ if (
868
+ typeof lastProps.onClick !== 'function' &&
869
+ typeof nextProps.onClick === 'function'
870
+ ) {
871
+ transaction
872
+ .getReactMountReady()
873
+ .enqueue(trapClickOnNonInteractiveElement, this);
874
}
875
break;
876
}
877
878
assertValidProps(this, nextProps);
879
var isCustomComponentTag = isCustomComponent(this._tag, nextProps);
899
- this._updateDOMProperties(lastProps, nextProps, transaction, isCustomComponentTag);
900
- this._updateDOMChildren(
880
+ this._updateDOMProperties(
881
lastProps,
882
nextProps,
883
transaction,
904
- context
884
+ isCustomComponentTag,
885
);
886
+ this._updateDOMChildren(lastProps, nextProps, transaction, context);
887
888
switch (this._tag) {
889
case 'input':
@@ -942,15 +923,17 @@ ReactDOMComponent.Mixin = {
923
lastProps,
924
nextProps,
925
transaction,
945
- isCustomComponentTag
926
+ isCustomComponentTag,
927
) {
928
var propKey;
929
var styleName;
930
var styleUpdates;
931
for (propKey in lastProps) {
951
- if (nextProps.hasOwnProperty(propKey) ||
952
- !lastProps.hasOwnProperty(propKey) ||
953
- lastProps[propKey] == null) {
932
+ if (
933
+ nextProps.hasOwnProperty(propKey) ||
934
+ !lastProps.hasOwnProperty(propKey) ||
935
+ lastProps[propKey] == null
936
+ ) {
937
continue;
938
}
939
if (propKey === STYLE) {
@@ -965,23 +948,23 @@ ReactDOMComponent.Mixin = {
948
// Do nothing for event names.
949
} else if (isCustomComponent(this._tag, lastProps)) {
950
if (!RESERVED_PROPS.hasOwnProperty(propKey)) {
968
- DOMPropertyOperations.deleteValueForAttribute(
969
- getNode(this),
970
- propKey
971
- );
951
+ DOMPropertyOperations.deleteValueForAttribute(getNode(this), propKey);
952
}
953
} else if (
974
- DOMProperty.properties[propKey] ||
975
- DOMProperty.isCustomAttribute(propKey)) {
954
+ DOMProperty.properties[propKey] ||
955
+ DOMProperty.isCustomAttribute(propKey)
956
+ ) {
957
DOMPropertyOperations.deleteValueForProperty(getNode(this), propKey);
958
}
959
}
960
for (propKey in nextProps) {
961
var nextProp = nextProps[propKey];
962
var lastProp = lastProps != null ? lastProps[propKey] : undefined;
982
- if (!nextProps.hasOwnProperty(propKey) ||
983
- nextProp === lastProp ||
984
- nextProp == null && lastProp == null) {
963
+ if (
964
+ !nextProps.hasOwnProperty(propKey) ||
965
+ nextProp === lastProp ||
966
+ (nextProp == null && lastProp == null)
967
+ ) {
968
continue;
969
}
970
if (propKey === STYLE) {
@@ -993,16 +976,20 @@ ReactDOMComponent.Mixin = {
976
if (lastProp) {
977
// Unset styles on `lastProp` but not on `nextProp`.
978
for (styleName in lastProp) {
996
- if (lastProp.hasOwnProperty(styleName) &&
997
- (!nextProp || !nextProp.hasOwnProperty(styleName))) {
979
+ if (
980
+ lastProp.hasOwnProperty(styleName) &&
981
+ (!nextProp || !nextProp.hasOwnProperty(styleName))
982
+ ) {
983
styleUpdates = styleUpdates || {};
984
styleUpdates[styleName] = '';
985
}
986
}
987
// Update styles that changed since `lastProp`.
988
for (styleName in nextProp) {
1004
- if (nextProp.hasOwnProperty(styleName) &&
1005
- lastProp[styleName] !== nextProp[styleName]) {
989
+ if (
990
+ nextProp.hasOwnProperty(styleName) &&
991
+ lastProp[styleName] !== nextProp[styleName]
992
+ ) {
993
styleUpdates = styleUpdates || {};
994
styleUpdates[styleName] = nextProp[styleName];
995
}
@@ -1020,12 +1007,13 @@ ReactDOMComponent.Mixin = {
1007
DOMPropertyOperations.setValueForAttribute(
1008
getNode(this),
1009
propKey,
1023
- nextProp
1010
+ nextProp,
1011
);
1012
}
1013
} else if (
1027
- DOMProperty.properties[propKey] ||
1028
- DOMProperty.isCustomAttribute(propKey)) {
1014
+ DOMProperty.properties[propKey] ||
1015
+ DOMProperty.isCustomAttribute(propKey)
1016
+ ) {
1017
var node = getNode(this);
1018
// If we're updating to null or undefined, we should remove the property
1019
// from the DOM node instead of inadvertently setting to a string. This
@@ -1048,7 +1036,7 @@ ReactDOMComponent.Mixin = {
1036
CSSPropertyOperations.setValueForStyles(
1037
getNode(this),
1038
styleUpdates,
1051
- this
1039
+ this,
1040
);
1041
}
1042
},
@@ -1063,16 +1051,16 @@ ReactDOMComponent.Mixin = {
1051
* @param {object} context
1052
*/
1053
_updateDOMChildren: function(lastProps, nextProps, transaction, context) {
1066
- var lastContent =
1067
- CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null;
1068
- var nextContent =
1069
- CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null;
1070
-
1071
- var lastHtml =
1072
- lastProps.dangerouslySetInnerHTML &&
1054
+ var lastContent = CONTENT_TYPES[typeof lastProps.children]
1055
+ ? lastProps.children
1056
+ : null;
1057
+ var nextContent = CONTENT_TYPES[typeof nextProps.children]
1058
+ ? nextProps.children
1059
+ : null;
1060
+
1061
+ var lastHtml = lastProps.dangerouslySetInnerHTML &&
1062
lastProps.dangerouslySetInnerHTML.__html;
1074
- var nextHtml =
1075
- nextProps.dangerouslySetInnerHTML &&
1063
+ var nextHtml = nextProps.dangerouslySetInnerHTML &&
1064
nextProps.dangerouslySetInnerHTML.__html;
1065
1066
// Note the use of `!=` which checks for null or undefined.
@@ -1159,11 +1147,11 @@ ReactDOMComponent.Mixin = {
1147
invariant(
1148
false,
1149
'<%s> tried to unmount. Because of cross-browser quirks it is ' +
1162
- 'impossible to unmount some top-level components (eg <html>, ' +
1163
- '<head>, and <body>) reliably and efficiently. To fix this, have a ' +
1164
- 'single top-level component that never unmounts render these ' +
1165
- 'elements.',
1166
- this._tag
1150
+ 'impossible to unmount some top-level components (eg <html>, ' +
1151
+ '<head>, and <body>) reliably and efficiently. To fix this, have a ' +
1152
+ 'single top-level component that never unmounts render these ' +
1153
+ 'elements.',
1154
+ this._tag,
1155
);
1156
break;
1157
}
@@ -1196,13 +1184,12 @@ ReactDOMComponent.Mixin = {
1184
getPublicInstance: function() {
1185
return getNode(this);
1186
},
1199
-
1187
};
1188
1189
Object.assign(
1190
ReactDOMComponent.prototype,
1191
ReactDOMComponent.Mixin,
1205
- ReactMultiChild
1192
+ ReactMultiChild,
1193
);
1194
1195
module.exports = ReactDOMComponent;
src/renderers/dom/stack/client/ReactDOMContainerInfo.js
+6
-5
@@ -19,16 +19,17 @@ function ReactDOMContainerInfo(topLevelWrapper, node) {
19
var info = {
20
_topLevelWrapper: topLevelWrapper,
21
_idCounter: 1,
22
- _ownerDocument: node ?
23
- node.nodeType === DOC_NODE_TYPE ? node : node.ownerDocument :
24
- null,
22
+ _ownerDocument: node
23
+ ? node.nodeType === DOC_NODE_TYPE ? node : node.ownerDocument
24
+ : null,
25
_node: node,
26
_tag: node ? node.nodeName.toLowerCase() : null,
27
_namespaceURI: node ? node.namespaceURI : null,
28
};
29
if (__DEV__) {
30
- info._ancestorInfo = node ?
31
- validateDOMNesting.updatedAncestorInfo(null, info._tag, null) : null;
30
+ info._ancestorInfo = node
31
+ ? validateDOMNesting.updatedAncestorInfo(null, info._tag, null)
32
+ : null;
33
}
34
return info;
35
}
src/renderers/dom/stack/client/ReactDOMEmptyComponent.js
+2
-4
@@ -14,7 +14,6 @@
14
var DOMLazyTree = require('DOMLazyTree');
15
var ReactDOMComponentTree = require('ReactDOMComponentTree');
16
17
-
17
var ReactDOMEmptyComponent = function(instantiate) {
18
// ReactCompositeComponent uses this:
19
this._currentElement = null;
@@ -29,7 +28,7 @@ Object.assign(ReactDOMEmptyComponent.prototype, {
28
transaction,
29
hostParent,
30
hostContainerInfo,
32
- context
31
+ context,
32
) {
33
var domID = hostContainerInfo._idCounter++;
34
this._domID = domID;
@@ -52,8 +51,7 @@ Object.assign(ReactDOMEmptyComponent.prototype, {
51
return '<!--' + nodeValue + '-->';
52
}
53
},
55
- receiveComponent: function() {
56
- },
54
+ receiveComponent: function() {},
55
getHostNode: function() {
56
return ReactDOMComponentTree.getNodeFromInstance(this);
57
},
src/renderers/dom/stack/client/ReactDOMIDOperations.js
-1
@@ -18,7 +18,6 @@ var ReactDOMComponentTree = require('ReactDOMComponentTree');
18
* Operations used to process updates to DOM nodes.
19
*/
20
var ReactDOMIDOperations = {
21
-
21
/**
22
* Updates a component's children by processing a series of updates.
23
*
src/renderers/dom/stack/client/ReactDOMStackInjection.js
+10
-17
@@ -12,8 +12,7 @@
12
'use strict';
13
14
var ReactComponentEnvironment = require('ReactComponentEnvironment');
15
-var ReactComponentBrowserEnvironment =
16
- require('ReactComponentBrowserEnvironment');
15
+var ReactComponentBrowserEnvironment = require('ReactComponentBrowserEnvironment');
16
var ReactDOMComponent = require('ReactDOMComponent');
17
var ReactDOMComponentTree = require('ReactDOMComponentTree');
18
var ReactDOMEmptyComponent = require('ReactDOMEmptyComponent');
@@ -40,31 +39,25 @@ function inject() {
39
alreadyInjected = true;
40
41
ReactGenericBatching.injection.injectStackBatchedUpdates(
43
- ReactUpdates.batchedUpdates
42
+ ReactUpdates.batchedUpdates,
43
);
44
46
- ReactHostComponent.injection.injectGenericComponentClass(
47
- ReactDOMComponent
48
- );
45
+ ReactHostComponent.injection.injectGenericComponentClass(ReactDOMComponent);
46
50
- ReactHostComponent.injection.injectTextComponentClass(
51
- ReactDOMTextComponent
52
- );
47
+ ReactHostComponent.injection.injectTextComponentClass(ReactDOMTextComponent);
48
49
ReactEmptyComponent.injection.injectEmptyComponentFactory(
50
function(instantiate) {
51
return new ReactDOMEmptyComponent(instantiate);
57
- }
52
+ },
53
);
54
60
- ReactUpdates.injection.injectReconcileTransaction(
61
- ReactReconcileTransaction
62
- );
63
- ReactUpdates.injection.injectBatchingStrategy(
64
- ReactDefaultBatchingStrategy
65
- );
55
+ ReactUpdates.injection.injectReconcileTransaction(ReactReconcileTransaction);
56
+ ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy);
57
67
- ReactComponentEnvironment.injection.injectEnvironment(ReactComponentBrowserEnvironment);
58
+ ReactComponentEnvironment.injection.injectEnvironment(
59
+ ReactComponentBrowserEnvironment,
60
+ );
61
62
findDOMNode._injectStack(function(inst) {
63
inst = getHostComponentFromComposite(inst);
src/renderers/dom/stack/client/ReactDOMTextComponent.js
+11
-10
@@ -50,7 +50,6 @@ var ReactDOMTextComponent = function(text) {
50
};
51
52
Object.assign(ReactDOMTextComponent.prototype, {
53
-
53
/**
54
* Creates the markup for this text node. This node is not intended to have
55
* any features besides containing text content.
@@ -63,7 +62,7 @@ Object.assign(ReactDOMTextComponent.prototype, {
62
transaction,
63
hostParent,
64
hostContainerInfo,
66
- context
65
+ context,
66
) {
67
if (__DEV__) {
68
var parentInfo;
@@ -93,7 +92,7 @@ Object.assign(ReactDOMTextComponent.prototype, {
92
if (this._stringText) {
93
DOMLazyTree.queueChild(
94
lazyTree,
96
- DOMLazyTree(ownerDocument.createTextNode(this._stringText))
95
+ DOMLazyTree(ownerDocument.createTextNode(this._stringText)),
96
);
97
}
98
DOMLazyTree.queueChild(lazyTree, DOMLazyTree(closingComment));
@@ -110,10 +109,13 @@ Object.assign(ReactDOMTextComponent.prototype, {
109
return escapedText;
110
}
111
113
- return (
114
- '<!--' + openingValue + '-->' + escapedText +
115
- '<!--' + closingValue + '-->'
116
- );
112
+ return '<!--' +
113
+ openingValue +
114
+ '-->' +
115
+ escapedText +
116
+ '<!--' +
117
+ closingValue +
118
+ '-->';
119
}
120
},
121
@@ -137,7 +139,7 @@ Object.assign(ReactDOMTextComponent.prototype, {
139
DOMChildrenOperations.replaceDelimitedText(
140
commentNodes[0],
141
commentNodes[1],
140
- nextStringText
142
+ nextStringText,
143
);
144
}
145
}
@@ -155,7 +157,7 @@ Object.assign(ReactDOMTextComponent.prototype, {
157
invariant(
158
node != null,
159
'Missing closing comment for text component %s',
158
- this._domID
160
+ this._domID,
161
);
162
if (node.nodeType === 8 && node.nodeValue === ' /react-text ') {
163
this._closingComment = node;
@@ -174,7 +176,6 @@ Object.assign(ReactDOMTextComponent.prototype, {
176
this._commentNodes = null;
177
ReactDOMComponentTree.uncacheNode(this);
178
},
177
-
179
});
180
181
module.exports = ReactDOMTextComponent;
src/renderers/dom/stack/client/ReactMount.js
+155
-134
@@ -81,7 +81,7 @@ function internalGetID(node) {
81
// If node is something like a window, document, or text node, none of
82
// which support attributes or a .getAttribute method, gracefully return
83
// the empty string, as if the attribute were missing.
84
- return node.getAttribute && node.getAttribute(ATTR_NAME) || '';
84
+ return (node.getAttribute && node.getAttribute(ATTR_NAME)) || '';
85
}
86
87
/**
@@ -97,16 +97,14 @@ function mountComponentIntoNode(
97
container,
98
transaction,
99
shouldReuseMarkup,
100
- context
100
+ context,
101
) {
102
var markerName;
103
if (ReactFeatureFlags.logTopLevelRenders) {
104
var wrappedElement = wrapperInstance._currentElement.props.child;
105
var type = wrappedElement.type;
106
- markerName = 'React mount: ' + (
107
- typeof type === 'string' ? type :
108
- type.displayName || type.name
109
- );
106
+ markerName = 'React mount: ' +
107
+ (typeof type === 'string' ? type : type.displayName || type.name);
108
console.time(markerName);
109
}
110
@@ -116,7 +114,7 @@ function mountComponentIntoNode(
114
null,
115
ReactDOMContainerInfo(wrapperInstance, container),
116
context,
119
- 0 /* parentDebugID */
117
+ 0 /* parentDebugID */,
118
);
119
120
if (markerName) {
@@ -129,7 +127,7 @@ function mountComponentIntoNode(
127
container,
128
wrapperInstance,
129
shouldReuseMarkup,
132
- transaction
130
+ transaction,
131
);
132
}
133
@@ -144,11 +142,11 @@ function batchedMountComponentIntoNode(
142
componentInstance,
143
container,
144
shouldReuseMarkup,
147
- context
145
+ context,
146
) {
147
var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(
148
/* useCreateElement */
151
- !shouldReuseMarkup && ReactDOMFeatureFlags.useCreateElement
149
+ !shouldReuseMarkup && ReactDOMFeatureFlags.useCreateElement,
150
);
151
transaction.perform(
152
mountComponentIntoNode,
@@ -157,7 +155,7 @@ function batchedMountComponentIntoNode(
155
container,
156
transaction,
157
shouldReuseMarkup,
160
- context
158
+ context,
159
);
160
ReactUpdates.ReactReconcileTransaction.release(transaction);
161
}
@@ -178,7 +176,7 @@ function unmountComponentFromNode(instance, container) {
176
ReactReconciler.unmountComponent(
177
instance,
178
false /* safely */,
181
- false /* skipLifecycle */
179
+ false /* skipLifecycle */,
180
);
181
if (__DEV__) {
182
ReactInstrumentation.debugTool.onEndFlush();
@@ -222,7 +220,9 @@ function hasNonRootReactChild(container) {
220
*/
221
function nodeIsRenderedByOtherInstance(container) {
222
var rootEl = getReactRootElementInContainer(container);
225
- return !!(rootEl && isReactNode(rootEl) && !ReactDOMComponentTree.getInstanceFromNode(rootEl));
223
+ return !!(rootEl &&
224
+ isReactNode(rootEl) &&
225
+ !ReactDOMComponentTree.getInstanceFromNode(rootEl));
226
}
227
228
/**
@@ -233,11 +233,10 @@ function nodeIsRenderedByOtherInstance(container) {
233
* @internal
234
*/
235
function isValidContainer(node) {
236
- return !!(node && (
237
- node.nodeType === ELEMENT_NODE_TYPE ||
238
- node.nodeType === DOC_NODE_TYPE ||
239
- node.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE
240
- ));
236
+ return !!(node &&
237
+ (node.nodeType === ELEMENT_NODE_TYPE ||
238
+ node.nodeType === DOC_NODE_TYPE ||
239
+ node.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE));
240
}
241
242
/**
@@ -248,17 +247,17 @@ function isValidContainer(node) {
247
* @internal
248
*/
249
function isReactNode(node) {
251
- return isValidContainer(node) && (node.hasAttribute(ROOT_ATTR_NAME) || node.hasAttribute(ATTR_NAME));
250
+ return isValidContainer(node) &&
251
+ (node.hasAttribute(ROOT_ATTR_NAME) || node.hasAttribute(ATTR_NAME));
252
}
253
254
function getHostRootInstanceInContainer(container) {
255
var rootEl = getReactRootElementInContainer(container);
256
- var prevHostInstance =
257
- rootEl && ReactDOMComponentTree.getInstanceFromNode(rootEl);
258
- return (
259
- prevHostInstance && !prevHostInstance._hostParent ?
260
- prevHostInstance : null
261
- );
256
+ var prevHostInstance = rootEl &&
257
+ ReactDOMComponentTree.getInstanceFromNode(rootEl);
258
+ return prevHostInstance && !prevHostInstance._hostParent
259
+ ? prevHostInstance
260
+ : null;
261
}
262
263
function getTopLevelWrapperInContainer(container) {
@@ -303,7 +302,6 @@ TopLevelWrapper.isReactTopLevelWrapper = true;
302
* Inside of `container`, the first element rendered is the "reactRoot".
303
*/
304
var ReactMount = {
306
-
305
TopLevelWrapper: TopLevelWrapper,
306
307
/**
@@ -331,13 +329,18 @@ var ReactMount = {
329
* @param {?function} callback function triggered on completion
330
*/
331
_updateRootComponent: function(
334
- prevComponent,
335
- nextElement,
336
- nextContext,
337
- container,
338
- callback) {
332
+ prevComponent,
333
+ nextElement,
334
+ nextContext,
335
+ container,
336
+ callback,
337
+ ) {
338
ReactMount.scrollMonitor(container, function() {
340
- ReactUpdateQueue.enqueueElementInternal(prevComponent, nextElement, nextContext);
339
+ ReactUpdateQueue.enqueueElementInternal(
340
+ prevComponent,
341
+ nextElement,
342
+ nextContext,
343
+ );
344
if (callback) {
345
ReactUpdateQueue.enqueueCallbackInternal(prevComponent, callback);
346
}
@@ -359,7 +362,7 @@ var ReactMount = {
362
container,
363
shouldReuseMarkup,
364
context,
362
- callback
365
+ callback,
366
) {
367
// Various parts of our code (such as ReactCompositeComponent's
368
// _renderValidatedComponent) assume that calls to render aren't nested;
@@ -367,26 +370,30 @@ var ReactMount = {
370
warning(
371
ReactCurrentOwner.current == null,
372
'_renderNewRootComponent(): Render methods should be a pure function ' +
370
- 'of props and state; triggering nested component updates from ' +
371
- 'render is not allowed. If necessary, trigger nested updates in ' +
372
- 'componentDidUpdate.\n\nCheck the render method of %s.',
373
- ReactCurrentOwner.current && ReactCurrentOwner.current.getName() ||
374
- 'ReactCompositeComponent'
373
+ 'of props and state; triggering nested component updates from ' +
374
+ 'render is not allowed. If necessary, trigger nested updates in ' +
375
+ 'componentDidUpdate.\n\nCheck the render method of %s.',
376
+ (ReactCurrentOwner.current && ReactCurrentOwner.current.getName()) ||
377
+ 'ReactCompositeComponent',
378
);
379
380
invariant(
381
isValidContainer(container),
379
- '_registerComponent(...): Target container is not a DOM element.'
382
+ '_registerComponent(...): Target container is not a DOM element.',
383
);
384
385
ReactBrowserEventEmitter.ensureScrollValueMonitoring();
386
var componentInstance = instantiateReactComponent(nextElement, false);
387
388
if (callback) {
386
- componentInstance._pendingCallbacks = [function() {
387
- validateCallback(callback);
388
- callback.call(componentInstance._renderedComponent.getPublicInstance());
389
- }];
389
+ componentInstance._pendingCallbacks = [
390
+ function() {
391
+ validateCallback(callback);
392
+ callback.call(
393
+ componentInstance._renderedComponent.getPublicInstance(),
394
+ );
395
+ },
396
+ ];
397
}
398
399
// The initial render is synchronous but any updates that happen during
@@ -398,7 +405,7 @@ var ReactMount = {
405
componentInstance,
406
container,
407
shouldReuseMarkup,
401
- context
408
+ context,
409
);
410
411
var wrapperID = componentInstance._instance.rootID;
@@ -420,27 +427,37 @@ var ReactMount = {
427
* @param {?function} callback function triggered on completion
428
* @return {ReactComponent} Component instance rendered in `container`.
429
*/
423
- renderSubtreeIntoContainer: function(parentComponent, nextElement, container, callback) {
430
+ renderSubtreeIntoContainer: function(
431
+ parentComponent,
432
+ nextElement,
433
+ container,
434
+ callback,
435
+ ) {
436
invariant(
437
parentComponent != null && ReactInstanceMap.has(parentComponent),
426
- 'parentComponent must be a valid React Component'
438
+ 'parentComponent must be a valid React Component',
439
);
440
return ReactMount._renderSubtreeIntoContainer(
441
parentComponent,
442
nextElement,
443
container,
432
- callback
444
+ callback,
445
);
446
},
447
436
- _renderSubtreeIntoContainer: function(parentComponent, nextElement, container, callback) {
448
+ _renderSubtreeIntoContainer: function(
449
+ parentComponent,
450
+ nextElement,
451
+ container,
452
+ callback,
453
+ ) {
454
callback = callback === undefined ? null : callback;
455
if (__DEV__) {
456
warning(
457
callback === null || typeof callback === 'function',
458
'render(...): Expected the last optional `callback` argument to be a ' +
442
- 'function. Instead received: %s.',
443
- '' + callback
459
+ 'function. Instead received: %s.',
460
+ '' + callback,
461
);
462
}
463
if (!React.isValidElement(nextElement)) {
@@ -448,46 +465,45 @@ var ReactMount = {
465
invariant(
466
false,
467
'ReactDOM.render(): Invalid component element. Instead of ' +
451
- 'passing a string like \'div\', pass ' +
452
- 'React.createElement(\'div\') or <div />.'
468
+ "passing a string like 'div', pass " +
469
+ "React.createElement('div') or <div />.",
470
);
471
} else if (typeof nextElement === 'function') {
472
invariant(
473
false,
474
'ReactDOM.render(): Invalid component element. Instead of ' +
458
- 'passing a class like Foo, pass React.createElement(Foo) ' +
459
- 'or <Foo />.'
475
+ 'passing a class like Foo, pass React.createElement(Foo) ' +
476
+ 'or <Foo />.',
477
);
461
- } else if (nextElement != null && typeof nextElement.props !== 'undefined') {
478
+ } else if (
479
+ nextElement != null && typeof nextElement.props !== 'undefined'
480
+ ) {
481
// Check if it quacks like an element
482
invariant(
483
false,
484
'ReactDOM.render(): Invalid component element. This may be ' +
466
- 'caused by unintentionally loading two independent copies ' +
467
- 'of React.'
485
+ 'caused by unintentionally loading two independent copies ' +
486
+ 'of React.',
487
);
488
} else {
470
- invariant(
471
- false,
472
- 'ReactDOM.render(): Invalid component element.'
473
- );
489
+ invariant(false, 'ReactDOM.render(): Invalid component element.');
490
}
491
}
492
493
warning(
478
- !container || !container.tagName ||
479
- container.tagName.toUpperCase() !== 'BODY',
494
+ !container ||
495
+ !container.tagName ||
496
+ container.tagName.toUpperCase() !== 'BODY',
497
'render(): Rendering components directly into document.body is ' +
481
- 'discouraged, since its children are often manipulated by third-party ' +
482
- 'scripts and browser extensions. This may lead to subtle ' +
483
- 'reconciliation issues. Try rendering into a container element created ' +
484
- 'for your app.'
498
+ 'discouraged, since its children are often manipulated by third-party ' +
499
+ 'scripts and browser extensions. This may lead to subtle ' +
500
+ 'reconciliation issues. Try rendering into a container element created ' +
501
+ 'for your app.',
502
);
503
487
- var nextWrappedElement = React.createElement(
488
- TopLevelWrapper,
489
- { child: nextElement }
490
- );
504
+ var nextWrappedElement = React.createElement(TopLevelWrapper, {
505
+ child: nextElement,
506
+ });
507
508
var nextContext = getContextForSubtree(parentComponent);
509
var prevComponent = getTopLevelWrapperInContainer(container);
@@ -497,16 +513,17 @@ var ReactMount = {
513
var prevElement = prevWrappedElement.props.child;
514
if (shouldUpdateReactComponent(prevElement, nextElement)) {
515
var publicInst = prevComponent._renderedComponent.getPublicInstance();
500
- var updatedCallback = callback && function() {
501
- validateCallback(callback);
502
- callback.call(publicInst);
503
- };
516
+ var updatedCallback = callback &&
517
+ function() {
518
+ validateCallback(callback);
519
+ callback.call(publicInst);
520
+ };
521
ReactMount._updateRootComponent(
522
prevComponent,
523
nextWrappedElement,
524
nextContext,
525
container,
509
- updatedCallback
526
+ updatedCallback,
527
);
528
return publicInst;
529
} else {
@@ -515,17 +532,17 @@ var ReactMount = {
532
}
533
534
var reactRootElement = getReactRootElementInContainer(container);
518
- var containerHasReactMarkup =
519
- reactRootElement && !!internalGetID(reactRootElement);
535
+ var containerHasReactMarkup = reactRootElement &&
536
+ !!internalGetID(reactRootElement);
537
var containerHasNonRootReactChild = hasNonRootReactChild(container);
538
539
if (__DEV__) {
540
warning(
541
!containerHasNonRootReactChild,
542
'render(...): Replacing React-rendered children with a new root ' +
526
- 'component. If you intended to update the children of this node, ' +
527
- 'you should instead have the existing children update their state ' +
528
- 'and render the new components instead of calling ReactDOM.render.'
543
+ 'component. If you intended to update the children of this node, ' +
544
+ 'you should instead have the existing children update their state ' +
545
+ 'and render the new components instead of calling ReactDOM.render.',
546
);
547
548
if (!containerHasReactMarkup || reactRootElement.nextSibling) {
@@ -535,8 +552,8 @@ var ReactMount = {
552
warning(
553
false,
554
'render(): Target node has markup rendered by React, but there ' +
538
- 'are unrelated nodes as well. This is most commonly caused by ' +
539
- 'white-space inserted around server-rendered markup.'
555
+ 'are unrelated nodes as well. This is most commonly caused by ' +
556
+ 'white-space inserted around server-rendered markup.',
557
);
558
break;
559
}
@@ -545,8 +562,7 @@ var ReactMount = {
562
}
563
}
564
548
- var shouldReuseMarkup =
549
- containerHasReactMarkup &&
565
+ var shouldReuseMarkup = containerHasReactMarkup &&
566
!prevComponent &&
567
!containerHasNonRootReactChild;
568
var component = ReactMount._renderNewRootComponent(
@@ -554,12 +570,11 @@ var ReactMount = {
570
container,
571
shouldReuseMarkup,
572
nextContext,
557
- callback
573
+ callback,
574
)._renderedComponent.getPublicInstance();
575
return component;
576
},
577
562
-
578
/**
579
* Renders a React component into the DOM in the supplied `container`.
580
* See https://facebook.github.io/react/docs/react-dom.html#render
@@ -574,7 +589,12 @@ var ReactMount = {
589
* @return {ReactComponent} Component instance rendered in `container`.
590
*/
591
render: function(nextElement, container, callback) {
577
- return ReactMount._renderSubtreeIntoContainer(null, nextElement, container, callback);
592
+ return ReactMount._renderSubtreeIntoContainer(
593
+ null,
594
+ nextElement,
595
+ container,
596
+ callback,
597
+ );
598
},
599
600
/**
@@ -593,23 +613,23 @@ var ReactMount = {
613
warning(
614
ReactCurrentOwner.current == null,
615
'unmountComponentAtNode(): Render methods should be a pure function ' +
596
- 'of props and state; triggering nested component updates from render ' +
597
- 'is not allowed. If necessary, trigger nested updates in ' +
598
- 'componentDidUpdate.\n\nCheck the render method of %s.',
599
- ReactCurrentOwner.current && ReactCurrentOwner.current.getName() ||
600
- 'ReactCompositeComponent'
616
+ 'of props and state; triggering nested component updates from render ' +
617
+ 'is not allowed. If necessary, trigger nested updates in ' +
618
+ 'componentDidUpdate.\n\nCheck the render method of %s.',
619
+ (ReactCurrentOwner.current && ReactCurrentOwner.current.getName()) ||
620
+ 'ReactCompositeComponent',
621
);
622
623
invariant(
624
isValidContainer(container),
605
- 'unmountComponentAtNode(...): Target container is not a DOM element.'
625
+ 'unmountComponentAtNode(...): Target container is not a DOM element.',
626
);
627
628
if (__DEV__) {
629
warning(
630
!nodeIsRenderedByOtherInstance(container),
611
- 'unmountComponentAtNode(): The node you\'re attempting to unmount ' +
612
- 'was rendered by another copy of React.'
631
+ "unmountComponentAtNode(): The node you're attempting to unmount " +
632
+ 'was rendered by another copy of React.',
633
);
634
}
635
@@ -620,21 +640,19 @@ var ReactMount = {
640
var containerHasNonRootReactChild = hasNonRootReactChild(container);
641
642
// Check if the container itself is a React root node.
623
- var isContainerReactRoot =
624
- container.nodeType === 1 && container.hasAttribute(ROOT_ATTR_NAME);
643
+ var isContainerReactRoot = container.nodeType === 1 &&
644
+ container.hasAttribute(ROOT_ATTR_NAME);
645
646
if (__DEV__) {
647
warning(
648
!containerHasNonRootReactChild,
629
- 'unmountComponentAtNode(): The node you\'re attempting to unmount ' +
630
- 'was rendered by React and is not a top-level container. %s',
631
- (
632
- isContainerReactRoot ?
633
- 'You may have accidentally passed in a React root node instead ' +
634
- 'of its container.' :
635
- 'Instead, have the parent component update its state and ' +
636
- 'rerender in order to remove this component.'
637
- )
649
+ "unmountComponentAtNode(): The node you're attempting to unmount " +
650
+ 'was rendered by React and is not a top-level container. %s',
651
+ isContainerReactRoot
652
+ ? 'You may have accidentally passed in a React root node instead ' +
653
+ 'of its container.'
654
+ : 'Instead, have the parent component update its state and ' +
655
+ 'rerender in order to remove this component.',
656
);
657
}
658
@@ -644,7 +662,7 @@ var ReactMount = {
662
ReactUpdates.batchedUpdates(
663
unmountComponentFromNode,
664
prevComponent,
647
- container
665
+ container,
666
);
667
return true;
668
},
@@ -654,11 +672,11 @@ var ReactMount = {
672
container,
673
instance,
674
shouldReuseMarkup,
657
- transaction
675
+ transaction,
676
) {
677
invariant(
678
isValidContainer(container),
661
- 'mountComponentIntoNode(...): Target container is not valid.'
679
+ 'mountComponentIntoNode(...): Target container is not valid.',
680
);
681
682
if (shouldReuseMarkup) {
@@ -668,14 +686,14 @@ var ReactMount = {
686
return;
687
} else {
688
var checksum = rootElement.getAttribute(
671
- ReactMarkupChecksum.CHECKSUM_ATTR_NAME
689
+ ReactMarkupChecksum.CHECKSUM_ATTR_NAME,
690
);
691
rootElement.removeAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME);
692
693
var rootMarkup = rootElement.outerHTML;
694
rootElement.setAttribute(
695
ReactMarkupChecksum.CHECKSUM_ATTR_NAME,
678
- checksum
696
+ checksum,
697
);
698
699
var normalizedMarkup = markup;
@@ -701,33 +719,34 @@ var ReactMount = {
719
var diffIndex = firstDifferenceIndex(normalizedMarkup, rootMarkup);
720
var difference = ' (client) ' +
721
normalizedMarkup.substring(diffIndex - 20, diffIndex + 20) +
704
- '\n (server) ' + rootMarkup.substring(diffIndex - 20, diffIndex + 20);
722
+ '\n (server) ' +
723
+ rootMarkup.substring(diffIndex - 20, diffIndex + 20);
724
725
invariant(
726
container.nodeType !== DOC_NODE_TYPE,
708
- 'You\'re trying to render a component to the document using ' +
709
- 'server rendering but the checksum was invalid. This usually ' +
710
- 'means you rendered a different component type or props on ' +
711
- 'the client from the one on the server, or your render() ' +
712
- 'methods are impure. React cannot handle this case due to ' +
713
- 'cross-browser quirks by rendering at the document root. You ' +
714
- 'should look for environment dependent code in your components ' +
715
- 'and ensure the props are the same client and server side:\n%s',
716
- difference
727
+ "You're trying to render a component to the document using " +
728
+ 'server rendering but the checksum was invalid. This usually ' +
729
+ 'means you rendered a different component type or props on ' +
730
+ 'the client from the one on the server, or your render() ' +
731
+ 'methods are impure. React cannot handle this case due to ' +
732
+ 'cross-browser quirks by rendering at the document root. You ' +
733
+ 'should look for environment dependent code in your components ' +
734
+ 'and ensure the props are the same client and server side:\n%s',
735
+ difference,
736
);
737
738
if (__DEV__) {
739
warning(
740
false,
741
'React attempted to reuse markup in a container but the ' +
723
- 'checksum was invalid. This generally means that you are ' +
724
- 'using server rendering and the markup generated on the ' +
725
- 'server was not what the client was expecting. React injected ' +
726
- 'new markup to compensate which works but you have lost many ' +
727
- 'of the benefits of server rendering. Instead, figure out ' +
728
- 'why the markup being generated is different on the client ' +
729
- 'or server:\n%s',
730
- difference
742
+ 'checksum was invalid. This generally means that you are ' +
743
+ 'using server rendering and the markup generated on the ' +
744
+ 'server was not what the client was expecting. React injected ' +
745
+ 'new markup to compensate which works but you have lost many ' +
746
+ 'of the benefits of server rendering. Instead, figure out ' +
747
+ 'why the markup being generated is different on the client ' +
748
+ 'or server:\n%s',
749
+ difference,
750
);
751
}
752
}
@@ -735,10 +754,10 @@ var ReactMount = {
754
755
invariant(
756
container.nodeType !== DOC_NODE_TYPE,
738
- 'You\'re trying to render a component to the document but ' +
739
- 'you didn\'t use server rendering. We can\'t do this ' +
757
+ "You're trying to render a component to the document but " +
758
+ "you didn't use server rendering. We can't do this " +
759
'without using server rendering due to cross-browser quirks. ' +
741
- 'See ReactDOMServer.renderToString() for server rendering.'
760
+ 'See ReactDOMServer.renderToString() for server rendering.',
761
);
762
763
if (transaction.useCreateElement) {
@@ -752,7 +771,9 @@ var ReactMount = {
771
}
772
773
if (__DEV__) {
755
- var hostNode = ReactDOMComponentTree.getInstanceFromNode(container.firstChild);
774
+ var hostNode = ReactDOMComponentTree.getInstanceFromNode(
775
+ container.firstChild,
776
+ );
777
if (hostNode._debugID !== 0) {
778
ReactInstrumentation.debugTool.onHostOperation({
779
instanceID: hostNode._debugID,
src/renderers/dom/stack/client/ReactReconcileTransaction.js
-2
@@ -19,7 +19,6 @@ var ReactInstrumentation = require('ReactInstrumentation');
19
var Transaction = require('Transaction');
20
var ReactUpdateQueue = require('ReactUpdateQueue');
21
22
-
22
/**
23
* Ensures that, when possible, the selection range (currently selected text
24
* input) is not disturbed by performing the transaction.
@@ -174,7 +173,6 @@ var Mixin = {
173
},
174
};
175
177
-
176
Object.assign(ReactReconcileTransaction.prototype, Transaction, Mixin);
177
178
PooledClass.addPoolingTo(ReactReconcileTransaction);
src/renderers/dom/stack/client/wrappers/ReactDOMInput.js
+64
-51
@@ -49,23 +49,27 @@ var ReactDOMInput = {
49
var value = props.value;
50
var checked = props.checked;
51
52
- var hostProps = Object.assign({
53
- // Make sure we set .type before any other properties (setting .value
54
- // before .type means .value is lost in IE11 and below)
55
- type: undefined,
56
- // Make sure we set .step before .value (setting .value before .step
57
- // means .value is rounded on mount, based upon step precision)
58
- step: undefined,
59
- // Make sure we set .min & .max before .value (to ensure proper order
60
- // in corner cases such as min or max deriving from value, e.g. Issue #7170)
61
- min: undefined,
62
- max: undefined,
63
- }, props, {
64
- defaultChecked: undefined,
65
- defaultValue: undefined,
66
- value: value != null ? value : inst._wrapperState.initialValue,
67
- checked: checked != null ? checked : inst._wrapperState.initialChecked,
68
- });
52
+ var hostProps = Object.assign(
53
+ {
54
+ // Make sure we set .type before any other properties (setting .value
55
+ // before .type means .value is lost in IE11 and below)
56
+ type: undefined,
57
+ // Make sure we set .step before .value (setting .value before .step
58
+ // means .value is rounded on mount, based upon step precision)
59
+ step: undefined,
60
+ // Make sure we set .min & .max before .value (to ensure proper order
61
+ // in corner cases such as min or max deriving from value, e.g. Issue #7170)
62
+ min: undefined,
63
+ max: undefined,
64
+ },
65
+ props,
66
+ {
67
+ defaultChecked: undefined,
68
+ defaultValue: undefined,
69
+ value: value != null ? value : inst._wrapperState.initialValue,
70
+ checked: checked != null ? checked : inst._wrapperState.initialChecked,
71
+ },
72
+ );
73
74
return hostProps;
75
},
@@ -76,7 +80,7 @@ var ReactDOMInput = {
80
ReactControlledValuePropTypes.checkPropTypes(
81
'input',
82
props,
79
- owner ? owner.getName() : null
83
+ owner ? owner.getName() : null,
84
);
85
86
if (
@@ -87,13 +91,13 @@ var ReactDOMInput = {
91
warning(
92
false,
93
'%s contains an input of type %s with both checked and defaultChecked props. ' +
90
- 'Input elements must be either controlled or uncontrolled ' +
91
- '(specify either the checked prop, or the defaultChecked prop, but not ' +
92
- 'both). Decide between using a controlled or uncontrolled input ' +
93
- 'element and remove one of these props. More info: ' +
94
- 'https://fb.me/react-controlled-components',
95
- owner && owner.getName() || 'A component',
96
- props.type
94
+ 'Input elements must be either controlled or uncontrolled ' +
95
+ '(specify either the checked prop, or the defaultChecked prop, but not ' +
96
+ 'both). Decide between using a controlled or uncontrolled input ' +
97
+ 'element and remove one of these props. More info: ' +
98
+ 'https://fb.me/react-controlled-components',
99
+ (owner && owner.getName()) || 'A component',
100
+ props.type,
101
);
102
didWarnCheckedDefaultChecked = true;
103
}
@@ -105,13 +109,13 @@ var ReactDOMInput = {
109
warning(
110
false,
111
'%s contains an input of type %s with both value and defaultValue props. ' +
108
- 'Input elements must be either controlled or uncontrolled ' +
109
- '(specify either the value prop, or the defaultValue prop, but not ' +
110
- 'both). Decide between using a controlled or uncontrolled input ' +
111
- 'element and remove one of these props. More info: ' +
112
- 'https://fb.me/react-controlled-components',
113
- owner && owner.getName() || 'A component',
114
- props.type
112
+ 'Input elements must be either controlled or uncontrolled ' +
113
+ '(specify either the value prop, or the defaultValue prop, but not ' +
114
+ 'both). Decide between using a controlled or uncontrolled input ' +
115
+ 'element and remove one of these props. More info: ' +
116
+ 'https://fb.me/react-controlled-components',
117
+ (owner && owner.getName()) || 'A component',
118
+ props.type,
119
);
120
didWarnValueDefaultValue = true;
121
}
@@ -119,7 +123,9 @@ var ReactDOMInput = {
123
124
var defaultValue = props.defaultValue;
125
inst._wrapperState = {
122
- initialChecked: props.checked != null ? props.checked : props.defaultChecked,
126
+ initialChecked: props.checked != null
127
+ ? props.checked
128
+ : props.defaultChecked,
129
initialValue: props.value != null ? props.value : defaultValue,
130
listeners: null,
131
};
@@ -136,27 +142,35 @@ var ReactDOMInput = {
142
var controlled = isControlled(props);
143
var owner = inst._currentElement._owner;
144
139
- if (!inst._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) {
145
+ if (
146
+ !inst._wrapperState.controlled &&
147
+ controlled &&
148
+ !didWarnUncontrolledToControlled
149
+ ) {
150
warning(
151
false,
152
'%s is changing an uncontrolled input of type %s to be controlled. ' +
143
- 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
144
- 'Decide between using a controlled or uncontrolled input ' +
145
- 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components',
146
- owner && owner.getName() || 'A component',
147
- props.type
153
+ 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
154
+ 'Decide between using a controlled or uncontrolled input ' +
155
+ 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components',
156
+ (owner && owner.getName()) || 'A component',
157
+ props.type,
158
);
159
didWarnUncontrolledToControlled = true;
160
}
151
- if (inst._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) {
161
+ if (
162
+ inst._wrapperState.controlled &&
163
+ !controlled &&
164
+ !didWarnControlledToUncontrolled
165
+ ) {
166
warning(
167
false,
168
'%s is changing a controlled input of type %s to be uncontrolled. ' +
155
- 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
156
- 'Decide between using a controlled or uncontrolled input ' +
157
- 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components',
158
- owner && owner.getName() || 'A component',
159
- props.type
169
+ 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
170
+ 'Decide between using a controlled or uncontrolled input ' +
171
+ 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components',
172
+ (owner && owner.getName()) || 'A component',
173
+ props.type,
174
);
175
didWarnControlledToUncontrolled = true;
176
}
@@ -167,14 +181,13 @@ var ReactDOMInput = {
181
DOMPropertyOperations.setValueForProperty(
182
ReactDOMComponentTree.getNodeFromInstance(inst),
183
'checked',
170
- checked || false
184
+ checked || false,
185
);
186
}
187
188
var node = ReactDOMComponentTree.getNodeFromInstance(inst);
189
var value = props.value;
190
if (value != null) {
177
-
191
// Cast `value` to a string to ensure the value is set correctly. While
192
// browsers typically do this as necessary, jsdom doesn't.
193
var newValue = '' + value;
@@ -281,12 +294,12 @@ function updateNamedCousins(thisInstance, props) {
294
// document. Let's just use the local `querySelectorAll` to ensure we don't
295
// miss anything.
296
var group = queryRoot.querySelectorAll(
284
- 'input[name=' + JSON.stringify('' + name) + '][type="radio"]');
297
+ 'input[name=' + JSON.stringify('' + name) + '][type="radio"]',
298
+ );
299
300
for (var i = 0; i < group.length; i++) {
301
var otherNode = group[i];
288
- if (otherNode === rootNode ||
289
- otherNode.form !== rootNode.form) {
302
+ if (otherNode === rootNode || otherNode.form !== rootNode.form) {
303
continue;
304
}
305
// This will throw if radio buttons rendered by different copies of React
@@ -297,7 +310,7 @@ function updateNamedCousins(thisInstance, props) {
310
invariant(
311
otherInstance,
312
'ReactDOMInput: Mixing React and non-React radio inputs with the ' +
300
- 'same `name` is not supported.'
313
+ 'same `name` is not supported.',
314
);
315
// If this is a controlled radio button group, forcing the input that
316
// was previously checked to update will cause it to be come re-checked
src/renderers/dom/stack/client/wrappers/ReactDOMOption.js
+7
-5
@@ -33,7 +33,7 @@ function flattenChildren(children) {
33
didWarnInvalidOptionChildren = true;
34
warning(
35
false,
36
- 'Only strings and numbers are supported as <option> children.'
36
+ 'Only strings and numbers are supported as <option> children.',
37
);
38
}
39
});
@@ -51,7 +51,7 @@ var ReactDOMOption = {
51
warning(
52
props.selected == null,
53
'Use the `defaultValue` or `value` props on <select> instead of ' +
54
- 'setting `selected` on <option>.'
54
+ 'setting `selected` on <option>.',
55
);
56
}
57
@@ -89,7 +89,7 @@ var ReactDOMOption = {
89
}
90
}
91
} else {
92
- selected = ('' + selectValue === value);
92
+ selected = '' + selectValue === value;
93
}
94
}
95
@@ -106,7 +106,10 @@ var ReactDOMOption = {
106
},
107
108
getHostProps: function(inst, props) {
109
- var hostProps = Object.assign({selected: undefined, children: undefined}, props);
109
+ var hostProps = Object.assign(
110
+ {selected: undefined, children: undefined},
111
+ props,
112
+ );
113
114
// Read state only from initial mount because <select> updates value
115
// manually; we need the initial state only for server rendering
@@ -122,7 +125,6 @@ var ReactDOMOption = {
125
126
return hostProps;
127
},
125
-
128
};
129
130
module.exports = ReactDOMOption;
src/renderers/dom/stack/client/wrappers/ReactDOMSelect.js
+9
-9
@@ -39,7 +39,7 @@ function checkSelectPropTypes(inst, props) {
39
ReactControlledValuePropTypes.checkPropTypes(
40
'select',
41
props,
42
- owner ? owner.getName() : null
42
+ owner ? owner.getName() : null,
43
);
44
45
for (var i = 0; i < valuePropNames.length; i++) {
@@ -52,17 +52,17 @@ function checkSelectPropTypes(inst, props) {
52
warning(
53
false,
54
'The `%s` prop supplied to <select> must be an array if ' +
55
- '`multiple` is true.%s',
55
+ '`multiple` is true.%s',
56
propName,
57
- getDeclarationErrorAddendum(owner)
57
+ getDeclarationErrorAddendum(owner),
58
);
59
} else if (!props.multiple && isArray) {
60
warning(
61
false,
62
'The `%s` prop supplied to <select> must be a scalar ' +
63
- 'value if `multiple` is false.%s',
63
+ 'value if `multiple` is false.%s',
64
propName,
65
- getDeclarationErrorAddendum(owner)
65
+ getDeclarationErrorAddendum(owner),
66
);
67
}
68
}
@@ -146,10 +146,10 @@ var ReactDOMSelect = {
146
warning(
147
false,
148
'Select elements must be either controlled or uncontrolled ' +
149
- '(specify either the value prop, or the defaultValue prop, but not ' +
150
- 'both). Decide between using a controlled or uncontrolled select ' +
151
- 'element and remove one of these props. More info: ' +
152
- 'https://fb.me/react-controlled-components'
149
+ '(specify either the value prop, or the defaultValue prop, but not ' +
150
+ 'both). Decide between using a controlled or uncontrolled select ' +
151
+ 'element and remove one of these props. More info: ' +
152
+ 'https://fb.me/react-controlled-components',
153
);
154
didWarnValueDefaultValue = true;
155
}
src/renderers/dom/stack/client/wrappers/ReactDOMTextarea.js
+9
-11
@@ -38,7 +38,7 @@ var ReactDOMTextarea = {
38
getHostProps: function(inst, props) {
39
invariant(
40
props.dangerouslySetInnerHTML == null,
41
- '`dangerouslySetInnerHTML` does not make sense on <textarea>.'
41
+ '`dangerouslySetInnerHTML` does not make sense on <textarea>.',
42
);
43
44
// Always set children to the same thing. In IE9, the selection range will
@@ -61,7 +61,7 @@ var ReactDOMTextarea = {
61
ReactControlledValuePropTypes.checkPropTypes(
62
'textarea',
63
props,
64
- owner ? owner.getName() : null
64
+ owner ? owner.getName() : null,
65
);
66
if (
67
props.value !== undefined &&
@@ -71,16 +71,15 @@ var ReactDOMTextarea = {
71
warning(
72
false,
73
'Textarea elements must be either controlled or uncontrolled ' +
74
- '(specify either the value prop, or the defaultValue prop, but not ' +
75
- 'both). Decide between using a controlled or uncontrolled textarea ' +
76
- 'and remove one of these props. More info: ' +
77
- 'https://fb.me/react-controlled-components'
74
+ '(specify either the value prop, or the defaultValue prop, but not ' +
75
+ 'both). Decide between using a controlled or uncontrolled textarea ' +
76
+ 'and remove one of these props. More info: ' +
77
+ 'https://fb.me/react-controlled-components',
78
);
79
didWarnValDefaultVal = true;
80
}
81
}
82
83
-
83
var value = props.value;
84
var initialValue = value;
85
@@ -94,17 +93,17 @@ var ReactDOMTextarea = {
93
warning(
94
false,
95
'Use the `defaultValue` or `value` props instead of setting ' +
97
- 'children on <textarea>.'
96
+ 'children on <textarea>.',
97
);
98
}
99
invariant(
100
defaultValue == null,
102
- 'If you supply `defaultValue` on a <textarea>, do not pass children.'
101
+ 'If you supply `defaultValue` on a <textarea>, do not pass children.',
102
);
103
if (Array.isArray(children)) {
104
invariant(
105
children.length <= 1,
107
- '<textarea> can only have at most one child.'
106
+ '<textarea> can only have at most one child.',
107
);
108
children = children[0];
109
}
@@ -167,7 +166,6 @@ var ReactDOMTextarea = {
166
ReactDOMTextarea.updateWrapper(inst);
167
}
168
},
170
-
169
};
170
171
module.exports = ReactDOMTextarea;
src/renderers/dom/stack/server/ReactMarkupChecksum.js
+2
-3
@@ -16,7 +16,6 @@ var adler32 = require('adler32');
16
var TAG_END = /\/?>/;
17
var COMMENT_START = /^<\!\-\-/;
18
19
-
19
var ReactMarkupChecksum = {
20
CHECKSUM_ATTR_NAME: 'data-react-checksum',
21
@@ -33,7 +32,7 @@ var ReactMarkupChecksum = {
32
} else {
33
return markup.replace(
34
TAG_END,
36
- ' ' + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '"$&'
35
+ ' ' + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '"$&',
36
);
37
}
38
},
@@ -45,7 +44,7 @@ var ReactMarkupChecksum = {
44
*/
45
canReuseMarkup: function(markup, element) {
46
var existingChecksum = element.getAttribute(
48
- ReactMarkupChecksum.CHECKSUM_ATTR_NAME
47
+ ReactMarkupChecksum.CHECKSUM_ATTR_NAME,
48
);
49
existingChecksum = existingChecksum && parseInt(existingChecksum, 10);
50
var markupChecksum = adler32(markup);
src/renderers/dom/stack/server/ReactServerRendering.js
+26
-26
@@ -16,8 +16,7 @@ var ReactInstrumentation = require('ReactInstrumentation');
16
var ReactMarkupChecksum = require('ReactMarkupChecksum');
17
var ReactReconciler = require('ReactReconciler');
18
var ReactServerBatchingStrategy = require('ReactServerBatchingStrategy');
19
-var ReactServerRenderingTransaction =
20
- require('ReactServerRenderingTransaction');
19
+var ReactServerRenderingTransaction = require('ReactServerRenderingTransaction');
20
var ReactUpdates = require('ReactUpdates');
21
22
var emptyObject = require('fbjs/lib/emptyObject');
@@ -41,35 +40,36 @@ function renderToStringImpl(element, makeStaticMarkup) {
40
41
pendingTransactions++;
42
44
- return transaction.perform(function() {
45
- var componentInstance = instantiateReactComponent(element, true);
46
- var markup = ReactReconciler.mountComponent(
47
- componentInstance,
48
- transaction,
49
- null,
50
- ReactDOMContainerInfo(),
51
- emptyObject,
52
- 0 /* parentDebugID */
53
- );
54
- if (__DEV__) {
55
- ReactInstrumentation.debugTool.onUnmountComponent(
56
- componentInstance._debugID
43
+ return transaction.perform(
44
+ function() {
45
+ var componentInstance = instantiateReactComponent(element, true);
46
+ var markup = ReactReconciler.mountComponent(
47
+ componentInstance,
48
+ transaction,
49
+ null,
50
+ ReactDOMContainerInfo(),
51
+ emptyObject,
52
+ 0 /* parentDebugID */,
53
);
58
- }
59
- if (!makeStaticMarkup) {
60
- markup = ReactMarkupChecksum.addChecksumToMarkup(markup);
61
- }
62
- return markup;
63
- }, null);
54
+ if (__DEV__) {
55
+ ReactInstrumentation.debugTool.onUnmountComponent(
56
+ componentInstance._debugID,
57
+ );
58
+ }
59
+ if (!makeStaticMarkup) {
60
+ markup = ReactMarkupChecksum.addChecksumToMarkup(markup);
61
+ }
62
+ return markup;
63
+ },
64
+ null,
65
+ );
66
} finally {
67
pendingTransactions--;
68
ReactServerRenderingTransaction.release(transaction);
69
// Revert to the DOM batching strategy since these two renderers
70
// currently share these stateful modules.
71
if (!pendingTransactions) {
70
- ReactUpdates.injection.injectBatchingStrategy(
71
- previousBatchingStrategy
72
- );
72
+ ReactUpdates.injection.injectBatchingStrategy(previousBatchingStrategy);
73
}
74
}
75
}
@@ -82,7 +82,7 @@ function renderToStringImpl(element, makeStaticMarkup) {
82
function renderToString(element) {
83
invariant(
84
React.isValidElement(element),
85
- 'renderToString(): You must pass a valid ReactElement.'
85
+ 'renderToString(): You must pass a valid ReactElement.',
86
);
87
return renderToStringImpl(element, false);
88
}
@@ -95,7 +95,7 @@ function renderToString(element) {
95
function renderToStaticMarkup(element) {
96
invariant(
97
React.isValidElement(element),
98
- 'renderToStaticMarkup(): You must pass a valid ReactElement.'
98
+ 'renderToStaticMarkup(): You must pass a valid ReactElement.',
99
);
100
return renderToStringImpl(element, true);
101
}
src/renderers/dom/stack/server/ReactServerRenderingTransaction.js
+4
-13
@@ -16,7 +16,6 @@ var Transaction = require('Transaction');
16
var ReactInstrumentation = require('ReactInstrumentation');
17
var ReactServerUpdateQueue = require('ReactServerUpdateQueue');
18
19
-
19
/**
20
* Executed within the scope of the `Transaction` instance. Consider these as
21
* being member methods, but with an implied ordering while being isolated from
@@ -75,22 +74,14 @@ var Mixin = {
74
* `PooledClass` looks for this, and will invoke this before allowing this
75
* instance to be reused.
76
*/
78
- destructor: function() {
79
- },
77
+ destructor: function() {},
78
81
- checkpoint: function() {
82
- },
79
+ checkpoint: function() {},
80
84
- rollback: function() {
85
- },
81
+ rollback: function() {},
82
};
83
88
-
89
-Object.assign(
90
- ReactServerRenderingTransaction.prototype,
91
- Transaction,
92
- Mixin
93
-);
84
+Object.assign(ReactServerRenderingTransaction.prototype, Transaction, Mixin);
85
86
PooledClass.addPoolingTo(ReactServerRenderingTransaction);
87
src/renderers/dom/stack/server/ReactServerUpdateQueue.js
+30
-12
@@ -16,19 +16,23 @@ var ReactUpdateQueue = require('ReactUpdateQueue');
16
17
var warning = require('fbjs/lib/warning');
18
19
-import type { Transaction } from 'Transaction';
19
+import type {Transaction} from 'Transaction';
20
21
-function warnNoop(publicInstance: ReactComponent<any, any, any>, callerName: string) {
21
+function warnNoop(
22
+ publicInstance: ReactComponent<any, any, any>,
23
+ callerName: string,
24
+) {
25
if (__DEV__) {
26
var constructor = publicInstance.constructor;
27
warning(
28
false,
29
'%s(...): Can only update a mounting component. ' +
27
- 'This usually means you called %s() outside componentWillMount() on the server. ' +
28
- 'This is a no-op.\n\nPlease check the code for the %s component.',
30
+ 'This usually means you called %s() outside componentWillMount() on the server. ' +
31
+ 'This is a no-op.\n\nPlease check the code for the %s component.',
32
callerName,
33
callerName,
31
- constructor && (constructor.displayName || constructor.name) || 'ReactClass'
34
+ (constructor && (constructor.displayName || constructor.name)) ||
35
+ 'ReactClass',
36
);
37
}
38
}
@@ -73,7 +77,11 @@ class ReactServerUpdateQueue {
77
* @param {?string} Name of the calling function in the public API.
78
* @internal
79
*/
76
- enqueueForceUpdate(publicInstance: ReactComponent<any, any, any>, callback?: Function, callerName?: string) {
80
+ enqueueForceUpdate(
81
+ publicInstance: ReactComponent<any, any, any>,
82
+ callback?: Function,
83
+ callerName?: string,
84
+ ) {
85
if (this.transaction.isInTransaction()) {
86
ReactUpdateQueue.enqueueForceUpdate(publicInstance, callback, callerName);
87
} else {
@@ -96,12 +104,17 @@ class ReactServerUpdateQueue {
104
*/
105
enqueueReplaceState(
106
publicInstance: ReactComponent<any, any, any>,
99
- completeState: Object|Function,
107
+ completeState: Object | Function,
108
callback?: Function,
101
- callerName?: string
109
+ callerName?: string,
110
) {
111
if (this.transaction.isInTransaction()) {
104
- ReactUpdateQueue.enqueueReplaceState(publicInstance, completeState, callback, callerName);
112
+ ReactUpdateQueue.enqueueReplaceState(
113
+ publicInstance,
114
+ completeState,
115
+ callback,
116
+ callerName,
117
+ );
118
} else {
119
warnNoop(publicInstance, 'replaceState');
120
}
@@ -119,12 +132,17 @@ class ReactServerUpdateQueue {
132
*/
133
enqueueSetState(
134
publicInstance: ReactComponent<any, any, any>,
122
- partialState: Object|Function,
135
+ partialState: Object | Function,
136
callback?: Function,
124
- callerName?: string
137
+ callerName?: string,
138
) {
139
if (this.transaction.isInTransaction()) {
127
- ReactUpdateQueue.enqueueSetState(publicInstance, partialState, callback, callerName);
140
+ ReactUpdateQueue.enqueueSetState(
141
+ publicInstance,
142
+ partialState,
143
+ callback,
144
+ callerName,
145
+ );
146
} else {
147
warnNoop(publicInstance, 'setState');
148
}
src/renderers/native/NativeMethodsMixin.js
+32
-21
@@ -24,30 +24,34 @@ type MeasureOnSuccessCallback = (
24
width: number,
25
height: number,
26
pageX: number,
27
- pageY: number
28
-) => void
27
+ pageY: number,
28
+) => void;
29
30
type MeasureInWindowOnSuccessCallback = (
31
x: number,
32
y: number,
33
width: number,
34
height: number,
35
-) => void
35
+) => void;
36
37
type MeasureLayoutOnSuccessCallback = (
38
left: number,
39
top: number,
40
width: number,
41
- height: number
42
-) => void
41
+ height: number,
42
+) => void;
43
44
function warnForStyleProps(props, validAttributes) {
45
for (var key in validAttributes.style) {
46
if (!(validAttributes[key] || props[key] === undefined)) {
47
console.error(
48
- 'You are setting the style `{ ' + key + ': ... }` as a prop. You ' +
49
- 'should nest it in a style object. ' +
50
- 'E.g. `{ style: { ' + key + ': ... } }`'
48
+ 'You are setting the style `{ ' +
49
+ key +
50
+ ': ... }` as a prop. You ' +
51
+ 'should nest it in a style object. ' +
52
+ 'E.g. `{ style: { ' +
53
+ key +
54
+ ': ... } }`',
55
);
56
}
57
}
@@ -86,7 +90,7 @@ var NativeMethodsMixin = {
90
measure: function(callback: MeasureOnSuccessCallback) {
91
UIManager.measure(
92
ReactNative.findNodeHandle(this),
89
- mountSafeCallback(this, callback)
93
+ mountSafeCallback(this, callback),
94
);
95
},
96
@@ -108,7 +112,7 @@ var NativeMethodsMixin = {
112
measureInWindow: function(callback: MeasureInWindowOnSuccessCallback) {
113
UIManager.measureInWindow(
114
ReactNative.findNodeHandle(this),
111
- mountSafeCallback(this, callback)
115
+ mountSafeCallback(this, callback),
116
);
117
},
118
@@ -123,13 +127,13 @@ var NativeMethodsMixin = {
127
measureLayout: function(
128
relativeToNativeNode: number,
129
onSuccess: MeasureLayoutOnSuccessCallback,
126
- onFail: () => void /* currently unused */
130
+ onFail: () => void /* currently unused */,
131
) {
132
UIManager.measureLayout(
133
ReactNative.findNodeHandle(this),
134
relativeToNativeNode,
135
mountSafeCallback(this, onFail),
132
- mountSafeCallback(this, onSuccess)
136
+ mountSafeCallback(this, onSuccess),
137
);
138
},
139
@@ -146,13 +150,13 @@ var NativeMethodsMixin = {
150
151
var updatePayload = ReactNativeAttributePayload.create(
152
nativeProps,
149
- this.viewConfig.validAttributes
153
+ this.viewConfig.validAttributes,
154
);
155
156
UIManager.updateView(
153
- (ReactNative.findNodeHandle(this) : any),
157
+ (ReactNative.findNodeHandle(this): any),
158
this.viewConfig.uiViewClassName,
155
- updatePayload
159
+ updatePayload,
160
);
161
},
162
@@ -176,10 +180,14 @@ function throwOnStylesProp(component, props) {
180
if (props.styles !== undefined) {
181
var owner = component._owner || null;
182
var name = component.constructor.displayName;
179
- var msg = '`styles` is not a supported property of `' + name + '`, did ' +
183
+ var msg = '`styles` is not a supported property of `' +
184
+ name +
185
+ '`, did ' +
186
'you mean `style` (singular)?';
187
if (owner && owner.constructor && owner.constructor.displayName) {
182
- msg += '\n\nCheck the `' + owner.constructor.displayName + '` parent ' +
188
+ msg += '\n\nCheck the `' +
189
+ owner.constructor.displayName +
190
+ '` parent ' +
191
' component.';
192
}
193
throw new Error(msg);
@@ -192,8 +200,8 @@ if (__DEV__) {
200
var NativeMethodsMixin_DEV = (NativeMethodsMixin: any);
201
invariant(
202
!NativeMethodsMixin_DEV.componentWillMount &&
195
- !NativeMethodsMixin_DEV.componentWillReceiveProps,
196
- 'Do not override existing functions.'
203
+ !NativeMethodsMixin_DEV.componentWillReceiveProps,
204
+ 'Do not override existing functions.',
205
);
206
NativeMethodsMixin_DEV.componentWillMount = function() {
207
throwOnStylesProp(this, this.props);
@@ -209,10 +217,13 @@ if (__DEV__) {
217
*/
218
function mountSafeCallback(
219
context: ReactComponent<any, any, any>,
212
- callback: ?Function
220
+ callback: ?Function,
221
): any {
222
return function() {
215
- if (!callback || (typeof context.isMounted === 'function' && !context.isMounted())) {
223
+ if (
224
+ !callback ||
225
+ (typeof context.isMounted === 'function' && !context.isMounted())
226
+ ) {
227
return undefined;
228
}
229
return callback.apply(context, arguments);
src/renderers/native/ReactNativeAttributePayload.js
+90
-94
@@ -31,14 +31,15 @@ type AttributeDiffer = (prevProp: mixed, nextProp: mixed) => boolean;
31
type AttributePreprocessor = (nextProp: mixed) => mixed;
32
33
type CustomAttributeConfiguration =
34
- { diff: AttributeDiffer, process: AttributePreprocessor } |
35
- { diff: AttributeDiffer } |
36
- { process: AttributePreprocessor };
37
-
38
-type AttributeConfiguration =
39
- { [key: string]: (
40
- CustomAttributeConfiguration | AttributeConfiguration /*| boolean*/
41
- ) };
34
+ | {diff: AttributeDiffer, process: AttributePreprocessor}
35
+ | {diff: AttributeDiffer}
36
+ | {process: AttributePreprocessor};
37
+
38
+type AttributeConfiguration = {
39
+ [key: string]:
40
+ | CustomAttributeConfiguration
41
+ | AttributeConfiguration /*| boolean*/,
42
+};
43
44
type NestedNode = Array<NestedNode> | Object | number;
45
@@ -46,7 +47,7 @@ type NestedNode = Array<NestedNode> | Object | number;
47
var removedKeys = null;
48
var removedKeyCount = 0;
49
49
-function defaultDiffer(prevProp: mixed, nextProp: mixed) : boolean {
50
+function defaultDiffer(prevProp: mixed, nextProp: mixed): boolean {
51
if (typeof nextProp !== 'object' || nextProp === null) {
52
// Scalars have already been checked for equality
53
return true;
@@ -56,7 +57,7 @@ function defaultDiffer(prevProp: mixed, nextProp: mixed) : boolean {
57
}
58
}
59
59
-function resolveObject(idOrObject: number | Object) : Object {
60
+function resolveObject(idOrObject: number | Object): Object {
61
if (typeof idOrObject === 'number') {
62
return ReactNativePropRegistry.getByID(idOrObject);
63
}
@@ -66,7 +67,7 @@ function resolveObject(idOrObject: number | Object) : Object {
67
function restoreDeletedValuesInNestedArray(
68
updatePayload: Object,
69
node: NestedNode,
69
- validAttributes: AttributeConfiguration
70
+ validAttributes: AttributeConfiguration,
71
) {
72
if (Array.isArray(node)) {
73
var i = node.length;
@@ -74,7 +75,7 @@ function restoreDeletedValuesInNestedArray(
75
restoreDeletedValuesInNestedArray(
76
updatePayload,
77
node[i],
77
- validAttributes
78
+ validAttributes,
79
);
80
}
81
} else if (node && removedKeyCount > 0) {
@@ -103,12 +104,14 @@ function restoreDeletedValuesInNestedArray(
104
if (typeof attributeConfig !== 'object') {
105
// case: !Object is the default case
106
updatePayload[propKey] = nextProp;
106
- } else if (typeof attributeConfig.diff === 'function' ||
107
- typeof attributeConfig.process === 'function') {
107
+ } else if (
108
+ typeof attributeConfig.diff === 'function' ||
109
+ typeof attributeConfig.process === 'function'
110
+ ) {
111
// case: CustomAttributeConfiguration
109
- var nextValue = typeof attributeConfig.process === 'function' ?
110
- attributeConfig.process(nextProp) :
111
- nextProp;
112
+ var nextValue = typeof attributeConfig.process === 'function'
113
+ ? attributeConfig.process(nextProp)
114
+ : nextProp;
115
updatePayload[propKey] = nextValue;
116
}
117
removedKeys[propKey] = false;
@@ -118,14 +121,14 @@ function restoreDeletedValuesInNestedArray(
121
}
122
123
function diffNestedArrayProperty(
121
- updatePayload:? Object,
124
+ updatePayload: ?Object,
125
prevArray: Array<NestedNode>,
126
nextArray: Array<NestedNode>,
124
- validAttributes: AttributeConfiguration
125
-) : ?Object {
126
- var minLength = prevArray.length < nextArray.length ?
127
- prevArray.length :
128
- nextArray.length;
127
+ validAttributes: AttributeConfiguration,
128
+): ?Object {
129
+ var minLength = prevArray.length < nextArray.length
130
+ ? prevArray.length
131
+ : nextArray.length;
132
var i;
133
for (i = 0; i < minLength; i++) {
134
// Diff any items in the array in the forward direction. Repeated keys
@@ -134,7 +137,7 @@ function diffNestedArrayProperty(
137
updatePayload,
138
prevArray[i],
139
nextArray[i],
137
- validAttributes
140
+ validAttributes,
141
);
142
}
143
for (; i < prevArray.length; i++) {
@@ -142,7 +145,7 @@ function diffNestedArrayProperty(
145
updatePayload = clearNestedProperty(
146
updatePayload,
147
prevArray[i],
145
- validAttributes
148
+ validAttributes,
149
);
150
}
151
for (; i < nextArray.length; i++) {
@@ -150,19 +153,18 @@ function diffNestedArrayProperty(
153
updatePayload = addNestedProperty(
154
updatePayload,
155
nextArray[i],
153
- validAttributes
156
+ validAttributes,
157
);
158
}
159
return updatePayload;
160
}
161
162
function diffNestedProperty(
160
- updatePayload:? Object,
163
+ updatePayload: ?Object,
164
prevProp: NestedNode,
165
nextProp: NestedNode,
163
- validAttributes: AttributeConfiguration
164
-) : ?Object {
165
-
166
+ validAttributes: AttributeConfiguration,
167
+): ?Object {
168
if (!updatePayload && prevProp === nextProp) {
169
// If no properties have been added, then we can bail out quickly on object
170
// equality.
@@ -171,18 +173,10 @@ function diffNestedProperty(
173
174
if (!prevProp || !nextProp) {
175
if (nextProp) {
174
- return addNestedProperty(
175
- updatePayload,
176
- nextProp,
177
- validAttributes
178
- );
176
+ return addNestedProperty(updatePayload, nextProp, validAttributes);
177
}
178
if (prevProp) {
181
- return clearNestedProperty(
182
- updatePayload,
183
- prevProp,
184
- validAttributes
185
- );
179
+ return clearNestedProperty(updatePayload, prevProp, validAttributes);
180
}
181
return updatePayload;
182
}
@@ -193,7 +187,7 @@ function diffNestedProperty(
187
updatePayload,
188
resolveObject(prevProp),
189
resolveObject(nextProp),
196
- validAttributes
190
+ validAttributes,
191
);
192
}
193
@@ -203,7 +197,7 @@ function diffNestedProperty(
197
updatePayload,
198
prevProp,
199
nextProp,
206
- validAttributes
200
+ validAttributes,
201
);
202
}
203
@@ -214,16 +208,16 @@ function diffNestedProperty(
208
flattenStyle(prevProp),
209
// $FlowFixMe - We know that this isn't an array because of above flow.
210
resolveObject(nextProp),
217
- validAttributes
211
+ validAttributes,
212
);
213
}
214
215
return diffProperties(
216
updatePayload,
217
resolveObject(prevProp),
224
- // $FlowFixMe - We know that this is always an object when the input is.
218
+ // $FlowFixMe - We know that this is always an object when the input is.
219
flattenStyle(nextProp),
226
- validAttributes
220
+ validAttributes,
221
);
222
}
223
@@ -233,9 +227,9 @@ function diffNestedProperty(
227
* updatePayload.
228
*/
229
function addNestedProperty(
236
- updatePayload:? Object,
230
+ updatePayload: ?Object,
231
nextProp: NestedNode,
238
- validAttributes: AttributeConfiguration
232
+ validAttributes: AttributeConfiguration,
233
) {
234
if (!nextProp) {
235
return updatePayload;
@@ -246,7 +240,7 @@ function addNestedProperty(
240
return addProperties(
241
updatePayload,
242
resolveObject(nextProp),
249
- validAttributes
243
+ validAttributes,
244
);
245
}
246
@@ -255,7 +249,7 @@ function addNestedProperty(
249
updatePayload = addNestedProperty(
250
updatePayload,
251
nextProp[i],
258
- validAttributes
252
+ validAttributes,
253
);
254
}
255
@@ -267,10 +261,10 @@ function addNestedProperty(
261
* adds a null sentinel to the updatePayload, for each prop key.
262
*/
263
function clearNestedProperty(
270
- updatePayload:? Object,
264
+ updatePayload: ?Object,
265
prevProp: NestedNode,
272
- validAttributes: AttributeConfiguration
273
-) : ?Object {
266
+ validAttributes: AttributeConfiguration,
267
+): ?Object {
268
if (!prevProp) {
269
return updatePayload;
270
}
@@ -280,7 +274,7 @@ function clearNestedProperty(
274
return clearProperties(
275
updatePayload,
276
resolveObject(prevProp),
283
- validAttributes
277
+ validAttributes,
278
);
279
}
280
@@ -289,7 +283,7 @@ function clearNestedProperty(
283
updatePayload = clearNestedProperty(
284
updatePayload,
285
prevProp[i],
292
- validAttributes
286
+ validAttributes,
287
);
288
}
289
return updatePayload;
@@ -305,9 +299,9 @@ function diffProperties(
299
updatePayload: ?Object,
300
prevProps: Object,
301
nextProps: Object,
308
- validAttributes: AttributeConfiguration
302
+ validAttributes: AttributeConfiguration,
303
): ?Object {
310
- var attributeConfig : ?(CustomAttributeConfiguration | AttributeConfiguration);
304
+ var attributeConfig: ?(CustomAttributeConfiguration | AttributeConfiguration);
305
var nextProp;
306
var prevProp;
307
@@ -323,20 +317,20 @@ function diffProperties(
317
// functions are converted to booleans as markers that the associated
318
// events should be sent from native.
319
if (typeof nextProp === 'function') {
326
- nextProp = (true : any);
320
+ nextProp = (true: any);
321
// If nextProp is not a function, then don't bother changing prevProp
322
// since nextProp will win and go into the updatePayload regardless.
323
if (typeof prevProp === 'function') {
330
- prevProp = (true : any);
324
+ prevProp = (true: any);
325
}
326
}
327
328
// An explicit value of undefined is treated as a null because it overrides
329
// any other preceding value.
330
if (typeof nextProp === 'undefined') {
337
- nextProp = (null : any);
331
+ nextProp = (null: any);
332
if (typeof prevProp === 'undefined') {
339
- prevProp = (null : any);
333
+ prevProp = (null: any);
334
}
335
}
336
@@ -354,12 +348,14 @@ function diffProperties(
348
if (typeof attributeConfig !== 'object') {
349
// case: !Object is the default case
350
updatePayload[propKey] = nextProp;
357
- } else if (typeof attributeConfig.diff === 'function' ||
358
- typeof attributeConfig.process === 'function') {
351
+ } else if (
352
+ typeof attributeConfig.diff === 'function' ||
353
+ typeof attributeConfig.process === 'function'
354
+ ) {
355
// case: CustomAttributeConfiguration
360
- var nextValue = typeof attributeConfig.process === 'function' ?
361
- attributeConfig.process(nextProp) :
362
- nextProp;
356
+ var nextValue = typeof attributeConfig.process === 'function'
357
+ ? attributeConfig.process(nextProp)
358
+ : nextProp;
359
updatePayload[propKey] = nextValue;
360
}
361
continue;
@@ -376,18 +372,19 @@ function diffProperties(
372
// a normal leaf has changed
373
(updatePayload || (updatePayload = {}))[propKey] = nextProp;
374
}
379
- } else if (typeof attributeConfig.diff === 'function' ||
380
- typeof attributeConfig.process === 'function') {
375
+ } else if (
376
+ typeof attributeConfig.diff === 'function' ||
377
+ typeof attributeConfig.process === 'function'
378
+ ) {
379
// case: CustomAttributeConfiguration
382
- var shouldUpdate = prevProp === undefined || (
383
- typeof attributeConfig.diff === 'function' ?
384
- attributeConfig.diff(prevProp, nextProp) :
385
- defaultDiffer(prevProp, nextProp)
386
- );
380
+ var shouldUpdate = prevProp === undefined ||
381
+ (typeof attributeConfig.diff === 'function'
382
+ ? attributeConfig.diff(prevProp, nextProp)
383
+ : defaultDiffer(prevProp, nextProp));
384
if (shouldUpdate) {
388
- nextValue = typeof attributeConfig.process === 'function' ?
389
- attributeConfig.process(nextProp) :
390
- nextProp;
385
+ nextValue = typeof attributeConfig.process === 'function'
386
+ ? attributeConfig.process(nextProp)
387
+ : nextProp;
388
(updatePayload || (updatePayload = {}))[propKey] = nextValue;
389
}
390
} else {
@@ -400,13 +397,13 @@ function diffProperties(
397
updatePayload,
398
prevProp,
399
nextProp,
403
- ((attributeConfig : any) : AttributeConfiguration)
400
+ ((attributeConfig: any): AttributeConfiguration),
401
);
402
if (removedKeyCount > 0 && updatePayload) {
403
restoreDeletedValuesInNestedArray(
404
updatePayload,
405
nextProp,
409
- ((attributeConfig : any) : AttributeConfiguration)
406
+ ((attributeConfig: any): AttributeConfiguration),
407
);
408
removedKeys = null;
409
}
@@ -435,10 +432,11 @@ function diffProperties(
432
continue; // was already empty anyway
433
}
434
// Pattern match on: attributeConfig
438
- if (typeof attributeConfig !== 'object' ||
439
- typeof attributeConfig.diff === 'function' ||
440
- typeof attributeConfig.process === 'function') {
441
-
435
+ if (
436
+ typeof attributeConfig !== 'object' ||
437
+ typeof attributeConfig.diff === 'function' ||
438
+ typeof attributeConfig.process === 'function'
439
+ ) {
440
// case: CustomAttributeConfiguration | !Object
441
// Flag the leaf property for removal by sending a sentinel.
442
(updatePayload || (updatePayload = {}))[propKey] = null;
@@ -456,7 +454,7 @@ function diffProperties(
454
updatePayload = clearNestedProperty(
455
updatePayload,
456
prevProp,
459
- ((attributeConfig : any) : AttributeConfiguration)
457
+ ((attributeConfig: any): AttributeConfiguration),
458
);
459
}
460
}
@@ -469,8 +467,8 @@ function diffProperties(
467
function addProperties(
468
updatePayload: ?Object,
469
props: Object,
472
- validAttributes: AttributeConfiguration
473
-) : ?Object {
470
+ validAttributes: AttributeConfiguration,
471
+): ?Object {
472
// TODO: Fast path
473
return diffProperties(updatePayload, emptyObject, props, validAttributes);
474
}
@@ -482,38 +480,36 @@ function addProperties(
480
function clearProperties(
481
updatePayload: ?Object,
482
prevProps: Object,
485
- validAttributes: AttributeConfiguration
486
-) :? Object {
483
+ validAttributes: AttributeConfiguration,
484
+): ?Object {
485
// TODO: Fast path
486
return diffProperties(updatePayload, prevProps, emptyObject, validAttributes);
487
}
488
489
var ReactNativeAttributePayload = {
492
-
490
create: function(
491
props: Object,
495
- validAttributes: AttributeConfiguration
496
- ) : ?Object {
492
+ validAttributes: AttributeConfiguration,
493
+ ): ?Object {
494
return addProperties(
495
null, // updatePayload
496
props,
500
- validAttributes
497
+ validAttributes,
498
);
499
},
500
501
diff: function(
502
prevProps: Object,
503
nextProps: Object,
507
- validAttributes: AttributeConfiguration
508
- ) : ?Object {
504
+ validAttributes: AttributeConfiguration,
505
+ ): ?Object {
506
return diffProperties(
507
null, // updatePayload
508
prevProps,
509
nextProps,
513
- validAttributes
510
+ validAttributes,
511
);
512
},
516
-
513
};
514
515
module.exports = ReactNativeAttributePayload;
src/renderers/native/ReactNativeBaseComponent.js
+14
-10
@@ -23,7 +23,7 @@ var deepFreezeAndThrowOnMutationInDev = require('deepFreezeAndThrowOnMutationInD
23
type ReactNativeBaseComponentViewConfig = {
24
validAttributes: Object,
25
uiViewClassName: string,
26
-}
26
+};
27
28
// require('UIManagerStatTracker').install(); // uncomment to enable
29
@@ -34,7 +34,7 @@ type ReactNativeBaseComponentViewConfig = {
34
* @param {!object} UIKit View Configuration.
35
*/
36
var ReactNativeBaseComponent = function(
37
- viewConfig: ReactNativeBaseComponentViewConfig
37
+ viewConfig: ReactNativeBaseComponentViewConfig,
38
) {
39
this.viewConfig = viewConfig;
40
};
@@ -69,7 +69,6 @@ ReactNativeBaseComponent.Mixin = {
69
// no children - let's avoid calling out to the native bridge for a large
70
// portion of the children.
71
if (mountImages.length) {
72
-
72
// TODO: Pool these per platform view class. Reusing the `mountImages`
73
// array would likely be a jit deopt.
74
var createdTags = [];
@@ -105,14 +104,14 @@ ReactNativeBaseComponent.Mixin = {
104
var updatePayload = ReactNativeAttributePayload.diff(
105
prevElement.props,
106
nextElement.props,
108
- this.viewConfig.validAttributes
107
+ this.viewConfig.validAttributes,
108
);
109
110
if (updatePayload) {
111
UIManager.updateView(
112
this._rootNodeID,
113
this.viewConfig.uiViewClassName,
115
- updatePayload
114
+ updatePayload,
115
);
116
}
117
@@ -135,7 +134,12 @@ ReactNativeBaseComponent.Mixin = {
134
* @param {object} context
135
* @return {string} Unique iOS view tag.
136
*/
138
- mountComponent: function(transaction, hostParent, hostContainerInfo, context) {
137
+ mountComponent: function(
138
+ transaction,
139
+ hostParent,
140
+ hostContainerInfo,
141
+ context,
142
+ ) {
143
var tag = ReactNativeTagHandles.allocateTag();
144
145
this._rootNodeID = tag;
@@ -152,7 +156,7 @@ ReactNativeBaseComponent.Mixin = {
156
157
var updatePayload = ReactNativeAttributePayload.create(
158
this._currentElement.props,
155
- this.viewConfig.validAttributes
159
+ this.viewConfig.validAttributes,
160
);
161
162
var nativeTopRootTag = hostContainerInfo._tag;
@@ -160,7 +164,7 @@ ReactNativeBaseComponent.Mixin = {
164
tag,
165
this.viewConfig.uiViewClassName,
166
nativeTopRootTag,
163
- updatePayload
167
+ updatePayload,
168
);
169
170
ReactNativeComponentTree.precacheNode(this, tag);
@@ -169,7 +173,7 @@ ReactNativeBaseComponent.Mixin = {
173
this._currentElement.props.children,
174
tag,
175
transaction,
172
- context
176
+ context,
177
);
178
return tag;
179
},
@@ -183,7 +187,7 @@ Object.assign(
187
ReactNativeBaseComponent.prototype,
188
ReactMultiChild,
189
ReactNativeBaseComponent.Mixin,
186
- NativeMethodsMixin
190
+ NativeMethodsMixin,
191
);
192
193
module.exports = ReactNativeBaseComponent;
src/renderers/native/ReactNativeBridgeEventPlugin.js
+7
-6
@@ -23,21 +23,22 @@ var customDirectEventTypes = UIManager.customDirectEventTypes;
23
var allTypesByEventName = {};
24
25
for (var bubblingTypeName in customBubblingEventTypes) {
26
- allTypesByEventName[bubblingTypeName] = customBubblingEventTypes[bubblingTypeName];
26
+ allTypesByEventName[bubblingTypeName] = customBubblingEventTypes[
27
+ bubblingTypeName
28
+ ];
29
}
30
31
for (var directTypeName in customDirectEventTypes) {
32
warning(
33
!customBubblingEventTypes[directTypeName],
34
'Event cannot be both direct and bubbling: %s',
33
- directTypeName
35
+ directTypeName,
36
);
37
allTypesByEventName[directTypeName] = customDirectEventTypes[directTypeName];
38
}
39
40
var ReactNativeBridgeEventPlugin = {
39
-
40
- eventTypes: { ...customBubblingEventTypes, ...customDirectEventTypes },
41
+ eventTypes: {...customBubblingEventTypes, ...customDirectEventTypes},
42
43
/**
44
* @see {EventPluginHub.extractEvents}
@@ -46,7 +47,7 @@ var ReactNativeBridgeEventPlugin = {
47
topLevelType: string,
48
targetInst: Object,
49
nativeEvent: Event,
49
- nativeEventTarget: Object
50
+ nativeEventTarget: Object,
51
): ?Object {
52
var bubbleDispatchConfig = customBubblingEventTypes[topLevelType];
53
var directDispatchConfig = customDirectEventTypes[topLevelType];
@@ -54,7 +55,7 @@ var ReactNativeBridgeEventPlugin = {
55
bubbleDispatchConfig || directDispatchConfig,
56
targetInst,
57
nativeEvent,
57
- nativeEventTarget
58
+ nativeEventTarget,
59
);
60
if (bubbleDispatchConfig) {
61
EventPropagators.accumulateTwoPhaseDispatches(event);
src/renderers/native/ReactNativeComponentEnvironment.js
+1
-4
@@ -15,7 +15,6 @@ var ReactNativeDOMIDOperations = require('ReactNativeDOMIDOperations');
15
var ReactNativeReconcileTransaction = require('ReactNativeReconcileTransaction');
16
17
var ReactNativeComponentEnvironment = {
18
-
18
processChildrenUpdates: ReactNativeDOMIDOperations.dangerouslyProcessChildrenUpdates,
19
20
replaceNodeWithMarkup: ReactNativeDOMIDOperations.dangerouslyReplaceNodeWithMarkupByID,
@@ -23,9 +22,7 @@ var ReactNativeComponentEnvironment = {
22
/**
23
* @param {DOMElement} Element to clear.
24
*/
26
- clearNode: function(/*containerView*/) {
27
-
28
- },
25
+ clearNode: function(/*containerView*/) {},
26
27
ReactReconcileTransaction: ReactNativeReconcileTransaction,
28
};
src/renderers/native/ReactNativeDOMIDOperations.js
+1
-1
@@ -59,7 +59,7 @@ var dangerouslyProcessChildrenUpdates = function(inst, childrenUpdates) {
59
moveToIndices,
60
addChildTags,
61
addAtIndices,
62
- removeAtIndices
62
+ removeAtIndices,
63
);
64
};
65
src/renderers/native/ReactNativeEventEmitter.js
+12
-14
@@ -56,7 +56,7 @@ var touchSubsequence = function(touches, indices) {
56
*/
57
var removeTouchesAtIndices = function(
58
touches: Array<Object>,
59
- indices: Array<number>
59
+ indices: Array<number>,
60
): Array<Object> {
61
var rippedOut = [];
62
// use an unsafe downcast to alias to nullable elements,
@@ -79,7 +79,6 @@ var removeTouchesAtIndices = function(
79
};
80
81
var ReactNativeEventEmitter = {
82
-
82
...ReactEventEmitterMixin,
83
84
registrationNames: EventPluginRegistry.registrationNameModules,
@@ -99,7 +98,7 @@ var ReactNativeEventEmitter = {
98
_receiveRootNodeIDEvent: function(
99
rootNodeID: number,
100
topLevelType: string,
102
- nativeEventParam: Object
101
+ nativeEventParam: Object,
102
) {
103
var nativeEvent = nativeEventParam || EMPTY_NATIVE_EVENT;
104
var inst = ReactNativeComponentTree.getInstanceFromNode(rootNodeID);
@@ -113,7 +112,7 @@ var ReactNativeEventEmitter = {
112
topLevelType,
113
inst,
114
nativeEvent,
116
- nativeEvent.target
115
+ nativeEvent.target,
116
);
117
});
118
// React Native doesn't use ReactControlledComponent but if it did, here's
@@ -130,13 +129,13 @@ var ReactNativeEventEmitter = {
129
receiveEvent: function(
130
tag: number,
131
topLevelType: string,
133
- nativeEventParam: Object
132
+ nativeEventParam: Object,
133
) {
134
var rootNodeID = tag;
135
ReactNativeEventEmitter._receiveRootNodeIDEvent(
136
rootNodeID,
137
topLevelType,
139
- nativeEventParam
138
+ nativeEventParam,
139
);
140
},
141
@@ -167,13 +166,12 @@ var ReactNativeEventEmitter = {
166
receiveTouches: function(
167
eventTopLevelType: string,
168
touches: Array<Object>,
170
- changedIndices: Array<number>
169
+ changedIndices: Array<number>,
170
) {
172
- var changedTouches =
173
- eventTopLevelType === 'topTouchEnd' ||
174
- eventTopLevelType === 'topTouchCancel' ?
175
- removeTouchesAtIndices(touches, changedIndices) :
176
- touchSubsequence(touches, changedIndices);
171
+ var changedTouches = eventTopLevelType === 'topTouchEnd' ||
172
+ eventTopLevelType === 'topTouchCancel'
173
+ ? removeTouchesAtIndices(touches, changedIndices)
174
+ : touchSubsequence(touches, changedIndices);
175
176
for (var jj = 0; jj < changedTouches.length; jj++) {
177
var touch = changedTouches[jj];
@@ -189,7 +187,7 @@ var ReactNativeEventEmitter = {
187
if (__DEV__) {
188
warning(
189
false,
192
- 'A view is reporting that a touch occurred on tag zero.'
190
+ 'A view is reporting that a touch occurred on tag zero.',
191
);
192
}
193
} else {
@@ -199,7 +197,7 @@ var ReactNativeEventEmitter = {
197
ReactNativeEventEmitter._receiveRootNodeIDEvent(
198
rootNodeID,
199
eventTopLevelType,
202
- nativeEvent
200
+ nativeEvent,
201
);
202
}
203
},
src/renderers/native/ReactNativeFiber.js
+100
-94
@@ -12,10 +12,12 @@
12
13
'use strict';
14
15
-import type { Element } from 'React';
16
-import type { Fiber } from 'ReactFiber';
17
-import type { ReactNodeList } from 'ReactTypes';
18
-import type { ReactNativeBaseComponentViewConfig } from 'ReactNativeViewConfigRegistry';
15
+import type {Element} from 'React';
16
+import type {Fiber} from 'ReactFiber';
17
+import type {ReactNodeList} from 'ReactTypes';
18
+import type {
19
+ ReactNativeBaseComponentViewConfig,
20
+} from 'ReactNativeViewConfigRegistry';
21
22
const NativeMethodsMixin = require('NativeMethodsMixin');
23
const ReactFiberReconciler = require('ReactFiberReconciler');
@@ -33,7 +35,7 @@ const emptyObject = require('fbjs/lib/emptyObject');
35
const findNodeHandle = require('findNodeHandle');
36
const invariant = require('fbjs/lib/invariant');
37
36
-const { injectInternals } = require('ReactFiberDevToolsHook');
38
+const {injectInternals} = require('ReactFiberDevToolsHook');
39
const {
40
precacheFiberNode,
41
uncacheFiberNode,
@@ -58,26 +60,27 @@ function NativeHostComponent(tag, viewConfig) {
60
}
61
Object.assign(NativeHostComponent.prototype, NativeMethodsMixin);
62
61
-function recursivelyUncacheFiberNode(node : Instance | TextInstance) {
62
- if (typeof node === 'number') { // Leaf node (eg text)
63
+function recursivelyUncacheFiberNode(node: Instance | TextInstance) {
64
+ if (typeof node === 'number') {
65
+ // Leaf node (eg text)
66
uncacheFiberNode(node);
67
} else {
65
- uncacheFiberNode((node : any)._nativeTag);
68
+ uncacheFiberNode((node: any)._nativeTag);
69
67
- (node : any)._children.forEach(recursivelyUncacheFiberNode);
70
+ (node: any)._children.forEach(recursivelyUncacheFiberNode);
71
}
72
}
73
74
const NativeRenderer = ReactFiberReconciler({
75
appendChild(
73
- parentInstance : Instance | Container,
74
- child : Instance | TextInstance
75
- ) : void {
76
+ parentInstance: Instance | Container,
77
+ child: Instance | TextInstance,
78
+ ): void {
79
if (typeof parentInstance === 'number') {
80
// Root container
81
UIManager.setChildren(
82
parentInstance, // containerTag
80
- [(child : any)._nativeTag] // reactTags
83
+ [(child: any)._nativeTag], // reactTags
84
);
85
} else {
86
const children = parentInstance._children;
@@ -88,22 +91,25 @@ const NativeRenderer = ReactFiberReconciler({
91
parentInstance._nativeTag, // containerTag
92
[], // moveFromIndices
93
[], // moveToIndices
91
- [(child : any)._nativeTag], // addChildReactTags
94
+ [(child: any)._nativeTag], // addChildReactTags
95
[children.length - 1], // addAtIndices
96
[], // removeAtIndices
97
);
98
}
99
},
100
98
- appendInitialChild(parentInstance : Instance, child : Instance | TextInstance) : void {
101
+ appendInitialChild(
102
+ parentInstance: Instance,
103
+ child: Instance | TextInstance,
104
+ ): void {
105
parentInstance._children.push(child);
106
},
107
108
commitTextUpdate(
103
- textInstance : TextInstance,
104
- oldText : string,
105
- newText : string
106
- ) : void {
109
+ textInstance: TextInstance,
110
+ oldText: string,
111
+ newText: string,
112
+ ): void {
113
UIManager.updateView(
114
textInstance, // reactTag
115
'RCTRawText', // viewName
@@ -112,22 +118,22 @@ const NativeRenderer = ReactFiberReconciler({
118
},
119
120
commitMount(
115
- instance : Instance,
116
- type : string,
117
- newProps : Props,
118
- internalInstanceHandle : Object
119
- ) : void {
121
+ instance: Instance,
122
+ type: string,
123
+ newProps: Props,
124
+ internalInstanceHandle: Object,
125
+ ): void {
126
// Noop
127
},
128
129
commitUpdate(
124
- instance : Instance,
125
- updatePayloadTODO : Object,
126
- type : string,
127
- oldProps : Props,
128
- newProps : Props,
129
- internalInstanceHandle : Object
130
- ) : void {
130
+ instance: Instance,
131
+ updatePayloadTODO: Object,
132
+ type: string,
133
+ oldProps: Props,
134
+ newProps: Props,
135
+ internalInstanceHandle: Object,
136
+ ): void {
137
const viewConfig = instance.viewConfig;
138
139
updateFiberProps(instance._nativeTag, newProps);
@@ -135,23 +141,23 @@ const NativeRenderer = ReactFiberReconciler({
141
const updatePayload = ReactNativeAttributePayload.diff(
142
oldProps,
143
newProps,
138
- viewConfig.validAttributes
144
+ viewConfig.validAttributes,
145
);
146
147
UIManager.updateView(
142
- (instance : any)._nativeTag, // reactTag
148
+ (instance: any)._nativeTag, // reactTag
149
viewConfig.uiViewClassName, // viewName
150
updatePayload, // props
151
);
152
},
153
154
createInstance(
149
- type : string,
150
- props : Props,
151
- rootContainerInstance : Container,
152
- hostContext : {||},
153
- internalInstanceHandle : Object
154
- ) : Instance {
155
+ type: string,
156
+ props: Props,
157
+ rootContainerInstance: Container,
158
+ hostContext: {},
159
+ internalInstanceHandle: Object,
160
+ ): Instance {
161
const tag = ReactNativeTagHandles.allocateTag();
162
const viewConfig = ReactNativeViewConfigRegistry.get(type);
163
@@ -165,7 +171,7 @@ const NativeRenderer = ReactFiberReconciler({
171
172
const updatePayload = ReactNativeAttributePayload.create(
173
props,
168
- viewConfig.validAttributes
174
+ viewConfig.validAttributes,
175
);
176
177
UIManager.createView(
@@ -184,18 +190,18 @@ const NativeRenderer = ReactFiberReconciler({
190
},
191
192
createTextInstance(
187
- text : string,
188
- rootContainerInstance : Container,
189
- hostContext : {||},
190
- internalInstanceHandle : Object,
191
- ) : TextInstance {
193
+ text: string,
194
+ rootContainerInstance: Container,
195
+ hostContext: {},
196
+ internalInstanceHandle: Object,
197
+ ): TextInstance {
198
const tag = ReactNativeTagHandles.allocateTag();
199
200
UIManager.createView(
201
tag, // reactTag
202
'RCTRawText', // viewName
203
rootContainerInstance, // rootTag
198
- {text: text} // props
204
+ {text: text}, // props
205
);
206
207
precacheFiberNode(internalInstanceHandle, tag);
@@ -204,11 +210,11 @@ const NativeRenderer = ReactFiberReconciler({
210
},
211
212
finalizeInitialChildren(
207
- parentInstance : Instance,
208
- type : string,
209
- props : Props,
210
- rootContainerInstance : Container,
211
- ) : boolean {
213
+ parentInstance: Instance,
214
+ type: string,
215
+ props: Props,
216
+ rootContainerInstance: Container,
217
+ ): boolean {
218
// Don't send a no-op message over the bridge.
219
if (parentInstance._children.length === 0) {
220
return false;
@@ -217,24 +223,25 @@ const NativeRenderer = ReactFiberReconciler({
223
// Map from child objects to native tags.
224
// Either way we need to pass a copy of the Array to prevent it from being frozen.
225
const nativeTags = parentInstance._children.map(
220
- (child) => typeof child === 'number'
221
- ? child // Leaf node (eg text)
222
- : child._nativeTag
226
+ child =>
227
+ typeof child === 'number'
228
+ ? child // Leaf node (eg text)
229
+ : child._nativeTag,
230
);
231
232
UIManager.setChildren(
233
parentInstance._nativeTag, // containerTag
227
- nativeTags // reactTags
234
+ nativeTags, // reactTags
235
);
236
237
return false;
238
},
239
233
- getRootHostContext() : {||} {
240
+ getRootHostContext(): {} {
241
return emptyObject;
242
},
243
237
- getChildHostContext() : {||} {
244
+ getChildHostContext(): {} {
245
return emptyObject;
246
},
247
@@ -243,10 +250,10 @@ const NativeRenderer = ReactFiberReconciler({
250
},
251
252
insertBefore(
246
- parentInstance : Instance | Container,
247
- child : Instance | TextInstance,
248
- beforeChild : Instance | TextInstance
249
- ) : void {
253
+ parentInstance: Instance | Container,
254
+ child: Instance | TextInstance,
255
+ beforeChild: Instance | TextInstance,
256
+ ): void {
257
// TODO (bvaughn): Remove this check when...
258
// We create a wrapper object for the container in ReactNative render()
259
// Or we refactor to remove wrapper objects entirely.
@@ -256,7 +263,7 @@ const NativeRenderer = ReactFiberReconciler({
263
'Container does not support insertBefore operation',
264
);
265
259
- const children = (parentInstance : any)._children;
266
+ const children = (parentInstance: any)._children;
267
268
const beforeChildIndex = children.indexOf(beforeChild);
269
const index = children.indexOf(child);
@@ -267,7 +274,7 @@ const NativeRenderer = ReactFiberReconciler({
274
children.splice(beforeChildIndex, 0, child);
275
276
UIManager.manageChildren(
270
- (parentInstance : any)._nativeTag, // containerID
277
+ (parentInstance: any)._nativeTag, // containerID
278
[index], // moveFromIndices
279
[beforeChildIndex], // moveToIndices
280
[], // addChildReactTags
@@ -278,35 +285,35 @@ const NativeRenderer = ReactFiberReconciler({
285
children.splice(beforeChildIndex, 0, child);
286
287
UIManager.manageChildren(
281
- (parentInstance : any)._nativeTag, // containerID
288
+ (parentInstance: any)._nativeTag, // containerID
289
[], // moveFromIndices
290
[], // moveToIndices
284
- [(child : any)._nativeTag], // addChildReactTags
291
+ [(child: any)._nativeTag], // addChildReactTags
292
[beforeChildIndex], // addAtIndices
293
[], // removeAtIndices
294
);
295
}
296
},
297
291
- prepareForCommit() : void {
298
+ prepareForCommit(): void {
299
// Noop
300
},
301
302
prepareUpdate(
296
- instance : Instance,
297
- type : string,
298
- oldProps : Props,
299
- newProps : Props,
300
- rootContainerInstance : Container,
301
- hostContext : {||}
302
- ) : null | Object {
303
+ instance: Instance,
304
+ type: string,
305
+ oldProps: Props,
306
+ newProps: Props,
307
+ rootContainerInstance: Container,
308
+ hostContext: {},
309
+ ): null | Object {
310
return emptyObject;
311
},
312
313
removeChild(
307
- parentInstance : Instance | Container,
308
- child : Instance | TextInstance
309
- ) : void {
314
+ parentInstance: Instance | Container,
315
+ child: Instance | TextInstance,
316
+ ): void {
317
recursivelyUncacheFiberNode(child);
318
319
if (typeof parentInstance === 'number') {
@@ -335,15 +342,15 @@ const NativeRenderer = ReactFiberReconciler({
342
}
343
},
344
338
- resetAfterCommit() : void {
345
+ resetAfterCommit(): void {
346
// Noop
347
},
348
342
- resetTextContent(instance : Instance) : void {
349
+ resetTextContent(instance: Instance): void {
350
// Noop
351
},
352
346
- shouldDeprioritizeSubtree(type : string, props : Props) : boolean {
353
+ shouldDeprioritizeSubtree(type: string, props: Props): boolean {
354
return false;
355
},
356
@@ -351,7 +358,7 @@ const NativeRenderer = ReactFiberReconciler({
358
359
scheduleDeferredCallback: global.requestIdleCallback,
360
354
- shouldSetTextContent(props : Props) : boolean {
361
+ shouldSetTextContent(props: Props): boolean {
362
// TODO (bvaughn) Revisit this decision.
363
// Always returning false simplifies the createInstance() implementation,
364
// But creates an additional child Fiber for raw text children.
@@ -365,25 +372,21 @@ const NativeRenderer = ReactFiberReconciler({
372
});
373
374
ReactGenericBatching.injection.injectFiberBatchedUpdates(
368
- NativeRenderer.batchedUpdates
375
+ NativeRenderer.batchedUpdates,
376
);
377
378
const roots = new Map();
379
373
-findNodeHandle.injection.injectFindNode(
374
- (fiber: Fiber) => {
375
- const instance: any = NativeRenderer.findHostInstance(fiber);
376
- return instance ? instance._nativeTag : null;
377
- }
378
-);
379
-findNodeHandle.injection.injectFindRootNodeID(
380
- (instance) => instance._nativeTag
381
-);
380
+findNodeHandle.injection.injectFindNode((fiber: Fiber) => {
381
+ const instance: any = NativeRenderer.findHostInstance(fiber);
382
+ return instance ? instance._nativeTag : null;
383
+});
384
+findNodeHandle.injection.injectFindRootNodeID(instance => instance._nativeTag);
385
386
const ReactNative = {
387
findNodeHandle,
388
386
- render(element : Element<any>, containerTag : any, callback: ?Function) {
389
+ render(element: Element<any>, containerTag: any, callback: ?Function) {
390
let root = roots.get(containerTag);
391
392
if (!root) {
@@ -397,7 +400,7 @@ const ReactNative = {
400
return NativeRenderer.getPublicRootInstance(root);
401
},
402
400
- unmountComponentAtNode(containerTag : number) {
403
+ unmountComponentAtNode(containerTag: number) {
404
const root = roots.get(containerTag);
405
if (root) {
406
// TODO: Is it safe to reset this now or should I wait since this unmount could be deferred?
@@ -414,12 +417,15 @@ const ReactNative = {
417
UIManager.removeRootView(containerTag);
418
},
419
417
- unstable_createPortal(children: ReactNodeList, containerTag : number, key : ?string = null) {
420
+ unstable_createPortal(
421
+ children: ReactNodeList,
422
+ containerTag: number,
423
+ key: ?string = null,
424
+ ) {
425
return ReactPortal.createPortal(children, containerTag, null, key);
426
},
427
428
unstable_batchedUpdates: ReactGenericBatching.batchedUpdates,
422
-
429
};
430
431
if (typeof injectInternals === 'function') {
src/renderers/native/ReactNativeInjection.js
+3
-3
@@ -42,7 +42,7 @@ function inject() {
42
EventPluginUtils.injection.injectComponentTree(ReactNativeComponentTree);
43
44
ResponderEventPlugin.injection.injectGlobalResponderHandler(
45
- ReactNativeGlobalResponderHandler
45
+ ReactNativeGlobalResponderHandler,
46
);
47
48
/**
@@ -50,8 +50,8 @@ function inject() {
50
* them).
51
*/
52
EventPluginHub.injection.injectEventPluginsByName({
53
- 'ResponderEventPlugin': ResponderEventPlugin,
54
- 'ReactNativeBridgeEventPlugin': ReactNativeBridgeEventPlugin,
53
+ ResponderEventPlugin: ResponderEventPlugin,
54
+ ReactNativeBridgeEventPlugin: ReactNativeBridgeEventPlugin,
55
});
56
}
57
src/renderers/native/ReactNativeMount.js
+23
-29
@@ -47,17 +47,14 @@ TopLevelWrapper.isReactTopLevelWrapper = true;
47
* @param {number} containerTag container element to mount into.
48
* @param {ReactReconcileTransaction} transaction
49
*/
50
-function mountComponentIntoNode(
51
- componentInstance,
52
- containerTag,
53
- transaction) {
50
+function mountComponentIntoNode(componentInstance, containerTag, transaction) {
51
var markup = ReactReconciler.mountComponent(
52
componentInstance,
53
transaction,
54
null,
55
ReactNativeContainerInfo(containerTag),
56
emptyObject,
60
- 0 /* parentDebugID */
57
+ 0 /* parentDebugID */,
58
);
59
componentInstance._renderedComponent._topLevelWrapper = componentInstance;
60
ReactNativeMount._mountImageIntoNode(markup, containerTag);
@@ -70,16 +67,14 @@ function mountComponentIntoNode(
67
* @param {number} rootID ID of the root node.
68
* @param {number} containerTag container element to mount into.
69
*/
73
-function batchedMountComponentIntoNode(
74
- componentInstance,
75
- containerTag) {
70
+function batchedMountComponentIntoNode(componentInstance, containerTag) {
71
var transaction = ReactUpdates.ReactReconcileTransaction.getPooled();
72
transaction.perform(
73
mountComponentIntoNode,
74
null,
75
componentInstance,
76
containerTag,
82
- transaction
77
+ transaction,
78
);
79
ReactUpdates.ReactReconcileTransaction.release(transaction);
80
}
@@ -101,12 +96,11 @@ var ReactNativeMount = {
96
renderComponent: function(
97
nextElement: ReactElement<*>,
98
containerTag: number,
104
- callback?: ?(() => void)
99
+ callback?: ?() => void,
100
): ?ReactComponent<any, any, any> {
106
- var nextWrappedElement = React.createElement(
107
- TopLevelWrapper,
108
- { child: nextElement }
109
- );
101
+ var nextWrappedElement = React.createElement(TopLevelWrapper, {
102
+ child: nextElement,
103
+ });
104
105
var topRootNodeID = containerTag;
106
var prevComponent = ReactNativeMount._instancesByContainerID[topRootNodeID];
@@ -114,7 +108,11 @@ var ReactNativeMount = {
108
var prevWrappedElement = prevComponent._currentElement;
109
var prevElement = prevWrappedElement.props.child;
110
if (shouldUpdateReactComponent(prevElement, nextElement)) {
117
- ReactUpdateQueue.enqueueElementInternal(prevComponent, nextWrappedElement, emptyObject);
111
+ ReactUpdateQueue.enqueueElementInternal(
112
+ prevComponent,
113
+ nextWrappedElement,
114
+ emptyObject,
115
+ );
116
if (callback) {
117
ReactUpdateQueue.enqueueCallbackInternal(prevComponent, callback);
118
}
@@ -136,9 +134,11 @@ var ReactNativeMount = {
134
135
if (callback) {
136
var nonNullCallback = callback;
139
- instance._pendingCallbacks = [function() {
140
- nonNullCallback.call(instance._renderedComponent.getPublicInstance());
141
- }];
137
+ instance._pendingCallbacks = [
138
+ function() {
139
+ nonNullCallback.call(instance._renderedComponent.getPublicInstance());
140
+ },
141
+ ];
142
}
143
144
// The initial render is synchronous but any updates that happen during
@@ -148,7 +148,7 @@ var ReactNativeMount = {
148
ReactUpdates.batchedUpdates(
149
batchedMountComponentIntoNode,
150
instance,
151
- containerTag
151
+ containerTag,
152
);
153
var component = instance._renderedComponent.getPublicInstance();
154
return component;
@@ -158,14 +158,11 @@ var ReactNativeMount = {
158
* @param {View} view View tree image.
159
* @param {number} containerViewID View to insert sub-view into.
160
*/
161
- _mountImageIntoNode: function(mountImage : number, containerID : number) {
161
+ _mountImageIntoNode: function(mountImage: number, containerID: number) {
162
// Since we now know that the `mountImage` has been mounted, we can
163
// mark it as such.
164
var childTag = mountImage;
165
- UIManager.setChildren(
166
- containerID,
167
- [childTag]
168
- );
165
+ UIManager.setChildren(containerID, [childTag]);
166
},
167
168
/**
@@ -176,9 +173,7 @@ var ReactNativeMount = {
173
* asynchronously, it's easier to just have this method be the one that calls
174
* for removal of the view.
175
*/
179
- unmountComponentAtNodeAndRemoveContainer: function(
180
- containerTag: number
181
- ) {
176
+ unmountComponentAtNodeAndRemoveContainer: function(containerTag: number) {
177
ReactNativeMount.unmountComponentAtNode(containerTag);
178
// call back into native to remove all of the subviews from this container
179
UIManager.removeRootView(containerTag);
@@ -221,13 +216,12 @@ var ReactNativeMount = {
216
*/
217
unmountComponentFromNode: function(
218
instance: ReactComponent<any, any, any>,
224
- containerID: number
219
+ containerID: number,
220
) {
221
// Call back into native to remove all of the subviews from this container
222
ReactReconciler.unmountComponent(instance);
223
UIManager.removeSubviewsFromContainerWithID(containerID);
224
},
230
-
225
};
226
227
module.exports = ReactNativeMount;
src/renderers/native/ReactNativeReconcileTransaction.js
+1
-1
@@ -124,7 +124,7 @@ Object.assign(
124
ReactNativeReconcileTransaction.prototype,
125
Transaction,
126
ReactNativeReconcileTransaction,
127
- Mixin
127
+ Mixin,
128
);
129
130
PooledClass.addPoolingTo(ReactNativeReconcileTransaction);
src/renderers/native/ReactNativeStack.js
+5
-8
@@ -25,17 +25,13 @@ ReactNativeStackInjection.inject();
25
var render = function(
26
element: ReactElement<any>,
27
mountInto: number,
28
- callback?: ?(() => void)
28
+ callback?: ?() => void,
29
): ?ReactComponent<any, any, any> {
30
return ReactNativeMount.renderComponent(element, mountInto, callback);
31
};
32
33
-findNodeHandle.injection.injectFindNode(
34
- (instance) => instance.getHostNode()
35
-);
36
-findNodeHandle.injection.injectFindRootNodeID(
37
- (instance) => instance._rootNodeID
38
-);
33
+findNodeHandle.injection.injectFindNode(instance => instance.getHostNode());
34
+findNodeHandle.injection.injectFindRootNodeID(instance => instance._rootNodeID);
35
36
var ReactNative = {
37
hasReactNativeInitialized: false,
@@ -55,7 +51,8 @@ var ReactNative = {
51
/* globals __REACT_DEVTOOLS_GLOBAL_HOOK__ */
52
if (
53
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
58
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') {
54
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function'
55
+) {
56
__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({
57
ComponentTree: {
58
getClosestInstanceFromNode: function(node) {
src/renderers/native/ReactNativeStackInjection.js
+10
-14
@@ -35,44 +35,40 @@ var invariant = require('fbjs/lib/invariant');
35
36
function inject() {
37
ReactGenericBatching.injection.injectStackBatchedUpdates(
38
- ReactUpdates.batchedUpdates
38
+ ReactUpdates.batchedUpdates,
39
);
40
41
ReactUpdates.injection.injectReconcileTransaction(
42
- ReactNativeComponentEnvironment.ReactReconcileTransaction
42
+ ReactNativeComponentEnvironment.ReactReconcileTransaction,
43
);
44
45
- ReactUpdates.injection.injectBatchingStrategy(
46
- ReactDefaultBatchingStrategy
47
- );
45
+ ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy);
46
47
ReactComponentEnvironment.injection.injectEnvironment(
50
- ReactNativeComponentEnvironment
48
+ ReactNativeComponentEnvironment,
49
);
50
53
- var EmptyComponent = (instantiate) => {
51
+ var EmptyComponent = instantiate => {
52
// Can't import View at the top because it depends on React to make its composite
53
var View = require('View');
54
return new ReactSimpleEmptyComponent(
55
React.createElement(View, {
56
collapsable: true,
59
- style: { position: 'absolute' },
57
+ style: {position: 'absolute'},
58
}),
61
- instantiate
59
+ instantiate,
60
);
61
};
62
65
- findNodeHandle.injection.injectFindNode(
66
- (instance) => instance.getHostNode()
67
- );
63
+ findNodeHandle.injection.injectFindNode(instance => instance.getHostNode());
64
findNodeHandle.injection.injectFindRootNodeID(
69
- (instance) => instance._rootNodeID
65
+ instance => instance._rootNodeID,
66
);
67
68
ReactEmptyComponent.injection.injectEmptyComponentFactory(EmptyComponent);
69
70
ReactHostComponent.injection.injectTextComponentClass(
75
- ReactNativeTextComponent
71
+ ReactNativeTextComponent,
72
);
73
ReactHostComponent.injection.injectGenericComponentClass(function(tag) {
74
// Show a nicer error message for non-function tags
src/renderers/native/ReactNativeTagHandles.js
+2
-1
@@ -44,7 +44,8 @@ var ReactNativeTagHandles = {
44
assertRootTag: function(tag: number): void {
45
invariant(
46
this.reactTagIsNativeTopRootID(tag),
47
- 'Expect a native root tag, instead got %s', tag
47
+ 'Expect a native root tag, instead got %s',
48
+ tag,
49
);
50
},
51
src/renderers/native/ReactNativeTextComponent.js
+13
-15
@@ -26,24 +26,25 @@ var ReactNativeTextComponent = function(text) {
26
};
27
28
Object.assign(ReactNativeTextComponent.prototype, {
29
-
30
- mountComponent: function(transaction, hostParent, hostContainerInfo, context) {
29
+ mountComponent: function(
30
+ transaction,
31
+ hostParent,
32
+ hostContainerInfo,
33
+ context,
34
+ ) {
35
// TODO: hostParent should have this context already. Stop abusing context.
36
invariant(
37
context.isInAParentText,
38
'RawText "%s" must be wrapped in an explicit <Text> component.',
35
- this._stringText
39
+ this._stringText,
40
);
41
this._hostParent = hostParent;
42
var tag = ReactNativeTagHandles.allocateTag();
43
this._rootNodeID = tag;
44
var nativeTopRootTag = hostContainerInfo._tag;
41
- UIManager.createView(
42
- tag,
43
- 'RCTRawText',
44
- nativeTopRootTag,
45
- {text: this._stringText}
46
- );
45
+ UIManager.createView(tag, 'RCTRawText', nativeTopRootTag, {
46
+ text: this._stringText,
47
+ });
48
49
ReactNativeComponentTree.precacheNode(this, tag);
50
@@ -60,11 +61,9 @@ Object.assign(ReactNativeTextComponent.prototype, {
61
var nextStringText = '' + nextText;
62
if (nextStringText !== this._stringText) {
63
this._stringText = nextStringText;
63
- UIManager.updateView(
64
- this._rootNodeID,
65
- 'RCTRawText',
66
- {text: this._stringText}
67
- );
64
+ UIManager.updateView(this._rootNodeID, 'RCTRawText', {
65
+ text: this._stringText,
66
+ });
67
}
68
}
69
},
@@ -75,7 +74,6 @@ Object.assign(ReactNativeTextComponent.prototype, {
74
this._stringText = null;
75
this._rootNodeID = 0;
76
},
78
-
77
});
78
79
module.exports = ReactNativeTextComponent;
src/renderers/native/ReactNativeViewConfigRegistry.js
+3
-7
@@ -25,12 +25,12 @@ const viewConfigs = new Map();
25
const prefix = 'topsecret-';
26
27
const ReactNativeViewConfigRegistry = {
28
- register(viewConfig : ReactNativeBaseComponentViewConfig) {
28
+ register(viewConfig: ReactNativeBaseComponentViewConfig) {
29
const name = viewConfig.uiViewClassName;
30
invariant(
31
!viewConfigs.has(name),
32
'Tried to register two views with the same name %s',
33
- name
33
+ name,
34
);
35
const secretName = prefix + name;
36
viewConfigs.set(secretName, viewConfig);
@@ -38,11 +38,7 @@ const ReactNativeViewConfigRegistry = {
38
},
39
get(secretName: string) {
40
const config = viewConfigs.get(secretName);
41
- invariant(
42
- config,
43
- 'View config not found for name %s',
44
- secretName
45
- );
41
+ invariant(config, 'View config not found for name %s', secretName);
42
return config;
43
},
44
};
src/renderers/native/__tests__/ReactNativeAttributePayload-test.js
+151
-156
@@ -15,55 +15,45 @@ var ReactNativePropRegistry = require('ReactNativePropRegistry');
15
var diff = ReactNativeAttributePayload.diff;
16
17
describe('ReactNativeAttributePayload', () => {
18
-
18
it('should work with simple example', () => {
20
- expect(diff(
21
- {a: 1, c: 3},
22
- {b: 2, c: 3},
23
- {a: true, b: true}
24
- )).toEqual({a: null, b: 2});
19
+ expect(diff({a: 1, c: 3}, {b: 2, c: 3}, {a: true, b: true})).toEqual({
20
+ a: null,
21
+ b: 2,
22
+ });
23
});
24
25
it('should skip fields that are equal', () => {
28
- expect(diff(
29
- {a: 1, b: 'two', c: true, d: false, e: undefined, f: 0},
30
- {a: 1, b: 'two', c: true, d: false, e: undefined, f: 0},
31
- {a: true, b: true, c: true, d: true, e: true, f: true}
32
- )).toEqual(null);
26
+ expect(
27
+ diff(
28
+ {a: 1, b: 'two', c: true, d: false, e: undefined, f: 0},
29
+ {a: 1, b: 'two', c: true, d: false, e: undefined, f: 0},
30
+ {a: true, b: true, c: true, d: true, e: true, f: true},
31
+ ),
32
+ ).toEqual(null);
33
});
34
35
it('should remove fields', () => {
36
- expect(diff(
37
- {a: 1},
38
- {},
39
- {a: true}
40
- )).toEqual({a: null});
36
+ expect(diff({a: 1}, {}, {a: true})).toEqual({a: null});
37
});
38
39
it('should remove fields that are set to undefined', () => {
44
- expect(diff(
45
- {a: 1},
46
- {a: undefined},
47
- {a: true}
48
- )).toEqual({a: null});
40
+ expect(diff({a: 1}, {a: undefined}, {a: true})).toEqual({a: null});
41
});
42
43
it('should ignore invalid fields', () => {
52
- expect(diff(
53
- {a: 1},
54
- {b: 2},
55
- {}
56
- )).toEqual(null);
44
+ expect(diff({a: 1}, {b: 2}, {})).toEqual(null);
45
});
46
47
it('should use the diff attribute', () => {
48
var diffA = jest.fn((a, b) => true);
49
var diffB = jest.fn((a, b) => false);
62
- expect(diff(
63
- {a: [1], b: [3]},
64
- {a: [2], b: [4]},
65
- {a: {diff: diffA}, b: {diff: diffB}}
66
- )).toEqual({a: [2]});
50
+ expect(
51
+ diff(
52
+ {a: [1], b: [3]},
53
+ {a: [2], b: [4]},
54
+ {a: {diff: diffA}, b: {diff: diffB}},
55
+ ),
56
+ ).toEqual({a: [2]});
57
expect(diffA).toBeCalledWith([1], [2]);
58
expect(diffB).toBeCalledWith([3], [4]);
59
});
@@ -71,171 +61,176 @@ describe('ReactNativeAttributePayload', () => {
61
it('should not use the diff attribute on addition/removal', () => {
62
var diffA = jest.fn();
63
var diffB = jest.fn();
74
- expect(diff(
75
- {a: [1]},
76
- {b: [2]},
77
- {a: {diff: diffA}, b: {diff: diffB}}
78
- )).toEqual({a: null, b: [2]});
64
+ expect(
65
+ diff({a: [1]}, {b: [2]}, {a: {diff: diffA}, b: {diff: diffB}}),
66
+ ).toEqual({a: null, b: [2]});
67
expect(diffA).not.toBeCalled();
68
expect(diffB).not.toBeCalled();
69
});
70
71
it('should do deep diffs of Objects by default', () => {
84
- expect(diff(
85
- {a: [1], b: {k: [3, 4]}, c: {k: [4, 4]} },
86
- {a: [2], b: {k: [3, 4]}, c: {k: [4, 5]} },
87
- {a: true, b: true, c: true}
88
- )).toEqual({a: [2], c: {k: [4, 5]}});
72
+ expect(
73
+ diff(
74
+ {a: [1], b: {k: [3, 4]}, c: {k: [4, 4]}},
75
+ {a: [2], b: {k: [3, 4]}, c: {k: [4, 5]}},
76
+ {a: true, b: true, c: true},
77
+ ),
78
+ ).toEqual({a: [2], c: {k: [4, 5]}});
79
});
80
81
it('should work with undefined styles', () => {
92
- expect(diff(
93
- { style: { a: '#ffffff', b: 1 } },
94
- { style: undefined },
95
- { style: { b: true } }
96
- )).toEqual({ b: null });
97
- expect(diff(
98
- { style: undefined },
99
- { style: { a: '#ffffff', b: 1 } },
100
- { style: { b: true } }
101
- )).toEqual({ b: 1 });
102
- expect(diff(
103
- { style: undefined },
104
- { style: undefined },
105
- { style: { b: true } }
106
- )).toEqual(null);
82
+ expect(
83
+ diff(
84
+ {style: {a: '#ffffff', b: 1}},
85
+ {style: undefined},
86
+ {style: {b: true}},
87
+ ),
88
+ ).toEqual({b: null});
89
+ expect(
90
+ diff(
91
+ {style: undefined},
92
+ {style: {a: '#ffffff', b: 1}},
93
+ {style: {b: true}},
94
+ ),
95
+ ).toEqual({b: 1});
96
+ expect(
97
+ diff({style: undefined}, {style: undefined}, {style: {b: true}}),
98
+ ).toEqual(null);
99
});
100
101
it('should work with empty styles', () => {
110
- expect(diff(
111
- {a: 1, c: 3},
112
- {},
113
- {a: true, b: true}
114
- )).toEqual({a: null});
115
- expect(diff(
116
- {},
117
- {a: 1, c: 3},
118
- {a: true, b: true}
119
- )).toEqual({a: 1});
120
- expect(diff(
121
- {},
122
- {},
123
- {a: true, b: true}
124
- )).toEqual(null);
102
+ expect(diff({a: 1, c: 3}, {}, {a: true, b: true})).toEqual({a: null});
103
+ expect(diff({}, {a: 1, c: 3}, {a: true, b: true})).toEqual({a: 1});
104
+ expect(diff({}, {}, {a: true, b: true})).toEqual(null);
105
});
106
107
it('should flatten nested styles and predefined styles', () => {
128
- var validStyleAttribute = { someStyle: { foo: true, bar: true } };
108
+ var validStyleAttribute = {someStyle: {foo: true, bar: true}};
109
130
- expect(diff(
131
- {},
132
- { someStyle: [{ foo: 1 }, { bar: 2 }]},
133
- validStyleAttribute
134
- )).toEqual({ foo: 1, bar: 2 });
110
+ expect(
111
+ diff({}, {someStyle: [{foo: 1}, {bar: 2}]}, validStyleAttribute),
112
+ ).toEqual({foo: 1, bar: 2});
113
136
- expect(diff(
137
- { someStyle: [{ foo: 1 }, { bar: 2 }]},
138
- {},
139
- validStyleAttribute
140
- )).toEqual({ foo: null, bar: null });
114
+ expect(
115
+ diff({someStyle: [{foo: 1}, {bar: 2}]}, {}, validStyleAttribute),
116
+ ).toEqual({foo: null, bar: null});
117
118
var barStyle = ReactNativePropRegistry.register({
119
bar: 3,
120
});
121
146
- expect(diff(
147
- {},
148
- { someStyle: [[{ foo: 1 }, { foo: 2 }], barStyle]},
149
- validStyleAttribute
150
- )).toEqual({ foo: 2, bar: 3 });
122
+ expect(
123
+ diff(
124
+ {},
125
+ {someStyle: [[{foo: 1}, {foo: 2}], barStyle]},
126
+ validStyleAttribute,
127
+ ),
128
+ ).toEqual({foo: 2, bar: 3});
129
});
130
131
it('should reset a value to a previous if it is removed', () => {
154
- var validStyleAttribute = { someStyle: { foo: true, bar: true } };
155
-
156
- expect(diff(
157
- { someStyle: [{ foo: 1 }, { foo: 3 }]},
158
- { someStyle: [{ foo: 1 }, { bar: 2 }]},
159
- validStyleAttribute
160
- )).toEqual({ foo: 1, bar: 2 });
132
+ var validStyleAttribute = {someStyle: {foo: true, bar: true}};
133
+
134
+ expect(
135
+ diff(
136
+ {someStyle: [{foo: 1}, {foo: 3}]},
137
+ {someStyle: [{foo: 1}, {bar: 2}]},
138
+ validStyleAttribute,
139
+ ),
140
+ ).toEqual({foo: 1, bar: 2});
141
});
142
143
it('should not clear removed props if they are still in another slot', () => {
164
- var validStyleAttribute = { someStyle: { foo: true, bar: true } };
165
-
166
- expect(diff(
167
- { someStyle: [{}, { foo: 3, bar: 2 }]},
168
- { someStyle: [{ foo: 3 }, { bar: 2 }]},
169
- validStyleAttribute
170
- )).toEqual({ foo: 3 }); // this should ideally be null. heuristic tradeoff.
171
-
172
- expect(diff(
173
- { someStyle: [{}, { foo: 3, bar: 2 }]},
174
- { someStyle: [{ foo: 1, bar: 1 }, { bar: 2 }]},
175
- validStyleAttribute
176
- )).toEqual({ bar: 2, foo: 1 });
144
+ var validStyleAttribute = {someStyle: {foo: true, bar: true}};
145
+
146
+ expect(
147
+ diff(
148
+ {someStyle: [{}, {foo: 3, bar: 2}]},
149
+ {someStyle: [{foo: 3}, {bar: 2}]},
150
+ validStyleAttribute,
151
+ ),
152
+ ).toEqual({foo: 3}); // this should ideally be null. heuristic tradeoff.
153
+
154
+ expect(
155
+ diff(
156
+ {someStyle: [{}, {foo: 3, bar: 2}]},
157
+ {someStyle: [{foo: 1, bar: 1}, {bar: 2}]},
158
+ validStyleAttribute,
159
+ ),
160
+ ).toEqual({bar: 2, foo: 1});
161
});
162
163
it('should clear a prop if a later style is explicit null/undefined', () => {
180
- var validStyleAttribute = { someStyle: { foo: true, bar: true } };
181
- expect(diff(
182
- { someStyle: [{}, { foo: 3, bar: 2 }]},
183
- { someStyle: [{ foo: 1 }, { bar: 2, foo: null }]},
184
- validStyleAttribute
185
- )).toEqual({ foo: null });
186
-
187
- expect(diff(
188
- { someStyle: [{ foo: 3 }, { foo: null, bar: 2 }]},
189
- { someStyle: [{ foo: null }, { bar: 2 }]},
190
- validStyleAttribute
191
- )).toEqual({ foo: null });
192
-
193
- expect(diff(
194
- { someStyle: [{ foo: 1 }, { foo: null }]},
195
- { someStyle: [{ foo: 2 }, { foo: null }]},
196
- validStyleAttribute
197
- )).toEqual({ foo: null }); // this should ideally be null. heuristic.
164
+ var validStyleAttribute = {someStyle: {foo: true, bar: true}};
165
+ expect(
166
+ diff(
167
+ {someStyle: [{}, {foo: 3, bar: 2}]},
168
+ {someStyle: [{foo: 1}, {bar: 2, foo: null}]},
169
+ validStyleAttribute,
170
+ ),
171
+ ).toEqual({foo: null});
172
+
173
+ expect(
174
+ diff(
175
+ {someStyle: [{foo: 3}, {foo: null, bar: 2}]},
176
+ {someStyle: [{foo: null}, {bar: 2}]},
177
+ validStyleAttribute,
178
+ ),
179
+ ).toEqual({foo: null});
180
+
181
+ expect(
182
+ diff(
183
+ {someStyle: [{foo: 1}, {foo: null}]},
184
+ {someStyle: [{foo: 2}, {foo: null}]},
185
+ validStyleAttribute,
186
+ ),
187
+ ).toEqual({foo: null}); // this should ideally be null. heuristic.
188
189
// Test the same case with object equality because an early bailout doesn't
190
// work in this case.
201
- var fooObj = { foo: 3 };
202
- expect(diff(
203
- { someStyle: [{ foo: 1 }, fooObj]},
204
- { someStyle: [{ foo: 2 }, fooObj]},
205
- validStyleAttribute
206
- )).toEqual({ foo: 3 }); // this should ideally be null. heuristic.
207
-
208
- expect(diff(
209
- { someStyle: [{ foo: 1 }, { foo: 3 }]},
210
- { someStyle: [{ foo: 2 }, { foo: undefined }]},
211
- validStyleAttribute
212
- )).toEqual({ foo: null }); // this should ideally be null. heuristic.
191
+ var fooObj = {foo: 3};
192
+ expect(
193
+ diff(
194
+ {someStyle: [{foo: 1}, fooObj]},
195
+ {someStyle: [{foo: 2}, fooObj]},
196
+ validStyleAttribute,
197
+ ),
198
+ ).toEqual({foo: 3}); // this should ideally be null. heuristic.
199
+
200
+ expect(
201
+ diff(
202
+ {someStyle: [{foo: 1}, {foo: 3}]},
203
+ {someStyle: [{foo: 2}, {foo: undefined}]},
204
+ validStyleAttribute,
205
+ ),
206
+ ).toEqual({foo: null}); // this should ideally be null. heuristic.
207
});
208
209
// Function properties are just markers to native that events should be sent.
210
it('should convert functions to booleans', () => {
211
// Note that if the property changes from one function to another, we don't
212
// need to send an update.
219
- expect(diff(
220
- {
221
- a: function() {
222
- return 1;
213
+ expect(
214
+ diff(
215
+ {
216
+ a: function() {
217
+ return 1;
218
+ },
219
+ b: function() {
220
+ return 2;
221
+ },
222
+ c: 3,
223
},
224
- b: function() {
225
- return 2;
224
+ {
225
+ b: function() {
226
+ return 9;
227
+ },
228
+ c: function() {
229
+ return 3;
230
+ },
231
},
227
- c: 3,
228
- },
229
- {
230
- b: function() {
231
- return 9;
232
- },
233
- c: function() {
234
- return 3;
235
- },
236
- },
237
- {a: true, b: true, c: true}
238
- )).toEqual({a: null, c: true});
232
+ {a: true, b: true, c: true},
233
+ ),
234
+ ).toEqual({a: null, c: true});
235
});
240
-
236
});
src/renderers/native/__tests__/ReactNativeEvents-test.js
+12
-12
@@ -33,7 +33,7 @@ it('handles events', () => {
33
expect(RCTEventEmitter.register.mock.calls.length).toBe(1);
34
var EventEmitter = RCTEventEmitter.register.mock.calls[0][0];
35
var View = createReactNativeComponentClass({
36
- validAttributes: { foo: true },
36
+ validAttributes: {foo: true},
37
uiViewClassName: 'View',
38
});
39
@@ -53,7 +53,7 @@ it('handles events', () => {
53
onTouchStart={() => log.push('inner touchstart')}
54
/>
55
</View>,
56
- 1
56
+ 1,
57
);
58
59
expect(UIManager.createView.mock.calls.length).toBe(2);
@@ -61,18 +61,18 @@ it('handles events', () => {
61
// Don't depend on the order of createView() calls.
62
// Stack creates views outside-in; fiber creates them inside-out.
63
var innerTag = UIManager.createView.mock.calls.find(
64
- args => args[3].foo === 'inner'
64
+ args => args[3].foo === 'inner',
65
)[0];
66
67
EventEmitter.receiveTouches(
68
'topTouchStart',
69
[{target: innerTag, identifier: 17}],
70
- [0]
70
+ [0],
71
);
72
EventEmitter.receiveTouches(
73
'topTouchEnd',
74
[{target: innerTag, identifier: 17}],
75
- [0]
75
+ [0],
76
);
77
78
expect(log).toEqual([
@@ -90,13 +90,13 @@ it('handles events', () => {
90
it('handles when a responder is unmounted while a touch sequence is in progress', () => {
91
var EventEmitter = RCTEventEmitter.register.mock.calls[0][0];
92
var View = createReactNativeComponentClass({
93
- validAttributes: { id: true },
93
+ validAttributes: {id: true},
94
uiViewClassName: 'View',
95
});
96
97
function getViewById(id) {
98
return UIManager.createView.mock.calls.find(
99
- args => args[3] && args[3].id === id
99
+ args => args[3] && args[3].id === id,
100
)[0];
101
}
102
@@ -131,13 +131,13 @@ it('handles when a responder is unmounted while a touch sequence is in progress'
131
/>
132
</View>
133
</View>,
134
- 1
134
+ 1,
135
);
136
137
EventEmitter.receiveTouches(
138
'topTouchStart',
139
[{target: getViewById('one'), identifier: 17}],
140
- [0]
140
+ [0],
141
);
142
143
expect(getResponderId()).toBe('one');
@@ -155,7 +155,7 @@ it('handles when a responder is unmounted while a touch sequence is in progress'
155
/>
156
</View>
157
</View>,
158
- 1
158
+ 1,
159
);
160
161
// TODO Verify the onResponderEnd listener has been called (before the unmount)
@@ -165,7 +165,7 @@ it('handles when a responder is unmounted while a touch sequence is in progress'
165
EventEmitter.receiveTouches(
166
'topTouchEnd',
167
[{target: getViewById('two'), identifier: 17}],
168
- [0]
168
+ [0],
169
);
170
171
expect(getResponderId()).toBeNull();
@@ -174,7 +174,7 @@ it('handles when a responder is unmounted while a touch sequence is in progress'
174
EventEmitter.receiveTouches(
175
'topTouchStart',
176
[{target: getViewById('two'), identifier: 17}],
177
- [0]
177
+ [0],
178
);
179
180
expect(getResponderId()).toBe('two');
src/renderers/native/__tests__/ReactNativeMount-test.js
+6
-7
@@ -28,7 +28,7 @@ describe('ReactNative', () => {
28
29
it('should be able to create and render a native component', () => {
30
var View = createReactNativeComponentClass({
31
- validAttributes: { foo: true },
31
+ validAttributes: {foo: true},
32
uiViewClassName: 'View',
33
});
34
@@ -41,7 +41,7 @@ describe('ReactNative', () => {
41
42
it('should be able to create and update a native component', () => {
43
var View = createReactNativeComponentClass({
44
- validAttributes: { foo: true },
44
+ validAttributes: {foo: true},
45
uiViewClassName: 'View',
46
});
47
@@ -57,28 +57,27 @@ describe('ReactNative', () => {
57
expect(UIManager.createView.mock.calls.length).toBe(1);
58
expect(UIManager.setChildren.mock.calls.length).toBe(1);
59
expect(UIManager.manageChildren).not.toBeCalled();
60
- expect(UIManager.updateView).toBeCalledWith(2, 'View', { foo: 'bar' });
60
+ expect(UIManager.updateView).toBeCalledWith(2, 'View', {foo: 'bar'});
61
});
62
63
it('returns the correct instance and calls it in the callback', () => {
64
var View = createReactNativeComponentClass({
65
- validAttributes: { foo: true },
65
+ validAttributes: {foo: true},
66
uiViewClassName: 'View',
67
});
68
69
var a;
70
var b;
71
var c = ReactNative.render(
72
- <View foo="foo" ref={(v) => a = v} />,
72
+ <View foo="foo" ref={v => a = v} />,
73
11,
74
function() {
75
b = this;
76
- }
76
+ },
77
);
78
79
expect(a).toBeTruthy();
80
expect(a).toBe(b);
81
expect(a).toBe(c);
82
});
83
-
83
});
src/renderers/native/createReactNativeComponentClass.js
+2
-2
@@ -28,7 +28,7 @@ type ReactNativeBaseComponentViewConfig = {
28
* @private
29
*/
30
const createReactNativeFiberComponentClass = function(
31
- viewConfig: ReactNativeBaseComponentViewConfig
31
+ viewConfig: ReactNativeBaseComponentViewConfig,
32
): string {
33
return ReactNativeViewConfigRegistry.register(viewConfig);
34
};
@@ -38,7 +38,7 @@ const createReactNativeFiberComponentClass = function(
38
* @private
39
*/
40
const createReactNativeComponentClass = function(
41
- viewConfig: ReactNativeBaseComponentViewConfig
41
+ viewConfig: ReactNativeBaseComponentViewConfig,
42
): ReactClass<any> {
43
const Constructor = function(element) {
44
this._currentElement = element;
src/renderers/native/findNodeHandle.js
+14
-20
@@ -18,7 +18,7 @@ var ReactInstanceMap = require('ReactInstanceMap');
18
var invariant = require('fbjs/lib/invariant');
19
var warning = require('fbjs/lib/warning');
20
21
-import type { ReactInstance } from 'ReactInstanceType';
21
+import type {ReactInstance} from 'ReactInstanceType';
22
23
/**
24
* ReactNative vs ReactWeb
@@ -61,11 +61,11 @@ function findNodeHandle(componentOrHandle: any): ?number {
61
warning(
62
owner._warnedAboutRefsInRender,
63
'%s is accessing findNodeHandle inside its render(). ' +
64
- 'render() should be a pure function of props and state. It should ' +
65
- 'never access something that requires stale data from the previous ' +
66
- 'render, such as refs. Move this logic to componentDidMount and ' +
67
- 'componentDidUpdate instead.',
68
- owner.getName() || 'A component'
64
+ 'render() should be a pure function of props and state. It should ' +
65
+ 'never access something that requires stale data from the previous ' +
66
+ 'render, such as refs. Move this logic to componentDidMount and ' +
67
+ 'componentDidUpdate instead.',
68
+ owner.getName() || 'A component',
69
);
70
71
owner._warnedAboutRefsInRender = true;
@@ -92,27 +92,21 @@ function findNodeHandle(componentOrHandle: any): ?number {
92
return rootNodeID;
93
} else {
94
invariant(
95
- (
96
- // Native
97
- typeof component === 'object' &&
98
- (
99
- '_rootNodeID' in component || // TODO (bvaughn) Clean up once Stack is deprecated
100
- '_nativeTag' in component
101
- )
102
- ) || (
95
+ // Native
96
+ (typeof component === 'object' &&
97
+ ('_rootNodeID' in component || // TODO (bvaughn) Clean up once Stack is deprecated
98
+ '_nativeTag' in component)) ||
99
// Composite
104
- component.render != null &&
105
- typeof component.render === 'function'
106
- ),
100
+ (component.render != null && typeof component.render === 'function'),
101
'findNodeHandle(...): Argument is not a component ' +
108
- '(type: %s, keys: %s)',
102
+ '(type: %s, keys: %s)',
103
typeof component,
110
- Object.keys(component)
104
+ Object.keys(component),
105
);
106
invariant(
107
false,
108
'findNodeHandle(...): Unable to find node handle for unmounted ' +
115
- 'component.'
109
+ 'component.',
110
);
111
}
112
}
src/renderers/noop/ReactNoop.js
+99
-66
@@ -19,8 +19,8 @@
19
20
'use strict';
21
22
-import type { Fiber } from 'ReactFiber';
23
-import type { UpdateQueue } from 'ReactFiberUpdateQueue';
22
+import type {Fiber} from 'ReactFiber';
23
+import type {UpdateQueue} from 'ReactFiberUpdateQueue';
24
25
var ReactFiberReconciler = require('ReactFiberReconciler');
26
var ReactInstanceMap = require('ReactInstanceMap');
@@ -34,17 +34,21 @@ const UPDATE_SIGNAL = {};
34
var scheduledAnimationCallback = null;
35
var scheduledDeferredCallback = null;
36
37
-type Container = { rootID: string, children: Array<Instance | TextInstance> };
38
-type Props = { prop: any, hidden ?: boolean };
39
-type Instance = {| type: string, id: number, children: Array<Instance | TextInstance>, prop: any |};
40
-type TextInstance = {| text: string, id: number |};
37
+type Container = {rootID: string, children: Array<Instance | TextInstance>};
38
+type Props = {prop: any, hidden?: boolean};
39
+type Instance = {|
40
+ type: string,
41
+ id: number,
42
+ children: Array<Instance | TextInstance>,
43
+ prop: any,
44
+|};
45
+type TextInstance = {|text: string, id: number|};
46
47
var instanceCounter = 0;
48
49
var failInBeginPhase = false;
50
51
var NoopRenderer = ReactFiberReconciler({
47
-
52
getRootHostContext() {
53
if (failInBeginPhase) {
54
throw new Error('Error in host config.');
@@ -60,7 +64,7 @@ var NoopRenderer = ReactFiberReconciler({
64
return instance;
65
},
66
63
- createInstance(type : string, props : Props) : Instance {
67
+ createInstance(type: string, props: Props): Instance {
68
const inst = {
69
id: instanceCounter++,
70
type: type,
@@ -68,60 +72,83 @@ var NoopRenderer = ReactFiberReconciler({
72
prop: props.prop,
73
};
74
// Hide from unit tests
71
- Object.defineProperty(inst, 'id', { value: inst.id, enumerable: false });
75
+ Object.defineProperty(inst, 'id', {value: inst.id, enumerable: false});
76
return inst;
77
},
78
75
- appendInitialChild(parentInstance : Instance, child : Instance | TextInstance) : void {
79
+ appendInitialChild(
80
+ parentInstance: Instance,
81
+ child: Instance | TextInstance,
82
+ ): void {
83
parentInstance.children.push(child);
84
},
85
79
- finalizeInitialChildren(domElement : Instance, type : string, props : Props) : boolean {
86
+ finalizeInitialChildren(
87
+ domElement: Instance,
88
+ type: string,
89
+ props: Props,
90
+ ): boolean {
91
return false;
92
},
93
83
- prepareUpdate(instance : Instance, type : string, oldProps : Props, newProps : Props) : null | {} {
94
+ prepareUpdate(
95
+ instance: Instance,
96
+ type: string,
97
+ oldProps: Props,
98
+ newProps: Props,
99
+ ): null | {} {
100
return UPDATE_SIGNAL;
101
},
102
87
- commitMount(instance : Instance, type : string, newProps : Props) : void {
103
+ commitMount(instance: Instance, type: string, newProps: Props): void {
104
// Noop
105
},
106
91
- commitUpdate(instance : Instance, updatePayload : Object, type : string, oldProps : Props, newProps : Props) : void {
107
+ commitUpdate(
108
+ instance: Instance,
109
+ updatePayload: Object,
110
+ type: string,
111
+ oldProps: Props,
112
+ newProps: Props,
113
+ ): void {
114
instance.prop = newProps.prop;
115
},
116
95
- shouldSetTextContent(props : Props) : boolean {
96
- return (
97
- typeof props.children === 'string' ||
98
- typeof props.children === 'number'
99
- );
117
+ shouldSetTextContent(props: Props): boolean {
118
+ return typeof props.children === 'string' ||
119
+ typeof props.children === 'number';
120
},
121
102
- resetTextContent(instance : Instance) : void {},
122
+ resetTextContent(instance: Instance): void {},
123
104
- shouldDeprioritizeSubtree(type : string, props : Props) : boolean {
124
+ shouldDeprioritizeSubtree(type: string, props: Props): boolean {
125
return !!props.hidden;
126
},
127
128
createTextInstance(
109
- text : string,
110
- rootContainerInstance : Container,
111
- hostContext : Object,
112
- internalInstanceHandle : Object
113
- ) : TextInstance {
114
- var inst = { text : text, id: instanceCounter++ };
129
+ text: string,
130
+ rootContainerInstance: Container,
131
+ hostContext: Object,
132
+ internalInstanceHandle: Object,
133
+ ): TextInstance {
134
+ var inst = {text: text, id: instanceCounter++};
135
// Hide from unit tests
116
- Object.defineProperty(inst, 'id', { value: inst.id, enumerable: false });
136
+ Object.defineProperty(inst, 'id', {value: inst.id, enumerable: false});
137
return inst;
138
},
139
120
- commitTextUpdate(textInstance : TextInstance, oldText : string, newText : string) : void {
140
+ commitTextUpdate(
141
+ textInstance: TextInstance,
142
+ oldText: string,
143
+ newText: string,
144
+ ): void {
145
textInstance.text = newText;
146
},
147
124
- appendChild(parentInstance : Instance | Container, child : Instance | TextInstance) : void {
148
+ appendChild(
149
+ parentInstance: Instance | Container,
150
+ child: Instance | TextInstance,
151
+ ): void {
152
const index = parentInstance.children.indexOf(child);
153
if (index !== -1) {
154
parentInstance.children.splice(index, 1);
@@ -130,10 +157,10 @@ var NoopRenderer = ReactFiberReconciler({
157
},
158
159
insertBefore(
133
- parentInstance : Instance | Container,
134
- child : Instance | TextInstance,
135
- beforeChild : Instance | TextInstance
136
- ) : void {
160
+ parentInstance: Instance | Container,
161
+ child: Instance | TextInstance,
162
+ beforeChild: Instance | TextInstance,
163
+ ): void {
164
const index = parentInstance.children.indexOf(child);
165
if (index !== -1) {
166
parentInstance.children.splice(index, 1);
@@ -145,7 +172,10 @@ var NoopRenderer = ReactFiberReconciler({
172
parentInstance.children.splice(beforeIndex, 0, child);
173
},
174
148
- removeChild(parentInstance : Instance | Container, child : Instance | TextInstance) : void {
175
+ removeChild(
176
+ parentInstance: Instance | Container,
177
+ child: Instance | TextInstance,
178
+ ): void {
179
const index = parentInstance.children.indexOf(child);
180
if (index === -1) {
181
throw new Error('This child does not exist.');
@@ -157,7 +187,7 @@ var NoopRenderer = ReactFiberReconciler({
187
if (scheduledAnimationCallback) {
188
throw new Error(
189
'Scheduling an animation callback twice is excessive. ' +
160
- 'Instead, keep track of whether the callback has already been scheduled.'
190
+ 'Instead, keep track of whether the callback has already been scheduled.',
191
);
192
}
193
scheduledAnimationCallback = callback;
@@ -167,18 +197,15 @@ var NoopRenderer = ReactFiberReconciler({
197
if (scheduledDeferredCallback) {
198
throw new Error(
199
'Scheduling deferred callback twice is excessive. ' +
170
- 'Instead, keep track of whether the callback has already been scheduled.'
200
+ 'Instead, keep track of whether the callback has already been scheduled.',
201
);
202
}
203
scheduledDeferredCallback = callback;
204
},
205
176
- prepareForCommit() : void {
177
- },
178
-
179
- resetAfterCommit() : void {
180
- },
206
+ prepareForCommit(): void {},
207
208
+ resetAfterCommit(): void {},
209
});
210
211
var rootContainers = new Map();
@@ -186,8 +213,7 @@ var roots = new Map();
213
var DEFAULT_ROOT_ID = '<default>';
214
215
var ReactNoop = {
189
-
190
- getChildren(rootID : string = DEFAULT_ROOT_ID) {
216
+ getChildren(rootID: string = DEFAULT_ROOT_ID) {
217
const container = rootContainers.get(rootID);
218
if (container) {
219
return container.children;
@@ -197,14 +223,18 @@ var ReactNoop = {
223
},
224
225
// Shortcut for testing a single root
200
- render(element : ReactElement<any>, callback: ?Function) {
226
+ render(element: ReactElement<any>, callback: ?Function) {
227
ReactNoop.renderToRootWithID(element, DEFAULT_ROOT_ID, callback);
228
},
229
204
- renderToRootWithID(element : ReactElement<any>, rootID : string, callback : ?Function) {
230
+ renderToRootWithID(
231
+ element: ReactElement<any>,
232
+ rootID: string,
233
+ callback: ?Function,
234
+ ) {
235
let root = roots.get(rootID);
236
if (!root) {
207
- const container = { rootID: rootID, children: [] };
237
+ const container = {rootID: rootID, children: []};
238
rootContainers.set(rootID, container);
239
root = NoopRenderer.createContainer(container);
240
roots.set(rootID, root);
@@ -212,7 +242,7 @@ var ReactNoop = {
242
NoopRenderer.updateContainer(element, root, null, callback);
243
},
244
215
- unmountRootWithID(rootID : string) {
245
+ unmountRootWithID(rootID: string) {
246
const root = roots.get(rootID);
247
if (root) {
248
NoopRenderer.updateContainer(null, root, null, () => {
@@ -222,12 +252,14 @@ var ReactNoop = {
252
}
253
},
254
225
- findInstance(componentOrElement : Element | ?ReactComponent<any, any, any>) : null | Instance | TextInstance {
255
+ findInstance(
256
+ componentOrElement: Element | ?ReactComponent<any, any, any>,
257
+ ): null | Instance | TextInstance {
258
if (componentOrElement == null) {
259
return null;
260
}
261
// Unsound duck typing.
230
- const component = (componentOrElement : any);
262
+ const component = (componentOrElement: any);
263
if (typeof component.id === 'number') {
264
return component;
265
}
@@ -244,7 +276,7 @@ var ReactNoop = {
276
cb();
277
},
278
247
- flushDeferredPri(timeout : number = Infinity) {
279
+ flushDeferredPri(timeout: number = Infinity) {
280
var cb = scheduledDeferredCallback;
281
if (cb === null) {
282
return;
@@ -279,7 +311,7 @@ var ReactNoop = {
311
syncUpdates: NoopRenderer.syncUpdates,
312
313
// Logs the current state of the tree.
282
- dumpTree(rootID : string = DEFAULT_ROOT_ID) {
314
+ dumpTree(rootID: string = DEFAULT_ROOT_ID) {
315
const root = roots.get(rootID);
316
const rootContainer = rootContainers.get(rootID);
317
if (!root || !rootContainer) {
@@ -306,15 +338,13 @@ var ReactNoop = {
338
}
339
}
340
}
309
- function logContainer(container : Container, depth) {
341
+ function logContainer(container: Container, depth) {
342
log(' '.repeat(depth) + '- [root#' + container.rootID + ']');
343
logHostInstances(container.children, depth + 1);
344
}
345
314
- function logUpdateQueue(updateQueue : UpdateQueue, depth) {
315
- log(
316
- ' '.repeat(depth + 1) + 'QUEUED UPDATES'
317
- );
346
+ function logUpdateQueue(updateQueue: UpdateQueue, depth) {
347
+ log(' '.repeat(depth + 1) + 'QUEUED UPDATES');
348
const firstUpdate = updateQueue.first;
349
if (!firstUpdate) {
350
return;
@@ -324,30 +354,34 @@ var ReactNoop = {
354
' '.repeat(depth + 1) + '~',
355
firstUpdate && firstUpdate.partialState,
356
firstUpdate.callback ? 'with callback' : '',
327
- '[' + firstUpdate.priorityLevel + ']'
357
+ '[' + firstUpdate.priorityLevel + ']',
358
);
359
var next;
330
- while (next = firstUpdate.next) {
360
+ while ((next = firstUpdate.next)) {
361
log(
362
' '.repeat(depth + 1) + '~',
363
next.partialState,
364
next.callback ? 'with callback' : '',
335
- '[' + firstUpdate.priorityLevel + ']'
365
+ '[' + firstUpdate.priorityLevel + ']',
366
);
367
}
368
}
369
340
- function logFiber(fiber : Fiber, depth) {
370
+ function logFiber(fiber: Fiber, depth) {
371
log(
342
- ' '.repeat(depth) + '- ' + (fiber.type ? fiber.type.name || fiber.type : '[root]'),
343
- '[' + fiber.pendingWorkPriority + (fiber.pendingProps ? '*' : '') + ']'
372
+ ' '.repeat(depth) +
373
+ '- ' +
374
+ (fiber.type ? fiber.type.name || fiber.type : '[root]'),
375
+ '[' + fiber.pendingWorkPriority + (fiber.pendingProps ? '*' : '') + ']',
376
);
377
if (fiber.updateQueue) {
378
logUpdateQueue(fiber.updateQueue, depth);
379
}
380
const childInProgress = fiber.progressedChild;
381
if (childInProgress && childInProgress !== fiber.child) {
350
- log(' '.repeat(depth + 1) + 'IN PROGRESS: ' + fiber.progressedPriority);
382
+ log(
383
+ ' '.repeat(depth + 1) + 'IN PROGRESS: ' + fiber.progressedPriority,
384
+ );
385
logFiber(childInProgress, depth + 1);
386
if (fiber.child) {
387
log(' '.repeat(depth + 1) + 'CURRENT');
@@ -371,7 +405,7 @@ var ReactNoop = {
405
console.log(...bufferedLog);
406
},
407
374
- simulateErrorInHostConfig(fn : () => void) {
408
+ simulateErrorInHostConfig(fn: () => void) {
409
failInBeginPhase = true;
410
try {
411
fn();
@@ -379,7 +413,6 @@ var ReactNoop = {
413
failInBeginPhase = false;
414
}
415
},
382
-
416
};
417
418
module.exports = ReactNoop;
src/renderers/shared/ReactDebugTool.js
+57
-43
@@ -20,22 +20,22 @@ var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
20
var performanceNow = require('fbjs/lib/performanceNow');
21
var warning = require('fbjs/lib/warning');
22
23
-import type { ReactElement } from 'ReactElementType';
24
-import type { DebugID } from 'ReactInstanceType';
25
-import type { Operation } from 'ReactHostOperationHistoryHook';
23
+import type {ReactElement} from 'ReactElementType';
24
+import type {DebugID} from 'ReactInstanceType';
25
+import type {Operation} from 'ReactHostOperationHistoryHook';
26
27
type Hook = any;
28
29
type TimerType =
30
- 'ctor' |
31
- 'render' |
32
- 'componentWillMount' |
33
- 'componentWillUnmount' |
34
- 'componentWillReceiveProps' |
35
- 'shouldComponentUpdate' |
36
- 'componentWillUpdate' |
37
- 'componentDidUpdate' |
38
- 'componentDidMount';
30
+ | 'ctor'
31
+ | 'render'
32
+ | 'componentWillMount'
33
+ | 'componentWillUnmount'
34
+ | 'componentWillReceiveProps'
35
+ | 'shouldComponentUpdate'
36
+ | 'componentWillUpdate'
37
+ | 'componentDidUpdate'
38
+ | 'componentDidMount';
39
40
type Measurement = {
41
timerType: TimerType,
@@ -51,7 +51,7 @@ type TreeSnapshot = {
51
childIDs: Array<DebugID>,
52
ownerID: DebugID,
53
parentID: DebugID,
54
- }
54
+ },
55
};
56
57
type HistoryItem = {
@@ -78,7 +78,7 @@ if (__DEV__) {
78
didHookThrowForEvent[event],
79
'Exception thrown by hook while handling %s: %s',
80
event,
81
- e + '\n' + e.stack
81
+ e + '\n' + e.stack,
82
);
83
didHookThrowForEvent[event] = true;
84
}
@@ -113,22 +113,25 @@ if (__DEV__) {
113
};
114
115
const getTreeSnapshot = function(registeredIDs) {
116
- return registeredIDs.reduce((tree, id) => {
117
- var ownerID = ReactComponentTreeHook.getOwnerID(id);
118
- var parentID = ReactComponentTreeHook.getParentID(id);
119
- tree[id] = {
120
- displayName: ReactComponentTreeHook.getDisplayName(id),
121
- text: ReactComponentTreeHook.getText(id),
122
- updateCount: ReactComponentTreeHook.getUpdateCount(id),
123
- childIDs: ReactComponentTreeHook.getChildIDs(id),
124
- // Text nodes don't have owners but this is close enough.
125
- ownerID: ownerID ||
126
- parentID && ReactComponentTreeHook.getOwnerID(parentID) ||
127
- 0,
128
- parentID,
129
- };
130
- return tree;
131
- }, {});
116
+ return registeredIDs.reduce(
117
+ (tree, id) => {
118
+ var ownerID = ReactComponentTreeHook.getOwnerID(id);
119
+ var parentID = ReactComponentTreeHook.getParentID(id);
120
+ tree[id] = {
121
+ displayName: ReactComponentTreeHook.getDisplayName(id),
122
+ text: ReactComponentTreeHook.getText(id),
123
+ updateCount: ReactComponentTreeHook.getUpdateCount(id),
124
+ childIDs: ReactComponentTreeHook.getChildIDs(id),
125
+ // Text nodes don't have owners but this is close enough.
126
+ ownerID: ownerID ||
127
+ (parentID && ReactComponentTreeHook.getOwnerID(parentID)) ||
128
+ 0,
129
+ parentID,
130
+ };
131
+ return tree;
132
+ },
133
+ {},
134
+ );
135
};
136
137
const resetMeasurements = function() {
@@ -175,11 +178,11 @@ if (__DEV__) {
178
warning(
179
false,
180
'There is an internal error in the React performance measurement code.' +
178
- '\n\nDid not expect %s timer to start while %s timer is still in ' +
179
- 'progress for %s instance.',
181
+ '\n\nDid not expect %s timer to start while %s timer is still in ' +
182
+ 'progress for %s instance.',
183
timerType,
184
currentTimerType || 'no',
182
- (debugID === currentTimerDebugID) ? 'the same' : 'another'
185
+ debugID === currentTimerDebugID ? 'the same' : 'another',
186
);
187
lifeCycleTimerHasWarned = true;
188
}
@@ -197,11 +200,11 @@ if (__DEV__) {
200
warning(
201
false,
202
'There is an internal error in the React performance measurement code. ' +
200
- 'We did not expect %s timer to stop while %s timer is still in ' +
201
- 'progress for %s instance. Please report this as a bug in React.',
203
+ 'We did not expect %s timer to stop while %s timer is still in ' +
204
+ 'progress for %s instance. Please report this as a bug in React.',
205
timerType,
206
currentTimerType || 'no',
204
- (debugID === currentTimerDebugID) ? 'the same' : 'another'
207
+ debugID === currentTimerDebugID ? 'the same' : 'another',
208
);
209
lifeCycleTimerHasWarned = true;
210
}
@@ -209,7 +212,9 @@ if (__DEV__) {
212
currentFlushMeasurements.push({
213
timerType,
214
instanceID: debugID,
212
- duration: performanceNow() - currentTimerStartTime - currentTimerNestedFlushDuration,
215
+ duration: performanceNow() -
216
+ currentTimerStartTime -
217
+ currentTimerNestedFlushDuration,
218
});
219
}
220
currentTimerStartTime = 0;
@@ -233,7 +238,12 @@ if (__DEV__) {
238
};
239
240
const resumeCurrentLifeCycleTimer = function() {
236
- var {startTime, nestedFlushStartTime, debugID, timerType} = lifeCycleTimerStack.pop();
241
+ var {
242
+ startTime,
243
+ nestedFlushStartTime,
244
+ debugID,
245
+ timerType,
246
+ } = lifeCycleTimerStack.pop();
247
var nestedFlushDuration = performanceNow() - nestedFlushStartTime;
248
currentTimerStartTime = startTime;
249
currentTimerNestedFlushDuration += nestedFlushDuration;
@@ -242,8 +252,7 @@ if (__DEV__) {
252
};
253
254
var lastMarkTimeStamp = 0;
245
- var canUsePerformanceMeasure: boolean =
246
- typeof performance !== 'undefined' &&
255
+ var canUsePerformanceMeasure: boolean = typeof performance !== 'undefined' &&
256
typeof performance.mark === 'function' &&
257
typeof performance.clearMarks === 'function' &&
258
typeof performance.measure === 'function' &&
@@ -280,7 +289,8 @@ if (__DEV__) {
289
}
290
291
var markName = `${debugID}::${markType}`;
283
- var displayName = ReactComponentTreeHook.getDisplayName(debugID) || 'Unknown';
292
+ var displayName = ReactComponentTreeHook.getDisplayName(debugID) ||
293
+ 'Unknown';
294
295
// Chrome has an issue of dropping markers recorded too fast:
296
// https://bugs.chromium.org/p/chromium/issues/detail?id=640652
@@ -377,7 +387,11 @@ if (__DEV__) {
387
childDebugIDs.forEach(checkDebugID);
388
emitEvent('onSetChildren', debugID, childDebugIDs);
389
},
380
- onBeforeMountComponent(debugID: DebugID, element: ReactElement, parentDebugID: DebugID): void {
390
+ onBeforeMountComponent(
391
+ debugID: DebugID,
392
+ element: ReactElement,
393
+ parentDebugID: DebugID,
394
+ ): void {
395
checkDebugID(debugID);
396
checkDebugID(parentDebugID, true);
397
emitEvent('onBeforeMountComponent', debugID, element, parentDebugID);
@@ -416,7 +430,7 @@ if (__DEV__) {
430
ReactDebugTool.addHook(ReactInvalidSetStateWarningHook);
431
ReactDebugTool.addHook(ReactComponentTreeHook);
432
var url = (ExecutionEnvironment.canUseDOM && window.location.href) || '';
419
- if ((/[?&]react_perf\b/).test(url)) {
433
+ if (/[?&]react_perf\b/.test(url)) {
434
ReactDebugTool.beginProfiling();
435
}
436
}
src/renderers/shared/ReactPerf.js
+29
-31
@@ -16,7 +16,7 @@ var ReactDebugTool = require('ReactDebugTool');
16
var warning = require('fbjs/lib/warning');
17
var alreadyWarned = false;
18
19
-import type { FlushHistory } from 'ReactDebugTool';
19
+import type {FlushHistory} from 'ReactDebugTool';
20
21
function roundFloat(val, base = 2) {
22
var n = Math.pow(10, base);
@@ -37,7 +37,7 @@ function warnInProduction() {
37
if (typeof console !== 'undefined') {
38
console.error(
39
'ReactPerf is not supported in the production builds of React. ' +
40
- 'To collect measurements, please use the development build of React instead.'
40
+ 'To collect measurements, please use the development build of React instead.',
41
);
42
}
43
}
@@ -60,19 +60,24 @@ function getExclusive(flushHistory = getLastMeasurements()) {
60
var aggregatedStats = {};
61
var affectedIDs = {};
62
63
- function updateAggregatedStats(treeSnapshot, instanceID, timerType, applyUpdate) {
63
+ function updateAggregatedStats(
64
+ treeSnapshot,
65
+ instanceID,
66
+ timerType,
67
+ applyUpdate,
68
+ ) {
69
var {displayName} = treeSnapshot[instanceID];
70
var key = displayName;
71
var stats = aggregatedStats[key];
72
if (!stats) {
73
affectedIDs[key] = {};
69
- stats = aggregatedStats[key] = {
74
+ stats = (aggregatedStats[key] = {
75
key,
76
instanceCount: 0,
77
counts: {},
78
durations: {},
79
totalDuration: 0,
75
- };
80
+ });
81
}
82
if (!stats.durations[timerType]) {
83
stats.durations[timerType] = 0;
@@ -101,9 +106,7 @@ function getExclusive(flushHistory = getLastMeasurements()) {
106
...aggregatedStats[key],
107
instanceCount: Object.keys(affectedIDs[key]).length,
108
}))
104
- .sort((a, b) =>
105
- b.totalDuration - a.totalDuration
106
- );
109
+ .sort((a, b) => b.totalDuration - a.totalDuration);
110
}
111
112
function getInclusive(flushHistory = getLastMeasurements()) {
@@ -122,12 +125,12 @@ function getInclusive(flushHistory = getLastMeasurements()) {
125
var stats = aggregatedStats[key];
126
if (!stats) {
127
affectedIDs[key] = {};
125
- stats = aggregatedStats[key] = {
128
+ stats = (aggregatedStats[key] = {
129
key,
130
instanceCount: 0,
131
inclusiveRenderDuration: 0,
132
renderCount: 0,
130
- };
133
+ });
134
}
135
affectedIDs[key][instanceID] = true;
136
applyUpdate(stats);
@@ -174,9 +177,7 @@ function getInclusive(flushHistory = getLastMeasurements()) {
177
...aggregatedStats[key],
178
instanceCount: Object.keys(affectedIDs[key]).length,
179
}))
177
- .sort((a, b) =>
178
- b.inclusiveRenderDuration - a.inclusiveRenderDuration
179
- );
180
+ .sort((a, b) => b.inclusiveRenderDuration - a.inclusiveRenderDuration);
181
}
182
183
function getWasted(flushHistory = getLastMeasurements()) {
@@ -195,12 +196,12 @@ function getWasted(flushHistory = getLastMeasurements()) {
196
var stats = aggregatedStats[key];
197
if (!stats) {
198
affectedIDs[key] = {};
198
- stats = aggregatedStats[key] = {
199
+ stats = (aggregatedStats[key] = {
200
key,
201
instanceCount: 0,
202
inclusiveRenderDuration: 0,
203
renderCount: 0,
203
- };
204
+ });
205
}
206
affectedIDs[key][instanceID] = true;
207
applyUpdate(stats);
@@ -240,7 +241,7 @@ function getWasted(flushHistory = getLastMeasurements()) {
241
242
// If there was a DOM update below this component, or it has just been
243
// mounted, its render() is not considered wasted.
243
- var { updateCount } = treeSnapshot[instanceID];
244
+ var {updateCount} = treeSnapshot[instanceID];
245
if (isDefinitelyNotWastedByID[instanceID] || updateCount === 0) {
246
return;
247
}
@@ -254,8 +255,7 @@ function getWasted(flushHistory = getLastMeasurements()) {
255
while (nextParentID) {
256
// Any parents rendered during this batch are considered wasted
257
// unless we previously marked them as dirty.
257
- var isWasted =
258
- renderedCompositeIDs[nextParentID] &&
258
+ var isWasted = renderedCompositeIDs[nextParentID] &&
259
!isDefinitelyNotWastedByID[nextParentID];
260
if (isWasted) {
261
updateAggregatedStats(treeSnapshot, nextParentID, stats => {
@@ -272,9 +272,7 @@ function getWasted(flushHistory = getLastMeasurements()) {
272
...aggregatedStats[key],
273
instanceCount: Object.keys(affectedIDs[key]).length,
274
}))
275
- .sort((a, b) =>
276
- b.inclusiveRenderDuration - a.inclusiveRenderDuration
277
- );
275
+ .sort((a, b) => b.inclusiveRenderDuration - a.inclusiveRenderDuration);
276
}
277
278
function getOperations(flushHistory = getLastMeasurements()) {
@@ -317,13 +315,13 @@ function printExclusive(flushHistory?: FlushHistory) {
315
var renderCount = item.counts.render || 0;
316
var renderDuration = item.durations.render || 0;
317
return {
320
- 'Component': key,
318
+ Component: key,
319
'Total time (ms)': roundFloat(totalDuration),
320
'Instance count': instanceCount,
321
'Total render time (ms)': roundFloat(renderDuration),
324
- 'Average render time (ms)': renderCount ?
325
- roundFloat(renderDuration / renderCount) :
326
- undefined,
322
+ 'Average render time (ms)': renderCount
323
+ ? roundFloat(renderDuration / renderCount)
324
+ : undefined,
325
'Render count': renderCount,
326
'Total lifecycle time (ms)': roundFloat(totalDuration - renderDuration),
327
};
@@ -378,10 +376,10 @@ function printOperations(flushHistory?: FlushHistory) {
376
var stats = getOperations(flushHistory);
377
var table = stats.map(stat => ({
378
'Owner > Node': stat.key,
381
- 'Operation': stat.type,
382
- 'Payload': typeof stat.payload === 'object' ?
383
- JSON.stringify(stat.payload) :
384
- stat.payload,
379
+ Operation: stat.type,
380
+ Payload: typeof stat.payload === 'object'
381
+ ? JSON.stringify(stat.payload)
382
+ : stat.payload,
383
'Flush index': stat.flushIndex,
384
'Owner Component ID': stat.ownerID,
385
'DOM Component ID': stat.instanceID,
@@ -394,7 +392,7 @@ function printDOM(measurements: FlushHistory) {
392
warning(
393
warnedAboutPrintDOM,
394
'`ReactPerf.printDOM(...)` is deprecated. Use ' +
397
- '`ReactPerf.printOperations(...)` instead.'
395
+ '`ReactPerf.printOperations(...)` instead.',
396
);
397
warnedAboutPrintDOM = true;
398
return printOperations(measurements);
@@ -405,7 +403,7 @@ function getMeasurementsSummaryMap(measurements: FlushHistory) {
403
warning(
404
warnedAboutGetMeasurementsSummaryMap,
405
'`ReactPerf.getMeasurementsSummaryMap(...)` is deprecated. Use ' +
408
- '`ReactPerf.getWasted(...)` instead.'
406
+ '`ReactPerf.getWasted(...)` instead.',
407
);
408
warnedAboutGetMeasurementsSummaryMap = true;
409
return getWasted(measurements);
src/renderers/shared/__tests__/ReactDebugTool-test.js
+1
-2
@@ -65,8 +65,7 @@ describe('ReactDebugTool', () => {
65
ReactDebugTool.onTestEvent();
66
expectDev(console.error.calls.count()).toBe(1);
67
expectDev(console.error.calls.argsFor(0)[0]).toContain(
68
- 'Exception thrown by hook while handling ' +
69
- 'onTestEvent: Error: Hi.'
68
+ 'Exception thrown by hook while handling ' + 'onTestEvent: Error: Hi.',
69
);
70
71
ReactDebugTool.onTestEvent();
src/renderers/shared/fiber/ReactChildFiber.js
+241
-225
@@ -12,12 +12,12 @@
12
13
'use strict';
14
15
-import type { ReactElement } from 'ReactElementType';
16
-import type { ReactCoroutine, ReactYield } from 'ReactCoroutine';
17
-import type { ReactPortal } from 'ReactPortal';
18
-import type { Fiber } from 'ReactFiber';
19
-import type { ReactInstance } from 'ReactInstanceType';
20
-import type { PriorityLevel } from 'ReactPriorityLevel';
15
+import type {ReactElement} from 'ReactElementType';
16
+import type {ReactCoroutine, ReactYield} from 'ReactCoroutine';
17
+import type {ReactPortal} from 'ReactPortal';
18
+import type {Fiber} from 'ReactFiber';
19
+import type {ReactInstance} from 'ReactInstanceType';
20
+import type {PriorityLevel} from 'ReactPriorityLevel';
21
22
var REACT_ELEMENT_TYPE = require('ReactElementSymbol');
23
var {
@@ -39,7 +39,7 @@ var ReactFeatureFlags = require('ReactFeatureFlags');
39
var ReactCurrentOwner = require('react/lib/ReactCurrentOwner');
40
41
if (__DEV__) {
42
- var { getCurrentFiberStackAddendum } = require('ReactDebugCurrentFiber');
42
+ var {getCurrentFiberStackAddendum} = require('ReactDebugCurrentFiber');
43
var getComponentName = require('getComponentName');
44
var warning = require('fbjs/lib/warning');
45
var didWarnAboutMaps = false;
@@ -77,27 +77,34 @@ function coerceRef(current: Fiber | null, element: ReactElement) {
77
let mixedRef = element.ref;
78
if (mixedRef !== null && typeof mixedRef !== 'function') {
79
if (element._owner) {
80
- const owner : ?(Fiber | ReactInstance) = (element._owner : any);
80
+ const owner: ?(Fiber | ReactInstance) = (element._owner: any);
81
let inst;
82
if (owner) {
83
if (typeof owner.tag === 'number') {
84
- const ownerFiber = ((owner : any) : Fiber);
85
- invariant(ownerFiber.tag === ClassComponent, 'Stateless function components cannot have refs.');
84
+ const ownerFiber = ((owner: any): Fiber);
85
+ invariant(
86
+ ownerFiber.tag === ClassComponent,
87
+ 'Stateless function components cannot have refs.',
88
+ );
89
inst = ownerFiber.stateNode;
90
} else {
91
// Stack
89
- inst = (owner : any).getPublicInstance();
92
+ inst = (owner: any).getPublicInstance();
93
}
94
}
95
invariant(
96
inst,
97
'Missing owner for string ref %s. This error is likely caused by a ' +
95
- 'bug in React. Please file an issue.',
96
- mixedRef
98
+ 'bug in React. Please file an issue.',
99
+ mixedRef,
100
);
101
const stringRef = '' + mixedRef;
102
// Check if previous string ref matches new string ref
100
- if (current !== null && current.ref !== null && current.ref._stringRef === stringRef) {
103
+ if (
104
+ current !== null &&
105
+ current.ref !== null &&
106
+ current.ref._stringRef === stringRef
107
+ ) {
108
return current.ref;
109
}
110
const ref = function(value) {
@@ -115,17 +122,16 @@ function coerceRef(current: Fiber | null, element: ReactElement) {
122
return mixedRef;
123
}
124
118
-function throwOnInvalidObjectType(returnFiber : Fiber, newChild : Object) {
125
+function throwOnInvalidObjectType(returnFiber: Fiber, newChild: Object) {
126
if (returnFiber.type !== 'textarea') {
127
let addendum = '';
128
if (__DEV__) {
122
- addendum =
123
- ' If you meant to render a collection of children, use an array ' +
129
+ addendum = ' If you meant to render a collection of children, use an array ' +
130
'instead or wrap the object using createFragment(object) from the ' +
131
'React add-ons.';
132
const owner = ReactCurrentOwner.owner || returnFiber._debugOwner;
133
if (owner && typeof owner.tag === 'number') {
128
- const name = getComponentName((owner : any));
134
+ const name = getComponentName((owner: any));
135
if (name) {
136
addendum += '\n\nCheck the render method of `' + name + '`.';
137
}
@@ -134,10 +140,10 @@ function throwOnInvalidObjectType(returnFiber : Fiber, newChild : Object) {
140
invariant(
141
false,
142
'Objects are not valid as a React child (found: %s).%s',
137
- Object.prototype.toString.call(newChild) === '[object Object]' ?
138
- 'object with keys {' + Object.keys(newChild).join(', ') + '}' :
139
- newChild,
140
- addendum
143
+ Object.prototype.toString.call(newChild) === '[object Object]'
144
+ ? 'object with keys {' + Object.keys(newChild).join(', ') + '}'
145
+ : newChild,
146
+ addendum,
147
);
148
}
149
}
@@ -147,11 +153,7 @@ function throwOnInvalidObjectType(returnFiber : Fiber, newChild : Object) {
153
// a compiler or we can do it manually. Helpers that don't need this branching
154
// live outside of this function.
155
function ChildReconciler(shouldClone, shouldTrackSideEffects) {
150
-
151
- function deleteChild(
152
- returnFiber : Fiber,
153
- childToDelete : Fiber
154
- ) : void {
156
+ function deleteChild(returnFiber: Fiber, childToDelete: Fiber): void {
157
if (!shouldTrackSideEffects) {
158
// Noop.
159
return;
@@ -171,18 +173,16 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
173
last.nextEffect = childToDelete;
174
returnFiber.progressedLastDeletion = childToDelete;
175
} else {
174
- returnFiber.progressedFirstDeletion =
175
- returnFiber.progressedLastDeletion =
176
- childToDelete;
176
+ returnFiber.progressedFirstDeletion = (returnFiber.progressedLastDeletion = childToDelete);
177
}
178
childToDelete.nextEffect = null;
179
childToDelete.effectTag = Deletion;
180
}
181
182
function deleteRemainingChildren(
183
- returnFiber : Fiber,
184
- currentFirstChild : Fiber | null
185
- ) : null {
183
+ returnFiber: Fiber,
184
+ currentFirstChild: Fiber | null,
185
+ ): null {
186
if (!shouldTrackSideEffects) {
187
// Noop.
188
return null;
@@ -199,13 +199,13 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
199
}
200
201
function mapRemainingChildren(
202
- returnFiber : Fiber,
203
- currentFirstChild : Fiber
204
- ) : Map<string | number, Fiber> {
202
+ returnFiber: Fiber,
203
+ currentFirstChild: Fiber,
204
+ ): Map<string | number, Fiber> {
205
// Add the remaining children to a temporary map so that we can find them by
206
// keys quickly. Implicit (null) keys get added to this set with their index
207
// instead.
208
- const existingChildren : Map<string | number, Fiber> = new Map();
208
+ const existingChildren: Map<string | number, Fiber> = new Map();
209
210
let existingChild = currentFirstChild;
211
while (existingChild !== null) {
@@ -219,7 +219,7 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
219
return existingChildren;
220
}
221
222
- function useFiber(fiber : Fiber, priority : PriorityLevel) : Fiber {
222
+ function useFiber(fiber: Fiber, priority: PriorityLevel): Fiber {
223
// We currently set sibling to null and index to 0 here because it is easy
224
// to forget to do before returning it. E.g. for the single child case.
225
if (shouldClone) {
@@ -239,7 +239,11 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
239
}
240
}
241
242
- function placeChild(newFiber : Fiber, lastPlacedIndex : number, newIndex : number) : number {
242
+ function placeChild(
243
+ newFiber: Fiber,
244
+ lastPlacedIndex: number,
245
+ newIndex: number,
246
+ ): number {
247
newFiber.index = newIndex;
248
if (!shouldTrackSideEffects) {
249
// Noop.
@@ -263,7 +267,7 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
267
}
268
}
269
266
- function placeSingleChild(newFiber : Fiber) : Fiber {
270
+ function placeSingleChild(newFiber: Fiber): Fiber {
271
// This is simpler for the single child case. We only need to do a
272
// placement for inserting new children.
273
if (shouldTrackSideEffects && newFiber.alternate === null) {
@@ -273,10 +277,10 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
277
}
278
279
function updateTextNode(
276
- returnFiber : Fiber,
277
- current : Fiber | null,
278
- textContent : string,
279
- priority : PriorityLevel
280
+ returnFiber: Fiber,
281
+ current: Fiber | null,
282
+ textContent: string,
283
+ priority: PriorityLevel,
284
) {
285
if (current === null || current.tag !== HostText) {
286
// Insert
@@ -293,11 +297,11 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
297
}
298
299
function updateElement(
296
- returnFiber : Fiber,
297
- current : Fiber | null,
298
- element : ReactElement,
299
- priority : PriorityLevel
300
- ) : Fiber {
300
+ returnFiber: Fiber,
301
+ current: Fiber | null,
302
+ element: ReactElement,
303
+ priority: PriorityLevel,
304
+ ): Fiber {
305
if (current === null || current.type !== element.type) {
306
// Insert
307
const created = createFiberFromElement(element, priority);
@@ -319,11 +323,11 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
323
}
324
325
function updateCoroutine(
322
- returnFiber : Fiber,
323
- current : Fiber | null,
324
- coroutine : ReactCoroutine,
325
- priority : PriorityLevel
326
- ) : Fiber {
326
+ returnFiber: Fiber,
327
+ current: Fiber | null,
328
+ coroutine: ReactCoroutine,
329
+ priority: PriorityLevel,
330
+ ): Fiber {
331
// TODO: Should this also compare handler to determine whether to reuse?
332
if (current === null || current.tag !== CoroutineComponent) {
333
// Insert
@@ -340,11 +344,11 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
344
}
345
346
function updateYield(
343
- returnFiber : Fiber,
344
- current : Fiber | null,
345
- yieldNode : ReactYield,
346
- priority : PriorityLevel
347
- ) : Fiber {
347
+ returnFiber: Fiber,
348
+ current: Fiber | null,
349
+ yieldNode: ReactYield,
350
+ priority: PriorityLevel,
351
+ ): Fiber {
352
if (current === null || current.tag !== YieldComponent) {
353
// Insert
354
const created = createFiberFromYield(yieldNode, priority);
@@ -361,11 +365,11 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
365
}
366
367
function updatePortal(
364
- returnFiber : Fiber,
365
- current : Fiber | null,
366
- portal : ReactPortal,
367
- priority : PriorityLevel
368
- ) : Fiber {
368
+ returnFiber: Fiber,
369
+ current: Fiber | null,
370
+ portal: ReactPortal,
371
+ priority: PriorityLevel,
372
+ ): Fiber {
373
if (
374
current === null ||
375
current.tag !== HostPortal ||
@@ -386,11 +390,11 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
390
}
391
392
function updateFragment(
389
- returnFiber : Fiber,
390
- current : Fiber | null,
391
- fragment : Iterable<*>,
392
- priority : PriorityLevel
393
- ) : Fiber {
393
+ returnFiber: Fiber,
394
+ current: Fiber | null,
395
+ fragment: Iterable<*>,
396
+ priority: PriorityLevel,
397
+ ): Fiber {
398
if (current === null || current.tag !== Fragment) {
399
// Insert
400
const created = createFiberFromFragment(fragment, priority);
@@ -406,10 +410,10 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
410
}
411
412
function createChild(
409
- returnFiber : Fiber,
410
- newChild : any,
411
- priority : PriorityLevel
412
- ) : Fiber | null {
413
+ returnFiber: Fiber,
414
+ newChild: any,
415
+ priority: PriorityLevel,
416
+ ): Fiber | null {
417
if (typeof newChild === 'string' || typeof newChild === 'number') {
418
// Text nodes doesn't have keys. If the previous node is implicitly keyed
419
// we can continue to replace it without aborting even if it is not a text
@@ -461,11 +465,11 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
465
}
466
467
function updateSlot(
464
- returnFiber : Fiber,
465
- oldFiber : Fiber | null,
466
- newChild : any,
467
- priority : PriorityLevel
468
- ) : Fiber | null {
468
+ returnFiber: Fiber,
469
+ oldFiber: Fiber | null,
470
+ newChild: any,
471
+ priority: PriorityLevel,
472
+ ): Fiber | null {
473
// Update the fiber if the keys match, otherwise return null.
474
475
const key = oldFiber !== null ? oldFiber.key : null;
@@ -534,13 +538,12 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
538
}
539
540
function updateFromMap(
537
- existingChildren : Map<string | number, Fiber>,
538
- returnFiber : Fiber,
539
- newIdx : number,
540
- newChild : any,
541
- priority : PriorityLevel
542
- ) : Fiber | null {
543
-
541
+ existingChildren: Map<string | number, Fiber>,
542
+ returnFiber: Fiber,
543
+ newIdx: number,
544
+ newChild: any,
545
+ priority: PriorityLevel,
546
+ ): Fiber | null {
547
if (typeof newChild === 'string' || typeof newChild === 'number') {
548
// Text nodes doesn't have keys, so we neither have to check the old nor
549
// new node for the key. If both are text nodes, they match.
@@ -552,14 +555,14 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
555
switch (newChild.$$typeof) {
556
case REACT_ELEMENT_TYPE: {
557
const matchedFiber = existingChildren.get(
555
- newChild.key === null ? newIdx : newChild.key
558
+ newChild.key === null ? newIdx : newChild.key,
559
) || null;
560
return updateElement(returnFiber, matchedFiber, newChild, priority);
561
}
562
563
case REACT_COROUTINE_TYPE: {
564
const matchedFiber = existingChildren.get(
562
- newChild.key === null ? newIdx : newChild.key
565
+ newChild.key === null ? newIdx : newChild.key,
566
) || null;
567
return updateCoroutine(returnFiber, matchedFiber, newChild, priority);
568
}
@@ -573,7 +576,7 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
576
577
case REACT_PORTAL_TYPE: {
578
const matchedFiber = existingChildren.get(
576
- newChild.key === null ? newIdx : newChild.key
579
+ newChild.key === null ? newIdx : newChild.key,
580
) || null;
581
return updatePortal(returnFiber, matchedFiber, newChild, priority);
582
}
@@ -591,9 +594,9 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
594
}
595
596
function warnOnDuplicateKey(
594
- child : mixed,
595
- knownKeys : Set<string> | null
596
- ) : Set<string> | null {
597
+ child: mixed,
598
+ knownKeys: Set<string> | null,
599
+ ): Set<string> | null {
600
if (__DEV__) {
601
if (typeof child !== 'object' || child === null) {
602
return knownKeys;
@@ -618,10 +621,10 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
621
warning(
622
false,
623
'Encountered two children with the same key, ' +
621
- '`%s`. Child keys must be unique; when two children share a key, ' +
622
- 'only the first child will be used.%s',
624
+ '`%s`. Child keys must be unique; when two children share a key, ' +
625
+ 'only the first child will be used.%s',
626
key,
624
- getCurrentFiberStackAddendum()
627
+ getCurrentFiberStackAddendum(),
628
);
629
break;
630
default:
@@ -632,11 +635,11 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
635
}
636
637
function reconcileChildrenArray(
635
- returnFiber : Fiber,
636
- currentFirstChild : Fiber | null,
637
- newChildren : Array<*>,
638
- priority : PriorityLevel) : Fiber | null {
639
-
638
+ returnFiber: Fiber,
639
+ currentFirstChild: Fiber | null,
640
+ newChildren: Array<*>,
641
+ priority: PriorityLevel,
642
+ ): Fiber | null {
643
// This algorithm can't optimize by searching from boths ends since we
644
// don't have backpointers on fibers. I'm trying to see how far we can get
645
// with that model. If it ends up not being worth the tradeoffs, we can
@@ -665,8 +668,8 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
668
}
669
}
670
668
- let resultingFirstChild : Fiber | null = null;
669
- let previousNewFiber : Fiber | null = null;
671
+ let resultingFirstChild: Fiber | null = null;
672
+ let previousNewFiber: Fiber | null = null;
673
674
let oldFiber = currentFirstChild;
675
let lastPlacedIndex = 0;
@@ -683,7 +686,7 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
686
returnFiber,
687
oldFiber,
688
newChildren[newIdx],
686
- priority
689
+ priority,
690
);
691
if (newFiber === null) {
692
// TODO: This breaks on empty slots like null children. That's
@@ -730,7 +733,7 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
733
const newFiber = createChild(
734
returnFiber,
735
newChildren[newIdx],
733
- priority
736
+ priority,
737
);
738
if (!newFiber) {
739
continue;
@@ -757,7 +760,7 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
760
returnFiber,
761
newIdx,
762
newChildren[newIdx],
760
- priority
763
+ priority,
764
);
765
if (newFiber) {
766
if (shouldTrackSideEffects) {
@@ -767,7 +770,7 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
770
// it from the child list so that we don't add it to the deletion
771
// list.
772
existingChildren.delete(
770
- newFiber.key === null ? newIdx : newFiber.key
773
+ newFiber.key === null ? newIdx : newFiber.key,
774
);
775
}
776
}
@@ -791,11 +794,11 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
794
}
795
796
function reconcileChildrenIterator(
794
- returnFiber : Fiber,
795
- currentFirstChild : Fiber | null,
796
- newChildrenIterable : Iterable<*>,
797
- priority : PriorityLevel) : Fiber | null {
798
-
797
+ returnFiber: Fiber,
798
+ currentFirstChild: Fiber | null,
799
+ newChildrenIterable: Iterable<*>,
800
+ priority: PriorityLevel,
801
+ ): Fiber | null {
802
// This is the same implementation as reconcileChildrenArray(),
803
// but using the iterator instead.
804
@@ -803,28 +806,30 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
806
invariant(
807
typeof iteratorFn === 'function',
808
'An object is not an iterable. This error is likely caused by a bug in ' +
806
- 'React. Please file an issue.'
809
+ 'React. Please file an issue.',
810
);
811
812
if (__DEV__) {
813
// Warn about using Maps as children
814
if (typeof newChildrenIterable.entries === 'function') {
812
- const possibleMap = (newChildrenIterable : any);
815
+ const possibleMap = (newChildrenIterable: any);
816
if (possibleMap.entries === iteratorFn) {
817
let mapsAsChildrenAddendum = '';
818
const owner = ReactCurrentOwner.owner || returnFiber._debugOwner;
819
if (owner && typeof owner.tag === 'number') {
817
- const mapsAsChildrenOwnerName = getComponentName((owner : any));
820
+ const mapsAsChildrenOwnerName = getComponentName((owner: any));
821
if (mapsAsChildrenOwnerName) {
819
- mapsAsChildrenAddendum = '\n\nCheck the render method of `' + mapsAsChildrenOwnerName + '`.';
822
+ mapsAsChildrenAddendum = '\n\nCheck the render method of `' +
823
+ mapsAsChildrenOwnerName +
824
+ '`.';
825
}
826
}
827
warning(
828
didWarnAboutMaps,
829
'Using Maps as children is unsupported and will likely yield ' +
825
- 'unexpected results. Convert it to a sequence/iterable of keyed ' +
826
- 'ReactElements instead.%s',
827
- mapsAsChildrenAddendum
830
+ 'unexpected results. Convert it to a sequence/iterable of keyed ' +
831
+ 'ReactElements instead.%s',
832
+ mapsAsChildrenAddendum,
833
);
834
didWarnAboutMaps = true;
835
}
@@ -844,13 +849,10 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
849
}
850
851
const newChildren = iteratorFn.call(newChildrenIterable);
847
- invariant(
848
- newChildren != null,
849
- 'An iterable object provided no iterator.',
850
- );
852
+ invariant(newChildren != null, 'An iterable object provided no iterator.');
853
852
- let resultingFirstChild : Fiber | null = null;
853
- let previousNewFiber : Fiber | null = null;
854
+ let resultingFirstChild: Fiber | null = null;
855
+ let previousNewFiber: Fiber | null = null;
856
857
let oldFiber = currentFirstChild;
858
let lastPlacedIndex = 0;
@@ -858,19 +860,18 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
860
let nextOldFiber = null;
861
862
let step = newChildren.next();
861
- for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) {
863
+ for (
864
+ ;
865
+ oldFiber !== null && !step.done;
866
+ newIdx++, (step = newChildren.next())
867
+ ) {
868
if (oldFiber.index > newIdx) {
869
nextOldFiber = oldFiber;
870
oldFiber = null;
871
} else {
872
nextOldFiber = oldFiber.sibling;
873
}
868
- const newFiber = updateSlot(
869
- returnFiber,
870
- oldFiber,
871
- step.value,
872
- priority
873
- );
874
+ const newFiber = updateSlot(returnFiber, oldFiber, step.value, priority);
875
if (newFiber === null) {
876
// TODO: This breaks on empty slots like null children. That's
877
// unfortunate because it triggers the slow path all the time. We need
@@ -912,12 +913,8 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
913
if (oldFiber === null) {
914
// If we don't have any more existing children we can choose a fast path
915
// since the rest will all be insertions.
915
- for (; !step.done; newIdx++, step = newChildren.next()) {
916
- const newFiber = createChild(
917
- returnFiber,
918
- step.value,
919
- priority
920
- );
916
+ for (; !step.done; newIdx++, (step = newChildren.next())) {
917
+ const newFiber = createChild(returnFiber, step.value, priority);
918
if (newFiber === null) {
919
continue;
920
}
@@ -937,13 +934,13 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
934
const existingChildren = mapRemainingChildren(returnFiber, oldFiber);
935
936
// Keep scanning and use the map to restore deleted items as moves.
940
- for (; !step.done; newIdx++, step = newChildren.next()) {
937
+ for (; !step.done; newIdx++, (step = newChildren.next())) {
938
const newFiber = updateFromMap(
939
existingChildren,
940
returnFiber,
941
newIdx,
942
step.value,
946
- priority
943
+ priority,
944
);
945
if (newFiber !== null) {
946
if (shouldTrackSideEffects) {
@@ -953,7 +950,7 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
950
// it from the child list so that we don't add it to the deletion
951
// list.
952
existingChildren.delete(
956
- newFiber.key === null ? newIdx : newFiber.key
953
+ newFiber.key === null ? newIdx : newFiber.key,
954
);
955
}
956
}
@@ -977,11 +974,11 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
974
}
975
976
function reconcileSingleTextNode(
980
- returnFiber : Fiber,
981
- currentFirstChild : Fiber | null,
982
- textContent : string,
983
- priority : PriorityLevel
984
- ) : Fiber {
977
+ returnFiber: Fiber,
978
+ currentFirstChild: Fiber | null,
979
+ textContent: string,
980
+ priority: PriorityLevel,
981
+ ): Fiber {
982
// There's no need to check for keys on text nodes since we don't have a
983
// way to define them.
984
if (currentFirstChild !== null && currentFirstChild.tag === HostText) {
@@ -1002,11 +999,11 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
999
}
1000
1001
function reconcileSingleElement(
1005
- returnFiber : Fiber,
1006
- currentFirstChild : Fiber | null,
1007
- element : ReactElement,
1008
- priority : PriorityLevel
1009
- ) : Fiber {
1002
+ returnFiber: Fiber,
1003
+ currentFirstChild: Fiber | null,
1004
+ element: ReactElement,
1005
+ priority: PriorityLevel,
1006
+ ): Fiber {
1007
const key = element.key;
1008
let child = currentFirstChild;
1009
while (child !== null) {
@@ -1041,11 +1038,11 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
1038
}
1039
1040
function reconcileSingleCoroutine(
1044
- returnFiber : Fiber,
1045
- currentFirstChild : Fiber | null,
1046
- coroutine : ReactCoroutine,
1047
- priority : PriorityLevel
1048
- ) : Fiber {
1041
+ returnFiber: Fiber,
1042
+ currentFirstChild: Fiber | null,
1043
+ coroutine: ReactCoroutine,
1044
+ priority: PriorityLevel,
1045
+ ): Fiber {
1046
const key = coroutine.key;
1047
let child = currentFirstChild;
1048
while (child !== null) {
@@ -1074,11 +1071,11 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
1071
}
1072
1073
function reconcileSingleYield(
1077
- returnFiber : Fiber,
1078
- currentFirstChild : Fiber | null,
1079
- yieldNode : ReactYield,
1080
- priority : PriorityLevel
1081
- ) : Fiber {
1074
+ returnFiber: Fiber,
1075
+ currentFirstChild: Fiber | null,
1076
+ yieldNode: ReactYield,
1077
+ priority: PriorityLevel,
1078
+ ): Fiber {
1079
// There's no need to check for keys on yields since they're stateless.
1080
let child = currentFirstChild;
1081
if (child !== null) {
@@ -1100,11 +1097,11 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
1097
}
1098
1099
function reconcileSinglePortal(
1103
- returnFiber : Fiber,
1104
- currentFirstChild : Fiber | null,
1105
- portal : ReactPortal,
1106
- priority : PriorityLevel
1107
- ) : Fiber {
1100
+ returnFiber: Fiber,
1101
+ currentFirstChild: Fiber | null,
1102
+ portal: ReactPortal,
1103
+ priority: PriorityLevel,
1104
+ ): Fiber {
1105
const key = portal.key;
1106
let child = currentFirstChild;
1107
while (child !== null) {
@@ -1140,11 +1137,11 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
1137
// itself. They will be added to the side-effect list as we pass through the
1138
// children and the parent.
1139
function reconcileChildFibers(
1143
- returnFiber : Fiber,
1144
- currentFirstChild : Fiber | null,
1145
- newChild : any,
1146
- priority : PriorityLevel
1147
- ) : Fiber | null {
1140
+ returnFiber: Fiber,
1141
+ currentFirstChild: Fiber | null,
1142
+ newChild: any,
1143
+ priority: PriorityLevel,
1144
+ ): Fiber | null {
1145
// This function is not recursive.
1146
// If the top level item is an array, we treat it as a set of children,
1147
// not as a fragment. Nested arrays on the other hand will be treated as
@@ -1160,54 +1157,66 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
1157
if (disableNewFiberFeatures) {
1158
switch (newChild.$$typeof) {
1159
case REACT_ELEMENT_TYPE:
1163
- return placeSingleChild(reconcileSingleElement(
1164
- returnFiber,
1165
- currentFirstChild,
1166
- newChild,
1167
- priority
1168
- ));
1160
+ return placeSingleChild(
1161
+ reconcileSingleElement(
1162
+ returnFiber,
1163
+ currentFirstChild,
1164
+ newChild,
1165
+ priority,
1166
+ ),
1167
+ );
1168
1169
case REACT_PORTAL_TYPE:
1171
- return placeSingleChild(reconcileSinglePortal(
1172
- returnFiber,
1173
- currentFirstChild,
1174
- newChild,
1175
- priority
1176
- ));
1170
+ return placeSingleChild(
1171
+ reconcileSinglePortal(
1172
+ returnFiber,
1173
+ currentFirstChild,
1174
+ newChild,
1175
+ priority,
1176
+ ),
1177
+ );
1178
}
1179
} else {
1180
switch (newChild.$$typeof) {
1181
case REACT_ELEMENT_TYPE:
1181
- return placeSingleChild(reconcileSingleElement(
1182
- returnFiber,
1183
- currentFirstChild,
1184
- newChild,
1185
- priority
1186
- ));
1182
+ return placeSingleChild(
1183
+ reconcileSingleElement(
1184
+ returnFiber,
1185
+ currentFirstChild,
1186
+ newChild,
1187
+ priority,
1188
+ ),
1189
+ );
1190
1191
case REACT_COROUTINE_TYPE:
1189
- return placeSingleChild(reconcileSingleCoroutine(
1190
- returnFiber,
1191
- currentFirstChild,
1192
- newChild,
1193
- priority
1194
- ));
1192
+ return placeSingleChild(
1193
+ reconcileSingleCoroutine(
1194
+ returnFiber,
1195
+ currentFirstChild,
1196
+ newChild,
1197
+ priority,
1198
+ ),
1199
+ );
1200
1201
case REACT_YIELD_TYPE:
1197
- return placeSingleChild(reconcileSingleYield(
1198
- returnFiber,
1199
- currentFirstChild,
1200
- newChild,
1201
- priority
1202
- ));
1202
+ return placeSingleChild(
1203
+ reconcileSingleYield(
1204
+ returnFiber,
1205
+ currentFirstChild,
1206
+ newChild,
1207
+ priority,
1208
+ ),
1209
+ );
1210
1211
case REACT_PORTAL_TYPE:
1205
- return placeSingleChild(reconcileSinglePortal(
1206
- returnFiber,
1207
- currentFirstChild,
1208
- newChild,
1209
- priority
1210
- ));
1212
+ return placeSingleChild(
1213
+ reconcileSinglePortal(
1214
+ returnFiber,
1215
+ currentFirstChild,
1216
+ newChild,
1217
+ priority,
1218
+ ),
1219
+ );
1220
}
1221
}
1222
}
@@ -1219,7 +1228,9 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
1228
case ClassComponent: {
1229
if (__DEV__) {
1230
const instance = returnFiber.stateNode;
1222
- if (instance.render._isMockFunction && typeof newChild === 'undefined') {
1231
+ if (
1232
+ instance.render._isMockFunction && typeof newChild === 'undefined'
1233
+ ) {
1234
// We allow auto-mocks to proceed as if they're
1235
// returning null.
1236
break;
@@ -1229,8 +1240,8 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
1240
invariant(
1241
newChild === null || newChild === false,
1242
'%s.render(): A valid React element (or null) must be returned. ' +
1232
- 'You may have returned undefined, an array or some other ' +
1233
- 'invalid object.',
1243
+ 'You may have returned undefined, an array or some other ' +
1244
+ 'invalid object.',
1245
Component.displayName || Component.name || 'Component',
1246
);
1247
break;
@@ -1241,8 +1252,8 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
1252
invariant(
1253
newChild === null || newChild === false,
1254
'%s(...): A valid React element (or null) must be returned. ' +
1244
- 'You may have returned undefined, an array or some other ' +
1245
- 'invalid object.',
1255
+ 'You may have returned undefined, an array or some other ' +
1256
+ 'invalid object.',
1257
Component.displayName || Component.name || 'Component',
1258
);
1259
break;
@@ -1251,12 +1262,14 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
1262
}
1263
1264
if (typeof newChild === 'string' || typeof newChild === 'number') {
1254
- return placeSingleChild(reconcileSingleTextNode(
1255
- returnFiber,
1256
- currentFirstChild,
1257
- '' + newChild,
1258
- priority
1259
- ));
1265
+ return placeSingleChild(
1266
+ reconcileSingleTextNode(
1267
+ returnFiber,
1268
+ currentFirstChild,
1269
+ '' + newChild,
1270
+ priority,
1271
+ ),
1272
+ );
1273
}
1274
1275
if (isArray(newChild)) {
@@ -1264,7 +1277,7 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
1277
returnFiber,
1278
currentFirstChild,
1279
newChild,
1267
- priority
1280
+ priority,
1281
);
1282
}
1283
@@ -1273,7 +1286,7 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
1286
returnFiber,
1287
currentFirstChild,
1288
newChild,
1276
- priority
1289
+ priority,
1290
);
1291
}
1292
@@ -1303,9 +1316,9 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
1316
invariant(
1317
false,
1318
'%s(...): Nothing was returned from render. This usually means a ' +
1306
- 'return statement is missing. Or, to render nothing, ' +
1307
- 'return null.',
1308
- Component.displayName || Component.name || 'Component'
1319
+ 'return statement is missing. Or, to render nothing, ' +
1320
+ 'return null.',
1321
+ Component.displayName || Component.name || 'Component',
1322
);
1323
}
1324
}
@@ -1324,7 +1337,10 @@ exports.reconcileChildFibersInPlace = ChildReconciler(false, true);
1337
1338
exports.mountChildFibersInPlace = ChildReconciler(false, false);
1339
1327
-exports.cloneChildFibers = function(current : Fiber | null, workInProgress : Fiber) : void {
1340
+exports.cloneChildFibers = function(
1341
+ current: Fiber | null,
1342
+ workInProgress: Fiber,
1343
+): void {
1344
if (!workInProgress.child) {
1345
return;
1346
}
@@ -1346,10 +1362,10 @@ exports.cloneChildFibers = function(current : Fiber | null, workInProgress : Fib
1362
newChild.return = workInProgress;
1363
while (currentChild.sibling !== null) {
1364
currentChild = currentChild.sibling;
1349
- newChild = newChild.sibling = cloneFiber(
1365
+ newChild = (newChild.sibling = cloneFiber(
1366
currentChild,
1351
- currentChild.pendingWorkPriority
1352
- );
1367
+ currentChild.pendingWorkPriority,
1368
+ ));
1369
newChild.return = workInProgress;
1370
}
1371
newChild.sibling = null;
src/renderers/shared/fiber/ReactDebugCurrentFiber.js
+8
-6
@@ -12,16 +12,18 @@
12
13
'use strict';
14
15
-import type { Fiber } from 'ReactFiber';
15
+import type {Fiber} from 'ReactFiber';
16
17
type LifeCyclePhase = 'render' | 'getChildContext';
18
19
if (__DEV__) {
20
var getComponentName = require('getComponentName');
21
- var { getStackAddendumByWorkInProgressFiber } = require('ReactFiberComponentTreeHook');
21
+ var {
22
+ getStackAddendumByWorkInProgressFiber,
23
+ } = require('ReactFiberComponentTreeHook');
24
}
25
24
-function getCurrentFiberOwnerName() : string | null {
26
+function getCurrentFiberOwnerName(): string | null {
27
if (__DEV__) {
28
const fiber = ReactDebugCurrentFiber.current;
29
if (fiber === null) {
@@ -34,7 +36,7 @@ function getCurrentFiberOwnerName() : string | null {
36
return null;
37
}
38
37
-function getCurrentFiberStackAddendum() : string | null {
39
+function getCurrentFiberStackAddendum(): string | null {
40
if (__DEV__) {
41
const fiber = ReactDebugCurrentFiber.current;
42
if (fiber === null) {
@@ -48,8 +50,8 @@ function getCurrentFiberStackAddendum() : string | null {
50
}
51
52
var ReactDebugCurrentFiber = {
51
- current: (null : Fiber | null),
52
- phase: (null : LifeCyclePhase | null),
53
+ current: (null: Fiber | null),
54
+ phase: (null: LifeCyclePhase | null),
55
56
getCurrentFiberOwnerName,
57
getCurrentFiberStackAddendum,
src/renderers/shared/fiber/ReactDebugFiberPerf.js
+62
-70
@@ -10,17 +10,17 @@
10
* @flow
11
*/
12
13
-import type { Fiber } from 'ReactFiber';
13
+import type {Fiber} from 'ReactFiber';
14
15
type MeasurementPhase =
16
- 'componentWillMount' |
17
- 'componentWillUnmount' |
18
- 'componentWillReceiveProps' |
19
- 'shouldComponentUpdate' |
20
- 'componentWillUpdate' |
21
- 'componentDidUpdate' |
22
- 'componentDidMount' |
23
- 'getChildContext';
16
+ | 'componentWillMount'
17
+ | 'componentWillUnmount'
18
+ | 'componentWillReceiveProps'
19
+ | 'shouldComponentUpdate'
20
+ | 'componentWillUpdate'
21
+ | 'componentDidUpdate'
22
+ | 'componentDidMount'
23
+ | 'getChildContext';
24
25
// Trust the developer to only use this with a __DEV__ check
26
let ReactDebugFiberPerf = ((null: any): typeof ReactDebugFiberPerf);
@@ -41,8 +41,7 @@ if (__DEV__) {
41
// Longer prefixes are hard to read in DevTools.
42
const reactEmoji = '\u269B';
43
const warningEmoji = '\u26D4';
44
- const supportsUserTiming =
45
- typeof performance !== 'undefined' &&
44
+ const supportsUserTiming = typeof performance !== 'undefined' &&
45
typeof performance.mark === 'function' &&
46
typeof performance.clearMarks === 'function' &&
47
typeof performance.measure === 'function' &&
@@ -50,44 +49,44 @@ if (__DEV__) {
49
50
// Keep track of current fiber so that we know the path to unwind on pause.
51
// TODO: this looks the same as nextUnitOfWork in scheduler. Can we unify them?
53
- let currentFiber : Fiber | null = null;
52
+ let currentFiber: Fiber | null = null;
53
// If we're in the middle of user code, which fiber and method is it?
54
// Reusing `currentFiber` would be confusing for this because user code fiber
55
// can change during commit phase too, but we don't need to unwind it (since
56
// lifecycles in the commit phase don't resemble a tree).
58
- let currentPhase : MeasurementPhase | null = null;
59
- let currentPhaseFiber : Fiber | null = null;
57
+ let currentPhase: MeasurementPhase | null = null;
58
+ let currentPhaseFiber: Fiber | null = null;
59
// Did lifecycle hook schedule an update? This is often a performance problem,
60
// so we will keep track of it, and include it in the report.
61
// Track commits caused by cascading updates.
63
- let isCommitting : boolean = false;
64
- let hasScheduledUpdateInCurrentCommit : boolean = false;
65
- let hasScheduledUpdateInCurrentPhase : boolean = false;
66
- let commitCountInCurrentWorkLoop : number = 0;
67
- let effectCountInCurrentCommit : number = 0;
62
+ let isCommitting: boolean = false;
63
+ let hasScheduledUpdateInCurrentCommit: boolean = false;
64
+ let hasScheduledUpdateInCurrentPhase: boolean = false;
65
+ let commitCountInCurrentWorkLoop: number = 0;
66
+ let effectCountInCurrentCommit: number = 0;
67
// During commits, we only show a measurement once per method name
68
// to avoid stretch the commit phase with measurement overhead.
70
- const labelsInCurrentCommit : Set<string> = new Set();
69
+ const labelsInCurrentCommit: Set<string> = new Set();
70
72
- const formatMarkName = (markName : string) => {
71
+ const formatMarkName = (markName: string) => {
72
return `${reactEmoji} ${markName}`;
73
};
74
76
- const formatLabel = (label : string, warning : string | null) => {
75
+ const formatLabel = (label: string, warning: string | null) => {
76
const prefix = warning ? `${warningEmoji} ` : `${reactEmoji} `;
77
const suffix = warning ? ` Warning: ${warning}` : '';
78
return `${prefix}${label}${suffix}`;
79
};
80
82
- const beginMark = (markName : string) => {
81
+ const beginMark = (markName: string) => {
82
performance.mark(formatMarkName(markName));
83
};
84
86
- const clearMark = (markName : string) => {
85
+ const clearMark = (markName: string) => {
86
performance.clearMarks(formatMarkName(markName));
87
};
88
90
- const endMark = (label : string, markName : string, warning : string | null) => {
89
+ const endMark = (label: string, markName: string, warning: string | null) => {
90
const formattedMarkName = formatMarkName(markName);
91
const formattedLabel = formatLabel(label, warning);
92
try {
@@ -102,14 +101,14 @@ if (__DEV__) {
101
performance.clearMeasures(formattedLabel);
102
};
103
105
- const getFiberMarkName = (label : string, debugID : number) => {
104
+ const getFiberMarkName = (label: string, debugID: number) => {
105
return `${label} (#${debugID})`;
106
};
107
108
const getFiberLabel = (
110
- componentName : string,
111
- isMounted : boolean,
112
- phase : MeasurementPhase | null,
109
+ componentName: string,
110
+ isMounted: boolean,
111
+ phase: MeasurementPhase | null,
112
) => {
113
if (phase === null) {
114
// These are composite component total time measurements.
@@ -121,11 +120,11 @@ if (__DEV__) {
120
};
121
122
const beginFiberMark = (
124
- fiber : Fiber,
125
- phase : MeasurementPhase | null,
126
- ) : boolean => {
123
+ fiber: Fiber,
124
+ phase: MeasurementPhase | null,
125
+ ): boolean => {
126
const componentName = getComponentName(fiber) || 'Unknown';
128
- const debugID = ((fiber._debugID : any) : number);
127
+ const debugID = ((fiber._debugID: any): number);
128
const isMounted = fiber.alternate !== null;
129
const label = getFiberLabel(componentName, isMounted, phase);
130
@@ -142,9 +141,9 @@ if (__DEV__) {
141
return true;
142
};
143
145
- const clearFiberMark = (fiber : Fiber, phase : MeasurementPhase | null) => {
144
+ const clearFiberMark = (fiber: Fiber, phase: MeasurementPhase | null) => {
145
const componentName = getComponentName(fiber) || 'Unknown';
147
- const debugID = ((fiber._debugID : any) : number);
146
+ const debugID = ((fiber._debugID: any): number);
147
const isMounted = fiber.alternate !== null;
148
const label = getFiberLabel(componentName, isMounted, phase);
149
const markName = getFiberMarkName(label, debugID);
@@ -152,19 +151,19 @@ if (__DEV__) {
151
};
152
153
const endFiberMark = (
155
- fiber : Fiber,
156
- phase : MeasurementPhase | null,
157
- warning : string | null,
154
+ fiber: Fiber,
155
+ phase: MeasurementPhase | null,
156
+ warning: string | null,
157
) => {
158
const componentName = getComponentName(fiber) || 'Unknown';
160
- const debugID = ((fiber._debugID : any) : number);
159
+ const debugID = ((fiber._debugID: any): number);
160
const isMounted = fiber.alternate !== null;
161
const label = getFiberLabel(componentName, isMounted, phase);
162
const markName = getFiberMarkName(label, debugID);
163
endMark(label, markName, warning);
164
};
165
167
- const shouldIgnoreFiber = (fiber : Fiber) : boolean => {
166
+ const shouldIgnoreFiber = (fiber: Fiber): boolean => {
167
// Host components should be skipped in the timeline.
168
// We could check typeof fiber.type, but does this work with RN?
169
switch (fiber.tag) {
@@ -201,7 +200,7 @@ if (__DEV__) {
200
}
201
};
202
204
- const resumeTimersRecursively = (fiber : Fiber) => {
203
+ const resumeTimersRecursively = (fiber: Fiber) => {
204
if (fiber.return !== null) {
205
resumeTimersRecursively(fiber.return);
206
}
@@ -218,11 +217,11 @@ if (__DEV__) {
217
};
218
219
ReactDebugFiberPerf = {
221
- recordEffect() : void {
220
+ recordEffect(): void {
221
effectCountInCurrentCommit++;
222
},
223
225
- recordScheduleUpdate() : void {
224
+ recordScheduleUpdate(): void {
225
if (isCommitting) {
226
hasScheduledUpdateInCurrentCommit = true;
227
}
@@ -235,7 +234,7 @@ if (__DEV__) {
234
}
235
},
236
238
- startWorkTimer(fiber : Fiber) : void {
237
+ startWorkTimer(fiber: Fiber): void {
238
if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
239
return;
240
}
@@ -247,7 +246,7 @@ if (__DEV__) {
246
fiber._debugIsCurrentlyTiming = true;
247
},
248
250
- cancelWorkTimer(fiber : Fiber) : void {
249
+ cancelWorkTimer(fiber: Fiber): void {
250
if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
251
return;
252
}
@@ -257,7 +256,7 @@ if (__DEV__) {
256
clearFiberMark(fiber, null);
257
},
258
260
- stopWorkTimer(fiber : Fiber) : void {
259
+ stopWorkTimer(fiber: Fiber): void {
260
if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
261
return;
262
}
@@ -270,10 +269,7 @@ if (__DEV__) {
269
endFiberMark(fiber, null, null);
270
},
271
273
- startPhaseTimer(
274
- fiber : Fiber,
275
- phase : MeasurementPhase,
276
- ) : void {
272
+ startPhaseTimer(fiber: Fiber, phase: MeasurementPhase): void {
273
if (!supportsUserTiming) {
274
return;
275
}
@@ -285,21 +281,21 @@ if (__DEV__) {
281
currentPhase = phase;
282
},
283
288
- stopPhaseTimer() : void {
284
+ stopPhaseTimer(): void {
285
if (!supportsUserTiming) {
286
return;
287
}
288
if (currentPhase !== null && currentPhaseFiber !== null) {
293
- const warning = hasScheduledUpdateInCurrentPhase ?
294
- 'Scheduled a cascading update' :
295
- null;
289
+ const warning = hasScheduledUpdateInCurrentPhase
290
+ ? 'Scheduled a cascading update'
291
+ : null;
292
endFiberMark(currentPhaseFiber, currentPhase, warning);
293
}
294
currentPhase = null;
295
currentPhaseFiber = null;
296
},
297
302
- startWorkLoopTimer() : void {
298
+ startWorkLoopTimer(): void {
299
if (!supportsUserTiming) {
300
return;
301
}
@@ -311,13 +307,13 @@ if (__DEV__) {
307
resumeTimers();
308
},
309
314
- stopWorkLoopTimer() : void {
310
+ stopWorkLoopTimer(): void {
311
if (!supportsUserTiming) {
312
return;
313
}
318
- const warning = commitCountInCurrentWorkLoop > 1 ?
319
- 'There were cascading updates' :
320
- null;
314
+ const warning = commitCountInCurrentWorkLoop > 1
315
+ ? 'There were cascading updates'
316
+ : null;
317
commitCountInCurrentWorkLoop = 0;
318
// Pause any measurements until the next loop.
319
pauseTimers();
@@ -328,7 +324,7 @@ if (__DEV__) {
324
);
325
},
326
331
- startCommitTimer() : void {
327
+ startCommitTimer(): void {
328
if (!supportsUserTiming) {
329
return;
330
}
@@ -338,7 +334,7 @@ if (__DEV__) {
334
beginMark('(Committing Changes)');
335
},
336
341
- stopCommitTimer() : void {
337
+ stopCommitTimer(): void {
338
if (!supportsUserTiming) {
339
return;
340
}
@@ -354,14 +350,10 @@ if (__DEV__) {
350
isCommitting = false;
351
labelsInCurrentCommit.clear();
352
357
- endMark(
358
- '(Committing Changes)',
359
- '(Committing Changes)',
360
- warning,
361
- );
353
+ endMark('(Committing Changes)', '(Committing Changes)', warning);
354
},
355
364
- startCommitHostEffectsTimer() : void {
356
+ startCommitHostEffectsTimer(): void {
357
if (!supportsUserTiming) {
358
return;
359
}
@@ -369,7 +361,7 @@ if (__DEV__) {
361
beginMark('(Committing Host Effects)');
362
},
363
372
- stopCommitHostEffectsTimer() : void {
364
+ stopCommitHostEffectsTimer(): void {
365
if (!supportsUserTiming) {
366
return;
367
}
@@ -382,7 +374,7 @@ if (__DEV__) {
374
);
375
},
376
385
- startCommitLifeCyclesTimer() : void {
377
+ startCommitLifeCyclesTimer(): void {
378
if (!supportsUserTiming) {
379
return;
380
}
@@ -390,7 +382,7 @@ if (__DEV__) {
382
beginMark('(Calling Lifecycle Methods)');
383
},
384
393
- stopCommitLifeCyclesTimer() : void {
385
+ stopCommitLifeCyclesTimer(): void {
386
if (!supportsUserTiming) {
387
return;
388
}
src/renderers/shared/fiber/ReactFiber.js
+60
-46
@@ -12,15 +12,15 @@
12
13
'use strict';
14
15
-import type { ReactElement, Source } from 'ReactElementType';
16
-import type { ReactInstance, DebugID } from 'ReactInstanceType';
17
-import type { ReactFragment } from 'ReactTypes';
18
-import type { ReactCoroutine, ReactYield } from 'ReactCoroutine';
19
-import type { ReactPortal } from 'ReactPortal';
20
-import type { TypeOfWork } from 'ReactTypeOfWork';
21
-import type { TypeOfSideEffect } from 'ReactTypeOfSideEffect';
22
-import type { PriorityLevel } from 'ReactPriorityLevel';
23
-import type { UpdateQueue } from 'ReactFiberUpdateQueue';
15
+import type {ReactElement, Source} from 'ReactElementType';
16
+import type {ReactInstance, DebugID} from 'ReactInstanceType';
17
+import type {ReactFragment} from 'ReactTypes';
18
+import type {ReactCoroutine, ReactYield} from 'ReactCoroutine';
19
+import type {ReactPortal} from 'ReactPortal';
20
+import type {TypeOfWork} from 'ReactTypeOfWork';
21
+import type {TypeOfSideEffect} from 'ReactTypeOfSideEffect';
22
+import type {PriorityLevel} from 'ReactPriorityLevel';
23
+import type {UpdateQueue} from 'ReactFiberUpdateQueue';
24
25
var ReactTypeOfWork = require('ReactTypeOfWork');
26
var {
@@ -57,10 +57,10 @@ if (__DEV__) {
57
// be more than one per component.
58
export type Fiber = {
59
// __DEV__ only
60
- _debugID ?: DebugID,
61
- _debugSource ?: Source | null,
62
- _debugOwner ?: Fiber | ReactInstance | null, // Stack compatible
63
- _debugIsCurrentlyTiming ?: boolean,
60
+ _debugID?: DebugID,
61
+ _debugSource?: Source | null,
62
+ _debugOwner?: Fiber | ReactInstance | null, // Stack compatible
63
+ _debugIsCurrentlyTiming?: boolean,
64
65
// These first fields are conceptually members of an Instance. This used to
66
// be split into a separate type and intersected with the other Fiber fields,
@@ -103,7 +103,7 @@ export type Fiber = {
103
104
// The ref last used to attach this node.
105
// I'll avoid adding an owner field for prod and model that as functions.
106
- ref: null | (((handle : mixed) => void) & { _stringRef: ?string }),
106
+ ref: null | (((handle: mixed) => void) & {_stringRef: ?string}),
107
108
// Input is the data coming into process this fiber. Arguments. Props.
109
pendingProps: any, // This type will be more specific once we overload the tag.
@@ -157,7 +157,6 @@ export type Fiber = {
157
// Conceptual aliases
158
// workInProgress : Fiber -> alternate The alternate used for reuse happens
159
// to be the same as work in progress.
160
-
160
};
161
162
if (__DEV__) {
@@ -177,9 +176,8 @@ if (__DEV__) {
176
// to optimize in a non-JIT environment.
177
// 5) It should be easy to port this to a C struct and keep a C implementation
178
// compatible.
180
-var createFiber = function(tag : TypeOfWork, key : null | string) : Fiber {
181
- var fiber : Fiber = {
182
-
179
+var createFiber = function(tag: TypeOfWork, key: null | string): Fiber {
180
+ var fiber: Fiber = {
181
// Instance
182
183
tag: tag,
@@ -217,7 +215,6 @@ var createFiber = function(tag : TypeOfWork, key : null | string) : Fiber {
215
progressedLastDeletion: null,
216
217
alternate: null,
220
-
218
};
219
220
if (__DEV__) {
@@ -230,7 +227,6 @@ var createFiber = function(tag : TypeOfWork, key : null | string) : Fiber {
227
}
228
}
229
233
-
230
return fiber;
231
};
232
@@ -240,7 +236,10 @@ function shouldConstruct(Component) {
236
237
// This is used to create an alternate fiber to do work on.
238
// TODO: Rename to createWorkInProgressFiber or something like that.
243
-exports.cloneFiber = function(fiber : Fiber, priorityLevel : PriorityLevel) : Fiber {
239
+exports.cloneFiber = function(
240
+ fiber: Fiber,
241
+ priorityLevel: PriorityLevel,
242
+): Fiber {
243
// We clone to get a work in progress. That means that this fiber is the
244
// current. To make it safe to reuse that fiber later on as work in progress
245
// we need to reset its work in progress flag now. We don't have an
@@ -298,12 +297,15 @@ exports.cloneFiber = function(fiber : Fiber, priorityLevel : PriorityLevel) : Fi
297
return alt;
298
};
299
301
-exports.createHostRootFiber = function() : Fiber {
300
+exports.createHostRootFiber = function(): Fiber {
301
const fiber = createFiber(HostRoot, null);
302
return fiber;
303
};
304
306
-exports.createFiberFromElement = function(element : ReactElement, priorityLevel : PriorityLevel) : Fiber {
305
+exports.createFiberFromElement = function(
306
+ element: ReactElement,
307
+ priorityLevel: PriorityLevel,
308
+): Fiber {
309
let owner = null;
310
if (__DEV__) {
311
owner = element._owner;
@@ -321,7 +323,10 @@ exports.createFiberFromElement = function(element : ReactElement, priorityLevel
323
return fiber;
324
};
325
324
-exports.createFiberFromFragment = function(elements : ReactFragment, priorityLevel : PriorityLevel) : Fiber {
326
+exports.createFiberFromFragment = function(
327
+ elements: ReactFragment,
328
+ priorityLevel: PriorityLevel,
329
+): Fiber {
330
// TODO: Consider supporting keyed fragments. Technically, we accidentally
331
// support that in the existing React.
332
const fiber = createFiber(Fragment, null);
@@ -330,7 +335,10 @@ exports.createFiberFromFragment = function(elements : ReactFragment, priorityLev
335
return fiber;
336
};
337
333
-exports.createFiberFromText = function(content : string, priorityLevel : PriorityLevel) : Fiber {
338
+exports.createFiberFromText = function(
339
+ content: string,
340
+ priorityLevel: PriorityLevel,
341
+): Fiber {
342
const fiber = createFiber(HostText, null);
343
fiber.pendingProps = content;
344
fiber.pendingWorkPriority = priorityLevel;
@@ -338,23 +346,21 @@ exports.createFiberFromText = function(content : string, priorityLevel : Priorit
346
};
347
348
function createFiberFromElementType(
341
- type : mixed,
342
- key : null | string,
343
- debugOwner : null | Fiber | ReactInstance
344
-) : Fiber {
349
+ type: mixed,
350
+ key: null | string,
351
+ debugOwner: null | Fiber | ReactInstance,
352
+): Fiber {
353
let fiber;
354
if (typeof type === 'function') {
347
- fiber = shouldConstruct(type) ?
348
- createFiber(ClassComponent, key) :
349
- createFiber(IndeterminateComponent, key);
355
+ fiber = shouldConstruct(type)
356
+ ? createFiber(ClassComponent, key)
357
+ : createFiber(IndeterminateComponent, key);
358
fiber.type = type;
359
} else if (typeof type === 'string') {
360
fiber = createFiber(HostComponent, key);
361
fiber.type = type;
362
} else if (
355
- typeof type === 'object' &&
356
- type !== null &&
357
- typeof type.tag === 'number'
363
+ typeof type === 'object' && type !== null && typeof type.tag === 'number'
364
) {
365
// Currently assumed to be a continuation and therefore is a fiber already.
366
// TODO: The yield system is currently broken for updates in some cases.
@@ -362,19 +368,18 @@ function createFiberFromElementType(
368
// the current or a workInProgress? When the continuation gets rendered here
369
// we don't know if we can reuse that fiber or if we need to clone it.
370
// There is probably a clever way to restructure this.
365
- fiber = ((type : any) : Fiber);
371
+ fiber = ((type: any): Fiber);
372
} else {
373
let info = '';
374
if (__DEV__) {
375
if (
376
type === undefined ||
371
- typeof type === 'object' &&
372
- type !== null &&
373
- Object.keys(type).length === 0
377
+ (typeof type === 'object' &&
378
+ type !== null &&
379
+ Object.keys(type).length === 0)
380
) {
375
- info +=
376
- ' You likely forgot to export your component from the file ' +
377
- 'it\'s defined in.';
381
+ info += ' You likely forgot to export your component from the file ' +
382
+ "it's defined in.";
383
}
384
const ownerName = debugOwner ? getComponentName(debugOwner) : null;
385
if (ownerName) {
@@ -384,7 +389,7 @@ function createFiberFromElementType(
389
invariant(
390
false,
391
'Element type is invalid: expected a string (for built-in components) ' +
387
- 'or a class/function (for composite components) but got: %s.%s',
392
+ 'or a class/function (for composite components) but got: %s.%s',
393
type == null ? type : typeof type,
394
info,
395
);
@@ -394,7 +399,10 @@ function createFiberFromElementType(
399
400
exports.createFiberFromElementType = createFiberFromElementType;
401
397
-exports.createFiberFromCoroutine = function(coroutine : ReactCoroutine, priorityLevel : PriorityLevel) : Fiber {
402
+exports.createFiberFromCoroutine = function(
403
+ coroutine: ReactCoroutine,
404
+ priorityLevel: PriorityLevel,
405
+): Fiber {
406
const fiber = createFiber(CoroutineComponent, coroutine.key);
407
fiber.type = coroutine.handler;
408
fiber.pendingProps = coroutine;
@@ -402,12 +410,18 @@ exports.createFiberFromCoroutine = function(coroutine : ReactCoroutine, priority
410
return fiber;
411
};
412
405
-exports.createFiberFromYield = function(yieldNode : ReactYield, priorityLevel : PriorityLevel) : Fiber {
413
+exports.createFiberFromYield = function(
414
+ yieldNode: ReactYield,
415
+ priorityLevel: PriorityLevel,
416
+): Fiber {
417
const fiber = createFiber(YieldComponent, null);
418
return fiber;
419
};
420
410
-exports.createFiberFromPortal = function(portal : ReactPortal, priorityLevel : PriorityLevel) : Fiber {
421
+exports.createFiberFromPortal = function(
422
+ portal: ReactPortal,
423
+ priorityLevel: PriorityLevel,
424
+): Fiber {
425
const fiber = createFiber(HostPortal, portal.key);
426
fiber.pendingProps = portal.children || [];
427
fiber.pendingWorkPriority = priorityLevel;
src/renderers/shared/fiber/ReactFiberBeginWork.js
+148
-83
@@ -12,12 +12,12 @@
12
13
'use strict';
14
15
-import type { ReactCoroutine } from 'ReactCoroutine';
16
-import type { Fiber } from 'ReactFiber';
17
-import type { HostContext } from 'ReactFiberHostContext';
18
-import type { FiberRoot } from 'ReactFiberRoot';
19
-import type { HostConfig } from 'ReactFiberReconciler';
20
-import type { PriorityLevel } from 'ReactPriorityLevel';
15
+import type {ReactCoroutine} from 'ReactCoroutine';
16
+import type {Fiber} from 'ReactFiber';
17
+import type {HostContext} from 'ReactFiberHostContext';
18
+import type {FiberRoot} from 'ReactFiberRoot';
19
+import type {HostConfig} from 'ReactFiberReconciler';
20
+import type {PriorityLevel} from 'ReactPriorityLevel';
21
22
var {
23
mountChildFibersInPlace,
@@ -73,13 +73,16 @@ if (__DEV__) {
73
}
74
75
module.exports = function<T, P, I, TI, PI, C, CX, PL>(
76
- config : HostConfig<T, P, I, TI, PI, C, CX, PL>,
77
- hostContext : HostContext<C, CX>,
78
- scheduleUpdate : (fiber : Fiber, priorityLevel : PriorityLevel) => void,
79
- getPriorityContext : () => PriorityLevel,
76
+ config: HostConfig<T, P, I, TI, PI, C, CX, PL>,
77
+ hostContext: HostContext<C, CX>,
78
+ scheduleUpdate: (fiber: Fiber, priorityLevel: PriorityLevel) => void,
79
+ getPriorityContext: () => PriorityLevel,
80
) {
81
-
82
- const { shouldSetTextContent, useSyncScheduling, shouldDeprioritizeSubtree } = config;
81
+ const {
82
+ shouldSetTextContent,
83
+ useSyncScheduling,
84
+ shouldDeprioritizeSubtree,
85
+ } = config;
86
87
const {
88
pushHostContext,
@@ -112,9 +115,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
115
}
116
117
function clearDeletions(workInProgress) {
115
- workInProgress.progressedFirstDeletion =
116
- workInProgress.progressedLastDeletion =
117
- null;
118
+ workInProgress.progressedFirstDeletion = (workInProgress.progressedLastDeletion = null);
119
}
120
121
function transferDeletions(workInProgress) {
@@ -125,10 +126,20 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
126
127
function reconcileChildren(current, workInProgress, nextChildren) {
128
const priorityLevel = workInProgress.pendingWorkPriority;
128
- reconcileChildrenAtPriority(current, workInProgress, nextChildren, priorityLevel);
129
+ reconcileChildrenAtPriority(
130
+ current,
131
+ workInProgress,
132
+ nextChildren,
133
+ priorityLevel,
134
+ );
135
}
136
131
- function reconcileChildrenAtPriority(current, workInProgress, nextChildren, priorityLevel) {
137
+ function reconcileChildrenAtPriority(
138
+ current,
139
+ workInProgress,
140
+ nextChildren,
141
+ priorityLevel,
142
+ ) {
143
// At this point any memoization is no longer valid since we'll have changed
144
// the children.
145
workInProgress.memoizedProps = null;
@@ -141,7 +152,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
152
workInProgress,
153
workInProgress.child,
154
nextChildren,
144
- priorityLevel
155
+ priorityLevel,
156
);
157
} else if (current.child === workInProgress.child) {
158
// If the current child is the same as the work in progress, it means that
@@ -156,7 +167,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
167
workInProgress,
168
workInProgress.child,
169
nextChildren,
159
- priorityLevel
170
+ priorityLevel,
171
);
172
173
transferDeletions(workInProgress);
@@ -168,7 +179,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
179
workInProgress,
180
workInProgress.child,
181
nextChildren,
171
- priorityLevel
182
+ priorityLevel,
183
);
184
185
transferDeletions(workInProgress);
@@ -184,7 +195,9 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
195
if (nextChildren === null) {
196
nextChildren = workInProgress.memoizedProps;
197
}
187
- } else if (nextChildren === null || workInProgress.memoizedProps === nextChildren) {
198
+ } else if (
199
+ nextChildren === null || workInProgress.memoizedProps === nextChildren
200
+ ) {
201
return bailoutOnAlreadyFinishedWork(current, workInProgress);
202
}
203
reconcileChildren(current, workInProgress, nextChildren);
@@ -192,7 +205,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
205
return workInProgress.child;
206
}
207
195
- function markRef(current : Fiber | null, workInProgress : Fiber) {
208
+ function markRef(current: Fiber | null, workInProgress: Fiber) {
209
const ref = workInProgress.ref;
210
if (ref !== null && (!current || current.ref !== ref)) {
211
// Schedule a Ref effect
@@ -217,8 +230,10 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
230
}
231
// TODO: Disable this before release, since it is not part of the public API
232
// I use this for testing to compare the relative overhead of classes.
220
- if (typeof fn.shouldComponentUpdate === 'function' &&
221
- !fn.shouldComponentUpdate(memoizedProps, nextProps)) {
233
+ if (
234
+ typeof fn.shouldComponentUpdate === 'function' &&
235
+ !fn.shouldComponentUpdate(memoizedProps, nextProps)
236
+ ) {
237
// Memoize props even if shouldComponentUpdate returns false
238
memoizeProps(workInProgress, nextProps);
239
return bailoutOnAlreadyFinishedWork(current, workInProgress);
@@ -243,7 +258,11 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
258
return workInProgress.child;
259
}
260
246
- function updateClassComponent(current : Fiber | null, workInProgress : Fiber, priorityLevel : PriorityLevel) {
261
+ function updateClassComponent(
262
+ current: Fiber | null,
263
+ workInProgress: Fiber,
264
+ priorityLevel: PriorityLevel,
265
+ ) {
266
// Push context providers early to prevent context stack mismatches.
267
// During mounting we don't know the child context yet as the instance doesn't exist.
268
// We will invalidate the child context in finishClassComponent() right after rendering.
@@ -261,16 +280,25 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
280
shouldUpdate = resumeMountClassInstance(workInProgress, priorityLevel);
281
}
282
} else {
264
- shouldUpdate = updateClassInstance(current, workInProgress, priorityLevel);
283
+ shouldUpdate = updateClassInstance(
284
+ current,
285
+ workInProgress,
286
+ priorityLevel,
287
+ );
288
}
266
- return finishClassComponent(current, workInProgress, shouldUpdate, hasContext);
289
+ return finishClassComponent(
290
+ current,
291
+ workInProgress,
292
+ shouldUpdate,
293
+ hasContext,
294
+ );
295
}
296
297
function finishClassComponent(
270
- current : Fiber | null,
271
- workInProgress : Fiber,
272
- shouldUpdate : boolean,
273
- hasContext : boolean,
298
+ current: Fiber | null,
299
+ workInProgress: Fiber,
300
+ shouldUpdate: boolean,
301
+ hasContext: boolean,
302
) {
303
// Refs should update even if shouldComponentUpdate returns false
304
markRef(current, workInProgress);
@@ -305,20 +333,16 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
333
}
334
335
function updateHostRoot(current, workInProgress, priorityLevel) {
308
- const root = (workInProgress.stateNode : FiberRoot);
336
+ const root = (workInProgress.stateNode: FiberRoot);
337
if (root.pendingContext) {
338
pushTopLevelContextObject(
339
workInProgress,
340
root.pendingContext,
313
- root.pendingContext !== root.context
341
+ root.pendingContext !== root.context,
342
);
343
} else if (root.context) {
344
// Should always be set
317
- pushTopLevelContextObject(
318
- workInProgress,
319
- root.context,
320
- false
321
- );
345
+ pushTopLevelContextObject(workInProgress, root.context, false);
346
}
347
348
pushHostContainer(workInProgress, root.containerInfo);
@@ -326,7 +350,14 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
350
const updateQueue = workInProgress.updateQueue;
351
if (updateQueue !== null) {
352
const prevState = workInProgress.memoizedState;
329
- const state = beginUpdateQueue(workInProgress, updateQueue, null, prevState, null, priorityLevel);
353
+ const state = beginUpdateQueue(
354
+ workInProgress,
355
+ updateQueue,
356
+ null,
357
+ prevState,
358
+ null,
359
+ priorityLevel,
360
+ );
361
if (prevState === state) {
362
// If the state is the same as before, that's a bailout because we had
363
// no work matching this priority.
@@ -355,13 +386,15 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
386
invariant(
387
nextProps !== null,
388
'We should always have pending or current props. This error is ' +
358
- 'likely caused by a bug in React. Please file an issue.'
389
+ 'likely caused by a bug in React. Please file an issue.',
390
);
391
}
392
} else if (nextProps === null || memoizedProps === nextProps) {
362
- if (!useSyncScheduling &&
363
- shouldDeprioritizeSubtree(workInProgress.type, memoizedProps) &&
364
- workInProgress.pendingWorkPriority !== OffscreenPriority) {
393
+ if (
394
+ !useSyncScheduling &&
395
+ shouldDeprioritizeSubtree(workInProgress.type, memoizedProps) &&
396
+ workInProgress.pendingWorkPriority !== OffscreenPriority
397
+ ) {
398
// This subtree still has work, but it should be deprioritized so we need
399
// to bail out and not do any work yet.
400
// TODO: It would be better if this tree got its correct priority set
@@ -390,10 +423,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
423
// this in the host environment that also have access to this prop. That
424
// avoids allocating another HostText fiber and traversing it.
425
nextChildren = null;
393
- } else if (
394
- prevProps &&
395
- shouldSetTextContent(prevProps)
396
- ) {
426
+ } else if (prevProps && shouldSetTextContent(prevProps)) {
427
// If we're switching from a direct text child to a normal child, or to
428
// empty, we need to schedule the text content to be reset.
429
workInProgress.effectTag |= ContentReset;
@@ -401,9 +431,11 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
431
432
markRef(current, workInProgress);
433
404
- if (!useSyncScheduling &&
405
- shouldDeprioritizeSubtree(workInProgress.type, nextProps) &&
406
- workInProgress.pendingWorkPriority !== OffscreenPriority) {
434
+ if (
435
+ !useSyncScheduling &&
436
+ shouldDeprioritizeSubtree(workInProgress.type, nextProps) &&
437
+ workInProgress.pendingWorkPriority !== OffscreenPriority
438
+ ) {
439
// If this host component is hidden, we can bail out on the children.
440
// We'll rerender the children later at the lower priority.
441
@@ -419,7 +451,12 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
451
}
452
453
// Reconcile the children and stash them for later work.
422
- reconcileChildrenAtPriority(current, workInProgress, nextChildren, OffscreenPriority);
454
+ reconcileChildrenAtPriority(
455
+ current,
456
+ workInProgress,
457
+ nextChildren,
458
+ OffscreenPriority,
459
+ );
460
memoizeProps(workInProgress, nextProps);
461
workInProgress.child = current !== null ? current.child : null;
462
@@ -460,7 +497,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
497
invariant(
498
current === null,
499
'An indeterminate component should never have mounted. This error is ' +
463
- 'likely caused by a bug in React. Please file an issue.'
500
+ 'likely caused by a bug in React. Please file an issue.',
501
);
502
var fn = workInProgress.type;
503
var props = workInProgress.pendingProps;
@@ -476,7 +513,11 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
513
value = fn(props, context);
514
}
515
479
- if (typeof value === 'object' && value !== null && typeof value.render === 'function') {
516
+ if (
517
+ typeof value === 'object' &&
518
+ value !== null &&
519
+ typeof value.render === 'function'
520
+ ) {
521
// Proceed under the assumption that this is a class instance
522
workInProgress.tag = ClassComponent;
523
@@ -497,7 +538,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
538
warning(
539
!Component.childContextTypes,
540
'%s(...): childContextTypes cannot be defined on a functional component.',
500
- Component.displayName || Component.name || 'Component'
541
+ Component.displayName || Component.name || 'Component',
542
);
543
}
544
if (workInProgress.ref !== null) {
@@ -517,9 +558,9 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
558
warning(
559
false,
560
'Stateless function components cannot be given refs. ' +
520
- 'Attempts to access this ref will fail.%s%s',
561
+ 'Attempts to access this ref will fail.%s%s',
562
info,
522
- ReactDebugCurrentFiber.getCurrentFiberStackAddendum()
563
+ ReactDebugCurrentFiber.getCurrentFiberStackAddendum(),
564
);
565
}
566
}
@@ -531,7 +572,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
572
}
573
574
function updateCoroutineComponent(current, workInProgress) {
534
- var nextCoroutine = (workInProgress.pendingProps : null | ReactCoroutine);
575
+ var nextCoroutine = (workInProgress.pendingProps: null | ReactCoroutine);
576
if (hasContextChanged()) {
577
// Normally we can bail out on props equality but if context has changed
578
// we don't do the bailout and we have to reuse existing props instead.
@@ -540,10 +581,12 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
581
invariant(
582
nextCoroutine !== null,
583
'We should always have pending or current props. This error is ' +
543
- 'likely caused by a bug in React. Please file an issue.'
584
+ 'likely caused by a bug in React. Please file an issue.',
585
);
586
}
546
- } else if (nextCoroutine === null || workInProgress.memoizedProps === nextCoroutine) {
587
+ } else if (
588
+ nextCoroutine === null || workInProgress.memoizedProps === nextCoroutine
589
+ ) {
590
nextCoroutine = workInProgress.memoizedProps;
591
// TODO: When bailing out, we might need to return the stateNode instead
592
// of the child. To check it for work.
@@ -564,7 +607,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
607
workInProgress,
608
workInProgress.stateNode,
609
nextChildren,
567
- priorityLevel
610
+ priorityLevel,
611
);
612
} else if (current.child === workInProgress.child) {
613
clearDeletions(workInProgress);
@@ -573,7 +616,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
616
workInProgress,
617
workInProgress.stateNode,
618
nextChildren,
576
- priorityLevel
619
+ priorityLevel,
620
);
621
622
transferDeletions(workInProgress);
@@ -582,7 +625,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
625
workInProgress,
626
workInProgress.stateNode,
627
nextChildren,
585
- priorityLevel
628
+ priorityLevel,
629
);
630
631
transferDeletions(workInProgress);
@@ -606,10 +649,12 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
649
invariant(
650
nextChildren != null,
651
'We should always have pending or current props. This error is ' +
609
- 'likely caused by a bug in React. Please file an issue.'
652
+ 'likely caused by a bug in React. Please file an issue.',
653
);
654
}
612
- } else if (nextChildren === null || workInProgress.memoizedProps === nextChildren) {
655
+ } else if (
656
+ nextChildren === null || workInProgress.memoizedProps === nextChildren
657
+ ) {
658
return bailoutOnAlreadyFinishedWork(current, workInProgress);
659
}
660
@@ -623,7 +668,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
668
workInProgress,
669
workInProgress.child,
670
nextChildren,
626
- priorityLevel
671
+ priorityLevel,
672
);
673
memoizeProps(workInProgress, nextChildren);
674
markChildAsProgressed(current, workInProgress, priorityLevel);
@@ -653,11 +698,14 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
698
}
699
*/
700
656
- function bailoutOnAlreadyFinishedWork(current, workInProgress : Fiber) : Fiber | null {
701
+ function bailoutOnAlreadyFinishedWork(
702
+ current,
703
+ workInProgress: Fiber,
704
+ ): Fiber | null {
705
if (__DEV__) {
706
cancelWorkTimer(workInProgress);
707
}
660
-
708
+
709
const priorityLevel = workInProgress.pendingWorkPriority;
710
// TODO: We should ideally be able to bail out early if the children have no
711
// more work to do. However, since we don't have a separation of this
@@ -696,7 +744,10 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
744
pushContextProvider(workInProgress);
745
break;
746
case HostPortal:
699
- pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
747
+ pushHostContainer(
748
+ workInProgress,
749
+ workInProgress.stateNode.containerInfo,
750
+ );
751
break;
752
}
753
// TODO: What if this is currently in progress?
@@ -704,21 +755,27 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
755
return null;
756
}
757
707
- function memoizeProps(workInProgress : Fiber, nextProps : any) {
758
+ function memoizeProps(workInProgress: Fiber, nextProps: any) {
759
workInProgress.memoizedProps = nextProps;
760
// Reset the pending props
761
workInProgress.pendingProps = null;
762
}
763
713
- function memoizeState(workInProgress : Fiber, nextState : any) {
764
+ function memoizeState(workInProgress: Fiber, nextState: any) {
765
workInProgress.memoizedState = nextState;
766
// Don't reset the updateQueue, in case there are pending updates. Resetting
767
// is handled by beginUpdateQueue.
768
}
769
719
- function beginWork(current : Fiber | null, workInProgress : Fiber, priorityLevel : PriorityLevel) : Fiber | null {
720
- if (workInProgress.pendingWorkPriority === NoWork ||
721
- workInProgress.pendingWorkPriority > priorityLevel) {
770
+ function beginWork(
771
+ current: Fiber | null,
772
+ workInProgress: Fiber,
773
+ priorityLevel: PriorityLevel,
774
+ ): Fiber | null {
775
+ if (
776
+ workInProgress.pendingWorkPriority === NoWork ||
777
+ workInProgress.pendingWorkPriority > priorityLevel
778
+ ) {
779
return bailoutOnLowPriority(current, workInProgress);
780
}
781
@@ -739,7 +796,11 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
796
797
switch (workInProgress.tag) {
798
case IndeterminateComponent:
742
- return mountIndeterminateComponent(current, workInProgress, priorityLevel);
799
+ return mountIndeterminateComponent(
800
+ current,
801
+ workInProgress,
802
+ priorityLevel,
803
+ );
804
case FunctionalComponent:
805
return updateFunctionalComponent(current, workInProgress);
806
case ClassComponent:
@@ -753,7 +814,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
814
case CoroutineHandlerPhase:
815
// This is a restart. Reset the tag to the initial phase.
816
workInProgress.tag = CoroutineComponent;
756
- // Intentionally fall through since this is now the same.
817
+ // Intentionally fall through since this is now the same.
818
case CoroutineComponent:
819
return updateCoroutineComponent(current, workInProgress);
820
case YieldComponent:
@@ -768,24 +829,29 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
829
invariant(
830
false,
831
'Unknown unit of work tag. This error is likely caused by a bug in ' +
771
- 'React. Please file an issue.'
832
+ 'React. Please file an issue.',
833
);
834
}
835
}
836
776
- function beginFailedWork(current : Fiber | null, workInProgress : Fiber, priorityLevel : PriorityLevel) {
837
+ function beginFailedWork(
838
+ current: Fiber | null,
839
+ workInProgress: Fiber,
840
+ priorityLevel: PriorityLevel,
841
+ ) {
842
invariant(
778
- workInProgress.tag === ClassComponent ||
779
- workInProgress.tag === HostRoot,
843
+ workInProgress.tag === ClassComponent || workInProgress.tag === HostRoot,
844
'Invalid type of work. This error is likely caused by a bug in React. ' +
781
- 'Please file an issue.'
845
+ 'Please file an issue.',
846
);
847
848
// Add an error effect so we can handle the error during the commit phase
849
workInProgress.effectTag |= Err;
850
787
- if (workInProgress.pendingWorkPriority === NoWork ||
788
- workInProgress.pendingWorkPriority > priorityLevel) {
851
+ if (
852
+ workInProgress.pendingWorkPriority === NoWork ||
853
+ workInProgress.pendingWorkPriority > priorityLevel
854
+ ) {
855
return bailoutOnLowPriority(current, workInProgress);
856
}
857
@@ -812,5 +878,4 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
878
beginWork,
879
beginFailedWork,
880
};
815
-
881
};
src/renderers/shared/fiber/ReactFiberClassComponent.js
+121
-91
@@ -12,8 +12,8 @@
12
13
'use strict';
14
15
-import type { Fiber } from 'ReactFiber';
16
-import type { PriorityLevel } from 'ReactPriorityLevel';
15
+import type {Fiber} from 'ReactFiber';
16
+import type {PriorityLevel} from 'ReactPriorityLevel';
17
18
var {
19
Update,
@@ -30,8 +30,8 @@ var {
30
addForceUpdate,
31
beginUpdateQueue,
32
} = require('ReactFiberUpdateQueue');
33
-var { hasContextChanged } = require('ReactFiberContext');
34
-var { isMounted } = require('ReactFiberTreeReflection');
33
+var {hasContextChanged} = require('ReactFiberContext');
34
+var {isMounted} = require('ReactFiberTreeReflection');
35
var ReactInstanceMap = require('ReactInstanceMap');
36
var emptyObject = require('fbjs/lib/emptyObject');
37
var getComponentName = require('getComponentName');
@@ -46,24 +46,23 @@ if (__DEV__) {
46
stopPhaseTimer,
47
} = require('ReactDebugFiberPerf');
48
var warning = require('fbjs/lib/warning');
49
- var warnOnInvalidCallback = function(callback : mixed, callerName : string) {
49
+ var warnOnInvalidCallback = function(callback: mixed, callerName: string) {
50
warning(
51
callback === null || typeof callback === 'function',
52
'%s(...): Expected the last optional `callback` argument to be a ' +
53
- 'function. Instead received: %s.',
53
+ 'function. Instead received: %s.',
54
callerName,
55
- callback
55
+ callback,
56
);
57
};
58
}
59
60
module.exports = function(
61
- scheduleUpdate : (fiber : Fiber, priorityLevel : PriorityLevel) => void,
62
- getPriorityContext : () => PriorityLevel,
63
- memoizeProps: (workInProgress : Fiber, props : any) => void,
64
- memoizeState: (workInProgress : Fiber, state : any) => void,
61
+ scheduleUpdate: (fiber: Fiber, priorityLevel: PriorityLevel) => void,
62
+ getPriorityContext: () => PriorityLevel,
63
+ memoizeProps: (workInProgress: Fiber, props: any) => void,
64
+ memoizeState: (workInProgress: Fiber, state: any) => void,
65
) {
66
-
66
// Class component state updater
67
const updater = {
68
isMounted,
@@ -99,8 +98,19 @@ module.exports = function(
98
},
99
};
100
102
- function checkShouldComponentUpdate(workInProgress, oldProps, newProps, oldState, newState, newContext) {
103
- if (oldProps === null || (workInProgress.updateQueue !== null && workInProgress.updateQueue.hasForceUpdate)) {
101
+ function checkShouldComponentUpdate(
102
+ workInProgress,
103
+ oldProps,
104
+ newProps,
105
+ oldState,
106
+ newState,
107
+ newContext,
108
+ ) {
109
+ if (
110
+ oldProps === null ||
111
+ (workInProgress.updateQueue !== null &&
112
+ workInProgress.updateQueue.hasForceUpdate)
113
+ ) {
114
// If the workInProgress already has an Update effect, return true
115
return true;
116
}
@@ -110,7 +120,11 @@ module.exports = function(
120
if (__DEV__) {
121
startPhaseTimer(workInProgress, 'shouldComponentUpdate');
122
}
113
- const shouldUpdate = instance.shouldComponentUpdate(newProps, newState, newContext);
123
+ const shouldUpdate = instance.shouldComponentUpdate(
124
+ newProps,
125
+ newState,
126
+ newContext,
127
+ );
128
if (__DEV__) {
129
stopPhaseTimer();
130
}
@@ -119,8 +133,8 @@ module.exports = function(
133
warning(
134
shouldUpdate !== undefined,
135
'%s.shouldComponentUpdate(): Returned undefined instead of a ' +
122
- 'boolean value. Make sure to return true or false.',
123
- getComponentName(workInProgress) || 'Unknown'
136
+ 'boolean value. Make sure to return true or false.',
137
+ getComponentName(workInProgress) || 'Unknown',
138
);
139
}
140
@@ -129,10 +143,8 @@ module.exports = function(
143
144
const type = workInProgress.type;
145
if (type.prototype && type.prototype.isPureReactComponent) {
132
- return (
133
- !shallowEqual(oldProps, newProps) ||
134
- !shallowEqual(oldState, newState)
135
- );
146
+ return !shallowEqual(oldProps, newProps) ||
147
+ !shallowEqual(oldState, newState);
148
}
149
150
return true;
@@ -146,77 +158,76 @@ module.exports = function(
158
warning(
159
renderPresent,
160
'%s(...): No `render` method found on the returned component ' +
149
- 'instance: you may have forgotten to define `render`.',
150
- name
161
+ 'instance: you may have forgotten to define `render`.',
162
+ name,
163
);
152
- const noGetInitialStateOnES6 = (
153
- !instance.getInitialState ||
164
+ const noGetInitialStateOnES6 = !instance.getInitialState ||
165
instance.getInitialState.isReactClassApproved ||
155
- instance.state
156
- );
166
+ instance.state;
167
warning(
168
noGetInitialStateOnES6,
169
'getInitialState was defined on %s, a plain JavaScript class. ' +
160
- 'This is only supported for classes created using React.createClass. ' +
161
- 'Did you mean to define a state property instead?',
162
- name
163
- );
164
- const noGetDefaultPropsOnES6 = (
165
- !instance.getDefaultProps ||
166
- instance.getDefaultProps.isReactClassApproved
170
+ 'This is only supported for classes created using React.createClass. ' +
171
+ 'Did you mean to define a state property instead?',
172
+ name,
173
);
174
+ const noGetDefaultPropsOnES6 = !instance.getDefaultProps ||
175
+ instance.getDefaultProps.isReactClassApproved;
176
warning(
177
noGetDefaultPropsOnES6,
178
'getDefaultProps was defined on %s, a plain JavaScript class. ' +
171
- 'This is only supported for classes created using React.createClass. ' +
172
- 'Use a static property to define defaultProps instead.',
173
- name
179
+ 'This is only supported for classes created using React.createClass. ' +
180
+ 'Use a static property to define defaultProps instead.',
181
+ name,
182
);
183
const noInstancePropTypes = !instance.propTypes;
184
warning(
185
noInstancePropTypes,
186
'propTypes was defined as an instance property on %s. Use a static ' +
179
- 'property to define propTypes instead.',
187
+ 'property to define propTypes instead.',
188
name,
189
);
190
const noInstanceContextTypes = !instance.contextTypes;
191
warning(
192
noInstanceContextTypes,
193
'contextTypes was defined as an instance property on %s. Use a static ' +
186
- 'property to define contextTypes instead.',
194
+ 'property to define contextTypes instead.',
195
name,
196
);
189
- const noComponentShouldUpdate = typeof instance.componentShouldUpdate !== 'function';
197
+ const noComponentShouldUpdate = typeof instance.componentShouldUpdate !==
198
+ 'function';
199
warning(
200
noComponentShouldUpdate,
201
'%s has a method called ' +
193
- 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' +
194
- 'The name is phrased as a question because the function is ' +
195
- 'expected to return a value.',
196
- name
202
+ 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' +
203
+ 'The name is phrased as a question because the function is ' +
204
+ 'expected to return a value.',
205
+ name,
206
);
198
- const noComponentDidUnmount = typeof instance.componentDidUnmount !== 'function';
207
+ const noComponentDidUnmount = typeof instance.componentDidUnmount !==
208
+ 'function';
209
warning(
210
noComponentDidUnmount,
211
'%s has a method called ' +
202
- 'componentDidUnmount(). But there is no such lifecycle method. ' +
203
- 'Did you mean componentWillUnmount()?',
204
- name
212
+ 'componentDidUnmount(). But there is no such lifecycle method. ' +
213
+ 'Did you mean componentWillUnmount()?',
214
+ name,
215
);
206
- const noComponentWillRecieveProps = typeof instance.componentWillRecieveProps !== 'function';
216
+ const noComponentWillRecieveProps = typeof instance.componentWillRecieveProps !==
217
+ 'function';
218
warning(
219
noComponentWillRecieveProps,
220
'%s has a method called ' +
210
- 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?',
211
- name
221
+ 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?',
222
+ name,
223
);
224
const hasMutatedProps = instance.props !== workInProgress.pendingProps;
225
warning(
226
instance.props === undefined || !hasMutatedProps,
227
'%s(...): When calling super() in `%s`, make sure to pass ' +
217
- 'up the same props that your component\'s constructor was passed.',
228
+ "up the same props that your component's constructor was passed.",
229
+ name,
230
name,
219
- name
231
);
232
}
233
@@ -225,37 +236,39 @@ module.exports = function(
236
invariant(
237
false,
238
'%s.state: must be set to an object or null',
228
- getComponentName(workInProgress)
239
+ getComponentName(workInProgress),
240
);
241
}
242
if (typeof instance.getChildContext === 'function') {
243
invariant(
244
typeof workInProgress.type.childContextTypes === 'object',
245
'%s.getChildContext(): childContextTypes must be defined in order to ' +
235
- 'use getChildContext().',
236
- getComponentName(workInProgress)
246
+ 'use getChildContext().',
247
+ getComponentName(workInProgress),
248
);
249
}
250
}
251
241
- function resetInputPointers(workInProgress : Fiber, instance : any) {
252
+ function resetInputPointers(workInProgress: Fiber, instance: any) {
253
instance.props = workInProgress.memoizedProps;
254
instance.state = workInProgress.memoizedState;
255
}
256
246
- function adoptClassInstance(workInProgress : Fiber, instance : any) : void {
257
+ function adoptClassInstance(workInProgress: Fiber, instance: any): void {
258
instance.updater = updater;
259
workInProgress.stateNode = instance;
260
// The instance needs access to the fiber so that it can schedule updates
261
ReactInstanceMap.set(instance, workInProgress);
262
}
263
253
- function constructClassInstance(workInProgress : Fiber) : any {
264
+ function constructClassInstance(workInProgress: Fiber): any {
265
const ctor = workInProgress.type;
266
const props = workInProgress.pendingProps;
267
const unmaskedContext = getUnmaskedContext(workInProgress);
268
const needsContext = isContextConsumer(workInProgress);
258
- const context = needsContext ? getMaskedContext(workInProgress, unmaskedContext) : emptyObject;
269
+ const context = needsContext
270
+ ? getMaskedContext(workInProgress, unmaskedContext)
271
+ : emptyObject;
272
const instance = new ctor(props, context);
273
adoptClassInstance(workInProgress, instance);
274
checkClassInstance(workInProgress);
@@ -270,7 +283,10 @@ module.exports = function(
283
}
284
285
// Invokes the mount life-cycles on a previously never rendered instance.
273
- function mountClassInstance(workInProgress : Fiber, priorityLevel : PriorityLevel) : void {
286
+ function mountClassInstance(
287
+ workInProgress: Fiber,
288
+ priorityLevel: PriorityLevel,
289
+ ): void {
290
const instance = workInProgress.stateNode;
291
const state = instance.state || null;
292
@@ -278,7 +294,7 @@ module.exports = function(
294
invariant(
295
props,
296
'There must be pending props for an initial mount. This error is ' +
281
- 'likely caused by a bug in React. Please file an issue.'
297
+ 'likely caused by a bug in React. Please file an issue.',
298
);
299
300
const unmaskedContext = getUnmaskedContext(workInProgress);
@@ -306,7 +322,7 @@ module.exports = function(
322
instance,
323
state,
324
props,
309
- priorityLevel
325
+ priorityLevel,
326
);
327
}
328
}
@@ -317,7 +333,10 @@ module.exports = function(
333
334
// Called on a preexisting class instance. Returns false if a resumed render
335
// could be reused.
320
- function resumeMountClassInstance(workInProgress : Fiber, priorityLevel : PriorityLevel) : boolean {
336
+ function resumeMountClassInstance(
337
+ workInProgress: Fiber,
338
+ priorityLevel: PriorityLevel,
339
+ ): boolean {
340
const instance = workInProgress.stateNode;
341
resetInputPointers(workInProgress, instance);
342
@@ -330,7 +349,7 @@ module.exports = function(
349
invariant(
350
newProps != null,
351
'There should always be pending or memoized props. This error is ' +
333
- 'likely caused by a bug in React. Please file an issue.'
352
+ 'likely caused by a bug in React. Please file an issue.',
353
);
354
}
355
const newUnmaskedContext = getUnmaskedContext(workInProgress);
@@ -340,14 +359,16 @@ module.exports = function(
359
// componentWillMount and before this componentWillMount? Probably
360
// unsupported anyway.
361
343
- if (!checkShouldComponentUpdate(
344
- workInProgress,
345
- workInProgress.memoizedProps,
346
- newProps,
347
- workInProgress.memoizedState,
348
- newState,
349
- newContext
350
- )) {
362
+ if (
363
+ !checkShouldComponentUpdate(
364
+ workInProgress,
365
+ workInProgress.memoizedProps,
366
+ newProps,
367
+ workInProgress.memoizedState,
368
+ newState,
369
+ newContext,
370
+ )
371
+ ) {
372
// Update the existing instance's state, props, and context pointers even
373
// though we're bailing out.
374
instance.props = newProps;
@@ -360,7 +381,7 @@ module.exports = function(
381
// want to reuse one that failed to fully mount.
382
const newInstance = constructClassInstance(workInProgress);
383
newInstance.props = newProps;
363
- newInstance.state = newState = newInstance.state || null;
384
+ newInstance.state = (newState = newInstance.state || null);
385
newInstance.context = newContext;
386
387
if (typeof newInstance.componentWillMount === 'function') {
@@ -383,7 +404,7 @@ module.exports = function(
404
newInstance,
405
newState,
406
newProps,
386
- priorityLevel
407
+ priorityLevel,
408
);
409
}
410
if (typeof instance.componentDidMount === 'function') {
@@ -393,7 +414,11 @@ module.exports = function(
414
}
415
416
// Invokes the update life-cycles and returns false if it shouldn't rerender.
396
- function updateClassInstance(current : Fiber, workInProgress : Fiber, priorityLevel : PriorityLevel) : boolean {
417
+ function updateClassInstance(
418
+ current: Fiber,
419
+ workInProgress: Fiber,
420
+ priorityLevel: PriorityLevel,
421
+ ): boolean {
422
const instance = workInProgress.stateNode;
423
resetInputPointers(workInProgress, instance);
424
@@ -406,7 +431,7 @@ module.exports = function(
431
invariant(
432
newProps != null,
433
'There should always be pending or memoized props. This error is ' +
409
- 'likely caused by a bug in React. Please file an issue.'
434
+ 'likely caused by a bug in React. Please file an issue.',
435
);
436
}
437
const oldContext = instance.context;
@@ -432,9 +457,9 @@ module.exports = function(
457
warning(
458
false,
459
'%s.componentWillReceiveProps(): Assigning directly to ' +
435
- 'this.state is deprecated (except inside a component\'s ' +
436
- 'constructor). Use setState instead.',
437
- getComponentName(workInProgress)
460
+ "this.state is deprecated (except inside a component's " +
461
+ 'constructor). Use setState instead.',
462
+ getComponentName(workInProgress),
463
);
464
}
465
updater.enqueueReplaceState(instance, instance.state, null);
@@ -454,21 +479,25 @@ module.exports = function(
479
instance,
480
oldState,
481
newProps,
457
- priorityLevel
482
+ priorityLevel,
483
);
484
} else {
485
newState = oldState;
486
}
487
463
- if (oldProps === newProps &&
464
- oldState === newState &&
465
- !hasContextChanged() &&
466
- !(updateQueue !== null && updateQueue.hasForceUpdate)) {
488
+ if (
489
+ oldProps === newProps &&
490
+ oldState === newState &&
491
+ !hasContextChanged() &&
492
+ !(updateQueue !== null && updateQueue.hasForceUpdate)
493
+ ) {
494
// If an update was already in progress, we should schedule an Update
495
// effect even though we're bailing out, so that cWU/cDU are called.
496
if (typeof instance.componentDidUpdate === 'function') {
470
- if (oldProps !== current.memoizedProps ||
471
- oldState !== current.memoizedState) {
497
+ if (
498
+ oldProps !== current.memoizedProps ||
499
+ oldState !== current.memoizedState
500
+ ) {
501
workInProgress.effectTag |= Update;
502
}
503
}
@@ -481,7 +510,7 @@ module.exports = function(
510
newProps,
511
oldState,
512
newState,
484
- newContext
513
+ newContext,
514
);
515
516
if (shouldUpdate) {
@@ -501,8 +530,10 @@ module.exports = function(
530
// If an update was already in progress, we should schedule an Update
531
// effect even though we're bailing out, so that cWU/cDU are called.
532
if (typeof instance.componentDidUpdate === 'function') {
504
- if (oldProps !== current.memoizedProps ||
505
- oldState !== current.memoizedState) {
533
+ if (
534
+ oldProps !== current.memoizedProps ||
535
+ oldState !== current.memoizedState
536
+ ) {
537
workInProgress.effectTag |= Update;
538
}
539
}
@@ -529,5 +560,4 @@ module.exports = function(
560
resumeMountClassInstance,
561
updateClassInstance,
562
};
532
-
563
};
src/renderers/shared/fiber/ReactFiberCommitWork.js
+50
-48
@@ -12,8 +12,8 @@
12
13
'use strict';
14
15
-import type { Fiber } from 'ReactFiber';
16
-import type { HostConfig } from 'ReactFiberReconciler';
15
+import type {Fiber} from 'ReactFiber';
16
+import type {HostConfig} from 'ReactFiberReconciler';
17
18
var ReactTypeOfWork = require('ReactTypeOfWork');
19
var {
@@ -24,9 +24,9 @@ var {
24
HostPortal,
25
CoroutineComponent,
26
} = ReactTypeOfWork;
27
-var { commitCallbacks } = require('ReactFiberUpdateQueue');
28
-var { onCommitUnmount } = require('ReactFiberDevToolsHook');
29
-var { invokeGuardedCallback } = require('ReactErrorUtils');
27
+var {commitCallbacks} = require('ReactFiberUpdateQueue');
28
+var {onCommitUnmount} = require('ReactFiberDevToolsHook');
29
+var {invokeGuardedCallback} = require('ReactErrorUtils');
30
31
var {
32
Placement,
@@ -45,10 +45,9 @@ if (__DEV__) {
45
}
46
47
module.exports = function<T, P, I, TI, PI, C, CX, PL>(
48
- config : HostConfig<T, P, I, TI, PI, C, CX, PL>,
49
- captureError : (failedFiber : Fiber, error: Error) => Fiber | null
48
+ config: HostConfig<T, P, I, TI, PI, C, CX, PL>,
49
+ captureError: (failedFiber: Fiber, error: Error) => Fiber | null,
50
) {
51
-
51
const {
52
commitMount,
53
commitUpdate,
@@ -90,7 +89,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
89
}
90
}
91
93
- function safelyDetachRef(current : Fiber) {
92
+ function safelyDetachRef(current: Fiber) {
93
const ref = current.ref;
94
if (ref !== null) {
95
if (__DEV__) {
@@ -108,7 +107,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
107
}
108
}
109
111
- function getHostParent(fiber : Fiber) : I | C {
110
+ function getHostParent(fiber: Fiber): I | C {
111
let parent = fiber.return;
112
while (parent !== null) {
113
switch (parent.tag) {
@@ -124,11 +123,11 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
123
invariant(
124
false,
125
'Expected to find a host parent. This error is likely caused by a bug ' +
127
- 'in React. Please file an issue.'
126
+ 'in React. Please file an issue.',
127
);
128
}
129
131
- function getHostParentFiber(fiber : Fiber) : Fiber {
130
+ function getHostParentFiber(fiber: Fiber): Fiber {
131
let parent = fiber.return;
132
while (parent !== null) {
133
if (isHostParent(parent)) {
@@ -139,24 +138,22 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
138
invariant(
139
false,
140
'Expected to find a host parent. This error is likely caused by a bug ' +
142
- 'in React. Please file an issue.'
141
+ 'in React. Please file an issue.',
142
);
143
}
144
146
- function isHostParent(fiber : Fiber) : boolean {
147
- return (
148
- fiber.tag === HostComponent ||
145
+ function isHostParent(fiber: Fiber): boolean {
146
+ return fiber.tag === HostComponent ||
147
fiber.tag === HostRoot ||
150
- fiber.tag === HostPortal
151
- );
148
+ fiber.tag === HostPortal;
149
}
150
154
- function getHostSibling(fiber : Fiber) : ?I {
151
+ function getHostSibling(fiber: Fiber): ?I {
152
// We're going to search forward into the tree until we find a sibling host
153
// node. Unfortunately, if multiple insertions are done in a row we have to
154
// search past them. This leads to exponential search for the next sibling.
155
// TODO: Find a more efficient way to do this.
159
- let node : Fiber = fiber;
156
+ let node: Fiber = fiber;
157
siblings: while (true) {
158
// If we didn't find anything, let's try the next sibling.
159
while (node.sibling === null) {
@@ -193,7 +190,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
190
}
191
}
192
196
- function commitPlacement(finishedWork : Fiber) : void {
193
+ function commitPlacement(finishedWork: Fiber): void {
194
// Recursively insert all host nodes into the parent.
195
const parentFiber = getHostParentFiber(finishedWork);
196
let parent;
@@ -211,7 +208,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
208
invariant(
209
false,
210
'Invalid host parent fiber. This error is likely caused by a bug ' +
214
- 'in React. Please file an issue.'
211
+ 'in React. Please file an issue.',
212
);
213
}
214
if (parentFiber.effectTag & ContentReset) {
@@ -224,7 +221,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
221
const before = getHostSibling(finishedWork);
222
// We only have the top Fiber that was inserted but we need recurse down its
223
// children to find all the terminal nodes.
227
- let node : Fiber = finishedWork;
224
+ let node: Fiber = finishedWork;
225
while (true) {
226
if (node.tag === HostComponent || node.tag === HostText) {
227
if (before) {
@@ -255,13 +252,13 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
252
}
253
}
254
258
- function commitNestedUnmounts(root : Fiber): void {
255
+ function commitNestedUnmounts(root: Fiber): void {
256
// While we're inside a removed host node we don't want to call
257
// removeChild on the inner nodes because they're removed by the top
258
// call anyway. We also want to call componentWillUnmount on all
259
// composites before this host node is removed from the tree. Therefore
260
// we do an inner loop while we're still inside the host node.
264
- let node : Fiber = root;
261
+ let node: Fiber = root;
262
while (true) {
263
commitUnmount(node);
264
// Visit children because they may contain more composite or host nodes.
@@ -288,7 +285,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
285
function unmountHostComponents(parent, current): void {
286
// We only have the top Fiber that was inserted but we need recurse down its
287
// children to find all the terminal nodes.
291
- let node : Fiber = current;
288
+ let node: Fiber = current;
289
while (true) {
290
if (node.tag === HostComponent || node.tag === HostText) {
291
commitNestedUnmounts(node);
@@ -334,7 +331,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
331
}
332
}
333
337
- function commitDeletion(current : Fiber) : void {
334
+ function commitDeletion(current: Fiber): void {
335
// Recursively delete all host nodes from the parent.
336
const parent = getHostParent(current);
337
// Detach refs and call componentWillUnmount() on the whole subtree.
@@ -356,7 +353,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
353
// User-originating errors (lifecycles and refs) should not interrupt
354
// deletion, so don't let them throw. Host-originating errors should
355
// interrupt deletion, so it's okay
359
- function commitUnmount(current : Fiber) : void {
356
+ function commitUnmount(current: Fiber): void {
357
if (typeof onCommitUnmount === 'function') {
358
onCommitUnmount(current);
359
}
@@ -389,23 +386,30 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
386
}
387
}
388
392
- function commitWork(current : Fiber | null, finishedWork : Fiber) : void {
389
+ function commitWork(current: Fiber | null, finishedWork: Fiber): void {
390
switch (finishedWork.tag) {
391
case ClassComponent: {
392
return;
393
}
394
case HostComponent: {
398
- const instance : I = finishedWork.stateNode;
395
+ const instance: I = finishedWork.stateNode;
396
if (instance != null && current !== null) {
397
// Commit the work prepared earlier.
398
const newProps = finishedWork.memoizedProps;
399
const oldProps = current.memoizedProps;
400
const type = finishedWork.type;
401
// TODO: Type the updateQueue to be specific to host components.
405
- const updatePayload : null | PL = (finishedWork.updateQueue : any);
402
+ const updatePayload: null | PL = (finishedWork.updateQueue: any);
403
finishedWork.updateQueue = null;
404
if (updatePayload !== null) {
408
- commitUpdate(instance, updatePayload, type, oldProps, newProps, finishedWork);
405
+ commitUpdate(
406
+ instance,
407
+ updatePayload,
408
+ type,
409
+ oldProps,
410
+ newProps,
411
+ finishedWork,
412
+ );
413
}
414
}
415
return;
@@ -414,11 +418,11 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
418
invariant(
419
finishedWork.stateNode !== null && current !== null,
420
'This should only be done during updates. This error is likely ' +
417
- 'caused by a bug in React. Please file an issue.'
421
+ 'caused by a bug in React. Please file an issue.',
422
);
419
- const textInstance : TI = finishedWork.stateNode;
420
- const newText : string = finishedWork.memoizedProps;
421
- const oldText : string = current.memoizedProps;
423
+ const textInstance: TI = finishedWork.stateNode;
424
+ const newText: string = finishedWork.memoizedProps;
425
+ const oldText: string = current.memoizedProps;
426
commitTextUpdate(textInstance, oldText, newText);
427
return;
428
}
@@ -432,13 +436,13 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
436
invariant(
437
false,
438
'This unit of work tag should not have side-effects. This error is ' +
435
- 'likely caused by a bug in React. Please file an issue.'
439
+ 'likely caused by a bug in React. Please file an issue.',
440
);
441
}
442
}
443
}
444
441
- function commitLifeCycles(current : Fiber | null, finishedWork : Fiber) : void {
445
+ function commitLifeCycles(current: Fiber | null, finishedWork: Fiber): void {
446
switch (finishedWork.tag) {
447
case ClassComponent: {
448
const instance = finishedWork.stateNode;
@@ -463,7 +467,9 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
467
}
468
}
469
}
466
- if ((finishedWork.effectTag & Callback) && finishedWork.updateQueue !== null) {
470
+ if (
471
+ finishedWork.effectTag & Callback && finishedWork.updateQueue !== null
472
+ ) {
473
commitCallbacks(finishedWork, finishedWork.updateQueue, instance);
474
}
475
return;
@@ -477,16 +483,13 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
483
return;
484
}
485
case HostComponent: {
480
- const instance : I = finishedWork.stateNode;
486
+ const instance: I = finishedWork.stateNode;
487
488
// Renderers may schedule work to be done after host components are mounted
489
// (eg DOM renderer may schedule auto-focus for inputs and form controls).
490
// These effects should only be committed when components are first mounted,
491
// aka when there is no current/alternate.
486
- if (
487
- current === null &&
488
- finishedWork.effectTag & Update
489
- ) {
492
+ if (current === null && finishedWork.effectTag & Update) {
493
const type = finishedWork.type;
494
const props = finishedWork.memoizedProps;
495
commitMount(instance, type, props, finishedWork);
@@ -506,13 +509,13 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
509
invariant(
510
false,
511
'This unit of work tag should not have side-effects. This error is ' +
509
- 'likely caused by a bug in React. Please file an issue.'
512
+ 'likely caused by a bug in React. Please file an issue.',
513
);
514
}
515
}
516
}
517
515
- function commitAttachRef(finishedWork : Fiber) {
518
+ function commitAttachRef(finishedWork: Fiber) {
519
const ref = finishedWork.ref;
520
if (ref !== null) {
521
const instance = getPublicInstance(finishedWork.stateNode);
@@ -520,7 +523,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
523
}
524
}
525
523
- function commitDetachRef(current : Fiber) {
526
+ function commitDetachRef(current: Fiber) {
527
const currentRef = current.ref;
528
if (currentRef !== null) {
529
currentRef(null);
@@ -535,5 +538,4 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
538
commitAttachRef,
539
commitDetachRef,
540
};
538
-
541
};
src/renderers/shared/fiber/ReactFiberCompleteWork.js
+55
-38
@@ -12,13 +12,13 @@
12
13
'use strict';
14
15
-import type { ReactCoroutine } from 'ReactCoroutine';
16
-import type { Fiber } from 'ReactFiber';
17
-import type { HostContext } from 'ReactFiberHostContext';
18
-import type { FiberRoot } from 'ReactFiberRoot';
19
-import type { HostConfig } from 'ReactFiberReconciler';
15
+import type {ReactCoroutine} from 'ReactCoroutine';
16
+import type {Fiber} from 'ReactFiber';
17
+import type {HostContext} from 'ReactFiberHostContext';
18
+import type {FiberRoot} from 'ReactFiberRoot';
19
+import type {HostConfig} from 'ReactFiberReconciler';
20
21
-var { reconcileChildFibers } = require('ReactChildFiber');
21
+var {reconcileChildFibers} = require('ReactChildFiber');
22
var {
23
popContextProvider,
24
} = require('ReactFiberContext');
@@ -49,8 +49,8 @@ if (__DEV__) {
49
var invariant = require('fbjs/lib/invariant');
50
51
module.exports = function<T, P, I, TI, PI, C, CX, PL>(
52
- config : HostConfig<T, P, I, TI, PI, C, CX, PL>,
53
- hostContext : HostContext<C, CX>,
52
+ config: HostConfig<T, P, I, TI, PI, C, CX, PL>,
53
+ hostContext: HostContext<C, CX>,
54
) {
55
const {
56
createInstance,
@@ -79,28 +79,28 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
79
}
80
}
81
82
- function markUpdate(workInProgress : Fiber) {
82
+ function markUpdate(workInProgress: Fiber) {
83
// Tag the fiber with an update effect. This turns a Placement into
84
// an UpdateAndPlacement.
85
workInProgress.effectTag |= Update;
86
}
87
88
- function markRef(workInProgress : Fiber) {
88
+ function markRef(workInProgress: Fiber) {
89
workInProgress.effectTag |= Ref;
90
}
91
92
- function appendAllYields(yields : Array<mixed>, workInProgress : Fiber) {
92
+ function appendAllYields(yields: Array<mixed>, workInProgress: Fiber) {
93
let node = workInProgress.stateNode;
94
if (node) {
95
node.return = workInProgress;
96
}
97
while (node !== null) {
98
- if (node.tag === HostComponent || node.tag === HostText ||
99
- node.tag === HostPortal) {
100
- invariant(
101
- false,
102
- 'A coroutine cannot have host component children.'
103
- );
98
+ if (
99
+ node.tag === HostComponent ||
100
+ node.tag === HostText ||
101
+ node.tag === HostPortal
102
+ ) {
103
+ invariant(false, 'A coroutine cannot have host component children.');
104
} else if (node.tag === YieldComponent) {
105
yields.push(node.type);
106
} else if (node.child !== null) {
@@ -119,12 +119,15 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
119
}
120
}
121
122
- function moveCoroutineToHandlerPhase(current : Fiber | null, workInProgress : Fiber) {
123
- var coroutine = (workInProgress.memoizedProps : ?ReactCoroutine);
122
+ function moveCoroutineToHandlerPhase(
123
+ current: Fiber | null,
124
+ workInProgress: Fiber,
125
+ ) {
126
+ var coroutine = (workInProgress.memoizedProps: ?ReactCoroutine);
127
invariant(
128
coroutine,
129
'Should be resolved by now. This error is likely caused by a bug in ' +
127
- 'React. Please file an issue.',
130
+ 'React. Please file an issue.',
131
);
132
133
// First step of the coroutine has completed. Now we need to do the second.
@@ -138,7 +141,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
141
142
// Build up the yields.
143
// TODO: Compare this to a generator or opaque helpers like Children.
141
- var yields : Array<mixed> = [];
144
+ var yields: Array<mixed> = [];
145
appendAllYields(yields, workInProgress);
146
var fn = coroutine.handler;
147
var props = coroutine.props;
@@ -151,13 +154,13 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
154
workInProgress,
155
currentFirstChild,
156
nextChildren,
154
- priority
157
+ priority,
158
);
159
markChildAsProgressed(current, workInProgress, priority);
160
return workInProgress.child;
161
}
162
160
- function appendAllChildren(parent : I, workInProgress : Fiber) {
163
+ function appendAllChildren(parent: I, workInProgress: Fiber) {
164
// We only have the top Fiber that was created but we need recurse down its
165
// children to find all the terminal nodes.
166
let node = workInProgress.child;
@@ -185,7 +188,10 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
188
}
189
}
190
188
- function completeWork(current : Fiber | null, workInProgress : Fiber) : Fiber | null {
191
+ function completeWork(
192
+ current: Fiber | null,
193
+ workInProgress: Fiber,
194
+ ): Fiber | null {
195
if (__DEV__) {
196
ReactDebugCurrentFiber.current = workInProgress;
197
}
@@ -200,7 +206,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
206
}
207
case HostRoot: {
208
// TODO: Pop the host container after #8607 lands.
203
- const fiberRoot = (workInProgress.stateNode : FiberRoot);
209
+ const fiberRoot = (workInProgress.stateNode: FiberRoot);
210
if (fiberRoot.pendingContext) {
211
fiberRoot.context = fiberRoot.pendingContext;
212
fiberRoot.pendingContext = null;
@@ -220,7 +226,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
226
// have newProps so we'll have to reuse them.
227
// TODO: Split the update API as separate for the props vs. children.
228
// Even better would be if children weren't special cased at all tho.
223
- const instance : I = workInProgress.stateNode;
229
+ const instance: I = workInProgress.stateNode;
230
const currentHostContext = getHostContext();
231
const updatePayload = prepareUpdate(
232
instance,
@@ -228,11 +234,11 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
234
oldProps,
235
newProps,
236
rootContainerInstance,
231
- currentHostContext
237
+ currentHostContext,
238
);
239
240
// TODO: Type this specific to this type of component.
235
- workInProgress.updateQueue = (updatePayload : any);
241
+ workInProgress.updateQueue = (updatePayload: any);
242
// If the update payload indicates that there is a change or if there
243
// is a new ref we mark this as an update.
244
if (updatePayload) {
@@ -246,7 +252,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
252
invariant(
253
workInProgress.stateNode !== null,
254
'We must have new props for new mounts. This error is likely ' +
249
- 'caused by a bug in React. Please file an issue.'
255
+ 'caused by a bug in React. Please file an issue.',
256
);
257
// This can happen when we abort work.
258
return null;
@@ -262,7 +268,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
268
newProps,
269
rootContainerInstance,
270
currentHostContext,
265
- workInProgress
271
+ workInProgress,
272
);
273
274
appendAllChildren(instance, workInProgress);
@@ -270,7 +276,14 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
276
// Certain renderers require commit-time effects for initial mount.
277
// (eg DOM renderer supports auto-focus for certain elements).
278
// Make sure such renderers get scheduled for later work.
273
- if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance)) {
279
+ if (
280
+ finalizeInitialChildren(
281
+ instance,
282
+ type,
283
+ newProps,
284
+ rootContainerInstance,
285
+ )
286
+ ) {
287
markUpdate(workInProgress);
288
}
289
@@ -296,14 +309,19 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
309
invariant(
310
workInProgress.stateNode !== null,
311
'We must have new props for new mounts. This error is likely ' +
299
- 'caused by a bug in React. Please file an issue.'
312
+ 'caused by a bug in React. Please file an issue.',
313
);
314
// This can happen when we abort work.
315
return null;
316
}
317
const rootContainerInstance = getRootHostContainer();
318
const currentHostContext = getHostContext();
306
- const textInstance = createTextInstance(newText, rootContainerInstance, currentHostContext, workInProgress);
319
+ const textInstance = createTextInstance(
320
+ newText,
321
+ rootContainerInstance,
322
+ currentHostContext,
323
+ workInProgress,
324
+ );
325
workInProgress.stateNode = textInstance;
326
}
327
return null;
@@ -330,15 +348,15 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
348
invariant(
349
false,
350
'An indeterminate component should have become determinate before ' +
333
- 'completing. This error is likely caused by a bug in React. Please ' +
334
- 'file an issue.'
351
+ 'completing. This error is likely caused by a bug in React. Please ' +
352
+ 'file an issue.',
353
);
336
- // eslint-disable-next-line no-fallthrough
354
+ // eslint-disable-next-line no-fallthrough
355
default:
356
invariant(
357
false,
358
'Unknown unit of work tag. This error is likely caused by a bug in ' +
341
- 'React. Please file an issue.'
359
+ 'React. Please file an issue.',
360
);
361
}
362
}
@@ -346,5 +364,4 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
364
return {
365
completeWork,
366
};
349
-
367
};
src/renderers/shared/fiber/ReactFiberContext.js
+52
-37
@@ -12,8 +12,8 @@
12
13
'use strict';
14
15
-import type { Fiber } from 'ReactFiber';
16
-import type { StackCursor } from 'ReactFiberStack';
15
+import type {Fiber} from 'ReactFiber';
16
+import type {StackCursor} from 'ReactFiberStack';
17
18
var emptyObject = require('fbjs/lib/emptyObject');
19
var getComponentName = require('getComponentName');
@@ -44,15 +44,15 @@ if (__DEV__) {
44
}
45
46
// A cursor to the current merged context object on the stack.
47
-let contextStackCursor : StackCursor<Object> = createCursor(emptyObject);
47
+let contextStackCursor: StackCursor<Object> = createCursor(emptyObject);
48
// A cursor to a boolean indicating whether the context has changed.
49
-let didPerformWorkStackCursor : StackCursor<boolean> = createCursor(false);
49
+let didPerformWorkStackCursor: StackCursor<boolean> = createCursor(false);
50
// Keep track of the previous context object that was on the stack.
51
// We use this to get access to the parent context after we have already
52
// pushed the next context provider, and now need to merge their contexts.
53
-let previousContext : Object = emptyObject;
53
+let previousContext: Object = emptyObject;
54
55
-function getUnmaskedContext(workInProgress : Fiber) : Object {
55
+function getUnmaskedContext(workInProgress: Fiber): Object {
56
const hasOwnContext = isContextProvider(workInProgress);
57
if (hasOwnContext) {
58
// If the fiber is a context provider itself, when we read its context
@@ -65,14 +65,21 @@ function getUnmaskedContext(workInProgress : Fiber) : Object {
65
}
66
exports.getUnmaskedContext = getUnmaskedContext;
67
68
-function cacheContext(workInProgress : Fiber, unmaskedContext : Object, maskedContext : Object) {
68
+function cacheContext(
69
+ workInProgress: Fiber,
70
+ unmaskedContext: Object,
71
+ maskedContext: Object,
72
+) {
73
const instance = workInProgress.stateNode;
74
instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext;
75
instance.__reactInternalMemoizedMaskedChildContext = maskedContext;
76
}
77
exports.cacheContext = cacheContext;
78
75
-exports.getMaskedContext = function(workInProgress : Fiber, unmaskedContext : Object) {
79
+exports.getMaskedContext = function(
80
+ workInProgress: Fiber,
81
+ unmaskedContext: Object,
82
+) {
83
const type = workInProgress.type;
84
const contextTypes = type.contextTypes;
85
if (!contextTypes) {
@@ -111,27 +118,21 @@ exports.getMaskedContext = function(workInProgress : Fiber, unmaskedContext : Ob
118
return context;
119
};
120
114
-exports.hasContextChanged = function() : boolean {
121
+exports.hasContextChanged = function(): boolean {
122
return didPerformWorkStackCursor.current;
123
};
124
118
-function isContextConsumer(fiber : Fiber) : boolean {
119
- return (
120
- fiber.tag === ClassComponent &&
121
- fiber.type.contextTypes != null
122
- );
125
+function isContextConsumer(fiber: Fiber): boolean {
126
+ return fiber.tag === ClassComponent && fiber.type.contextTypes != null;
127
}
128
exports.isContextConsumer = isContextConsumer;
129
126
-function isContextProvider(fiber : Fiber) : boolean {
127
- return (
128
- fiber.tag === ClassComponent &&
129
- fiber.type.childContextTypes != null
130
- );
130
+function isContextProvider(fiber: Fiber): boolean {
131
+ return fiber.tag === ClassComponent && fiber.type.childContextTypes != null;
132
}
133
exports.isContextProvider = isContextProvider;
134
134
-function popContextProvider(fiber : Fiber) : void {
135
+function popContextProvider(fiber: Fiber): void {
136
if (!isContextProvider(fiber)) {
137
return;
138
}
@@ -141,14 +142,25 @@ function popContextProvider(fiber : Fiber) : void {
142
}
143
exports.popContextProvider = popContextProvider;
144
144
-exports.pushTopLevelContextObject = function(fiber : Fiber, context : Object, didChange : boolean) : void {
145
- invariant(contextStackCursor.cursor == null, 'Unexpected context found on stack');
145
+exports.pushTopLevelContextObject = function(
146
+ fiber: Fiber,
147
+ context: Object,
148
+ didChange: boolean,
149
+): void {
150
+ invariant(
151
+ contextStackCursor.cursor == null,
152
+ 'Unexpected context found on stack',
153
+ );
154
155
push(contextStackCursor, context, fiber);
156
push(didPerformWorkStackCursor, didChange, fiber);
157
};
158
151
-function processChildContext(fiber : Fiber, parentContext : Object, isReconciling : boolean): Object {
159
+function processChildContext(
160
+ fiber: Fiber,
161
+ parentContext: Object,
162
+ isReconciling: boolean,
163
+): Object {
164
const instance = fiber.stateNode;
165
const childContextTypes = fiber.type.childContextTypes;
166
@@ -163,8 +175,8 @@ function processChildContext(fiber : Fiber, parentContext : Object, isReconcilin
175
warning(
176
false,
177
'%s.childContextTypes is specified but there is no getChildContext() method ' +
166
- 'on the instance. You can either define getChildContext() on %s or remove ' +
167
- 'childContextTypes from it.',
178
+ 'on the instance. You can either define getChildContext() on %s or remove ' +
179
+ 'childContextTypes from it.',
180
componentName,
181
componentName,
182
);
@@ -188,7 +200,7 @@ function processChildContext(fiber : Fiber, parentContext : Object, isReconcilin
200
contextKey in childContextTypes,
201
'%s.getChildContext(): key "%s" is not defined in childContextTypes.',
202
getComponentName(fiber) || 'Unknown',
191
- contextKey
203
+ contextKey,
204
);
205
}
206
if (__DEV__) {
@@ -208,7 +220,7 @@ function processChildContext(fiber : Fiber, parentContext : Object, isReconcilin
220
}
221
exports.processChildContext = processChildContext;
222
211
-exports.pushContextProvider = function(workInProgress : Fiber) : boolean {
223
+exports.pushContextProvider = function(workInProgress: Fiber): boolean {
224
if (!isContextProvider(workInProgress)) {
225
return false;
226
}
@@ -217,10 +229,9 @@ exports.pushContextProvider = function(workInProgress : Fiber) : boolean {
229
// We push the context as early as possible to ensure stack integrity.
230
// If the instance does not exist yet, we will push null at first,
231
// and replace it on the stack later when invalidating the context.
220
- const memoizedMergedChildContext = (
221
- instance &&
222
- instance.__reactInternalMemoizedMergedChildContext
223
- ) || emptyObject;
232
+ const memoizedMergedChildContext = (instance &&
233
+ instance.__reactInternalMemoizedMergedChildContext) ||
234
+ emptyObject;
235
236
// Remember the parent context so we can merge with it later.
237
previousContext = contextStackCursor.current;
@@ -230,12 +241,16 @@ exports.pushContextProvider = function(workInProgress : Fiber) : boolean {
241
return true;
242
};
243
233
-exports.invalidateContextProvider = function(workInProgress : Fiber) : void {
244
+exports.invalidateContextProvider = function(workInProgress: Fiber): void {
245
const instance = workInProgress.stateNode;
246
invariant(instance, 'Expected to have an instance by this point.');
247
248
// Merge parent and own context.
238
- const mergedContext = processChildContext(workInProgress, previousContext, true);
249
+ const mergedContext = processChildContext(
250
+ workInProgress,
251
+ previousContext,
252
+ true,
253
+ );
254
instance.__reactInternalMemoizedMergedChildContext = mergedContext;
255
256
// Replace the old (or empty) context with the new one.
@@ -247,21 +262,21 @@ exports.invalidateContextProvider = function(workInProgress : Fiber) : void {
262
push(didPerformWorkStackCursor, true, workInProgress);
263
};
264
250
-exports.resetContext = function() : void {
265
+exports.resetContext = function(): void {
266
previousContext = emptyObject;
267
contextStackCursor.current = emptyObject;
268
didPerformWorkStackCursor.current = false;
269
};
270
256
-exports.findCurrentUnmaskedContext = function(fiber: Fiber) : Object {
271
+exports.findCurrentUnmaskedContext = function(fiber: Fiber): Object {
272
// Currently this is only used with renderSubtreeIntoContainer; not sure if it
273
// makes sense elsewhere
274
invariant(
275
isFiberMounted(fiber) && fiber.tag === ClassComponent,
261
- 'Expected subtree parent to be a mounted class component'
276
+ 'Expected subtree parent to be a mounted class component',
277
);
278
264
- let node : Fiber = fiber;
279
+ let node: Fiber = fiber;
280
while (node.tag !== HostRoot) {
281
if (isContextProvider(node)) {
282
return node.stateNode.__reactInternalMemoizedMergedChildContext;
src/renderers/shared/fiber/ReactFiberDevToolsHook.js
+6
-6
@@ -14,10 +14,10 @@
14
15
var warning = require('fbjs/lib/warning');
16
17
-import type { Fiber } from 'ReactFiber';
18
-import type { FiberRoot } from 'ReactFiberRoot';
17
+import type {Fiber} from 'ReactFiber';
18
+import type {FiberRoot} from 'ReactFiberRoot';
19
20
-declare var __REACT_DEVTOOLS_GLOBAL_HOOK__ : Object | void;
20
+declare var __REACT_DEVTOOLS_GLOBAL_HOOK__: Object | void;
21
22
let rendererID = null;
23
let injectInternals = null;
@@ -33,12 +33,12 @@ if (
33
onCommitFiberUnmount,
34
} = __REACT_DEVTOOLS_GLOBAL_HOOK__;
35
36
- injectInternals = function(internals : Object) {
36
+ injectInternals = function(internals: Object) {
37
warning(rendererID == null, 'Cannot inject into DevTools twice.');
38
rendererID = inject(internals);
39
};
40
41
- onCommitRoot = function(root : FiberRoot) {
41
+ onCommitRoot = function(root: FiberRoot) {
42
if (rendererID == null) {
43
return;
44
}
@@ -52,7 +52,7 @@ if (
52
}
53
};
54
55
- onCommitUnmount = function(fiber : Fiber) {
55
+ onCommitUnmount = function(fiber: Fiber) {
56
if (rendererID == null) {
57
return;
58
}
src/renderers/shared/fiber/ReactFiberErrorLogger.js
+14
-19
@@ -12,9 +12,9 @@
12
13
'use strict';
14
15
-import type { CapturedError } from 'ReactFiberScheduler';
15
+import type {CapturedError} from 'ReactFiberScheduler';
16
17
-function logCapturedError(capturedError : CapturedError) : void {
17
+function logCapturedError(capturedError: CapturedError): void {
18
if (__DEV__) {
19
const {
20
componentName,
@@ -31,9 +31,7 @@ function logCapturedError(capturedError : CapturedError) : void {
31
stack,
32
} = error;
33
34
- const errorSummary = message
35
- ? `${name}: ${message}`
36
- : name;
34
+ const errorSummary = message ? `${name}: ${message}` : name;
35
36
const componentNameMessage = componentName
37
? `React caught an error thrown by ${componentName}.`
@@ -43,48 +41,45 @@ function logCapturedError(capturedError : CapturedError) : void {
41
// Chrome prepends the Error name and type.
42
// Firefox, Safari, and IE don't indent the stack lines.
43
// Format it in a consistent way for error logging.
46
- let formattedCallStack = stack.slice(0, errorSummary.length) === errorSummary
44
+ let formattedCallStack = stack.slice(0, errorSummary.length) ===
45
+ errorSummary
46
? stack.slice(errorSummary.length)
47
: stack;
48
formattedCallStack = formattedCallStack
49
.trim()
50
.split('\n')
52
- .map((line) => `\n ${line.trim()}`)
51
+ .map(line => `\n ${line.trim()}`)
52
.join();
53
54
let errorBoundaryMessage;
55
// errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow.
56
if (errorBoundaryFound && errorBoundaryName) {
57
if (willRetry) {
59
- errorBoundaryMessage =
60
- `React will try to recreate this component tree from scratch ` +
58
+ errorBoundaryMessage = `React will try to recreate this component tree from scratch ` +
59
`using the error boundary you provided, ${errorBoundaryName}.`;
60
} else {
63
- errorBoundaryMessage =
64
- `This error was initially handled by the error boundary ${errorBoundaryName}. ` +
61
+ errorBoundaryMessage = `This error was initially handled by the error boundary ${errorBoundaryName}. ` +
62
`Recreating the tree from scratch failed so React will unmount the tree.`;
63
}
64
} else {
65
// TODO Link to unstable_handleError() documentation once it exists.
69
- errorBoundaryMessage =
70
- 'Consider adding an error boundary to your tree to customize error handling behavior.';
66
+ errorBoundaryMessage = 'Consider adding an error boundary to your tree to customize error handling behavior.';
67
}
68
69
console.error(
70
`${componentNameMessage} You should fix this error in your code. ${errorBoundaryMessage}\n\n` +
75
- `${errorSummary}\n\n` +
76
- `The error is located at: ${componentStack}\n\n` +
77
- `The error was thrown at: ${formattedCallStack}`
71
+ `${errorSummary}\n\n` +
72
+ `The error is located at: ${componentStack}\n\n` +
73
+ `The error was thrown at: ${formattedCallStack}`,
74
);
75
}
76
77
if (!__DEV__) {
82
- const { error } = capturedError;
78
+ const {error} = capturedError;
79
console.error(
84
- `React caught an error thrown by one of your components.\n\n${error.stack}`
80
+ `React caught an error thrown by one of your components.\n\n${error.stack}`,
81
);
82
}
83
}
84
85
exports.logCapturedError = logCapturedError;
90
-
src/renderers/shared/fiber/ReactFiberHostContext.js
+29
-27
@@ -12,9 +12,9 @@
12
13
'use strict';
14
15
-import type { Fiber } from 'ReactFiber';
16
-import type { HostConfig } from 'ReactFiberReconciler';
17
-import type { StackCursor } from 'ReactFiberStack';
15
+import type {Fiber} from 'ReactFiber';
16
+import type {HostConfig} from 'ReactFiberReconciler';
17
+import type {StackCursor} from 'ReactFiberStack';
18
19
const emptyObject = require('fbjs/lib/emptyObject');
20
@@ -27,38 +27,40 @@ const {
27
const invariant = require('fbjs/lib/invariant');
28
29
export type HostContext<C, CX> = {
30
- getHostContext() : CX,
31
- getRootHostContainer() : C,
32
- popHostContainer(fiber : Fiber) : void,
33
- popHostContext(fiber : Fiber) : void,
34
- pushHostContainer(fiber : Fiber, container : C) : void,
35
- pushHostContext(fiber : Fiber) : void,
36
- resetHostContainer() : void,
30
+ getHostContext(): CX,
31
+ getRootHostContainer(): C,
32
+ popHostContainer(fiber: Fiber): void,
33
+ popHostContext(fiber: Fiber): void,
34
+ pushHostContainer(fiber: Fiber, container: C): void,
35
+ pushHostContext(fiber: Fiber): void,
36
+ resetHostContainer(): void,
37
};
38
39
module.exports = function<T, P, I, TI, PI, C, CX, PL>(
40
- config : HostConfig<T, P, I, TI, PI, C, CX, PL>
41
-) : HostContext<C, CX> {
40
+ config: HostConfig<T, P, I, TI, PI, C, CX, PL>,
41
+): HostContext<C, CX> {
42
const {
43
getChildHostContext,
44
getRootHostContext,
45
} = config;
46
47
- let contextStackCursor : StackCursor<CX | null> = createCursor((null: ?CX));
48
- let contextFiberStackCursor : StackCursor<Fiber | null> = createCursor((null: Fiber | null));
49
- let rootInstanceStackCursor : StackCursor<C | null> = createCursor((null: ?C));
47
+ let contextStackCursor: StackCursor<CX | null> = createCursor((null: ?CX));
48
+ let contextFiberStackCursor: StackCursor<Fiber | null> = createCursor(
49
+ (null: Fiber | null),
50
+ );
51
+ let rootInstanceStackCursor: StackCursor<C | null> = createCursor((null: ?C));
52
51
- function getRootHostContainer() : C {
53
+ function getRootHostContainer(): C {
54
const rootInstance = rootInstanceStackCursor.current;
55
invariant(
56
rootInstance !== null,
57
'Expected root container to exist. This error is likely caused by a ' +
56
- 'bug in React. Please file an issue.'
58
+ 'bug in React. Please file an issue.',
59
);
60
return rootInstance;
61
}
62
61
- function pushHostContainer(fiber : Fiber, nextRootInstance : C) {
63
+ function pushHostContainer(fiber: Fiber, nextRootInstance: C) {
64
// Push current root instance onto the stack;
65
// This allows us to reset root when portals are popped.
66
push(rootInstanceStackCursor, nextRootInstance, fiber);
@@ -71,33 +73,33 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
73
push(contextStackCursor, nextRootContext, fiber);
74
}
75
74
- function popHostContainer(fiber : Fiber) {
76
+ function popHostContainer(fiber: Fiber) {
77
pop(contextStackCursor, fiber);
78
pop(contextFiberStackCursor, fiber);
79
pop(rootInstanceStackCursor, fiber);
80
}
81
80
- function getHostContext() : CX {
82
+ function getHostContext(): CX {
83
const context = contextStackCursor.current;
84
invariant(
85
context != null,
86
'Expected host context to exist. This error is likely caused by a bug ' +
85
- 'in React. Please file an issue.'
87
+ 'in React. Please file an issue.',
88
);
89
return context;
90
}
91
90
- function pushHostContext(fiber : Fiber) : void {
92
+ function pushHostContext(fiber: Fiber): void {
93
const rootInstance = rootInstanceStackCursor.current;
94
invariant(
95
rootInstance != null,
96
'Expected root host context to exist. This error is likely caused by ' +
95
- 'a bug in React. Please file an issue.'
97
+ 'a bug in React. Please file an issue.',
98
);
99
98
- const context = contextStackCursor.current !== null ?
99
- contextStackCursor.current :
100
- emptyObject;
100
+ const context = contextStackCursor.current !== null
101
+ ? contextStackCursor.current
102
+ : emptyObject;
103
const nextContext = getChildHostContext(context, fiber.type, rootInstance);
104
105
// Don't push this Fiber's context unless it's unique.
@@ -111,7 +113,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
113
push(contextStackCursor, nextContext, fiber);
114
}
115
114
- function popHostContext(fiber : Fiber) : void {
116
+ function popHostContext(fiber: Fiber): void {
117
// Do not pop unless this Fiber provided the current context.
118
// pushHostContext() only pushes Fibers that provide unique contexts.
119
if (contextFiberStackCursor.current !== fiber) {
src/renderers/shared/fiber/ReactFiberReconciler.js
+111
-93
@@ -12,10 +12,10 @@
12
13
'use strict';
14
15
-import type { Fiber } from 'ReactFiber';
16
-import type { FiberRoot } from 'ReactFiberRoot';
17
-import type { PriorityLevel } from 'ReactPriorityLevel';
18
-import type { ReactNodeList } from 'ReactTypes';
15
+import type {Fiber} from 'ReactFiber';
16
+import type {FiberRoot} from 'ReactFiberRoot';
17
+import type {PriorityLevel} from 'ReactPriorityLevel';
18
+import type {ReactNodeList} from 'ReactTypes';
19
20
var {
21
addTopLevelUpdate,
@@ -26,7 +26,7 @@ var {
26
isContextProvider,
27
processChildContext,
28
} = require('ReactFiberContext');
29
-var { createFiberRoot } = require('ReactFiberRoot');
29
+var {createFiberRoot} = require('ReactFiberRoot');
30
var ReactFiberScheduler = require('ReactFiberScheduler');
31
32
if (__DEV__) {
@@ -36,106 +36,121 @@ if (__DEV__) {
36
var getComponentName = require('getComponentName');
37
}
38
39
-var { findCurrentHostFiber } = require('ReactFiberTreeReflection');
39
+var {findCurrentHostFiber} = require('ReactFiberTreeReflection');
40
41
var getContextForSubtree = require('getContextForSubtree');
42
43
export type Deadline = {
44
- timeRemaining : () => number
44
+ timeRemaining: () => number,
45
};
46
47
type OpaqueHandle = Fiber;
48
type OpaqueRoot = FiberRoot;
49
50
export type HostConfig<T, P, I, TI, PI, C, CX, PL> = {
51
-
52
- getRootHostContext(rootContainerInstance : C) : CX,
53
- getChildHostContext(parentHostContext : CX, type : T) : CX,
54
- getPublicInstance(instance : I | TI) : PI,
51
+ getRootHostContext(rootContainerInstance: C): CX,
52
+ getChildHostContext(parentHostContext: CX, type: T): CX,
53
+ getPublicInstance(instance: I | TI): PI,
54
55
createInstance(
57
- type : T,
58
- props : P,
59
- rootContainerInstance : C,
60
- hostContext : CX,
61
- internalInstanceHandle : OpaqueHandle
62
- ) : I,
63
- appendInitialChild(parentInstance : I, child : I | TI) : void,
64
- finalizeInitialChildren(parentInstance : I, type : T, props : P, rootContainerInstance : C) : boolean,
56
+ type: T,
57
+ props: P,
58
+ rootContainerInstance: C,
59
+ hostContext: CX,
60
+ internalInstanceHandle: OpaqueHandle,
61
+ ): I,
62
+ appendInitialChild(parentInstance: I, child: I | TI): void,
63
+ finalizeInitialChildren(
64
+ parentInstance: I,
65
+ type: T,
66
+ props: P,
67
+ rootContainerInstance: C,
68
+ ): boolean,
69
70
prepareUpdate(
67
- instance : I,
68
- type : T,
69
- oldProps : P,
70
- newProps : P,
71
- rootContainerInstance : C,
72
- hostContext : CX
73
- ) : null | PL,
71
+ instance: I,
72
+ type: T,
73
+ oldProps: P,
74
+ newProps: P,
75
+ rootContainerInstance: C,
76
+ hostContext: CX,
77
+ ): null | PL,
78
commitUpdate(
75
- instance : I,
76
- updatePayload : PL,
77
- type : T,
78
- oldProps : P,
79
- newProps : P,
80
- internalInstanceHandle : OpaqueHandle
81
- ) : void,
82
- commitMount(instance : I, type : T, newProps : P, internalInstanceHandle : OpaqueHandle) : void,
83
-
84
- shouldSetTextContent(props : P) : boolean,
85
- resetTextContent(instance : I) : void,
86
- shouldDeprioritizeSubtree(type : T, props : P) : boolean,
79
+ instance: I,
80
+ updatePayload: PL,
81
+ type: T,
82
+ oldProps: P,
83
+ newProps: P,
84
+ internalInstanceHandle: OpaqueHandle,
85
+ ): void,
86
+ commitMount(
87
+ instance: I,
88
+ type: T,
89
+ newProps: P,
90
+ internalInstanceHandle: OpaqueHandle,
91
+ ): void,
92
+
93
+ shouldSetTextContent(props: P): boolean,
94
+ resetTextContent(instance: I): void,
95
+ shouldDeprioritizeSubtree(type: T, props: P): boolean,
96
97
createTextInstance(
89
- text : string,
90
- rootContainerInstance : C,
91
- hostContext : CX,
92
- internalInstanceHandle : OpaqueHandle
93
- ) : TI,
94
- commitTextUpdate(textInstance : TI, oldText : string, newText : string) : void,
95
-
96
- appendChild(parentInstance : I | C, child : I | TI) : void,
97
- insertBefore(parentInstance : I | C, child : I | TI, beforeChild : I | TI) : void,
98
- removeChild(parentInstance : I | C, child : I | TI) : void,
99
-
100
- scheduleAnimationCallback(callback : () => void) : number | void,
101
- scheduleDeferredCallback(callback : (deadline : Deadline) => void) : number | void,
102
-
103
- prepareForCommit() : void,
104
- resetAfterCommit() : void,
105
-
106
- useSyncScheduling ?: boolean,
98
+ text: string,
99
+ rootContainerInstance: C,
100
+ hostContext: CX,
101
+ internalInstanceHandle: OpaqueHandle,
102
+ ): TI,
103
+ commitTextUpdate(textInstance: TI, oldText: string, newText: string): void,
104
+
105
+ appendChild(parentInstance: I | C, child: I | TI): void,
106
+ insertBefore(parentInstance: I | C, child: I | TI, beforeChild: I | TI): void,
107
+ removeChild(parentInstance: I | C, child: I | TI): void,
108
+
109
+ scheduleAnimationCallback(callback: () => void): number | void,
110
+ scheduleDeferredCallback(callback: (deadline: Deadline) => void):
111
+ | number
112
+ | void,
113
+
114
+ prepareForCommit(): void,
115
+ resetAfterCommit(): void,
116
+
117
+ useSyncScheduling?: boolean,
118
};
119
120
export type Reconciler<C, I, TI> = {
110
- createContainer(containerInfo : C) : OpaqueRoot,
121
+ createContainer(containerInfo: C): OpaqueRoot,
122
updateContainer(
112
- element : ReactNodeList,
113
- container : OpaqueRoot,
114
- parentComponent : ?ReactComponent<any, any, any>
115
- ) : void,
116
- performWithPriority(priorityLevel : PriorityLevel, fn : Function) : void,
117
- batchedUpdates<A>(fn : () => A) : A,
118
- unbatchedUpdates<A>(fn : () => A) : A,
119
- syncUpdates<A>(fn : () => A) : A,
120
- deferredUpdates<A>(fn : () => A) : A,
123
+ element: ReactNodeList,
124
+ container: OpaqueRoot,
125
+ parentComponent: ?ReactComponent<any, any, any>,
126
+ ): void,
127
+ performWithPriority(priorityLevel: PriorityLevel, fn: Function): void,
128
+ batchedUpdates<A>(fn: () => A): A,
129
+ unbatchedUpdates<A>(fn: () => A): A,
130
+ syncUpdates<A>(fn: () => A): A,
131
+ deferredUpdates<A>(fn: () => A): A,
132
133
// Used to extract the return value from the initial render. Legacy API.
123
- getPublicRootInstance(container : OpaqueRoot) : (ReactComponent<any, any, any> | TI | I | null),
134
+ getPublicRootInstance(container: OpaqueRoot):
135
+ | ReactComponent<any, any, any>
136
+ | TI
137
+ | I
138
+ | null,
139
140
// Use for findDOMNode/findHostNode. Legacy API.
126
- findHostInstance(component : Fiber) : I | TI | null,
141
+ findHostInstance(component: Fiber): I | TI | null,
142
};
143
129
-getContextForSubtree._injectFiber(function(fiber : Fiber) {
144
+getContextForSubtree._injectFiber(function(fiber: Fiber) {
145
const parentContext = findCurrentUnmaskedContext(fiber);
131
- return isContextProvider(fiber) ?
132
- processChildContext(fiber, parentContext, false) :
133
- parentContext;
146
+ return isContextProvider(fiber)
147
+ ? processChildContext(fiber, parentContext, false)
148
+ : parentContext;
149
});
150
151
module.exports = function<T, P, I, TI, PI, C, CX, PL>(
137
- config : HostConfig<T, P, I, TI, PI, C, CX, PL>
138
-) : Reconciler<C, I, TI> {
152
+ config: HostConfig<T, P, I, TI, PI, C, CX, PL>,
153
+): Reconciler<C, I, TI> {
154
var {
155
scheduleUpdate,
156
getPriorityContext,
@@ -146,7 +161,11 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
161
deferredUpdates,
162
} = ReactFiberScheduler(config);
163
149
- function scheduleTopLevelUpdate(current : Fiber, element : ReactNodeList, callback : ?Function) {
164
+ function scheduleTopLevelUpdate(
165
+ current: Fiber,
166
+ element: ReactNodeList,
167
+ callback: ?Function,
168
+ ) {
169
if (__DEV__) {
170
if (
171
ReactDebugCurrentFiber.phase === 'render' &&
@@ -155,23 +174,23 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
174
warning(
175
false,
176
'Render methods should be a pure function of props and state; ' +
158
- 'triggering nested component updates from render is not allowed. ' +
159
- 'If necessary, trigger nested updates in componentDidUpdate.\n\n' +
160
- 'Check the render method of %s.',
161
- getComponentName(ReactDebugCurrentFiber.current) || 'Unknown'
177
+ 'triggering nested component updates from render is not allowed. ' +
178
+ 'If necessary, trigger nested updates in componentDidUpdate.\n\n' +
179
+ 'Check the render method of %s.',
180
+ getComponentName(ReactDebugCurrentFiber.current) || 'Unknown',
181
);
182
}
183
}
184
185
const priorityLevel = getPriorityContext();
167
- const nextState = { element };
186
+ const nextState = {element};
187
callback = callback === undefined ? null : callback;
188
if (__DEV__) {
189
warning(
190
callback === null || typeof callback === 'function',
191
'render(...): Expected the last optional `callback` argument to be a ' +
173
- 'function. Instead received: %s.',
174
- callback
192
+ 'function. Instead received: %s.',
193
+ callback,
194
);
195
}
196
addTopLevelUpdate(current, nextState, callback, priorityLevel);
@@ -179,17 +198,16 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
198
}
199
200
return {
182
-
183
- createContainer(containerInfo : C) : OpaqueRoot {
201
+ createContainer(containerInfo: C): OpaqueRoot {
202
return createFiberRoot(containerInfo);
203
},
204
205
updateContainer(
188
- element : ReactNodeList,
189
- container : OpaqueRoot,
190
- parentComponent : ?ReactComponent<any, any, any>,
191
- callback: ?Function
192
- ) : void {
206
+ element: ReactNodeList,
207
+ container: OpaqueRoot,
208
+ parentComponent: ?ReactComponent<any, any, any>,
209
+ callback: ?Function,
210
+ ): void {
211
// TODO: If this is a nested container, this won't be the root.
212
const current = container.current;
213
@@ -225,7 +243,9 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
243
244
deferredUpdates,
245
228
- getPublicRootInstance(container : OpaqueRoot) : (ReactComponent<any, any, any> | I | TI | null) {
246
+ getPublicRootInstance(
247
+ container: OpaqueRoot,
248
+ ): ReactComponent<any, any, any> | I | TI | null {
249
const containerFiber = container.current;
250
if (!containerFiber.child) {
251
return null;
@@ -233,14 +253,12 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
253
return containerFiber.child.stateNode;
254
},
255
236
- findHostInstance(fiber : Fiber) : I | TI | null {
256
+ findHostInstance(fiber: Fiber): I | TI | null {
257
const hostFiber = findCurrentHostFiber(fiber);
258
if (hostFiber === null) {
259
return null;
260
}
261
return hostFiber.stateNode;
262
},
243
-
263
};
245
-
264
};
src/renderers/shared/fiber/ReactFiberRoot.js
+3
-3
@@ -12,9 +12,9 @@
12
13
'use strict';
14
15
-import type { Fiber } from 'ReactFiber';
15
+import type {Fiber} from 'ReactFiber';
16
17
-const { createHostRootFiber } = require('ReactFiber');
17
+const {createHostRootFiber} = require('ReactFiber');
18
19
export type FiberRoot = {
20
// Any additional information from the host associated with this root.
@@ -30,7 +30,7 @@ export type FiberRoot = {
30
pendingContext: Object | null,
31
};
32
33
-exports.createFiberRoot = function(containerInfo : any) : FiberRoot {
33
+exports.createFiberRoot = function(containerInfo: any): FiberRoot {
34
// Cyclic construction. This cheats the type system right now because
35
// stateNode is any.
36
const uninitializedFiber = createHostRootFiber();
src/renderers/shared/fiber/ReactFiberScheduler.js
+169
-130
@@ -12,34 +12,34 @@
12
13
'use strict';
14
15
-import type { Fiber } from 'ReactFiber';
16
-import type { FiberRoot } from 'ReactFiberRoot';
17
-import type { HostConfig, Deadline } from 'ReactFiberReconciler';
18
-import type { PriorityLevel } from 'ReactPriorityLevel';
15
+import type {Fiber} from 'ReactFiber';
16
+import type {FiberRoot} from 'ReactFiberRoot';
17
+import type {HostConfig, Deadline} from 'ReactFiberReconciler';
18
+import type {PriorityLevel} from 'ReactPriorityLevel';
19
20
export type CapturedError = {
21
- componentName : ?string,
22
- componentStack : string,
23
- error : Error,
24
- errorBoundary : ?Object,
25
- errorBoundaryFound : boolean,
26
- errorBoundaryName : string | null,
27
- willRetry : boolean,
21
+ componentName: ?string,
22
+ componentStack: string,
23
+ error: Error,
24
+ errorBoundary: ?Object,
25
+ errorBoundaryFound: boolean,
26
+ errorBoundaryName: string | null,
27
+ willRetry: boolean,
28
};
29
30
export type HandleErrorInfo = {
31
- componentStack : string,
31
+ componentStack: string,
32
};
33
34
var {
35
popContextProvider,
36
} = require('ReactFiberContext');
37
-const { reset } = require('ReactFiberStack');
37
+const {reset} = require('ReactFiberStack');
38
var {
39
getStackAddendumByWorkInProgressFiber,
40
} = require('ReactFiberComponentTreeHook');
41
-var { logCapturedError } = require('ReactFiberErrorLogger');
42
-var { invokeGuardedCallback } = require('ReactErrorUtils');
41
+var {logCapturedError} = require('ReactFiberErrorLogger');
42
+var {invokeGuardedCallback} = require('ReactErrorUtils');
43
44
var ReactFiberBeginWork = require('ReactFiberBeginWork');
45
var ReactFiberCompleteWork = require('ReactFiberCompleteWork');
@@ -49,8 +49,8 @@ var ReactCurrentOwner = require('react/lib/ReactCurrentOwner');
49
var ReactFeatureFlags = require('ReactFeatureFlags');
50
var getComponentName = require('getComponentName');
51
52
-var { cloneFiber } = require('ReactFiber');
53
-var { onCommitRoot } = require('ReactFiberDevToolsHook');
52
+var {cloneFiber} = require('ReactFiber');
53
+var {onCommitRoot} = require('ReactFiberDevToolsHook');
54
55
var {
56
NoWork,
@@ -110,19 +110,19 @@ if (__DEV__) {
110
stopCommitLifeCyclesTimer,
111
} = require('ReactDebugFiberPerf');
112
113
- var warnAboutUpdateOnUnmounted = function(instance : ReactClass<any>) {
113
+ var warnAboutUpdateOnUnmounted = function(instance: ReactClass<any>) {
114
const ctor = instance.constructor;
115
warning(
116
false,
117
'Can only update a mounted or mounting component. This usually means ' +
118
- 'you called setState, replaceState, or forceUpdate on an unmounted ' +
119
- 'component. This is a no-op.\n\nPlease check the code for the ' +
120
- '%s component.',
121
- ctor && (ctor.displayName || ctor.name) || 'ReactClass'
118
+ 'you called setState, replaceState, or forceUpdate on an unmounted ' +
119
+ 'component. This is a no-op.\n\nPlease check the code for the ' +
120
+ '%s component.',
121
+ (ctor && (ctor.displayName || ctor.name)) || 'ReactClass',
122
);
123
};
124
125
- var warnAboutInvalidUpdates = function(instance : ReactClass<any>) {
125
+ var warnAboutInvalidUpdates = function(instance: ReactClass<any>) {
126
switch (ReactDebugCurrentFiber.phase) {
127
case 'getChildContext':
128
warning(
@@ -134,9 +134,9 @@ if (__DEV__) {
134
warning(
135
false,
136
'Cannot update during an existing state transition (such as within ' +
137
- '`render` or another component\'s constructor). Render methods should ' +
138
- 'be a pure function of props and state; constructor side-effects are ' +
139
- 'an anti-pattern, but can be moved to `componentWillMount`.'
137
+ "`render` or another component's constructor). Render methods should " +
138
+ 'be a pure function of props and state; constructor side-effects are ' +
139
+ 'an anti-pattern, but can be moved to `componentWillMount`.',
140
);
141
break;
142
}
@@ -145,16 +145,18 @@ if (__DEV__) {
145
146
var timeHeuristicForUnitOfWork = 1;
147
148
-module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P, I, TI, PI, C, CX, PL>) {
148
+module.exports = function<T, P, I, TI, PI, C, CX, PL>(
149
+ config: HostConfig<T, P, I, TI, PI, C, CX, PL>,
150
+) {
151
const hostContext = ReactFiberHostContext(config);
150
- const { popHostContainer, popHostContext, resetHostContainer } = hostContext;
151
- const { beginWork, beginFailedWork } = ReactFiberBeginWork(
152
+ const {popHostContainer, popHostContext, resetHostContainer} = hostContext;
153
+ const {beginWork, beginFailedWork} = ReactFiberBeginWork(
154
config,
155
hostContext,
156
scheduleUpdate,
157
getPriorityContext,
158
);
157
- const { completeWork } = ReactFiberCompleteWork(config, hostContext);
159
+ const {completeWork} = ReactFiberCompleteWork(config, hostContext);
160
const {
161
commitPlacement,
162
commitDeletion,
@@ -173,55 +175,55 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
175
176
// The priority level to use when scheduling an update.
177
// TODO: Should we change this to an array? Might be less confusing.
176
- let priorityContext : PriorityLevel = useSyncScheduling ?
177
- SynchronousPriority :
178
- LowPriority;
178
+ let priorityContext: PriorityLevel = useSyncScheduling
179
+ ? SynchronousPriority
180
+ : LowPriority;
181
182
// Keep track of this so we can reset the priority context if an error
183
// is thrown during reconciliation.
182
- let priorityContextBeforeReconciliation : PriorityLevel = NoWork;
184
+ let priorityContextBeforeReconciliation: PriorityLevel = NoWork;
185
186
// Keeps track of whether we're currently in a work loop.
185
- let isPerformingWork : boolean = false;
187
+ let isPerformingWork: boolean = false;
188
189
// Keeps track of whether the current deadline has expired.
188
- let deadlineHasExpired : boolean = false;
190
+ let deadlineHasExpired: boolean = false;
191
192
// Keeps track of whether we should should batch sync updates.
191
- let isBatchingUpdates : boolean = false;
193
+ let isBatchingUpdates: boolean = false;
194
195
// The next work in progress fiber that we're currently working on.
194
- let nextUnitOfWork : Fiber | null = null;
195
- let nextPriorityLevel : PriorityLevel = NoWork;
196
+ let nextUnitOfWork: Fiber | null = null;
197
+ let nextPriorityLevel: PriorityLevel = NoWork;
198
199
// The next fiber with an effect that we're currently committing.
198
- let nextEffect : Fiber | null = null;
200
+ let nextEffect: Fiber | null = null;
201
200
- let pendingCommit : Fiber | null = null;
202
+ let pendingCommit: Fiber | null = null;
203
204
// Linked list of roots with scheduled work on them.
203
- let nextScheduledRoot : FiberRoot | null = null;
204
- let lastScheduledRoot : FiberRoot | null = null;
205
+ let nextScheduledRoot: FiberRoot | null = null;
206
+ let lastScheduledRoot: FiberRoot | null = null;
207
208
// Keep track of which host environment callbacks are scheduled.
207
- let isAnimationCallbackScheduled : boolean = false;
208
- let isDeferredCallbackScheduled : boolean = false;
209
+ let isAnimationCallbackScheduled: boolean = false;
210
+ let isDeferredCallbackScheduled: boolean = false;
211
212
// Keep track of which fibers have captured an error that need to be handled.
213
// Work is removed from this collection after unstable_handleError is called.
212
- let capturedErrors : Map<Fiber, CapturedError> | null = null;
214
+ let capturedErrors: Map<Fiber, CapturedError> | null = null;
215
// Keep track of which fibers have failed during the current batch of work.
216
// This is a different set than capturedErrors, because it is not reset until
217
// the end of the batch. This is needed to propagate errors correctly if a
218
// subtree fails more than once.
217
- let failedBoundaries : Set<Fiber> | null = null;
219
+ let failedBoundaries: Set<Fiber> | null = null;
220
// Error boundaries that captured an error during the current commit.
219
- let commitPhaseBoundaries : Set<Fiber> | null = null;
220
- let firstUncaughtError : Error | null = null;
221
- let fatalError : Error | null = null;
221
+ let commitPhaseBoundaries: Set<Fiber> | null = null;
222
+ let firstUncaughtError: Error | null = null;
223
+ let fatalError: Error | null = null;
224
223
- let isCommitting : boolean = false;
224
- let isUnmounting : boolean = false;
225
+ let isCommitting: boolean = false;
226
+ let isUnmounting: boolean = false;
227
228
function scheduleAnimationCallback(callback) {
229
if (!isAnimationCallbackScheduled) {
@@ -250,7 +252,10 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
252
// the work loop.
253
function findNextUnitOfWork() {
254
// Clear out roots with no more work on them, or if they have uncaught errors
253
- while (nextScheduledRoot !== null && nextScheduledRoot.current.pendingWorkPriority === NoWork) {
255
+ while (
256
+ nextScheduledRoot !== null &&
257
+ nextScheduledRoot.current.pendingWorkPriority === NoWork
258
+ ) {
259
// Unschedule this root.
260
nextScheduledRoot.isScheduled = false;
261
// Read the next pointer now.
@@ -273,9 +278,11 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
278
let highestPriorityRoot = null;
279
let highestPriorityLevel = NoWork;
280
while (root !== null) {
276
- if (root.current.pendingWorkPriority !== NoWork && (
277
- highestPriorityLevel === NoWork ||
278
- highestPriorityLevel > root.current.pendingWorkPriority)) {
281
+ if (
282
+ root.current.pendingWorkPriority !== NoWork &&
283
+ (highestPriorityLevel === NoWork ||
284
+ highestPriorityLevel > root.current.pendingWorkPriority)
285
+ ) {
286
highestPriorityLevel = root.current.pendingWorkPriority;
287
highestPriorityRoot = root;
288
}
@@ -293,10 +300,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
300
// unfortunately this is it.
301
resetContextStack();
302
296
- return cloneFiber(
297
- highestPriorityRoot.current,
298
- highestPriorityLevel
299
- );
303
+ return cloneFiber(highestPriorityRoot.current, highestPriorityLevel);
304
}
305
306
nextPriorityLevel = NoWork;
@@ -409,7 +413,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
413
}
414
}
415
412
- function commitAllWork(finishedWork : Fiber) {
416
+ function commitAllWork(finishedWork: Fiber) {
417
// We keep track of this so that captureError can collect any boundaries
418
// that capture an error during the commit phase. The reason these aren't
419
// local to this function is because errors that occur during cWU are
@@ -420,12 +424,12 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
424
}
425
426
pendingCommit = null;
423
- const root : FiberRoot = (finishedWork.stateNode : any);
427
+ const root: FiberRoot = (finishedWork.stateNode: any);
428
invariant(
429
root.current !== finishedWork,
430
'Cannot commit the same tree as before. This is probably a bug ' +
427
- 'related to the return field. This error is likely caused by a bug ' +
428
- 'in React. Please file an issue.'
431
+ 'related to the return field. This error is likely caused by a bug ' +
432
+ 'in React. Please file an issue.',
433
);
434
435
// Reset this to null before calling lifecycles
@@ -464,7 +468,12 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
468
while (nextEffect !== null) {
469
let error = null;
470
if (__DEV__) {
467
- error = invokeGuardedCallback(null, commitAllHostEffects, null, finishedWork);
471
+ error = invokeGuardedCallback(
472
+ null,
473
+ commitAllHostEffects,
474
+ null,
475
+ finishedWork,
476
+ );
477
} else {
478
try {
479
commitAllHostEffects(finishedWork);
@@ -476,7 +485,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
485
invariant(
486
nextEffect !== null,
487
'Should have next effect. This error is likely caused by a bug ' +
479
- 'in React. Please file an issue.'
488
+ 'in React. Please file an issue.',
489
);
490
captureError(nextEffect, error);
491
// Clean-up
@@ -508,7 +517,12 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
517
while (nextEffect !== null) {
518
let error = null;
519
if (__DEV__) {
511
- error = invokeGuardedCallback(null, commitAllLifeCycles, null, finishedWork);
520
+ error = invokeGuardedCallback(
521
+ null,
522
+ commitAllLifeCycles,
523
+ null,
524
+ finishedWork,
525
+ );
526
} else {
527
try {
528
commitAllLifeCycles(finishedWork);
@@ -520,7 +534,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
534
invariant(
535
nextEffect !== null,
536
'Should have next effect. This error is likely caused by a bug ' +
523
- 'in React. Please file an issue.'
537
+ 'in React. Please file an issue.',
538
);
539
captureError(nextEffect, error);
540
if (nextEffect !== null) {
@@ -551,7 +565,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
565
priorityContext = previousPriorityContext;
566
}
567
554
- function resetWorkPriority(workInProgress : Fiber) {
568
+ function resetWorkPriority(workInProgress: Fiber) {
569
let newPriority = NoWork;
570
571
// Check for pending update priority. This is usually null so it shouldn't
@@ -569,9 +583,10 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
583
let child = workInProgress.progressedChild;
584
while (child !== null) {
585
// Ensure that remaining work priority bubbles up.
572
- if (child.pendingWorkPriority !== NoWork &&
573
- (newPriority === NoWork ||
574
- newPriority > child.pendingWorkPriority)) {
586
+ if (
587
+ child.pendingWorkPriority !== NoWork &&
588
+ (newPriority === NoWork || newPriority > child.pendingWorkPriority)
589
+ ) {
590
newPriority = child.pendingWorkPriority;
591
}
592
child = child.sibling;
@@ -579,7 +594,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
594
workInProgress.pendingWorkPriority = newPriority;
595
}
596
582
- function completeUnitOfWork(workInProgress : Fiber) : Fiber | null {
597
+ function completeUnitOfWork(workInProgress: Fiber): Fiber | null {
598
while (true) {
599
// The current, flushed, state of this fiber is the alternate.
600
// Ideally nothing should rely on this, but relying on it here
@@ -665,7 +680,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
680
}
681
}
682
668
- function performUnitOfWork(workInProgress : Fiber) : Fiber | null {
683
+ function performUnitOfWork(workInProgress: Fiber): Fiber | null {
684
// The current, flushed, state of this fiber is the alternate.
685
// Ideally nothing should rely on this, but relying on it here
686
// means that we don't need an additional field on the work in
@@ -694,8 +709,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
709
return next;
710
}
711
697
- function performFailedUnitOfWork(workInProgress : Fiber) : Fiber | null {
698
-
712
+ function performFailedUnitOfWork(workInProgress: Fiber): Fiber | null {
713
// The current, flushed, state of this fiber is the alternate.
714
// Ideally nothing should rely on this, but relying on it here
715
// means that we don't need an additional field on the work in
@@ -741,10 +755,13 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
755
nextUnitOfWork = findNextUnitOfWork();
756
}
757
// Keep performing work until there are no more errors
744
- while (capturedErrors !== null && capturedErrors.size &&
745
- nextUnitOfWork !== null &&
746
- nextPriorityLevel !== NoWork &&
747
- nextPriorityLevel <= TaskPriority) {
758
+ while (
759
+ capturedErrors !== null &&
760
+ capturedErrors.size &&
761
+ nextUnitOfWork !== null &&
762
+ nextPriorityLevel !== NoWork &&
763
+ nextPriorityLevel <= TaskPriority
764
+ ) {
765
if (hasCapturedError(nextUnitOfWork)) {
766
// Use a forked version of performUnitOfWork
767
nextUnitOfWork = performFailedUnitOfWork(nextUnitOfWork);
@@ -761,7 +778,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
778
}
779
}
780
764
- function workLoop(priorityLevel, deadline : Deadline | null) {
781
+ function workLoop(priorityLevel, deadline: Deadline | null) {
782
// Clear any errors.
783
clearErrors();
784
@@ -813,9 +830,11 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
830
// If there's no deadline, or if we're performing Task work, use this loop
831
// that doesn't check how much time is remaining. It will keep running
832
// until we run out of work at this priority level.
816
- while (nextUnitOfWork !== null &&
817
- nextPriorityLevel !== NoWork &&
818
- nextPriorityLevel <= priorityLevel) {
833
+ while (
834
+ nextUnitOfWork !== null &&
835
+ nextPriorityLevel !== NoWork &&
836
+ nextPriorityLevel <= priorityLevel
837
+ ) {
838
nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
839
if (nextUnitOfWork === null) {
840
nextUnitOfWork = findNextUnitOfWork();
@@ -831,7 +850,10 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
850
}
851
}
852
834
- function performWork(priorityLevel : PriorityLevel, deadline : Deadline | null) {
853
+ function performWork(
854
+ priorityLevel: PriorityLevel,
855
+ deadline: Deadline | null,
856
+ ) {
857
if (__DEV__) {
858
startWorkLoopTimer();
859
}
@@ -839,7 +861,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
861
invariant(
862
!isPerformingWork,
863
'performWork was called recursively. This error is likely caused ' +
842
- 'by a bug in React. Please file an issue.'
864
+ 'by a bug in React. Please file an issue.',
865
);
866
isPerformingWork = true;
867
const isPerformingDeferredWork = !!deadline;
@@ -849,9 +871,9 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
871
// deferred batch.
872
while (priorityLevel !== NoWork && !fatalError) {
873
invariant(
852
- deadline !== null || (priorityLevel < HighPriority),
874
+ deadline !== null || priorityLevel < HighPriority,
875
'Cannot perform deferred work without a deadline. This error is ' +
854
- 'likely caused by a bug in React. Please file an issue.'
876
+ 'likely caused by a bug in React. Please file an issue.',
877
);
878
879
// Before starting any work, check to see if there are any pending
@@ -866,7 +888,13 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
888
priorityContextBeforeReconciliation = priorityContext;
889
let error = null;
890
if (__DEV__) {
869
- error = invokeGuardedCallback(null, workLoop, null, priorityLevel, deadline);
891
+ error = invokeGuardedCallback(
892
+ null,
893
+ workLoop,
894
+ null,
895
+ priorityLevel,
896
+ deadline,
897
+ );
898
} else {
899
try {
900
workLoop(priorityLevel, deadline);
@@ -919,7 +947,11 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
947
948
// If have we more work, and we're in a deferred batch, check to see
949
// if the deadline has expired.
922
- if (nextPriorityLevel !== NoWork && isPerformingDeferredWork && !deadlineHasExpired) {
950
+ if (
951
+ nextPriorityLevel !== NoWork &&
952
+ isPerformingDeferredWork &&
953
+ !deadlineHasExpired
954
+ ) {
955
// We have more time to do work.
956
priorityLevel = nextPriorityLevel;
957
continue;
@@ -970,7 +1002,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
1002
}
1003
1004
// Returns the boundary that captured the error, or null if the error is ignored
973
- function captureError(failedWork : Fiber, error : Error) : Fiber | null {
1005
+ function captureError(failedWork: Fiber, error: Error): Fiber | null {
1006
// It is no longer valid because we exited the user code.
1007
ReactCurrentOwner.current = null;
1008
if (__DEV__) {
@@ -981,12 +1013,12 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
1013
nextUnitOfWork = null;
1014
1015
// Search for the nearest error boundary.
984
- let boundary : Fiber | null = null;
1016
+ let boundary: Fiber | null = null;
1017
1018
// Passed to logCapturedError()
987
- let errorBoundaryFound : boolean = false;
988
- let willRetry : boolean = false;
989
- let errorBoundaryName : string | null = null;
1019
+ let errorBoundaryFound: boolean = false;
1020
+ let willRetry: boolean = false;
1021
+ let errorBoundaryName: string | null = null;
1022
1023
// Host containers are a special case. If the failed work itself is a host
1024
// container, then it acts as its own boundary. In all other cases, we
@@ -1032,10 +1064,12 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
1064
// this boundary already captured an error during this commit.
1065
// This case exists because multiple errors can be thrown during
1066
// a single commit without interruption.
1035
- if (commitPhaseBoundaries !== null && (
1036
- commitPhaseBoundaries.has(node) ||
1037
- (node.alternate !== null && commitPhaseBoundaries.has(node.alternate))
1038
- )) {
1067
+ if (
1068
+ commitPhaseBoundaries !== null &&
1069
+ (commitPhaseBoundaries.has(node) ||
1070
+ (node.alternate !== null &&
1071
+ commitPhaseBoundaries.has(node.alternate)))
1072
+ ) {
1073
// If so, we should ignore this error.
1074
return null;
1075
}
@@ -1100,25 +1134,23 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
1134
return null;
1135
}
1136
1103
- function hasCapturedError(fiber : Fiber) : boolean {
1137
+ function hasCapturedError(fiber: Fiber): boolean {
1138
// TODO: capturedErrors should store the boundary instance, to avoid needing
1139
// to check the alternate.
1106
- return (
1107
- capturedErrors !== null &&
1108
- (capturedErrors.has(fiber) || (fiber.alternate !== null && capturedErrors.has(fiber.alternate)))
1109
- );
1140
+ return capturedErrors !== null &&
1141
+ (capturedErrors.has(fiber) ||
1142
+ (fiber.alternate !== null && capturedErrors.has(fiber.alternate)));
1143
}
1144
1112
- function isFailedBoundary(fiber : Fiber) : boolean {
1145
+ function isFailedBoundary(fiber: Fiber): boolean {
1146
// TODO: failedBoundaries should store the boundary instance, to avoid
1147
// needing to check the alternate.
1115
- return (
1116
- failedBoundaries !== null &&
1117
- (failedBoundaries.has(fiber) || (fiber.alternate !== null && failedBoundaries.has(fiber.alternate)))
1118
- );
1148
+ return failedBoundaries !== null &&
1149
+ (failedBoundaries.has(fiber) ||
1150
+ (fiber.alternate !== null && failedBoundaries.has(fiber.alternate)));
1151
}
1152
1121
- function commitErrorHandling(effectfulFiber : Fiber) {
1153
+ function commitErrorHandling(effectfulFiber: Fiber) {
1154
let capturedError;
1155
if (capturedErrors !== null) {
1156
capturedError = capturedErrors.get(effectfulFiber);
@@ -1135,7 +1167,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
1167
invariant(
1168
capturedError != null,
1169
'No error for given unit of work. This error is likely caused by a ' +
1138
- 'bug in React. Please file an issue.'
1170
+ 'bug in React. Please file an issue.',
1171
);
1172
1173
const error = capturedError.error;
@@ -1151,7 +1183,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
1183
case ClassComponent:
1184
const instance = effectfulFiber.stateNode;
1185
1154
- const info : HandleErrorInfo = {
1186
+ const info: HandleErrorInfo = {
1187
componentStack: capturedError.componentStack,
1188
};
1189
@@ -1171,14 +1203,14 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
1203
invariant(
1204
false,
1205
'Invalid type of work. This error is likely caused by a bug in ' +
1174
- 'React. Please file an issue.'
1206
+ 'React. Please file an issue.',
1207
);
1208
}
1209
}
1210
1179
- function unwindContexts(from : Fiber, to: Fiber) {
1211
+ function unwindContexts(from: Fiber, to: Fiber) {
1212
let node = from;
1181
- while (node !== null && (node !== to) && (node.alternate !== to)) {
1213
+ while (node !== null && node !== to && node.alternate !== to) {
1214
switch (node.tag) {
1215
case ClassComponent:
1216
popContextProvider(node);
@@ -1200,7 +1232,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
1232
}
1233
}
1234
1203
- function scheduleRoot(root : FiberRoot, priorityLevel : PriorityLevel) {
1235
+ function scheduleRoot(root: FiberRoot, priorityLevel: PriorityLevel) {
1236
if (priorityLevel === NoWork) {
1237
return;
1238
}
@@ -1219,7 +1251,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
1251
}
1252
}
1253
1222
- function scheduleUpdate(fiber : Fiber, priorityLevel : PriorityLevel) {
1254
+ function scheduleUpdate(fiber: Fiber, priorityLevel: PriorityLevel) {
1255
if (__DEV__) {
1256
recordScheduleUpdate();
1257
}
@@ -1245,15 +1277,19 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
1277
// we reach a node whose priority matches (and whose alternate's priority
1278
// matches) we can exit safely knowing that the rest of the path is correct.
1279
shouldContinue = false;
1248
- if (node.pendingWorkPriority === NoWork ||
1249
- node.pendingWorkPriority > priorityLevel) {
1280
+ if (
1281
+ node.pendingWorkPriority === NoWork ||
1282
+ node.pendingWorkPriority > priorityLevel
1283
+ ) {
1284
// Priority did not match. Update and keep going.
1285
shouldContinue = true;
1286
node.pendingWorkPriority = priorityLevel;
1287
}
1288
if (node.alternate !== null) {
1255
- if (node.alternate.pendingWorkPriority === NoWork ||
1256
- node.alternate.pendingWorkPriority > priorityLevel) {
1289
+ if (
1290
+ node.alternate.pendingWorkPriority === NoWork ||
1291
+ node.alternate.pendingWorkPriority > priorityLevel
1292
+ ) {
1293
// Priority did not match. Update and keep going.
1294
shouldContinue = true;
1295
node.alternate.pendingWorkPriority = priorityLevel;
@@ -1261,7 +1297,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
1297
}
1298
if (node.return === null) {
1299
if (node.tag === HostRoot) {
1264
- const root : FiberRoot = (node.stateNode : any);
1300
+ const root: FiberRoot = (node.stateNode: any);
1301
scheduleRoot(root, priorityLevel);
1302
// Depending on the priority level, either perform work now or
1303
// schedule a callback to perform work later.
@@ -1295,20 +1331,23 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
1331
}
1332
}
1333
1298
- function getPriorityContext() : PriorityLevel {
1334
+ function getPriorityContext(): PriorityLevel {
1335
// If we're in a batch, or if we're already performing work, downgrade sync
1336
// priority to task priority
1301
- if (priorityContext === SynchronousPriority && (isPerformingWork || isBatchingUpdates)) {
1337
+ if (
1338
+ priorityContext === SynchronousPriority &&
1339
+ (isPerformingWork || isBatchingUpdates)
1340
+ ) {
1341
return TaskPriority;
1342
}
1343
return priorityContext;
1344
}
1345
1307
- function scheduleErrorRecovery(fiber : Fiber) {
1346
+ function scheduleErrorRecovery(fiber: Fiber) {
1347
scheduleUpdate(fiber, TaskPriority);
1348
}
1349
1311
- function performWithPriority(priorityLevel : PriorityLevel, fn : Function) {
1350
+ function performWithPriority(priorityLevel: PriorityLevel, fn: Function) {
1351
const previousPriorityContext = priorityContext;
1352
priorityContext = priorityLevel;
1353
try {
@@ -1318,7 +1357,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
1357
}
1358
}
1359
1321
- function batchedUpdates<A, R>(fn : (a: A) => R, a : A) : R {
1360
+ function batchedUpdates<A, R>(fn: (a: A) => R, a: A): R {
1361
const previousIsBatchingUpdates = isBatchingUpdates;
1362
isBatchingUpdates = true;
1363
try {
@@ -1333,7 +1372,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
1372
}
1373
}
1374
1336
- function unbatchedUpdates<A>(fn : () => A) : A {
1375
+ function unbatchedUpdates<A>(fn: () => A): A {
1376
const previousIsBatchingUpdates = isBatchingUpdates;
1377
isBatchingUpdates = false;
1378
try {
@@ -1343,7 +1382,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
1382
}
1383
}
1384
1346
- function syncUpdates<A>(fn : () => A) : A {
1385
+ function syncUpdates<A>(fn: () => A): A {
1386
const previousPriorityContext = priorityContext;
1387
priorityContext = SynchronousPriority;
1388
try {
@@ -1353,7 +1392,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(config : HostConfig<T, P,
1392
}
1393
}
1394
1356
- function deferredUpdates<A>(fn : () => A) : A {
1395
+ function deferredUpdates<A>(fn: () => A): A {
1396
const previousPriorityContext = priorityContext;
1397
priorityContext = LowPriority;
1398
try {
src/renderers/shared/fiber/ReactFiberStack.js
+11
-14
@@ -12,36 +12,33 @@
12
13
'use strict';
14
15
-import type { Fiber } from 'ReactFiber';
15
+import type {Fiber} from 'ReactFiber';
16
17
export type StackCursor<T> = {
18
- current: T
18
+ current: T,
19
};
20
21
const warning = require('fbjs/lib/warning');
22
23
-const valueStack : Array<any> = [];
23
+const valueStack: Array<any> = [];
24
25
if (__DEV__) {
26
- var fiberStack : Array<Fiber | null> = [];
26
+ var fiberStack: Array<Fiber | null> = [];
27
}
28
29
let index = -1;
30
31
-exports.createCursor = function<T>(defaultValue : T) : StackCursor<T> {
31
+exports.createCursor = function<T>(defaultValue: T): StackCursor<T> {
32
return {
33
current: defaultValue,
34
};
35
};
36
37
-exports.isEmpty = function() : boolean {
37
+exports.isEmpty = function(): boolean {
38
return index === -1;
39
};
40
41
-exports.pop = function<T>(
42
- cursor : StackCursor<T>,
43
- fiber: Fiber,
44
-) : void {
41
+exports.pop = function<T>(cursor: StackCursor<T>, fiber: Fiber): void {
42
if (index < 0) {
43
if (__DEV__) {
44
warning(false, 'Unexpected pop.');
@@ -67,10 +64,10 @@ exports.pop = function<T>(
64
};
65
66
exports.push = function<T>(
70
- cursor : StackCursor<T>,
71
- value : T,
67
+ cursor: StackCursor<T>,
68
+ value: T,
69
fiber: Fiber,
73
-) : void {
70
+): void {
71
index++;
72
73
valueStack[index] = cursor.current;
@@ -82,7 +79,7 @@ exports.push = function<T>(
79
cursor.current = value;
80
};
81
85
-exports.reset = function() : void {
82
+exports.reset = function(): void {
83
while (index > -1) {
84
valueStack[index] = null;
85
src/renderers/shared/fiber/ReactFiberTreeReflection.js
+23
-24
@@ -12,7 +12,7 @@
12
13
'use strict';
14
15
-import type { Fiber } from 'ReactFiber';
15
+import type {Fiber} from 'ReactFiber';
16
17
var ReactInstanceMap = require('ReactInstanceMap');
18
var ReactCurrentOwner = require('react/lib/ReactCurrentOwner');
@@ -40,7 +40,7 @@ var MOUNTING = 1;
40
var MOUNTED = 2;
41
var UNMOUNTED = 3;
42
43
-function isFiberMountedImpl(fiber : Fiber) : number {
43
+function isFiberMountedImpl(fiber: Fiber): number {
44
let node = fiber;
45
if (!fiber.alternate) {
46
// If there is no alternate, this might be a new tree that isn't inserted
@@ -68,30 +68,32 @@ function isFiberMountedImpl(fiber : Fiber) : number {
68
// that has been unmounted.
69
return UNMOUNTED;
70
}
71
-exports.isFiberMounted = function(fiber : Fiber) : boolean {
71
+exports.isFiberMounted = function(fiber: Fiber): boolean {
72
return isFiberMountedImpl(fiber) === MOUNTED;
73
};
74
75
-exports.isMounted = function(component : ReactComponent<any, any, any>) : boolean {
75
+exports.isMounted = function(
76
+ component: ReactComponent<any, any, any>,
77
+): boolean {
78
if (__DEV__) {
77
- const owner = (ReactCurrentOwner.current : any);
79
+ const owner = (ReactCurrentOwner.current: any);
80
if (owner !== null && owner.tag === ClassComponent) {
79
- const ownerFiber : Fiber = owner;
81
+ const ownerFiber: Fiber = owner;
82
const instance = ownerFiber.stateNode;
83
warning(
84
instance._warnedAboutRefsInRender,
85
'%s is accessing isMounted inside its render() function. ' +
84
- 'render() should be a pure function of props and state. It should ' +
85
- 'never access something that requires stale data from the previous ' +
86
- 'render, such as refs. Move this logic to componentDidMount and ' +
87
- 'componentDidUpdate instead.',
88
- getComponentName(ownerFiber) || 'A component'
86
+ 'render() should be a pure function of props and state. It should ' +
87
+ 'never access something that requires stale data from the previous ' +
88
+ 'render, such as refs. Move this logic to componentDidMount and ' +
89
+ 'componentDidUpdate instead.',
90
+ getComponentName(ownerFiber) || 'A component',
91
);
92
instance._warnedAboutRefsInRender = true;
93
}
94
}
95
94
- var fiber : ?Fiber = ReactInstanceMap.get(component);
96
+ var fiber: ?Fiber = ReactInstanceMap.get(component);
97
if (!fiber) {
98
return false;
99
}
@@ -101,18 +103,18 @@ exports.isMounted = function(component : ReactComponent<any, any, any>) : boolea
103
function assertIsMounted(fiber) {
104
invariant(
105
isFiberMountedImpl(fiber) === MOUNTED,
104
- 'Unable to find node on an unmounted component.'
106
+ 'Unable to find node on an unmounted component.',
107
);
108
}
109
108
-function findCurrentFiberUsingSlowPath(fiber : Fiber) : Fiber | null {
110
+function findCurrentFiberUsingSlowPath(fiber: Fiber): Fiber | null {
111
let alternate = fiber.alternate;
112
if (!alternate) {
113
// If there is no alternate, then we only need to check if it is mounted.
114
const state = isFiberMountedImpl(fiber);
115
invariant(
116
state !== UNMOUNTED,
115
- 'Unable to find node on an unmounted component.'
117
+ 'Unable to find node on an unmounted component.',
118
);
119
if (state === MOUNTING) {
120
return null;
@@ -152,10 +154,7 @@ function findCurrentFiberUsingSlowPath(fiber : Fiber) : Fiber | null {
154
}
155
// We should never have an alternate for any mounting node. So the only
156
// way this could possibly happen is if this was unmounted, if at all.
155
- invariant(
156
- false,
157
- 'Unable to find node on an unmounted component.'
158
- );
157
+ invariant(false, 'Unable to find node on an unmounted component.');
158
}
159
160
if (a.return !== b.return) {
@@ -209,21 +208,21 @@ function findCurrentFiberUsingSlowPath(fiber : Fiber) : Fiber | null {
208
invariant(
209
didFindChild,
210
'Child was not found in either parent set. This indicates a bug ' +
212
- 'related to the return pointer.'
211
+ 'related to the return pointer.',
212
);
213
}
214
}
215
216
invariant(
217
a.alternate === b,
219
- 'Return fibers should always be each others\' alternates.'
218
+ "Return fibers should always be each others' alternates.",
219
);
220
}
221
// If the root is not a host container, we're in a disconnected tree. I.e.
222
// unmounted.
223
invariant(
224
a.tag === HostRoot,
226
- 'Unable to find node on an unmounted component.'
225
+ 'Unable to find node on an unmounted component.',
226
);
227
if (a.stateNode.current === a) {
228
// We've determined that A is the current branch.
@@ -234,14 +233,14 @@ function findCurrentFiberUsingSlowPath(fiber : Fiber) : Fiber | null {
233
}
234
exports.findCurrentFiberUsingSlowPath = findCurrentFiberUsingSlowPath;
235
237
-exports.findCurrentHostFiber = function(parent : Fiber) : Fiber | null {
236
+exports.findCurrentHostFiber = function(parent: Fiber): Fiber | null {
237
const currentParent = findCurrentFiberUsingSlowPath(parent);
238
if (!currentParent) {
239
return null;
240
}
241
242
// Next we'll drill down this component to find the first HostComponent/Text.
244
- let node : Fiber = currentParent;
243
+ let node: Fiber = currentParent;
244
while (true) {
245
if (node.tag === HostComponent || node.tag === HostText) {
246
return node;
src/renderers/shared/fiber/ReactFiberUpdateQueue.js
+66
-52
@@ -12,8 +12,8 @@
12
13
'use strict';
14
15
-import type { Fiber } from 'ReactFiber';
16
-import type { PriorityLevel } from 'ReactPriorityLevel';
15
+import type {Fiber} from 'ReactFiber';
16
+import type {PriorityLevel} from 'ReactPriorityLevel';
17
18
const {
19
Callback: CallbackEffect,
@@ -31,8 +31,8 @@ if (__DEV__) {
31
}
32
33
type PartialState<State, Props> =
34
- $Subtype<State> |
35
- (prevState: State, props: Props) => $Subtype<State>;
34
+ | $Subtype<State>
35
+ | ((prevState: State, props: Props) => $Subtype<State>);
36
37
// Callbacks are not validated until invocation
38
type Callback = mixed;
@@ -68,12 +68,14 @@ export type UpdateQueue = {
68
isProcessing?: boolean,
69
};
70
71
-function comparePriority(a : PriorityLevel, b : PriorityLevel) : number {
71
+function comparePriority(a: PriorityLevel, b: PriorityLevel): number {
72
// When comparing update priorities, treat sync and Task work as equal.
73
// TODO: Could we avoid the need for this by always coercing sync priority
74
// to Task when scheduling an update?
75
- if ((a === TaskPriority || a === SynchronousPriority) &&
76
- (b === TaskPriority || b === SynchronousPriority)) {
75
+ if (
76
+ (a === TaskPriority || a === SynchronousPriority) &&
77
+ (b === TaskPriority || b === SynchronousPriority)
78
+ ) {
79
return 0;
80
}
81
if (a === NoWork && b !== NoWork) {
@@ -87,7 +89,7 @@ function comparePriority(a : PriorityLevel, b : PriorityLevel) : number {
89
90
// Ensures that a fiber has an update queue, creating a new one if needed.
91
// Returns the new or existing queue.
90
-function ensureUpdateQueue(fiber : Fiber) : UpdateQueue {
92
+function ensureUpdateQueue(fiber: Fiber): UpdateQueue {
93
if (fiber.updateQueue) {
94
// We already have an update queue.
95
return fiber.updateQueue;
@@ -116,7 +118,10 @@ function ensureUpdateQueue(fiber : Fiber) : UpdateQueue {
118
}
119
120
// Clones an update queue from a source fiber onto its alternate.
119
-function cloneUpdateQueue(current : Fiber, workInProgress : Fiber) : UpdateQueue | null {
121
+function cloneUpdateQueue(
122
+ current: Fiber,
123
+ workInProgress: Fiber,
124
+): UpdateQueue | null {
125
const currentQueue = current.updateQueue;
126
if (!currentQueue) {
127
// The source fiber does not have an update queue.
@@ -139,7 +144,7 @@ function cloneUpdateQueue(current : Fiber, workInProgress : Fiber) : UpdateQueue
144
}
145
exports.cloneUpdateQueue = cloneUpdateQueue;
146
142
-function cloneUpdate(update : Update) : Update {
147
+function cloneUpdate(update: Update): Update {
148
return {
149
priorityLevel: update.priorityLevel,
150
partialState: update.partialState,
@@ -170,17 +175,22 @@ function insertUpdateIntoQueue(queue, update, insertAfter, insertBefore) {
175
176
// Returns the update after which the incoming update should be inserted into
177
// the queue, or null if it should be inserted at beginning.
173
-function findInsertionPosition(queue, update) : Update | null {
178
+function findInsertionPosition(queue, update): Update | null {
179
const priorityLevel = update.priorityLevel;
180
let insertAfter = null;
181
let insertBefore = null;
177
- if (queue.last && comparePriority(queue.last.priorityLevel, priorityLevel) <= 0) {
182
+ if (
183
+ queue.last && comparePriority(queue.last.priorityLevel, priorityLevel) <= 0
184
+ ) {
185
// Fast path for the common case where the update should be inserted at
186
// the end of the queue.
187
insertAfter = queue.last;
188
} else {
189
insertBefore = queue.first;
183
- while (insertBefore && comparePriority(insertBefore.priorityLevel, priorityLevel) <= 0) {
190
+ while (
191
+ insertBefore &&
192
+ comparePriority(insertBefore.priorityLevel, priorityLevel) <= 0
193
+ ) {
194
insertAfter = insertBefore;
195
insertBefore = insertBefore.next;
196
}
@@ -217,7 +227,7 @@ function findInsertionPosition(queue, update) : Update | null {
227
// we shouldn't make a copy.
228
//
229
// If the update is cloned, it returns the cloned update.
220
-function insertUpdate(fiber : Fiber, update : Update) : Update | null {
230
+function insertUpdate(fiber: Fiber, update: Update): Update | null {
231
const queue1 = ensureUpdateQueue(fiber);
232
const queue2 = fiber.alternate ? ensureUpdateQueue(fiber.alternate) : null;
233
@@ -227,9 +237,9 @@ function insertUpdate(fiber : Fiber, update : Update) : Update | null {
237
warning(
238
false,
239
'An update (setState, replaceState, or forceUpdate) was scheduled ' +
230
- 'from inside an update function. Update functions should be pure, ' +
231
- 'with zero side-effects. Consider using componentDidUpdate or a ' +
232
- 'callback.'
240
+ 'from inside an update function. Update functions should be pure, ' +
241
+ 'with zero side-effects. Consider using componentDidUpdate or a ' +
242
+ 'callback.',
243
);
244
}
245
}
@@ -275,11 +285,11 @@ function insertUpdate(fiber : Fiber, update : Update) : Update | null {
285
}
286
287
function addUpdate(
278
- fiber : Fiber,
279
- partialState : PartialState<any, any> | null,
280
- callback : mixed,
281
- priorityLevel : PriorityLevel
282
-) : void {
288
+ fiber: Fiber,
289
+ partialState: PartialState<any, any> | null,
290
+ callback: mixed,
291
+ priorityLevel: PriorityLevel,
292
+): void {
293
const update = {
294
priorityLevel,
295
partialState,
@@ -294,11 +304,11 @@ function addUpdate(
304
exports.addUpdate = addUpdate;
305
306
function addReplaceUpdate(
297
- fiber : Fiber,
298
- state : any | null,
299
- callback : Callback | null,
300
- priorityLevel : PriorityLevel
301
-) : void {
307
+ fiber: Fiber,
308
+ state: any | null,
309
+ callback: Callback | null,
310
+ priorityLevel: PriorityLevel,
311
+): void {
312
const update = {
313
priorityLevel,
314
partialState: state,
@@ -313,10 +323,10 @@ function addReplaceUpdate(
323
exports.addReplaceUpdate = addReplaceUpdate;
324
325
function addForceUpdate(
316
- fiber : Fiber,
317
- callback : Callback | null,
318
- priorityLevel : PriorityLevel
319
-) : void {
326
+ fiber: Fiber,
327
+ callback: Callback | null,
328
+ priorityLevel: PriorityLevel,
329
+): void {
330
const update = {
331
priorityLevel,
332
partialState: null,
@@ -330,21 +340,18 @@ function addForceUpdate(
340
}
341
exports.addForceUpdate = addForceUpdate;
342
333
-function getPendingPriority(queue : UpdateQueue) : PriorityLevel {
343
+function getPendingPriority(queue: UpdateQueue): PriorityLevel {
344
return queue.first ? queue.first.priorityLevel : NoWork;
345
}
346
exports.getPendingPriority = getPendingPriority;
347
348
function addTopLevelUpdate(
339
- fiber : Fiber,
340
- partialState : PartialState<any, any>,
341
- callback : Callback | null,
342
- priorityLevel : PriorityLevel
343
-) : void {
344
- const isTopLevelUnmount = !!(
345
- partialState &&
346
- partialState.element === null
347
- );
349
+ fiber: Fiber,
350
+ partialState: PartialState<any, any>,
351
+ callback: Callback | null,
352
+ priorityLevel: PriorityLevel,
353
+): void {
354
+ const isTopLevelUnmount = !!(partialState && partialState.element === null);
355
356
const update = {
357
priorityLevel,
@@ -386,13 +393,13 @@ function getStateFromUpdate(update, instance, prevState, props) {
393
}
394
395
function beginUpdateQueue(
389
- workInProgress : Fiber,
390
- queue : UpdateQueue,
391
- instance : any,
392
- prevState : any,
393
- props : any,
394
- priorityLevel : PriorityLevel
395
-) : any {
396
+ workInProgress: Fiber,
397
+ queue: UpdateQueue,
398
+ instance: any,
399
+ prevState: any,
400
+ props: any,
401
+ priorityLevel: PriorityLevel,
402
+): any {
403
if (__DEV__) {
404
// Set this flag so we can warn if setState is called inside the update
405
// function of another setState.
@@ -436,7 +443,10 @@ function beginUpdateQueue(
443
}
444
// Second condition ignores top-level unmount callbacks if they are not the
445
// last update in the queue, since a subsequent update will cause a remount.
439
- if (update.callback !== null && !(update.isTopLevelUnmount && update.next !== null)) {
446
+ if (
447
+ update.callback !== null &&
448
+ !(update.isTopLevelUnmount && update.next !== null)
449
+ ) {
450
callbackList = callbackList || [];
451
callbackList.push(update.callback);
452
workInProgress.effectTag |= CallbackEffect;
@@ -459,7 +469,11 @@ function beginUpdateQueue(
469
}
470
exports.beginUpdateQueue = beginUpdateQueue;
471
462
-function commitCallbacks(finishedWork : Fiber, queue : UpdateQueue, context : mixed) {
472
+function commitCallbacks(
473
+ finishedWork: Fiber,
474
+ queue: UpdateQueue,
475
+ context: mixed,
476
+) {
477
const callbackList = queue.callbackList;
478
if (!callbackList) {
479
return;
@@ -469,8 +483,8 @@ function commitCallbacks(finishedWork : Fiber, queue : UpdateQueue, context : mi
483
invariant(
484
typeof callback === 'function',
485
'Invalid argument passed as callback. Expected a function. Instead ' +
472
- 'received: %s',
473
- callback
486
+ 'received: %s',
487
+ callback,
488
);
489
callback.call(context);
490
}
src/renderers/shared/fiber/ReactTypeOfSideEffect.js
+9
-9
@@ -15,13 +15,13 @@
15
export type TypeOfSideEffect = 0 | 1 | 2 | 3 | 4 | 8 | 16 | 32 | 64;
16
17
module.exports = {
18
- NoEffect: 0, // 0b0000000
19
- Placement: 1, // 0b0000001
20
- Update: 2, // 0b0000010
21
- PlacementAndUpdate: 3, // 0b0000011
22
- Deletion: 4, // 0b0000100
23
- ContentReset: 8, // 0b0001000
24
- Callback: 16, // 0b0010000
25
- Err: 32, // 0b0100000
26
- Ref: 64, // 0b1000000
18
+ NoEffect: 0, // 0b0000000
19
+ Placement: 1, // 0b0000001
20
+ Update: 2, // 0b0000010
21
+ PlacementAndUpdate: 3, // 0b0000011
22
+ Deletion: 4, // 0b0000100
23
+ ContentReset: 8, // 0b0001000
24
+ Callback: 16, // 0b0010000
25
+ Err: 32, // 0b0100000
26
+ Ref: 64, // 0b1000000
27
};
src/renderers/shared/fiber/__tests__/ReactCoroutine-test.js
+22
-49
@@ -27,25 +27,25 @@ describe('ReactCoroutine', () => {
27
});
28
29
function div(...children) {
30
- children = children.map(c => typeof c === 'string' ? { text: c } : c);
31
- return { type: 'div', children, prop: undefined };
30
+ children = children.map(c => typeof c === 'string' ? {text: c} : c);
31
+ return {type: 'div', children, prop: undefined};
32
}
33
34
function span(prop) {
35
- return { type: 'span', children: [], prop };
35
+ return {type: 'span', children: [], prop};
36
}
37
38
it('should render a coroutine', () => {
39
var ops = [];
40
41
- function Continuation({ isSame }) {
41
+ function Continuation({isSame}) {
42
ops.push(['Continuation', isSame]);
43
return <span prop={isSame ? 'foo==bar' : 'foo!=bar'} />;
44
}
45
46
// An alternative API could mark Continuation as something that needs
47
// yielding. E.g. Continuation.yieldType = 123;
48
- function Child({ bar }) {
48
+ function Child({bar}) {
49
ops.push(['Child', bar]);
50
return ReactCoroutine.createYield({
51
props: {
@@ -62,9 +62,9 @@ describe('ReactCoroutine', () => {
62
63
function HandleYields(props, yields) {
64
ops.push('HandleYields');
65
- return yields.map(y =>
65
+ return yields.map(y => (
66
<y.continuation isSame={props.foo === y.props.bar} />
67
- );
67
+ ));
68
}
69
70
// An alternative API could mark Parent as something that needs
@@ -74,7 +74,7 @@ describe('ReactCoroutine', () => {
74
return ReactCoroutine.createCoroutine(
75
props.children,
76
HandleYields,
77
- props
77
+ props,
78
);
79
}
80
@@ -98,19 +98,16 @@ describe('ReactCoroutine', () => {
98
['Continuation', false],
99
]);
100
expect(ReactNoop.getChildren()).toEqual([
101
- div(
102
- span('foo==bar'),
103
- span('foo!=bar'),
104
- ),
101
+ div(span('foo==bar'), span('foo!=bar')),
102
]);
103
});
104
105
it('should update a coroutine', () => {
109
- function Continuation({ isSame }) {
106
+ function Continuation({isSame}) {
107
return <span prop={isSame ? 'foo==bar' : 'foo!=bar'} />;
108
}
109
113
- function Child({ bar }) {
110
+ function Child({bar}) {
111
return ReactCoroutine.createYield({
112
props: {
113
bar: bar,
@@ -124,16 +121,16 @@ describe('ReactCoroutine', () => {
121
}
122
123
function HandleYields(props, yields) {
127
- return yields.map(y =>
124
+ return yields.map(y => (
125
<y.continuation isSame={props.foo === y.props.bar} />
129
- );
126
+ ));
127
}
128
129
function Parent(props) {
130
return ReactCoroutine.createCoroutine(
131
props.children,
132
HandleYields,
136
- props
133
+ props,
134
);
135
}
136
@@ -144,19 +141,13 @@ describe('ReactCoroutine', () => {
141
ReactNoop.render(<App foo={true} />);
142
ReactNoop.flush();
143
expect(ReactNoop.getChildren()).toEqual([
147
- div(
148
- span('foo==bar'),
149
- span('foo!=bar'),
150
- ),
144
+ div(span('foo==bar'), span('foo!=bar')),
145
]);
146
147
ReactNoop.render(<App foo={false} />);
148
ReactNoop.flush();
149
expect(ReactNoop.getChildren()).toEqual([
156
- div(
157
- span('foo!=bar'),
158
- span('foo==bar'),
159
- ),
150
+ div(span('foo!=bar'), span('foo==bar')),
151
]);
152
});
153
@@ -194,7 +185,7 @@ describe('ReactCoroutine', () => {
185
return ReactCoroutine.createCoroutine(
186
this.props.children,
187
HandleYields,
197
- this.props
188
+ this.props,
189
);
190
}
191
componentWillUnmount() {
@@ -205,12 +196,7 @@ describe('ReactCoroutine', () => {
196
ReactNoop.render(<Parent><Child /></Parent>);
197
ReactNoop.flush();
198
208
- expect(ops).toEqual([
209
- 'Parent',
210
- 'Child',
211
- 'HandleYields',
212
- 'Continuation',
213
- ]);
199
+ expect(ops).toEqual(['Parent', 'Child', 'HandleYields', 'Continuation']);
200
201
ops = [];
202
@@ -222,7 +208,6 @@ describe('ReactCoroutine', () => {
208
'Unmount Child',
209
'Unmount Continuation',
210
]);
225
-
211
});
212
213
it('should handle deep updates in coroutine', () => {
@@ -238,31 +223,19 @@ describe('ReactCoroutine', () => {
223
224
function App(props) {
225
return ReactCoroutine.createCoroutine(
241
- [
242
- <Counter id="a" />,
243
- <Counter id="b" />,
244
- <Counter id="c" />,
245
- ],
226
+ [<Counter id="a" />, <Counter id="b" />, <Counter id="c" />],
227
(p, yields) => yields.map(y => <span prop={y * 100} />),
247
- {}
228
+ {},
229
);
230
}
231
232
ReactNoop.render(<App />);
233
ReactNoop.flush();
253
- expect(ReactNoop.getChildren()).toEqual([
254
- span(500),
255
- span(500),
256
- span(500),
257
- ]);
234
+ expect(ReactNoop.getChildren()).toEqual([span(500), span(500), span(500)]);
235
236
instances.a.setState({value: 1});
237
instances.b.setState({value: 2});
238
ReactNoop.flush();
262
- expect(ReactNoop.getChildren()).toEqual([
263
- span(100),
264
- span(200),
265
- span(500),
266
- ]);
239
+ expect(ReactNoop.getChildren()).toEqual([span(100), span(200), span(500)]);
240
});
241
});
src/renderers/shared/fiber/__tests__/ReactIncremental-test.js
+89
-118
@@ -26,7 +26,6 @@ describe('ReactIncremental', () => {
26
});
27
28
it('should render a simple component', () => {
29
-
29
function Bar() {
30
return <div>Hello World</div>;
31
}
@@ -37,11 +36,9 @@ describe('ReactIncremental', () => {
36
37
ReactNoop.render(<Foo />);
38
ReactNoop.flush();
40
-
39
});
40
41
it('should render a simple component, in steps if needed', () => {
44
-
42
var renderCallbackCalled = false;
43
var barCalled = false;
44
function Bar() {
@@ -52,10 +49,7 @@ describe('ReactIncremental', () => {
49
var fooCalled = false;
50
function Foo() {
51
fooCalled = true;
55
- return [
56
- <Bar isBar={true} />,
57
- <Bar isBar={true} />,
58
- ];
52
+ return [<Bar isBar={true} />, <Bar isBar={true} />];
53
}
54
55
ReactNoop.render(<Foo />, () => renderCallbackCalled = true);
@@ -75,7 +69,6 @@ describe('ReactIncremental', () => {
69
});
70
71
it('updates a previous render', () => {
78
-
72
var ops = [];
73
74
function Header() {
@@ -107,27 +100,39 @@ describe('ReactIncremental', () => {
100
);
101
}
102
110
- ReactNoop.render(<Foo text="foo" />, () => ops.push('renderCallbackCalled'));
103
+ ReactNoop.render(<Foo text="foo" />, () =>
104
+ ops.push('renderCallbackCalled'));
105
ReactNoop.flush();
106
113
- expect(ops).toEqual(['Foo', 'Header', 'Content', 'Footer', 'renderCallbackCalled']);
107
+ expect(ops).toEqual([
108
+ 'Foo',
109
+ 'Header',
110
+ 'Content',
111
+ 'Footer',
112
+ 'renderCallbackCalled',
113
+ ]);
114
115
ops = [];
116
117
- ReactNoop.render(<Foo text="bar" />, () => ops.push('firstRenderCallbackCalled'));
118
- ReactNoop.render(<Foo text="bar" />, () => ops.push('secondRenderCallbackCalled'));
117
+ ReactNoop.render(<Foo text="bar" />, () =>
118
+ ops.push('firstRenderCallbackCalled'));
119
+ ReactNoop.render(<Foo text="bar" />, () =>
120
+ ops.push('secondRenderCallbackCalled'));
121
ReactNoop.flush();
122
123
// TODO: Test bail out of host components. This is currently unobservable.
124
125
// Since this is an update, it should bail out and reuse the work from
126
// Header and Content.
125
- expect(ops).toEqual(['Foo', 'Content', 'firstRenderCallbackCalled', 'secondRenderCallbackCalled']);
126
-
127
+ expect(ops).toEqual([
128
+ 'Foo',
129
+ 'Content',
130
+ 'firstRenderCallbackCalled',
131
+ 'secondRenderCallbackCalled',
132
+ ]);
133
});
134
135
it('can cancel partially rendered work and restart', () => {
130
-
136
var ops = [];
137
138
function Bar(props) {
@@ -171,11 +176,9 @@ describe('ReactIncremental', () => {
176
ReactNoop.flush(20);
177
178
expect(ops).toEqual(['Foo', 'Bar', 'Bar']);
174
-
179
});
180
181
it('can deprioritize unfinished work and resume it later', () => {
178
-
182
var ops = [];
183
184
function Bar(props) {
@@ -225,7 +228,6 @@ describe('ReactIncremental', () => {
228
ReactNoop.flush();
229
230
expect(ops).toEqual(['Middle', 'Middle']);
228
-
231
});
232
233
it('can deprioritize a tree from without dropping work', () => {
@@ -285,7 +287,6 @@ describe('ReactIncremental', () => {
287
});
288
289
it('can resume work in a subtree even when a parent bails out', () => {
288
-
290
var ops = [];
291
292
function Bar(props) {
@@ -447,7 +448,6 @@ describe('ReactIncremental', () => {
448
});
449
450
it('can reuse work done after being preempted', () => {
450
-
451
var ops = [];
452
453
function Bar(props) {
@@ -482,11 +482,7 @@ describe('ReactIncremental', () => {
482
<div>
483
<Bar>{props.text2}</Bar>
484
<div hidden={true}>
485
- {
486
- props.step === 0 ?
487
- step0
488
- : middleContent
489
- }
485
+ {props.step === 0 ? step0 : middleContent}
486
</div>
487
</div>
488
);
@@ -542,7 +538,6 @@ describe('ReactIncremental', () => {
538
// without restarting.
539
ReactNoop.flush();
540
expect(ops).toEqual(['Middle']);
545
-
541
});
542
543
it('can reuse work that began but did not complete, after being preempted', () => {
@@ -561,7 +556,7 @@ describe('ReactIncremental', () => {
556
}
557
558
class Child extends React.Component {
564
- state = { step: 0 };
559
+ state = {step: 0};
560
render() {
561
child = this;
562
ops.push('Child');
@@ -597,12 +592,9 @@ describe('ReactIncremental', () => {
592
593
// Begin working on a low priority update to Child, but stop before
594
// GreatGrandchild. Child and Grandchild begin but don't complete.
600
- child.setState({ step: 1 });
595
+ child.setState({step: 1});
596
ReactNoop.flushDeferredPri(30);
602
- expect(ops).toEqual([
603
- 'Child',
604
- 'Grandchild',
605
- ]);
597
+ expect(ops).toEqual(['Child', 'Grandchild']);
598
599
// Interrupt the current low pri work with a high pri update elsewhere in
600
// the tree.
@@ -625,7 +617,6 @@ describe('ReactIncremental', () => {
617
});
618
619
it('can reuse work if shouldComponentUpdate is false, after being preempted', () => {
628
-
620
var ops = [];
621
622
function Bar(props) {
@@ -708,7 +699,6 @@ describe('ReactIncremental', () => {
699
// without restarting.
700
ReactNoop.flush();
701
expect(ops).toEqual(['Middle']);
711
-
702
});
703
704
it('memoizes work even if shouldComponentUpdate returns false', () => {
@@ -733,9 +723,7 @@ describe('ReactIncremental', () => {
723
ops = [];
724
ReactNoop.render(<Foo step={2} />);
725
ReactNoop.flush();
736
- expect(ops).toEqual([
737
- 'shouldComponentUpdate: false',
738
- ]);
726
+ expect(ops).toEqual(['shouldComponentUpdate: false']);
727
728
ops = [];
729
ReactNoop.render(<Foo step={3} />);
@@ -753,7 +741,7 @@ describe('ReactIncremental', () => {
741
class Bar extends React.Component {
742
constructor() {
743
super();
756
- this.state = { a: 'a' };
744
+ this.state = {a: 'a'};
745
instance = this;
746
}
747
render() {
@@ -771,10 +759,10 @@ describe('ReactIncremental', () => {
759
760
ReactNoop.render(<Foo />);
761
ReactNoop.flush();
774
- expect(instance.state).toEqual({ a: 'a' });
775
- instance.setState({ b: 'b' });
762
+ expect(instance.state).toEqual({a: 'a'});
763
+ instance.setState({b: 'b'});
764
ReactNoop.flush();
777
- expect(instance.state).toEqual({ a: 'a', b: 'b' });
765
+ expect(instance.state).toEqual({a: 'a', b: 'b'});
766
});
767
768
it('can queue multiple state updates', () => {
@@ -782,7 +770,7 @@ describe('ReactIncremental', () => {
770
class Bar extends React.Component {
771
constructor() {
772
super();
785
- this.state = { a: 'a' };
773
+ this.state = {a: 'a'};
774
instance = this;
775
}
776
render() {
@@ -801,11 +789,11 @@ describe('ReactIncremental', () => {
789
ReactNoop.render(<Foo />);
790
ReactNoop.flush();
791
// Call setState multiple times before flushing
804
- instance.setState({ b: 'b' });
805
- instance.setState({ c: 'c' });
806
- instance.setState({ d: 'd' });
792
+ instance.setState({b: 'b'});
793
+ instance.setState({c: 'c'});
794
+ instance.setState({d: 'd'});
795
ReactNoop.flush();
808
- expect(instance.state).toEqual({ a: 'a', b: 'b', c: 'c', d: 'd' });
796
+ expect(instance.state).toEqual({a: 'a', b: 'b', c: 'c', d: 'd'});
797
});
798
799
it('can use updater form of setState', () => {
@@ -813,7 +801,7 @@ describe('ReactIncremental', () => {
801
class Bar extends React.Component {
802
constructor() {
803
super();
816
- this.state = { num: 1 };
804
+ this.state = {num: 1};
805
instance = this;
806
}
807
render() {
@@ -821,7 +809,7 @@ describe('ReactIncremental', () => {
809
}
810
}
811
824
- function Foo({ multiplier }) {
812
+ function Foo({multiplier}) {
813
return (
814
<div>
815
<Bar multiplier={multiplier} />
@@ -830,7 +818,7 @@ describe('ReactIncremental', () => {
818
}
819
820
function updater(state, props) {
833
- return { num: state.num * props.multiplier };
821
+ return {num: state.num * props.multiplier};
822
}
823
824
ReactNoop.render(<Foo multiplier={2} />);
@@ -850,7 +838,7 @@ describe('ReactIncremental', () => {
838
class Bar extends React.Component {
839
constructor() {
840
super();
853
- this.state = { num: 1 };
841
+ this.state = {num: 1};
842
instance = this;
843
}
844
render() {
@@ -858,7 +846,7 @@ describe('ReactIncremental', () => {
846
}
847
}
848
861
- function Foo({ multiplier }) {
849
+ function Foo({multiplier}) {
850
return (
851
<div>
852
<Bar multiplier={multiplier} />
@@ -867,11 +855,11 @@ describe('ReactIncremental', () => {
855
}
856
857
function updater(state, props) {
870
- return { num: state.num * props.multiplier };
858
+ return {num: state.num * props.multiplier};
859
}
860
861
function callback() {
874
- this.setState({ called: true });
862
+ this.setState({called: true});
863
}
864
865
ReactNoop.render(<Foo multiplier={2} />);
@@ -888,7 +876,7 @@ describe('ReactIncremental', () => {
876
const Bar = React.createClass({
877
getInitialState() {
878
instance = this;
891
- return { a: 'a' };
879
+ return {a: 'a'};
880
},
881
render() {
882
return <div>{this.props.children}</div>;
@@ -905,11 +893,11 @@ describe('ReactIncremental', () => {
893
894
ReactNoop.render(<Foo />);
895
ReactNoop.flush();
908
- instance.setState({ b: 'b' });
909
- instance.setState({ c: 'c' });
910
- instance.replaceState({ d: 'd' });
896
+ instance.setState({b: 'b'});
897
+ instance.setState({c: 'c'});
898
+ instance.replaceState({d: 'd'});
899
ReactNoop.flush();
912
- expect(instance.state).toEqual({ d: 'd' });
900
+ expect(instance.state).toEqual({d: 'd'});
901
});
902
903
it('can forceUpdate', () => {
@@ -958,14 +946,13 @@ describe('ReactIncremental', () => {
946
var instances = new Set();
947
948
class Bar extends React.Component {
961
- state = { y: 'A' };
949
+ state = {y: 'A'};
950
constructor() {
951
super();
952
instances.add(this);
953
}
954
shouldComponentUpdate(newProps, newState) {
967
- return this.props.x !== newProps.x ||
968
- this.state.y !== newState.y;
955
+ return this.props.x !== newProps.x || this.state.y !== newState.y;
956
}
957
render() {
958
ops.push('Bar:' + this.props.x);
@@ -1007,7 +994,7 @@ describe('ReactIncremental', () => {
994
var instances = [];
995
996
class Bar extends React.Component {
1010
- state = { y: 'A' };
997
+ state = {y: 'A'};
998
constructor() {
999
super();
1000
instances.push(this);
@@ -1062,7 +1049,7 @@ describe('ReactIncremental', () => {
1049
var ops = [];
1050
1051
class LifeCycle extends React.Component {
1065
- state = { x: this.props.x };
1052
+ state = {x: this.props.x};
1053
componentWillMount() {
1054
ops.push('componentWillMount:' + this.state.x + '-' + this.props.x);
1055
}
@@ -1092,10 +1079,7 @@ describe('ReactIncremental', () => {
1079
ReactNoop.render(<App x={0} />);
1080
ReactNoop.flushDeferredPri(30);
1081
1095
- expect(ops).toEqual([
1096
- 'App',
1097
- 'componentWillMount:0-0',
1098
- ]);
1082
+ expect(ops).toEqual(['App', 'componentWillMount:0-0']);
1083
1084
ops = [];
1085
@@ -1168,7 +1152,9 @@ describe('ReactIncremental', () => {
1152
ops.push('componentDidMount:' + this.props.x);
1153
}
1154
componentWillReceiveProps(nextProps) {
1171
- ops.push('componentWillReceiveProps:' + this.props.x + '-' + nextProps.x);
1155
+ ops.push(
1156
+ 'componentWillReceiveProps:' + this.props.x + '-' + nextProps.x,
1157
+ );
1158
}
1159
shouldComponentUpdate(nextProps) {
1160
ops.push('shouldComponentUpdate:' + this.props.x + '-' + nextProps.x);
@@ -1196,10 +1182,7 @@ describe('ReactIncremental', () => {
1182
function App(props) {
1183
ops.push('App');
1184
1199
- return [
1200
- <LifeCycle key="a" x={props.x} />,
1201
- <Sibling key="b" />,
1202
- ];
1185
+ return [<LifeCycle key="a" x={props.x} />, <Sibling key="b" />];
1186
}
1187
1188
ReactNoop.render(<App x={0} />);
@@ -1251,7 +1234,7 @@ describe('ReactIncremental', () => {
1234
var instances = [];
1235
1236
class LifeCycle extends React.Component {
1254
- state = { x: 0 };
1237
+ state = {x: 0};
1238
tick() {
1239
this.setState({
1240
x: this.state.x + 1,
@@ -1287,7 +1270,7 @@ describe('ReactIncremental', () => {
1270
// there is currently an issue where a component can't reuse its render
1271
// output unless it fully completed.
1272
class Wrap extends React.Component {
1290
- state = { y: 0 };
1273
+ state = {y: 0};
1274
componentWillMount() {
1275
instances.push(this);
1276
}
@@ -1311,10 +1294,7 @@ describe('ReactIncremental', () => {
1294
1295
function App(props) {
1296
ops.push('App');
1314
- return [
1315
- <Wrap key="a" />,
1316
- <Sibling key="b" />,
1317
- ];
1297
+ return [<Wrap key="a" />, <Sibling key="b" />];
1298
}
1299
1300
ReactNoop.render(<App y={0} />);
@@ -1395,7 +1375,6 @@ describe('ReactIncremental', () => {
1375
1376
// TODO: Test that we get the expected values for the same scenario with
1377
// incomplete parents.
1398
-
1378
});
1379
1380
it('skips will/DidUpdate when bailing unless an update was already in progress', () => {
@@ -1434,10 +1413,7 @@ describe('ReactIncremental', () => {
1413
}
1414
1415
function App(props) {
1437
- return [
1438
- <LifeCycle x={props.x} />,
1439
- <Sibling />,
1440
- ];
1416
+ return [<LifeCycle x={props.x} />, <Sibling />];
1417
}
1418
1419
ReactNoop.render(<App x={0} />);
@@ -1502,7 +1478,7 @@ describe('ReactIncremental', () => {
1478
var instance;
1479
1480
class Foo extends React.Component {
1505
- state = { n: 0 };
1481
+ state = {n: 0};
1482
render() {
1483
instance = this;
1484
return <div />;
@@ -1515,8 +1491,8 @@ describe('ReactIncremental', () => {
1491
1492
ReactNoop.syncUpdates(() => {
1493
ReactNoop.batchedUpdates(() => {
1518
- instance.setState({ n: 1 }, () => ops.push('setState 1'));
1519
- instance.setState({ n: 2 }, () => ops.push('setState 2'));
1494
+ instance.setState({n: 1}, () => ops.push('setState 1'));
1495
+ instance.setState({n: 2}, () => ops.push('setState 2'));
1496
ops.push('end batchedUpdates');
1497
});
1498
ops.push('end syncUpdates');
@@ -1538,7 +1514,7 @@ describe('ReactIncremental', () => {
1514
var instance;
1515
1516
class Foo extends React.Component {
1541
- state = { n: 0 };
1517
+ state = {n: 0};
1518
render() {
1519
instance = this;
1520
return <div />;
@@ -1551,11 +1527,11 @@ describe('ReactIncremental', () => {
1527
1528
ReactNoop.syncUpdates(() => {
1529
ReactNoop.batchedUpdates(() => {
1554
- instance.setState({ n: 1 }, () => ops.push('setState 1'));
1555
- instance.setState({ n: 2 }, () => ops.push('setState 2'));
1530
+ instance.setState({n: 1}, () => ops.push('setState 1'));
1531
+ instance.setState({n: 2}, () => ops.push('setState 2'));
1532
ReactNoop.batchedUpdates(() => {
1557
- instance.setState({ n: 3 }, () => ops.push('setState 3'));
1558
- instance.setState({ n: 4 }, () => ops.push('setState 4'));
1533
+ instance.setState({n: 3}, () => ops.push('setState 3'));
1534
+ instance.setState({n: 4}, () => ops.push('setState 4'));
1535
ops.push('end inner batchedUpdates');
1536
});
1537
ops.push('end outer batchedUpdates');
@@ -1582,7 +1558,7 @@ describe('ReactIncremental', () => {
1558
var instance;
1559
1560
class Foo extends React.Component {
1585
- state = { n: 0 };
1561
+ state = {n: 0};
1562
render() {
1563
instance = this;
1564
return <div />;
@@ -1593,8 +1569,8 @@ describe('ReactIncremental', () => {
1569
ReactNoop.flush();
1570
ops = [];
1571
1596
- function updater({ n }) {
1597
- return { n: n + 1 };
1572
+ function updater({n}) {
1573
+ return {n: n + 1};
1574
}
1575
1576
instance.setState(updater, () => ops.push('first callback'));
@@ -1609,10 +1585,7 @@ describe('ReactIncremental', () => {
1585
}).toThrow('callback error');
1586
1587
// The third callback isn't called because the second one throws
1612
- expect(ops).toEqual([
1613
- 'first callback',
1614
- 'second callback',
1615
- ]);
1588
+ expect(ops).toEqual(['first callback', 'second callback']);
1589
expect(instance.state.n).toEqual(3);
1590
});
1591
@@ -1707,7 +1680,7 @@ describe('ReactIncremental', () => {
1680
<div>
1681
<ShowBoth />
1682
</div>
1710
- </Intl>
1683
+ </Intl>,
1684
);
1685
ReactNoop.flush();
1686
expect(ops).toEqual([
@@ -1723,7 +1696,7 @@ describe('ReactIncremental', () => {
1696
<div>
1697
<ShowBoth />
1698
</div>
1726
- </Intl>
1699
+ </Intl>,
1700
);
1701
ReactNoop.flush();
1702
expect(ops).toEqual([
@@ -1739,12 +1712,10 @@ describe('ReactIncremental', () => {
1712
<div>
1713
<ShowBoth />
1714
</div>
1742
- </Intl>
1715
+ </Intl>,
1716
);
1717
ReactNoop.flushDeferredPri(15);
1745
- expect(ops).toEqual([
1746
- 'Intl {}',
1747
- ]);
1718
+ expect(ops).toEqual(['Intl {}']);
1719
1720
ops.length = 0;
1721
ReactNoop.render(
@@ -1754,7 +1725,7 @@ describe('ReactIncremental', () => {
1725
<Indirection />
1726
</Router>
1727
<ShowBoth />
1757
- </Intl>
1728
+ </Intl>,
1729
);
1730
ReactNoop.flush();
1731
expect(ops).toEqual([
@@ -1842,7 +1813,7 @@ describe('ReactIncremental', () => {
1813
</Intl>
1814
</div>
1815
<ShowLocale />
1845
- </Intl>
1816
+ </Intl>,
1817
);
1818
ReactNoop.flushDeferredPri(40);
1819
expect(ops).toEqual([
@@ -1930,7 +1901,7 @@ describe('ReactIncremental', () => {
1901
</Stateful>
1902
</IndirectionClass>
1903
</IndirectionFn>
1933
- </Intl>
1904
+ </Intl>,
1905
);
1906
ReactNoop.flush();
1907
expect(ops).toEqual([
@@ -2022,7 +1993,7 @@ describe('ReactIncremental', () => {
1993
<ShowLocaleFn />
1994
</IndirectionClass>
1995
</IndirectionFn>
2025
- </Stateful>
1996
+ </Stateful>,
1997
);
1998
ReactNoop.flush();
1999
expect(ops).toEqual([
@@ -2047,7 +2018,7 @@ describe('ReactIncremental', () => {
2018
// these components even though they don't depend on context.
2019
'IndirectionFn {}',
2020
'IndirectionClass {}',
2050
- // These components depend on context:
2021
+ // These components depend on context:
2022
'ShowLocaleClass:read {"locale":"gr"}',
2023
'ShowLocaleFn:read {"locale":"gr"}',
2024
]);
@@ -2152,17 +2123,17 @@ describe('ReactIncremental', () => {
2123
static contextTypes = {};
2124
componentDidMount(prevProps, prevState) {
2125
ops.push('componentDidMount');
2155
- this.setState({ setStateInCDU: true });
2126
+ this.setState({setStateInCDU: true});
2127
}
2128
componentDidUpdate(prevProps, prevState) {
2129
ops.push('componentDidUpdate');
2130
if (this.state.setStateInCDU) {
2160
- this.setState({ setStateInCDU: false });
2131
+ this.setState({setStateInCDU: false});
2132
}
2133
}
2134
componentWillReceiveProps(nextProps) {
2135
ops.push('componentWillReceiveProps');
2165
- this.setState({ setStateInCDU: true });
2136
+ this.setState({setStateInCDU: true});
2137
}
2138
render() {
2139
ops.push('render');
@@ -2251,8 +2222,8 @@ describe('ReactIncremental', () => {
2222
// At this point our FirstChild component has rendered a second time,
2223
// But since the render is not completed cDU should not be called yet.
2224
expect(renderCounter).toBe(2);
2254
- expect(scuPrevProps).toEqual([{ children: 'A' }]);
2255
- expect(scuNextProps).toEqual([{ children: 'B' }]);
2225
+ expect(scuPrevProps).toEqual([{children: 'A'}]);
2226
+ expect(scuNextProps).toEqual([{children: 'B'}]);
2227
expect(cduPrevProps).toEqual([]);
2228
expect(cduNextProps).toEqual([]);
2229
@@ -2266,9 +2237,9 @@ describe('ReactIncremental', () => {
2237
// Since FirstChild props didn't change, sCU returned false.
2238
// The previous memoized copy should be used.
2239
expect(renderCounter).toBe(2);
2269
- expect(scuPrevProps).toEqual([{ children: 'A' }, { children: 'B' }]);
2270
- expect(scuNextProps).toEqual([{ children: 'B' }, { children: 'B' }]);
2271
- expect(cduPrevProps).toEqual([{ children: 'A' }]);
2272
- expect(cduNextProps).toEqual([{ children: 'B' }]);
2240
+ expect(scuPrevProps).toEqual([{children: 'A'}, {children: 'B'}]);
2241
+ expect(scuNextProps).toEqual([{children: 'B'}, {children: 'B'}]);
2242
+ expect(cduPrevProps).toEqual([{children: 'A'}]);
2243
+ expect(cduNextProps).toEqual([{children: 'B'}]);
2244
});
2245
});
src/renderers/shared/fiber/__tests__/ReactIncrementalErrorHandling-test.js
+90
-80
@@ -25,12 +25,12 @@ describe('ReactIncrementalErrorHandling', () => {
25
});
26
27
function div(...children) {
28
- children = children.map(c => typeof c === 'string' ? { text: c } : c);
29
- return { type: 'div', children, prop: undefined };
28
+ children = children.map(c => typeof c === 'string' ? {text: c} : c);
29
+ return {type: 'div', children, prop: undefined};
30
}
31
32
function span(prop) {
33
- return { type: 'span', children: [], prop };
33
+ return {type: 'span', children: [], prop};
34
}
35
36
it('catches render error in a boundary during full deferred mounting', () => {
@@ -41,7 +41,9 @@ describe('ReactIncrementalErrorHandling', () => {
41
}
42
render() {
43
if (this.state.error) {
44
- return <span prop={`Caught an error: ${this.state.error.message}.`} />;
44
+ return (
45
+ <span prop={`Caught an error: ${this.state.error.message}.`} />
46
+ );
47
}
48
return this.props.children;
49
}
@@ -54,7 +56,7 @@ describe('ReactIncrementalErrorHandling', () => {
56
ReactNoop.render(
57
<ErrorBoundary>
58
<BrokenRender />
57
- </ErrorBoundary>
59
+ </ErrorBoundary>,
60
);
61
ReactNoop.flushDeferredPri();
62
expect(ReactNoop.getChildren()).toEqual([span('Caught an error: Hello.')]);
@@ -71,7 +73,9 @@ describe('ReactIncrementalErrorHandling', () => {
73
render() {
74
if (this.state.error) {
75
ops.push('ErrorBoundary render error');
74
- return <span prop={`Caught an error: ${this.state.error.message}.`} />;
76
+ return (
77
+ <span prop={`Caught an error: ${this.state.error.message}.`} />
78
+ );
79
}
80
ops.push('ErrorBoundary render success');
81
return this.props.children;
@@ -86,13 +90,11 @@ describe('ReactIncrementalErrorHandling', () => {
90
ReactNoop.render(
91
<ErrorBoundary>
92
<BrokenRender />
89
- </ErrorBoundary>
93
+ </ErrorBoundary>,
94
);
95
96
ReactNoop.flushDeferredPri(15);
93
- expect(ops).toEqual([
94
- 'ErrorBoundary render success',
95
- ]);
97
+ expect(ops).toEqual(['ErrorBoundary render success']);
98
expect(ReactNoop.getChildren()).toEqual([]);
99
100
ops.length = 0;
@@ -116,7 +118,9 @@ describe('ReactIncrementalErrorHandling', () => {
118
render() {
119
if (this.state.error) {
120
ops.push('ErrorBoundary render error');
119
- return <span prop={`Caught an error: ${this.state.error.message}.`} />;
121
+ return (
122
+ <span prop={`Caught an error: ${this.state.error.message}.`} />
123
+ );
124
}
125
ops.push('ErrorBoundary render success');
126
return this.props.children;
@@ -132,7 +136,7 @@ describe('ReactIncrementalErrorHandling', () => {
136
ReactNoop.render(
137
<ErrorBoundary>
138
<BrokenRender />
135
- </ErrorBoundary>
139
+ </ErrorBoundary>,
140
);
141
});
142
@@ -157,7 +161,9 @@ describe('ReactIncrementalErrorHandling', () => {
161
render() {
162
if (this.state.error) {
163
ops.push('ErrorBoundary render error');
160
- return <span prop={`Caught an error: ${this.state.error.message}.`} />;
164
+ return (
165
+ <span prop={`Caught an error: ${this.state.error.message}.`} />
166
+ );
167
}
168
ops.push('ErrorBoundary render success');
169
return this.props.children;
@@ -173,7 +179,7 @@ describe('ReactIncrementalErrorHandling', () => {
179
ReactNoop.render(
180
<ErrorBoundary>
181
<BrokenRender />
176
- </ErrorBoundary>
182
+ </ErrorBoundary>,
183
);
184
});
185
@@ -197,7 +203,9 @@ describe('ReactIncrementalErrorHandling', () => {
203
render() {
204
if (this.state.error) {
205
ops.push('ErrorBoundary render error');
200
- return <span prop={`Caught an error: ${this.state.error.message}.`} />;
206
+ return (
207
+ <span prop={`Caught an error: ${this.state.error.message}.`} />
208
+ );
209
}
210
ops.push('ErrorBoundary render success');
211
return this.props.children;
@@ -214,12 +222,12 @@ describe('ReactIncrementalErrorHandling', () => {
222
ReactNoop.render(
223
<ErrorBoundary>
224
Before the storm.
217
- </ErrorBoundary>
225
+ </ErrorBoundary>,
226
);
227
ReactNoop.render(
228
<ErrorBoundary>
229
<BrokenRender />
222
- </ErrorBoundary>
230
+ </ErrorBoundary>,
231
);
232
});
233
});
@@ -254,7 +262,7 @@ describe('ReactIncrementalErrorHandling', () => {
262
ReactNoop.render(
263
<RethrowErrorBoundary>
264
<BrokenRender />
257
- </RethrowErrorBoundary>
265
+ </RethrowErrorBoundary>,
266
);
267
268
expect(() => {
@@ -289,13 +297,11 @@ describe('ReactIncrementalErrorHandling', () => {
297
ReactNoop.render(
298
<RethrowErrorBoundary>
299
<BrokenRender />
292
- </RethrowErrorBoundary>
300
+ </RethrowErrorBoundary>,
301
);
302
303
ReactNoop.flushDeferredPri(15);
296
- expect(ops).toEqual([
297
- 'RethrowErrorBoundary render',
298
- ]);
304
+ expect(ops).toEqual(['RethrowErrorBoundary render']);
305
306
ops.length = 0;
307
expect(() => {
@@ -330,7 +336,7 @@ describe('ReactIncrementalErrorHandling', () => {
336
ReactNoop.render(
337
<RethrowErrorBoundary>
338
<BrokenRender />
333
- </RethrowErrorBoundary>
339
+ </RethrowErrorBoundary>,
340
);
341
});
342
@@ -368,7 +374,7 @@ describe('ReactIncrementalErrorHandling', () => {
374
ReactNoop.render(
375
<RethrowErrorBoundary>
376
<BrokenRender />
371
- </RethrowErrorBoundary>
377
+ </RethrowErrorBoundary>,
378
);
379
});
380
}).toThrow('Hello');
@@ -404,12 +410,12 @@ describe('ReactIncrementalErrorHandling', () => {
410
ReactNoop.render(
411
<RethrowErrorBoundary>
412
Before the storm.
407
- </RethrowErrorBoundary>
413
+ </RethrowErrorBoundary>,
414
);
415
ReactNoop.render(
416
<RethrowErrorBoundary>
417
<BrokenRender />
412
- </RethrowErrorBoundary>
418
+ </RethrowErrorBoundary>,
419
);
420
});
421
});
@@ -562,7 +568,9 @@ describe('ReactIncrementalErrorHandling', () => {
568
}
569
render() {
570
if (this.state.error) {
565
- return <span prop={`Caught an error: ${this.state.error.message}.`} />;
571
+ return (
572
+ <span prop={`Caught an error: ${this.state.error.message}.`} />
573
+ );
574
}
575
return this.props.children;
576
}
@@ -576,11 +584,13 @@ describe('ReactIncrementalErrorHandling', () => {
584
<ErrorBoundary>
585
<BrokenRender />
586
</ErrorBoundary>,
579
- 'a'
587
+ 'a',
588
);
589
ReactNoop.renderToRootWithID(<span prop="b:1" />, 'b');
590
ReactNoop.flush();
583
- expect(ReactNoop.getChildren('a')).toEqual([span('Caught an error: Hello.')]);
591
+ expect(ReactNoop.getChildren('a')).toEqual([
592
+ span('Caught an error: Hello.'),
593
+ ]);
594
expect(ReactNoop.getChildren('b')).toEqual([span('b:1')]);
595
});
596
@@ -669,8 +679,8 @@ describe('ReactIncrementalErrorHandling', () => {
679
680
it('unwinds the context stack correctly on error', () => {
681
class Provider extends React.Component {
672
- static childContextTypes = { message: React.PropTypes.string };
673
- static contextTypes = { message: React.PropTypes.string };
682
+ static childContextTypes = {message: React.PropTypes.string};
683
+ static contextTypes = {message: React.PropTypes.string};
684
getChildContext() {
685
return {
686
message: (this.context.message || '') + this.props.message,
@@ -694,9 +704,9 @@ describe('ReactIncrementalErrorHandling', () => {
704
}
705
706
class Boundary extends React.Component {
697
- state = { error: null };
707
+ state = {error: null};
708
unstable_handleError(error) {
699
- this.setState({ error });
709
+ this.setState({error});
710
}
711
render() {
712
return (
@@ -717,14 +727,12 @@ describe('ReactIncrementalErrorHandling', () => {
727
<Provider message="a">
728
<Boundary />
729
<Connector />
720
- </Provider>
730
+ </Provider>,
731
);
732
ReactNoop.flush();
733
734
// If the context stack does not unwind, span will get 'abcde'
725
- expect(ReactNoop.getChildren()).toEqual([
726
- span('a'),
727
- ]);
735
+ expect(ReactNoop.getChildren()).toEqual([span('a')]);
736
});
737
738
it('catches reconciler errors in a boundary during mounting', () => {
@@ -750,15 +758,17 @@ describe('ReactIncrementalErrorHandling', () => {
758
ReactNoop.render(
759
<ErrorBoundary>
760
<BrokenRender />
753
- </ErrorBoundary>
761
+ </ErrorBoundary>,
762
);
763
ReactNoop.flush();
756
- expect(ReactNoop.getChildren()).toEqual([span(
757
- 'Element type is invalid: expected a string (for built-in components) or ' +
758
- 'a class/function (for composite components) but got: undefined. ' +
759
- 'You likely forgot to export your component from the file it\'s ' +
760
- 'defined in.\n\nCheck the render method of `BrokenRender`.'
761
- )]);
764
+ expect(ReactNoop.getChildren()).toEqual([
765
+ span(
766
+ 'Element type is invalid: expected a string (for built-in components) or ' +
767
+ 'a class/function (for composite components) but got: undefined. ' +
768
+ "You likely forgot to export your component from the file it's " +
769
+ 'defined in.\n\nCheck the render method of `BrokenRender`.',
770
+ ),
771
+ ]);
772
expect(console.error.calls.count()).toBe(1);
773
});
774
@@ -786,22 +796,24 @@ describe('ReactIncrementalErrorHandling', () => {
796
ReactNoop.render(
797
<ErrorBoundary>
798
<BrokenRender fail={false} />
789
- </ErrorBoundary>
799
+ </ErrorBoundary>,
800
);
801
ReactNoop.flush();
802
803
ReactNoop.render(
804
<ErrorBoundary>
805
<BrokenRender fail={true} />
796
- </ErrorBoundary>
806
+ </ErrorBoundary>,
807
);
808
ReactNoop.flush();
799
- expect(ReactNoop.getChildren()).toEqual([span(
800
- 'Element type is invalid: expected a string (for built-in components) or ' +
801
- 'a class/function (for composite components) but got: undefined. ' +
802
- 'You likely forgot to export your component from the file it\'s ' +
803
- 'defined in.\n\nCheck the render method of `BrokenRender`.'
804
- )]);
809
+ expect(ReactNoop.getChildren()).toEqual([
810
+ span(
811
+ 'Element type is invalid: expected a string (for built-in components) or ' +
812
+ 'a class/function (for composite components) but got: undefined. ' +
813
+ "You likely forgot to export your component from the file it's " +
814
+ 'defined in.\n\nCheck the render method of `BrokenRender`.',
815
+ ),
816
+ ]);
817
expect(console.error.calls.count()).toBe(1);
818
});
819
@@ -813,9 +825,9 @@ describe('ReactIncrementalErrorHandling', () => {
825
ReactNoop.flush();
826
}).toThrowError(
827
'Element type is invalid: expected a string (for built-in components) or ' +
816
- 'a class/function (for composite components) but got: undefined. ' +
817
- 'You likely forgot to export your component from the file it\'s ' +
818
- 'defined in.'
828
+ 'a class/function (for composite components) but got: undefined. ' +
829
+ "You likely forgot to export your component from the file it's " +
830
+ 'defined in.',
831
);
832
833
ReactNoop.render(<span prop="hi" />);
@@ -856,7 +868,7 @@ describe('ReactIncrementalErrorHandling', () => {
868
<Parent>
869
<BrokenRenderAndUnmount />
870
</Parent>
859
- </Parent>
871
+ </Parent>,
872
);
873
ReactNoop.flush();
874
@@ -906,11 +918,7 @@ describe('ReactIncrementalErrorHandling', () => {
918
ReactNoop.render(<Foo />);
919
ReactNoop.flush();
920
expect(ops).toEqual(['barRef attach']);
909
- expect(ReactNoop.getChildren()).toEqual([
910
- div(
911
- span('Bar'),
912
- ),
913
- ]);
921
+ expect(ReactNoop.getChildren()).toEqual([div(span('Bar'))]);
922
923
ops = [];
924
@@ -978,15 +986,15 @@ describe('ReactIncrementalErrorHandling', () => {
986
const errorMessage = console.error.calls.argsFor(0)[0];
987
expect(errorMessage).toContain(
988
'React caught an error thrown by ErrorThrowingComponent. ' +
981
- 'You should fix this error in your code. ' +
982
- 'Consider adding an error boundary to your tree to customize error handling behavior.'
989
+ 'You should fix this error in your code. ' +
990
+ 'Consider adding an error boundary to your tree to customize error handling behavior.',
991
);
992
expect(errorMessage).toContain('Error: componentWillMount error');
993
expect(normalizeCodeLocInfo(errorMessage)).toContain(
994
'The error is located at: \n' +
987
- ' in ErrorThrowingComponent (at **)\n' +
988
- ' in span (at **)\n' +
989
- ' in div (at **)'
995
+ ' in ErrorThrowingComponent (at **)\n' +
996
+ ' in span (at **)\n' +
997
+ ' in div (at **)',
998
);
999
});
1000
@@ -1012,15 +1020,15 @@ describe('ReactIncrementalErrorHandling', () => {
1020
const errorMessage = console.error.calls.argsFor(0)[0];
1021
expect(errorMessage).toContain(
1022
'React caught an error thrown by ErrorThrowingComponent. ' +
1015
- 'You should fix this error in your code. ' +
1016
- 'Consider adding an error boundary to your tree to customize error handling behavior.'
1023
+ 'You should fix this error in your code. ' +
1024
+ 'Consider adding an error boundary to your tree to customize error handling behavior.',
1025
);
1026
expect(errorMessage).toContain('Error: componentDidMount error');
1027
expect(normalizeCodeLocInfo(errorMessage)).toContain(
1028
'The error is located at: \n' +
1021
- ' in ErrorThrowingComponent (at **)\n' +
1022
- ' in span (at **)\n' +
1023
- ' in div (at **)'
1029
+ ' in ErrorThrowingComponent (at **)\n' +
1030
+ ' in span (at **)\n' +
1031
+ ' in div (at **)',
1032
);
1033
});
1034
@@ -1038,10 +1046,10 @@ describe('ReactIncrementalErrorHandling', () => {
1046
1047
const ReactFiberErrorLogger = require('ReactFiberErrorLogger');
1048
ReactFiberErrorLogger.logCapturedError.mockImplementation(
1041
- (capturedError) => {
1049
+ capturedError => {
1050
logCapturedErrorCalls.push(capturedError);
1051
throw Error('logCapturedError error');
1044
- }
1052
+ },
1053
);
1054
1055
try {
@@ -1053,7 +1061,9 @@ describe('ReactIncrementalErrorHandling', () => {
1061
1062
// The error thrown in logCapturedError should also be logged
1063
expect(console.error.calls.count()).toBe(1);
1056
- expect(console.error.calls.argsFor(0)[0].message).toContain('logCapturedError error');
1064
+ expect(console.error.calls.argsFor(0)[0].message).toContain(
1065
+ 'logCapturedError error',
1066
+ );
1067
});
1068
1069
it('should relay info about error boundary and retry attempts if applicable', () => {
@@ -1099,15 +1109,15 @@ describe('ReactIncrementalErrorHandling', () => {
1109
expect(console.error.calls.count()).toBe(2);
1110
expect(console.error.calls.argsFor(0)[0]).toContain(
1111
'React caught an error thrown by ErrorThrowingComponent. ' +
1102
- 'You should fix this error in your code. ' +
1103
- 'React will try to recreate this component tree from scratch ' +
1104
- 'using the error boundary you provided, ErrorBoundaryComponent.'
1112
+ 'You should fix this error in your code. ' +
1113
+ 'React will try to recreate this component tree from scratch ' +
1114
+ 'using the error boundary you provided, ErrorBoundaryComponent.',
1115
);
1116
expect(console.error.calls.argsFor(1)[0]).toContain(
1117
'React caught an error thrown by ErrorThrowingComponent. ' +
1108
- 'You should fix this error in your code. ' +
1109
- 'This error was initially handled by the error boundary ErrorBoundaryComponent. ' +
1110
- 'Recreating the tree from scratch failed so React will unmount the tree.'
1118
+ 'You should fix this error in your code. ' +
1119
+ 'This error was initially handled by the error boundary ErrorBoundaryComponent. ' +
1120
+ 'Recreating the tree from scratch failed so React will unmount the tree.',
1121
);
1122
});
1123
});
src/renderers/shared/fiber/__tests__/ReactIncrementalPerf-test.js
+17
-18
@@ -41,7 +41,7 @@ describe('ReactDebugFiberPerf', () => {
41
42
function addComment(comment) {
43
activeMeasure.children.push(
44
- `${' '.repeat(activeMeasure.indent + 1)}// ${comment}`
44
+ `${' '.repeat(activeMeasure.indent + 1)}// ${comment}`,
45
);
46
}
47
@@ -73,10 +73,9 @@ describe('ReactDebugFiberPerf', () => {
73
return [
74
' '.repeat(this.indent) + this.label,
75
...this.children.map(c => c.toString()),
76
- ].join('\n') + (
76
+ ].join('\n') +
77
// Extra newline after each root reconciliation
78
- this.indent === 0 ? '\n' : ''
79
- );
78
+ (this.indent === 0 ? '\n' : '');
79
},
80
};
81
// Step one level deeper
@@ -175,7 +174,7 @@ describe('ReactDebugFiberPerf', () => {
174
<Parent>
175
<B ref={inst => b = inst} />
176
</Parent>
178
- </Parent>
177
+ </Parent>,
178
);
179
ReactNoop.flush();
180
resetFlamechart();
@@ -283,7 +282,7 @@ describe('ReactDebugFiberPerf', () => {
282
<div hidden={true}>
283
<Child />
284
</div>
286
- </Parent>
285
+ </Parent>,
286
);
287
});
288
addComment('Flush the parent');
@@ -314,7 +313,7 @@ describe('ReactDebugFiberPerf', () => {
313
<B>
314
<Child />
315
</B>
317
- </Parent>
316
+ </Parent>,
317
);
318
addComment('Start mounting Parent and A');
319
ReactNoop.flushDeferredPri(40);
@@ -372,7 +371,7 @@ describe('ReactDebugFiberPerf', () => {
371
<Baddie />
372
</Parent>
373
</Boundary>
375
- </Parent>
374
+ </Parent>,
375
);
376
addComment('Stop on Baddie and restart from Boundary');
377
ReactNoop.flush();
@@ -404,7 +403,7 @@ describe('ReactDebugFiberPerf', () => {
403
<B />
404
<A />
405
<B />
407
- </Parent>
406
+ </Parent>,
407
);
408
ReactNoop.flush();
409
resetFlamechart();
@@ -415,7 +414,7 @@ describe('ReactDebugFiberPerf', () => {
414
<B />
415
<A />
416
<B />
418
- </Parent>
417
+ </Parent>,
418
);
419
addComment('The commit phase should mention A and B just once');
420
ReactNoop.flush();
@@ -425,20 +424,20 @@ describe('ReactDebugFiberPerf', () => {
424
<B />
425
<A />
426
<B cascade={true} />
428
- </Parent>
427
+ </Parent>,
428
);
430
- addComment('Because of deduplication, we don\'t know B was cascading,');
429
+ addComment("Because of deduplication, we don't know B was cascading,");
430
addComment('but we should still see the warning for the commit phase.');
431
ReactNoop.flush();
432
expect(getFlameChart()).toMatchSnapshot();
433
});
434
435
it('supports coroutines', () => {
437
- function Continuation({ isSame }) {
436
+ function Continuation({isSame}) {
437
return <span prop={isSame ? 'foo==bar' : 'foo!=bar'} />;
438
}
439
441
- function CoChild({ bar }) {
440
+ function CoChild({bar}) {
441
return ReactCoroutine.createYield({
442
props: {
443
bar: bar,
@@ -452,16 +451,16 @@ describe('ReactDebugFiberPerf', () => {
451
}
452
453
function HandleYields(props, yields) {
455
- return yields.map(y =>
454
+ return yields.map(y => (
455
<y.continuation isSame={props.foo === y.props.bar} />
457
- );
456
+ ));
457
}
458
459
function CoParent(props) {
460
return ReactCoroutine.createCoroutine(
461
props.children,
462
HandleYields,
464
- props
463
+ props,
464
);
465
}
466
@@ -479,7 +478,7 @@ describe('ReactDebugFiberPerf', () => {
478
ReactNoop.render(
479
<Parent>
480
{ReactPortal.createPortal(<Child />, noopContainer, null)}
482
- </Parent>
481
+ </Parent>,
482
);
483
ReactNoop.flush();
484
expect(getFlameChart()).toMatchSnapshot();
src/renderers/shared/fiber/__tests__/ReactIncrementalReflection-test.js
+27
-44
@@ -25,7 +25,6 @@ describe('ReactIncrementalReflection', () => {
25
});
26
27
it('handles isMounted even when the initial render is deferred', () => {
28
-
28
let ops = [];
29
30
const instances = [];
@@ -52,9 +51,7 @@ describe('ReactIncrementalReflection', () => {
51
// Render part way through but don't yet commit the updates.
52
ReactNoop.flushDeferredPri(20);
53
55
- expect(ops).toEqual([
56
- 'componentWillMount', false,
57
- ]);
54
+ expect(ops).toEqual(['componentWillMount', false]);
55
56
expect(instances[0].isMounted()).toBe(false);
57
@@ -63,16 +60,12 @@ describe('ReactIncrementalReflection', () => {
60
// Render the rest and commit the updates.
61
ReactNoop.flush();
62
66
- expect(ops).toEqual([
67
- 'componentDidMount', true,
68
- ]);
63
+ expect(ops).toEqual(['componentDidMount', true]);
64
65
expect(instances[0].isMounted()).toBe(true);
71
-
66
});
67
68
it('handles isMounted when an unmount is deferred', () => {
75
-
69
let ops = [];
70
71
const instances = [];
@@ -120,16 +113,12 @@ describe('ReactIncrementalReflection', () => {
113
// Finish flushing the unmount.
114
ReactNoop.flush();
115
123
- expect(ops).toEqual([
124
- 'componentWillUnmount', true,
125
- ]);
116
+ expect(ops).toEqual(['componentWillUnmount', true]);
117
118
expect(instances[0].isMounted()).toBe(false);
128
-
119
});
120
121
it('finds no node before insertion and correct node before deletion', () => {
132
-
122
let ops = [];
123
124
let classInstance = null;
@@ -153,15 +142,15 @@ describe('ReactIncrementalReflection', () => {
142
}
143
render() {
144
ops.push('render');
156
- return this.props.step < 2 ?
157
- <span ref={ref => this.span = ref} /> :
158
- this.props.step === 2 ?
159
- <div ref={ref => this.div = ref} /> :
160
- this.props.step === 3 ?
161
- null :
162
- this.props.step === 4 ?
163
- <div ref={ref => this.span = ref} /> :
164
- null;
145
+ return this.props.step < 2
146
+ ? <span ref={ref => this.span = ref} />
147
+ : this.props.step === 2
148
+ ? <div ref={ref => this.div = ref} />
149
+ : this.props.step === 3
150
+ ? null
151
+ : this.props.step === 4
152
+ ? <div ref={ref => this.span = ref} />
153
+ : null;
154
}
155
}
156
@@ -172,10 +161,7 @@ describe('ReactIncrementalReflection', () => {
161
}
162
163
function Foo(props) {
175
- return [
176
- <Component step={props.step} />,
177
- <Sibling />,
178
- ];
164
+ return [<Component step={props.step} />, <Sibling />];
165
}
166
167
ReactNoop.render(<Foo step={0} />);
@@ -183,7 +169,8 @@ describe('ReactIncrementalReflection', () => {
169
ReactNoop.flushDeferredPri(30);
170
171
expect(ops).toEqual([
186
- 'componentWillMount', null,
172
+ 'componentWillMount',
173
+ null,
174
'render',
175
'render sibling',
176
]);
@@ -202,9 +189,7 @@ describe('ReactIncrementalReflection', () => {
189
190
expect(ReactNoop.findInstance(classInstance)).toBe(hostSpan);
191
205
- expect(ops).toEqual([
206
- 'componentDidMount', hostSpan,
207
- ]);
192
+ expect(ops).toEqual(['componentDidMount', hostSpan]);
193
194
ops = [];
195
@@ -214,10 +199,12 @@ describe('ReactIncrementalReflection', () => {
199
ReactNoop.flush();
200
201
expect(ops).toEqual([
217
- 'componentWillUpdate', hostSpan,
202
+ 'componentWillUpdate',
203
+ hostSpan,
204
'render',
205
'render sibling',
220
- 'componentDidUpdate', hostSpan,
206
+ 'componentDidUpdate',
207
+ hostSpan,
208
]);
209
210
expect(ReactNoop.findInstance(classInstance)).toBe(hostSpan);
@@ -230,7 +217,8 @@ describe('ReactIncrementalReflection', () => {
217
ReactNoop.flushDeferredPri(30);
218
219
expect(ops).toEqual([
233
- 'componentWillUpdate', hostSpan,
220
+ 'componentWillUpdate',
221
+ hostSpan,
222
'render',
223
'render sibling',
224
]);
@@ -248,9 +236,7 @@ describe('ReactIncrementalReflection', () => {
236
expect(hostDiv).toBeDefined();
237
expect(hostSpan).not.toBe(hostDiv);
238
251
- expect(ops).toEqual([
252
- 'componentDidUpdate', hostDiv,
253
- ]);
239
+ expect(ops).toEqual(['componentDidUpdate', hostDiv]);
240
241
ops = [];
242
@@ -262,7 +248,8 @@ describe('ReactIncrementalReflection', () => {
248
ReactNoop.flushDeferredPri(25);
249
250
expect(ops).toEqual([
265
- 'componentWillUpdate', hostDiv,
251
+ 'componentWillUpdate',
252
+ hostDiv,
253
'render',
254
'render sibling',
255
]);
@@ -274,9 +261,7 @@ describe('ReactIncrementalReflection', () => {
261
262
ReactNoop.flush();
263
277
- expect(ops).toEqual([
278
- 'componentDidUpdate', null,
279
- ]);
264
+ expect(ops).toEqual(['componentDidUpdate', null]);
265
266
// This should still be the host div since the deletion is not committed.
267
expect(ReactNoop.findInstance(classInstance)).toBe(null);
@@ -290,8 +275,6 @@ describe('ReactIncrementalReflection', () => {
275
// Unmount the component.
276
ReactNoop.render([]);
277
ReactNoop.flush();
293
- expect(ops).toEqual([
294
- 'componentWillUnmount', hostDiv,
295
- ]);
278
+ expect(ops).toEqual(['componentWillUnmount', hostDiv]);
279
});
280
});
src/renderers/shared/fiber/__tests__/ReactIncrementalScheduling-test.js
+30
-34
@@ -25,7 +25,7 @@ describe('ReactIncrementalScheduling', () => {
25
});
26
27
function span(prop) {
28
- return { type: 'span', children: [], prop };
28
+ return {type: 'span', children: [], prop};
29
}
30
31
it('schedules and flushes deferred work', () => {
@@ -60,12 +60,12 @@ describe('ReactIncrementalScheduling', () => {
60
61
it('schedules an animation callback when there`\s leftover animation work', () => {
62
class Foo extends React.Component {
63
- state = { step: 0 };
63
+ state = {step: 0};
64
componentDidMount() {
65
ReactNoop.performAnimationWork(() => {
66
- this.setState({ step: 2 });
66
+ this.setState({step: 2});
67
});
68
- this.setState({ step: 1 });
68
+ this.setState({step: 1});
69
}
70
render() {
71
return <span prop={this.state.step} />;
@@ -152,11 +152,11 @@ describe('ReactIncrementalScheduling', () => {
152
var ops = [];
153
154
class Foo extends React.Component {
155
- state = { tick: 0 };
155
+ state = {tick: 0};
156
157
componentDidMount() {
158
ops.push('componentDidMount (before setState): ' + this.state.tick);
159
- this.setState({ tick: 1 });
159
+ this.setState({tick: 1});
160
// We're in a batch. Update hasn't flushed yet.
161
ops.push('componentDidMount (after setState): ' + this.state.tick);
162
}
@@ -165,7 +165,7 @@ describe('ReactIncrementalScheduling', () => {
165
ops.push('componentDidUpdate: ' + this.state.tick);
166
if (this.state.tick === 2) {
167
ops.push('componentDidUpdate (before setState): ' + this.state.tick);
168
- this.setState({ tick: 3 });
168
+ this.setState({tick: 3});
169
ops.push('componentDidUpdate (after setState): ' + this.state.tick);
170
// We're in a batch. Update hasn't flushed yet.
171
}
@@ -192,7 +192,7 @@ describe('ReactIncrementalScheduling', () => {
192
]);
193
194
ops = [];
195
- instance.setState({ tick: 2 });
195
+ instance.setState({tick: 2});
196
ReactNoop.flushDeferredPri(20 + 5);
197
198
expect(ops).toEqual([
@@ -212,12 +212,12 @@ describe('ReactIncrementalScheduling', () => {
212
var ops = [];
213
214
class Foo extends React.Component {
215
- state = { tick: 0 };
215
+ state = {tick: 0};
216
217
componentDidMount() {
218
ReactNoop.performAnimationWork(() => {
219
ops.push('componentDidMount (before setState): ' + this.state.tick);
220
- this.setState({ tick: 1 });
220
+ this.setState({tick: 1});
221
ops.push('componentDidMount (after setState): ' + this.state.tick);
222
});
223
}
@@ -226,8 +226,10 @@ describe('ReactIncrementalScheduling', () => {
226
ReactNoop.performAnimationWork(() => {
227
ops.push('componentDidUpdate: ' + this.state.tick);
228
if (this.state.tick === 2) {
229
- ops.push('componentDidUpdate (before setState): ' + this.state.tick);
230
- this.setState({ tick: 3 });
229
+ ops.push(
230
+ 'componentDidUpdate (before setState): ' + this.state.tick,
231
+ );
232
+ this.setState({tick: 3});
233
ops.push('componentDidUpdate (after setState): ' + this.state.tick);
234
}
235
});
@@ -256,13 +258,10 @@ describe('ReactIncrementalScheduling', () => {
258
ops = [];
259
260
ReactNoop.flushAnimationPri();
259
- expect(ops).toEqual([
260
- 'render: 1',
261
- 'componentDidUpdate: 1',
262
- ]);
261
+ expect(ops).toEqual(['render: 1', 'componentDidUpdate: 1']);
262
263
ops = [];
265
- instance.setState({ tick: 2 });
264
+ instance.setState({tick: 2});
265
ReactNoop.flushDeferredPri(20 + 5);
266
267
expect(ops).toEqual([
@@ -279,20 +278,17 @@ describe('ReactIncrementalScheduling', () => {
278
ops = [];
279
280
ReactNoop.flushAnimationPri();
282
- expect(ops).toEqual([
283
- 'render: 3',
284
- 'componentDidUpdate: 3',
285
- ]);
281
+ expect(ops).toEqual(['render: 3', 'componentDidUpdate: 3']);
282
});
283
284
it('performs Task work even after time runs out', () => {
285
class Foo extends React.Component {
290
- state = { step: 1 };
286
+ state = {step: 1};
287
componentDidMount() {
292
- this.setState({ step: 2 }, () => {
293
- this.setState({ step: 3 }, () => {
294
- this.setState({ step: 4 }, () => {
295
- this.setState({ step: 5 });
288
+ this.setState({step: 2}, () => {
289
+ this.setState({step: 3}, () => {
290
+ this.setState({step: 4}, () => {
291
+ this.setState({step: 5});
292
});
293
});
294
});
@@ -315,13 +311,13 @@ describe('ReactIncrementalScheduling', () => {
311
312
it('does not perform animation work after time runs out', () => {
313
class Foo extends React.Component {
318
- state = { step: 1 };
314
+ state = {step: 1};
315
componentDidMount() {
316
ReactNoop.performAnimationWork(() => {
321
- this.setState({ step: 2 }, () => {
322
- this.setState({ step: 3 }, () => {
323
- this.setState({ step: 4 }, () => {
324
- this.setState({ step: 5 });
317
+ this.setState({step: 2}, () => {
318
+ this.setState({step: 3}, () => {
319
+ this.setState({step: 4}, () => {
320
+ this.setState({step: 5});
321
});
322
});
323
});
@@ -374,7 +370,7 @@ describe('ReactIncrementalScheduling', () => {
370
let instance;
371
let ops = [];
372
class Foo extends React.Component {
377
- state = { step: 0 };
373
+ state = {step: 0};
374
componentDidUpdate() {
375
ops.push('componentDidUpdate: ' + this.state.step);
376
if (this.state.step === 1) {
@@ -382,7 +378,7 @@ describe('ReactIncrementalScheduling', () => {
378
// This is a nested state update, so it should not be
379
// flushed synchronously, even though we wrapped it
380
// in unbatchedUpdates.
385
- this.setState({ step: 2 });
381
+ this.setState({step: 2});
382
});
383
expect(ReactNoop.getChildren()).toEqual([span(1)]);
384
}
@@ -398,7 +394,7 @@ describe('ReactIncrementalScheduling', () => {
394
expect(ReactNoop.getChildren()).toEqual([span(0)]);
395
396
ReactNoop.syncUpdates(() => {
401
- instance.setState({ step: 1 });
397
+ instance.setState({step: 1});
398
expect(ReactNoop.getChildren()).toEqual([span(2)]);
399
});
400
src/renderers/shared/fiber/__tests__/ReactIncrementalSideEffects-test.js
+98
-192
@@ -29,16 +29,15 @@ describe('ReactIncrementalSideEffects', () => {
29
}
30
31
function div(...children) {
32
- children = children.map(c => typeof c === 'string' ? { text: c } : c);
33
- return { type: 'div', children, prop: undefined };
32
+ children = children.map(c => typeof c === 'string' ? {text: c} : c);
33
+ return {type: 'div', children, prop: undefined};
34
}
35
36
function span(prop) {
37
- return { type: 'span', children: [], prop };
37
+ return {type: 'span', children: [], prop};
38
}
39
40
it('can update child nodes of a host instance', () => {
41
-
41
function Bar(props) {
42
return <span>{props.text}</span>;
43
}
@@ -54,20 +53,14 @@ describe('ReactIncrementalSideEffects', () => {
53
54
ReactNoop.render(<Foo text="Hello" />);
55
ReactNoop.flush();
57
- expect(ReactNoop.getChildren()).toEqual([
58
- div(span()),
59
- ]);
56
+ expect(ReactNoop.getChildren()).toEqual([div(span())]);
57
58
ReactNoop.render(<Foo text="World" />);
59
ReactNoop.flush();
63
- expect(ReactNoop.getChildren()).toEqual([
64
- div(span(), span()),
65
- ]);
66
-
60
+ expect(ReactNoop.getChildren()).toEqual([div(span(), span())]);
61
});
62
63
it('can update child nodes of a fragment', function() {
70
-
64
function Bar(props) {
65
return <span>{props.text}</span>;
66
}
@@ -76,13 +69,11 @@ describe('ReactIncrementalSideEffects', () => {
69
return (
70
<div>
71
<Bar text={props.text} />
79
- {props.text === 'World' ? [
80
- <Bar key="a" text={props.text} />,
81
- <div key="b" />,
82
- ] : props.text === 'Hi' ? [
83
- <div key="b" />,
84
- <Bar key="a" text={props.text} />,
85
- ] : null}
72
+ {props.text === 'World'
73
+ ? [<Bar key="a" text={props.text} />, <div key="b" />]
74
+ : props.text === 'Hi'
75
+ ? [<div key="b" />, <Bar key="a" text={props.text} />]
76
+ : null}
77
<span prop="test" />
78
</div>
79
);
@@ -90,9 +81,7 @@ describe('ReactIncrementalSideEffects', () => {
81
82
ReactNoop.render(<Foo text="Hello" />);
83
ReactNoop.flush();
93
- expect(ReactNoop.getChildren()).toEqual([
94
- div(span(), span('test')),
95
- ]);
84
+ expect(ReactNoop.getChildren()).toEqual([div(span(), span('test'))]);
85
86
ReactNoop.render(<Foo text="World" />);
87
ReactNoop.flush();
@@ -105,11 +94,9 @@ describe('ReactIncrementalSideEffects', () => {
94
expect(ReactNoop.getChildren()).toEqual([
95
div(span(), div(), span(), span('test')),
96
]);
108
-
97
});
98
99
it('can update child nodes rendering into text nodes', function() {
112
-
100
function Bar(props) {
101
return props.text;
102
}
@@ -118,30 +105,23 @@ describe('ReactIncrementalSideEffects', () => {
105
return (
106
<div>
107
<Bar text={props.text} />
121
- {props.text === 'World' ? [
122
- <Bar key="a" text={props.text} />,
123
- '!',
124
- ] : null}
108
+ {props.text === 'World'
109
+ ? [<Bar key="a" text={props.text} />, '!']
110
+ : null}
111
</div>
112
);
113
}
114
115
ReactNoop.render(<Foo text="Hello" />);
116
ReactNoop.flush();
131
- expect(ReactNoop.getChildren()).toEqual([
132
- div('Hello'),
133
- ]);
117
+ expect(ReactNoop.getChildren()).toEqual([div('Hello')]);
118
119
ReactNoop.render(<Foo text="World" />);
120
ReactNoop.flush();
137
- expect(ReactNoop.getChildren()).toEqual([
138
- div('World', 'World', '!'),
139
- ]);
140
-
121
+ expect(ReactNoop.getChildren()).toEqual([div('World', 'World', '!')]);
122
});
123
124
it('can deletes children either components, host or text', function() {
144
-
125
function Bar(props) {
126
return <span prop={props.children} />;
127
}
@@ -149,11 +129,9 @@ describe('ReactIncrementalSideEffects', () => {
129
function Foo(props) {
130
return (
131
<div>
152
- {props.show ? [
153
- <div key="a" />,
154
- <Bar key="b">Hello</Bar>,
155
- 'World',
156
- ] : []}
132
+ {props.show
133
+ ? [<div key="a" />, <Bar key="b">Hello</Bar>, 'World']
134
+ : []}
135
</div>
136
);
137
}
@@ -166,14 +144,10 @@ describe('ReactIncrementalSideEffects', () => {
144
145
ReactNoop.render(<Foo show={false} />);
146
ReactNoop.flush();
169
- expect(ReactNoop.getChildren()).toEqual([
170
- div(),
171
- ]);
172
-
147
+ expect(ReactNoop.getChildren()).toEqual([div()]);
148
});
149
150
it('can delete a child that changes type - implicit keys', function() {
176
-
151
let unmounted = false;
152
153
class ClassComponent extends React.Component {
@@ -192,14 +166,11 @@ describe('ReactIncrementalSideEffects', () => {
166
function Foo(props) {
167
return (
168
<div>
195
- {props.useClass ?
196
- <ClassComponent /> :
197
- props.useFunction ?
198
- <FunctionalComponent /> :
199
- props.useText ?
200
- 'Text' :
201
- null
202
- }
169
+ {props.useClass
170
+ ? <ClassComponent />
171
+ : props.useFunction
172
+ ? <FunctionalComponent />
173
+ : props.useText ? 'Text' : null}
174
Trail
175
</div>
176
);
@@ -207,36 +178,26 @@ describe('ReactIncrementalSideEffects', () => {
178
179
ReactNoop.render(<Foo useClass={true} />);
180
ReactNoop.flush();
210
- expect(ReactNoop.getChildren()).toEqual([
211
- div(span('Class'), 'Trail'),
212
- ]);
181
+ expect(ReactNoop.getChildren()).toEqual([div(span('Class'), 'Trail')]);
182
183
expect(unmounted).toBe(false);
184
185
ReactNoop.render(<Foo useFunction={true} />);
186
ReactNoop.flush();
218
- expect(ReactNoop.getChildren()).toEqual([
219
- div(span('Function'), 'Trail'),
220
- ]);
187
+ expect(ReactNoop.getChildren()).toEqual([div(span('Function'), 'Trail')]);
188
189
expect(unmounted).toBe(true);
190
191
ReactNoop.render(<Foo useText={true} />);
192
ReactNoop.flush();
226
- expect(ReactNoop.getChildren()).toEqual([
227
- div('Text', 'Trail'),
228
- ]);
193
+ expect(ReactNoop.getChildren()).toEqual([div('Text', 'Trail')]);
194
195
ReactNoop.render(<Foo />);
196
ReactNoop.flush();
232
- expect(ReactNoop.getChildren()).toEqual([
233
- div('Trail'),
234
- ]);
235
-
197
+ expect(ReactNoop.getChildren()).toEqual([div('Trail')]);
198
});
199
200
it('can delete a child that changes type - explicit keys', function() {
239
-
201
let unmounted = false;
202
203
class ClassComponent extends React.Component {
@@ -255,12 +216,9 @@ describe('ReactIncrementalSideEffects', () => {
216
function Foo(props) {
217
return (
218
<div>
258
- {props.useClass ?
259
- <ClassComponent key="a" /> :
260
- props.useFunction ?
261
- <FunctionalComponent key="a" /> :
262
- null
263
- }
219
+ {props.useClass
220
+ ? <ClassComponent key="a" />
221
+ : props.useFunction ? <FunctionalComponent key="a" /> : null}
222
Trail
223
</div>
224
);
@@ -268,30 +226,22 @@ describe('ReactIncrementalSideEffects', () => {
226
227
ReactNoop.render(<Foo useClass={true} />);
228
ReactNoop.flush();
271
- expect(ReactNoop.getChildren()).toEqual([
272
- div(span('Class'), 'Trail'),
273
- ]);
229
+ expect(ReactNoop.getChildren()).toEqual([div(span('Class'), 'Trail')]);
230
231
expect(unmounted).toBe(false);
232
233
ReactNoop.render(<Foo useFunction={true} />);
234
ReactNoop.flush();
279
- expect(ReactNoop.getChildren()).toEqual([
280
- div(span('Function'), 'Trail'),
281
- ]);
235
+ expect(ReactNoop.getChildren()).toEqual([div(span('Function'), 'Trail')]);
236
237
expect(unmounted).toBe(true);
238
239
ReactNoop.render(<Foo />);
240
ReactNoop.flush();
287
- expect(ReactNoop.getChildren()).toEqual([
288
- div('Trail'),
289
- ]);
290
-
241
+ expect(ReactNoop.getChildren()).toEqual([div('Trail')]);
242
});
243
244
it('does not update child nodes if a flush is aborted', () => {
294
-
245
function Bar(props) {
246
return <span prop={props.text} />;
247
}
@@ -319,11 +269,9 @@ describe('ReactIncrementalSideEffects', () => {
269
expect(ReactNoop.getChildren()).toEqual([
270
div(div(span('Hello'), span('Hello')), span('Yo')),
271
]);
322
-
272
});
273
274
it('preserves a previously rendered node when deprioritized', () => {
326
-
275
function Middle(props) {
276
return <span prop={props.children} />;
277
}
@@ -341,27 +289,19 @@ describe('ReactIncrementalSideEffects', () => {
289
ReactNoop.render(<Foo text="foo" />);
290
ReactNoop.flush();
291
344
- expect(ReactNoop.getChildren()).toEqual([
345
- div(div(span('foo'))),
346
- ]);
292
+ expect(ReactNoop.getChildren()).toEqual([div(div(span('foo')))]);
293
294
ReactNoop.render(<Foo text="bar" />);
295
ReactNoop.flushDeferredPri(20);
296
351
- expect(ReactNoop.getChildren()).toEqual([
352
- div(div(span('foo'))),
353
- ]);
297
+ expect(ReactNoop.getChildren()).toEqual([div(div(span('foo')))]);
298
299
ReactNoop.flush();
300
357
- expect(ReactNoop.getChildren()).toEqual([
358
- div(div(span('bar'))),
359
- ]);
360
-
301
+ expect(ReactNoop.getChildren()).toEqual([div(div(span('bar')))]);
302
});
303
304
it('can reuse side-effects after being preempted', () => {
364
-
305
function Bar(props) {
306
return <span prop={props.children} />;
307
}
@@ -376,14 +316,12 @@ describe('ReactIncrementalSideEffects', () => {
316
function Foo(props) {
317
return (
318
<div hidden={true}>
379
- {
380
- props.step === 0 ?
381
- <div>
319
+ {props.step === 0
320
+ ? <div>
321
<Bar>Hi</Bar>
322
<Bar>{props.text}</Bar>
323
</div>
385
- : middleContent
386
- }
324
+ : middleContent}
325
</div>
326
);
327
}
@@ -422,7 +360,6 @@ describe('ReactIncrementalSideEffects', () => {
360
});
361
362
it('can reuse side-effects after being preempted, if shouldComponentUpdate is false', () => {
425
-
363
class Bar extends React.Component {
364
shouldComponentUpdate(nextProps) {
365
return this.props.children !== nextProps.children;
@@ -530,9 +467,7 @@ describe('ReactIncrementalSideEffects', () => {
467
468
ReactNoop.render(<Foo />);
469
ReactNoop.flush();
533
- expect(ReactNoop.getChildren()).toEqual([
534
- div(span(1)),
535
- ]);
470
+ expect(ReactNoop.getChildren()).toEqual([div(span(1))]);
471
});
472
473
it('can defer side-effects and resume them later on', function() {
@@ -560,16 +495,13 @@ describe('ReactIncrementalSideEffects', () => {
495
expect(ReactNoop.getChildren()).toEqual([
496
div(
497
span(0),
563
- div(/*the spans are down-prioritized and not rendered yet*/)
498
+ div(/*the spans are down-prioritized and not rendered yet*/),
499
),
500
]);
501
ReactNoop.render(<Foo tick={1} idx={0} />);
502
ReactNoop.flushDeferredPri(35 + 25);
503
expect(ReactNoop.getChildren()).toEqual([
569
- div(
570
- span(1),
571
- div(/*still not rendered yet*/)
572
- ),
504
+ div(span(1), div(/*still not rendered yet*/)),
505
]);
506
ReactNoop.flushDeferredPri(30 + 25);
507
expect(ReactNoop.getChildren()).toEqual([
@@ -578,8 +510,8 @@ describe('ReactIncrementalSideEffects', () => {
510
div(
511
// Now we had enough time to finish the spans.
512
span(0),
581
- span(1)
582
- )
513
+ span(1),
514
+ ),
515
),
516
]);
517
var innerSpanA = ReactNoop.getChildren()[0].children[1].children[1];
@@ -591,8 +523,8 @@ describe('ReactIncrementalSideEffects', () => {
523
div(
524
// Still same old numbers.
525
span(0),
594
- span(1)
595
- )
526
+ span(1),
527
+ ),
528
),
529
]);
530
ReactNoop.render(<Foo tick={3} idx={1} />);
@@ -603,8 +535,8 @@ describe('ReactIncrementalSideEffects', () => {
535
div(
536
// New numbers.
537
span(1),
606
- span(2)
607
- )
538
+ span(2),
539
+ ),
540
),
541
]);
542
@@ -654,7 +586,7 @@ describe('ReactIncrementalSideEffects', () => {
586
expect(ReactNoop.getChildren()).toEqual([
587
div(
588
span(0),
657
- div(/*the spans are down-prioritized and not rendered yet*/)
589
+ div(/*the spans are down-prioritized and not rendered yet*/),
590
),
591
]);
592
@@ -664,10 +596,7 @@ describe('ReactIncrementalSideEffects', () => {
596
ReactNoop.render(<Foo tick={1} idx={0} />);
597
ReactNoop.flushDeferredPri(70);
598
expect(ReactNoop.getChildren()).toEqual([
667
- div(
668
- span(1),
669
- div(/*still not rendered yet*/)
670
- ),
599
+ div(span(1), div(/*still not rendered yet*/)),
600
]);
601
602
expect(ops).toEqual(['Foo']);
@@ -684,8 +613,8 @@ describe('ReactIncrementalSideEffects', () => {
613
span(0),
614
span(0),
615
span(0),
687
- span(0)
688
- )
616
+ span(0),
617
+ ),
618
),
619
]);
620
@@ -706,8 +635,8 @@ describe('ReactIncrementalSideEffects', () => {
635
span(0),
636
span(0),
637
span(0),
709
- span(0)
710
- )
638
+ span(0),
639
+ ),
640
),
641
]);
642
@@ -730,8 +659,8 @@ describe('ReactIncrementalSideEffects', () => {
659
span(0),
660
span(0),
661
span(0),
733
- span(0)
734
- )
662
+ span(0),
663
+ ),
664
),
665
]);
666
@@ -751,8 +680,8 @@ describe('ReactIncrementalSideEffects', () => {
680
span(1),
681
span(1),
682
span(1),
754
- span(1)
755
- )
683
+ span(1),
684
+ ),
685
),
686
]);
687
@@ -767,11 +696,11 @@ describe('ReactIncrementalSideEffects', () => {
696
class Bar extends React.Component {
697
constructor() {
698
super();
770
- this.state = { active: false };
699
+ this.state = {active: false};
700
barInstances.push(this);
701
}
702
activate() {
774
- this.setState({ active: true });
703
+ this.setState({active: true});
704
}
705
render() {
706
ops.push('Bar');
@@ -794,14 +723,7 @@ describe('ReactIncrementalSideEffects', () => {
723
ReactNoop.render(<Foo tick={0} idx={0} />);
724
ReactNoop.flush();
725
expect(ReactNoop.getChildren()).toEqual([
797
- div(
798
- span(0),
799
- div(
800
- span(0),
801
- span(0),
802
- span(0)
803
- )
804
- ),
726
+ div(span(0), div(span(0), span(0), span(0))),
727
]);
728
729
expect(ops).toEqual(['Foo', 'Bar', 'Bar', 'Bar']);
@@ -818,8 +740,8 @@ describe('ReactIncrementalSideEffects', () => {
740
// Still not updated.
741
span(0),
742
span(0),
821
- span(0)
822
- )
743
+ span(0),
744
+ ),
745
),
746
]);
747
@@ -841,8 +763,8 @@ describe('ReactIncrementalSideEffects', () => {
763
// Still not updated.
764
span(0),
765
span(0),
844
- span(0)
845
- )
766
+ span(0),
767
+ ),
768
),
769
]);
770
@@ -860,7 +782,7 @@ describe('ReactIncrementalSideEffects', () => {
782
span('X'),
783
span(1),
784
span(1),
863
- )
785
+ ),
786
),
787
]);
788
@@ -876,7 +798,7 @@ describe('ReactIncrementalSideEffects', () => {
798
constructor() {
799
super();
800
instance = this;
879
- this.state = { text: 'foo' };
801
+ this.state = {text: 'foo'};
802
}
803
render() {
804
return <span prop={this.state.text} />;
@@ -885,14 +807,10 @@ describe('ReactIncrementalSideEffects', () => {
807
808
ReactNoop.render(<Foo />);
809
ReactNoop.flush();
888
- expect(ReactNoop.getChildren()).toEqual([
889
- span('foo'),
890
- ]);
810
+ expect(ReactNoop.getChildren()).toEqual([span('foo')]);
811
let called = false;
892
- instance.setState({ text: 'bar' }, () => {
893
- expect(ReactNoop.getChildren()).toEqual([
894
- span('bar'),
895
- ]);
812
+ instance.setState({text: 'bar'}, () => {
813
+ expect(ReactNoop.getChildren()).toEqual([span('bar')]);
814
called = true;
815
});
816
ReactNoop.flush();
@@ -905,7 +823,7 @@ describe('ReactIncrementalSideEffects', () => {
823
constructor() {
824
super();
825
instance = this;
908
- this.state = { text: 'foo' };
826
+ this.state = {text: 'foo'};
827
}
828
shouldComponentUpdate(nextProps, nextState) {
829
return this.state.text !== nextState.text;
@@ -917,9 +835,7 @@ describe('ReactIncrementalSideEffects', () => {
835
836
ReactNoop.render(<Foo />);
837
ReactNoop.flush();
920
- expect(ReactNoop.getChildren()).toEqual([
921
- span('foo'),
922
- ]);
838
+ expect(ReactNoop.getChildren()).toEqual([span('foo')]);
839
let called = false;
840
instance.setState({}, () => {
841
called = true;
@@ -931,7 +847,6 @@ describe('ReactIncrementalSideEffects', () => {
847
// TODO: Test that callbacks are not lost if an update is preempted.
848
849
it('calls componentWillUnmount after a deletion, even if nested', () => {
934
-
850
var ops = [];
851
852
class Bar extends React.Component {
@@ -955,18 +870,17 @@ describe('ReactIncrementalSideEffects', () => {
870
function Foo(props) {
871
return (
872
<div>
958
- {props.show ? [
959
- <Bar key="a" name="A" />,
960
- <Wrapper key="b" name="B" />,
961
- <div key="cd">
962
- <Bar name="C" />
963
- <Wrapper name="D" />,
964
- </div>,
965
- [
966
- <Bar key="e" name="E" />,
967
- <Bar key="f" name="F" />,
968
- ],
969
- ] : []}
873
+ {props.show
874
+ ? [
875
+ <Bar key="a" name="A" />,
876
+ <Wrapper key="b" name="B" />,
877
+ <div key="cd">
878
+ <Bar name="C" />
879
+ <Wrapper name="D" />,
880
+ </div>,
881
+ [<Bar key="e" name="E" />, <Bar key="f" name="F" />],
882
+ ]
883
+ : []}
884
<div>
885
{props.show ? <Bar key="g" name="G" /> : null}
886
</div>
@@ -992,11 +906,9 @@ describe('ReactIncrementalSideEffects', () => {
906
'F',
907
'G',
908
]);
995
-
909
});
910
911
it('calls componentDidMount/Update after insertion/update', () => {
999
-
912
var ops = [];
913
914
class Bar extends React.Component {
@@ -1032,10 +944,7 @@ describe('ReactIncrementalSideEffects', () => {
944
<Bar name="C" />
945
<Wrapper name="D" />
946
</div>
1035
- {[
1036
- <Bar key="e" name="E" />,
1037
- <Bar key="f" name="F" />,
1038
- ]}
947
+ {[<Bar key="e" name="E" />, <Bar key="f" name="F" />]}
948
<div>
949
<Bar key="g" name="G" />
950
</div>
@@ -1072,7 +981,6 @@ describe('ReactIncrementalSideEffects', () => {
981
'update:F',
982
'update:G',
983
]);
1075
-
984
});
985
986
it('invokes ref callbacks after insertion/update/unmount', () => {
@@ -1093,15 +1001,13 @@ describe('ReactIncrementalSideEffects', () => {
1001
}
1002
1003
function Foo(props) {
1096
- return (
1097
- props.show ?
1098
- <div>
1099
- <ClassComponent ref={n => ops.push(n)} />
1100
- <FunctionalComponent ref={n => ops.push(n)} />
1101
- <div ref={n => ops.push(n)} />
1102
- </div> :
1103
- null
1104
- );
1004
+ return props.show
1005
+ ? <div>
1006
+ <ClassComponent ref={n => ops.push(n)} />
1007
+ <FunctionalComponent ref={n => ops.push(n)} />
1008
+ <div ref={n => ops.push(n)} />
1009
+ </div>
1010
+ : null;
1011
}
1012
1013
ReactNoop.render(<Foo show={true} />);
@@ -1138,11 +1044,11 @@ describe('ReactIncrementalSideEffects', () => {
1044
1045
expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
1046
'Warning: Stateless function components cannot be given refs. ' +
1141
- 'Attempts to access this ref will fail.\n\nCheck the render method ' +
1142
- 'of `Foo`.\n' +
1143
- ' in FunctionalComponent (at **)\n' +
1144
- ' in div (at **)\n' +
1145
- ' in Foo (at **)'
1047
+ 'Attempts to access this ref will fail.\n\nCheck the render method ' +
1048
+ 'of `Foo`.\n' +
1049
+ ' in FunctionalComponent (at **)\n' +
1050
+ ' in div (at **)\n' +
1051
+ ' in Foo (at **)',
1052
);
1053
});
1054
src/renderers/shared/fiber/__tests__/ReactIncrementalUpdates-test.js
+43
-42
@@ -31,11 +31,11 @@ describe('ReactIncrementalUpdates', () => {
31
componentDidMount() {
32
ReactNoop.performAnimationWork(() => {
33
// Has Animation priority
34
- this.setState({ b: 'b' });
35
- this.setState({ c: 'c' });
34
+ this.setState({b: 'b'});
35
+ this.setState({c: 'c'});
36
});
37
// Has Task priority
38
- this.setState({ a: 'a' });
38
+ this.setState({a: 'a'});
39
}
40
render() {
41
state = this.state;
@@ -45,9 +45,9 @@ describe('ReactIncrementalUpdates', () => {
45
46
ReactNoop.render(<Foo />);
47
ReactNoop.flushDeferredPri(25);
48
- expect(state).toEqual({ a: 'a' });
48
+ expect(state).toEqual({a: 'a'});
49
ReactNoop.flush();
50
- expect(state).toEqual({ a: 'a', b: 'b', c: 'c' });
50
+ expect(state).toEqual({a: 'a', b: 'b', c: 'c'});
51
});
52
53
it('applies updates with equal priority in insertion order', () => {
@@ -56,9 +56,9 @@ describe('ReactIncrementalUpdates', () => {
56
state = {};
57
componentDidMount() {
58
// All have Task priority
59
- this.setState({ a: 'a' });
60
- this.setState({ b: 'b' });
61
- this.setState({ c: 'c' });
59
+ this.setState({a: 'a'});
60
+ this.setState({b: 'b'});
61
+ this.setState({c: 'c'});
62
}
63
render() {
64
state = this.state;
@@ -68,7 +68,7 @@ describe('ReactIncrementalUpdates', () => {
68
69
ReactNoop.render(<Foo />);
70
ReactNoop.flush();
71
- expect(state).toEqual({ a: 'a', b: 'b', c: 'c' });
71
+ expect(state).toEqual({a: 'a', b: 'b', c: 'c'});
72
});
73
74
it('only drops updates with equal or lesser priority when replaceState is called', () => {
@@ -94,19 +94,19 @@ describe('ReactIncrementalUpdates', () => {
94
ReactNoop.render(<Foo />);
95
ReactNoop.flush();
96
97
- instance.setState({ x: 'x' });
98
- instance.setState({ y: 'y' });
97
+ instance.setState({x: 'x'});
98
+ instance.setState({y: 'y'});
99
ReactNoop.performAnimationWork(() => {
100
- instance.setState({ a: 'a' });
101
- instance.setState({ b: 'b' });
100
+ instance.setState({a: 'a'});
101
+ instance.setState({b: 'b'});
102
});
103
- instance.replaceState({ c: 'c' });
104
- instance.setState({ d: 'd' });
103
+ instance.replaceState({c: 'c'});
104
+ instance.setState({d: 'd'});
105
106
ReactNoop.flushAnimationPri();
107
// Even though a replaceState has been already scheduled, it hasn't been
108
// flushed yet because it has low priority.
109
- expect(instance.state).toEqual({ a: 'a', b: 'b' });
109
+ expect(instance.state).toEqual({a: 'a', b: 'b'});
110
expect(ops).toEqual([
111
'render',
112
'componentDidMount',
@@ -118,11 +118,8 @@ describe('ReactIncrementalUpdates', () => {
118
119
ReactNoop.flush();
120
// Now the rest of the updates are flushed.
121
- expect(instance.state).toEqual({ c: 'c', d: 'd' });
122
- expect(ops).toEqual([
123
- 'render',
124
- 'componentDidUpdate',
125
- ]);
121
+ expect(instance.state).toEqual({c: 'c', d: 'd'});
122
+ expect(ops).toEqual(['render', 'componentDidUpdate']);
123
});
124
125
it('can abort an update, schedule additional updates, and resume', () => {
@@ -164,7 +161,7 @@ describe('ReactIncrementalUpdates', () => {
161
// expect(ReactNoop.getChildren()).toEqual([span('')]);
162
expect(ops).toEqual(['render']);
163
expect(progressedUpdates).toEqual(['a', 'b', 'c']);
167
- expect(instance.state).toEqual({ a: 'a', b: 'b', c: 'c' });
164
+ expect(instance.state).toEqual({a: 'a', b: 'b', c: 'c'});
165
166
ops = [];
167
progressedUpdates = [];
@@ -190,7 +187,15 @@ describe('ReactIncrementalUpdates', () => {
187
'componentDidUpdate',
188
]);
189
expect(progressedUpdates).toEqual(['d', 'e', 'a', 'b', 'c', 'f', 'g']);
193
- expect(instance.state).toEqual({ a: 'a', b: 'b', c: 'c', d: 'd', e: 'e', f: 'f', g: 'g' });
190
+ expect(instance.state).toEqual({
191
+ a: 'a',
192
+ b: 'b',
193
+ c: 'c',
194
+ d: 'd',
195
+ e: 'e',
196
+ f: 'f',
197
+ g: 'g',
198
+ });
199
});
200
201
it('can abort an update, schedule a replaceState, and resume', () => {
@@ -232,7 +237,7 @@ describe('ReactIncrementalUpdates', () => {
237
ReactNoop.flushDeferredPri(20);
238
expect(ops).toEqual(['render']);
239
expect(progressedUpdates).toEqual(['a', 'b', 'c']);
235
- expect(instance.state).toEqual({ a: 'a', b: 'b', c: 'c' });
240
+ expect(instance.state).toEqual({a: 'a', b: 'b', c: 'c'});
241
242
ops = [];
243
progressedUpdates = [];
@@ -246,7 +251,7 @@ describe('ReactIncrementalUpdates', () => {
251
252
ReactNoop.flush();
253
expect(progressedUpdates).toEqual(['d', 'e', 'f', 'g']);
249
- expect(instance.state).toEqual({ e: 'e', f: 'f', g: 'g' });
254
+ expect(instance.state).toEqual({e: 'e', f: 'f', g: 'g'});
255
});
256
257
it('passes accumulation of previous updates to replaceState updater function', () => {
@@ -263,11 +268,11 @@ describe('ReactIncrementalUpdates', () => {
268
ReactNoop.render(<Foo />);
269
ReactNoop.flush();
270
266
- instance.setState({ a: 'a' });
267
- instance.setState({ b: 'b' });
268
- instance.replaceState(previousState => ({ previousState }));
271
+ instance.setState({a: 'a'});
272
+ instance.setState({b: 'b'});
273
+ instance.replaceState(previousState => ({previousState}));
274
ReactNoop.flush();
270
- expect(instance.state).toEqual({ previousState: { a: 'a', b : 'b' } });
275
+ expect(instance.state).toEqual({previousState: {a: 'a', b: 'b'}});
276
});
277
278
it('does not call callbacks that are scheduled by another callback until a later commit', () => {
@@ -276,9 +281,9 @@ describe('ReactIncrementalUpdates', () => {
281
state = {};
282
componentDidMount() {
283
ops.push('did mount');
279
- this.setState({ a: 'a' }, () => {
284
+ this.setState({a: 'a'}, () => {
285
ops.push('callback a');
281
- this.setState({ b: 'b' }, () => {
286
+ this.setState({b: 'b'}, () => {
287
ops.push('callback b');
288
});
289
});
@@ -309,7 +314,7 @@ describe('ReactIncrementalUpdates', () => {
314
state = {};
315
componentWillReceiveProps() {
316
ops.push('componentWillReceiveProps');
312
- this.setState({ b: 'b' });
317
+ this.setState({b: 'b'});
318
}
319
render() {
320
ops.push('render');
@@ -323,19 +328,15 @@ describe('ReactIncrementalUpdates', () => {
328
ops = [];
329
330
ReactNoop.performAnimationWork(() => {
326
- instance.setState({ a: 'a' });
331
+ instance.setState({a: 'a'});
332
ReactNoop.render(<Foo />); // Trigger componentWillReceiveProps
333
});
334
ReactNoop.flush();
335
331
- expect(instance.state).toEqual({ a: 'a', b: 'b' });
332
- expect(ops).toEqual([
333
- 'componentWillReceiveProps',
334
- 'render',
335
- ]);
336
+ expect(instance.state).toEqual({a: 'a', b: 'b'});
337
+ expect(ops).toEqual(['componentWillReceiveProps', 'render']);
338
});
339
338
-
340
it('enqueues setState inside an updater function as if the in-progress update is progressed (and warns)', () => {
341
spyOn(console, 'error');
342
let instance;
@@ -354,8 +355,8 @@ describe('ReactIncrementalUpdates', () => {
355
356
instance.setState(function a() {
357
ops.push('setState updater');
357
- this.setState({ b: 'b' });
358
- return { a: 'a' };
358
+ this.setState({b: 'b'});
359
+ return {a: 'a'};
360
});
361
362
ReactNoop.flush();
@@ -367,7 +368,7 @@ describe('ReactIncrementalUpdates', () => {
368
// be flushed in the same commit.
369
'render',
370
]);
370
- expect(instance.state).toEqual({ a: 'a', b: 'b' });
371
+ expect(instance.state).toEqual({a: 'a', b: 'b'});
372
373
expectDev(console.error.calls.count()).toBe(1);
374
console.error.calls.reset();
src/renderers/shared/fiber/__tests__/ReactTopLevelFragment-test.js
+16
-23
@@ -27,17 +27,14 @@ describe('ReactTopLevelFragment', function() {
27
});
28
29
it('should render a simple fragment at the top of a component', function() {
30
-
30
function Fragment() {
31
return [<div key="a">Hello</div>, <div key="b">World</div>];
32
}
33
ReactNoop.render(<Fragment />);
34
ReactNoop.flush();
36
-
35
});
36
37
it('should preserve state when switching from a single child', function() {
40
-
38
var instance = null;
39
40
class Stateful extends React.Component {
@@ -47,9 +44,10 @@ describe('ReactTopLevelFragment', function() {
44
}
45
}
46
50
- function Fragment({ condition }) {
51
- return condition ? <Stateful key="a" /> :
52
- [<Stateful key="a" />, <div key="b">World</div>];
47
+ function Fragment({condition}) {
48
+ return condition
49
+ ? <Stateful key="a" />
50
+ : [<Stateful key="a" />, <div key="b">World</div>];
51
}
52
ReactNoop.render(<Fragment />);
53
ReactNoop.flush();
@@ -64,11 +62,9 @@ describe('ReactTopLevelFragment', function() {
62
var instanceB = instance;
63
64
expect(instanceB).toBe(instanceA);
67
-
65
});
66
67
it('should not preserve state when switching to a nested array', function() {
71
-
68
var instance = null;
69
70
class Stateful extends React.Component {
@@ -78,9 +74,10 @@ describe('ReactTopLevelFragment', function() {
74
}
75
}
76
81
- function Fragment({ condition }) {
82
- return condition ? <Stateful key="a" /> :
83
- [[<Stateful key="a" />, <div key="b">World</div>], <div />];
77
+ function Fragment({condition}) {
78
+ return condition
79
+ ? <Stateful key="a" />
80
+ : [[<Stateful key="a" />, <div key="b">World</div>], <div />];
81
}
82
ReactNoop.render(<Fragment />);
83
ReactNoop.flush();
@@ -95,11 +92,9 @@ describe('ReactTopLevelFragment', function() {
92
var instanceB = instance;
93
94
expect(instanceB).not.toBe(instanceA);
98
-
95
});
96
97
it('preserves state if an implicit key slot switches from/to null', function() {
102
-
98
var instance = null;
99
100
class Stateful extends React.Component {
@@ -109,9 +104,10 @@ describe('ReactTopLevelFragment', function() {
104
}
105
}
106
112
- function Fragment({ condition }) {
113
- return condition ? [null, <Stateful />] :
114
- [<div>Hello</div>, <Stateful />];
107
+ function Fragment({condition}) {
108
+ return condition
109
+ ? [null, <Stateful />]
110
+ : [<div>Hello</div>, <Stateful />];
111
}
112
ReactNoop.render(<Fragment />);
113
ReactNoop.flush();
@@ -133,11 +129,9 @@ describe('ReactTopLevelFragment', function() {
129
var instanceC = instance;
130
131
expect(instanceC === instanceA).toBe(true);
136
-
132
});
133
134
it('should preserve state in a reorder', function() {
140
-
135
var instance = null;
136
137
class Stateful extends React.Component {
@@ -147,9 +141,10 @@ describe('ReactTopLevelFragment', function() {
141
}
142
}
143
150
- function Fragment({ condition }) {
151
- return condition ? [[<div key="b">World</div>, <Stateful key="a" />]] :
152
- [[<Stateful key="a" />, <div key="b">World</div>], <div />];
144
+ function Fragment({condition}) {
145
+ return condition
146
+ ? [[<div key="b">World</div>, <Stateful key="a" />]]
147
+ : [[<Stateful key="a" />, <div key="b">World</div>], <div />];
148
}
149
ReactNoop.render(<Fragment />);
150
ReactNoop.flush();
@@ -164,7 +159,5 @@ describe('ReactTopLevelFragment', function() {
159
var instanceB = instance;
160
161
expect(instanceB).toBe(instanceA);
167
-
162
});
169
-
163
});
src/renderers/shared/fiber/__tests__/ReactTopLevelText-test.js
-1
@@ -39,5 +39,4 @@ describe('ReactTopLevelText', () => {
39
ReactNoop.flush();
40
expect(ReactNoop.getChildren()).toEqual([{text: '10'}]);
41
});
42
-
42
});
src/renderers/shared/fiber/isomorphic/ReactCoroutine.js
+13
-17
@@ -12,7 +12,7 @@
12
13
'use strict';
14
15
-import type { ReactNodeList } from 'ReactTypes';
15
+import type {ReactNodeList} from 'ReactTypes';
16
17
// The Symbol used to tag the special React types. If there is no native Symbol
18
// nor polyfill, then a plain number is used for performance.
@@ -42,11 +42,11 @@ export type ReactYield = {
42
};
43
44
exports.createCoroutine = function<T>(
45
- children : mixed,
46
- handler : CoroutineHandler<T>,
47
- props : T,
48
- key : ?string = null
49
-) : ReactCoroutine {
45
+ children: mixed,
46
+ handler: CoroutineHandler<T>,
47
+ props: T,
48
+ key: ?string = null,
49
+): ReactCoroutine {
50
var coroutine = {
51
// This tag allow us to uniquely identify this as a React Coroutine
52
$$typeof: REACT_COROUTINE_TYPE,
@@ -67,7 +67,7 @@ exports.createCoroutine = function<T>(
67
return coroutine;
68
};
69
70
-exports.createYield = function(value : mixed) : ReactYield {
70
+exports.createYield = function(value: mixed): ReactYield {
71
var yieldNode = {
72
// This tag allow us to uniquely identify this as a React Yield
73
$$typeof: REACT_YIELD_TYPE,
@@ -87,23 +87,19 @@ exports.createYield = function(value : mixed) : ReactYield {
87
/**
88
* Verifies the object is a coroutine object.
89
*/
90
-exports.isCoroutine = function(object : mixed) : boolean {
91
- return (
92
- typeof object === 'object' &&
90
+exports.isCoroutine = function(object: mixed): boolean {
91
+ return typeof object === 'object' &&
92
object !== null &&
94
- object.$$typeof === REACT_COROUTINE_TYPE
95
- );
93
+ object.$$typeof === REACT_COROUTINE_TYPE;
94
};
95
96
/**
97
* Verifies the object is a yield object.
98
*/
101
-exports.isYield = function(object : mixed) : boolean {
102
- return (
103
- typeof object === 'object' &&
99
+exports.isYield = function(object: mixed): boolean {
100
+ return typeof object === 'object' &&
101
object !== null &&
105
- object.$$typeof === REACT_YIELD_TYPE
106
- );
102
+ object.$$typeof === REACT_YIELD_TYPE;
103
};
104
105
exports.REACT_YIELD_TYPE = REACT_YIELD_TYPE;
src/renderers/shared/fiber/isomorphic/ReactPortal.js
+12
-13
@@ -12,30 +12,31 @@
12
13
'use strict';
14
15
-import type { ReactNodeList } from 'ReactTypes';
15
+import type {ReactNodeList} from 'ReactTypes';
16
17
// The Symbol used to tag the special React types. If there is no native Symbol
18
// nor polyfill, then a plain number is used for performance.
19
-var REACT_PORTAL_TYPE =
20
- (typeof Symbol === 'function' && Symbol.for && Symbol.for('react.portal')) ||
19
+var REACT_PORTAL_TYPE = (typeof Symbol === 'function' &&
20
+ Symbol.for &&
21
+ Symbol.for('react.portal')) ||
22
0xeaca;
23
24
export type ReactPortal = {
25
$$typeof: Symbol | number,
26
key: null | string,
27
containerInfo: any,
27
- children : ReactNodeList,
28
+ children: ReactNodeList,
29
// TODO: figure out the API for cross-renderer implementation.
30
implementation: any,
31
};
32
33
exports.createPortal = function(
33
- children : ReactNodeList,
34
- containerInfo : any,
34
+ children: ReactNodeList,
35
+ containerInfo: any,
36
// TODO: figure out the API for cross-renderer implementation.
37
implementation: any,
37
- key : ?string = null
38
-) : ReactPortal {
38
+ key: ?string = null,
39
+): ReactPortal {
40
return {
41
// This tag allow us to uniquely identify this as a React Portal
42
$$typeof: REACT_PORTAL_TYPE,
@@ -49,12 +50,10 @@ exports.createPortal = function(
50
/**
51
* Verifies the object is a portal object.
52
*/
52
-exports.isPortal = function(object : mixed) : boolean {
53
- return (
54
- typeof object === 'object' &&
53
+exports.isPortal = function(object: mixed): boolean {
54
+ return typeof object === 'object' &&
55
object !== null &&
56
- object.$$typeof === REACT_PORTAL_TYPE
57
- );
56
+ object.$$typeof === REACT_PORTAL_TYPE;
57
};
58
59
exports.REACT_PORTAL_TYPE = REACT_PORTAL_TYPE;
src/renderers/shared/fiber/isomorphic/ReactTypes.js
+9
-3
@@ -12,10 +12,16 @@
12
13
'use strict';
14
15
-import type { ReactCoroutine, ReactYield } from 'ReactCoroutine';
16
-import type { ReactPortal } from 'ReactPortal';
15
+import type {ReactCoroutine, ReactYield} from 'ReactCoroutine';
16
+import type {ReactPortal} from 'ReactPortal';
17
18
-export type ReactNode = ReactElement<any> | ReactCoroutine | ReactYield | ReactPortal | ReactText | ReactFragment;
18
+export type ReactNode =
19
+ | ReactElement<any>
20
+ | ReactCoroutine
21
+ | ReactYield
22
+ | ReactPortal
23
+ | ReactText
24
+ | ReactFragment;
25
26
export type ReactFragment = ReactEmpty | Iterable<ReactNode>;
27
src/renderers/shared/hooks/ReactHostOperationHistoryHook.js
+14
-13
@@ -12,19 +12,20 @@
12
13
'use strict';
14
15
-import type { DebugID } from 'ReactInstanceType';
16
-
17
-export type Operation = {instanceID: DebugID} & (
18
- {type: 'mount', payload: string} |
19
- {type: 'insert child', payload: {toIndex: number, content: string}} |
20
- {type: 'move child', payload: {fromIndex: number, toIndex: number}} |
21
- {type: 'replace children', payload: string} |
22
- {type: 'replace text', payload: string} |
23
- {type: 'replace with', payload: string} |
24
- {type: 'update styles', payload: mixed /* Style Object */} |
25
- {type: 'update attribute', payload: {[name: string]: string}} |
26
- {type: 'remove attribute', payload: string}
27
-);
15
+import type {DebugID} from 'ReactInstanceType';
16
+
17
+export type Operation =
18
+ & {instanceID: DebugID}
19
+ & (
20
+ | {type: 'mount', payload: string}
21
+ | {type: 'insert child', payload: {toIndex: number, content: string}}
22
+ | {type: 'move child', payload: {fromIndex: number, toIndex: number}}
23
+ | {type: 'replace children', payload: string}
24
+ | {type: 'replace text', payload: string}
25
+ | {type: 'replace with', payload: string}
26
+ | {type: 'update styles', payload: mixed /* Style Object */}
27
+ | {type: 'update attribute', payload: {[name: string]: string}}
28
+ | {type: 'remove attribute', payload: string});
29
30
// Trust the developer to only use this with a __DEV__ check
31
var ReactHostOperationHistoryHook = ((null: any): typeof ReactHostOperationHistoryHook);
src/renderers/shared/hooks/ReactInvalidSetStateWarningHook.js
+1
-1
@@ -22,7 +22,7 @@ if (__DEV__) {
22
var warnInvalidSetState = function() {
23
warning(
24
!processingChildContext,
25
- 'setState(...): Cannot call setState() inside getChildContext()'
25
+ 'setState(...): Cannot call setState() inside getChildContext()',
26
);
27
};
28
src/renderers/shared/shared/ReactInstanceMap.js
-2
@@ -20,7 +20,6 @@
20
21
// TODO: Replace this with ES6: var ReactInstanceMap = new Map();
22
var ReactInstanceMap = {
23
-
23
/**
24
* This API should be called `delete` but we'd have to make sure to always
25
* transform these to strings for IE support. When this transform is fully
@@ -41,7 +40,6 @@ var ReactInstanceMap = {
40
set: function(key, value) {
41
key._reactInternalInstance = value;
42
},
44
-
43
};
44
45
module.exports = ReactInstanceMap;
src/renderers/shared/shared/ReactTreeTraversal.js
+3
-3
@@ -11,7 +11,7 @@
11
12
'use strict';
13
14
-var { HostComponent } = require('ReactTypeOfWork');
14
+var {HostComponent} = require('ReactTypeOfWork');
15
16
function getParent(inst) {
17
if (inst._hostParent !== undefined) {
@@ -101,7 +101,7 @@ function traverseTwoPhase(inst, fn, arg) {
101
inst = getParent(inst);
102
}
103
var i;
104
- for (i = path.length; i-- > 0;) {
104
+ for (i = path.length; i-- > 0; ) {
105
fn(path[i], 'captured', arg);
106
}
107
for (i = 0; i < path.length; i++) {
@@ -132,7 +132,7 @@ function traverseEnterLeave(from, to, fn, argFrom, argTo) {
132
for (i = 0; i < pathFrom.length; i++) {
133
fn(pathFrom[i], 'bubbled', argFrom);
134
}
135
- for (i = pathTo.length; i-- > 0;) {
135
+ for (i = pathTo.length; i-- > 0; ) {
136
fn(pathTo[i], 'captured', argTo);
137
}
138
}
src/renderers/shared/shared/event/EventPluginHub.js
+21
-18
@@ -49,10 +49,10 @@ var executeDispatchesAndReleaseTopLevel = function(e) {
49
};
50
51
function isInteractive(tag) {
52
- return (
53
- tag === 'button' || tag === 'input' ||
54
- tag === 'select' || tag === 'textarea'
55
- );
52
+ return tag === 'button' ||
53
+ tag === 'input' ||
54
+ tag === 'select' ||
55
+ tag === 'textarea';
56
}
57
58
function shouldPreventMouseEvent(name, type, props) {
@@ -96,12 +96,10 @@ function shouldPreventMouseEvent(name, type, props) {
96
* @public
97
*/
98
var EventPluginHub = {
99
-
99
/**
100
* Methods for injecting dependencies.
101
*/
102
injection: {
104
-
103
/**
104
* @param {array} InjectedEventPluginOrder
105
* @public
@@ -112,7 +110,6 @@ var EventPluginHub = {
110
* @param {object} injectedNamesToPlugins Map from names to plugin modules.
111
*/
112
injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName,
115
-
113
},
114
115
/**
@@ -151,7 +148,13 @@ var EventPluginHub = {
148
}
149
const props = inst._currentElement.props;
150
listener = props[registrationName];
154
- if (shouldPreventMouseEvent(registrationName, inst._currentElement.type, props)) {
151
+ if (
152
+ shouldPreventMouseEvent(
153
+ registrationName,
154
+ inst._currentElement.type,
155
+ props,
156
+ )
157
+ ) {
158
return null;
159
}
160
}
@@ -160,7 +163,7 @@ var EventPluginHub = {
163
!listener || typeof listener === 'function',
164
'Expected %s listener to be a function, instead got type %s',
165
registrationName,
163
- typeof listener
166
+ typeof listener,
167
);
168
return listener;
169
},
@@ -173,10 +176,11 @@ var EventPluginHub = {
176
* @internal
177
*/
178
extractEvents: function(
176
- topLevelType,
177
- targetInst,
178
- nativeEvent,
179
- nativeEventTarget) {
179
+ topLevelType,
180
+ targetInst,
181
+ nativeEvent,
182
+ nativeEventTarget,
183
+ ) {
184
var events;
185
var plugins = EventPluginRegistry.plugins;
186
for (var i = 0; i < plugins.length; i++) {
@@ -187,7 +191,7 @@ var EventPluginHub = {
191
topLevelType,
192
targetInst,
193
nativeEvent,
190
- nativeEventTarget
194
+ nativeEventTarget,
195
);
196
if (extractedEvents) {
197
events = accumulateInto(events, extractedEvents);
@@ -223,23 +227,22 @@ var EventPluginHub = {
227
if (simulated) {
228
forEachAccumulated(
229
processingEventQueue,
226
- executeDispatchesAndReleaseSimulated
230
+ executeDispatchesAndReleaseSimulated,
231
);
232
} else {
233
forEachAccumulated(
234
processingEventQueue,
231
- executeDispatchesAndReleaseTopLevel
235
+ executeDispatchesAndReleaseTopLevel,
236
);
237
}
238
invariant(
239
!eventQueue,
240
'processEventQueue(): Additional events were enqueued while processing ' +
237
- 'an event queue. Support for this has not yet been implemented.'
241
+ 'an event queue. Support for this has not yet been implemented.',
242
);
243
// This would be a good time to rethrow if any of the event handlers threw.
244
ReactErrorUtils.rethrowCaughtError();
245
},
242
-
246
};
247
248
module.exports = EventPluginHub;
src/renderers/shared/shared/event/EventPluginRegistry.js
+19
-23
@@ -12,15 +12,9 @@
12
13
'use strict';
14
15
-import type {
16
- DispatchConfig,
17
-} from 'ReactSyntheticEventType';
15
+import type {DispatchConfig} from 'ReactSyntheticEventType';
16
19
-import type {
20
- AnyNativeEvent,
21
- PluginName,
22
- PluginModule,
23
-} from 'PluginModuleType';
17
+import type {AnyNativeEvent, PluginName, PluginModule} from 'PluginModuleType';
18
19
type NamesToPlugins = {[key: PluginName]: PluginModule<AnyNativeEvent>};
20
@@ -54,7 +48,7 @@ function recomputePluginOrdering(): void {
48
invariant(
49
pluginIndex > -1,
50
'EventPluginRegistry: Cannot inject event plugins that do not exist in ' +
57
- 'the plugin ordering, `%s`.',
51
+ 'the plugin ordering, `%s`.',
52
pluginName,
53
);
54
if (EventPluginRegistry.plugins[pluginIndex]) {
@@ -63,7 +57,7 @@ function recomputePluginOrdering(): void {
57
invariant(
58
pluginModule.extractEvents,
59
'EventPluginRegistry: Event plugins must implement an `extractEvents` ' +
66
- 'method, but `%s` does not.',
60
+ 'method, but `%s` does not.',
61
pluginName,
62
);
63
EventPluginRegistry.plugins[pluginIndex] = pluginModule;
@@ -99,7 +93,7 @@ function publishEventForPlugin(
93
invariant(
94
!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName),
95
'EventPluginHub: More than one plugin attempted to publish the same ' +
102
- 'event name, `%s`.',
96
+ 'event name, `%s`.',
97
eventName,
98
);
99
EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig;
@@ -143,18 +137,19 @@ function publishRegistrationName(
137
invariant(
138
!EventPluginRegistry.registrationNameModules[registrationName],
139
'EventPluginHub: More than one plugin attempted to publish the same ' +
146
- 'registration name, `%s`.',
140
+ 'registration name, `%s`.',
141
registrationName,
142
);
143
EventPluginRegistry.registrationNameModules[registrationName] = pluginModule;
150
- EventPluginRegistry.registrationNameDependencies[registrationName] =
151
- pluginModule.eventTypes[eventName].dependencies;
144
+ EventPluginRegistry.registrationNameDependencies[
145
+ registrationName
146
+ ] = pluginModule.eventTypes[eventName].dependencies;
147
148
if (__DEV__) {
149
var lowerCasedName = registrationName.toLowerCase();
155
- EventPluginRegistry.possibleRegistrationNames[lowerCasedName] =
156
- registrationName;
157
-
150
+ EventPluginRegistry.possibleRegistrationNames[
151
+ lowerCasedName
152
+ ] = registrationName;
153
154
if (registrationName === 'onDoubleClick') {
155
EventPluginRegistry.possibleRegistrationNames.ondblclick = registrationName;
@@ -168,7 +163,6 @@ function publishRegistrationName(
163
* @see {EventPluginHub}
164
*/
165
var EventPluginRegistry = {
171
-
166
/**
167
* Ordered list of injected plugins.
168
*/
@@ -213,7 +207,7 @@ var EventPluginRegistry = {
207
invariant(
208
!eventPluginOrder,
209
'EventPluginRegistry: Cannot inject event plugin ordering more than ' +
216
- 'once. You are likely trying to load more than one copy of React.',
210
+ 'once. You are likely trying to load more than one copy of React.',
211
);
212
// Clone the ordering so it cannot be dynamically mutated.
213
eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder);
@@ -231,7 +225,7 @@ var EventPluginRegistry = {
225
* @see {EventPluginHub.injection.injectEventPluginsByName}
226
*/
227
injectEventPluginsByName: function(
234
- injectedNamesToPlugins: NamesToPlugins
228
+ injectedNamesToPlugins: NamesToPlugins,
229
): void {
230
var isOrderingDirty = false;
231
for (var pluginName in injectedNamesToPlugins) {
@@ -239,12 +233,14 @@ var EventPluginRegistry = {
233
continue;
234
}
235
var pluginModule = injectedNamesToPlugins[pluginName];
242
- if (!namesToPlugins.hasOwnProperty(pluginName) ||
243
- namesToPlugins[pluginName] !== pluginModule) {
236
+ if (
237
+ !namesToPlugins.hasOwnProperty(pluginName) ||
238
+ namesToPlugins[pluginName] !== pluginModule
239
+ ) {
240
invariant(
241
!namesToPlugins[pluginName],
242
'EventPluginRegistry: Cannot inject two different event plugins ' +
247
- 'using the same name, `%s`.',
243
+ 'using the same name, `%s`.',
244
pluginName,
245
);
246
namesToPlugins[pluginName] = pluginModule;
src/renderers/shared/shared/event/EventPluginUtils.js
+25
-21
@@ -31,10 +31,10 @@ var injection = {
31
if (__DEV__) {
32
warning(
33
Injected &&
34
- Injected.getNodeFromInstance &&
35
- Injected.getInstanceFromNode,
34
+ Injected.getNodeFromInstance &&
35
+ Injected.getInstanceFromNode,
36
'EventPluginUtils.injection.injectComponentTree(...): Injected ' +
37
- 'module is missing getNodeFromInstance or getInstanceFromNode.'
37
+ 'module is missing getNodeFromInstance or getInstanceFromNode.',
38
);
39
}
40
},
@@ -42,20 +42,17 @@ var injection = {
42
43
function isEndish(topLevelType) {
44
return topLevelType === 'topMouseUp' ||
45
- topLevelType === 'topTouchEnd' ||
46
- topLevelType === 'topTouchCancel';
45
+ topLevelType === 'topTouchEnd' ||
46
+ topLevelType === 'topTouchCancel';
47
}
48
49
function isMoveish(topLevelType) {
50
- return topLevelType === 'topMouseMove' ||
51
- topLevelType === 'topTouchMove';
50
+ return topLevelType === 'topMouseMove' || topLevelType === 'topTouchMove';
51
}
52
function isStartish(topLevelType) {
54
- return topLevelType === 'topMouseDown' ||
55
- topLevelType === 'topTouchStart';
53
+ return topLevelType === 'topMouseDown' || topLevelType === 'topTouchStart';
54
}
55
58
-
56
var validateEventDispatches;
57
if (__DEV__) {
58
validateEventDispatches = function(event) {
@@ -63,18 +60,18 @@ if (__DEV__) {
60
var dispatchInstances = event._dispatchInstances;
61
62
var listenersIsArr = Array.isArray(dispatchListeners);
66
- var listenersLen = listenersIsArr ?
67
- dispatchListeners.length :
68
- dispatchListeners ? 1 : 0;
63
+ var listenersLen = listenersIsArr
64
+ ? dispatchListeners.length
65
+ : dispatchListeners ? 1 : 0;
66
67
var instancesIsArr = Array.isArray(dispatchInstances);
71
- var instancesLen = instancesIsArr ?
72
- dispatchInstances.length :
73
- dispatchInstances ? 1 : 0;
68
+ var instancesLen = instancesIsArr
69
+ ? dispatchInstances.length
70
+ : dispatchInstances ? 1 : 0;
71
72
warning(
73
instancesIsArr === listenersIsArr && instancesLen === listenersLen,
77
- 'EventPluginUtils: Invalid `event`.'
74
+ 'EventPluginUtils: Invalid `event`.',
75
);
76
};
77
}
@@ -89,7 +86,12 @@ if (__DEV__) {
86
function executeDispatch(event, simulated, listener, inst) {
87
var type = event.type || 'unknown-event';
88
event.currentTarget = EventPluginUtils.getNodeFromInstance(inst);
92
- ReactErrorUtils.invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);
89
+ ReactErrorUtils.invokeGuardedCallbackAndCatchFirstError(
90
+ type,
91
+ listener,
92
+ undefined,
93
+ event,
94
+ );
95
event.currentTarget = null;
96
}
97
@@ -112,7 +114,7 @@ function executeDispatchesInOrder(event, simulated) {
114
event,
115
simulated,
116
dispatchListeners[i],
115
- dispatchInstances[i]
117
+ dispatchInstances[i],
118
);
119
}
120
} else if (dispatchListeners) {
@@ -180,9 +182,11 @@ function executeDirectDispatch(event) {
182
var dispatchInstance = event._dispatchInstances;
183
invariant(
184
!Array.isArray(dispatchListener),
183
- 'executeDirectDispatch(...): Invalid `event`.'
185
+ 'executeDirectDispatch(...): Invalid `event`.',
186
);
185
- event.currentTarget = dispatchListener ? EventPluginUtils.getNodeFromInstance(dispatchInstance) : null;
187
+ event.currentTarget = dispatchListener
188
+ ? EventPluginUtils.getNodeFromInstance(dispatchInstance)
189
+ : null;
190
var res = dispatchListener ? dispatchListener(event) : null;
191
event.currentTarget = null;
192
event._dispatchListeners = null;
src/renderers/shared/shared/event/EventPropagators.js
+19
-20
@@ -18,7 +18,7 @@ var accumulateInto = require('accumulateInto');
18
var forEachAccumulated = require('forEachAccumulated');
19
var warning = require('fbjs/lib/warning');
20
21
-import type { PropagationPhases } from 'EventConstants';
21
+import type {PropagationPhases} from 'EventConstants';
22
23
var getListener = EventPluginHub.getListener;
24
@@ -27,8 +27,9 @@ var getListener = EventPluginHub.getListener;
27
* "phases" of propagation. This finds listeners by a given phase.
28
*/
29
function listenerAtPhase(inst, event, propagationPhase: PropagationPhases) {
30
- var registrationName =
31
- event.dispatchConfig.phasedRegistrationNames[propagationPhase];
30
+ var registrationName = event.dispatchConfig.phasedRegistrationNames[
31
+ propagationPhase
32
+ ];
33
return getListener(inst, registrationName);
34
}
35
@@ -40,15 +41,14 @@ function listenerAtPhase(inst, event, propagationPhase: PropagationPhases) {
41
*/
42
function accumulateDirectionalDispatches(inst, phase, event) {
43
if (__DEV__) {
43
- warning(
44
- inst,
45
- 'Dispatching inst must not be null'
46
- );
44
+ warning(inst, 'Dispatching inst must not be null');
45
}
46
var listener = listenerAtPhase(inst, event, phase);
47
if (listener) {
50
- event._dispatchListeners =
51
- accumulateInto(event._dispatchListeners, listener);
48
+ event._dispatchListeners = accumulateInto(
49
+ event._dispatchListeners,
50
+ listener,
51
+ );
52
event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
53
}
54
}
@@ -65,7 +65,7 @@ function accumulateTwoPhaseDispatchesSingle(event) {
65
ReactTreeTraversal.traverseTwoPhase(
66
event._targetInst,
67
accumulateDirectionalDispatches,
68
- event
68
+ event,
69
);
70
}
71
}
@@ -76,17 +76,17 @@ function accumulateTwoPhaseDispatchesSingle(event) {
76
function accumulateTwoPhaseDispatchesSingleSkipTarget(event) {
77
if (event && event.dispatchConfig.phasedRegistrationNames) {
78
var targetInst = event._targetInst;
79
- var parentInst =
80
- targetInst ? ReactTreeTraversal.getParentInstance(targetInst) : null;
79
+ var parentInst = targetInst
80
+ ? ReactTreeTraversal.getParentInstance(targetInst)
81
+ : null;
82
ReactTreeTraversal.traverseTwoPhase(
83
parentInst,
84
accumulateDirectionalDispatches,
84
- event
85
+ event,
86
);
87
}
88
}
89
89
-
90
/**
91
* Accumulates without regard to direction, does not look for phased
92
* registration names. Same as `accumulateDirectDispatchesSingle` but without
@@ -97,8 +97,10 @@ function accumulateDispatches(inst, ignoredDirection, event) {
97
var registrationName = event.dispatchConfig.registrationName;
98
var listener = getListener(inst, registrationName);
99
if (listener) {
100
- event._dispatchListeners =
101
- accumulateInto(event._dispatchListeners, listener);
100
+ event._dispatchListeners = accumulateInto(
101
+ event._dispatchListeners,
102
+ listener,
103
+ );
104
event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
105
}
106
}
@@ -129,17 +131,14 @@ function accumulateEnterLeaveDispatches(leave, enter, from, to) {
131
to,
132
accumulateDispatches,
133
leave,
132
- enter
134
+ enter,
135
);
136
}
137
136
-
138
function accumulateDirectDispatches(events) {
139
forEachAccumulated(events, accumulateDirectDispatchesSingle);
140
}
141
141
-
142
-
142
/**
143
* A small set of propagation patterns, each of which will accept a small amount
144
* of information, and generate a set of "dispatch ready event objects" - which
src/renderers/shared/shared/event/PluginModuleType.js
+1
-5
@@ -20,11 +20,7 @@ import type {
20
21
export type EventTypes = {[key: string]: DispatchConfig};
22
23
-export type AnyNativeEvent =
24
- Event |
25
- KeyboardEvent |
26
- MouseEvent |
27
- Touch;
23
+export type AnyNativeEvent = Event | KeyboardEvent | MouseEvent | Touch;
24
25
export type PluginName = string;
26
src/renderers/shared/shared/event/ReactControlledComponent.js
+5
-5
@@ -41,23 +41,23 @@ function restoreStateOfTarget(target) {
41
if (typeof internalInstance.tag === 'number') {
42
invariant(
43
fiberHostComponent &&
44
- typeof fiberHostComponent.restoreControlledState === 'function',
44
+ typeof fiberHostComponent.restoreControlledState === 'function',
45
'Fiber needs to be injected to handle a fiber target for controlled ' +
46
- 'events.'
46
+ 'events.',
47
);
48
const props = EventPluginUtils.getFiberCurrentPropsFromNode(
49
- internalInstance.stateNode
49
+ internalInstance.stateNode,
50
);
51
fiberHostComponent.restoreControlledState(
52
internalInstance.stateNode,
53
internalInstance.type,
54
- props
54
+ props,
55
);
56
return;
57
}
58
invariant(
59
typeof internalInstance.restoreControlledState === 'function',
60
- 'The internal instance must be a React host component.'
60
+ 'The internal instance must be a React host component.',
61
);
62
// If it is not a Fiber, we can just use dynamic dispatch.
63
internalInstance.restoreControlledState();
src/renderers/shared/shared/event/ReactEventEmitterMixin.js
+6
-6
@@ -19,21 +19,21 @@ function runEventQueueInBatch(events) {
19
}
20
21
var ReactEventEmitterMixin = {
22
-
22
/**
23
* Streams a fired top-level event to `EventPluginHub` where plugins have the
24
* opportunity to create `ReactEvent`s to be dispatched.
25
*/
26
handleTopLevel: function(
28
- topLevelType,
29
- targetInst,
30
- nativeEvent,
31
- nativeEventTarget) {
27
+ topLevelType,
28
+ targetInst,
29
+ nativeEvent,
30
+ nativeEventTarget,
31
+ ) {
32
var events = EventPluginHub.extractEvents(
33
topLevelType,
34
targetInst,
35
nativeEvent,
36
- nativeEventTarget
36
+ nativeEventTarget,
37
);
38
runEventQueueInBatch(events);
39
},
src/renderers/shared/shared/event/ReactSyntheticEventType.js
+10
-8
@@ -25,12 +25,14 @@ export type DispatchConfig = {
25
registrationName?: string,
26
};
27
28
-export type ReactSyntheticEvent = {
29
- dispatchConfig: DispatchConfig,
30
- getPooled: (
28
+export type ReactSyntheticEvent =
29
+ & {
30
dispatchConfig: DispatchConfig,
32
- targetInst: ReactInstance,
33
- nativeTarget: Event,
34
- nativeEventTarget: EventTarget,
35
- ) => ReactSyntheticEvent,
36
-} & SyntheticEvent;
31
+ getPooled: (
32
+ dispatchConfig: DispatchConfig,
33
+ targetInst: ReactInstance,
34
+ nativeTarget: Event,
35
+ nativeEventTarget: EventTarget,
36
+ ) => ReactSyntheticEvent,
37
+ }
38
+ & SyntheticEvent;
src/renderers/shared/shared/event/SyntheticEvent.js
+38
-25
@@ -66,7 +66,12 @@ var EventInterface = {
66
* @param {object} nativeEvent Native browser event.
67
* @param {DOMEventTarget} nativeEventTarget Target node.
68
*/
69
-function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) {
69
+function SyntheticEvent(
70
+ dispatchConfig,
71
+ targetInst,
72
+ nativeEvent,
73
+ nativeEventTarget,
74
+) {
75
if (__DEV__) {
76
// these have a getter/setter for warnings
77
delete this.nativeEvent;
@@ -98,9 +103,9 @@ function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarg
103
}
104
}
105
101
- var defaultPrevented = nativeEvent.defaultPrevented != null ?
102
- nativeEvent.defaultPrevented :
103
- nativeEvent.returnValue === false;
106
+ var defaultPrevented = nativeEvent.defaultPrevented != null
107
+ ? nativeEvent.defaultPrevented
108
+ : nativeEvent.returnValue === false;
109
if (defaultPrevented) {
110
this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
111
} else {
@@ -111,7 +116,6 @@ function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarg
116
}
117
118
Object.assign(SyntheticEvent.prototype, {
114
-
119
preventDefault: function() {
120
this.defaultPrevented = true;
121
var event = this.nativeEvent;
@@ -121,7 +125,8 @@ Object.assign(SyntheticEvent.prototype, {
125
126
if (event.preventDefault) {
127
event.preventDefault();
124
- } else if (typeof event.returnValue !== 'unknown') { // eslint-disable-line valid-typeof
128
+ } else if (typeof event.returnValue !== 'unknown') {
129
+ // eslint-disable-line valid-typeof
130
event.returnValue = false;
131
}
132
this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
@@ -135,7 +140,8 @@ Object.assign(SyntheticEvent.prototype, {
140
141
if (event.stopPropagation) {
142
event.stopPropagation();
138
- } else if (typeof event.cancelBubble !== 'unknown') { // eslint-disable-line valid-typeof
143
+ } else if (typeof event.cancelBubble !== 'unknown') {
144
+ // eslint-disable-line valid-typeof
145
// The ChangeEventPlugin registers a "propertychange" event for
146
// IE. This event does not support bubbling or cancelling, and
147
// any references to cancelBubble throw "Member not found". A
@@ -170,7 +176,11 @@ Object.assign(SyntheticEvent.prototype, {
176
var Interface = this.constructor.Interface;
177
for (var propName in Interface) {
178
if (__DEV__) {
173
- Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName]));
179
+ Object.defineProperty(
180
+ this,
181
+ propName,
182
+ getPooledWarningPropertyDefinition(propName, Interface[propName]),
183
+ );
184
} else {
185
this[propName] = null;
186
}
@@ -182,21 +192,20 @@ Object.assign(SyntheticEvent.prototype, {
192
Object.defineProperty(
193
this,
194
'nativeEvent',
185
- getPooledWarningPropertyDefinition('nativeEvent', null)
195
+ getPooledWarningPropertyDefinition('nativeEvent', null),
196
);
197
Object.defineProperty(
198
this,
199
'preventDefault',
190
- getPooledWarningPropertyDefinition('preventDefault', emptyFunction)
200
+ getPooledWarningPropertyDefinition('preventDefault', emptyFunction),
201
);
202
Object.defineProperty(
203
this,
204
'stopPropagation',
195
- getPooledWarningPropertyDefinition('stopPropagation', emptyFunction)
205
+ getPooledWarningPropertyDefinition('stopPropagation', emptyFunction),
206
);
207
}
208
},
199
-
209
});
210
211
SyntheticEvent.Interface = EventInterface;
@@ -211,15 +220,17 @@ if (__DEV__) {
220
apply: function(constructor, that, args) {
221
return new Proxy(constructor.apply(that, args), {
222
set: function(target, prop, value) {
214
- if (prop !== 'isPersistent' &&
215
- !target.constructor.Interface.hasOwnProperty(prop) &&
216
- shouldBeReleasedProperties.indexOf(prop) === -1) {
223
+ if (
224
+ prop !== 'isPersistent' &&
225
+ !target.constructor.Interface.hasOwnProperty(prop) &&
226
+ shouldBeReleasedProperties.indexOf(prop) === -1
227
+ ) {
228
warning(
229
didWarnForAddedNewProperty || target.isPersistent(),
219
- 'This synthetic event is reused for performance reasons. If you\'re ' +
220
- 'seeing this, you\'re adding a new property in the synthetic event object. ' +
221
- 'The property is never released. See ' +
222
- 'https://fb.me/react-event-pooling for more information.'
230
+ "This synthetic event is reused for performance reasons. If you're " +
231
+ "seeing this, you're adding a new property in the synthetic event object. " +
232
+ 'The property is never released. See ' +
233
+ 'https://fb.me/react-event-pooling for more information.',
234
);
235
didWarnForAddedNewProperty = true;
236
}
@@ -282,7 +293,9 @@ function getPooledWarningPropertyDefinition(propName, getVal) {
293
294
function get() {
295
var action = isFunction ? 'accessing the method' : 'accessing the property';
285
- var result = isFunction ? 'This is a no-op function' : 'This is set to null';
296
+ var result = isFunction
297
+ ? 'This is a no-op function'
298
+ : 'This is set to null';
299
warn(action, result);
300
return getVal;
301
}
@@ -291,13 +304,13 @@ function getPooledWarningPropertyDefinition(propName, getVal) {
304
var warningCondition = false;
305
warning(
306
warningCondition,
294
- 'This synthetic event is reused for performance reasons. If you\'re seeing this, ' +
295
- 'you\'re %s `%s` on a released/nullified synthetic event. %s. ' +
296
- 'If you must keep the original synthetic event around, use event.persist(). ' +
297
- 'See https://fb.me/react-event-pooling for more information.',
307
+ "This synthetic event is reused for performance reasons. If you're seeing this, " +
308
+ "you're %s `%s` on a released/nullified synthetic event. %s. " +
309
+ 'If you must keep the original synthetic event around, use event.persist(). ' +
310
+ 'See https://fb.me/react-event-pooling for more information.',
311
action,
312
propName,
300
- result
313
+ result,
314
);
315
}
316
}
src/renderers/shared/shared/event/__tests__/EventPluginRegistry-test.js
+20
-13
@@ -11,7 +11,6 @@
11
12
'use strict';
13
14
-
14
describe('EventPluginRegistry', () => {
15
var EventPluginRegistry;
16
var createPlugin;
@@ -97,7 +96,7 @@ describe('EventPluginRegistry', () => {
96
});
97
}).toThrowError(
98
'EventPluginRegistry: Event plugins must implement an `extractEvents` ' +
100
- 'method, but `bad` does not.'
99
+ 'method, but `bad` does not.',
100
);
101
});
102
@@ -114,7 +113,7 @@ describe('EventPluginRegistry', () => {
113
});
114
}).toThrowError(
115
'EventPluginRegistry: Cannot inject event plugins that do not exist ' +
117
- 'in the plugin ordering, `random`.'
116
+ 'in the plugin ordering, `random`.',
117
);
118
});
119
@@ -127,7 +126,7 @@ describe('EventPluginRegistry', () => {
126
EventPluginRegistry.injectEventPluginOrder(pluginOrdering);
127
}).toThrowError(
128
'EventPluginRegistry: Cannot inject event plugin ordering more than ' +
130
- 'once. You are likely trying to load more than one copy of React.'
129
+ 'once. You are likely trying to load more than one copy of React.',
130
);
131
});
132
@@ -141,7 +140,7 @@ describe('EventPluginRegistry', () => {
140
EventPluginRegistry.injectEventPluginsByName({same: TwoPlugin});
141
}).toThrowError(
142
'EventPluginRegistry: Cannot inject two different event plugins using ' +
144
- 'the same name, `same`.'
143
+ 'the same name, `same`.',
144
);
145
});
146
@@ -166,17 +165,23 @@ describe('EventPluginRegistry', () => {
165
EventPluginRegistry.injectEventPluginsByName({one: OnePlugin});
166
EventPluginRegistry.injectEventPluginOrder(['one', 'two']);
167
169
- expect(Object.keys(EventPluginRegistry.registrationNameModules).length).toBe(2);
168
+ expect(
169
+ Object.keys(EventPluginRegistry.registrationNameModules).length,
170
+ ).toBe(2);
171
expect(EventPluginRegistry.registrationNameModules.onClick).toBe(OnePlugin);
172
expect(EventPluginRegistry.registrationNameModules.onFocus).toBe(OnePlugin);
173
174
EventPluginRegistry.injectEventPluginsByName({two: TwoPlugin});
175
175
- expect(Object.keys(EventPluginRegistry.registrationNameModules).length).toBe(4);
176
- expect(EventPluginRegistry.registrationNameModules.onMagicBubble).toBe(TwoPlugin);
176
expect(
178
- EventPluginRegistry.registrationNameModules.onMagicCapture
179
- ).toBe(TwoPlugin);
177
+ Object.keys(EventPluginRegistry.registrationNameModules).length,
178
+ ).toBe(4);
179
+ expect(EventPluginRegistry.registrationNameModules.onMagicBubble).toBe(
180
+ TwoPlugin,
181
+ );
182
+ expect(EventPluginRegistry.registrationNameModules.onMagicCapture).toBe(
183
+ TwoPlugin,
184
+ );
185
});
186
187
it('should throw if multiple registration names collide', () => {
@@ -205,14 +210,16 @@ describe('EventPluginRegistry', () => {
210
EventPluginRegistry.injectEventPluginOrder(['one', 'two']);
211
}).toThrowError(
212
'EventPluginHub: More than one plugin attempted to publish the same ' +
208
- 'registration name, `onPhotoCapture`.'
213
+ 'registration name, `onPhotoCapture`.',
214
);
215
});
216
217
it('should throw if an invalid event is published', () => {
218
var OnePlugin = createPlugin({
219
eventTypes: {
215
- badEvent: {/* missing configuration */},
220
+ badEvent: {
221
+ /* missing configuration */
222
+ },
223
},
224
});
225
@@ -222,7 +229,7 @@ describe('EventPluginRegistry', () => {
229
EventPluginRegistry.injectEventPluginOrder(['one']);
230
}).toThrowError(
231
'EventPluginRegistry: Failed to publish event `badEvent` for plugin ' +
225
- '`one`.'
232
+ '`one`.',
233
);
234
});
235
});
src/renderers/shared/shared/event/eventPlugins/ResponderEventPlugin.js
+59
-66
@@ -24,8 +24,7 @@ var isMoveish = EventPluginUtils.isMoveish;
24
var isEndish = EventPluginUtils.isEndish;
25
var executeDirectDispatch = EventPluginUtils.executeDirectDispatch;
26
var hasDispatches = EventPluginUtils.hasDispatches;
27
-var executeDispatchesInOrderStopAtTrue =
28
- EventPluginUtils.executeDispatchesInOrderStopAtTrue;
27
+var executeDispatchesInOrderStopAtTrue = EventPluginUtils.executeDispatchesInOrderStopAtTrue;
28
29
/**
30
* Instance of element that should respond to touch/move types of interactions,
@@ -51,7 +50,7 @@ var changeResponder = function(nextResponderInst, blockHostResponder) {
50
ResponderEventPlugin.GlobalResponderHandler.onChange(
51
oldResponderInst,
52
nextResponderInst,
54
- blockHostResponder
53
+ blockHostResponder,
54
);
55
}
56
};
@@ -254,8 +253,6 @@ to return true:wantsResponderID| |
253
| |
254
+ + */
255
257
-
258
-
256
/**
257
* A note about event ordering in the `EventPluginHub`.
258
*
@@ -320,19 +317,20 @@ function setResponderAndExtractTransfer(
317
topLevelType,
318
targetInst,
319
nativeEvent,
323
- nativeEventTarget
320
+ nativeEventTarget,
321
) {
325
- var shouldSetEventType =
326
- isStartish(topLevelType) ? eventTypes.startShouldSetResponder :
327
- isMoveish(topLevelType) ? eventTypes.moveShouldSetResponder :
328
- topLevelType === 'topSelectionChange' ?
329
- eventTypes.selectionChangeShouldSetResponder :
330
- eventTypes.scrollShouldSetResponder;
322
+ var shouldSetEventType = isStartish(topLevelType)
323
+ ? eventTypes.startShouldSetResponder
324
+ : isMoveish(topLevelType)
325
+ ? eventTypes.moveShouldSetResponder
326
+ : topLevelType === 'topSelectionChange'
327
+ ? eventTypes.selectionChangeShouldSetResponder
328
+ : eventTypes.scrollShouldSetResponder;
329
330
// TODO: stop one short of the current responder.
333
- var bubbleShouldSetFrom = !responderInst ?
334
- targetInst :
335
- ReactTreeTraversal.getLowestCommonAncestor(responderInst, targetInst);
331
+ var bubbleShouldSetFrom = !responderInst
332
+ ? targetInst
333
+ : ReactTreeTraversal.getLowestCommonAncestor(responderInst, targetInst);
334
335
// When capturing/bubbling the "shouldSet" event, we want to skip the target
336
// (deepest ID) if it happens to be the current responder. The reasoning:
@@ -343,7 +341,7 @@ function setResponderAndExtractTransfer(
341
shouldSetEventType,
342
bubbleShouldSetFrom,
343
nativeEvent,
346
- nativeEventTarget
344
+ nativeEventTarget,
345
);
346
shouldSetEvent.touchHistory = ResponderTouchHistoryStore.touchHistory;
347
if (skipOverBubbleShouldSetFrom) {
@@ -364,19 +362,18 @@ function setResponderAndExtractTransfer(
362
eventTypes.responderGrant,
363
wantsResponderInst,
364
nativeEvent,
367
- nativeEventTarget
365
+ nativeEventTarget,
366
);
367
grantEvent.touchHistory = ResponderTouchHistoryStore.touchHistory;
368
369
EventPropagators.accumulateDirectDispatches(grantEvent);
370
var blockHostResponder = executeDirectDispatch(grantEvent) === true;
371
if (responderInst) {
374
-
372
var terminationRequestEvent = ResponderSyntheticEvent.getPooled(
373
eventTypes.responderTerminationRequest,
374
responderInst,
375
nativeEvent,
379
- nativeEventTarget
376
+ nativeEventTarget,
377
);
378
terminationRequestEvent.touchHistory = ResponderTouchHistoryStore.touchHistory;
379
EventPropagators.accumulateDirectDispatches(terminationRequestEvent);
@@ -391,7 +388,7 @@ function setResponderAndExtractTransfer(
388
eventTypes.responderTerminate,
389
responderInst,
390
nativeEvent,
394
- nativeEventTarget
391
+ nativeEventTarget,
392
);
393
terminateEvent.touchHistory = ResponderTouchHistoryStore.touchHistory;
394
EventPropagators.accumulateDirectDispatches(terminateEvent);
@@ -402,7 +399,7 @@ function setResponderAndExtractTransfer(
399
eventTypes.responderReject,
400
wantsResponderInst,
401
nativeEvent,
405
- nativeEventTarget
402
+ nativeEventTarget,
403
);
404
rejectEvent.touchHistory = ResponderTouchHistoryStore.touchHistory;
405
EventPropagators.accumulateDirectDispatches(rejectEvent);
@@ -424,17 +421,14 @@ function setResponderAndExtractTransfer(
421
* @return {boolean} True if a transfer of responder could possibly occur.
422
*/
423
function canTriggerTransfer(topLevelType, topLevelInst, nativeEvent) {
427
- return topLevelInst && (
424
+ return topLevelInst &&
425
// responderIgnoreScroll: We are trying to migrate away from specifically
426
// tracking native scroll events here and responderIgnoreScroll indicates we
427
// will send topTouchCancel to handle canceling touch events instead
431
- (topLevelType === 'topScroll' &&
432
- !nativeEvent.responderIgnoreScroll) ||
433
- (trackedTouchCount > 0 &&
434
- topLevelType === 'topSelectionChange') ||
435
- isStartish(topLevelType) ||
436
- isMoveish(topLevelType)
437
- );
428
+ ((topLevelType === 'topScroll' && !nativeEvent.responderIgnoreScroll) ||
429
+ (trackedTouchCount > 0 && topLevelType === 'topSelectionChange') ||
430
+ isStartish(topLevelType) ||
431
+ isMoveish(topLevelType));
432
}
433
434
/**
@@ -463,9 +457,7 @@ function noResponderTouches(nativeEvent) {
457
return true;
458
}
459
466
-
460
var ResponderEventPlugin = {
468
-
461
/* For unit testing only */
462
_getResponder: function() {
463
return responderInst;
@@ -482,7 +474,7 @@ var ResponderEventPlugin = {
474
topLevelType,
475
targetInst,
476
nativeEvent,
485
- nativeEventTarget
477
+ nativeEventTarget,
478
) {
479
if (isStartish(topLevelType)) {
480
trackedTouchCount += 1;
@@ -491,7 +483,7 @@ var ResponderEventPlugin = {
483
trackedTouchCount -= 1;
484
} else {
485
console.error(
494
- 'Ended a touch event which was not counted in `trackedTouchCount`.'
486
+ 'Ended a touch event which was not counted in `trackedTouchCount`.',
487
);
488
return null;
489
}
@@ -499,13 +491,14 @@ var ResponderEventPlugin = {
491
492
ResponderTouchHistoryStore.recordTouchTrack(topLevelType, nativeEvent);
493
502
- var extracted = canTriggerTransfer(topLevelType, targetInst, nativeEvent) ?
503
- setResponderAndExtractTransfer(
504
- topLevelType,
505
- targetInst,
506
- nativeEvent,
507
- nativeEventTarget) :
508
- null;
494
+ var extracted = canTriggerTransfer(topLevelType, targetInst, nativeEvent)
495
+ ? setResponderAndExtractTransfer(
496
+ topLevelType,
497
+ targetInst,
498
+ nativeEvent,
499
+ nativeEventTarget,
500
+ )
501
+ : null;
502
// Responder may or may not have transferred on a new touch start/move.
503
// Regardless, whoever is the responder after any potential transfer, we
504
// direct all touch start/move/ends to them in the form of
@@ -519,40 +512,39 @@ var ResponderEventPlugin = {
512
var isResponderTouchStart = responderInst && isStartish(topLevelType);
513
var isResponderTouchMove = responderInst && isMoveish(topLevelType);
514
var isResponderTouchEnd = responderInst && isEndish(topLevelType);
522
- var incrementalTouch =
523
- isResponderTouchStart ? eventTypes.responderStart :
524
- isResponderTouchMove ? eventTypes.responderMove :
525
- isResponderTouchEnd ? eventTypes.responderEnd :
526
- null;
515
+ var incrementalTouch = isResponderTouchStart
516
+ ? eventTypes.responderStart
517
+ : isResponderTouchMove
518
+ ? eventTypes.responderMove
519
+ : isResponderTouchEnd ? eventTypes.responderEnd : null;
520
521
if (incrementalTouch) {
529
- var gesture =
530
- ResponderSyntheticEvent.getPooled(
531
- incrementalTouch,
532
- responderInst,
533
- nativeEvent,
534
- nativeEventTarget
535
- );
522
+ var gesture = ResponderSyntheticEvent.getPooled(
523
+ incrementalTouch,
524
+ responderInst,
525
+ nativeEvent,
526
+ nativeEventTarget,
527
+ );
528
gesture.touchHistory = ResponderTouchHistoryStore.touchHistory;
529
EventPropagators.accumulateDirectDispatches(gesture);
530
extracted = accumulate(extracted, gesture);
531
}
532
541
- var isResponderTerminate =
542
- responderInst &&
533
+ var isResponderTerminate = responderInst &&
534
topLevelType === 'topTouchCancel';
544
- var isResponderRelease =
545
- responderInst &&
535
+ var isResponderRelease = responderInst &&
536
!isResponderTerminate &&
537
isEndish(topLevelType) &&
538
noResponderTouches(nativeEvent);
549
- var finalTouch =
550
- isResponderTerminate ? eventTypes.responderTerminate :
551
- isResponderRelease ? eventTypes.responderRelease :
552
- null;
539
+ var finalTouch = isResponderTerminate
540
+ ? eventTypes.responderTerminate
541
+ : isResponderRelease ? eventTypes.responderRelease : null;
542
if (finalTouch) {
543
var finalEvent = ResponderSyntheticEvent.getPooled(
555
- finalTouch, responderInst, nativeEvent, nativeEventTarget
544
+ finalTouch,
545
+ responderInst,
546
+ nativeEvent,
547
+ nativeEventTarget,
548
);
549
finalEvent.touchHistory = ResponderTouchHistoryStore.touchHistory;
550
EventPropagators.accumulateDirectDispatches(finalEvent);
@@ -560,12 +552,13 @@ var ResponderEventPlugin = {
552
changeResponder(null);
553
}
554
563
- var numberActiveTouches =
564
- ResponderTouchHistoryStore.touchHistory.numberActiveTouches;
565
- if (ResponderEventPlugin.GlobalInteractionHandler &&
566
- numberActiveTouches !== previousActiveTouches) {
555
+ var numberActiveTouches = ResponderTouchHistoryStore.touchHistory.numberActiveTouches;
556
+ if (
557
+ ResponderEventPlugin.GlobalInteractionHandler &&
558
+ numberActiveTouches !== previousActiveTouches
559
+ ) {
560
ResponderEventPlugin.GlobalInteractionHandler.onChange(
568
- numberActiveTouches
561
+ numberActiveTouches,
562
);
563
}
564
previousActiveTouches = numberActiveTouches;
src/renderers/shared/shared/event/eventPlugins/ResponderSyntheticEvent.js
+13
-2
@@ -30,8 +30,19 @@ var ResponderEventInterface = {
30
* @param {object} nativeEvent Native event.
31
* @extends {SyntheticEvent}
32
*/
33
-function ResponderSyntheticEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
34
- return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
33
+function ResponderSyntheticEvent(
34
+ dispatchConfig,
35
+ dispatchMarker,
36
+ nativeEvent,
37
+ nativeEventTarget,
38
+) {
39
+ return SyntheticEvent.call(
40
+ this,
41
+ dispatchConfig,
42
+ dispatchMarker,
43
+ nativeEvent,
44
+ nativeEventTarget,
45
+ );
46
}
47
48
SyntheticEvent.augmentClass(ResponderSyntheticEvent, ResponderEventInterface);
src/renderers/shared/shared/event/eventPlugins/ResponderTouchHistoryStore.js
+11
-14
@@ -108,9 +108,9 @@ function getTouchIdentifier({identifier}: Touch): number {
108
warning(
109
identifier <= MAX_TOUCH_BANK,
110
'Touch identifier %s is greater than maximum supported %s which causes ' +
111
- 'performance issues backfilling array locations for all of the indices.',
111
+ 'performance issues backfilling array locations for all of the indices.',
112
identifier,
113
- MAX_TOUCH_BANK
113
+ MAX_TOUCH_BANK,
114
);
115
return identifier;
116
}
@@ -139,11 +139,10 @@ function recordTouchMove(touch: Touch): void {
139
touchHistory.mostRecentTimeStamp = timestampForTouch(touch);
140
} else {
141
console.error(
142
- 'Cannot record touch move without a touch start.\n' +
143
- 'Touch Move: %s\n',
142
+ 'Cannot record touch move without a touch start.\n' + 'Touch Move: %s\n',
143
'Touch Bank: %s',
144
printTouch(touch),
146
- printTouchBank()
145
+ printTouchBank(),
146
);
147
}
148
}
@@ -161,11 +160,10 @@ function recordTouchEnd(touch: Touch): void {
160
touchHistory.mostRecentTimeStamp = timestampForTouch(touch);
161
} else {
162
console.error(
164
- 'Cannot record touch end without a touch start.\n' +
165
- 'Touch End: %s\n',
163
+ 'Cannot record touch end without a touch start.\n' + 'Touch End: %s\n',
164
'Touch Bank: %s',
165
printTouch(touch),
168
- printTouchBank()
166
+ printTouchBank(),
167
);
168
}
169
}
@@ -195,8 +193,9 @@ const ResponderTouchHistoryStore = {
193
nativeEvent.changedTouches.forEach(recordTouchStart);
194
touchHistory.numberActiveTouches = nativeEvent.touches.length;
195
if (touchHistory.numberActiveTouches === 1) {
198
- touchHistory.indexOfSingleActiveTouch =
199
- nativeEvent.touches[0].identifier;
196
+ touchHistory.indexOfSingleActiveTouch = nativeEvent.touches[
197
+ 0
198
+ ].identifier;
199
}
200
} else if (isEndish(topLevelType)) {
201
nativeEvent.changedTouches.forEach(recordTouchEnd);
@@ -212,9 +211,8 @@ const ResponderTouchHistoryStore = {
211
if (__DEV__) {
212
const activeRecord = touchBank[touchHistory.indexOfSingleActiveTouch];
213
warning(
215
- activeRecord != null &&
216
- activeRecord.touchActive,
217
- 'Cannot find single active touch.'
214
+ activeRecord != null && activeRecord.touchActive,
215
+ 'Cannot find single active touch.',
216
);
217
}
218
}
@@ -224,5 +222,4 @@ const ResponderTouchHistoryStore = {
222
touchHistory,
223
};
224
227
-
225
module.exports = ResponderTouchHistoryStore;
src/renderers/shared/shared/event/eventPlugins/TouchHistoryMath.js
+57
-31
@@ -21,30 +21,44 @@ var TouchHistoryMath = {
21
* touches vs. previous centroid of now actively moving touches.
22
* @return {number} value of centroid in specified dimension.
23
*/
24
- centroidDimension: function(touchHistory, touchesChangedAfter, isXAxis, ofCurrent) {
24
+ centroidDimension: function(
25
+ touchHistory,
26
+ touchesChangedAfter,
27
+ isXAxis,
28
+ ofCurrent,
29
+ ) {
30
var touchBank = touchHistory.touchBank;
31
var total = 0;
32
var count = 0;
33
29
- var oneTouchData = touchHistory.numberActiveTouches === 1 ?
30
- touchHistory.touchBank[touchHistory.indexOfSingleActiveTouch] : null;
34
+ var oneTouchData = touchHistory.numberActiveTouches === 1
35
+ ? touchHistory.touchBank[touchHistory.indexOfSingleActiveTouch]
36
+ : null;
37
38
if (oneTouchData !== null) {
33
- if (oneTouchData.touchActive && oneTouchData.currentTimeStamp > touchesChangedAfter) {
34
- total += ofCurrent && isXAxis ? oneTouchData.currentPageX :
35
- ofCurrent && !isXAxis ? oneTouchData.currentPageY :
36
- !ofCurrent && isXAxis ? oneTouchData.previousPageX :
37
- oneTouchData.previousPageY;
39
+ if (
40
+ oneTouchData.touchActive &&
41
+ oneTouchData.currentTimeStamp > touchesChangedAfter
42
+ ) {
43
+ total += ofCurrent && isXAxis
44
+ ? oneTouchData.currentPageX
45
+ : ofCurrent && !isXAxis
46
+ ? oneTouchData.currentPageY
47
+ : !ofCurrent && isXAxis
48
+ ? oneTouchData.previousPageX
49
+ : oneTouchData.previousPageY;
50
count = 1;
51
}
52
} else {
53
for (var i = 0; i < touchBank.length; i++) {
54
var touchTrack = touchBank[i];
43
- if (touchTrack !== null &&
44
- touchTrack !== undefined &&
45
- touchTrack.touchActive &&
46
- touchTrack.currentTimeStamp >= touchesChangedAfter) {
47
- var toAdd; // Yuck, program temporarily in invalid state.
55
+ if (
56
+ touchTrack !== null &&
57
+ touchTrack !== undefined &&
58
+ touchTrack.touchActive &&
59
+ touchTrack.currentTimeStamp >= touchesChangedAfter
60
+ ) {
61
+ var toAdd; // Yuck, program temporarily in invalid state.
62
if (ofCurrent && isXAxis) {
63
toAdd = touchTrack.currentPageX;
64
} else if (ofCurrent && !isXAxis) {
@@ -62,57 +76,69 @@ var TouchHistoryMath = {
76
return count > 0 ? total / count : TouchHistoryMath.noCentroid;
77
},
78
65
- currentCentroidXOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) {
79
+ currentCentroidXOfTouchesChangedAfter: function(
80
+ touchHistory,
81
+ touchesChangedAfter,
82
+ ) {
83
return TouchHistoryMath.centroidDimension(
84
touchHistory,
85
touchesChangedAfter,
69
- true, // isXAxis
70
- true // ofCurrent
86
+ true, // isXAxis
87
+ true, // ofCurrent
88
);
89
},
90
74
- currentCentroidYOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) {
91
+ currentCentroidYOfTouchesChangedAfter: function(
92
+ touchHistory,
93
+ touchesChangedAfter,
94
+ ) {
95
return TouchHistoryMath.centroidDimension(
96
touchHistory,
97
touchesChangedAfter,
78
- false, // isXAxis
79
- true // ofCurrent
98
+ false, // isXAxis
99
+ true, // ofCurrent
100
);
101
},
102
83
- previousCentroidXOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) {
103
+ previousCentroidXOfTouchesChangedAfter: function(
104
+ touchHistory,
105
+ touchesChangedAfter,
106
+ ) {
107
return TouchHistoryMath.centroidDimension(
108
touchHistory,
109
touchesChangedAfter,
87
- true, // isXAxis
88
- false // ofCurrent
110
+ true, // isXAxis
111
+ false, // ofCurrent
112
);
113
},
114
92
- previousCentroidYOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) {
115
+ previousCentroidYOfTouchesChangedAfter: function(
116
+ touchHistory,
117
+ touchesChangedAfter,
118
+ ) {
119
return TouchHistoryMath.centroidDimension(
120
touchHistory,
121
touchesChangedAfter,
96
- false, // isXAxis
97
- false // ofCurrent
122
+ false, // isXAxis
123
+ false, // ofCurrent
124
);
125
},
126
127
currentCentroidX: function(touchHistory) {
128
return TouchHistoryMath.centroidDimension(
129
touchHistory,
104
- 0, // touchesChangedAfter
105
- true, // isXAxis
106
- true // ofCurrent
130
+ 0, // touchesChangedAfter
131
+ true, // isXAxis
132
+ true, // ofCurrent
133
);
134
},
135
136
currentCentroidY: function(touchHistory) {
137
return TouchHistoryMath.centroidDimension(
138
touchHistory,
113
- 0, // touchesChangedAfter
114
- false, // isXAxis
115
- true // ofCurrent
139
+ 0, // touchesChangedAfter
140
+ false, // isXAxis
141
+ true, // ofCurrent
142
);
143
},
144
src/renderers/shared/shared/event/eventPlugins/__tests__/ResponderEventPlugin-test.js
+553
-208
@@ -62,22 +62,25 @@ var _touchConfig = function(
62
targetNodeHandle,
63
allTouchHandles,
64
changedIndices,
65
- eventTarget
65
+ eventTarget,
66
) {
67
var allTouchObjects = allTouchHandles.map(touch);
68
var changedTouchObjects = subsequence(allTouchObjects, changedIndices);
69
- var activeTouchObjects =
70
- topType === 'topTouchStart' ? allTouchObjects :
71
- topType === 'topTouchMove' ? allTouchObjects :
72
- topType === 'topTouchEnd' ? antiSubsequence(allTouchObjects, changedIndices) :
73
- topType === 'topTouchCancel' ? antiSubsequence(allTouchObjects, changedIndices) :
74
- null;
69
+ var activeTouchObjects = topType === 'topTouchStart'
70
+ ? allTouchObjects
71
+ : topType === 'topTouchMove'
72
+ ? allTouchObjects
73
+ : topType === 'topTouchEnd'
74
+ ? antiSubsequence(allTouchObjects, changedIndices)
75
+ : topType === 'topTouchCancel'
76
+ ? antiSubsequence(allTouchObjects, changedIndices)
77
+ : null;
78
79
return {
80
nativeEvent: touchEvent(
81
targetNodeHandle,
82
activeTouchObjects,
80
- changedTouchObjects
83
+ changedTouchObjects,
84
),
85
topLevelType: topType,
86
targetInst: getInstanceFromNode(targetNodeHandle),
@@ -108,7 +111,7 @@ var startConfig = function(nodeHandle, allTouchHandles, changedIndices) {
111
nodeHandle,
112
allTouchHandles,
113
changedIndices,
111
- nodeHandle
114
+ nodeHandle,
115
);
116
};
117
@@ -121,7 +124,7 @@ var moveConfig = function(nodeHandle, allTouchHandles, changedIndices) {
124
nodeHandle,
125
allTouchHandles,
126
changedIndices,
124
- nodeHandle
127
+ nodeHandle,
128
);
129
};
130
@@ -134,7 +137,7 @@ var endConfig = function(nodeHandle, allTouchHandles, changedIndices) {
137
nodeHandle,
138
allTouchHandles,
139
changedIndices,
137
- nodeHandle
140
+ nodeHandle,
141
);
142
};
143
@@ -169,31 +172,40 @@ var NA = -1;
172
var oneEventLoopTestConfig = function(readableIDToID) {
173
var ret = {
174
// Negotiation
172
- scrollShouldSetResponder: {bubbled: {}, captured: {}},
173
- startShouldSetResponder: {bubbled: {}, captured: {}},
174
- moveShouldSetResponder: {bubbled: {}, captured: {}},
175
+ scrollShouldSetResponder: {bubbled: {}, captured: {}},
176
+ startShouldSetResponder: {bubbled: {}, captured: {}},
177
+ moveShouldSetResponder: {bubbled: {}, captured: {}},
178
responderTerminationRequest: {},
179
180
// Non-negotiation
178
- responderReject: {}, // These do not bubble capture.
179
- responderGrant: {},
180
- responderStart: {},
181
- responderMove: {},
181
+ responderReject: {}, // These do not bubble capture.
182
+ responderGrant: {},
183
+ responderStart: {},
184
+ responderMove: {},
185
responderTerminate: {},
183
- responderEnd: {},
184
- responderRelease: {},
186
+ responderEnd: {},
187
+ responderRelease: {},
188
};
189
for (var eventName in ret) {
190
for (var readableNodeName in readableIDToID) {
191
if (ret[eventName].bubbled) {
192
// Two phase
190
- ret[eventName].bubbled[readableNodeName] =
191
- {order: NA, assertEvent: null, returnVal: undefined};
192
- ret[eventName].captured[readableNodeName] =
193
- {order: NA, assertEvent: null, returnVal: undefined};
193
+ ret[eventName].bubbled[readableNodeName] = {
194
+ order: NA,
195
+ assertEvent: null,
196
+ returnVal: undefined,
197
+ };
198
+ ret[eventName].captured[readableNodeName] = {
199
+ order: NA,
200
+ assertEvent: null,
201
+ returnVal: undefined,
202
+ };
203
} else {
195
- ret[eventName][readableNodeName] =
196
- {order: NA, assertEvent: null, returnVal: undefined};
204
+ ret[eventName][readableNodeName] = {
205
+ order: NA,
206
+ assertEvent: null,
207
+ returnVal: undefined,
208
+ };
209
}
210
}
211
}
@@ -209,9 +221,13 @@ var registerTestHandlers = function(eventTestConfig, readableIDToID) {
221
var neverFire = function(readableID, registrationName) {
222
runs.dispatchCount++;
223
expect('').toBe(
212
- 'Event type: ' + registrationName +
213
- '\nShould never occur on:' + readableID +
214
- '\nFor event test config:\n' + JSON.stringify(eventTestConfig) + '\n'
224
+ 'Event type: ' +
225
+ registrationName +
226
+ '\nShould never occur on:' +
227
+ readableID +
228
+ '\nFor event test config:\n' +
229
+ JSON.stringify(eventTestConfig) +
230
+ '\n',
231
);
232
};
233
@@ -219,20 +235,19 @@ var registerTestHandlers = function(eventTestConfig, readableIDToID) {
235
for (var readableID in eventTypeTestConfig) {
236
var nodeConfig = eventTypeTestConfig[readableID];
237
var id = readableIDToID[readableID];
222
- var handler = nodeConfig.order === NA ? neverFire.bind(null, readableID, registrationName) :
223
- // We partially apply readableID and nodeConfig, as they change in the
224
- // parent closure across iterations.
225
- function(rID, config, e) {
226
- expect(
227
- rID + '->' + registrationName + ' index:' + runs.dispatchCount++
228
- ).toBe(
229
- rID + '->' + registrationName + ' index:' + config.order
230
- );
231
- if (config.assertEvent) {
232
- config.assertEvent(e);
233
- }
234
- return config.returnVal;
235
- }.bind(null, readableID, nodeConfig);
238
+ var handler = nodeConfig.order === NA
239
+ ? neverFire.bind(null, readableID, registrationName)
240
+ : // We partially apply readableID and nodeConfig, as they change in the
241
+ // parent closure across iterations.
242
+ function(rID, config, e) {
243
+ expect(
244
+ rID + '->' + registrationName + ' index:' + runs.dispatchCount++,
245
+ ).toBe(rID + '->' + registrationName + ' index:' + config.order);
246
+ if (config.assertEvent) {
247
+ config.assertEvent(e);
248
+ }
249
+ return config.returnVal;
250
+ }.bind(null, readableID, nodeConfig);
251
putListener(getInstanceFromNode(id), registrationName, handler);
252
}
253
};
@@ -241,17 +256,21 @@ var registerTestHandlers = function(eventTestConfig, readableIDToID) {
256
var hasTwoPhase = !!oneEventTypeTestConfig.bubbled;
257
if (hasTwoPhase) {
258
registerOneEventType(
244
- ResponderEventPlugin.eventTypes[eventName].phasedRegistrationNames.bubbled,
245
- oneEventTypeTestConfig.bubbled
259
+ ResponderEventPlugin.eventTypes[
260
+ eventName
261
+ ].phasedRegistrationNames.bubbled,
262
+ oneEventTypeTestConfig.bubbled,
263
);
264
registerOneEventType(
248
- ResponderEventPlugin.eventTypes[eventName].phasedRegistrationNames.captured,
249
- oneEventTypeTestConfig.captured
265
+ ResponderEventPlugin.eventTypes[
266
+ eventName
267
+ ].phasedRegistrationNames.captured,
268
+ oneEventTypeTestConfig.captured,
269
);
270
} else {
271
registerOneEventType(
272
ResponderEventPlugin.eventTypes[eventName].registrationName,
254
- oneEventTypeTestConfig
273
+ oneEventTypeTestConfig,
274
);
275
}
276
}
@@ -284,7 +303,7 @@ var run = function(config, hierarchyConfig, nativeEventConfig) {
303
nativeEventConfig.topLevelType,
304
nativeEventConfig.targetInst,
305
nativeEventConfig.nativeEvent,
287
- nativeEventConfig.target
306
+ nativeEventConfig.target,
307
);
308
309
// At this point the negotiation events have been dispatched as part of the
@@ -294,41 +313,39 @@ var run = function(config, hierarchyConfig, nativeEventConfig) {
313
EventPluginHub.processEventQueue(true);
314
315
// Ensure that every event that declared an `order`, was actually dispatched.
297
- expect(
298
- 'number of events dispatched:' + runData.dispatchCount
299
- ).toBe(
300
- 'number of events dispatched:' + (max + 1)
316
+ expect('number of events dispatched:' + runData.dispatchCount).toBe(
317
+ 'number of events dispatched:' + (max + 1),
318
); // +1 for extra ++
319
};
320
304
-var GRANDPARENT_HOST_NODE = { };
305
-var PARENT_HOST_NODE = { };
306
-var CHILD_HOST_NODE = { };
307
-var CHILD_HOST_NODE2 = { };
321
+var GRANDPARENT_HOST_NODE = {};
322
+var PARENT_HOST_NODE = {};
323
+var CHILD_HOST_NODE = {};
324
+var CHILD_HOST_NODE2 = {};
325
326
var GRANDPARENT_INST = {
327
_hostParent: null,
328
_rootNodeID: '1',
329
_hostNode: GRANDPARENT_HOST_NODE,
313
- _currentElement: { props: {} },
330
+ _currentElement: {props: {}},
331
};
332
var PARENT_INST = {
333
_hostParent: GRANDPARENT_INST,
334
_rootNodeID: '2',
335
_hostNode: PARENT_HOST_NODE,
319
- _currentElement: { props: {} },
336
+ _currentElement: {props: {}},
337
};
338
var CHILD_INST = {
339
_hostParent: PARENT_INST,
340
_rootNodeID: '3',
341
_hostNode: CHILD_HOST_NODE,
325
- _currentElement: { props: {} },
342
+ _currentElement: {props: {}},
343
};
344
var CHILD_INST2 = {
345
_hostParent: PARENT_INST,
346
_rootNodeID: '4',
347
_hostNode: CHILD_HOST_NODE2,
331
- _currentElement: { props: {} },
348
+ _currentElement: {props: {}},
349
};
350
351
GRANDPARENT_HOST_NODE._reactInstance = GRANDPARENT_INST;
@@ -365,7 +382,6 @@ function deleteAllListeners(node) {
382
}
383
384
describe('ResponderEventPlugin', () => {
368
-
385
beforeEach(() => {
386
jest.resetModules();
387
@@ -386,12 +402,27 @@ describe('ResponderEventPlugin', () => {
402
403
it('should do nothing when no one wants to respond', () => {
404
var config = oneEventLoopTestConfig(three);
389
- config.startShouldSetResponder.captured.grandParent = {order: 0, returnVal: false};
390
- config.startShouldSetResponder.captured.parent = {order: 1, returnVal: false};
391
- config.startShouldSetResponder.captured.child = {order: 2, returnVal: false};
405
+ config.startShouldSetResponder.captured.grandParent = {
406
+ order: 0,
407
+ returnVal: false,
408
+ };
409
+ config.startShouldSetResponder.captured.parent = {
410
+ order: 1,
411
+ returnVal: false,
412
+ };
413
+ config.startShouldSetResponder.captured.child = {
414
+ order: 2,
415
+ returnVal: false,
416
+ };
417
config.startShouldSetResponder.bubbled.child = {order: 3, returnVal: false};
393
- config.startShouldSetResponder.bubbled.parent = {order: 4, returnVal: false};
394
- config.startShouldSetResponder.bubbled.grandParent = {order: 5, returnVal: false};
418
+ config.startShouldSetResponder.bubbled.parent = {
419
+ order: 4,
420
+ returnVal: false,
421
+ };
422
+ config.startShouldSetResponder.bubbled.grandParent = {
423
+ order: 5,
424
+ returnVal: false,
425
+ };
426
run(config, three, startConfig(three.child, [three.child], [0]));
427
expect(ResponderEventPlugin._getResponder()).toBe(null);
428
@@ -401,20 +432,23 @@ describe('ResponderEventPlugin', () => {
432
expect(ResponderEventPlugin._getResponder()).toBe(null);
433
});
434
404
-
435
/**
436
* Simple Start Granting
437
* --------------------
438
*/
439
410
-
440
it('should grant responder grandParent while capturing', () => {
441
var config = oneEventLoopTestConfig(three);
413
- config.startShouldSetResponder.captured.grandParent = {order: 0, returnVal: true};
442
+ config.startShouldSetResponder.captured.grandParent = {
443
+ order: 0,
444
+ returnVal: true,
445
+ };
446
config.responderGrant.grandParent = {order: 1};
447
config.responderStart.grandParent = {order: 2};
448
run(config, three, startConfig(three.child, [three.child], [0]));
417
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(three.grandParent));
449
+ expect(ResponderEventPlugin._getResponder()).toBe(
450
+ getInstanceFromNode(three.grandParent),
451
+ );
452
453
config = oneEventLoopTestConfig(three);
454
config.responderEnd.grandParent = {order: 0};
@@ -425,12 +459,20 @@ describe('ResponderEventPlugin', () => {
459
460
it('should grant responder parent while capturing', () => {
461
var config = oneEventLoopTestConfig(three);
428
- config.startShouldSetResponder.captured.grandParent = {order: 0, returnVal: false};
429
- config.startShouldSetResponder.captured.parent = {order: 1, returnVal: true};
462
+ config.startShouldSetResponder.captured.grandParent = {
463
+ order: 0,
464
+ returnVal: false,
465
+ };
466
+ config.startShouldSetResponder.captured.parent = {
467
+ order: 1,
468
+ returnVal: true,
469
+ };
470
config.responderGrant.parent = {order: 2};
471
config.responderStart.parent = {order: 3};
472
run(config, three, startConfig(three.child, [three.child], [0]));
433
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(three.parent));
473
+ expect(ResponderEventPlugin._getResponder()).toBe(
474
+ getInstanceFromNode(three.parent),
475
+ );
476
477
config = oneEventLoopTestConfig(three);
478
config.responderEnd.parent = {order: 0};
@@ -441,13 +483,21 @@ describe('ResponderEventPlugin', () => {
483
484
it('should grant responder child while capturing', () => {
485
var config = oneEventLoopTestConfig(three);
444
- config.startShouldSetResponder.captured.grandParent = {order: 0, returnVal: false};
445
- config.startShouldSetResponder.captured.parent = {order: 1, returnVal: false};
486
+ config.startShouldSetResponder.captured.grandParent = {
487
+ order: 0,
488
+ returnVal: false,
489
+ };
490
+ config.startShouldSetResponder.captured.parent = {
491
+ order: 1,
492
+ returnVal: false,
493
+ };
494
config.startShouldSetResponder.captured.child = {order: 2, returnVal: true};
495
config.responderGrant.child = {order: 3};
496
config.responderStart.child = {order: 4};
497
run(config, three, startConfig(three.child, [three.child], [0]));
450
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(three.child));
498
+ expect(ResponderEventPlugin._getResponder()).toBe(
499
+ getInstanceFromNode(three.child),
500
+ );
501
502
config = oneEventLoopTestConfig(three);
503
config.responderEnd.child = {order: 0};
@@ -458,14 +508,25 @@ describe('ResponderEventPlugin', () => {
508
509
it('should grant responder child while bubbling', () => {
510
var config = oneEventLoopTestConfig(three);
461
- config.startShouldSetResponder.captured.grandParent = {order: 0, returnVal: false};
462
- config.startShouldSetResponder.captured.parent = {order: 1, returnVal: false};
463
- config.startShouldSetResponder.captured.child = {order: 2, returnVal: false};
511
+ config.startShouldSetResponder.captured.grandParent = {
512
+ order: 0,
513
+ returnVal: false,
514
+ };
515
+ config.startShouldSetResponder.captured.parent = {
516
+ order: 1,
517
+ returnVal: false,
518
+ };
519
+ config.startShouldSetResponder.captured.child = {
520
+ order: 2,
521
+ returnVal: false,
522
+ };
523
config.startShouldSetResponder.bubbled.child = {order: 3, returnVal: true};
524
config.responderGrant.child = {order: 4};
525
config.responderStart.child = {order: 5};
526
run(config, three, startConfig(three.child, [three.child], [0]));
468
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(three.child));
527
+ expect(ResponderEventPlugin._getResponder()).toBe(
528
+ getInstanceFromNode(three.child),
529
+ );
530
531
config = oneEventLoopTestConfig(three);
532
config.responderEnd.child = {order: 0};
@@ -476,15 +537,26 @@ describe('ResponderEventPlugin', () => {
537
538
it('should grant responder parent while bubbling', () => {
539
var config = oneEventLoopTestConfig(three);
479
- config.startShouldSetResponder.captured.grandParent = {order: 0, returnVal: false};
480
- config.startShouldSetResponder.captured.parent = {order: 1, returnVal: false};
481
- config.startShouldSetResponder.captured.child = {order: 2, returnVal: false};
540
+ config.startShouldSetResponder.captured.grandParent = {
541
+ order: 0,
542
+ returnVal: false,
543
+ };
544
+ config.startShouldSetResponder.captured.parent = {
545
+ order: 1,
546
+ returnVal: false,
547
+ };
548
+ config.startShouldSetResponder.captured.child = {
549
+ order: 2,
550
+ returnVal: false,
551
+ };
552
config.startShouldSetResponder.bubbled.child = {order: 3, returnVal: false};
553
config.startShouldSetResponder.bubbled.parent = {order: 4, returnVal: true};
554
config.responderGrant.parent = {order: 5};
555
config.responderStart.parent = {order: 6};
556
run(config, three, startConfig(three.child, [three.child], [0]));
487
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(three.parent));
557
+ expect(ResponderEventPlugin._getResponder()).toBe(
558
+ getInstanceFromNode(three.parent),
559
+ );
560
561
config = oneEventLoopTestConfig(three);
562
config.responderEnd.parent = {order: 0};
@@ -495,16 +567,33 @@ describe('ResponderEventPlugin', () => {
567
568
it('should grant responder grandParent while bubbling', () => {
569
var config = oneEventLoopTestConfig(three);
498
- config.startShouldSetResponder.captured.grandParent = {order: 0, returnVal: false};
499
- config.startShouldSetResponder.captured.parent = {order: 1, returnVal: false};
500
- config.startShouldSetResponder.captured.child = {order: 2, returnVal: false};
570
+ config.startShouldSetResponder.captured.grandParent = {
571
+ order: 0,
572
+ returnVal: false,
573
+ };
574
+ config.startShouldSetResponder.captured.parent = {
575
+ order: 1,
576
+ returnVal: false,
577
+ };
578
+ config.startShouldSetResponder.captured.child = {
579
+ order: 2,
580
+ returnVal: false,
581
+ };
582
config.startShouldSetResponder.bubbled.child = {order: 3, returnVal: false};
502
- config.startShouldSetResponder.bubbled.parent = {order: 4, returnVal: false};
503
- config.startShouldSetResponder.bubbled.grandParent = {order: 5, returnVal: true};
583
+ config.startShouldSetResponder.bubbled.parent = {
584
+ order: 4,
585
+ returnVal: false,
586
+ };
587
+ config.startShouldSetResponder.bubbled.grandParent = {
588
+ order: 5,
589
+ returnVal: true,
590
+ };
591
config.responderGrant.grandParent = {order: 6};
592
config.responderStart.grandParent = {order: 7};
593
run(config, three, startConfig(three.child, [three.child], [0]));
507
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(three.grandParent));
594
+ expect(ResponderEventPlugin._getResponder()).toBe(
595
+ getInstanceFromNode(three.grandParent),
596
+ );
597
598
config = oneEventLoopTestConfig(three);
599
config.responderEnd.grandParent = {order: 0};
@@ -513,8 +602,6 @@ describe('ResponderEventPlugin', () => {
602
expect(ResponderEventPlugin._getResponder()).toBe(null);
603
});
604
516
-
517
-
605
/**
606
* Simple Move Granting
607
* --------------------
@@ -532,11 +619,16 @@ describe('ResponderEventPlugin', () => {
619
run(config, three, startConfig(three.child, [three.child], [0]));
620
621
config = oneEventLoopTestConfig(three);
535
- config.moveShouldSetResponder.captured.grandParent = {order: 0, returnVal: true};
622
+ config.moveShouldSetResponder.captured.grandParent = {
623
+ order: 0,
624
+ returnVal: true,
625
+ };
626
config.responderGrant.grandParent = {order: 1};
627
config.responderMove.grandParent = {order: 2};
628
run(config, three, moveConfig(three.child, [three.child], [0]));
539
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(three.grandParent));
629
+ expect(ResponderEventPlugin._getResponder()).toBe(
630
+ getInstanceFromNode(three.grandParent),
631
+ );
632
633
config = oneEventLoopTestConfig(three);
634
config.responderEnd.grandParent = {order: 0};
@@ -557,12 +649,17 @@ describe('ResponderEventPlugin', () => {
649
run(config, three, startConfig(three.child, [three.child], [0]));
650
651
config = oneEventLoopTestConfig(three);
560
- config.moveShouldSetResponder.captured.grandParent = {order: 0, returnVal: false};
652
+ config.moveShouldSetResponder.captured.grandParent = {
653
+ order: 0,
654
+ returnVal: false,
655
+ };
656
config.moveShouldSetResponder.captured.parent = {order: 1, returnVal: true};
657
config.responderGrant.parent = {order: 2};
658
config.responderMove.parent = {order: 3};
659
run(config, three, moveConfig(three.child, [three.child], [0]));
565
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(three.parent));
660
+ expect(ResponderEventPlugin._getResponder()).toBe(
661
+ getInstanceFromNode(three.parent),
662
+ );
663
664
config = oneEventLoopTestConfig(three);
665
config.responderEnd.parent = {order: 0};
@@ -583,13 +680,21 @@ describe('ResponderEventPlugin', () => {
680
run(config, three, startConfig(three.child, [three.child], [0]));
681
682
config = oneEventLoopTestConfig(three);
586
- config.moveShouldSetResponder.captured.grandParent = {order: 0, returnVal: false};
587
- config.moveShouldSetResponder.captured.parent = {order: 1, returnVal: false};
683
+ config.moveShouldSetResponder.captured.grandParent = {
684
+ order: 0,
685
+ returnVal: false,
686
+ };
687
+ config.moveShouldSetResponder.captured.parent = {
688
+ order: 1,
689
+ returnVal: false,
690
+ };
691
config.moveShouldSetResponder.captured.child = {order: 2, returnVal: true};
692
config.responderGrant.child = {order: 3};
693
config.responderMove.child = {order: 4};
694
run(config, three, moveConfig(three.child, [three.child], [0]));
592
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(three.child));
695
+ expect(ResponderEventPlugin._getResponder()).toBe(
696
+ getInstanceFromNode(three.child),
697
+ );
698
699
config = oneEventLoopTestConfig(three);
700
config.responderEnd.child = {order: 0};
@@ -610,14 +715,22 @@ describe('ResponderEventPlugin', () => {
715
run(config, three, startConfig(three.child, [three.child], [0]));
716
717
config = oneEventLoopTestConfig(three);
613
- config.moveShouldSetResponder.captured.grandParent = {order: 0, returnVal: false};
614
- config.moveShouldSetResponder.captured.parent = {order: 1, returnVal: false};
718
+ config.moveShouldSetResponder.captured.grandParent = {
719
+ order: 0,
720
+ returnVal: false,
721
+ };
722
+ config.moveShouldSetResponder.captured.parent = {
723
+ order: 1,
724
+ returnVal: false,
725
+ };
726
config.moveShouldSetResponder.captured.child = {order: 2, returnVal: false};
727
config.moveShouldSetResponder.bubbled.child = {order: 3, returnVal: true};
728
config.responderGrant.child = {order: 4};
729
config.responderMove.child = {order: 5};
730
run(config, three, moveConfig(three.child, [three.child], [0]));
620
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(three.child));
731
+ expect(ResponderEventPlugin._getResponder()).toBe(
732
+ getInstanceFromNode(three.child),
733
+ );
734
735
config = oneEventLoopTestConfig(three);
736
config.responderEnd.child = {order: 0};
@@ -638,15 +751,23 @@ describe('ResponderEventPlugin', () => {
751
run(config, three, startConfig(three.child, [three.child], [0]));
752
753
config = oneEventLoopTestConfig(three);
641
- config.moveShouldSetResponder.captured.grandParent = {order: 0, returnVal: false};
642
- config.moveShouldSetResponder.captured.parent = {order: 1, returnVal: false};
754
+ config.moveShouldSetResponder.captured.grandParent = {
755
+ order: 0,
756
+ returnVal: false,
757
+ };
758
+ config.moveShouldSetResponder.captured.parent = {
759
+ order: 1,
760
+ returnVal: false,
761
+ };
762
config.moveShouldSetResponder.captured.child = {order: 2, returnVal: false};
763
config.moveShouldSetResponder.bubbled.child = {order: 3, returnVal: false};
764
config.moveShouldSetResponder.bubbled.parent = {order: 4, returnVal: true};
765
config.responderGrant.parent = {order: 5};
766
config.responderMove.parent = {order: 6};
767
run(config, three, moveConfig(three.child, [three.child], [0]));
649
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(three.parent));
768
+ expect(ResponderEventPlugin._getResponder()).toBe(
769
+ getInstanceFromNode(three.parent),
770
+ );
771
772
config = oneEventLoopTestConfig(three);
773
config.responderEnd.parent = {order: 0};
@@ -667,16 +788,27 @@ describe('ResponderEventPlugin', () => {
788
run(config, three, startConfig(three.child, [three.child], [0]));
789
790
config = oneEventLoopTestConfig(three);
670
- config.moveShouldSetResponder.captured.grandParent = {order: 0, returnVal: false};
671
- config.moveShouldSetResponder.captured.parent = {order: 1, returnVal: false};
791
+ config.moveShouldSetResponder.captured.grandParent = {
792
+ order: 0,
793
+ returnVal: false,
794
+ };
795
+ config.moveShouldSetResponder.captured.parent = {
796
+ order: 1,
797
+ returnVal: false,
798
+ };
799
config.moveShouldSetResponder.captured.child = {order: 2, returnVal: false};
800
config.moveShouldSetResponder.bubbled.child = {order: 3, returnVal: false};
801
config.moveShouldSetResponder.bubbled.parent = {order: 4, returnVal: false};
675
- config.moveShouldSetResponder.bubbled.grandParent = {order: 5, returnVal: true};
802
+ config.moveShouldSetResponder.bubbled.grandParent = {
803
+ order: 5,
804
+ returnVal: true,
805
+ };
806
config.responderGrant.grandParent = {order: 6};
807
config.responderMove.grandParent = {order: 7};
808
run(config, three, moveConfig(three.child, [three.child], [0]));
679
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(three.grandParent));
809
+ expect(ResponderEventPlugin._getResponder()).toBe(
810
+ getInstanceFromNode(three.grandParent),
811
+ );
812
813
config = oneEventLoopTestConfig(three);
814
config.responderEnd.grandParent = {order: 0};
@@ -685,7 +817,6 @@ describe('ResponderEventPlugin', () => {
817
expect(ResponderEventPlugin._getResponder()).toBe(null);
818
});
819
688
-
820
/**
821
* Common ancestor tests
822
* ---------------------
@@ -693,22 +824,38 @@ describe('ResponderEventPlugin', () => {
824
825
it('should bubble negotiation to first common ancestor of responder', () => {
826
var config = oneEventLoopTestConfig(three);
696
- config.startShouldSetResponder.captured.grandParent = {order: 0, returnVal: false};
697
- config.startShouldSetResponder.captured.parent = {order: 1, returnVal: true};
827
+ config.startShouldSetResponder.captured.grandParent = {
828
+ order: 0,
829
+ returnVal: false,
830
+ };
831
+ config.startShouldSetResponder.captured.parent = {
832
+ order: 1,
833
+ returnVal: true,
834
+ };
835
config.responderGrant.parent = {order: 2};
836
config.responderStart.parent = {order: 3};
837
run(config, three, startConfig(three.child, [three.child], [0]));
701
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(three.parent));
838
+ expect(ResponderEventPlugin._getResponder()).toBe(
839
+ getInstanceFromNode(three.parent),
840
+ );
841
842
// While `parent` is still responder, we create new handlers that verify
843
// the ordering of propagation, restarting the count at `0`.
844
config = oneEventLoopTestConfig(three);
706
- config.startShouldSetResponder.captured.grandParent = {order: 0, returnVal: false};
707
-
708
- config.startShouldSetResponder.bubbled.grandParent = {order: 1, returnVal: false};
845
+ config.startShouldSetResponder.captured.grandParent = {
846
+ order: 0,
847
+ returnVal: false,
848
+ };
849
+
850
+ config.startShouldSetResponder.bubbled.grandParent = {
851
+ order: 1,
852
+ returnVal: false,
853
+ };
854
config.responderStart.parent = {order: 2};
855
run(config, three, startConfig(three.child, [three.child], [0]));
711
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(three.parent));
856
+ expect(ResponderEventPlugin._getResponder()).toBe(
857
+ getInstanceFromNode(three.parent),
858
+ );
859
860
config = oneEventLoopTestConfig(three);
861
config.responderEnd.parent = {order: 0};
@@ -719,29 +866,48 @@ describe('ResponderEventPlugin', () => {
866
867
it('should bubble negotiation to first common ancestor of responder then transfer', () => {
868
var config = oneEventLoopTestConfig(three);
722
- config.startShouldSetResponder.captured.grandParent = {order: 0, returnVal: false};
723
- config.startShouldSetResponder.captured.parent = {order: 1, returnVal: true};
869
+ config.startShouldSetResponder.captured.grandParent = {
870
+ order: 0,
871
+ returnVal: false,
872
+ };
873
+ config.startShouldSetResponder.captured.parent = {
874
+ order: 1,
875
+ returnVal: true,
876
+ };
877
config.responderGrant.parent = {order: 2};
878
config.responderStart.parent = {order: 3};
879
run(config, three, startConfig(three.child, [three.child], [0]));
727
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(three.parent));
880
+ expect(ResponderEventPlugin._getResponder()).toBe(
881
+ getInstanceFromNode(three.parent),
882
+ );
883
884
config = oneEventLoopTestConfig(three);
885
886
// Parent is responder, and responder is transferred by a second touch start
732
- config.startShouldSetResponder.captured.grandParent = {order: 0, returnVal: true};
887
+ config.startShouldSetResponder.captured.grandParent = {
888
+ order: 0,
889
+ returnVal: true,
890
+ };
891
config.responderGrant.grandParent = {order: 1};
892
config.responderTerminationRequest.parent = {order: 2, returnVal: true};
893
config.responderTerminate.parent = {order: 3};
894
config.responderStart.grandParent = {order: 4};
737
- run(config, three, startConfig(three.child, [three.child, three.child], [1]));
738
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(three.grandParent));
895
+ run(
896
+ config,
897
+ three,
898
+ startConfig(three.child, [three.child, three.child], [1]),
899
+ );
900
+ expect(ResponderEventPlugin._getResponder()).toBe(
901
+ getInstanceFromNode(three.grandParent),
902
+ );
903
904
config = oneEventLoopTestConfig(three);
905
config.responderEnd.grandParent = {order: 0};
742
- // one remains\ /one ended \
906
+ // one remains\ /one ended \
907
run(config, three, endConfig(three.child, [three.child, three.child], [1]));
744
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(three.grandParent));
908
+ expect(ResponderEventPlugin._getResponder()).toBe(
909
+ getInstanceFromNode(three.grandParent),
910
+ );
911
912
config = oneEventLoopTestConfig(three);
913
config.responderEnd.grandParent = {order: 0};
@@ -757,10 +923,22 @@ describe('ResponderEventPlugin', () => {
923
it('should negotiate with deepest target on second touch if nothing is responder', () => {
924
// Initially nothing wants to become the responder
925
var config = oneEventLoopTestConfig(three);
760
- config.startShouldSetResponder.captured.grandParent = {order: 0, returnVal: false};
761
- config.startShouldSetResponder.captured.parent = {order: 1, returnVal: false};
762
- config.startShouldSetResponder.bubbled.parent = {order: 2, returnVal: false};
763
- config.startShouldSetResponder.bubbled.grandParent = {order: 3, returnVal: false};
926
+ config.startShouldSetResponder.captured.grandParent = {
927
+ order: 0,
928
+ returnVal: false,
929
+ };
930
+ config.startShouldSetResponder.captured.parent = {
931
+ order: 1,
932
+ returnVal: false,
933
+ };
934
+ config.startShouldSetResponder.bubbled.parent = {
935
+ order: 2,
936
+ returnVal: false,
937
+ };
938
+ config.startShouldSetResponder.bubbled.grandParent = {
939
+ order: 3,
940
+ returnVal: false,
941
+ };
942
943
run(config, three, startConfig(three.parent, [three.parent], [0]));
944
expect(ResponderEventPlugin._getResponder()).toBe(null);
@@ -771,16 +949,30 @@ describe('ResponderEventPlugin', () => {
949
// as the target is because we don't find first common ancestor (with
950
// current responder) because there is no current responder.
951
// (Even if this is the second active touch).
774
- config.startShouldSetResponder.captured.grandParent = {order: 0, returnVal: false};
775
- config.startShouldSetResponder.captured.parent = {order: 1, returnVal: false};
776
- config.startShouldSetResponder.captured.child = {order: 2, returnVal: false};
952
+ config.startShouldSetResponder.captured.grandParent = {
953
+ order: 0,
954
+ returnVal: false,
955
+ };
956
+ config.startShouldSetResponder.captured.parent = {
957
+ order: 1,
958
+ returnVal: false,
959
+ };
960
+ config.startShouldSetResponder.captured.child = {
961
+ order: 2,
962
+ returnVal: false,
963
+ };
964
config.startShouldSetResponder.bubbled.child = {order: 3, returnVal: true};
965
config.responderGrant.child = {order: 4};
966
config.responderStart.child = {order: 5};
967
// / Two active touches \ /one of them new\
781
- run(config, three, startConfig(three.child, [three.parent, three.child], [1]));
782
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(three.child));
783
-
968
+ run(
969
+ config,
970
+ three,
971
+ startConfig(three.child, [three.parent, three.child], [1]),
972
+ );
973
+ expect(ResponderEventPlugin._getResponder()).toBe(
974
+ getInstanceFromNode(three.child),
975
+ );
976
977
// Now we remove the original first touch, keeping the second touch that
978
// started within the current responder (child). Nothing changes because
@@ -788,50 +980,90 @@ describe('ResponderEventPlugin', () => {
980
config = oneEventLoopTestConfig(three);
981
config.responderEnd.child = {order: 0};
982
// / one ended\ /one remains \
791
- run(config, three, endConfig(three.child, [three.parent, three.child], [0]));
792
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(three.child));
983
+ run(
984
+ config,
985
+ three,
986
+ endConfig(three.child, [three.parent, three.child], [0]),
987
+ );
988
+ expect(ResponderEventPlugin._getResponder()).toBe(
989
+ getInstanceFromNode(three.child),
990
+ );
991
992
// Okay, now let's add back that first touch (nothing should change) and
993
// then we'll try peeling back the touches in the opposite order to make
994
// sure that first removing the second touch instantly causes responder to
995
// be released.
996
config = oneEventLoopTestConfig(three);
799
- config.startShouldSetResponder.captured.grandParent = {order: 0, returnVal: false};
800
- config.startShouldSetResponder.captured.parent = {order: 1, returnVal: false};
801
- config.startShouldSetResponder.bubbled.parent = {order: 2, returnVal: false};
802
- config.startShouldSetResponder.bubbled.grandParent = {order: 3, returnVal: false};
997
+ config.startShouldSetResponder.captured.grandParent = {
998
+ order: 0,
999
+ returnVal: false,
1000
+ };
1001
+ config.startShouldSetResponder.captured.parent = {
1002
+ order: 1,
1003
+ returnVal: false,
1004
+ };
1005
+ config.startShouldSetResponder.bubbled.parent = {
1006
+ order: 2,
1007
+ returnVal: false,
1008
+ };
1009
+ config.startShouldSetResponder.bubbled.grandParent = {
1010
+ order: 3,
1011
+ returnVal: false,
1012
+ };
1013
// Interesting: child still gets moves even though touch target is parent!
1014
// Current responder gets a `responderStart` for any touch while responder.
1015
config.responderStart.child = {order: 4};
1016
// / Two active touches \ /one of them new\
807
- run(config, three, startConfig(three.parent, [three.child, three.parent], [1]));
808
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(three.child));
809
-
1017
+ run(
1018
+ config,
1019
+ three,
1020
+ startConfig(three.parent, [three.child, three.parent], [1]),
1021
+ );
1022
+ expect(ResponderEventPlugin._getResponder()).toBe(
1023
+ getInstanceFromNode(three.child),
1024
+ );
1025
1026
// Now, move that new touch that had no effect, and did not start within
1027
// the current responder.
1028
config = oneEventLoopTestConfig(three);
814
- config.moveShouldSetResponder.captured.grandParent = {order: 0, returnVal: false};
815
- config.moveShouldSetResponder.captured.parent = {order: 1, returnVal: false};
1029
+ config.moveShouldSetResponder.captured.grandParent = {
1030
+ order: 0,
1031
+ returnVal: false,
1032
+ };
1033
+ config.moveShouldSetResponder.captured.parent = {
1034
+ order: 1,
1035
+ returnVal: false,
1036
+ };
1037
config.moveShouldSetResponder.bubbled.parent = {order: 2, returnVal: false};
817
- config.moveShouldSetResponder.bubbled.grandParent = {order: 3, returnVal: false};
1038
+ config.moveShouldSetResponder.bubbled.grandParent = {
1039
+ order: 3,
1040
+ returnVal: false,
1041
+ };
1042
// Interesting: child still gets moves even though touch target is parent!
1043
// Current responder gets a `responderMove` for any touch while responder.
1044
config.responderMove.child = {order: 4};
1045
// / Two active touches \ /one of them moved\
822
- run(config, three, moveConfig(three.parent, [three.child, three.parent], [1]));
823
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(three.child));
824
-
1046
+ run(
1047
+ config,
1048
+ three,
1049
+ moveConfig(three.parent, [three.child, three.parent], [1]),
1050
+ );
1051
+ expect(ResponderEventPlugin._getResponder()).toBe(
1052
+ getInstanceFromNode(three.child),
1053
+ );
1054
1055
config = oneEventLoopTestConfig(three);
1056
config.responderEnd.child = {order: 0};
1057
config.responderRelease.child = {order: 1};
1058
// /child end \ /parent remain\
830
- run(config, three, endConfig(three.child, [three.child, three.parent], [0]));
1059
+ run(
1060
+ config,
1061
+ three,
1062
+ endConfig(three.child, [three.child, three.parent], [0]),
1063
+ );
1064
expect(ResponderEventPlugin._getResponder()).toBe(null);
1065
});
1066
834
-
1067
/**
1068
* If nothing is responder, then the negotiation should propagate directly to
1069
* the deepest target in the second touch.
@@ -839,65 +1071,131 @@ describe('ResponderEventPlugin', () => {
1071
it('should negotiate until first common ancestor when there are siblings', () => {
1072
// Initially nothing wants to become the responder
1073
var config = oneEventLoopTestConfig(siblings);
842
- config.startShouldSetResponder.captured.parent = {order: 0, returnVal: false};
843
- config.startShouldSetResponder.captured.childOne = {order: 1, returnVal: false};
844
- config.startShouldSetResponder.bubbled.childOne = {order: 2, returnVal: true};
1074
+ config.startShouldSetResponder.captured.parent = {
1075
+ order: 0,
1076
+ returnVal: false,
1077
+ };
1078
+ config.startShouldSetResponder.captured.childOne = {
1079
+ order: 1,
1080
+ returnVal: false,
1081
+ };
1082
+ config.startShouldSetResponder.bubbled.childOne = {
1083
+ order: 2,
1084
+ returnVal: true,
1085
+ };
1086
config.responderGrant.childOne = {order: 3};
1087
config.responderStart.childOne = {order: 4};
1088
848
- run(config, siblings, startConfig(siblings.childOne, [siblings.childOne], [0]));
849
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(siblings.childOne));
1089
+ run(
1090
+ config,
1091
+ siblings,
1092
+ startConfig(siblings.childOne, [siblings.childOne], [0]),
1093
+ );
1094
+ expect(ResponderEventPlugin._getResponder()).toBe(
1095
+ getInstanceFromNode(siblings.childOne),
1096
+ );
1097
1098
// If the touch target is the sibling item, the negotiation should only
1099
// propagate to first common ancestor of current responder and sibling (so
1100
// the parent).
1101
config = oneEventLoopTestConfig(siblings);
855
- config.startShouldSetResponder.captured.parent = {order: 0, returnVal: false};
856
- config.startShouldSetResponder.bubbled.parent = {order: 1, returnVal: false};
1102
+ config.startShouldSetResponder.captured.parent = {
1103
+ order: 0,
1104
+ returnVal: false,
1105
+ };
1106
+ config.startShouldSetResponder.bubbled.parent = {
1107
+ order: 1,
1108
+ returnVal: false,
1109
+ };
1110
config.responderStart.childOne = {order: 2};
1111
859
- var touchConfig =
860
- startConfig(siblings.childTwo, [siblings.childOne, siblings.childTwo], [1]);
1112
+ var touchConfig = startConfig(
1113
+ siblings.childTwo,
1114
+ [siblings.childOne, siblings.childTwo],
1115
+ [1],
1116
+ );
1117
run(config, siblings, touchConfig);
862
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(siblings.childOne));
863
-
1118
+ expect(ResponderEventPlugin._getResponder()).toBe(
1119
+ getInstanceFromNode(siblings.childOne),
1120
+ );
1121
1122
// move childOne
1123
config = oneEventLoopTestConfig(siblings);
867
- config.moveShouldSetResponder.captured.parent = {order: 0, returnVal: false};
1124
+ config.moveShouldSetResponder.captured.parent = {
1125
+ order: 0,
1126
+ returnVal: false,
1127
+ };
1128
config.moveShouldSetResponder.bubbled.parent = {order: 1, returnVal: false};
1129
config.responderMove.childOne = {order: 2};
870
- run(config, siblings, moveConfig(siblings.childOne, [siblings.childOne, siblings.childTwo], [0]));
871
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(siblings.childOne));
1130
+ run(
1131
+ config,
1132
+ siblings,
1133
+ moveConfig(
1134
+ siblings.childOne,
1135
+ [siblings.childOne, siblings.childTwo],
1136
+ [0],
1137
+ ),
1138
+ );
1139
+ expect(ResponderEventPlugin._getResponder()).toBe(
1140
+ getInstanceFromNode(siblings.childOne),
1141
+ );
1142
1143
// move childTwo: Only negotiates to `parent`.
1144
config = oneEventLoopTestConfig(siblings);
875
- config.moveShouldSetResponder.captured.parent = {order: 0, returnVal: false};
1145
+ config.moveShouldSetResponder.captured.parent = {
1146
+ order: 0,
1147
+ returnVal: false,
1148
+ };
1149
config.moveShouldSetResponder.bubbled.parent = {order: 1, returnVal: false};
1150
config.responderMove.childOne = {order: 2};
878
- run(config, siblings, moveConfig(siblings.childTwo, [siblings.childOne, siblings.childTwo], [1]));
879
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(siblings.childOne));
880
-
1151
+ run(
1152
+ config,
1153
+ siblings,
1154
+ moveConfig(
1155
+ siblings.childTwo,
1156
+ [siblings.childOne, siblings.childTwo],
1157
+ [1],
1158
+ ),
1159
+ );
1160
+ expect(ResponderEventPlugin._getResponder()).toBe(
1161
+ getInstanceFromNode(siblings.childOne),
1162
+ );
1163
});
1164
883
-
1165
it('should notify of being rejected. responderStart/Move happens on current responder', () => {
1166
// Initially nothing wants to become the responder
1167
var config = oneEventLoopTestConfig(three);
887
- config.startShouldSetResponder.captured.grandParent = {order: 0, returnVal: false};
888
- config.startShouldSetResponder.captured.parent = {order: 1, returnVal: false};
889
- config.startShouldSetResponder.captured.child = {order: 2, returnVal: false};
1168
+ config.startShouldSetResponder.captured.grandParent = {
1169
+ order: 0,
1170
+ returnVal: false,
1171
+ };
1172
+ config.startShouldSetResponder.captured.parent = {
1173
+ order: 1,
1174
+ returnVal: false,
1175
+ };
1176
+ config.startShouldSetResponder.captured.child = {
1177
+ order: 2,
1178
+ returnVal: false,
1179
+ };
1180
config.startShouldSetResponder.bubbled.child = {order: 3, returnVal: true};
1181
config.responderGrant.child = {order: 4};
1182
config.responderStart.child = {order: 5};
1183
1184
run(config, three, startConfig(three.child, [three.child], [0]));
895
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(three.child));
1185
+ expect(ResponderEventPlugin._getResponder()).toBe(
1186
+ getInstanceFromNode(three.child),
1187
+ );
1188
1189
// Suppose parent wants to become responder on move, and is rejected
1190
config = oneEventLoopTestConfig(three);
899
- config.moveShouldSetResponder.captured.grandParent = {order: 0, returnVal: false};
900
- config.moveShouldSetResponder.captured.parent = {order: 1, returnVal: false};
1191
+ config.moveShouldSetResponder.captured.grandParent = {
1192
+ order: 0,
1193
+ returnVal: false,
1194
+ };
1195
+ config.moveShouldSetResponder.captured.parent = {
1196
+ order: 1,
1197
+ returnVal: false,
1198
+ };
1199
config.moveShouldSetResponder.bubbled.parent = {order: 2, returnVal: true};
1200
config.responderGrant.parent = {order: 3};
1201
config.responderTerminationRequest.child = {order: 4, returnVal: false};
@@ -905,14 +1203,21 @@ describe('ResponderEventPlugin', () => {
1203
// The start/move should occur on the original responder if new one is rejected
1204
config.responderMove.child = {order: 6};
1205
908
- var touchConfig =
909
- moveConfig(three.child, [three.child], [0]);
1206
+ var touchConfig = moveConfig(three.child, [three.child], [0]);
1207
run(config, three, touchConfig);
911
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(three.child));
1208
+ expect(ResponderEventPlugin._getResponder()).toBe(
1209
+ getInstanceFromNode(three.child),
1210
+ );
1211
1212
config = oneEventLoopTestConfig(three);
914
- config.startShouldSetResponder.captured.grandParent = {order: 0, returnVal: false};
915
- config.startShouldSetResponder.captured.parent = {order: 1, returnVal: false};
1213
+ config.startShouldSetResponder.captured.grandParent = {
1214
+ order: 0,
1215
+ returnVal: false,
1216
+ };
1217
+ config.startShouldSetResponder.captured.parent = {
1218
+ order: 1,
1219
+ returnVal: false,
1220
+ };
1221
config.startShouldSetResponder.bubbled.parent = {order: 2, returnVal: true};
1222
config.responderGrant.parent = {order: 3};
1223
config.responderTerminationRequest.child = {order: 4, returnVal: false};
@@ -920,34 +1225,53 @@ describe('ResponderEventPlugin', () => {
1225
// The start/move should occur on the original responder if new one is rejected
1226
config.responderStart.child = {order: 6};
1227
923
- touchConfig =
924
- startConfig(three.child, [three.child, three.child], [1]);
1228
+ touchConfig = startConfig(three.child, [three.child, three.child], [1]);
1229
run(config, three, touchConfig);
926
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(three.child));
927
-
1230
+ expect(ResponderEventPlugin._getResponder()).toBe(
1231
+ getInstanceFromNode(three.child),
1232
+ );
1233
});
1234
930
-
1235
it('should negotiate scroll', () => {
1236
// Initially nothing wants to become the responder
1237
var config = oneEventLoopTestConfig(three);
934
- config.startShouldSetResponder.captured.grandParent = {order: 0, returnVal: false};
935
- config.startShouldSetResponder.captured.parent = {order: 1, returnVal: false};
936
- config.startShouldSetResponder.captured.child = {order: 2, returnVal: false};
1238
+ config.startShouldSetResponder.captured.grandParent = {
1239
+ order: 0,
1240
+ returnVal: false,
1241
+ };
1242
+ config.startShouldSetResponder.captured.parent = {
1243
+ order: 1,
1244
+ returnVal: false,
1245
+ };
1246
+ config.startShouldSetResponder.captured.child = {
1247
+ order: 2,
1248
+ returnVal: false,
1249
+ };
1250
config.startShouldSetResponder.bubbled.child = {order: 3, returnVal: true};
1251
config.responderGrant.child = {order: 4};
1252
config.responderStart.child = {order: 5};
1253
1254
run(config, three, startConfig(three.child, [three.child], [0]));
942
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(three.child));
1255
+ expect(ResponderEventPlugin._getResponder()).toBe(
1256
+ getInstanceFromNode(three.child),
1257
+ );
1258
1259
// If the touch target is the sibling item, the negotiation should only
1260
// propagate to first common ancestor of current responder and sibling (so
1261
// the parent).
1262
config = oneEventLoopTestConfig(three);
948
- config.scrollShouldSetResponder.captured.grandParent = {order: 0, returnVal: false};
949
- config.scrollShouldSetResponder.captured.parent = {order: 1, returnVal: false};
950
- config.scrollShouldSetResponder.bubbled.parent = {order: 2, returnVal: true};
1263
+ config.scrollShouldSetResponder.captured.grandParent = {
1264
+ order: 0,
1265
+ returnVal: false,
1266
+ };
1267
+ config.scrollShouldSetResponder.captured.parent = {
1268
+ order: 1,
1269
+ returnVal: false,
1270
+ };
1271
+ config.scrollShouldSetResponder.bubbled.parent = {
1272
+ order: 2,
1273
+ returnVal: true,
1274
+ };
1275
config.responderGrant.parent = {order: 3};
1276
config.responderTerminationRequest.child = {order: 4, returnVal: false};
1277
config.responderReject.parent = {order: 5};
@@ -957,14 +1281,24 @@ describe('ResponderEventPlugin', () => {
1281
targetInst: getInstanceFromNode(three.parent),
1282
nativeEvent: {},
1283
});
960
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(three.child));
961
-
1284
+ expect(ResponderEventPlugin._getResponder()).toBe(
1285
+ getInstanceFromNode(three.child),
1286
+ );
1287
1288
// Now lets let the scroll take control this time.
1289
config = oneEventLoopTestConfig(three);
965
- config.scrollShouldSetResponder.captured.grandParent = {order: 0, returnVal: false};
966
- config.scrollShouldSetResponder.captured.parent = {order: 1, returnVal: false};
967
- config.scrollShouldSetResponder.bubbled.parent = {order: 2, returnVal: true};
1290
+ config.scrollShouldSetResponder.captured.grandParent = {
1291
+ order: 0,
1292
+ returnVal: false,
1293
+ };
1294
+ config.scrollShouldSetResponder.captured.parent = {
1295
+ order: 1,
1296
+ returnVal: false,
1297
+ };
1298
+ config.scrollShouldSetResponder.bubbled.parent = {
1299
+ order: 2,
1300
+ returnVal: true,
1301
+ };
1302
config.responderGrant.parent = {order: 3};
1303
config.responderTerminationRequest.child = {order: 4, returnVal: true};
1304
config.responderTerminate.child = {order: 5};
@@ -974,23 +1308,34 @@ describe('ResponderEventPlugin', () => {
1308
targetInst: getInstanceFromNode(three.parent),
1309
nativeEvent: {},
1310
});
977
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(three.parent));
978
-
979
-
1311
+ expect(ResponderEventPlugin._getResponder()).toBe(
1312
+ getInstanceFromNode(three.parent),
1313
+ );
1314
});
1315
1316
it('should cancel correctly', () => {
1317
// Initially our child becomes responder
1318
var config = oneEventLoopTestConfig(three);
985
- config.startShouldSetResponder.captured.grandParent = {order: 0, returnVal: false};
986
- config.startShouldSetResponder.captured.parent = {order: 1, returnVal: false};
987
- config.startShouldSetResponder.captured.child = {order: 2, returnVal: false};
1319
+ config.startShouldSetResponder.captured.grandParent = {
1320
+ order: 0,
1321
+ returnVal: false,
1322
+ };
1323
+ config.startShouldSetResponder.captured.parent = {
1324
+ order: 1,
1325
+ returnVal: false,
1326
+ };
1327
+ config.startShouldSetResponder.captured.child = {
1328
+ order: 2,
1329
+ returnVal: false,
1330
+ };
1331
config.startShouldSetResponder.bubbled.child = {order: 3, returnVal: true};
1332
config.responderGrant.child = {order: 4};
1333
config.responderStart.child = {order: 5};
1334
1335
run(config, three, startConfig(three.child, [three.child], [0]));
993
- expect(ResponderEventPlugin._getResponder()).toBe(getInstanceFromNode(three.child));
1336
+ expect(ResponderEventPlugin._getResponder()).toBe(
1337
+ getInstanceFromNode(three.child),
1338
+ );
1339
1340
config = oneEventLoopTestConfig(three);
1341
config.responderEnd.child = {order: 0};
@@ -1000,7 +1345,7 @@ describe('ResponderEventPlugin', () => {
1345
'topTouchCancel',
1346
three.child,
1347
[three.child],
1003
- [0]
1348
+ [0],
1349
);
1350
run(config, three, nativeEvent);
1351
expect(ResponderEventPlugin._getResponder()).toBe(null);
src/renderers/shared/shared/getContextForSubtree.js
+3
-1
@@ -19,7 +19,9 @@ let getContextFiber = function(arg) {
19
invariant(false, 'Missing injection for fiber getContextForSubtree');
20
};
21
22
-function getContextForSubtree(parentComponent : ?ReactComponent<any, any, any>) : Object {
22
+function getContextForSubtree(
23
+ parentComponent: ?ReactComponent<any, any, any>,
24
+): Object {
25
if (!parentComponent) {
26
return emptyObject;
27
}
src/renderers/shared/shared/shouldUpdateReactComponent.js
+3
-5
@@ -32,13 +32,11 @@ function shouldUpdateReactComponent(prevElement, nextElement) {
32
var prevType = typeof prevElement;
33
var nextType = typeof nextElement;
34
if (prevType === 'string' || prevType === 'number') {
35
- return (nextType === 'string' || nextType === 'number');
35
+ return nextType === 'string' || nextType === 'number';
36
} else {
37
- return (
38
- nextType === 'object' &&
37
+ return nextType === 'object' &&
38
prevElement.type === nextElement.type &&
40
- prevElement.key === nextElement.key
41
- );
39
+ prevElement.key === nextElement.key;
40
}
41
}
42
src/renderers/shared/stack/reconciler/CallbackQueue.js
+1
-1
@@ -66,7 +66,7 @@ class CallbackQueue<T> {
66
if (callbacks && contexts) {
67
invariant(
68
callbacks.length === contexts.length,
69
- 'Mismatched list of contexts in callback queue'
69
+ 'Mismatched list of contexts in callback queue',
70
);
71
this._callbacks = null;
72
this._contexts = null;
src/renderers/shared/stack/reconciler/ReactChildReconciler.js
+30
-30
@@ -37,7 +37,7 @@ if (
37
38
function instantiateChild(childInstances, child, name, selfDebugID) {
39
// We found a component instance.
40
- var keyUnique = (childInstances[name] === undefined);
40
+ var keyUnique = childInstances[name] === undefined;
41
if (__DEV__) {
42
if (!ReactComponentTreeHook) {
43
ReactComponentTreeHook = require('react/lib/ReactComponentTreeHook');
@@ -46,10 +46,10 @@ function instantiateChild(childInstances, child, name, selfDebugID) {
46
warning(
47
false,
48
'flattenChildren(...): Encountered two children with the same key, ' +
49
- '`%s`. Child keys must be unique; when two children share a key, only ' +
50
- 'the first child will be used.%s',
49
+ '`%s`. Child keys must be unique; when two children share a key, only ' +
50
+ 'the first child will be used.%s',
51
KeyEscapeUtils.unescape(name),
52
- ReactComponentTreeHook.getStackAddendumByID(selfDebugID)
52
+ ReactComponentTreeHook.getStackAddendumByID(selfDebugID),
53
);
54
}
55
}
@@ -76,7 +76,7 @@ var ReactChildReconciler = {
76
nestedChildNodes,
77
transaction,
78
context,
79
- selfDebugID // 0 in production and for roots
79
+ selfDebugID, // 0 in production and for roots
80
) {
81
if (nestedChildNodes == null) {
82
return null;
@@ -86,13 +86,9 @@ var ReactChildReconciler = {
86
if (__DEV__) {
87
traverseAllChildren(
88
nestedChildNodes,
89
- (childInsts, child, name) => instantiateChild(
90
- childInsts,
91
- child,
92
- name,
93
- selfDebugID
94
- ),
95
- childInstances
89
+ (childInsts, child, name) =>
90
+ instantiateChild(childInsts, child, name, selfDebugID),
91
+ childInstances,
92
);
93
} else {
94
traverseAllChildren(nestedChildNodes, instantiateChild, childInstances);
@@ -119,7 +115,7 @@ var ReactChildReconciler = {
115
hostParent,
116
hostContainerInfo,
117
context,
122
- selfDebugID // 0 in production and for roots
118
+ selfDebugID, // 0 in production and for roots
119
) {
120
// We currently don't have a way to track moves here but if we use iterators
121
// instead of for..in we can zip the iterators and check if an item has
@@ -138,22 +134,26 @@ var ReactChildReconciler = {
134
prevChild = prevChildren && prevChildren[name];
135
var prevElement = prevChild && prevChild._currentElement;
136
var nextElement = nextChildren[name];
141
- if (prevChild != null &&
142
- shouldUpdateReactComponent(prevElement, nextElement)) {
137
+ if (
138
+ prevChild != null &&
139
+ shouldUpdateReactComponent(prevElement, nextElement)
140
+ ) {
141
ReactReconciler.receiveComponent(
144
- prevChild, nextElement, transaction, context
142
+ prevChild,
143
+ nextElement,
144
+ transaction,
145
+ context,
146
);
147
nextChildren[name] = prevChild;
148
} else {
149
if (
149
- !ReactFeatureFlags.prepareNewChildrenBeforeUnmountInStack &&
150
- prevChild
150
+ !ReactFeatureFlags.prepareNewChildrenBeforeUnmountInStack && prevChild
151
) {
152
removedNodes[name] = ReactReconciler.getHostNode(prevChild);
153
ReactReconciler.unmountComponent(
154
prevChild,
155
- false, /* safely */
156
- false /* skipLifecycle */
155
+ false /* safely */,
156
+ false /* skipLifecycle */,
157
);
158
}
159
// The child must be instantiated before it's mounted.
@@ -167,32 +167,33 @@ var ReactChildReconciler = {
167
hostParent,
168
hostContainerInfo,
169
context,
170
- selfDebugID
170
+ selfDebugID,
171
);
172
mountImages.push(nextChildMountImage);
173
if (
174
- ReactFeatureFlags.prepareNewChildrenBeforeUnmountInStack &&
175
- prevChild
174
+ ReactFeatureFlags.prepareNewChildrenBeforeUnmountInStack && prevChild
175
) {
176
removedNodes[name] = ReactReconciler.getHostNode(prevChild);
177
ReactReconciler.unmountComponent(
178
prevChild,
180
- false, /* safely */
181
- false /* skipLifecycle */
179
+ false /* safely */,
180
+ false /* skipLifecycle */,
181
);
182
}
183
}
184
}
185
// Unmount children that are no longer present.
186
for (name in prevChildren) {
188
- if (prevChildren.hasOwnProperty(name) &&
189
- !(nextChildren && nextChildren.hasOwnProperty(name))) {
187
+ if (
188
+ prevChildren.hasOwnProperty(name) &&
189
+ !(nextChildren && nextChildren.hasOwnProperty(name))
190
+ ) {
191
prevChild = prevChildren[name];
192
removedNodes[name] = ReactReconciler.getHostNode(prevChild);
193
ReactReconciler.unmountComponent(
194
prevChild,
194
- false, /* safely */
195
- false /* skipLifecycle */
195
+ false /* safely */,
196
+ false /* skipLifecycle */,
197
);
198
}
199
}
@@ -213,7 +214,6 @@ var ReactChildReconciler = {
214
}
215
}
216
},
216
-
217
};
218
219
module.exports = ReactChildReconciler;
src/renderers/shared/stack/reconciler/ReactComponentEnvironment.js
+3
-7
@@ -25,7 +25,6 @@ type Environment = {
25
var injected = false;
26
27
var ReactComponentEnvironment = {
28
-
28
/**
29
* Optionally injectable hook for swapping out mount images in the middle of
30
* the tree.
@@ -42,16 +41,13 @@ var ReactComponentEnvironment = {
41
injectEnvironment: function(environment: Environment) {
42
invariant(
43
!injected,
45
- 'ReactCompositeComponent: injectEnvironment() can only be called once.'
44
+ 'ReactCompositeComponent: injectEnvironment() can only be called once.',
45
);
47
- ReactComponentEnvironment.replaceNodeWithMarkup =
48
- environment.replaceNodeWithMarkup;
49
- ReactComponentEnvironment.processChildrenUpdates =
50
- environment.processChildrenUpdates;
46
+ ReactComponentEnvironment.replaceNodeWithMarkup = environment.replaceNodeWithMarkup;
47
+ ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates;
48
injected = true;
49
},
50
},
54
-
51
};
52
53
module.exports = ReactComponentEnvironment;
src/renderers/shared/stack/reconciler/ReactCompositeComponent.js
+164
-151
@@ -34,8 +34,7 @@ var shallowEqual = require('fbjs/lib/shallowEqual');
34
var shouldUpdateReactComponent = require('shouldUpdateReactComponent');
35
var warning = require('fbjs/lib/warning');
36
37
-function StatelessComponent(Component) {
38
-}
37
+function StatelessComponent(Component) {}
38
StatelessComponent.prototype.render = function() {
39
var Component = ReactInstanceMap.get(this)._currentElement.type;
40
var element = Component(this.props, this.context, this.updater);
@@ -106,7 +105,6 @@ var nextMountID = 1;
105
* @lends {ReactCompositeComponent.prototype}
106
*/
107
var ReactCompositeComponent = {
109
-
108
/**
109
* Base constructor for all composite component.
110
*
@@ -161,7 +159,7 @@ var ReactCompositeComponent = {
159
transaction,
160
hostParent,
161
hostContainerInfo,
164
- context
162
+ context,
163
) {
164
this._context = context;
165
this._mountOrder = nextMountID++;
@@ -181,7 +179,7 @@ var ReactCompositeComponent = {
179
doConstruct,
180
publicProps,
181
publicContext,
184
- updateQueue
182
+ updateQueue,
183
);
184
var renderedElement;
185
@@ -192,16 +190,14 @@ var ReactCompositeComponent = {
190
warning(
191
!Component.childContextTypes,
192
'%s(...): childContextTypes cannot be defined on a functional component.',
195
- Component.displayName || Component.name || 'Component'
193
+ Component.displayName || Component.name || 'Component',
194
);
195
}
196
invariant(
199
- inst === null ||
200
- inst === false ||
201
- React.isValidElement(inst),
197
+ inst === null || inst === false || React.isValidElement(inst),
198
'%s(...): A valid React element (or null) must be returned. You may have ' +
203
- 'returned undefined, an array or some other invalid object.',
204
- Component.displayName || Component.name || 'Component'
199
+ 'returned undefined, an array or some other invalid object.',
200
+ Component.displayName || Component.name || 'Component',
201
);
202
inst = new StatelessComponent(Component);
203
this._compositeType = ReactCompositeComponentTypes.StatelessFunctional;
@@ -220,20 +216,22 @@ var ReactCompositeComponent = {
216
warning(
217
false,
218
'%s(...): No `render` method found on the returned component ' +
223
- 'instance: you may have forgotten to define `render`.',
224
- Component.displayName || Component.name || 'Component'
219
+ 'instance: you may have forgotten to define `render`.',
220
+ Component.displayName || Component.name || 'Component',
221
);
222
}
223
224
var propsMutated = inst.props !== publicProps;
229
- var componentName =
230
- Component.displayName || Component.name || 'Component';
225
+ var componentName = Component.displayName ||
226
+ Component.name ||
227
+ 'Component';
228
229
warning(
230
inst.props === undefined || !propsMutated,
231
'%s(...): When calling super() in `%s`, make sure to pass ' +
235
- 'up the same props that your component\'s constructor was passed.',
236
- componentName, componentName
232
+ "up the same props that your component's constructor was passed.",
233
+ componentName,
234
+ componentName,
235
);
236
}
237
@@ -255,64 +253,63 @@ var ReactCompositeComponent = {
253
// catch them here, at initialization time, instead.
254
warning(
255
!inst.getInitialState ||
258
- inst.getInitialState.isReactClassApproved ||
259
- inst.state,
256
+ inst.getInitialState.isReactClassApproved ||
257
+ inst.state,
258
'getInitialState was defined on %s, a plain JavaScript class. ' +
261
- 'This is only supported for classes created using React.createClass. ' +
262
- 'Did you mean to define a state property instead?',
263
- this.getName() || 'a component'
259
+ 'This is only supported for classes created using React.createClass. ' +
260
+ 'Did you mean to define a state property instead?',
261
+ this.getName() || 'a component',
262
);
263
warning(
266
- !inst.getDefaultProps ||
267
- inst.getDefaultProps.isReactClassApproved,
264
+ !inst.getDefaultProps || inst.getDefaultProps.isReactClassApproved,
265
'getDefaultProps was defined on %s, a plain JavaScript class. ' +
269
- 'This is only supported for classes created using React.createClass. ' +
270
- 'Use a static property to define defaultProps instead.',
271
- this.getName() || 'a component'
266
+ 'This is only supported for classes created using React.createClass. ' +
267
+ 'Use a static property to define defaultProps instead.',
268
+ this.getName() || 'a component',
269
);
270
warning(
271
!inst.propTypes,
272
'propTypes was defined as an instance property on %s. Use a static ' +
276
- 'property to define propTypes instead.',
277
- this.getName() || 'a component'
273
+ 'property to define propTypes instead.',
274
+ this.getName() || 'a component',
275
);
276
warning(
277
!inst.contextTypes,
278
'contextTypes was defined as an instance property on %s. Use a ' +
282
- 'static property to define contextTypes instead.',
283
- this.getName() || 'a component'
279
+ 'static property to define contextTypes instead.',
280
+ this.getName() || 'a component',
281
);
282
warning(
283
typeof inst.componentShouldUpdate !== 'function',
284
'%s has a method called ' +
288
- 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' +
289
- 'The name is phrased as a question because the function is ' +
290
- 'expected to return a value.',
291
- (this.getName() || 'A component')
285
+ 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' +
286
+ 'The name is phrased as a question because the function is ' +
287
+ 'expected to return a value.',
288
+ this.getName() || 'A component',
289
);
290
warning(
291
typeof inst.componentDidUnmount !== 'function',
292
'%s has a method called ' +
296
- 'componentDidUnmount(). But there is no such lifecycle method. ' +
297
- 'Did you mean componentWillUnmount()?',
298
- this.getName() || 'A component'
293
+ 'componentDidUnmount(). But there is no such lifecycle method. ' +
294
+ 'Did you mean componentWillUnmount()?',
295
+ this.getName() || 'A component',
296
);
297
warning(
298
typeof inst.componentWillRecieveProps !== 'function',
299
'%s has a method called ' +
303
- 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?',
304
- (this.getName() || 'A component')
300
+ 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?',
301
+ this.getName() || 'A component',
302
);
303
}
304
305
var initialState = inst.state;
306
if (initialState === undefined) {
310
- inst.state = initialState = null;
307
+ inst.state = (initialState = null);
308
}
309
invariant(
310
typeof initialState === 'object' && !Array.isArray(initialState),
311
'%s.state: must be set to an object or null',
315
- this.getName() || 'ReactCompositeComponent'
312
+ this.getName() || 'ReactCompositeComponent',
313
);
314
315
this._pendingStateQueue = null;
@@ -324,7 +321,7 @@ var ReactCompositeComponent = {
321
measureLifeCyclePerf(
322
() => inst.componentWillMount(),
323
this._debugID,
327
- 'componentWillMount'
324
+ 'componentWillMount',
325
);
326
} else {
327
inst.componentWillMount();
@@ -343,7 +340,7 @@ var ReactCompositeComponent = {
340
hostParent,
341
hostContainerInfo,
342
transaction,
346
- context
343
+ context,
344
);
345
} else {
346
markup = this.performInitialMount(
@@ -351,7 +348,7 @@ var ReactCompositeComponent = {
348
hostParent,
349
hostContainerInfo,
350
transaction,
354
- context
351
+ context,
352
);
353
}
354
@@ -361,7 +358,7 @@ var ReactCompositeComponent = {
358
measureLifeCyclePerf(
359
() => inst.componentDidMount(),
360
this._debugID,
364
- 'componentDidMount'
361
+ 'componentDidMount',
362
);
363
});
364
} else {
@@ -374,10 +371,7 @@ var ReactCompositeComponent = {
371
if (callbacks) {
372
this._pendingCallbacks = null;
373
for (let i = 0; i < callbacks.length; i++) {
377
- transaction.getReactMountReady().enqueue(
378
- callbacks[i],
379
- inst
380
- );
374
+ transaction.getReactMountReady().enqueue(callbacks[i], inst);
375
}
376
}
377
@@ -388,7 +382,7 @@ var ReactCompositeComponent = {
382
doConstruct,
383
publicProps,
384
publicContext,
391
- updateQueue
385
+ updateQueue,
386
) {
387
if (__DEV__) {
388
ReactCurrentOwner.current = this;
@@ -397,7 +391,7 @@ var ReactCompositeComponent = {
391
doConstruct,
392
publicProps,
393
publicContext,
400
- updateQueue
394
+ updateQueue,
395
);
396
} finally {
397
ReactCurrentOwner.current = null;
@@ -407,7 +401,7 @@ var ReactCompositeComponent = {
401
doConstruct,
402
publicProps,
403
publicContext,
410
- updateQueue
404
+ updateQueue,
405
);
406
}
407
},
@@ -416,7 +410,7 @@ var ReactCompositeComponent = {
410
doConstruct,
411
publicProps,
412
publicContext,
419
- updateQueue
413
+ updateQueue,
414
) {
415
var Component = this._currentElement.type;
416
@@ -425,7 +419,7 @@ var ReactCompositeComponent = {
419
return measureLifeCyclePerf(
420
() => new Component(publicProps, publicContext, updateQueue),
421
this._debugID,
428
- 'ctor'
422
+ 'ctor',
423
);
424
} else {
425
return new Component(publicProps, publicContext, updateQueue);
@@ -438,7 +432,7 @@ var ReactCompositeComponent = {
432
return measureLifeCyclePerf(
433
() => Component(publicProps, publicContext, updateQueue),
434
this._debugID,
441
- 'render'
435
+ 'render',
436
);
437
} else {
438
return Component(publicProps, publicContext, updateQueue);
@@ -450,7 +444,7 @@ var ReactCompositeComponent = {
444
hostParent,
445
hostContainerInfo,
446
transaction,
453
- context
447
+ context,
448
) {
449
var markup;
450
var checkpoint = transaction.checkpoint();
@@ -460,20 +454,23 @@ var ReactCompositeComponent = {
454
hostParent,
455
hostContainerInfo,
456
transaction,
463
- context
457
+ context,
458
);
459
} catch (e) {
460
// Roll back to checkpoint, handle error (which may add items to the transaction), and take a new checkpoint
461
transaction.rollback(checkpoint);
462
this._instance.unstable_handleError(e);
463
if (this._pendingStateQueue) {
470
- this._instance.state = this._processPendingState(this._instance.props, this._instance.context);
464
+ this._instance.state = this._processPendingState(
465
+ this._instance.props,
466
+ this._instance.context,
467
+ );
468
}
469
checkpoint = transaction.checkpoint();
470
this._renderedComponent.unmountComponent(
474
- true, /* safely */
471
+ true /* safely */,
472
// Don't call componentWillUnmount() because they never fully mounted:
476
- true /* skipLifecyle */
473
+ true /* skipLifecyle */,
474
);
475
transaction.rollback(checkpoint);
476
@@ -484,7 +481,7 @@ var ReactCompositeComponent = {
481
hostParent,
482
hostContainerInfo,
483
transaction,
487
- context
484
+ context,
485
);
486
}
487
return markup;
@@ -495,7 +492,7 @@ var ReactCompositeComponent = {
492
hostParent,
493
hostContainerInfo,
494
transaction,
498
- context
495
+ context,
496
) {
497
// If not a stateless component, we now render
498
if (renderedElement === undefined) {
@@ -506,7 +503,7 @@ var ReactCompositeComponent = {
503
this._renderedNodeType = nodeType;
504
var child = this._instantiateReactComponent(
505
renderedElement,
509
- nodeType !== ReactNodeTypes.EMPTY /* shouldHaveDebugID */
506
+ nodeType !== ReactNodeTypes.EMPTY /* shouldHaveDebugID */,
507
);
508
this._renderedComponent = child;
509
@@ -521,7 +518,7 @@ var ReactCompositeComponent = {
518
hostParent,
519
hostContainerInfo,
520
this._processChildContext(context),
524
- debugID
521
+ debugID,
522
);
523
524
if (__DEV__) {
@@ -557,14 +554,18 @@ var ReactCompositeComponent = {
554
if (safely) {
555
if (!skipLifecycle) {
556
var name = this.getName() + '.componentWillUnmount()';
560
- ReactErrorUtils.invokeGuardedCallbackAndCatchFirstError(name, inst.componentWillUnmount, inst);
557
+ ReactErrorUtils.invokeGuardedCallbackAndCatchFirstError(
558
+ name,
559
+ inst.componentWillUnmount,
560
+ inst,
561
+ );
562
}
563
} else {
564
if (__DEV__) {
565
measureLifeCyclePerf(
566
() => inst.componentWillUnmount(),
567
this._debugID,
567
- 'componentWillUnmount'
568
+ 'componentWillUnmount',
569
);
570
} else {
571
inst.componentWillUnmount();
@@ -576,7 +577,7 @@ var ReactCompositeComponent = {
577
ReactReconciler.unmountComponent(
578
this._renderedComponent,
579
safely,
579
- skipLifecycle
580
+ skipLifecycle,
581
);
582
this._renderedNodeType = null;
583
this._renderedComponent = null;
@@ -647,7 +648,7 @@ var ReactCompositeComponent = {
648
this._checkContextTypes(
649
Component.contextTypes,
650
maskedContext,
650
- 'context'
651
+ 'context',
652
);
653
}
654
}
@@ -679,14 +680,14 @@ var ReactCompositeComponent = {
680
invariant(
681
typeof Component.childContextTypes === 'object',
682
'%s.getChildContext(): childContextTypes must be defined in order to ' +
682
- 'use getChildContext().',
683
- this.getName() || 'ReactCompositeComponent'
683
+ 'use getChildContext().',
684
+ this.getName() || 'ReactCompositeComponent',
685
);
686
if (__DEV__) {
687
this._checkContextTypes(
688
Component.childContextTypes,
689
childContext,
689
- 'child context'
690
+ 'child context',
691
);
692
}
693
for (var name in childContext) {
@@ -694,7 +695,7 @@ var ReactCompositeComponent = {
695
name in Component.childContextTypes,
696
'%s.getChildContext(): key "%s" is not defined in childContextTypes.',
697
this.getName() || 'ReactCompositeComponent',
697
- name
698
+ name,
699
);
700
}
701
return Object.assign({}, currentContext, childContext);
@@ -707,8 +708,8 @@ var ReactCompositeComponent = {
708
warning(
709
!Component.childContextTypes,
710
'%s.childContextTypes is specified but there is no getChildContext() method ' +
710
- 'on the instance. You can either define getChildContext() on %s or remove ' +
711
- 'childContextTypes from it.',
711
+ 'on the instance. You can either define getChildContext() on %s or remove ' +
712
+ 'childContextTypes from it.',
713
componentName,
714
componentName,
715
);
@@ -726,19 +727,10 @@ var ReactCompositeComponent = {
727
* @param {string} location e.g. "prop", "context", "child context"
728
* @private
729
*/
729
- _checkContextTypes: function(
730
- typeSpecs,
731
- values,
732
- location: string,
733
- ) {
730
+ _checkContextTypes: function(typeSpecs, values, location: string) {
731
if (__DEV__) {
732
ReactDebugCurrentFrame.current = this._debugID;
736
- checkReactTypeSpec(
737
- typeSpecs,
738
- values,
739
- location,
740
- this.getName()
741
- );
733
+ checkReactTypeSpec(typeSpecs, values, location, this.getName());
734
ReactDebugCurrentFrame.current = null;
735
}
736
},
@@ -754,7 +746,7 @@ var ReactCompositeComponent = {
746
prevElement,
747
nextElement,
748
prevContext,
757
- nextContext
749
+ nextContext,
750
);
751
},
752
@@ -771,7 +763,7 @@ var ReactCompositeComponent = {
763
this,
764
this._pendingElement,
765
transaction,
774
- this._context
766
+ this._context,
767
);
768
} else if (this._pendingStateQueue !== null || this._pendingForceUpdate) {
769
this.updateComponent(
@@ -779,17 +771,16 @@ var ReactCompositeComponent = {
771
this._currentElement,
772
this._currentElement,
773
this._context,
782
- this._context
774
+ this._context,
775
);
776
} else {
777
var callbacks = this._pendingCallbacks;
778
this._pendingCallbacks = null;
779
if (callbacks) {
780
for (var j = 0; j < callbacks.length; j++) {
789
- transaction.getReactMountReady().enqueue(
790
- callbacks[j],
791
- this.getPublicInstance()
792
- );
781
+ transaction
782
+ .getReactMountReady()
783
+ .enqueue(callbacks[j], this.getPublicInstance());
784
}
785
}
786
this._updateBatchNumber = null;
@@ -816,14 +807,14 @@ var ReactCompositeComponent = {
807
prevParentElement,
808
nextParentElement,
809
prevUnmaskedContext,
819
- nextUnmaskedContext
810
+ nextUnmaskedContext,
811
) {
812
var inst = this._instance;
813
invariant(
814
inst != null,
815
'Attempted to update component `%s` that has already been unmounted ' +
825
- '(or failed to mount).',
826
- this.getName() || 'ReactCompositeComponent'
816
+ '(or failed to mount).',
817
+ this.getName() || 'ReactCompositeComponent',
818
);
819
820
var willReceive = false;
@@ -867,9 +858,9 @@ var ReactCompositeComponent = {
858
warning(
859
false,
860
'%s.componentWillReceiveProps(): Assigning directly to ' +
870
- 'this.state is deprecated (except inside a component\'s ' +
871
- 'constructor). Use setState instead.',
872
- this.getName() || 'ReactCompositeComponent'
861
+ "this.state is deprecated (except inside a component's " +
862
+ 'constructor). Use setState instead.',
863
+ this.getName() || 'ReactCompositeComponent',
864
);
865
}
866
}
@@ -890,15 +881,18 @@ var ReactCompositeComponent = {
881
shouldUpdate = measureLifeCyclePerf(
882
() => inst.shouldComponentUpdate(nextProps, nextState, nextContext),
883
this._debugID,
893
- 'shouldComponentUpdate'
884
+ 'shouldComponentUpdate',
885
);
886
} else {
896
- shouldUpdate = inst.shouldComponentUpdate(nextProps, nextState, nextContext);
887
+ shouldUpdate = inst.shouldComponentUpdate(
888
+ nextProps,
889
+ nextState,
890
+ nextContext,
891
+ );
892
}
893
} else {
894
if (this._compositeType === ReactCompositeComponentTypes.PureClass) {
900
- shouldUpdate =
901
- !shallowEqual(prevProps, nextProps) ||
895
+ shouldUpdate = !shallowEqual(prevProps, nextProps) ||
896
!shallowEqual(inst.state, nextState);
897
}
898
}
@@ -908,8 +902,8 @@ var ReactCompositeComponent = {
902
warning(
903
shouldUpdate !== undefined,
904
'%s.shouldComponentUpdate(): Returned undefined instead of a ' +
911
- 'boolean value. Make sure to return true or false.',
912
- this.getName() || 'ReactCompositeComponent'
905
+ 'boolean value. Make sure to return true or false.',
906
+ this.getName() || 'ReactCompositeComponent',
907
);
908
}
909
@@ -923,7 +917,7 @@ var ReactCompositeComponent = {
917
nextState,
918
nextContext,
919
transaction,
926
- nextUnmaskedContext
920
+ nextUnmaskedContext,
921
);
922
} else {
923
// If it's determined that a component should not update, we still want
@@ -937,10 +931,9 @@ var ReactCompositeComponent = {
931
932
if (callbacks) {
933
for (var j = 0; j < callbacks.length; j++) {
940
- transaction.getReactMountReady().enqueue(
941
- callbacks[j],
942
- this.getPublicInstance()
943
- );
934
+ transaction
935
+ .getReactMountReady()
936
+ .enqueue(callbacks[j], this.getPublicInstance());
937
}
938
}
939
},
@@ -964,9 +957,9 @@ var ReactCompositeComponent = {
957
var dontMutate = true;
958
for (var i = replace ? 1 : 0; i < queue.length; i++) {
959
var partial = queue[i];
967
- let partialState = typeof partial === 'function' ?
968
- partial.call(inst, nextState, props, context) :
969
- partial;
960
+ let partialState = typeof partial === 'function'
961
+ ? partial.call(inst, nextState, props, context)
962
+ : partial;
963
if (partialState) {
964
if (dontMutate) {
965
dontMutate = false;
@@ -998,7 +991,7 @@ var ReactCompositeComponent = {
991
nextState,
992
nextContext,
993
transaction,
1001
- unmaskedContext
994
+ unmaskedContext,
995
) {
996
var inst = this._instance;
997
@@ -1017,7 +1010,7 @@ var ReactCompositeComponent = {
1010
measureLifeCyclePerf(
1011
() => inst.componentWillUpdate(nextProps, nextState, nextContext),
1012
this._debugID,
1020
- 'componentWillUpdate'
1013
+ 'componentWillUpdate',
1014
);
1015
} else {
1016
inst.componentWillUpdate(nextProps, nextState, nextContext);
@@ -1031,7 +1024,10 @@ var ReactCompositeComponent = {
1024
inst.context = nextContext;
1025
1026
if (inst.unstable_handleError) {
1034
- this._updateRenderedComponentWithErrorHandling(transaction, unmaskedContext);
1027
+ this._updateRenderedComponentWithErrorHandling(
1028
+ transaction,
1029
+ unmaskedContext,
1030
+ );
1031
} else {
1032
this._updateRenderedComponent(transaction, unmaskedContext);
1033
}
@@ -1040,16 +1036,28 @@ var ReactCompositeComponent = {
1036
if (__DEV__) {
1037
transaction.getReactMountReady().enqueue(() => {
1038
measureLifeCyclePerf(
1043
- inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext),
1039
+ inst.componentDidUpdate.bind(
1040
+ inst,
1041
+ prevProps,
1042
+ prevState,
1043
+ prevContext,
1044
+ ),
1045
this._debugID,
1045
- 'componentDidUpdate'
1046
+ 'componentDidUpdate',
1047
);
1048
});
1049
} else {
1049
- transaction.getReactMountReady().enqueue(
1050
- inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext),
1051
- inst
1052
- );
1050
+ transaction
1051
+ .getReactMountReady()
1052
+ .enqueue(
1053
+ inst.componentDidUpdate.bind(
1054
+ inst,
1055
+ prevProps,
1056
+ prevState,
1057
+ prevContext,
1058
+ ),
1059
+ inst,
1060
+ );
1061
}
1062
}
1063
},
@@ -1070,7 +1078,10 @@ var ReactCompositeComponent = {
1078
transaction.rollback(checkpoint);
1079
this._instance.unstable_handleError(e);
1080
if (this._pendingStateQueue) {
1073
- this._instance.state = this._processPendingState(this._instance.props, this._instance.context);
1081
+ this._instance.state = this._processPendingState(
1082
+ this._instance.props,
1083
+ this._instance.context,
1084
+ );
1085
}
1086
checkpoint = transaction.checkpoint();
1087
@@ -1079,7 +1090,7 @@ var ReactCompositeComponent = {
1090
transaction,
1091
context,
1092
null,
1082
- true /* safely */
1093
+ true /* safely */,
1094
);
1095
1096
// Try again - we've informed the component about the error, so they can render an error message this time.
@@ -1100,7 +1111,7 @@ var ReactCompositeComponent = {
1111
transaction,
1112
context,
1113
nextRenderedElement,
1103
- false /* safely */
1114
+ false /* safely */,
1115
);
1116
},
1117
@@ -1114,7 +1125,7 @@ var ReactCompositeComponent = {
1125
transaction,
1126
context,
1127
nextRenderedElement,
1117
- safely
1128
+ safely,
1129
) {
1130
var prevComponentInstance = this._renderedComponent;
1131
var prevRenderedElement = prevComponentInstance._currentElement;
@@ -1129,7 +1140,7 @@ var ReactCompositeComponent = {
1140
prevComponentInstance,
1141
nextRenderedElement,
1142
transaction,
1132
- this._processChildContext(context)
1143
+ this._processChildContext(context),
1144
);
1145
} else {
1146
var oldHostNode = ReactReconciler.getHostNode(prevComponentInstance);
@@ -1138,7 +1149,7 @@ var ReactCompositeComponent = {
1149
ReactReconciler.unmountComponent(
1150
prevComponentInstance,
1151
safely,
1141
- false /* skipLifecycle */
1152
+ false /* skipLifecycle */,
1153
);
1154
}
1155
@@ -1146,7 +1157,7 @@ var ReactCompositeComponent = {
1157
this._renderedNodeType = nodeType;
1158
var child = this._instantiateReactComponent(
1159
nextRenderedElement,
1149
- nodeType !== ReactNodeTypes.EMPTY /* shouldHaveDebugID */
1160
+ nodeType !== ReactNodeTypes.EMPTY /* shouldHaveDebugID */,
1161
);
1162
this._renderedComponent = child;
1163
@@ -1156,14 +1167,14 @@ var ReactCompositeComponent = {
1167
this._hostParent,
1168
this._hostContainerInfo,
1169
this._processChildContext(context),
1159
- debugID
1170
+ debugID,
1171
);
1172
1173
if (ReactFeatureFlags.prepareNewChildrenBeforeUnmountInStack) {
1174
ReactReconciler.unmountComponent(
1175
prevComponentInstance,
1176
safely,
1166
- false /* skipLifecycle */
1177
+ false /* skipLifecycle */,
1178
);
1179
}
1180
@@ -1177,7 +1188,7 @@ var ReactCompositeComponent = {
1188
this._replaceNodeWithMarkup(
1189
oldHostNode,
1190
nextMarkup,
1180
- prevComponentInstance
1191
+ prevComponentInstance,
1192
);
1193
}
1194
},
@@ -1191,7 +1202,7 @@ var ReactCompositeComponent = {
1202
ReactComponentEnvironment.replaceNodeWithMarkup(
1203
oldHostNode,
1204
nextMarkup,
1194
- prevInstance
1205
+ prevInstance,
1206
);
1207
},
1208
@@ -1206,7 +1217,7 @@ var ReactCompositeComponent = {
1217
renderedElement = measureLifeCyclePerf(
1218
() => inst.render(),
1219
this._debugID,
1209
- 'render'
1220
+ 'render',
1221
);
1222
} else {
1223
renderedElement = inst.render();
@@ -1214,8 +1225,7 @@ var ReactCompositeComponent = {
1225
1226
if (__DEV__) {
1227
// We allow auto-mocks to proceed as if they're returning null.
1217
- if (renderedElement === undefined &&
1218
- inst.render._isMockFunction) {
1228
+ if (renderedElement === undefined && inst.render._isMockFunction) {
1229
// This is probably bad practice. Consider warning here and
1230
// deprecating this convenience.
1231
renderedElement = null;
@@ -1230,25 +1240,27 @@ var ReactCompositeComponent = {
1240
*/
1241
_renderValidatedComponent: function() {
1242
var renderedElement;
1233
- if (__DEV__ || this._compositeType !== ReactCompositeComponentTypes.StatelessFunctional) {
1243
+ if (
1244
+ __DEV__ ||
1245
+ this._compositeType !== ReactCompositeComponentTypes.StatelessFunctional
1246
+ ) {
1247
ReactCurrentOwner.current = this;
1248
try {
1236
- renderedElement =
1237
- this._renderValidatedComponentWithoutOwnerOrContext();
1249
+ renderedElement = this._renderValidatedComponentWithoutOwnerOrContext();
1250
} finally {
1251
ReactCurrentOwner.current = null;
1252
}
1253
} else {
1242
- renderedElement =
1243
- this._renderValidatedComponentWithoutOwnerOrContext();
1254
+ renderedElement = this._renderValidatedComponentWithoutOwnerOrContext();
1255
}
1256
invariant(
1257
// TODO: An `isValidNode` function would probably be more appropriate
1247
- renderedElement === null || renderedElement === false ||
1248
- React.isValidElement(renderedElement),
1258
+ renderedElement === null ||
1259
+ renderedElement === false ||
1260
+ React.isValidElement(renderedElement),
1261
'%s.render(): A valid React element (or null) must be returned. You may have ' +
1262
'returned undefined, an array or some other invalid object.',
1251
- this.getName() || 'ReactCompositeComponent'
1263
+ this.getName() || 'ReactCompositeComponent',
1264
);
1265
1266
return renderedElement;
@@ -1291,11 +1303,11 @@ var ReactCompositeComponent = {
1303
getName: function() {
1304
var type = this._currentElement.type;
1305
var constructor = this._instance && this._instance.constructor;
1294
- return (
1295
- type.displayName || (constructor && constructor.displayName) ||
1296
- type.name || (constructor && constructor.name) ||
1297
- null
1298
- );
1306
+ return type.displayName ||
1307
+ (constructor && constructor.displayName) ||
1308
+ type.name ||
1309
+ (constructor && constructor.name) ||
1310
+ null;
1311
},
1312
1313
/**
@@ -1308,7 +1320,9 @@ var ReactCompositeComponent = {
1320
*/
1321
getPublicInstance: function() {
1322
var inst = this._instance;
1311
- if (this._compositeType === ReactCompositeComponentTypes.StatelessFunctional) {
1323
+ if (
1324
+ this._compositeType === ReactCompositeComponentTypes.StatelessFunctional
1325
+ ) {
1326
return null;
1327
}
1328
return inst;
@@ -1316,7 +1330,6 @@ var ReactCompositeComponent = {
1330
1331
// Stub
1332
_instantiateReactComponent: null,
1319
-
1333
};
1334
1335
module.exports = ReactCompositeComponent;
src/renderers/shared/stack/reconciler/ReactDefaultBatchingStrategy.js
+5
-9
@@ -34,15 +34,11 @@ function ReactDefaultBatchingStrategyTransaction() {
34
this.reinitializeTransaction();
35
}
36
37
-Object.assign(
38
- ReactDefaultBatchingStrategyTransaction.prototype,
39
- Transaction,
40
- {
41
- getTransactionWrappers: function() {
42
- return TRANSACTION_WRAPPERS;
43
- },
44
- }
45
-);
37
+Object.assign(ReactDefaultBatchingStrategyTransaction.prototype, Transaction, {
38
+ getTransactionWrappers: function() {
39
+ return TRANSACTION_WRAPPERS;
40
+ },
41
+});
42
43
var transaction = new ReactDefaultBatchingStrategyTransaction();
44
src/renderers/shared/stack/reconciler/ReactHostComponent.js
+1
-1
@@ -39,7 +39,7 @@ function createInternalComponent(element) {
39
invariant(
40
genericComponentClass,
41
'There is no registered component for the tag %s',
42
- element.type
42
+ element.type,
43
);
44
return new genericComponentClass(element);
45
}
src/renderers/shared/stack/reconciler/ReactMultiChild.js
+39
-25
@@ -133,10 +133,7 @@ function enqueue(queue, update) {
133
* @private
134
*/
135
function processQueue(inst, updateQueue) {
136
- ReactComponentEnvironment.processChildrenUpdates(
137
- inst,
138
- updateQueue,
139
- );
136
+ ReactComponentEnvironment.processChildrenUpdates(inst, updateQueue);
137
}
138
139
var setChildrenForInstrumentation = emptyFunction;
@@ -158,7 +155,9 @@ if (__DEV__) {
155
if (debugID !== 0) {
156
ReactInstrumentation.debugTool.onSetChildren(
157
debugID,
161
- children ? Object.keys(children).map(key => children[key]._debugID) : []
158
+ children
159
+ ? Object.keys(children).map(key => children[key]._debugID)
160
+ : [],
161
);
162
}
163
};
@@ -170,14 +169,21 @@ if (__DEV__) {
169
* unmount child components.
170
*/
171
var ReactMultiChild = {
173
- _reconcilerInstantiateChildren: function(nestedChildren, transaction, context) {
172
+ _reconcilerInstantiateChildren: function(
173
+ nestedChildren,
174
+ transaction,
175
+ context,
176
+ ) {
177
if (__DEV__) {
178
var selfDebugID = getDebugID(this);
179
if (this._currentElement) {
180
try {
181
ReactCurrentOwner.current = this._currentElement._owner;
182
return ReactChildReconciler.instantiateChildren(
180
- nestedChildren, transaction, context, selfDebugID
183
+ nestedChildren,
184
+ transaction,
185
+ context,
186
+ selfDebugID,
187
);
188
} finally {
189
ReactCurrentOwner.current = null;
@@ -185,7 +191,9 @@ var ReactMultiChild = {
191
}
192
}
193
return ReactChildReconciler.instantiateChildren(
188
- nestedChildren, transaction, context
194
+ nestedChildren,
195
+ transaction,
196
+ context,
197
);
198
},
199
@@ -195,7 +203,7 @@ var ReactMultiChild = {
203
mountImages,
204
removedNodes,
205
transaction,
198
- context
206
+ context,
207
) {
208
var nextChildren;
209
var selfDebugID = 0;
@@ -204,7 +212,10 @@ var ReactMultiChild = {
212
if (this._currentElement) {
213
try {
214
ReactCurrentOwner.current = this._currentElement._owner;
207
- nextChildren = flattenChildren(nextNestedChildrenElements, selfDebugID);
215
+ nextChildren = flattenChildren(
216
+ nextNestedChildrenElements,
217
+ selfDebugID,
218
+ );
219
} finally {
220
ReactCurrentOwner.current = null;
221
}
@@ -217,7 +228,7 @@ var ReactMultiChild = {
228
this,
229
this._hostContainerInfo,
230
context,
220
- selfDebugID
231
+ selfDebugID,
232
);
233
return nextChildren;
234
}
@@ -232,7 +243,7 @@ var ReactMultiChild = {
243
this,
244
this._hostContainerInfo,
245
context,
235
- selfDebugID
246
+ selfDebugID,
247
);
248
return nextChildren;
249
},
@@ -247,7 +258,9 @@ var ReactMultiChild = {
258
*/
259
mountChildren: function(nestedChildren, transaction, context) {
260
var children = this._reconcilerInstantiateChildren(
250
- nestedChildren, transaction, context
261
+ nestedChildren,
262
+ transaction,
263
+ context,
264
);
265
this._renderedChildren = children;
266
@@ -266,7 +279,7 @@ var ReactMultiChild = {
279
this,
280
this._hostContainerInfo,
281
context,
269
- selfDebugID
282
+ selfDebugID,
283
);
284
child._mountIndex = index++;
285
mountImages.push(mountImage);
@@ -291,8 +304,8 @@ var ReactMultiChild = {
304
// Remove any rendered children.
305
ReactChildReconciler.unmountChildren(
306
prevChildren,
294
- false, /* safely */
295
- false /* skipLifecycle */
307
+ false /* safely */,
308
+ false /* skipLifecycle */,
309
);
310
for (var name in prevChildren) {
311
if (prevChildren.hasOwnProperty(name)) {
@@ -315,8 +328,8 @@ var ReactMultiChild = {
328
// Remove any rendered children.
329
ReactChildReconciler.unmountChildren(
330
prevChildren,
318
- false, /* safely */
319
- false /* skipLifecycle */
331
+ false /* safely */,
332
+ false /* skipLifecycle */,
333
);
334
for (var name in prevChildren) {
335
if (prevChildren.hasOwnProperty(name)) {
@@ -355,7 +368,7 @@ var ReactMultiChild = {
368
mountImages,
369
removedNodes,
370
transaction,
358
- context
371
+ context,
372
);
373
if (!nextChildren && !prevChildren) {
374
return;
@@ -378,7 +391,7 @@ var ReactMultiChild = {
391
if (prevChild === nextChild) {
392
updates = enqueue(
393
updates,
381
- this.moveChild(prevChild, lastPlacedNode, nextIndex, lastIndex)
394
+ this.moveChild(prevChild, lastPlacedNode, nextIndex, lastIndex),
395
);
396
lastIndex = Math.max(prevChild._mountIndex, lastIndex);
397
prevChild._mountIndex = nextIndex;
@@ -397,8 +410,8 @@ var ReactMultiChild = {
410
lastPlacedNode,
411
nextIndex,
412
transaction,
400
- context
401
- )
413
+ context,
414
+ ),
415
);
416
nextMountIndex++;
417
}
@@ -410,7 +423,7 @@ var ReactMultiChild = {
423
if (removedNodes.hasOwnProperty(name)) {
424
updates = enqueue(
425
updates,
413
- this._unmountChild(prevChildren[name], removedNodes[name])
426
+ this._unmountChild(prevChildren[name], removedNodes[name]),
427
);
428
}
429
}
@@ -436,7 +449,7 @@ var ReactMultiChild = {
449
ReactChildReconciler.unmountChildren(
450
renderedChildren,
451
safely,
439
- skipLifecycle
452
+ skipLifecycle,
453
);
454
this._renderedChildren = null;
455
},
@@ -496,7 +509,8 @@ var ReactMultiChild = {
509
afterNode,
510
index,
511
transaction,
499
- context) {
512
+ context,
513
+ ) {
514
child._mountIndex = index;
515
return this.createChild(child, afterNode, mountImage);
516
},
src/renderers/shared/stack/reconciler/ReactMultiChildUpdateTypes.js
+5
-5
@@ -18,8 +18,8 @@
18
* Enumerates all the possible types of update configurations.
19
*/
20
export type ReactMultiChildUpdateTypes =
21
- 'INSERT_MARKUP' |
22
- 'MOVE_EXISTING' |
23
- 'REMOVE_NODE' |
24
- 'SET_MARKUP' |
25
- 'TEXT_CONTENT';
21
+ | 'INSERT_MARKUP'
22
+ | 'MOVE_EXISTING'
23
+ | 'REMOVE_NODE'
24
+ | 'SET_MARKUP'
25
+ | 'TEXT_CONTENT';
src/renderers/shared/stack/reconciler/ReactOwner.js
+22
-22
@@ -12,13 +12,13 @@
12
13
'use strict';
14
15
-var { ClassComponent } = require('ReactTypeOfWork');
15
+var {ClassComponent} = require('ReactTypeOfWork');
16
17
var emptyObject = require('fbjs/lib/emptyObject');
18
var invariant = require('fbjs/lib/invariant');
19
20
-import type { Fiber } from 'ReactFiber';
21
-import type { ReactInstance } from 'ReactInstanceType';
20
+import type {Fiber} from 'ReactFiber';
21
+import type {ReactInstance} from 'ReactInstanceType';
22
23
/**
24
* @param {?object} object
@@ -26,11 +26,9 @@ import type { ReactInstance } from 'ReactInstanceType';
26
* @final
27
*/
28
function isValidOwner(object: any): boolean {
29
- return !!(
30
- object &&
29
+ return !!(object &&
30
typeof object.attachRef === 'function' &&
32
- typeof object.detachRef === 'function'
33
- );
31
+ typeof object.detachRef === 'function');
32
}
33
34
/**
@@ -78,19 +76,19 @@ var ReactOwner = {
76
ref: string,
77
owner: ReactInstance | Fiber,
78
): void {
81
- if (owner && (owner : any).tag === ClassComponent) {
82
- const inst = (owner : any).stateNode;
79
+ if (owner && (owner: any).tag === ClassComponent) {
80
+ const inst = (owner: any).stateNode;
81
const refs = inst.refs === emptyObject ? (inst.refs = {}) : inst.refs;
82
refs[ref] = component.getPublicInstance();
83
} else {
84
invariant(
85
isValidOwner(owner),
86
'addComponentAsRefTo(...): Only a ReactOwner can have refs. You might ' +
89
- 'be adding a ref to a component that was not created inside a component\'s ' +
90
- '`render` method, or you have multiple copies of React loaded ' +
91
- '(details: https://fb.me/react-refs-must-have-owner).'
87
+ "be adding a ref to a component that was not created inside a component's " +
88
+ '`render` method, or you have multiple copies of React loaded ' +
89
+ '(details: https://fb.me/react-refs-must-have-owner).',
90
);
93
- (owner : any).attachRef(ref, component);
91
+ (owner: any).attachRef(ref, component);
92
}
93
},
94
@@ -108,8 +106,8 @@ var ReactOwner = {
106
ref: string,
107
owner: ReactInstance | Fiber,
108
): void {
111
- if (owner && (owner : any).tag === ClassComponent) {
112
- const inst = (owner : any).stateNode;
109
+ if (owner && (owner: any).tag === ClassComponent) {
110
+ const inst = (owner: any).stateNode;
111
if (inst && inst.refs[ref] === component.getPublicInstance()) {
112
delete inst.refs[ref];
113
}
@@ -117,19 +115,21 @@ var ReactOwner = {
115
invariant(
116
isValidOwner(owner),
117
'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. You might ' +
120
- 'be removing a ref to a component that was not created inside a component\'s ' +
121
- '`render` method, or you have multiple copies of React loaded ' +
122
- '(details: https://fb.me/react-refs-must-have-owner).'
118
+ "be removing a ref to a component that was not created inside a component's " +
119
+ '`render` method, or you have multiple copies of React loaded ' +
120
+ '(details: https://fb.me/react-refs-must-have-owner).',
121
);
124
- var ownerPublicInstance = (owner : any).getPublicInstance();
122
+ var ownerPublicInstance = (owner: any).getPublicInstance();
123
// Check that `component`'s owner is still alive and that `component` is still the current ref
124
// because we do not want to detach the ref if another component stole it.
127
- if (ownerPublicInstance && ownerPublicInstance.refs[ref] === component.getPublicInstance()) {
128
- (owner : any).detachRef(ref);
125
+ if (
126
+ ownerPublicInstance &&
127
+ ownerPublicInstance.refs[ref] === component.getPublicInstance()
128
+ ) {
129
+ (owner: any).detachRef(ref);
130
}
131
}
132
},
132
-
133
};
134
135
module.exports = ReactOwner;
src/renderers/shared/stack/reconciler/ReactReconciler.js
+29
-29
@@ -25,7 +25,6 @@ function attachRefs() {
25
}
26
27
var ReactReconciler = {
28
-
28
/**
29
* Initializes the component, renders markup, and registers event listeners.
30
*
@@ -43,14 +42,14 @@ var ReactReconciler = {
42
hostParent,
43
hostContainerInfo,
44
context,
46
- parentDebugID // 0 in production and for roots
45
+ parentDebugID, // 0 in production and for roots
46
) {
47
if (__DEV__) {
48
if (internalInstance._debugID !== 0) {
49
ReactInstrumentation.debugTool.onBeforeMountComponent(
50
internalInstance._debugID,
51
internalInstance._currentElement,
53
- parentDebugID
52
+ parentDebugID,
53
);
54
}
55
}
@@ -59,16 +58,18 @@ var ReactReconciler = {
58
hostParent,
59
hostContainerInfo,
60
context,
62
- parentDebugID
61
+ parentDebugID,
62
);
64
- if (internalInstance._currentElement &&
65
- internalInstance._currentElement.ref != null) {
63
+ if (
64
+ internalInstance._currentElement &&
65
+ internalInstance._currentElement.ref != null
66
+ ) {
67
transaction.getReactMountReady().enqueue(attachRefs, internalInstance);
68
}
69
if (__DEV__) {
70
if (internalInstance._debugID !== 0) {
71
ReactInstrumentation.debugTool.onMountComponent(
71
- internalInstance._debugID
72
+ internalInstance._debugID,
73
);
74
}
75
}
@@ -93,7 +94,7 @@ var ReactReconciler = {
94
if (__DEV__) {
95
if (internalInstance._debugID !== 0) {
96
ReactInstrumentation.debugTool.onBeforeUnmountComponent(
96
- internalInstance._debugID
97
+ internalInstance._debugID,
98
);
99
}
100
}
@@ -102,7 +103,7 @@ var ReactReconciler = {
103
if (__DEV__) {
104
if (internalInstance._debugID !== 0) {
105
ReactInstrumentation.debugTool.onUnmountComponent(
105
- internalInstance._debugID
106
+ internalInstance._debugID,
107
);
108
}
109
}
@@ -118,13 +119,14 @@ var ReactReconciler = {
119
* @internal
120
*/
121
receiveComponent: function(
121
- internalInstance, nextElement, transaction, context
122
+ internalInstance,
123
+ nextElement,
124
+ transaction,
125
+ context,
126
) {
127
var prevElement = internalInstance._currentElement;
128
125
- if (nextElement === prevElement &&
126
- context === internalInstance._context
127
- ) {
129
+ if (nextElement === prevElement && context === internalInstance._context) {
130
// Since elements are immutable after the owner is rendered,
131
// we can do a cheap identity compare here to determine if this is a
132
// superfluous reconcile. It's possible for state to be mutable but such
@@ -142,15 +144,12 @@ var ReactReconciler = {
144
if (internalInstance._debugID !== 0) {
145
ReactInstrumentation.debugTool.onBeforeUpdateComponent(
146
internalInstance._debugID,
145
- nextElement
147
+ nextElement,
148
);
149
}
150
}
151
150
- var refsChanged = ReactRef.shouldUpdateRefs(
151
- prevElement,
152
- nextElement
153
- );
152
+ var refsChanged = ReactRef.shouldUpdateRefs(prevElement, nextElement);
153
154
if (refsChanged) {
155
ReactRef.detachRefs(internalInstance, prevElement);
@@ -158,16 +157,18 @@ var ReactReconciler = {
157
158
internalInstance.receiveComponent(nextElement, transaction, context);
159
161
- if (refsChanged &&
162
- internalInstance._currentElement &&
163
- internalInstance._currentElement.ref != null) {
160
+ if (
161
+ refsChanged &&
162
+ internalInstance._currentElement &&
163
+ internalInstance._currentElement.ref != null
164
+ ) {
165
transaction.getReactMountReady().enqueue(attachRefs, internalInstance);
166
}
167
168
if (__DEV__) {
169
if (internalInstance._debugID !== 0) {
170
ReactInstrumentation.debugTool.onUpdateComponent(
170
- internalInstance._debugID
171
+ internalInstance._debugID,
172
);
173
}
174
}
@@ -183,18 +184,18 @@ var ReactReconciler = {
184
performUpdateIfNecessary: function(
185
internalInstance,
186
transaction,
186
- updateBatchNumber
187
+ updateBatchNumber,
188
) {
189
if (internalInstance._updateBatchNumber !== updateBatchNumber) {
190
// The component's enqueued batch number should always be the current
191
// batch or the following one.
192
warning(
193
internalInstance._updateBatchNumber == null ||
193
- internalInstance._updateBatchNumber === updateBatchNumber + 1,
194
+ internalInstance._updateBatchNumber === updateBatchNumber + 1,
195
'performUpdateIfNecessary: Unexpected batch number (current %s, ' +
195
- 'pending %s)',
196
+ 'pending %s)',
197
updateBatchNumber,
197
- internalInstance._updateBatchNumber
198
+ internalInstance._updateBatchNumber,
199
);
200
return;
201
}
@@ -202,7 +203,7 @@ var ReactReconciler = {
203
if (internalInstance._debugID !== 0) {
204
ReactInstrumentation.debugTool.onBeforeUpdateComponent(
205
internalInstance._debugID,
205
- internalInstance._currentElement
206
+ internalInstance._currentElement,
207
);
208
}
209
}
@@ -210,12 +211,11 @@ var ReactReconciler = {
211
if (__DEV__) {
212
if (internalInstance._debugID !== 0) {
213
ReactInstrumentation.debugTool.onUpdateComponent(
213
- internalInstance._debugID
214
+ internalInstance._debugID,
215
);
216
}
217
}
218
},
218
-
219
};
220
221
module.exports = ReactReconciler;
src/renderers/shared/stack/reconciler/ReactRef.js
+14
-15
@@ -14,8 +14,8 @@
14
15
var ReactOwner = require('ReactOwner');
16
17
-import type { ReactInstance } from 'ReactInstanceType';
18
-import type { ReactElement } from 'ReactElementType';
17
+import type {ReactInstance} from 'ReactInstanceType';
18
+import type {ReactElement} from 'ReactElementType';
19
20
var ReactRef = {};
21
@@ -29,7 +29,10 @@ if (__DEV__) {
29
30
function attachRef(ref, component, owner) {
31
if (__DEV__) {
32
- if (component._compositeType === ReactCompositeComponentTypes.StatelessFunctional) {
32
+ if (
33
+ component._compositeType ===
34
+ ReactCompositeComponentTypes.StatelessFunctional
35
+ ) {
36
let info = '';
37
let ownerName;
38
if (owner) {
@@ -44,16 +47,18 @@ function attachRef(ref, component, owner) {
47
let warningKey = ownerName || component._debugID;
48
let element = component._currentElement;
49
if (element && element._source) {
47
- warningKey = element._source.fileName + ':' + element._source.lineNumber;
50
+ warningKey = element._source.fileName +
51
+ ':' +
52
+ element._source.lineNumber;
53
}
54
if (!warnedAboutStatelessRefs[warningKey]) {
55
warnedAboutStatelessRefs[warningKey] = true;
56
warning(
57
false,
58
'Stateless function components cannot be given refs. ' +
54
- 'Attempts to access this ref will fail.%s%s',
59
+ 'Attempts to access this ref will fail.%s%s',
60
info,
56
- ReactComponentTreeHook.getStackAddendumByID(component._debugID)
61
+ ReactComponentTreeHook.getStackAddendumByID(component._debugID),
62
);
63
}
64
}
@@ -63,11 +68,7 @@ function attachRef(ref, component, owner) {
68
ref(component.getPublicInstance());
69
} else {
70
// Legacy ref
66
- ReactOwner.addComponentAsRefTo(
67
- component,
68
- ref,
69
- owner,
70
- );
71
+ ReactOwner.addComponentAsRefTo(component, ref, owner);
72
}
73
}
74
@@ -123,11 +124,9 @@ ReactRef.shouldUpdateRefs = function(
124
nextOwner = nextElement._owner;
125
}
126
126
- return (
127
- prevRef !== nextRef ||
127
+ return prevRef !== nextRef ||
128
// If owner changes but we have an unchanged function ref, don't update refs
129
- (typeof nextRef === 'string' && nextOwner !== prevOwner)
130
- );
129
+ (typeof nextRef === 'string' && nextOwner !== prevOwner);
130
};
131
132
ReactRef.detachRefs = function(
src/renderers/shared/stack/reconciler/ReactSimpleEmptyComponent.js
+4
-6
@@ -13,7 +13,6 @@
13
14
var ReactReconciler = require('ReactReconciler');
15
16
-
16
var ReactSimpleEmptyComponent = function(placeholderElement, instantiate) {
17
this._currentElement = null;
18
this._renderedComponent = instantiate(placeholderElement);
@@ -24,7 +23,7 @@ Object.assign(ReactSimpleEmptyComponent.prototype, {
23
hostParent,
24
hostContainerInfo,
25
context,
27
- parentDebugID // 0 in production and for roots
26
+ parentDebugID, // 0 in production and for roots
27
) {
28
return ReactReconciler.mountComponent(
29
this._renderedComponent,
@@ -32,11 +31,10 @@ Object.assign(ReactSimpleEmptyComponent.prototype, {
31
hostParent,
32
hostContainerInfo,
33
context,
35
- parentDebugID
34
+ parentDebugID,
35
);
36
},
38
- receiveComponent: function() {
39
- },
37
+ receiveComponent: function() {},
38
getHostNode: function() {
39
return ReactReconciler.getHostNode(this._renderedComponent);
40
},
@@ -44,7 +42,7 @@ Object.assign(ReactSimpleEmptyComponent.prototype, {
42
ReactReconciler.unmountComponent(
43
this._renderedComponent,
44
safely,
47
- skipLifecycle
45
+ skipLifecycle,
46
);
47
this._renderedComponent = null;
48
},
src/renderers/shared/stack/reconciler/ReactUpdateQueue.js
+29
-22
@@ -18,13 +18,13 @@ var ReactUpdates = require('ReactUpdates');
18
19
if (__DEV__) {
20
var warning = require('fbjs/lib/warning');
21
- var warnOnInvalidCallback = function(callback : mixed, callerName : string) {
21
+ var warnOnInvalidCallback = function(callback: mixed, callerName: string) {
22
warning(
23
callback === null || typeof callback === 'function',
24
'%s(...): Expected the last optional `callback` argument to be a ' +
25
- 'function. Instead received: %s.',
25
+ 'function. Instead received: %s.',
26
callerName,
27
- '' + callback
27
+ '' + callback,
28
);
29
};
30
}
@@ -41,10 +41,10 @@ function getInternalInstanceReadyForUpdate(publicInstance, callerName) {
41
warning(
42
false,
43
'Can only update a mounted or mounting component. This usually means ' +
44
- 'you called setState, replaceState, or forceUpdate on an unmounted ' +
45
- 'component. This is a no-op.\n\nPlease check the code for the ' +
46
- '%s component.',
47
- ctor && (ctor.displayName || ctor.name) || 'ReactClass'
44
+ 'you called setState, replaceState, or forceUpdate on an unmounted ' +
45
+ 'component. This is a no-op.\n\nPlease check the code for the ' +
46
+ '%s component.',
47
+ (ctor && (ctor.displayName || ctor.name)) || 'ReactClass',
48
);
49
}
50
return null;
@@ -54,9 +54,9 @@ function getInternalInstanceReadyForUpdate(publicInstance, callerName) {
54
warning(
55
ReactCurrentOwner.current == null,
56
'Cannot update during an existing state transition (such as within ' +
57
- '`render` or another component\'s constructor). Render methods should ' +
58
- 'be a pure function of props and state; constructor side-effects are ' +
59
- 'an anti-pattern, but can be moved to `componentWillMount`.',
57
+ "`render` or another component's constructor). Render methods should " +
58
+ 'be a pure function of props and state; constructor side-effects are ' +
59
+ 'an anti-pattern, but can be moved to `componentWillMount`.',
60
);
61
}
62
@@ -68,7 +68,6 @@ function getInternalInstanceReadyForUpdate(publicInstance, callerName) {
68
* reconciliation step.
69
*/
70
var ReactUpdateQueue = {
71
-
71
/**
72
* Checks whether or not this composite component is mounted.
73
* @param {ReactClass} publicInstance The instance we want to test.
@@ -83,11 +82,11 @@ var ReactUpdateQueue = {
82
warning(
83
owner._warnedAboutRefsInRender,
84
'%s is accessing isMounted inside its render() function. ' +
86
- 'render() should be a pure function of props and state. It should ' +
87
- 'never access something that requires stale data from the previous ' +
88
- 'render, such as refs. Move this logic to componentDidMount and ' +
89
- 'componentDidUpdate instead.',
90
- owner.getName() || 'A component'
85
+ 'render() should be a pure function of props and state. It should ' +
86
+ 'never access something that requires stale data from the previous ' +
87
+ 'render, such as refs. Move this logic to componentDidMount and ' +
88
+ 'componentDidUpdate instead.',
89
+ owner.getName() || 'A component',
90
);
91
owner._warnedAboutRefsInRender = true;
92
}
@@ -164,7 +163,12 @@ var ReactUpdateQueue = {
163
* @param {?string} Name of the calling function in the public API.
164
* @internal
165
*/
167
- enqueueReplaceState: function(publicInstance, completeState, callback, callerName) {
166
+ enqueueReplaceState: function(
167
+ publicInstance,
168
+ completeState,
169
+ callback,
170
+ callerName,
171
+ ) {
172
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance);
173
174
if (!internalInstance) {
@@ -201,13 +205,18 @@ var ReactUpdateQueue = {
205
* @param {?string} Name of the calling function in the public API.
206
* @internal
207
*/
204
- enqueueSetState: function(publicInstance, partialState, callback, callerName) {
208
+ enqueueSetState: function(
209
+ publicInstance,
210
+ partialState,
211
+ callback,
212
+ callerName,
213
+ ) {
214
if (__DEV__) {
215
ReactInstrumentation.debugTool.onSetState();
216
warning(
217
partialState != null,
218
'setState(...): You passed an undefined or null state object; ' +
210
- 'instead, use forceUpdate().'
219
+ 'instead, use forceUpdate().',
220
);
221
}
222
@@ -217,8 +226,7 @@ var ReactUpdateQueue = {
226
return;
227
}
228
220
- var queue =
221
- internalInstance._pendingStateQueue ||
229
+ var queue = internalInstance._pendingStateQueue ||
230
(internalInstance._pendingStateQueue = []);
231
queue.push(partialState);
232
@@ -243,7 +251,6 @@ var ReactUpdateQueue = {
251
internalInstance._context = nextContext;
252
enqueueUpdate(internalInstance);
253
},
246
-
254
};
255
256
module.exports = ReactUpdateQueue;
src/renderers/shared/stack/reconciler/ReactUpdates.js
+34
-38
@@ -27,7 +27,7 @@ function ensureInjected() {
27
invariant(
28
ReactUpdates.ReactReconcileTransaction && batchingStrategy,
29
'ReactUpdates: must inject a reconcile transaction class and batching ' +
30
- 'strategy'
30
+ 'strategy',
31
);
32
}
33
@@ -56,38 +56,34 @@ function ReactUpdatesFlushTransaction() {
56
this.reinitializeTransaction();
57
this.dirtyComponentsLength = null;
58
this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled(
59
- /* useCreateElement */ true
59
+ /* useCreateElement */ true,
60
);
61
}
62
63
-Object.assign(
64
- ReactUpdatesFlushTransaction.prototype,
65
- Transaction,
66
- {
67
- getTransactionWrappers: function() {
68
- return TRANSACTION_WRAPPERS;
69
- },
70
-
71
- destructor: function() {
72
- this.dirtyComponentsLength = null;
73
- ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction);
74
- this.reconcileTransaction = null;
75
- },
76
-
77
- perform: function(method, scope, a) {
78
- // Essentially calls `this.reconcileTransaction.perform(method, scope, a)`
79
- // with this transaction's wrappers around it.
80
- return Transaction.perform.call(
81
- this,
82
- this.reconcileTransaction.perform,
83
- this.reconcileTransaction,
84
- method,
85
- scope,
86
- a
87
- );
88
- },
89
- }
90
-);
63
+Object.assign(ReactUpdatesFlushTransaction.prototype, Transaction, {
64
+ getTransactionWrappers: function() {
65
+ return TRANSACTION_WRAPPERS;
66
+ },
67
+
68
+ destructor: function() {
69
+ this.dirtyComponentsLength = null;
70
+ ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction);
71
+ this.reconcileTransaction = null;
72
+ },
73
+
74
+ perform: function(method, scope, a) {
75
+ // Essentially calls `this.reconcileTransaction.perform(method, scope, a)`
76
+ // with this transaction's wrappers around it.
77
+ return Transaction.perform.call(
78
+ this,
79
+ this.reconcileTransaction.perform,
80
+ this.reconcileTransaction,
81
+ method,
82
+ scope,
83
+ a,
84
+ );
85
+ },
86
+});
87
88
PooledClass.addPoolingTo(ReactUpdatesFlushTransaction);
89
@@ -111,10 +107,10 @@ function runBatchedUpdates(transaction) {
107
var len = transaction.dirtyComponentsLength;
108
invariant(
109
len === dirtyComponents.length,
114
- 'Expected flush transaction\'s stored dirty-components length (%s) to ' +
115
- 'match dirty-components array length (%s).',
110
+ "Expected flush transaction's stored dirty-components length (%s) to " +
111
+ 'match dirty-components array length (%s).',
112
len,
117
- dirtyComponents.length
113
+ dirtyComponents.length,
114
);
115
116
// Since reconciling a component higher in the owner hierarchy usually (not
@@ -149,7 +145,7 @@ function runBatchedUpdates(transaction) {
145
ReactReconciler.performUpdateIfNecessary(
146
component,
147
transaction.reconcileTransaction,
152
- updateBatchNumber
148
+ updateBatchNumber,
149
);
150
151
if (markerName) {
@@ -198,7 +194,7 @@ var ReactUpdatesInjection = {
194
injectReconcileTransaction: function(ReconcileTransaction) {
195
invariant(
196
ReconcileTransaction,
201
- 'ReactUpdates: must provide a reconcile transaction class'
197
+ 'ReactUpdates: must provide a reconcile transaction class',
198
);
199
ReactUpdates.ReactReconcileTransaction = ReconcileTransaction;
200
},
@@ -206,15 +202,15 @@ var ReactUpdatesInjection = {
202
injectBatchingStrategy: function(_batchingStrategy) {
203
invariant(
204
_batchingStrategy,
209
- 'ReactUpdates: must provide a batching strategy'
205
+ 'ReactUpdates: must provide a batching strategy',
206
);
207
invariant(
208
typeof _batchingStrategy.batchedUpdates === 'function',
213
- 'ReactUpdates: must provide a batchedUpdates() function'
209
+ 'ReactUpdates: must provide a batchedUpdates() function',
210
);
211
invariant(
212
typeof _batchingStrategy.isBatchingUpdates === 'boolean',
217
- 'ReactUpdates: must provide an isBatchingUpdates boolean attribute'
213
+ 'ReactUpdates: must provide an isBatchingUpdates boolean attribute',
214
);
215
batchingStrategy = _batchingStrategy;
216
},
src/renderers/shared/stack/reconciler/Transaction.js
+16
-18
@@ -124,17 +124,18 @@ var TransactionImpl = {
124
*
125
* @return {*} Return value from `method`.
126
*/
127
- perform: function<
128
- A, B, C, D, E, F, G,
129
- T: (a: A, b: B, c: C, d: D, e: E, f: F) => G // eslint-disable-line space-before-function-paren
130
- >(
131
- method: T, scope: any,
132
- a: A, b: B, c: C, d: D, e: E, f: F,
133
- ): G {
127
+ perform: function<A, B, C, D, E, F, G, T: (
128
+ a: A,
129
+ b: B,
130
+ c: C,
131
+ d: D,
132
+ e: E,
133
+ f: F,
134
+ ) => G>(method: T, scope: any, a: A, b: B, c: C, d: D, e: E, f: F): G { // eslint-disable-line space-before-function-paren
135
invariant(
136
!this.isInTransaction(),
137
'Transaction.perform(...): Cannot initialize a transaction when there ' +
137
- 'is already an outstanding transaction.'
138
+ 'is already an outstanding transaction.',
139
);
140
var errorThrown;
141
var ret;
@@ -155,8 +156,7 @@ var TransactionImpl = {
156
// by invoking `closeAll`.
157
try {
158
this.closeAll(0);
158
- } catch (err) {
159
- }
159
+ } catch (err) {}
160
} else {
161
// Since `method` didn't throw, we don't want to silence the exception
162
// here.
@@ -179,9 +179,9 @@ var TransactionImpl = {
179
// of initialize -- if it's still set to OBSERVED_ERROR in the finally
180
// block, it means wrapper.initialize threw.
181
this.wrapperInitData[i] = OBSERVED_ERROR;
182
- this.wrapperInitData[i] = wrapper.initialize ?
183
- wrapper.initialize.call(this) :
184
- null;
182
+ this.wrapperInitData[i] = wrapper.initialize
183
+ ? wrapper.initialize.call(this)
184
+ : null;
185
} finally {
186
if (this.wrapperInitData[i] === OBSERVED_ERROR) {
187
// The initializer for wrapper i threw an error; initialize the
@@ -189,8 +189,7 @@ var TransactionImpl = {
189
// that the first error is the one to bubble up.
190
try {
191
this.initializeAll(i + 1);
192
- } catch (err) {
193
- }
192
+ } catch (err) {}
193
}
194
}
195
}
@@ -205,7 +204,7 @@ var TransactionImpl = {
204
closeAll: function(startIndex: number): void {
205
invariant(
206
this.isInTransaction(),
208
- 'Transaction.closeAll(): Cannot close transaction when none are open.'
207
+ 'Transaction.closeAll(): Cannot close transaction when none are open.',
208
);
209
var transactionWrappers = this.transactionWrappers;
210
for (var i = startIndex; i < transactionWrappers.length; i++) {
@@ -229,8 +228,7 @@ var TransactionImpl = {
228
// first error is the one to bubble up.
229
try {
230
this.closeAll(i + 1);
232
- } catch (e) {
233
- }
231
+ } catch (e) {}
232
}
233
}
234
}
src/renderers/shared/stack/reconciler/__tests__/Transaction-test.js
+23
-24
@@ -11,10 +11,9 @@
11
12
'use strict';
13
14
-
14
var Transaction;
15
17
-var INIT_ERRORED = 'initErrored'; // Just a dummy value to check for.
16
+var INIT_ERRORED = 'initErrored'; // Just a dummy value to check for.
17
describe('Transaction', () => {
18
beforeEach(() => {
19
jest.resetModules();
@@ -41,9 +40,9 @@ describe('Transaction', () => {
40
*/
41
var TestTransaction = function() {
42
this.reinitializeTransaction();
44
- this.firstCloseParam = INIT_ERRORED; // WON'T be set to something else
45
- this.secondCloseParam = INIT_ERRORED; // WILL be set to something else
46
- this.lastCloseParam = INIT_ERRORED; // WON'T be set to something else
43
+ this.firstCloseParam = INIT_ERRORED; // WON'T be set to something else
44
+ this.secondCloseParam = INIT_ERRORED; // WILL be set to something else
45
+ this.lastCloseParam = INIT_ERRORED; // WON'T be set to something else
46
};
47
Object.assign(TestTransaction.prototype, Transaction);
48
TestTransaction.prototype.getTransactionWrappers = function() {
@@ -85,16 +84,15 @@ describe('Transaction', () => {
84
});
85
86
it('should invoke closers and wrapped method when inits success', () => {
88
-
87
var performSideEffect;
88
/**
89
* New test Transaction subclass.
90
*/
91
var TestTransaction = function() {
92
this.reinitializeTransaction();
95
- this.firstCloseParam = INIT_ERRORED; // WILL be set to something else
96
- this.secondCloseParam = INIT_ERRORED; // WILL be set to something else
97
- this.lastCloseParam = INIT_ERRORED; // WILL be set to something else
93
+ this.firstCloseParam = INIT_ERRORED; // WILL be set to something else
94
+ this.secondCloseParam = INIT_ERRORED; // WILL be set to something else
95
+ this.lastCloseParam = INIT_ERRORED; // WILL be set to something else
96
};
97
Object.assign(TestTransaction.prototype, Transaction);
98
TestTransaction.prototype.getTransactionWrappers = function() {
@@ -146,16 +144,15 @@ describe('Transaction', () => {
144
* encountered earlier in the operation.
145
*/
146
it('should throw when wrapped operation throws', () => {
149
-
147
var performSideEffect;
148
/**
149
* New test Transaction subclass.
150
*/
151
var TestTransaction = function() {
152
this.reinitializeTransaction();
156
- this.firstCloseParam = INIT_ERRORED; // WILL be set to something else
157
- this.secondCloseParam = INIT_ERRORED; // WILL be set to something else
158
- this.lastCloseParam = INIT_ERRORED; // WILL be set to something else
153
+ this.firstCloseParam = INIT_ERRORED; // WILL be set to something else
154
+ this.secondCloseParam = INIT_ERRORED; // WILL be set to something else
155
+ this.lastCloseParam = INIT_ERRORED; // WILL be set to something else
156
};
157
Object.assign(TestTransaction.prototype, Transaction);
158
// Now, none of the close/inits throw, but the operation we wrap will throw.
@@ -198,17 +195,19 @@ describe('Transaction', () => {
195
196
var transaction = new TestTransaction();
197
201
- expect(function() {
202
- var isTypeError = false;
203
- try {
204
- transaction.perform(function() {
205
- throw new TypeError('Thrown in main wrapped operation');
206
- });
207
- } catch (err) {
208
- isTypeError = (err instanceof TypeError);
209
- }
210
- return isTypeError;
211
- }()).toBe(true);
198
+ expect(
199
+ (function() {
200
+ var isTypeError = false;
201
+ try {
202
+ transaction.perform(function() {
203
+ throw new TypeError('Thrown in main wrapped operation');
204
+ });
205
+ } catch (err) {
206
+ isTypeError = err instanceof TypeError;
207
+ }
208
+ return isTypeError;
209
+ })(),
210
+ ).toBe(true);
211
212
expect(performSideEffect).toBe(undefined);
213
expect(transaction.firstCloseParam).toBe('firstResult');
src/renderers/shared/stack/reconciler/instantiateReactComponent.js
+15
-25
@@ -42,12 +42,10 @@ function getDeclarationErrorAddendum(owner) {
42
* @return {boolean} Returns true if this is a valid internal type.
43
*/
44
function isInternalComponentType(type) {
45
- return (
46
- typeof type === 'function' &&
45
+ return typeof type === 'function' &&
46
typeof type.prototype !== 'undefined' &&
47
typeof type.prototype.mountComponent === 'function' &&
49
- typeof type.prototype.receiveComponent === 'function'
50
- );
48
+ typeof type.prototype.receiveComponent === 'function';
49
}
50
51
/**
@@ -66,28 +64,24 @@ function instantiateReactComponent(node, shouldHaveDebugID) {
64
} else if (typeof node === 'object') {
65
var element = node;
66
var type = element.type;
69
- if (
70
- typeof type !== 'function' &&
71
- typeof type !== 'string'
72
- ) {
67
+ if (typeof type !== 'function' && typeof type !== 'string') {
68
var info = '';
69
if (__DEV__) {
70
if (
71
type === undefined ||
77
- typeof type === 'object' &&
78
- type !== null &&
79
- Object.keys(type).length === 0
72
+ (typeof type === 'object' &&
73
+ type !== null &&
74
+ Object.keys(type).length === 0)
75
) {
81
- info +=
82
- ' You likely forgot to export your component from the file ' +
83
- 'it\'s defined in.';
76
+ info += ' You likely forgot to export your component from the file ' +
77
+ "it's defined in.";
78
}
79
}
80
info += getDeclarationErrorAddendum(element._owner);
81
invariant(
82
false,
83
'Element type is invalid: expected a string (for built-in components) ' +
90
- 'or a class/function (for composite components) but got: %s.%s',
84
+ 'or a class/function (for composite components) but got: %s.%s',
85
type == null ? type : typeof type,
86
info,
87
);
@@ -112,20 +106,16 @@ function instantiateReactComponent(node, shouldHaveDebugID) {
106
} else if (typeof node === 'string' || typeof node === 'number') {
107
instance = ReactHostComponent.createInstanceForText(node);
108
} else {
115
- invariant(
116
- false,
117
- 'Encountered invalid React node of type %s',
118
- typeof node
119
- );
109
+ invariant(false, 'Encountered invalid React node of type %s', typeof node);
110
}
111
112
if (__DEV__) {
113
warning(
114
typeof instance.mountComponent === 'function' &&
125
- typeof instance.receiveComponent === 'function' &&
126
- typeof instance.getHostNode === 'function' &&
127
- typeof instance.unmountComponent === 'function',
128
- 'Only React Components can be mounted.'
115
+ typeof instance.receiveComponent === 'function' &&
116
+ typeof instance.getHostNode === 'function' &&
117
+ typeof instance.unmountComponent === 'function',
118
+ 'Only React Components can be mounted.',
119
);
120
}
121
@@ -155,7 +145,7 @@ Object.assign(
145
ReactCompositeComponent,
146
{
147
_instantiateReactComponent: instantiateReactComponent,
158
- }
148
+ },
149
);
150
151
module.exports = instantiateReactComponent;
src/renderers/shared/utils/ReactErrorUtils.js
+8
-7
@@ -1,4 +1,4 @@
1
- /**
1
+/**
2
* Copyright 2013-present, Facebook, Inc.
3
* All rights reserved.
4
*
@@ -88,11 +88,12 @@ if (__DEV__) {
88
* To help development we can get better devtools integration by simulating a
89
* real browser event.
90
*/
91
- if (typeof window !== 'undefined' &&
92
- typeof window.dispatchEvent === 'function' &&
93
- typeof document !== 'undefined' &&
94
- typeof document.createEvent === 'function') {
95
-
91
+ if (
92
+ typeof window !== 'undefined' &&
93
+ typeof window.dispatchEvent === 'function' &&
94
+ typeof document !== 'undefined' &&
95
+ typeof document.createEvent === 'function'
96
+ ) {
97
const fakeNode = document.createElement('react');
98
let depth = 0;
99
@@ -105,7 +106,7 @@ if (__DEV__) {
106
c,
107
d,
108
e,
108
- f
109
+ f,
110
) {
111
depth++;
112
const thisDepth = depth;
src/renderers/shared/utils/__tests__/ReactErrorUtils-test.js
+71
-24
@@ -14,13 +14,15 @@
14
var ReactErrorUtils;
15
16
describe('ReactErrorUtils', () => {
17
-
17
beforeEach(() => {
18
ReactErrorUtils = require('ReactErrorUtils');
19
});
20
21
// Run tests in both DEV and production
23
- describe('invokeGuardedCallback (development)', invokeGuardedCallbackTests.bind(null, 'development'));
22
+ describe(
23
+ 'invokeGuardedCallback (development)',
24
+ invokeGuardedCallbackTests.bind(null, 'development'),
25
+ );
26
describe('invokeGuardedCallback (production)', () => {
27
let oldProcess;
28
beforeEach(() => {
@@ -47,35 +49,59 @@ describe('ReactErrorUtils', () => {
49
var callback = function() {
50
throw err;
51
};
50
- ReactErrorUtils.invokeGuardedCallbackAndCatchFirstError('foo', callback, null);
52
+ ReactErrorUtils.invokeGuardedCallbackAndCatchFirstError(
53
+ 'foo',
54
+ callback,
55
+ null,
56
+ );
57
expect(() => ReactErrorUtils.rethrowCaughtError()).toThrow(err);
58
});
59
60
it(`should call the callback the passed arguments (${environment})`, () => {
61
var callback = jest.fn();
56
- ReactErrorUtils.invokeGuardedCallback('foo', callback, null, 'arg1', 'arg2');
62
+ ReactErrorUtils.invokeGuardedCallback(
63
+ 'foo',
64
+ callback,
65
+ null,
66
+ 'arg1',
67
+ 'arg2',
68
+ );
69
expect(callback).toBeCalledWith('arg1', 'arg2');
70
});
71
72
it(`should call the callback with the provided context (${environment})`, () => {
61
- var context = { didCall: false };
62
- ReactErrorUtils.invokeGuardedCallback('foo', function() {
63
- this.didCall = true;
64
- }, context);
73
+ var context = {didCall: false};
74
+ ReactErrorUtils.invokeGuardedCallback(
75
+ 'foo',
76
+ function() {
77
+ this.didCall = true;
78
+ },
79
+ context,
80
+ );
81
expect(context.didCall).toBe(true);
82
});
83
84
it(`should return a caught error (${environment})`, () => {
85
const error = new Error();
70
- const returnValue = ReactErrorUtils.invokeGuardedCallback('foo', function() {
71
- throw error;
72
- }, null, 'arg1', 'arg2');
86
+ const returnValue = ReactErrorUtils.invokeGuardedCallback(
87
+ 'foo',
88
+ function() {
89
+ throw error;
90
+ },
91
+ null,
92
+ 'arg1',
93
+ 'arg2',
94
+ );
95
expect(returnValue).toBe(error);
96
});
97
98
it(`should return null if no error is thrown (${environment})`, () => {
99
var callback = jest.fn();
78
- const returnValue = ReactErrorUtils.invokeGuardedCallback('foo', callback, null);
100
+ const returnValue = ReactErrorUtils.invokeGuardedCallback(
101
+ 'foo',
102
+ callback,
103
+ null,
104
+ );
105
expect(returnValue).toBe(null);
106
});
107
@@ -83,12 +109,20 @@ describe('ReactErrorUtils', () => {
109
const err1 = new Error();
110
let err2;
111
const err3 = new Error();
86
- const err4 = ReactErrorUtils.invokeGuardedCallback('foo', function() {
87
- err2 = ReactErrorUtils.invokeGuardedCallback('foo', function() {
88
- throw err1;
89
- }, null);
90
- throw err3;
91
- }, null);
112
+ const err4 = ReactErrorUtils.invokeGuardedCallback(
113
+ 'foo',
114
+ function() {
115
+ err2 = ReactErrorUtils.invokeGuardedCallback(
116
+ 'foo',
117
+ function() {
118
+ throw err1;
119
+ },
120
+ null,
121
+ );
122
+ throw err3;
123
+ },
124
+ null,
125
+ );
126
127
expect(err2).toBe(err1);
128
expect(err4).toBe(err3);
@@ -97,11 +131,19 @@ describe('ReactErrorUtils', () => {
131
it(`does not return nested errors (${environment})`, () => {
132
const err1 = new Error();
133
let err2;
100
- const err3 = ReactErrorUtils.invokeGuardedCallback('foo', function() {
101
- err2 = ReactErrorUtils.invokeGuardedCallback('foo', function() {
102
- throw err1;
103
- }, null);
104
- }, null);
134
+ const err3 = ReactErrorUtils.invokeGuardedCallback(
135
+ 'foo',
136
+ function() {
137
+ err2 = ReactErrorUtils.invokeGuardedCallback(
138
+ 'foo',
139
+ function() {
140
+ throw err1;
141
+ },
142
+ null,
143
+ );
144
+ },
145
+ null,
146
+ );
147
148
expect(err3).toBe(null); // Returns null because inner error was already captured
149
expect(err2).toBe(err1);
@@ -124,7 +166,12 @@ describe('ReactErrorUtils', () => {
166
var callback = function() {
167
throw err;
168
};
127
- ReactErrorUtils.invokeGuardedCallbackAndCatchFirstError('foo', callback, null, 'somearg');
169
+ ReactErrorUtils.invokeGuardedCallbackAndCatchFirstError(
170
+ 'foo',
171
+ callback,
172
+ null,
173
+ 'somearg',
174
+ );
175
expect(() => ReactErrorUtils.rethrowCaughtError()).toThrow(err);
176
// invokeGuardedCallbackAndCatchFirstError and rethrowCaughtError close
177
// over ReactErrorUtils.invokeGuardedCallback so should use the
src/renderers/shared/utils/__tests__/accumulateInto-test.js
+1
-2
@@ -14,7 +14,6 @@
14
var accumulateInto;
15
16
describe('accumulateInto', () => {
17
-
17
beforeEach(() => {
18
accumulateInto = require('accumulateInto');
19
});
@@ -23,7 +22,7 @@ describe('accumulateInto', () => {
22
expect(function() {
23
accumulateInto([], null);
24
}).toThrowError(
26
- 'accumulateInto(...): Accumulated items must not be null or undefined.'
25
+ 'accumulateInto(...): Accumulated items must not be null or undefined.',
26
);
27
});
28
src/renderers/shared/utils/__tests__/adler32-test.js
+2
-2
@@ -26,7 +26,7 @@ describe('adler32', () => {
26
expect(adler32('a')).not.toBe(adler32('A'));
27
});
28
29
- it('doesn\'t barf on large inputs', () => {
29
+ it("doesn't barf on large inputs", () => {
30
var str = '';
31
for (var i = 0; i < 100000; i++) {
32
str += 'This will be repeated to be very large indeed. ';
@@ -34,7 +34,7 @@ describe('adler32', () => {
34
expect(adler32(str)).toBe(692898118);
35
});
36
37
- it('doesn\'t barf on international inputs', () => {
37
+ it("doesn't barf on international inputs", () => {
38
var str = 'Linux 是一個真棒操作系統!';
39
expect(adler32(str)).toBe(-1183804097);
40
});
src/renderers/shared/utils/accumulate.js
+5
-2
@@ -21,10 +21,13 @@ var invariant = require('fbjs/lib/invariant');
21
*
22
* @return {*|array<*>} An accumulation of items.
23
*/
24
-function accumulate<T>(current: ?(T | Array<T>), next: T | Array<T>): T | Array<T> {
24
+function accumulate<T>(
25
+ current: ?(T | Array<T>),
26
+ next: T | Array<T>,
27
+): T | Array<T> {
28
invariant(
29
next != null,
27
- 'accumulate(...): Accumulated items must be not be null or undefined.'
30
+ 'accumulate(...): Accumulated items must be not be null or undefined.',
31
);
32
33
if (current == null) {
src/renderers/shared/utils/accumulateInto.js
+5
-2
@@ -27,10 +27,13 @@ var invariant = require('fbjs/lib/invariant');
27
* @return {*|array<*>} An accumulation of items.
28
*/
29
30
-function accumulateInto<T>(current: ?(T | Array<T>), next: T | Array<T>): T | Array<T> {
30
+function accumulateInto<T>(
31
+ current: ?(T | Array<T>),
32
+ next: T | Array<T>,
33
+): T | Array<T> {
34
invariant(
35
next != null,
33
- 'accumulateInto(...): Accumulated items must not be null or undefined.'
36
+ 'accumulateInto(...): Accumulated items must not be null or undefined.',
37
);
38
39
if (current == null) {
src/renderers/shared/utils/adler32.js
+3
-5
@@ -28,12 +28,10 @@ function adler32(data: string): number {
28
while (i < m) {
29
var n = Math.min(i + 4096, m);
30
for (; i < n; i += 4) {
31
- b += (
32
- (a += data.charCodeAt(i)) +
31
+ b += (a += data.charCodeAt(i)) +
32
(a += data.charCodeAt(i + 1)) +
33
(a += data.charCodeAt(i + 2)) +
35
- (a += data.charCodeAt(i + 3))
36
- );
34
+ (a += data.charCodeAt(i + 3));
35
}
36
a %= MOD;
37
b %= MOD;
@@ -43,7 +41,7 @@ function adler32(data: string): number {
41
}
42
a %= MOD;
43
b %= MOD;
46
- return a | (b << 16);
44
+ return a | b << 16;
45
}
46
47
module.exports = adler32;
src/renderers/shared/utils/forEachAccumulated.js
+1
-1
@@ -23,7 +23,7 @@
23
*/
24
function forEachAccumulated<T>(
25
arr: ?(T | Array<T>),
26
- cb: ((elem: T) => void),
26
+ cb: (elem: T) => void,
27
scope: ?any,
28
) {
29
if (Array.isArray(arr)) {
src/renderers/shared/utils/isTextInputElement.js
+14
-14
@@ -16,21 +16,21 @@
16
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
17
*/
18
var supportedInputTypes: {[key: string]: true | void} = {
19
- 'color': true,
20
- 'date': true,
21
- 'datetime': true,
19
+ color: true,
20
+ date: true,
21
+ datetime: true,
22
'datetime-local': true,
23
- 'email': true,
24
- 'month': true,
25
- 'number': true,
26
- 'password': true,
27
- 'range': true,
28
- 'search': true,
29
- 'tel': true,
30
- 'text': true,
31
- 'time': true,
32
- 'url': true,
33
- 'week': true,
23
+ email: true,
24
+ month: true,
25
+ number: true,
26
+ password: true,
27
+ range: true,
28
+ search: true,
29
+ tel: true,
30
+ text: true,
31
+ time: true,
32
+ url: true,
33
+ week: true,
34
};
35
36
function isTextInputElement(elem: ?HTMLElement): boolean {
src/renderers/shared/utils/validateCallback.js
+2
-2
@@ -18,8 +18,8 @@ function validateCallback(callback: ?Function) {
18
invariant(
19
!callback || typeof callback === 'function',
20
'Invalid argument passed as callback. Expected a function. Instead ' +
21
- 'received: %s',
22
- callback
21
+ 'received: %s',
22
+ callback,
23
);
24
}
25
src/renderers/testing/ReactTestRendererFiber.js
+91
-76
@@ -26,36 +26,36 @@ var {
26
HostRoot,
27
} = ReactTypeOfWork;
28
29
-import type { TestRendererOptions } from 'ReactTestMount';
30
-import type { Fiber } from 'ReactFiber';
31
-import type { FiberRoot } from 'ReactFiberRoot';
29
+import type {TestRendererOptions} from 'ReactTestMount';
30
+import type {Fiber} from 'ReactFiber';
31
+import type {FiberRoot} from 'ReactFiberRoot';
32
33
type ReactTestRendererJSON = {|
34
- type : string,
35
- props : {[propName: string] : any },
36
- children : null | Array<ReactTestRendererNode>,
37
- $$typeof ?: Symbol, // Optional because we add it with defineProperty().
34
+ type: string,
35
+ props: {[propName: string]: any},
36
+ children: null | Array<ReactTestRendererNode>,
37
+ $$typeof?: Symbol, // Optional because we add it with defineProperty().
38
|};
39
type ReactTestRendererNode = ReactTestRendererJSON | string;
40
41
type Container = {|
42
- children : Array<Instance | TextInstance>,
43
- createNodeMock : Function,
44
- tag : 'CONTAINER',
42
+ children: Array<Instance | TextInstance>,
43
+ createNodeMock: Function,
44
+ tag: 'CONTAINER',
45
|};
46
47
type Props = Object;
48
type Instance = {|
49
- type : string,
50
- props : Object,
51
- children : Array<Instance | TextInstance>,
52
- rootContainerInstance : Container,
53
- tag : 'INSTANCE',
49
+ type: string,
50
+ props: Object,
51
+ children: Array<Instance | TextInstance>,
52
+ rootContainerInstance: Container,
53
+ tag: 'INSTANCE',
54
|};
55
56
type TextInstance = {|
57
- text : string,
58
- tag : 'TEXT',
57
+ text: string,
58
+ tag: 'TEXT',
59
|};
60
61
const UPDATE_SIGNAL = {};
@@ -69,21 +69,21 @@ var TestRenderer = ReactFiberReconciler({
69
return emptyObject;
70
},
71
72
- prepareForCommit() : void {
72
+ prepareForCommit(): void {
73
// noop
74
},
75
76
- resetAfterCommit() : void {
76
+ resetAfterCommit(): void {
77
// noop
78
},
79
80
createInstance(
81
- type : string,
82
- props : Props,
83
- rootContainerInstance : Container,
84
- hostContext : Object,
85
- internalInstanceHandle : Object,
86
- ) : Instance {
81
+ type: string,
82
+ props: Props,
83
+ rootContainerInstance: Container,
84
+ hostContext: Object,
85
+ internalInstanceHandle: Object,
86
+ ): Instance {
87
return {
88
type,
89
props,
@@ -93,7 +93,10 @@ var TestRenderer = ReactFiberReconciler({
93
};
94
},
95
96
- appendInitialChild(parentInstance : Instance, child : Instance | TextInstance) : void {
96
+ appendInitialChild(
97
+ parentInstance: Instance,
98
+ child: Instance | TextInstance,
99
+ ): void {
100
const index = parentInstance.children.indexOf(child);
101
if (index !== -1) {
102
parentInstance.children.splice(index, 1);
@@ -102,75 +105,82 @@ var TestRenderer = ReactFiberReconciler({
105
},
106
107
finalizeInitialChildren(
105
- testElement : Instance,
106
- type : string,
107
- props : Props,
108
- rootContainerInstance : Container,
109
- ) : boolean {
108
+ testElement: Instance,
109
+ type: string,
110
+ props: Props,
111
+ rootContainerInstance: Container,
112
+ ): boolean {
113
return false;
114
},
115
116
prepareUpdate(
114
- testElement : Instance,
115
- type : string,
116
- oldProps : Props,
117
- newProps : Props,
118
- rootContainerInstance : Container,
119
- hostContext : Object,
120
- ) : null | {} {
117
+ testElement: Instance,
118
+ type: string,
119
+ oldProps: Props,
120
+ newProps: Props,
121
+ rootContainerInstance: Container,
122
+ hostContext: Object,
123
+ ): null | {} {
124
return UPDATE_SIGNAL;
125
},
126
127
commitUpdate(
125
- instance : Instance,
126
- updatePayload : {},
127
- type : string,
128
- oldProps : Props,
129
- newProps : Props,
130
- internalInstanceHandle : Object,
131
- ) : void {
128
+ instance: Instance,
129
+ updatePayload: {},
130
+ type: string,
131
+ oldProps: Props,
132
+ newProps: Props,
133
+ internalInstanceHandle: Object,
134
+ ): void {
135
instance.type = type;
136
instance.props = newProps;
137
},
138
139
commitMount(
137
- instance : Instance,
138
- type : string,
139
- newProps : Props,
140
- internalInstanceHandle : Object
141
- ) : void {
140
+ instance: Instance,
141
+ type: string,
142
+ newProps: Props,
143
+ internalInstanceHandle: Object,
144
+ ): void {
145
// noop
146
},
147
145
- shouldSetTextContent(props : Props) : boolean {
148
+ shouldSetTextContent(props: Props): boolean {
149
return false;
150
},
151
149
- resetTextContent(testElement : Instance) : void {
152
+ resetTextContent(testElement: Instance): void {
153
// noop
154
},
155
153
- shouldDeprioritizeSubtree(type: string, props : Props) : boolean {
156
+ shouldDeprioritizeSubtree(type: string, props: Props): boolean {
157
return false;
158
},
159
160
createTextInstance(
158
- text : string,
159
- rootContainerInstance : Container,
160
- hostContext : Object,
161
- internalInstanceHandle : Object
162
- ) : TextInstance {
161
+ text: string,
162
+ rootContainerInstance: Container,
163
+ hostContext: Object,
164
+ internalInstanceHandle: Object,
165
+ ): TextInstance {
166
return {
167
text,
168
tag: 'TEXT',
169
};
170
},
171
169
- commitTextUpdate(textInstance : TextInstance, oldText : string, newText : string) : void {
172
+ commitTextUpdate(
173
+ textInstance: TextInstance,
174
+ oldText: string,
175
+ newText: string,
176
+ ): void {
177
textInstance.text = newText;
178
},
179
173
- appendChild(parentInstance : Instance | Container, child : Instance | TextInstance) : void {
180
+ appendChild(
181
+ parentInstance: Instance | Container,
182
+ child: Instance | TextInstance,
183
+ ): void {
184
const index = parentInstance.children.indexOf(child);
185
if (index !== -1) {
186
parentInstance.children.splice(index, 1);
@@ -179,10 +189,10 @@ var TestRenderer = ReactFiberReconciler({
189
},
190
191
insertBefore(
182
- parentInstance : Instance | Container,
183
- child : Instance | TextInstance,
184
- beforeChild : Instance | TextInstance
185
- ) : void {
192
+ parentInstance: Instance | Container,
193
+ child: Instance | TextInstance,
194
+ beforeChild: Instance | TextInstance,
195
+ ): void {
196
const index = parentInstance.children.indexOf(child);
197
if (index !== -1) {
198
parentInstance.children.splice(index, 1);
@@ -191,16 +201,19 @@ var TestRenderer = ReactFiberReconciler({
201
parentInstance.children.splice(beforeIndex, 0, child);
202
},
203
194
- removeChild(parentInstance : Instance | Container, child : Instance | TextInstance) : void {
204
+ removeChild(
205
+ parentInstance: Instance | Container,
206
+ child: Instance | TextInstance,
207
+ ): void {
208
const index = parentInstance.children.indexOf(child);
209
parentInstance.children.splice(index, 1);
210
},
211
199
- scheduleAnimationCallback(fn : Function) : void {
212
+ scheduleAnimationCallback(fn: Function): void {
213
setTimeout(fn);
214
},
215
203
- scheduleDeferredCallback(fn : Function) : void {
216
+ scheduleDeferredCallback(fn: Function): void {
217
setTimeout(fn, 0, {timeRemaining: Infinity});
218
},
219
@@ -226,7 +239,7 @@ var defaultTestOptions = {
239
},
240
};
241
229
-function toJSON(inst : Instance | TextInstance) : ReactTestRendererNode {
242
+function toJSON(inst: Instance | TextInstance): ReactTestRendererNode {
243
switch (inst.tag) {
244
case 'TEXT':
245
return inst.text;
@@ -240,12 +253,14 @@ function toJSON(inst : Instance | TextInstance) : ReactTestRendererNode {
253
if (inst.children && inst.children.length) {
254
renderedChildren = inst.children.map(toJSON);
255
}
243
- const json : ReactTestRendererJSON = {
256
+ const json: ReactTestRendererJSON = {
257
type: inst.type,
258
props: props,
259
children: renderedChildren,
260
};
248
- Object.defineProperty(json, '$$typeof', {value: Symbol.for('react.test.json')});
261
+ Object.defineProperty(json, '$$typeof', {
262
+ value: Symbol.for('react.test.json'),
263
+ });
264
return json;
265
default:
266
throw new Error(`Unexpected node type in toJSON: ${inst.tag}`);
@@ -273,7 +288,7 @@ function toTree(node: ?Fiber) {
288
return {
289
nodeType: 'component',
290
type: node.type,
276
- props: { ...node.memoizedProps },
291
+ props: {...node.memoizedProps},
292
instance: node.stateNode,
293
rendered: toTree(node.child),
294
};
@@ -281,7 +296,7 @@ function toTree(node: ?Fiber) {
296
return {
297
nodeType: 'component',
298
type: node.type,
284
- props: { ...node.memoizedProps },
299
+ props: {...node.memoizedProps},
300
instance: null,
301
rendered: toTree(node.child),
302
};
@@ -289,7 +304,7 @@ function toTree(node: ?Fiber) {
304
return {
305
nodeType: 'host',
306
type: node.type,
292
- props: { ...node.memoizedProps },
307
+ props: {...node.memoizedProps},
308
instance: null, // TODO: use createNodeMock here somehow?
309
rendered: nodeAndSiblingsArray(node.child).map(toTree),
310
};
@@ -299,13 +314,13 @@ function toTree(node: ?Fiber) {
314
invariant(
315
false,
316
'toTree() does not yet know how to handle nodes with tag=%s',
302
- node.tag
317
+ node.tag,
318
);
319
}
320
}
321
322
var ReactTestFiberRenderer = {
308
- create(element : ReactElement<any>, options : TestRendererOptions) {
323
+ create(element: ReactElement<any>, options: TestRendererOptions) {
324
var createNodeMock = defaultTestOptions.createNodeMock;
325
if (options && typeof options.createNodeMock === 'function') {
326
createNodeMock = options.createNodeMock;
@@ -338,7 +353,7 @@ var ReactTestFiberRenderer = {
353
}
354
return toTree(root.current);
355
},
341
- update(newElement : ReactElement<any>) {
356
+ update(newElement: ReactElement<any>) {
357
if (root == null || root.current == null) {
358
return;
359
}
src/renderers/testing/__tests__/ReactTestRenderer-test.js
+101
-128
@@ -30,7 +30,7 @@ function cleanNode(node) {
30
}
31
if (node && node.props && node.props.children) {
32
// eslint-disable-next-line no-unused-vars
33
- var { children, ...props } = node.props;
33
+ var {children, ...props} = node.props;
34
node.props = props;
35
}
36
if (Array.isArray(node.rendered)) {
@@ -57,7 +57,7 @@ describe('ReactTestRenderer', () => {
57
var renderer = ReactTestRenderer.create(<Link />);
58
expect(renderer.toJSON()).toEqual({
59
type: 'a',
60
- props: { role: 'link' },
60
+ props: {role: 'link'},
61
children: null,
62
});
63
});
@@ -104,10 +104,8 @@ describe('ReactTestRenderer', () => {
104
var renderer = ReactTestRenderer.create(<Component />);
105
expect(renderer.toJSON()).toEqual({
106
type: 'div',
107
- props: { className: 'purple' },
108
- children: [
109
- { type: 'moo', props: {}, children: null },
110
- ],
107
+ props: {className: 'purple'},
108
+ children: [{type: 'moo', props: {}, children: null}],
109
});
110
});
111
@@ -146,10 +144,10 @@ describe('ReactTestRenderer', () => {
144
var renderer = ReactTestRenderer.create(<Component />);
145
expect(renderer.toJSON()).toEqual({
146
type: 'div',
149
- props: { className: 'purple' },
147
+ props: {className: 'purple'},
148
children: [
149
ReactDOMFeatureFlags.useFiber ? '7' : 7,
152
- { type: 'moo', props: {}, children: null },
150
+ {type: 'moo', props: {}, children: null},
151
],
152
});
153
expect(renders).toBe(6);
@@ -207,7 +205,7 @@ describe('ReactTestRenderer', () => {
205
<span key="a">A</span>
206
<span key="b">B</span>
207
<span key="c">C</span>
210
- </div>
208
+ </div>,
209
);
210
expect(renderer.toJSON()).toEqual({
211
type: 'div',
@@ -224,7 +222,7 @@ describe('ReactTestRenderer', () => {
222
<span key="d">D</span>
223
<span key="c">C</span>
224
<span key="b">B</span>
227
- </div>
225
+ </div>,
226
);
227
expect(renderer.toJSON()).toEqual({
228
type: 'div',
@@ -268,7 +266,7 @@ describe('ReactTestRenderer', () => {
266
267
it('gives a ref to native components', () => {
268
var log = [];
271
- ReactTestRenderer.create(<div ref={(r) => log.push(r)} />);
269
+ ReactTestRenderer.create(<div ref={r => log.push(r)} />);
270
expect(log).toEqual([null]);
271
});
272
@@ -292,26 +290,24 @@ describe('ReactTestRenderer', () => {
290
expectDev(console.error.calls.count()).toBe(1);
291
expectDev(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
292
'Warning: Stateless function components cannot be given refs. Attempts ' +
295
- 'to access this ref will fail.\n\nCheck the render method of `Foo`.\n' +
296
- ' in Bar (at **)\n' +
297
- ' in Foo (at **)'
293
+ 'to access this ref will fail.\n\nCheck the render method of `Foo`.\n' +
294
+ ' in Bar (at **)\n' +
295
+ ' in Foo (at **)',
296
);
297
});
298
299
it('allows an optional createNodeMock function', () => {
302
- var mockDivInstance = { appendChild: () => {} };
303
- var mockInputInstance = { focus: () => {} };
304
- var mockListItemInstance = { click: () => {} };
305
- var mockAnchorInstance = { hover: () => {} };
300
+ var mockDivInstance = {appendChild: () => {}};
301
+ var mockInputInstance = {focus: () => {}};
302
+ var mockListItemInstance = {click: () => {}};
303
+ var mockAnchorInstance = {hover: () => {}};
304
var log = [];
305
class Foo extends React.Component {
306
componentDidMount() {
307
log.push(this.refs.bar);
308
}
309
render() {
312
- return (
313
- <a ref="bar">Hello, world</a>
314
- );
310
+ return <a ref="bar">Hello, world</a>;
311
}
312
}
313
function createNodeMock(element) {
@@ -328,39 +324,27 @@ describe('ReactTestRenderer', () => {
324
return {};
325
}
326
}
331
- ReactTestRenderer.create(
332
- <div ref={(r) => log.push(r)} />,
333
- {createNodeMock}
334
- );
335
- ReactTestRenderer.create(
336
- <input ref={(r) => log.push(r)} />,
337
- {createNodeMock},
338
- );
327
+ ReactTestRenderer.create(<div ref={r => log.push(r)} />, {createNodeMock});
328
+ ReactTestRenderer.create(<input ref={r => log.push(r)} />, {
329
+ createNodeMock,
330
+ });
331
ReactTestRenderer.create(
332
<div>
333
<span>
334
<ul>
343
- <li ref={(r) => log.push(r)} />
335
+ <li ref={r => log.push(r)} />
336
</ul>
337
<ul>
346
- <li ref={(r) => log.push(r)} />
347
- <li ref={(r) => log.push(r)} />
338
+ <li ref={r => log.push(r)} />
339
+ <li ref={r => log.push(r)} />
340
</ul>
341
</span>
342
</div>,
343
{createNodeMock, foobar: true},
344
);
353
- ReactTestRenderer.create(
354
- <Foo />,
355
- {createNodeMock},
356
- );
357
- ReactTestRenderer.create(
358
- <div ref={(r) => log.push(r)} />,
359
- );
360
- ReactTestRenderer.create(
361
- <div ref={(r) => log.push(r)} />,
362
- {}
363
- );
345
+ ReactTestRenderer.create(<Foo />, {createNodeMock});
346
+ ReactTestRenderer.create(<div ref={r => log.push(r)} />);
347
+ ReactTestRenderer.create(<div ref={r => log.push(r)} />, {});
348
expect(log).toEqual([
349
mockDivInstance,
350
mockInputInstance,
@@ -379,10 +363,9 @@ describe('ReactTestRenderer', () => {
363
return <div ref="foo" />;
364
}
365
}
382
- const inst = ReactTestRenderer.create(
383
- <Foo />,
384
- {createNodeMock: () => 'foo'}
385
- );
366
+ const inst = ReactTestRenderer.create(<Foo />, {
367
+ createNodeMock: () => 'foo',
368
+ });
369
expect(() => inst.unmount()).not.toThrow();
370
});
371
@@ -396,10 +379,9 @@ describe('ReactTestRenderer', () => {
379
return <div />;
380
}
381
}
399
- const inst = ReactTestRenderer.create(
400
- <div><Foo /></div>,
401
- {createNodeMock: () => 'foo'}
402
- );
382
+ const inst = ReactTestRenderer.create(<div><Foo /></div>, {
383
+ createNodeMock: () => 'foo',
384
+ });
385
expect(() => inst.unmount()).not.toThrow();
386
expect(count).toEqual(1);
387
});
@@ -412,15 +394,12 @@ describe('ReactTestRenderer', () => {
394
};
395
class Foo extends React.Component {
396
render() {
415
- return this.props.useDiv
416
- ? <div ref="foo" />
417
- : <span ref="foo" />;
397
+ return this.props.useDiv ? <div ref="foo" /> : <span ref="foo" />;
398
}
399
}
420
- const inst = ReactTestRenderer.create(
421
- <Foo useDiv={true} />,
422
- {createNodeMock}
423
- );
400
+ const inst = ReactTestRenderer.create(<Foo useDiv={true} />, {
401
+ createNodeMock,
402
+ });
403
inst.update(<Foo useDiv={false} />);
404
expect(log).toEqual(['div', 'span']);
405
});
@@ -524,48 +503,46 @@ describe('ReactTestRenderer', () => {
503
renderer.update(<Component>{42}</Component>);
504
expect(renderer.toJSON()).toEqual({
505
type: 'div',
527
- children: [
528
- ReactDOMFeatureFlags.useFiber ? '42' : 42,
529
- ],
506
+ children: [ReactDOMFeatureFlags.useFiber ? '42' : 42],
507
props: {},
508
});
509
renderer.update(<Component><div /></Component>);
510
expect(renderer.toJSON()).toEqual({
511
type: 'div',
535
- children: [{
536
- type: 'div',
537
- children: null,
538
- props: {},
539
- }],
512
+ children: [
513
+ {
514
+ type: 'div',
515
+ children: null,
516
+ props: {},
517
+ },
518
+ ],
519
props: {},
520
});
521
});
522
523
it('toTree() renders simple components returning host components', () => {
545
-
546
- var Qoo = () => (
547
- <span className="Qoo">Hello World!</span>
548
- );
524
+ var Qoo = () => <span className="Qoo">Hello World!</span>;
525
526
var renderer = ReactTestRenderer.create(<Qoo />);
527
var tree = renderer.toTree();
528
529
cleanNode(tree);
530
555
- expect(prettyFormat(tree)).toEqual(prettyFormat({
556
- nodeType: 'component',
557
- type: Qoo,
558
- props: {},
559
- instance: null,
560
- rendered: {
561
- nodeType: 'host',
562
- type: 'span',
563
- props: { className: 'Qoo' },
531
+ expect(prettyFormat(tree)).toEqual(
532
+ prettyFormat({
533
+ nodeType: 'component',
534
+ type: Qoo,
535
+ props: {},
536
instance: null,
565
- rendered: ['Hello World!'],
566
- },
567
- }));
568
-
537
+ rendered: {
538
+ nodeType: 'host',
539
+ type: 'span',
540
+ props: {className: 'Qoo'},
541
+ instance: null,
542
+ rendered: ['Hello World!'],
543
+ },
544
+ }),
545
+ );
546
});
547
548
it('toTree() handles null rendering components', () => {
@@ -585,21 +562,18 @@ describe('ReactTestRenderer', () => {
562
expect(tree).toEqual({
563
type: Foo,
564
nodeType: 'component',
588
- props: { },
565
+ props: {},
566
instance: null,
567
rendered: null,
568
});
592
-
569
});
570
571
it('toTree() renders complicated trees of composites and hosts', () => {
572
// SFC returning host. no children props.
597
- var Qoo = () => (
598
- <span className="Qoo">Hello World!</span>
599
- );
573
+ var Qoo = () => <span className="Qoo">Hello World!</span>;
574
575
// SFC returning host. passes through children.
602
- var Foo = ({ className, children }) => (
576
+ var Foo = ({className, children}) => (
577
<div className={'Foo ' + className}>
578
<span className="Foo2">Literal</span>
579
{children}
@@ -609,7 +583,7 @@ describe('ReactTestRenderer', () => {
583
// class composite returning composite. passes through children.
584
class Bar extends React.Component {
585
render() {
612
- const { special, children } = this.props;
586
+ const {special, children} = this.props;
587
return (
588
<Foo className={special ? 'special' : 'normal'}>
589
{children}
@@ -638,53 +612,54 @@ describe('ReactTestRenderer', () => {
612
613
cleanNode(tree);
614
641
- expect(prettyFormat(tree)).toEqual(prettyFormat({
642
- type: Bam,
643
- nodeType: 'component',
644
- props: {},
645
- instance: null,
646
- rendered: {
647
- type: Bar,
615
+ expect(prettyFormat(tree)).toEqual(
616
+ prettyFormat({
617
+ type: Bam,
618
nodeType: 'component',
649
- props: { special: true },
619
+ props: {},
620
instance: null,
621
rendered: {
652
- type: Foo,
622
+ type: Bar,
623
nodeType: 'component',
654
- props: { className: 'special' },
624
+ props: {special: true},
625
instance: null,
626
rendered: {
657
- type: 'div',
658
- nodeType: 'host',
659
- props: { className: 'Foo special' },
627
+ type: Foo,
628
+ nodeType: 'component',
629
+ props: {className: 'special'},
630
instance: null,
661
- rendered: [
662
- {
663
- type: 'span',
664
- nodeType: 'host',
665
- props: { className: 'Foo2' },
666
- instance: null,
667
- rendered: ['Literal'],
668
- },
669
- {
670
- type: Qoo,
671
- nodeType: 'component',
672
- props: {},
673
- instance: null,
674
- rendered: {
631
+ rendered: {
632
+ type: 'div',
633
+ nodeType: 'host',
634
+ props: {className: 'Foo special'},
635
+ instance: null,
636
+ rendered: [
637
+ {
638
type: 'span',
639
nodeType: 'host',
677
- props: { className: 'Qoo' },
640
+ props: {className: 'Foo2'},
641
instance: null,
679
- rendered: ['Hello World!'],
642
+ rendered: ['Literal'],
643
},
681
- },
682
- ],
644
+ {
645
+ type: Qoo,
646
+ nodeType: 'component',
647
+ props: {},
648
+ instance: null,
649
+ rendered: {
650
+ type: 'span',
651
+ nodeType: 'host',
652
+ props: {className: 'Qoo'},
653
+ instance: null,
654
+ rendered: ['Hello World!'],
655
+ },
656
+ },
657
+ ],
658
+ },
659
},
660
},
685
- },
686
- }));
687
-
661
+ }),
662
+ );
663
});
664
665
if (ReactDOMFeatureFlags.useFiber) {
@@ -698,7 +673,7 @@ describe('ReactTestRenderer', () => {
673
});
674
675
it('can render and update root fragments', () => {
701
- var Component = (props) => props.children;
676
+ var Component = props => props.children;
677
678
var renderer = ReactTestRenderer.create([
679
<Component>Hi</Component>,
@@ -715,9 +690,7 @@ describe('ReactTestRenderer', () => {
690
expect(renderer.toJSON()).toEqual([
691
{
692
type: 'div',
718
- children: [
719
- 'goodbye',
720
- ],
693
+ children: ['goodbye'],
694
props: {},
695
},
696
'world',
src/renderers/testing/stack/ReactTestMount.js
+20
-27
@@ -54,17 +54,17 @@ TopLevelWrapper.isReactTopLevelWrapper = true;
54
* @param {Object} hostContainerInfo
55
*/
56
function mountComponentIntoNode(
57
- componentInstance,
58
- transaction,
59
- hostParent,
60
- hostContainerInfo
61
- ) {
57
+ componentInstance,
58
+ transaction,
59
+ hostParent,
60
+ hostContainerInfo,
61
+) {
62
var image = ReactReconciler.mountComponent(
63
componentInstance,
64
transaction,
65
null,
66
hostContainerInfo,
67
- emptyObject
67
+ emptyObject,
68
);
69
componentInstance._renderedComponent._topLevelWrapper = componentInstance;
70
return image;
@@ -77,10 +77,7 @@ function mountComponentIntoNode(
77
* @param {number} rootID ID of the root node.
78
* @param {number} containerTag container element to mount into.
79
*/
80
-function batchedMountComponentIntoNode(
81
- componentInstance,
82
- options,
83
- ) {
80
+function batchedMountComponentIntoNode(componentInstance, options) {
81
var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(true);
82
var image = transaction.perform(
83
mountComponentIntoNode,
@@ -88,7 +85,7 @@ function batchedMountComponentIntoNode(
85
componentInstance,
86
transaction,
87
null,
91
- options
88
+ options,
89
);
90
ReactUpdates.ReactReconcileTransaction.release(transaction);
91
return image;
@@ -103,12 +100,11 @@ ReactTestInstance.prototype.getInstance = function() {
100
ReactTestInstance.prototype.update = function(nextElement) {
101
invariant(
102
this._component,
106
- "ReactTestRenderer: .update() can't be called after unmount."
107
- );
108
- var nextWrappedElement = React.createElement(
109
- TopLevelWrapper,
110
- { child: nextElement }
103
+ "ReactTestRenderer: .update() can't be called after unmount.",
104
);
105
+ var nextWrappedElement = React.createElement(TopLevelWrapper, {
106
+ child: nextElement,
107
+ });
108
var component = this._component;
109
ReactUpdates.batchedUpdates(function() {
110
var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(true);
@@ -117,7 +113,7 @@ ReactTestInstance.prototype.update = function(nextElement) {
113
component,
114
nextWrappedElement,
115
transaction,
120
- emptyObject
116
+ emptyObject,
117
);
118
});
119
ReactUpdates.ReactReconcileTransaction.release(transaction);
@@ -130,8 +126,8 @@ ReactTestInstance.prototype.unmount = function(nextElement) {
126
transaction.perform(function() {
127
ReactReconciler.unmountComponent(
128
component,
133
- false, /* safely */
134
- false /* skipLifecycle */
129
+ false /* safely */,
130
+ false /* skipLifecycle */,
131
);
132
});
133
ReactUpdates.ReactReconcileTransaction.release(transaction);
@@ -167,7 +163,7 @@ function toTree(component) {
163
return {
164
nodeType: 'host',
165
type: element.type,
170
- props: { ...element.props },
166
+ props: {...element.props},
167
instance: component._nodeMock,
168
rendered: rendered,
169
};
@@ -175,7 +171,7 @@ function toTree(component) {
171
return {
172
nodeType: 'component',
173
type: element.type,
178
- props: { ...element.props },
174
+ props: {...element.props},
175
instance: component._instance,
176
rendered: toTree(component._renderedComponent),
177
};
@@ -187,15 +183,13 @@ function toTree(component) {
183
* code between the two. For now, we'll hard code the ID logic.
184
*/
185
var ReactTestMount = {
190
-
186
render: function(
187
nextElement: ReactElement<any>,
188
options?: TestRendererOptions,
189
): ReactTestInstance {
195
- var nextWrappedElement = React.createElement(
196
- TopLevelWrapper,
197
- {child: nextElement},
198
- );
190
+ var nextWrappedElement = React.createElement(TopLevelWrapper, {
191
+ child: nextElement,
192
+ });
193
194
var instance = instantiateReactComponent(nextWrappedElement, false);
195
@@ -209,7 +203,6 @@ var ReactTestMount = {
203
);
204
return new ReactTestInstance(instance);
205
},
212
-
206
};
207
208
module.exports = ReactTestMount;
src/renderers/testing/stack/ReactTestReconcileTransaction.js
+2
-2
@@ -16,7 +16,7 @@ var PooledClass = require('PooledClass');
16
var Transaction = require('Transaction');
17
var ReactUpdateQueue = require('ReactUpdateQueue');
18
19
-import type { TestRendererOptions } from 'ReactTestMount';
19
+import type {TestRendererOptions} from 'ReactTestMount';
20
21
/**
22
* Provides a `CallbackQueue` queue for collecting `onDOMReady` callbacks during
@@ -126,7 +126,7 @@ Object.assign(
126
ReactTestReconcileTransaction.prototype,
127
Transaction,
128
ReactTestReconcileTransaction,
129
- Mixin
129
+ Mixin,
130
);
131
132
PooledClass.addPoolingTo(ReactTestReconcileTransaction);
src/renderers/testing/stack/ReactTestRendererStack.js
+8
-8
@@ -25,16 +25,16 @@ var ReactTestTextComponent = require('ReactTestTextComponent');
25
var ReactTestEmptyComponent = require('ReactTestEmptyComponent');
26
var invariant = require('fbjs/lib/invariant');
27
28
-import type { ReactElement } from 'ReactElementType';
29
-import type { ReactInstance } from 'ReactInstanceType';
30
-import type { ReactText } from 'ReactTypes';
28
+import type {ReactElement} from 'ReactElementType';
29
+import type {ReactInstance} from 'ReactInstanceType';
30
+import type {ReactText} from 'ReactTypes';
31
32
type ReactTestRendererJSON = {
33
type: string,
34
- props: { [propName: string]: any },
34
+ props: {[propName: string]: any},
35
children: null | Array<ReactText | ReactTestRendererJSON>,
36
- $$typeof?: any
37
-}
36
+ $$typeof?: any,
37
+};
38
39
/**
40
* Drill down (through composites and empty components) until we get a native or
@@ -94,7 +94,7 @@ class ReactTestComponent {
94
getPublicInstance(): Object {
95
invariant(
96
this._nodeMock !== UNSET,
97
- 'getPublicInstance should not be called before component is mounted.'
97
+ 'getPublicInstance should not be called before component is mounted.',
98
);
99
return this._nodeMock;
100
}
@@ -135,7 +135,7 @@ Object.assign(ReactTestComponent.prototype, ReactMultiChild);
135
// =============================================================================
136
137
ReactUpdates.injection.injectReconcileTransaction(
138
- ReactTestReconcileTransaction
138
+ ReactTestReconcileTransaction,
139
);
140
ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy);
141
src/renderers/testing/stack/ReactTestTextComponent.js
+1
-1
@@ -13,7 +13,7 @@
13
14
'use strict';
15
16
-import type { ReactText } from 'ReactTypes';
16
+import type {ReactText} from 'ReactTypes';
17
18
class ReactTestTextComponent {
19
_currentElement: ReactText;
src/shared/ReactFiberComponentTreeHook.js
+12
-11
@@ -21,20 +21,21 @@ var {
21
} = ReactTypeOfWork;
22
var getComponentName = require('getComponentName');
23
24
-import type { Fiber } from 'ReactFiber';
24
+import type {Fiber} from 'ReactFiber';
25
26
function describeComponentFrame(name, source: any, ownerName) {
27
- return '\n in ' + (name || 'Unknown') + (
28
- source ?
29
- ' (at ' + source.fileName.replace(/^.*[\\\/]/, '') + ':' +
30
- source.lineNumber + ')' :
31
- ownerName ?
32
- ' (created by ' + ownerName + ')' :
33
- ''
34
- );
27
+ return '\n in ' +
28
+ (name || 'Unknown') +
29
+ (source
30
+ ? ' (at ' +
31
+ source.fileName.replace(/^.*[\\\/]/, '') +
32
+ ':' +
33
+ source.lineNumber +
34
+ ')'
35
+ : ownerName ? ' (created by ' + ownerName + ')' : '');
36
}
37
37
-function describeFiber(fiber : Fiber) : string {
38
+function describeFiber(fiber: Fiber): string {
39
switch (fiber.tag) {
40
case IndeterminateComponent:
41
case FunctionalComponent:
@@ -56,7 +57,7 @@ function describeFiber(fiber : Fiber) : string {
57
// This function can only be called with a work-in-progress fiber and
58
// only during begin or complete phase. Do not call it under any other
59
// circumstances.
59
-function getStackAddendumByWorkInProgressFiber(workInProgress : Fiber) : string {
60
+function getStackAddendumByWorkInProgressFiber(workInProgress: Fiber): string {
61
var info = '';
62
var node = workInProgress;
63
do {
src/shared/types/checkReactTypeSpec.js
+3
-9
@@ -12,21 +12,15 @@
12
'use strict';
13
14
var checkPropTypes = require('react/lib/checkPropTypes');
15
-var { getStackAddendum } = require('react/lib/ReactDebugCurrentFrame');
15
+var {getStackAddendum} = require('react/lib/ReactDebugCurrentFrame');
16
17
function checkReactTypeSpec(
18
typeSpecs,
19
values,
20
location: string,
21
- componentName
21
+ componentName,
22
) {
23
- checkPropTypes(
24
- typeSpecs,
25
- values,
26
- location,
27
- componentName,
28
- getStackAddendum
29
- );
23
+ checkPropTypes(typeSpecs, values, location, componentName, getStackAddendum);
24
}
25
26
module.exports = checkReactTypeSpec;
src/shared/utils/KeyEscapeUtils.js
+9
-14
@@ -24,12 +24,9 @@ function escape(key: string): string {
24
'=': '=0',
25
':': '=2',
26
};
27
- var escapedString = ('' + key).replace(
28
- escapeRegex,
29
- function(match) {
30
- return escaperLookup[match];
31
- }
32
- );
27
+ var escapedString = ('' + key).replace(escapeRegex, function(match) {
28
+ return escaperLookup[match];
29
+ });
30
31
return '$' + escapedString;
32
}
@@ -46,15 +43,13 @@ function unescape(key: string): string {
43
'=0': '=',
44
'=2': ':',
45
};
49
- var keySubstring = (key[0] === '.' && key[1] === '$')
50
- ? key.substring(2) : key.substring(1);
46
+ var keySubstring = key[0] === '.' && key[1] === '$'
47
+ ? key.substring(2)
48
+ : key.substring(1);
49
52
- return ('' + keySubstring).replace(
53
- unescapeRegex,
54
- function(match) {
55
- return unescaperLookup[match];
56
- }
57
- );
50
+ return ('' + keySubstring).replace(unescapeRegex, function(match) {
51
+ return unescaperLookup[match];
52
+ });
53
}
54
55
var KeyEscapeUtils = {
src/shared/utils/PooledClass.js
+2
-2
@@ -69,7 +69,7 @@ var standardReleaser = function(instance) {
69
var Klass = this;
70
invariant(
71
instance instanceof Klass,
72
- 'Trying to release an instance into a pool of a different type.'
72
+ 'Trying to release an instance into a pool of a different type.',
73
);
74
instance.destructor();
75
if (Klass.instancePool.length < Klass.poolSize) {
@@ -95,7 +95,7 @@ var addPoolingTo = function<T>(
95
CopyConstructor: Class<T>,
96
pooler: Pooler,
97
): Class<T> & {
98
- getPooled(/* arguments of the constructor */): T,
98
+ getPooled /* arguments of the constructor */(): T,
99
release(): void,
100
} {
101
// Casting as any so that flow ignores the actual implementation and trusts
src/shared/utils/ReactElementSymbol.js
+3
-2
@@ -14,8 +14,9 @@
14
15
// The Symbol used to tag the ReactElement type. If there is no native Symbol
16
// nor polyfill, then a plain number is used for performance.
17
-var REACT_ELEMENT_TYPE =
18
- (typeof Symbol === 'function' && Symbol.for && Symbol.for('react.element')) ||
17
+var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' &&
18
+ Symbol.for &&
19
+ Symbol.for('react.element')) ||
20
0xeac7;
21
22
module.exports = REACT_ELEMENT_TYPE;
src/shared/utils/__tests__/PooledClass-test.js
+21
-29
@@ -31,14 +31,12 @@ describe('Pooled class', () => {
31
expect(instance instanceof PoolableClass).toBe(true);
32
});
33
34
- it('should return the instance back into the pool when it gets released',
35
- () => {
36
- var instance = PoolableClass.getPooled();
37
- PoolableClass.release(instance);
38
- expect(PoolableClass.instancePool.length).toBe(1);
39
- expect(PoolableClass.instancePool[0]).toBe(instance);
40
- }
41
- );
34
+ it('should return the instance back into the pool when it gets released', () => {
35
+ var instance = PoolableClass.getPooled();
36
+ PoolableClass.release(instance);
37
+ expect(PoolableClass.instancePool.length).toBe(1);
38
+ expect(PoolableClass.instancePool[0]).toBe(instance);
39
+ });
40
41
it('should return an old instance if available in the pool', () => {
42
var instance = PoolableClass.getPooled();
@@ -67,7 +65,7 @@ describe('Pooled class', () => {
65
PoolableClassWithMultiArguments.prototype.destructor = function() {};
66
PooledClass.addPoolingTo(
67
PoolableClassWithMultiArguments,
70
- PooledClass.twoArgumentPooler
68
+ PooledClass.twoArgumentPooler,
69
);
70
PoolableClassWithMultiArguments.getPooled('a', 'b', 'c');
71
expect(log).toEqual(['a', 'b']);
@@ -79,9 +77,7 @@ describe('Pooled class', () => {
77
log.push(a);
78
};
79
PoolableClassWithOneArgument.prototype.destructor = function() {};
82
- PooledClass.addPoolingTo(
83
- PoolableClassWithOneArgument
84
- );
80
+ PooledClass.addPoolingTo(PoolableClassWithOneArgument);
81
PoolableClassWithOneArgument.getPooled('new');
82
expect(log).toEqual(['new']);
83
});
@@ -92,29 +88,25 @@ describe('Pooled class', () => {
88
log.push(a);
89
};
90
PoolableClassWithOneArgument.prototype.destructor = function() {};
95
- PooledClass.addPoolingTo(
96
- PoolableClassWithOneArgument
97
- );
91
+ PooledClass.addPoolingTo(PoolableClassWithOneArgument);
92
var instance = PoolableClassWithOneArgument.getPooled('new');
93
PoolableClassWithOneArgument.release(instance);
94
PoolableClassWithOneArgument.getPooled('old');
95
expect(log).toEqual(['new', 'old']);
96
});
97
104
- it('should throw when the class releases an instance of a different type',
105
- () => {
106
- var RandomClass = function() {};
107
- RandomClass.prototype.destructor = function() {};
108
- PooledClass.addPoolingTo(RandomClass);
109
- var randomInstance = RandomClass.getPooled();
110
- PoolableClass.getPooled();
111
- expect(function() {
112
- PoolableClass.release(randomInstance);
113
- }).toThrowError(
114
- 'Trying to release an instance into a pool of a different type.'
115
- );
116
- }
117
- );
98
+ it('should throw when the class releases an instance of a different type', () => {
99
+ var RandomClass = function() {};
100
+ RandomClass.prototype.destructor = function() {};
101
+ PooledClass.addPoolingTo(RandomClass);
102
+ var randomInstance = RandomClass.getPooled();
103
+ PoolableClass.getPooled();
104
+ expect(function() {
105
+ PoolableClass.release(randomInstance);
106
+ }).toThrowError(
107
+ 'Trying to release an instance into a pool of a different type.',
108
+ );
109
+ });
110
111
it('should throw if no destructor is defined', () => {
112
var ImmortalClass = function() {};
src/shared/utils/__tests__/reactProdInvariant-test.js
+9
-9
@@ -23,27 +23,27 @@ describe('reactProdInvariant', () => {
23
reactProdInvariant(124, 'foo', 'bar');
24
}).toThrowError(
25
'Minified React error #124; visit ' +
26
- 'http://facebook.github.io/react/docs/error-decoder.html?invariant=124&args[]=foo&args[]=bar' +
27
- ' for the full message or use the non-minified dev environment' +
28
- ' for full errors and additional helpful warnings.'
26
+ 'http://facebook.github.io/react/docs/error-decoder.html?invariant=124&args[]=foo&args[]=bar' +
27
+ ' for the full message or use the non-minified dev environment' +
28
+ ' for full errors and additional helpful warnings.',
29
);
30
31
expect(function() {
32
reactProdInvariant(20);
33
}).toThrowError(
34
'Minified React error #20; visit ' +
35
- 'http://facebook.github.io/react/docs/error-decoder.html?invariant=20' +
36
- ' for the full message or use the non-minified dev environment' +
37
- ' for full errors and additional helpful warnings.'
35
+ 'http://facebook.github.io/react/docs/error-decoder.html?invariant=20' +
36
+ ' for the full message or use the non-minified dev environment' +
37
+ ' for full errors and additional helpful warnings.',
38
);
39
40
expect(function() {
41
reactProdInvariant(77, '<div>', '&?bar');
42
}).toThrowError(
43
'Minified React error #77; visit ' +
44
- 'http://facebook.github.io/react/docs/error-decoder.html?invariant=77&args[]=%3Cdiv%3E&args[]=%26%3Fbar' +
45
- ' for the full message or use the non-minified dev environment' +
46
- ' for full errors and additional helpful warnings.'
44
+ 'http://facebook.github.io/react/docs/error-decoder.html?invariant=77&args[]=%3Cdiv%3E&args[]=%26%3Fbar' +
45
+ ' for the full message or use the non-minified dev environment' +
46
+ ' for full errors and additional helpful warnings.',
47
);
48
});
49
});
src/shared/utils/deprecated.js
+4
-3
@@ -41,12 +41,13 @@ function deprecated<T: Function>(
41
// Require examples in this string must be split to prevent React's
42
// build tools from mistaking them for real requires.
43
// Otherwise the build tools will attempt to build a '%s' module.
44
- 'React.%s is deprecated. Please use %s.%s from require' + '(\'%s\') ' +
45
- 'instead.',
44
+ 'React.%s is deprecated. Please use %s.%s from require' +
45
+ "('%s') " +
46
+ 'instead.',
47
fnName,
48
newModule,
49
fnName,
49
- newPackage
50
+ newPackage,
51
);
52
/* eslint-enable no-useless-concat */
53
warned = true;
src/shared/utils/flattenChildren.js
+13
-12
@@ -46,7 +46,7 @@ function flattenSingleChildIntoContext(
46
// We found a component instance.
47
if (traverseContext && typeof traverseContext === 'object') {
48
const result = traverseContext;
49
- const keyUnique = (result[name] === undefined);
49
+ const keyUnique = result[name] === undefined;
50
if (__DEV__) {
51
if (!ReactComponentTreeHook) {
52
ReactComponentTreeHook = require('react/lib/ReactComponentTreeHook');
@@ -55,10 +55,10 @@ function flattenSingleChildIntoContext(
55
warning(
56
false,
57
'flattenChildren(...): Encountered two children with the same key, ' +
58
- '`%s`. Child keys must be unique; when two children share a key, only ' +
59
- 'the first child will be used.%s',
58
+ '`%s`. Child keys must be unique; when two children share a key, only ' +
59
+ 'the first child will be used.%s',
60
KeyEscapeUtils.unescape(name),
61
- ReactComponentTreeHook.getStackAddendumByID(selfDebugID)
61
+ ReactComponentTreeHook.getStackAddendumByID(selfDebugID),
62
);
63
}
64
}
@@ -76,7 +76,7 @@ function flattenSingleChildIntoContext(
76
function flattenChildren(
77
children: ReactElement<any>,
78
selfDebugID?: number,
79
-): ?{ [name: string]: ReactElement<any> } {
79
+): ?{[name: string]: ReactElement<any>} {
80
if (children == null) {
81
return children;
82
}
@@ -85,13 +85,14 @@ function flattenChildren(
85
if (__DEV__) {
86
traverseAllChildren(
87
children,
88
- (traverseContext, child, name) => flattenSingleChildIntoContext(
89
- traverseContext,
90
- child,
91
- name,
92
- selfDebugID
93
- ),
94
- result
88
+ (traverseContext, child, name) =>
89
+ flattenSingleChildIntoContext(
90
+ traverseContext,
91
+ child,
92
+ name,
93
+ selfDebugID,
94
+ ),
95
+ result,
96
);
97
} else {
98
traverseAllChildren(children, flattenSingleChildIntoContext, result);
src/shared/utils/getComponentName.js
+7
-5
@@ -12,18 +12,20 @@
12
13
'use strict';
14
15
-import type { ReactInstance } from 'ReactInstanceType';
16
-import type { Fiber } from 'ReactFiber';
15
+import type {ReactInstance} from 'ReactInstanceType';
16
+import type {Fiber} from 'ReactFiber';
17
18
-function getComponentName(instanceOrFiber : ReactInstance | Fiber) : string | null {
18
+function getComponentName(
19
+ instanceOrFiber: ReactInstance | Fiber,
20
+): string | null {
21
if (typeof instanceOrFiber.getName === 'function') {
22
// Stack reconciler
21
- const instance = ((instanceOrFiber : any) : ReactInstance);
23
+ const instance = ((instanceOrFiber: any): ReactInstance);
24
return instance.getName();
25
}
26
if (typeof instanceOrFiber.tag === 'number') {
27
// Fiber reconciler
26
- const fiber = ((instanceOrFiber : any) : Fiber);
28
+ const fiber = ((instanceOrFiber: any): Fiber);
29
const {type} = fiber;
30
if (typeof type === 'string') {
31
return type;
src/shared/utils/getIteratorFn.js
+4
-5
@@ -30,11 +30,10 @@ var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
30
* @param {?object} maybeIterable
31
* @return {?function}
32
*/
33
-function getIteratorFn(maybeIterable: ?any): ?(() => ?Iterator<*>) {
34
- var iteratorFn = maybeIterable && (
35
- (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL]) ||
36
- maybeIterable[FAUX_ITERATOR_SYMBOL]
37
- );
33
+function getIteratorFn(maybeIterable: ?any): ?() => ?Iterator<*> {
34
+ var iteratorFn = maybeIterable &&
35
+ ((ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL]) ||
36
+ maybeIterable[FAUX_ITERATOR_SYMBOL]);
37
if (typeof iteratorFn === 'function') {
38
return iteratorFn;
39
}
src/shared/utils/reactProdInvariant.js
+8
-9
@@ -20,21 +20,20 @@
20
function reactProdInvariant(code: string): void {
21
var argCount = arguments.length - 1;
22
23
- var message = (
24
- 'Minified React error #' + code + '; visit ' +
25
- 'http://facebook.github.io/react/docs/error-decoder.html?invariant=' + code
26
- );
23
+ var message = 'Minified React error #' +
24
+ code +
25
+ '; visit ' +
26
+ 'http://facebook.github.io/react/docs/error-decoder.html?invariant=' +
27
+ code;
28
29
for (var argIdx = 0; argIdx < argCount; argIdx++) {
30
message += '&args[]=' + encodeURIComponent(arguments[argIdx + 1]);
31
}
32
32
- message += (
33
- ' for the full message or use the non-minified dev environment' +
34
- ' for full errors and additional helpful warnings.'
35
- );
33
+ message += ' for the full message or use the non-minified dev environment' +
34
+ ' for full errors and additional helpful warnings.';
35
37
- var error: Error & { framesToPop?: number } = new Error(message);
36
+ var error: Error & {framesToPop?: number} = new Error(message);
37
error.name = 'Invariant Violation';
38
error.framesToPop = 1; // we don't care about reactProdInvariant's own frame
39
src/shared/utils/traverseAllChildren.js
+23
-20
@@ -65,7 +65,7 @@ function traverseAllChildrenImpl(
65
children,
66
nameSoFar,
67
callback,
68
- traverseContext
68
+ traverseContext,
69
) {
70
var type = typeof children;
71
@@ -74,18 +74,20 @@ function traverseAllChildrenImpl(
74
children = null;
75
}
76
77
- if (children === null ||
78
- type === 'string' ||
79
- type === 'number' ||
80
- // The following is inlined from ReactElement. This means we can optimize
81
- // some checks. React Fiber also inlines this logic for similar purposes.
82
- (type === 'object' && children.$$typeof === REACT_ELEMENT_TYPE)) {
77
+ if (
78
+ children === null ||
79
+ type === 'string' ||
80
+ type === 'number' ||
81
+ // The following is inlined from ReactElement. This means we can optimize
82
+ // some checks. React Fiber also inlines this logic for similar purposes.
83
+ (type === 'object' && children.$$typeof === REACT_ELEMENT_TYPE)
84
+ ) {
85
callback(
86
traverseContext,
87
children,
88
// If it's the only child, treat the name as if it was wrapped in an array
89
// so that it's consistent if the number of children grows.
88
- nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar
90
+ nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar,
91
);
92
return 1;
93
}
@@ -103,7 +105,7 @@ function traverseAllChildrenImpl(
105
child,
106
nextName,
107
callback,
106
- traverseContext
108
+ traverseContext,
109
);
110
}
111
} else {
@@ -116,15 +118,17 @@ function traverseAllChildrenImpl(
118
if (ReactCurrentOwner.current) {
119
var mapsAsChildrenOwnerName = ReactCurrentOwner.current.getName();
120
if (mapsAsChildrenOwnerName) {
119
- mapsAsChildrenAddendum = '\n\nCheck the render method of `' + mapsAsChildrenOwnerName + '`.';
121
+ mapsAsChildrenAddendum = '\n\nCheck the render method of `' +
122
+ mapsAsChildrenOwnerName +
123
+ '`.';
124
}
125
}
126
warning(
127
didWarnAboutMaps,
128
'Using Maps as children is unsupported and will likely yield ' +
125
- 'unexpected results. Convert it to a sequence/iterable of keyed ' +
126
- 'ReactElements instead.%s',
127
- mapsAsChildrenAddendum
129
+ 'unexpected results. Convert it to a sequence/iterable of keyed ' +
130
+ 'ReactElements instead.%s',
131
+ mapsAsChildrenAddendum,
132
);
133
didWarnAboutMaps = true;
134
}
@@ -140,14 +144,13 @@ function traverseAllChildrenImpl(
144
child,
145
nextName,
146
callback,
143
- traverseContext
147
+ traverseContext,
148
);
149
}
150
} else if (type === 'object') {
151
var addendum = '';
152
if (__DEV__) {
149
- addendum =
150
- ' If you meant to render a collection of children, use an array ' +
153
+ addendum = ' If you meant to render a collection of children, use an array ' +
154
'instead or wrap the object using createFragment(object) from the ' +
155
'React add-ons.';
156
if (ReactCurrentOwner.current) {
@@ -161,10 +164,10 @@ function traverseAllChildrenImpl(
164
invariant(
165
false,
166
'Objects are not valid as a React child (found: %s).%s',
164
- childrenString === '[object Object]' ?
165
- 'object with keys {' + Object.keys(children).join(', ') + '}' :
166
- childrenString,
167
- addendum
167
+ childrenString === '[object Object]'
168
+ ? 'object with keys {' + Object.keys(children).join(', ') + '}'
169
+ : childrenString,
170
+ addendum,
171
);
172
}
173
}
src/test/ReactComponentTreeTestUtils.js
+11
-9
@@ -14,13 +14,15 @@
14
var ReactComponentTreeHook = require('react/lib/ReactComponentTreeHook');
15
16
function getRootDisplayNames() {
17
- return ReactComponentTreeHook.getRootIDs()
18
- .map(ReactComponentTreeHook.getDisplayName);
17
+ return ReactComponentTreeHook.getRootIDs().map(
18
+ ReactComponentTreeHook.getDisplayName,
19
+ );
20
}
21
22
function getRegisteredDisplayNames() {
22
- return ReactComponentTreeHook.getRegisteredIDs()
23
- .map(ReactComponentTreeHook.getDisplayName);
23
+ return ReactComponentTreeHook.getRegisteredIDs().map(
24
+ ReactComponentTreeHook.getDisplayName,
25
+ );
26
}
27
28
function expectTree(rootID, expectedTree, parentPath) {
@@ -48,14 +50,14 @@ function expectTree(rootID, expectedTree, parentPath) {
50
expectEqual(
51
ReactComponentTreeHook.getDisplayName(parentID),
52
expectedTree.parentDisplayName,
51
- 'parentDisplayName'
53
+ 'parentDisplayName',
54
);
55
}
56
if (expectedTree.ownerDisplayName !== undefined) {
57
expectEqual(
58
ReactComponentTreeHook.getDisplayName(ownerID),
59
expectedTree.ownerDisplayName,
58
- 'ownerDisplayName'
60
+ 'ownerDisplayName',
61
);
62
}
63
if (expectedTree.parentID !== undefined) {
@@ -73,7 +75,7 @@ function expectTree(rootID, expectedTree, parentPath) {
75
expectEqual(
76
element && element.type,
77
expectedTree.element && expectedTree.element.type,
76
- 'element.type'
78
+ 'element.type',
79
);
80
} else if (text == null) {
81
expectEqual(typeof element, 'object', 'typeof element');
@@ -82,13 +84,13 @@ function expectTree(rootID, expectedTree, parentPath) {
84
expectEqual(
85
childIDs.length,
86
expectedTree.children.length,
85
- 'children.length'
87
+ 'children.length',
88
);
89
for (var i = 0; i < childIDs.length; i++) {
90
expectTree(
91
childIDs[i],
92
{parentID: rootID, ...expectedTree.children[i]},
91
- path
93
+ path,
94
);
95
}
96
} else {
src/test/ReactShallowRenderer.js
+30
-30
@@ -54,20 +54,14 @@ var ShallowComponentWrapper = function(element) {
54
55
this.construct(element);
56
};
57
-Object.assign(
58
- ShallowComponentWrapper.prototype,
59
- ReactCompositeComponent, {
60
- _constructComponent:
61
- ReactCompositeComponent._constructComponentWithoutOwner,
62
- _instantiateReactComponent: function(element) {
63
- return new NoopInternalComponent(element);
64
- },
65
- _replaceNodeWithMarkup: function() {},
66
- _renderValidatedComponent:
67
- ReactCompositeComponent
68
- ._renderValidatedComponentWithoutOwnerOrContext,
69
- }
70
-);
57
+Object.assign(ShallowComponentWrapper.prototype, ReactCompositeComponent, {
58
+ _constructComponent: ReactCompositeComponent._constructComponentWithoutOwner,
59
+ _instantiateReactComponent: function(element) {
60
+ return new NoopInternalComponent(element);
61
+ },
62
+ _replaceNodeWithMarkup: function() {},
63
+ _renderValidatedComponent: ReactCompositeComponent._renderValidatedComponentWithoutOwnerOrContext,
64
+});
65
66
function _batchedRender(renderer, element, context) {
67
var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(true);
@@ -90,17 +84,17 @@ class ReactShallowRenderer {
84
invariant(
85
React.isValidElement(element),
86
'ReactShallowRenderer render(): Invalid component element.%s',
93
- typeof element === 'function' ?
94
- ' Instead of passing a component class, make sure to instantiate ' +
95
- 'it by passing it to React.createElement.' :
96
- ''
87
+ typeof element === 'function'
88
+ ? ' Instead of passing a component class, make sure to instantiate ' +
89
+ 'it by passing it to React.createElement.'
90
+ : '',
91
);
92
invariant(
93
typeof element.type !== 'string',
94
'ReactShallowRenderer render(): Shallow rendering works only with custom ' +
101
- 'components, not primitives (%s). Instead of calling `.render(el)` and ' +
102
- 'inspecting the rendered output, look at `el.props` directly instead.',
103
- element.type
95
+ 'components, not primitives (%s). Instead of calling `.render(el)` and ' +
96
+ 'inspecting the rendered output, look at `el.props` directly instead.',
97
+ element.type,
98
);
99
100
if (!context) {
@@ -111,18 +105,17 @@ class ReactShallowRenderer {
105
return this.getRenderOutput();
106
}
107
getRenderOutput() {
114
- return (
115
- (this._instance && this._instance._renderedComponent &&
116
- this._instance._renderedComponent._renderedOutput)
117
- || null
118
- );
108
+ return (this._instance &&
109
+ this._instance._renderedComponent &&
110
+ this._instance._renderedComponent._renderedOutput) ||
111
+ null;
112
}
113
unmount() {
114
if (this._instance) {
115
ReactReconciler.unmountComponent(
116
this._instance,
124
- false, /* safely */
125
- false /* skipLifecycle */
117
+ false /* safely */,
118
+ false /* skipLifecycle */,
119
);
120
}
121
}
@@ -132,11 +125,18 @@ class ReactShallowRenderer {
125
this._instance,
126
element,
127
transaction,
135
- context
128
+ context,
129
);
130
} else {
131
var instance = new ShallowComponentWrapper(element);
139
- ReactReconciler.mountComponent(instance, transaction, null, null, context, 0);
132
+ ReactReconciler.mountComponent(
133
+ instance,
134
+ transaction,
135
+ null,
136
+ null,
137
+ context,
138
+ 0,
139
+ );
140
this._instance = instance;
141
}
142
}
src/test/ReactTestUtils.js
+66
-70
@@ -59,10 +59,7 @@ function findAllInRenderedStackTreeInternal(inst, test) {
59
continue;
60
}
61
ret = ret.concat(
62
- findAllInRenderedStackTreeInternal(
63
- renderedChildren[key],
64
- test
65
- )
62
+ findAllInRenderedStackTreeInternal(renderedChildren[key], test),
63
);
64
}
65
} else if (
@@ -70,7 +67,7 @@ function findAllInRenderedStackTreeInternal(inst, test) {
67
typeof currentElement.type === 'function'
68
) {
69
ret = ret.concat(
73
- findAllInRenderedStackTreeInternal(inst._renderedComponent, test)
70
+ findAllInRenderedStackTreeInternal(inst._renderedComponent, test),
71
);
72
}
73
return ret;
@@ -81,7 +78,7 @@ function findAllInRenderedFiberTreeInternal(fiber, test) {
78
return [];
79
}
80
var currentParent = ReactFiberTreeReflection.findCurrentFiberUsingSlowPath(
84
- fiber
81
+ fiber,
82
);
83
if (!currentParent) {
84
return [];
@@ -89,8 +86,12 @@ function findAllInRenderedFiberTreeInternal(fiber, test) {
86
let node = currentParent;
87
let ret = [];
88
while (true) {
92
- if (node.tag === HostComponent || node.tag === HostText ||
93
- node.tag === ClassComponent || node.tag === FunctionalComponent) {
89
+ if (
90
+ node.tag === HostComponent ||
91
+ node.tag === HostText ||
92
+ node.tag === ClassComponent ||
93
+ node.tag === FunctionalComponent
94
+ ) {
95
var publicInst = node.stateNode;
96
if (test(publicInst)) {
97
ret.push(publicInst);
@@ -140,10 +141,7 @@ var ReactTestUtils = {
141
},
142
143
isElementOfType: function(inst, convenienceConstructor) {
143
- return (
144
- React.isValidElement(inst) &&
145
- inst.type === convenienceConstructor
146
- );
144
+ return React.isValidElement(inst) && inst.type === convenienceConstructor;
145
},
146
147
isDOMComponent: function(inst) {
@@ -151,9 +149,7 @@ var ReactTestUtils = {
149
},
150
151
isDOMComponentElement: function(inst) {
154
- return !!(inst &&
155
- React.isValidElement(inst) &&
156
- !!inst.tagName);
152
+ return !!(inst && React.isValidElement(inst) && !!inst.tagName);
153
},
154
155
isCompositeComponent: function(inst) {
@@ -163,8 +159,8 @@ var ReactTestUtils = {
159
return false;
160
}
161
return inst != null &&
166
- typeof inst.render === 'function' &&
167
- typeof inst.setState === 'function';
162
+ typeof inst.render === 'function' &&
163
+ typeof inst.setState === 'function';
164
},
165
166
isCompositeComponentWithType: function(inst, type) {
@@ -172,11 +168,11 @@ var ReactTestUtils = {
168
return false;
169
}
170
var internalInstance = ReactInstanceMap.get(inst);
175
- var constructor = typeof internalInstance.tag === 'number' ?
176
- internalInstance.type : // Fiber reconciler
177
- internalInstance._currentElement.type; // Stack reconciler
171
+ var constructor = typeof internalInstance.tag === 'number'
172
+ ? internalInstance.type // Fiber reconciler
173
+ : internalInstance._currentElement.type; // Stack reconciler
174
179
- return (constructor === type);
175
+ return constructor === type;
176
},
177
178
// TODO: deprecate? It's undocumented and unused.
@@ -187,21 +183,17 @@ var ReactTestUtils = {
183
// We check the prototype of the type that will get mounted, not the
184
// instance itself. This is a future proof way of duck typing.
185
var prototype = inst.type.prototype;
190
- return (
191
- typeof prototype.render === 'function' &&
192
- typeof prototype.setState === 'function'
193
- );
186
+ return typeof prototype.render === 'function' &&
187
+ typeof prototype.setState === 'function';
188
},
189
190
// TODO: deprecate? It's undocumented and unused.
191
isCompositeComponentElementWithType: function(inst, type) {
192
var internalInstance = ReactInstanceMap.get(inst);
199
- var constructor = internalInstance
200
- ._currentElement
201
- .type;
193
+ var constructor = internalInstance._currentElement.type;
194
195
return !!(ReactTestUtils.isCompositeComponentElement(inst) &&
204
- (constructor === type));
196
+ constructor === type);
197
},
198
199
// TODO: deprecate? It's undocumented and unused.
@@ -219,7 +211,7 @@ var ReactTestUtils = {
211
}
212
invariant(
213
ReactTestUtils.isCompositeComponent(inst),
222
- 'findAllInRenderedTree(...): instance must be a composite component'
214
+ 'findAllInRenderedTree(...): instance must be a composite component',
215
);
216
var internalInstance = ReactInstanceMap.get(inst);
217
if (internalInstance && typeof internalInstance.tag === 'number') {
@@ -248,7 +240,7 @@ var ReactTestUtils = {
240
invariant(
241
classNames !== undefined,
242
'TestUtils.scryRenderedDOMComponentsWithClass expects a ' +
251
- 'className as a second argument.'
243
+ 'className as a second argument.',
244
);
245
classNames = classNames.split(/\s+/);
246
}
@@ -267,18 +259,22 @@ var ReactTestUtils = {
259
* @return {!ReactDOMComponent} The one match.
260
*/
261
findRenderedDOMComponentWithClass: function(root, className) {
270
- var all =
271
- ReactTestUtils.scryRenderedDOMComponentsWithClass(root, className);
262
+ var all = ReactTestUtils.scryRenderedDOMComponentsWithClass(
263
+ root,
264
+ className,
265
+ );
266
if (all.length !== 1) {
267
throw new Error(
274
- 'Did not find exactly one match (found: ' + all.length + ') ' +
275
- 'for class:' + className
268
+ 'Did not find exactly one match (found: ' +
269
+ all.length +
270
+ ') ' +
271
+ 'for class:' +
272
+ className,
273
);
274
}
275
return all[0];
276
},
277
281
-
278
/**
279
* Finds all instance of components in the rendered tree that are DOM
280
* components with the tag name matching `tagName`.
@@ -287,7 +283,7 @@ var ReactTestUtils = {
283
scryRenderedDOMComponentsWithTag: function(root, tagName) {
284
return ReactTestUtils.findAllInRenderedTree(root, function(inst) {
285
return ReactTestUtils.isDOMComponent(inst) &&
290
- inst.tagName.toUpperCase() === tagName.toUpperCase();
286
+ inst.tagName.toUpperCase() === tagName.toUpperCase();
287
});
288
},
289
@@ -301,24 +297,23 @@ var ReactTestUtils = {
297
var all = ReactTestUtils.scryRenderedDOMComponentsWithTag(root, tagName);
298
if (all.length !== 1) {
299
throw new Error(
304
- 'Did not find exactly one match (found: ' + all.length + ') ' +
305
- 'for tag:' + tagName
300
+ 'Did not find exactly one match (found: ' +
301
+ all.length +
302
+ ') ' +
303
+ 'for tag:' +
304
+ tagName,
305
);
306
}
307
return all[0];
308
},
309
311
-
310
/**
311
* Finds all instances of components with type equal to `componentType`.
312
* @return {array} an array of all the matches.
313
*/
314
scryRenderedComponentsWithType: function(root, componentType) {
315
return ReactTestUtils.findAllInRenderedTree(root, function(inst) {
318
- return ReactTestUtils.isCompositeComponentWithType(
319
- inst,
320
- componentType
321
- );
316
+ return ReactTestUtils.isCompositeComponentWithType(inst, componentType);
317
});
318
},
319
@@ -331,12 +326,15 @@ var ReactTestUtils = {
326
findRenderedComponentWithType: function(root, componentType) {
327
var all = ReactTestUtils.scryRenderedComponentsWithType(
328
root,
334
- componentType
329
+ componentType,
330
);
331
if (all.length !== 1) {
332
throw new Error(
338
- 'Did not find exactly one match (found: ' + all.length + ') ' +
339
- 'for componentType:' + componentType
333
+ 'Did not find exactly one match (found: ' +
334
+ all.length +
335
+ ') ' +
336
+ 'for componentType:' +
337
+ componentType,
338
);
339
}
340
return all[0];
@@ -359,11 +357,7 @@ var ReactTestUtils = {
357
mockTagName = mockTagName || module.mockTagName || 'div';
358
359
module.prototype.render.mockImplementation(function() {
362
- return React.createElement(
363
- mockTagName,
364
- null,
365
- this.props.children
366
- );
360
+ return React.createElement(mockTagName, null, this.props.children);
361
});
362
363
return this;
@@ -380,7 +374,7 @@ var ReactTestUtils = {
374
fakeNativeEvent.target = node;
375
ReactBrowserEventEmitter.ReactEventListener.dispatchEvent(
376
topLevelType,
383
- fakeNativeEvent
377
+ fakeNativeEvent,
378
);
379
},
380
@@ -392,21 +386,20 @@ var ReactTestUtils = {
386
* @param {?Event} fakeNativeEvent Fake native event to use in SyntheticEvent.
387
*/
388
simulateNativeEventOnDOMComponent: function(
395
- topLevelType,
396
- comp,
397
- fakeNativeEvent) {
389
+ topLevelType,
390
+ comp,
391
+ fakeNativeEvent,
392
+ ) {
393
ReactTestUtils.simulateNativeEventOnNode(
394
topLevelType,
395
findDOMNode(comp),
401
- fakeNativeEvent
396
+ fakeNativeEvent,
397
);
398
},
399
400
nativeTouchData: function(x, y) {
401
return {
407
- touches: [
408
- {pageX: x, pageY: y},
409
- ],
402
+ touches: [{pageX: x, pageY: y}],
403
};
404
},
405
@@ -432,7 +425,7 @@ function makeSimulator(eventType) {
425
invariant(
426
!React.isValidElement(domComponentOrNode),
427
'TestUtils.Simulate expects a component instance and not a ReactElement.' +
435
- 'TestUtils.Simulate will not work if you are using shallow rendering.'
428
+ 'TestUtils.Simulate will not work if you are using shallow rendering.',
429
);
430
if (ReactTestUtils.isDOMComponent(domComponentOrNode)) {
431
node = findDOMNode(domComponentOrNode);
@@ -440,8 +433,9 @@ function makeSimulator(eventType) {
433
node = domComponentOrNode;
434
}
435
443
- var dispatchConfig =
444
- EventPluginRegistry.eventNameDispatchConfigs[eventType];
436
+ var dispatchConfig = EventPluginRegistry.eventNameDispatchConfigs[
437
+ eventType
438
+ ];
439
440
var fakeNativeEvent = new Event();
441
fakeNativeEvent.target = node;
@@ -454,7 +448,7 @@ function makeSimulator(eventType) {
448
dispatchConfig,
449
targetInst,
450
fakeNativeEvent,
457
- node
451
+ node,
452
);
453
454
// Since we aren't using pooling, always persist the event. This will make
@@ -530,14 +524,14 @@ function makeNativeSimulator(eventType) {
524
ReactTestUtils.simulateNativeEventOnDOMComponent(
525
eventType,
526
domComponentOrNode,
533
- fakeNativeEvent
527
+ fakeNativeEvent,
528
);
529
} else if (domComponentOrNode.tagName) {
530
// Will allow on actual dom nodes.
531
ReactTestUtils.simulateNativeEventOnNode(
532
eventType,
533
domComponentOrNode,
540
- fakeNativeEvent
534
+ fakeNativeEvent,
535
);
536
}
537
};
@@ -545,14 +539,16 @@ function makeNativeSimulator(eventType) {
539
540
Object.keys(topLevelTypes).forEach(function(eventType) {
541
// Event type is stored as 'topClick' - we transform that to 'click'
548
- var convenienceName = eventType.indexOf('top') === 0 ?
549
- eventType.charAt(3).toLowerCase() + eventType.substr(4) : eventType;
542
+ var convenienceName = eventType.indexOf('top') === 0
543
+ ? eventType.charAt(3).toLowerCase() + eventType.substr(4)
544
+ : eventType;
545
/**
546
* @param {!Element|ReactDOMComponent} domComponentOrNode
547
* @param {?Event} nativeEventData Fake native event to use in SyntheticEvent.
548
*/
554
- ReactTestUtils.SimulateNative[convenienceName] =
555
- makeNativeSimulator(eventType);
549
+ ReactTestUtils.SimulateNative[convenienceName] = makeNativeSimulator(
550
+ eventType,
551
+ );
552
});
553
554
module.exports = ReactTestUtils;
src/test/__tests__/ReactTestUtils-test.js
+43
-37
@@ -17,7 +17,6 @@ var ReactDOMServer;
17
var ReactTestUtils;
18
19
describe('ReactTestUtils', () => {
20
-
20
beforeEach(() => {
21
React = require('react');
22
ReactDOM = require('react-dom');
@@ -77,14 +76,14 @@ describe('ReactTestUtils', () => {
76
var shallowRenderer = ReactTestUtils.createRenderer();
77
expect(() => shallowRenderer.render(SomeComponent)).toThrowError(
78
'ReactShallowRenderer render(): Invalid component element. Instead of ' +
80
- 'passing a component class, make sure to instantiate it by passing it ' +
81
- 'to React.createElement.'
79
+ 'passing a component class, make sure to instantiate it by passing it ' +
80
+ 'to React.createElement.',
81
);
82
expect(() => shallowRenderer.render(<div />)).toThrowError(
83
'ReactShallowRenderer render(): Shallow rendering works only with ' +
85
- 'custom components, not primitives (div). Instead of calling ' +
86
- '`.render(el)` and inspecting the rendered output, look at `el.props` ' +
87
- 'directly instead.'
84
+ 'custom components, not primitives (div). Instead of calling ' +
85
+ '`.render(el)` and inspecting the rendered output, look at `el.props` ' +
86
+ 'directly instead.',
87
);
88
});
89
@@ -143,10 +142,7 @@ describe('ReactTestUtils', () => {
142
143
if (this.props.aNew === 'prop') {
144
return (
146
- <a
147
- href="#"
148
- onClick={this.onClick}
149
- className={className}>
145
+ <a href="#" onClick={this.onClick} className={className}>
146
Test link
147
</a>
148
);
@@ -217,7 +213,7 @@ describe('ReactTestUtils', () => {
213
state = {clicked: false};
214
215
handleUserClick = () => {
220
- this.setState({ clicked: true });
216
+ this.setState({clicked: true});
217
};
218
219
render() {
@@ -294,11 +290,11 @@ describe('ReactTestUtils', () => {
290
shallowRenderer.render(<SimpleComponent />);
291
expectDev(console.error.calls.count()).toBe(1);
292
expect(
297
- console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)')
293
+ console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)'),
294
).toBe(
295
'Warning: Failed context type: The context `name` is marked as ' +
300
- 'required in `SimpleComponent`, but its value is `undefined`.\n' +
301
- ' in SimpleComponent (at **)'
296
+ 'required in `SimpleComponent`, but its value is `undefined`.\n' +
297
+ ' in SimpleComponent (at **)',
298
);
299
});
300
@@ -312,7 +308,7 @@ describe('ReactTestUtils', () => {
308
var renderedComponent = ReactTestUtils.renderIntoDocument(<Wrapper />);
309
var scryResults = ReactTestUtils.scryRenderedDOMComponentsWithClass(
310
renderedComponent,
315
- 'NonExistentClass'
311
+ 'NonExistentClass',
312
);
313
expect(scryResults.length).toBe(0);
314
});
@@ -327,7 +323,7 @@ describe('ReactTestUtils', () => {
323
var renderedComponent = ReactTestUtils.renderIntoDocument(<Wrapper />);
324
var scryResults = ReactTestUtils.scryRenderedDOMComponentsWithClass(
325
renderedComponent,
330
- 'x'
326
+ 'x',
327
);
328
expect(scryResults.length).toBe(1);
329
});
@@ -342,19 +338,19 @@ describe('ReactTestUtils', () => {
338
var renderedComponent = ReactTestUtils.renderIntoDocument(<Wrapper />);
339
var scryResults1 = ReactTestUtils.scryRenderedDOMComponentsWithClass(
340
renderedComponent,
345
- 'x y'
341
+ 'x y',
342
);
343
expect(scryResults1.length).toBe(1);
344
345
var scryResults2 = ReactTestUtils.scryRenderedDOMComponentsWithClass(
346
renderedComponent,
351
- 'x z'
347
+ 'x z',
348
);
349
expect(scryResults2.length).toBe(1);
350
351
var scryResults3 = ReactTestUtils.scryRenderedDOMComponentsWithClass(
352
renderedComponent,
357
- ['x', 'y']
353
+ ['x', 'y'],
354
);
355
expect(scryResults3.length).toBe(1);
356
@@ -363,13 +359,13 @@ describe('ReactTestUtils', () => {
359
360
var scryResults4 = ReactTestUtils.scryRenderedDOMComponentsWithClass(
361
renderedComponent,
366
- ['x', 'a']
362
+ ['x', 'a'],
363
);
364
expect(scryResults4.length).toBe(0);
365
366
var scryResults5 = ReactTestUtils.scryRenderedDOMComponentsWithClass(
367
renderedComponent,
372
- ['x a']
368
+ ['x a'],
369
);
370
expect(scryResults5.length).toBe(0);
371
});
@@ -387,14 +383,14 @@ describe('ReactTestUtils', () => {
383
{null}
384
<div>purple</div>
385
</Wrapper>,
390
- container
386
+ container,
387
);
388
var tree = ReactDOM.render(
389
<Wrapper>
390
<div>orange</div>
391
<div>purple</div>
392
</Wrapper>,
397
- container
393
+ container,
394
);
395
396
var log = [];
@@ -424,7 +420,7 @@ describe('ReactTestUtils', () => {
420
421
injectedDOMComponents.forEach(function(type) {
422
var testComponent = ReactTestUtils.renderIntoDocument(
427
- React.createElement(type)
423
+ React.createElement(type),
424
);
425
expect(testComponent.tagName).toBe(type.toUpperCase());
426
expect(ReactTestUtils.isDOMComponent(testComponent)).toBe(true);
@@ -467,13 +463,18 @@ describe('ReactTestUtils', () => {
463
};
464
spyOn(obj, 'handler').and.callThrough();
465
var container = document.createElement('div');
470
- var instance = ReactDOM.render(<input type="text" onChange={obj.handler} />, container);
466
+ var instance = ReactDOM.render(
467
+ <input type="text" onChange={obj.handler} />,
468
+ container,
469
+ );
470
471
var node = ReactDOM.findDOMNode(instance);
472
node.value = 'giraffe';
473
ReactTestUtils.Simulate.change(node);
474
476
- expect(obj.handler).toHaveBeenCalledWith(jasmine.objectContaining({target: node}));
475
+ expect(obj.handler).toHaveBeenCalledWith(
476
+ jasmine.objectContaining({target: node}),
477
+ );
478
});
479
480
it('should change the value of an input field in a component', () => {
@@ -494,13 +495,18 @@ describe('ReactTestUtils', () => {
495
};
496
spyOn(obj, 'handler').and.callThrough();
497
var container = document.createElement('div');
497
- var instance = ReactDOM.render(<SomeComponent handleChange={obj.handler} />, container);
498
+ var instance = ReactDOM.render(
499
+ <SomeComponent handleChange={obj.handler} />,
500
+ container,
501
+ );
502
503
var node = ReactDOM.findDOMNode(instance.refs.input);
504
node.value = 'zebra';
505
ReactTestUtils.Simulate.change(node);
506
503
- expect(obj.handler).toHaveBeenCalledWith(jasmine.objectContaining({target: node}));
507
+ expect(obj.handler).toHaveBeenCalledWith(
508
+ jasmine.objectContaining({target: node}),
509
+ );
510
});
511
512
it('should throw when attempting to use ReactTestUtils.Simulate with shallow rendering', () => {
@@ -516,11 +522,13 @@ describe('ReactTestUtils', () => {
522
523
var handler = jasmine.createSpy('spy');
524
var shallowRenderer = ReactTestUtils.createRenderer();
519
- var result = shallowRenderer.render(<SomeComponent handleClick={handler} />);
525
+ var result = shallowRenderer.render(
526
+ <SomeComponent handleClick={handler} />,
527
+ );
528
529
expect(() => ReactTestUtils.Simulate.click(result)).toThrowError(
530
'TestUtils.Simulate expects a component instance and not a ReactElement.' +
523
- 'TestUtils.Simulate will not work if you are using shallow rendering.'
531
+ 'TestUtils.Simulate will not work if you are using shallow rendering.',
532
);
533
expect(handler).not.toHaveBeenCalled();
534
});
@@ -531,7 +539,7 @@ describe('ReactTestUtils', () => {
539
var CLIENT_X = 100;
540
541
class Component extends React.Component {
534
- handleClick = (e) => {
542
+ handleClick = e => {
543
expect(e.clientX).toBe(CLIENT_X);
544
};
545
@@ -542,10 +550,9 @@ describe('ReactTestUtils', () => {
550
551
var element = document.createElement('div');
552
var instance = ReactDOM.render(<Component />, element);
545
- ReactTestUtils.Simulate.click(
546
- ReactDOM.findDOMNode(instance),
547
- {clientX: CLIENT_X}
548
- );
553
+ ReactTestUtils.Simulate.click(ReactDOM.findDOMNode(instance), {
554
+ clientX: CLIENT_X,
555
+ });
556
expectDev(console.error.calls.count()).toBe(0);
557
});
558
@@ -571,7 +578,7 @@ describe('ReactTestUtils', () => {
578
describe('Simulate', () => {
579
it('should set the type of the event', () => {
580
let event;
574
- const stub = jest.genMockFn().mockImplementation((e) => {
581
+ const stub = jest.genMockFn().mockImplementation(e => {
582
e.persist();
583
event = e;
584
});
@@ -586,5 +593,4 @@ describe('ReactTestUtils', () => {
593
expect(event.nativeEvent.type).toBe('keydown');
594
});
595
});
589
-
596
});
src/test/__tests__/reactComponentExpect-test.js
+2
-7
@@ -16,7 +16,6 @@ var ReactTestUtils;
16
var reactComponentExpect;
17
18
describe('reactComponentExpect', () => {
19
-
19
beforeEach(() => {
20
React = require('react');
21
ReactTestUtils = require('ReactTestUtils');
@@ -27,9 +26,7 @@ describe('reactComponentExpect', () => {
26
class SomeComponent extends React.Component {
27
state = {y: 2};
28
render() {
30
- return (
31
- <div className="Hello" />
32
- );
29
+ return <div className="Hello" />;
30
}
31
}
32
@@ -46,9 +43,7 @@ describe('reactComponentExpect', () => {
43
it('should match empty DOM components', () => {
44
class SomeComponent extends React.Component {
45
render() {
49
- return (
50
- <div className="Hello" />
51
- );
46
+ return <div className="Hello" />;
47
}
48
}
49
src/test/getTestDocument.js
+2
-1
@@ -14,7 +14,8 @@
14
function getTestDocument(markup) {
15
document.open();
16
document.write(
17
- markup || '<!doctype html><html><meta charset=utf-8><title>test doc</title>'
17
+ markup ||
18
+ '<!doctype html><html><meta charset=utf-8><title>test doc</title>',
19
);
20
document.close();
21
return document;
src/test/reactComponentExpect.js
+17
-17
@@ -44,7 +44,7 @@ function reactComponentExpect(instance) {
44
45
invariant(
46
ReactTestUtils.isCompositeComponent(instance),
47
- 'reactComponentExpect(...): instance must be a composite component'
47
+ 'reactComponentExpect(...): instance must be a composite component',
48
);
49
var internalInstance = ReactInstanceMap.get(instance);
50
@@ -124,8 +124,7 @@ Object.assign(reactComponentExpectInternal.prototype, {
124
}
125
} else {
126
// Stack reconciler
127
- var renderedChildren =
128
- this._instance._renderedChildren || {};
127
+ var renderedChildren = this._instance._renderedChildren || {};
128
for (var name in renderedChildren) {
129
if (!renderedChildren.hasOwnProperty(name)) {
130
continue;
@@ -174,14 +173,10 @@ Object.assign(reactComponentExpectInternal.prototype, {
173
toBeComponentOfType: function(constructor) {
174
if (typeof this._instance.tag === 'number') {
175
// Fiber reconciler
177
- expect(
178
- this._instance.type === constructor
179
- ).toBe(true);
176
+ expect(this._instance.type === constructor).toBe(true);
177
} else {
178
// Stack reconciler
182
- expect(
183
- this._instance._currentElement.type === constructor
184
- ).toBe(true);
179
+ expect(this._instance._currentElement.type === constructor).toBe(true);
180
}
181
return this;
182
},
@@ -195,7 +190,7 @@ Object.assign(reactComponentExpectInternal.prototype, {
190
// and doesn't work with them.
191
expect(
192
typeof this.instance() === 'object' &&
198
- typeof this.instance().render === 'function'
193
+ typeof this.instance().render === 'function',
194
).toBe(true);
195
return this;
196
},
@@ -211,7 +206,9 @@ Object.assign(reactComponentExpectInternal.prototype, {
206
// Fiber reconciler
207
expect(this._instance.tag === HostText).toBe(true);
208
var actualVal = this._instance.memoizedProps;
214
- expect(typeof actualVal === 'string' || typeof actualVal === 'number').toBe(true);
209
+ expect(
210
+ typeof actualVal === 'string' || typeof actualVal === 'number',
211
+ ).toBe(true);
212
expect('' + actualVal).toBe(val);
213
} else {
214
// Fiber reconciler
@@ -256,8 +253,9 @@ Object.assign(reactComponentExpectInternal.prototype, {
253
if (!stateNameToExpectedValue.hasOwnProperty(stateName)) {
254
continue;
255
}
259
- expect(this.instance().state[stateName])
260
- .toEqual(stateNameToExpectedValue[stateName]);
256
+ expect(this.instance().state[stateName]).toEqual(
257
+ stateNameToExpectedValue[stateName],
258
+ );
259
}
260
return this;
261
},
@@ -272,8 +270,9 @@ Object.assign(reactComponentExpectInternal.prototype, {
270
if (!propNameToExpectedValue.hasOwnProperty(propName)) {
271
continue;
272
}
275
- expect(this.instance().props[propName])
276
- .toEqual(propNameToExpectedValue[propName]);
273
+ expect(this.instance().props[propName]).toEqual(
274
+ propNameToExpectedValue[propName],
275
+ );
276
}
277
return this;
278
},
@@ -288,8 +287,9 @@ Object.assign(reactComponentExpectInternal.prototype, {
287
if (!contextNameToExpectedValue.hasOwnProperty(contextName)) {
288
continue;
289
}
291
- expect(this.instance().context[contextName])
292
- .toEqual(contextNameToExpectedValue[contextName]);
290
+ expect(this.instance().context[contextName]).toEqual(
291
+ contextNameToExpectedValue[contextName],
292
+ );
293
}
294
return this;
295
},
src/umd/ReactUMDEntry.js
+8
-5
@@ -14,11 +14,14 @@
14
var React = require('React');
15
16
// `version` will be added here by the React module.
17
-var ReactUMDEntry = Object.assign({
18
- __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: {
19
- ReactCurrentOwner: require('react/lib/ReactCurrentOwner'),
17
+var ReactUMDEntry = Object.assign(
18
+ {
19
+ __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: {
20
+ ReactCurrentOwner: require('react/lib/ReactCurrentOwner'),
21
+ },
22
},
21
-}, React);
23
+ React,
24
+);
25
26
if (__DEV__) {
27
Object.assign(
@@ -26,7 +29,7 @@ if (__DEV__) {
29
{
30
// ReactComponentTreeHook should not be included in production.
31
ReactComponentTreeHook: require('react/lib/ReactComponentTreeHook'),
29
- }
32
+ },
33
);
34
}
35
src/umd/ReactWithAddonsUMDEntry.js
+9
-6
@@ -14,12 +14,15 @@
14
var ReactWithAddons = require('ReactWithAddons');
15
16
// `version` will be added here by the React module.
17
-var ReactWithAddonsUMDEntry = Object.assign({
18
- __SECRET_INJECTED_REACT_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: null, // Will be injected by ReactDOM UMD build.
19
- __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: {
20
- ReactCurrentOwner: require('react/lib/ReactCurrentOwner'),
17
+var ReactWithAddonsUMDEntry = Object.assign(
18
+ {
19
+ __SECRET_INJECTED_REACT_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: null, // Will be injected by ReactDOM UMD build.
20
+ __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: {
21
+ ReactCurrentOwner: require('react/lib/ReactCurrentOwner'),
22
+ },
23
},
22
-}, ReactWithAddons);
24
+ ReactWithAddons,
25
+);
26
27
if (__DEV__) {
28
Object.assign(
@@ -27,7 +30,7 @@ if (__DEV__) {
30
{
31
// ReactComponentTreeHook should not be included in production.
32
ReactComponentTreeHook: require('react/lib/ReactComponentTreeHook'),
30
- }
33
+ },
34
);
35
}
36