mirror of
https://github.com/facebook/react.git
synced 2025-11-01 09:12:30 +00:00
Merge branch '15-dev' into 15-stable
This commit is contained in:
commit
1808ecb348
220 files changed
+13719
-8768
No files matched your search
@@ -2,7 +2,6 @@
|
||||
"presets": ["react"],
|
||||
"ignore": ["third_party"],
|
||||
"plugins": [
|
||||
"fbjs-scripts/babel-6/dev-expression",
|
||||
"syntax-trailing-function-commas",
|
||||
"babel-plugin-transform-object-rest-spread",
|
||||
"transform-es2015-template-literals",
|
||||
@@ -22,6 +21,7 @@
|
||||
"transform-es2015-modules-commonjs",
|
||||
"transform-es3-member-expression-literals",
|
||||
"transform-es3-property-literals",
|
||||
"./scripts/babel/transform-object-assign-require"
|
||||
"./scripts/babel/transform-object-assign-require",
|
||||
"transform-react-jsx-source"
|
||||
]
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
# We can probably lint these later but not important at this point
|
||||
src/renderers/art
|
||||
src/shared/vendor
|
||||
# But not in docs/_js/examples/*
|
||||
docs/_js/*.js
|
||||
|
||||
@@ -30,6 +30,7 @@ module.exports = {
|
||||
'indent': [ERROR, 2, {SwitchCase: 1}],
|
||||
'jsx-quotes': [ERROR, 'prefer-double'],
|
||||
'no-bitwise': OFF,
|
||||
'no-inner-declarations': [ERROR, 'functions'],
|
||||
'no-multi-spaces': ERROR,
|
||||
'no-restricted-syntax': [ERROR, 'WithStatement'],
|
||||
'no-shadow': ERROR,
|
||||
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
[ignore]
|
||||
|
||||
.*/examples/.*
|
||||
.*/build/.*
|
||||
.*/node_modules/y18n/.*
|
||||
.*/__mocks__/.*
|
||||
.*/__tests__/.*
|
||||
|
||||
# Ignore Docs
|
||||
.*/docs/.*
|
||||
|
||||
[include]
|
||||
|
||||
[libs]
|
||||
./node_modules/fbjs/flow/lib
|
||||
./flow
|
||||
|
||||
[options]
|
||||
module.system=haste
|
||||
|
||||
esproposal.class_static_fields=enable
|
||||
esproposal.class_instance_fields=enable
|
||||
|
||||
experimental.strict_type_args=true
|
||||
|
||||
munge_underscores=false
|
||||
|
||||
suppress_type=$FlowIssue
|
||||
suppress_type=$FlowFixMe
|
||||
suppress_type=$FixMe
|
||||
|
||||
suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(>=0\\.\\(2[0-4]\\|1[0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*\\)?)\\)
|
||||
suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(>=0\\.\\(2[0-4]\\|1[0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*\\)?)\\)? #[0-9]+
|
||||
suppress_comment=\\(.\\|\n\\)*\\$FlowFixedInNextDeploy
|
||||
|
||||
[version]
|
||||
^0.26.0
|
||||
+9
-1
@@ -68,7 +68,14 @@ script:
|
||||
fi
|
||||
elif [ "$TEST_TYPE" = test ]; then
|
||||
set -e
|
||||
./node_modules/.bin/grunt jest:normal
|
||||
# Disabling coverage because it's broken:
|
||||
# https://travis-ci.org/facebook/react/jobs/128163922
|
||||
if false; then
|
||||
./node_modules/.bin/grunt jest:coverage
|
||||
cat ./coverage/lcov.info | ./node_modules/.bin/coveralls
|
||||
else
|
||||
./node_modules/.bin/grunt jest:normal
|
||||
fi
|
||||
echo 'Testing in server-render (HTML generation) mode...'
|
||||
printf '\nmodule.exports.useCreateElement = false;\n' \
|
||||
>> src/renderers/dom/shared/ReactDOMFeatureFlags.js
|
||||
@@ -83,6 +90,7 @@ env:
|
||||
- TEST_TYPE=build
|
||||
- TEST_TYPE=test
|
||||
- TEST_TYPE=lint
|
||||
- TEST_TYPE=flow
|
||||
- TEST_TYPE=build_website
|
||||
global:
|
||||
# SERVER
|
||||
|
||||
+44
-2
@@ -1,3 +1,45 @@
|
||||
/## 15.2.0 (July 1, 2016)
|
||||
|
||||
### React
|
||||
- Add error codes to production invariants, with links to the view the full error text. ([@keyanzhang](https://github.com/keyanzhang) in [#6948](https://github.com/facebook/react/pull/6948))
|
||||
- Include component stack information in PropType validation warnings. ([@spicyj](https://github.com/spicyj) in [#6771](https://github.com/facebook/react/pull/6771))
|
||||
- Include component stack information in key warnings. ([@keyanzhang](https://github.com/keyanzhang) in [#6799](https://github.com/facebook/react/pull/6799))
|
||||
- Stop validating props at mount time, only validate at element creation. ([@keyanzhang](https://github.com/keyanzhang) in [#6823](https://github.com/facebook/react/pull/6823))
|
||||
- New invariant providing actionable error in missing instance case. ([@yungsters](https://github.com/yungsters) in [#6990](https://github.com/facebook/react/pull/6990))
|
||||
- Add `React.PropTypes.symbol` to support ES2015 Symbols as props. ([@puradox](https://github.com/puradox) in [#6377](https://github.com/facebook/react/pull/6377))
|
||||
- Fix incorrect coercion of ref or key that are undefined in development ([@gaearon](https://github.com/gaearon) in [#6880](https://github.com/facebook/react/pull/6880))
|
||||
- Fix a false positive when passing other element’s props to cloneElement ([@ericmatthys](https://github.com/ericmatthys) in [#6268](https://github.com/facebook/react/pull/6268))
|
||||
|
||||
### React DOM
|
||||
- Add warning for unknown properties on DOM elements. ([@jimfb](https://github.com/jimfb) in [#6800](https://github.com/facebook/react/pull/6800), [@gm758](https://github.com/gm758) in [#7152](https://github.com/facebook/react/pull/7152))
|
||||
- Properly remove attributes from custom elements. ([@grassator](https://github.com/grassator) in [#6748](https://github.com/facebook/react/pull/6748))
|
||||
- Fix invalid unicode escape in attribute name regular expression. ([@nbjahan](https://github.com/nbjahan) in [#6772](https://github.com/facebook/react/pull/6772))
|
||||
- Add `onLoad` handling to `<link>` element. ([@roderickhsiao](https://github.com/roderickhsiao) in [#6815](https://github.com/facebook/react/pull/6815))
|
||||
- Add `onError` handling to `<source>` element. ([@wadahiro](https://github.com/wadahiro) in [#6941](https://github.com/facebook/react/pull/6941))
|
||||
- Handle `value` and `defaultValue` more accurately in the DOM. ([@jimfb](https://github.com/jimfb) in [#6406](https://github.com/facebook/react/pull/6406))
|
||||
- Fix events issue in environments with mutated `Object.prototype`. ([@Weizenlol](https://github.com/Weizenlol) in [#6886](https://github.com/facebook/react/pull/6886))
|
||||
- Fix issue where `is="null"` ended up in the DOM in Firefox. ([@darobin](https://github.com/darobin) in [#6896](https://github.com/facebook/react/pull/6896))
|
||||
- Improved performance of text escaping by using [escape-html](https://github.com/component/escape-html). ([@aickin](https://github.com/aickin) in [#6862](https://github.com/facebook/react/pull/6862))
|
||||
- Fix issue with `dangerouslySetInnerHTML` and SVG in Internet Explorer. ([@joshhunt](https://github.com/joshhunt) in [#6982](https://github.com/facebook/react/pull/6982))
|
||||
- Fix issue with `<textarea>` placeholders. ([@jimfb](https://github.com/jimfb) in [#7002](https://github.com/facebook/react/pull/7002))
|
||||
- Fix controlled vs uncontrolled detection of `<input type="radio"/>`. ([@jimfb](https://github.com/jimfb) in [#7003](https://github.com/facebook/react/pull/7003))
|
||||
- Improve performance of updating text content. ([@trueadm](https://github.com/trueadm) in [#7005](https://github.com/facebook/react/pull/7005))
|
||||
- Ensure controlled `<select>` components behave the same on initial render as they do on updates. ([@yiminghe](https://github.com/yiminghe) in [#5362](https://github.com/facebook/react/pull/5362))
|
||||
|
||||
### React Perf Add-on
|
||||
- Add `isRunning()` API. ([@nfcampos](https://github.com/nfcampos) in [#6763](https://github.com/facebook/react/pull/6763))
|
||||
- Improve accuracy of lifecycle hook timing. ([@gaearon](https://github.com/gaearon) in [#6858](https://github.com/facebook/react/pull/6858))
|
||||
- Fix internal errors when using ReactPerf with portal components. ([@gaearon](https://github.com/gaearon) in [#6860](https://github.com/facebook/react/pull/6860))
|
||||
- Fix performance regression. ([@spicyj](https://github.com/spicyj) in [#6770](https://github.com/facebook/react/pull/6770))
|
||||
- Add warning that ReactPerf is not enabled in production. ([@sashashakun](https://github.com/sashashakun) in [#6884](https://github.com/facebook/react/pull/6884))
|
||||
|
||||
### React CSSTransitionGroup Add-on
|
||||
- Fix timing issue with `null` node. ([@keyanzhang](https://github.com/keyanzhang) in [#6958](https://github.com/facebook/react/pull/6958))
|
||||
|
||||
### React Native Renderer
|
||||
- Dependencies on React Native modules use CommonJS requires instead of providesModule. ([@davidaurelio](https://github.com/davidaurelio) in [#6715](https://github.com/facebook/react/pull/6715))
|
||||
|
||||
|
||||
## 15.1.0 (May 20, 2016)
|
||||
|
||||
### React
|
||||
@@ -874,14 +916,14 @@ Each of these changes will continue to work as before with a new warning until t
|
||||
|
||||
* Upgrade Commoner so `require` statements are no longer relativized when passing through the transformer. This was a feature needed when building React, but doesn't translate well for other consumers of `bin/jsx`.
|
||||
* Upgraded our dependencies on Commoner and Recast so they use a different directory for their cache.
|
||||
* Freeze our esprima dependency.
|
||||
* Freeze our Esprima dependency.
|
||||
|
||||
|
||||
## 0.3.2 (May 31, 2013)
|
||||
|
||||
### JSX
|
||||
|
||||
* Improved compatability with other coding styles (specifically, multiple assignments with a single `var`).
|
||||
* Improved compatibility with other coding styles (specifically, multiple assignments with a single `var`).
|
||||
|
||||
### react-tools
|
||||
|
||||
|
||||
@@ -56,6 +56,8 @@ module.exports = function(grunt) {
|
||||
|
||||
grunt.registerTask('lint', ['eslint']);
|
||||
|
||||
grunt.registerTask('flow', require('./grunt/tasks/flow'));
|
||||
|
||||
grunt.registerTask('delete-build-modules', function() {
|
||||
// Use gulp here.
|
||||
spawnGulp(['react:clean'], null, this.async());
|
||||
|
||||
@@ -2,11 +2,9 @@
|
||||
|
||||
React is a JavaScript library for building user interfaces.
|
||||
|
||||
* **Just the UI:** Lots of people use React as the V in MVC. Since React makes no assumptions about the rest of your technology stack, it's easy to try it out on a small feature in an existing project.
|
||||
* **Virtual DOM:** React abstracts away the DOM from you, giving a simpler programming model and better performance. React can also render on the server using Node, and it can power native apps using [React Native](https://facebook.github.io/react-native/).
|
||||
* **Data flow:** React implements one-way reactive data flow which reduces boilerplate and is easier to reason about than traditional data binding.
|
||||
|
||||
**NEW**! Check out our newest project [React Native](https://github.com/facebook/react-native), which uses React and JavaScript to create native mobile apps.
|
||||
* **Declarative:** React makes it painless to create interactive UIs. Design simple views for each state in your application, and React will efficiently update and render just the right components when your data changes. Declarative views make your code more predictable, simpler to understand, and easier to debug.
|
||||
* **Component-Based:** Build encapsulated components that manage their own state, then compose them to make complex UIs. Since component logic is written in JavaScript instead of templates, you can easily pass rich data through your app and keep state out of the DOM.
|
||||
* **Learn Once, Write Anywhere:** We don't make assumptions about the rest of your technology stack, so you can develop new features in React without rewriting existing code. React can also render on the server using Node and power mobile apps using [React Native](https://facebook.github.io/react-native/).
|
||||
|
||||
[Learn how to use React in your own project](https://facebook.github.io/react/docs/getting-started.html).
|
||||
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Copyright (c) 2015-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.
|
||||
*
|
||||
* @flow
|
||||
*/
|
||||
|
||||
/* eslint-disable */
|
||||
|
||||
declare var __REACT_DEVTOOLS_GLOBAL_HOOK__: any; /*?{
|
||||
inject: ?((stuff: Object) => void)
|
||||
};*/
|
||||
|
||||
// temporary patches for React.Component and React.Element
|
||||
declare var ReactComponent: typeof React$Component;
|
||||
declare var ReactElement: typeof React$Element;
|
||||
Vendored
+44
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* Copyright (c) 2015-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.
|
||||
*
|
||||
* @flow
|
||||
*/
|
||||
|
||||
/* eslint-disable */
|
||||
|
||||
declare module 'deepDiffer' {
|
||||
declare function exports(one: any, two: any): bool;
|
||||
}
|
||||
declare module 'deepFreezeAndThrowOnMutationInDev' {
|
||||
declare function exports<T>(obj : T) : T;
|
||||
}
|
||||
declare module 'flattenStyle' { }
|
||||
declare module 'InitializeJavaScriptAppEngine' { }
|
||||
declare module 'RCTEventEmitter' {
|
||||
declare function register() : void;
|
||||
}
|
||||
declare module 'TextInputState' {
|
||||
declare function blurTextInput(object : any) : void;
|
||||
declare function focusTextInput(object : any) : void;
|
||||
}
|
||||
declare module 'UIManager' {
|
||||
declare var customBubblingEventTypes : Object;
|
||||
declare var customDirectEventTypes : Object;
|
||||
declare function createView() : void;
|
||||
declare function manageChildren() : void;
|
||||
declare function measure() : void;
|
||||
declare function measureInWindow() : void;
|
||||
declare function measureLayout() : void;
|
||||
declare function removeRootView() : void;
|
||||
declare function removeSubviewsFromContainerWithID() : void;
|
||||
declare function replaceExistingNonRootView() : void;
|
||||
declare function setChildren() : void;
|
||||
declare function setChildren() : void;
|
||||
declare function updateView() : void;
|
||||
}
|
||||
declare module 'View' { }
|
||||
@@ -0,0 +1,22 @@
|
||||
'use strict';
|
||||
|
||||
var grunt = require('grunt');
|
||||
|
||||
var extension = process.platform === 'win32' ? '.cmd': '';
|
||||
|
||||
module.exports = function() {
|
||||
var done = this.async();
|
||||
grunt.util.spawn({
|
||||
cmd: 'node_modules/.bin/flow' + extension,
|
||||
args: ['check', '.'],
|
||||
opts: {stdio: 'inherit'},
|
||||
}, function(err, result, code) {
|
||||
if (err) {
|
||||
grunt.log.error('Flow failed');
|
||||
} else {
|
||||
grunt.log.ok('Flow passed');
|
||||
}
|
||||
|
||||
done(code === 0);
|
||||
});
|
||||
};
|
||||
+13
-9
@@ -1,9 +1,3 @@
|
||||
// We run our own grunt task instead of using grunt-jest so that we can have
|
||||
// more control. Specifically we want to set NODE_ENV and make sure stdio is
|
||||
// inherited. We also run with --harmony directly so that we don't have to
|
||||
// respawn immediately. We should be able to reduce some of this complexity
|
||||
// when jest 0.5 is run on top of iojs.
|
||||
|
||||
'use strict';
|
||||
|
||||
var async = require('async');
|
||||
@@ -52,6 +46,7 @@ function getJestConfig(callback) {
|
||||
getCollectCoverageOnlyFrom(function(err, data) {
|
||||
callback(err, Object.assign({}, config, {
|
||||
rootDir: rootDir,
|
||||
name: 'react',
|
||||
collectCoverage: true,
|
||||
collectCoverageOnlyFrom: data,
|
||||
}));
|
||||
@@ -75,16 +70,25 @@ function writeTempConfig(callback) {
|
||||
}
|
||||
|
||||
function run(done, configPath) {
|
||||
grunt.log.writeln('running jest (this may take a while)');
|
||||
grunt.log.writeln('running jest');
|
||||
|
||||
var args = ['--harmony', path.join('node_modules', 'jest-cli', 'bin', 'jest'), '--runInBand'];
|
||||
var args = [
|
||||
path.join('node_modules', 'jest', 'bin', 'jest'),
|
||||
'--runInBand',
|
||||
'--no-watchman',
|
||||
];
|
||||
if (configPath) {
|
||||
args.push('--config', configPath);
|
||||
}
|
||||
grunt.util.spawn({
|
||||
cmd: 'node',
|
||||
args: args,
|
||||
opts: { stdio: 'inherit', env: { NODE_ENV: 'test' } },
|
||||
opts: {
|
||||
stdio: 'inherit',
|
||||
env: Object.assign({}, process.env, {
|
||||
NODE_ENV: 'test',
|
||||
}),
|
||||
},
|
||||
}, function(spawnErr, result, code) {
|
||||
if (spawnErr) {
|
||||
onError(spawnErr);
|
||||
|
||||
+19
-21
@@ -16,6 +16,7 @@ var del = require('del');
|
||||
|
||||
var babelPluginModules = require('fbjs-scripts/babel-6/rewrite-modules');
|
||||
var extractErrors = require('./scripts/error-codes/gulp-extract-errors');
|
||||
var devExpressionWithCodes = require('./scripts/error-codes/dev-expression-with-codes');
|
||||
|
||||
var paths = {
|
||||
react: {
|
||||
@@ -24,33 +25,29 @@ var paths = {
|
||||
'!src/**/__benchmarks__/**/*.js',
|
||||
'!src/**/__tests__/**/*.js',
|
||||
'!src/**/__mocks__/**/*.js',
|
||||
'!src/renderers/art/**/*.js',
|
||||
'!src/renderers/shared/fiber/**/*.js',
|
||||
'!src/shared/vendor/**/*.js',
|
||||
],
|
||||
lib: 'build/modules',
|
||||
},
|
||||
};
|
||||
|
||||
var fbjsModuleMap = require('fbjs/module-map');
|
||||
var moduleMap = {};
|
||||
for (var key in fbjsModuleMap) {
|
||||
moduleMap[key] = fbjsModuleMap[key];
|
||||
}
|
||||
var whiteListNames = [
|
||||
'deepDiffer',
|
||||
'deepFreezeAndThrowOnMutationInDev',
|
||||
'flattenStyle',
|
||||
'InitializeJavaScriptAppEngine',
|
||||
'RCTEventEmitter',
|
||||
'TextInputState',
|
||||
'UIManager',
|
||||
'View',
|
||||
];
|
||||
|
||||
whiteListNames.forEach(function(name) {
|
||||
moduleMap[name] = name;
|
||||
});
|
||||
|
||||
moduleMap['object-assign'] = 'object-assign';
|
||||
var moduleMap = Object.assign(
|
||||
{'object-assign': 'object-assign'},
|
||||
require('fbjs/module-map'),
|
||||
{
|
||||
deepDiffer: 'react-native/lib/deepDiffer',
|
||||
deepFreezeAndThrowOnMutationInDev: 'react-native/lib/deepFreezeAndThrowOnMutationInDev',
|
||||
flattenStyle: 'react-native/lib/flattenStyle',
|
||||
InitializeJavaScriptAppEngine: 'react-native/lib/InitializeJavaScriptAppEngine',
|
||||
RCTEventEmitter: 'react-native/lib/RCTEventEmitter',
|
||||
TextInputState: 'react-native/lib/TextInputState',
|
||||
UIManager: 'react-native/lib/UIManager',
|
||||
UIManagerStatTracker: 'react-native/lib/UIManagerStatTracker',
|
||||
View: 'react-native/lib/View',
|
||||
}
|
||||
);
|
||||
|
||||
var errorCodeOpts = {
|
||||
errorMapFilePath: 'scripts/error-codes/codes.json',
|
||||
@@ -58,6 +55,7 @@ var errorCodeOpts = {
|
||||
|
||||
var babelOpts = {
|
||||
plugins: [
|
||||
devExpressionWithCodes, // this pass has to run before `rewrite-modules`
|
||||
[babelPluginModules, {map: moduleMap}],
|
||||
],
|
||||
};
|
||||
|
||||
Generated
+6033
-6623
File diff suppressed because it is too large.
Load diff
+11
-7
@@ -1,8 +1,9 @@
|
||||
{
|
||||
"name": "react-build",
|
||||
"private": true,
|
||||
"version": "15.1.0",
|
||||
"version": "15.2.0-rc.2",
|
||||
"devDependencies": {
|
||||
"art": "^0.10.1",
|
||||
"async": "^1.5.0",
|
||||
"babel-cli": "^6.6.5",
|
||||
"babel-core": "^6.0.0",
|
||||
@@ -26,20 +27,23 @@
|
||||
"babel-plugin-transform-es3-member-expression-literals": "^6.5.0",
|
||||
"babel-plugin-transform-es3-property-literals": "^6.5.0",
|
||||
"babel-plugin-transform-object-rest-spread": "^6.6.5",
|
||||
"babel-plugin-transform-react-jsx-source": "^6.8.0",
|
||||
"babel-preset-react": "^6.5.0",
|
||||
"babel-traverse": "^6.9.0",
|
||||
"babylon": "^6.8.0",
|
||||
"babylon": "6.8.0",
|
||||
"browserify": "^13.0.0",
|
||||
"bundle-collapser": "^1.1.1",
|
||||
"coffee-script": "^1.8.0",
|
||||
"core-js": "^2.2.1",
|
||||
"coveralls": "^2.11.6",
|
||||
"del": "^2.0.2",
|
||||
"derequire": "^2.0.3",
|
||||
"eslint": "1.10.3",
|
||||
"eslint-plugin-react": "4.1.0",
|
||||
"eslint-plugin-react-internal": "file:eslint-rules",
|
||||
"fbjs": "^0.8.0",
|
||||
"fbjs": "^0.8.1",
|
||||
"fbjs-scripts": "^0.6.0",
|
||||
"flow-bin": "^0.26.0",
|
||||
"glob": "^6.0.1",
|
||||
"grunt": "^0.4.5",
|
||||
"grunt-cli": "^0.1.13",
|
||||
@@ -51,19 +55,19 @@
|
||||
"gulp-flatten": "^0.2.0",
|
||||
"gulp-util": "^3.0.7",
|
||||
"gzip-js": "~0.3.2",
|
||||
"jest-cli": "^12.0.2",
|
||||
"jest": "^12.1.1",
|
||||
"loose-envify": "^1.1.0",
|
||||
"object-assign": "^4.1.0",
|
||||
"platform": "^1.1.0",
|
||||
"run-sequence": "^1.1.4",
|
||||
"through2": "^2.0.0",
|
||||
"tmp": "~0.0.28",
|
||||
"typescript": "~1.4.0",
|
||||
"typescript": "~1.8.10",
|
||||
"uglify-js": "^2.5.0",
|
||||
"uglifyify": "^3.0.1"
|
||||
},
|
||||
"devEngines": {
|
||||
"node": "4.x || 5.x",
|
||||
"node": "4.x || 5.x || 6.x",
|
||||
"npm": "2.x || 3.x"
|
||||
},
|
||||
"commonerConfig": {
|
||||
@@ -86,7 +90,6 @@
|
||||
"scriptPreprocessor": "scripts/jest/preprocessor.js",
|
||||
"setupEnvScriptFile": "scripts/jest/environment.js",
|
||||
"setupTestFrameworkScriptFile": "scripts/jest/test-framework-setup.js",
|
||||
"testRunner": "jasmine1",
|
||||
"testFileExtensions": [
|
||||
"coffee",
|
||||
"js",
|
||||
@@ -95,6 +98,7 @@
|
||||
"testPathDirs": [
|
||||
"<rootDir>/eslint-rules",
|
||||
"<rootDir>/mocks",
|
||||
"<rootDir>/scripts",
|
||||
"<rootDir>/src",
|
||||
"node_modules/fbjs"
|
||||
],
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "react-addons-template",
|
||||
"version": "15.1.0",
|
||||
"version": "15.2.0-rc.2",
|
||||
"main": "index.js",
|
||||
"repository": "facebook/react",
|
||||
"keywords": [
|
||||
@@ -10,6 +10,6 @@
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {},
|
||||
"peerDependencies": {
|
||||
"react": "^15.1.0"
|
||||
"react": "^15.2.0-rc.2"
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "react-dom",
|
||||
"version": "15.1.0",
|
||||
"version": "15.2.0-rc.2",
|
||||
"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.1.0"
|
||||
"react": "^15.2.0-rc.2"
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "react-native-renderer",
|
||||
"version": "15.1.0",
|
||||
"version": "15.2.0-rc.2",
|
||||
"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.1.0"
|
||||
"react": "^15.2.0-rc.2"
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "react",
|
||||
"description": "React is a JavaScript library for building user interfaces.",
|
||||
"version": "15.1.0",
|
||||
"version": "15.2.0-rc.2",
|
||||
"keywords": [
|
||||
"react"
|
||||
],
|
||||
@@ -23,7 +23,7 @@
|
||||
"node": ">=0.10.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"fbjs": "^0.8.0",
|
||||
"fbjs": "^0.8.1",
|
||||
"loose-envify": "^1.1.0",
|
||||
"object-assign": "^4.1.0"
|
||||
},
|
||||
|
||||
@@ -112,7 +112,7 @@ function print(outerComponent) {
|
||||
var values = keys.map((childKey) => renderedChildren[childKey]);
|
||||
|
||||
if (keys.length) {
|
||||
function dump(children) {
|
||||
var dump = function(children) {
|
||||
if (typeof children === 'boolean' || children == null) {
|
||||
return '' + children;
|
||||
}
|
||||
@@ -130,7 +130,7 @@ function print(outerComponent) {
|
||||
debugger;
|
||||
throw new Error('hmm');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
markup += '\n';
|
||||
var children = element.props.children;
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
/**
|
||||
* Copyright (c) 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.
|
||||
*/
|
||||
/* eslint-disable quotes */
|
||||
'use strict';
|
||||
|
||||
let babel = require('babel-core');
|
||||
let devExpressionWithCodes = require('../dev-expression-with-codes');
|
||||
|
||||
function transform(input) {
|
||||
return babel.transform(input, {
|
||||
plugins: [devExpressionWithCodes],
|
||||
}).code;
|
||||
}
|
||||
|
||||
function compare(input, output) {
|
||||
var compiled = transform(input);
|
||||
expect(compiled).toEqual(output);
|
||||
}
|
||||
|
||||
var oldEnv;
|
||||
|
||||
describe('dev-expression', function() {
|
||||
beforeEach(() => {
|
||||
oldEnv = process.env.NODE_ENV;
|
||||
process.env.NODE_ENV = '';
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.env.NODE_ENV = oldEnv;
|
||||
});
|
||||
|
||||
it('should replace __DEV__ in if', () => {
|
||||
compare(
|
||||
`
|
||||
if (__DEV__) {
|
||||
console.log('foo')
|
||||
}`,
|
||||
`
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
console.log('foo');
|
||||
}`
|
||||
);
|
||||
});
|
||||
|
||||
it('should replace warning calls', () => {
|
||||
compare(
|
||||
"warning(condition, 'a %s b', 'c');",
|
||||
"process.env.NODE_ENV !== 'production' ? warning(condition, 'a %s b', 'c') : void 0;"
|
||||
);
|
||||
});
|
||||
|
||||
it("should add `reactProdInvariant` when it finds `require('invariant')`", () => {
|
||||
compare(
|
||||
"var invariant = require('invariant');",
|
||||
|
||||
`var _prodInvariant = require('reactProdInvariant');
|
||||
|
||||
var invariant = require('invariant');`
|
||||
);
|
||||
});
|
||||
|
||||
it('should replace simple invariant calls', () => {
|
||||
compare(
|
||||
"invariant(condition, 'Do not override existing functions.');",
|
||||
"var _prodInvariant = require('reactProdInvariant');\n\n" +
|
||||
"!condition ? " +
|
||||
"process.env.NODE_ENV !== 'production' ? " +
|
||||
"invariant(false, 'Do not override existing functions.') : " +
|
||||
`_prodInvariant('16') : void 0;`
|
||||
);
|
||||
});
|
||||
|
||||
it("should only add `reactProdInvariant` once", () => {
|
||||
var expectedInvariantTransformResult = (
|
||||
"!condition ? " +
|
||||
"process.env.NODE_ENV !== 'production' ? " +
|
||||
"invariant(false, 'Do not override existing functions.') : " +
|
||||
`_prodInvariant('16') : void 0;`
|
||||
);
|
||||
|
||||
compare(
|
||||
`var invariant = require('invariant');
|
||||
invariant(condition, 'Do not override existing functions.');
|
||||
invariant(condition, 'Do not override existing functions.');`,
|
||||
|
||||
`var _prodInvariant = require('reactProdInvariant');
|
||||
|
||||
var invariant = require('invariant');
|
||||
${expectedInvariantTransformResult}
|
||||
${expectedInvariantTransformResult}`
|
||||
);
|
||||
});
|
||||
|
||||
it('should support invariant calls with args', () => {
|
||||
compare(
|
||||
"invariant(condition, 'Expected %s target to be an array; got %s', 'foo', 'bar');",
|
||||
"var _prodInvariant = require('reactProdInvariant');\n\n" +
|
||||
"!condition ? " +
|
||||
"process.env.NODE_ENV !== 'production' ? " +
|
||||
"invariant(false, 'Expected %s target to be an array; got %s', 'foo', 'bar') : " +
|
||||
`_prodInvariant('7', 'foo', 'bar') : void 0;`
|
||||
);
|
||||
});
|
||||
|
||||
it('should support invariant calls with a concatenated template string and args', () => {
|
||||
compare(
|
||||
"invariant(condition, 'Expected a component class, ' + 'got %s.' + '%s', 'Foo', 'Bar');",
|
||||
"var _prodInvariant = require('reactProdInvariant');\n\n" +
|
||||
"!condition ? " +
|
||||
"process.env.NODE_ENV !== 'production' ? " +
|
||||
"invariant(false, 'Expected a component class, got %s.%s', 'Foo', 'Bar') : " +
|
||||
`_prodInvariant('18', 'Foo', 'Bar') : void 0;`
|
||||
);
|
||||
});
|
||||
|
||||
it('should warn in non-test envs if the error message cannot be found', () => {
|
||||
spyOn(console, 'warn');
|
||||
transform("invariant(condition, 'a %s b', 'c');");
|
||||
|
||||
expect(console.warn.calls.count()).toBe(1);
|
||||
expect(console.warn.calls.argsFor(0)[0]).toBe(
|
||||
'Error message "a %s b" ' +
|
||||
'cannot be found. The current React version ' +
|
||||
'and the error map are probably out of sync. ' +
|
||||
'Please run `gulp react:extract-errors` before building React.'
|
||||
);
|
||||
});
|
||||
|
||||
it('should not warn in test env if the error message cannot be found', () => {
|
||||
process.env.NODE_ENV = 'test';
|
||||
|
||||
spyOn(console, 'warn');
|
||||
transform("invariant(condition, 'a %s b', 'c');");
|
||||
|
||||
expect(console.warn.calls.count()).toBe(0);
|
||||
|
||||
process.env.NODE_ENV = '';
|
||||
});
|
||||
});
|
||||
@@ -134,5 +134,6 @@
|
||||
"132": "Ended a touch event which was not counted in trackedTouchCount.",
|
||||
"133": "Touch object is missing identifier",
|
||||
"134": "Touch data should have been recorded on start",
|
||||
"135": "Cannot find single active touch"
|
||||
"135": "Cannot find single active touch",
|
||||
"136": "Attempted to update component `%s` that has already been unmounted (or failed to mount)."
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
/**
|
||||
* Copyright (c) 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.
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
var evalToString = require('./evalToString');
|
||||
var existingErrorMap = require('./codes.json');
|
||||
var invertObject = require('./invertObject');
|
||||
|
||||
var errorMap = invertObject(existingErrorMap);
|
||||
|
||||
module.exports = function(babel) {
|
||||
var t = babel.types;
|
||||
|
||||
var SEEN_SYMBOL = Symbol('dev-expression-with-codes.seen');
|
||||
|
||||
// Generate a hygienic identifier
|
||||
function getProdInvariantIdentifier(path, localState) {
|
||||
if (!localState.prodInvariantIdentifier) {
|
||||
localState.prodInvariantIdentifier = path.scope.generateUidIdentifier('prodInvariant');
|
||||
path.scope.getProgramParent().push({
|
||||
id: localState.prodInvariantIdentifier,
|
||||
init: t.callExpression(
|
||||
t.identifier('require'),
|
||||
[t.stringLiteral('reactProdInvariant')]
|
||||
),
|
||||
});
|
||||
}
|
||||
return localState.prodInvariantIdentifier;
|
||||
}
|
||||
|
||||
var DEV_EXPRESSION = t.binaryExpression(
|
||||
'!==',
|
||||
t.memberExpression(
|
||||
t.memberExpression(
|
||||
t.identifier('process'),
|
||||
t.identifier('env'),
|
||||
false
|
||||
),
|
||||
t.identifier('NODE_ENV'),
|
||||
false
|
||||
),
|
||||
t.stringLiteral('production')
|
||||
);
|
||||
|
||||
return {
|
||||
pre: function() {
|
||||
this.prodInvariantIdentifier = null;
|
||||
},
|
||||
|
||||
visitor: {
|
||||
Identifier: {
|
||||
enter: function(path) {
|
||||
// Do nothing when testing
|
||||
if (process.env.NODE_ENV === 'test') {
|
||||
return;
|
||||
}
|
||||
// Replace __DEV__ with process.env.NODE_ENV !== 'production'
|
||||
if (path.isIdentifier({name: '__DEV__'})) {
|
||||
path.replaceWith(DEV_EXPRESSION);
|
||||
}
|
||||
},
|
||||
},
|
||||
CallExpression: {
|
||||
exit: function(path) {
|
||||
var node = path.node;
|
||||
// Ignore if it's already been processed
|
||||
if (node[SEEN_SYMBOL]) {
|
||||
return;
|
||||
}
|
||||
// Insert `var PROD_INVARIANT = require('reactProdInvariant');`
|
||||
// before all `require('invariant')`s.
|
||||
// NOTE it doesn't support ES6 imports yet.
|
||||
if (
|
||||
path.get('callee').isIdentifier({name: 'require'}) &&
|
||||
path.get('arguments')[0] &&
|
||||
path.get('arguments')[0].isStringLiteral({value: 'invariant'})
|
||||
) {
|
||||
node[SEEN_SYMBOL] = true;
|
||||
getProdInvariantIdentifier(path, this);
|
||||
} else if (path.get('callee').isIdentifier({name: 'invariant'})) {
|
||||
// Turns this code:
|
||||
//
|
||||
// invariant(condition, argument, 'foo', 'bar');
|
||||
//
|
||||
// into this:
|
||||
//
|
||||
// if (!condition) {
|
||||
// if ("production" !== process.env.NODE_ENV) {
|
||||
// invariant(false, argument, 'foo', 'bar');
|
||||
// } else {
|
||||
// PROD_INVARIANT('XYZ', 'foo', 'bar');
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// where
|
||||
// - `XYZ` is an error code: a unique identifier (a number string)
|
||||
// that references a verbose error message.
|
||||
// The mapping is stored in `scripts/error-codes/codes.json`.
|
||||
// - `PROD_INVARIANT` is the `reactProdInvariant` function that always throws with an error URL like
|
||||
// http://facebook.github.io/react/docs/error-decoder.html?invariant=XYZ&args[]=foo&args[]=bar
|
||||
//
|
||||
// Specifically this does 3 things:
|
||||
// 1. Checks the condition first, preventing an extra function call.
|
||||
// 2. Adds an environment check so that verbose error messages aren't
|
||||
// shipped to production.
|
||||
// 3. Rewrites the call to `invariant` in production to `reactProdInvariant`
|
||||
// - `reactProdInvariant` is always renamed to avoid shadowing
|
||||
// The generated code is longer than the original code but will dead
|
||||
// code removal in a minifier will strip that out.
|
||||
var condition = node.arguments[0];
|
||||
var errorMsgLiteral = evalToString(node.arguments[1]);
|
||||
|
||||
var prodErrorId = errorMap[errorMsgLiteral];
|
||||
if (prodErrorId === undefined) {
|
||||
// The error cannot be found in the map.
|
||||
node[SEEN_SYMBOL] = true;
|
||||
if (process.env.NODE_ENV !== 'test') {
|
||||
console.warn(
|
||||
'Error message "' + errorMsgLiteral +
|
||||
'" cannot be found. The current React version ' +
|
||||
'and the error map are probably out of sync. ' +
|
||||
'Please run `gulp react:extract-errors` before building React.'
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
var devInvariant = t.callExpression(node.callee, [
|
||||
t.booleanLiteral(false),
|
||||
t.stringLiteral(errorMsgLiteral),
|
||||
].concat(node.arguments.slice(2)));
|
||||
|
||||
devInvariant[SEEN_SYMBOL] = true;
|
||||
|
||||
var localInvariantId = getProdInvariantIdentifier(path, this);
|
||||
var prodInvariant = t.callExpression(localInvariantId, [
|
||||
t.stringLiteral(prodErrorId),
|
||||
].concat(node.arguments.slice(2)));
|
||||
|
||||
prodInvariant[SEEN_SYMBOL] = true;
|
||||
path.replaceWith(t.ifStatement(
|
||||
t.unaryExpression('!', condition),
|
||||
t.blockStatement([
|
||||
t.ifStatement(
|
||||
DEV_EXPRESSION,
|
||||
t.blockStatement([
|
||||
t.expressionStatement(devInvariant),
|
||||
]),
|
||||
t.blockStatement([
|
||||
t.expressionStatement(prodInvariant),
|
||||
])
|
||||
),
|
||||
])
|
||||
));
|
||||
} else if (path.get('callee').isIdentifier({name: 'warning'})) {
|
||||
// Turns this code:
|
||||
//
|
||||
// warning(condition, argument, argument);
|
||||
//
|
||||
// into this:
|
||||
//
|
||||
// if ("production" !== process.env.NODE_ENV) {
|
||||
// warning(condition, argument, argument);
|
||||
// }
|
||||
//
|
||||
// The goal is to strip out warning calls entirely in production. We
|
||||
// don't need the same optimizations for conditions that we use for
|
||||
// invariant because we don't care about an extra call in __DEV__
|
||||
|
||||
node[SEEN_SYMBOL] = true;
|
||||
path.replaceWith(t.ifStatement(
|
||||
DEV_EXPRESSION,
|
||||
t.blockStatement([
|
||||
t.expressionStatement(
|
||||
node
|
||||
),
|
||||
])
|
||||
));
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
Vendored
+1
@@ -17,6 +17,7 @@ declare function xit(name: string, fn: any): void;
|
||||
interface Expect {
|
||||
not: Expect
|
||||
toThrow(message?: string): void
|
||||
toThrowError(message?: string): void
|
||||
toBe(value: any): void
|
||||
toEqual(value: any): void
|
||||
toBeFalsy(): void
|
||||
|
||||
@@ -20,13 +20,14 @@ var createCacheKeyFunction = require('fbjs-scripts/jest/createCacheKeyFunction')
|
||||
// Use require.resolve to be resilient to file moves, npm updates, etc
|
||||
var pathToBabel = path.join(require.resolve('babel-core'), '..', 'package.json');
|
||||
var pathToModuleMap = require.resolve('fbjs/module-map');
|
||||
var pathToBabelPluginDev = require.resolve('fbjs-scripts/babel-6/dev-expression');
|
||||
var pathToBabelPluginDevWithCode = require.resolve('../error-codes/dev-expression-with-codes');
|
||||
var pathToBabelPluginModules = require.resolve('fbjs-scripts/babel-6/rewrite-modules');
|
||||
var pathToBabelrc = path.join(__dirname, '..', '..', '.babelrc');
|
||||
|
||||
// TODO: make sure this stays in sync with gulpfile
|
||||
var babelOptions = {
|
||||
plugins: [
|
||||
pathToBabelPluginDevWithCode, // this pass has to run before `rewrite-modules`
|
||||
[babelPluginModules, {
|
||||
map: Object.assign(
|
||||
{},
|
||||
@@ -54,7 +55,10 @@ module.exports = {
|
||||
) {
|
||||
return babel.transform(
|
||||
src,
|
||||
Object.assign({filename: filePath}, babelOptions)
|
||||
Object.assign(
|
||||
{filename: path.relative(process.cwd(), filePath)},
|
||||
babelOptions
|
||||
)
|
||||
).code;
|
||||
}
|
||||
return src;
|
||||
@@ -65,7 +69,7 @@ module.exports = {
|
||||
pathToBabel,
|
||||
pathToBabelrc,
|
||||
pathToModuleMap,
|
||||
pathToBabelPluginDev,
|
||||
pathToBabelPluginDevWithCode,
|
||||
pathToBabelPluginModules,
|
||||
]),
|
||||
};
|
||||
@@ -2,34 +2,49 @@
|
||||
|
||||
var env = jasmine.getEnv();
|
||||
|
||||
var callCount = 0;
|
||||
var oldError = console.error;
|
||||
var newError = function() {
|
||||
callCount++;
|
||||
oldError.apply(this, arguments);
|
||||
var spec = env.currentSpec;
|
||||
if (spec) {
|
||||
var expectationResult = new jasmine.ExpectationResult({
|
||||
passed: false,
|
||||
message:
|
||||
'Expected test not to warn. If the warning is expected, mock it ' +
|
||||
'out using spyOn(console, \'error\'); and test that the warning ' +
|
||||
'occurs.',
|
||||
});
|
||||
spec.addMatcherResult(expectationResult);
|
||||
}
|
||||
};
|
||||
|
||||
console.error = newError;
|
||||
|
||||
// Make sure console.error is set back at the end of each test, or else the
|
||||
// above logic won't work
|
||||
afterEach(function() {
|
||||
// TODO: Catch test cases that call spyOn() but don't inspect the mock
|
||||
// properly.
|
||||
|
||||
if (console.error !== newError && !console.error.isSpy) {
|
||||
var expectationResult = new jasmine.ExpectationResult({
|
||||
passed: false,
|
||||
message: 'Test did not tear down console.error mock properly.',
|
||||
});
|
||||
env.currentSpec.addMatcherResult(expectationResult);
|
||||
}
|
||||
env.beforeEach(() => {
|
||||
callCount = 0;
|
||||
jasmine.addMatchers({
|
||||
toBeReset() {
|
||||
return {
|
||||
compare(actual) {
|
||||
// TODO: Catch test cases that call spyOn() but don't inspect the mock
|
||||
// properly.
|
||||
if (actual !== newError && !jasmine.isSpy(actual)) {
|
||||
return {
|
||||
pass: false,
|
||||
message: 'Test did not tear down console.error mock properly.',
|
||||
};
|
||||
}
|
||||
return {pass: true};
|
||||
},
|
||||
};
|
||||
},
|
||||
toNotHaveBeenCalled() {
|
||||
return {
|
||||
compare(actual) {
|
||||
return {
|
||||
pass: callCount === 0,
|
||||
message:
|
||||
'Expected test not to warn. If the warning is expected, mock ' +
|
||||
'it out using spyOn(console, \'error\'); and test that the ' +
|
||||
'warning occurs.',
|
||||
};
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
});
|
||||
env.afterEach(() => {
|
||||
expect(console.error).toBeReset();
|
||||
expect(console.error).toNotHaveBeenCalled();
|
||||
});
|
||||
@@ -4,12 +4,15 @@ var fs = require('fs');
|
||||
var path = require('path');
|
||||
var ts = require('typescript');
|
||||
|
||||
var tsOptions = {module: 'commonjs'};
|
||||
var tsOptions = {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
jsx: ts.JsxEmit.React,
|
||||
};
|
||||
|
||||
function formatErrorMessage(error) {
|
||||
return (
|
||||
error.file.filename + '(' +
|
||||
error.file.getLineAndCharacterFromPosition(error.start).line +
|
||||
error.file.getLineAndCharacterOfPosition(error.start).line +
|
||||
'): ' +
|
||||
error.messageText
|
||||
);
|
||||
@@ -18,7 +21,7 @@ function formatErrorMessage(error) {
|
||||
function compile(content, contentFilename) {
|
||||
var output = null;
|
||||
var compilerHost = {
|
||||
getSourceFile: function(filename, languageVersion) {
|
||||
getSourceFile(filename, languageVersion) {
|
||||
var source;
|
||||
|
||||
// `path.normalize` and `path.join` are used to turn forward slashes in
|
||||
@@ -28,11 +31,13 @@ function compile(content, contentFilename) {
|
||||
path.join('/', '(?:React|ReactDOM)(?:\.d)?\.ts$')
|
||||
);
|
||||
|
||||
var jestRegex = /jest\.d\.ts/;
|
||||
|
||||
if (filename === 'lib.d.ts') {
|
||||
source = fs.readFileSync(
|
||||
require.resolve('typescript/bin/lib.d.ts')
|
||||
require.resolve('typescript/lib/lib.d.ts')
|
||||
).toString();
|
||||
} else if (filename === 'jest.d.ts') {
|
||||
} else if (filename.match(jestRegex)) {
|
||||
source = fs.readFileSync(
|
||||
path.join(__dirname, 'jest.d.ts')
|
||||
).toString();
|
||||
@@ -55,34 +60,36 @@ function compile(content, contentFilename) {
|
||||
}
|
||||
return ts.createSourceFile(filename, source, 'ES5', '0');
|
||||
},
|
||||
writeFile: function(name, text, writeByteOrderMark) {
|
||||
writeFile(name, text, writeByteOrderMark) {
|
||||
if (output === null) {
|
||||
output = text;
|
||||
} else {
|
||||
throw new Error('Expected only one dependency.');
|
||||
}
|
||||
},
|
||||
getCanonicalFileName: function(filename) {
|
||||
getCanonicalFileName(filename) {
|
||||
return filename;
|
||||
},
|
||||
getCurrentDirectory: function() {
|
||||
getCurrentDirectory() {
|
||||
return '';
|
||||
},
|
||||
getNewLine: function() {
|
||||
getNewLine() {
|
||||
return '\n';
|
||||
},
|
||||
fileExists(filename) {
|
||||
return ts.sys.fileExists(filename);
|
||||
},
|
||||
useCaseSensitiveFileNames() {
|
||||
return ts.sys.useCaseSensitiveFileNames;
|
||||
},
|
||||
};
|
||||
var program = ts.createProgram([
|
||||
'lib.d.ts',
|
||||
'jest.d.ts',
|
||||
contentFilename,
|
||||
], tsOptions, compilerHost);
|
||||
var errors = program.getDiagnostics();
|
||||
if (!errors.length) {
|
||||
var checker = program.getTypeChecker(true);
|
||||
errors = checker.getDiagnostics();
|
||||
checker.emitFiles();
|
||||
}
|
||||
var emitResult = program.emit();
|
||||
var errors = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
|
||||
if (errors.length) {
|
||||
throw new Error(errors.map(formatErrorMessage).join('\n'));
|
||||
}
|
||||
|
||||
+1
-1
@@ -11,4 +11,4 @@
|
||||
|
||||
'use strict';
|
||||
|
||||
module.exports = '15.1.0';
|
||||
module.exports = '15.2.0-rc.2';
|
||||
@@ -31,7 +31,7 @@ describe('ReactFragment', function() {
|
||||
};
|
||||
var element = <div>{[children]}</div>;
|
||||
var container = document.createElement('div');
|
||||
expect(() => ReactDOM.render(element, container)).toThrow(
|
||||
expect(() => ReactDOM.render(element, container)).toThrowError(
|
||||
'Objects are not valid as a React child (found: object with keys ' +
|
||||
'{x, y, z}). If you meant to render a collection of children, use an ' +
|
||||
'array instead or wrap the object using createFragment(object) from ' +
|
||||
@@ -51,7 +51,7 @@ describe('ReactFragment', function() {
|
||||
}
|
||||
}
|
||||
var container = document.createElement('div');
|
||||
expect(() => ReactDOM.render(<Foo />, container)).toThrow(
|
||||
expect(() => ReactDOM.render(<Foo />, container)).toThrowError(
|
||||
'Objects are not valid as a React child (found: object with keys ' +
|
||||
'{a, b, c}). If you meant to render a collection of children, use an ' +
|
||||
'array instead or wrap the object using createFragment(object) from ' +
|
||||
@@ -62,7 +62,7 @@ describe('ReactFragment', function() {
|
||||
it('should throw if a plain object looks like an old element', function() {
|
||||
var oldEl = {_isReactElement: true, type: 'span', props: {}};
|
||||
var container = document.createElement('div');
|
||||
expect(() => ReactDOM.render(<div>{oldEl}</div>, container)).toThrow(
|
||||
expect(() => ReactDOM.render(<div>{oldEl}</div>, container)).toThrowError(
|
||||
'Objects are not valid as a React child (found: object with keys ' +
|
||||
'{_isReactElement, type, props}). It looks like you\'re using an ' +
|
||||
'element created by a different version of React. Make sure to use ' +
|
||||
@@ -75,8 +75,8 @@ describe('ReactFragment', function() {
|
||||
|
||||
ReactFragment.create({1: <span />, 2: <span />});
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'Child objects should have non-numeric keys so ordering is preserved.'
|
||||
);
|
||||
});
|
||||
@@ -84,8 +84,8 @@ describe('ReactFragment', function() {
|
||||
it('should warn if passing null to createFragment', function() {
|
||||
spyOn(console, 'error');
|
||||
ReactFragment.create(null);
|
||||
expect(console.error.calls.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'React.addons.createFragment only accepts a single object.'
|
||||
);
|
||||
});
|
||||
@@ -93,8 +93,8 @@ describe('ReactFragment', function() {
|
||||
it('should warn if passing an array to createFragment', function() {
|
||||
spyOn(console, 'error');
|
||||
ReactFragment.create([]);
|
||||
expect(console.error.calls.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'React.addons.createFragment only accepts a single object.'
|
||||
);
|
||||
});
|
||||
@@ -102,8 +102,8 @@ describe('ReactFragment', function() {
|
||||
it('should warn if passing a ReactElement to createFragment', function() {
|
||||
spyOn(console, 'error');
|
||||
ReactFragment.create(<div />);
|
||||
expect(console.error.calls.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'React.addons.createFragment does not accept a ReactElement without a ' +
|
||||
'wrapper object.'
|
||||
);
|
||||
|
||||
@@ -88,7 +88,7 @@ describe('renderSubtreeIntoContainer', function() {
|
||||
componentDidMount: function() {
|
||||
expect(function() {
|
||||
renderSubtreeIntoContainer(<Parent />, <Component />, portal);
|
||||
}).toThrow('parentComponentmust be a valid React Component');
|
||||
}).toThrowError('parentComponentmust be a valid React Component');
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -25,13 +25,13 @@ describe('update', function() {
|
||||
expect(obj).toEqual([1]);
|
||||
});
|
||||
it('only pushes an array', function() {
|
||||
expect(update.bind(null, [], {$push: 7})).toThrow(
|
||||
expect(update.bind(null, [], {$push: 7})).toThrowError(
|
||||
'update(): expected spec of $push to be an array; got 7. Did you ' +
|
||||
'forget to wrap your parameter in an array?'
|
||||
);
|
||||
});
|
||||
it('only pushes unto an array', function() {
|
||||
expect(update.bind(null, 1, {$push: 7})).toThrow(
|
||||
expect(update.bind(null, 1, {$push: 7})).toThrowError(
|
||||
'update(): expected target of $push to be an array; got 1.'
|
||||
);
|
||||
});
|
||||
@@ -47,13 +47,13 @@ describe('update', function() {
|
||||
expect(obj).toEqual([1]);
|
||||
});
|
||||
it('only unshifts an array', function() {
|
||||
expect(update.bind(null, [], {$unshift: 7})).toThrow(
|
||||
expect(update.bind(null, [], {$unshift: 7})).toThrowError(
|
||||
'update(): expected spec of $unshift to be an array; got 7. Did you ' +
|
||||
'forget to wrap your parameter in an array?'
|
||||
);
|
||||
});
|
||||
it('only unshifts unto an array', function() {
|
||||
expect(update.bind(null, 1, {$unshift: 7})).toThrow(
|
||||
expect(update.bind(null, 1, {$unshift: 7})).toThrowError(
|
||||
'update(): expected target of $unshift to be an array; got 1.'
|
||||
);
|
||||
});
|
||||
@@ -69,17 +69,17 @@ describe('update', function() {
|
||||
expect(obj).toEqual([1, 4, 3]);
|
||||
});
|
||||
it('only splices an array of arrays', function() {
|
||||
expect(update.bind(null, [], {$splice: 1})).toThrow(
|
||||
expect(update.bind(null, [], {$splice: 1})).toThrowError(
|
||||
'update(): expected spec of $splice to be an array of arrays; got 1. ' +
|
||||
'Did you forget to wrap your parameters in an array?'
|
||||
);
|
||||
expect(update.bind(null, [], {$splice: [1]})).toThrow(
|
||||
expect(update.bind(null, [], {$splice: [1]})).toThrowError(
|
||||
'update(): expected spec of $splice to be an array of arrays; got 1. ' +
|
||||
'Did you forget to wrap your parameters in an array?'
|
||||
);
|
||||
});
|
||||
it('only splices unto an array', function() {
|
||||
expect(update.bind(null, 1, {$splice: 7})).toThrow(
|
||||
expect(update.bind(null, 1, {$splice: 7})).toThrowError(
|
||||
'Expected $splice target to be an array; got 1'
|
||||
);
|
||||
});
|
||||
@@ -95,12 +95,12 @@ describe('update', function() {
|
||||
expect(obj).toEqual({a: 'b'});
|
||||
});
|
||||
it('only merges with an object', function() {
|
||||
expect(update.bind(null, {}, {$merge: 7})).toThrow(
|
||||
expect(update.bind(null, {}, {$merge: 7})).toThrowError(
|
||||
'update(): $merge expects a spec of type \'object\'; got 7'
|
||||
);
|
||||
});
|
||||
it('only merges with an object', function() {
|
||||
expect(update.bind(null, 7, {$merge: {a: 'b'}})).toThrow(
|
||||
expect(update.bind(null, 7, {$merge: {a: 'b'}})).toThrowError(
|
||||
'update(): $merge expects a target of type \'object\'; got 7'
|
||||
);
|
||||
});
|
||||
@@ -130,7 +130,7 @@ describe('update', function() {
|
||||
expect(obj).toEqual({v: 2});
|
||||
});
|
||||
it('only applies a function', function() {
|
||||
expect(update.bind(null, 2, {$apply: 123})).toThrow(
|
||||
expect(update.bind(null, 2, {$apply: 123})).toThrowError(
|
||||
'update(): expected spec of $apply to be a function; got 123.'
|
||||
);
|
||||
});
|
||||
@@ -170,7 +170,7 @@ describe('update', function() {
|
||||
});
|
||||
|
||||
it('should require a command', function() {
|
||||
expect(update.bind(null, {a: 'b'}, {a: 'c'})).toThrow(
|
||||
expect(update.bind(null, {a: 'b'}, {a: 'c'})).toThrowError(
|
||||
'update(): You provided a key path to update() that did not contain ' +
|
||||
'one of $push, $unshift, $splice, $set, $merge, $apply. Did you ' +
|
||||
'forget to include {$set: ...}?'
|
||||
|
||||
@@ -89,7 +89,7 @@ var ReactCSSTransitionGroupChild = React.createClass({
|
||||
CSSCore.addClass(node, className);
|
||||
|
||||
// Need to do this to actually trigger a transition.
|
||||
this.queueClass(activeClassName);
|
||||
this.queueClassAndNode(activeClassName, node);
|
||||
|
||||
// If the user specified a timeout delay.
|
||||
if (userSpecifiedDelay) {
|
||||
@@ -102,26 +102,29 @@ var ReactCSSTransitionGroupChild = React.createClass({
|
||||
}
|
||||
},
|
||||
|
||||
queueClass: function(className) {
|
||||
this.classNameQueue.push(className);
|
||||
queueClassAndNode: function(className, node) {
|
||||
this.classNameAndNodeQueue.push({
|
||||
className: className,
|
||||
node: node,
|
||||
});
|
||||
|
||||
if (!this.timeout) {
|
||||
this.timeout = setTimeout(this.flushClassNameQueue, TICK);
|
||||
this.timeout = setTimeout(this.flushClassNameAndNodeQueue, TICK);
|
||||
}
|
||||
},
|
||||
|
||||
flushClassNameQueue: function() {
|
||||
flushClassNameAndNodeQueue: function() {
|
||||
if (this.isMounted()) {
|
||||
this.classNameQueue.forEach(
|
||||
CSSCore.addClass.bind(CSSCore, ReactDOM.findDOMNode(this))
|
||||
);
|
||||
this.classNameAndNodeQueue.forEach(function(obj) {
|
||||
CSSCore.addClass(obj.node, obj.className);
|
||||
});
|
||||
}
|
||||
this.classNameQueue.length = 0;
|
||||
this.classNameAndNodeQueue.length = 0;
|
||||
this.timeout = null;
|
||||
},
|
||||
|
||||
componentWillMount: function() {
|
||||
this.classNameQueue = [];
|
||||
this.classNameAndNodeQueue = [];
|
||||
this.transitionTimeouts = [];
|
||||
},
|
||||
|
||||
@@ -132,6 +135,8 @@ var ReactCSSTransitionGroupChild = React.createClass({
|
||||
this.transitionTimeouts.forEach(function(timeout) {
|
||||
clearTimeout(timeout);
|
||||
});
|
||||
|
||||
this.classNameAndNodeQueue.length = 0;
|
||||
},
|
||||
|
||||
componentWillAppear: function(done) {
|
||||
|
||||
@@ -19,12 +19,18 @@ var ReactTransitionChildMapping = {
|
||||
* simple syntactic sugar around flattenChildren().
|
||||
*
|
||||
* @param {*} children `this.props.children`
|
||||
* @param {number=} selfDebugID Optional debugID of the current internal instance.
|
||||
* @return {object} Mapping of key to child
|
||||
*/
|
||||
getChildMapping: function(children) {
|
||||
getChildMapping: function(children, selfDebugID) {
|
||||
if (!children) {
|
||||
return children;
|
||||
}
|
||||
|
||||
if (__DEV__) {
|
||||
return flattenChildren(children, selfDebugID);
|
||||
}
|
||||
|
||||
return flattenChildren(children);
|
||||
},
|
||||
|
||||
|
||||
@@ -12,12 +12,13 @@
|
||||
'use strict';
|
||||
|
||||
var React = require('React');
|
||||
var ReactInstanceMap = require('ReactInstanceMap');
|
||||
var ReactTransitionChildMapping = require('ReactTransitionChildMapping');
|
||||
|
||||
var emptyFunction = require('emptyFunction');
|
||||
|
||||
/**
|
||||
* A basis for animatins. When children are declaratively added or removed,
|
||||
* A basis for animations. When children are declaratively added or removed,
|
||||
* special lifecycle hooks are called.
|
||||
* See https://facebook.github.io/react/docs/animation.html#low-level-api-reacttransitiongroup
|
||||
*/
|
||||
@@ -38,6 +39,7 @@ var ReactTransitionGroup = React.createClass({
|
||||
|
||||
getInitialState: function() {
|
||||
return {
|
||||
// TODO: can we get useful debug information to show at this point?
|
||||
children: ReactTransitionChildMapping.getChildMapping(this.props.children),
|
||||
};
|
||||
},
|
||||
@@ -58,9 +60,17 @@ var ReactTransitionGroup = React.createClass({
|
||||
},
|
||||
|
||||
componentWillReceiveProps: function(nextProps) {
|
||||
var nextChildMapping = ReactTransitionChildMapping.getChildMapping(
|
||||
nextProps.children
|
||||
);
|
||||
var nextChildMapping;
|
||||
if (__DEV__) {
|
||||
nextChildMapping = ReactTransitionChildMapping.getChildMapping(
|
||||
nextProps.children,
|
||||
ReactInstanceMap.get(this)._debugID
|
||||
);
|
||||
} else {
|
||||
nextChildMapping = ReactTransitionChildMapping.getChildMapping(
|
||||
nextProps.children
|
||||
);
|
||||
}
|
||||
var prevChildMapping = this.state.children;
|
||||
|
||||
this.setState({
|
||||
@@ -123,9 +133,17 @@ var ReactTransitionGroup = React.createClass({
|
||||
|
||||
delete this.currentlyTransitioningKeys[key];
|
||||
|
||||
var currentChildMapping = ReactTransitionChildMapping.getChildMapping(
|
||||
this.props.children
|
||||
);
|
||||
var currentChildMapping;
|
||||
if (__DEV__) {
|
||||
currentChildMapping = ReactTransitionChildMapping.getChildMapping(
|
||||
this.props.children,
|
||||
ReactInstanceMap.get(this)._debugID
|
||||
);
|
||||
} else {
|
||||
currentChildMapping = ReactTransitionChildMapping.getChildMapping(
|
||||
this.props.children
|
||||
);
|
||||
}
|
||||
|
||||
if (!currentChildMapping || !currentChildMapping.hasOwnProperty(key)) {
|
||||
// This was removed before it had fully appeared. Remove it.
|
||||
@@ -155,9 +173,17 @@ var ReactTransitionGroup = React.createClass({
|
||||
|
||||
delete this.currentlyTransitioningKeys[key];
|
||||
|
||||
var currentChildMapping = ReactTransitionChildMapping.getChildMapping(
|
||||
this.props.children
|
||||
);
|
||||
var currentChildMapping;
|
||||
if (__DEV__) {
|
||||
currentChildMapping = ReactTransitionChildMapping.getChildMapping(
|
||||
this.props.children,
|
||||
ReactInstanceMap.get(this)._debugID
|
||||
);
|
||||
} else {
|
||||
currentChildMapping = ReactTransitionChildMapping.getChildMapping(
|
||||
this.props.children
|
||||
);
|
||||
}
|
||||
|
||||
if (!currentChildMapping || !currentChildMapping.hasOwnProperty(key)) {
|
||||
// This was removed before it had fully entered. Remove it.
|
||||
@@ -188,9 +214,17 @@ var ReactTransitionGroup = React.createClass({
|
||||
|
||||
delete this.currentlyTransitioningKeys[key];
|
||||
|
||||
var currentChildMapping = ReactTransitionChildMapping.getChildMapping(
|
||||
this.props.children
|
||||
);
|
||||
var currentChildMapping;
|
||||
if (__DEV__) {
|
||||
currentChildMapping = ReactTransitionChildMapping.getChildMapping(
|
||||
this.props.children,
|
||||
ReactInstanceMap.get(this)._debugID
|
||||
);
|
||||
} else {
|
||||
currentChildMapping = ReactTransitionChildMapping.getChildMapping(
|
||||
this.props.children
|
||||
);
|
||||
}
|
||||
|
||||
if (currentChildMapping && currentChildMapping.hasOwnProperty(key)) {
|
||||
// This entered again before it fully left. Add it again.
|
||||
@@ -222,9 +256,21 @@ var ReactTransitionGroup = React.createClass({
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Do not forward ReactTransitionGroup props to primitive DOM nodes
|
||||
var props = Object.assign({}, this.props);
|
||||
delete props.transitionLeave;
|
||||
delete props.transitionName;
|
||||
delete props.transitionAppear;
|
||||
delete props.transitionEnter;
|
||||
delete props.childFactory;
|
||||
delete props.transitionLeaveTimeout;
|
||||
delete props.transitionEnterTimeout;
|
||||
delete props.component;
|
||||
|
||||
return React.createElement(
|
||||
this.props.component,
|
||||
this.props,
|
||||
props,
|
||||
childrenToRender
|
||||
);
|
||||
},
|
||||
|
||||
@@ -45,7 +45,7 @@ describe('ReactCSSTransitionGroup', function() {
|
||||
);
|
||||
|
||||
// Warning about the missing transitionLeaveTimeout prop
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
});
|
||||
|
||||
it('should not warn if timeouts is zero', function() {
|
||||
@@ -61,7 +61,7 @@ describe('ReactCSSTransitionGroup', function() {
|
||||
container
|
||||
);
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
it('should clean-up silently after the timeout elapses', function() {
|
||||
@@ -103,7 +103,7 @@ describe('ReactCSSTransitionGroup', function() {
|
||||
}
|
||||
|
||||
// No warnings
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
|
||||
// The leaving child has been removed
|
||||
expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(1);
|
||||
@@ -291,4 +291,42 @@ describe('ReactCSSTransitionGroup', function() {
|
||||
// Testing that no exception is thrown here, as the timeout has been cleared.
|
||||
jest.runAllTimers();
|
||||
});
|
||||
|
||||
it('should handle unmounted elements properly', function() {
|
||||
var Child = React.createClass({
|
||||
render() {
|
||||
if (!this.props.show) {
|
||||
return null;
|
||||
}
|
||||
return <div />;
|
||||
},
|
||||
});
|
||||
|
||||
var Component = React.createClass({
|
||||
getInitialState() {
|
||||
return { showChild: true };
|
||||
},
|
||||
|
||||
componentDidMount() {
|
||||
this.setState({ showChild: false });
|
||||
},
|
||||
|
||||
render() {
|
||||
return (
|
||||
<ReactCSSTransitionGroup
|
||||
transitionName="yolo"
|
||||
transitionAppear={true}
|
||||
transitionAppearTimeout={0}
|
||||
>
|
||||
<Child show={this.state.showChild} />
|
||||
</ReactCSSTransitionGroup>
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
ReactDOM.render(<Component/>, container);
|
||||
|
||||
// Testing that no exception is thrown here, as the timeout has been cleared.
|
||||
jest.runAllTimers();
|
||||
});
|
||||
});
|
||||
@@ -20,6 +20,10 @@ var ReactTransitionGroup;
|
||||
describe('ReactTransitionGroup', function() {
|
||||
var container;
|
||||
|
||||
function normalizeCodeLocInfo(str) {
|
||||
return str.replace(/\(at .+?:\d+\)/g, '(at **)');
|
||||
}
|
||||
|
||||
beforeEach(function() {
|
||||
React = require('React');
|
||||
ReactDOM = require('ReactDOM');
|
||||
@@ -269,4 +273,33 @@ describe('ReactTransitionGroup', function() {
|
||||
'willLeave2', 'didLeave2', 'willUnmount0', 'willUnmount1', 'willUnmount2',
|
||||
]);
|
||||
});
|
||||
|
||||
it('should warn for duplicated keys with component stack info', function() {
|
||||
spyOn(console, 'error');
|
||||
|
||||
var Component = React.createClass({
|
||||
render: function() {
|
||||
var children = [<div key="1"/>, <div key="1" />];
|
||||
return <ReactTransitionGroup>{children}</ReactTransitionGroup>;
|
||||
},
|
||||
});
|
||||
|
||||
ReactDOM.render(<Component />, container);
|
||||
|
||||
expect(console.error.calls.count()).toBe(2);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: flattenChildren(...): ' +
|
||||
'Encountered two children with the same key, `1`. ' +
|
||||
'Child keys must be unique; when two children share a key, ' +
|
||||
'only the first child will be used.'
|
||||
);
|
||||
expect(normalizeCodeLocInfo(console.error.calls.argsFor(1)[0])).toBe(
|
||||
'Warning: flattenChildren(...): ' +
|
||||
'Encountered two children with the same key, `1`. ' +
|
||||
'Child keys must be unique; when two children share a key, ' +
|
||||
'only the first child will be used.\n' +
|
||||
' in ReactTransitionGroup (at **)\n' +
|
||||
' in Component (at **)'
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -16,7 +16,6 @@ var ReactComponent = require('ReactComponent');
|
||||
var ReactClass = require('ReactClass');
|
||||
var ReactDOMFactories = require('ReactDOMFactories');
|
||||
var ReactElement = require('ReactElement');
|
||||
var ReactElementValidator = require('ReactElementValidator');
|
||||
var ReactPropTypes = require('ReactPropTypes');
|
||||
var ReactVersion = require('ReactVersion');
|
||||
|
||||
@@ -28,6 +27,7 @@ var createFactory = ReactElement.createFactory;
|
||||
var cloneElement = ReactElement.cloneElement;
|
||||
|
||||
if (__DEV__) {
|
||||
var ReactElementValidator = require('ReactElementValidator');
|
||||
createElement = ReactElementValidator.createElement;
|
||||
createFactory = ReactElementValidator.createFactory;
|
||||
cloneElement = ReactElementValidator.cloneElement;
|
||||
|
||||
@@ -23,7 +23,7 @@ describe('ReactChildren', function() {
|
||||
});
|
||||
|
||||
it('should support identity for simple', function() {
|
||||
var callback = jasmine.createSpy().andCallFake(function(kid, index) {
|
||||
var callback = jasmine.createSpy().and.callFake(function(kid, index) {
|
||||
return kid;
|
||||
});
|
||||
|
||||
@@ -35,14 +35,14 @@ describe('ReactChildren', function() {
|
||||
var instance = <div>{simpleKid}</div>;
|
||||
ReactChildren.forEach(instance.props.children, callback);
|
||||
expect(callback).toHaveBeenCalledWith(simpleKid, 0);
|
||||
callback.reset();
|
||||
callback.calls.reset();
|
||||
var mappedChildren = ReactChildren.map(instance.props.children, callback);
|
||||
expect(callback).toHaveBeenCalledWith(simpleKid, 0);
|
||||
expect(mappedChildren[0]).toEqual(<span key=".$simple" />);
|
||||
});
|
||||
|
||||
it('should treat single arrayless child as being in array', function() {
|
||||
var callback = jasmine.createSpy().andCallFake(function(kid, index) {
|
||||
var callback = jasmine.createSpy().and.callFake(function(kid, index) {
|
||||
return kid;
|
||||
});
|
||||
|
||||
@@ -50,14 +50,14 @@ describe('ReactChildren', function() {
|
||||
var instance = <div>{simpleKid}</div>;
|
||||
ReactChildren.forEach(instance.props.children, callback);
|
||||
expect(callback).toHaveBeenCalledWith(simpleKid, 0);
|
||||
callback.reset();
|
||||
callback.calls.reset();
|
||||
var mappedChildren = ReactChildren.map(instance.props.children, callback);
|
||||
expect(callback).toHaveBeenCalledWith(simpleKid, 0);
|
||||
expect(mappedChildren[0]).toEqual(<span key=".0" />);
|
||||
});
|
||||
|
||||
it('should treat single child in array as expected', function() {
|
||||
var callback = jasmine.createSpy().andCallFake(function(kid, index) {
|
||||
var callback = jasmine.createSpy().and.callFake(function(kid, index) {
|
||||
return kid;
|
||||
});
|
||||
|
||||
@@ -65,7 +65,7 @@ describe('ReactChildren', function() {
|
||||
var instance = <div>{[simpleKid]}</div>;
|
||||
ReactChildren.forEach(instance.props.children, callback);
|
||||
expect(callback).toHaveBeenCalledWith(simpleKid, 0);
|
||||
callback.reset();
|
||||
callback.calls.reset();
|
||||
var mappedChildren = ReactChildren.map(instance.props.children, callback);
|
||||
expect(callback).toHaveBeenCalledWith(simpleKid, 0);
|
||||
expect(mappedChildren[0]).toEqual(<span key=".$simple" />);
|
||||
@@ -124,7 +124,7 @@ describe('ReactChildren', function() {
|
||||
<span />, // Map from null to something.
|
||||
<div key="keyFour" />,
|
||||
];
|
||||
var callback = jasmine.createSpy().andCallFake(function(kid, index) {
|
||||
var callback = jasmine.createSpy().and.callFake(function(kid, index) {
|
||||
return mapped[index];
|
||||
});
|
||||
|
||||
@@ -144,11 +144,11 @@ describe('ReactChildren', function() {
|
||||
expect(callback).toHaveBeenCalledWith(two, 2);
|
||||
expect(callback).toHaveBeenCalledWith(three, 3);
|
||||
expect(callback).toHaveBeenCalledWith(four, 4);
|
||||
callback.reset();
|
||||
callback.calls.reset();
|
||||
|
||||
var mappedChildren =
|
||||
ReactChildren.map(instance.props.children, callback);
|
||||
expect(callback.calls.length).toBe(5);
|
||||
expect(callback.calls.count()).toBe(5);
|
||||
expect(ReactChildren.count(mappedChildren)).toBe(4);
|
||||
// Keys default to indices.
|
||||
expect([
|
||||
@@ -190,7 +190,7 @@ describe('ReactChildren', function() {
|
||||
var fourMapped = <div key="keyFour" />;
|
||||
var fiveMapped = <div />;
|
||||
|
||||
var callback = jasmine.createSpy().andCallFake(function(kid, index) {
|
||||
var callback = jasmine.createSpy().and.callFake(function(kid, index) {
|
||||
return index === 0 ? zeroMapped :
|
||||
index === 1 ? twoMapped :
|
||||
index === 2 ? fourMapped : fiveMapped;
|
||||
@@ -216,15 +216,15 @@ describe('ReactChildren', function() {
|
||||
]);
|
||||
|
||||
ReactChildren.forEach(instance.props.children, callback);
|
||||
expect(callback.calls.length).toBe(4);
|
||||
expect(callback.calls.count()).toBe(4);
|
||||
expect(callback).toHaveBeenCalledWith(frag[0], 0);
|
||||
expect(callback).toHaveBeenCalledWith(frag[1], 1);
|
||||
expect(callback).toHaveBeenCalledWith(frag[2], 2);
|
||||
expect(callback).toHaveBeenCalledWith(frag[3], 3);
|
||||
callback.reset();
|
||||
callback.calls.reset();
|
||||
|
||||
var mappedChildren = ReactChildren.map(instance.props.children, callback);
|
||||
expect(callback.calls.length).toBe(4);
|
||||
expect(callback.calls.count()).toBe(4);
|
||||
expect(callback).toHaveBeenCalledWith(frag[0], 0);
|
||||
expect(callback).toHaveBeenCalledWith(frag[1], 1);
|
||||
expect(callback).toHaveBeenCalledWith(frag[2], 2);
|
||||
|
||||
@@ -24,6 +24,10 @@ var ReactTestUtils;
|
||||
var reactComponentExpect;
|
||||
|
||||
describe('ReactContextValidator', function() {
|
||||
function normalizeCodeLocInfo(str) {
|
||||
return str.replace(/\(at .+?:\d+\)/g, '(at **)');
|
||||
}
|
||||
|
||||
beforeEach(function() {
|
||||
jest.resetModuleRegistry();
|
||||
|
||||
@@ -145,10 +149,11 @@ describe('ReactContextValidator', function() {
|
||||
|
||||
ReactTestUtils.renderIntoDocument(<Component />);
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
'Warning: Failed Context Types: ' +
|
||||
'Required context `foo` was not specified in `Component`.'
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
|
||||
'Warning: Failed context type: ' +
|
||||
'Required context `foo` was not specified in `Component`.\n' +
|
||||
' in Component (at **)'
|
||||
);
|
||||
|
||||
var ComponentInFooStringContext = React.createClass({
|
||||
@@ -172,7 +177,7 @@ describe('ReactContextValidator', function() {
|
||||
);
|
||||
|
||||
// Previous call should not error
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
|
||||
var ComponentInFooNumberContext = React.createClass({
|
||||
childContextTypes: {
|
||||
@@ -192,12 +197,13 @@ describe('ReactContextValidator', function() {
|
||||
|
||||
ReactTestUtils.renderIntoDocument(<ComponentInFooNumberContext fooValue={123} />);
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(2);
|
||||
expect(console.error.argsForCall[1][0]).toBe(
|
||||
'Warning: Failed Context Types: ' +
|
||||
expect(console.error.calls.count()).toBe(2);
|
||||
expect(normalizeCodeLocInfo(console.error.calls.argsFor(1)[0])).toBe(
|
||||
'Warning: Failed context type: ' +
|
||||
'Invalid context `foo` of type `number` supplied ' +
|
||||
'to `Component`, expected `string`.' +
|
||||
' Check the render method of `ComponentInFooNumberContext`.'
|
||||
'to `Component`, expected `string`.\n' +
|
||||
' in Component (at **)\n' +
|
||||
' in ComponentInFooNumberContext (at **)'
|
||||
);
|
||||
});
|
||||
|
||||
@@ -220,19 +226,21 @@ describe('ReactContextValidator', function() {
|
||||
});
|
||||
|
||||
ReactTestUtils.renderIntoDocument(<Component testContext={{bar: 123}} />);
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
'Warning: Failed Context Types: ' +
|
||||
'Required child context `foo` was not specified in `Component`.'
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
|
||||
'Warning: Failed childContext type: ' +
|
||||
'Required child context `foo` was not specified in `Component`.\n' +
|
||||
' in Component (at **)'
|
||||
);
|
||||
|
||||
ReactTestUtils.renderIntoDocument(<Component testContext={{foo: 123}} />);
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(2);
|
||||
expect(console.error.argsForCall[1][0]).toBe(
|
||||
'Warning: Failed Context Types: ' +
|
||||
expect(console.error.calls.count()).toBe(2);
|
||||
expect(normalizeCodeLocInfo(console.error.calls.argsFor(1)[0])).toBe(
|
||||
'Warning: Failed childContext type: ' +
|
||||
'Invalid child context `foo` of type `number` ' +
|
||||
'supplied to `Component`, expected `string`.'
|
||||
'supplied to `Component`, expected `string`.\n' +
|
||||
' in Component (at **)'
|
||||
);
|
||||
|
||||
ReactTestUtils.renderIntoDocument(
|
||||
@@ -244,7 +252,7 @@ describe('ReactContextValidator', function() {
|
||||
);
|
||||
|
||||
// Previous calls should not log errors
|
||||
expect(console.error.argsForCall.length).toBe(2);
|
||||
expect(console.error.calls.count()).toBe(2);
|
||||
});
|
||||
|
||||
});
|
||||
@@ -55,7 +55,7 @@ var injectedMixins = [];
|
||||
|
||||
/**
|
||||
* Composite components are higher-level components that compose other composite
|
||||
* or native components.
|
||||
* or host components.
|
||||
*
|
||||
* To create a new type of `ReactClass`, pass a specification of
|
||||
* your new class to `React.createClass`. The only requirement of your class
|
||||
|
||||
@@ -132,8 +132,8 @@ describe('autobinding', function() {
|
||||
|
||||
ReactTestUtils.renderIntoDocument(<TestBindComponent />);
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: bind(): You are binding a component method to the component. ' +
|
||||
'React does this for you automatically in a high-performance ' +
|
||||
'way, so you can safely remove this call. See TestBindComponent'
|
||||
@@ -160,7 +160,7 @@ describe('autobinding', function() {
|
||||
|
||||
ReactTestUtils.renderIntoDocument(<TestBindComponent />);
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
});
|
||||
@@ -203,7 +203,7 @@ describe('autobind optout', function() {
|
||||
|
||||
ReactTestUtils.renderIntoDocument(<TestBindComponent />);
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
it('does not warn if you pass an manually bound method to setState', function() {
|
||||
@@ -227,7 +227,7 @@ describe('autobind optout', function() {
|
||||
|
||||
ReactTestUtils.renderIntoDocument(<TestBindComponent />);
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
});
|
||||
@@ -26,7 +26,7 @@ describe('ReactClass-spec', function() {
|
||||
it('should throw when `render` is not specified', function() {
|
||||
expect(function() {
|
||||
React.createClass({});
|
||||
}).toThrow(
|
||||
}).toThrowError(
|
||||
'createClass(...): Class specification must implement a `render` method.'
|
||||
);
|
||||
});
|
||||
@@ -69,8 +69,8 @@ describe('ReactClass-spec', function() {
|
||||
return <span>{this.props.prop}</span>;
|
||||
},
|
||||
});
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: Component: prop type `prop` is invalid; ' +
|
||||
'it must be a function, usually from React.PropTypes.'
|
||||
);
|
||||
@@ -87,8 +87,8 @@ describe('ReactClass-spec', function() {
|
||||
return <span>{this.props.prop}</span>;
|
||||
},
|
||||
});
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: Component: context type `prop` is invalid; ' +
|
||||
'it must be a function, usually from React.PropTypes.'
|
||||
);
|
||||
@@ -105,8 +105,8 @@ describe('ReactClass-spec', function() {
|
||||
return <span>{this.props.prop}</span>;
|
||||
},
|
||||
});
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: Component: child context type `prop` is invalid; ' +
|
||||
'it must be a function, usually from React.PropTypes.'
|
||||
);
|
||||
@@ -123,8 +123,8 @@ describe('ReactClass-spec', function() {
|
||||
return <div />;
|
||||
},
|
||||
});
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: A component has a method called componentShouldUpdate(). Did you ' +
|
||||
'mean shouldComponentUpdate()? The name is phrased as a question ' +
|
||||
'because the function is expected to return a value.'
|
||||
@@ -139,8 +139,8 @@ describe('ReactClass-spec', function() {
|
||||
return <div />;
|
||||
},
|
||||
});
|
||||
expect(console.error.argsForCall.length).toBe(2);
|
||||
expect(console.error.argsForCall[1][0]).toBe(
|
||||
expect(console.error.calls.count()).toBe(2);
|
||||
expect(console.error.calls.argsFor(1)[0]).toBe(
|
||||
'Warning: NamedComponent has a method called componentShouldUpdate(). Did you ' +
|
||||
'mean shouldComponentUpdate()? The name is phrased as a question ' +
|
||||
'because the function is expected to return a value.'
|
||||
@@ -157,8 +157,8 @@ describe('ReactClass-spec', function() {
|
||||
return <div />;
|
||||
},
|
||||
});
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: A component has a method called componentWillRecieveProps(). Did you ' +
|
||||
'mean componentWillReceiveProps()?'
|
||||
);
|
||||
@@ -179,7 +179,7 @@ describe('ReactClass-spec', function() {
|
||||
return <span />;
|
||||
},
|
||||
});
|
||||
}).toThrow(
|
||||
}).toThrowError(
|
||||
'ReactClass: You are attempting to define a reserved property, ' +
|
||||
'`getDefaultProps`, that shouldn\'t be on the "statics" key. Define ' +
|
||||
'it as an instance property instead; it will still be accessible on ' +
|
||||
@@ -206,20 +206,20 @@ describe('ReactClass-spec', function() {
|
||||
return <div />;
|
||||
},
|
||||
});
|
||||
expect(console.error.argsForCall.length).toBe(4);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
expect(console.error.calls.count()).toBe(4);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'createClass(...): `mixins` is now a static property and should ' +
|
||||
'be defined inside "statics".'
|
||||
);
|
||||
expect(console.error.argsForCall[1][0]).toBe(
|
||||
expect(console.error.calls.argsFor(1)[0]).toBe(
|
||||
'createClass(...): `propTypes` is now a static property and should ' +
|
||||
'be defined inside "statics".'
|
||||
);
|
||||
expect(console.error.argsForCall[2][0]).toBe(
|
||||
expect(console.error.calls.argsFor(2)[0]).toBe(
|
||||
'createClass(...): `contextTypes` is now a static property and ' +
|
||||
'should be defined inside "statics".'
|
||||
);
|
||||
expect(console.error.argsForCall[3][0]).toBe(
|
||||
expect(console.error.calls.argsFor(3)[0]).toBe(
|
||||
'createClass(...): `childContextTypes` is now a static property and ' +
|
||||
'should be defined inside "statics".'
|
||||
);
|
||||
@@ -314,7 +314,7 @@ describe('ReactClass-spec', function() {
|
||||
var instance = <Component />;
|
||||
expect(function() {
|
||||
instance = ReactTestUtils.renderIntoDocument(instance);
|
||||
}).toThrow(
|
||||
}).toThrowError(
|
||||
'Component.getInitialState(): must return an object or null'
|
||||
);
|
||||
});
|
||||
@@ -343,8 +343,8 @@ describe('ReactClass-spec', function() {
|
||||
});
|
||||
|
||||
expect(() => Component()).toThrow();
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: Something is calling a React component directly. Use a ' +
|
||||
'factory or JSX instead. See: https://fb.me/react-legacyfactory'
|
||||
);
|
||||
|
||||
@@ -155,12 +155,12 @@ describe('ReactClass-mixin', function() {
|
||||
|
||||
it('should override mixin prop types with class prop types', function() {
|
||||
// Sanity check...
|
||||
expect(componentPropValidator).toNotBe(mixinPropValidator);
|
||||
expect(componentPropValidator).not.toBe(mixinPropValidator);
|
||||
// Actually check...
|
||||
expect(TestComponentWithPropTypes.propTypes)
|
||||
.toBeDefined();
|
||||
expect(TestComponentWithPropTypes.propTypes.value)
|
||||
.toNotBe(mixinPropValidator);
|
||||
.not.toBe(mixinPropValidator);
|
||||
expect(TestComponentWithPropTypes.propTypes.value)
|
||||
.toBe(componentPropValidator);
|
||||
});
|
||||
@@ -205,7 +205,7 @@ describe('ReactClass-mixin', function() {
|
||||
var instance = <Component />;
|
||||
expect(function() {
|
||||
instance = ReactTestUtils.renderIntoDocument(instance);
|
||||
}).toThrow(
|
||||
}).toThrowError(
|
||||
'mergeIntoWithNoDuplicateKeys(): Tried to merge two objects with the ' +
|
||||
'same key: `x`. This conflict may be due to a mixin; in particular, ' +
|
||||
'this may be caused by two getInitialState() or getDefaultProps() ' +
|
||||
@@ -276,7 +276,7 @@ describe('ReactClass-mixin', function() {
|
||||
return <span />;
|
||||
},
|
||||
});
|
||||
}).toThrow(
|
||||
}).toThrowError(
|
||||
'ReactClass: You are attempting to define `abc` on your component more ' +
|
||||
'than once. This conflict may be due to a mixin.'
|
||||
);
|
||||
@@ -304,7 +304,7 @@ describe('ReactClass-mixin', function() {
|
||||
return <span />;
|
||||
},
|
||||
});
|
||||
}).toThrow(
|
||||
}).toThrowError(
|
||||
'ReactClass: You are attempting to define `abc` on your component ' +
|
||||
'more than once. This conflict may be due to a mixin.'
|
||||
);
|
||||
@@ -319,7 +319,7 @@ describe('ReactClass-mixin', function() {
|
||||
return <span />;
|
||||
},
|
||||
});
|
||||
}).toThrow(
|
||||
}).toThrowError(
|
||||
'ReactClass: You\'re attempting to use a component as a mixin. ' +
|
||||
'Instead, just use a regular object.'
|
||||
);
|
||||
@@ -340,7 +340,7 @@ describe('ReactClass-mixin', function() {
|
||||
return <span />;
|
||||
},
|
||||
});
|
||||
}).toThrow(
|
||||
}).toThrowError(
|
||||
'ReactClass: You\'re attempting to use a component class or function ' +
|
||||
'as a mixin. Instead, just use a regular object.'
|
||||
);
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
'use strict';
|
||||
|
||||
var ReactElement = require('ReactElement');
|
||||
var ReactElementValidator = require('ReactElementValidator');
|
||||
|
||||
var mapObject = require('mapObject');
|
||||
|
||||
@@ -24,6 +23,7 @@ var mapObject = require('mapObject');
|
||||
*/
|
||||
function createDOMFactory(tag) {
|
||||
if (__DEV__) {
|
||||
var ReactElementValidator = require('ReactElementValidator');
|
||||
return ReactElementValidator.createFactory(tag);
|
||||
}
|
||||
return ReactElement.createFactory(tag);
|
||||
|
||||
@@ -15,6 +15,7 @@ var ReactCurrentOwner = require('ReactCurrentOwner');
|
||||
|
||||
var warning = require('warning');
|
||||
var canDefineProperty = require('canDefineProperty');
|
||||
var hasOwnProperty = Object.prototype.hasOwnProperty;
|
||||
|
||||
// The Symbol used to tag the ReactElement type. If there is no native Symbol
|
||||
// nor polyfill, then a plain number is used for performance.
|
||||
@@ -31,6 +32,30 @@ var RESERVED_PROPS = {
|
||||
|
||||
var specialPropKeyWarningShown, specialPropRefWarningShown;
|
||||
|
||||
function hasValidRef(config) {
|
||||
if (__DEV__) {
|
||||
if (hasOwnProperty.call(config, 'ref')) {
|
||||
var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;
|
||||
if (getter && getter.isReactWarning) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return config.ref !== undefined;
|
||||
}
|
||||
|
||||
function hasValidKey(config) {
|
||||
if (__DEV__) {
|
||||
if (hasOwnProperty.call(config, 'key')) {
|
||||
var getter = Object.getOwnPropertyDescriptor(config, 'key').get;
|
||||
if (getter && getter.isReactWarning) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return config.key !== undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Factory method to create a new React element. This no longer adheres to
|
||||
* the class pattern, so do not use new to call it. Also, no instanceof check
|
||||
@@ -137,19 +162,20 @@ ReactElement.createElement = function(type, config, children) {
|
||||
'React.createElement(...): Expected props argument to be a plain object. ' +
|
||||
'Properties defined in its prototype chain will be ignored.'
|
||||
);
|
||||
ref = !config.hasOwnProperty('ref') ||
|
||||
Object.getOwnPropertyDescriptor(config, 'ref').get ? null : config.ref;
|
||||
key = !config.hasOwnProperty('key') ||
|
||||
Object.getOwnPropertyDescriptor(config, 'key').get ? null : '' + config.key;
|
||||
} else {
|
||||
ref = config.ref === undefined ? null : config.ref;
|
||||
key = config.key === undefined ? null : '' + config.key;
|
||||
}
|
||||
|
||||
if (hasValidRef(config)) {
|
||||
ref = config.ref;
|
||||
}
|
||||
if (hasValidKey(config)) {
|
||||
key = '' + config.key;
|
||||
}
|
||||
|
||||
self = config.__self === undefined ? null : config.__self;
|
||||
source = config.__source === undefined ? null : config.__source;
|
||||
// Remaining properties are added to a new props object
|
||||
for (propName in config) {
|
||||
if (config.hasOwnProperty(propName) &&
|
||||
if (hasOwnProperty.call(config, propName) &&
|
||||
!RESERVED_PROPS.hasOwnProperty(propName)) {
|
||||
props[propName] = config[propName];
|
||||
}
|
||||
@@ -179,45 +205,54 @@ ReactElement.createElement = function(type, config, children) {
|
||||
}
|
||||
}
|
||||
if (__DEV__) {
|
||||
// Create dummy `key` and `ref` property to `props` to warn users
|
||||
// against its use
|
||||
var displayName = typeof type === 'function' ?
|
||||
(type.displayName || type.name || 'Unknown') :
|
||||
type;
|
||||
|
||||
// Create dummy `key` and `ref` property to `props` to warn users against its use
|
||||
var warnAboutAccessingKey = function() {
|
||||
if (!specialPropKeyWarningShown) {
|
||||
specialPropKeyWarningShown = true;
|
||||
warning(
|
||||
false,
|
||||
'%s: `key` is not a prop. Trying to access it will result ' +
|
||||
'in `undefined` being returned. If you need to access the same ' +
|
||||
'value within the child component, you should pass it as a different ' +
|
||||
'prop. (https://fb.me/react-special-props)',
|
||||
displayName
|
||||
);
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
warnAboutAccessingKey.isReactWarning = true;
|
||||
|
||||
var warnAboutAccessingRef = function() {
|
||||
if (!specialPropRefWarningShown) {
|
||||
specialPropRefWarningShown = true;
|
||||
warning(
|
||||
false,
|
||||
'%s: `ref` is not a prop. Trying to access it will result ' +
|
||||
'in `undefined` being returned. If you need to access the same ' +
|
||||
'value within the child component, you should pass it as a different ' +
|
||||
'prop. (https://fb.me/react-special-props)',
|
||||
displayName
|
||||
);
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
warnAboutAccessingRef.isReactWarning = true;
|
||||
|
||||
if (typeof props.$$typeof === 'undefined' ||
|
||||
props.$$typeof !== REACT_ELEMENT_TYPE) {
|
||||
if (!props.hasOwnProperty('key')) {
|
||||
Object.defineProperty(props, 'key', {
|
||||
get: function() {
|
||||
if (!specialPropKeyWarningShown) {
|
||||
specialPropKeyWarningShown = true;
|
||||
warning(
|
||||
false,
|
||||
'%s: `key` is not a prop. Trying to access it will result ' +
|
||||
'in `undefined` being returned. If you need to access the same ' +
|
||||
'value within the child component, you should pass it as a different ' +
|
||||
'prop. (https://fb.me/react-special-props)',
|
||||
typeof type === 'function' && 'displayName' in type ? type.displayName : 'Element'
|
||||
);
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
get: warnAboutAccessingKey,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
if (!props.hasOwnProperty('ref')) {
|
||||
Object.defineProperty(props, 'ref', {
|
||||
get: function() {
|
||||
if (!specialPropRefWarningShown) {
|
||||
specialPropRefWarningShown = true;
|
||||
warning(
|
||||
false,
|
||||
'%s: `ref` is not a prop. Trying to access it will result ' +
|
||||
'in `undefined` being returned. If you need to access the same ' +
|
||||
'value within the child component, you should pass it as a different ' +
|
||||
'prop. (https://fb.me/react-special-props)',
|
||||
typeof type === 'function' && 'displayName' in type ? type.displayName : 'Element'
|
||||
);
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
get: warnAboutAccessingRef,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
@@ -296,21 +331,23 @@ ReactElement.cloneElement = function(element, config, children) {
|
||||
'Properties defined in its prototype chain will be ignored.'
|
||||
);
|
||||
}
|
||||
if (config.ref !== undefined) {
|
||||
|
||||
if (hasValidRef(config)) {
|
||||
// Silently steal the ref from the parent.
|
||||
ref = config.ref;
|
||||
owner = ReactCurrentOwner.current;
|
||||
}
|
||||
if (config.key !== undefined) {
|
||||
if (hasValidKey(config)) {
|
||||
key = '' + config.key;
|
||||
}
|
||||
|
||||
// Remaining properties override existing props
|
||||
var defaultProps;
|
||||
if (element.type && element.type.defaultProps) {
|
||||
defaultProps = element.type.defaultProps;
|
||||
}
|
||||
for (propName in config) {
|
||||
if (config.hasOwnProperty(propName) &&
|
||||
if (hasOwnProperty.call(config, propName) &&
|
||||
!RESERVED_PROPS.hasOwnProperty(propName)) {
|
||||
if (config[propName] === undefined && defaultProps !== undefined) {
|
||||
// Resolve default props
|
||||
@@ -361,4 +398,6 @@ ReactElement.isValidElement = function(object) {
|
||||
);
|
||||
};
|
||||
|
||||
ReactElement.REACT_ELEMENT_TYPE = REACT_ELEMENT_TYPE;
|
||||
|
||||
module.exports = ReactElement;
|
||||
@@ -18,14 +18,15 @@
|
||||
|
||||
'use strict';
|
||||
|
||||
var ReactCurrentOwner = require('ReactCurrentOwner');
|
||||
var ReactComponentTreeDevtool = require('ReactComponentTreeDevtool');
|
||||
var ReactElement = require('ReactElement');
|
||||
var ReactPropTypeLocations = require('ReactPropTypeLocations');
|
||||
var ReactPropTypeLocationNames = require('ReactPropTypeLocationNames');
|
||||
var ReactCurrentOwner = require('ReactCurrentOwner');
|
||||
|
||||
var checkReactTypeSpec = require('checkReactTypeSpec');
|
||||
|
||||
var canDefineProperty = require('canDefineProperty');
|
||||
var getIteratorFn = require('getIteratorFn');
|
||||
var invariant = require('invariant');
|
||||
var warning = require('warning');
|
||||
|
||||
function getDeclarationErrorAddendum() {
|
||||
@@ -45,13 +46,25 @@ function getDeclarationErrorAddendum() {
|
||||
*/
|
||||
var ownerHasKeyUseWarning = {};
|
||||
|
||||
var loggedTypeFailures = {};
|
||||
function getCurrentComponentErrorInfo(parentType) {
|
||||
var info = getDeclarationErrorAddendum();
|
||||
|
||||
if (!info) {
|
||||
var parentName = typeof parentType === 'string' ?
|
||||
parentType : parentType.displayName || parentType.name;
|
||||
if (parentName) {
|
||||
info = ` Check the top-level render call using <${parentName}>.`;
|
||||
}
|
||||
}
|
||||
return info;
|
||||
}
|
||||
|
||||
/**
|
||||
* Warn if the element doesn't have an explicit key assigned to it.
|
||||
* This element is in an array. The array could grow and shrink or be
|
||||
* reordered. All children that haven't already been validated are required to
|
||||
* have a "key" property assigned to it.
|
||||
* have a "key" property assigned to it. Error statuses are cached so a warning
|
||||
* will only be shown once.
|
||||
*
|
||||
* @internal
|
||||
* @param {ReactElement} element Element that requires a key.
|
||||
@@ -63,67 +76,36 @@ function validateExplicitKey(element, parentType) {
|
||||
}
|
||||
element._store.validated = true;
|
||||
|
||||
var addenda = getAddendaForKeyUse('uniqueKey', element, parentType);
|
||||
if (addenda === null) {
|
||||
// we already showed the warning
|
||||
var memoizer = ownerHasKeyUseWarning.uniqueKey || (
|
||||
ownerHasKeyUseWarning.uniqueKey = {}
|
||||
);
|
||||
|
||||
var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
|
||||
if (memoizer[currentComponentErrorInfo]) {
|
||||
return;
|
||||
}
|
||||
warning(
|
||||
false,
|
||||
'Each child in an array or iterator should have a unique "key" prop.' +
|
||||
'%s%s%s',
|
||||
addenda.parentOrOwner || '',
|
||||
addenda.childOwner || '',
|
||||
addenda.url || ''
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared warning and monitoring code for the key warnings.
|
||||
*
|
||||
* @internal
|
||||
* @param {string} messageType A key used for de-duping warnings.
|
||||
* @param {ReactElement} element Component that requires a key.
|
||||
* @param {*} parentType element's parent's type.
|
||||
* @returns {?object} A set of addenda to use in the warning message, or null
|
||||
* if the warning has already been shown before (and shouldn't be shown again).
|
||||
*/
|
||||
function getAddendaForKeyUse(messageType, element, parentType) {
|
||||
var addendum = getDeclarationErrorAddendum();
|
||||
if (!addendum) {
|
||||
var parentName = typeof parentType === 'string' ?
|
||||
parentType : parentType.displayName || parentType.name;
|
||||
if (parentName) {
|
||||
addendum = ` Check the top-level render call using <${parentName}>.`;
|
||||
}
|
||||
}
|
||||
|
||||
var memoizer = ownerHasKeyUseWarning[messageType] || (
|
||||
ownerHasKeyUseWarning[messageType] = {}
|
||||
);
|
||||
if (memoizer[addendum]) {
|
||||
return null;
|
||||
}
|
||||
memoizer[addendum] = true;
|
||||
|
||||
var addenda = {
|
||||
parentOrOwner: addendum,
|
||||
url: ' See https://fb.me/react-warning-keys for more information.',
|
||||
childOwner: null,
|
||||
};
|
||||
memoizer[currentComponentErrorInfo] = true;
|
||||
|
||||
// Usually the current owner is the offender, but if it accepts children as a
|
||||
// property, it may be the creator of the child that's responsible for
|
||||
// assigning it a key.
|
||||
var childOwner = '';
|
||||
if (element &&
|
||||
element._owner &&
|
||||
element._owner !== ReactCurrentOwner.current) {
|
||||
// Give the component that originally created this child.
|
||||
addenda.childOwner =
|
||||
childOwner =
|
||||
` It was passed a child from ${element._owner.getName()}.`;
|
||||
}
|
||||
|
||||
return addenda;
|
||||
warning(
|
||||
false,
|
||||
'Each child in an array or iterator should have a unique "key" prop.' +
|
||||
'%s%s See https://fb.me/react-warning-keys for more information.%s',
|
||||
currentComponentErrorInfo,
|
||||
childOwner,
|
||||
ReactComponentTreeDevtool.getCurrentStackAddendum(element)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -168,61 +150,6 @@ function validateChildKeys(node, parentType) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert that the props are valid
|
||||
*
|
||||
* @param {string} componentName Name of the component for error messages.
|
||||
* @param {object} propTypes Map of prop name to a ReactPropType
|
||||
* @param {object} props
|
||||
* @param {string} location e.g. "prop", "context", "child context"
|
||||
* @private
|
||||
*/
|
||||
function checkPropTypes(componentName, propTypes, props, location) {
|
||||
for (var propName in propTypes) {
|
||||
if (propTypes.hasOwnProperty(propName)) {
|
||||
var error;
|
||||
// Prop type validation may throw. In case they do, we don't want to
|
||||
// fail the render phase where it didn't fail before. So we log it.
|
||||
// After these have been cleaned up, we'll let them throw.
|
||||
try {
|
||||
// This is intentionally an invariant that gets caught. It's the same
|
||||
// behavior as without this statement except with a better message.
|
||||
invariant(
|
||||
typeof propTypes[propName] === 'function',
|
||||
'%s: %s type `%s` is invalid; it must be a function, usually from ' +
|
||||
'React.PropTypes.',
|
||||
componentName || 'React class',
|
||||
ReactPropTypeLocationNames[location],
|
||||
propName
|
||||
);
|
||||
error = propTypes[propName](props, propName, componentName, location);
|
||||
} catch (ex) {
|
||||
error = ex;
|
||||
}
|
||||
warning(
|
||||
!error || error instanceof Error,
|
||||
'%s: type specification of %s `%s` is invalid; the type checker ' +
|
||||
'function must return `null` or an `Error` but returned a %s. ' +
|
||||
'You may have forgotten to pass an argument to the type checker ' +
|
||||
'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +
|
||||
'shape all require an argument).',
|
||||
componentName || 'React class',
|
||||
ReactPropTypeLocationNames[location],
|
||||
propName,
|
||||
typeof error
|
||||
);
|
||||
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
|
||||
// Only monitor this failure once because there tends to be a lot of the
|
||||
// same error.
|
||||
loggedTypeFailures[error.message] = true;
|
||||
|
||||
var addendum = getDeclarationErrorAddendum();
|
||||
warning(false, 'Failed propType: %s%s', error.message, addendum);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Given an element, validate that its props follow the propTypes definition,
|
||||
* provided by the type.
|
||||
@@ -236,11 +163,13 @@ function validatePropTypes(element) {
|
||||
}
|
||||
var name = componentClass.displayName || componentClass.name;
|
||||
if (componentClass.propTypes) {
|
||||
checkPropTypes(
|
||||
name,
|
||||
checkReactTypeSpec(
|
||||
componentClass.propTypes,
|
||||
element.props,
|
||||
ReactPropTypeLocations.prop
|
||||
ReactPropTypeLocations.prop,
|
||||
name,
|
||||
element,
|
||||
null
|
||||
);
|
||||
}
|
||||
if (typeof componentClass.getDefaultProps === 'function') {
|
||||
|
||||
@@ -52,12 +52,12 @@ describe('ReactElement', function() {
|
||||
expect(element.type).toBe(ComponentClass);
|
||||
expect(element.key).toBe(null);
|
||||
expect(element.ref).toBe(null);
|
||||
var expectation = {};
|
||||
Object.freeze(expectation);
|
||||
expect(element.props).toEqual(expectation);
|
||||
expect(Object.isFrozen(element)).toBe(true);
|
||||
expect(Object.isFrozen(element.props)).toBe(true);
|
||||
expect(element.props).toEqual({});
|
||||
});
|
||||
|
||||
it('should warn when `key` is being accessed', function() {
|
||||
it('should warn when `key` is being accessed on createClass element', function() {
|
||||
spyOn(console, 'error');
|
||||
var container = document.createElement('div');
|
||||
var Child = React.createClass({
|
||||
@@ -76,10 +76,10 @@ describe('ReactElement', function() {
|
||||
);
|
||||
},
|
||||
});
|
||||
expect(console.error.calls.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
ReactDOM.render(<Parent />, container);
|
||||
expect(console.error.calls.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'Child: `key` is not a prop. Trying to access it will result ' +
|
||||
'in `undefined` being returned. If you need to access the same ' +
|
||||
'value within the child component, you should pass it as a different ' +
|
||||
@@ -87,6 +87,50 @@ describe('ReactElement', function() {
|
||||
);
|
||||
});
|
||||
|
||||
it('should warn when `key` is being accessed on ES class element', function() {
|
||||
spyOn(console, 'error');
|
||||
var container = document.createElement('div');
|
||||
class Child extends React.Component {
|
||||
render() {
|
||||
return <div> {this.props.key} </div>;
|
||||
}
|
||||
}
|
||||
var Parent = React.createClass({
|
||||
render: function() {
|
||||
return (
|
||||
<div>
|
||||
<Child key="0" />
|
||||
<Child key="1" />
|
||||
<Child key="2" />
|
||||
</div>
|
||||
);
|
||||
},
|
||||
});
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
ReactDOM.render(<Parent />, container);
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'Child: `key` is not a prop. Trying to access it will result ' +
|
||||
'in `undefined` being returned. If you need to access the same ' +
|
||||
'value within the child component, you should pass it as a different ' +
|
||||
'prop. (https://fb.me/react-special-props)'
|
||||
);
|
||||
});
|
||||
|
||||
it('should warn when `key` is being accessed on a host element', function() {
|
||||
spyOn(console, 'error');
|
||||
var element = <div key="3" />;
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
void element.props.key;
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'div: `key` is not a prop. Trying to access it will result ' +
|
||||
'in `undefined` being returned. If you need to access the same ' +
|
||||
'value within the child component, you should pass it as a different ' +
|
||||
'prop. (https://fb.me/react-special-props)'
|
||||
);
|
||||
});
|
||||
|
||||
it('should warn when `ref` is being accessed', function() {
|
||||
spyOn(console, 'error');
|
||||
var container = document.createElement('div');
|
||||
@@ -104,10 +148,10 @@ describe('ReactElement', function() {
|
||||
);
|
||||
},
|
||||
});
|
||||
expect(console.error.calls.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
ReactDOM.render(<Parent />, container);
|
||||
expect(console.error.calls.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'Child: `ref` is not a prop. Trying to access it will result ' +
|
||||
'in `undefined` being returned. If you need to access the same ' +
|
||||
'value within the child component, you should pass it as a different ' +
|
||||
@@ -120,9 +164,9 @@ describe('ReactElement', function() {
|
||||
expect(element.type).toBe('div');
|
||||
expect(element.key).toBe(null);
|
||||
expect(element.ref).toBe(null);
|
||||
var expectation = {};
|
||||
Object.freeze(expectation);
|
||||
expect(element.props).toEqual(expectation);
|
||||
expect(Object.isFrozen(element)).toBe(true);
|
||||
expect(Object.isFrozen(element.props)).toBe(true);
|
||||
expect(element.props).toEqual({});
|
||||
});
|
||||
|
||||
it('returns an immutable element', function() {
|
||||
@@ -138,13 +182,19 @@ describe('ReactElement', function() {
|
||||
expect(element.props.foo).toBe(1);
|
||||
});
|
||||
|
||||
it('does not fail if config has no prototype', function() {
|
||||
var config = Object.create(null, {foo: {value: 1, enumerable: true}});
|
||||
var element = React.createFactory(ComponentClass)(config);
|
||||
expect(element.props.foo).toBe(1);
|
||||
});
|
||||
|
||||
it('warns if the config object inherits from any type other than Object', function() {
|
||||
spyOn(console, 'error');
|
||||
React.createElement('div', {foo: 1});
|
||||
expect(console.error).not.toHaveBeenCalled();
|
||||
React.createElement('div', Object.create({foo: 1}));
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'React.createElement(...): Expected props argument to be a plain object. ' +
|
||||
'Properties defined in its prototype chain will be ignored.'
|
||||
);
|
||||
@@ -159,9 +209,45 @@ describe('ReactElement', function() {
|
||||
expect(element.type).toBe(ComponentClass);
|
||||
expect(element.key).toBe('12');
|
||||
expect(element.ref).toBe('34');
|
||||
var expectation = {foo:'56'};
|
||||
Object.freeze(expectation);
|
||||
expect(element.props).toEqual(expectation);
|
||||
expect(Object.isFrozen(element)).toBe(true);
|
||||
expect(Object.isFrozen(element.props)).toBe(true);
|
||||
expect(element.props).toEqual({foo: '56'});
|
||||
});
|
||||
|
||||
it('extracts null key and ref', function() {
|
||||
var element = React.createFactory(ComponentClass)({
|
||||
key: null,
|
||||
ref: null,
|
||||
foo: '12',
|
||||
});
|
||||
expect(element.type).toBe(ComponentClass);
|
||||
expect(element.key).toBe('null');
|
||||
expect(element.ref).toBe(null);
|
||||
expect(Object.isFrozen(element)).toBe(true);
|
||||
expect(Object.isFrozen(element.props)).toBe(true);
|
||||
expect(element.props).toEqual({foo: '12'});
|
||||
});
|
||||
|
||||
it('ignores undefined key and ref', function() {
|
||||
var props = {
|
||||
foo: '56',
|
||||
key: undefined,
|
||||
ref: undefined,
|
||||
};
|
||||
var element = React.createFactory(ComponentClass)(props);
|
||||
expect(element.type).toBe(ComponentClass);
|
||||
expect(element.key).toBe(null);
|
||||
expect(element.ref).toBe(null);
|
||||
expect(Object.isFrozen(element)).toBe(true);
|
||||
expect(Object.isFrozen(element.props)).toBe(true);
|
||||
expect(element.props).toEqual({foo: '56'});
|
||||
});
|
||||
|
||||
it('ignores key and ref warning getters', function() {
|
||||
var elementA = React.createElement('div');
|
||||
var elementB = React.createElement('div', elementA.props);
|
||||
expect(elementB.key).toBe(null);
|
||||
expect(elementB.ref).toBe(null);
|
||||
});
|
||||
|
||||
it('coerces the key to a string', function() {
|
||||
@@ -172,9 +258,9 @@ describe('ReactElement', function() {
|
||||
expect(element.type).toBe(ComponentClass);
|
||||
expect(element.key).toBe('12');
|
||||
expect(element.ref).toBe(null);
|
||||
var expectation = {foo:'56'};
|
||||
Object.freeze(expectation);
|
||||
expect(element.props).toEqual(expectation);
|
||||
expect(Object.isFrozen(element)).toBe(true);
|
||||
expect(Object.isFrozen(element.props)).toBe(true);
|
||||
expect(element.props).toEqual({foo: '56'});
|
||||
});
|
||||
|
||||
it('preserves the owner on the element', function() {
|
||||
@@ -202,7 +288,7 @@ describe('ReactElement', function() {
|
||||
children: 'text',
|
||||
}, a);
|
||||
expect(element.props.children).toBe(a);
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
it('does not override children if no rest args are provided', function() {
|
||||
@@ -211,7 +297,7 @@ describe('ReactElement', function() {
|
||||
children: 'text',
|
||||
});
|
||||
expect(element.props.children).toBe('text');
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
it('overrides children if null is provided as an argument', function() {
|
||||
@@ -220,7 +306,7 @@ describe('ReactElement', function() {
|
||||
children: 'text',
|
||||
}, null);
|
||||
expect(element.props.children).toBe(null);
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
it('merges rest arguments onto the children prop in an array', function() {
|
||||
@@ -230,7 +316,7 @@ describe('ReactElement', function() {
|
||||
var c = 3;
|
||||
var element = React.createFactory(ComponentClass)(null, a, b, c);
|
||||
expect(element.props.children).toEqual([1, 2, 3]);
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
// NOTE: We're explicitly not using JSX here. This is intended to test
|
||||
@@ -254,7 +340,7 @@ describe('ReactElement', function() {
|
||||
|
||||
var element = React.createElement(StaticMethodComponentClass);
|
||||
expect(element.type.someStaticMethod()).toBe('someReturnValue');
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
// NOTE: We're explicitly not using JSX here. This is intended to test
|
||||
@@ -352,29 +438,6 @@ describe('ReactElement', function() {
|
||||
expect(inst2.props.prop).toBe(null);
|
||||
});
|
||||
|
||||
it('should normalize props with default values in cloning', function() {
|
||||
var Component = React.createClass({
|
||||
getDefaultProps: function() {
|
||||
return {prop: 'testKey'};
|
||||
},
|
||||
render: function() {
|
||||
return <span />;
|
||||
},
|
||||
});
|
||||
|
||||
var instance = React.createElement(Component);
|
||||
var clonedInstance = React.cloneElement(instance, {prop: undefined});
|
||||
expect(clonedInstance.props.prop).toBe('testKey');
|
||||
var clonedInstance2 = React.cloneElement(instance, {prop: null});
|
||||
expect(clonedInstance2.props.prop).toBe(null);
|
||||
|
||||
var instance2 = React.createElement(Component, {prop: 'newTestKey'});
|
||||
var cloneInstance3 = React.cloneElement(instance2, {prop: undefined});
|
||||
expect(cloneInstance3.props.prop).toBe('testKey');
|
||||
var cloneInstance4 = React.cloneElement(instance2, {});
|
||||
expect(cloneInstance4.props.prop).toBe('newTestKey');
|
||||
});
|
||||
|
||||
it('throws when changing a prop (in dev) after element creation', function() {
|
||||
var Outer = React.createClass({
|
||||
render: function() {
|
||||
@@ -422,7 +485,7 @@ describe('ReactElement', function() {
|
||||
});
|
||||
var test = ReactTestUtils.renderIntoDocument(<Test value={+undefined} />);
|
||||
expect(test.props.value).toBeNaN();
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
// NOTE: We're explicitly not using JSX here. This is intended to test
|
||||
@@ -565,4 +628,5 @@ describe('comparing jsx vs .createFactory() vs .createElement()', function() {
|
||||
expect(Child.mock.calls[0][0]).toEqual({ foo: 'foo value', children: 'children value' });
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
@@ -16,11 +16,20 @@ var ReactDOM;
|
||||
var ReactTestUtils;
|
||||
|
||||
describe('ReactElementClone', function() {
|
||||
var ComponentClass;
|
||||
|
||||
beforeEach(function() {
|
||||
React = require('React');
|
||||
ReactDOM = require('ReactDOM');
|
||||
ReactTestUtils = require('ReactTestUtils');
|
||||
|
||||
// NOTE: We're explicitly not using JSX here. This is intended to test
|
||||
// classic JS without JSX.
|
||||
ComponentClass = React.createClass({
|
||||
render: function() {
|
||||
return React.createElement('div');
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should clone a DOM component with new props', function() {
|
||||
@@ -71,13 +80,18 @@ describe('ReactElementClone', function() {
|
||||
React.cloneElement('div', {foo: 1});
|
||||
expect(console.error).not.toHaveBeenCalled();
|
||||
React.cloneElement('div', Object.create({foo: 1}));
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'React.cloneElement(...): Expected props argument to be a plain object. ' +
|
||||
'Properties defined in its prototype chain will be ignored.'
|
||||
);
|
||||
});
|
||||
|
||||
it('does not fail if config has no prototype', function() {
|
||||
var config = Object.create(null, {foo: {value: 1, enumerable: true}});
|
||||
React.cloneElement(<div />, config);
|
||||
});
|
||||
|
||||
it('should keep the original ref if it is not overridden', function() {
|
||||
var Grandparent = React.createClass({
|
||||
render: function() {
|
||||
@@ -155,6 +169,18 @@ describe('ReactElementClone', function() {
|
||||
]);
|
||||
});
|
||||
|
||||
it('should override children if undefined is provided as an argument', function() {
|
||||
var element = React.createElement(ComponentClass, {
|
||||
children: 'text',
|
||||
}, undefined);
|
||||
expect(element.props.children).toBe(undefined);
|
||||
|
||||
var element2 = React.cloneElement(React.createElement(ComponentClass, {
|
||||
children: 'text',
|
||||
}), {}, undefined);
|
||||
expect(element2.props.children).toBe(undefined);
|
||||
});
|
||||
|
||||
it('should support keys and refs', function() {
|
||||
var Parent = React.createClass({
|
||||
render: function() {
|
||||
@@ -208,13 +234,36 @@ describe('ReactElementClone', function() {
|
||||
);
|
||||
});
|
||||
|
||||
it('should normalize props with default values', function() {
|
||||
var Component = React.createClass({
|
||||
getDefaultProps: function() {
|
||||
return {prop: 'testKey'};
|
||||
},
|
||||
render: function() {
|
||||
return <span />;
|
||||
},
|
||||
});
|
||||
|
||||
var instance = React.createElement(Component);
|
||||
var clonedInstance = React.cloneElement(instance, {prop: undefined});
|
||||
expect(clonedInstance.props.prop).toBe('testKey');
|
||||
var clonedInstance2 = React.cloneElement(instance, {prop: null});
|
||||
expect(clonedInstance2.props.prop).toBe(null);
|
||||
|
||||
var instance2 = React.createElement(Component, {prop: 'newTestKey'});
|
||||
var cloneInstance3 = React.cloneElement(instance2, {prop: undefined});
|
||||
expect(cloneInstance3.props.prop).toBe('testKey');
|
||||
var cloneInstance4 = React.cloneElement(instance2, {});
|
||||
expect(cloneInstance4.props.prop).toBe('newTestKey');
|
||||
});
|
||||
|
||||
it('warns for keys for arrays of elements in rest args', function() {
|
||||
spyOn(console, 'error');
|
||||
|
||||
React.cloneElement(<div />, null, [<div />, <div />]);
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'Each child in an array or iterator should have a unique "key" prop.'
|
||||
);
|
||||
});
|
||||
@@ -224,7 +273,7 @@ describe('ReactElementClone', function() {
|
||||
|
||||
React.cloneElement(<div />, null, [<div key="#1" />, <div key="#2" />]);
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
it('does not warn when the element is directly in rest args', function() {
|
||||
@@ -232,7 +281,7 @@ describe('ReactElementClone', function() {
|
||||
|
||||
React.cloneElement(<div />, null, <div />, <div />);
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
it('does not warn when the array contains a non-element', function() {
|
||||
@@ -240,7 +289,7 @@ describe('ReactElementClone', function() {
|
||||
|
||||
React.cloneElement(<div />, null, [{}, {}]);
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
it('should check declared prop types after clone', function() {
|
||||
@@ -267,12 +316,62 @@ describe('ReactElementClone', function() {
|
||||
},
|
||||
});
|
||||
ReactTestUtils.renderIntoDocument(React.createElement(GrandParent));
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
'Warning: Failed propType: ' +
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: Failed prop type: ' +
|
||||
'Invalid prop `color` of type `number` supplied to `Component`, ' +
|
||||
'expected `string`. Check the render method of `Parent`.'
|
||||
'expected `string`.\n' +
|
||||
' in Component (created by GrandParent)\n' +
|
||||
' in Parent (created by GrandParent)\n' +
|
||||
' in GrandParent'
|
||||
);
|
||||
});
|
||||
|
||||
it('should ignore key and ref warning getters', function() {
|
||||
var elementA = React.createElement('div');
|
||||
var elementB = React.cloneElement(elementA, elementA.props);
|
||||
expect(elementB.key).toBe(null);
|
||||
expect(elementB.ref).toBe(null);
|
||||
});
|
||||
|
||||
it('should ignore undefined key and ref', function() {
|
||||
var element = React.createFactory(ComponentClass)({
|
||||
key: '12',
|
||||
ref: '34',
|
||||
foo: '56',
|
||||
});
|
||||
var props = {
|
||||
key: undefined,
|
||||
ref: undefined,
|
||||
foo: 'ef',
|
||||
};
|
||||
var clone = React.cloneElement(element, props);
|
||||
expect(clone.type).toBe(ComponentClass);
|
||||
expect(clone.key).toBe('12');
|
||||
expect(clone.ref).toBe('34');
|
||||
expect(Object.isFrozen(element)).toBe(true);
|
||||
expect(Object.isFrozen(element.props)).toBe(true);
|
||||
expect(clone.props).toEqual({foo: 'ef'});
|
||||
});
|
||||
|
||||
it('should extract null key and ref', function() {
|
||||
var element = React.createFactory(ComponentClass)({
|
||||
key: '12',
|
||||
ref: '34',
|
||||
foo: '56',
|
||||
});
|
||||
var props = {
|
||||
key: null,
|
||||
ref: null,
|
||||
foo: 'ef',
|
||||
};
|
||||
var clone = React.cloneElement(element, props);
|
||||
expect(clone.type).toBe(ComponentClass);
|
||||
expect(clone.key).toBe('null');
|
||||
expect(clone.ref).toBe(null);
|
||||
expect(Object.isFrozen(element)).toBe(true);
|
||||
expect(Object.isFrozen(element.props)).toBe(true);
|
||||
expect(clone.props).toEqual({foo: 'ef'});
|
||||
});
|
||||
|
||||
});
|
||||
@@ -19,6 +19,10 @@ var ReactDOM;
|
||||
var ReactTestUtils;
|
||||
|
||||
describe('ReactElementValidator', function() {
|
||||
function normalizeCodeLocInfo(str) {
|
||||
return str.replace(/\(at .+?:\d+\)/g, '(at **)');
|
||||
}
|
||||
|
||||
var ComponentClass;
|
||||
|
||||
beforeEach(function() {
|
||||
@@ -40,8 +44,8 @@ describe('ReactElementValidator', function() {
|
||||
|
||||
Component(null, [Component(), Component()]);
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'Each child in an array or iterator should have a unique "key" prop.'
|
||||
);
|
||||
});
|
||||
@@ -70,8 +74,8 @@ describe('ReactElementValidator', function() {
|
||||
React.createElement(ComponentWrapper)
|
||||
);
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'Each child in an array or iterator should have a unique "key" prop. ' +
|
||||
'Check the render method of `InnerClass`. ' +
|
||||
'It was passed a child from ComponentWrapper. '
|
||||
@@ -94,10 +98,11 @@ describe('ReactElementValidator', function() {
|
||||
];
|
||||
ReactTestUtils.renderIntoDocument(<Anonymous>{divs}</Anonymous>);
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
|
||||
'Warning: Each child in an array or iterator should have a unique ' +
|
||||
'"key" prop. See https://fb.me/react-warning-keys for more information.'
|
||||
'"key" prop. See https://fb.me/react-warning-keys for more information.\n' +
|
||||
' in div (at **)'
|
||||
);
|
||||
});
|
||||
|
||||
@@ -110,11 +115,47 @@ describe('ReactElementValidator', function() {
|
||||
];
|
||||
ReactTestUtils.renderIntoDocument(<div>{divs}</div>);
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
|
||||
'Warning: Each child in an array or iterator should have a unique ' +
|
||||
'"key" prop. Check the top-level render call using <div>. See ' +
|
||||
'https://fb.me/react-warning-keys for more information.'
|
||||
'https://fb.me/react-warning-keys for more information.\n' +
|
||||
' in div (at **)'
|
||||
);
|
||||
});
|
||||
|
||||
it('warns for keys with component stack info', function() {
|
||||
spyOn(console, 'error');
|
||||
|
||||
var Component = React.createClass({
|
||||
render: function() {
|
||||
return <div>{[<div />, <div />]}</div>;
|
||||
},
|
||||
});
|
||||
|
||||
var Parent = React.createClass({
|
||||
render: function() {
|
||||
return React.cloneElement(this.props.child);
|
||||
},
|
||||
});
|
||||
|
||||
var GrandParent = React.createClass({
|
||||
render: function() {
|
||||
return <Parent child={<Component />} />;
|
||||
},
|
||||
});
|
||||
|
||||
ReactTestUtils.renderIntoDocument(<GrandParent />);
|
||||
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
|
||||
'Warning: Each child in an array or iterator should have a unique ' +
|
||||
'"key" prop. Check the render method of `Component`. See ' +
|
||||
'https://fb.me/react-warning-keys for more information.\n' +
|
||||
' in div (at **)\n' +
|
||||
' in Component (at **)\n' +
|
||||
' in Parent (at **)\n' +
|
||||
' in GrandParent (at **)'
|
||||
);
|
||||
});
|
||||
|
||||
@@ -139,7 +180,7 @@ describe('ReactElementValidator', function() {
|
||||
</Wrapper>
|
||||
);
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
it('warns for keys for iterables of elements in rest args', function() {
|
||||
@@ -160,8 +201,8 @@ describe('ReactElementValidator', function() {
|
||||
|
||||
Component(null, iterable);
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'Each child in an array or iterator should have a unique "key" prop.'
|
||||
);
|
||||
});
|
||||
@@ -172,7 +213,7 @@ describe('ReactElementValidator', function() {
|
||||
|
||||
Component(null, [Component({key: '#1'}), Component({key: '#2'})]);
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
it('does not warns for iterable elements with keys', function() {
|
||||
@@ -196,7 +237,7 @@ describe('ReactElementValidator', function() {
|
||||
|
||||
Component(null, iterable);
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
it('does not warn when the element is directly in rest args', function() {
|
||||
@@ -205,7 +246,7 @@ describe('ReactElementValidator', function() {
|
||||
|
||||
Component(null, Component(), Component());
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
it('does not warn when the array contains a non-element', function() {
|
||||
@@ -214,7 +255,7 @@ describe('ReactElementValidator', function() {
|
||||
|
||||
Component(null, [{}, {}]);
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
// TODO: These warnings currently come from the composite component, but
|
||||
@@ -239,10 +280,12 @@ describe('ReactElementValidator', function() {
|
||||
},
|
||||
});
|
||||
ReactTestUtils.renderIntoDocument(React.createElement(ParentComp));
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
'Warning: Failed propType: ' +
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: Failed prop type: ' +
|
||||
'Invalid prop `color` of type `number` supplied to `MyComp`, ' +
|
||||
'expected `string`. Check the render method of `ParentComp`.'
|
||||
'expected `string`.\n' +
|
||||
' in MyComp (created by ParentComp)\n' +
|
||||
' in ParentComp'
|
||||
);
|
||||
});
|
||||
|
||||
@@ -252,29 +295,29 @@ describe('ReactElementValidator', function() {
|
||||
React.createElement(null);
|
||||
React.createElement(true);
|
||||
React.createElement(123);
|
||||
expect(console.error.calls.length).toBe(4);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
expect(console.error.calls.count()).toBe(4);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: React.createElement: type should not be null, undefined, ' +
|
||||
'boolean, or number. It should be a string (for DOM elements) or a ' +
|
||||
'ReactClass (for composite components).'
|
||||
);
|
||||
expect(console.error.argsForCall[1][0]).toBe(
|
||||
expect(console.error.calls.argsFor(1)[0]).toBe(
|
||||
'Warning: React.createElement: type should not be null, undefined, ' +
|
||||
'boolean, or number. It should be a string (for DOM elements) or a ' +
|
||||
'ReactClass (for composite components).'
|
||||
);
|
||||
expect(console.error.argsForCall[2][0]).toBe(
|
||||
expect(console.error.calls.argsFor(2)[0]).toBe(
|
||||
'Warning: React.createElement: type should not be null, undefined, ' +
|
||||
'boolean, or number. It should be a string (for DOM elements) or a ' +
|
||||
'ReactClass (for composite components).'
|
||||
);
|
||||
expect(console.error.argsForCall[3][0]).toBe(
|
||||
expect(console.error.calls.argsFor(3)[0]).toBe(
|
||||
'Warning: React.createElement: type should not be null, undefined, ' +
|
||||
'boolean, or number. It should be a string (for DOM elements) or a ' +
|
||||
'ReactClass (for composite components).'
|
||||
);
|
||||
React.createElement('div');
|
||||
expect(console.error.calls.length).toBe(4);
|
||||
expect(console.error.calls.count()).toBe(4);
|
||||
});
|
||||
|
||||
it('includes the owner name when passing null, undefined, boolean, or number', function() {
|
||||
@@ -286,13 +329,13 @@ describe('ReactElementValidator', function() {
|
||||
});
|
||||
expect(function() {
|
||||
ReactTestUtils.renderIntoDocument(React.createElement(ParentComp));
|
||||
}).toThrow(
|
||||
}).toThrowError(
|
||||
'Element type is invalid: expected a string (for built-in components) ' +
|
||||
'or a class/function (for composite components) but got: null. Check ' +
|
||||
'the render method of `ParentComp`.'
|
||||
);
|
||||
expect(console.error.calls.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: React.createElement: type should not be null, undefined, ' +
|
||||
'boolean, or number. It should be a string (for DOM elements) or a ' +
|
||||
'ReactClass (for composite components). Check the render method of ' +
|
||||
@@ -315,10 +358,11 @@ describe('ReactElementValidator', function() {
|
||||
|
||||
ReactTestUtils.renderIntoDocument(React.createElement(Component));
|
||||
|
||||
expect(console.error.calls.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
'Warning: Failed propType: ' +
|
||||
'Required prop `prop` was not specified in `Component`.'
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: Failed prop type: ' +
|
||||
'Required prop `prop` was not specified in `Component`.\n' +
|
||||
' in Component'
|
||||
);
|
||||
});
|
||||
|
||||
@@ -339,10 +383,11 @@ describe('ReactElementValidator', function() {
|
||||
React.createElement(Component, {prop:null})
|
||||
);
|
||||
|
||||
expect(console.error.calls.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
'Warning: Failed propType: ' +
|
||||
'Required prop `prop` was not specified in `Component`.'
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: Failed prop type: ' +
|
||||
'Required prop `prop` was not specified in `Component`.\n' +
|
||||
' in Component'
|
||||
);
|
||||
});
|
||||
|
||||
@@ -365,16 +410,18 @@ describe('ReactElementValidator', function() {
|
||||
React.createElement(Component, {prop: 42})
|
||||
);
|
||||
|
||||
expect(console.error.calls.length).toBe(2);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
'Warning: Failed propType: ' +
|
||||
'Required prop `prop` was not specified in `Component`.'
|
||||
expect(console.error.calls.count()).toBe(2);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: Failed prop type: ' +
|
||||
'Required prop `prop` was not specified in `Component`.\n' +
|
||||
' in Component'
|
||||
);
|
||||
|
||||
expect(console.error.argsForCall[1][0]).toBe(
|
||||
'Warning: Failed propType: ' +
|
||||
expect(console.error.calls.argsFor(1)[0]).toBe(
|
||||
'Warning: Failed prop type: ' +
|
||||
'Invalid prop `prop` of type `number` supplied to ' +
|
||||
'`Component`, expected `string`.'
|
||||
'`Component`, expected `string`.\n' +
|
||||
' in Component'
|
||||
);
|
||||
|
||||
ReactTestUtils.renderIntoDocument(
|
||||
@@ -382,7 +429,7 @@ describe('ReactElementValidator', function() {
|
||||
);
|
||||
|
||||
// Should not error for strings
|
||||
expect(console.error.calls.length).toBe(2);
|
||||
expect(console.error.calls.count()).toBe(2);
|
||||
});
|
||||
|
||||
it('should warn if a PropType creator is used as a PropType', function() {
|
||||
@@ -401,8 +448,8 @@ describe('ReactElementValidator', function() {
|
||||
React.createElement(Component, {myProp: {value: 'hi'}})
|
||||
);
|
||||
|
||||
expect(console.error.calls.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: Component: type specification of prop `myProp` is invalid; ' +
|
||||
'the type checker function must return `null` or an `Error` but ' +
|
||||
'returned a function. You may have forgotten to pass an argument to ' +
|
||||
@@ -420,14 +467,14 @@ describe('ReactElementValidator', function() {
|
||||
});
|
||||
var TestFactory = React.createFactory(TestComponent);
|
||||
expect(TestFactory.type).toBe(TestComponent);
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: Factory.type is deprecated. Access the class directly before ' +
|
||||
'passing it to createFactory.'
|
||||
);
|
||||
// Warn once, not again
|
||||
expect(TestFactory.type).toBe(TestComponent);
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
});
|
||||
|
||||
it('does not warn when using DOM node as children', function() {
|
||||
@@ -444,7 +491,7 @@ describe('ReactElementValidator', function() {
|
||||
var node = document.createElement('div');
|
||||
// This shouldn't cause a stack overflow or any other problems (#3883)
|
||||
ReactTestUtils.renderIntoDocument(<DOMContainer>{node}</DOMContainer>);
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
it('should not enumerate enumerable numbers (#4776)', function() {
|
||||
@@ -487,8 +534,8 @@ describe('ReactElementValidator', function() {
|
||||
spyOn(console, 'error');
|
||||
var Foo = undefined;
|
||||
void <Foo>{[<div />]}</Foo>;
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: React.createElement: type should not be null, undefined, ' +
|
||||
'boolean, or number. It should be a string (for DOM elements) or a ' +
|
||||
'ReactClass (for composite components).'
|
||||
|
||||
@@ -73,6 +73,7 @@ var ReactPropTypes = {
|
||||
number: createPrimitiveTypeChecker('number'),
|
||||
object: createPrimitiveTypeChecker('object'),
|
||||
string: createPrimitiveTypeChecker('string'),
|
||||
symbol: createPrimitiveTypeChecker('symbol'),
|
||||
|
||||
any: createAnyTypeChecker(),
|
||||
arrayOf: createArrayOfTypeChecker,
|
||||
@@ -406,6 +407,25 @@ function isNode(propValue) {
|
||||
}
|
||||
}
|
||||
|
||||
function isSymbol(propType, propValue) {
|
||||
// Native Symbol.
|
||||
if (propType === 'symbol') {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
|
||||
if (propValue['@@toStringTag'] === 'Symbol') {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Fallback for non-spec compliant Symbols which are polyfilled.
|
||||
if (typeof Symbol === 'function' && propValue instanceof Symbol) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// Equivalent of `typeof` but with special handling for array and regexp.
|
||||
function getPropType(propValue) {
|
||||
var propType = typeof propValue;
|
||||
@@ -418,6 +438,9 @@ function getPropType(propValue) {
|
||||
// passes PropTypes.object.
|
||||
return 'object';
|
||||
}
|
||||
if (isSymbol(propType, propValue)) {
|
||||
return 'symbol';
|
||||
}
|
||||
return propType;
|
||||
}
|
||||
|
||||
|
||||
@@ -80,6 +80,12 @@ describe('ReactPropTypes', function() {
|
||||
'Invalid prop `testProp` of type `object` supplied to ' +
|
||||
'`testComponent`, expected `string`.'
|
||||
);
|
||||
typeCheckFail(
|
||||
PropTypes.string,
|
||||
Symbol(),
|
||||
'Invalid prop `testProp` of type `symbol` supplied to ' +
|
||||
'`testComponent`, expected `string`.'
|
||||
);
|
||||
});
|
||||
|
||||
it('should fail date and regexp correctly', function() {
|
||||
@@ -106,6 +112,7 @@ describe('ReactPropTypes', function() {
|
||||
typeCheckPass(PropTypes.object, {});
|
||||
typeCheckPass(PropTypes.object, new Date());
|
||||
typeCheckPass(PropTypes.object, /please/);
|
||||
typeCheckPass(PropTypes.symbol, Symbol());
|
||||
});
|
||||
|
||||
it('should be implicitly optional and not warn without values', function() {
|
||||
@@ -124,6 +131,7 @@ describe('ReactPropTypes', function() {
|
||||
typeCheckPass(PropTypes.any, 0);
|
||||
typeCheckPass(PropTypes.any, 'str');
|
||||
typeCheckPass(PropTypes.any, []);
|
||||
typeCheckPass(PropTypes.any, Symbol());
|
||||
});
|
||||
|
||||
it('should be implicitly optional and not warn without values', function() {
|
||||
@@ -150,6 +158,7 @@ describe('ReactPropTypes', function() {
|
||||
typeCheckPass(PropTypes.arrayOf(PropTypes.number), [1, 2, 3]);
|
||||
typeCheckPass(PropTypes.arrayOf(PropTypes.string), ['a', 'b', 'c']);
|
||||
typeCheckPass(PropTypes.arrayOf(PropTypes.oneOf(['a', 'b'])), ['a', 'b']);
|
||||
typeCheckPass(PropTypes.arrayOf(PropTypes.symbol), [Symbol(), Symbol()]);
|
||||
});
|
||||
|
||||
it('should support arrayOf with complex types', function() {
|
||||
@@ -262,7 +271,7 @@ describe('ReactPropTypes', function() {
|
||||
var instance = <Component label={<div />} />;
|
||||
instance = ReactTestUtils.renderIntoDocument(instance);
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
it('should warn when passing no label and isRequired is set', () => {
|
||||
@@ -271,7 +280,7 @@ describe('ReactPropTypes', function() {
|
||||
var instance = <Component />;
|
||||
instance = ReactTestUtils.renderIntoDocument(instance);
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
});
|
||||
|
||||
it('should be implicitly optional and not warn without values', function() {
|
||||
@@ -412,7 +421,7 @@ describe('ReactPropTypes', function() {
|
||||
k4: null,
|
||||
k5: undefined,
|
||||
}));
|
||||
expect(console.error.calls).toEqual([]);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
it('should not warn for iterables', function() {
|
||||
@@ -490,6 +499,10 @@ describe('ReactPropTypes', function() {
|
||||
PropTypes.objectOf(PropTypes.oneOf(['a', 'b'])),
|
||||
{a: 'a', b: 'b'}
|
||||
);
|
||||
typeCheckPass(
|
||||
PropTypes.objectOf(PropTypes.symbol),
|
||||
{a: Symbol(), b: Symbol(), c: Symbol()}
|
||||
);
|
||||
});
|
||||
|
||||
it('should support objectOf with complex types', function() {
|
||||
@@ -545,6 +558,12 @@ describe('ReactPropTypes', function() {
|
||||
'Invalid prop `testProp` of type `string` supplied to ' +
|
||||
'`testComponent`, expected an object.'
|
||||
);
|
||||
typeCheckFail(
|
||||
PropTypes.objectOf(PropTypes.symbol),
|
||||
Symbol(),
|
||||
'Invalid prop `testProp` of type `symbol` supplied to ' +
|
||||
'`testComponent`, expected an object.'
|
||||
);
|
||||
});
|
||||
|
||||
it('should not warn when passing an empty object', function() {
|
||||
@@ -782,6 +801,36 @@ describe('ReactPropTypes', function() {
|
||||
});
|
||||
});
|
||||
|
||||
describe('Symbol Type', function() {
|
||||
it('should warn for non-symbol', function() {
|
||||
typeCheckFail(
|
||||
PropTypes.symbol,
|
||||
'hello',
|
||||
'Invalid prop `testProp` of type `string` supplied to ' +
|
||||
'`testComponent`, expected `symbol`.'
|
||||
);
|
||||
typeCheckFail(
|
||||
PropTypes.symbol,
|
||||
function() { },
|
||||
'Invalid prop `testProp` of type `function` supplied to ' +
|
||||
'`testComponent`, expected `symbol`.'
|
||||
);
|
||||
typeCheckFail(
|
||||
PropTypes.symbol,
|
||||
{
|
||||
'@@toStringTag': 'Katana',
|
||||
},
|
||||
'Invalid prop `testProp` of type `object` supplied to ' +
|
||||
'`testComponent`, expected `symbol`.'
|
||||
);
|
||||
});
|
||||
|
||||
it('should not warn for a polyfilled Symbol', function() {
|
||||
var CoreSymbol = require('core-js/library/es6/symbol');
|
||||
typeCheckPass(PropTypes.symbol, CoreSymbol('core-js'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('Custom validator', function() {
|
||||
beforeEach(function() {
|
||||
jest.resetModuleRegistry();
|
||||
@@ -800,9 +849,8 @@ describe('ReactPropTypes', function() {
|
||||
var instance = <Component num={5} />;
|
||||
instance = ReactTestUtils.renderIntoDocument(instance);
|
||||
|
||||
expect(spy.argsForCall.length).toBe(2); // temp double validation
|
||||
expect(spy.argsForCall[0][1]).toBe('num');
|
||||
expect(spy.argsForCall[0][2]).toBe('Component');
|
||||
expect(spy.calls.count()).toBe(1);
|
||||
expect(spy.calls.argsFor(0)[1]).toBe('num');
|
||||
});
|
||||
|
||||
it('should have been called even if the prop is not present', function() {
|
||||
@@ -818,13 +866,13 @@ describe('ReactPropTypes', function() {
|
||||
var instance = <Component bla={5} />;
|
||||
instance = ReactTestUtils.renderIntoDocument(instance);
|
||||
|
||||
expect(spy.argsForCall.length).toBe(2); // temp double validation
|
||||
expect(spy.calls.count()).toBe(1);
|
||||
expect(spy.calls.argsFor(0)[1]).toBe('num');
|
||||
});
|
||||
|
||||
it('should have received the validator\'s return value', function() {
|
||||
spyOn(console, 'error');
|
||||
|
||||
var spy = jasmine.createSpy().andCallFake(
|
||||
var spy = jasmine.createSpy().and.callFake(
|
||||
function(props, propName, componentName) {
|
||||
if (props[propName] !== 5) {
|
||||
return new Error('num must be 5!');
|
||||
@@ -841,17 +889,19 @@ describe('ReactPropTypes', function() {
|
||||
|
||||
var instance = <Component num={6} />;
|
||||
instance = ReactTestUtils.renderIntoDocument(instance);
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
'Warning: Failed propType: num must be 5!'
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(
|
||||
console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)')
|
||||
).toBe(
|
||||
'Warning: Failed prop type: num must be 5!\n' +
|
||||
' in Component (at **)'
|
||||
);
|
||||
});
|
||||
|
||||
it('should not warn if the validator returned null',
|
||||
function() {
|
||||
spyOn(console, 'error');
|
||||
|
||||
var spy = jasmine.createSpy().andCallFake(
|
||||
var spy = jasmine.createSpy().and.callFake(
|
||||
function(props, propName, componentName) {
|
||||
return null;
|
||||
}
|
||||
@@ -866,7 +916,7 @@ describe('ReactPropTypes', function() {
|
||||
|
||||
var instance = <Component num={5} />;
|
||||
instance = ReactTestUtils.renderIntoDocument(instance);
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* 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 checkReactTypeSpec
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var ReactComponentTreeDevtool = require('ReactComponentTreeDevtool');
|
||||
var ReactPropTypeLocationNames = require('ReactPropTypeLocationNames');
|
||||
|
||||
var invariant = require('invariant');
|
||||
var warning = require('warning');
|
||||
|
||||
var loggedTypeFailures = {};
|
||||
|
||||
/**
|
||||
* Assert that the values match with the type specs.
|
||||
* Error messages are memorized and will only be shown once.
|
||||
*
|
||||
* @param {object} typeSpecs Map of name to a ReactPropType
|
||||
* @param {object} values Runtime values that need to be type-checked
|
||||
* @param {string} location e.g. "prop", "context", "child context"
|
||||
* @param {string} componentName Name of the component for error messages.
|
||||
* @param {?object} element The React element that is being type-checked
|
||||
* @param {?number} debugID The React component instance that is being type-checked
|
||||
* @private
|
||||
*/
|
||||
function checkReactTypeSpec(typeSpecs, values, location, componentName, element, debugID) {
|
||||
for (var typeSpecName in typeSpecs) {
|
||||
if (typeSpecs.hasOwnProperty(typeSpecName)) {
|
||||
var error;
|
||||
// Prop type validation may throw. In case they do, we don't want to
|
||||
// fail the render phase where it didn't fail before. So we log it.
|
||||
// After these have been cleaned up, we'll let them throw.
|
||||
try {
|
||||
// This is intentionally an invariant that gets caught. It's the same
|
||||
// behavior as without this statement except with a better message.
|
||||
invariant(
|
||||
typeof typeSpecs[typeSpecName] === 'function',
|
||||
'%s: %s type `%s` is invalid; it must be a function, usually from ' +
|
||||
'React.PropTypes.',
|
||||
componentName || 'React class',
|
||||
ReactPropTypeLocationNames[location],
|
||||
typeSpecName
|
||||
);
|
||||
error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location);
|
||||
} catch (ex) {
|
||||
error = ex;
|
||||
}
|
||||
warning(
|
||||
!error || error instanceof Error,
|
||||
'%s: type specification of %s `%s` is invalid; the type checker ' +
|
||||
'function must return `null` or an `Error` but returned a %s. ' +
|
||||
'You may have forgotten to pass an argument to the type checker ' +
|
||||
'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +
|
||||
'shape all require an argument).',
|
||||
componentName || 'React class',
|
||||
ReactPropTypeLocationNames[location],
|
||||
typeSpecName,
|
||||
typeof error
|
||||
);
|
||||
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
|
||||
// Only monitor this failure once because there tends to be a lot of the
|
||||
// same error.
|
||||
loggedTypeFailures[error.message] = true;
|
||||
|
||||
var componentStackInfo = '';
|
||||
|
||||
if (debugID !== null) {
|
||||
componentStackInfo = ReactComponentTreeDevtool.getStackAddendumByID(debugID);
|
||||
} else if (element !== null) {
|
||||
componentStackInfo = ReactComponentTreeDevtool.getCurrentStackAddendum(element);
|
||||
}
|
||||
|
||||
warning(
|
||||
false,
|
||||
'Failed %s type: %s%s',
|
||||
location,
|
||||
error.message,
|
||||
componentStackInfo
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = checkReactTypeSpec;
|
||||
@@ -12,7 +12,6 @@
|
||||
'use strict';
|
||||
|
||||
var ReactNoopUpdateQueue = require('ReactNoopUpdateQueue');
|
||||
var ReactInstrumentation = require('ReactInstrumentation');
|
||||
|
||||
var canDefineProperty = require('canDefineProperty');
|
||||
var emptyObject = require('emptyObject');
|
||||
@@ -66,14 +65,6 @@ ReactComponent.prototype.setState = function(partialState, callback) {
|
||||
'setState(...): takes an object of state variables to update or a ' +
|
||||
'function which returns an object of state variables.'
|
||||
);
|
||||
if (__DEV__) {
|
||||
ReactInstrumentation.debugTool.onSetState();
|
||||
warning(
|
||||
partialState != null,
|
||||
'setState(...): You passed an undefined or null state object; ' +
|
||||
'instead, use forceUpdate().'
|
||||
);
|
||||
}
|
||||
this.updater.enqueueSetState(this, partialState);
|
||||
if (callback) {
|
||||
this.updater.enqueueCallback(this, callback, 'setState');
|
||||
|
||||
@@ -11,24 +11,62 @@
|
||||
|
||||
'use strict';
|
||||
|
||||
var MetaMatchers = require('MetaMatchers');
|
||||
var spawnSync = require('child_process').spawnSync;
|
||||
var path = require('path');
|
||||
|
||||
describe('ReactClassEquivalence', function() {
|
||||
|
||||
beforeEach(function() {
|
||||
this.addMatchers(MetaMatchers);
|
||||
});
|
||||
|
||||
var es6 = () => require('./ReactES6Class-test.js');
|
||||
var coffee = () => require('./ReactCoffeeScriptClass-test.coffee');
|
||||
var ts = () => require('./ReactTypeScriptClass-test.ts');
|
||||
|
||||
it('tests the same thing for es6 classes and CoffeeScript', function() {
|
||||
expect(coffee).toEqualSpecsIn(es6);
|
||||
var result1 = runJest('ReactCoffeeScriptClass-test.coffee');
|
||||
var result2 = runJest('ReactES6Class-test.js');
|
||||
compareResults(result1, result2);
|
||||
});
|
||||
|
||||
it('tests the same thing for es6 classes and TypeScript', function() {
|
||||
expect(ts).toEqualSpecsIn(es6);
|
||||
var result1 = runJest('ReactTypeScriptClass-test.ts');
|
||||
var result2 = runJest('ReactES6Class-test.js');
|
||||
compareResults(result1, result2);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
function runJest(testFile) {
|
||||
var cwd = process.cwd();
|
||||
var jestBin = path.resolve('node_modules', '.bin', 'jest');
|
||||
var setupFile = path.resolve(__dirname, 'setupSpecEquivalenceReporter.js');
|
||||
var result = spawnSync('node', [
|
||||
jestBin,
|
||||
testFile,
|
||||
'--setupTestFrameworkScriptFile',
|
||||
setupFile,
|
||||
], {cwd});
|
||||
|
||||
if (result.error) {
|
||||
throw result.error;
|
||||
}
|
||||
|
||||
if (result.status !== 0) {
|
||||
throw new Error(
|
||||
'jest process exited with: ' +
|
||||
result.status +
|
||||
'\n' +
|
||||
'stdout: ' +
|
||||
result.stdout.toString() +
|
||||
'stderr: ' +
|
||||
result.stderr.toString()
|
||||
);
|
||||
}
|
||||
|
||||
return result.stdout.toString();
|
||||
}
|
||||
|
||||
function compareResults(a, b) {
|
||||
var regexp = /^EQUIVALENCE.*$/gm;
|
||||
var aSpecs = (a.match(regexp) || []).sort().join('\n');
|
||||
var bSpecs = (b.match(regexp) || []).sort().join('\n');
|
||||
|
||||
if (aSpecs.length === 0 && bSpecs.length === 0) {
|
||||
throw new Error('No spec results found in the output');
|
||||
}
|
||||
|
||||
expect(aSpecs).toEqual(bSpecs);
|
||||
}
|
||||
@@ -51,8 +51,9 @@ describe 'ReactCoffeeScriptClass', ->
|
||||
expect(->
|
||||
ReactDOM.render React.createElement(Foo), container
|
||||
).toThrow()
|
||||
expect(console.error.calls.length).toBe(1)
|
||||
expect(console.error.argsForCall[0][0]).toContain('No `render` method found on the returned component instance')
|
||||
expect(console.error.calls.count()).toBe(1)
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain('No `render` method found on the returned component instance')
|
||||
undefined
|
||||
|
||||
it 'renders a simple stateless component with prop', ->
|
||||
class Foo extends React.Component
|
||||
@@ -62,6 +63,7 @@ describe 'ReactCoffeeScriptClass', ->
|
||||
|
||||
test React.createElement(Foo, bar: 'foo'), 'DIV', 'foo'
|
||||
test React.createElement(Foo, bar: 'bar'), 'DIV', 'bar'
|
||||
undefined
|
||||
|
||||
it 'renders based on state using initial values in this.props', ->
|
||||
class Foo extends React.Component
|
||||
@@ -74,6 +76,7 @@ describe 'ReactCoffeeScriptClass', ->
|
||||
className: @state.bar
|
||||
|
||||
test React.createElement(Foo, initialValue: 'foo'), 'SPAN', 'foo'
|
||||
undefined
|
||||
|
||||
it 'renders based on state using props in the constructor', ->
|
||||
class Foo extends React.Component
|
||||
@@ -94,6 +97,7 @@ describe 'ReactCoffeeScriptClass', ->
|
||||
instance = test React.createElement(Foo, initialValue: 'foo'), 'DIV', 'foo'
|
||||
instance.changeState()
|
||||
test React.createElement(Foo), 'SPAN', 'bar'
|
||||
undefined
|
||||
|
||||
it 'renders based on context in the constructor', ->
|
||||
class Foo extends React.Component
|
||||
@@ -125,6 +129,7 @@ describe 'ReactCoffeeScriptClass', ->
|
||||
React.createElement Foo
|
||||
|
||||
test React.createElement(Outer), 'SPAN', 'foo'
|
||||
undefined
|
||||
|
||||
it 'renders only once when setting state in componentWillMount', ->
|
||||
renderCount = 0
|
||||
@@ -141,6 +146,7 @@ describe 'ReactCoffeeScriptClass', ->
|
||||
|
||||
test React.createElement(Foo, initialValue: 'foo'), 'SPAN', 'bar'
|
||||
expect(renderCount).toBe 1
|
||||
undefined
|
||||
|
||||
it 'should throw with non-object in the initial state property', ->
|
||||
[['an array'], 'a string', 1234].forEach (state) ->
|
||||
@@ -153,9 +159,10 @@ describe 'ReactCoffeeScriptClass', ->
|
||||
|
||||
expect(->
|
||||
test React.createElement(Foo), 'span', ''
|
||||
).toThrow(
|
||||
).toThrowError(
|
||||
'Foo.state: must be set to an object or null'
|
||||
)
|
||||
undefined
|
||||
|
||||
it 'should render with null in the initial state property', ->
|
||||
class Foo extends React.Component
|
||||
@@ -166,6 +173,7 @@ describe 'ReactCoffeeScriptClass', ->
|
||||
span()
|
||||
|
||||
test React.createElement(Foo), 'SPAN', ''
|
||||
undefined
|
||||
|
||||
it 'setState through an event handler', ->
|
||||
class Foo extends React.Component
|
||||
@@ -183,6 +191,7 @@ describe 'ReactCoffeeScriptClass', ->
|
||||
test React.createElement(Foo, initialValue: 'foo'), 'DIV', 'foo'
|
||||
attachedListener()
|
||||
expect(renderedName).toBe 'bar'
|
||||
undefined
|
||||
|
||||
it 'should not implicitly bind event handlers', ->
|
||||
class Foo extends React.Component
|
||||
@@ -199,6 +208,7 @@ describe 'ReactCoffeeScriptClass', ->
|
||||
|
||||
test React.createElement(Foo, initialValue: 'foo'), 'DIV', 'foo'
|
||||
expect(attachedListener).toThrow()
|
||||
undefined
|
||||
|
||||
it 'renders using forceUpdate even when there is no state', ->
|
||||
class Foo extends React.Component
|
||||
@@ -217,6 +227,7 @@ describe 'ReactCoffeeScriptClass', ->
|
||||
test React.createElement(Foo, initialValue: 'foo'), 'DIV', 'foo'
|
||||
attachedListener()
|
||||
expect(renderedName).toBe 'bar'
|
||||
undefined
|
||||
|
||||
it 'will call all the normal life cycle methods', ->
|
||||
lifeCycles = []
|
||||
@@ -266,6 +277,7 @@ describe 'ReactCoffeeScriptClass', ->
|
||||
lifeCycles = [] # reset
|
||||
ReactDOM.unmountComponentAtNode container
|
||||
expect(lifeCycles).toEqual ['will-unmount']
|
||||
undefined
|
||||
|
||||
it 'warns when classic properties are defined on the instance,
|
||||
but does not invoke them.', ->
|
||||
@@ -292,19 +304,20 @@ describe 'ReactCoffeeScriptClass', ->
|
||||
test React.createElement(Foo), 'SPAN', 'foo'
|
||||
expect(getInitialStateWasCalled).toBe false
|
||||
expect(getDefaultPropsWasCalled).toBe false
|
||||
expect(console.error.calls.length).toBe 4
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe 4
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'getInitialState was defined on Foo, a plain JavaScript class.'
|
||||
)
|
||||
expect(console.error.argsForCall[1][0]).toContain(
|
||||
expect(console.error.calls.argsFor(1)[0]).toContain(
|
||||
'getDefaultProps was defined on Foo, a plain JavaScript class.'
|
||||
)
|
||||
expect(console.error.argsForCall[2][0]).toContain(
|
||||
expect(console.error.calls.argsFor(2)[0]).toContain(
|
||||
'propTypes was defined as an instance property on Foo.'
|
||||
)
|
||||
expect(console.error.argsForCall[3][0]).toContain(
|
||||
expect(console.error.calls.argsFor(3)[0]).toContain(
|
||||
'contextTypes was defined as an instance property on Foo.'
|
||||
)
|
||||
undefined
|
||||
|
||||
it 'should warn when misspelling shouldComponentUpdate', ->
|
||||
spyOn console, 'error'
|
||||
@@ -317,12 +330,13 @@ describe 'ReactCoffeeScriptClass', ->
|
||||
className: 'foo'
|
||||
|
||||
test React.createElement(NamedComponent), 'SPAN', 'foo'
|
||||
expect(console.error.calls.length).toBe 1
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
expect(console.error.calls.count()).toBe 1
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: NamedComponent has a method called componentShouldUpdate().
|
||||
Did you mean shouldComponentUpdate()? The name is phrased as a
|
||||
question because the function is expected to return a value.'
|
||||
)
|
||||
undefined
|
||||
|
||||
it 'should warn when misspelling componentWillReceiveProps', ->
|
||||
spyOn console, 'error'
|
||||
@@ -335,11 +349,12 @@ describe 'ReactCoffeeScriptClass', ->
|
||||
className: 'foo'
|
||||
|
||||
test React.createElement(NamedComponent), 'SPAN', 'foo'
|
||||
expect(console.error.calls.length).toBe 1
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
expect(console.error.calls.count()).toBe 1
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: NamedComponent has a method called componentWillRecieveProps().
|
||||
Did you mean componentWillReceiveProps()?'
|
||||
)
|
||||
undefined
|
||||
|
||||
it 'should throw AND warn when trying to access classic APIs', ->
|
||||
spyOn console, 'error'
|
||||
@@ -349,13 +364,14 @@ describe 'ReactCoffeeScriptClass', ->
|
||||
expect(-> instance.isMounted()).toThrow()
|
||||
expect(-> instance.setProps name: 'bar').toThrow()
|
||||
expect(-> instance.replaceProps name: 'bar').toThrow()
|
||||
expect(console.error.calls.length).toBe 2
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe 2
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'replaceState(...) is deprecated in plain JavaScript React classes'
|
||||
)
|
||||
expect(console.error.argsForCall[1][0]).toContain(
|
||||
expect(console.error.calls.argsFor(1)[0]).toContain(
|
||||
'isMounted(...) is deprecated in plain JavaScript React classes'
|
||||
)
|
||||
undefined
|
||||
|
||||
it 'supports this.context passed via getChildContext', ->
|
||||
class Bar extends React.Component
|
||||
@@ -373,6 +389,7 @@ describe 'ReactCoffeeScriptClass', ->
|
||||
React.createElement Bar
|
||||
|
||||
test React.createElement(Foo), 'DIV', 'bar-through-context'
|
||||
undefined
|
||||
|
||||
it 'supports classic refs', ->
|
||||
class Foo extends React.Component
|
||||
@@ -383,8 +400,10 @@ describe 'ReactCoffeeScriptClass', ->
|
||||
|
||||
instance = test(React.createElement(Foo), 'DIV', 'foo')
|
||||
expect(instance.refs.inner.getName()).toBe 'foo'
|
||||
undefined
|
||||
|
||||
it 'supports drilling through to the DOM using findDOMNode', ->
|
||||
instance = test Inner(name: 'foo'), 'DIV', 'foo'
|
||||
node = ReactDOM.findDOMNode(instance)
|
||||
expect(node).toBe container.firstChild
|
||||
undefined
|
||||
@@ -61,8 +61,8 @@ describe('ReactES6Class', function() {
|
||||
class Foo extends React.Component { }
|
||||
expect(() => ReactDOM.render(<Foo />, container)).toThrow();
|
||||
|
||||
expect(console.error.calls.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: Foo(...): No `render` method found on the returned component ' +
|
||||
'instance: you may have forgotten to define `render`.'
|
||||
);
|
||||
@@ -173,7 +173,7 @@ describe('ReactES6Class', function() {
|
||||
return <span />;
|
||||
}
|
||||
}
|
||||
expect(() => test(<Foo />, 'span', '')).toThrow(
|
||||
expect(() => test(<Foo />, 'span', '')).toThrowError(
|
||||
'Foo.state: must be set to an object or null'
|
||||
);
|
||||
});
|
||||
@@ -339,17 +339,17 @@ describe('ReactES6Class', function() {
|
||||
test(<Foo />, 'SPAN', 'foo');
|
||||
expect(getInitialStateWasCalled).toBe(false);
|
||||
expect(getDefaultPropsWasCalled).toBe(false);
|
||||
expect(console.error.calls.length).toBe(4);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(4);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'getInitialState was defined on Foo, a plain JavaScript class.'
|
||||
);
|
||||
expect(console.error.argsForCall[1][0]).toContain(
|
||||
expect(console.error.calls.argsFor(1)[0]).toContain(
|
||||
'getDefaultProps was defined on Foo, a plain JavaScript class.'
|
||||
);
|
||||
expect(console.error.argsForCall[2][0]).toContain(
|
||||
expect(console.error.calls.argsFor(2)[0]).toContain(
|
||||
'propTypes was defined as an instance property on Foo.'
|
||||
);
|
||||
expect(console.error.argsForCall[3][0]).toContain(
|
||||
expect(console.error.calls.argsFor(3)[0]).toContain(
|
||||
'contextTypes was defined as an instance property on Foo.'
|
||||
);
|
||||
});
|
||||
@@ -367,8 +367,8 @@ describe('ReactES6Class', function() {
|
||||
}
|
||||
test(<NamedComponent />, 'SPAN', 'foo');
|
||||
|
||||
expect(console.error.calls.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: ' +
|
||||
'NamedComponent has a method called componentShouldUpdate(). Did you ' +
|
||||
'mean shouldComponentUpdate()? The name is phrased as a question ' +
|
||||
@@ -389,8 +389,8 @@ describe('ReactES6Class', function() {
|
||||
}
|
||||
test(<NamedComponent />, 'SPAN', 'foo');
|
||||
|
||||
expect(console.error.calls.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: ' +
|
||||
'NamedComponent has a method called componentWillRecieveProps(). Did ' +
|
||||
'you mean componentWillReceiveProps()?'
|
||||
@@ -404,11 +404,11 @@ describe('ReactES6Class', function() {
|
||||
expect(() => instance.isMounted()).toThrow();
|
||||
expect(() => instance.setProps({name: 'bar'})).toThrow();
|
||||
expect(() => instance.replaceProps({name: 'bar'})).toThrow();
|
||||
expect(console.error.calls.length).toBe(2);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(2);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'replaceState(...) is deprecated in plain JavaScript React classes'
|
||||
);
|
||||
expect(console.error.argsForCall[1][0]).toContain(
|
||||
expect(console.error.calls.argsFor(1)[0]).toContain(
|
||||
'isMounted(...) is deprecated in plain JavaScript React classes'
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
/// <reference path="../React.d.ts" />
|
||||
/// <reference path="../ReactDOM.d.ts" />
|
||||
|
||||
/*!
|
||||
* Copyright 2015-present, Facebook, Inc.
|
||||
* All rights reserved.
|
||||
@@ -316,8 +319,8 @@ describe('ReactTypeScriptClass', function() {
|
||||
|
||||
expect(() => ReactDOM.render(React.createElement(Empty), container)).toThrow();
|
||||
|
||||
expect((<any>console.error).argsForCall.length).toBe(1);
|
||||
expect((<any>console.error).argsForCall[0][0]).toBe(
|
||||
expect((<any>console.error).calls.count()).toBe(1);
|
||||
expect((<any>console.error).calls.argsFor(0)[0]).toBe(
|
||||
'Warning: Empty(...): No `render` method found on the returned ' +
|
||||
'component instance: you may have forgotten to define `render`.'
|
||||
);
|
||||
@@ -358,15 +361,15 @@ describe('ReactTypeScriptClass', function() {
|
||||
|
||||
it('should throw with non-object in the initial state property', function() {
|
||||
expect(() => test(React.createElement(ArrayState), 'span', ''))
|
||||
.toThrow(
|
||||
.toThrowError(
|
||||
'ArrayState.state: must be set to an object or null'
|
||||
);
|
||||
expect(() => test(React.createElement(StringState), 'span', ''))
|
||||
.toThrow(
|
||||
.toThrowError(
|
||||
'StringState.state: must be set to an object or null'
|
||||
);
|
||||
expect(() => test(React.createElement(NumberState), 'span', ''))
|
||||
.toThrow(
|
||||
.toThrowError(
|
||||
'NumberState.state: must be set to an object or null'
|
||||
);
|
||||
});
|
||||
@@ -434,19 +437,19 @@ describe('ReactTypeScriptClass', function() {
|
||||
test(React.createElement(ClassicProperties), 'SPAN', 'foo');
|
||||
expect(getInitialStateWasCalled).toBe(false);
|
||||
expect(getDefaultPropsWasCalled).toBe(false);
|
||||
expect((<any>console.error).argsForCall.length).toBe(4);
|
||||
expect((<any>console.error).argsForCall[0][0]).toContain(
|
||||
expect((<any>console.error).calls.count()).toBe(4);
|
||||
expect((<any>console.error).calls.argsFor(0)[0]).toContain(
|
||||
'getInitialState was defined on ClassicProperties, ' +
|
||||
'a plain JavaScript class.'
|
||||
);
|
||||
expect((<any>console.error).argsForCall[1][0]).toContain(
|
||||
expect((<any>console.error).calls.argsFor(1)[0]).toContain(
|
||||
'getDefaultProps was defined on ClassicProperties, ' +
|
||||
'a plain JavaScript class.'
|
||||
);
|
||||
expect((<any>console.error).argsForCall[2][0]).toContain(
|
||||
expect((<any>console.error).calls.argsFor(2)[0]).toContain(
|
||||
'propTypes was defined as an instance property on ClassicProperties.'
|
||||
);
|
||||
expect((<any>console.error).argsForCall[3][0]).toContain(
|
||||
expect((<any>console.error).calls.argsFor(3)[0]).toContain(
|
||||
'contextTypes was defined as an instance property on ClassicProperties.'
|
||||
);
|
||||
});
|
||||
@@ -456,8 +459,8 @@ describe('ReactTypeScriptClass', function() {
|
||||
|
||||
test(React.createElement(MisspelledComponent1), 'SPAN', 'foo');
|
||||
|
||||
expect((<any>console.error).argsForCall.length).toBe(1);
|
||||
expect((<any>console.error).argsForCall[0][0]).toBe(
|
||||
expect((<any>console.error).calls.count()).toBe(1);
|
||||
expect((<any>console.error).calls.argsFor(0)[0]).toBe(
|
||||
'Warning: ' +
|
||||
'MisspelledComponent1 has a method called componentShouldUpdate(). Did ' +
|
||||
'you mean shouldComponentUpdate()? The name is phrased as a question ' +
|
||||
@@ -470,8 +473,8 @@ describe('ReactTypeScriptClass', function() {
|
||||
|
||||
test(React.createElement(MisspelledComponent2), 'SPAN', 'foo');
|
||||
|
||||
expect((<any>console.error).argsForCall.length).toBe(1);
|
||||
expect((<any>console.error).argsForCall[0][0]).toBe(
|
||||
expect((<any>console.error).calls.count()).toBe(1);
|
||||
expect((<any>console.error).calls.argsFor(0)[0]).toBe(
|
||||
'Warning: ' +
|
||||
'MisspelledComponent2 has a method called componentWillRecieveProps(). ' +
|
||||
'Did you mean componentWillReceiveProps()?'
|
||||
@@ -488,11 +491,11 @@ describe('ReactTypeScriptClass', function() {
|
||||
expect(() => instance.isMounted()).toThrow();
|
||||
expect(() => instance.setProps({ name: 'bar' })).toThrow();
|
||||
expect(() => instance.replaceProps({ name: 'bar' })).toThrow();
|
||||
expect((<any>console.error).argsForCall.length).toBe(2);
|
||||
expect((<any>console.error).argsForCall[0][0]).toContain(
|
||||
expect((<any>console.error).calls.count()).toBe(2);
|
||||
expect((<any>console.error).calls.argsFor(0)[0]).toContain(
|
||||
'replaceState(...) is deprecated in plain JavaScript React classes'
|
||||
);
|
||||
expect((<any>console.error).argsForCall[1][0]).toContain(
|
||||
expect((<any>console.error).calls.argsFor(1)[0]).toContain(
|
||||
'isMounted(...) is deprecated in plain JavaScript React classes'
|
||||
);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
/*!
|
||||
* Copyright 2015-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.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
var expect = global.expect;
|
||||
|
||||
var numExpectations = 0;
|
||||
|
||||
global.expect = function() {
|
||||
numExpectations += 1;
|
||||
return expect.apply(this, arguments);
|
||||
};
|
||||
|
||||
beforeEach(() => numExpectations = 0);
|
||||
|
||||
jasmine.currentEnv_.addReporter({
|
||||
specDone: (spec) => {
|
||||
console.log(
|
||||
`EQUIVALENCE: ${spec.description}, ` +
|
||||
`status: ${spec.status}, ` +
|
||||
`numExpectations: ${numExpectations}`
|
||||
);
|
||||
},
|
||||
});
|
||||
@@ -100,21 +100,33 @@ describe('ReactJSXElement', function() {
|
||||
var a = 1;
|
||||
var element = <Component children="text">{a}</Component>;
|
||||
expect(element.props.children).toBe(a);
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
it('does not override children if no JSX children are provided', function() {
|
||||
spyOn(console, 'error');
|
||||
var element = <Component children="text" />;
|
||||
expect(element.props.children).toBe('text');
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
it('overrides children if null is provided as a JSX child', function() {
|
||||
spyOn(console, 'error');
|
||||
var element = <Component children="text">{null}</Component>;
|
||||
expect(element.props.children).toBe(null);
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
it('overrides children if undefined is provided as an argument', function() {
|
||||
var element = <Component children="text">{undefined}</Component>;
|
||||
expect(element.props.children).toBe(undefined);
|
||||
|
||||
var element2 = React.cloneElement(
|
||||
<Component children="text" />,
|
||||
{},
|
||||
undefined
|
||||
);
|
||||
expect(element2.props.children).toBe(undefined);
|
||||
});
|
||||
|
||||
it('merges JSX children onto the children prop in an array', function() {
|
||||
@@ -124,7 +136,7 @@ describe('ReactJSXElement', function() {
|
||||
var c = 3;
|
||||
var element = <Component>{a}{b}{c}</Component>;
|
||||
expect(element.props.children).toEqual([1, 2, 3]);
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
it('allows static methods to be called using the type property', function() {
|
||||
@@ -141,7 +153,7 @@ describe('ReactJSXElement', function() {
|
||||
|
||||
var element = <StaticMethodComponent />;
|
||||
expect(element.type.someStaticMethod()).toBe('someReturnValue');
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
it('identifies valid elements', function() {
|
||||
|
||||
@@ -47,8 +47,8 @@ describe('ReactJSXElementValidator', function() {
|
||||
|
||||
void <Component>{[<Component />, <Component />]}</Component>;
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'Each child in an array or iterator should have a unique "key" prop.'
|
||||
);
|
||||
});
|
||||
@@ -74,8 +74,8 @@ describe('ReactJSXElementValidator', function() {
|
||||
|
||||
ReactTestUtils.renderIntoDocument(<ComponentWrapper />);
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'Each child in an array or iterator should have a unique "key" prop. ' +
|
||||
'Check the render method of `InnerComponent`. ' +
|
||||
'It was passed a child from ComponentWrapper. '
|
||||
@@ -99,8 +99,8 @@ describe('ReactJSXElementValidator', function() {
|
||||
|
||||
void <Component>{iterable}</Component>;
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'Each child in an array or iterator should have a unique "key" prop.'
|
||||
);
|
||||
});
|
||||
@@ -110,7 +110,7 @@ describe('ReactJSXElementValidator', function() {
|
||||
|
||||
void <Component>{[<Component key="#1" />, <Component key="#2" />]}</Component>;
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
it('does not warns for iterable elements with keys', function() {
|
||||
@@ -133,7 +133,7 @@ describe('ReactJSXElementValidator', function() {
|
||||
|
||||
void <Component>{iterable}</Component>;
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
it('does not warn for numeric keys in entry iterable as a child', function() {
|
||||
@@ -154,7 +154,7 @@ describe('ReactJSXElementValidator', function() {
|
||||
|
||||
void <Component>{iterable}</Component>;
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
it('does not warn when the element is directly as children', function() {
|
||||
@@ -162,7 +162,7 @@ describe('ReactJSXElementValidator', function() {
|
||||
|
||||
void <Component><Component /><Component /></Component>;
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
it('does not warn when the child array contains non-elements', function() {
|
||||
@@ -170,7 +170,7 @@ describe('ReactJSXElementValidator', function() {
|
||||
|
||||
void <Component>{[{}, {}]}</Component>;
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
// TODO: These warnings currently come from the composite component, but
|
||||
@@ -195,10 +195,14 @@ describe('ReactJSXElementValidator', function() {
|
||||
}
|
||||
}
|
||||
ReactTestUtils.renderIntoDocument(<ParentComp />);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
'Warning: Failed propType: ' +
|
||||
expect(
|
||||
console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)')
|
||||
).toBe(
|
||||
'Warning: Failed prop type: ' +
|
||||
'Invalid prop `color` of type `number` supplied to `MyComp`, ' +
|
||||
'expected `string`. Check the render method of `ParentComp`.'
|
||||
'expected `string`.\n' +
|
||||
' in MyComp (at **)\n' +
|
||||
' in ParentComp (at **)'
|
||||
);
|
||||
});
|
||||
|
||||
@@ -213,25 +217,25 @@ describe('ReactJSXElementValidator', function() {
|
||||
void <Null />;
|
||||
void <True />;
|
||||
void <Num />;
|
||||
expect(console.error.calls.length).toBe(4);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(4);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'type should not be null, undefined, boolean, or number. It should be ' +
|
||||
'a string (for DOM elements) or a ReactClass (for composite components).'
|
||||
);
|
||||
expect(console.error.argsForCall[1][0]).toContain(
|
||||
expect(console.error.calls.argsFor(1)[0]).toContain(
|
||||
'type should not be null, undefined, boolean, or number. It should be ' +
|
||||
'a string (for DOM elements) or a ReactClass (for composite components).'
|
||||
);
|
||||
expect(console.error.argsForCall[2][0]).toContain(
|
||||
expect(console.error.calls.argsFor(2)[0]).toContain(
|
||||
'type should not be null, undefined, boolean, or number. It should be ' +
|
||||
'a string (for DOM elements) or a ReactClass (for composite components).'
|
||||
);
|
||||
expect(console.error.argsForCall[3][0]).toContain(
|
||||
expect(console.error.calls.argsFor(3)[0]).toContain(
|
||||
'type should not be null, undefined, boolean, or number. It should be ' +
|
||||
'a string (for DOM elements) or a ReactClass (for composite components).'
|
||||
);
|
||||
void <Div />;
|
||||
expect(console.error.calls.length).toBe(4);
|
||||
expect(console.error.calls.count()).toBe(4);
|
||||
});
|
||||
|
||||
it('should check default prop values', function() {
|
||||
@@ -241,10 +245,13 @@ describe('ReactJSXElementValidator', function() {
|
||||
|
||||
ReactTestUtils.renderIntoDocument(<RequiredPropComponent />);
|
||||
|
||||
expect(console.error.calls.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
'Warning: Failed propType: ' +
|
||||
'Required prop `prop` was not specified in `RequiredPropComponent`.'
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(
|
||||
console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)')
|
||||
).toBe(
|
||||
'Warning: Failed prop type: ' +
|
||||
'Required prop `prop` was not specified in `RequiredPropComponent`.\n' +
|
||||
' in RequiredPropComponent (at **)'
|
||||
);
|
||||
});
|
||||
|
||||
@@ -253,10 +260,13 @@ describe('ReactJSXElementValidator', function() {
|
||||
|
||||
ReactTestUtils.renderIntoDocument(<RequiredPropComponent prop={null} />);
|
||||
|
||||
expect(console.error.calls.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
'Warning: Failed propType: ' +
|
||||
'Required prop `prop` was not specified in `RequiredPropComponent`.'
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(
|
||||
console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)')
|
||||
).toBe(
|
||||
'Warning: Failed prop type: ' +
|
||||
'Required prop `prop` was not specified in `RequiredPropComponent`.\n' +
|
||||
' in RequiredPropComponent (at **)'
|
||||
);
|
||||
});
|
||||
|
||||
@@ -266,22 +276,28 @@ describe('ReactJSXElementValidator', function() {
|
||||
ReactTestUtils.renderIntoDocument(<RequiredPropComponent />);
|
||||
ReactTestUtils.renderIntoDocument(<RequiredPropComponent prop={42} />);
|
||||
|
||||
expect(console.error.calls.length).toBe(2);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
'Warning: Failed propType: ' +
|
||||
'Required prop `prop` was not specified in `RequiredPropComponent`.'
|
||||
expect(console.error.calls.count()).toBe(2);
|
||||
expect(
|
||||
console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)')
|
||||
).toBe(
|
||||
'Warning: Failed prop type: ' +
|
||||
'Required prop `prop` was not specified in `RequiredPropComponent`.\n' +
|
||||
' in RequiredPropComponent (at **)'
|
||||
);
|
||||
|
||||
expect(console.error.argsForCall[1][0]).toBe(
|
||||
'Warning: Failed propType: ' +
|
||||
expect(
|
||||
console.error.calls.argsFor(1)[0].replace(/\(at .+?:\d+\)/g, '(at **)')
|
||||
).toBe(
|
||||
'Warning: Failed prop type: ' +
|
||||
'Invalid prop `prop` of type `number` supplied to ' +
|
||||
'`RequiredPropComponent`, expected `string`.'
|
||||
'`RequiredPropComponent`, expected `string`.\n' +
|
||||
' in RequiredPropComponent (at **)'
|
||||
);
|
||||
|
||||
ReactTestUtils.renderIntoDocument(<RequiredPropComponent prop="string" />);
|
||||
|
||||
// Should not error for strings
|
||||
expect(console.error.calls.length).toBe(2);
|
||||
expect(console.error.calls.count()).toBe(2);
|
||||
});
|
||||
|
||||
it('should warn on invalid prop types', function() {
|
||||
@@ -299,8 +315,8 @@ describe('ReactJSXElementValidator', function() {
|
||||
prop: null,
|
||||
};
|
||||
ReactTestUtils.renderIntoDocument(<NullPropTypeComponent />);
|
||||
expect(console.error.calls.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'NullPropTypeComponent: prop type `prop` is invalid; it must be a ' +
|
||||
'function, usually from React.PropTypes.'
|
||||
);
|
||||
@@ -317,8 +333,8 @@ describe('ReactJSXElementValidator', function() {
|
||||
prop: null,
|
||||
};
|
||||
ReactTestUtils.renderIntoDocument(<NullContextTypeComponent />);
|
||||
expect(console.error.calls.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'NullContextTypeComponent: context type `prop` is invalid; it must ' +
|
||||
'be a function, usually from React.PropTypes.'
|
||||
);
|
||||
@@ -335,8 +351,8 @@ describe('ReactJSXElementValidator', function() {
|
||||
prop: 'foo',
|
||||
});
|
||||
ReactTestUtils.renderIntoDocument(<GetDefaultPropsComponent />);
|
||||
expect(console.error.calls.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'getDefaultProps is only used on classic React.createClass definitions.' +
|
||||
' Use a static property named `defaultProps` instead.'
|
||||
);
|
||||
|
||||
@@ -0,0 +1,641 @@
|
||||
/**
|
||||
* Copyright (c) 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 ReactART
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
require('art/modes/current').setCurrent(
|
||||
require('art/modes/fast-noSideEffects') // Flip this to DOM mode for debugging
|
||||
);
|
||||
|
||||
const Transform = require('art/core/transform');
|
||||
const Mode = require('art/modes/current');
|
||||
|
||||
const React = require('React');
|
||||
const ReactDOM = require('ReactDOM');
|
||||
const ReactInstanceMap = require('ReactInstanceMap');
|
||||
const ReactMultiChild = require('ReactMultiChild');
|
||||
const ReactUpdates = require('ReactUpdates');
|
||||
|
||||
const emptyObject = require('emptyObject');
|
||||
const invariant = require('invariant');
|
||||
|
||||
const assign = require('object-assign');
|
||||
const pooledTransform = new Transform();
|
||||
|
||||
// Utilities
|
||||
|
||||
function childrenAsString(children) {
|
||||
if (!children) {
|
||||
return '';
|
||||
}
|
||||
if (typeof children === 'string') {
|
||||
return children;
|
||||
}
|
||||
if (children.length) {
|
||||
return children.join('\n');
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function createComponent(name) {
|
||||
const ReactARTComponent = function(element) {
|
||||
this.node = null;
|
||||
this.subscriptions = null;
|
||||
this.listeners = null;
|
||||
this._mountImage = null;
|
||||
this._renderedChildren = null;
|
||||
this.construct(element);
|
||||
};
|
||||
ReactARTComponent.displayName = name;
|
||||
for (let i = 1, l = arguments.length; i < l; i++) {
|
||||
assign(ReactARTComponent.prototype, arguments[i]);
|
||||
}
|
||||
|
||||
return ReactARTComponent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert `node` into `parentNode` after `referenceNode`.
|
||||
*/
|
||||
function injectAfter(parentNode, referenceNode, node) {
|
||||
let beforeNode;
|
||||
if (node.parentNode === parentNode &&
|
||||
node.previousSibling === referenceNode) {
|
||||
return;
|
||||
}
|
||||
if (referenceNode == null) {
|
||||
// node is supposed to be first.
|
||||
beforeNode = parentNode.firstChild;
|
||||
} else {
|
||||
// node is supposed to be after referenceNode.
|
||||
beforeNode = referenceNode.nextSibling;
|
||||
}
|
||||
if (beforeNode && beforeNode.previousSibling !== node) {
|
||||
// Cases where `node === beforeNode` should get filtered out by earlier
|
||||
// checks and the behavior isn't well-defined.
|
||||
invariant(
|
||||
node !== beforeNode,
|
||||
'ReactART: Can not insert node before itself'
|
||||
);
|
||||
node.injectBefore(beforeNode);
|
||||
} else if (node.parentNode !== parentNode) {
|
||||
node.inject(parentNode);
|
||||
}
|
||||
}
|
||||
|
||||
// ContainerMixin for components that can hold ART nodes
|
||||
|
||||
const ContainerMixin = assign({}, ReactMultiChild.Mixin, {
|
||||
|
||||
/**
|
||||
* Moves a child component to the supplied index.
|
||||
*
|
||||
* @param {ReactComponent} child Component to move.
|
||||
* @param {number} toIndex Destination index of the element.
|
||||
* @protected
|
||||
*/
|
||||
moveChild: function(child, afterNode, toIndex, lastIndex) {
|
||||
const childNode = child._mountImage;
|
||||
injectAfter(this.node, afterNode, childNode);
|
||||
},
|
||||
|
||||
/**
|
||||
* Creates a child component.
|
||||
*
|
||||
* @param {ReactComponent} child Component to create.
|
||||
* @param {object} childNode ART node to insert.
|
||||
* @protected
|
||||
*/
|
||||
createChild: function(child, afterNode, childNode) {
|
||||
child._mountImage = childNode;
|
||||
injectAfter(this.node, afterNode, childNode);
|
||||
},
|
||||
|
||||
/**
|
||||
* Removes a child component.
|
||||
*
|
||||
* @param {ReactComponent} child Child to remove.
|
||||
* @protected
|
||||
*/
|
||||
removeChild: function(child) {
|
||||
child._mountImage.eject();
|
||||
child._mountImage = null;
|
||||
},
|
||||
|
||||
updateChildrenAtRoot: function(nextChildren, transaction) {
|
||||
this.updateChildren(nextChildren, transaction, emptyObject);
|
||||
},
|
||||
|
||||
mountAndInjectChildrenAtRoot: function(children, transaction) {
|
||||
this.mountAndInjectChildren(children, transaction, emptyObject);
|
||||
},
|
||||
|
||||
/**
|
||||
* Override to bypass batch updating because it is not necessary.
|
||||
*
|
||||
* @param {?object} nextChildren.
|
||||
* @param {ReactReconcileTransaction} transaction
|
||||
* @internal
|
||||
* @override {ReactMultiChild.Mixin.updateChildren}
|
||||
*/
|
||||
updateChildren: function(nextChildren, transaction, context) {
|
||||
this._updateChildren(nextChildren, transaction, context);
|
||||
},
|
||||
|
||||
// Shorthands
|
||||
|
||||
mountAndInjectChildren: function(children, transaction, context) {
|
||||
const mountedImages = this.mountChildren(
|
||||
children,
|
||||
transaction,
|
||||
context
|
||||
);
|
||||
// Each mount image corresponds to one of the flattened children
|
||||
let i = 0;
|
||||
for (let key in this._renderedChildren) {
|
||||
if (this._renderedChildren.hasOwnProperty(key)) {
|
||||
const child = this._renderedChildren[key];
|
||||
child._mountImage = mountedImages[i];
|
||||
mountedImages[i].inject(this.node);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
// Surface is a React DOM Component, not an ART component. It serves as the
|
||||
// entry point into the ART reconciler.
|
||||
|
||||
const Surface = React.createClass({
|
||||
|
||||
displayName: 'Surface',
|
||||
|
||||
mixins: [ContainerMixin],
|
||||
|
||||
componentDidMount: function() {
|
||||
const domNode = ReactDOM.findDOMNode(this);
|
||||
|
||||
this.node = Mode.Surface(+this.props.width, +this.props.height, domNode);
|
||||
|
||||
const transaction = ReactUpdates.ReactReconcileTransaction.getPooled();
|
||||
transaction.perform(
|
||||
this.mountAndInjectChildren,
|
||||
this,
|
||||
this.props.children,
|
||||
transaction,
|
||||
ReactInstanceMap.get(this)._context
|
||||
);
|
||||
ReactUpdates.ReactReconcileTransaction.release(transaction);
|
||||
},
|
||||
|
||||
componentDidUpdate: function(oldProps) {
|
||||
const node = this.node;
|
||||
if (this.props.width != oldProps.width ||
|
||||
this.props.height != oldProps.height) {
|
||||
node.resize(+this.props.width, +this.props.height);
|
||||
}
|
||||
|
||||
const transaction = ReactUpdates.ReactReconcileTransaction.getPooled();
|
||||
transaction.perform(
|
||||
this.updateChildren,
|
||||
this,
|
||||
this.props.children,
|
||||
transaction,
|
||||
ReactInstanceMap.get(this)._context
|
||||
);
|
||||
ReactUpdates.ReactReconcileTransaction.release(transaction);
|
||||
|
||||
if (node.render) {
|
||||
node.render();
|
||||
}
|
||||
},
|
||||
|
||||
componentWillUnmount: function() {
|
||||
this.unmountChildren();
|
||||
},
|
||||
|
||||
render: function() {
|
||||
// This is going to be a placeholder because we don't know what it will
|
||||
// actually resolve to because ART may render canvas, vml or svg tags here.
|
||||
// We only allow a subset of properties since others might conflict with
|
||||
// ART's properties.
|
||||
const props = this.props;
|
||||
|
||||
// TODO: ART's Canvas Mode overrides surface title and cursor
|
||||
const Tag = Mode.Surface.tagName;
|
||||
return (
|
||||
<Tag
|
||||
className={props.className}
|
||||
draggable={props.draggable}
|
||||
role={props.role}
|
||||
style={props.style}
|
||||
title={props.title}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
// Various nodes that can go into a surface
|
||||
|
||||
const EventTypes = {
|
||||
onMouseMove: 'mousemove',
|
||||
onMouseOver: 'mouseover',
|
||||
onMouseOut: 'mouseout',
|
||||
onMouseUp: 'mouseup',
|
||||
onMouseDown: 'mousedown',
|
||||
onClick: 'click'
|
||||
};
|
||||
|
||||
const NodeMixin = {
|
||||
|
||||
construct: function(element) {
|
||||
this._currentElement = element;
|
||||
},
|
||||
|
||||
getNativeNode: function() {
|
||||
return this.node;
|
||||
},
|
||||
|
||||
getPublicInstance: function() {
|
||||
return this.node;
|
||||
},
|
||||
|
||||
putEventListener: function(type, listener) {
|
||||
const subscriptions = this.subscriptions || (this.subscriptions = {});
|
||||
const listeners = this.listeners || (this.listeners = {});
|
||||
listeners[type] = listener;
|
||||
if (listener) {
|
||||
if (!subscriptions[type]) {
|
||||
subscriptions[type] = this.node.subscribe(type, listener, this);
|
||||
}
|
||||
} else {
|
||||
if (subscriptions[type]) {
|
||||
subscriptions[type]();
|
||||
delete subscriptions[type];
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
handleEvent: function(event) {
|
||||
const listener = this.listeners[event.type];
|
||||
if (!listener) {
|
||||
return;
|
||||
}
|
||||
if (typeof listener === 'function') {
|
||||
listener.call(this, event);
|
||||
} else if (listener.handleEvent) {
|
||||
listener.handleEvent(event);
|
||||
}
|
||||
},
|
||||
|
||||
destroyEventListeners: function() {
|
||||
const subscriptions = this.subscriptions;
|
||||
if (subscriptions) {
|
||||
for (let type in subscriptions) {
|
||||
subscriptions[type]();
|
||||
}
|
||||
}
|
||||
this.subscriptions = null;
|
||||
this.listeners = null;
|
||||
},
|
||||
|
||||
applyNodeProps: function(oldProps, props) {
|
||||
const node = this.node;
|
||||
|
||||
const scaleX = props.scaleX != null ? props.scaleX :
|
||||
props.scale != null ? props.scale : 1;
|
||||
const scaleY = props.scaleY != null ? props.scaleY :
|
||||
props.scale != null ? props.scale : 1;
|
||||
|
||||
pooledTransform
|
||||
.transformTo(1, 0, 0, 1, 0, 0)
|
||||
.move(props.x || 0, props.y || 0)
|
||||
.rotate(props.rotation || 0, props.originX, props.originY)
|
||||
.scale(scaleX, scaleY, props.originX, props.originY);
|
||||
|
||||
if (props.transform != null) {
|
||||
pooledTransform.transform(props.transform);
|
||||
}
|
||||
|
||||
if (node.xx !== pooledTransform.xx || node.yx !== pooledTransform.yx ||
|
||||
node.xy !== pooledTransform.xy || node.yy !== pooledTransform.yy ||
|
||||
node.x !== pooledTransform.x || node.y !== pooledTransform.y) {
|
||||
node.transformTo(pooledTransform);
|
||||
}
|
||||
|
||||
if (props.cursor !== oldProps.cursor || props.title !== oldProps.title) {
|
||||
node.indicate(props.cursor, props.title);
|
||||
}
|
||||
|
||||
if (node.blend && props.opacity !== oldProps.opacity) {
|
||||
node.blend(props.opacity == null ? 1 : props.opacity);
|
||||
}
|
||||
|
||||
if (props.visible !== oldProps.visible) {
|
||||
if (props.visible == null || props.visible) {
|
||||
node.show();
|
||||
} else {
|
||||
node.hide();
|
||||
}
|
||||
}
|
||||
|
||||
for (let type in EventTypes) {
|
||||
this.putEventListener(EventTypes[type], props[type]);
|
||||
}
|
||||
},
|
||||
|
||||
mountComponentIntoNode: function(rootID, container) {
|
||||
throw new Error(
|
||||
'You cannot render an ART component standalone. ' +
|
||||
'You need to wrap it in a Surface.'
|
||||
);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
// Group
|
||||
|
||||
const Group = createComponent('Group', NodeMixin, ContainerMixin, {
|
||||
|
||||
mountComponent: function(
|
||||
transaction,
|
||||
nativeParent,
|
||||
nativeContainerInfo,
|
||||
context
|
||||
) {
|
||||
this.node = Mode.Group();
|
||||
const props = this._currentElement.props;
|
||||
this.applyGroupProps(emptyObject, props);
|
||||
this.mountAndInjectChildren(props.children, transaction, context);
|
||||
return this.node;
|
||||
},
|
||||
|
||||
receiveComponent: function(nextComponent, transaction, context) {
|
||||
const props = nextComponent.props;
|
||||
const oldProps = this._currentElement.props;
|
||||
this.applyGroupProps(oldProps, props);
|
||||
this.updateChildren(props.children, transaction, context);
|
||||
this._currentElement = nextComponent;
|
||||
},
|
||||
|
||||
applyGroupProps: function(oldProps, props) {
|
||||
this.node.width = props.width;
|
||||
this.node.height = props.height;
|
||||
this.applyNodeProps(oldProps, props);
|
||||
},
|
||||
|
||||
unmountComponent: function() {
|
||||
this.destroyEventListeners();
|
||||
this.unmountChildren();
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
// ClippingRectangle
|
||||
const ClippingRectangle = createComponent(
|
||||
'ClippingRectangle', NodeMixin, ContainerMixin, {
|
||||
|
||||
mountComponent: function(
|
||||
transaction,
|
||||
nativeParent,
|
||||
nativeContainerInfo,
|
||||
context
|
||||
) {
|
||||
this.node = Mode.ClippingRectangle();
|
||||
const props = this._currentElement.props;
|
||||
this.applyClippingProps(emptyObject, props);
|
||||
this.mountAndInjectChildren(props.children, transaction, context);
|
||||
return this.node;
|
||||
},
|
||||
|
||||
receiveComponent: function(nextComponent, transaction, context) {
|
||||
const props = nextComponent.props;
|
||||
const oldProps = this._currentElement.props;
|
||||
this.applyClippingProps(oldProps, props);
|
||||
this.updateChildren(props.children, transaction, context);
|
||||
this._currentElement = nextComponent;
|
||||
},
|
||||
|
||||
applyClippingProps: function(oldProps, props) {
|
||||
this.node.width = props.width;
|
||||
this.node.height = props.height;
|
||||
this.node.x = props.x;
|
||||
this.node.y = props.y;
|
||||
this.applyNodeProps(oldProps, props);
|
||||
},
|
||||
|
||||
unmountComponent: function() {
|
||||
this.destroyEventListeners();
|
||||
this.unmountChildren();
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
|
||||
// Renderables
|
||||
|
||||
const RenderableMixin = assign({}, NodeMixin, {
|
||||
|
||||
applyRenderableProps: function(oldProps, props) {
|
||||
if (oldProps.fill !== props.fill) {
|
||||
if (props.fill && props.fill.applyFill) {
|
||||
props.fill.applyFill(this.node);
|
||||
} else {
|
||||
this.node.fill(props.fill);
|
||||
}
|
||||
}
|
||||
if (
|
||||
oldProps.stroke !== props.stroke ||
|
||||
oldProps.strokeWidth !== props.strokeWidth ||
|
||||
oldProps.strokeCap !== props.strokeCap ||
|
||||
oldProps.strokeJoin !== props.strokeJoin ||
|
||||
// TODO: Consider a deep check of stokeDash.
|
||||
// This may benefit the VML version in IE.
|
||||
oldProps.strokeDash !== props.strokeDash
|
||||
) {
|
||||
this.node.stroke(
|
||||
props.stroke,
|
||||
props.strokeWidth,
|
||||
props.strokeCap,
|
||||
props.strokeJoin,
|
||||
props.strokeDash
|
||||
);
|
||||
}
|
||||
this.applyNodeProps(oldProps, props);
|
||||
},
|
||||
|
||||
unmountComponent: function() {
|
||||
this.destroyEventListeners();
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
// Shape
|
||||
|
||||
const Shape = createComponent('Shape', RenderableMixin, {
|
||||
|
||||
construct: function(element) {
|
||||
this._currentElement = element;
|
||||
this._oldDelta = null;
|
||||
this._oldPath = null;
|
||||
},
|
||||
|
||||
mountComponent: function(
|
||||
transaction,
|
||||
nativeParent,
|
||||
nativeContainerInfo,
|
||||
context
|
||||
) {
|
||||
this.node = Mode.Shape();
|
||||
const props = this._currentElement.props;
|
||||
this.applyShapeProps(emptyObject, props);
|
||||
return this.node;
|
||||
},
|
||||
|
||||
receiveComponent: function(nextComponent, transaction, context) {
|
||||
const props = nextComponent.props;
|
||||
const oldProps = this._currentElement.props;
|
||||
this.applyShapeProps(oldProps, props);
|
||||
this._currentElement = nextComponent;
|
||||
},
|
||||
|
||||
applyShapeProps: function(oldProps, props) {
|
||||
const oldDelta = this._oldDelta;
|
||||
const oldPath = this._oldPath;
|
||||
const path = props.d || childrenAsString(props.children);
|
||||
|
||||
if (path.delta !== oldDelta ||
|
||||
path !== oldPath ||
|
||||
oldProps.width !== props.width ||
|
||||
oldProps.height !== props.height) {
|
||||
|
||||
this.node.draw(
|
||||
path,
|
||||
props.width,
|
||||
props.height
|
||||
);
|
||||
|
||||
this._oldPath = path;
|
||||
this._oldDelta = path.delta;
|
||||
}
|
||||
|
||||
this.applyRenderableProps(oldProps, props);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
// Text
|
||||
|
||||
const Text = createComponent('Text', RenderableMixin, {
|
||||
|
||||
construct: function(element) {
|
||||
this._currentElement = element;
|
||||
this._oldString = null;
|
||||
},
|
||||
|
||||
mountComponent: function(
|
||||
transaction,
|
||||
nativeParent,
|
||||
nativeContainerInfo,
|
||||
context
|
||||
) {
|
||||
const props = this._currentElement.props;
|
||||
const newString = childrenAsString(props.children);
|
||||
this.node = Mode.Text(newString, props.font, props.alignment, props.path);
|
||||
this._oldString = newString;
|
||||
this.applyRenderableProps(emptyObject, props);
|
||||
return this.node;
|
||||
},
|
||||
|
||||
isSameFont: function(oldFont, newFont) {
|
||||
if (oldFont === newFont) {
|
||||
return true;
|
||||
}
|
||||
if (typeof newFont === 'string' || typeof oldFont === 'string') {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
newFont.fontSize === oldFont.fontSize &&
|
||||
newFont.fontStyle === oldFont.fontStyle &&
|
||||
newFont.fontVariant === oldFont.fontVariant &&
|
||||
newFont.fontWeight === oldFont.fontWeight &&
|
||||
newFont.fontFamily === oldFont.fontFamily
|
||||
);
|
||||
},
|
||||
|
||||
receiveComponent: function(nextComponent, transaction, context) {
|
||||
const props = nextComponent.props;
|
||||
const oldProps = this._currentElement.props;
|
||||
|
||||
const oldString = this._oldString;
|
||||
const newString = childrenAsString(props.children);
|
||||
|
||||
if (oldString !== newString ||
|
||||
!this.isSameFont(oldProps.font, props.font) ||
|
||||
oldProps.alignment !== props.alignment ||
|
||||
oldProps.path !== props.path) {
|
||||
this.node.draw(
|
||||
newString,
|
||||
props.font,
|
||||
props.alignment,
|
||||
props.path
|
||||
);
|
||||
this._oldString = newString;
|
||||
}
|
||||
|
||||
this.applyRenderableProps(oldProps, props);
|
||||
this._currentElement = nextComponent;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
// Declarative fill type objects - API design not finalized
|
||||
|
||||
const slice = Array.prototype.slice;
|
||||
|
||||
function LinearGradient(stops, x1, y1, x2, y2) {
|
||||
this.args = slice.call(arguments);
|
||||
}
|
||||
|
||||
LinearGradient.prototype.applyFill = function(node) {
|
||||
node.fillLinear.apply(node, this.args);
|
||||
};
|
||||
|
||||
function RadialGradient(stops, fx, fy, rx, ry, cx, cy) {
|
||||
this.args = slice.call(arguments);
|
||||
}
|
||||
|
||||
RadialGradient.prototype.applyFill = function(node) {
|
||||
node.fillRadial.apply(node, this.args);
|
||||
};
|
||||
|
||||
function Pattern(url, width, height, left, top) {
|
||||
this.args = slice.call(arguments);
|
||||
}
|
||||
|
||||
Pattern.prototype.applyFill = function(node) {
|
||||
node.fillImage.apply(node, this.args);
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
ClippingRectangle,
|
||||
Group,
|
||||
LinearGradient,
|
||||
Path: Mode.Path,
|
||||
Pattern,
|
||||
RadialGradient,
|
||||
Shape,
|
||||
Surface,
|
||||
Text,
|
||||
Transform,
|
||||
};
|
||||
@@ -0,0 +1,289 @@
|
||||
/**
|
||||
* Copyright (c) 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
|
||||
*/
|
||||
|
||||
/*jslint evil: true */
|
||||
|
||||
'use strict';
|
||||
|
||||
jest
|
||||
.unmock('ReactART');
|
||||
|
||||
var React = require('React');
|
||||
var ReactDOM = require('ReactDOM');
|
||||
var ReactTestUtils = require('ReactTestUtils');
|
||||
|
||||
var Group;
|
||||
var Shape;
|
||||
var Surface;
|
||||
var TestComponent;
|
||||
|
||||
var Missing = {};
|
||||
|
||||
var ReactART = require('ReactART');
|
||||
var ARTSVGMode = require('art/modes/svg');
|
||||
var ARTCurrentMode = require('art/modes/current');
|
||||
|
||||
function testDOMNodeStructure(domNode, expectedStructure) {
|
||||
expect(domNode).toBeDefined();
|
||||
expect(domNode.nodeName).toBe(expectedStructure.nodeName);
|
||||
for (var prop in expectedStructure) {
|
||||
if (!expectedStructure.hasOwnProperty(prop)) continue;
|
||||
if (prop != 'nodeName' && prop != 'children') {
|
||||
if (expectedStructure[prop] === Missing) {
|
||||
expect(domNode.hasAttribute(prop)).toBe(false);
|
||||
} else {
|
||||
expect(domNode.getAttribute(prop)).toBe(expectedStructure[prop]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (expectedStructure.children) {
|
||||
expectedStructure.children.forEach(function(subTree, index) {
|
||||
testDOMNodeStructure(domNode.childNodes[index], subTree);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
describe('ReactART', function() {
|
||||
|
||||
beforeEach(function() {
|
||||
ARTCurrentMode.setCurrent(ARTSVGMode);
|
||||
|
||||
Group = ReactART.Group;
|
||||
Shape = ReactART.Shape;
|
||||
Surface = ReactART.Surface;
|
||||
|
||||
TestComponent = React.createClass({
|
||||
render: function() {
|
||||
|
||||
var a =
|
||||
<Shape
|
||||
d="M0,0l50,0l0,50l-50,0z"
|
||||
fill={new ReactART.LinearGradient(["black", "white"])}
|
||||
key="a"
|
||||
width={50} height={50}
|
||||
x={50} y={50}
|
||||
opacity={0.1}
|
||||
/>;
|
||||
|
||||
var b =
|
||||
<Shape
|
||||
fill="#3C5A99"
|
||||
key="b"
|
||||
scale={0.5}
|
||||
x={50} y={50}
|
||||
title="This is an F"
|
||||
cursor="pointer">
|
||||
M64.564,38.583H54l0.008-5.834c0-3.035,0.293-4.666,4.657-4.666
|
||||
h5.833V16.429h-9.33c-11.213,0-15.159,5.654-15.159,15.16v6.994
|
||||
h-6.99v11.652h6.99v33.815H54V50.235h9.331L64.564,38.583z
|
||||
</Shape>;
|
||||
|
||||
var c = <Group key="c" />;
|
||||
|
||||
return (
|
||||
<Surface width={150} height={200}>
|
||||
<Group ref="group">
|
||||
{this.props.flipped ? [b, a, c] : [a, b, c]}
|
||||
</Group>
|
||||
</Surface>
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should have the correct lifecycle state', function() {
|
||||
var instance = <TestComponent />;
|
||||
instance = ReactTestUtils.renderIntoDocument(instance);
|
||||
var group = instance.refs.group;
|
||||
// Duck type test for an ART group
|
||||
expect(typeof group.indicate).toBe('function');
|
||||
});
|
||||
|
||||
it('should render a reasonable SVG structure in SVG mode', function() {
|
||||
var instance = <TestComponent />;
|
||||
instance = ReactTestUtils.renderIntoDocument(instance);
|
||||
|
||||
var expectedStructure = {
|
||||
nodeName: 'svg',
|
||||
width: '150',
|
||||
height: '200',
|
||||
children: [
|
||||
{ nodeName: 'defs' },
|
||||
{
|
||||
nodeName: 'g',
|
||||
children: [
|
||||
{
|
||||
nodeName: 'defs',
|
||||
children: [
|
||||
{ nodeName: 'linearGradient' }
|
||||
]
|
||||
},
|
||||
{ nodeName: 'path' },
|
||||
{ nodeName: 'path' },
|
||||
{ nodeName: 'g' }
|
||||
]
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
var realNode = ReactDOM.findDOMNode(instance);
|
||||
testDOMNodeStructure(realNode, expectedStructure);
|
||||
});
|
||||
|
||||
it('should be able to reorder components', function() {
|
||||
var container = document.createElement('div');
|
||||
var instance = ReactDOM.render(<TestComponent flipped={false} />, container);
|
||||
|
||||
var expectedStructure = {
|
||||
nodeName: 'svg',
|
||||
children: [
|
||||
{ nodeName: 'defs' },
|
||||
{
|
||||
nodeName: 'g',
|
||||
children: [
|
||||
{ nodeName: 'defs' },
|
||||
{ nodeName: 'path', opacity: '0.1' },
|
||||
{ nodeName: 'path', opacity: Missing },
|
||||
{ nodeName: 'g' }
|
||||
]
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
var realNode = ReactDOM.findDOMNode(instance);
|
||||
testDOMNodeStructure(realNode, expectedStructure);
|
||||
|
||||
ReactDOM.render(<TestComponent flipped={true} />, container);
|
||||
|
||||
var expectedNewStructure = {
|
||||
nodeName: 'svg',
|
||||
children: [
|
||||
{ nodeName: 'defs' },
|
||||
{
|
||||
nodeName: 'g',
|
||||
children: [
|
||||
{ nodeName: 'defs' },
|
||||
{ nodeName: 'path', opacity: Missing },
|
||||
{ nodeName: 'path', opacity: '0.1' },
|
||||
{ nodeName: 'g' }
|
||||
]
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
testDOMNodeStructure(realNode, expectedNewStructure);
|
||||
});
|
||||
|
||||
it('should be able to reorder many components', function() {
|
||||
var container = document.createElement('div');
|
||||
|
||||
var Component = React.createClass({
|
||||
render: function() {
|
||||
var chars = this.props.chars.split('');
|
||||
return (
|
||||
<Surface>
|
||||
{chars.map((text) => <Shape key={text} title={text} />)}
|
||||
</Surface>
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
// Mini multi-child stress test: lots of reorders, some adds, some removes.
|
||||
var before = 'abcdefghijklmnopqrst';
|
||||
var after = 'mxhpgwfralkeoivcstzy';
|
||||
|
||||
var instance = ReactDOM.render(<Component chars={before} />, container);
|
||||
var realNode = ReactDOM.findDOMNode(instance);
|
||||
expect(realNode.textContent).toBe(before);
|
||||
|
||||
instance = ReactDOM.render(<Component chars={after} />, container);
|
||||
expect(realNode.textContent).toBe(after);
|
||||
|
||||
ReactDOM.unmountComponentAtNode(container);
|
||||
});
|
||||
|
||||
it('renders composite with lifecycle inside group', function() {
|
||||
var mounted = false;
|
||||
var CustomShape = React.createClass({
|
||||
render: function() {
|
||||
return <Shape />;
|
||||
},
|
||||
componentDidMount: function() {
|
||||
mounted = true;
|
||||
}
|
||||
});
|
||||
ReactTestUtils.renderIntoDocument(
|
||||
<Surface>
|
||||
<Group>
|
||||
<CustomShape />
|
||||
</Group>
|
||||
</Surface>
|
||||
);
|
||||
expect(mounted).toBe(true);
|
||||
});
|
||||
|
||||
it('resolves refs before componentDidMount', function() {
|
||||
var CustomShape = React.createClass({
|
||||
render: function() {
|
||||
return <Shape />;
|
||||
}
|
||||
});
|
||||
var ref = null;
|
||||
var Outer = React.createClass({
|
||||
componentDidMount: function() {
|
||||
ref = this.refs.test;
|
||||
},
|
||||
render: function() {
|
||||
return (
|
||||
<Surface>
|
||||
<Group>
|
||||
<CustomShape ref="test" />
|
||||
</Group>
|
||||
</Surface>
|
||||
);
|
||||
}
|
||||
});
|
||||
ReactTestUtils.renderIntoDocument(<Outer />);
|
||||
expect(ref.constructor).toBe(CustomShape);
|
||||
});
|
||||
|
||||
it('resolves refs before componentDidUpdate', function() {
|
||||
var CustomShape = React.createClass({
|
||||
render: function() {
|
||||
return <Shape />;
|
||||
}
|
||||
});
|
||||
var ref = {};
|
||||
var Outer = React.createClass({
|
||||
componentDidMount: function() {
|
||||
ref = this.refs.test;
|
||||
},
|
||||
componentDidUpdate: function() {
|
||||
ref = this.refs.test;
|
||||
},
|
||||
render: function() {
|
||||
return (
|
||||
<Surface>
|
||||
<Group>
|
||||
{this.props.mountCustomShape && <CustomShape ref="test" />}
|
||||
</Group>
|
||||
</Surface>
|
||||
);
|
||||
}
|
||||
});
|
||||
var container = document.createElement('div');
|
||||
ReactDOM.render(<Outer />, container);
|
||||
expect(ref).not.toBeDefined();
|
||||
ReactDOM.render(<Outer mountCustomShape={true} />, container);
|
||||
expect(ref.constructor).toBe(CustomShape);
|
||||
});
|
||||
|
||||
});
|
||||
@@ -21,7 +21,7 @@ var ReactUpdates = require('ReactUpdates');
|
||||
var ReactVersion = require('ReactVersion');
|
||||
|
||||
var findDOMNode = require('findDOMNode');
|
||||
var getNativeComponentFromComposite = require('getNativeComponentFromComposite');
|
||||
var getHostComponentFromComposite = require('getHostComponentFromComposite');
|
||||
var renderSubtreeIntoContainer = require('renderSubtreeIntoContainer');
|
||||
var warning = require('warning');
|
||||
|
||||
@@ -51,7 +51,7 @@ if (
|
||||
getNodeFromInstance: function(inst) {
|
||||
// inst is an internal instance (but could be a composite)
|
||||
if (inst._renderedComponent) {
|
||||
inst = getNativeComponentFromComposite(inst);
|
||||
inst = getHostComponentFromComposite(inst);
|
||||
}
|
||||
if (inst) {
|
||||
return ReactDOMComponentTree.getNodeFromInstance(inst);
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
*
|
||||
* @emails react-core
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
describe('ReactDOMProduction', function() {
|
||||
@@ -37,7 +36,7 @@ describe('ReactDOMProduction', function() {
|
||||
|
||||
spyOn(console, 'error');
|
||||
warning(false, 'Do cows go moo?');
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
it('should use prod React', function() {
|
||||
@@ -46,7 +45,7 @@ describe('ReactDOMProduction', function() {
|
||||
// no key warning
|
||||
void <div>{[<span />]}</div>;
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
it('should handle a simple flow', function() {
|
||||
@@ -87,4 +86,20 @@ describe('ReactDOMProduction', function() {
|
||||
expect(container.childNodes.length).toBe(0);
|
||||
});
|
||||
|
||||
it('should throw with an error code in production', function() {
|
||||
expect(function() {
|
||||
var Component = React.createClass({
|
||||
render: function() {
|
||||
return ['this is wrong'];
|
||||
},
|
||||
});
|
||||
var container = document.createElement('div');
|
||||
ReactDOM.render(<Component />, container);
|
||||
}).toThrowError(
|
||||
'Minified React error #109; visit ' +
|
||||
'http://facebook.github.io/react/docs/error-decoder.html?invariant=109&args[]=Component' +
|
||||
' for the full message or use the non-minified dev environment' +
|
||||
' for full errors and additional helpful warnings.'
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -23,13 +23,13 @@ var internalInstanceKey =
|
||||
'__reactInternalInstance$' + Math.random().toString(36).slice(2);
|
||||
|
||||
/**
|
||||
* Drill down (through composites and empty components) until we get a native or
|
||||
* native text component.
|
||||
* Drill down (through composites and empty components) until we get a host or
|
||||
* host text component.
|
||||
*
|
||||
* This is pretty polymorphic but unavoidable with the current structure we have
|
||||
* for `_renderedChildren`.
|
||||
*/
|
||||
function getRenderedNativeOrTextFromComponent(component) {
|
||||
function getRenderedHostOrTextFromComponent(component) {
|
||||
var rendered;
|
||||
while ((rendered = component._renderedComponent)) {
|
||||
component = rendered;
|
||||
@@ -38,25 +38,25 @@ function getRenderedNativeOrTextFromComponent(component) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Populate `_nativeNode` on the rendered native/text component with the given
|
||||
* Populate `_hostNode` on the rendered host/text component with the given
|
||||
* DOM node. The passed `inst` can be a composite.
|
||||
*/
|
||||
function precacheNode(inst, node) {
|
||||
var nativeInst = getRenderedNativeOrTextFromComponent(inst);
|
||||
nativeInst._nativeNode = node;
|
||||
node[internalInstanceKey] = nativeInst;
|
||||
var hostInst = getRenderedHostOrTextFromComponent(inst);
|
||||
hostInst._hostNode = node;
|
||||
node[internalInstanceKey] = hostInst;
|
||||
}
|
||||
|
||||
function uncacheNode(inst) {
|
||||
var node = inst._nativeNode;
|
||||
var node = inst._hostNode;
|
||||
if (node) {
|
||||
delete node[internalInstanceKey];
|
||||
inst._nativeNode = null;
|
||||
inst._hostNode = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Populate `_nativeNode` on each child of `inst`, assuming that the children
|
||||
* Populate `_hostNode` on each child of `inst`, assuming that the children
|
||||
* match up with the DOM (element) children of `node`.
|
||||
*
|
||||
* We cache entire levels at once to avoid an n^2 problem where we access the
|
||||
@@ -80,7 +80,7 @@ function precacheChildNodes(inst, node) {
|
||||
continue;
|
||||
}
|
||||
var childInst = children[name];
|
||||
var childID = getRenderedNativeOrTextFromComponent(childInst)._domID;
|
||||
var childID = getRenderedHostOrTextFromComponent(childInst)._domID;
|
||||
if (childID == null) {
|
||||
// We're currently unmounting this child in ReactMultiChild; skip it.
|
||||
continue;
|
||||
@@ -143,7 +143,7 @@ function getClosestInstanceFromNode(node) {
|
||||
*/
|
||||
function getInstanceFromNode(node) {
|
||||
var inst = getClosestInstanceFromNode(node);
|
||||
if (inst != null && inst._nativeNode === node) {
|
||||
if (inst != null && inst._hostNode === node) {
|
||||
return inst;
|
||||
} else {
|
||||
return null;
|
||||
@@ -158,32 +158,32 @@ function getNodeFromInstance(inst) {
|
||||
// Without this first invariant, passing a non-DOM-component triggers the next
|
||||
// invariant for a missing parent, which is super confusing.
|
||||
invariant(
|
||||
inst._nativeNode !== undefined,
|
||||
inst._hostNode !== undefined,
|
||||
'getNodeFromInstance: Invalid argument.'
|
||||
);
|
||||
|
||||
if (inst._nativeNode) {
|
||||
return inst._nativeNode;
|
||||
if (inst._hostNode) {
|
||||
return inst._hostNode;
|
||||
}
|
||||
|
||||
// Walk up the tree until we find an ancestor whose DOM node we have cached.
|
||||
var parents = [];
|
||||
while (!inst._nativeNode) {
|
||||
while (!inst._hostNode) {
|
||||
parents.push(inst);
|
||||
invariant(
|
||||
inst._nativeParent,
|
||||
inst._hostParent,
|
||||
'React DOM tree root should always have a node reference.'
|
||||
);
|
||||
inst = inst._nativeParent;
|
||||
inst = inst._hostParent;
|
||||
}
|
||||
|
||||
// Now parents contains each ancestor that does *not* have a cached native
|
||||
// node, and `inst` is the deepest ancestor that does.
|
||||
for (; parents.length; inst = parents.pop()) {
|
||||
precacheChildNodes(inst, inst._nativeNode);
|
||||
precacheChildNodes(inst, inst._hostNode);
|
||||
}
|
||||
|
||||
return inst._nativeNode;
|
||||
return inst._hostNode;
|
||||
}
|
||||
|
||||
var ReactDOMComponentTree = {
|
||||
|
||||
@@ -18,27 +18,27 @@ var invariant = require('invariant');
|
||||
* different trees.
|
||||
*/
|
||||
function getLowestCommonAncestor(instA, instB) {
|
||||
invariant('_nativeNode' in instA, 'getNodeFromInstance: Invalid argument.');
|
||||
invariant('_nativeNode' in instB, 'getNodeFromInstance: Invalid argument.');
|
||||
invariant('_hostNode' in instA, 'getNodeFromInstance: Invalid argument.');
|
||||
invariant('_hostNode' in instB, 'getNodeFromInstance: Invalid argument.');
|
||||
|
||||
var depthA = 0;
|
||||
for (var tempA = instA; tempA; tempA = tempA._nativeParent) {
|
||||
for (var tempA = instA; tempA; tempA = tempA._hostParent) {
|
||||
depthA++;
|
||||
}
|
||||
var depthB = 0;
|
||||
for (var tempB = instB; tempB; tempB = tempB._nativeParent) {
|
||||
for (var tempB = instB; tempB; tempB = tempB._hostParent) {
|
||||
depthB++;
|
||||
}
|
||||
|
||||
// If A is deeper, crawl up.
|
||||
while (depthA - depthB > 0) {
|
||||
instA = instA._nativeParent;
|
||||
instA = instA._hostParent;
|
||||
depthA--;
|
||||
}
|
||||
|
||||
// If B is deeper, crawl up.
|
||||
while (depthB - depthA > 0) {
|
||||
instB = instB._nativeParent;
|
||||
instB = instB._hostParent;
|
||||
depthB--;
|
||||
}
|
||||
|
||||
@@ -48,8 +48,8 @@ function getLowestCommonAncestor(instA, instB) {
|
||||
if (instA === instB) {
|
||||
return instA;
|
||||
}
|
||||
instA = instA._nativeParent;
|
||||
instB = instB._nativeParent;
|
||||
instA = instA._hostParent;
|
||||
instB = instB._hostParent;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -58,14 +58,14 @@ function getLowestCommonAncestor(instA, instB) {
|
||||
* Return if A is an ancestor of B.
|
||||
*/
|
||||
function isAncestor(instA, instB) {
|
||||
invariant('_nativeNode' in instA, 'isAncestor: Invalid argument.');
|
||||
invariant('_nativeNode' in instB, 'isAncestor: Invalid argument.');
|
||||
invariant('_hostNode' in instA, 'isAncestor: Invalid argument.');
|
||||
invariant('_hostNode' in instB, 'isAncestor: Invalid argument.');
|
||||
|
||||
while (instB) {
|
||||
if (instB === instA) {
|
||||
return true;
|
||||
}
|
||||
instB = instB._nativeParent;
|
||||
instB = instB._hostParent;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -74,9 +74,9 @@ function isAncestor(instA, instB) {
|
||||
* Return the parent instance of the passed-in instance.
|
||||
*/
|
||||
function getParentInstance(inst) {
|
||||
invariant('_nativeNode' in inst, 'getParentInstance: Invalid argument.');
|
||||
invariant('_hostNode' in inst, 'getParentInstance: Invalid argument.');
|
||||
|
||||
return inst._nativeParent;
|
||||
return inst._hostParent;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -86,7 +86,7 @@ function traverseTwoPhase(inst, fn, arg) {
|
||||
var path = [];
|
||||
while (inst) {
|
||||
path.push(inst);
|
||||
inst = inst._nativeParent;
|
||||
inst = inst._hostParent;
|
||||
}
|
||||
var i;
|
||||
for (i = path.length; i-- > 0;) {
|
||||
@@ -109,12 +109,12 @@ function traverseEnterLeave(from, to, fn, argFrom, argTo) {
|
||||
var pathFrom = [];
|
||||
while (from && from !== common) {
|
||||
pathFrom.push(from);
|
||||
from = from._nativeParent;
|
||||
from = from._hostParent;
|
||||
}
|
||||
var pathTo = [];
|
||||
while (to && to !== common) {
|
||||
pathTo.push(to);
|
||||
to = to._nativeParent;
|
||||
to = to._hostParent;
|
||||
}
|
||||
var i;
|
||||
for (i = 0; i < pathFrom.length; i++) {
|
||||
|
||||
@@ -29,8 +29,8 @@ function findParent(inst) {
|
||||
// TODO: It may be a good idea to cache this to prevent unnecessary DOM
|
||||
// traversal, but caching is difficult to do correctly without using a
|
||||
// mutation observer to listen for all DOM changes.
|
||||
while (inst._nativeParent) {
|
||||
inst = inst._nativeParent;
|
||||
while (inst._hostParent) {
|
||||
inst = inst._hostParent;
|
||||
}
|
||||
var rootNode = ReactDOMComponentTree.getNodeFromInstance(inst);
|
||||
var container = rootNode.parentNode;
|
||||
|
||||
@@ -169,7 +169,13 @@ function batchedMountComponentIntoNode(
|
||||
* @see {ReactMount.unmountComponentAtNode}
|
||||
*/
|
||||
function unmountComponentFromNode(instance, container, safely) {
|
||||
if (__DEV__) {
|
||||
ReactInstrumentation.debugTool.onBeginFlush();
|
||||
}
|
||||
ReactReconciler.unmountComponent(instance, safely);
|
||||
if (__DEV__) {
|
||||
ReactInstrumentation.debugTool.onEndFlush();
|
||||
}
|
||||
|
||||
if (container.nodeType === DOC_NODE_TYPE) {
|
||||
container = container.documentElement;
|
||||
@@ -195,23 +201,23 @@ function hasNonRootReactChild(container) {
|
||||
var rootEl = getReactRootElementInContainer(container);
|
||||
if (rootEl) {
|
||||
var inst = ReactDOMComponentTree.getInstanceFromNode(rootEl);
|
||||
return !!(inst && inst._nativeParent);
|
||||
return !!(inst && inst._hostParent);
|
||||
}
|
||||
}
|
||||
|
||||
function getNativeRootInstanceInContainer(container) {
|
||||
function getHostRootInstanceInContainer(container) {
|
||||
var rootEl = getReactRootElementInContainer(container);
|
||||
var prevNativeInstance =
|
||||
var prevHostInstance =
|
||||
rootEl && ReactDOMComponentTree.getInstanceFromNode(rootEl);
|
||||
return (
|
||||
prevNativeInstance && !prevNativeInstance._nativeParent ?
|
||||
prevNativeInstance : null
|
||||
prevHostInstance && !prevHostInstance._hostParent ?
|
||||
prevHostInstance : null
|
||||
);
|
||||
}
|
||||
|
||||
function getTopLevelWrapperInContainer(container) {
|
||||
var root = getNativeRootInstanceInContainer(container);
|
||||
return root ? root._nativeContainerInfo._topLevelWrapper : null;
|
||||
var root = getHostRootInstanceInContainer(container);
|
||||
return root ? root._hostContainerInfo._topLevelWrapper : null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -701,10 +707,10 @@ var ReactMount = {
|
||||
}
|
||||
|
||||
if (__DEV__) {
|
||||
var nativeNode = ReactDOMComponentTree.getInstanceFromNode(container.firstChild);
|
||||
if (nativeNode._debugID !== 0) {
|
||||
ReactInstrumentation.debugTool.onNativeOperation(
|
||||
nativeNode._debugID,
|
||||
var hostNode = ReactDOMComponentTree.getInstanceFromNode(container.firstChild);
|
||||
if (hostNode._debugID !== 0) {
|
||||
ReactInstrumentation.debugTool.onHostOperation(
|
||||
hostNode._debugID,
|
||||
'mount',
|
||||
markup.toString()
|
||||
);
|
||||
|
||||
@@ -110,7 +110,7 @@ function ReactReconcileTransaction(useCreateElement) {
|
||||
// `ReactServerRendering`), but server-side uses
|
||||
// `ReactServerRenderingTransaction` instead. This option is here so that it's
|
||||
// accessible and defaults to false when `ReactDOMComponent` and
|
||||
// `ReactTextComponent` checks it in `mountComponent`.`
|
||||
// `ReactDOMTextComponent` checks it in `mountComponent`.`
|
||||
this.renderToStaticMarkup = false;
|
||||
this.reactMountReady = CallbackQueue.getPooled(null);
|
||||
this.useCreateElement = useCreateElement;
|
||||
|
||||
@@ -271,7 +271,7 @@ describe('ReactBrowserEventEmitter', function() {
|
||||
expect(idCallOrder[0]).toBe(getInternal(CHILD));
|
||||
expect(idCallOrder[1]).toBe(getInternal(PARENT));
|
||||
expect(idCallOrder[2]).toBe(getInternal(GRANDPARENT));
|
||||
expect(console.error.calls.length).toEqual(0);
|
||||
expect(console.error.calls.count()).toEqual(0);
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -388,7 +388,7 @@ describe('ReactBrowserEventEmitter', function() {
|
||||
spyOn(EventListener, 'listen');
|
||||
ReactBrowserEventEmitter.listenTo(ON_CLICK_KEY, document);
|
||||
ReactBrowserEventEmitter.listenTo(ON_CLICK_KEY, document);
|
||||
expect(EventListener.listen.calls.length).toBe(1);
|
||||
expect(EventListener.listen.calls.count()).toBe(1);
|
||||
});
|
||||
|
||||
it('should work with event plugins without dependencies', function() {
|
||||
@@ -396,7 +396,7 @@ describe('ReactBrowserEventEmitter', function() {
|
||||
|
||||
ReactBrowserEventEmitter.listenTo(ON_CLICK_KEY, document);
|
||||
|
||||
expect(EventListener.listen.argsForCall[0][1]).toBe('click');
|
||||
expect(EventListener.listen.calls.argsFor(0)[1]).toBe('click');
|
||||
});
|
||||
|
||||
it('should work with event plugins with dependencies', function() {
|
||||
@@ -406,8 +406,8 @@ describe('ReactBrowserEventEmitter', function() {
|
||||
ReactBrowserEventEmitter.listenTo(ON_CHANGE_KEY, document);
|
||||
|
||||
var setEventListeners = [];
|
||||
var listenCalls = EventListener.listen.argsForCall;
|
||||
var captureCalls = EventListener.capture.argsForCall;
|
||||
var listenCalls = EventListener.listen.calls.allArgs();
|
||||
var captureCalls = EventListener.capture.calls.allArgs();
|
||||
for (var i = 0; i < listenCalls.length; i++) {
|
||||
setEventListeners.push(listenCalls[i][1]);
|
||||
}
|
||||
|
||||
@@ -115,7 +115,7 @@ describe('ReactDOM', function() {
|
||||
spyOn(console, 'error');
|
||||
var element = React.DOM.div();
|
||||
expect(element.type).toBe('div');
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
it('throws in render() if the mount callback is not a function', function() {
|
||||
@@ -133,15 +133,15 @@ describe('ReactDOM', function() {
|
||||
});
|
||||
|
||||
var myDiv = document.createElement('div');
|
||||
expect(() => ReactDOM.render(<A />, myDiv, 'no')).toThrow(
|
||||
expect(() => ReactDOM.render(<A />, myDiv, 'no')).toThrowError(
|
||||
'ReactDOM.render(...): Expected the last optional `callback` argument ' +
|
||||
'to be a function. Instead received: string.'
|
||||
);
|
||||
expect(() => ReactDOM.render(<A />, myDiv, {})).toThrow(
|
||||
expect(() => ReactDOM.render(<A />, myDiv, {})).toThrowError(
|
||||
'ReactDOM.render(...): Expected the last optional `callback` argument ' +
|
||||
'to be a function. Instead received: Object.'
|
||||
);
|
||||
expect(() => ReactDOM.render(<A />, myDiv, new Foo())).toThrow(
|
||||
expect(() => ReactDOM.render(<A />, myDiv, new Foo())).toThrowError(
|
||||
'ReactDOM.render(...): Expected the last optional `callback` argument ' +
|
||||
'to be a function. Instead received: Foo (keys: a, b).'
|
||||
);
|
||||
@@ -164,15 +164,15 @@ describe('ReactDOM', function() {
|
||||
var myDiv = document.createElement('div');
|
||||
ReactDOM.render(<A />, myDiv);
|
||||
|
||||
expect(() => ReactDOM.render(<A />, myDiv, 'no')).toThrow(
|
||||
expect(() => ReactDOM.render(<A />, myDiv, 'no')).toThrowError(
|
||||
'ReactDOM.render(...): Expected the last optional `callback` argument ' +
|
||||
'to be a function. Instead received: string.'
|
||||
);
|
||||
expect(() => ReactDOM.render(<A />, myDiv, {})).toThrow(
|
||||
expect(() => ReactDOM.render(<A />, myDiv, {})).toThrowError(
|
||||
'ReactDOM.render(...): Expected the last optional `callback` argument ' +
|
||||
'to be a function. Instead received: Object.'
|
||||
);
|
||||
expect(() => ReactDOM.render(<A />, myDiv, new Foo())).toThrow(
|
||||
expect(() => ReactDOM.render(<A />, myDiv, new Foo())).toThrowError(
|
||||
'ReactDOM.render(...): Expected the last optional `callback` argument ' +
|
||||
'to be a function. Instead received: Foo (keys: a, b).'
|
||||
);
|
||||
|
||||
@@ -44,7 +44,7 @@ describe('ReactMount', function() {
|
||||
var nodeArray = document.getElementsByTagName('div');
|
||||
expect(function() {
|
||||
ReactDOM.unmountComponentAtNode(nodeArray);
|
||||
}).toThrow(
|
||||
}).toThrowError(
|
||||
'unmountComponentAtNode(...): Target container is not a DOM element.'
|
||||
);
|
||||
});
|
||||
@@ -53,7 +53,7 @@ describe('ReactMount', function() {
|
||||
it('throws when given a string', function() {
|
||||
expect(function() {
|
||||
ReactTestUtils.renderIntoDocument('div');
|
||||
}).toThrow(
|
||||
}).toThrowError(
|
||||
'ReactDOM.render(): Invalid component element. Instead of passing a ' +
|
||||
'string like \'div\', pass React.createElement(\'div\') or <div />.'
|
||||
);
|
||||
@@ -67,7 +67,7 @@ describe('ReactMount', function() {
|
||||
});
|
||||
expect(function() {
|
||||
ReactTestUtils.renderIntoDocument(Component);
|
||||
}).toThrow(
|
||||
}).toThrowError(
|
||||
'ReactDOM.render(): Invalid component element. Instead of passing a ' +
|
||||
'class like Foo, pass React.createElement(Foo) or <Foo />.'
|
||||
);
|
||||
@@ -133,12 +133,12 @@ describe('ReactMount', function() {
|
||||
|
||||
spyOn(console, 'error');
|
||||
ReactMount.render(<div />, container);
|
||||
expect(console.error.calls.length).toBe(1);
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
|
||||
container.innerHTML = ' ' + ReactDOMServer.renderToString(<div />);
|
||||
|
||||
ReactMount.render(<div />, container);
|
||||
expect(console.error.calls.length).toBe(2);
|
||||
expect(console.error.calls.count()).toBe(2);
|
||||
});
|
||||
|
||||
it('should not warn if mounting into non-empty node', function() {
|
||||
@@ -147,7 +147,7 @@ describe('ReactMount', function() {
|
||||
|
||||
spyOn(console, 'error');
|
||||
ReactMount.render(<div />, container);
|
||||
expect(console.error.calls.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
it('should warn when mounting into document.body', function() {
|
||||
@@ -157,8 +157,8 @@ describe('ReactMount', function() {
|
||||
|
||||
ReactMount.render(<div />, iFrame.contentDocument.body);
|
||||
|
||||
expect(console.error.calls.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'Rendering components directly into document.body is discouraged'
|
||||
);
|
||||
});
|
||||
@@ -174,8 +174,8 @@ describe('ReactMount', function() {
|
||||
<div>This markup contains an nbsp entity: client text</div>,
|
||||
div
|
||||
);
|
||||
expect(console.error.calls.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
' (client) nbsp entity: client text</div>\n' +
|
||||
' (server) nbsp entity: server text</div>'
|
||||
);
|
||||
@@ -217,8 +217,8 @@ describe('ReactMount', function() {
|
||||
spyOn(console, 'error');
|
||||
var rootNode = container.firstChild;
|
||||
ReactDOM.render(<span />, rootNode);
|
||||
expect(console.error.calls.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: render(...): Replacing React-rendered children with a new ' +
|
||||
'root component. If you intended to update the children of this node, ' +
|
||||
'you should instead have the existing children update their state and ' +
|
||||
@@ -300,10 +300,10 @@ describe('ReactMount', function() {
|
||||
|
||||
ReactTestUtils.renderIntoDocument(<Foo />);
|
||||
|
||||
expect(console.time.argsForCall.length).toBe(1);
|
||||
expect(console.time.argsForCall[0][0]).toBe('React mount: Foo');
|
||||
expect(console.timeEnd.argsForCall.length).toBe(1);
|
||||
expect(console.timeEnd.argsForCall[0][0]).toBe('React mount: Foo');
|
||||
expect(console.time.calls.count()).toBe(1);
|
||||
expect(console.time.calls.argsFor(0)[0]).toBe('React mount: Foo');
|
||||
expect(console.timeEnd.calls.count()).toBe(1);
|
||||
expect(console.timeEnd.calls.argsFor(0)[0]).toBe('React mount: Foo');
|
||||
} finally {
|
||||
ReactFeatureFlags.logTopLevelRenders = false;
|
||||
}
|
||||
|
||||
@@ -53,8 +53,8 @@ describe('ReactMount', function() {
|
||||
var rootDiv = mainContainerDiv.firstChild;
|
||||
spyOn(console, 'error');
|
||||
ReactDOM.unmountComponentAtNode(rootDiv);
|
||||
expect(console.error.calls.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: unmountComponentAtNode(): The node you\'re attempting to ' +
|
||||
'unmount was rendered by React and is not a top-level container. You ' +
|
||||
'may have accidentally passed in a React root node instead of its ' +
|
||||
@@ -77,8 +77,8 @@ describe('ReactMount', function() {
|
||||
var nonRootDiv = mainContainerDiv.firstChild.firstChild;
|
||||
spyOn(console, 'error');
|
||||
ReactDOM.unmountComponentAtNode(nonRootDiv);
|
||||
expect(console.error.calls.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: unmountComponentAtNode(): The node you\'re attempting to ' +
|
||||
'unmount was rendered by React and is not a top-level container. ' +
|
||||
'Instead, have the parent component update its state and rerender in ' +
|
||||
|
||||
@@ -94,7 +94,7 @@ describe('rendering React components at document', function() {
|
||||
|
||||
expect(function() {
|
||||
ReactDOM.unmountComponentAtNode(testDocument);
|
||||
}).toThrow(UNMOUNT_INVARIANT_MESSAGE);
|
||||
}).toThrowError(UNMOUNT_INVARIANT_MESSAGE);
|
||||
|
||||
expect(testDocument.body.innerHTML).toBe('Hello world');
|
||||
});
|
||||
@@ -142,7 +142,7 @@ describe('rendering React components at document', function() {
|
||||
// Reactive update
|
||||
expect(function() {
|
||||
ReactDOM.render(<Component2 />, testDocument);
|
||||
}).toThrow(UNMOUNT_INVARIANT_MESSAGE);
|
||||
}).toThrowError(UNMOUNT_INVARIANT_MESSAGE);
|
||||
|
||||
expect(testDocument.body.innerHTML).toBe('Hello world');
|
||||
});
|
||||
@@ -201,7 +201,7 @@ describe('rendering React components at document', function() {
|
||||
expect(function() {
|
||||
// Notice the text is different!
|
||||
ReactDOM.render(<Component text="Hello world" />, testDocument);
|
||||
}).toThrow(
|
||||
}).toThrowError(
|
||||
'You\'re trying to render a component to the document using ' +
|
||||
'server rendering but the checksum was invalid. This usually ' +
|
||||
'means you rendered a different component type or props on ' +
|
||||
@@ -237,7 +237,7 @@ describe('rendering React components at document', function() {
|
||||
|
||||
expect(function() {
|
||||
ReactDOM.render(<Component />, container);
|
||||
}).toThrow(
|
||||
}).toThrowError(
|
||||
'You\'re trying to render a component to the document but you didn\'t ' +
|
||||
'use server rendering. We can\'t do this without using server ' +
|
||||
'rendering due to cross-browser quirks. See ' +
|
||||
|
||||
@@ -37,7 +37,7 @@ describe('findDOMNode', function() {
|
||||
it('findDOMNode should reject random objects', function() {
|
||||
expect(function() {
|
||||
ReactDOM.findDOMNode({foo: 'bar'});
|
||||
}).toThrow(
|
||||
}).toThrowError(
|
||||
'Element appears to be neither ReactComponent nor DOMNode (keys: foo)'
|
||||
);
|
||||
});
|
||||
@@ -53,7 +53,7 @@ describe('findDOMNode', function() {
|
||||
var inst = ReactDOM.render(<Foo />, container);
|
||||
ReactDOM.unmountComponentAtNode(container);
|
||||
|
||||
expect(() => ReactDOM.findDOMNode(inst)).toThrow(
|
||||
expect(() => ReactDOM.findDOMNode(inst)).toThrowError(
|
||||
'findDOMNode was called on an unmounted component.'
|
||||
);
|
||||
});
|
||||
|
||||
@@ -15,7 +15,7 @@ var ReactCurrentOwner = require('ReactCurrentOwner');
|
||||
var ReactDOMComponentTree = require('ReactDOMComponentTree');
|
||||
var ReactInstanceMap = require('ReactInstanceMap');
|
||||
|
||||
var getNativeComponentFromComposite = require('getNativeComponentFromComposite');
|
||||
var getHostComponentFromComposite = require('getHostComponentFromComposite');
|
||||
var invariant = require('invariant');
|
||||
var warning = require('warning');
|
||||
|
||||
@@ -52,7 +52,7 @@ function findDOMNode(componentOrElement) {
|
||||
|
||||
var inst = ReactInstanceMap.get(componentOrElement);
|
||||
if (inst) {
|
||||
inst = getNativeComponentFromComposite(inst);
|
||||
inst = getHostComponentFromComposite(inst);
|
||||
return inst ? ReactDOMComponentTree.getNodeFromInstance(inst) : null;
|
||||
}
|
||||
|
||||
|
||||
@@ -173,10 +173,21 @@ Object.assign(SyntheticEvent.prototype, {
|
||||
this[shouldBeReleasedProperties[i]] = null;
|
||||
}
|
||||
if (__DEV__) {
|
||||
var noop = require('emptyFunction');
|
||||
Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null));
|
||||
Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', noop));
|
||||
Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', noop));
|
||||
Object.defineProperty(
|
||||
this,
|
||||
'nativeEvent',
|
||||
getPooledWarningPropertyDefinition('nativeEvent', null)
|
||||
);
|
||||
Object.defineProperty(
|
||||
this,
|
||||
'preventDefault',
|
||||
getPooledWarningPropertyDefinition('preventDefault', emptyFunction)
|
||||
);
|
||||
Object.defineProperty(
|
||||
this,
|
||||
'stopPropagation',
|
||||
getPooledWarningPropertyDefinition('stopPropagation', emptyFunction)
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ var UIEventInterface = {
|
||||
}
|
||||
|
||||
var target = getEventTarget(event);
|
||||
if (target != null && target.window === target) {
|
||||
if (target.window === target) {
|
||||
// target is a window object
|
||||
return target;
|
||||
}
|
||||
|
||||
@@ -87,9 +87,9 @@ describe('SyntheticEvent', function() {
|
||||
expect(syntheticEvent.nativeEvent).toBe(null);
|
||||
expect(syntheticEvent.target).toBe(null);
|
||||
// once for each property accessed
|
||||
expect(console.error.calls.length).toBe(3);
|
||||
expect(console.error.calls.count()).toBe(3);
|
||||
// assert the first warning for accessing `type`
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: This synthetic event is reused for performance reasons. If ' +
|
||||
'you\'re seeing this, you\'re accessing the property `type` on a ' +
|
||||
'released/nullified synthetic event. This is set to null. If you must ' +
|
||||
@@ -104,8 +104,8 @@ describe('SyntheticEvent', function() {
|
||||
var syntheticEvent = createEvent({srcElement: target});
|
||||
syntheticEvent.destructor();
|
||||
expect(syntheticEvent.type = 'MouseEvent').toBe('MouseEvent');
|
||||
expect(console.error.calls.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: This synthetic event is reused for performance reasons. If ' +
|
||||
'you\'re seeing this, you\'re setting the property `type` on a ' +
|
||||
'released/nullified synthetic event. This is effectively a no-op. If you must ' +
|
||||
@@ -119,8 +119,8 @@ describe('SyntheticEvent', function() {
|
||||
var syntheticEvent = createEvent({});
|
||||
SyntheticEvent.release(syntheticEvent);
|
||||
syntheticEvent.preventDefault();
|
||||
expect(console.error.calls.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: This synthetic event is reused for performance reasons. If ' +
|
||||
'you\'re seeing this, you\'re accessing the method `preventDefault` on a ' +
|
||||
'released/nullified synthetic event. This is a no-op function. If you must ' +
|
||||
@@ -134,8 +134,8 @@ describe('SyntheticEvent', function() {
|
||||
var syntheticEvent = createEvent({});
|
||||
SyntheticEvent.release(syntheticEvent);
|
||||
syntheticEvent.stopPropagation();
|
||||
expect(console.error.calls.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: This synthetic event is reused for performance reasons. If ' +
|
||||
'you\'re seeing this, you\'re accessing the method `stopPropagation` on a ' +
|
||||
'released/nullified synthetic event. This is a no-op function. If you must ' +
|
||||
@@ -156,13 +156,13 @@ describe('SyntheticEvent', function() {
|
||||
}
|
||||
var instance = ReactDOM.render(<div onClick={assignEvent} />, element);
|
||||
ReactTestUtils.Simulate.click(ReactDOM.findDOMNode(instance));
|
||||
expect(console.error.calls.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
|
||||
// access a property to cause the warning
|
||||
event.nativeEvent; // eslint-disable-line no-unused-expressions
|
||||
|
||||
expect(console.error.calls.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: This synthetic event is reused for performance reasons. If ' +
|
||||
'you\'re seeing this, you\'re accessing the property `nativeEvent` on a ' +
|
||||
'released/nullified synthetic event. This is set to null. If you must ' +
|
||||
@@ -178,15 +178,15 @@ describe('SyntheticEvent', function() {
|
||||
SyntheticEvent.release(syntheticEvent);
|
||||
expect(syntheticEvent.foo).toBe('bar');
|
||||
if (typeof Proxy === 'function') {
|
||||
expect(console.error.calls.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toBe(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toBe(
|
||||
'Warning: This synthetic event is reused for performance reasons. If ' +
|
||||
'you\'re seeing this, you\'re adding a new property in the synthetic ' +
|
||||
'event object. The property is never released. ' +
|
||||
'See https://fb.me/react-event-pooling for more information.'
|
||||
);
|
||||
} else {
|
||||
expect(console.error.calls.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -23,7 +23,7 @@ var setTextContent = require('setTextContent');
|
||||
|
||||
function getNodeAfter(parentNode, node) {
|
||||
// Special case for text components, which return [open, close] comments
|
||||
// from getNativeNode.
|
||||
// from getHostNode.
|
||||
if (Array.isArray(node)) {
|
||||
node = node[1];
|
||||
}
|
||||
@@ -123,7 +123,7 @@ function replaceDelimitedText(openingComment, closingComment, stringText) {
|
||||
}
|
||||
|
||||
if (__DEV__) {
|
||||
ReactInstrumentation.debugTool.onNativeOperation(
|
||||
ReactInstrumentation.debugTool.onHostOperation(
|
||||
ReactDOMComponentTree.getInstanceFromNode(openingComment)._debugID,
|
||||
'replace text',
|
||||
stringText
|
||||
@@ -136,7 +136,7 @@ if (__DEV__) {
|
||||
dangerouslyReplaceNodeWithMarkup = function(oldChild, markup, prevInstance) {
|
||||
Danger.dangerouslyReplaceNodeWithMarkup(oldChild, markup);
|
||||
if (prevInstance._debugID !== 0) {
|
||||
ReactInstrumentation.debugTool.onNativeOperation(
|
||||
ReactInstrumentation.debugTool.onHostOperation(
|
||||
prevInstance._debugID,
|
||||
'replace with',
|
||||
markup.toString()
|
||||
@@ -144,7 +144,7 @@ if (__DEV__) {
|
||||
} else {
|
||||
var nextInstance = ReactDOMComponentTree.getInstanceFromNode(markup.node);
|
||||
if (nextInstance._debugID !== 0) {
|
||||
ReactInstrumentation.debugTool.onNativeOperation(
|
||||
ReactInstrumentation.debugTool.onHostOperation(
|
||||
nextInstance._debugID,
|
||||
'mount',
|
||||
markup.toString()
|
||||
@@ -186,7 +186,7 @@ var DOMChildrenOperations = {
|
||||
getNodeAfter(parentNode, update.afterNode)
|
||||
);
|
||||
if (__DEV__) {
|
||||
ReactInstrumentation.debugTool.onNativeOperation(
|
||||
ReactInstrumentation.debugTool.onHostOperation(
|
||||
parentNodeDebugID,
|
||||
'insert child',
|
||||
{toIndex: update.toIndex, content: update.content.toString()}
|
||||
@@ -200,7 +200,7 @@ var DOMChildrenOperations = {
|
||||
getNodeAfter(parentNode, update.afterNode)
|
||||
);
|
||||
if (__DEV__) {
|
||||
ReactInstrumentation.debugTool.onNativeOperation(
|
||||
ReactInstrumentation.debugTool.onHostOperation(
|
||||
parentNodeDebugID,
|
||||
'move child',
|
||||
{fromIndex: update.fromIndex, toIndex: update.toIndex}
|
||||
@@ -213,7 +213,7 @@ var DOMChildrenOperations = {
|
||||
update.content
|
||||
);
|
||||
if (__DEV__) {
|
||||
ReactInstrumentation.debugTool.onNativeOperation(
|
||||
ReactInstrumentation.debugTool.onHostOperation(
|
||||
parentNodeDebugID,
|
||||
'replace children',
|
||||
update.content.toString()
|
||||
@@ -226,7 +226,7 @@ var DOMChildrenOperations = {
|
||||
update.content
|
||||
);
|
||||
if (__DEV__) {
|
||||
ReactInstrumentation.debugTool.onNativeOperation(
|
||||
ReactInstrumentation.debugTool.onHostOperation(
|
||||
parentNodeDebugID,
|
||||
'replace text',
|
||||
update.content.toString()
|
||||
@@ -236,7 +236,7 @@ var DOMChildrenOperations = {
|
||||
case ReactMultiChildUpdateTypes.REMOVE_NODE:
|
||||
removeChild(parentNode, update.fromNode);
|
||||
if (__DEV__) {
|
||||
ReactInstrumentation.debugTool.onNativeOperation(
|
||||
ReactInstrumentation.debugTool.onHostOperation(
|
||||
parentNodeDebugID,
|
||||
'remove child',
|
||||
{fromIndex: update.fromIndex}
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
'use strict';
|
||||
|
||||
var DOMNamespaces = require('DOMNamespaces');
|
||||
var setInnerHTML = require('setInnerHTML');
|
||||
|
||||
var createMicrosoftUnsafeLocalFunction = require('createMicrosoftUnsafeLocalFunction');
|
||||
var setTextContent = require('setTextContent');
|
||||
@@ -50,7 +51,7 @@ function insertTreeChildren(tree) {
|
||||
insertTreeBefore(node, children[i], null);
|
||||
}
|
||||
} else if (tree.html != null) {
|
||||
node.innerHTML = tree.html;
|
||||
setInnerHTML(node, tree.html);
|
||||
} else if (tree.text != null) {
|
||||
setTextContent(node, tree.text);
|
||||
}
|
||||
@@ -96,7 +97,7 @@ function queueHTML(tree, html) {
|
||||
if (enableLazy) {
|
||||
tree.html = html;
|
||||
} else {
|
||||
tree.node.innerHTML = html;
|
||||
setInnerHTML(tree.node, html);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* Copyright 2016-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 setInnerHTML = require('setInnerHTML');
|
||||
var DOMNamespaces = require('DOMNamespaces');
|
||||
|
||||
describe('setInnerHTML', function() {
|
||||
describe('when the node has innerHTML property', () => {
|
||||
it('sets innerHTML on it', function() {
|
||||
var node = document.createElement('div');
|
||||
var html = '<h1>hello</h1>';
|
||||
setInnerHTML(node, html);
|
||||
expect(node.innerHTML).toBe(html);
|
||||
});
|
||||
});
|
||||
|
||||
describe('when the node does not have an innerHTML property', () => {
|
||||
it('sets innerHTML on it', function() {
|
||||
// Create a mock node that looks like an SVG in IE (without innerHTML)
|
||||
var node = {
|
||||
namespaceURI: DOMNamespaces.svg,
|
||||
appendChild: jasmine.createSpy(),
|
||||
};
|
||||
|
||||
var html = '<circle></circle><rect></rect>';
|
||||
setInnerHTML(node, html);
|
||||
|
||||
expect(node.appendChild.calls.argsFor(0)[0].outerHTML).toBe('<circle></circle>');
|
||||
expect(node.appendChild.calls.argsFor(1)[0].outerHTML).toBe('<rect></rect>');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -12,12 +12,16 @@
|
||||
'use strict';
|
||||
|
||||
var ExecutionEnvironment = require('ExecutionEnvironment');
|
||||
var DOMNamespaces = require('DOMNamespaces');
|
||||
|
||||
var WHITESPACE_TEST = /^[ \r\n\t\f]/;
|
||||
var NONVISIBLE_TEST = /<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/;
|
||||
|
||||
var createMicrosoftUnsafeLocalFunction = require('createMicrosoftUnsafeLocalFunction');
|
||||
|
||||
// SVG temp container for IE lacking innerHTML
|
||||
var reusableSVGContainer;
|
||||
|
||||
/**
|
||||
* Set the innerHTML property of a node, ensuring that whitespace is preserved
|
||||
* even in IE8.
|
||||
@@ -28,7 +32,19 @@ var createMicrosoftUnsafeLocalFunction = require('createMicrosoftUnsafeLocalFunc
|
||||
*/
|
||||
var setInnerHTML = createMicrosoftUnsafeLocalFunction(
|
||||
function(node, html) {
|
||||
node.innerHTML = html;
|
||||
// IE does not have innerHTML for SVG nodes, so instead we inject the
|
||||
// new markup in a temp node and then move the child nodes across into
|
||||
// the target node
|
||||
if (node.namespaceURI === DOMNamespaces.svg && !('innerHTML' in node)) {
|
||||
reusableSVGContainer = reusableSVGContainer || document.createElement('div');
|
||||
reusableSVGContainer.innerHTML = '<svg>' + html + '</svg>';
|
||||
var newNodes = reusableSVGContainer.firstChild.childNodes;
|
||||
for (var i = 0; i < newNodes.length; i++) {
|
||||
node.appendChild(newNodes[i]);
|
||||
}
|
||||
} else {
|
||||
node.innerHTML = html;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
@@ -26,6 +26,14 @@ var setInnerHTML = require('setInnerHTML');
|
||||
* @internal
|
||||
*/
|
||||
var setTextContent = function(node, text) {
|
||||
if (text) {
|
||||
var firstChild = node.firstChild;
|
||||
|
||||
if (firstChild && firstChild === node.lastChild && firstChild.nodeType === 3) {
|
||||
firstChild.nodeValue = text;
|
||||
return;
|
||||
}
|
||||
}
|
||||
node.textContent = text;
|
||||
};
|
||||
|
||||
|
||||
@@ -26,24 +26,24 @@ var disableableMouseListenerNames = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Implements a native component that does not receive mouse events
|
||||
* Implements a host component that does not receive mouse events
|
||||
* when `disabled` is set.
|
||||
*/
|
||||
var DisabledInputUtils = {
|
||||
getNativeProps: function(inst, props) {
|
||||
getHostProps: function(inst, props) {
|
||||
if (!props.disabled) {
|
||||
return props;
|
||||
}
|
||||
|
||||
// Copy the props, except the mouse listeners
|
||||
var nativeProps = {};
|
||||
var hostProps = {};
|
||||
for (var key in props) {
|
||||
if (!disableableMouseListenerNames[key] && props.hasOwnProperty(key)) {
|
||||
nativeProps[key] = props[key];
|
||||
hostProps[key] = props[key];
|
||||
}
|
||||
}
|
||||
|
||||
return nativeProps;
|
||||
return hostProps;
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -14,11 +14,11 @@
|
||||
var DisabledInputUtils = require('DisabledInputUtils');
|
||||
|
||||
/**
|
||||
* Implements a <button> native component that does not receive mouse events
|
||||
* Implements a <button> host component that does not receive mouse events
|
||||
* when `disabled` is set.
|
||||
*/
|
||||
var ReactDOMButton = {
|
||||
getNativeProps: DisabledInputUtils.getNativeProps,
|
||||
getHostProps: DisabledInputUtils.getHostProps,
|
||||
};
|
||||
|
||||
module.exports = ReactDOMButton;
|
||||
@@ -48,8 +48,13 @@ function warnIfValueIsNull(props) {
|
||||
}
|
||||
}
|
||||
|
||||
function isControlled(props) {
|
||||
var usesChecked = props.type === 'checkbox' || props.type === 'radio';
|
||||
return usesChecked ? props.checked !== undefined : props.value !== undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements an <input> native component that allows setting these optional
|
||||
* Implements an <input> host component that allows setting these optional
|
||||
* props: `checked`, `value`, `defaultChecked`, and `defaultValue`.
|
||||
*
|
||||
* If `checked` or `value` are not supplied (or null/undefined), user actions
|
||||
@@ -65,15 +70,15 @@ function warnIfValueIsNull(props) {
|
||||
* @see http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html
|
||||
*/
|
||||
var ReactDOMInput = {
|
||||
getNativeProps: function(inst, props) {
|
||||
getHostProps: function(inst, props) {
|
||||
var value = LinkedValueUtils.getValue(props);
|
||||
var checked = LinkedValueUtils.getChecked(props);
|
||||
|
||||
var nativeProps = Object.assign({
|
||||
var hostProps = Object.assign({
|
||||
// Make sure we set .type before any other properties (setting .value
|
||||
// before .type means .value is lost in IE11 and below)
|
||||
type: undefined,
|
||||
}, DisabledInputUtils.getNativeProps(inst, props), {
|
||||
}, DisabledInputUtils.getHostProps(inst, props), {
|
||||
defaultChecked: undefined,
|
||||
defaultValue: undefined,
|
||||
value: value != null ? value : inst._wrapperState.initialValue,
|
||||
@@ -81,7 +86,7 @@ var ReactDOMInput = {
|
||||
onChange: inst._wrapperState.onChange,
|
||||
});
|
||||
|
||||
return nativeProps;
|
||||
return hostProps;
|
||||
},
|
||||
|
||||
mountWrapper: function(inst, props) {
|
||||
@@ -149,14 +154,14 @@ var ReactDOMInput = {
|
||||
|
||||
var defaultValue = props.defaultValue;
|
||||
inst._wrapperState = {
|
||||
initialChecked: props.defaultChecked || false,
|
||||
initialValue: defaultValue != null ? defaultValue : null,
|
||||
initialChecked: props.checked != null ? props.checked : props.defaultChecked,
|
||||
initialValue: props.value != null ? props.value : defaultValue,
|
||||
listeners: null,
|
||||
onChange: _handleChange.bind(inst),
|
||||
};
|
||||
|
||||
if (__DEV__) {
|
||||
inst._wrapperState.controlled = props.checked !== undefined || props.value !== undefined;
|
||||
inst._wrapperState.controlled = isControlled(props);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -166,15 +171,10 @@ var ReactDOMInput = {
|
||||
if (__DEV__) {
|
||||
warnIfValueIsNull(props);
|
||||
|
||||
var initialValue = inst._wrapperState.initialChecked || inst._wrapperState.initialValue;
|
||||
var defaultValue = props.defaultChecked || props.defaultValue;
|
||||
var controlled = props.checked !== undefined || props.value !== undefined;
|
||||
var controlled = isControlled(props);
|
||||
var owner = inst._currentElement._owner;
|
||||
|
||||
if (
|
||||
(initialValue || !inst._wrapperState.controlled) &&
|
||||
controlled && !didWarnUncontrolledToControlled
|
||||
) {
|
||||
if (!inst._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) {
|
||||
warning(
|
||||
false,
|
||||
'%s is changing an uncontrolled input of type %s to be controlled. ' +
|
||||
@@ -186,11 +186,7 @@ var ReactDOMInput = {
|
||||
);
|
||||
didWarnUncontrolledToControlled = true;
|
||||
}
|
||||
if (
|
||||
inst._wrapperState.controlled &&
|
||||
(defaultValue || !controlled) &&
|
||||
!didWarnControlledToUncontrolled
|
||||
) {
|
||||
if (inst._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) {
|
||||
warning(
|
||||
false,
|
||||
'%s is changing a controlled input of type %s to be uncontrolled. ' +
|
||||
@@ -214,17 +210,45 @@ var ReactDOMInput = {
|
||||
);
|
||||
}
|
||||
|
||||
var node = ReactDOMComponentTree.getNodeFromInstance(inst);
|
||||
var value = LinkedValueUtils.getValue(props);
|
||||
if (value != null) {
|
||||
|
||||
// Cast `value` to a string to ensure the value is set correctly. While
|
||||
// browsers typically do this as necessary, jsdom doesn't.
|
||||
DOMPropertyOperations.setValueForProperty(
|
||||
ReactDOMComponentTree.getNodeFromInstance(inst),
|
||||
'value',
|
||||
'' + value
|
||||
);
|
||||
var newValue = '' + value;
|
||||
|
||||
// To avoid side effects (such as losing text selection), only set value if changed
|
||||
if (newValue !== node.value) {
|
||||
node.value = newValue;
|
||||
}
|
||||
} else {
|
||||
if (props.value == null && props.defaultValue != null) {
|
||||
node.defaultValue = '' + props.defaultValue;
|
||||
}
|
||||
if (props.checked == null && props.defaultChecked != null) {
|
||||
node.defaultChecked = !!props.defaultChecked;
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
postMountWrapper: function(inst) {
|
||||
// This is in postMount because we need access to the DOM node, which is not
|
||||
// available until after the component has mounted.
|
||||
var node = ReactDOMComponentTree.getNodeFromInstance(inst);
|
||||
node.value = node.value; // Detach value from defaultValue
|
||||
|
||||
// Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug
|
||||
// this is needed to work around a chrome bug where setting defaultChecked
|
||||
// will sometimes influence the value of checked (even after detachment).
|
||||
// Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416
|
||||
// We need to temporarily unset name to avoid disrupting radio button groups.
|
||||
var name = node.name;
|
||||
node.name = undefined;
|
||||
node.defaultChecked = !node.defaultChecked;
|
||||
node.defaultChecked = !node.defaultChecked;
|
||||
node.name = name;
|
||||
},
|
||||
};
|
||||
|
||||
function _handleChange(event) {
|
||||
|
||||
@@ -16,12 +16,36 @@ var ReactDOMComponentTree = require('ReactDOMComponentTree');
|
||||
var ReactDOMSelect = require('ReactDOMSelect');
|
||||
|
||||
var warning = require('warning');
|
||||
var didWarnInvalidOptionChildren = false;
|
||||
|
||||
function flattenChildren(children) {
|
||||
var content = '';
|
||||
|
||||
// Flatten children and warn if they aren't strings or numbers;
|
||||
// invalid types are ignored.
|
||||
ReactChildren.forEach(children, function(child) {
|
||||
if (child == null) {
|
||||
return;
|
||||
}
|
||||
if (typeof child === 'string' || typeof child === 'number') {
|
||||
content += child;
|
||||
} else if (!didWarnInvalidOptionChildren) {
|
||||
didWarnInvalidOptionChildren = true;
|
||||
warning(
|
||||
false,
|
||||
'Only strings and numbers are supported as <option> children.'
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
return content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements an <option> native component that warns when `selected` is set.
|
||||
* Implements an <option> host component that warns when `selected` is set.
|
||||
*/
|
||||
var ReactDOMOption = {
|
||||
mountWrapper: function(inst, props, nativeParent) {
|
||||
mountWrapper: function(inst, props, hostParent) {
|
||||
// TODO (yungsters): Remove support for `selected` in <option>.
|
||||
if (__DEV__) {
|
||||
warning(
|
||||
@@ -33,11 +57,11 @@ var ReactDOMOption = {
|
||||
|
||||
// Look up whether this option is 'selected'
|
||||
var selectValue = null;
|
||||
if (nativeParent != null) {
|
||||
var selectParent = nativeParent;
|
||||
if (hostParent != null) {
|
||||
var selectParent = hostParent;
|
||||
|
||||
if (selectParent._tag === 'optgroup') {
|
||||
selectParent = selectParent._nativeParent;
|
||||
selectParent = selectParent._hostParent;
|
||||
}
|
||||
|
||||
if (selectParent != null && selectParent._tag === 'select') {
|
||||
@@ -49,17 +73,23 @@ var ReactDOMOption = {
|
||||
// or missing (e.g., for <datalist>), we don't change props.selected
|
||||
var selected = null;
|
||||
if (selectValue != null) {
|
||||
var value;
|
||||
if (props.value != null) {
|
||||
value = props.value + '';
|
||||
} else {
|
||||
value = flattenChildren(props.children);
|
||||
}
|
||||
selected = false;
|
||||
if (Array.isArray(selectValue)) {
|
||||
// multiple
|
||||
for (var i = 0; i < selectValue.length; i++) {
|
||||
if ('' + selectValue[i] === '' + props.value) {
|
||||
if ('' + selectValue[i] === value) {
|
||||
selected = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
selected = ('' + selectValue === '' + props.value);
|
||||
selected = ('' + selectValue === value);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,38 +105,22 @@ var ReactDOMOption = {
|
||||
}
|
||||
},
|
||||
|
||||
getNativeProps: function(inst, props) {
|
||||
var nativeProps = Object.assign({selected: undefined, children: undefined}, props);
|
||||
getHostProps: function(inst, props) {
|
||||
var hostProps = Object.assign({selected: undefined, children: undefined}, props);
|
||||
|
||||
// Read state only from initial mount because <select> updates value
|
||||
// manually; we need the initial state only for server rendering
|
||||
if (inst._wrapperState.selected != null) {
|
||||
nativeProps.selected = inst._wrapperState.selected;
|
||||
hostProps.selected = inst._wrapperState.selected;
|
||||
}
|
||||
|
||||
var content = '';
|
||||
|
||||
// Flatten children and warn if they aren't strings or numbers;
|
||||
// invalid types are ignored.
|
||||
ReactChildren.forEach(props.children, function(child) {
|
||||
if (child == null) {
|
||||
return;
|
||||
}
|
||||
if (typeof child === 'string' || typeof child === 'number') {
|
||||
content += child;
|
||||
} else {
|
||||
warning(
|
||||
false,
|
||||
'Only strings and numbers are supported as <option> children.'
|
||||
);
|
||||
}
|
||||
});
|
||||
var content = flattenChildren(props.children);
|
||||
|
||||
if (content) {
|
||||
nativeProps.children = content;
|
||||
hostProps.children = content;
|
||||
}
|
||||
|
||||
return nativeProps;
|
||||
return hostProps;
|
||||
},
|
||||
|
||||
};
|
||||
|
||||
@@ -143,7 +143,7 @@ function updateOptions(inst, multiple, propValue) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements a <select> native component that allows optionally setting the
|
||||
* Implements a <select> host component that allows optionally setting the
|
||||
* props `value` and `defaultValue`. If `multiple` is false, the prop must be a
|
||||
* stringable. If `multiple` is true, the prop must be an array of stringables.
|
||||
*
|
||||
@@ -158,8 +158,8 @@ function updateOptions(inst, multiple, propValue) {
|
||||
* selected.
|
||||
*/
|
||||
var ReactDOMSelect = {
|
||||
getNativeProps: function(inst, props) {
|
||||
return Object.assign({}, DisabledInputUtils.getNativeProps(inst, props), {
|
||||
getHostProps: function(inst, props) {
|
||||
return Object.assign({}, DisabledInputUtils.getHostProps(inst, props), {
|
||||
onChange: inst._wrapperState.onChange,
|
||||
value: undefined,
|
||||
});
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
'use strict';
|
||||
|
||||
var DisabledInputUtils = require('DisabledInputUtils');
|
||||
var DOMPropertyOperations = require('DOMPropertyOperations');
|
||||
var LinkedValueUtils = require('LinkedValueUtils');
|
||||
var ReactDOMComponentTree = require('ReactDOMComponentTree');
|
||||
var ReactUpdates = require('ReactUpdates');
|
||||
@@ -45,7 +44,7 @@ function warnIfValueIsNull(props) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements a <textarea> native component that allows setting `value`, and
|
||||
* Implements a <textarea> host component that allows setting `value`, and
|
||||
* `defaultValue`. This differs from the traditional DOM API because value is
|
||||
* usually set as PCDATA children.
|
||||
*
|
||||
@@ -60,22 +59,25 @@ function warnIfValueIsNull(props) {
|
||||
* `defaultValue` if specified, or the children content (deprecated).
|
||||
*/
|
||||
var ReactDOMTextarea = {
|
||||
getNativeProps: function(inst, props) {
|
||||
getHostProps: function(inst, props) {
|
||||
invariant(
|
||||
props.dangerouslySetInnerHTML == null,
|
||||
'`dangerouslySetInnerHTML` does not make sense on <textarea>.'
|
||||
);
|
||||
|
||||
// Always set children to the same thing. In IE9, the selection range will
|
||||
// get reset if `textContent` is mutated.
|
||||
var nativeProps = Object.assign({}, DisabledInputUtils.getNativeProps(inst, props), {
|
||||
defaultValue: undefined,
|
||||
// get reset if `textContent` is mutated. We could add a check in setTextContent
|
||||
// to only set the value if/when the value differs from the node value (which would
|
||||
// completely solve this IE9 bug), but Sebastian+Ben seemed to like this solution.
|
||||
// The value can be a boolean or object so that's why it's forced to be a string.
|
||||
var hostProps = Object.assign({}, DisabledInputUtils.getHostProps(inst, props), {
|
||||
value: undefined,
|
||||
children: inst._wrapperState.initialValue,
|
||||
defaultValue: undefined,
|
||||
children: '' + inst._wrapperState.initialValue,
|
||||
onChange: inst._wrapperState.onChange,
|
||||
});
|
||||
|
||||
return nativeProps;
|
||||
return hostProps;
|
||||
},
|
||||
|
||||
mountWrapper: function(inst, props) {
|
||||
@@ -110,41 +112,45 @@ var ReactDOMTextarea = {
|
||||
warnIfValueIsNull(props);
|
||||
}
|
||||
|
||||
var defaultValue = props.defaultValue;
|
||||
// TODO (yungsters): Remove support for children content in <textarea>.
|
||||
var children = props.children;
|
||||
if (children != null) {
|
||||
if (__DEV__) {
|
||||
warning(
|
||||
false,
|
||||
'Use the `defaultValue` or `value` props instead of setting ' +
|
||||
'children on <textarea>.'
|
||||
);
|
||||
}
|
||||
invariant(
|
||||
defaultValue == null,
|
||||
'If you supply `defaultValue` on a <textarea>, do not pass children.'
|
||||
);
|
||||
if (Array.isArray(children)) {
|
||||
invariant(
|
||||
children.length <= 1,
|
||||
'<textarea> can only have at most one child.'
|
||||
);
|
||||
children = children[0];
|
||||
}
|
||||
|
||||
defaultValue = '' + children;
|
||||
}
|
||||
if (defaultValue == null) {
|
||||
defaultValue = '';
|
||||
}
|
||||
var value = LinkedValueUtils.getValue(props);
|
||||
var initialValue = value;
|
||||
|
||||
// Only bother fetching default value if we're going to use it
|
||||
if (value == null) {
|
||||
var defaultValue = props.defaultValue;
|
||||
// TODO (yungsters): Remove support for children content in <textarea>.
|
||||
var children = props.children;
|
||||
if (children != null) {
|
||||
if (__DEV__) {
|
||||
warning(
|
||||
false,
|
||||
'Use the `defaultValue` or `value` props instead of setting ' +
|
||||
'children on <textarea>.'
|
||||
);
|
||||
}
|
||||
invariant(
|
||||
defaultValue == null,
|
||||
'If you supply `defaultValue` on a <textarea>, do not pass children.'
|
||||
);
|
||||
if (Array.isArray(children)) {
|
||||
invariant(
|
||||
children.length <= 1,
|
||||
'<textarea> can only have at most one child.'
|
||||
);
|
||||
children = children[0];
|
||||
}
|
||||
|
||||
defaultValue = '' + children;
|
||||
}
|
||||
if (defaultValue == null) {
|
||||
defaultValue = '';
|
||||
}
|
||||
initialValue = defaultValue;
|
||||
}
|
||||
|
||||
inst._wrapperState = {
|
||||
// We save the initial value so that `ReactDOMComponent` doesn't update
|
||||
// `textContent` (unnecessary since we update value).
|
||||
// The initial value can be a boolean or object so that's why it's
|
||||
// forced to be a string.
|
||||
initialValue: '' + (value != null ? value : defaultValue),
|
||||
initialValue: '' + initialValue,
|
||||
listeners: null,
|
||||
onChange: _handleChange.bind(inst),
|
||||
};
|
||||
@@ -157,16 +163,33 @@ var ReactDOMTextarea = {
|
||||
warnIfValueIsNull(props);
|
||||
}
|
||||
|
||||
var node = ReactDOMComponentTree.getNodeFromInstance(inst);
|
||||
var value = LinkedValueUtils.getValue(props);
|
||||
if (value != null) {
|
||||
// Cast `value` to a string to ensure the value is set correctly. While
|
||||
// browsers typically do this as necessary, jsdom doesn't.
|
||||
DOMPropertyOperations.setValueForProperty(
|
||||
ReactDOMComponentTree.getNodeFromInstance(inst),
|
||||
'value',
|
||||
'' + value
|
||||
);
|
||||
var newValue = '' + value;
|
||||
|
||||
// To avoid side effects (such as losing text selection), only set value if changed
|
||||
if (newValue !== node.value) {
|
||||
node.value = newValue;
|
||||
}
|
||||
if (props.defaultValue == null) {
|
||||
node.defaultValue = newValue;
|
||||
}
|
||||
}
|
||||
if (props.defaultValue != null) {
|
||||
node.defaultValue = props.defaultValue;
|
||||
}
|
||||
},
|
||||
|
||||
postMountWrapper: function(inst) {
|
||||
// This is in postMount because we need access to the DOM node, which is not
|
||||
// available until after the component has mounted.
|
||||
var node = ReactDOMComponentTree.getNodeFromInstance(inst);
|
||||
|
||||
// Warning: node.value may be the empty string at this point (IE11) if placeholder is set.
|
||||
node.value = node.textContent; // Detach value from defaultValue
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ describe('ReactDOMInput', function() {
|
||||
var EventConstants;
|
||||
var React;
|
||||
var ReactDOM;
|
||||
var ReactDOMServer;
|
||||
var ReactDOMFeatureFlags;
|
||||
var ReactLink;
|
||||
var ReactTestUtils;
|
||||
@@ -27,6 +28,7 @@ describe('ReactDOMInput', function() {
|
||||
EventConstants = require('EventConstants');
|
||||
React = require('React');
|
||||
ReactDOM = require('ReactDOM');
|
||||
ReactDOMServer = require('ReactDOMServer');
|
||||
ReactDOMFeatureFlags = require('ReactDOMFeatureFlags');
|
||||
ReactLink = require('ReactLink');
|
||||
ReactTestUtils = require('ReactTestUtils');
|
||||
@@ -38,6 +40,7 @@ describe('ReactDOMInput', function() {
|
||||
stub = ReactTestUtils.renderIntoDocument(stub);
|
||||
var node = ReactDOM.findDOMNode(stub);
|
||||
|
||||
expect(node.getAttribute('value')).toBe('0');
|
||||
expect(node.value).toBe('0');
|
||||
});
|
||||
|
||||
@@ -57,6 +60,48 @@ describe('ReactDOMInput', function() {
|
||||
expect(node.value).toBe('false');
|
||||
});
|
||||
|
||||
it('should update `defaultValue` for uncontrolled input', function() {
|
||||
var container = document.createElement('div');
|
||||
|
||||
var node = ReactDOM.render(<input type="text" defaultValue="0" />, container);
|
||||
|
||||
expect(node.value).toBe('0');
|
||||
|
||||
ReactDOM.render(<input type="text" defaultValue="1" />, container);
|
||||
|
||||
expect(node.value).toBe('0');
|
||||
expect(node.defaultValue).toBe('1');
|
||||
});
|
||||
|
||||
it('should take `defaultValue` when changing to uncontrolled input', function() {
|
||||
var container = document.createElement('div');
|
||||
|
||||
var node = ReactDOM.render(<input type="text" value="0" readOnly="true" />, container);
|
||||
|
||||
expect(node.value).toBe('0');
|
||||
|
||||
ReactDOM.render(<input type="text" defaultValue="1" />, container);
|
||||
|
||||
expect(node.value).toBe('0');
|
||||
});
|
||||
|
||||
it('should render defaultValue for SSR', function() {
|
||||
var markup = ReactDOMServer.renderToString(<input type="text" defaultValue="1" />);
|
||||
var div = document.createElement('div');
|
||||
div.innerHTML = markup;
|
||||
expect(div.firstChild.getAttribute('value')).toBe('1');
|
||||
expect(div.firstChild.getAttribute('defaultValue')).toBe(null);
|
||||
});
|
||||
|
||||
it('should render value for SSR', function() {
|
||||
var element = <input type="text" value="1" onChange={function() {}} />;
|
||||
var markup = ReactDOMServer.renderToString(element);
|
||||
var div = document.createElement('div');
|
||||
div.innerHTML = markup;
|
||||
expect(div.firstChild.getAttribute('value')).toBe('1');
|
||||
expect(div.firstChild.getAttribute('defaultValue')).toBe(null);
|
||||
});
|
||||
|
||||
it('should display "foobar" for `defaultValue` of `objToString`', function() {
|
||||
var objToString = {
|
||||
toString: function() {
|
||||
@@ -82,8 +127,7 @@ describe('ReactDOMInput', function() {
|
||||
it('should allow setting `value` to `true`', function() {
|
||||
var container = document.createElement('div');
|
||||
var stub = <input type="text" value="yolo" onChange={emptyFunction} />;
|
||||
stub = ReactDOM.render(stub, container);
|
||||
var node = ReactDOM.findDOMNode(stub);
|
||||
var node = ReactDOM.render(stub, container);
|
||||
|
||||
expect(node.value).toBe('yolo');
|
||||
|
||||
@@ -97,8 +141,7 @@ describe('ReactDOMInput', function() {
|
||||
it('should allow setting `value` to `false`', function() {
|
||||
var container = document.createElement('div');
|
||||
var stub = <input type="text" value="yolo" onChange={emptyFunction} />;
|
||||
stub = ReactDOM.render(stub, container);
|
||||
var node = ReactDOM.findDOMNode(stub);
|
||||
var node = ReactDOM.render(stub, container);
|
||||
|
||||
expect(node.value).toBe('yolo');
|
||||
|
||||
@@ -112,8 +155,7 @@ describe('ReactDOMInput', function() {
|
||||
it('should allow setting `value` to `objToString`', function() {
|
||||
var container = document.createElement('div');
|
||||
var stub = <input type="text" value="foo" onChange={emptyFunction} />;
|
||||
stub = ReactDOM.render(stub, container);
|
||||
var node = ReactDOM.findDOMNode(stub);
|
||||
var node = ReactDOM.render(stub, container);
|
||||
|
||||
expect(node.value).toBe('foo');
|
||||
|
||||
@@ -129,6 +171,29 @@ describe('ReactDOMInput', function() {
|
||||
expect(node.value).toEqual('foobar');
|
||||
});
|
||||
|
||||
it('should not incur unnecessary DOM mutations', function() {
|
||||
var container = document.createElement('div');
|
||||
ReactDOM.render(<input value="a" />, container);
|
||||
|
||||
var node = container.firstChild;
|
||||
var nodeValue = 'a';
|
||||
var nodeValueSetter = jest.genMockFn();
|
||||
Object.defineProperty(node, 'value', {
|
||||
get: function() {
|
||||
return nodeValue;
|
||||
},
|
||||
set: nodeValueSetter.mockImplementation(function(newValue) {
|
||||
nodeValue = newValue;
|
||||
}),
|
||||
});
|
||||
|
||||
ReactDOM.render(<input value="a" />, container);
|
||||
expect(nodeValueSetter.mock.calls.length).toBe(0);
|
||||
|
||||
ReactDOM.render(<input value="b"/>, container);
|
||||
expect(nodeValueSetter.mock.calls.length).toBe(1);
|
||||
});
|
||||
|
||||
it('should properly control a value of number `0`', function() {
|
||||
var stub = <input type="text" value={0} onChange={emptyFunction} />;
|
||||
stub = ReactTestUtils.renderIntoDocument(stub);
|
||||
@@ -255,29 +320,29 @@ describe('ReactDOMInput', function() {
|
||||
it('should warn with value and no onChange handler', function() {
|
||||
var link = new ReactLink('yolo', jest.fn());
|
||||
ReactTestUtils.renderIntoDocument(<input type="text" valueLink={link} />);
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'`valueLink` prop on `input` is deprecated; set `value` and `onChange` instead.'
|
||||
);
|
||||
|
||||
ReactTestUtils.renderIntoDocument(
|
||||
<input type="text" value="zoink" onChange={jest.fn()} />
|
||||
);
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
ReactTestUtils.renderIntoDocument(<input type="text" value="zoink" />);
|
||||
expect(console.error.argsForCall.length).toBe(2);
|
||||
expect(console.error.calls.count()).toBe(2);
|
||||
});
|
||||
|
||||
it('should warn with value and no onChange handler and readOnly specified', function() {
|
||||
ReactTestUtils.renderIntoDocument(
|
||||
<input type="text" value="zoink" readOnly={true} />
|
||||
);
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
|
||||
ReactTestUtils.renderIntoDocument(
|
||||
<input type="text" value="zoink" readOnly={false} />
|
||||
);
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
});
|
||||
|
||||
it('should have a this value of undefined if bind is not used', function() {
|
||||
@@ -333,8 +398,8 @@ describe('ReactDOMInput', function() {
|
||||
var node = document.createElement('div');
|
||||
var link = new ReactLink(true, jest.fn());
|
||||
ReactDOM.render(<input type="checkbox" checkedLink={link} />, node);
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'`checkedLink` prop on `input` is deprecated; set `value` and `onChange` instead.'
|
||||
);
|
||||
|
||||
@@ -345,27 +410,27 @@ describe('ReactDOMInput', function() {
|
||||
onChange={jest.fn()}
|
||||
/>
|
||||
);
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
|
||||
ReactTestUtils.renderIntoDocument(
|
||||
<input type="checkbox" checked="false" readOnly={true} />
|
||||
);
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
|
||||
ReactTestUtils.renderIntoDocument(<input type="checkbox" checked="false" />);
|
||||
expect(console.error.argsForCall.length).toBe(2);
|
||||
expect(console.error.calls.count()).toBe(2);
|
||||
});
|
||||
|
||||
it('should warn with checked and no onChange handler with readOnly specified', function() {
|
||||
ReactTestUtils.renderIntoDocument(
|
||||
<input type="checkbox" checked="false" readOnly={true} />
|
||||
);
|
||||
expect(console.error.argsForCall.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
|
||||
ReactTestUtils.renderIntoDocument(
|
||||
<input type="checkbox" checked="false" readOnly={false} />
|
||||
);
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
});
|
||||
|
||||
it('should throw if both checked and checkedLink are provided', function() {
|
||||
@@ -390,6 +455,13 @@ describe('ReactDOMInput', function() {
|
||||
|
||||
});
|
||||
|
||||
it('should update defaultValue to empty string', function() {
|
||||
var container = document.createElement('div');
|
||||
ReactDOM.render(<input type="text" defaultValue={'foo'} />, container);
|
||||
ReactDOM.render(<input type="text" defaultValue={''} />, container);
|
||||
expect(container.firstChild.defaultValue).toBe('');
|
||||
});
|
||||
|
||||
it('should throw if both checkedLink and valueLink are provided', function() {
|
||||
var node = document.createElement('div');
|
||||
var link = new ReactLink(true, jest.fn());
|
||||
@@ -407,21 +479,21 @@ describe('ReactDOMInput', function() {
|
||||
|
||||
it('should warn if value is null', function() {
|
||||
ReactTestUtils.renderIntoDocument(<input type="text" value={null} />);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'`value` prop on `input` should not be null. ' +
|
||||
'Consider using the empty string to clear the component or `undefined` ' +
|
||||
'for uncontrolled components.'
|
||||
);
|
||||
|
||||
ReactTestUtils.renderIntoDocument(<input type="text" value={null} />);
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
});
|
||||
|
||||
it('should warn if checked and defaultChecked props are specified', function() {
|
||||
ReactTestUtils.renderIntoDocument(
|
||||
<input type="radio" checked={true} defaultChecked={true} readOnly={true} />
|
||||
);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'A component contains an input of type radio with both checked and defaultChecked props. ' +
|
||||
'Input elements must be either controlled or uncontrolled ' +
|
||||
'(specify either the checked prop, or the defaultChecked prop, but not ' +
|
||||
@@ -433,14 +505,14 @@ describe('ReactDOMInput', function() {
|
||||
ReactTestUtils.renderIntoDocument(
|
||||
<input type="radio" checked={true} defaultChecked={true} readOnly={true} />
|
||||
);
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
});
|
||||
|
||||
it('should warn if value and defaultValue props are specified', function() {
|
||||
ReactTestUtils.renderIntoDocument(
|
||||
<input type="text" value="foo" defaultValue="bar" readOnly={true} />
|
||||
);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'A component contains an input of type text with both value and defaultValue props. ' +
|
||||
'Input elements must be either controlled or uncontrolled ' +
|
||||
'(specify either the value prop, or the defaultValue prop, but not ' +
|
||||
@@ -452,7 +524,7 @@ describe('ReactDOMInput', function() {
|
||||
ReactTestUtils.renderIntoDocument(
|
||||
<input type="text" value="foo" defaultValue="bar" readOnly={true} />
|
||||
);
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
});
|
||||
|
||||
it('should warn if controlled input switches to uncontrolled', function() {
|
||||
@@ -460,8 +532,8 @@ describe('ReactDOMInput', function() {
|
||||
var container = document.createElement('div');
|
||||
ReactDOM.render(stub, container);
|
||||
ReactDOM.render(<input type="text" />, container);
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'A component is changing a controlled input of type text to be uncontrolled. ' +
|
||||
'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
|
||||
'Decide between using a controlled or uncontrolled input ' +
|
||||
@@ -474,8 +546,8 @@ describe('ReactDOMInput', function() {
|
||||
var container = document.createElement('div');
|
||||
ReactDOM.render(stub, container);
|
||||
ReactDOM.render(<input type="text" defaultValue="uncontrolled" />, container);
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'A component is changing a controlled input of type text to be uncontrolled. ' +
|
||||
'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
|
||||
'Decide between using a controlled or uncontrolled input ' +
|
||||
@@ -488,8 +560,8 @@ describe('ReactDOMInput', function() {
|
||||
var container = document.createElement('div');
|
||||
ReactDOM.render(stub, container);
|
||||
ReactDOM.render(<input type="text" value="controlled" />, container);
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'A component is changing an uncontrolled input of type text to be controlled. ' +
|
||||
'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
|
||||
'Decide between using a controlled or uncontrolled input ' +
|
||||
@@ -502,8 +574,8 @@ describe('ReactDOMInput', function() {
|
||||
var container = document.createElement('div');
|
||||
ReactDOM.render(stub, container);
|
||||
ReactDOM.render(<input type="checkbox" />, container);
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'A component is changing a controlled input of type checkbox to be uncontrolled. ' +
|
||||
'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
|
||||
'Decide between using a controlled or uncontrolled input ' +
|
||||
@@ -516,8 +588,8 @@ describe('ReactDOMInput', function() {
|
||||
var container = document.createElement('div');
|
||||
ReactDOM.render(stub, container);
|
||||
ReactDOM.render(<input type="checkbox" defaultChecked={true} />, container);
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'A component is changing a controlled input of type checkbox to be uncontrolled. ' +
|
||||
'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
|
||||
'Decide between using a controlled or uncontrolled input ' +
|
||||
@@ -530,8 +602,8 @@ describe('ReactDOMInput', function() {
|
||||
var container = document.createElement('div');
|
||||
ReactDOM.render(stub, container);
|
||||
ReactDOM.render(<input type="checkbox" checked={true} />, container);
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'A component is changing an uncontrolled input of type checkbox to be controlled. ' +
|
||||
'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
|
||||
'Decide between using a controlled or uncontrolled input ' +
|
||||
@@ -544,8 +616,8 @@ describe('ReactDOMInput', function() {
|
||||
var container = document.createElement('div');
|
||||
ReactDOM.render(stub, container);
|
||||
ReactDOM.render(<input type="radio" />, container);
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'A component is changing a controlled input of type radio to be uncontrolled. ' +
|
||||
'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
|
||||
'Decide between using a controlled or uncontrolled input ' +
|
||||
@@ -558,8 +630,8 @@ describe('ReactDOMInput', function() {
|
||||
var container = document.createElement('div');
|
||||
ReactDOM.render(stub, container);
|
||||
ReactDOM.render(<input type="radio" defaultChecked={true} />, container);
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'A component is changing a controlled input of type radio to be uncontrolled. ' +
|
||||
'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
|
||||
'Decide between using a controlled or uncontrolled input ' +
|
||||
@@ -572,8 +644,8 @@ describe('ReactDOMInput', function() {
|
||||
var container = document.createElement('div');
|
||||
ReactDOM.render(stub, container);
|
||||
ReactDOM.render(<input type="radio" checked={true} />, container);
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'A component is changing an uncontrolled input of type radio to be controlled. ' +
|
||||
'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
|
||||
'Decide between using a controlled or uncontrolled input ' +
|
||||
@@ -581,13 +653,49 @@ describe('ReactDOMInput', function() {
|
||||
);
|
||||
});
|
||||
|
||||
it('should not warn if radio value changes but never becomes controlled', function() {
|
||||
var container = document.createElement('div');
|
||||
ReactDOM.render(<input type="radio" value="value" />, container);
|
||||
ReactDOM.render(<input type="radio" />, container);
|
||||
ReactDOM.render(<input type="radio" value="value" defaultChecked={true} />, container);
|
||||
ReactDOM.render(<input type="radio" value="value" onChange={() => null} />, container);
|
||||
ReactDOM.render(<input type="radio" />, container);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
it('should not warn if radio value changes but never becomes uncontrolled', function() {
|
||||
var container = document.createElement('div');
|
||||
ReactDOM.render(<input type="radio" checked={false} onChange={() => null} />, container);
|
||||
ReactDOM.render(
|
||||
<input
|
||||
type="radio"
|
||||
value="value"
|
||||
defaultChecked={true}
|
||||
checked={false}
|
||||
onChange={() => null}
|
||||
/>, container);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
});
|
||||
|
||||
it('should warn if radio checked false changes to become uncontrolled', function() {
|
||||
var container = document.createElement('div');
|
||||
ReactDOM.render(<input type="radio" value="value" checked={false} onChange={() => null} />, container);
|
||||
ReactDOM.render(<input type="radio" value="value" />, container);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'A component is changing a controlled input of type radio to be uncontrolled. ' +
|
||||
'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
|
||||
'Decide between using a controlled or uncontrolled input ' +
|
||||
'element for the lifetime of the component. More info: https://fb.me/react-controlled-components'
|
||||
);
|
||||
});
|
||||
|
||||
it('sets type before value always', function() {
|
||||
if (!ReactDOMFeatureFlags.useCreateElement) {
|
||||
return;
|
||||
}
|
||||
var log = [];
|
||||
var originalCreateElement = document.createElement;
|
||||
spyOn(document, 'createElement').andCallFake(function(type) {
|
||||
spyOn(document, 'createElement').and.callFake(function(type) {
|
||||
var el = originalCreateElement.apply(this, arguments);
|
||||
if (type === 'input') {
|
||||
Object.defineProperty(el, 'value', {
|
||||
@@ -596,7 +704,7 @@ describe('ReactDOMInput', function() {
|
||||
log.push('set value');
|
||||
},
|
||||
});
|
||||
spyOn(el, 'setAttribute').andCallFake(function(name, value) {
|
||||
spyOn(el, 'setAttribute').and.callFake(function(name, value) {
|
||||
log.push('set ' + name);
|
||||
});
|
||||
}
|
||||
@@ -609,6 +717,11 @@ describe('ReactDOMInput', function() {
|
||||
'set data-reactroot',
|
||||
'set type',
|
||||
'set value',
|
||||
'set value',
|
||||
'set name',
|
||||
'set checked',
|
||||
'set checked',
|
||||
'set name',
|
||||
]);
|
||||
});
|
||||
|
||||
|
||||
@@ -31,26 +31,16 @@ describe('ReactDOMOption', function() {
|
||||
expect(node.innerHTML).toBe('1 foo');
|
||||
});
|
||||
|
||||
it('should ignore invalid children types', function() {
|
||||
it('should ignore and warn invalid children types', function() {
|
||||
spyOn(console, 'error');
|
||||
var stub = <option>{1} <div /> {2}</option>;
|
||||
stub = ReactTestUtils.renderIntoDocument(stub);
|
||||
var node = ReactDOM.findDOMNode(stub);
|
||||
|
||||
expect(node.innerHTML).toBe('1 2');
|
||||
expect(console.error.calls.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain('Only strings and numbers are supported as <option> children.');
|
||||
});
|
||||
|
||||
it('should warn when passing invalid children', function() {
|
||||
var stub = <option>{1} <div /></option>;
|
||||
spyOn(console, 'error');
|
||||
stub = ReactTestUtils.renderIntoDocument(stub);
|
||||
|
||||
expect(console.error.calls.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
'Only strings and numbers are supported as <option> children.'
|
||||
);
|
||||
ReactTestUtils.renderIntoDocument(<option>{1} <div /> {2}</option>);
|
||||
// only warn once
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain('Only strings and numbers are supported as <option> children.');
|
||||
});
|
||||
|
||||
it('should ignore null/undefined/false children without warning', function() {
|
||||
@@ -60,7 +50,7 @@ describe('ReactDOMOption', function() {
|
||||
|
||||
var node = ReactDOM.findDOMNode(stub);
|
||||
|
||||
expect(console.error.calls.length).toBe(0);
|
||||
expect(console.error.calls.count()).toBe(0);
|
||||
expect(node.innerHTML).toBe('1 2');
|
||||
});
|
||||
|
||||
@@ -82,4 +72,26 @@ describe('ReactDOMOption', function() {
|
||||
expect(option.hasAttribute('value')).toBe(true);
|
||||
expect(option.getAttribute('value')).toBe('lava');
|
||||
});
|
||||
|
||||
it('should allow ignoring `value` on option', function() {
|
||||
var a = 'a';
|
||||
var stub =
|
||||
<select value="giraffe" onChange={() => {}}>
|
||||
<option>monkey</option>
|
||||
<option>gir{a}ffe</option>
|
||||
<option>gorill{a}</option>
|
||||
</select>;
|
||||
var options = stub.props.children;
|
||||
var container = document.createElement('div');
|
||||
stub = ReactDOM.render(stub, container);
|
||||
var node = ReactDOM.findDOMNode(stub);
|
||||
|
||||
expect(node.selectedIndex).toBe(1);
|
||||
|
||||
ReactDOM.render(
|
||||
<select value="gorilla">{options}</select>,
|
||||
container
|
||||
);
|
||||
expect(node.selectedIndex).toEqual(2);
|
||||
});
|
||||
});
|
||||
@@ -360,8 +360,8 @@ describe('ReactDOMSelect', function() {
|
||||
|
||||
stub = ReactTestUtils.renderIntoDocument(stub);
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'`valueLink` prop on `select` is deprecated; set `value` and `onChange` instead.'
|
||||
);
|
||||
|
||||
@@ -466,14 +466,14 @@ describe('ReactDOMSelect', function() {
|
||||
spyOn(console, 'error');
|
||||
|
||||
ReactTestUtils.renderIntoDocument(<select value={null}><option value="test"/></select>);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'`value` prop on `select` should not be null. ' +
|
||||
'Consider using the empty string to clear the component or `undefined` ' +
|
||||
'for uncontrolled components.'
|
||||
);
|
||||
|
||||
ReactTestUtils.renderIntoDocument(<select value={null}><option value="test"/></select>);
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
});
|
||||
|
||||
it('should refresh state on change', function() {
|
||||
@@ -500,7 +500,7 @@ describe('ReactDOMSelect', function() {
|
||||
<option value="gorilla">A gorilla!</option>
|
||||
</select>
|
||||
);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'Select elements must be either controlled or uncontrolled ' +
|
||||
'(specify either the value prop, or the defaultValue prop, but not ' +
|
||||
'both). Decide between using a controlled or uncontrolled select ' +
|
||||
@@ -515,7 +515,7 @@ describe('ReactDOMSelect', function() {
|
||||
<option value="gorilla">A gorilla!</option>
|
||||
</select>
|
||||
);
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
});
|
||||
|
||||
it('should be able to safely remove select onChange', function() {
|
||||
|
||||
@@ -16,6 +16,7 @@ var emptyFunction = require('emptyFunction');
|
||||
describe('ReactDOMTextarea', function() {
|
||||
var React;
|
||||
var ReactDOM;
|
||||
var ReactDOMServer;
|
||||
var ReactLink;
|
||||
var ReactTestUtils;
|
||||
|
||||
@@ -24,6 +25,7 @@ describe('ReactDOMTextarea', function() {
|
||||
beforeEach(function() {
|
||||
React = require('React');
|
||||
ReactDOM = require('ReactDOM');
|
||||
ReactDOMServer = require('ReactDOMServer');
|
||||
ReactLink = require('ReactLink');
|
||||
ReactTestUtils = require('ReactTestUtils');
|
||||
|
||||
@@ -31,39 +33,41 @@ describe('ReactDOMTextarea', function() {
|
||||
if (!container) {
|
||||
container = document.createElement('div');
|
||||
}
|
||||
var stub = ReactDOM.render(component, container);
|
||||
var node = ReactDOM.findDOMNode(stub);
|
||||
var node = ReactDOM.render(component, container);
|
||||
|
||||
// Fixing jsdom's quirky behavior -- in reality, the parser should strip
|
||||
// off the leading newline but we need to do it by hand here.
|
||||
node.value = node.innerHTML.replace(/^\n/, '');
|
||||
return stub;
|
||||
node.defaultValue = node.innerHTML.replace(/^\n/, '');
|
||||
return node;
|
||||
};
|
||||
});
|
||||
|
||||
it('should allow setting `defaultValue`', function() {
|
||||
var container = document.createElement('div');
|
||||
var stub = renderTextarea(<textarea defaultValue="giraffe" />, container);
|
||||
var node = ReactDOM.findDOMNode(stub);
|
||||
var node = renderTextarea(<textarea defaultValue="giraffe" />, container);
|
||||
|
||||
expect(node.value).toBe('giraffe');
|
||||
|
||||
// Changing `defaultValue` should do nothing.
|
||||
stub = renderTextarea(<textarea defaultValue="gorilla" />, container);
|
||||
renderTextarea(<textarea defaultValue="gorilla" />, container);
|
||||
expect(node.value).toEqual('giraffe');
|
||||
|
||||
node.value = 'cat';
|
||||
|
||||
renderTextarea(<textarea defaultValue="monkey" />, container);
|
||||
expect(node.value).toEqual('cat');
|
||||
});
|
||||
|
||||
it('should display `defaultValue` of number 0', function() {
|
||||
var stub = <textarea defaultValue={0} />;
|
||||
stub = renderTextarea(stub);
|
||||
var node = ReactDOM.findDOMNode(stub);
|
||||
var node = renderTextarea(stub);
|
||||
|
||||
expect(node.value).toBe('0');
|
||||
});
|
||||
|
||||
it('should display "false" for `defaultValue` of `false`', function() {
|
||||
var stub = <textarea defaultValue={false} />;
|
||||
stub = renderTextarea(stub);
|
||||
var node = ReactDOM.findDOMNode(stub);
|
||||
var node = renderTextarea(stub);
|
||||
|
||||
expect(node.value).toBe('false');
|
||||
});
|
||||
@@ -76,33 +80,44 @@ describe('ReactDOMTextarea', function() {
|
||||
};
|
||||
|
||||
var stub = <textarea defaultValue={objToString} />;
|
||||
stub = renderTextarea(stub);
|
||||
var node = ReactDOM.findDOMNode(stub);
|
||||
var node = renderTextarea(stub);
|
||||
|
||||
expect(node.value).toBe('foobar');
|
||||
});
|
||||
|
||||
it('should set defaultValue', function() {
|
||||
var container = document.createElement('div');
|
||||
ReactDOM.render(<textarea defaultValue="foo" />, container);
|
||||
ReactDOM.render(<textarea defaultValue="bar" />, container);
|
||||
ReactDOM.render(<textarea defaultValue="noise" />, container);
|
||||
expect(container.firstChild.defaultValue).toBe('noise');
|
||||
});
|
||||
|
||||
it('should not render value as an attribute', function() {
|
||||
var stub = <textarea value="giraffe" onChange={emptyFunction} />;
|
||||
stub = renderTextarea(stub);
|
||||
var node = ReactDOM.findDOMNode(stub);
|
||||
var node = renderTextarea(stub);
|
||||
|
||||
expect(node.getAttribute('value')).toBe(null);
|
||||
});
|
||||
|
||||
it('should display `value` of number 0', function() {
|
||||
var stub = <textarea value={0} />;
|
||||
stub = renderTextarea(stub);
|
||||
var node = ReactDOM.findDOMNode(stub);
|
||||
var node = renderTextarea(stub);
|
||||
|
||||
expect(node.value).toBe('0');
|
||||
});
|
||||
|
||||
it('should update defaultValue to empty string', function() {
|
||||
var container = document.createElement('div');
|
||||
ReactDOM.render(<textarea defaultValue={'foo'} />, container);
|
||||
ReactDOM.render(<textarea defaultValue={''} />, container);
|
||||
expect(container.firstChild.defaultValue).toBe('');
|
||||
});
|
||||
|
||||
it('should allow setting `value` to `giraffe`', function() {
|
||||
var container = document.createElement('div');
|
||||
var stub = <textarea value="giraffe" onChange={emptyFunction} />;
|
||||
stub = renderTextarea(stub, container);
|
||||
var node = ReactDOM.findDOMNode(stub);
|
||||
var node = renderTextarea(stub, container);
|
||||
|
||||
expect(node.value).toBe('giraffe');
|
||||
|
||||
@@ -113,11 +128,27 @@ describe('ReactDOMTextarea', function() {
|
||||
expect(node.value).toEqual('gorilla');
|
||||
});
|
||||
|
||||
it('should render defaultValue for SSR', function() {
|
||||
var markup = ReactDOMServer.renderToString(<textarea defaultValue="1" />);
|
||||
var div = document.createElement('div');
|
||||
div.innerHTML = markup;
|
||||
expect(div.firstChild.innerHTML).toBe('1');
|
||||
expect(div.firstChild.getAttribute('defaultValue')).toBe(null);
|
||||
});
|
||||
|
||||
it('should render value for SSR', function() {
|
||||
var element = <textarea value="1" onChange={function() {}} />;
|
||||
var markup = ReactDOMServer.renderToString(element);
|
||||
var div = document.createElement('div');
|
||||
div.innerHTML = markup;
|
||||
expect(div.firstChild.innerHTML).toBe('1');
|
||||
expect(div.firstChild.getAttribute('defaultValue')).toBe(null);
|
||||
});
|
||||
|
||||
it('should allow setting `value` to `true`', function() {
|
||||
var container = document.createElement('div');
|
||||
var stub = <textarea value="giraffe" onChange={emptyFunction} />;
|
||||
stub = renderTextarea(stub, container);
|
||||
var node = ReactDOM.findDOMNode(stub);
|
||||
var node = renderTextarea(stub, container);
|
||||
|
||||
expect(node.value).toBe('giraffe');
|
||||
|
||||
@@ -131,8 +162,7 @@ describe('ReactDOMTextarea', function() {
|
||||
it('should allow setting `value` to `false`', function() {
|
||||
var container = document.createElement('div');
|
||||
var stub = <textarea value="giraffe" onChange={emptyFunction} />;
|
||||
stub = renderTextarea(stub, container);
|
||||
var node = ReactDOM.findDOMNode(stub);
|
||||
var node = renderTextarea(stub, container);
|
||||
|
||||
expect(node.value).toBe('giraffe');
|
||||
|
||||
@@ -146,8 +176,7 @@ describe('ReactDOMTextarea', function() {
|
||||
it('should allow setting `value` to `objToString`', function() {
|
||||
var container = document.createElement('div');
|
||||
var stub = <textarea value="giraffe" onChange={emptyFunction} />;
|
||||
stub = renderTextarea(stub, container);
|
||||
var node = ReactDOM.findDOMNode(stub);
|
||||
var node = renderTextarea(stub, container);
|
||||
|
||||
expect(node.value).toBe('giraffe');
|
||||
|
||||
@@ -163,10 +192,58 @@ describe('ReactDOMTextarea', function() {
|
||||
expect(node.value).toEqual('foo');
|
||||
});
|
||||
|
||||
it('should take updates to `defaultValue` for uncontrolled textarea', function() {
|
||||
var container = document.createElement('div');
|
||||
|
||||
var node = ReactDOM.render(<textarea defaultValue="0" />, container);
|
||||
|
||||
expect(node.value).toBe('0');
|
||||
|
||||
ReactDOM.render(<textarea defaultValue="1" />, container);
|
||||
|
||||
expect(node.value).toBe('0');
|
||||
});
|
||||
|
||||
it('should take updates to children in lieu of `defaultValue` for uncontrolled textarea', function() {
|
||||
var container = document.createElement('div');
|
||||
|
||||
var node = ReactDOM.render(<textarea defaultValue="0" />, container);
|
||||
|
||||
expect(node.value).toBe('0');
|
||||
|
||||
spyOn(console, 'error'); // deprecation warning for `children` content
|
||||
|
||||
ReactDOM.render(<textarea>1</textarea>, container);
|
||||
|
||||
expect(node.value).toBe('0');
|
||||
});
|
||||
|
||||
it('should not incur unnecessary DOM mutations', function() {
|
||||
var container = document.createElement('div');
|
||||
ReactDOM.render(<textarea value="a" onChange={emptyFunction} />, container);
|
||||
|
||||
var node = container.firstChild;
|
||||
var nodeValue = 'a';
|
||||
var nodeValueSetter = jest.genMockFn();
|
||||
Object.defineProperty(node, 'value', {
|
||||
get: function() {
|
||||
return nodeValue;
|
||||
},
|
||||
set: nodeValueSetter.mockImplementation(function(newValue) {
|
||||
nodeValue = newValue;
|
||||
}),
|
||||
});
|
||||
|
||||
ReactDOM.render(<textarea value="a" onChange={emptyFunction} />, container);
|
||||
expect(nodeValueSetter.mock.calls.length).toBe(0);
|
||||
|
||||
ReactDOM.render(<textarea value="b" onChange={emptyFunction} />, container);
|
||||
expect(nodeValueSetter.mock.calls.length).toBe(1);
|
||||
});
|
||||
|
||||
it('should properly control a value of number `0`', function() {
|
||||
var stub = <textarea value={0} onChange={emptyFunction} />;
|
||||
stub = renderTextarea(stub);
|
||||
var node = ReactDOM.findDOMNode(stub);
|
||||
var node = renderTextarea(stub);
|
||||
|
||||
node.value = 'giraffe';
|
||||
ReactTestUtils.Simulate.change(node);
|
||||
@@ -178,10 +255,9 @@ describe('ReactDOMTextarea', function() {
|
||||
|
||||
var container = document.createElement('div');
|
||||
var stub = <textarea>giraffe</textarea>;
|
||||
stub = renderTextarea(stub, container);
|
||||
var node = ReactDOM.findDOMNode(stub);
|
||||
var node = renderTextarea(stub, container);
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(node.value).toBe('giraffe');
|
||||
|
||||
// Changing children should do nothing, it functions like `defaultValue`.
|
||||
@@ -189,17 +265,45 @@ describe('ReactDOMTextarea', function() {
|
||||
expect(node.value).toEqual('giraffe');
|
||||
});
|
||||
|
||||
it('should keep value when switching to uncontrolled element if not changed', function() {
|
||||
var container = document.createElement('div');
|
||||
|
||||
var node = renderTextarea(<textarea value="kitten" onChange={emptyFunction} />, container);
|
||||
|
||||
expect(node.value).toBe('kitten');
|
||||
|
||||
ReactDOM.render(<textarea defaultValue="gorilla"></textarea>, container);
|
||||
|
||||
expect(node.value).toEqual('kitten');
|
||||
});
|
||||
|
||||
it('should keep value when switching to uncontrolled element if changed', function() {
|
||||
var container = document.createElement('div');
|
||||
|
||||
var node = renderTextarea(<textarea value="kitten" onChange={emptyFunction} />, container);
|
||||
|
||||
expect(node.value).toBe('kitten');
|
||||
|
||||
ReactDOM.render(<textarea value="puppies" onChange={emptyFunction}></textarea>, container);
|
||||
|
||||
expect(node.value).toBe('puppies');
|
||||
|
||||
ReactDOM.render(<textarea defaultValue="gorilla"></textarea>, container);
|
||||
|
||||
expect(node.value).toEqual('puppies');
|
||||
});
|
||||
|
||||
it('should allow numbers as children', function() {
|
||||
spyOn(console, 'error');
|
||||
var node = ReactDOM.findDOMNode(renderTextarea(<textarea>{17}</textarea>));
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
var node = renderTextarea(<textarea>{17}</textarea>);
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(node.value).toBe('17');
|
||||
});
|
||||
|
||||
it('should allow booleans as children', function() {
|
||||
spyOn(console, 'error');
|
||||
var node = ReactDOM.findDOMNode(renderTextarea(<textarea>{false}</textarea>));
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
var node = renderTextarea(<textarea>{false}</textarea>);
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(node.value).toBe('false');
|
||||
});
|
||||
|
||||
@@ -210,8 +314,8 @@ describe('ReactDOMTextarea', function() {
|
||||
return 'sharkswithlasers';
|
||||
},
|
||||
};
|
||||
var node = ReactDOM.findDOMNode(renderTextarea(<textarea>{obj}</textarea>));
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
var node = renderTextarea(<textarea>{obj}</textarea>);
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(node.value).toBe('sharkswithlasers');
|
||||
});
|
||||
|
||||
@@ -224,16 +328,16 @@ describe('ReactDOMTextarea', function() {
|
||||
);
|
||||
}).toThrow();
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
|
||||
var node;
|
||||
expect(function() {
|
||||
node = ReactDOM.findDOMNode(renderTextarea(<textarea><strong /></textarea>));
|
||||
node = renderTextarea(<textarea><strong /></textarea>);
|
||||
}).not.toThrow();
|
||||
|
||||
expect(node.value).toBe('[object Object]');
|
||||
|
||||
expect(console.error.argsForCall.length).toBe(2);
|
||||
expect(console.error.calls.count()).toBe(2);
|
||||
});
|
||||
|
||||
it('should support ReactLink', function() {
|
||||
@@ -242,18 +346,18 @@ describe('ReactDOMTextarea', function() {
|
||||
|
||||
spyOn(console, 'error');
|
||||
instance = renderTextarea(instance);
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'`valueLink` prop on `textarea` is deprecated; set `value` and `onChange` instead.'
|
||||
);
|
||||
|
||||
|
||||
expect(ReactDOM.findDOMNode(instance).value).toBe('yolo');
|
||||
expect(instance.value).toBe('yolo');
|
||||
expect(link.value).toBe('yolo');
|
||||
expect(link.requestChange.mock.calls.length).toBe(0);
|
||||
|
||||
ReactDOM.findDOMNode(instance).value = 'test';
|
||||
ReactTestUtils.Simulate.change(ReactDOM.findDOMNode(instance));
|
||||
instance.value = 'test';
|
||||
ReactTestUtils.Simulate.change(instance);
|
||||
|
||||
expect(link.requestChange.mock.calls.length).toBe(1);
|
||||
expect(link.requestChange.mock.calls[0][0]).toEqual('test');
|
||||
@@ -269,14 +373,14 @@ describe('ReactDOMTextarea', function() {
|
||||
spyOn(console, 'error');
|
||||
|
||||
ReactTestUtils.renderIntoDocument(<textarea value={null} />);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'`value` prop on `textarea` should not be null. ' +
|
||||
'Consider using the empty string to clear the component or `undefined` ' +
|
||||
'for uncontrolled components.'
|
||||
);
|
||||
|
||||
ReactTestUtils.renderIntoDocument(<textarea value={null} />);
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
});
|
||||
|
||||
it('should warn if value and defaultValue are specified', function() {
|
||||
@@ -284,7 +388,7 @@ describe('ReactDOMTextarea', function() {
|
||||
ReactTestUtils.renderIntoDocument(
|
||||
<textarea value="foo" defaultValue="bar" readOnly={true} />
|
||||
);
|
||||
expect(console.error.argsForCall[0][0]).toContain(
|
||||
expect(console.error.calls.argsFor(0)[0]).toContain(
|
||||
'Textarea elements must be either controlled or uncontrolled ' +
|
||||
'(specify either the value prop, or the defaultValue prop, but not ' +
|
||||
'both). Decide between using a controlled or uncontrolled textarea ' +
|
||||
@@ -295,6 +399,7 @@ describe('ReactDOMTextarea', function() {
|
||||
ReactTestUtils.renderIntoDocument(
|
||||
<textarea value="foo" defaultValue="bar" readOnly={true} />
|
||||
);
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
});
|
||||
|
||||
});
|
||||
@@ -232,9 +232,15 @@ describe('ReactServerRendering', function() {
|
||||
ExecutionEnvironment.canUseDOM = true;
|
||||
element.innerHTML = lastMarkup;
|
||||
|
||||
ReactDOM.render(<TestComponent name="x" />, element);
|
||||
var instance = ReactDOM.render(<TestComponent name="x" />, element);
|
||||
expect(mountCount).toEqual(3);
|
||||
expect(element.innerHTML).toBe(lastMarkup);
|
||||
|
||||
// Ensure the events system works after mount into server markup
|
||||
expect(numClicks).toEqual(0);
|
||||
ReactTestUtils.Simulate.click(ReactDOM.findDOMNode(instance.refs.span));
|
||||
expect(numClicks).toEqual(1);
|
||||
|
||||
ReactDOM.unmountComponentAtNode(element);
|
||||
expect(element.innerHTML).toEqual('');
|
||||
|
||||
@@ -242,16 +248,16 @@ describe('ReactServerRendering', function() {
|
||||
// warn but do the right thing.
|
||||
element.innerHTML = lastMarkup;
|
||||
spyOn(console, 'error');
|
||||
var instance = ReactDOM.render(<TestComponent name="y" />, element);
|
||||
instance = ReactDOM.render(<TestComponent name="y" />, element);
|
||||
expect(mountCount).toEqual(4);
|
||||
expect(console.error.argsForCall.length).toBe(1);
|
||||
expect(console.error.calls.count()).toBe(1);
|
||||
expect(element.innerHTML.length > 0).toBe(true);
|
||||
expect(element.innerHTML).not.toEqual(lastMarkup);
|
||||
|
||||
// Ensure the events system works
|
||||
expect(numClicks).toEqual(0);
|
||||
ReactTestUtils.Simulate.click(ReactDOM.findDOMNode(instance.refs.span));
|
||||
// Ensure the events system works after markup mismatch.
|
||||
expect(numClicks).toEqual(1);
|
||||
ReactTestUtils.Simulate.click(ReactDOM.findDOMNode(instance.refs.span));
|
||||
expect(numClicks).toEqual(2);
|
||||
});
|
||||
|
||||
it('should throw with silly args', function() {
|
||||
@@ -260,7 +266,7 @@ describe('ReactServerRendering', function() {
|
||||
ReactServerRendering,
|
||||
'not a component'
|
||||
)
|
||||
).toThrow(
|
||||
).toThrowError(
|
||||
'renderToString(): You must pass a valid ReactElement.'
|
||||
);
|
||||
});
|
||||
@@ -369,7 +375,7 @@ describe('ReactServerRendering', function() {
|
||||
ReactServerRendering,
|
||||
'not a component'
|
||||
)
|
||||
).toThrow(
|
||||
).toThrowError(
|
||||
'renderToStaticMarkup(): You must pass a valid ReactElement.'
|
||||
);
|
||||
});
|
||||
|
||||
@@ -193,7 +193,7 @@ var CSSPropertyOperations = {
|
||||
*/
|
||||
setValueForStyles: function(node, styles, component) {
|
||||
if (__DEV__) {
|
||||
ReactInstrumentation.debugTool.onNativeOperation(
|
||||
ReactInstrumentation.debugTool.onHostOperation(
|
||||
component._debugID,
|
||||
'update styles',
|
||||
styles
|
||||
|
||||
@@ -166,7 +166,7 @@ var DOMProperty = {
|
||||
ROOT_ATTRIBUTE_NAME: 'data-reactroot',
|
||||
|
||||
ATTRIBUTE_NAME_START_CHAR: ATTRIBUTE_NAME_START_CHAR,
|
||||
ATTRIBUTE_NAME_CHAR: ATTRIBUTE_NAME_START_CHAR + '\\-.0-9\\uB7\\u0300-\\u036F\\u203F-\\u2040',
|
||||
ATTRIBUTE_NAME_CHAR: ATTRIBUTE_NAME_START_CHAR + '\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040',
|
||||
|
||||
/**
|
||||
* Map from property "standard name" to an object with info about how to set
|
||||
|
||||
@@ -177,7 +177,7 @@ var DOMPropertyOperations = {
|
||||
ReactDOMInstrumentation.debugTool.onSetValueForProperty(node, name, value);
|
||||
var payload = {};
|
||||
payload[name] = value;
|
||||
ReactInstrumentation.debugTool.onNativeOperation(
|
||||
ReactInstrumentation.debugTool.onHostOperation(
|
||||
ReactDOMComponentTree.getInstanceFromNode(node)._debugID,
|
||||
'update attribute',
|
||||
payload
|
||||
@@ -198,7 +198,7 @@ var DOMPropertyOperations = {
|
||||
if (__DEV__) {
|
||||
var payload = {};
|
||||
payload[name] = value;
|
||||
ReactInstrumentation.debugTool.onNativeOperation(
|
||||
ReactInstrumentation.debugTool.onHostOperation(
|
||||
ReactDOMComponentTree.getInstanceFromNode(node)._debugID,
|
||||
'update attribute',
|
||||
payload
|
||||
@@ -206,6 +206,24 @@ var DOMPropertyOperations = {
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Deletes an attributes from a node.
|
||||
*
|
||||
* @param {DOMElement} node
|
||||
* @param {string} name
|
||||
*/
|
||||
deleteValueForAttribute: function(node, name) {
|
||||
node.removeAttribute(name);
|
||||
if (__DEV__) {
|
||||
ReactDOMInstrumentation.debugTool.onDeleteValueForProperty(node, name);
|
||||
ReactInstrumentation.debugTool.onHostOperation(
|
||||
ReactDOMComponentTree.getInstanceFromNode(node)._debugID,
|
||||
'remove attribute',
|
||||
name
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Deletes the value for a property on a node.
|
||||
*
|
||||
@@ -239,7 +257,7 @@ var DOMPropertyOperations = {
|
||||
|
||||
if (__DEV__) {
|
||||
ReactDOMInstrumentation.debugTool.onDeleteValueForProperty(node, name);
|
||||
ReactInstrumentation.debugTool.onNativeOperation(
|
||||
ReactInstrumentation.debugTool.onHostOperation(
|
||||
ReactDOMComponentTree.getInstanceFromNode(node)._debugID,
|
||||
'remove attribute',
|
||||
name
|
||||
|
||||
@@ -15,7 +15,6 @@ var DOMProperty = require('DOMProperty');
|
||||
|
||||
var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY;
|
||||
var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE;
|
||||
var HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS;
|
||||
var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE;
|
||||
var HAS_POSITIVE_NUMERIC_VALUE =
|
||||
DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE;
|
||||
@@ -153,7 +152,7 @@ var HTMLDOMPropertyConfig = {
|
||||
// Setting .type throws on non-<input> tags
|
||||
type: 0,
|
||||
useMap: 0,
|
||||
value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS,
|
||||
value: 0,
|
||||
width: 0,
|
||||
wmode: 0,
|
||||
wrap: 0,
|
||||
|
||||
Loaded 100 of 220 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user