Fixed merge conflicts in ReactNative.js and ReactMethodsMixin.js

This commit is contained in:
Dominic Gannaway committed 2017-03-21 14:10:04 +00:00
commit 4a578dbc65
93 files changed
+1291 -3660

No files matched your search

+1 -1
View File
@@ -36,4 +36,4 @@ suppress_comment=\\(.\\|\n\\)*\\$FlowFixedInNextDeploy
suppress_comment=\\(.\\|\n\\)*\\$FlowExpectedError
[version]
^0.37.0
^0.41.0
-2
View File
@@ -63,8 +63,6 @@ script:
curl \
-F "react=@build/react.js" \
-F "react.min=@build/react.min.js" \
-F "react-with-addons=@build/react-with-addons.js" \
-F "react-with-addons.min=@build/react-with-addons.min.js" \
-F "react-dom=@build/react-dom.js" \
-F "react-dom.min=@build/react-dom.min.js" \
-F "react-dom-server=@build/react-dom-server.js" \
-16
View File
@@ -84,10 +84,6 @@ module.exports = function(grunt) {
grunt.registerTask('npm-react-native:release', npmReactNativeTasks.buildRelease);
grunt.registerTask('npm-react-native:pack', npmReactNativeTasks.packRelease);
var npmReactAddonsTasks = require('./grunt/tasks/npm-react-addons');
grunt.registerTask('npm-react-addons:release', npmReactAddonsTasks.buildReleases);
grunt.registerTask('npm-react-addons:pack', npmReactAddonsTasks.packReleases);
var npmReactTestRendererTasks = require('./grunt/tasks/npm-react-test');
grunt.registerTask('npm-react-test:release', npmReactTestRendererTasks.buildRelease);
grunt.registerTask('npm-react-test:pack', npmReactTestRendererTasks.packRelease);
@@ -106,19 +102,11 @@ module.exports = function(grunt) {
'version-check',
'browserify:basic',
]);
grunt.registerTask('build:addons', [
'build-modules',
'browserify:addons',
]);
grunt.registerTask('build:min', [
'build-modules',
'version-check',
'browserify:min',
]);
grunt.registerTask('build:addons-min', [
'build-modules',
'browserify:addonsMin',
]);
grunt.registerTask('build:dom', [
'build-modules',
'version-check',
@@ -169,9 +157,7 @@ module.exports = function(grunt) {
'build-modules',
'version-check',
'browserify:basic',
'browserify:addons',
'browserify:min',
'browserify:addonsMin',
'browserify:dom',
'browserify:domMin',
'browserify:domServer',
@@ -184,8 +170,6 @@ module.exports = function(grunt) {
'npm-react-dom:pack',
'npm-react-native:release',
'npm-react-native:pack',
'npm-react-addons:release',
'npm-react-addons:pack',
'npm-react-test:release',
'npm-react-test:pack',
'npm-react-noop:release',
-2
View File
@@ -37,8 +37,6 @@ task :update_hashes do
map = {
'react.js' => 'dev',
'react.min.js' => 'prod',
'react-with-addons.js' => 'addons_dev',
'react-with-addons.min.js' => 'addons_prod',
'react-dom.js' => 'dom_dev',
'react-dom.min.js' => 'dom_prod',
'react-dom-server.js' => 'dom_server_dev',
+3 -3
View File
@@ -248,9 +248,9 @@ If you're using Create React App, both `Object.assign` and the object spread syn
Immutability makes tracking changes cheap. A change will always result in a new object so we only need to check if the reference to the object has changed. For example, in this regular JavaScript code:
```javascript
const x = { foo: "bar" };
const x = { foo: 'bar' };
const y = x;
y.foo = "baz";
y.foo = 'baz';
x === y; // true
```
@@ -258,7 +258,7 @@ Although `y` was edited, since it's a reference to the same object as `x`, this
```javascript
const SomeRecord = Immutable.Record({ foo: null });
const x = new SomeRecord({ foo: 'bar' });
const x = new SomeRecord({ foo: 'bar' });
const y = x.set('foo', 'baz');
x === y; // false
```
+2 -2
View File
@@ -6,7 +6,7 @@ If you use React you don't need to worry about it.
These fixtures verify that the built React distributions are usable in different environments.
**They are not running automatically.** (At least not yet, feel free to contribute to automate them.)
Run them when you make changes to how we package React, ReactDOM, and addons.
Run them when you make changes to how we package React and ReactDOM.
## How to Run
@@ -46,5 +46,5 @@ open http://localhost:9000/fixtures/webpack-alias/index.html
You should see two things:
* "Hello World" fading in with an animation.
* "Hello World" is rendered.
* No errors in the console.
-10
View File
@@ -1,15 +1,5 @@
<html>
<body>
<style>
.example-appear {
opacity: 0.01;
}
.example-appear.example-appear-active {
opacity: 1;
transition: opacity .5s ease-in;
}
</style>
<div id="container"></div>
<script src="output.js"></script>
</body>
+1 -10
View File
@@ -1,16 +1,7 @@
var React = require('react');
var CSSTransitionGroup = require('react-addons-css-transition-group');
var ReactDOM = require('react-dom');
ReactDOM.render(
React.createElement(CSSTransitionGroup, {
transitionName: 'example',
transitionAppear: true,
transitionAppearTimeout: 500,
transitionEnterTimeout: 0,
transitionLeaveTimeout: 0,
}, React.createElement('h1', null,
'Hello World!'
)),
React.createElement('h1', null, 'Hello World!'),
document.getElementById('container')
);
+1 -10
View File
@@ -1,16 +1,7 @@
var React = require('react');
var CSSTransitionGroup = require('react-addons-css-transition-group');
var ReactDOM = require('react-dom');
ReactDOM.render(
React.createElement(CSSTransitionGroup, {
transitionName: 'example',
transitionAppear: true,
transitionAppearTimeout: 500,
transitionEnterTimeout: 0,
transitionLeaveTimeout: 0,
}, React.createElement('h1', null,
'Hello World!'
)),
React.createElement('h1', null, 'Hello World!'),
document.getElementById('container')
);
-10
View File
@@ -1,15 +1,5 @@
<html>
<body>
<style>
.example-appear {
opacity: 0.01;
}
.example-appear.example-appear-active {
opacity: 1;
transition: opacity .5s ease-in;
}
</style>
<div id="container"></div>
<script src="output.js"></script>
<script>require('initialize');</script>
+1 -10
View File
@@ -1,16 +1,7 @@
var React = require('react');
var CSSTransitionGroup = require('react-addons-css-transition-group');
var ReactDOM = require('react-dom');
ReactDOM.render(
React.createElement(CSSTransitionGroup, {
transitionName: 'example',
transitionAppear: true,
transitionAppearTimeout: 500,
transitionEnterTimeout: 0,
transitionLeaveTimeout: 0,
}, React.createElement('h1', null,
'Hello World!'
)),
React.createElement('h1', null, 'Hello World!'),
document.getElementById('container')
);
+1 -1
View File
@@ -5,6 +5,6 @@
"javascript-brunch": "^2.0.0"
},
"scripts": {
"build": "rm -rf public && ln -fs ../../../../build/packages/react node_modules/react && ln -fs ../../../../build/packages/react-dom node_modules/react-dom && ln -fs ../../../../build/packages/react-addons-css-transition-group node_modules/react-addons-css-transition-group && brunch build"
"build": "rm -rf public && ln -fs ../../../../build/packages/react node_modules/react && ln -fs ../../../../build/packages/react-dom node_modules/react-dom && brunch build"
}
}
+2 -21
View File
@@ -1,30 +1,11 @@
<html>
<body>
<script src="../../build/react-with-addons.js"></script>
<script src="../../build/react.js"></script>
<script src="../../build/react-dom.js"></script>
<style>
.example-appear {
opacity: 0.01;
}
.example-appear.example-appear-active {
opacity: 1;
transition: opacity .5s ease-in;
}
</style>
<div id="container"></div>
<script>
var CSSTransitionGroup = React.addons.CSSTransitionGroup;
ReactDOM.render(
React.createElement(CSSTransitionGroup, {
transitionName: 'example',
transitionAppear: true,
transitionAppearTimeout: 500,
transitionEnterTimeout: 0,
transitionLeaveTimeout: 0,
}, React.createElement('h1', null,
'Hello World!'
)),
React.createElement('h1', null, 'Hello World!'),
document.getElementById('container')
);
</script>
+2 -21
View File
@@ -1,37 +1,18 @@
<html>
<body>
<script src="https://unpkg.com/requirejs@2.3.2/require.js"></script>
<style>
.example-appear {
opacity: 0.01;
}
.example-appear.example-appear-active {
opacity: 1;
transition: opacity .5s ease-in;
}
</style>
<div id="container"></div>
<script>
requirejs.config({
paths: {
react: '../../build/react-with-addons',
react: '../../build/react',
'react-dom': '../../build/react-dom'
}
});
require(['react', 'react-dom'], function(React, ReactDOM) {
var CSSTransitionGroup = React.addons.CSSTransitionGroup;
ReactDOM.render(
React.createElement(CSSTransitionGroup, {
transitionName: 'example',
transitionAppear: true,
transitionAppearTimeout: 500,
transitionEnterTimeout: 0,
transitionLeaveTimeout: 0,
}, React.createElement('h1', null,
'Hello World!'
)),
React.createElement('h1', null, 'Hello World!'),
document.getElementById('container')
);
});
+1 -1
View File
@@ -4,7 +4,7 @@ module.exports = {
out: 'output.js',
optimize: 'none',
paths: {
react: '../../../build/react-with-addons',
react: '../../../build/react',
'react-dom': '../../../build/react-dom',
},
};
-10
View File
@@ -1,15 +1,5 @@
<html>
<body>
<style>
.example-appear {
opacity: 0.01;
}
.example-appear.example-appear-active {
opacity: 1;
transition: opacity .5s ease-in;
}
</style>
<div id="container"></div>
<script src="https://unpkg.com/requirejs@2.3.2/require.js"></script>
<script src="output.js"></script>
+1 -10
View File
@@ -1,15 +1,6 @@
require(['react', 'react-dom'], function(React, ReactDOM) {
var CSSTransitionGroup = React.addons.CSSTransitionGroup;
ReactDOM.render(
React.createElement(CSSTransitionGroup, {
transitionName: 'example',
transitionAppear: true,
transitionAppearTimeout: 500,
transitionEnterTimeout: 0,
transitionLeaveTimeout: 0,
}, React.createElement('h1', null,
'Hello World!'
)),
React.createElement('h1', null, 'Hello World!'),
document.getElementById('container')
);
});
@@ -1,6 +1,6 @@
System.config({
paths: {
react: '../../../build/react-with-addons.js',
react: '../../../build/react.js',
'react-dom': '../../../build/react-dom.js',
},
});
@@ -1,15 +1,5 @@
<html>
<body>
<style>
.example-appear {
opacity: 0.01;
}
.example-appear.example-appear-active {
opacity: 1;
transition: opacity .5s ease-in;
}
</style>
<div id="container"></div>
<script src="output.js"></script>
</body>
+1 -10
View File
@@ -1,16 +1,7 @@
import React from 'react';
import ReactDOM from 'react-dom';
var CSSTransitionGroup = React.addons.CSSTransitionGroup;
ReactDOM.render(
React.createElement(CSSTransitionGroup, {
transitionName: 'example',
transitionAppear: true,
transitionAppearTimeout: 500,
transitionEnterTimeout: 0,
transitionLeaveTimeout: 0,
}, React.createElement('h1', null,
'Hello World!'
)),
React.createElement('h1', null, 'Hello World!'),
document.getElementById('container')
);
+2 -21
View File
@@ -1,21 +1,11 @@
<html>
<body>
<script src="https://unpkg.com/systemjs@0.19.41/dist/system.js"></script>
<style>
.example-appear {
opacity: 0.01;
}
.example-appear.example-appear-active {
opacity: 1;
transition: opacity .5s ease-in;
}
</style>
<div id="container"></div>
<script>
System.config({
paths: {
react: '../../build/react-with-addons.js',
react: '../../build/react.js',
'react-dom': '../../build/react-dom.js'
}
});
@@ -27,17 +17,8 @@
var React = deps[0];
var ReactDOM = deps[1];
var CSSTransitionGroup = React.addons.CSSTransitionGroup;
ReactDOM.render(
React.createElement(CSSTransitionGroup, {
transitionName: 'example',
transitionAppear: true,
transitionAppearTimeout: 500,
transitionEnterTimeout: 0,
transitionLeaveTimeout: 0,
}, React.createElement('h1', null,
'Hello World!'
)),
React.createElement('h1', null, 'Hello World!'),
document.getElementById('container')
);
});
+1 -1
View File
@@ -8,7 +8,7 @@ module.exports = {
resolve: {
root: path.resolve('../../../build/packages'),
alias: {
'react': 'react/dist/react-with-addons',
'react': 'react/dist/react',
'react-dom': 'react-dom/dist/react-dom',
},
},
@@ -1,15 +1,5 @@
<html>
<body>
<style>
.example-appear {
opacity: 0.01;
}
.example-appear.example-appear-active {
opacity: 1;
transition: opacity .5s ease-in;
}
</style>
<div id="container"></div>
<script src="output.js"></script>
</body>
+1 -10
View File
@@ -1,16 +1,7 @@
var React = require('react');
var ReactDOM = require('react-dom');
var CSSTransitionGroup = React.addons.CSSTransitionGroup;
ReactDOM.render(
React.createElement(CSSTransitionGroup, {
transitionName: 'example',
transitionAppear: true,
transitionAppearTimeout: 500,
transitionEnterTimeout: 0,
transitionLeaveTimeout: 0,
}, React.createElement('h1', null,
'Hello World!'
)),
React.createElement('h1', null, 'Hello World!'),
document.getElementById('container')
);
-10
View File
@@ -1,15 +1,5 @@
<html>
<body>
<style>
.example-appear {
opacity: 0.01;
}
.example-appear.example-appear-active {
opacity: 1;
transition: opacity .5s ease-in;
}
</style>
<div id="container"></div>
<script src="output.js"></script>
</body>
+1 -10
View File
@@ -1,16 +1,7 @@
var React = require('react');
var CSSTransitionGroup = require('react-addons-css-transition-group');
var ReactDOM = require('react-dom');
ReactDOM.render(
React.createElement(CSSTransitionGroup, {
transitionName: 'example',
transitionAppear: true,
transitionAppearTimeout: 500,
transitionEnterTimeout: 0,
transitionLeaveTimeout: 0,
}, React.createElement('h1', null,
'Hello World!'
)),
React.createElement('h1', null, 'Hello World!'),
document.getElementById('container')
);
-39
View File
@@ -21,12 +21,6 @@ var shimSharedModules = aliasify.configure({
},
});
var shimDOMModules = aliasify.configure({
'aliases': {
'./ReactAddonsDOMDependencies': {relative: './ReactAddonsDOMDependenciesUMDShim'},
},
});
var SIMPLE_TEMPLATE =
grunt.file.read('./grunt/data/header-template-short.txt');
@@ -172,37 +166,6 @@ var min = {
after: [minify, bannerify],
};
var addons = {
entries: [
'./build/node_modules/react/lib/ReactWithAddonsUMDEntry.js',
],
outfile: './build/react-with-addons.js',
debug: false,
standalone: 'React',
packageName: 'React (with addons)',
transforms: [shimDOMModules],
globalTransforms: [envifyDev],
plugins: [collapser],
after: [derequire, simpleBannerify],
};
var addonsMin = {
entries: [
'./build/node_modules/react/lib/ReactWithAddonsUMDEntry.js',
],
outfile: './build/react-with-addons.min.js',
debug: false,
standalone: 'React',
packageName: 'React (with addons)',
transforms: [shimDOMModules, envifyProd, uglifyify],
globalTransforms: [envifyProd],
plugins: [collapser],
// No need to derequire because the minifier will mangle
// the "require" calls.
after: [minify, bannerify],
};
// The DOM Builds
var dom = {
entries: [
@@ -303,8 +266,6 @@ var domFiberMin = {
module.exports = {
basic: basic,
min: min,
addons: addons,
addonsMin: addonsMin,
dom: dom,
domMin: domMin,
domServer: domServer,
-151
View File
@@ -1,151 +0,0 @@
'use strict';
var fs = require('fs');
var grunt = require('grunt');
var path = require('path');
var addons = {
CSSTransitionGroup: {
peerDependency: 'react',
module: 'ReactCSSTransitionGroup',
name: 'css-transition-group',
docs: 'animation',
},
LinkedStateMixin: {
peerDependency: 'react',
module: 'LinkedStateMixin',
name: 'linked-state-mixin',
docs: 'two-way-binding-helpers',
},
Perf: {
peerDependency: 'react-dom',
module: 'ReactPerf',
name: 'perf',
docs: 'perf',
},
PureRenderMixin: {
peerDependency: 'react',
module: 'ReactComponentWithPureRenderMixin',
name: 'pure-render-mixin',
docs: 'pure-render-mixin',
},
TestUtils: {
peerDependency: 'react-dom',
module: 'ReactTestUtils',
name: 'test-utils',
docs: 'test-utils',
},
TransitionGroup: {
peerDependency: 'react',
module: 'ReactTransitionGroup',
name: 'transition-group',
docs: 'animation',
},
createFragment: {
peerDependency: 'react',
module: 'ReactFragment',
method: 'create',
name: 'create-fragment',
docs: 'create-fragment',
},
shallowCompare: {
peerDependency: 'react',
module: 'shallowCompare',
name: 'shallow-compare',
docs: 'shallow-compare',
},
updates: {
peerDependency: 'react',
module: 'update',
name: 'update',
docs: 'update',
},
};
function generateSource(info) {
var pieces = [
'module.exports = require(\'',
info.peerDependency,
'/lib/',
info.module,
'\')',
];
if (info.method) {
pieces.push('.', info.method);
}
pieces.push(';');
return pieces.join('');
}
function buildReleases() {
var pkgTemplate = grunt.file.readJSON('./packages/react-addons/package.json');
Object.keys(addons).map(function(k) {
var info = addons[k];
var pkgName = 'react-addons-' + info.name;
var destDir = 'build/packages/' + pkgName;
var destLicense = path.join(destDir, 'LICENSE');
var destPatents = path.join(destDir, 'PATENTS');
var pkgData = Object.assign({}, pkgTemplate);
pkgData.name = pkgName;
var version = pkgTemplate.peerDependencies.react;
if (info.peerDependency !== 'react') {
pkgData.peerDependencies = {};
pkgData.peerDependencies[info.peerDependency] = version;
}
grunt.file.mkdir(destDir);
var link = info.docs ? info.docs : 'addons';
link = `https://facebook.github.io/react/docs/${link}.html`;
fs.writeFileSync(path.join(destDir, 'index.js'), generateSource(info));
fs.writeFileSync(path.join(destDir, 'package.json'), JSON.stringify(pkgData, null, 2));
grunt.file.copy('LICENSE', destLicense);
grunt.file.copy('PATENTS', destPatents);
fs.writeFileSync(
path.join(destDir, 'README.md'),
`
# ${pkgName}
This package provides the React ${k} add-on.
See <${link}> for more information.`.slice(1)
);
});
}
function packReleases() {
var done = this.async();
var count = 0;
var addonKeys = Object.keys(addons);
addonKeys.forEach(function(k) {
var info = addons[k];
var pkgName = 'react-addons-' + info.name;
var pkgDir = 'build/packages/' + pkgName;
var spawnCmd = {
cmd: 'npm',
args: ['pack', pkgDir],
};
grunt.util.spawn(spawnCmd, function() {
var buildSrc = pkgName + '-' + grunt.config.data.pkg.version + '.tgz';
var buildDest = 'build/packages/' + pkgName + '.tgz';
fs.rename(buildSrc, buildDest, maybeDone);
});
});
function maybeDone() {
if (++count === addonKeys.length) {
done();
}
}
}
module.exports = {
buildReleases: buildReleases,
packReleases: packReleases,
};
-2
View File
@@ -11,8 +11,6 @@ var dist = dest + 'dist/';
var distFiles = [
'react.js',
'react.min.js',
'react-with-addons.js',
'react-with-addons.min.js',
];
function buildRelease() {
-2
View File
@@ -7,8 +7,6 @@ var BOWER_GLOB = [BOWER_PATH + '*.{js}'];
var BOWER_FILES = [
'react.js',
'react.min.js',
'react-with-addons.js',
'react-with-addons.min.js',
'react-dom.js',
'react-dom.min.js',
'react-dom-server.js',
-5
View File
@@ -15,7 +15,6 @@ module.exports = function(gulp, plugins) {
return function(done) {
var reactVersion = require('../../package.json').version;
var addonsData = require('../../packages/react-addons/package.json');
var versions = {
'packages/react/package.json':
require('../../packages/react/package.json').version,
@@ -23,10 +22,6 @@ module.exports = function(gulp, plugins) {
require('../../packages/react-dom/package.json').version,
'packages/react-native-renderer/package.json':
require('../../packages/react-native-renderer/package.json').version,
'packages/react-addons/package.json (version)': addonsData.version,
'packages/react-addons/package.json (react dependency)':
// Get the "version" without the range bit
addonsData.peerDependencies.react.slice(1),
'packages/react-test-renderer/package.json':
require('../../packages/react-test-renderer/package.json').version,
'src/ReactVersion.js': require('../../src/ReactVersion'),
-2
View File
@@ -31,11 +31,9 @@ var paths = {
react: {
src: [
'src/umd/ReactUMDEntry.js',
'src/umd/ReactWithAddonsUMDEntry.js',
'src/umd/shims/**/*.js',
'src/isomorphic/**/*.js',
'src/addons/**/*.js',
'src/ReactVersion.js',
'src/shared/**/*.js',
+1 -1
View File
@@ -52,7 +52,7 @@
"eslint-plugin-react-internal": "file:./eslint-rules",
"fbjs": "^0.8.9",
"fbjs-scripts": "^0.6.0",
"flow-bin": "^0.37.0",
"flow-bin": "^0.41.0",
"glob": "^6.0.4",
"glob-stream": "^6.1.0",
"grunt": "^0.4.5",
@@ -1 +0,0 @@
node_modules
@@ -1,31 +0,0 @@
# JSX Orphaned Brackets Transformer
React 0.13 no longer parses orphaned > and } as text.
Take this example block:
```js
<div>
> }
</div>
```
In 0.12 and below, this would be transformed to the following:
```js
React.DOM.div(null,
"> }",
)
```
In 0.13, this will instead throw a parser error.
## Usage
The `jsx_orphaned_brackets_transformer` module ships an executable which transforms a file or directory of files. Files will be modified in place, so be sure you are prepared for that.
```sh
$ npm -g install jsx_orphaned_brackets_transformer
$ jsx_orphaned_brackets_transformer <path_to_file_or_files>
```
@@ -1,17 +0,0 @@
{
"name": "jsx_orphaned_brackets_transformer",
"description": "A utility to update your JSX to work with React 0.13.",
"version": "1.0.1",
"main": "run.js",
"dependencies": {
"graceful-fs": "~2.0.0",
"jstransform": "~8.2.0",
"node-find-files": "0.0.2",
"optimist": "~0.6.0"
},
"bin": {
"jsx_orphaned_brackets_transformer": "./run.js"
},
"license": "BSD-3-Clause",
"preferGlobal": true
}
@@ -1,166 +0,0 @@
#!/usr/bin/env node
'use strict';
var FileFinder = require('node-find-files');
var fs = require('graceful-fs');
var jstransform = require('jstransform');
var path = require('path');
var visitReactTag = require('./transforms/react').visitReactTag;
/*eslint-disable no-shadow*/
var S = jstransform.Syntax;
var USAGE =
'Read a file (or directory of files) from disk, transform any orphaned ' +
'} and > characters to avoid parser errors with React 0.13.';
function _visitFbt(node, path, state) {
return false;
}
_visitFbt.test = function(node, path, state) {
return node.type === S.XJSElement
&& node.openingElement.name.name === 'fbt';
};
var VISITORS_LIST = [
_visitFbt,
visitReactTag,
];
function _transformSource(source) {
return jstransform.transform(VISITORS_LIST, source).code;
}
function transformDir(dirPath, exclude) {
var finder = new FileFinder({
rootFolder: dirPath,
filterFunction: function(path, stat) {
return /\.jsx?$/.test(path) && (!exclude || !exclude.test(path));
},
});
var numTransforms = 0;
var completeTransforms = 0;
var findingComplete = false;
function _printProgress() {
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write(
completeTransforms + '/' + numTransforms + ' transforms complete'
);
if (findingComplete && completeTransforms === numTransforms) {
console.log('\ndone!');
}
}
finder.on('match', function(pathStr, stat) {
fs.readFile(pathStr, 'utf8', function(err, data) {
if (err) {
err.message = err.message + ' (' + pathStr + ')';
throw err;
}
numTransforms++;
_printProgress();
var transformedData;
try {
transformedData = _transformSource(data);
} catch (e) {
e.message = e.message + ' (' + pathStr + ')';
throw e;
}
if (transformedData !== data) {
fs.writeFile(pathStr, transformedData, function(err) {
if (err) {
err.message = err.message + ' (' + pathStr + ')';
throw err;
}
completeTransforms++;
_printProgress();
});
} else {
completeTransforms++;
_printProgress();
}
});
});
finder.on('error', function(err) {
console.log('\nError: ', err.stack);
throw err;
});
finder.on('complete', function() {
findingComplete = true;
});
finder.startSearch();
}
function transformFile(pathStr) {
fs.readFile(pathStr, 'utf8', function(err, data) {
if (err) {
err.message = err.message + ' (' + pathStr + ')';
throw err;
}
var transformedData;
try {
transformedData = _transformSource(data);
} catch (e) {
e.message = e.message + ' (' + pathStr + ')';
throw e;
}
if (transformedData !== data) {
fs.writeFile(pathStr, transformedData, function(err) {
if (err) {
err.message = err.message + ' (' + pathStr + ')';
throw err;
}
console.log('done!');
});
} else {
console.log('done!');
}
});
}
if (require.main === module) {
var argv = require('optimist')
.usage(USAGE)
.argv;
if (argv._.length === 0) {
throw new Error(
'Please specify a file or directory path as the first arg!'
);
}
argv._.forEach(function(arg) {
var absPath = path.resolve(arg);
fs.stat(absPath, function(err, stat) {
if (err) {
throw err;
}
if (stat.isFile()) {
transformFile(absPath);
} else if (stat.isDirectory()) {
var exclude = null;
if (argv.exclude) {
exclude = new RegExp(argv.exclude);
}
transformDir(absPath, exclude);
} else {
throw new Error('Unknown filesystem node type: ' + absPath);
}
});
});
}
exports.transformDir = transformDir;
@@ -1,52 +0,0 @@
/**
* 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.
*/
/*global exports:true*/
'use strict';
var jstransform = require('jstransform');
var Syntax = jstransform.Syntax;
var utils = require('jstransform/src/utils');
function visitReactTag(traverse, object, path, state) {
object.openingElement.attributes.forEach(function(attr, index) {
if (attr.value) {
traverse(attr.value, path, state);
}
});
object.children.forEach(function(child, index) {
if (child.type === Syntax.Literal) {
codemodXJSLiteral(child, state);
} else {
traverse(child, path, state);
}
});
return false;
}
visitReactTag.test = function(object, path, state) {
return object.type === Syntax.XJSElement;
};
function codemodXJSLiteral(object, state) {
var value = object.raw;
utils.catchup(object.range[0], state);
var rightCurlyBracket = '&#125;'; // or {'}'}
var rightAngledBracket = '&gt;'; // or {'>'}
value = value.replace(/\}/g, rightCurlyBracket);
value = value.replace(/\>/g, rightAngledBracket);
utils.append(value, state);
utils.move(object.range[1], state);
}
exports.visitReactTag = visitReactTag;
-24
View File
@@ -1,24 +0,0 @@
{
"name": "react-addons-template",
"version": "16.0.0-alpha.4",
"main": "index.js",
"repository": "facebook/react",
"keywords": [
"react",
"react-addon"
],
"license": "BSD-3-Clause",
"dependencies": {
"fbjs": "^0.8.9",
"object-assign": "^4.1.0"
},
"peerDependencies": {
"react": "^16.0.0-alpha.4"
},
"files": [
"LICENSE",
"PATENTS",
"README.md",
"index.js"
]
}
-27
View File
@@ -1,27 +0,0 @@
/**
* 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.
*/
'use strict';
var React = require('react');
var LinkedValueUtils = require('react-dom/lib/LinkedValueUtils');
class LinkedInput extends React.Component {
render() {
var newProps = Object.assign({}, this.props);
newProps.value = LinkedValueUtils.getValue(this.props);
newProps.checked = LinkedValueUtils.getChecked(this.props);
delete newProps.valueLink;
delete newProps.checkedLink;
return React.createElement('input', newProps);
}
}
module.exports = LinkedInput;
-11
View File
@@ -1,11 +0,0 @@
This component supports the ReactLink API (valueLink, etc) for input components. Support for ReactLink on DOM elements will be removed from React. This component may be used as a migration plan (so your code doesn't break in the next version of React) or may be used if you just like the ReactLink data binding semantics. However, this component is not maintained, so use at your own risk.
```
var React = require('react');
var ReactDOM = require('react-dom');
var LinkedInput = require('react-linked-input');
var link = {value: 'boo', requestChange: function() {}};
React.render(<LinkedInput valueLink={link} />, container);
```
@@ -1,42 +0,0 @@
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails react-core
*/
'use strict';
describe('LinkedStateMixin', function() {
var LinkedInput;
var React;
var ReactDOM;
beforeEach(function() {
LinkedInput = require('LinkedInput');
React = require('React');
ReactDOM = require('ReactDOM');
});
it('should basically work', function() {
var container = document.createElement('div');
var component = ReactDOM.render(<LinkedInput value="foo" onChange={function() {}} />, container);
var input = ReactDOM.findDOMNode(component);
expect(input.value).toBe('foo');
ReactDOM.render(<LinkedInput valueLink={{value: 'boo', requestChange: function() {}}} />, container);
expect(input.value).toBe('boo');
});
it('should throw', function() {
var container = document.createElement('div');
var element = <LinkedInput value="foo" valueLink={{value: 'boo', requestChange: function() {}}} />;
expect(function() {
ReactDOM.render(element, container);
}).toThrow();
});
});
-25
View File
@@ -1,25 +0,0 @@
{
"name": "react-linked-input",
"version": "1.0.1",
"description": "LinkedInput supports the ReactLink semantics",
"main": "LinkedInput.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/facebook/react.git"
},
"keywords": [
"react",
"linkedinput",
"input",
"linked",
"reactlink"
],
"author": "",
"license": "BSD-3-Clause",
"peerDependencies": {
"react": "^15.0.1"
}
}
-2
View File
@@ -6,8 +6,6 @@ if [ -z $CI_PULL_REQUEST ] && [ -n "$BUILD_SERVER_ENDPOINT" ]; then
curl \
-F "react=@build/react.js" \
-F "react.min=@build/react.min.js" \
-F "react-with-addons=@build/react-with-addons.js" \
-F "react-with-addons.min=@build/react-with-addons.min.js" \
-F "react-dom=@build/react-dom.js" \
-F "react-dom.min=@build/react-dom.min.js" \
-F "react-dom-server=@build/react-dom-server.js" \
+41
View File
@@ -6,6 +6,47 @@ src/renderers/dom/shared/__tests__/ReactDOMComponent-test.js
* gives source code refs for unknown prop warning for exact elements (ssr)
* gives source code refs for unknown prop warning for exact elements in composition (ssr)
src/renderers/dom/shared/__tests__/ReactDOMServerIntegration-test.js
* renders a blank div with client render on top of good server markup
* renders a div with inline styles with client render on top of good server markup
* renders a self-closing tag with client render on top of good server markup
* renders a self-closing tag as a child with client render on top of good server markup
* renders simple numbers with client render on top of good server markup
* renders simple strings with client render on top of good server markup
* renders string prop with true value with client render on top of good server markup
* renders string prop with false value with client render on top of good server markup
* renders boolean prop with true value with client render on top of good server markup
* renders boolean prop with false value with client render on top of good server markup
* renders boolean prop with self value with client render on top of good server markup
* renders boolean prop with "" value with client render on top of good server markup
* renders boolean prop with string value with client render on top of good server markup
* renders boolean prop with array value with client render on top of good server markup
* renders boolean prop with object value with client render on top of good server markup
* renders boolean prop with non-zero number value with client render on top of good server markup
* renders boolean prop with zero value with client render on top of good server markup
* renders download prop with true value with client render on top of good server markup
* renders download prop with false value with client render on top of good server markup
* renders download prop with string value with client render on top of good server markup
* renders download prop with string "true" value with client render on top of good server markup
* renders className prop with string value with client render on top of good server markup
* renders className prop with empty string value with client render on top of good server markup
* renders className prop with true value with client render on top of good server markup
* renders className prop with false value with client render on top of good server markup
* renders htmlFor with string value with client render on top of good server markup
* renders htmlFor with an empty string with client render on top of good server markup
* renders className prop with true value with client render on top of good server markup
* renders className prop with false value with client render on top of good server markup
* renders no ref attribute with client render on top of good server markup
* renders no children attribute with client render on top of good server markup
* renders no key attribute with client render on top of good server markup
* renders no dangerouslySetInnerHTML attribute with client render on top of good server markup
* renders no unknown attributes with client render on top of good server markup
* renders unknown data- attributes with client render on top of good server markup
* renders no unknown attributes for non-standard elements with client render on top of good server markup
* renders unknown attributes for custom elements with client render on top of good server markup
* renders unknown attributes for custom elements using is with client render on top of good server markup
* renders no HTML events with client render on top of good server markup
src/renderers/dom/shared/__tests__/ReactDOMTextComponent-test.js
* can reconcile text merged by Node.normalize() alongside other elements
* can reconcile text merged by Node.normalize()
@@ -10,6 +10,43 @@ src/renderers/dom/shared/__tests__/ReactDOMServerIntegration-test.js
* renders a div with inline styles with client render on top of bad server markup
* renders a self-closing tag with client render on top of bad server markup
* renders a self-closing tag as a child with client render on top of bad server markup
* renders simple numbers with client render on top of bad server markup
* renders simple strings with client render on top of bad server markup
* renders string prop with true value with client render on top of bad server markup
* renders string prop with false value with client render on top of bad server markup
* renders boolean prop with true value with client render on top of bad server markup
* renders boolean prop with false value with client render on top of bad server markup
* renders boolean prop with self value with client render on top of bad server markup
* renders boolean prop with "" value with client render on top of bad server markup
* renders boolean prop with string value with client render on top of bad server markup
* renders boolean prop with array value with client render on top of bad server markup
* renders boolean prop with object value with client render on top of bad server markup
* renders boolean prop with non-zero number value with client render on top of bad server markup
* renders boolean prop with zero value with client render on top of bad server markup
* renders download prop with true value with client render on top of bad server markup
* renders download prop with false value with client render on top of bad server markup
* renders download prop with string value with client render on top of bad server markup
* renders download prop with string "true" value with client render on top of bad server markup
* renders className prop with string value with client render on top of bad server markup
* renders className prop with empty string value with client render on top of bad server markup
* renders className prop with true value with client render on top of bad server markup
* renders className prop with false value with client render on top of bad server markup
* renders htmlFor with string value with client render on top of bad server markup
* renders htmlFor with an empty string with client render on top of bad server markup
* renders className prop with true value with client render on top of bad server markup
* renders className prop with false value with client render on top of bad server markup
* renders no ref attribute with client render on top of bad server markup
* renders no children attribute with client render on top of bad server markup
* renders no key attribute with client render on top of bad server markup
* renders no dangerouslySetInnerHTML attribute with client render on top of bad server markup
* renders no unknown attributes with server string render
* renders no unknown attributes with client render on top of bad server markup
* renders unknown data- attributes with client render on top of bad server markup
* renders no unknown attributes for non-standard elements with server string render
* renders no unknown attributes for non-standard elements with client render on top of bad server markup
* renders unknown attributes for custom elements with client render on top of bad server markup
* renders unknown attributes for custom elements using is with client render on top of bad server markup
* renders no HTML events with client render on top of bad server markup
src/renderers/dom/shared/__tests__/ReactMount-test.js
* should warn if mounting into dirty rendered markup
+83 -80
View File
@@ -42,82 +42,6 @@ scripts/error-codes/__tests__/invertObject-test.js
* should take the last value when there're duplications in vals
* should preserve the original order
src/addons/__tests__/ReactComponentWithPureRenderMixin-test.js
* provides a default shouldComponentUpdate implementation
* does not do a deep comparison
src/addons/__tests__/ReactFragment-test.js
* should throw if a plain object is used as a child
* should throw if a plain object even if it is in an owner
* warns for numeric keys on objects as children
* should warn if passing null to createFragment
* should warn if passing an array to createFragment
* should warn if passing a ReactElement to createFragment
src/addons/__tests__/renderSubtreeIntoContainer-test.js
* should pass context when rendering subtree elsewhere
* should throw if parentComponent is invalid
* should update context if it changes due to setState
* should update context if it changes due to re-render
* should render portal with non-context-provider parent
* should get context through non-context-provider parent
* should get context through middle non-context-provider layer
src/addons/__tests__/update-test.js
* pushes
* does not mutate the original object
* only pushes an array
* only pushes unto an array
* unshifts
* does not mutate the original object
* only unshifts an array
* only unshifts unto an array
* splices
* does not mutate the original object
* only splices an array of arrays
* only splices unto an array
* merges
* does not mutate the original object
* only merges with an object
* only merges with an object
* sets
* does not mutate the original object
* applies
* does not mutate the original object
* only applies a function
* should support deep updates
* should require a command
* should perform safe hasOwnProperty check
src/addons/transitions/__tests__/ReactCSSTransitionGroup-test.js
* should warn if timeouts aren't specified
* should not warn if timeouts is zero
* should clean-up silently after the timeout elapses
* should keep both sets of DOM nodes around
* should switch transitionLeave from false to true
* should work with no children
* should work with a null child
* should transition from one to null
* should transition from false to one
* should use transition-type specific names when they're provided
* should clear transition timeouts when unmounted
* should handle unmounted elements properly
src/addons/transitions/__tests__/ReactTransitionChildMapping-test.js
* should support getChildMapping
* should support mergeChildMappings for adding keys
* should support mergeChildMappings for removing keys
* should support mergeChildMappings for adding and removing
* should reconcile overlapping insertions and deletions
* should support mergeChildMappings with undefined input
src/addons/transitions/__tests__/ReactTransitionGroup-test.js
* should handle willEnter correctly
* should handle enter/leave/enter/leave correctly
* should handle enter/leave/enter correctly
* should handle entering/leaving several elements at once
* should warn for duplicated keys
src/isomorphic/__tests__/React-test.js
* should log a deprecation warning once when using React.createMixin
@@ -542,6 +466,8 @@ src/renderers/__tests__/ReactComponent-test.js
* fires the callback after a component is rendered
* throws usefully when rendering badly-typed elements
* includes owner name in the error about badly-typed elements
* throws if a plain object is used as a child
* throws if a plain object even if it is in an owner
src/renderers/__tests__/ReactComponentLifeCycle-test.js
* should not reuse an instance when it has been unmounted
@@ -602,6 +528,8 @@ src/renderers/__tests__/ReactCompositeComponent-test.js
* should warn when mutated props are passed
* should only call componentWillUnmount once
* prepares new child before unmounting old
* respects a shallow shouldComponentUpdate implementation
* does not do a deep comparison for a shallow shouldComponentUpdate implementation
src/renderers/__tests__/ReactCompositeComponentDOMMinimalism-test.js
* should not render extra nodes for non-interpolated text
@@ -1064,16 +992,80 @@ src/renderers/dom/shared/__tests__/ReactDOMSVG-test.js
src/renderers/dom/shared/__tests__/ReactDOMServerIntegration-test.js
* renders a blank div with server string render
* renders a blank div with clean client render
* renders a blank div with client render on top of good server markup
* renders a div with inline styles with server string render
* renders a div with inline styles with clean client render
* renders a div with inline styles with client render on top of good server markup
* renders a self-closing tag with server string render
* renders a self-closing tag with clean client render
* renders a self-closing tag with client render on top of good server markup
* renders a self-closing tag as a child with server string render
* renders a self-closing tag as a child with clean client render
* renders a self-closing tag as a child with client render on top of good server markup
* renders simple numbers with server string render
* renders simple numbers with clean client render
* renders simple strings with server string render
* renders simple strings with clean client render
* renders string prop with true value with server string render
* renders string prop with true value with clean client render
* renders string prop with false value with server string render
* renders string prop with false value with clean client render
* renders boolean prop with true value with server string render
* renders boolean prop with true value with clean client render
* renders boolean prop with false value with server string render
* renders boolean prop with false value with clean client render
* renders boolean prop with self value with server string render
* renders boolean prop with self value with clean client render
* renders boolean prop with "" value with server string render
* renders boolean prop with "" value with clean client render
* renders boolean prop with string value with server string render
* renders boolean prop with string value with clean client render
* renders boolean prop with array value with server string render
* renders boolean prop with array value with clean client render
* renders boolean prop with object value with server string render
* renders boolean prop with object value with clean client render
* renders boolean prop with non-zero number value with server string render
* renders boolean prop with non-zero number value with clean client render
* renders boolean prop with zero value with server string render
* renders boolean prop with zero value with clean client render
* renders download prop with true value with server string render
* renders download prop with true value with clean client render
* renders download prop with false value with server string render
* renders download prop with false value with clean client render
* renders download prop with string value with server string render
* renders download prop with string value with clean client render
* renders download prop with string "true" value with server string render
* renders download prop with string "true" value with clean client render
* renders className prop with string value with server string render
* renders className prop with string value with clean client render
* renders className prop with empty string value with server string render
* renders className prop with empty string value with clean client render
* renders className prop with true value with server string render
* renders className prop with true value with clean client render
* renders className prop with false value with server string render
* renders className prop with false value with clean client render
* renders htmlFor with string value with server string render
* renders htmlFor with string value with clean client render
* renders htmlFor with an empty string with server string render
* renders htmlFor with an empty string with clean client render
* renders className prop with true value with server string render
* renders className prop with true value with clean client render
* renders className prop with false value with server string render
* renders className prop with false value with clean client render
* renders no ref attribute with server string render
* renders no ref attribute with clean client render
* renders no children attribute with server string render
* renders no children attribute with clean client render
* renders no key attribute with server string render
* renders no key attribute with clean client render
* renders no dangerouslySetInnerHTML attribute with server string render
* renders no dangerouslySetInnerHTML attribute with clean client render
* renders no unknown attributes with clean client render
* renders unknown data- attributes with server string render
* renders unknown data- attributes with clean client render
* renders no unknown attributes for non-standard elements with clean client render
* renders unknown attributes for custom elements with server string render
* renders unknown attributes for custom elements with clean client render
* renders unknown attributes for custom elements using is with server string render
* renders unknown attributes for custom elements using is with clean client render
* renders no HTML events with server string render
* renders no HTML events with clean client render
src/renderers/dom/shared/__tests__/ReactDOMTextComponent-test.js
* updates a mounted text component in place
@@ -1163,6 +1155,15 @@ src/renderers/dom/shared/__tests__/quoteAttributeValueForBrowser-test.js
* should escape number to string
* should escape string
src/renderers/dom/shared/__tests__/renderSubtreeIntoContainer-test.js
* should pass context when rendering subtree elsewhere
* should throw if parentComponent is invalid
* should update context if it changes due to setState
* should update context if it changes due to re-render
* should render portal with non-context-provider parent
* should get context through non-context-provider parent
* should get context through middle non-context-provider layer
src/renderers/dom/shared/__tests__/validateDOMNesting-test.js
* allows any tag with no context
* allows valid nestings
@@ -1436,7 +1437,9 @@ src/renderers/native/__tests__/ReactNativeAttributePayload-test.js
src/renderers/native/__tests__/ReactNativeEvents-test.js
* handles events
* handles events on text nodes
* handles when a responder is unmounted while a touch sequence is in progress
* handles events without target
src/renderers/native/__tests__/ReactNativeMount-test.js
* should be able to create and render a native component
@@ -3,15 +3,6 @@
const querystring = require('querystring');
const PACKAGES = [
'react-addons-create-fragment',
'react-addons-css-transition-group',
'react-addons-linked-state-mixin',
'react-addons-perf',
'react-addons-pure-render-mixin',
'react-addons-shallow-compare',
'react-addons-test-utils',
'react-addons-transition-group',
'react-addons-update',
'react-dom',
'react-native-renderer',
'react-test-renderer',
-37
View File
@@ -1,37 +0,0 @@
/**
* 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 ReactAddonsDOMDependencies
*/
'use strict';
var ReactDOM = require('react-dom');
exports.getReactDOM = function() {
return ReactDOM;
};
if (__DEV__) {
var ReactPerf;
var ReactTestUtils;
exports.getReactPerf = function() {
if (!ReactPerf) {
ReactPerf = require('react-dom/lib/ReactPerf');
}
return ReactPerf;
};
exports.getReactTestUtils = function() {
if (!ReactTestUtils) {
ReactTestUtils = require('react-dom/lib/ReactTestUtils');
}
return ReactTestUtils;
};
}
@@ -1,48 +0,0 @@
/**
* 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 ReactComponentWithPureRenderMixin
*/
'use strict';
var shallowCompare = require('shallowCompare');
/**
* If your React component's render function is "pure", e.g. it will render the
* same result given the same props and state, provide this mixin for a
* considerable performance boost.
*
* Most React components have pure render functions.
*
* Example:
*
* var ReactComponentWithPureRenderMixin =
* require('ReactComponentWithPureRenderMixin');
* React.createClass({
* mixins: [ReactComponentWithPureRenderMixin],
*
* render: function() {
* return <div className={this.props.className}>foo</div>;
* }
* });
*
* Note: This only checks shallow equality for props and state. If these contain
* complex data structures this mixin may have false-negatives for deeper
* differences. Only mixin to components which have simple props and state, or
* use `forceUpdate()` when you know deep data structures have changed.
*
* See https://facebook.github.io/react/docs/pure-render-mixin.html
*/
var ReactComponentWithPureRenderMixin = {
shouldComponentUpdate: function(nextProps, nextState) {
return shallowCompare(this, nextProps, nextState);
},
};
module.exports = ReactComponentWithPureRenderMixin;
-88
View File
@@ -1,88 +0,0 @@
/**
* 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.
*
* @providesModule ReactFragment
*/
'use strict';
var ReactChildren = require('ReactChildren');
var ReactElement = require('ReactElement');
var emptyFunction = require('fbjs/lib/emptyFunction');
var invariant = require('fbjs/lib/invariant');
var warning = require('fbjs/lib/warning');
/**
* We used to allow keyed objects to serve as a collection of ReactElements,
* or nested sets. This allowed us a way to explicitly key a set or fragment of
* components. This is now being replaced with an opaque data structure.
* The upgrade path is to call React.addons.createFragment({ key: value }) to
* create a keyed fragment. The resulting data structure is an array.
*/
var numericPropertyRegex = /^\d+$/;
var warnedAboutNumeric = false;
var ReactFragment = {
/**
* Wrap a keyed object in an opaque proxy that warns you if you access any
* of its properties.
* See https://facebook.github.io/react/docs/create-fragment.html
*/
create: function(object) {
if (typeof object !== 'object' || !object || Array.isArray(object)) {
warning(
false,
'React.addons.createFragment only accepts a single object. Got: %s',
object,
);
return object;
}
if (ReactElement.isValidElement(object)) {
warning(
false,
'React.addons.createFragment does not accept a ReactElement ' +
'without a wrapper object.',
);
return object;
}
invariant(
object.nodeType !== 1,
'React.addons.createFragment(...): Encountered an invalid child; DOM ' +
'elements are not valid children of React components.',
);
var result = [];
for (var key in object) {
if (__DEV__) {
if (!warnedAboutNumeric && numericPropertyRegex.test(key)) {
warning(
false,
'React.addons.createFragment(...): Child objects should have ' +
'non-numeric keys so ordering is preserved.',
);
warnedAboutNumeric = true;
}
}
ReactChildren.mapIntoWithKeyPrefixInternal(
object[key],
result,
key,
emptyFunction.thatReturnsArgument,
);
}
return result;
},
};
module.exports = ReactFragment;
-51
View File
@@ -1,51 +0,0 @@
/**
* 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 ReactWithAddons
*/
'use strict';
var React = require('react');
var ReactAddonsDOMDependencies = require('ReactAddonsDOMDependencies');
var ReactComponentWithPureRenderMixin = require('ReactComponentWithPureRenderMixin');
var ReactCSSTransitionGroup = require('ReactCSSTransitionGroup');
var ReactFragment = require('ReactFragment');
var ReactTransitionGroup = require('ReactTransitionGroup');
var shallowCompare = require('shallowCompare');
var update = require('update');
React.addons = {
CSSTransitionGroup: ReactCSSTransitionGroup,
PureRenderMixin: ReactComponentWithPureRenderMixin,
TransitionGroup: ReactTransitionGroup,
createFragment: ReactFragment.create,
shallowCompare: shallowCompare,
update: update,
};
if (__DEV__) {
// For the UMD build we get these lazily from the global since they're tied
// to the DOM renderer and it hasn't loaded yet.
Object.defineProperty(React.addons, 'Perf', {
enumerable: true,
get: function() {
return ReactAddonsDOMDependencies.getReactPerf();
},
});
Object.defineProperty(React.addons, 'TestUtils', {
enumerable: true,
get: function() {
return ReactAddonsDOMDependencies.getReactTestUtils();
},
});
}
module.exports = React;
@@ -1,137 +0,0 @@
/**
* 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.
*
* @emails react-core
*/
'use strict';
var React;
var ReactComponentWithPureRenderMixin;
var ReactTestUtils;
describe('ReactComponentWithPureRenderMixin', () => {
beforeEach(() => {
React = require('react');
ReactComponentWithPureRenderMixin = require('ReactComponentWithPureRenderMixin');
ReactTestUtils = require('ReactTestUtils');
});
it('provides a default shouldComponentUpdate implementation', () => {
var renderCalls = 0;
class PlasticWrap extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
color: 'green',
};
}
render() {
return <Apple color={this.state.color} ref="apple" />;
}
}
var Apple = React.createClass({
mixins: [ReactComponentWithPureRenderMixin],
getInitialState: function() {
return {
cut: false,
slices: 1,
};
},
cut: function() {
this.setState({
cut: true,
slices: 10,
});
},
eatSlice: function() {
this.setState({
slices: this.state.slices - 1,
});
},
render: function() {
renderCalls++;
return <div />;
},
});
var instance = ReactTestUtils.renderIntoDocument(<PlasticWrap />);
expect(renderCalls).toBe(1);
// Do not re-render based on props
instance.setState({color: 'green'});
expect(renderCalls).toBe(1);
// Re-render based on props
instance.setState({color: 'red'});
expect(renderCalls).toBe(2);
// Re-render base on state
instance.refs.apple.cut();
expect(renderCalls).toBe(3);
// No re-render based on state
instance.refs.apple.cut();
expect(renderCalls).toBe(3);
// Re-render based on state again
instance.refs.apple.eatSlice();
expect(renderCalls).toBe(4);
});
it('does not do a deep comparison', () => {
function getInitialState() {
return {
foo: [1, 2, 3],
bar: {a: 4, b: 5, c: 6},
};
}
var renderCalls = 0;
var initialSettings = getInitialState();
var Component = React.createClass({
mixins: [ReactComponentWithPureRenderMixin],
getInitialState: function() {
return initialSettings;
},
render: function() {
renderCalls++;
return <div />;
},
});
var instance = ReactTestUtils.renderIntoDocument(<Component />);
expect(renderCalls).toBe(1);
// Do not re-render if state is equal
var settings = {
foo: initialSettings.foo,
bar: initialSettings.bar,
};
instance.setState(settings);
expect(renderCalls).toBe(1);
// Re-render because one field changed
initialSettings.foo = [1, 2, 3];
instance.setState(initialSettings);
expect(renderCalls).toBe(2);
// Re-render because the object changed
instance.setState(getInitialState());
expect(renderCalls).toBe(3);
});
});
@@ -1,99 +0,0 @@
/**
* 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.
*
* @emails react-core
*/
'use strict';
var React;
var ReactDOM;
var ReactFragment;
describe('ReactFragment', () => {
beforeEach(() => {
React = require('react');
ReactDOM = require('react-dom');
ReactFragment = require('ReactFragment');
});
it('should throw if a plain object is used as a child', () => {
var children = {
x: <span />,
y: <span />,
z: <span />,
};
var element = <div>{[children]}</div>;
var container = document.createElement('div');
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 ' +
'the React add-ons.',
);
});
it('should throw if a plain object even if it is in an owner', () => {
class Foo extends React.Component {
render() {
var children = {
a: <span />,
b: <span />,
c: <span />,
};
return <div>{[children]}</div>;
}
}
var container = document.createElement('div');
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 ' +
'the React add-ons.\n\nCheck the render method of `Foo`.',
);
});
it('warns for numeric keys on objects as children', () => {
spyOn(console, 'error');
ReactFragment.create({1: <span />, 2: <span />});
expectDev(console.error.calls.count()).toBe(1);
expectDev(console.error.calls.argsFor(0)[0]).toContain(
'Child objects should have non-numeric keys so ordering is preserved.',
);
});
it('should warn if passing null to createFragment', () => {
spyOn(console, 'error');
ReactFragment.create(null);
expectDev(console.error.calls.count()).toBe(1);
expectDev(console.error.calls.argsFor(0)[0]).toContain(
'React.addons.createFragment only accepts a single object.',
);
});
it('should warn if passing an array to createFragment', () => {
spyOn(console, 'error');
ReactFragment.create([]);
expectDev(console.error.calls.count()).toBe(1);
expectDev(console.error.calls.argsFor(0)[0]).toContain(
'React.addons.createFragment only accepts a single object.',
);
});
it('should warn if passing a ReactElement to createFragment', () => {
spyOn(console, 'error');
ReactFragment.create(<div />);
expectDev(console.error.calls.count()).toBe(1);
expectDev(console.error.calls.argsFor(0)[0]).toContain(
'React.addons.createFragment does not accept a ReactElement without a ' +
'wrapper object.',
);
});
});
-189
View File
@@ -1,189 +0,0 @@
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails react-core
*/
'use strict';
var update = require('update');
describe('update', () => {
describe('$push', () => {
it('pushes', () => {
expect(update([1], {$push: [7]})).toEqual([1, 7]);
});
it('does not mutate the original object', () => {
var obj = [1];
update(obj, {$push: [7]});
expect(obj).toEqual([1]);
});
it('only pushes an array', () => {
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', () => {
expect(update.bind(null, 1, {$push: 7})).toThrowError(
'update(): expected target of $push to be an array; got 1.',
);
});
});
describe('$unshift', () => {
it('unshifts', () => {
expect(update([1], {$unshift: [7]})).toEqual([7, 1]);
});
it('does not mutate the original object', () => {
var obj = [1];
update(obj, {$unshift: [7]});
expect(obj).toEqual([1]);
});
it('only unshifts an array', () => {
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', () => {
expect(update.bind(null, 1, {$unshift: 7})).toThrowError(
'update(): expected target of $unshift to be an array; got 1.',
);
});
});
describe('$splice', () => {
it('splices', () => {
expect(update([1, 4, 3], {$splice: [[1, 1, 2]]})).toEqual([1, 2, 3]);
});
it('does not mutate the original object', () => {
var obj = [1, 4, 3];
update(obj, {$splice: [[1, 1, 2]]});
expect(obj).toEqual([1, 4, 3]);
});
it('only splices an array of arrays', () => {
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]})).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', () => {
expect(update.bind(null, 1, {$splice: 7})).toThrowError(
'Expected $splice target to be an array; got 1',
);
});
});
describe('$merge', () => {
it('merges', () => {
expect(update({a: 'b'}, {$merge: {c: 'd'}})).toEqual({a: 'b', c: 'd'});
});
it('does not mutate the original object', () => {
var obj = {a: 'b'};
update(obj, {$merge: {c: 'd'}});
expect(obj).toEqual({a: 'b'});
});
it('only merges with an object', () => {
expect(update.bind(null, {}, {$merge: 7})).toThrowError(
"update(): $merge expects a spec of type 'object'; got 7",
);
});
it('only merges with an object', () => {
expect(update.bind(null, 7, {$merge: {a: 'b'}})).toThrowError(
"update(): $merge expects a target of type 'object'; got 7",
);
});
});
describe('$set', () => {
it('sets', () => {
expect(update({a: 'b'}, {$set: {c: 'd'}})).toEqual({c: 'd'});
});
it('does not mutate the original object', () => {
var obj = {a: 'b'};
update(obj, {$set: {c: 'd'}});
expect(obj).toEqual({a: 'b'});
});
});
describe('$apply', () => {
var applier = function(node) {
return {v: node.v * 2};
};
it('applies', () => {
expect(update({v: 2}, {$apply: applier})).toEqual({v: 4});
});
it('does not mutate the original object', () => {
var obj = {v: 2};
update(obj, {$apply: applier});
expect(obj).toEqual({v: 2});
});
it('only applies a function', () => {
expect(update.bind(null, 2, {$apply: 123})).toThrowError(
'update(): expected spec of $apply to be a function; got 123.',
);
});
});
it('should support deep updates', () => {
expect(
update(
{
a: 'b',
c: {
d: 'e',
f: [1],
g: [2],
h: [3],
i: {j: 'k'},
l: 4,
},
},
{
c: {
d: {$set: 'm'},
f: {$push: [5]},
g: {$unshift: [6]},
h: {$splice: [[0, 1, 7]]},
i: {$merge: {n: 'o'}},
l: {$apply: x => x * 2},
},
},
),
).toEqual({
a: 'b',
c: {
d: 'm',
f: [1, 5],
g: [6, 2],
h: [7],
i: {j: 'k', n: 'o'},
l: 8,
},
});
});
it('should require a command', () => {
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: ...}?',
);
});
it('should perform safe hasOwnProperty check', () => {
expect(update({}, {hasOwnProperty: {$set: 'a'}})).toEqual({
hasOwnProperty: 'a',
});
});
});
-26
View File
@@ -1,26 +0,0 @@
/**
* 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 shallowCompare
*/
'use strict';
var shallowEqual = require('fbjs/lib/shallowEqual');
/**
* Does a shallow comparison for props and state.
* See ReactComponentWithPureRenderMixin
* See also https://facebook.github.io/react/docs/shallow-compare.html
*/
function shallowCompare(instance, nextProps, nextState) {
return !shallowEqual(instance.props, nextProps) ||
!shallowEqual(instance.state, nextState);
}
module.exports = shallowCompare;
@@ -1,99 +0,0 @@
/**
* 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 ReactCSSTransitionGroup
*/
'use strict';
var React = require('react');
var ReactTransitionGroup = require('ReactTransitionGroup');
var ReactCSSTransitionGroupChild = require('ReactCSSTransitionGroupChild');
function createTransitionTimeoutPropValidator(transitionType) {
var timeoutPropName = 'transition' + transitionType + 'Timeout';
var enabledPropName = 'transition' + transitionType;
return function(props) {
// If the transition is enabled
if (props[enabledPropName]) {
// If no timeout duration is provided
if (props[timeoutPropName] == null) {
return new Error(
timeoutPropName +
" wasn't supplied to ReactCSSTransitionGroup: " +
"this can cause unreliable animations and won't be supported in " +
'a future version of React. See ' +
'https://fb.me/react-animation-transition-group-timeout for more ' +
'information.',
);
// If the duration isn't a number
} else if (typeof props[timeoutPropName] !== 'number') {
return new Error(
timeoutPropName + ' must be a number (in milliseconds)',
);
}
}
};
}
/**
* An easy way to perform CSS transitions and animations when a React component
* enters or leaves the DOM.
* See https://facebook.github.io/react/docs/animation.html#high-level-api-reactcsstransitiongroup
*/
class ReactCSSTransitionGroup extends React.Component {
static displayName = 'ReactCSSTransitionGroup';
static propTypes = {
transitionName: ReactCSSTransitionGroupChild.propTypes.name,
transitionAppear: React.PropTypes.bool,
transitionEnter: React.PropTypes.bool,
transitionLeave: React.PropTypes.bool,
transitionAppearTimeout: createTransitionTimeoutPropValidator('Appear'),
transitionEnterTimeout: createTransitionTimeoutPropValidator('Enter'),
transitionLeaveTimeout: createTransitionTimeoutPropValidator('Leave'),
};
static defaultProps = {
transitionAppear: false,
transitionEnter: true,
transitionLeave: true,
};
_wrapChild = child => {
// We need to provide this childFactory so that
// ReactCSSTransitionGroupChild can receive updates to name, enter, and
// leave while it is leaving.
return React.createElement(
ReactCSSTransitionGroupChild,
{
name: this.props.transitionName,
appear: this.props.transitionAppear,
enter: this.props.transitionEnter,
leave: this.props.transitionLeave,
appearTimeout: this.props.transitionAppearTimeout,
enterTimeout: this.props.transitionEnterTimeout,
leaveTimeout: this.props.transitionLeaveTimeout,
},
child,
);
};
render() {
return React.createElement(
ReactTransitionGroup,
Object.assign({}, this.props, {childFactory: this._wrapChild}),
);
}
}
module.exports = ReactCSSTransitionGroup;
@@ -1,173 +0,0 @@
/**
* 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 ReactCSSTransitionGroupChild
*/
'use strict';
var React = require('react');
var ReactAddonsDOMDependencies = require('ReactAddonsDOMDependencies');
var CSSCore = require('fbjs/lib/CSSCore');
var ReactTransitionEvents = require('ReactTransitionEvents');
var onlyChild = require('onlyChild');
var TICK = 17;
var ReactCSSTransitionGroupChild = React.createClass({
displayName: 'ReactCSSTransitionGroupChild',
propTypes: {
name: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.shape({
enter: React.PropTypes.string,
leave: React.PropTypes.string,
active: React.PropTypes.string,
}),
React.PropTypes.shape({
enter: React.PropTypes.string,
enterActive: React.PropTypes.string,
leave: React.PropTypes.string,
leaveActive: React.PropTypes.string,
appear: React.PropTypes.string,
appearActive: React.PropTypes.string,
}),
]).isRequired,
// Once we require timeouts to be specified, we can remove the
// boolean flags (appear etc.) and just accept a number
// or a bool for the timeout flags (appearTimeout etc.)
appear: React.PropTypes.bool,
enter: React.PropTypes.bool,
leave: React.PropTypes.bool,
appearTimeout: React.PropTypes.number,
enterTimeout: React.PropTypes.number,
leaveTimeout: React.PropTypes.number,
},
transition: function(animationType, finishCallback, userSpecifiedDelay) {
var node = ReactAddonsDOMDependencies.getReactDOM().findDOMNode(this);
if (!node) {
if (finishCallback) {
finishCallback();
}
return;
}
var className = this.props.name[animationType] ||
this.props.name + '-' + animationType;
var activeClassName = this.props.name[animationType + 'Active'] ||
className + '-active';
var timeout = null;
var endListener = function(e) {
if (e && e.target !== node) {
return;
}
clearTimeout(timeout);
CSSCore.removeClass(node, className);
CSSCore.removeClass(node, activeClassName);
ReactTransitionEvents.removeEndEventListener(node, endListener);
// Usually this optional callback is used for informing an owner of
// a leave animation and telling it to remove the child.
if (finishCallback) {
finishCallback();
}
};
CSSCore.addClass(node, className);
// Need to do this to actually trigger a transition.
this.queueClassAndNode(activeClassName, node);
// If the user specified a timeout delay.
if (userSpecifiedDelay) {
// Clean-up the animation after the specified delay
timeout = setTimeout(endListener, userSpecifiedDelay);
this.transitionTimeouts.push(timeout);
} else {
// DEPRECATED: this listener will be removed in a future version of react
ReactTransitionEvents.addEndEventListener(node, endListener);
}
},
queueClassAndNode: function(className, node) {
this.classNameAndNodeQueue.push({
className: className,
node: node,
});
if (!this.timeout) {
this.timeout = setTimeout(this.flushClassNameAndNodeQueue, TICK);
}
},
flushClassNameAndNodeQueue: function() {
if (this.isMounted()) {
this.classNameAndNodeQueue.forEach(function(obj) {
CSSCore.addClass(obj.node, obj.className);
});
}
this.classNameAndNodeQueue.length = 0;
this.timeout = null;
},
componentWillMount: function() {
this.classNameAndNodeQueue = [];
this.transitionTimeouts = [];
},
componentWillUnmount: function() {
if (this.timeout) {
clearTimeout(this.timeout);
}
this.transitionTimeouts.forEach(function(timeout) {
clearTimeout(timeout);
});
this.classNameAndNodeQueue.length = 0;
},
componentWillAppear: function(done) {
if (this.props.appear) {
this.transition('appear', done, this.props.appearTimeout);
} else {
done();
}
},
componentWillEnter: function(done) {
if (this.props.enter) {
this.transition('enter', done, this.props.enterTimeout);
} else {
done();
}
},
componentWillLeave: function(done) {
if (this.props.leave) {
this.transition('leave', done, this.props.leaveTimeout);
} else {
done();
}
},
render: function() {
return onlyChild(this.props.children);
},
});
module.exports = ReactCSSTransitionGroupChild;
@@ -1,105 +0,0 @@
/**
* 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 ReactTransitionChildMapping
*/
'use strict';
var flattenChildren = require('flattenChildren');
var ReactTransitionChildMapping = {
/**
* Given `this.props.children`, return an object mapping key to child. Just
* 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, selfDebugID) {
if (!children) {
return children;
}
if (__DEV__) {
return flattenChildren(children, selfDebugID);
}
return flattenChildren(children);
},
/**
* When you're adding or removing children some may be added or removed in the
* same render pass. We want to show *both* since we want to simultaneously
* animate elements in and out. This function takes a previous set of keys
* and a new set of keys and merges them with its best guess of the correct
* ordering. In the future we may expose some of the utilities in
* ReactMultiChild to make this easy, but for now React itself does not
* directly have this concept of the union of prevChildren and nextChildren
* so we implement it here.
*
* @param {object} prev prev children as returned from
* `ReactTransitionChildMapping.getChildMapping()`.
* @param {object} next next children as returned from
* `ReactTransitionChildMapping.getChildMapping()`.
* @return {object} a key set that contains all keys in `prev` and all keys
* in `next` in a reasonable order.
*/
mergeChildMappings: function(prev, next) {
prev = prev || {};
next = next || {};
function getValueForKey(key) {
if (next.hasOwnProperty(key)) {
return next[key];
} else {
return prev[key];
}
}
// For each key of `next`, the list of keys to insert before that key in
// the combined list
var nextKeysPending = {};
var pendingKeys = [];
for (var prevKey in prev) {
if (next.hasOwnProperty(prevKey)) {
if (pendingKeys.length) {
nextKeysPending[prevKey] = pendingKeys;
pendingKeys = [];
}
} else {
pendingKeys.push(prevKey);
}
}
var i;
var childMapping = {};
for (var nextKey in next) {
if (nextKeysPending.hasOwnProperty(nextKey)) {
for (i = 0; i < nextKeysPending[nextKey].length; i++) {
var pendingNextKey = nextKeysPending[nextKey][i];
childMapping[nextKeysPending[nextKey][i]] = getValueForKey(
pendingNextKey,
);
}
}
childMapping[nextKey] = getValueForKey(nextKey);
}
// Finally, add the keys which didn't appear before any key in `next`
for (i = 0; i < pendingKeys.length; i++) {
childMapping[pendingKeys[i]] = getValueForKey(pendingKeys[i]);
}
return childMapping;
},
};
module.exports = ReactTransitionChildMapping;
@@ -1,73 +0,0 @@
/**
* 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 ReactTransitionEvents
*/
'use strict';
var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
var getVendorPrefixedEventName = require('react-dom/lib/getVendorPrefixedEventName');
var endEvents = [];
function detectEvents() {
var animEnd = getVendorPrefixedEventName('animationend');
var transEnd = getVendorPrefixedEventName('transitionend');
if (animEnd) {
endEvents.push(animEnd);
}
if (transEnd) {
endEvents.push(transEnd);
}
}
if (ExecutionEnvironment.canUseDOM) {
detectEvents();
}
// We use the raw {add|remove}EventListener() call because EventListener
// does not know how to remove event listeners and we really should
// clean up. Also, these events are not triggered in older browsers
// so we should be A-OK here.
function addEventListener(node, eventName, eventListener) {
node.addEventListener(eventName, eventListener, false);
}
function removeEventListener(node, eventName, eventListener) {
node.removeEventListener(eventName, eventListener, false);
}
var ReactTransitionEvents = {
addEndEventListener: function(node, eventListener) {
if (endEvents.length === 0) {
// If CSS transitions are not supported, trigger an "end animation"
// event immediately.
window.setTimeout(eventListener, 0);
return;
}
endEvents.forEach(function(endEvent) {
addEventListener(node, endEvent, eventListener);
});
},
removeEndEventListener: function(node, eventListener) {
if (endEvents.length === 0) {
return;
}
endEvents.forEach(function(endEvent) {
removeEventListener(node, endEvent, eventListener);
});
},
};
module.exports = ReactTransitionEvents;
@@ -1,243 +0,0 @@
/**
* 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 ReactTransitionGroup
*/
'use strict';
var React = require('react');
var ReactTransitionChildMapping = require('ReactTransitionChildMapping');
var emptyFunction = require('fbjs/lib/emptyFunction');
/**
* 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
*/
class ReactTransitionGroup extends React.Component {
static displayName = 'ReactTransitionGroup';
static propTypes = {
component: React.PropTypes.any,
childFactory: React.PropTypes.func,
};
static defaultProps = {
component: 'span',
childFactory: emptyFunction.thatReturnsArgument,
};
state = {
// TODO: can we get useful debug information to show at this point?
children: ReactTransitionChildMapping.getChildMapping(this.props.children),
};
componentWillMount() {
this.currentlyTransitioningKeys = {};
this.keysToEnter = [];
this.keysToLeave = [];
}
componentDidMount() {
var initialChildMapping = this.state.children;
for (var key in initialChildMapping) {
if (initialChildMapping[key]) {
this.performAppear(key);
}
}
}
componentWillReceiveProps(nextProps) {
var nextChildMapping = ReactTransitionChildMapping.getChildMapping(
nextProps.children,
);
var prevChildMapping = this.state.children;
this.setState({
children: ReactTransitionChildMapping.mergeChildMappings(
prevChildMapping,
nextChildMapping,
),
});
var key;
for (key in nextChildMapping) {
var hasPrev = prevChildMapping && prevChildMapping.hasOwnProperty(key);
if (
nextChildMapping[key] &&
!hasPrev &&
!this.currentlyTransitioningKeys[key]
) {
this.keysToEnter.push(key);
}
}
for (key in prevChildMapping) {
var hasNext = nextChildMapping && nextChildMapping.hasOwnProperty(key);
if (
prevChildMapping[key] &&
!hasNext &&
!this.currentlyTransitioningKeys[key]
) {
this.keysToLeave.push(key);
}
}
// If we want to someday check for reordering, we could do it here.
}
componentDidUpdate() {
var keysToEnter = this.keysToEnter;
this.keysToEnter = [];
keysToEnter.forEach(this.performEnter);
var keysToLeave = this.keysToLeave;
this.keysToLeave = [];
keysToLeave.forEach(this.performLeave);
}
performAppear = key => {
this.currentlyTransitioningKeys[key] = true;
var component = this.refs[key];
if (component.componentWillAppear) {
component.componentWillAppear(this._handleDoneAppearing.bind(this, key));
} else {
this._handleDoneAppearing(key);
}
};
_handleDoneAppearing = key => {
var component = this.refs[key];
if (component.componentDidAppear) {
component.componentDidAppear();
}
delete this.currentlyTransitioningKeys[key];
var currentChildMapping = ReactTransitionChildMapping.getChildMapping(
this.props.children,
);
if (!currentChildMapping || !currentChildMapping.hasOwnProperty(key)) {
// This was removed before it had fully appeared. Remove it.
this.performLeave(key);
}
};
performEnter = key => {
this.currentlyTransitioningKeys[key] = true;
var component = this.refs[key];
if (component.componentWillEnter) {
component.componentWillEnter(this._handleDoneEntering.bind(this, key));
} else {
this._handleDoneEntering(key);
}
};
_handleDoneEntering = key => {
var component = this.refs[key];
if (component.componentDidEnter) {
component.componentDidEnter();
}
delete this.currentlyTransitioningKeys[key];
var currentChildMapping = ReactTransitionChildMapping.getChildMapping(
this.props.children,
);
if (!currentChildMapping || !currentChildMapping.hasOwnProperty(key)) {
// This was removed before it had fully entered. Remove it.
this.performLeave(key);
}
};
performLeave = key => {
this.currentlyTransitioningKeys[key] = true;
var component = this.refs[key];
if (component.componentWillLeave) {
component.componentWillLeave(this._handleDoneLeaving.bind(this, key));
} else {
// Note that this is somewhat dangerous b/c it calls setState()
// again, effectively mutating the component before all the work
// is done.
this._handleDoneLeaving(key);
}
};
_handleDoneLeaving = key => {
var component = this.refs[key];
if (component.componentDidLeave) {
component.componentDidLeave();
}
delete this.currentlyTransitioningKeys[key];
var currentChildMapping = ReactTransitionChildMapping.getChildMapping(
this.props.children,
);
if (currentChildMapping && currentChildMapping.hasOwnProperty(key)) {
// This entered again before it fully left. Add it again.
this.performEnter(key);
} else {
this.setState(function(state) {
var newChildren = Object.assign({}, state.children);
delete newChildren[key];
return {children: newChildren};
});
}
};
render() {
// TODO: we could get rid of the need for the wrapper node
// by cloning a single child
var childrenToRender = [];
for (var key in this.state.children) {
var child = this.state.children[key];
if (child) {
// You may need to apply reactive updates to a child as it is leaving.
// The normal React way to do it won't work since the child will have
// already been removed. In case you need this behavior you can provide
// a childFactory function to wrap every child, even the ones that are
// leaving.
childrenToRender.push(
React.cloneElement(this.props.childFactory(child), {
ref: key,
key: key,
}),
);
}
}
// 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.transitionAppearTimeout;
delete props.component;
return React.createElement(this.props.component, props, childrenToRender);
}
}
module.exports = ReactTransitionGroup;
@@ -1,325 +0,0 @@
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails react-core
*/
'use strict';
var CSSCore = require('fbjs/lib/CSSCore');
var React;
var ReactDOM;
var ReactCSSTransitionGroup;
// Most of the real functionality is covered in other unit tests, this just
// makes sure we're wired up correctly.
describe('ReactCSSTransitionGroup', () => {
var container;
beforeEach(() => {
jest.resetModules();
React = require('react');
ReactDOM = require('react-dom');
ReactCSSTransitionGroup = require('ReactCSSTransitionGroup');
container = document.createElement('div');
spyOn(console, 'error');
});
it("should warn if timeouts aren't specified", () => {
ReactDOM.render(
<ReactCSSTransitionGroup
transitionName="yolo"
transitionEnter={false}
transitionLeave={true}>
<span key="one" id="one" />
</ReactCSSTransitionGroup>,
container,
);
// Warning about the missing transitionLeaveTimeout prop
expectDev(console.error.calls.count()).toBe(1);
});
it('should not warn if timeouts is zero', () => {
ReactDOM.render(
<ReactCSSTransitionGroup
transitionName="yolo"
transitionEnter={false}
transitionLeave={true}
transitionLeaveTimeout={0}>
<span key="one" id="one" />
</ReactCSSTransitionGroup>,
container,
);
expectDev(console.error.calls.count()).toBe(0);
});
it('should clean-up silently after the timeout elapses', () => {
var a = ReactDOM.render(
<ReactCSSTransitionGroup
transitionName="yolo"
transitionEnter={false}
transitionLeaveTimeout={200}>
<span key="one" id="one" />
</ReactCSSTransitionGroup>,
container,
);
expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(1);
setTimeout.mock.calls.length = 0;
ReactDOM.render(
<ReactCSSTransitionGroup
transitionName="yolo"
transitionEnter={false}
transitionLeaveTimeout={200}>
<span key="two" id="two" />
</ReactCSSTransitionGroup>,
container,
);
expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(2);
expect(ReactDOM.findDOMNode(a).childNodes[0].id).toBe('two');
expect(ReactDOM.findDOMNode(a).childNodes[1].id).toBe('one');
// For some reason jst is adding extra setTimeout()s and grunt test isn't,
// so we need to do this disgusting hack.
for (var i = 0; i < setTimeout.mock.calls.length; i++) {
if (setTimeout.mock.calls[i][1] === 200) {
setTimeout.mock.calls[i][0]();
break;
}
}
// No warnings
expectDev(console.error.calls.count()).toBe(0);
// The leaving child has been removed
expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(1);
expect(ReactDOM.findDOMNode(a).childNodes[0].id).toBe('two');
});
it('should keep both sets of DOM nodes around', () => {
var a = ReactDOM.render(
<ReactCSSTransitionGroup transitionName="yolo">
<span key="one" id="one" />
</ReactCSSTransitionGroup>,
container,
);
expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(1);
ReactDOM.render(
<ReactCSSTransitionGroup transitionName="yolo">
<span key="two" id="two" />
</ReactCSSTransitionGroup>,
container,
);
expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(2);
expect(ReactDOM.findDOMNode(a).childNodes[0].id).toBe('two');
expect(ReactDOM.findDOMNode(a).childNodes[1].id).toBe('one');
});
it('should switch transitionLeave from false to true', () => {
var a = ReactDOM.render(
<ReactCSSTransitionGroup
transitionName="yolo"
transitionEnter={false}
transitionLeave={false}>
<span key="one" id="one" />
</ReactCSSTransitionGroup>,
container,
);
expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(1);
ReactDOM.render(
<ReactCSSTransitionGroup
transitionName="yolo"
transitionEnter={false}
transitionLeave={false}>
<span key="two" id="two" />
</ReactCSSTransitionGroup>,
container,
);
expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(1);
ReactDOM.render(
<ReactCSSTransitionGroup
transitionName="yolo"
transitionEnter={false}
transitionLeave={true}>
<span key="three" id="three" />
</ReactCSSTransitionGroup>,
container,
);
expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(2);
expect(ReactDOM.findDOMNode(a).childNodes[0].id).toBe('three');
expect(ReactDOM.findDOMNode(a).childNodes[1].id).toBe('two');
});
it('should work with no children', () => {
ReactDOM.render(
<ReactCSSTransitionGroup transitionName="yolo" />,
container,
);
});
it('should work with a null child', () => {
ReactDOM.render(
<ReactCSSTransitionGroup transitionName="yolo">
{[null]}
</ReactCSSTransitionGroup>,
container,
);
});
it('should transition from one to null', () => {
var a = ReactDOM.render(
<ReactCSSTransitionGroup transitionName="yolo">
<span key="one" id="one" />
</ReactCSSTransitionGroup>,
container,
);
expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(1);
ReactDOM.render(
<ReactCSSTransitionGroup transitionName="yolo">
{null}
</ReactCSSTransitionGroup>,
container,
);
// (Here, we expect the original child to stick around but test that no
// exception is thrown)
expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(1);
expect(ReactDOM.findDOMNode(a).childNodes[0].id).toBe('one');
});
it('should transition from false to one', () => {
var a = ReactDOM.render(
<ReactCSSTransitionGroup transitionName="yolo">
{false}
</ReactCSSTransitionGroup>,
container,
);
expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(0);
ReactDOM.render(
<ReactCSSTransitionGroup transitionName="yolo">
<span key="one" id="one" />
</ReactCSSTransitionGroup>,
container,
);
expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(1);
expect(ReactDOM.findDOMNode(a).childNodes[0].id).toBe('one');
});
it("should use transition-type specific names when they're provided", () => {
var customTransitionNames = {
enter: 'custom-entering',
leave: 'custom-leaving',
};
var a = ReactDOM.render(
<ReactCSSTransitionGroup
transitionName={customTransitionNames}
transitionEnterTimeout={1}
transitionLeaveTimeout={1}>
<span key="one" id="one" />
</ReactCSSTransitionGroup>,
container,
);
expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(1);
// Add an element
ReactDOM.render(
<ReactCSSTransitionGroup
transitionName={customTransitionNames}
transitionEnterTimeout={1}
transitionLeaveTimeout={1}>
<span key="one" id="one" />
<span key="two" id="two" />
</ReactCSSTransitionGroup>,
container,
);
expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(2);
var enteringNode = ReactDOM.findDOMNode(a).childNodes[1];
expect(CSSCore.hasClass(enteringNode, 'custom-entering')).toBe(true);
// Remove an element
ReactDOM.render(
<ReactCSSTransitionGroup
transitionName={customTransitionNames}
transitionEnterTimeout={1}
transitionLeaveTimeout={1}>
<span key="two" id="two" />
</ReactCSSTransitionGroup>,
container,
);
expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(2);
var leavingNode = ReactDOM.findDOMNode(a).childNodes[0];
expect(CSSCore.hasClass(leavingNode, 'custom-leaving')).toBe(true);
});
it('should clear transition timeouts when unmounted', () => {
class Component extends React.Component {
render() {
return (
<ReactCSSTransitionGroup
transitionName="yolo"
transitionEnterTimeout={500}>
{this.props.children}
</ReactCSSTransitionGroup>
);
}
}
ReactDOM.render(<Component />, container);
ReactDOM.render(
<Component><span key="yolo" id="yolo" /></Component>,
container,
);
ReactDOM.unmountComponentAtNode(container);
// Testing that no exception is thrown here, as the timeout has been cleared.
jest.runAllTimers();
});
it('should handle unmounted elements properly', () => {
class Child extends React.Component {
render() {
if (!this.props.show) {
return null;
}
return <div />;
}
}
class Component extends React.Component {
state = {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();
});
});
@@ -1,137 +0,0 @@
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails react-core
*/
'use strict';
var React;
var ReactTransitionChildMapping;
describe('ReactTransitionChildMapping', () => {
beforeEach(() => {
React = require('react');
ReactTransitionChildMapping = require('ReactTransitionChildMapping');
});
it('should support getChildMapping', () => {
var oneone = <div key="oneone" />;
var onetwo = <div key="onetwo" />;
var one = <div key="one">{oneone}{onetwo}</div>;
var two = <div key="two" />;
var component = <div>{one}{two}</div>;
expect(
ReactTransitionChildMapping.getChildMapping(component.props.children),
).toEqual({
'.$one': one,
'.$two': two,
});
});
it('should support mergeChildMappings for adding keys', () => {
var prev = {
one: true,
two: true,
};
var next = {
one: true,
two: true,
three: true,
};
expect(ReactTransitionChildMapping.mergeChildMappings(prev, next)).toEqual({
one: true,
two: true,
three: true,
});
});
it('should support mergeChildMappings for removing keys', () => {
var prev = {
one: true,
two: true,
three: true,
};
var next = {
one: true,
two: true,
};
expect(ReactTransitionChildMapping.mergeChildMappings(prev, next)).toEqual({
one: true,
two: true,
three: true,
});
});
it('should support mergeChildMappings for adding and removing', () => {
var prev = {
one: true,
two: true,
three: true,
};
var next = {
one: true,
two: true,
four: true,
};
expect(ReactTransitionChildMapping.mergeChildMappings(prev, next)).toEqual({
one: true,
two: true,
three: true,
four: true,
});
});
it('should reconcile overlapping insertions and deletions', () => {
var prev = {
one: true,
two: true,
four: true,
five: true,
};
var next = {
one: true,
two: true,
three: true,
five: true,
};
expect(ReactTransitionChildMapping.mergeChildMappings(prev, next)).toEqual({
one: true,
two: true,
three: true,
four: true,
five: true,
});
});
it('should support mergeChildMappings with undefined input', () => {
var prev = {
one: true,
two: true,
};
var next = undefined;
expect(ReactTransitionChildMapping.mergeChildMappings(prev, next)).toEqual({
one: true,
two: true,
});
prev = undefined;
next = {
three: true,
four: true,
};
expect(ReactTransitionChildMapping.mergeChildMappings(prev, next)).toEqual({
three: true,
four: true,
});
});
});
@@ -1,334 +0,0 @@
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails react-core
*/
'use strict';
var React;
var ReactDOM;
var ReactTransitionGroup;
// Most of the real functionality is covered in other unit tests, this just
// makes sure we're wired up correctly.
describe('ReactTransitionGroup', () => {
var container;
beforeEach(() => {
React = require('react');
ReactDOM = require('react-dom');
ReactTransitionGroup = require('ReactTransitionGroup');
container = document.createElement('div');
});
it('should handle willEnter correctly', () => {
var log = [];
class Child extends React.Component {
componentDidMount() {
log.push('didMount');
}
componentWillAppear = cb => {
log.push('willAppear');
cb();
};
componentDidAppear = () => {
log.push('didAppear');
};
componentWillEnter = cb => {
log.push('willEnter');
cb();
};
componentDidEnter = () => {
log.push('didEnter');
};
componentWillLeave = cb => {
log.push('willLeave');
cb();
};
componentDidLeave = () => {
log.push('didLeave');
};
componentWillUnmount() {
log.push('willUnmount');
}
render() {
return <span />;
}
}
class Component extends React.Component {
state = {count: 1};
render() {
var children = [];
for (var i = 0; i < this.state.count; i++) {
children.push(<Child key={i} />);
}
return <ReactTransitionGroup>{children}</ReactTransitionGroup>;
}
}
var instance = ReactDOM.render(<Component />, container);
expect(log).toEqual(['didMount', 'willAppear', 'didAppear']);
log = [];
instance.setState({count: 2}, function() {
expect(log).toEqual(['didMount', 'willEnter', 'didEnter']);
log = [];
instance.setState({count: 1});
});
expect(log).toEqual(['willLeave', 'didLeave', 'willUnmount']);
});
it('should handle enter/leave/enter/leave correctly', () => {
var log = [];
var willEnterCb;
class Child extends React.Component {
componentDidMount() {
log.push('didMount');
}
componentWillEnter = cb => {
log.push('willEnter');
willEnterCb = cb;
};
componentDidEnter = () => {
log.push('didEnter');
};
componentWillLeave = cb => {
log.push('willLeave');
cb();
};
componentDidLeave = () => {
log.push('didLeave');
};
componentWillUnmount() {
log.push('willUnmount');
}
render() {
return <span />;
}
}
class Component extends React.Component {
state = {count: 1};
render() {
var children = [];
for (var i = 0; i < this.state.count; i++) {
children.push(<Child key={i} />);
}
return <ReactTransitionGroup>{children}</ReactTransitionGroup>;
}
}
var instance = ReactDOM.render(<Component />, container);
expect(log).toEqual(['didMount']);
instance.setState({count: 2});
expect(log).toEqual(['didMount', 'didMount', 'willEnter']);
for (var k = 0; k < 5; k++) {
instance.setState({count: 2});
expect(log).toEqual(['didMount', 'didMount', 'willEnter']);
instance.setState({count: 1});
}
// other animations are blocked until willEnterCb is called
willEnterCb();
expect(log).toEqual([
'didMount',
'didMount',
'willEnter',
'didEnter',
'willLeave',
'didLeave',
'willUnmount',
]);
});
it('should handle enter/leave/enter correctly', () => {
var log = [];
var willEnterCb;
class Child extends React.Component {
componentDidMount() {
log.push('didMount');
}
componentWillEnter = cb => {
log.push('willEnter');
willEnterCb = cb;
};
componentDidEnter = () => {
log.push('didEnter');
};
componentWillLeave = cb => {
log.push('willLeave');
cb();
};
componentDidLeave = () => {
log.push('didLeave');
};
componentWillUnmount() {
log.push('willUnmount');
}
render() {
return <span />;
}
}
class Component extends React.Component {
state = {count: 1};
render() {
var children = [];
for (var i = 0; i < this.state.count; i++) {
children.push(<Child key={i} />);
}
return <ReactTransitionGroup>{children}</ReactTransitionGroup>;
}
}
var instance = ReactDOM.render(<Component />, container);
expect(log).toEqual(['didMount']);
instance.setState({count: 2});
expect(log).toEqual(['didMount', 'didMount', 'willEnter']);
for (var k = 0; k < 5; k++) {
instance.setState({count: 1});
expect(log).toEqual(['didMount', 'didMount', 'willEnter']);
instance.setState({count: 2});
}
willEnterCb();
expect(log).toEqual(['didMount', 'didMount', 'willEnter', 'didEnter']);
});
it('should handle entering/leaving several elements at once', () => {
var log = [];
class Child extends React.Component {
componentDidMount() {
log.push('didMount' + this.props.id);
}
componentWillEnter = cb => {
log.push('willEnter' + this.props.id);
cb();
};
componentDidEnter = () => {
log.push('didEnter' + this.props.id);
};
componentWillLeave = cb => {
log.push('willLeave' + this.props.id);
cb();
};
componentDidLeave = () => {
log.push('didLeave' + this.props.id);
};
componentWillUnmount() {
log.push('willUnmount' + this.props.id);
}
render() {
return <span />;
}
}
class Component extends React.Component {
state = {count: 1};
render() {
var children = [];
for (var i = 0; i < this.state.count; i++) {
children.push(<Child key={i} id={i} />);
}
return <ReactTransitionGroup>{children}</ReactTransitionGroup>;
}
}
var instance = ReactDOM.render(<Component />, container);
expect(log).toEqual(['didMount0']);
log = [];
instance.setState({count: 3});
expect(log).toEqual([
'didMount1',
'didMount2',
'willEnter1',
'didEnter1',
'willEnter2',
'didEnter2',
]);
log = [];
instance.setState({count: 0});
expect(log).toEqual([
'willLeave0',
'didLeave0',
'willLeave1',
'didLeave1',
'willLeave2',
'didLeave2',
'willUnmount0',
'willUnmount1',
'willUnmount2',
]);
});
it('should warn for duplicated keys', () => {
spyOn(console, 'error');
class Component extends React.Component {
render() {
var children = [<div key="1" />, <div key="1" />];
return <ReactTransitionGroup>{children}</ReactTransitionGroup>;
}
}
ReactDOM.render(<Component />, container);
expectDev(console.error.calls.count()).toBe(2);
expectDev(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.',
);
expectDev(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.',
);
});
});
-169
View File
@@ -1,169 +0,0 @@
/**
* 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 update
*/
/* global hasOwnProperty:true */
'use strict';
var invariant = require('fbjs/lib/invariant');
var hasOwnProperty = {}.hasOwnProperty;
function shallowCopy(x) {
if (Array.isArray(x)) {
return x.concat();
} else if (x && typeof x === 'object') {
return Object.assign(new x.constructor(), x);
} else {
return x;
}
}
var COMMAND_PUSH = '$push';
var COMMAND_UNSHIFT = '$unshift';
var COMMAND_SPLICE = '$splice';
var COMMAND_SET = '$set';
var COMMAND_MERGE = '$merge';
var COMMAND_APPLY = '$apply';
var ALL_COMMANDS_LIST = [
COMMAND_PUSH,
COMMAND_UNSHIFT,
COMMAND_SPLICE,
COMMAND_SET,
COMMAND_MERGE,
COMMAND_APPLY,
];
var ALL_COMMANDS_SET = {};
ALL_COMMANDS_LIST.forEach(function(command) {
ALL_COMMANDS_SET[command] = true;
});
function invariantArrayCase(value, spec, command) {
invariant(
Array.isArray(value),
'update(): expected target of %s to be an array; got %s.',
command,
value,
);
var specValue = spec[command];
invariant(
Array.isArray(specValue),
'update(): expected spec of %s to be an array; got %s. ' +
'Did you forget to wrap your parameter in an array?',
command,
specValue,
);
}
/**
* Returns a updated shallow copy of an object without mutating the original.
* See https://facebook.github.io/react/docs/update.html for details.
*/
function update(value, spec) {
invariant(
typeof spec === 'object',
'update(): You provided a key path to update() that did not contain one ' +
'of %s. Did you forget to include {%s: ...}?',
ALL_COMMANDS_LIST.join(', '),
COMMAND_SET,
);
if (hasOwnProperty.call(spec, COMMAND_SET)) {
invariant(
Object.keys(spec).length === 1,
'Cannot have more than one key in an object with %s',
COMMAND_SET,
);
return spec[COMMAND_SET];
}
var nextValue = shallowCopy(value);
if (hasOwnProperty.call(spec, COMMAND_MERGE)) {
var mergeObj = spec[COMMAND_MERGE];
invariant(
mergeObj && typeof mergeObj === 'object',
"update(): %s expects a spec of type 'object'; got %s",
COMMAND_MERGE,
mergeObj,
);
invariant(
nextValue && typeof nextValue === 'object',
"update(): %s expects a target of type 'object'; got %s",
COMMAND_MERGE,
nextValue,
);
Object.assign(nextValue, spec[COMMAND_MERGE]);
}
if (hasOwnProperty.call(spec, COMMAND_PUSH)) {
invariantArrayCase(value, spec, COMMAND_PUSH);
spec[COMMAND_PUSH].forEach(function(item) {
nextValue.push(item);
});
}
if (hasOwnProperty.call(spec, COMMAND_UNSHIFT)) {
invariantArrayCase(value, spec, COMMAND_UNSHIFT);
spec[COMMAND_UNSHIFT].forEach(function(item) {
nextValue.unshift(item);
});
}
if (hasOwnProperty.call(spec, COMMAND_SPLICE)) {
invariant(
Array.isArray(value),
'Expected %s target to be an array; got %s',
COMMAND_SPLICE,
value,
);
invariant(
Array.isArray(spec[COMMAND_SPLICE]),
'update(): expected spec of %s to be an array of arrays; got %s. ' +
'Did you forget to wrap your parameters in an array?',
COMMAND_SPLICE,
spec[COMMAND_SPLICE],
);
spec[COMMAND_SPLICE].forEach(function(args) {
invariant(
Array.isArray(args),
'update(): expected spec of %s to be an array of arrays; got %s. ' +
'Did you forget to wrap your parameters in an array?',
COMMAND_SPLICE,
spec[COMMAND_SPLICE],
);
nextValue.splice.apply(nextValue, args);
});
}
if (hasOwnProperty.call(spec, COMMAND_APPLY)) {
invariant(
typeof spec[COMMAND_APPLY] === 'function',
'update(): expected spec of %s to be a function; got %s.',
COMMAND_APPLY,
spec[COMMAND_APPLY],
);
nextValue = spec[COMMAND_APPLY](nextValue);
}
for (var k in spec) {
if (!(ALL_COMMANDS_SET.hasOwnProperty(k) && ALL_COMMANDS_SET[k])) {
nextValue[k] = update(value[k], spec[k]);
}
}
return nextValue;
}
module.exports = update;
@@ -13,12 +13,10 @@
describe('ReactChildren', () => {
var React;
var ReactFragment;
beforeEach(() => {
jest.resetModules();
React = require('react');
ReactFragment = require('ReactFragment');
});
it('should support identity for simple', () => {
@@ -150,8 +148,8 @@ describe('ReactChildren', () => {
var instance = (
<div>
{div}
{[ReactFragment.create({span})]}
{ReactFragment.create({a: a})}
{[[span]]}
{[a]}
{'string'}
{1234}
{true}
@@ -164,8 +162,8 @@ describe('ReactChildren', () => {
function assertCalls() {
expect(callback.calls.count()).toBe(9);
expect(callback).toHaveBeenCalledWith(div, 0);
expect(callback).toHaveBeenCalledWith(<span key="span/.$spanNode" />, 1);
expect(callback).toHaveBeenCalledWith(<a key="a/.$aNode" />, 2);
expect(callback).toHaveBeenCalledWith(span, 1);
expect(callback).toHaveBeenCalledWith(a, 2);
expect(callback).toHaveBeenCalledWith('string', 3);
expect(callback).toHaveBeenCalledWith(1234, 4);
expect(callback).toHaveBeenCalledWith(null, 5);
@@ -186,8 +184,8 @@ describe('ReactChildren', () => {
assertCalls();
expect(mappedChildren).toEqual([
<div key=".$divNode" />,
<span key=".1:0:$span/.$spanNode" />,
<a key=".2:$a/.$aNode" />,
<span key=".1:0:$spanNode" />,
<a key=".2:$aNode" />,
'string',
1234,
]);
@@ -199,12 +197,7 @@ describe('ReactChildren', () => {
var two = <div key="keyTwo" />;
var three = null;
var four = <div key="keyFour" />;
var five = <div key="keyFiveInner" />;
// five is placed into a JS object with a key that is joined to the
// component key attribute.
// Precedence is as follows:
// 1. If grouped in an Object, the object key combined with `key` prop
// 2. If grouped in an Array, the `key` prop, falling back to array index
var five = <div key="keyFive" />;
var context = {};
var callback = jasmine.createSpy().and.callFake(function(kid) {
@@ -213,34 +206,18 @@ describe('ReactChildren', () => {
var instance = (
<div>
{[
ReactFragment.create({
firstHalfKey: [zero, one, two],
secondHalfKey: [three, four],
keyFive: five,
}),
]}
{[[zero, one, two], [three, four], five]}
</div>
);
function assertCalls() {
expect(callback.calls.count()).toBe(4);
expect(callback).toHaveBeenCalledWith(
<div key="firstHalfKey/.$keyZero" />,
0,
);
expect(callback).toHaveBeenCalledWith(
<div key="firstHalfKey/.$keyTwo" />,
1,
);
expect(callback).toHaveBeenCalledWith(
<div key="secondHalfKey/.$keyFour" />,
2,
);
expect(callback).toHaveBeenCalledWith(
<div key="keyFive/.$keyFiveInner" />,
3,
);
expect(callback.calls.count()).toBe(6);
expect(callback).toHaveBeenCalledWith(zero, 0);
expect(callback).toHaveBeenCalledWith(one, 1);
expect(callback).toHaveBeenCalledWith(two, 2);
expect(callback).toHaveBeenCalledWith(three, 3);
expect(callback).toHaveBeenCalledWith(four, 4);
expect(callback).toHaveBeenCalledWith(five, 5);
callback.calls.reset();
}
@@ -254,10 +231,10 @@ describe('ReactChildren', () => {
);
assertCalls();
expect(mappedChildren).toEqual([
<div key=".0:$firstHalfKey/.$keyZero" />,
<div key=".0:$firstHalfKey/.$keyTwo" />,
<div key=".0:$secondHalfKey/.$keyFour" />,
<div key=".0:$keyFive/.$keyFiveInner" />,
<div key=".0:$keyZero" />,
<div key=".0:$keyTwo" />,
<div key=".1:$keyFour" />,
<div key=".$keyFive" />,
]);
});
@@ -601,52 +578,49 @@ describe('ReactChildren', () => {
var two = <div key="keyTwo" />;
var three = null;
var four = <div key="keyFour" />;
var five = <div key="keyFiveInner" />;
// five is placed into a JS object with a key that is joined to the
// component key attribute.
// Precedence is as follows:
// 1. If grouped in an Object, the object key combined with `key` prop
// 2. If grouped in an Array, the `key` prop, falling back to array index
var five = <div key="keyFive" />;
var zeroMapped = <div key="giraffe" />; // Key should be overridden
var twoMapped = <div />; // Key should be added even if not supplied!
var fourMapped = <div key="keyFour" />;
var fiveMapped = <div />;
var callback = jasmine.createSpy().and.callFake(function(kid, index) {
return index === 0
? zeroMapped
: index === 1 ? twoMapped : index === 2 ? fourMapped : fiveMapped;
var callback = jasmine.createSpy().and.callFake(function(kid) {
switch (kid) {
case zero:
return zeroMapped;
case two:
return twoMapped;
case four:
return fourMapped;
case five:
return fiveMapped;
default:
return kid;
}
});
var frag = ReactFragment.create({
firstHalfKey: [zero, one, two],
secondHalfKey: [three, four],
keyFive: five,
});
var frag = [[zero, one, two], [three, four], five];
var instance = <div>{[frag]}</div>;
expect([frag[0].key, frag[1].key, frag[2].key, frag[3].key]).toEqual([
'firstHalfKey/.$keyZero',
'firstHalfKey/.$keyTwo',
'secondHalfKey/.$keyFour',
'keyFive/.$keyFiveInner',
]);
React.Children.forEach(instance.props.children, callback);
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);
expect(callback.calls.count()).toBe(6);
expect(callback).toHaveBeenCalledWith(zero, 0);
expect(callback).toHaveBeenCalledWith(one, 1);
expect(callback).toHaveBeenCalledWith(two, 2);
expect(callback).toHaveBeenCalledWith(three, 3);
expect(callback).toHaveBeenCalledWith(four, 4);
expect(callback).toHaveBeenCalledWith(five, 5);
callback.calls.reset();
var mappedChildren = React.Children.map(instance.props.children, callback);
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);
expect(callback.calls.count()).toBe(6);
expect(callback).toHaveBeenCalledWith(zero, 0);
expect(callback).toHaveBeenCalledWith(one, 1);
expect(callback).toHaveBeenCalledWith(two, 2);
expect(callback).toHaveBeenCalledWith(three, 3);
expect(callback).toHaveBeenCalledWith(four, 4);
expect(callback).toHaveBeenCalledWith(five, 5);
expect(React.Children.count(mappedChildren)).toBe(4);
// Keys default to indices.
@@ -656,20 +630,16 @@ describe('ReactChildren', () => {
mappedChildren[2].key,
mappedChildren[3].key,
]).toEqual([
'giraffe/.0:$firstHalfKey/.$keyZero',
'.0:$firstHalfKey/.$keyTwo',
'keyFour/.0:$secondHalfKey/.$keyFour',
'.0:$keyFive/.$keyFiveInner',
'giraffe/.0:0:$keyZero',
'.0:0:$keyTwo',
'.0:1:$keyFour',
'.0:$keyFive',
]);
expect(mappedChildren[0]).toEqual(
<div key="giraffe/.0:$firstHalfKey/.$keyZero" />,
);
expect(mappedChildren[1]).toEqual(<div key=".0:$firstHalfKey/.$keyTwo" />);
expect(mappedChildren[2]).toEqual(
<div key="keyFour/.0:$secondHalfKey/.$keyFour" />,
);
expect(mappedChildren[3]).toEqual(<div key=".0:$keyFive/.$keyFiveInner" />);
expect(mappedChildren[0]).toEqual(<div key="giraffe/.0:0:$keyZero" />);
expect(mappedChildren[1]).toEqual(<div key=".0:0:$keyTwo" />);
expect(mappedChildren[2]).toEqual(<div key=".0:1:$keyFour" />);
expect(mappedChildren[3]).toEqual(<div key=".0:$keyFive" />);
});
it('should retain key across two mappings', () => {
@@ -812,27 +782,15 @@ describe('ReactChildren', () => {
var two = <div key="keyTwo" />;
var three = null;
var four = <div key="keyFour" />;
var five = <div key="keyFiveInner" />;
// five is placed into a JS object with a key that is joined to the
// component key attribute.
// Precedence is as follows:
// 1. If grouped in an Object, the object key combined with `key` prop
// 2. If grouped in an Array, the `key` prop, falling back to array index
var five = <div key="keyFive" />;
var instance = (
<div>
{[
ReactFragment.create({
firstHalfKey: [zero, one, two],
secondHalfKey: [three, four],
keyFive: five,
}),
null,
]}
{[[[zero, one, two], [three, four], five], null]}
</div>
);
var numberOfChildren = React.Children.count(instance.props.children);
expect(numberOfChildren).toBe(5);
expect(numberOfChildren).toBe(7);
});
it('should flatten children to an array', () => {
@@ -878,8 +836,7 @@ describe('ReactChildren', () => {
}).toThrowError(
'Objects are not valid as a React child (found: object with keys ' +
'{a, b}). If you meant to render a collection of children, use an ' +
'array instead or wrap the object using createFragment(object) from ' +
'the React add-ons.',
'array instead.',
);
});
@@ -890,8 +847,7 @@ describe('ReactChildren', () => {
React.Children.forEach(/abc/, function() {}, null);
}).toThrowError(
'Objects are not valid as a React child (found: /abc/). If you meant ' +
'to render a collection of children, use an array instead or wrap the ' +
'object using createFragment(object) from the React add-ons.',
'to render a collection of children, use an array instead.',
);
});
});
@@ -13,13 +13,11 @@
describe('onlyChild', () => {
var React;
var ReactFragment;
var onlyChild;
var WrapComponent;
beforeEach(() => {
React = require('react');
ReactFragment = require('ReactFragment');
onlyChild = require('onlyChild');
WrapComponent = class extends React.Component {
render() {
@@ -68,7 +66,7 @@ describe('onlyChild', () => {
expect(function() {
var instance = (
<WrapComponent>
{ReactFragment.create({oneThing: <span />})}
{[<span key="abc" />]}
</WrapComponent>
);
onlyChild(instance.props.children);
@@ -16,7 +16,6 @@ var checkPropTypes;
var checkReactTypeSpec;
var React;
var ReactDOM;
var ReactFragment;
var Component;
var MyComponent;
@@ -115,7 +114,6 @@ describe('ReactPropTypes', () => {
PropTypes = require('ReactPropTypes');
React = require('react');
ReactDOM = require('react-dom');
ReactFragment = require('ReactFragment');
resetWarningCache();
});
@@ -615,39 +613,20 @@ describe('ReactPropTypes', () => {
});
it('should not warn for valid values', () => {
spyOn(console, 'error');
typeCheckPass(PropTypes.node, <div />);
typeCheckPass(PropTypes.node, false);
typeCheckPass(PropTypes.node, <MyComponent />);
typeCheckPass(PropTypes.node, 'Some string');
typeCheckPass(PropTypes.node, []);
typeCheckPass(PropTypes.node, [
123,
'Some string',
<div />,
['Another string', [456], <span />, <MyComponent />],
<MyComponent />,
null,
undefined,
]);
// Object of renderable things
var frag = ReactFragment.create;
typeCheckPass(
PropTypes.node,
frag({
k0: 123,
k1: 'Some string',
k2: <div />,
k3: frag({
k30: <MyComponent />,
k31: frag({k310: <a />}),
k32: 'Another string',
}),
k4: null,
k5: undefined,
}),
);
expectDev(console.error.calls.count()).toBe(0);
});
it('should not warn for iterables', () => {
@@ -380,4 +380,38 @@ describe('ReactComponent', () => {
// One warning for each element creation
expectDev(console.error.calls.count()).toBe(1);
});
it('throws if a plain object is used as a child', () => {
var children = {
x: <span />,
y: <span />,
z: <span />,
};
var element = <div>{[children]}</div>;
var container = document.createElement('div');
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.',
);
});
it('throws if a plain object even if it is in an owner', () => {
class Foo extends React.Component {
render() {
var children = {
a: <span />,
b: <span />,
c: <span />,
};
return <div>{[children]}</div>;
}
}
var container = document.createElement('div');
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.\n\nCheck the render method of `Foo`.',
);
});
});
@@ -20,6 +20,8 @@ var ReactDOMServer;
var ReactCurrentOwner;
var ReactPropTypes;
var ReactTestUtils;
var shallowEqual;
var shallowCompare;
describe('ReactCompositeComponent', () => {
beforeEach(() => {
@@ -31,6 +33,12 @@ describe('ReactCompositeComponent', () => {
ReactCurrentOwner = require('react/lib/ReactCurrentOwner');
ReactPropTypes = require('ReactPropTypes');
ReactTestUtils = require('ReactTestUtils');
shallowEqual = require('fbjs/lib/shallowEqual');
shallowCompare = function(instance, nextProps, nextState) {
return !shallowEqual(instance.props, nextProps) ||
!shallowEqual(instance.state, nextState);
};
MorphingComponent = class extends React.Component {
state = {activated: false};
@@ -1396,4 +1404,119 @@ describe('ReactCompositeComponent', () => {
'B componentDidMount',
]);
});
it('respects a shallow shouldComponentUpdate implementation', () => {
var renderCalls = 0;
class PlasticWrap extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
color: 'green',
};
}
render() {
return <Apple color={this.state.color} ref="apple" />;
}
}
class Apple extends React.Component {
state = {
cut: false,
slices: 1,
};
shouldComponentUpdate(nextProps, nextState) {
return shallowCompare(this, nextProps, nextState);
}
cut() {
this.setState({
cut: true,
slices: 10,
});
}
eatSlice() {
this.setState({
slices: this.state.slices - 1,
});
}
render() {
renderCalls++;
return <div />;
}
}
var container = document.createElement('div');
var instance = ReactDOM.render(<PlasticWrap />, container);
expect(renderCalls).toBe(1);
// Do not re-render based on props
instance.setState({color: 'green'});
expect(renderCalls).toBe(1);
// Re-render based on props
instance.setState({color: 'red'});
expect(renderCalls).toBe(2);
// Re-render base on state
instance.refs.apple.cut();
expect(renderCalls).toBe(3);
// No re-render based on state
instance.refs.apple.cut();
expect(renderCalls).toBe(3);
// Re-render based on state again
instance.refs.apple.eatSlice();
expect(renderCalls).toBe(4);
});
it('does not do a deep comparison for a shallow shouldComponentUpdate implementation', () => {
function getInitialState() {
return {
foo: [1, 2, 3],
bar: {a: 4, b: 5, c: 6},
};
}
var renderCalls = 0;
var initialSettings = getInitialState();
class Component extends React.Component {
state = initialSettings;
shouldComponentUpdate(nextProps, nextState) {
return shallowCompare(this, nextProps, nextState);
}
render() {
renderCalls++;
return <div />;
}
}
var container = document.createElement('div');
var instance = ReactDOM.render(<Component />, container);
expect(renderCalls).toBe(1);
// Do not re-render if state is equal
var settings = {
foo: initialSettings.foo,
bar: initialSettings.bar,
};
instance.setState(settings);
expect(renderCalls).toBe(1);
// Re-render because one field changed
initialSettings.foo = [1, 2, 3];
instance.setState(initialSettings);
expect(renderCalls).toBe(2);
// Re-render because the object changed
instance.setState(getInitialState());
expect(renderCalls).toBe(3);
});
});
+3 -17
View File
@@ -13,7 +13,6 @@
var React;
var ReactDOM;
var ReactFragment;
var ReactTestUtils;
describe('ReactIdentity', () => {
@@ -21,14 +20,9 @@ describe('ReactIdentity', () => {
jest.resetModules();
React = require('react');
ReactDOM = require('react-dom');
ReactFragment = require('ReactFragment');
ReactTestUtils = require('ReactTestUtils');
});
function frag(obj) {
return ReactFragment.create(obj);
}
it('should allow key property to express identity', () => {
var node;
var Component = props => (
@@ -72,21 +66,13 @@ describe('ReactIdentity', () => {
function renderAComponentWithKeyIntoContainer(key, container) {
class Wrapper extends React.Component {
render() {
var s1 = <span ref="span1" key={key} />;
var s2 = <span ref="span2" />;
var map = {};
map[key] = s2;
return <div>{[s1, frag(map)]}</div>;
return <div><span ref="span" key={key} /></div>;
}
}
var instance = ReactDOM.render(<Wrapper />, container);
var span1 = instance.refs.span1;
var span2 = instance.refs.span2;
expect(ReactDOM.findDOMNode(span1)).not.toBe(null);
expect(ReactDOM.findDOMNode(span2)).not.toBe(null);
var span = instance.refs.span;
expect(ReactDOM.findDOMNode(span)).not.toBe(null);
}
it('should allow any character as a key, in a detached parent', () => {
@@ -65,14 +65,20 @@ function renderIntoDom(reactElement, domElement, errorCount = 0) {
);
}
async function renderIntoString(reactElement, errorCount = 0) {
return await expectErrors(
() =>
new Promise(resolve =>
resolve(ReactDOMServer.renderToString(reactElement))),
errorCount,
);
}
// Renders text using SSR and then stuffs it into a DOM node; returns the DOM
// element that corresponds with the reactElement.
// Does not render on client or perform client-side revival.
async function serverRender(reactElement, errorCount = 0) {
const markup = await expectErrors(
() => Promise.resolve(ReactDOMServer.renderToString(reactElement)),
errorCount,
);
const markup = await renderIntoString(reactElement, errorCount);
var domElement = document.createElement('div');
domElement.innerHTML = markup;
return domElement.firstChild;
@@ -84,10 +90,17 @@ const clientCleanRender = (element, errorCount = 0) => {
};
const clientRenderOnServerString = async (element, errorCount = 0) => {
const markup = await serverRender(element, errorCount);
const markup = await renderIntoString(element, errorCount);
resetModules();
var domElement = document.createElement('div');
domElement.innerHTML = markup;
return renderIntoDom(element, domElement, errorCount);
const serverElement = domElement.firstChild;
const clientElement = await renderIntoDom(element, domElement, errorCount);
// assert that the DOM element hasn't been replaced.
// Note that we cannot use expect(serverElement).toBe(clientElement) because
// of jest bug #1772
expect(serverElement === clientElement).toBe(true);
return clientElement;
};
const clientRenderOnBadMarkup = (element, errorCount = 0) => {
@@ -135,14 +148,22 @@ function itClientRenders(desc, testFn) {
testFn(clientRenderOnBadMarkup));
}
// When there is a test that renders on server and then on client and expects a logged
// error, you want to see the error show up both on server and client. Unfortunately,
// React refuses to issue the same error twice to avoid clogging up the console.
// To get around this, we must reload React modules in between server and client render.
function resetModules() {
jest.resetModuleRegistry();
React = require('React');
ReactDOM = require('ReactDOM');
ReactDOMServer = require('ReactDOMServer');
ExecutionEnvironment = require('ExecutionEnvironment');
}
describe('ReactDOMServerIntegration', () => {
beforeEach(() => {
jest.resetModuleRegistry();
React = require('React');
ReactDOM = require('ReactDOM');
ReactDOMServer = require('ReactDOMServer');
resetModules();
ExecutionEnvironment = require('ExecutionEnvironment');
ExecutionEnvironment.canUseDOM = false;
});
@@ -169,4 +190,224 @@ describe('ReactDOMServerIntegration', () => {
expect(e.firstChild.tagName).toBe('BR');
});
});
describe('property to attribute mapping', function() {
describe('string properties', function() {
itRenders('simple numbers', async render => {
const e = await render(<div width={30} />);
expect(e.getAttribute('width')).toBe('30');
});
itRenders('simple strings', async render => {
const e = await render(<div width={'30'} />);
expect(e.getAttribute('width')).toBe('30');
});
// this seems like it might mask programmer error, but it's existing behavior.
itRenders('string prop with true value', async render => {
const e = await render(<a href={true} />);
expect(e.getAttribute('href')).toBe('true');
});
// this seems like it might mask programmer error, but it's existing behavior.
itRenders('string prop with false value', async render => {
const e = await render(<a href={false} />);
expect(e.getAttribute('href')).toBe('false');
});
});
describe('boolean properties', function() {
itRenders('boolean prop with true value', async render => {
const e = await render(<div hidden={true} />);
expect(e.getAttribute('hidden')).toBe('');
});
itRenders('boolean prop with false value', async render => {
const e = await render(<div hidden={false} />);
expect(e.getAttribute('hidden')).toBe(null);
});
itRenders('boolean prop with self value', async render => {
const e = await render(<div hidden="hidden" />);
expect(e.getAttribute('hidden')).toBe('');
});
// this does not seem like correct behavior, since hidden="" in HTML indicates
// that the boolean property is present. however, it is how the current code
// behaves, so the test is included here.
itRenders('boolean prop with "" value', async render => {
const e = await render(<div hidden="" />);
expect(e.getAttribute('hidden')).toBe(null);
});
// this seems like it might mask programmer error, but it's existing behavior.
itRenders('boolean prop with string value', async render => {
const e = await render(<div hidden="foo" />);
expect(e.getAttribute('hidden')).toBe('');
});
// this seems like it might mask programmer error, but it's existing behavior.
itRenders('boolean prop with array value', async render => {
const e = await render(<div hidden={['foo', 'bar']} />);
expect(e.getAttribute('hidden')).toBe('');
});
// this seems like it might mask programmer error, but it's existing behavior.
itRenders('boolean prop with object value', async render => {
const e = await render(<div hidden={{foo: 'bar'}} />);
expect(e.getAttribute('hidden')).toBe('');
});
// this seems like it might mask programmer error, but it's existing behavior.
itRenders('boolean prop with non-zero number value', async render => {
const e = await render(<div hidden={10} />);
expect(e.getAttribute('hidden')).toBe('');
});
// this seems like it might mask programmer error, but it's existing behavior.
itRenders('boolean prop with zero value', async render => {
const e = await render(<div hidden={0} />);
expect(e.getAttribute('hidden')).toBe(null);
});
});
describe('download property (combined boolean/string attribute)', function() {
itRenders('download prop with true value', async render => {
const e = await render(<a download={true} />);
expect(e.getAttribute('download')).toBe('');
});
itRenders('download prop with false value', async render => {
const e = await render(<a download={false} />);
expect(e.getAttribute('download')).toBe(null);
});
itRenders('download prop with string value', async render => {
const e = await render(<a download="myfile" />);
expect(e.getAttribute('download')).toBe('myfile');
});
itRenders('download prop with string "true" value', async render => {
const e = await render(<a download={'true'} />);
expect(e.getAttribute('download')).toBe('true');
});
});
describe('className property', function() {
itRenders('className prop with string value', async render => {
const e = await render(<div className="myClassName" />);
expect(e.getAttribute('class')).toBe('myClassName');
});
itRenders('className prop with empty string value', async render => {
const e = await render(<div className="" />);
expect(e.getAttribute('class')).toBe('');
});
// this probably is just masking programmer error, but it is existing behavior.
itRenders('className prop with true value', async render => {
const e = await render(<div className={true} />);
expect(e.getAttribute('class')).toBe('true');
});
// this probably is just masking programmer error, but it is existing behavior.
itRenders('className prop with false value', async render => {
const e = await render(<div className={false} />);
expect(e.getAttribute('class')).toBe('false');
});
});
describe('htmlFor property', function() {
itRenders('htmlFor with string value', async render => {
const e = await render(<div htmlFor="myFor" />);
expect(e.getAttribute('for')).toBe('myFor');
});
itRenders('htmlFor with an empty string', async render => {
const e = await render(<div htmlFor="" />);
expect(e.getAttribute('for')).toBe('');
});
// this probably is just masking programmer error, but it is existing behavior.
itRenders('className prop with true value', async render => {
const e = await render(<div htmlFor={true} />);
expect(e.getAttribute('for')).toBe('true');
});
// this probably is just masking programmer error, but it is existing behavior.
itRenders('className prop with false value', async render => {
const e = await render(<div htmlFor={false} />);
expect(e.getAttribute('for')).toBe('false');
});
});
describe('props with special meaning in React', function() {
itRenders('no ref attribute', async render => {
class RefComponent extends React.Component {
render() {
return <div ref="foo" />;
}
}
const e = await render(<RefComponent />);
expect(e.getAttribute('ref')).toBe(null);
});
itRenders('no children attribute', async render => {
const e = await render(React.createElement('div', {}, 'foo'));
expect(e.getAttribute('children')).toBe(null);
});
itRenders('no key attribute', async render => {
const e = await render(<div key="foo" />);
expect(e.getAttribute('key')).toBe(null);
});
itRenders('no dangerouslySetInnerHTML attribute', async render => {
const e = await render(
<div dangerouslySetInnerHTML={{__html: 'foo'}} />,
);
expect(e.getAttribute('dangerouslySetInnerHTML')).toBe(null);
});
});
describe('unknown attributes', function() {
itRenders('no unknown attributes', async render => {
const e = await render(<div foo="bar" />, 1);
expect(e.getAttribute('foo')).toBe(null);
});
itRenders('unknown data- attributes', async render => {
const e = await render(<div data-foo="bar" />);
expect(e.getAttribute('data-foo')).toBe('bar');
});
itRenders(
'no unknown attributes for non-standard elements',
async render => {
const e = await render(<nonstandard foo="bar" />, 1);
expect(e.getAttribute('foo')).toBe(null);
},
);
itRenders('unknown attributes for custom elements', async render => {
const e = await render(<custom-element foo="bar" />);
expect(e.getAttribute('foo')).toBe('bar');
});
itRenders(
'unknown attributes for custom elements using is',
async render => {
const e = await render(<div is="custom-element" foo="bar" />);
expect(e.getAttribute('foo')).toBe('bar');
},
);
});
itRenders('no HTML events', async render => {
const e = await render(<div onClick={() => {}} />);
expect(e.getAttribute('onClick')).toBe(null);
expect(e.getAttribute('onClick')).toBe(null);
expect(e.getAttribute('click')).toBe(null);
});
});
});
+133 -89
View File
@@ -11,56 +11,30 @@
*/
'use strict';
var ReactNative = require('ReactNative');
var ReactNativeFeatureFlags = require('ReactNativeFeatureFlags');
var ReactNativeAttributePayload = require('ReactNativeAttributePayload');
var TextInputState = require('TextInputState');
var UIManager = require('UIManager');
var invariant = require('fbjs/lib/invariant');
var findNodeHandle = require('findNodeHandle');
type MeasureOnSuccessCallback = (
x: number,
y: number,
width: number,
height: number,
pageX: number,
pageY: number,
) => void;
var {
mountSafeCallback,
throwOnStylesProp,
warnForStyleProps,
} = require('NativeMethodsMixinUtils');
type MeasureInWindowOnSuccessCallback = (
x: number,
y: number,
width: number,
height: number,
) => void;
import type {
MeasureInWindowOnSuccessCallback,
MeasureLayoutOnSuccessCallback,
MeasureOnSuccessCallback,
} from 'NativeMethodsMixinUtils';
import type {
ReactNativeBaseComponentViewConfig,
} from 'ReactNativeViewConfigRegistry';
type MeasureLayoutOnSuccessCallback = (
left: number,
top: number,
width: number,
height: number,
) => void;
var ReactNative;
function injectReactNative(RN) {
ReactNative = RN;
}
function warnForStyleProps(props, validAttributes) {
for (var key in validAttributes.style) {
if (!(validAttributes[key] || props[key] === undefined)) {
console.error(
'You are setting the style `{ ' +
key +
': ... }` as a prop. You ' +
'should nest it in a style object. ' +
'E.g. `{ style: { ' +
key +
': ... } }`',
);
}
}
}
/**
* `NativeMethodsMixin` provides methods to access the underlying native
@@ -74,6 +48,10 @@ function warnForStyleProps(props, validAttributes) {
* information, see [Direct
* Manipulation](docs/direct-manipulation.html).
*/
// TODO (bvaughn) Figure out how to use the NativeMethodsInterface type to-
// ensure that these mixins and ReactNativeFiberHostComponent stay in sync.
// Unfortunately, using it causes Flow to complain WRT createClass mixins:
// "call of method `createClass`. Expected an exact object instead of ..."
var NativeMethodsMixin = {
/**
* Determines the location on screen, width, and height of the given view and
@@ -149,20 +127,15 @@ var NativeMethodsMixin = {
* Manipulation](docs/direct-manipulation.html)).
*/
setNativeProps: function(nativeProps: Object) {
if (__DEV__) {
warnForStyleProps(nativeProps, this.viewConfig.validAttributes);
}
// Ensure ReactNative factory function has configured findNodeHandle.
// Requiring it won't execute the factory function until first referenced.
// It's possible for tests that use ReactTestRenderer to reach this point,
// Without having executed ReactNative.
// Defer the factory function until now to avoid a cycle with UIManager.
// TODO (bvaughn) Remove this once ReactNativeStack is dropped.
require('ReactNative');
var updatePayload = ReactNativeAttributePayload.create(
nativeProps,
this.viewConfig.validAttributes,
);
UIManager.updateView(
(ReactNative.findNodeHandle(this): any),
this.viewConfig.uiViewClassName,
updatePayload,
);
injectedSetNativeProps(this, nativeProps);
},
/**
@@ -184,23 +157,113 @@ var NativeMethodsMixin = {
__injectReactNative: injectReactNative,
};
function throwOnStylesProp(component, props) {
if (props.styles !== undefined) {
var owner = component._owner || null;
var name = component.constructor.displayName;
var msg = '`styles` is not a supported property of `' +
name +
'`, did ' +
'you mean `style` (singular)?';
if (owner && owner.constructor && owner.constructor.displayName) {
msg += '\n\nCheck the `' +
owner.constructor.displayName +
'` parent ' +
' component.';
}
throw new Error(msg);
// TODO (bvaughn) Inline this once ReactNativeStack is dropped.
function setNativePropsFiber(componentOrHandle: any, nativeProps: Object) {
// Class components don't have viewConfig -> validateAttributes.
// Nor does it make sense to set native props on a non-native component.
// Instead, find the nearest host component and set props on it.
// Use findNodeHandle() rather than ReactNative.findNodeHandle() because
// We want the instance/wrapper (not the native tag).
let maybeInstance;
// Fiber errors if findNodeHandle is called for an umounted component.
// Tests using ReactTestRenderer will trigger this case indirectly.
// Mimicking stack behavior, we should silently ignore this case.
// TODO Fix ReactTestRenderer so we can remove this try/catch.
try {
maybeInstance = findNodeHandle(componentOrHandle);
} catch (error) {}
// If there is no host component beneath this we should fail silently.
// This is not an error; it could mean a class component rendered null.
if (maybeInstance == null) {
return;
}
const viewConfig: ReactNativeBaseComponentViewConfig = maybeInstance.viewConfig;
if (__DEV__) {
warnForStyleProps(nativeProps, viewConfig.validAttributes);
}
var updatePayload = ReactNativeAttributePayload.create(
nativeProps,
viewConfig.validAttributes,
);
UIManager.updateView(
maybeInstance._nativeTag,
viewConfig.uiViewClassName,
updatePayload,
);
}
// TODO (bvaughn) Remove this once ReactNativeStack is dropped.
function setNativePropsStack(componentOrHandle: any, nativeProps: Object) {
// Class components don't have viewConfig -> validateAttributes.
// Nor does it make sense to set native props on a non-native component.
// Instead, find the nearest host component and set props on it.
// Use findNodeHandle() rather than ReactNative.findNodeHandle() because
// We want the instance/wrapper (not the native tag).
let maybeInstance = findNodeHandle(componentOrHandle);
// If there is no host component beneath this we should fail silently.
// This is not an error; it could mean a class component rendered null.
if (maybeInstance == null) {
return;
}
let viewConfig: ReactNativeBaseComponentViewConfig;
if (maybeInstance.viewConfig !== undefined) {
// ReactNativeBaseComponent
viewConfig = maybeInstance.viewConfig;
} else if (
maybeInstance._instance !== undefined &&
maybeInstance._instance.viewConfig !== undefined
) {
// ReactCompositeComponentWrapper
// Some instances (eg Text) define their own viewConfig
viewConfig = maybeInstance._instance.viewConfig;
} else {
// ReactCompositeComponentWrapper
// Other instances (eg TextInput) defer to their children's viewConfig
while (maybeInstance._renderedComponent !== undefined) {
maybeInstance = maybeInstance._renderedComponent;
}
viewConfig = maybeInstance.viewConfig;
}
const tag: number = typeof maybeInstance.getHostNode === 'function'
? maybeInstance.getHostNode()
: maybeInstance._rootNodeID;
if (__DEV__) {
warnForStyleProps(nativeProps, viewConfig.validAttributes);
}
var updatePayload = ReactNativeAttributePayload.create(
nativeProps,
viewConfig.validAttributes,
);
UIManager.updateView(tag, viewConfig.uiViewClassName, updatePayload);
}
// Switching based on fiber vs stack to avoid a lot of inline checks at runtime.
// HACK Normally this injection would be done by the renderer, but in this case
// that would result in a cycle between ReactNative and NativeMethodsMixin.
// We avoid requiring additional code for this injection so it's probably ok?
// TODO (bvaughn) Remove this once ReactNativeStack is gone.
let injectedSetNativeProps: (
componentOrHandle: any,
nativeProps: Object,
) => void;
if (ReactNativeFeatureFlags.useFiber) {
injectedSetNativeProps = setNativePropsFiber;
} else {
injectedSetNativeProps = setNativePropsStack;
}
if (__DEV__) {
// hide this from Flow since we can't define these properties outside of
// __DEV__ without actually implementing them (setting them to undefined
@@ -219,23 +282,4 @@ if (__DEV__) {
};
}
/**
* In the future, we should cleanup callbacks by cancelling them instead of
* using this.
*/
function mountSafeCallback(
context: ReactComponent<any, any, any>,
callback: ?Function,
): any {
return function() {
if (
!callback ||
(typeof context.isMounted === 'function' && !context.isMounted())
) {
return undefined;
}
return callback.apply(context, arguments);
};
}
module.exports = NativeMethodsMixin;
@@ -0,0 +1,108 @@
/**
* 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.
*
* @providesModule NativeMethodsMixinUtils
* @flow
*/
'use strict';
export type MeasureOnSuccessCallback = (
x: number,
y: number,
width: number,
height: number,
pageX: number,
pageY: number,
) => void;
export type MeasureInWindowOnSuccessCallback = (
x: number,
y: number,
width: number,
height: number,
) => void;
export type MeasureLayoutOnSuccessCallback = (
left: number,
top: number,
width: number,
height: number,
) => void;
/**
* Shared between ReactNativeFiberHostComponent and NativeMethodsMixin to keep
* API in sync.
*/
export interface NativeMethodsInterface {
blur(): void,
focus(): void,
measure(callback: MeasureOnSuccessCallback): void,
measureInWindow(callback: MeasureInWindowOnSuccessCallback): void,
measureLayout(
relativeToNativeNode: number,
onSuccess: MeasureLayoutOnSuccessCallback,
onFail: () => void,
): void,
setNativeProps(nativeProps: Object): void,
}
/**
* In the future, we should cleanup callbacks by cancelling them instead of
* using this.
*/
function mountSafeCallback(context: any, callback: ?Function): any {
return function() {
if (
!callback ||
(typeof context.isMounted === 'function' && !context.isMounted())
) {
return undefined;
}
return callback.apply(context, arguments);
};
}
function throwOnStylesProp(component: any, props: any) {
if (props.styles !== undefined) {
var owner = component._owner || null;
var name = component.constructor.displayName;
var msg = '`styles` is not a supported property of `' +
name +
'`, did ' +
'you mean `style` (singular)?';
if (owner && owner.constructor && owner.constructor.displayName) {
msg += '\n\nCheck the `' +
owner.constructor.displayName +
'` parent ' +
' component.';
}
throw new Error(msg);
}
}
function warnForStyleProps(props: any, validAttributes: any) {
for (var key in validAttributes.style) {
if (!(validAttributes[key] || props[key] === undefined)) {
console.error(
'You are setting the style `{ ' +
key +
': ... }` as a prop. You ' +
'should nest it in a style object. ' +
'E.g. `{ style: { ' +
key +
': ... } }`',
);
}
}
}
module.exports = {
mountSafeCallback,
throwOnStylesProp,
warnForStyleProps,
};
+4 -7
View File
@@ -10,14 +10,11 @@
*/
'use strict';
var ReactNativeStack = require('ReactNativeStack');
var NativeMethodsMixin = require('NativeMethodsMixin');
const ReactNativeFeatureFlags = require('ReactNativeFeatureFlags');
// TODO (bvaughn) Enable Fiber experiement via ReactNativeFeatureFlags
var ReactNative = ReactNativeStack;
// TODO: unroll the circular dependency
NativeMethodsMixin.__injectReactNative(ReactNative);
var ReactNative = ReactNativeFeatureFlags.useFiber
? require('ReactNativeFiber')
: require('ReactNativeStack');
ReactNative.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = {
createReactNativeComponentClass: require('createReactNativeComponentClass'),
@@ -102,11 +102,6 @@ var ReactNativeEventEmitter = {
) {
var nativeEvent = nativeEventParam || EMPTY_NATIVE_EVENT;
var inst = ReactNativeComponentTree.getInstanceFromNode(rootNodeID);
if (!inst) {
// If the original instance is already gone, we don't have to dispatch
// any events.
return;
}
ReactGenericBatching.batchedUpdates(function() {
ReactNativeEventEmitter.handleTopLevel(
topLevelType,
+24 -25
View File
@@ -12,18 +12,11 @@
'use strict';
import type {Element} from 'React';
import type {Fiber} from 'ReactFiber';
import type {ReactNodeList} from 'ReactTypes';
import type {
ReactNativeBaseComponentViewConfig,
} from 'ReactNativeViewConfigRegistry';
const NativeMethodsMixin = require('NativeMethodsMixin');
const ReactFiberReconciler = require('ReactFiberReconciler');
const ReactGenericBatching = require('ReactGenericBatching');
const ReactNativeAttributePayload = require('ReactNativeAttributePayload');
const ReactNativeComponentTree = require('ReactNativeComponentTree');
const ReactNativeFiberHostComponent = require('ReactNativeFiberHostComponent');
const ReactNativeInjection = require('ReactNativeInjection');
const ReactNativeTagHandles = require('ReactNativeTagHandles');
const ReactNativeViewConfigRegistry = require('ReactNativeViewConfigRegistry');
@@ -36,6 +29,13 @@ const findNodeHandle = require('findNodeHandle');
const invariant = require('fbjs/lib/invariant');
const {injectInternals} = require('ReactFiberDevToolsHook');
import type {Element} from 'React';
import type {Fiber} from 'ReactFiber';
import type {
ReactNativeBaseComponentViewConfig,
} from 'ReactNativeViewConfigRegistry';
import type {ReactNodeList} from 'ReactTypes';
const {
precacheFiberNode,
uncacheFiberNode,
@@ -45,7 +45,7 @@ const {
ReactNativeInjection.inject();
type Container = number;
type Instance = {
export type Instance = {
_children: Array<Instance | number>,
_nativeTag: number,
viewConfig: ReactNativeBaseComponentViewConfig,
@@ -53,13 +53,6 @@ type Instance = {
type Props = Object;
type TextInstance = number;
function NativeHostComponent(tag, viewConfig) {
this._nativeTag = tag;
this._children = [];
this.viewConfig = viewConfig;
}
Object.assign(NativeHostComponent.prototype, NativeMethodsMixin);
function recursivelyUncacheFiberNode(node: Instance | TextInstance) {
if (typeof node === 'number') {
// Leaf node (eg text)
@@ -162,7 +155,7 @@ const NativeRenderer = ReactFiberReconciler({
const viewConfig = ReactNativeViewConfigRegistry.get(type);
if (__DEV__) {
for (let key in viewConfig.validAttributes) {
for (const key in viewConfig.validAttributes) {
if (props.hasOwnProperty(key)) {
deepFreezeAndThrowOnMutationInDev(props[key]);
}
@@ -181,12 +174,14 @@ const NativeRenderer = ReactFiberReconciler({
updatePayload, // props
);
const component = new NativeHostComponent(tag, viewConfig);
const component = new ReactNativeFiberHostComponent(tag, viewConfig);
precacheFiberNode(internalInstanceHandle, tag);
updateFiberProps(tag, props);
return component;
// Not sure how to avoid this cast. Flow is okay if the component is defined
// in the same file but if it's external it can't see the types.
return ((component: any): Instance);
},
createTextInstance(
@@ -377,14 +372,18 @@ ReactGenericBatching.injection.injectFiberBatchedUpdates(
const roots = new Map();
findNodeHandle.injection.injectFindNode((fiber: Fiber) => {
const instance: any = NativeRenderer.findHostInstance(fiber);
return instance ? instance._nativeTag : null;
});
findNodeHandle.injection.injectFindRootNodeID(instance => instance._nativeTag);
findNodeHandle.injection.injectFindNode((fiber: Fiber) =>
NativeRenderer.findHostInstance(fiber));
findNodeHandle.injection.injectFindRootNodeID(instance => instance);
const ReactNative = {
findNodeHandle,
// External users of findNodeHandle() expect the host tag number return type.
// The injected findNodeHandle() strategy returns the instance wrapper though.
// See NativeMethodsMixin#setNativeProps for more info on why this is done.
findNodeHandle(componentOrHandle: any): ?number {
const instance: any = findNodeHandle(componentOrHandle);
return instance ? instance._nativeTag : null;
},
render(element: Element<any>, containerTag: any, callback: ?Function) {
let root = roots.get(containerTag);
@@ -0,0 +1,104 @@
/**
* 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 ReactNativeFiberHostComponent
* @flow
* @preventMunge
*/
'use strict';
var ReactNativeAttributePayload = require('ReactNativeAttributePayload');
var TextInputState = require('TextInputState');
var UIManager = require('UIManager');
var {
mountSafeCallback,
warnForStyleProps,
} = require('NativeMethodsMixinUtils');
import type {
MeasureInWindowOnSuccessCallback,
MeasureLayoutOnSuccessCallback,
MeasureOnSuccessCallback,
NativeMethodsInterface,
} from 'NativeMethodsMixinUtils';
import type {Instance} from 'ReactNativeFiber';
import type {
ReactNativeBaseComponentViewConfig,
} from 'ReactNativeViewConfigRegistry';
/**
* This component defines the same methods as NativeMethodsMixin but without the
* findNodeHandle wrapper. This wrapper is unnecessary for HostComponent views
* and would also result in a circular require.js dependency (since
* ReactNativeFiber depends on this component and NativeMethodsMixin depends on
* ReactNativeFiber).
*/
class ReactNativeFiberHostComponent implements NativeMethodsInterface {
_children: Array<Instance | number>;
_nativeTag: number;
viewConfig: ReactNativeBaseComponentViewConfig;
constructor(tag: number, viewConfig: ReactNativeBaseComponentViewConfig) {
this._nativeTag = tag;
this._children = [];
this.viewConfig = viewConfig;
}
blur() {
TextInputState.blurTextInput(this._nativeTag);
}
focus() {
TextInputState.focusTextInput(this._nativeTag);
}
measure(callback: MeasureOnSuccessCallback) {
UIManager.measure(this._nativeTag, mountSafeCallback(this, callback));
}
measureInWindow(callback: MeasureInWindowOnSuccessCallback) {
UIManager.measureInWindow(
this._nativeTag,
mountSafeCallback(this, callback),
);
}
measureLayout(
relativeToNativeNode: number,
onSuccess: MeasureLayoutOnSuccessCallback,
onFail: () => void /* currently unused */,
) {
UIManager.measureLayout(
this._nativeTag,
relativeToNativeNode,
mountSafeCallback(this, onFail),
mountSafeCallback(this, onSuccess),
);
}
setNativeProps(nativeProps: Object) {
if (__DEV__) {
warnForStyleProps(nativeProps, this.viewConfig.validAttributes);
}
var updatePayload = ReactNativeAttributePayload.create(
nativeProps,
this.viewConfig.validAttributes,
);
UIManager.updateView(
this._nativeTag,
this.viewConfig.uiViewClassName,
updatePayload,
);
}
}
module.exports = ReactNativeFiberHostComponent;
+9 -5
View File
@@ -13,8 +13,8 @@
var ReactNativeComponentTree = require('ReactNativeComponentTree');
var ReactNativeInjection = require('ReactNativeInjection');
var ReactNativeStackInjection = require('ReactNativeStackInjection');
var ReactNativeMount = require('ReactNativeMount');
var ReactNativeStackInjection = require('ReactNativeStackInjection');
var ReactUpdates = require('ReactUpdates');
var findNodeHandle = require('findNodeHandle');
@@ -30,12 +30,16 @@ var render = function(
return ReactNativeMount.renderComponent(element, mountInto, callback);
};
findNodeHandle.injection.injectFindNode(instance => instance.getHostNode());
findNodeHandle.injection.injectFindRootNodeID(instance => instance._rootNodeID);
var ReactNative = {
hasReactNativeInitialized: false,
findNodeHandle: findNodeHandle,
// External users of findNodeHandle() expect the host tag number return type.
// The injected findNodeHandle() strategy returns the instance wrapper though.
// See NativeMethodsMixin#setNativeProps for more info on why this is done.
findNodeHandle(componentOrHandle: any): ?number {
return findNodeHandle(componentOrHandle).getHostNode();
},
render: render,
unmountComponentAtNode: ReactNativeMount.unmountComponentAtNode,
@@ -60,10 +60,8 @@ function inject() {
);
};
findNodeHandle.injection.injectFindNode(instance => instance.getHostNode());
findNodeHandle.injection.injectFindRootNodeID(
instance => instance._rootNodeID,
);
findNodeHandle.injection.injectFindNode(instance => instance);
findNodeHandle.injection.injectFindRootNodeID(instance => instance);
ReactEmptyComponent.injection.injectEmptyComponentFactory(EmptyComponent);
@@ -87,6 +87,93 @@ it('handles events', () => {
]);
});
it('handles events on text nodes', () => {
expect(RCTEventEmitter.register.mock.calls.length).toBe(1);
var EventEmitter = RCTEventEmitter.register.mock.calls[0][0];
var Text = createReactNativeComponentClass({
validAttributes: {foo: true},
uiViewClassName: 'Text',
});
class ContextHack extends React.Component {
static childContextTypes = {isInAParentText: React.PropTypes.bool};
getChildContext() {
return {isInAParentText: true};
}
render() {
return this.props.children;
}
}
var log = [];
ReactNative.render(
<ContextHack>
<Text>
<Text
onTouchEnd={() => log.push('string touchend')}
onTouchEndCapture={() => log.push('string touchend capture')}
onTouchStart={() => log.push('string touchstart')}
onTouchStartCapture={() => log.push('string touchstart capture')}>
Text Content
</Text>
<Text
onTouchEnd={() => log.push('number touchend')}
onTouchEndCapture={() => log.push('number touchend capture')}
onTouchStart={() => log.push('number touchstart')}
onTouchStartCapture={() => log.push('number touchstart capture')}>
{123}
</Text>
</Text>
</ContextHack>,
1,
);
expect(UIManager.createView.mock.calls.length).toBe(5);
// Don't depend on the order of createView() calls.
// Stack creates views outside-in; fiber creates them inside-out.
var innerTagString = UIManager.createView.mock.calls.find(
args => args[3] && args[3].text === 'Text Content',
)[0];
var innerTagNumber = UIManager.createView.mock.calls.find(
args => args[3] && args[3].text === '123',
)[0];
EventEmitter.receiveTouches(
'topTouchStart',
[{target: innerTagString, identifier: 17}],
[0],
);
EventEmitter.receiveTouches(
'topTouchEnd',
[{target: innerTagString, identifier: 17}],
[0],
);
EventEmitter.receiveTouches(
'topTouchStart',
[{target: innerTagNumber, identifier: 18}],
[0],
);
EventEmitter.receiveTouches(
'topTouchEnd',
[{target: innerTagNumber, identifier: 18}],
[0],
);
expect(log).toEqual([
'string touchstart capture',
'string touchstart',
'string touchend capture',
'string touchend',
'number touchstart capture',
'number touchstart',
'number touchend capture',
'number touchend',
]);
});
it('handles when a responder is unmounted while a touch sequence is in progress', () => {
var EventEmitter = RCTEventEmitter.register.mock.calls[0][0];
var View = createReactNativeComponentClass({
@@ -180,3 +267,97 @@ it('handles when a responder is unmounted while a touch sequence is in progress'
expect(getResponderId()).toBe('two');
expect(log).toEqual(['two responder start']);
});
it('handles events without target', () => {
var EventEmitter = RCTEventEmitter.register.mock.calls[0][0];
var View = createReactNativeComponentClass({
validAttributes: {id: true},
uiViewClassName: 'View',
});
function getViewById(id) {
return UIManager.createView.mock.calls.find(
args => args[3] && args[3].id === id,
)[0];
}
function getResponderId() {
const responder = ResponderEventPlugin._getResponder();
if (responder === null) {
return null;
}
const props = typeof responder.tag === 'number'
? responder.memoizedProps
: responder._currentElement.props;
return props ? props.id : null;
}
var log = [];
function render(renderFirstComponent) {
ReactNative.render(
<View id="parent">
<View key={1}>
{renderFirstComponent
? <View
id="one"
onResponderEnd={() => log.push('one responder end')}
onResponderStart={() => log.push('one responder start')}
onStartShouldSetResponder={() => true}
/>
: null}
</View>
<View key={2}>
<View
id="two"
onResponderEnd={() => log.push('two responder end')}
onResponderStart={() => log.push('two responder start')}
onStartShouldSetResponder={() => true}
/>
</View>
</View>,
1,
);
}
render(true);
EventEmitter.receiveTouches(
'topTouchStart',
[{target: getViewById('one'), identifier: 17}],
[0],
);
// Unmounting component 'one'.
render(false);
EventEmitter.receiveTouches(
'topTouchEnd',
[{target: getViewById('one'), identifier: 17}],
[0],
);
expect(getResponderId()).toBe(null);
EventEmitter.receiveTouches(
'topTouchStart',
[{target: getViewById('two'), identifier: 18}],
[0],
);
expect(getResponderId()).toBe('two');
EventEmitter.receiveTouches(
'topTouchEnd',
[{target: getViewById('two'), identifier: 18}],
[0],
);
expect(getResponderId()).toBe(null);
expect(log).toEqual([
'one responder start',
'two responder start',
'two responder end',
]);
});
@@ -13,8 +13,8 @@
'use strict';
const ReactNativeBaseComponent = require('ReactNativeBaseComponent');
const ReactNativeViewConfigRegistry = require('ReactNativeViewConfigRegistry');
const ReactNativeFeatureFlags = require('ReactNativeFeatureFlags');
const ReactNativeViewConfigRegistry = require('ReactNativeViewConfigRegistry');
// See also ReactNativeBaseComponent
type ReactNativeBaseComponentViewConfig = {
+4 -1
View File
@@ -53,7 +53,10 @@ import type {ReactInstance} from 'ReactInstanceType';
let injectedFindNode;
let injectedFindRootNodeID;
function findNodeHandle(componentOrHandle: any): ?number {
// TODO (bvaughn) Rename the findNodeHandle module to something more descriptive
// eg findInternalHostInstance. This will reduce the likelihood of someone
// accidentally deep-requiring this version.
function findNodeHandle(componentOrHandle: any): any {
if (__DEV__) {
// TODO: fix this unsafe cast to work with Fiber.
var owner = ((ReactCurrentOwner.current: any): ReactInstance | null);
@@ -127,8 +127,7 @@ function throwOnInvalidObjectType(returnFiber: Fiber, newChild: Object) {
let addendum = '';
if (__DEV__) {
addendum = ' If you meant to render a collection of children, use an array ' +
'instead or wrap the object using createFragment(object) from the ' +
'React add-ons.';
'instead.';
const owner = ReactCurrentOwner.owner || returnFiber._debugOwner;
if (owner && typeof owner.tag === 'number') {
const name = getComponentName((owner: any));
@@ -571,7 +571,13 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
// Check for pending update priority. This is usually null so it shouldn't
// be a perf issue.
const queue = workInProgress.updateQueue;
if (queue !== null) {
const tag = workInProgress.tag;
if (
queue !== null &&
// TODO: Revisit once updateQueue is typed properly to distinguish between
// update payloads for host components and update queues for composites
(tag === ClassComponent || tag === HostRoot)
) {
newPriority = getPendingPriority(queue);
}
@@ -90,7 +90,7 @@ function comparePriority(a: PriorityLevel, b: PriorityLevel): number {
// Ensures that a fiber has an update queue, creating a new one if needed.
// Returns the new or existing queue.
function ensureUpdateQueue(fiber: Fiber): UpdateQueue {
if (fiber.updateQueue) {
if (fiber.updateQueue !== null) {
// We already have an update queue.
return fiber.updateQueue;
}
@@ -123,13 +123,15 @@ function cloneUpdateQueue(
workInProgress: Fiber,
): UpdateQueue | null {
const currentQueue = current.updateQueue;
if (!currentQueue) {
if (currentQueue === null) {
// The source fiber does not have an update queue.
workInProgress.updateQueue = null;
return null;
}
// If the alternate already has a queue, reuse the previous object.
const altQueue = workInProgress.updateQueue || {};
const altQueue = workInProgress.updateQueue !== null
? workInProgress.updateQueue
: {};
altQueue.first = currentQueue.first;
altQueue.last = currentQueue.last;
@@ -156,8 +158,13 @@ function cloneUpdate(update: Update): Update {
};
}
function insertUpdateIntoQueue(queue, update, insertAfter, insertBefore) {
if (insertAfter) {
function insertUpdateIntoQueue(
queue: UpdateQueue,
update: Update,
insertAfter: Update | null,
insertBefore: Update | null,
) {
if (insertAfter !== null) {
insertAfter.next = update;
} else {
// This is the first item in the queue.
@@ -165,7 +172,7 @@ function insertUpdateIntoQueue(queue, update, insertAfter, insertBefore) {
queue.first = update;
}
if (insertBefore) {
if (insertBefore !== null) {
update.next = insertBefore;
} else {
// This is the last item in the queue.
@@ -180,7 +187,8 @@ function findInsertionPosition(queue, update): Update | null {
let insertAfter = null;
let insertBefore = null;
if (
queue.last && comparePriority(queue.last.priorityLevel, priorityLevel) <= 0
queue.last !== null &&
comparePriority(queue.last.priorityLevel, priorityLevel) <= 0
) {
// Fast path for the common case where the update should be inserted at
// the end of the queue.
@@ -188,7 +196,7 @@ function findInsertionPosition(queue, update): Update | null {
} else {
insertBefore = queue.first;
while (
insertBefore &&
insertBefore !== null &&
comparePriority(insertBefore.priorityLevel, priorityLevel) <= 0
) {
insertAfter = insertBefore;
@@ -229,11 +237,13 @@ function findInsertionPosition(queue, update): Update | null {
// If the update is cloned, it returns the cloned update.
function insertUpdate(fiber: Fiber, update: Update): Update | null {
const queue1 = ensureUpdateQueue(fiber);
const queue2 = fiber.alternate ? ensureUpdateQueue(fiber.alternate) : null;
const queue2 = fiber.alternate !== null
? ensureUpdateQueue(fiber.alternate)
: null;
// Warn if an update is scheduled from inside an updater function.
if (__DEV__) {
if (queue1.isProcessing || (queue2 && queue2.isProcessing)) {
if (queue1.isProcessing || (queue2 !== null && queue2.isProcessing)) {
warning(
false,
'An update (setState, replaceState, or forceUpdate) was scheduled ' +
@@ -246,9 +256,11 @@ function insertUpdate(fiber: Fiber, update: Update): Update | null {
// Find the insertion position in the first queue.
const insertAfter1 = findInsertionPosition(queue1, update);
const insertBefore1 = insertAfter1 ? insertAfter1.next : queue1.first;
const insertBefore1 = insertAfter1 !== null
? insertAfter1.next
: queue1.first;
if (!queue2) {
if (queue2 === null) {
// If there's no alternate queue, there's nothing else to do but insert.
insertUpdateIntoQueue(queue1, update, insertAfter1, insertBefore1);
return null;
@@ -256,7 +268,9 @@ function insertUpdate(fiber: Fiber, update: Update): Update | null {
// If there is an alternate queue, find the insertion position.
const insertAfter2 = findInsertionPosition(queue2, update);
const insertBefore2 = insertAfter2 ? insertAfter2.next : queue2.first;
const insertBefore2 = insertAfter2 !== null
? insertAfter2.next
: queue2.first;
// Now we can insert into the first queue. This must come after finding both
// insertion positions because it mutates the list.
@@ -273,10 +287,10 @@ function insertUpdate(fiber: Fiber, update: Update): Update | null {
// queue, it also inserted into the alternate. All we need to do is update
// the alternate queue's `first` and `last` pointers, in case they
// have changed.
if (!insertAfter2) {
if (insertAfter2 === null) {
queue2.first = update;
}
if (!insertBefore2) {
if (insertBefore2 === null) {
queue2.last = null;
}
}
@@ -341,7 +355,7 @@ function addForceUpdate(
exports.addForceUpdate = addForceUpdate;
function getPendingPriority(queue: UpdateQueue): PriorityLevel {
return queue.first ? queue.first.priorityLevel : NoWork;
return queue.first !== null ? queue.first.priorityLevel : NoWork;
}
exports.getPendingPriority = getPendingPriority;
@@ -351,7 +365,7 @@ function addTopLevelUpdate(
callback: Callback | null,
priorityLevel: PriorityLevel,
): void {
const isTopLevelUnmount = !!(partialState && partialState.element === null);
const isTopLevelUnmount = partialState.element === null;
const update = {
priorityLevel,
@@ -368,13 +382,15 @@ function addTopLevelUpdate(
// Drop all updates that are lower-priority, so that the tree is not
// remounted. We need to do this for both queues.
const queue1 = fiber.updateQueue;
const queue2 = fiber.alternate && fiber.alternate.updateQueue;
const queue2 = fiber.alternate !== null
? fiber.alternate.updateQueue
: null;
if (queue1 && update.next) {
if (queue1 !== null && update.next !== null) {
update.next = null;
queue1.last = update;
}
if (queue2 && update2 && update2.next) {
if (queue2 !== null && update2 !== null && update2.next !== null) {
update2.next = null;
queue2.last = update;
}
@@ -414,12 +430,14 @@ function beginUpdateQueue(
let dontMutatePrevState = true;
let callbackList = null;
let update = queue.first;
while (update && comparePriority(update.priorityLevel, priorityLevel) <= 0) {
while (
update !== null && comparePriority(update.priorityLevel, priorityLevel) <= 0
) {
// Remove each update from the queue right before it is processed. That way
// if setState is called from inside an updater function, the new update
// will be inserted in the correct position.
queue.first = update.next;
if (!queue.first) {
if (queue.first === null) {
queue.last = null;
}
@@ -456,7 +474,7 @@ function beginUpdateQueue(
queue.callbackList = callbackList;
if (!queue.first && !callbackList && !queue.hasForceUpdate) {
if (queue.first === null && callbackList === null && !queue.hasForceUpdate) {
// The queue is empty and there are no callbacks. We can reset it.
workInProgress.updateQueue = null;
}
@@ -475,7 +493,7 @@ function commitCallbacks(
context: mixed,
) {
const callbackList = queue.callbackList;
if (!callbackList) {
if (callbackList === null) {
return;
}
for (let i = 0; i < callbackList.length; i++) {
@@ -138,7 +138,10 @@ var EventPluginHub = {
return null;
}
} else {
if (typeof inst._currentElement === 'string') {
const currentElement = inst._currentElement;
if (
typeof currentElement === 'string' || typeof currentElement === 'number'
) {
// Text node, let it bubble through.
return null;
}
@@ -146,14 +149,10 @@ var EventPluginHub = {
// If the instance is already unmounted, we have no listeners.
return null;
}
const props = inst._currentElement.props;
const props = currentElement.props;
listener = props[registrationName];
if (
shouldPreventMouseEvent(
registrationName,
inst._currentElement.type,
props,
)
shouldPreventMouseEvent(registrationName, currentElement.type, props)
) {
return null;
}
+1 -2
View File
@@ -151,8 +151,7 @@ function traverseAllChildrenImpl(
var addendum = '';
if (__DEV__) {
addendum = ' If you meant to render a collection of children, use an array ' +
'instead or wrap the object using createFragment(object) from the ' +
'React add-ons.';
'instead.';
if (ReactCurrentOwner.current) {
var name = ReactCurrentOwner.current.getName();
if (name) {
-7
View File
@@ -11,7 +11,6 @@
'use strict';
var React = require('react');
var ReactDOM = require('react-dom');
var ReactDOMUMDEntry = ReactDOM;
@@ -25,10 +24,4 @@ if (__DEV__) {
};
}
// Inject ReactDOM into React for the addons UMD build that depends on ReactDOM (TransitionGroup).
// We can remove this after we deprecate and remove the addons UMD build.
if (React.addons) {
React.__SECRET_INJECTED_REACT_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactDOMUMDEntry;
}
module.exports = ReactDOMUMDEntry;
-37
View File
@@ -1,37 +0,0 @@
/**
* 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 ReactWithAddonsUMDEntry
*/
'use strict';
var ReactWithAddons = require('ReactWithAddons');
// `version` will be added here by the React module.
var ReactWithAddonsUMDEntry = Object.assign(
{
__SECRET_INJECTED_REACT_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: null, // Will be injected by ReactDOM UMD build.
__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: {
ReactCurrentOwner: require('react/lib/ReactCurrentOwner'),
},
},
ReactWithAddons,
);
if (__DEV__) {
Object.assign(
ReactWithAddonsUMDEntry.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,
{
// ReactComponentTreeHook should not be included in production.
ReactComponentTreeHook: require('react/lib/ReactComponentTreeHook'),
},
);
}
module.exports = ReactWithAddonsUMDEntry;
@@ -1,36 +0,0 @@
/**
* 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 ReactAddonsDOMDependenciesUMDShim
*/
'use strict';
var ReactDOM;
function getReactDOM() {
if (!ReactDOM) {
// This is safe to use because current module only exists in the addons build:
var ReactWithAddonsUMDEntry = require('ReactWithAddonsUMDEntry');
// This is injected by the ReactDOM UMD build:
ReactDOM = ReactWithAddonsUMDEntry.__SECRET_INJECTED_REACT_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
}
return ReactDOM;
}
exports.getReactDOM = getReactDOM;
if (__DEV__) {
exports.getReactPerf = function() {
return getReactDOM().__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactPerf;
};
exports.getReactTestUtils = function() {
return getReactDOM().__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactTestUtils;
};
}
+3 -3
View File
@@ -2306,9 +2306,9 @@ flat-cache@^1.2.1:
graceful-fs "^4.1.2"
write "^0.2.1"
flow-bin@^0.37.0:
version "0.37.4"
resolved "https://registry.yarnpkg.com/flow-bin/-/flow-bin-0.37.4.tgz#3d8da2ef746e80e730d166e09040f4198969b76b"
flow-bin@^0.41.0:
version "0.41.0"
resolved "https://registry.yarnpkg.com/flow-bin/-/flow-bin-0.41.0.tgz#8badac9a19da45004997e599bd316518db489b2e"
flow-parser@0.40.0:
version "0.40.0"