mirror of
https://github.com/facebook/react.git
synced 2026-11-18 20:15:56 +00:00
Merge branch '15-dev' into 15-stable
This commit is contained in:
commit
41f21520d1
69 files changed
+18057
-15228
No files matched your search
@@ -32,6 +32,8 @@ Just make sure to run the whole test suite before submitting a pull request!
|
||||
|
||||
**Working on your first Pull Request?** You can learn how from this *free* series [How to Contribute to an Open Source Project on GitHub](https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github)
|
||||
|
||||
You may also be interested in watching [this short video](https://www.youtube.com/watch?v=wUpPsEcGsg8) (26 mins) which gives an introduction on how to contribute to the React JS project.
|
||||
|
||||
The core team will be monitoring for pull requests. When we get one, we'll run some Facebook-specific integration tests on it first. From here, we'll need to get another person to sign off on the changes and then merge the pull request. For API changes we may need to fix internal uses, which could cause some delay. We'll do our best to provide updates and feedback throughout the process.
|
||||
|
||||
*Before* submitting a pull request, please make sure the following is done…
|
||||
|
||||
@@ -90,6 +90,10 @@ module.exports = function(grunt) {
|
||||
grunt.registerTask('npm-react-addons:release', npmReactAddonsTasks.buildReleases);
|
||||
grunt.registerTask('npm-react-addons:pack', npmReactAddonsTasks.packReleases);
|
||||
|
||||
var npmReactTestRendererTasks = require('./grunt/tasks/npm-react-test');
|
||||
grunt.registerTask('npm-react-test:release', npmReactTestRendererTasks.buildRelease);
|
||||
grunt.registerTask('npm-react-test:pack', npmReactTestRendererTasks.packRelease);
|
||||
|
||||
grunt.registerTask('version-check', function() {
|
||||
// Use gulp here.
|
||||
spawnGulp(['version-check'], null, this.async());
|
||||
@@ -146,6 +150,8 @@ module.exports = function(grunt) {
|
||||
'npm-react-native:pack',
|
||||
'npm-react-addons:release',
|
||||
'npm-react-addons:pack',
|
||||
'npm-react-test:release',
|
||||
'npm-react-test:pack',
|
||||
'compare_size',
|
||||
]);
|
||||
|
||||
|
||||
@@ -25,6 +25,16 @@ module.exports = function() {
|
||||
entries: entries,
|
||||
debug: config.debug, // sourcemaps
|
||||
standalone: config.standalone, // global
|
||||
insertGlobalVars: {
|
||||
// We can remove this when we remove the few direct
|
||||
// process.env.NODE_ENV checks against "test".
|
||||
// The intention is to avoid embedding Browserify's `process` shim
|
||||
// because we don't really need it.
|
||||
// See https://github.com/facebook/react/pull/7245 for context.
|
||||
process: function() {
|
||||
return 'undefined';
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
var bundle = browserify(options);
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
'use strict';
|
||||
|
||||
var fs = require('fs');
|
||||
var grunt = require('grunt');
|
||||
|
||||
var src = 'packages/react-test-renderer/';
|
||||
var dest = 'build/packages/react-test-renderer/';
|
||||
|
||||
function buildRelease() {
|
||||
if (grunt.file.exists(dest)) {
|
||||
grunt.file.delete(dest);
|
||||
}
|
||||
|
||||
// Copy to build/packages/react-native-renderer
|
||||
var mappings = [].concat(
|
||||
grunt.file.expandMapping('**/*', dest, {cwd: src}),
|
||||
grunt.file.expandMapping('{LICENSE,PATENTS}', dest)
|
||||
);
|
||||
mappings.forEach(function(mapping) {
|
||||
var mappingSrc = mapping.src[0];
|
||||
var mappingDest = mapping.dest;
|
||||
if (grunt.file.isDir(mappingSrc)) {
|
||||
grunt.file.mkdir(mappingDest);
|
||||
} else {
|
||||
grunt.file.copy(mappingSrc, mappingDest);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function packRelease() {
|
||||
var done = this.async();
|
||||
var spawnCmd = {
|
||||
cmd: 'npm',
|
||||
args: ['pack', 'packages/react-test-renderer'],
|
||||
};
|
||||
grunt.util.spawn(spawnCmd, function() {
|
||||
var buildSrc = 'react-test-renderer-' + grunt.config.data.pkg.version + '.tgz';
|
||||
var buildDest = 'build/packages/react-test-renderer.tgz';
|
||||
fs.rename(buildSrc, buildDest, done);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
buildRelease: buildRelease,
|
||||
packRelease: packRelease,
|
||||
};
|
||||
@@ -27,6 +27,8 @@ module.exports = function(gulp, plugins) {
|
||||
'packages/react-addons/package.json (react dependency)':
|
||||
// Get the "version" without the range bit
|
||||
addonsData.peerDependencies.react.slice(1),
|
||||
'packages/react-test-renderer/package.json':
|
||||
require('../../packages/react-test-renderer/package.json').version,
|
||||
'src/ReactVersion.js': require('../../src/ReactVersion'),
|
||||
};
|
||||
|
||||
|
||||
Generated
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "react-build",
|
||||
"version": "15.2.0",
|
||||
"version": "15.3.0-rc.3",
|
||||
"dependencies": {
|
||||
"art": {
|
||||
"version": "0.10.1",
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "react-build",
|
||||
"private": true,
|
||||
"version": "15.2.1",
|
||||
"version": "15.3.0-rc.3",
|
||||
"devDependencies": {
|
||||
"art": "^0.10.1",
|
||||
"async": "^1.5.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "react-addons-template",
|
||||
"version": "15.2.1",
|
||||
"version": "15.3.0-rc.3",
|
||||
"main": "index.js",
|
||||
"repository": "facebook/react",
|
||||
"keywords": [
|
||||
@@ -10,6 +10,6 @@
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {},
|
||||
"peerDependencies": {
|
||||
"react": "^15.2.1"
|
||||
"react": "^15.3.0-rc.3"
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "react-dom",
|
||||
"version": "15.2.1",
|
||||
"version": "15.3.0-rc.3",
|
||||
"description": "React package for working with the DOM.",
|
||||
"main": "index.js",
|
||||
"repository": "facebook/react",
|
||||
@@ -14,6 +14,6 @@
|
||||
"homepage": "https://facebook.github.io/react/",
|
||||
"dependencies": {},
|
||||
"peerDependencies": {
|
||||
"react": "^15.2.1"
|
||||
"react": "^15.3.0-rc.3"
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "react-native-renderer",
|
||||
"version": "15.2.1",
|
||||
"version": "15.3.0-rc.3",
|
||||
"description": "React package for use inside react-native.",
|
||||
"main": "index.js",
|
||||
"repository": "facebook/react",
|
||||
@@ -14,6 +14,6 @@
|
||||
},
|
||||
"homepage": "https://facebook.github.io/react-native/",
|
||||
"dependencies": {
|
||||
"react": "^15.2.1"
|
||||
"react": "^15.3.0-rc.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
# `react-test-renderer`
|
||||
|
||||
This package provides an experimental React renderer that can be used to render React components to pure JavaScript objects, without depending on the DOM or a native mobile environment.
|
||||
|
||||
Essentially, this package makes it easy to grab a snapshot of the "DOM tree" rendered by a React DOM or React Native component without using a browser or jsdom.
|
||||
|
||||
Usage:
|
||||
|
||||
```jsx
|
||||
const ReactTestRenderer = require('react-test-renderer');
|
||||
|
||||
const renderer = ReactTestRenderer.create(
|
||||
<Link page="https://www.facebook.com/">Facebook</Link>
|
||||
);
|
||||
|
||||
console.log(renderer.toJSON());
|
||||
// { type: 'a',
|
||||
// props: { href: 'https://www.facebook.com/' },
|
||||
// children: [ 'Facebook' ] }
|
||||
```
|
||||
|
||||
You can also use Jest's snapshot testing feature to automatically save a copy of the JSON tree to a file and check in your tests that it hasn't changed: http://facebook.github.io/jest/blog/2016/07/27/jest-14.html.
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
|
||||
'use strict';
|
||||
|
||||
module.exports = require('react/lib/ReactTestRenderer');
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"name": "react-test-renderer",
|
||||
"version": "15.3.0-rc.3",
|
||||
"description": "React package for snapshot testing.",
|
||||
"main": "index.js",
|
||||
"repository": "facebook/react",
|
||||
"keywords": [
|
||||
"react",
|
||||
"react-native",
|
||||
"react-testing"
|
||||
],
|
||||
"license": "BSD-3-Clause",
|
||||
"bugs": {
|
||||
"url": "https://github.com/facebook/react/issues"
|
||||
},
|
||||
"homepage": "https://facebook.github.io/react/",
|
||||
"peerDependencies": {
|
||||
"react": "^15.3.0-rc.3"
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "react",
|
||||
"description": "React is a JavaScript library for building user interfaces.",
|
||||
"version": "15.2.1",
|
||||
"version": "15.3.0-rc.3",
|
||||
"keywords": [
|
||||
"react"
|
||||
],
|
||||
|
||||
+4783
-8681
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+3884
-6330
File diff suppressed because it is too large.
Load diff
@@ -2,11 +2,18 @@
|
||||
/*eslint-disable no-debugger */
|
||||
|
||||
// Copy and paste this file into your (Chrome) browser console after changing
|
||||
// the React root ID. Works on facebook.com as of 10/28/15 (use a test user).
|
||||
// the React root ID. Works on facebook.com as of 7/6/16 (use a test user).
|
||||
// Then run this to convert the JSX:
|
||||
//
|
||||
// ../../node_modules/.bin/babel \
|
||||
// --presets ../../node_modules/babel-preset-react \
|
||||
// --no-babelrc --compact=false \
|
||||
// bench-foo.js -o bench-foo-es5.js
|
||||
|
||||
'use strict';
|
||||
|
||||
var rootID = '.0';
|
||||
var rootID = 5;
|
||||
var outputStatelessFunctional = false;
|
||||
|
||||
var React = require('React');
|
||||
var ReactMount = require('ReactMount');
|
||||
@@ -28,18 +35,50 @@ function elementMeta(element) {
|
||||
}
|
||||
|
||||
function print(outerComponent) {
|
||||
function addComposite(name, child) {
|
||||
output += 'var ' + name + ' = React.createClass({\n';
|
||||
output += ' render: function() {\n';
|
||||
if (child.indexOf('\n') !== -1) {
|
||||
output += ' return (\n';
|
||||
output += child.replace(/^|\n/g, '$& ') + '\n';
|
||||
output += ' );\n';
|
||||
var typeCounter = 0;
|
||||
var elementCounter = 0;
|
||||
var composites = new Map();
|
||||
|
||||
function addComposite(type, child) {
|
||||
var info = composites.get(type);
|
||||
if (!info) {
|
||||
var name = (type.displayName || type.name || 'Component').replace(/(?:^[^a-z]|\W)+/gi, '_') + typeCounter++;
|
||||
if (!/^[A-Z]/.test(name)) {
|
||||
name = '_' + name;
|
||||
}
|
||||
info = {name: name, values: new Map()};
|
||||
composites.set(type, info);
|
||||
}
|
||||
var c = elementCounter++;
|
||||
info.values.set(c, child);
|
||||
return '<' + info.name + ' x={' + c + '} />';
|
||||
}
|
||||
|
||||
function printComposite(info) {
|
||||
if (outputStatelessFunctional) {
|
||||
output += 'var ' + info.name + ' = function(props) {\n';
|
||||
} else {
|
||||
output += ' return ' + child + ';\n';
|
||||
output += 'var ' + info.name + ' = React.createClass({\n';
|
||||
output += ' render: function() {\n';
|
||||
output += ' var props = this.props;\n';
|
||||
}
|
||||
for (var [c, child] of info.values) {
|
||||
output += ' if (props.x === ' + c + ') {\n';
|
||||
if (child.indexOf('\n') !== -1) {
|
||||
output += ' return (\n';
|
||||
output += child.replace(/^|\n/g, '$& ') + '\n';
|
||||
output += ' );\n';
|
||||
} else {
|
||||
output += ' return ' + child + ';\n';
|
||||
}
|
||||
output += ' }\n';
|
||||
}
|
||||
if (outputStatelessFunctional) {
|
||||
output += '};\n';
|
||||
} else {
|
||||
output += ' },\n';
|
||||
output += '});\n';
|
||||
}
|
||||
output += ' },\n';
|
||||
output += '});\n';
|
||||
output += '\n';
|
||||
}
|
||||
|
||||
@@ -59,15 +98,8 @@ function print(outerComponent) {
|
||||
// Composite component
|
||||
if (typeof element.type === 'function') {
|
||||
var rendered = printImpl(component._renderedComponent);
|
||||
var name = (component.getName() || 'Component').replace(/(?:^[^a-z]|\W)+/gi, '_') + counter++;
|
||||
if (!/^[A-Z]/.test(name)) {
|
||||
name = '_' + name;
|
||||
}
|
||||
addComposite(name, rendered);
|
||||
var compositeMarkup = '<' + name;
|
||||
compositeMarkup += elementMeta(component._currentElement);
|
||||
compositeMarkup += ' />';
|
||||
return compositeMarkup;
|
||||
return addComposite(component._currentElement.type, rendered)
|
||||
.replace(/(?= \/>$)/, elementMeta(component._currentElement));
|
||||
}
|
||||
|
||||
// Native component
|
||||
@@ -116,6 +148,10 @@ function print(outerComponent) {
|
||||
if (typeof children === 'boolean' || children == null) {
|
||||
return '' + children;
|
||||
}
|
||||
if (typeof children === 'object' && !Array.isArray(children) && children[Symbol.iterator]) {
|
||||
// TODO: Not quite right.
|
||||
children = Array.from(children);
|
||||
}
|
||||
if (Array.isArray(children)) {
|
||||
return children.length ? (
|
||||
'[\n' +
|
||||
@@ -159,10 +195,12 @@ function print(outerComponent) {
|
||||
}
|
||||
|
||||
var output = '(function() {\n\n';
|
||||
var counter = 0;
|
||||
|
||||
var tail = printImpl(outerComponent);
|
||||
addComposite('Benchmark', tail);
|
||||
for (var info of composites.values()) {
|
||||
printComposite(info);
|
||||
}
|
||||
printComposite({name: 'Benchmark', values: new Map([[undefined, tail]])});
|
||||
output += 'this.Benchmark = Benchmark;\n';
|
||||
output += '\n})(this);\n';
|
||||
return output;
|
||||
|
||||
@@ -137,5 +137,6 @@
|
||||
"135": "Cannot find single active touch",
|
||||
"136": "Attempted to update component `%s` that has already been unmounted (or failed to mount).",
|
||||
"137": "%s is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`.%s",
|
||||
"138": "Touch object is missing identifier."
|
||||
"138": "Touch object is missing identifier.",
|
||||
"139": "ReactTestRenderer: .update() can't be called after unmount."
|
||||
}
|
||||
+1
-1
@@ -11,4 +11,4 @@
|
||||
|
||||
'use strict';
|
||||
|
||||
module.exports = '15.2.1';
|
||||
module.exports = '15.3.0-rc.3';
|
||||
@@ -15,6 +15,7 @@ var emptyFunction = require('emptyFunction');
|
||||
var LinkPropTypes = require('ReactLink').PropTypes;
|
||||
var React = require('React');
|
||||
var ReactPropTypeLocations = require('ReactPropTypeLocations');
|
||||
var ReactPropTypesSecret = require('ReactPropTypesSecret');
|
||||
|
||||
var invalidMessage = 'Invalid prop `testProp` supplied to `testComponent`.';
|
||||
var requiredMessage =
|
||||
@@ -26,7 +27,9 @@ function typeCheckFail(declaration, value, message) {
|
||||
props,
|
||||
'testProp',
|
||||
'testComponent',
|
||||
ReactPropTypeLocations.prop
|
||||
ReactPropTypeLocations.prop,
|
||||
null,
|
||||
ReactPropTypesSecret
|
||||
);
|
||||
expect(error instanceof Error).toBe(true);
|
||||
expect(error.message).toBe(message);
|
||||
@@ -38,7 +41,9 @@ function typeCheckPass(declaration, value) {
|
||||
props,
|
||||
'testProp',
|
||||
'testComponent',
|
||||
ReactPropTypeLocations.prop
|
||||
ReactPropTypeLocations.prop,
|
||||
null,
|
||||
ReactPropTypesSecret
|
||||
);
|
||||
expect(error).toBe(null);
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
|
||||
var ReactChildren = require('ReactChildren');
|
||||
var ReactComponent = require('ReactComponent');
|
||||
var ReactPureComponent = require('ReactPureComponent');
|
||||
var ReactClass = require('ReactClass');
|
||||
var ReactDOMFactories = require('ReactDOMFactories');
|
||||
var ReactElement = require('ReactElement');
|
||||
@@ -63,6 +64,7 @@ var React = {
|
||||
},
|
||||
|
||||
Component: ReactComponent,
|
||||
PureComponent: ReactPureComponent,
|
||||
|
||||
createElement: createElement,
|
||||
cloneElement: cloneElement,
|
||||
|
||||
@@ -436,6 +436,21 @@ function validateMethodOverride(isAlreadyDefined, name) {
|
||||
*/
|
||||
function mixSpecIntoComponent(Constructor, spec) {
|
||||
if (!spec) {
|
||||
if (__DEV__) {
|
||||
var typeofSpec = typeof spec;
|
||||
var isMixinValid = typeofSpec === 'object' && spec !== null;
|
||||
|
||||
warning(
|
||||
isMixinValid,
|
||||
'%s: You\'re attempting to include a mixin that is either null ' +
|
||||
'or not an object. Check the mixins included by the component, ' +
|
||||
'as well as any mixins they include themselves. ' +
|
||||
'Expected object but got %s.',
|
||||
Constructor.displayName || 'ReactClass',
|
||||
spec === null ? null : typeofSpec
|
||||
);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -310,6 +310,94 @@ describe('ReactClass-mixin', function() {
|
||||
);
|
||||
});
|
||||
|
||||
it('should warn if the mixin is undefined', function() {
|
||||
spyOn(console, 'error');
|
||||
|
||||
React.createClass({
|
||||
mixins: [undefined],
|
||||
|
||||
render: function() {
|
||||
return <span />;
|
||||
},
|
||||
});
|
||||
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: ReactClass: You\'re attempting to include a mixin that is ' +
|
||||
'either null or not an object. Check the mixins included by the ' +
|
||||
'component, as well as any mixins they include themselves. ' +
|
||||
'Expected object but got undefined.'
|
||||
);
|
||||
});
|
||||
|
||||
it('should warn if the mixin is null', function() {
|
||||
spyOn(console, 'error');
|
||||
|
||||
React.createClass({
|
||||
mixins: [null],
|
||||
|
||||
render: function() {
|
||||
return <span />;
|
||||
},
|
||||
});
|
||||
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: ReactClass: You\'re attempting to include a mixin that is ' +
|
||||
'either null or not an object. Check the mixins included by the ' +
|
||||
'component, as well as any mixins they include themselves. ' +
|
||||
'Expected object but got null.'
|
||||
);
|
||||
});
|
||||
|
||||
it('should warn if an undefined mixin is included in another mixin', function() {
|
||||
spyOn(console, 'error');
|
||||
|
||||
var mixinA = {
|
||||
mixins: [undefined],
|
||||
};
|
||||
|
||||
React.createClass({
|
||||
mixins: [mixinA],
|
||||
|
||||
render: function() {
|
||||
return <span />;
|
||||
},
|
||||
});
|
||||
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: ReactClass: You\'re attempting to include a mixin that is ' +
|
||||
'either null or not an object. Check the mixins included by the ' +
|
||||
'component, as well as any mixins they include themselves. ' +
|
||||
'Expected object but got undefined.'
|
||||
);
|
||||
});
|
||||
|
||||
it('should warn if a null mixin is included in another mixin', function() {
|
||||
spyOn(console, 'error');
|
||||
|
||||
var mixinA = {
|
||||
mixins: [null],
|
||||
};
|
||||
|
||||
React.createClass({
|
||||
mixins: [mixinA],
|
||||
|
||||
render: function() {
|
||||
return <span />;
|
||||
},
|
||||
});
|
||||
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: ReactClass: You\'re attempting to include a mixin that is ' +
|
||||
'either null or not an object. Check the mixins included by the ' +
|
||||
'component, as well as any mixins they include themselves. ' +
|
||||
'Expected object but got null.'
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw if the mixin is a React component', function() {
|
||||
expect(function() {
|
||||
React.createClass({
|
||||
|
||||
@@ -97,6 +97,7 @@ var ReactElement = function(type, key, ref, self, source, owner, props) {
|
||||
// This can be replaced with a WeakMap once they are implemented in
|
||||
// commonly used development environments.
|
||||
element._store = {};
|
||||
var shadowChildren = Array.isArray(props.children) ? props.children.slice(0) : props.children;
|
||||
|
||||
// To make comparing ReactElements easier for testing purposes, we make
|
||||
// the validation flag non-enumerable (where possible, which should
|
||||
@@ -116,6 +117,12 @@ var ReactElement = function(type, key, ref, self, source, owner, props) {
|
||||
writable: false,
|
||||
value: self,
|
||||
});
|
||||
Object.defineProperty(element, '_shadowChildren', {
|
||||
configurable: false,
|
||||
enumerable: false,
|
||||
writable: false,
|
||||
value: shadowChildren,
|
||||
});
|
||||
// Two elements created in two different places should be considered
|
||||
// equal for testing purposes and therefore we hide it from enumeration.
|
||||
Object.defineProperty(element, '_source', {
|
||||
@@ -127,6 +134,7 @@ var ReactElement = function(type, key, ref, self, source, owner, props) {
|
||||
} else {
|
||||
element._store.validated = false;
|
||||
element._self = self;
|
||||
element._shadowChildren = shadowChildren;
|
||||
element._source = source;
|
||||
}
|
||||
if (Object.freeze) {
|
||||
|
||||
@@ -13,9 +13,11 @@
|
||||
|
||||
var ReactElement = require('ReactElement');
|
||||
var ReactPropTypeLocationNames = require('ReactPropTypeLocationNames');
|
||||
var ReactPropTypesSecret = require('ReactPropTypesSecret');
|
||||
|
||||
var emptyFunction = require('emptyFunction');
|
||||
var getIteratorFn = require('getIteratorFn');
|
||||
var warning = require('warning');
|
||||
|
||||
/**
|
||||
* Collection of methods that allow declaration and validation of props that are
|
||||
@@ -104,16 +106,41 @@ function is(x, y) {
|
||||
/*eslint-enable no-self-compare*/
|
||||
|
||||
function createChainableTypeChecker(validate) {
|
||||
if (__DEV__) {
|
||||
var manualPropTypeCallCache = {};
|
||||
}
|
||||
function checkType(
|
||||
isRequired,
|
||||
props,
|
||||
propName,
|
||||
componentName,
|
||||
location,
|
||||
propFullName
|
||||
propFullName,
|
||||
secret
|
||||
) {
|
||||
componentName = componentName || ANONYMOUS;
|
||||
propFullName = propFullName || propName;
|
||||
if (__DEV__) {
|
||||
if (
|
||||
secret !== ReactPropTypesSecret &&
|
||||
typeof console !== 'undefined'
|
||||
) {
|
||||
var cacheKey = `${componentName}:${propName}`;
|
||||
if (!manualPropTypeCallCache[cacheKey]) {
|
||||
warning(
|
||||
false,
|
||||
'You are manually calling a React.PropTypes validation ' +
|
||||
'function for the `%s` prop on `%s`. This is deprecated ' +
|
||||
'and will not work in the next major version. You may be ' +
|
||||
'seeing this warning due to a third-party PropTypes library. ' +
|
||||
'See https://fb.me/react-warning-dont-call-proptypes for details.',
|
||||
propFullName,
|
||||
componentName
|
||||
);
|
||||
manualPropTypeCallCache[cacheKey] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (props[propName] == null) {
|
||||
var locationName = ReactPropTypeLocationNames[location];
|
||||
if (isRequired) {
|
||||
@@ -124,7 +151,13 @@ function createChainableTypeChecker(validate) {
|
||||
}
|
||||
return null;
|
||||
} else {
|
||||
return validate(props, propName, componentName, location, propFullName);
|
||||
return validate(
|
||||
props,
|
||||
propName,
|
||||
componentName,
|
||||
location,
|
||||
propFullName,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -135,7 +168,14 @@ function createChainableTypeChecker(validate) {
|
||||
}
|
||||
|
||||
function createPrimitiveTypeChecker(expectedType) {
|
||||
function validate(props, propName, componentName, location, propFullName) {
|
||||
function validate(
|
||||
props,
|
||||
propName,
|
||||
componentName,
|
||||
location,
|
||||
propFullName,
|
||||
secret
|
||||
) {
|
||||
var propValue = props[propName];
|
||||
var propType = getPropType(propValue);
|
||||
if (propType !== expectedType) {
|
||||
@@ -182,7 +222,8 @@ function createArrayOfTypeChecker(typeChecker) {
|
||||
i,
|
||||
componentName,
|
||||
location,
|
||||
`${propFullName}[${i}]`
|
||||
`${propFullName}[${i}]`,
|
||||
ReactPropTypesSecret
|
||||
);
|
||||
if (error instanceof Error) {
|
||||
return error;
|
||||
@@ -195,11 +236,13 @@ function createArrayOfTypeChecker(typeChecker) {
|
||||
|
||||
function createElementTypeChecker() {
|
||||
function validate(props, propName, componentName, location, propFullName) {
|
||||
if (!ReactElement.isValidElement(props[propName])) {
|
||||
var propValue = props[propName];
|
||||
if (!ReactElement.isValidElement(propValue)) {
|
||||
var locationName = ReactPropTypeLocationNames[location];
|
||||
var propType = getPropType(propValue);
|
||||
return new Error(
|
||||
`Invalid ${locationName} \`${propFullName}\` supplied to ` +
|
||||
`\`${componentName}\`, expected a single ReactElement.`
|
||||
`Invalid ${locationName} \`${propFullName}\` of type ` +
|
||||
`\`${propType}\` supplied to \`${componentName}\`, expected a single ReactElement.`
|
||||
);
|
||||
}
|
||||
return null;
|
||||
@@ -226,11 +269,8 @@ function createInstanceTypeChecker(expectedClass) {
|
||||
|
||||
function createEnumTypeChecker(expectedValues) {
|
||||
if (!Array.isArray(expectedValues)) {
|
||||
return createChainableTypeChecker(function() {
|
||||
return new Error(
|
||||
`Invalid argument supplied to oneOf, expected an instance of array.`
|
||||
);
|
||||
});
|
||||
warning(false, 'Invalid argument supplied to oneOf, expected an instance of array.');
|
||||
return emptyFunction.thatReturnsNull;
|
||||
}
|
||||
|
||||
function validate(props, propName, componentName, location, propFullName) {
|
||||
@@ -274,7 +314,8 @@ function createObjectOfTypeChecker(typeChecker) {
|
||||
key,
|
||||
componentName,
|
||||
location,
|
||||
`${propFullName}.${key}`
|
||||
`${propFullName}.${key}`,
|
||||
ReactPropTypesSecret
|
||||
);
|
||||
if (error instanceof Error) {
|
||||
return error;
|
||||
@@ -288,18 +329,22 @@ function createObjectOfTypeChecker(typeChecker) {
|
||||
|
||||
function createUnionTypeChecker(arrayOfTypeCheckers) {
|
||||
if (!Array.isArray(arrayOfTypeCheckers)) {
|
||||
return createChainableTypeChecker(function() {
|
||||
return new Error(
|
||||
`Invalid argument supplied to oneOfType, expected an instance of array.`
|
||||
);
|
||||
});
|
||||
warning(false, 'Invalid argument supplied to oneOfType, expected an instance of array.');
|
||||
return emptyFunction.thatReturnsNull;
|
||||
}
|
||||
|
||||
function validate(props, propName, componentName, location, propFullName) {
|
||||
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
|
||||
var checker = arrayOfTypeCheckers[i];
|
||||
if (
|
||||
checker(props, propName, componentName, location, propFullName) == null
|
||||
checker(
|
||||
props,
|
||||
propName,
|
||||
componentName,
|
||||
location,
|
||||
propFullName,
|
||||
ReactPropTypesSecret
|
||||
) == null
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
@@ -349,7 +394,8 @@ function createShapeTypeChecker(shapeTypes) {
|
||||
key,
|
||||
componentName,
|
||||
location,
|
||||
`${propFullName}.${key}`
|
||||
`${propFullName}.${key}`,
|
||||
ReactPropTypesSecret
|
||||
);
|
||||
if (error) {
|
||||
return error;
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* @providesModule ReactPropTypesSecret
|
||||
*/
|
||||
|
||||
|
||||
'use strict';
|
||||
|
||||
|
||||
const ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
|
||||
|
||||
module.exports = ReactPropTypesSecret;
|
||||
@@ -16,6 +16,7 @@ var React;
|
||||
var ReactFragment;
|
||||
var ReactPropTypeLocations;
|
||||
var ReactTestUtils;
|
||||
var ReactPropTypesSecret;
|
||||
|
||||
var Component;
|
||||
var MyComponent;
|
||||
@@ -28,7 +29,9 @@ function typeCheckFail(declaration, value, message) {
|
||||
props,
|
||||
'testProp',
|
||||
'testComponent',
|
||||
ReactPropTypeLocations.prop
|
||||
ReactPropTypeLocations.prop,
|
||||
null,
|
||||
ReactPropTypesSecret
|
||||
);
|
||||
expect(error instanceof Error).toBe(true);
|
||||
expect(error.message).toBe(message);
|
||||
@@ -40,11 +43,32 @@ function typeCheckPass(declaration, value) {
|
||||
props,
|
||||
'testProp',
|
||||
'testComponent',
|
||||
ReactPropTypeLocations.prop
|
||||
ReactPropTypeLocations.prop,
|
||||
null,
|
||||
ReactPropTypesSecret
|
||||
);
|
||||
expect(error).toBe(null);
|
||||
}
|
||||
|
||||
function expectWarningInDevelopment(declaration, value) {
|
||||
var props = {testProp: value};
|
||||
var propName = 'testProp' + Math.random().toString();
|
||||
var componentName = 'testComponent' + Math.random().toString();
|
||||
for (var i = 0; i < 3; i ++) {
|
||||
declaration(
|
||||
props,
|
||||
propName,
|
||||
componentName,
|
||||
'prop'
|
||||
);
|
||||
}
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'You are manually calling a React.PropTypes validation '
|
||||
);
|
||||
console.error.calls.reset();
|
||||
}
|
||||
|
||||
describe('ReactPropTypes', function() {
|
||||
beforeEach(function() {
|
||||
PropTypes = require('ReactPropTypes');
|
||||
@@ -52,6 +76,7 @@ describe('ReactPropTypes', function() {
|
||||
ReactFragment = require('ReactFragment');
|
||||
ReactPropTypeLocations = require('ReactPropTypeLocations');
|
||||
ReactTestUtils = require('ReactTestUtils');
|
||||
ReactPropTypesSecret = require('ReactPropTypesSecret');
|
||||
});
|
||||
|
||||
describe('Primitive Types', function() {
|
||||
@@ -124,6 +149,54 @@ describe('ReactPropTypes', function() {
|
||||
typeCheckFail(PropTypes.string.isRequired, null, requiredMessage);
|
||||
typeCheckFail(PropTypes.string.isRequired, undefined, requiredMessage);
|
||||
});
|
||||
|
||||
it('should warn if called manually in development', function() {
|
||||
spyOn(console, 'error');
|
||||
expectWarningInDevelopment(PropTypes.array, /please/);
|
||||
expectWarningInDevelopment(PropTypes.array, []);
|
||||
expectWarningInDevelopment(PropTypes.array.isRequired, /please/);
|
||||
expectWarningInDevelopment(PropTypes.array.isRequired, []);
|
||||
expectWarningInDevelopment(PropTypes.array.isRequired, null);
|
||||
expectWarningInDevelopment(PropTypes.array.isRequired, undefined);
|
||||
expectWarningInDevelopment(PropTypes.bool, []);
|
||||
expectWarningInDevelopment(PropTypes.bool, true);
|
||||
expectWarningInDevelopment(PropTypes.bool.isRequired, []);
|
||||
expectWarningInDevelopment(PropTypes.bool.isRequired, true);
|
||||
expectWarningInDevelopment(PropTypes.bool.isRequired, null);
|
||||
expectWarningInDevelopment(PropTypes.bool.isRequired, undefined);
|
||||
expectWarningInDevelopment(PropTypes.func, false);
|
||||
expectWarningInDevelopment(PropTypes.func, function() {});
|
||||
expectWarningInDevelopment(PropTypes.func.isRequired, false);
|
||||
expectWarningInDevelopment(PropTypes.func.isRequired, function() {});
|
||||
expectWarningInDevelopment(PropTypes.func.isRequired, null);
|
||||
expectWarningInDevelopment(PropTypes.func.isRequired, undefined);
|
||||
expectWarningInDevelopment(PropTypes.number, function() {});
|
||||
expectWarningInDevelopment(PropTypes.number, 42);
|
||||
expectWarningInDevelopment(PropTypes.number.isRequired, function() {});
|
||||
expectWarningInDevelopment(PropTypes.number.isRequired, 42);
|
||||
expectWarningInDevelopment(PropTypes.number.isRequired, null);
|
||||
expectWarningInDevelopment(PropTypes.number.isRequired, undefined);
|
||||
expectWarningInDevelopment(PropTypes.string, 0);
|
||||
expectWarningInDevelopment(PropTypes.string, 'foo');
|
||||
expectWarningInDevelopment(PropTypes.string.isRequired, 0);
|
||||
expectWarningInDevelopment(PropTypes.string.isRequired, 'foo');
|
||||
expectWarningInDevelopment(PropTypes.string.isRequired, null);
|
||||
expectWarningInDevelopment(PropTypes.string.isRequired, undefined);
|
||||
expectWarningInDevelopment(PropTypes.symbol, 0);
|
||||
expectWarningInDevelopment(PropTypes.symbol, Symbol('Foo'));
|
||||
expectWarningInDevelopment(PropTypes.symbol.isRequired, 0);
|
||||
expectWarningInDevelopment(PropTypes.symbol.isRequired, Symbol('Foo'));
|
||||
expectWarningInDevelopment(PropTypes.symbol.isRequired, null);
|
||||
expectWarningInDevelopment(PropTypes.symbol.isRequired, undefined);
|
||||
expectWarningInDevelopment(PropTypes.object, '');
|
||||
expectWarningInDevelopment(PropTypes.object, {foo: 'bar'});
|
||||
expectWarningInDevelopment(PropTypes.object.isRequired, '');
|
||||
expectWarningInDevelopment(PropTypes.object.isRequired, {foo: 'bar'});
|
||||
expectWarningInDevelopment(PropTypes.object.isRequired, null);
|
||||
expectWarningInDevelopment(PropTypes.object.isRequired, undefined);
|
||||
});
|
||||
|
||||
|
||||
});
|
||||
|
||||
describe('Any type', function() {
|
||||
@@ -143,6 +216,14 @@ describe('ReactPropTypes', function() {
|
||||
typeCheckFail(PropTypes.any.isRequired, null, requiredMessage);
|
||||
typeCheckFail(PropTypes.any.isRequired, undefined, requiredMessage);
|
||||
});
|
||||
|
||||
it('should warn if called manually in development', function() {
|
||||
spyOn(console, 'error');
|
||||
expectWarningInDevelopment(PropTypes.any, null);
|
||||
expectWarningInDevelopment(PropTypes.any.isRequired, null);
|
||||
expectWarningInDevelopment(PropTypes.any.isRequired, undefined);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe('ArrayOf Type', function() {
|
||||
@@ -237,6 +318,24 @@ describe('ReactPropTypes', function() {
|
||||
requiredMessage
|
||||
);
|
||||
});
|
||||
|
||||
it('should warn if called manually in development', function() {
|
||||
spyOn(console, 'error');
|
||||
expectWarningInDevelopment(
|
||||
PropTypes.arrayOf({ foo: PropTypes.string }),
|
||||
{ foo: 'bar' }
|
||||
);
|
||||
expectWarningInDevelopment(
|
||||
PropTypes.arrayOf(PropTypes.number),
|
||||
[1, 2, 'b']
|
||||
);
|
||||
expectWarningInDevelopment(
|
||||
PropTypes.arrayOf(PropTypes.number),
|
||||
{'0': 'maybe-array', length: 1}
|
||||
);
|
||||
expectWarningInDevelopment(PropTypes.arrayOf(PropTypes.number).isRequired, null);
|
||||
expectWarningInDevelopment(PropTypes.arrayOf(PropTypes.number).isRequired, undefined);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Component Type', function() {
|
||||
@@ -257,12 +356,30 @@ describe('ReactPropTypes', function() {
|
||||
});
|
||||
|
||||
it('should not support multiple components or scalar values', () => {
|
||||
var message = 'Invalid prop `testProp` supplied to `testComponent`, ' +
|
||||
'expected a single ReactElement.';
|
||||
typeCheckFail(PropTypes.element, [<div />, <div />], message);
|
||||
typeCheckFail(PropTypes.element, 123, message);
|
||||
typeCheckFail(PropTypes.element, 'foo', message);
|
||||
typeCheckFail(PropTypes.element, false, message);
|
||||
typeCheckFail(
|
||||
PropTypes.element,
|
||||
[<div />, <div />],
|
||||
'Invalid prop `testProp` of type `array` supplied to `testComponent`, ' +
|
||||
'expected a single ReactElement.'
|
||||
);
|
||||
typeCheckFail(
|
||||
PropTypes.element,
|
||||
123,
|
||||
'Invalid prop `testProp` of type `number` supplied to `testComponent`, ' +
|
||||
'expected a single ReactElement.'
|
||||
);
|
||||
typeCheckFail(
|
||||
PropTypes.element,
|
||||
'foo',
|
||||
'Invalid prop `testProp` of type `string` supplied to `testComponent`, ' +
|
||||
'expected a single ReactElement.'
|
||||
);
|
||||
typeCheckFail(
|
||||
PropTypes.element,
|
||||
false,
|
||||
'Invalid prop `testProp` of type `boolean` supplied to `testComponent`, ' +
|
||||
'expected a single ReactElement.'
|
||||
);
|
||||
});
|
||||
|
||||
it('should be able to define a single child as label', () => {
|
||||
@@ -292,6 +409,18 @@ describe('ReactPropTypes', function() {
|
||||
typeCheckFail(PropTypes.element.isRequired, null, requiredMessage);
|
||||
typeCheckFail(PropTypes.element.isRequired, undefined, requiredMessage);
|
||||
});
|
||||
|
||||
it('should warn if called manually in development', function() {
|
||||
spyOn(console, 'error');
|
||||
expectWarningInDevelopment(PropTypes.element, [<div />, <div />]);
|
||||
expectWarningInDevelopment(PropTypes.element, <div />);
|
||||
expectWarningInDevelopment(PropTypes.element, 123);
|
||||
expectWarningInDevelopment(PropTypes.element, 'foo');
|
||||
expectWarningInDevelopment(PropTypes.element, false);
|
||||
expectWarningInDevelopment(PropTypes.element.isRequired, null);
|
||||
expectWarningInDevelopment(PropTypes.element.isRequired, undefined);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe('Instance Types', function() {
|
||||
@@ -371,6 +500,15 @@ describe('ReactPropTypes', function() {
|
||||
PropTypes.instanceOf(String).isRequired, undefined, requiredMessage
|
||||
);
|
||||
});
|
||||
|
||||
it('should warn if called manually in development', function() {
|
||||
spyOn(console, 'error');
|
||||
expectWarningInDevelopment(PropTypes.instanceOf(Date), {});
|
||||
expectWarningInDevelopment(PropTypes.instanceOf(Date), new Date());
|
||||
expectWarningInDevelopment(PropTypes.instanceOf(Date).isRequired, {});
|
||||
expectWarningInDevelopment(PropTypes.instanceOf(Date).isRequired, new Date());
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe('React Component Types', function() {
|
||||
@@ -478,6 +616,16 @@ describe('ReactPropTypes', function() {
|
||||
it('should accept empty array for required props', function() {
|
||||
typeCheckPass(PropTypes.node.isRequired, []);
|
||||
});
|
||||
|
||||
it('should warn if called manually in development', function() {
|
||||
spyOn(console, 'error');
|
||||
expectWarningInDevelopment(PropTypes.node, 'node');
|
||||
expectWarningInDevelopment(PropTypes.node, {});
|
||||
expectWarningInDevelopment(PropTypes.node.isRequired, 'node');
|
||||
expectWarningInDevelopment(PropTypes.node.isRequired, undefined);
|
||||
expectWarningInDevelopment(PropTypes.node.isRequired, undefined);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe('ObjectOf Type', function() {
|
||||
@@ -587,15 +735,34 @@ describe('ReactPropTypes', function() {
|
||||
requiredMessage
|
||||
);
|
||||
});
|
||||
|
||||
it('should warn if called manually in development', function() {
|
||||
spyOn(console, 'error');
|
||||
expectWarningInDevelopment(
|
||||
PropTypes.objectOf({ foo: PropTypes.string }),
|
||||
{ foo: 'bar' }
|
||||
);
|
||||
expectWarningInDevelopment(
|
||||
PropTypes.objectOf(PropTypes.number),
|
||||
{a: 1, b: 2, c: 'b'}
|
||||
);
|
||||
expectWarningInDevelopment(PropTypes.objectOf(PropTypes.number), [1, 2]);
|
||||
expectWarningInDevelopment(PropTypes.objectOf(PropTypes.number), null);
|
||||
expectWarningInDevelopment(PropTypes.objectOf(PropTypes.number), undefined);
|
||||
});
|
||||
});
|
||||
|
||||
describe('OneOf Types', function() {
|
||||
it('should fail for invalid argument', function() {
|
||||
typeCheckFail(
|
||||
PropTypes.oneOf('red', 'blue'),
|
||||
'red',
|
||||
'Invalid argument supplied to oneOf, expected an instance of array.'
|
||||
);
|
||||
it('should warn but not error for invalid argument', function() {
|
||||
spyOn(console, 'error');
|
||||
|
||||
PropTypes.oneOf('red', 'blue');
|
||||
|
||||
expect(console.error).toHaveBeenCalled();
|
||||
expect(console.error.calls.argsFor(0)[0])
|
||||
.toContain('Invalid argument supplied to oneOf, expected an instance of array.');
|
||||
|
||||
typeCheckPass(PropTypes.oneOf('red', 'blue'), 'red');
|
||||
});
|
||||
|
||||
it('should warn for invalid values', function() {
|
||||
@@ -648,15 +815,26 @@ describe('ReactPropTypes', function() {
|
||||
requiredMessage
|
||||
);
|
||||
});
|
||||
|
||||
it('should warn if called manually in development', function() {
|
||||
spyOn(console, 'error');
|
||||
expectWarningInDevelopment(PropTypes.oneOf(['red', 'blue']), true);
|
||||
expectWarningInDevelopment(PropTypes.oneOf(['red', 'blue']), null);
|
||||
expectWarningInDevelopment(PropTypes.oneOf(['red', 'blue']), undefined);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Union Types', function() {
|
||||
it('should fail for invalid argument', function() {
|
||||
typeCheckFail(
|
||||
PropTypes.oneOfType(PropTypes.string, PropTypes.number),
|
||||
'red',
|
||||
'Invalid argument supplied to oneOfType, expected an instance of array.'
|
||||
);
|
||||
it('should warn but not error for invalid argument', function() {
|
||||
spyOn(console, 'error');
|
||||
|
||||
PropTypes.oneOfType(PropTypes.string, PropTypes.number);
|
||||
|
||||
expect(console.error).toHaveBeenCalled();
|
||||
expect(console.error.calls.argsFor(0)[0])
|
||||
.toContain('Invalid argument supplied to oneOfType, expected an instance of array.');
|
||||
|
||||
typeCheckPass(PropTypes.oneOf(PropTypes.string, PropTypes.number), []);
|
||||
});
|
||||
|
||||
it('should warn if none of the types are valid', function() {
|
||||
@@ -715,6 +893,23 @@ describe('ReactPropTypes', function() {
|
||||
requiredMessage
|
||||
);
|
||||
});
|
||||
|
||||
it('should warn if called manually in development', function() {
|
||||
spyOn(console, 'error');
|
||||
expectWarningInDevelopment(
|
||||
PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
|
||||
[]
|
||||
);
|
||||
expectWarningInDevelopment(
|
||||
PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
|
||||
null
|
||||
);
|
||||
expectWarningInDevelopment(
|
||||
PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
|
||||
undefined
|
||||
);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe('Shape Types', function() {
|
||||
@@ -799,6 +994,21 @@ describe('ReactPropTypes', function() {
|
||||
requiredMessage
|
||||
);
|
||||
});
|
||||
|
||||
it('should warn if called manually in development', function() {
|
||||
spyOn(console, 'error');
|
||||
expectWarningInDevelopment(PropTypes.shape({}), 'some string');
|
||||
expectWarningInDevelopment(PropTypes.shape({ foo: PropTypes.number }), { foo: 42 });
|
||||
expectWarningInDevelopment(
|
||||
PropTypes.shape({key: PropTypes.number}).isRequired,
|
||||
null
|
||||
);
|
||||
expectWarningInDevelopment(
|
||||
PropTypes.shape({key: PropTypes.number}).isRequired,
|
||||
undefined
|
||||
);
|
||||
expectWarningInDevelopment(PropTypes.element, <div />);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Symbol Type', function() {
|
||||
|
||||
@@ -12,10 +12,26 @@
|
||||
'use strict';
|
||||
|
||||
var ReactPropTypeLocationNames = require('ReactPropTypeLocationNames');
|
||||
var ReactPropTypesSecret = require('ReactPropTypesSecret');
|
||||
|
||||
var invariant = require('invariant');
|
||||
var warning = require('warning');
|
||||
|
||||
var ReactComponentTreeDevtool;
|
||||
|
||||
if (
|
||||
typeof process !== 'undefined' &&
|
||||
process.env &&
|
||||
process.env.NODE_ENV === 'test'
|
||||
) {
|
||||
// Temporary hack.
|
||||
// Inline requires don't work well with Jest:
|
||||
// https://github.com/facebook/react/issues/7240
|
||||
// Remove the inline requires when we don't need them anymore:
|
||||
// https://github.com/facebook/react/pull/7178
|
||||
ReactComponentTreeDevtool = require('ReactComponentTreeDevtool')
|
||||
}
|
||||
|
||||
var loggedTypeFailures = {};
|
||||
|
||||
/**
|
||||
@@ -48,7 +64,7 @@ function checkReactTypeSpec(typeSpecs, values, location, componentName, element,
|
||||
ReactPropTypeLocationNames[location],
|
||||
typeSpecName
|
||||
);
|
||||
error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location);
|
||||
error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
|
||||
} catch (ex) {
|
||||
error = ex;
|
||||
}
|
||||
@@ -72,7 +88,9 @@ function checkReactTypeSpec(typeSpecs, values, location, componentName, element,
|
||||
var componentStackInfo = '';
|
||||
|
||||
if (__DEV__) {
|
||||
var ReactComponentTreeDevtool = require('ReactComponentTreeDevtool');
|
||||
if (!ReactComponentTreeDevtool) {
|
||||
ReactComponentTreeDevtool = require('ReactComponentTreeDevtool');
|
||||
}
|
||||
if (debugID !== null) {
|
||||
componentStackInfo = ReactComponentTreeDevtool.getStackAddendumByID(debugID);
|
||||
} else if (element !== null) {
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* @providesModule ReactPureComponent
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var ReactComponent = require('ReactComponent');
|
||||
var ReactNoopUpdateQueue = require('ReactNoopUpdateQueue');
|
||||
|
||||
var emptyObject = require('emptyObject');
|
||||
|
||||
/**
|
||||
* Base class helpers for the updating state of a component.
|
||||
*/
|
||||
function ReactPureComponent(props, context, updater) {
|
||||
// Duplicated from ReactComponent.
|
||||
this.props = props;
|
||||
this.context = context;
|
||||
this.refs = emptyObject;
|
||||
// We initialize the default updater but the real one gets injected by the
|
||||
// renderer.
|
||||
this.updater = updater || ReactNoopUpdateQueue;
|
||||
}
|
||||
|
||||
function ComponentDummy() {}
|
||||
ComponentDummy.prototype = ReactComponent.prototype;
|
||||
ReactPureComponent.prototype = new ComponentDummy();
|
||||
ReactPureComponent.prototype.constructor = ReactPureComponent;
|
||||
// Avoid an extra prototype jump for these methods.
|
||||
Object.assign(ReactPureComponent.prototype, ReactComponent.prototype);
|
||||
ReactPureComponent.prototype.isPureReactComponent = true;
|
||||
|
||||
module.exports = ReactPureComponent;
|
||||
@@ -0,0 +1,97 @@
|
||||
/**
|
||||
* 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;
|
||||
var ReactDOM;
|
||||
|
||||
describe('ReactPureComponent', function() {
|
||||
beforeEach(function() {
|
||||
React = require('React');
|
||||
ReactDOM = require('ReactDOM');
|
||||
});
|
||||
|
||||
it('should render', function() {
|
||||
var renders = 0;
|
||||
class Component extends React.PureComponent {
|
||||
constructor() {
|
||||
super();
|
||||
this.state = {type: 'mushrooms'};
|
||||
}
|
||||
render() {
|
||||
renders++;
|
||||
return <div>{this.props.text[0]}</div>;
|
||||
}
|
||||
}
|
||||
|
||||
var container = document.createElement('div');
|
||||
var text;
|
||||
var component;
|
||||
|
||||
text = ['porcini'];
|
||||
component = ReactDOM.render(<Component text={text} />, container);
|
||||
expect(container.textContent).toBe('porcini');
|
||||
expect(renders).toBe(1);
|
||||
|
||||
text = ['morel'];
|
||||
component = ReactDOM.render(<Component text={text} />, container);
|
||||
expect(container.textContent).toBe('morel');
|
||||
expect(renders).toBe(2);
|
||||
|
||||
text[0] = 'portobello';
|
||||
component = ReactDOM.render(<Component text={text} />, container);
|
||||
expect(container.textContent).toBe('morel');
|
||||
expect(renders).toBe(2);
|
||||
|
||||
// Setting state without changing it doesn't cause a rerender.
|
||||
component.setState({type: 'mushrooms'});
|
||||
expect(container.textContent).toBe('morel');
|
||||
expect(renders).toBe(2);
|
||||
|
||||
// But changing state does.
|
||||
component.setState({type: 'portobello mushrooms'});
|
||||
expect(container.textContent).toBe('portobello');
|
||||
expect(renders).toBe(3);
|
||||
});
|
||||
|
||||
it('can override shouldComponentUpdate', function() {
|
||||
var renders = 0;
|
||||
class Component extends React.PureComponent {
|
||||
render() {
|
||||
renders++;
|
||||
return <div />;
|
||||
}
|
||||
shouldComponentUpdate() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
var container = document.createElement('div');
|
||||
ReactDOM.render(<Component />, container);
|
||||
ReactDOM.render(<Component />, container);
|
||||
expect(renders).toBe(2);
|
||||
});
|
||||
|
||||
it('extends React.Component', function() {
|
||||
var renders = 0;
|
||||
class Component extends React.PureComponent {
|
||||
render() {
|
||||
expect(this instanceof React.Component).toBe(true);
|
||||
expect(this instanceof React.PureComponent).toBe(true);
|
||||
renders++;
|
||||
return <div />;
|
||||
}
|
||||
}
|
||||
ReactDOM.render(<Component />, document.createElement('div'));
|
||||
expect(renders).toBe(1);
|
||||
});
|
||||
|
||||
});
|
||||
@@ -27,7 +27,7 @@ var warning = require('warning');
|
||||
|
||||
ReactDefaultInjection.inject();
|
||||
|
||||
var React = {
|
||||
var ReactDOM = {
|
||||
findDOMNode: findDOMNode,
|
||||
render: ReactMount.render,
|
||||
unmountComponentAtNode: ReactMount.unmountComponentAtNode,
|
||||
@@ -135,4 +135,4 @@ if (__DEV__) {
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = React;
|
||||
module.exports = ReactDOM;
|
||||
@@ -483,6 +483,10 @@ for (var type in topLevelEventsToDispatchConfig) {
|
||||
var ON_CLICK_KEY = keyOf({onClick: null});
|
||||
var onClickListeners = {};
|
||||
|
||||
function getDictionaryKey(inst) {
|
||||
return '.' + inst._rootNodeID;
|
||||
}
|
||||
|
||||
var SimpleEventPlugin = {
|
||||
|
||||
eventTypes: eventTypes,
|
||||
@@ -620,10 +624,10 @@ var SimpleEventPlugin = {
|
||||
// fire. The workaround for this bug involves attaching an empty click
|
||||
// listener on the target node.
|
||||
if (registrationName === ON_CLICK_KEY) {
|
||||
var id = inst._rootNodeID;
|
||||
var key = getDictionaryKey(inst);
|
||||
var node = ReactDOMComponentTree.getNodeFromInstance(inst);
|
||||
if (!onClickListeners[id]) {
|
||||
onClickListeners[id] = EventListener.listen(
|
||||
if (!onClickListeners[key]) {
|
||||
onClickListeners[key] = EventListener.listen(
|
||||
node,
|
||||
'click',
|
||||
emptyFunction
|
||||
@@ -634,9 +638,9 @@ var SimpleEventPlugin = {
|
||||
|
||||
willDeleteListener: function(inst, registrationName) {
|
||||
if (registrationName === ON_CLICK_KEY) {
|
||||
var id = inst._rootNodeID;
|
||||
onClickListeners[id].remove();
|
||||
delete onClickListeners[id];
|
||||
var key = getDictionaryKey(inst);
|
||||
onClickListeners[key].remove();
|
||||
delete onClickListeners[key];
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
|
||||
var ReactPropTypes = require('ReactPropTypes');
|
||||
var ReactPropTypeLocations = require('ReactPropTypeLocations');
|
||||
var ReactPropTypesSecret = require('ReactPropTypesSecret');
|
||||
|
||||
var invariant = require('invariant');
|
||||
var warning = require('warning');
|
||||
@@ -109,7 +110,9 @@ var LinkedValueUtils = {
|
||||
props,
|
||||
propName,
|
||||
tagName,
|
||||
ReactPropTypeLocations.prop
|
||||
ReactPropTypeLocations.prop,
|
||||
null,
|
||||
ReactPropTypesSecret
|
||||
);
|
||||
}
|
||||
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
|
||||
|
||||
@@ -64,6 +64,9 @@ var ReactDOMInput = {
|
||||
// Make sure we set .type before any other properties (setting .value
|
||||
// before .type means .value is lost in IE11 and below)
|
||||
type: undefined,
|
||||
// Make sure we set .step before .value (setting .value before .step
|
||||
// means .value is rounded on mount, based upon step precision)
|
||||
step: undefined,
|
||||
}, DisabledInputUtils.getHostProps(inst, props), {
|
||||
defaultChecked: undefined,
|
||||
defaultValue: undefined,
|
||||
|
||||
@@ -718,7 +718,7 @@ describe('ReactDOMInput', function() {
|
||||
);
|
||||
});
|
||||
|
||||
it('sets type before value always', function() {
|
||||
it('sets type and step before value always', function() {
|
||||
if (!ReactDOMFeatureFlags.useCreateElement) {
|
||||
return;
|
||||
}
|
||||
@@ -740,12 +740,14 @@ describe('ReactDOMInput', function() {
|
||||
return el;
|
||||
});
|
||||
|
||||
ReactTestUtils.renderIntoDocument(<input value="hi" type="radio" />);
|
||||
// Setting value before type does bad things. Make sure we set type first.
|
||||
ReactTestUtils.renderIntoDocument(<input value="0" type="range" min="0" max="100" step="1" />);
|
||||
expect(log).toEqual([
|
||||
'set data-reactroot',
|
||||
'set type',
|
||||
'set step',
|
||||
'set value',
|
||||
'set min',
|
||||
'set max',
|
||||
'set value',
|
||||
'set checked',
|
||||
'set checked',
|
||||
|
||||
@@ -55,7 +55,12 @@ var DOMRenderer = ReactFiberReconciler({
|
||||
return domElement;
|
||||
},
|
||||
|
||||
prepareUpdate(domElement : Instance, oldProps : Props, newProps : Props, children : HostChildren<Instance>) : boolean {
|
||||
prepareUpdate(
|
||||
domElement : Instance,
|
||||
oldProps : Props,
|
||||
newProps : Props,
|
||||
children : HostChildren<Instance>
|
||||
) : boolean {
|
||||
return true;
|
||||
},
|
||||
|
||||
|
||||
@@ -25,6 +25,8 @@ var emptyObject = require('emptyObject');
|
||||
var instantiateReactComponent = require('instantiateReactComponent');
|
||||
var invariant = require('invariant');
|
||||
|
||||
var pendingTransactions = 0;
|
||||
|
||||
/**
|
||||
* @param {ReactElement} element
|
||||
* @return {string} the HTML markup
|
||||
@@ -36,6 +38,8 @@ function renderToStringImpl(element, makeStaticMarkup) {
|
||||
|
||||
transaction = ReactServerRenderingTransaction.getPooled(makeStaticMarkup);
|
||||
|
||||
pendingTransactions++;
|
||||
|
||||
return transaction.perform(function() {
|
||||
var componentInstance = instantiateReactComponent(element, true);
|
||||
var markup = ReactReconciler.mountComponent(
|
||||
@@ -56,10 +60,15 @@ function renderToStringImpl(element, makeStaticMarkup) {
|
||||
return markup;
|
||||
}, null);
|
||||
} finally {
|
||||
pendingTransactions--;
|
||||
ReactServerRenderingTransaction.release(transaction);
|
||||
// Revert to the DOM batching strategy since these two renderers
|
||||
// currently share these stateful modules.
|
||||
ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy);
|
||||
if (!pendingTransactions) {
|
||||
ReactUpdates.injection.injectBatchingStrategy(
|
||||
ReactDefaultBatchingStrategy
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -399,6 +399,37 @@ describe('ReactServerRendering', function() {
|
||||
);
|
||||
expect(markup.indexOf('hello, world') >= 0).toBe(true);
|
||||
});
|
||||
|
||||
it('renders components with different batching strategies', function() {
|
||||
var StaticComponent = React.createClass({
|
||||
render: function() {
|
||||
const staticContent = ReactServerRendering.renderToStaticMarkup(
|
||||
<div>
|
||||
<img src="foo-bar.jpg" />
|
||||
</div>
|
||||
);
|
||||
return <div dangerouslySetInnerHTML={{__html: staticContent}} />;
|
||||
},
|
||||
});
|
||||
|
||||
var Component = React.createClass({
|
||||
componentWillMount: function() {
|
||||
this.setState({text: 'hello, world'});
|
||||
},
|
||||
render: function() {
|
||||
return <div>{this.state.text}</div>;
|
||||
},
|
||||
});
|
||||
expect(
|
||||
ReactServerRendering.renderToString.bind(
|
||||
ReactServerRendering,
|
||||
<div>
|
||||
<StaticComponent />
|
||||
<Component />
|
||||
</div>
|
||||
)
|
||||
).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
it('warns with a no-op when an async setState is triggered', function() {
|
||||
|
||||
@@ -121,6 +121,7 @@ var HTMLDOMPropertyConfig = {
|
||||
profile: 0,
|
||||
radioGroup: 0,
|
||||
readOnly: HAS_BOOLEAN_VALUE,
|
||||
referrerPolicy: 0,
|
||||
rel: 0,
|
||||
required: HAS_BOOLEAN_VALUE,
|
||||
reversed: HAS_BOOLEAN_VALUE,
|
||||
|
||||
@@ -706,6 +706,13 @@ ReactDOMComponent.Mixin = {
|
||||
break;
|
||||
}
|
||||
|
||||
if (__DEV__) {
|
||||
if (this._debugID) {
|
||||
var callback = () => ReactInstrumentation.debugTool.onComponentHasMounted(this._debugID);
|
||||
transaction.getReactMountReady().enqueue(callback, this);
|
||||
}
|
||||
}
|
||||
|
||||
return mountImage;
|
||||
},
|
||||
|
||||
@@ -926,6 +933,13 @@ ReactDOMComponent.Mixin = {
|
||||
// reconciliation
|
||||
transaction.getReactMountReady().enqueue(postUpdateSelectWrapper, this);
|
||||
}
|
||||
|
||||
if (__DEV__) {
|
||||
if (this._debugID) {
|
||||
var callback = () => ReactInstrumentation.debugTool.onComponentHasUpdated(this._debugID);
|
||||
transaction.getReactMountReady().enqueue(callback, this);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
|
||||
@@ -263,6 +263,8 @@ var ATTRS = {
|
||||
xlinkTitle: 'xlink:title',
|
||||
xlinkType: 'xlink:type',
|
||||
xmlBase: 'xml:base',
|
||||
xmlns: 0,
|
||||
xmlnsXlink: 'xmlns:xlink',
|
||||
xmlLang: 'xml:lang',
|
||||
xmlSpace: 'xml:space',
|
||||
y: 0,
|
||||
|
||||
@@ -217,6 +217,6 @@ function mountSafeCallback(
|
||||
}
|
||||
return callback.apply(context, arguments);
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = NativeMethodsMixin;
|
||||
@@ -169,7 +169,10 @@ var ReactNoop = {
|
||||
}
|
||||
|
||||
function logFiber(fiber : Fiber, depth) {
|
||||
console.log(' '.repeat(depth) + '- ' + (fiber.type ? fiber.type.name || fiber.type : '[root]'), '[' + fiber.pendingWorkPriority + (fiber.pendingProps ? '*' : '') + ']');
|
||||
console.log(
|
||||
' '.repeat(depth) + '- ' + (fiber.type ? fiber.type.name || fiber.type : '[root]'),
|
||||
'[' + fiber.pendingWorkPriority + (fiber.pendingProps ? '*' : '') + ']'
|
||||
);
|
||||
if (fiber.child) {
|
||||
logFiber(fiber.child, depth + 1);
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
var ReactInvalidSetStateWarningDevTool = require('ReactInvalidSetStateWarningDevTool');
|
||||
var ReactHostOperationHistoryDevtool = require('ReactHostOperationHistoryDevtool');
|
||||
var ReactComponentTreeDevtool = require('ReactComponentTreeDevtool');
|
||||
var ReactChildrenMutationWarningDevtool = require('ReactChildrenMutationWarningDevtool');
|
||||
var ExecutionEnvironment = require('ExecutionEnvironment');
|
||||
|
||||
var performanceNow = require('performanceNow');
|
||||
@@ -51,6 +52,8 @@ var currentTimerStartTime = null;
|
||||
var currentTimerNestedFlushDuration = null;
|
||||
var currentTimerType = null;
|
||||
|
||||
var lifeCycleTimerHasWarned = false;
|
||||
|
||||
function clearHistory() {
|
||||
ReactComponentTreeDevtool.purgeUnmountedComponents();
|
||||
ReactHostOperationHistoryDevtool.clearHistory();
|
||||
@@ -108,15 +111,18 @@ function beginLifeCycleTimer(debugID, timerType) {
|
||||
if (currentFlushNesting === 0) {
|
||||
return;
|
||||
}
|
||||
warning(
|
||||
!currentTimerType,
|
||||
'There is an internal error in the React performance measurement code. ' +
|
||||
'Did not expect %s timer to start while %s timer is still in ' +
|
||||
'progress for %s instance.',
|
||||
timerType,
|
||||
currentTimerType || 'no',
|
||||
(debugID === currentTimerDebugID) ? 'the same' : 'another'
|
||||
);
|
||||
if (currentTimerType && !lifeCycleTimerHasWarned) {
|
||||
warning(
|
||||
false,
|
||||
'There is an internal error in the React performance measurement code. ' +
|
||||
'Did not expect %s timer to start while %s timer is still in ' +
|
||||
'progress for %s instance.',
|
||||
timerType,
|
||||
currentTimerType || 'no',
|
||||
(debugID === currentTimerDebugID) ? 'the same' : 'another'
|
||||
);
|
||||
lifeCycleTimerHasWarned = true;
|
||||
}
|
||||
currentTimerStartTime = performanceNow();
|
||||
currentTimerNestedFlushDuration = 0;
|
||||
currentTimerDebugID = debugID;
|
||||
@@ -127,15 +133,18 @@ function endLifeCycleTimer(debugID, timerType) {
|
||||
if (currentFlushNesting === 0) {
|
||||
return;
|
||||
}
|
||||
warning(
|
||||
currentTimerType === timerType,
|
||||
'There is an internal error in the React performance measurement code. ' +
|
||||
'We did not expect %s timer to stop while %s timer is still in ' +
|
||||
'progress for %s instance. Please report this as a bug in React.',
|
||||
timerType,
|
||||
currentTimerType || 'no',
|
||||
(debugID === currentTimerDebugID) ? 'the same' : 'another'
|
||||
);
|
||||
if (currentTimerType !== timerType && !lifeCycleTimerHasWarned) {
|
||||
warning(
|
||||
false,
|
||||
'There is an internal error in the React performance measurement code. ' +
|
||||
'We did not expect %s timer to stop while %s timer is still in ' +
|
||||
'progress for %s instance. Please report this as a bug in React.',
|
||||
timerType,
|
||||
currentTimerType || 'no',
|
||||
(debugID === currentTimerDebugID) ? 'the same' : 'another'
|
||||
);
|
||||
lifeCycleTimerHasWarned = true;
|
||||
}
|
||||
if (isProfiling) {
|
||||
currentFlushMeasurements.push({
|
||||
timerType,
|
||||
@@ -255,6 +264,14 @@ var ReactDebugTool = {
|
||||
checkDebugID(debugID);
|
||||
emitEvent('onHostOperation', debugID, type, payload);
|
||||
},
|
||||
onComponentHasMounted(debugID) {
|
||||
checkDebugID(debugID);
|
||||
emitEvent('onComponentHasMounted', debugID);
|
||||
},
|
||||
onComponentHasUpdated(debugID) {
|
||||
checkDebugID(debugID);
|
||||
emitEvent('onComponentHasUpdated', debugID);
|
||||
},
|
||||
onSetState() {
|
||||
emitEvent('onSetState');
|
||||
},
|
||||
@@ -310,6 +327,7 @@ var ReactDebugTool = {
|
||||
|
||||
ReactDebugTool.addDevtool(ReactInvalidSetStateWarningDevTool);
|
||||
ReactDebugTool.addDevtool(ReactComponentTreeDevtool);
|
||||
ReactDebugTool.addDevtool(ReactChildrenMutationWarningDevtool);
|
||||
var url = (ExecutionEnvironment.canUseDOM && window.location.href) || '';
|
||||
if ((/[?&]react_perf\b/).test(url)) {
|
||||
ReactDebugTool.beginProfiling();
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* @providesModule ReactChildrenMutationWarningDevtool
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var ReactComponentTreeDevtool = require('ReactComponentTreeDevtool');
|
||||
|
||||
var warning = require('warning');
|
||||
|
||||
var elements = {};
|
||||
|
||||
function handleElement(debugID, element) {
|
||||
if (element == null) {
|
||||
return;
|
||||
}
|
||||
if (element._shadowChildren === undefined) {
|
||||
return;
|
||||
}
|
||||
if (element._shadowChildren === element.props.children) {
|
||||
return;
|
||||
}
|
||||
var isMutated = false;
|
||||
if (Array.isArray(element._shadowChildren)) {
|
||||
if (element._shadowChildren.length === element.props.children.length) {
|
||||
for (var i = 0; i < element._shadowChildren.length; i++) {
|
||||
if (element._shadowChildren[i] !== element.props.children[i]) {
|
||||
isMutated = true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
isMutated = true;
|
||||
}
|
||||
}
|
||||
warning(
|
||||
Array.isArray(element._shadowChildren) && !isMutated,
|
||||
'Component\'s children should not be mutated.%s',
|
||||
ReactComponentTreeDevtool.getStackAddendumByID(debugID),
|
||||
);
|
||||
}
|
||||
|
||||
var ReactDOMUnknownPropertyDevtool = {
|
||||
onBeforeMountComponent(debugID, element) {
|
||||
elements[debugID] = element;
|
||||
},
|
||||
onBeforeUpdateComponent(debugID, element) {
|
||||
elements[debugID] = element;
|
||||
},
|
||||
onComponentHasMounted(debugID) {
|
||||
handleElement(debugID, elements[debugID]);
|
||||
delete elements[debugID];
|
||||
},
|
||||
onComponentHasUpdated(debugID) {
|
||||
handleElement(debugID, elements[debugID]);
|
||||
delete elements[debugID];
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = ReactDOMUnknownPropertyDevtool;
|
||||
@@ -1848,5 +1848,5 @@ describe('ReactComponentTreeDevtool', () => {
|
||||
}
|
||||
ReactDOM.render(<Foo />, el);
|
||||
});
|
||||
})
|
||||
});
|
||||
});
|
||||
@@ -34,7 +34,7 @@ describe('ReactHostOperationHistoryDevtool', () => {
|
||||
|
||||
afterEach(() => {
|
||||
ReactPerf.stop();
|
||||
})
|
||||
});
|
||||
|
||||
function assertHistoryMatches(expectedHistory) {
|
||||
var actualHistory = ReactHostOperationHistoryDevtool.getHistory();
|
||||
|
||||
@@ -29,7 +29,13 @@ var {
|
||||
var ReactFiber = require('ReactFiber');
|
||||
var ReactReifiedYield = require('ReactReifiedYield');
|
||||
|
||||
function createSubsequentChild(returnFiber : Fiber, existingChild : ?Fiber, previousSibling : Fiber, newChildren, priority : PriorityLevel) : Fiber {
|
||||
function createSubsequentChild(
|
||||
returnFiber : Fiber,
|
||||
existingChild : ?Fiber,
|
||||
previousSibling : Fiber,
|
||||
newChildren,
|
||||
priority : PriorityLevel
|
||||
) : Fiber {
|
||||
if (typeof newChildren !== 'object' || newChildren === null) {
|
||||
return previousSibling;
|
||||
}
|
||||
@@ -163,6 +169,11 @@ function createFirstChild(returnFiber, existingChild, newChildren, priority) {
|
||||
|
||||
// TODO: This API won't work because we'll need to transfer the side-effects of
|
||||
// unmounting children to the returnFiber.
|
||||
exports.reconcileChildFibers = function(returnFiber : Fiber, currentFirstChild : ?Fiber, newChildren : ReactNodeList, priority : PriorityLevel) : ?Fiber {
|
||||
exports.reconcileChildFibers = function(
|
||||
returnFiber : Fiber,
|
||||
currentFirstChild : ?Fiber,
|
||||
newChildren : ReactNodeList,
|
||||
priority : PriorityLevel
|
||||
) : ?Fiber {
|
||||
return createFirstChild(returnFiber, currentFirstChild, newChildren, priority);
|
||||
};
|
||||
@@ -56,7 +56,10 @@ module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
|
||||
}
|
||||
|
||||
function updateHostComponent(current, workInProgress) {
|
||||
console.log('host component', workInProgress.type, typeof workInProgress.pendingProps.children === 'string' ? workInProgress.pendingProps.children : '');
|
||||
console.log(
|
||||
'host component', workInProgress.type,
|
||||
typeof workInProgress.pendingProps.children === 'string' ? workInProgress.pendingProps.children : ''
|
||||
);
|
||||
|
||||
var nextChildren = workInProgress.pendingProps.children;
|
||||
|
||||
|
||||
@@ -53,6 +53,10 @@ var executeDispatchesAndReleaseTopLevel = function(e) {
|
||||
return executeDispatchesAndRelease(e, false);
|
||||
};
|
||||
|
||||
var getDictionaryKey = function(inst) {
|
||||
return '.' + inst._rootNodeID;
|
||||
};
|
||||
|
||||
/**
|
||||
* This is a unified interface for event plugins to be installed and configured.
|
||||
*
|
||||
@@ -96,7 +100,7 @@ var EventPluginHub = {
|
||||
},
|
||||
|
||||
/**
|
||||
* Stores `listener` at `listenerBank[registrationName][id]`. Is idempotent.
|
||||
* Stores `listener` at `listenerBank[registrationName][key]`. Is idempotent.
|
||||
*
|
||||
* @param {object} inst The instance, which is the source of events.
|
||||
* @param {string} registrationName Name of listener (e.g. `onClick`).
|
||||
@@ -109,9 +113,10 @@ var EventPluginHub = {
|
||||
registrationName, typeof listener
|
||||
);
|
||||
|
||||
var key = getDictionaryKey(inst);
|
||||
var bankForRegistrationName =
|
||||
listenerBank[registrationName] || (listenerBank[registrationName] = {});
|
||||
bankForRegistrationName[inst._rootNodeID] = listener;
|
||||
bankForRegistrationName[key] = listener;
|
||||
|
||||
var PluginModule =
|
||||
EventPluginRegistry.registrationNameModules[registrationName];
|
||||
@@ -127,7 +132,8 @@ var EventPluginHub = {
|
||||
*/
|
||||
getListener: function(inst, registrationName) {
|
||||
var bankForRegistrationName = listenerBank[registrationName];
|
||||
return bankForRegistrationName && bankForRegistrationName[inst._rootNodeID];
|
||||
var key = getDictionaryKey(inst);
|
||||
return bankForRegistrationName && bankForRegistrationName[key];
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -146,7 +152,8 @@ var EventPluginHub = {
|
||||
var bankForRegistrationName = listenerBank[registrationName];
|
||||
// TODO: This should never be null -- when is it?
|
||||
if (bankForRegistrationName) {
|
||||
delete bankForRegistrationName[inst._rootNodeID];
|
||||
var key = getDictionaryKey(inst);
|
||||
delete bankForRegistrationName[key];
|
||||
}
|
||||
},
|
||||
|
||||
@@ -156,12 +163,13 @@ var EventPluginHub = {
|
||||
* @param {object} inst The instance, which is the source of events.
|
||||
*/
|
||||
deleteAllListeners: function(inst) {
|
||||
var key = getDictionaryKey(inst);
|
||||
for (var registrationName in listenerBank) {
|
||||
if (!listenerBank.hasOwnProperty(registrationName)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!listenerBank[registrationName][inst._rootNodeID]) {
|
||||
|
||||
if (!listenerBank[registrationName][key]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -171,7 +179,7 @@ var EventPluginHub = {
|
||||
PluginModule.willDeleteListener(inst, registrationName);
|
||||
}
|
||||
|
||||
delete listenerBank[registrationName][inst._rootNodeID];
|
||||
delete listenerBank[registrationName][key];
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
@@ -19,11 +19,28 @@ var shouldUpdateReactComponent = require('shouldUpdateReactComponent');
|
||||
var traverseAllChildren = require('traverseAllChildren');
|
||||
var warning = require('warning');
|
||||
|
||||
var ReactComponentTreeDevtool;
|
||||
|
||||
if (
|
||||
typeof process !== 'undefined' &&
|
||||
process.env &&
|
||||
process.env.NODE_ENV === 'test'
|
||||
) {
|
||||
// Temporary hack.
|
||||
// Inline requires don't work well with Jest:
|
||||
// https://github.com/facebook/react/issues/7240
|
||||
// Remove the inline requires when we don't need them anymore:
|
||||
// https://github.com/facebook/react/pull/7178
|
||||
ReactComponentTreeDevtool = require('ReactComponentTreeDevtool')
|
||||
}
|
||||
|
||||
function instantiateChild(childInstances, child, name, selfDebugID) {
|
||||
// We found a component instance.
|
||||
var keyUnique = (childInstances[name] === undefined);
|
||||
if (__DEV__) {
|
||||
var ReactComponentTreeDevtool = require('ReactComponentTreeDevtool');
|
||||
if (!ReactComponentTreeDevtool) {
|
||||
ReactComponentTreeDevtool = require('ReactComponentTreeDevtool');
|
||||
}
|
||||
warning(
|
||||
keyUnique,
|
||||
'flattenChildren(...): Encountered two children with the same key, ' +
|
||||
@@ -93,8 +110,11 @@ var ReactChildReconciler = {
|
||||
updateChildren: function(
|
||||
prevChildren,
|
||||
nextChildren,
|
||||
mountImages,
|
||||
removedNodes,
|
||||
transaction,
|
||||
hostParent,
|
||||
hostContainerInfo,
|
||||
context) {
|
||||
// We currently don't have a way to track moves here but if we use iterators
|
||||
// instead of for..in we can zip the iterators and check if an item has
|
||||
@@ -127,6 +147,16 @@ var ReactChildReconciler = {
|
||||
// The child must be instantiated before it's mounted.
|
||||
var nextChildInstance = instantiateReactComponent(nextElement, true);
|
||||
nextChildren[name] = nextChildInstance;
|
||||
// Creating mount image now ensures refs are resolved in right order
|
||||
// (see https://github.com/facebook/react/pull/7101 for explanation).
|
||||
var nextChildMountImage = ReactReconciler.mountComponent(
|
||||
nextChildInstance,
|
||||
transaction,
|
||||
hostParent,
|
||||
hostContainerInfo,
|
||||
context
|
||||
);
|
||||
mountImages.push(nextChildMountImage);
|
||||
}
|
||||
}
|
||||
// Unmount children that are no longer present.
|
||||
|
||||
@@ -22,12 +22,18 @@ var ReactPropTypeLocations = require('ReactPropTypeLocations');
|
||||
var ReactReconciler = require('ReactReconciler');
|
||||
|
||||
var checkReactTypeSpec = require('checkReactTypeSpec');
|
||||
|
||||
var emptyObject = require('emptyObject');
|
||||
var invariant = require('invariant');
|
||||
var shallowEqual = require('shallowEqual');
|
||||
var shouldUpdateReactComponent = require('shouldUpdateReactComponent');
|
||||
var warning = require('warning');
|
||||
|
||||
var CompositeTypes = {
|
||||
ImpureClass: 0,
|
||||
PureClass: 1,
|
||||
StatelessFunctional: 2,
|
||||
};
|
||||
|
||||
function StatelessComponent(Component) {
|
||||
}
|
||||
StatelessComponent.prototype.render = function() {
|
||||
@@ -88,7 +94,11 @@ function invokeComponentDidUpdateWithTimer(prevProps, prevState, prevContext) {
|
||||
}
|
||||
|
||||
function shouldConstruct(Component) {
|
||||
return Component.prototype && Component.prototype.isReactComponent;
|
||||
return !!(Component.prototype && Component.prototype.isReactComponent);
|
||||
}
|
||||
|
||||
function isPureComponent(Component) {
|
||||
return !!(Component.prototype && Component.prototype.isPureReactComponent);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -141,6 +151,7 @@ var ReactCompositeComponentMixin = {
|
||||
construct: function(element) {
|
||||
this._currentElement = element;
|
||||
this._rootNodeID = null;
|
||||
this._compositeType = null;
|
||||
this._instance = null;
|
||||
this._hostParent = null;
|
||||
this._hostContainerInfo = null;
|
||||
@@ -199,11 +210,17 @@ var ReactCompositeComponentMixin = {
|
||||
var updateQueue = transaction.getUpdateQueue();
|
||||
|
||||
// Initialize the public class
|
||||
var inst = this._constructComponent(publicProps, publicContext, updateQueue);
|
||||
var doConstruct = shouldConstruct(Component);
|
||||
var inst = this._constructComponent(
|
||||
doConstruct,
|
||||
publicProps,
|
||||
publicContext,
|
||||
updateQueue
|
||||
);
|
||||
var renderedElement;
|
||||
|
||||
// Support functional components
|
||||
if (!shouldConstruct(Component) && (inst == null || inst.render == null)) {
|
||||
if (!doConstruct && (inst == null || inst.render == null)) {
|
||||
renderedElement = inst;
|
||||
warnIfInvalidElement(Component, renderedElement);
|
||||
invariant(
|
||||
@@ -215,6 +232,13 @@ var ReactCompositeComponentMixin = {
|
||||
Component.displayName || Component.name || 'Component'
|
||||
);
|
||||
inst = new StatelessComponent(Component);
|
||||
this._compositeType = CompositeTypes.StatelessFunctional;
|
||||
} else {
|
||||
if (isPureComponent(Component)) {
|
||||
this._compositeType = CompositeTypes.PureClass;
|
||||
} else {
|
||||
this._compositeType = CompositeTypes.ImpureClass;
|
||||
}
|
||||
}
|
||||
|
||||
if (__DEV__) {
|
||||
@@ -343,26 +367,53 @@ var ReactCompositeComponentMixin = {
|
||||
}
|
||||
}
|
||||
|
||||
if (__DEV__) {
|
||||
if (this._debugID) {
|
||||
var callback = (component) => ReactInstrumentation.debugTool.onComponentHasMounted(this._debugID);
|
||||
transaction.getReactMountReady().enqueue(callback, this);
|
||||
}
|
||||
}
|
||||
|
||||
return markup;
|
||||
},
|
||||
|
||||
_constructComponent: function(publicProps, publicContext, updateQueue) {
|
||||
_constructComponent: function(
|
||||
doConstruct,
|
||||
publicProps,
|
||||
publicContext,
|
||||
updateQueue
|
||||
) {
|
||||
if (__DEV__) {
|
||||
ReactCurrentOwner.current = this;
|
||||
try {
|
||||
return this._constructComponentWithoutOwner(publicProps, publicContext, updateQueue);
|
||||
return this._constructComponentWithoutOwner(
|
||||
doConstruct,
|
||||
publicProps,
|
||||
publicContext,
|
||||
updateQueue
|
||||
);
|
||||
} finally {
|
||||
ReactCurrentOwner.current = null;
|
||||
}
|
||||
} else {
|
||||
return this._constructComponentWithoutOwner(publicProps, publicContext, updateQueue);
|
||||
return this._constructComponentWithoutOwner(
|
||||
doConstruct,
|
||||
publicProps,
|
||||
publicContext,
|
||||
updateQueue
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
_constructComponentWithoutOwner: function(publicProps, publicContext, updateQueue) {
|
||||
_constructComponentWithoutOwner: function(
|
||||
doConstruct,
|
||||
publicProps,
|
||||
publicContext,
|
||||
updateQueue
|
||||
) {
|
||||
var Component = this._currentElement.type;
|
||||
var instanceOrElement;
|
||||
if (shouldConstruct(Component)) {
|
||||
if (doConstruct) {
|
||||
if (__DEV__) {
|
||||
if (this._debugID !== 0) {
|
||||
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(
|
||||
@@ -763,7 +814,6 @@ var ReactCompositeComponentMixin = {
|
||||
|
||||
var willReceive = false;
|
||||
var nextContext;
|
||||
var nextProps;
|
||||
|
||||
// Determine if the context has changed or not
|
||||
if (this._context === nextUnmaskedContext) {
|
||||
@@ -773,7 +823,8 @@ var ReactCompositeComponentMixin = {
|
||||
willReceive = true;
|
||||
}
|
||||
|
||||
nextProps = nextParentElement.props;
|
||||
var prevProps = prevParentElement.props;
|
||||
var nextProps = nextParentElement.props;
|
||||
|
||||
// Not a simple state update but a props update
|
||||
if (prevParentElement !== nextParentElement) {
|
||||
@@ -806,22 +857,30 @@ var ReactCompositeComponentMixin = {
|
||||
var nextState = this._processPendingState(nextProps, nextContext);
|
||||
var shouldUpdate = true;
|
||||
|
||||
if (!this._pendingForceUpdate && inst.shouldComponentUpdate) {
|
||||
if (__DEV__) {
|
||||
if (this._debugID !== 0) {
|
||||
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(
|
||||
this._debugID,
|
||||
'shouldComponentUpdate'
|
||||
);
|
||||
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 = inst.shouldComponentUpdate(nextProps, nextState, nextContext);
|
||||
if (__DEV__) {
|
||||
if (this._debugID !== 0) {
|
||||
ReactInstrumentation.debugTool.onEndLifeCycleTimer(
|
||||
this._debugID,
|
||||
'shouldComponentUpdate'
|
||||
);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (this._compositeType === CompositeTypes.PureClass) {
|
||||
shouldUpdate =
|
||||
!shallowEqual(prevProps, nextProps) ||
|
||||
!shallowEqual(inst.state, nextState);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -960,6 +1019,13 @@ var ReactCompositeComponentMixin = {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (__DEV__) {
|
||||
if (this._debugID) {
|
||||
var callback = () => ReactInstrumentation.debugTool.onComponentHasUpdated(this._debugID);
|
||||
transaction.getReactMountReady().enqueue(callback, this);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -1079,12 +1145,17 @@ var ReactCompositeComponentMixin = {
|
||||
*/
|
||||
_renderValidatedComponent: function() {
|
||||
var renderedComponent;
|
||||
ReactCurrentOwner.current = this;
|
||||
try {
|
||||
if (__DEV__ || this._compositeType !== CompositeTypes.StatelessFunctional) {
|
||||
ReactCurrentOwner.current = this;
|
||||
try {
|
||||
renderedComponent =
|
||||
this._renderValidatedComponentWithoutOwnerOrContext();
|
||||
} finally {
|
||||
ReactCurrentOwner.current = null;
|
||||
}
|
||||
} else {
|
||||
renderedComponent =
|
||||
this._renderValidatedComponentWithoutOwnerOrContext();
|
||||
} finally {
|
||||
ReactCurrentOwner.current = null;
|
||||
}
|
||||
invariant(
|
||||
// TODO: An `isValidNode` function would probably be more appropriate
|
||||
@@ -1164,7 +1235,7 @@ var ReactCompositeComponentMixin = {
|
||||
*/
|
||||
getPublicInstance: function() {
|
||||
var inst = this._instance;
|
||||
if (inst instanceof StatelessComponent) {
|
||||
if (this._compositeType === CompositeTypes.StatelessFunctional) {
|
||||
return null;
|
||||
}
|
||||
return inst;
|
||||
|
||||
@@ -212,6 +212,7 @@ var ReactMultiChild = {
|
||||
_reconcilerUpdateChildren: function(
|
||||
prevChildren,
|
||||
nextNestedChildrenElements,
|
||||
mountImages,
|
||||
removedNodes,
|
||||
transaction,
|
||||
context
|
||||
@@ -226,14 +227,28 @@ var ReactMultiChild = {
|
||||
ReactCurrentOwner.current = null;
|
||||
}
|
||||
ReactChildReconciler.updateChildren(
|
||||
prevChildren, nextChildren, removedNodes, transaction, context
|
||||
prevChildren,
|
||||
nextChildren,
|
||||
mountImages,
|
||||
removedNodes,
|
||||
transaction,
|
||||
this,
|
||||
this._hostContainerInfo,
|
||||
context
|
||||
);
|
||||
return nextChildren;
|
||||
}
|
||||
}
|
||||
nextChildren = flattenChildren(nextNestedChildrenElements);
|
||||
ReactChildReconciler.updateChildren(
|
||||
prevChildren, nextChildren, removedNodes, transaction, context
|
||||
prevChildren,
|
||||
nextChildren,
|
||||
mountImages,
|
||||
removedNodes,
|
||||
transaction,
|
||||
this,
|
||||
this._hostContainerInfo,
|
||||
context
|
||||
);
|
||||
return nextChildren;
|
||||
},
|
||||
@@ -339,9 +354,11 @@ var ReactMultiChild = {
|
||||
_updateChildren: function(nextNestedChildrenElements, transaction, context) {
|
||||
var prevChildren = this._renderedChildren;
|
||||
var removedNodes = {};
|
||||
var mountImages = [];
|
||||
var nextChildren = this._reconcilerUpdateChildren(
|
||||
prevChildren,
|
||||
nextNestedChildrenElements,
|
||||
mountImages,
|
||||
removedNodes,
|
||||
transaction,
|
||||
context
|
||||
@@ -353,8 +370,10 @@ var ReactMultiChild = {
|
||||
var name;
|
||||
// `nextIndex` will increment for each child in `nextChildren`, but
|
||||
// `lastIndex` will be the last index visited in `prevChildren`.
|
||||
var lastIndex = 0;
|
||||
var nextIndex = 0;
|
||||
var lastIndex = 0;
|
||||
// `nextMountIndex` will increment for each newly mounted child.
|
||||
var nextMountIndex = 0;
|
||||
var lastPlacedNode = null;
|
||||
for (name in nextChildren) {
|
||||
if (!nextChildren.hasOwnProperty(name)) {
|
||||
@@ -380,12 +399,14 @@ var ReactMultiChild = {
|
||||
updates,
|
||||
this._mountChildAtIndex(
|
||||
nextChild,
|
||||
mountImages[nextMountIndex],
|
||||
lastPlacedNode,
|
||||
nextIndex,
|
||||
transaction,
|
||||
context
|
||||
)
|
||||
);
|
||||
nextMountIndex++;
|
||||
}
|
||||
nextIndex++;
|
||||
lastPlacedNode = ReactReconciler.getHostNode(nextChild);
|
||||
@@ -473,17 +494,11 @@ var ReactMultiChild = {
|
||||
*/
|
||||
_mountChildAtIndex: function(
|
||||
child,
|
||||
mountImage,
|
||||
afterNode,
|
||||
index,
|
||||
transaction,
|
||||
context) {
|
||||
var mountImage = ReactReconciler.mountComponent(
|
||||
child,
|
||||
transaction,
|
||||
this,
|
||||
this._hostContainerInfo,
|
||||
context
|
||||
);
|
||||
child._mountIndex = index;
|
||||
return this.createChild(child, afterNode, mountImage);
|
||||
},
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
var ReactRef = require('ReactRef');
|
||||
var ReactInstrumentation = require('ReactInstrumentation');
|
||||
|
||||
var invariant = require('invariant');
|
||||
var warning = require('warning');
|
||||
|
||||
/**
|
||||
* Helper to call ReactRef.attachRefs with this composite component, split out
|
||||
@@ -206,7 +206,7 @@ var ReactReconciler = {
|
||||
if (internalInstance._updateBatchNumber !== updateBatchNumber) {
|
||||
// The component's enqueued batch number should always be the current
|
||||
// batch or the following one.
|
||||
invariant(
|
||||
warning(
|
||||
internalInstance._updateBatchNumber == null ||
|
||||
internalInstance._updateBatchNumber === updateBatchNumber + 1,
|
||||
'performUpdateIfNecessary: Unexpected batch number (current %s, ' +
|
||||
|
||||
@@ -62,8 +62,10 @@ ReactRef.shouldUpdateRefs = function(prevElement, nextElement) {
|
||||
return (
|
||||
// This has a few false positives w/r/t empty components.
|
||||
prevEmpty || nextEmpty ||
|
||||
nextElement._owner !== prevElement._owner ||
|
||||
nextElement.ref !== prevElement.ref
|
||||
nextElement.ref !== prevElement.ref ||
|
||||
// If owner changes but we have an unchanged function ref, don't update refs
|
||||
(typeof nextElement.ref === 'string' &&
|
||||
nextElement._owner !== prevElement._owner)
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ function getInternalInstanceReadyForUpdate(publicInstance, callerName) {
|
||||
var internalInstance = ReactInstanceMap.get(publicInstance);
|
||||
if (!internalInstance) {
|
||||
if (__DEV__) {
|
||||
var ctor = publicInstance.constructor;
|
||||
// Only warn when we have a callerName. Otherwise we should be silent.
|
||||
// We're probably calling from enqueueCallback. We don't want to warn
|
||||
// there because we already warned for the corresponding lifecycle method.
|
||||
@@ -50,7 +51,7 @@ function getInternalInstanceReadyForUpdate(publicInstance, callerName) {
|
||||
'This is a no-op. Please check the code for the %s component.',
|
||||
callerName,
|
||||
callerName,
|
||||
publicInstance.constructor.displayName
|
||||
ctor && (ctor.displayName || ctor.name) || 'ReactClass'
|
||||
);
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -15,6 +15,10 @@ var React;
|
||||
var ReactDOM;
|
||||
var ReactTestUtils;
|
||||
|
||||
function normalizeCodeLocInfo(str) {
|
||||
return str.replace(/\(at .+?:\d+\)/g, '(at **)');
|
||||
}
|
||||
|
||||
describe('ReactComponent', function() {
|
||||
beforeEach(function() {
|
||||
React = require('React');
|
||||
@@ -45,6 +49,32 @@ describe('ReactComponent', function() {
|
||||
}).toThrow();
|
||||
});
|
||||
|
||||
it('should warn when children are mutated before render', function() {
|
||||
spyOn(console, 'error');
|
||||
var children = [<span key={0} />, <span key={1} />, <span key={2} />];
|
||||
var element = <div>{children}</div>;
|
||||
children[1] = <p key={1} />; // Mutation is illegal
|
||||
ReactTestUtils.renderIntoDocument(element);
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
|
||||
'Warning: Component\'s children should not be mutated.\n in div (at **)'
|
||||
);
|
||||
});
|
||||
|
||||
it('should warn when children are mutated', function() {
|
||||
spyOn(console, 'error');
|
||||
var children = [<span key={0} />, <span key={1} />, <span key={2} />];
|
||||
function Wrapper(props) {
|
||||
props.children[1] = <p key={1} />; // Mutation is illegal
|
||||
return <div>{props.children}</div>;
|
||||
}
|
||||
ReactTestUtils.renderIntoDocument(<Wrapper>{children}</Wrapper>);
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
|
||||
'Warning: Component\'s children should not be mutated.\n in Wrapper (at **)'
|
||||
);
|
||||
});
|
||||
|
||||
it('should support refs on owned components', function() {
|
||||
var innerObj = {};
|
||||
var outerObj = {};
|
||||
|
||||
@@ -60,6 +60,14 @@ var StatusDisplay = React.createClass({
|
||||
return this.state.internalState;
|
||||
},
|
||||
|
||||
componentDidMount: function() {
|
||||
this.props.onFlush();
|
||||
},
|
||||
|
||||
componentDidUpdate: function() {
|
||||
this.props.onFlush();
|
||||
},
|
||||
|
||||
render: function() {
|
||||
return (
|
||||
<div>
|
||||
@@ -74,35 +82,61 @@ var StatusDisplay = React.createClass({
|
||||
*/
|
||||
var FriendsStatusDisplay = React.createClass({
|
||||
/**
|
||||
* Retrieves the rendered children in a nice format for comparing to the input
|
||||
* `this.props.usernameToStatus`. Gets the order directly from each rendered
|
||||
* child's `index` field. Refs are not maintained in the rendered order, and
|
||||
* neither is `this._renderedChildren` (surprisingly).
|
||||
*/
|
||||
getStatusDisplays: function() {
|
||||
var name;
|
||||
var orderOfUsernames = [];
|
||||
* Gets the order directly from each rendered child's `index` field.
|
||||
* Refs are not maintained in the rendered order, and neither is
|
||||
* `this._renderedChildren` (surprisingly).
|
||||
*/
|
||||
getOriginalKeys: function() {
|
||||
var originalKeys = [];
|
||||
// TODO: Update this to a better test that doesn't rely so much on internal
|
||||
// implementation details.
|
||||
var statusDisplays =
|
||||
ReactInstanceMap.get(this)
|
||||
._renderedComponent
|
||||
._renderedChildren;
|
||||
var name;
|
||||
for (name in statusDisplays) {
|
||||
var child = statusDisplays[name];
|
||||
var isPresent = !!child;
|
||||
if (isPresent) {
|
||||
orderOfUsernames[child._mountIndex] = getOriginalKey(name);
|
||||
originalKeys[child._mountIndex] = getOriginalKey(name);
|
||||
}
|
||||
}
|
||||
return originalKeys;
|
||||
},
|
||||
/**
|
||||
* Retrieves the rendered children in a nice format for comparing to the input
|
||||
* `this.props.usernameToStatus`.
|
||||
*/
|
||||
getStatusDisplays: function() {
|
||||
var res = {};
|
||||
var i;
|
||||
for (i = 0; i < orderOfUsernames.length; i++) {
|
||||
var key = orderOfUsernames[i];
|
||||
var originalKeys = this.getOriginalKeys();
|
||||
for (i = 0; i < originalKeys.length; i++) {
|
||||
var key = originalKeys[i];
|
||||
res[key] = this.refs[key];
|
||||
}
|
||||
return res;
|
||||
},
|
||||
/**
|
||||
* Verifies that by the time a child is flushed, the refs that appeared
|
||||
* earlier have already been resolved.
|
||||
* TODO: This assumption will likely break with incremental reconciler
|
||||
* but our internal layer API depends on this assumption. We need to change
|
||||
* it to be more declarative before making ref resolution indeterministic.
|
||||
*/
|
||||
verifyPreviousRefsResolved: function(flushedKey) {
|
||||
var i;
|
||||
var originalKeys = this.getOriginalKeys();
|
||||
for (i = 0; i < originalKeys.length; i++) {
|
||||
var key = originalKeys[i];
|
||||
if (key === flushedKey) {
|
||||
// We are only interested in children up to the current key.
|
||||
return;
|
||||
}
|
||||
expect(this.refs[key]).toBeTruthy();
|
||||
}
|
||||
},
|
||||
render: function() {
|
||||
var children = [];
|
||||
var key;
|
||||
@@ -110,7 +144,12 @@ var FriendsStatusDisplay = React.createClass({
|
||||
var status = this.props.usernameToStatus[key];
|
||||
children.push(
|
||||
!status ? null :
|
||||
<StatusDisplay key={key} ref={key} status={status} />
|
||||
<StatusDisplay
|
||||
key={key}
|
||||
ref={key}
|
||||
onFlush={this.verifyPreviousRefsResolved.bind(this, key)}
|
||||
status={status}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
@@ -239,12 +278,6 @@ function testPropsSequence(sequence) {
|
||||
describe('ReactMultiChildReconcile', function() {
|
||||
beforeEach(function() {
|
||||
jest.resetModuleRegistry();
|
||||
|
||||
React = require('React');
|
||||
ReactDOM = require('ReactDOM');
|
||||
ReactDOMComponentTree = require('ReactDOMComponentTree');
|
||||
ReactInstanceMap = require('ReactInstanceMap');
|
||||
mapObject = require('mapObject');
|
||||
});
|
||||
|
||||
it('should reset internal state if removed then readded', function() {
|
||||
|
||||
@@ -116,10 +116,6 @@ var expectClickLogsLengthToBe = function(instance, length) {
|
||||
describe('reactiverefs', function() {
|
||||
beforeEach(function() {
|
||||
jest.resetModuleRegistry();
|
||||
|
||||
React = require('React');
|
||||
ReactTestUtils = require('ReactTestUtils');
|
||||
reactComponentExpect = require('reactComponentExpect');
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -163,10 +159,6 @@ describe('reactiverefs', function() {
|
||||
describe('ref swapping', function() {
|
||||
beforeEach(function() {
|
||||
jest.resetModuleRegistry();
|
||||
|
||||
React = require('React');
|
||||
ReactTestUtils = require('ReactTestUtils');
|
||||
reactComponentExpect = require('reactComponentExpect');
|
||||
});
|
||||
|
||||
var RefHopsAround = React.createClass({
|
||||
@@ -248,4 +240,38 @@ describe('ref swapping', function() {
|
||||
var instance = ReactTestUtils.renderIntoDocument(<Component />);
|
||||
expect(!!instance.refs).toBe(true);
|
||||
});
|
||||
|
||||
function testRefCall() {
|
||||
var refCalled = 0;
|
||||
function Inner(props) {
|
||||
return <a ref={props.saveA} />;
|
||||
}
|
||||
var Outer = React.createClass({
|
||||
saveA() {
|
||||
refCalled++;
|
||||
},
|
||||
componentDidMount() {
|
||||
this.setState({});
|
||||
},
|
||||
render() {
|
||||
return <Inner saveA={this.saveA} />;
|
||||
},
|
||||
});
|
||||
ReactTestUtils.renderIntoDocument(<Outer />);
|
||||
expect(refCalled).toBe(1);
|
||||
}
|
||||
|
||||
it('ref called correctly for stateless component when __DEV__ = false', function() {
|
||||
var originalDev = __DEV__;
|
||||
__DEV__ = false;
|
||||
testRefCall();
|
||||
__DEV__ = originalDev;
|
||||
});
|
||||
|
||||
it('ref called correctly for stateless component when __DEV__ = true', function() {
|
||||
var originalDev = __DEV__;
|
||||
__DEV__ = true;
|
||||
testRefCall();
|
||||
__DEV__ = originalDev;
|
||||
});
|
||||
});
|
||||
@@ -19,6 +19,7 @@ var ReactUpdates = require('ReactUpdates');
|
||||
var emptyObject = require('emptyObject');
|
||||
var getHostComponentFromComposite = require('getHostComponentFromComposite');
|
||||
var instantiateReactComponent = require('instantiateReactComponent');
|
||||
var invariant = require('invariant');
|
||||
|
||||
/**
|
||||
* Temporary (?) hack so that we can store all top-level pending updates on
|
||||
@@ -83,6 +84,48 @@ var ReactTestInstance = function(component) {
|
||||
ReactTestInstance.prototype.getInstance = function() {
|
||||
return this._component._renderedComponent.getPublicInstance();
|
||||
};
|
||||
ReactTestInstance.prototype.update = function(nextElement) {
|
||||
invariant(
|
||||
this._component,
|
||||
"ReactTestRenderer: .update() can't be called after unmount."
|
||||
);
|
||||
var nextWrappedElement = new ReactElement(
|
||||
TopLevelWrapper,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
nextElement
|
||||
);
|
||||
var component = this._component;
|
||||
ReactUpdates.batchedUpdates(function() {
|
||||
var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(true);
|
||||
transaction.perform(function() {
|
||||
ReactReconciler.receiveComponent(
|
||||
component,
|
||||
nextWrappedElement,
|
||||
transaction,
|
||||
emptyObject
|
||||
);
|
||||
});
|
||||
ReactUpdates.ReactReconcileTransaction.release(transaction);
|
||||
});
|
||||
};
|
||||
ReactTestInstance.prototype.unmount = function(nextElement) {
|
||||
var component = this._component;
|
||||
ReactUpdates.batchedUpdates(function() {
|
||||
var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(true);
|
||||
transaction.perform(function() {
|
||||
ReactReconciler.unmountComponent(
|
||||
component,
|
||||
false
|
||||
);
|
||||
});
|
||||
ReactUpdates.ReactReconcileTransaction.release(transaction);
|
||||
});
|
||||
this._component = null;
|
||||
};
|
||||
ReactTestInstance.prototype.toJSON = function() {
|
||||
var inst = getHostComponentFromComposite(this._component);
|
||||
return inst.toJSON();
|
||||
@@ -92,7 +135,7 @@ ReactTestInstance.prototype.toJSON = function() {
|
||||
* As soon as `ReactMount` is refactored to not rely on the DOM, we can share
|
||||
* code between the two. For now, we'll hard code the ID logic.
|
||||
*/
|
||||
var ReactHostMount = {
|
||||
var ReactTestMount = {
|
||||
|
||||
render: function(
|
||||
nextElement: ReactElement
|
||||
@@ -107,19 +150,6 @@ var ReactHostMount = {
|
||||
nextElement
|
||||
);
|
||||
|
||||
// var prevComponent = ReactHostMount._instancesByContainerID[containerTag];
|
||||
// if (prevComponent) {
|
||||
// var prevWrappedElement = prevComponent._currentElement;
|
||||
// var prevElement = prevWrappedElement.props;
|
||||
// if (shouldUpdateReactComponent(prevElement, nextElement)) {
|
||||
// ReactUpdateQueue.enqueueElementInternal(prevComponent, nextWrappedElement);
|
||||
// if (callback) {
|
||||
// ReactUpdateQueue.enqueueCallbackInternal(prevComponent, callback);
|
||||
// }
|
||||
// return prevComponent;
|
||||
// }
|
||||
// }
|
||||
|
||||
var instance = instantiateReactComponent(nextWrappedElement, false);
|
||||
|
||||
// The initial render is synchronous but any updates that happen during
|
||||
@@ -141,4 +171,4 @@ var ReactHostMount = {
|
||||
|
||||
};
|
||||
|
||||
module.exports = ReactHostMount;
|
||||
module.exports = ReactTestMount;
|
||||
@@ -11,6 +11,7 @@
|
||||
|
||||
'use strict';
|
||||
|
||||
var ReactComponentEnvironment = require('ReactComponentEnvironment');
|
||||
var ReactDefaultBatchingStrategy = require('ReactDefaultBatchingStrategy');
|
||||
var ReactEmptyComponent = require('ReactEmptyComponent');
|
||||
var ReactMultiChild = require('ReactMultiChild');
|
||||
@@ -62,6 +63,11 @@ ReactTestComponent.prototype.receiveComponent = function(
|
||||
this.updateChildren(nextElement.props.children, transaction, context);
|
||||
};
|
||||
ReactTestComponent.prototype.getHostNode = function() {};
|
||||
ReactTestComponent.prototype.getPublicInstance = function() {
|
||||
// I can't say this makes a ton of sense but it seems better than throwing.
|
||||
// Maybe we'll revise later if someone has a good use case.
|
||||
return null;
|
||||
};
|
||||
ReactTestComponent.prototype.unmountComponent = function() {};
|
||||
ReactTestComponent.prototype.toJSON = function() {
|
||||
var {children, ...props} = this._currentElement.props;
|
||||
@@ -125,6 +131,11 @@ ReactEmptyComponent.injection.injectEmptyComponentFactory(function() {
|
||||
return new ReactTestEmptyComponent();
|
||||
});
|
||||
|
||||
ReactComponentEnvironment.injection.injectEnvironment({
|
||||
processChildrenUpdates: function() {},
|
||||
replaceNodeWithMarkup: function() {},
|
||||
});
|
||||
|
||||
var ReactTestRenderer = {
|
||||
create: ReactTestMount.render,
|
||||
|
||||
|
||||
@@ -110,4 +110,91 @@ describe('ReactTestRenderer', function() {
|
||||
});
|
||||
});
|
||||
|
||||
it('updates types', function() {
|
||||
var renderer = ReactTestRenderer.create(<div>mouse</div>);
|
||||
expect(renderer.toJSON()).toEqual({
|
||||
type: 'div',
|
||||
props: {},
|
||||
children: ['mouse'],
|
||||
});
|
||||
|
||||
renderer.update(<span>mice</span>);
|
||||
expect(renderer.toJSON()).toEqual({
|
||||
type: 'span',
|
||||
props: {},
|
||||
children: ['mice'],
|
||||
});
|
||||
});
|
||||
|
||||
it('updates children', function() {
|
||||
var renderer = ReactTestRenderer.create(
|
||||
<div>
|
||||
<span key="a">A</span>
|
||||
<span key="b">B</span>
|
||||
<span key="c">C</span>
|
||||
</div>
|
||||
);
|
||||
expect(renderer.toJSON()).toEqual({
|
||||
type: 'div',
|
||||
props: {},
|
||||
children: [
|
||||
{type: 'span', props: {}, children: ['A']},
|
||||
{type: 'span', props: {}, children: ['B']},
|
||||
{type: 'span', props: {}, children: ['C']},
|
||||
],
|
||||
});
|
||||
|
||||
renderer.update(
|
||||
<div>
|
||||
<span key="d">D</span>
|
||||
<span key="c">C</span>
|
||||
<span key="b">B</span>
|
||||
</div>
|
||||
);
|
||||
expect(renderer.toJSON()).toEqual({
|
||||
type: 'div',
|
||||
props: {},
|
||||
children: [
|
||||
{type: 'span', props: {}, children: ['D']},
|
||||
{type: 'span', props: {}, children: ['C']},
|
||||
{type: 'span', props: {}, children: ['B']},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('does the full lifecycle', function() {
|
||||
var log = [];
|
||||
class Log extends React.Component {
|
||||
render() {
|
||||
log.push('render ' + this.props.name);
|
||||
return <div />;
|
||||
}
|
||||
componentDidMount() {
|
||||
log.push('mount ' + this.props.name);
|
||||
}
|
||||
componentWillUnmount() {
|
||||
log.push('unmount ' + this.props.name);
|
||||
}
|
||||
}
|
||||
|
||||
var renderer = ReactTestRenderer.create(<Log key="foo" name="Foo" />);
|
||||
renderer.update(<Log key="bar" name="Bar" />);
|
||||
renderer.unmount();
|
||||
|
||||
expect(log).toEqual([
|
||||
'render Foo',
|
||||
'mount Foo',
|
||||
'unmount Foo',
|
||||
'render Bar',
|
||||
'mount Bar',
|
||||
'unmount Bar',
|
||||
]);
|
||||
});
|
||||
|
||||
it('gives a ref to native components', function() {
|
||||
var log = [];
|
||||
ReactTestRenderer.create(<div ref={(r) => log.push(r)} />);
|
||||
expect(log).toEqual([null]);
|
||||
});
|
||||
|
||||
});
|
||||
@@ -15,11 +15,14 @@ describe('traverseAllChildren', function() {
|
||||
var traverseAllChildren;
|
||||
var React;
|
||||
var ReactFragment;
|
||||
var ReactTestUtils;
|
||||
|
||||
beforeEach(function() {
|
||||
jest.resetModuleRegistry();
|
||||
traverseAllChildren = require('traverseAllChildren');
|
||||
React = require('React');
|
||||
ReactFragment = require('ReactFragment');
|
||||
ReactTestUtils = require('ReactTestUtils');
|
||||
});
|
||||
|
||||
function frag(obj) {
|
||||
@@ -536,4 +539,24 @@ describe('traverseAllChildren', function() {
|
||||
);
|
||||
});
|
||||
|
||||
it('should warn for using maps as children with owner info', function() {
|
||||
spyOn(console, 'error');
|
||||
|
||||
var Parent = React.createClass({
|
||||
render() {
|
||||
return (
|
||||
<div>{new Map([['foo', 0], ['bar', 1]])}</div>
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
ReactTestUtils.renderIntoDocument(<Parent />);
|
||||
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: Using Maps as children is not yet fully supported. It is an ' +
|
||||
'experimental feature that might be removed. Convert it to a sequence ' +
|
||||
'/ iterable of keyed ReactElements instead. Check the render method of `Parent`.'
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -16,6 +16,21 @@ var KeyEscapeUtils = require('KeyEscapeUtils');
|
||||
var traverseAllChildren = require('traverseAllChildren');
|
||||
var warning = require('warning');
|
||||
|
||||
var ReactComponentTreeDevtool;
|
||||
|
||||
if (
|
||||
typeof process !== 'undefined' &&
|
||||
process.env &&
|
||||
process.env.NODE_ENV === 'test'
|
||||
) {
|
||||
// Temporary hack.
|
||||
// Inline requires don't work well with Jest:
|
||||
// https://github.com/facebook/react/issues/7240
|
||||
// Remove the inline requires when we don't need them anymore:
|
||||
// https://github.com/facebook/react/pull/7178
|
||||
ReactComponentTreeDevtool = require('ReactComponentTreeDevtool')
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {function} traverseContext Context passed through traversal.
|
||||
* @param {?ReactComponent} child React child component.
|
||||
@@ -33,7 +48,9 @@ function flattenSingleChildIntoContext(
|
||||
const result = traverseContext;
|
||||
const keyUnique = (result[name] === undefined);
|
||||
if (__DEV__) {
|
||||
var ReactComponentTreeDevtool = require('ReactComponentTreeDevtool');
|
||||
if (!ReactComponentTreeDevtool) {
|
||||
ReactComponentTreeDevtool = require('ReactComponentTreeDevtool');
|
||||
}
|
||||
warning(
|
||||
keyUnique,
|
||||
'flattenChildren(...): Encountered two children with the same key, ' +
|
||||
|
||||
@@ -117,11 +117,19 @@ function traverseAllChildrenImpl(
|
||||
}
|
||||
} else {
|
||||
if (__DEV__) {
|
||||
var mapsAsChildrenAddendum = '';
|
||||
if (ReactCurrentOwner.current) {
|
||||
var mapsAsChildrenOwnerName = ReactCurrentOwner.current.getName();
|
||||
if (mapsAsChildrenOwnerName) {
|
||||
mapsAsChildrenAddendum = ' Check the render method of `' + mapsAsChildrenOwnerName + '`.';
|
||||
}
|
||||
}
|
||||
warning(
|
||||
didWarnAboutMaps,
|
||||
'Using Maps as children is not yet fully supported. It is an ' +
|
||||
'experimental feature that might be removed. Convert it to a ' +
|
||||
'sequence / iterable of keyed ReactElements instead.'
|
||||
'sequence / iterable of keyed ReactElements instead.%s',
|
||||
mapsAsChildrenAddendum
|
||||
);
|
||||
didWarnAboutMaps = true;
|
||||
}
|
||||
|
||||
@@ -410,9 +410,11 @@ NoopInternalComponent.prototype = {
|
||||
|
||||
var ShallowComponentWrapper = function(element) {
|
||||
// TODO: Consolidate with instantiateReactComponent
|
||||
this._debugID = nextDebugID++;
|
||||
var displayName = element.type.displayName || element.type.name || 'Unknown';
|
||||
ReactInstrumentation.debugTool.onSetDisplayName(this._debugID, displayName);
|
||||
if (__DEV__) {
|
||||
this._debugID = nextDebugID++;
|
||||
var displayName = element.type.displayName || element.type.name || 'Unknown';
|
||||
ReactInstrumentation.debugTool.onSetDisplayName(this._debugID, displayName);
|
||||
}
|
||||
|
||||
this.construct(element);
|
||||
};
|
||||
@@ -523,6 +525,8 @@ function makeSimulator(eventType) {
|
||||
|
||||
var fakeNativeEvent = new Event();
|
||||
fakeNativeEvent.target = node;
|
||||
fakeNativeEvent.type = eventType.toLowerCase();
|
||||
|
||||
// We don't use SyntheticEvent.getPooled in order to not have to worry about
|
||||
// properly destroying any properties assigned from `eventData` upon release
|
||||
var event = new SyntheticEvent(
|
||||
|
||||
@@ -558,4 +558,23 @@ describe('ReactTestUtils', function() {
|
||||
expect(hrs.length).toBe(2);
|
||||
});
|
||||
|
||||
describe('Simulate', () => {
|
||||
it('should set the type of the event', () => {
|
||||
let event;
|
||||
const stub = jest.genMockFn().mockImpl((e) => {
|
||||
e.persist();
|
||||
event = e;
|
||||
});
|
||||
|
||||
const container = document.createElement('div');
|
||||
const instance = ReactDOM.render(<div onKeyDown={stub} />, container);
|
||||
const node = ReactDOM.findDOMNode(instance);
|
||||
|
||||
ReactTestUtils.Simulate.keyDown(node);
|
||||
|
||||
expect(event.type).toBe('keydown');
|
||||
expect(event.nativeEvent.type).toBe('keydown');
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
Reference in new issue
Block a user