Merge branch '15-dev' into 15-stable

This commit is contained in:
Paul O’Shannessy committed 2016-09-19 10:22:31 -07:00
commit 15631e02a2
36 files changed
+990 -315

No files matched your search

+1
View File
@@ -44,6 +44,7 @@ var addons = {
shallowCompare: {
module: 'shallowCompare',
name: 'shallow-compare',
docs: 'shallow-compare',
},
updates: {
module: 'update',
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "react-build",
"version": "15.3.1",
"version": "15.3.2-rc.1",
"dependencies": {
"art": {
"version": "0.10.1",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "react-build",
"private": true,
"version": "15.3.1",
"version": "15.3.2-rc.1",
"devDependencies": {
"art": "^0.10.1",
"async": "^1.5.0",
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "react-addons-template",
"version": "15.3.1",
"version": "15.3.2-rc.1",
"main": "index.js",
"repository": "facebook/react",
"keywords": [
@@ -10,7 +10,7 @@
"license": "BSD-3-Clause",
"dependencies": {},
"peerDependencies": {
"react": "^15.3.1"
"react": "^15.3.2-rc.1"
},
"files": [
"LICENSE",
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "react-dom",
"version": "15.3.1",
"version": "15.3.2-rc.1",
"description": "React package for working with the DOM.",
"main": "index.js",
"repository": "facebook/react",
@@ -14,7 +14,7 @@
"homepage": "https://facebook.github.io/react/",
"dependencies": {},
"peerDependencies": {
"react": "^15.3.1"
"react": "^15.3.2-rc.1"
},
"files": [
"LICENSE",
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "react-native-renderer",
"version": "15.3.1",
"version": "15.3.2-rc.1",
"description": "React package for use inside react-native.",
"main": "index.js",
"repository": "facebook/react",
@@ -14,7 +14,7 @@
},
"homepage": "https://facebook.github.io/react-native/",
"dependencies": {
"react": "^15.3.1"
"react": "^15.3.2-rc.1"
},
"files": [
"LICENSE",
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "react-test-renderer",
"version": "15.3.1",
"version": "15.3.2-rc.1",
"description": "React package for snapshot testing.",
"main": "index.js",
"repository": "facebook/react",
@@ -15,7 +15,7 @@
},
"homepage": "https://facebook.github.io/react/",
"peerDependencies": {
"react": "^15.3.1"
"react": "^15.3.2-rc.1"
},
"files": [
"LICENSE",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "react",
"description": "React is a JavaScript library for building user interfaces.",
"version": "15.3.1",
"version": "15.3.2-rc.1",
"keywords": [
"react"
],
+1 -1
View File
@@ -11,4 +11,4 @@
'use strict';
module.exports = '15.3.1';
module.exports = '15.3.2-rc.1';
@@ -204,16 +204,6 @@ ReactElement.createElement = function(type, config, children) {
var source = null;
if (config != null) {
if (__DEV__) {
warning(
/* eslint-disable no-proto */
config.__proto__ == null || config.__proto__ === Object.prototype,
/* eslint-enable no-proto */
'React.createElement(...): Expected props argument to be a plain object. ' +
'Properties defined in its prototype chain will be ignored.'
);
}
if (hasValidRef(config)) {
ref = config.ref;
}
@@ -334,16 +324,6 @@ ReactElement.cloneElement = function(element, config, children) {
var owner = element._owner;
if (config != null) {
if (__DEV__) {
warning(
/* eslint-disable no-proto */
config.__proto__ == null || config.__proto__ === Object.prototype,
/* eslint-enable no-proto */
'React.cloneElement(...): Expected props argument to be a plain object. ' +
'Properties defined in its prototype chain will be ignored.'
);
}
if (hasValidRef(config)) {
// Silently steal the ref from the parent.
ref = config.ref;
@@ -188,18 +188,6 @@ describe('ReactElement', function() {
expect(element.props.foo).toBe(1);
});
it('warns if the config object inherits from any type other than Object', function() {
spyOn(console, 'error');
React.createElement('div', {foo: 1});
expect(console.error).not.toHaveBeenCalled();
React.createElement('div', Object.create({foo: 1}));
expect(console.error.calls.count()).toBe(1);
expect(console.error.calls.argsFor(0)[0]).toContain(
'React.createElement(...): Expected props argument to be a plain object. ' +
'Properties defined in its prototype chain will be ignored.'
);
});
it('extracts key and ref from the config', function() {
var element = React.createFactory(ComponentClass)({
key: '12',
@@ -75,18 +75,6 @@ describe('ReactElementClone', function() {
expect(ReactDOM.findDOMNode(component).childNodes[0].className).toBe('xyz');
});
it('should warn if the config object inherits from any type other than Object', function() {
spyOn(console, 'error');
React.cloneElement('div', {foo: 1});
expect(console.error).not.toHaveBeenCalled();
React.cloneElement('div', Object.create({foo: 1}));
expect(console.error.calls.count()).toBe(1);
expect(console.error.calls.argsFor(0)[0]).toContain(
'React.cloneElement(...): Expected props argument to be a plain object. ' +
'Properties defined in its prototype chain will be ignored.'
);
});
it('does not fail if config has no prototype', function() {
var config = Object.create(null, {foo: {value: 1, enumerable: true}});
React.cloneElement(<div />, config);
@@ -86,6 +86,94 @@ describe('ReactDOMProduction', function() {
expect(container.childNodes.length).toBe(0);
});
it('should call lifecycle methods', function() {
var log = [];
class Component extends React.Component {
state = {y: 1};
shouldComponentUpdate(nextProps, nextState) {
log.push(['shouldComponentUpdate', nextProps, nextState]);
return nextProps.x !== this.props.x || nextState.y !== this.state.y;
}
componentWillMount() {
log.push(['componentWillMount']);
}
componentDidMount() {
log.push(['componentDidMount']);
}
componentWillReceiveProps(nextProps) {
log.push(['componentWillReceiveProps', nextProps]);
}
componentWillUpdate(nextProps, nextState) {
log.push(['componentWillUpdate', nextProps, nextState]);
}
componentDidUpdate(prevProps, prevState) {
log.push(['componentDidUpdate', prevProps, prevState]);
}
componentWillUnmount() {
log.push(['componentWillUnmount']);
}
render() {
log.push(['render']);
return null;
}
}
var container = document.createElement('div');
var inst = ReactDOM.render(
<Component x={1} />,
container
);
expect(log).toEqual([
['componentWillMount'],
['render'],
['componentDidMount'],
]);
log = [];
inst.setState({y: 2});
expect(log).toEqual([
['shouldComponentUpdate', {x: 1}, {y: 2}],
['componentWillUpdate', {x: 1}, {y: 2}],
['render'],
['componentDidUpdate', {x: 1}, {y: 1}],
]);
log = [];
inst.setState({y: 2});
expect(log).toEqual([
['shouldComponentUpdate', {x: 1}, {y: 2}],
]);
log = [];
ReactDOM.render(
<Component x={2} />,
container
);
expect(log).toEqual([
['componentWillReceiveProps', {x: 2}],
['shouldComponentUpdate', {x: 2}, {y: 2}],
['componentWillUpdate', {x: 2}, {y: 2}],
['render'],
['componentDidUpdate', {x: 1}, {y: 2}],
]);
log = [];
ReactDOM.render(
<Component x={2} />,
container
);
expect(log).toEqual([
['componentWillReceiveProps', {x: 2}],
['shouldComponentUpdate', {x: 2}, {y: 2}],
]);
log = [];
ReactDOM.unmountComponentAtNode(container);
expect(log).toEqual([
['componentWillUnmount'],
]);
});
it('should throw with an error code in production', function() {
expect(function() {
class Component extends React.Component {
@@ -346,6 +346,19 @@ var ReactBrowserEventEmitter = Object.assign({}, ReactEventEmitterMixin, {
);
},
/**
* Protect against document.createEvent() returning null
* Some popup blocker extensions appear to do this:
* https://github.com/facebook/react/issues/6887
*/
supportsEventPageXY: function() {
if (!document.createEvent) {
return false;
}
var ev = document.createEvent('MouseEvent');
return ev != null && 'pageX' in ev;
},
/**
* Listens to window scroll and resize events. We cache scroll values so that
* application code can access them without triggering reflows.
@@ -359,8 +372,7 @@ var ReactBrowserEventEmitter = Object.assign({}, ReactEventEmitterMixin, {
*/
ensureScrollValueMonitoring: function() {
if (hasEventPageXY === undefined) {
hasEventPageXY =
document.createEvent && 'pageX' in document.createEvent('MouseEvent');
hasEventPageXY = ReactBrowserEventEmitter.supportsEventPageXY();
}
if (!hasEventPageXY && !isMonitoringScrollValue) {
var refresh = ViewportMetrics.refreshScrollValues;
@@ -454,4 +454,20 @@ describe('ReactBrowserEventEmitter', function() {
expect(idCallOrder[2]).toBe(getInternal(GRANDPARENT));
});
it('should not crash ensureScrollValueMonitoring when createEvent returns null', function() {
var originalCreateEvent = document.createEvent;
document.createEvent = function() {
return null;
};
spyOn(document, 'createEvent');
try {
var hasEventPageXY = ReactBrowserEventEmitter.supportsEventPageXY();
expect(document.createEvent.calls.count()).toBe(1);
expect(hasEventPageXY).toBe(false);
} finally {
document.createEvent = originalCreateEvent;
}
});
});
@@ -348,11 +348,12 @@ function getNativeBeforeInputChars(topLevelType, nativeEvent) {
function getFallbackBeforeInputChars(topLevelType, nativeEvent) {
// If we are currently composing (IME) and using a fallback to do so,
// try to extract the composed characters from the fallback object.
// If composition event is available, we extract a string only at
// compositionevent, otherwise extract it at fallback events.
if (currentComposition) {
if (
topLevelType === topLevelTypes.topCompositionEnd ||
isFallbackCompositionEnd(topLevelType, nativeEvent)
) {
if (topLevelType === topLevelTypes.topCompositionEnd
|| (!canUseCompositionEvent
&& isFallbackCompositionEnd(topLevelType, nativeEvent))) {
var chars = currentComposition.getData();
FallbackCompositionState.release(currentComposition);
currentComposition = null;
@@ -68,7 +68,7 @@ var doesChangeEventBubble = false;
if (ExecutionEnvironment.canUseDOM) {
// See `handleChange` comment below
doesChangeEventBubble = isEventSupported('change') && (
!('documentMode' in document) || document.documentMode > 8
!document.documentMode || document.documentMode > 8
);
}
@@ -149,7 +149,7 @@ if (ExecutionEnvironment.canUseDOM) {
// IE10+ fire input events to often, such when a placeholder
// changes or when an input with a placeholder is focused.
isInputEventSupported = isEventSupported('input') && (
!('documentMode' in document) || document.documentMode > 11
!document.documentMode || document.documentMode > 11
);
}
@@ -42,6 +42,7 @@ var eventTypes = {
topLevelTypes.topContextMenu,
topLevelTypes.topFocus,
topLevelTypes.topKeyDown,
topLevelTypes.topKeyUp,
topLevelTypes.topMouseDown,
topLevelTypes.topMouseUp,
topLevelTypes.topSelectionChange,
@@ -0,0 +1,209 @@
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails react-core
*/
'use strict';
var React = require('React');
var ReactTestUtils = require('ReactTestUtils');
var EventMapping = {
compositionstart : 'topCompositionStart',
compositionend : 'topCompositionEnd',
keyup : 'topKeyUp',
keydown : 'topKeyDown',
textInput : 'topTextInput',
textinput : null, // Not defined now
};
describe('BeforeInputEventPlugin', function() {
var ModuleCache;
function simulateIE11() {
document.documentMode = 11;
window.CompositionEvent = {};
delete window.TextEvent;
}
function simulateWebkit() {
delete document.documentMode;
window.CompositionEvent = {};
window.TextEvent = {};
}
function initialize(simulator) {
// Need to delete cached modules before executing simulator
jest.resetModuleRegistry();
// Initialize variables in the scope of BeforeInputEventPlugin
simulator();
// Modules which have dependency on BeforeInputEventPlugin are stored
// in ModuleCache so that we can use these modules ouside test functions.
this.ReactDOM = require('ReactDOM');
this.ReactDOMComponentTree = require('ReactDOMComponentTree');
this.SyntheticCompositionEvent = require('SyntheticCompositionEvent');
this.SyntheticInputEvent = require('SyntheticInputEvent');
this.BeforeInputEventPlugin = require('BeforeInputEventPlugin');
}
function extract(node, eventType, optionalData) {
var evt = document.createEvent('HTMLEvents');
evt.initEvent(eventType, true, true);
evt = Object.assign(evt, optionalData);
return ModuleCache.BeforeInputEventPlugin.extractEvents(
EventMapping[eventType],
ModuleCache.ReactDOMComponentTree.getInstanceFromNode(node),
evt,
node
);
}
function setElementText(node) {
return (args) => node.innerHTML = args;
}
function accumulateEvents(node, events) {
// We don't use accumulateInto module to apply partial application.
return function() {
var newArgs = [node].concat(Array.prototype.slice.call(arguments));
var newEvents = extract.apply(this, newArgs);
Array.prototype.push.apply(events, newEvents);
};
}
function EventMismatchError(idx, message) {
this.name = 'EventMismatchError';
this.message = '[' + idx + '] ' + message;
}
EventMismatchError.prototype = Object.create(Error.prototype);
function verifyEvents(actualEvents, expectedEvents) {
expect(actualEvents.length).toBe(expectedEvents.length);
expectedEvents.forEach(function(expected, idx) {
var actual = actualEvents[idx];
expect(function() {
if (actual === null && expected.type === null) {
// Both are null. Expected.
} else if (actual === null) {
throw new EventMismatchError(idx, 'Expected not to be null');
} else if (expected.type === null
|| !(actual instanceof expected.type)) {
throw new EventMismatchError(idx, 'Unexpected type: ' + actual);
} else {
// Type match.
Object.keys(expected.data).forEach(function(expectedKey) {
if (!(expectedKey in actual)) {
throw new EventMismatchError(idx, 'KeyNotFound: ' + expectedKey);
} else if (actual[expectedKey] !== expected.data[expectedKey]) {
throw new EventMismatchError(idx,
'ValueMismatch: ' + actual[expectedKey]);
}
});
}
}).not.toThrow();
});
}
// IE fires an event named `textinput` with all lowercase characters,
// instead of a standard name `textInput`. As of now, React does not have
// a corresponding topEvent to IE's textinput, but both events are added to
// this scenario data for future use.
var Scenario_Composition = [
{run: accumulateEvents, arg: ['compositionstart', {data: ''}]},
{run: accumulateEvents, arg: ['textInput', {data: 'A'}]},
{run: accumulateEvents, arg: ['textinput', {data: 'A'}]},
{run: accumulateEvents, arg: ['keyup', {keyCode: 65}]},
{run: setElementText, arg: ['ABC']},
{run: accumulateEvents, arg: ['textInput', {data: 'abc'}]},
{run: accumulateEvents, arg: ['textinput', {data: 'abc'}]},
{run: accumulateEvents, arg: ['keyup', {keyCode: 32}]},
{run: setElementText, arg: ['XYZ']},
{run: accumulateEvents, arg: ['textInput', {data: 'xyz'}]},
{run: accumulateEvents, arg: ['textinput', {data: 'xyz'}]},
{run: accumulateEvents, arg: ['keyup', {keyCode: 32}]},
{run: accumulateEvents, arg: ['compositionend', {data: 'Hello'}]},
];
/* Defined expected results as a factory of result data because we need
lazy evaluation for event modules.
Event modules are reloaded to simulate a different platform per testcase.
If we define expected results as a simple dictionary here, the comparison
of 'instanceof' fails after module cache is reset. */
// Webkit behavior is simple. We expect SyntheticInputEvent at each
// textInput, SyntheticCompositionEvent at composition, and nothing from
// keyUp.
var Expected_Webkit = () => [
{type: ModuleCache.SyntheticCompositionEvent, data: {}}, {type: null},
{type: null}, {type: ModuleCache.SyntheticInputEvent, data: {data: 'A'}},
{type: null}, {type: null}, // textinput of A
{type: null}, {type: null}, // keyUp of 65
{type: null}, {type: ModuleCache.SyntheticInputEvent, data: {data: 'abc'}},
{type: null}, {type: null}, // textinput of abc
{type: null}, {type: null}, // keyUp of 32
{type: null}, {type: ModuleCache.SyntheticInputEvent, data: {data: 'xyz'}},
{type: null}, {type: null}, // textinput of xyz
{type: null}, {type: null}, // keyUp of 32
{type: ModuleCache.SyntheticCompositionEvent, data: {data: 'Hello'}},
{type: null},
];
// For IE11, we use fallback data instead of IE's textinput events.
// We expect no SyntheticInputEvent from textinput. Fallback beforeInput is
// expected to be triggered at compositionend with a text of the target
// element, not event data.
var Expected_IE11 = () => [
{type: ModuleCache.SyntheticCompositionEvent, data: {}}, {type: null},
{type: null}, {type: null}, // textInput of A
{type: null}, {type: null}, // textinput of A
{type: null}, {type: null}, // keyUp of 65
{type: null}, {type: null}, // textInput of abc
{type: null}, {type: null}, // textinput of abc
// fallbackData should NOT be set at keyUp with any of END_KEYCODES
{type: null}, {type: null}, // keyUp of 32
{type: null}, {type: null}, // textInput of xyz
{type: null}, {type: null}, // textinput of xyz
{type: null}, {type: null}, // keyUp of 32
// fallbackData is retrieved from the element, which is XYZ,
// at a time of compositionend
{type: ModuleCache.SyntheticCompositionEvent, data: {}},
{type: ModuleCache.SyntheticInputEvent, data: {data: 'XYZ'}},
];
function TestEditableReactComponent(Emulator, Scenario, ExpectedResult) {
ModuleCache = new initialize(Emulator);
var EditableDiv = React.createClass({
render: () => (<div contentEditable="true" />),
});
var rendered = ReactTestUtils.renderIntoDocument(<EditableDiv />);
var node = ModuleCache.ReactDOM.findDOMNode(rendered);
var events = [];
Scenario.forEach((el) =>
el.run.call(this, node, events).apply(this, el.arg));
verifyEvents(events, ExpectedResult());
}
it('extract onBeforeInput from native textinput events', function() {
TestEditableReactComponent(
simulateWebkit, Scenario_Composition, Expected_Webkit);
});
it('extract onBeforeInput from fallback objects', function() {
TestEditableReactComponent(
simulateIE11, Scenario_Composition, Expected_IE11);
});
});
@@ -121,7 +121,7 @@ Object.assign(SyntheticEvent.prototype, {
if (event.preventDefault) {
event.preventDefault();
} else {
} else if (typeof event.returnValue !== 'unknown') { // eslint-disable-line valid-typeof
event.returnValue = false;
}
this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
@@ -25,7 +25,9 @@ describe('setInnerHTML', function() {
});
describe('when the node does not have an innerHTML property', () => {
it('sets innerHTML on it', function() {
// Disabled. JSDOM doesn't seem to remove nodes when using appendChild to
// move existing nodes.
xit('sets innerHTML on it', function() {
// Create a mock node that looks like an SVG in IE (without innerHTML)
var node = {
namespaceURI: DOMNamespaces.svg,
@@ -38,9 +38,9 @@ var setInnerHTML = createMicrosoftUnsafeLocalFunction(
if (node.namespaceURI === DOMNamespaces.svg && !('innerHTML' in node)) {
reusableSVGContainer = reusableSVGContainer || document.createElement('div');
reusableSVGContainer.innerHTML = '<svg>' + html + '</svg>';
var newNodes = reusableSVGContainer.firstChild.childNodes;
for (var i = 0; i < newNodes.length; i++) {
node.appendChild(newNodes[i]);
var svgNode = reusableSVGContainer.firstChild;
while (svgNode.firstChild) {
node.appendChild(svgNode.firstChild);
}
} else {
node.innerHTML = html;
+27 -3
View File
@@ -322,11 +322,24 @@ if (__DEV__) {
var didWarn = {};
validateDOMNesting = function(childTag, childInstance, ancestorInfo) {
validateDOMNesting = function(
childTag,
childText,
childInstance,
ancestorInfo
) {
ancestorInfo = ancestorInfo || emptyAncestorInfo;
var parentInfo = ancestorInfo.current;
var parentTag = parentInfo && parentInfo.tag;
if (childText != null) {
warning(
childTag == null,
'validateDOMNesting: when childText is passed, childTag should be null'
);
childTag = '#text';
}
var invalidParent =
isTagValidWithParent(childTag, parentTag) ? null : parentInfo;
var invalidAncestor =
@@ -385,7 +398,17 @@ if (__DEV__) {
didWarn[warnKey] = true;
var tagDisplayName = childTag;
if (childTag !== '#text') {
var whitespaceInfo = '';
if (childTag === '#text') {
if (/\S/.test(childText)) {
tagDisplayName = 'Text nodes';
} else {
tagDisplayName = 'Whitespace text nodes';
whitespaceInfo =
' Make sure you don\'t have any extra whitespace between tags on ' +
'each line of your source code.';
}
} else {
tagDisplayName = '<' + childTag + '>';
}
@@ -398,10 +421,11 @@ if (__DEV__) {
}
warning(
false,
'validateDOMNesting(...): %s cannot appear as a child of <%s>. ' +
'validateDOMNesting(...): %s cannot appear as a child of <%s>.%s ' +
'See %s.%s',
tagDisplayName,
ancestorTag,
whitespaceInfo,
ownerInfo,
info
);
@@ -36,7 +36,7 @@ function forceUpdateIfMounted() {
function isControlled(props) {
var usesChecked = props.type === 'checkbox' || props.type === 'radio';
return usesChecked ? props.checked !== undefined : props.value !== undefined;
return usesChecked ? props.checked != null : props.value != null;
}
/**
@@ -571,7 +571,7 @@ describe('ReactDOMInput', function() {
expect(console.error.calls.count()).toBe(1);
});
it('should warn if controlled input switches to uncontrolled', function() {
it('should warn if controlled input switches to uncontrolled (value is undefined)', function() {
var stub = <input type="text" value="controlled" onChange={emptyFunction} />;
var container = document.createElement('div');
ReactDOM.render(stub, container);
@@ -585,6 +585,20 @@ describe('ReactDOMInput', function() {
);
});
it('should warn if controlled input switches to uncontrolled (value is null)', function() {
var stub = <input type="text" value="controlled" onChange={emptyFunction} />;
var container = document.createElement('div');
ReactDOM.render(stub, container);
ReactDOM.render(<input type="text" value={null} />, container);
expect(console.error.calls.count()).toBeGreaterThan(0);
expect(console.error.calls.argsFor(1)[0]).toContain(
'A component is changing a controlled input of type text to be uncontrolled. ' +
'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
'Decide between using a controlled or uncontrolled input ' +
'element for the lifetime of the component. More info: https://fb.me/react-controlled-components'
);
});
it('should warn if controlled input switches to uncontrolled with defaultValue', function() {
var stub = <input type="text" value="controlled" onChange={emptyFunction} />;
var container = document.createElement('div');
@@ -599,7 +613,7 @@ describe('ReactDOMInput', function() {
);
});
it('should warn if uncontrolled input switches to controlled', function() {
it('should warn if uncontrolled input (value is undefined) switches to controlled', function() {
var stub = <input type="text" />;
var container = document.createElement('div');
ReactDOM.render(stub, container);
@@ -613,7 +627,21 @@ describe('ReactDOMInput', function() {
);
});
it('should warn if controlled checkbox switches to uncontrolled', function() {
it('should warn if uncontrolled input (value is null) switches to controlled', function() {
var stub = <input type="text" value={null} />;
var container = document.createElement('div');
ReactDOM.render(stub, container);
ReactDOM.render(<input type="text" value="controlled" />, container);
expect(console.error.calls.count()).toBeGreaterThan(0);
expect(console.error.calls.argsFor(1)[0]).toContain(
'A component is changing an uncontrolled input of type text to be controlled. ' +
'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
'Decide between using a controlled or uncontrolled input ' +
'element for the lifetime of the component. More info: https://fb.me/react-controlled-components'
);
});
it('should warn if controlled checkbox switches to uncontrolled (checked is undefined)', function() {
var stub = <input type="checkbox" checked={true} onChange={emptyFunction} />;
var container = document.createElement('div');
ReactDOM.render(stub, container);
@@ -627,6 +655,20 @@ describe('ReactDOMInput', function() {
);
});
it('should warn if controlled checkbox switches to uncontrolled (checked is null)', function() {
var stub = <input type="checkbox" checked={true} onChange={emptyFunction} />;
var container = document.createElement('div');
ReactDOM.render(stub, container);
ReactDOM.render(<input type="checkbox" checked={null} />, container);
expect(console.error.calls.count()).toBe(1);
expect(console.error.calls.argsFor(0)[0]).toContain(
'A component is changing a controlled input of type checkbox to be uncontrolled. ' +
'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
'Decide between using a controlled or uncontrolled input ' +
'element for the lifetime of the component. More info: https://fb.me/react-controlled-components'
);
});
it('should warn if controlled checkbox switches to uncontrolled with defaultChecked', function() {
var stub = <input type="checkbox" checked={true} onChange={emptyFunction} />;
var container = document.createElement('div');
@@ -641,7 +683,7 @@ describe('ReactDOMInput', function() {
);
});
it('should warn if uncontrolled checkbox switches to controlled', function() {
it('should warn if uncontrolled checkbox (checked is undefined) switches to controlled', function() {
var stub = <input type="checkbox" />;
var container = document.createElement('div');
ReactDOM.render(stub, container);
@@ -655,7 +697,21 @@ describe('ReactDOMInput', function() {
);
});
it('should warn if controlled radio switches to uncontrolled', function() {
it('should warn if uncontrolled checkbox (checked is null) switches to controlled', function() {
var stub = <input type="checkbox" checked={null} />;
var container = document.createElement('div');
ReactDOM.render(stub, container);
ReactDOM.render(<input type="checkbox" checked={true} />, container);
expect(console.error.calls.count()).toBe(1);
expect(console.error.calls.argsFor(0)[0]).toContain(
'A component is changing an uncontrolled input of type checkbox to be controlled. ' +
'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
'Decide between using a controlled or uncontrolled input ' +
'element for the lifetime of the component. More info: https://fb.me/react-controlled-components'
);
});
it('should warn if controlled radio switches to uncontrolled (checked is undefined)', function() {
var stub = <input type="radio" checked={true} onChange={emptyFunction} />;
var container = document.createElement('div');
ReactDOM.render(stub, container);
@@ -669,6 +725,20 @@ describe('ReactDOMInput', function() {
);
});
it('should warn if controlled radio switches to uncontrolled (checked is null)', function() {
var stub = <input type="radio" checked={true} onChange={emptyFunction} />;
var container = document.createElement('div');
ReactDOM.render(stub, container);
ReactDOM.render(<input type="radio" checked={null} />, container);
expect(console.error.calls.count()).toBe(1);
expect(console.error.calls.argsFor(0)[0]).toContain(
'A component is changing a controlled input of type radio to be uncontrolled. ' +
'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
'Decide between using a controlled or uncontrolled input ' +
'element for the lifetime of the component. More info: https://fb.me/react-controlled-components'
);
});
it('should warn if controlled radio switches to uncontrolled with defaultChecked', function() {
var stub = <input type="radio" checked={true} onChange={emptyFunction} />;
var container = document.createElement('div');
@@ -683,7 +753,7 @@ describe('ReactDOMInput', function() {
);
});
it('should warn if uncontrolled radio switches to controlled', function() {
it('should warn if uncontrolled radio (checked is undefined) switches to controlled', function() {
var stub = <input type="radio" />;
var container = document.createElement('div');
ReactDOM.render(stub, container);
@@ -697,6 +767,20 @@ describe('ReactDOMInput', function() {
);
});
it('should warn if uncontrolled radio (checked is null) switches to controlled', function() {
var stub = <input type="radio" checked={null} />;
var container = document.createElement('div');
ReactDOM.render(stub, container);
ReactDOM.render(<input type="radio" checked={true} />, container);
expect(console.error.calls.count()).toBe(1);
expect(console.error.calls.argsFor(0)[0]).toContain(
'A component is changing an uncontrolled input of type radio to be controlled. ' +
'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
'Decide between using a controlled or uncontrolled input ' +
'element for the lifetime of the component. More info: https://fb.me/react-controlled-components'
);
});
it('should not warn if radio value changes but never becomes controlled', function() {
var container = document.createElement('div');
ReactDOM.render(<input type="radio" value="value" />, container);
@@ -36,6 +36,8 @@ var HTMLDOMPropertyConfig = {
allowFullScreen: HAS_BOOLEAN_VALUE,
allowTransparency: 0,
alt: 0,
// specifies target context for links with `preload` type
as: 0,
async: HAS_BOOLEAN_VALUE,
autoComplete: 0,
// autoFocus is polyfilled/normalized by AutoFocusUtils
@@ -116,6 +118,7 @@ var HTMLDOMPropertyConfig = {
optimum: 0,
pattern: 0,
placeholder: 0,
playsInline: HAS_BOOLEAN_VALUE,
poster: 0,
preload: 0,
profile: 0,
+10 -9
View File
@@ -253,9 +253,9 @@ function optionPostMount() {
ReactDOMOption.postMountWrapper(inst);
}
var setContentChildForInstrumentation = emptyFunction;
var setAndValidateContentChildDev = emptyFunction;
if (__DEV__) {
setContentChildForInstrumentation = function(content) {
setAndValidateContentChildDev = function(content) {
var hasExistingContent = this._contentDebugID != null;
var debugID = this._debugID;
// This ID represents the inlined child that has no backing instance:
@@ -269,6 +269,7 @@ if (__DEV__) {
return;
}
validateDOMNesting(null, String(content), this, this._ancestorInfo);
this._contentDebugID = contentDebugID;
if (hasExistingContent) {
ReactInstrumentation.debugTool.onBeforeUpdateComponent(contentDebugID, content);
@@ -492,7 +493,7 @@ function ReactDOMComponent(element) {
this._flags = 0;
if (__DEV__) {
this._ancestorInfo = null;
setContentChildForInstrumentation.call(this, null);
setAndValidateContentChildDev.call(this, null);
}
}
@@ -598,7 +599,7 @@ ReactDOMComponent.Mixin = {
if (parentInfo) {
// parentInfo should always be present except for the top-level
// component when server rendering
validateDOMNesting(this._tag, this, parentInfo);
validateDOMNesting(this._tag, null, this, parentInfo);
}
this._ancestorInfo =
validateDOMNesting.updatedAncestorInfo(parentInfo, this._tag, this);
@@ -794,7 +795,7 @@ ReactDOMComponent.Mixin = {
// TODO: Validate that text is allowed as a child of this node
ret = escapeTextContentForBrowser(contentToUse);
if (__DEV__) {
setContentChildForInstrumentation.call(this, contentToUse);
setAndValidateContentChildDev.call(this, contentToUse);
}
} else if (childrenToUse != null) {
var mountImages = this.mountChildren(
@@ -836,7 +837,7 @@ ReactDOMComponent.Mixin = {
if (contentToUse != null) {
// TODO: Validate that text is allowed as a child of this node
if (__DEV__) {
setContentChildForInstrumentation.call(this, contentToUse);
setAndValidateContentChildDev.call(this, contentToUse);
}
DOMLazyTree.queueText(lazyTree, contentToUse);
} else if (childrenToUse != null) {
@@ -1110,7 +1111,7 @@ ReactDOMComponent.Mixin = {
if (lastContent !== nextContent) {
this.updateTextContent('' + nextContent);
if (__DEV__) {
setContentChildForInstrumentation.call(this, nextContent);
setAndValidateContentChildDev.call(this, nextContent);
}
}
} else if (nextHtml != null) {
@@ -1122,7 +1123,7 @@ ReactDOMComponent.Mixin = {
}
} else if (nextChildren != null) {
if (__DEV__) {
setContentChildForInstrumentation.call(this, null);
setAndValidateContentChildDev.call(this, null);
}
this.updateChildren(nextChildren, transaction, context);
@@ -1185,7 +1186,7 @@ ReactDOMComponent.Mixin = {
this._wrapperState = null;
if (__DEV__) {
setContentChildForInstrumentation.call(this, null);
setAndValidateContentChildDev.call(this, null);
}
},
@@ -75,7 +75,7 @@ Object.assign(ReactDOMTextComponent.prototype, {
if (parentInfo) {
// parentInfo should always be present except for the top-level
// component when server rendering
validateDOMNesting('#text', this, parentInfo);
validateDOMNesting(null, this._stringText, this, parentInfo);
}
}
@@ -777,7 +777,7 @@ describe('ReactDOMComponent', function() {
});
it('should work error event on <source> element', function() {
spyOn(console, 'error');
spyOn(console, 'error');
var container = document.createElement('div');
ReactDOM.render(
<video>
@@ -1224,7 +1224,7 @@ describe('ReactDOMComponent', function() {
class Row extends React.Component {
render() {
return <tr />;
return <tr>x</tr>;
}
}
@@ -1236,15 +1236,21 @@ describe('ReactDOMComponent', function() {
ReactTestUtils.renderIntoDocument(<Foo />);
expect(console.error.calls.count()).toBe(2);
expect(console.error.calls.count()).toBe(3);
expect(console.error.calls.argsFor(0)[0]).toBe(
'Warning: validateDOMNesting(...): <tr> cannot appear as a child of ' +
'<table>. See Foo > table > Row > tr. Add a <tbody> to your code to ' +
'match the DOM tree generated by the browser.'
);
expect(console.error.calls.argsFor(1)[0]).toBe(
'Warning: validateDOMNesting(...): #text cannot appear as a child ' +
'of <table>. See Foo > table > #text.'
'Warning: validateDOMNesting(...): Text nodes cannot appear as a ' +
'child of <tr>. See Row > tr > #text.'
);
expect(console.error.calls.argsFor(2)[0]).toBe(
'Warning: validateDOMNesting(...): Whitespace text nodes cannot ' +
'appear as a child of <table>. Make sure you don\'t have any extra ' +
'whitespace between tags on each line of your source code. See Foo > ' +
'table > #text.'
);
});
@@ -97,6 +97,19 @@ var Mixin = {
return ReactUpdateQueue;
},
/**
* Save current transaction state -- if the return value from this method is
* passed to `rollback`, the transaction will be reset to that state.
*/
checkpoint: function() {
// reactMountReady is the our only stateful wrapper
return this.reactMountReady.checkpoint();
},
rollback: function(checkpoint) {
this.reactMountReady.rollback(checkpoint);
},
/**
* `PooledClass` looks for this, and will invoke this before allowing this
* instance to be reused.
-6
View File
@@ -251,12 +251,6 @@ var ReactDebugTool = {
endLifeCycleTimer(debugID, timerType);
emitEvent('onEndLifeCycleTimer', debugID, timerType);
},
onError(debugID) {
if (currentTimerDebugID != null) {
endLifeCycleTimer(currentTimerDebugID, currentTimerType);
}
emitEvent('onError', debugID);
},
onBeginProcessingChildContext() {
emitEvent('onBeginProcessingChildContext');
},
@@ -516,4 +516,208 @@ describe('ReactPerf', function() {
renderCount: 2,
}]);
});
it('should not print errant warnings if render() throws', () => {
var container = document.createElement('div');
var thrownErr = new Error('Muhaha!');
class Evil extends React.Component {
render() {
throw thrownErr;
}
}
ReactPerf.start();
try {
ReactDOM.render(
<div>
<LifeCycle />
<Evil />
</div>,
container
);
} catch (err) {
if (err !== thrownErr) {
throw err;
}
}
ReactPerf.stop();
});
it('should not print errant warnings if componentWillMount() throws', () => {
var container = document.createElement('div');
var thrownErr = new Error('Muhaha!');
class Evil extends React.Component {
componentWillMount() {
throw thrownErr;
}
render() {
return <div />;
}
}
ReactPerf.start();
try {
ReactDOM.render(
<div>
<LifeCycle />
<Evil />
</div>,
container
);
} catch (err) {
if (err !== thrownErr) {
throw err;
}
}
ReactPerf.stop();
});
it('should not print errant warnings if componentDidMount() throws', () => {
var container = document.createElement('div');
var thrownErr = new Error('Muhaha!');
class Evil extends React.Component {
componentDidMount() {
throw thrownErr;
}
render() {
return <div />;
}
}
ReactPerf.start();
try {
ReactDOM.render(
<div>
<LifeCycle />
<Evil />
</div>,
container
);
} catch (err) {
if (err !== thrownErr) {
throw err;
}
}
ReactPerf.stop();
});
it('should not print errant warnings if portal throws in render()', () => {
var container = document.createElement('div');
var thrownErr = new Error('Muhaha!');
class Evil extends React.Component {
render() {
throw thrownErr;
}
}
class EvilPortal extends React.Component {
componentWillMount() {
var portalContainer = document.createElement('div');
ReactDOM.render(<Evil />, portalContainer);
}
render() {
return <div />;
}
}
ReactPerf.start();
try {
ReactDOM.render(
<div>
<LifeCycle />
<EvilPortal />
</div>,
container
);
} catch (err) {
if (err !== thrownErr) {
throw err;
}
}
ReactDOM.unmountComponentAtNode(container);
ReactPerf.stop();
});
it('should not print errant warnings if portal throws in componentWillMount()', () => {
var container = document.createElement('div');
var thrownErr = new Error('Muhaha!');
class Evil extends React.Component {
componentWillMount() {
throw thrownErr;
}
render() {
return <div />;
}
}
class EvilPortal extends React.Component {
componentWillMount() {
var portalContainer = document.createElement('div');
ReactDOM.render(<Evil />, portalContainer);
}
render() {
return <div />;
}
}
ReactPerf.start();
try {
ReactDOM.render(
<div>
<LifeCycle />
<EvilPortal />
</div>,
container
);
} catch (err) {
if (err !== thrownErr) {
throw err;
}
}
ReactDOM.unmountComponentAtNode(container);
ReactPerf.stop();
});
it('should not print errant warnings if portal throws in componentDidMount()', () => {
var container = document.createElement('div');
var thrownErr = new Error('Muhaha!');
class Evil extends React.Component {
componentDidMount() {
throw thrownErr;
}
render() {
return <div />;
}
}
class EvilPortal extends React.Component {
componentWillMount() {
var portalContainer = document.createElement('div');
ReactDOM.render(<Evil />, portalContainer);
}
render() {
return <div />;
}
}
ReactPerf.start();
try {
ReactDOM.render(
<div>
<LifeCycle />
<EvilPortal />
</div>,
container
);
} catch (err) {
if (err !== thrownErr) {
throw err;
}
}
ReactDOM.unmountComponentAtNode(container);
ReactPerf.stop();
});
});
@@ -59,40 +59,6 @@ function warnIfInvalidElement(Component, element) {
}
}
function invokeComponentDidMountWithTimer() {
var publicInstance = this._instance;
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(
this._debugID,
'componentDidMount'
);
}
publicInstance.componentDidMount();
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(
this._debugID,
'componentDidMount'
);
}
}
function invokeComponentDidUpdateWithTimer(prevProps, prevState, prevContext) {
var publicInstance = this._instance;
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(
this._debugID,
'componentDidUpdate'
);
}
publicInstance.componentDidUpdate(prevProps, prevState, prevContext);
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(
this._debugID,
'componentDidUpdate'
);
}
}
function shouldConstruct(Component) {
return !!(Component.prototype && Component.prototype.isReactComponent);
}
@@ -101,6 +67,23 @@ function isPureComponent(Component) {
return !!(Component.prototype && Component.prototype.isPureReactComponent);
}
// Separated into a function to contain deoptimizations caused by try/finally.
function measureLifeCyclePerf(fn, debugID, timerType) {
if (debugID === 0) {
// Top-level wrappers (see ReactMount) and empty components (see
// ReactDOMEmptyComponent) are invisible to hooks and devtools.
// Both are implementation details that should go away in the future.
return fn();
}
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(debugID, timerType);
try {
return fn();
} finally {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(debugID, timerType);
}
}
/**
* ------------------ The Life-Cycle of a Composite Component ------------------
*
@@ -361,7 +344,13 @@ var ReactCompositeComponentMixin = {
if (inst.componentDidMount) {
if (__DEV__) {
transaction.getReactMountReady().enqueue(invokeComponentDidMountWithTimer, this);
transaction.getReactMountReady().enqueue(() => {
measureLifeCyclePerf(
() => inst.componentDidMount(),
this._debugID,
'componentDidMount'
);
});
} else {
transaction.getReactMountReady().enqueue(inst.componentDidMount, inst);
}
@@ -405,47 +394,30 @@ var ReactCompositeComponentMixin = {
updateQueue
) {
var Component = this._currentElement.type;
var instanceOrElement;
if (doConstruct) {
if (__DEV__) {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(
this._debugID,
'ctor'
);
}
}
instanceOrElement = new Component(publicProps, publicContext, updateQueue);
if (__DEV__) {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(
this._debugID,
'ctor'
);
}
}
} else {
// This can still be an instance in case of factory components
// but we'll count this as time spent rendering as the more common case.
if (__DEV__) {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(
this._debugID,
'render'
);
}
}
instanceOrElement = Component(publicProps, publicContext, updateQueue);
if (__DEV__) {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(
this._debugID,
'render'
);
}
return measureLifeCyclePerf(
() => new Component(publicProps, publicContext, updateQueue),
this._debugID,
'ctor'
);
} else {
return new Component(publicProps, publicContext, updateQueue);
}
}
return instanceOrElement;
// This can still be an instance in case of factory components
// but we'll count this as time spent rendering as the more common case.
if (__DEV__) {
return measureLifeCyclePerf(
() => Component(publicProps, publicContext, updateQueue),
this._debugID,
'render'
);
} else {
return Component(publicProps, publicContext, updateQueue);
}
},
performInitialMountWithErrorHandling: function(
@@ -460,11 +432,6 @@ var ReactCompositeComponentMixin = {
try {
markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context);
} catch (e) {
if (__DEV__) {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onError();
}
}
// Roll back to checkpoint, handle error (which may add items to the transaction), and take a new checkpoint
transaction.rollback(checkpoint);
this._instance.unstable_handleError(e);
@@ -485,23 +452,21 @@ var ReactCompositeComponentMixin = {
performInitialMount: function(renderedElement, hostParent, hostContainerInfo, transaction, context) {
var inst = this._instance;
var debugID = 0;
if (__DEV__) {
debugID = this._debugID;
}
if (inst.componentWillMount) {
if (__DEV__) {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(
this._debugID,
'componentWillMount'
);
}
}
inst.componentWillMount();
if (__DEV__) {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(
this._debugID,
'componentWillMount'
);
}
measureLifeCyclePerf(
() => inst.componentWillMount(),
debugID,
'componentWillMount'
);
} else {
inst.componentWillMount();
}
// When mounting, calls to `setState` by `componentWillMount` will set
// `this._pendingStateQueue` without triggering a re-render.
@@ -523,25 +488,19 @@ var ReactCompositeComponentMixin = {
);
this._renderedComponent = child;
var selfDebugID = 0;
if (__DEV__) {
selfDebugID = this._debugID;
}
var markup = ReactReconciler.mountComponent(
child,
transaction,
hostParent,
hostContainerInfo,
this._processChildContext(context),
selfDebugID
debugID
);
if (__DEV__) {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onSetChildren(
this._debugID,
child._debugID !== 0 ? [child._debugID] : []
);
if (debugID !== 0) {
var childDebugIDs = child._debugID !== 0 ? [child._debugID] : [];
ReactInstrumentation.debugTool.onSetChildren(debugID, childDebugIDs);
}
}
@@ -562,30 +521,24 @@ var ReactCompositeComponentMixin = {
if (!this._renderedComponent) {
return;
}
var inst = this._instance;
if (inst.componentWillUnmount && !inst._calledComponentWillUnmount) {
inst._calledComponentWillUnmount = true;
if (__DEV__) {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(
this._debugID,
'componentWillUnmount'
);
}
}
if (safely) {
var name = this.getName() + '.componentWillUnmount()';
ReactErrorUtils.invokeGuardedCallback(name, inst.componentWillUnmount.bind(inst));
} else {
inst.componentWillUnmount();
}
if (__DEV__) {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(
if (__DEV__) {
measureLifeCyclePerf(
() => inst.componentWillUnmount(),
this._debugID,
'componentWillUnmount'
);
} else {
inst.componentWillUnmount();
}
}
}
@@ -676,13 +629,21 @@ var ReactCompositeComponentMixin = {
_processChildContext: function(currentContext) {
var Component = this._currentElement.type;
var inst = this._instance;
if (__DEV__) {
ReactInstrumentation.debugTool.onBeginProcessingChildContext();
}
var childContext = inst.getChildContext && inst.getChildContext();
if (__DEV__) {
ReactInstrumentation.debugTool.onEndProcessingChildContext();
var childContext;
if (inst.getChildContext) {
if (__DEV__) {
ReactInstrumentation.debugTool.onBeginProcessingChildContext();
try {
childContext = inst.getChildContext();
} finally {
ReactInstrumentation.debugTool.onEndProcessingChildContext();
}
} else {
childContext = inst.getChildContext();
}
}
if (childContext) {
invariant(
typeof Component.childContextTypes === 'object',
@@ -826,21 +787,13 @@ var ReactCompositeComponentMixin = {
// immediately reconciled instead of waiting for the next batch.
if (willReceive && inst.componentWillReceiveProps) {
if (__DEV__) {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(
this._debugID,
'componentWillReceiveProps'
);
}
}
inst.componentWillReceiveProps(nextProps, nextContext);
if (__DEV__) {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(
this._debugID,
'componentWillReceiveProps'
);
}
measureLifeCyclePerf(
() => inst.componentWillReceiveProps(nextProps, nextContext),
this._debugID,
'componentWillReceiveProps',
);
} else {
inst.componentWillReceiveProps(nextProps, nextContext);
}
}
@@ -850,21 +803,13 @@ var ReactCompositeComponentMixin = {
if (!this._pendingForceUpdate) {
if (inst.shouldComponentUpdate) {
if (__DEV__) {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(
this._debugID,
'shouldComponentUpdate'
);
}
}
shouldUpdate = inst.shouldComponentUpdate(nextProps, nextState, nextContext);
if (__DEV__) {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(
this._debugID,
'shouldComponentUpdate'
);
}
shouldUpdate = measureLifeCyclePerf(
() => inst.shouldComponentUpdate(nextProps, nextState, nextContext),
this._debugID,
'shouldComponentUpdate'
);
} else {
shouldUpdate = inst.shouldComponentUpdate(nextProps, nextState, nextContext);
}
} else {
if (this._compositeType === CompositeTypes.PureClass) {
@@ -970,21 +915,13 @@ var ReactCompositeComponentMixin = {
if (inst.componentWillUpdate) {
if (__DEV__) {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(
this._debugID,
'componentWillUpdate'
);
}
}
inst.componentWillUpdate(nextProps, nextState, nextContext);
if (__DEV__) {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(
this._debugID,
'componentWillUpdate'
);
}
measureLifeCyclePerf(
() => inst.componentWillUpdate(nextProps, nextState, nextContext),
this._debugID,
'componentWillUpdate'
);
} else {
inst.componentWillUpdate(nextProps, nextState, nextContext);
}
}
@@ -998,10 +935,13 @@ var ReactCompositeComponentMixin = {
if (hasComponentDidUpdate) {
if (__DEV__) {
transaction.getReactMountReady().enqueue(
invokeComponentDidUpdateWithTimer.bind(this, prevProps, prevState, prevContext),
this
);
transaction.getReactMountReady().enqueue(() => {
measureLifeCyclePerf(
inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext),
this._debugID,
'componentDidUpdate'
);
});
} else {
transaction.getReactMountReady().enqueue(
inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext),
@@ -1021,6 +961,12 @@ var ReactCompositeComponentMixin = {
var prevComponentInstance = this._renderedComponent;
var prevRenderedElement = prevComponentInstance._currentElement;
var nextRenderedElement = this._renderValidatedComponent();
var debugID = 0;
if (__DEV__) {
debugID = this._debugID;
}
if (shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement)) {
ReactReconciler.receiveComponent(
prevComponentInstance,
@@ -1040,25 +986,19 @@ var ReactCompositeComponentMixin = {
);
this._renderedComponent = child;
var selfDebugID = 0;
if (__DEV__) {
selfDebugID = this._debugID;
}
var nextMarkup = ReactReconciler.mountComponent(
child,
transaction,
this._hostParent,
this._hostContainerInfo,
this._processChildContext(context),
selfDebugID
debugID
);
if (__DEV__) {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onSetChildren(
this._debugID,
child._debugID !== 0 ? [child._debugID] : []
);
if (debugID !== 0) {
var childDebugIDs = child._debugID !== 0 ? [child._debugID] : [];
ReactInstrumentation.debugTool.onSetChildren(debugID, childDebugIDs);
}
}
@@ -1088,23 +1028,16 @@ var ReactCompositeComponentMixin = {
*/
_renderValidatedComponentWithoutOwnerOrContext: function() {
var inst = this._instance;
var renderedComponent;
if (__DEV__) {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(
this._debugID,
'render'
);
}
}
var renderedComponent = inst.render();
if (__DEV__) {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(
this._debugID,
'render'
);
}
renderedComponent = measureLifeCyclePerf(
() => inst.render(),
this._debugID,
'render'
);
} else {
renderedComponent = inst.render();
}
if (__DEV__) {
@@ -1164,7 +1097,9 @@ var ReactCompositeComponentMixin = {
if (__DEV__) {
var componentName = component && component.getName ?
component.getName() : 'a component';
warning(publicComponentInstance != null,
warning(
publicComponentInstance != null ||
component._compositeType !== CompositeTypes.StatelessFunctional,
'Stateless function components cannot be given refs ' +
'(See ref "%s" in %s created by %s). ' +
'Attempts to access this ref will fail.',
@@ -13,13 +13,11 @@
var React;
var ReactDOM;
var ReactDOMServer;
describe('ReactErrorBoundaries', function() {
beforeEach(function() {
ReactDOM = require('ReactDOM');
ReactDOMServer = require('ReactDOMServer');
React = require('React');
});
@@ -37,9 +35,11 @@ describe('ReactErrorBoundaries', function() {
}
render() {
if (!this.state.error) {
return (<div><button onClick={this.onClick}>ClickMe</button><Angry /></div>);
return (
<div><button onClick={this.onClick}>ClickMe</button><Angry /></div>
);
} else {
return (<div>Happy Birthday!</div>);
return <div>Happy Birthday!</div>;
}
}
onClick() {
@@ -57,11 +57,19 @@ describe('ReactErrorBoundaries', function() {
expect(EventPluginHub.putListener).not.toBeCalled();
});
it('renders an error state (ssr)', function() {
it('renders an error state', function() {
var log = [];
class Angry extends React.Component {
render() {
log.push('Angry render');
throw new Error('Please, do not render me.');
}
componentDidMount() {
log.push('Angry componentDidMount');
}
componentWillUnmount() {
log.push('Angry componentWillUnmount');
}
}
class Boundary extends React.Component {
@@ -70,12 +78,21 @@ describe('ReactErrorBoundaries', function() {
this.state = {error: false};
}
render() {
log.push('Boundary render');
if (!this.state.error) {
return (<div><button onClick={this.onClick}>ClickMe</button><Angry /></div>);
return (
<div><button onClick={this.onClick}>ClickMe</button><Angry /></div>
);
} else {
return (<div>Happy Birthday!</div>);
return <div>Happy Birthday!</div>;
}
}
componentDidMount() {
log.push('Boundary componentDidMount');
}
componentWillUnmount() {
log.push('Boundary componentWillUnmount');
}
onClick() {
/* do nothing */
}
@@ -84,12 +101,15 @@ describe('ReactErrorBoundaries', function() {
}
}
var EventPluginHub = require('EventPluginHub');
var container = document.createElement('div');
EventPluginHub.putListener = jest.fn();
container.innerHTML = ReactDOMServer.renderToString(<Boundary />);
ReactDOM.render(<Boundary />, container);
expect(container.firstChild.innerHTML).toBe('Happy Birthday!');
expect(EventPluginHub.putListener).not.toBeCalled();
expect(log).toEqual([
'Boundary render',
'Angry render',
'Boundary render',
'Boundary componentDidMount',
]);
});
it('will catch exceptions in componentWillUnmount', function() {
@@ -98,14 +118,14 @@ describe('ReactErrorBoundaries', function() {
super();
this.state = {error: false};
}
render() {
if (!this.state.error) {
return <div>{this.props.children}</div>;
}
return <div>Error has been caught</div>;
}
unstable_handleError() {
this.setState({error: true});
}
@@ -139,27 +159,36 @@ describe('ReactErrorBoundaries', function() {
});
it('expect uneventful render to succeed', function() {
var log = [];
class Boundary extends React.Component {
constructor(props) {
super(props);
this.state = {error: false};
}
render() {
return (<div><button onClick={this.onClick}>ClickMe</button></div>);
log.push('Boundary render');
return <div><button onClick={this.onClick}>ClickMe</button></div>;
}
onClick() {
/* do nothing */
}
componentDidMount() {
log.push('Boundary componentDidMount');
}
componentWillUnmount() {
log.push('Boundary componentWillUnmount');
}
unstable_handleError() {
this.setState({error: true});
}
}
var EventPluginHub = require('EventPluginHub');
var container = document.createElement('div');
EventPluginHub.putListener = jest.fn();
ReactDOM.render(<Boundary />, container);
expect(EventPluginHub.putListener).toBeCalled();
expect(log).toEqual([
'Boundary render',
'Boundary componentDidMount',
]);
});
it('correctly handles composite siblings', function() {
@@ -168,14 +197,14 @@ describe('ReactErrorBoundaries', function() {
super();
this.state = {error: false};
}
render() {
if (!this.state.error) {
return <div>{this.props.children}</div>;
}
return <div>Error has been caught</div>;
}
unstable_handleError() {
this.setState({error: true});
}
@@ -89,6 +89,19 @@ var Mixin = {
return ReactUpdateQueue;
},
/**
* Save current transaction state -- if the return value from this method is
* passed to `rollback`, the transaction will be reset to that state.
*/
checkpoint: function() {
// reactMountReady is the our only stateful wrapper
return this.reactMountReady.checkpoint();
},
rollback: function(checkpoint) {
this.reactMountReady.rollback(checkpoint);
},
/**
* `PooledClass` looks for this, and will invoke this before allowing this
* instance to be reused.
@@ -206,4 +206,87 @@ describe('ReactTestRenderer', function() {
expect(log).toEqual([null]);
});
it('warns correctly for refs on SFCs', function() {
spyOn(console, 'error');
function Bar() {
return <div>Hello, world</div>
}
class Foo extends React.Component {
render() {
return <Bar ref="foo" />
}
}
class Baz extends React.Component {
render() {
return <div ref="baz" />
}
}
ReactTestRenderer.create(<Baz />);
ReactTestRenderer.create(<Foo />);
expect(console.error.calls.count()).toBe(1);
expect(console.error.calls.argsFor(0)[0]).toContain(
'Stateless function components cannot be given refs ' +
'(See ref "foo" in Bar created by Foo). ' +
'Attempts to access this ref will fail.'
);
});
it('supports error boundaries', function() {
var log = [];
class Angry extends React.Component {
render() {
log.push('Angry render');
throw new Error('Please, do not render me.');
}
componentDidMount() {
log.push('Angry componentDidMount');
}
componentWillUnmount() {
log.push('Angry componentWillUnmount');
}
}
class Boundary extends React.Component {
constructor(props) {
super(props);
this.state = {error: false};
}
render() {
log.push('Boundary render');
if (!this.state.error) {
return (
<div><button onClick={this.onClick}>ClickMe</button><Angry /></div>
);
} else {
return <div>Happy Birthday!</div>;
}
}
componentDidMount() {
log.push('Boundary componentDidMount');
}
componentWillUnmount() {
log.push('Boundary componentWillUnmount');
}
onClick() {
/* do nothing */
}
unstable_handleError() {
this.setState({error: true});
}
}
var renderer = ReactTestRenderer.create(<Boundary />);
expect(renderer.toJSON()).toEqual({
type: 'div',
props: {},
children: ['Happy Birthday!'],
});
expect(log).toEqual([
'Boundary render',
'Angry render',
'Boundary render',
'Boundary componentDidMount',
]);
});
});