Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4c67be212d | ||
|
|
93e0bdf2ee | ||
|
|
a684f09e58 |
@@ -40,9 +40,3 @@ jobs:
|
||||
key: v1-node-{{ arch }}-{{ .Branch }}-{{ checksum "yarn.lock" }}
|
||||
paths:
|
||||
- node_modules
|
||||
|
||||
- store_artifacts:
|
||||
path: ./node_modules.tgz
|
||||
|
||||
- store_artifacts:
|
||||
path: ./scripts/error-codes/codes.json
|
||||
48
.eslintrc.js
48
.eslintrc.js
@@ -1,10 +1,5 @@
|
||||
'use strict';
|
||||
|
||||
const {
|
||||
es5Paths,
|
||||
esNextPaths,
|
||||
} = require('./scripts/shared/pathsByLanguageVersion');
|
||||
|
||||
const OFF = 0;
|
||||
const ERROR = 2;
|
||||
|
||||
@@ -21,15 +16,6 @@ module.exports = {
|
||||
'react-internal',
|
||||
],
|
||||
|
||||
parser: 'espree',
|
||||
parserOptions: {
|
||||
ecmaVersion: 2017,
|
||||
sourceType: 'script',
|
||||
ecmaFeatures: {
|
||||
experimentalObjectRestSpread: true,
|
||||
},
|
||||
},
|
||||
|
||||
// We're stricter than the default config, mostly. We'll override a few rules
|
||||
// and then enable some React specific ones.
|
||||
rules: {
|
||||
@@ -58,13 +44,6 @@ module.exports = {
|
||||
'space-before-function-paren': OFF,
|
||||
'valid-typeof': [ERROR, {requireStringLiterals: true}],
|
||||
|
||||
// We apply these settings to files that should run on Node.
|
||||
// They can't use JSX or ES6 modules, and must be in strict mode.
|
||||
// They can, however, use other ES6 features.
|
||||
// (Note these rules are overridden later for source files.)
|
||||
'no-var': ERROR,
|
||||
strict: ERROR,
|
||||
|
||||
// React & JSX
|
||||
// Our transforms set this automatically
|
||||
'react/jsx-boolean-value': [ERROR, 'always'],
|
||||
@@ -92,33 +71,6 @@ module.exports = {
|
||||
},
|
||||
|
||||
overrides: [
|
||||
{
|
||||
// We apply these settings to files that we ship through npm.
|
||||
// They must be ES5.
|
||||
files: es5Paths,
|
||||
parser: 'espree',
|
||||
parserOptions: {
|
||||
ecmaVersion: 5,
|
||||
sourceType: 'script',
|
||||
},
|
||||
rules: {
|
||||
'no-var': OFF,
|
||||
strict: ERROR,
|
||||
},
|
||||
},
|
||||
{
|
||||
// We apply these settings to the source files that get compiled.
|
||||
// They can use all features including JSX (but shouldn't use `var`).
|
||||
files: esNextPaths,
|
||||
parser: 'babel-eslint',
|
||||
parserOptions: {
|
||||
sourceType: 'module',
|
||||
},
|
||||
rules: {
|
||||
'no-var': ERROR,
|
||||
strict: OFF,
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/__tests__/*.js'],
|
||||
rules: {
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
'use strict';
|
||||
|
||||
const {esNextPaths} = require('./scripts/shared/pathsByLanguageVersion');
|
||||
|
||||
module.exports = {
|
||||
|
||||
67
CHANGELOG.md
67
CHANGELOG.md
@@ -4,74 +4,9 @@
|
||||
Changes that have landed in master but are not yet released.
|
||||
Click to see more.
|
||||
</summary>
|
||||
|
||||
</details>
|
||||
|
||||
## 16.6.3 (November 12, 2018)
|
||||
|
||||
### React DOM
|
||||
|
||||
* Fix bugs in `Suspense` and `lazy`. ([@acdlite](https://github.com/acdlite) in [#14133](https://github.com/facebook/react/pull/14133), [#14157](https://github.com/facebook/react/pull/14157), and [#14164](https://github.com/facebook/react/pull/14164))
|
||||
* Fix highlighting of `React.memo` updates in React DevTools. ([@bvaughn](https://github.com/bvaughn) in [#14141](https://github.com/facebook/react/pull/14141))
|
||||
* Fix interaction of Suspense with the React Profiler. ([@bvaughn](https://github.com/bvaughn) in [#14065](https://github.com/facebook/react/pull/14065))
|
||||
* Fix a false positive warning when using Suspense. ([@acdlite](https://github.com/acdlite) in [#14158](https://github.com/facebook/react/pull/14158))
|
||||
|
||||
### React DOM Server
|
||||
|
||||
* Fix incorrect sharing of context state between `renderToNodeStream()` calls. ([@sebmarkbage](https://github.com/sebmarkbage) in [#14182](https://github.com/facebook/react/pull/14182))
|
||||
* Add a warning about incorrect usage of the context API. ([@trueadm](https://github.com/trueadm) in [#14033](https://github.com/facebook/react/pull/14033))
|
||||
|
||||
## 16.6.2 (November 12, 2018)
|
||||
|
||||
This release was published in a broken state and should be skipped.
|
||||
|
||||
## 16.6.1 (November 6, 2018)
|
||||
|
||||
### React DOM
|
||||
|
||||
* Fallback should not remount every time a promise resolves. ([@acdlite](https://github.com/acdlite) in [#14083](https://github.com/facebook/react/pull/14083))
|
||||
* Fix bug where Suspense keeps showing fallback even after everything finishes loading. ([@acdlite](https://github.com/acdlite) in [#14083](https://github.com/facebook/react/pull/14083))
|
||||
* Fix unresolved default props in lifecycle methods of a lazy component. ([@gaearon](https://github.com/gaearon) in [#14112](https://github.com/facebook/react/pull/14112))
|
||||
* Fix bug when recovering from an error thrown during complete phase. ([@gaearon](https://github.com/gaearon) in [#14104](https://github.com/facebook/react/pull/14104))
|
||||
|
||||
### Scheduler (Experimental)
|
||||
|
||||
* Switch from deadline object to `shouldYield` API. ([@acdlite](https://github.com/acdlite) in [#14025](https://github.com/facebook/react/pull/14025))
|
||||
|
||||
|
||||
## 16.6.0 (October 23, 2018)
|
||||
|
||||
### React
|
||||
|
||||
* Add `React.memo()` as an alternative to `PureComponent` for functions. ([@acdlite](https://github.com/acdlite) in [#13748](https://github.com/facebook/react/pull/13748))
|
||||
* Add `React.lazy()` for code splitting components. ([@acdlite](https://github.com/acdlite) in [#13885](https://github.com/facebook/react/pull/13885))
|
||||
* `React.StrictMode` now warns about legacy context API. ([@bvaughn](https://github.com/bvaughn) in [#13760](https://github.com/facebook/react/pull/13760))
|
||||
* `React.StrictMode` now warns about `findDOMNode`. ([@sebmarkbage](https://github.com/sebmarkbage) in [#13841](https://github.com/facebook/react/pull/13841))
|
||||
* Rename `unstable_AsyncMode` to `unstable_ConcurrentMode`. ([@trueadm](https://github.com/trueadm) in [#13732](https://github.com/facebook/react/pull/13732))
|
||||
* Rename `unstable_Placeholder` to `Suspense`, and `delayMs` to `maxDuration`. ([@gaearon](https://github.com/gaearon) in [#13799](https://github.com/facebook/react/pull/13799) and [@sebmarkbage](https://github.com/sebmarkbage) in [#13922](https://github.com/facebook/react/pull/13922))
|
||||
|
||||
### React DOM
|
||||
|
||||
* Add `contextType` as a more ergonomic way to subscribe to context from a class. ([@bvaughn](https://github.com/bvaughn) in [#13728](https://github.com/facebook/react/pull/13728))
|
||||
* Add `getDerivedStateFromError` lifecycle method for catching errors in a future asynchronous server-side renderer. ([@bvaughn](https://github.com/bvaughn) in [#13746](https://github.com/facebook/react/pull/13746))
|
||||
* Warn when `<Context>` is used instead of `<Context.Consumer>`. ([@trueadm](https://github.com/trueadm) in [#13829](https://github.com/facebook/react/pull/13829))
|
||||
* Fix gray overlay on iOS Safari. ([@philipp-spiess](https://github.com/philipp-spiess) in [#13778](https://github.com/facebook/react/pull/13778))
|
||||
* Fix a bug caused by overwriting `window.event` in development. ([@sergei-startsev](https://github.com/sergei-startsev) in [#13697](https://github.com/facebook/react/pull/13697))
|
||||
|
||||
### React DOM Server
|
||||
|
||||
* Add support for `React.memo()`. ([@alexmckenley](https://github.com/alexmckenley) in [#13855](https://github.com/facebook/react/pull/13855))
|
||||
* Add support for `contextType`. ([@alexmckenley](https://github.com/alexmckenley) and [@sebmarkbage](https://github.com/sebmarkbage) in [#13889](https://github.com/facebook/react/pull/13889))
|
||||
|
||||
### Scheduler (Experimental)
|
||||
|
||||
* Rename the package to `scheduler`. ([@gaearon](https://github.com/gaearon) in [#13683](https://github.com/facebook/react/pull/13683))
|
||||
* Support priority levels, continuations, and wrapped callbacks. ([@acdlite](https://github.com/acdlite) in [#13720](https://github.com/facebook/react/pull/13720) and [#13842](https://github.com/facebook/react/pull/13842))
|
||||
* Improve the fallback mechanism in non-DOM environments. ([@acdlite](https://github.com/acdlite) in [#13740](https://github.com/facebook/react/pull/13740))
|
||||
* Schedule `requestAnimationFrame` earlier. ([@acdlite](https://github.com/acdlite) in [#13785](https://github.com/facebook/react/pull/13785))
|
||||
* Fix the DOM detection to be more thorough. ([@trueadm](https://github.com/trueadm) in [#13731](https://github.com/facebook/react/pull/13731))
|
||||
* Fix bugs with interaction tracing. ([@bvaughn](https://github.com/bvaughn) in [#13590](https://github.com/facebook/react/pull/13590))
|
||||
* Add the `envify` transform to the package. ([@mridgway](https://github.com/mridgway) in [#13766](https://github.com/facebook/react/pull/13766))
|
||||
|
||||
## 16.5.2 (September 18, 2018)
|
||||
|
||||
### React DOM
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
//
|
||||
// You'll need a GitHub token, you can re-use this one:
|
||||
//
|
||||
// 0a7d5c3cad9a6dbec2d9 9a5222cf49062a4c1ef7
|
||||
// e622517d9f1136ea8900 07c6373666312cdfaa69
|
||||
//
|
||||
// (Just remove the space)
|
||||
//
|
||||
@@ -29,16 +29,9 @@ const {markdown, danger} = require('danger');
|
||||
const fetch = require('node-fetch');
|
||||
|
||||
const {generateResultsArray} = require('./scripts/rollup/stats');
|
||||
const {existsSync, readFileSync} = require('fs');
|
||||
const {readFileSync} = require('fs');
|
||||
const {exec} = require('child_process');
|
||||
|
||||
if (!existsSync('./scripts/rollup/results.json')) {
|
||||
// This indicates the build failed previously.
|
||||
// In that case, there's nothing for the Dangerfile to do.
|
||||
// Exit early to avoid leaving a redundant (and potentially confusing) PR comment.
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const currentBuildResults = JSON.parse(
|
||||
readFileSync('./scripts/rollup/results.json')
|
||||
);
|
||||
|
||||
@@ -32,7 +32,7 @@ class VectorWidget extends React.Component {
|
||||
/**
|
||||
* When the component is mounted into the document - this is similar to a
|
||||
* constructor, but invoked when the instance is actually mounted into the
|
||||
* document. Here, we'll just set up an animation loop that invokes our
|
||||
* document. Here's, we'll just set up an animation loop that invokes our
|
||||
* method. Binding of `this.onTick` is not needed because all React methods
|
||||
* are automatically bound before being mounted.
|
||||
*/
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
},
|
||||
"scripts": {
|
||||
"prestart":
|
||||
"cp ../../build/node_modules/react/umd/react.development.js public/ && cp ../../build/node_modules/react-dom/umd/react-dom.development.js public/ && cp ../../build/node_modules/react-dom/umd/react-dom-server.browser.development.js public/",
|
||||
"cp ../../build/dist/react.development.js public/ && cp ../../build/dist/react-dom.development.js public/ && cp ../../build/dist/react-dom-server.browser.development.js public/",
|
||||
"start": "react-scripts start",
|
||||
"build": "react-scripts build",
|
||||
"test": "react-scripts test --env=jsdom",
|
||||
|
||||
@@ -860,7 +860,7 @@ class App extends React.Component {
|
||||
});
|
||||
break;
|
||||
default:
|
||||
throw new Error('Switch statement should be exhaustive');
|
||||
throw new Error('Switch statement should be exhuastive');
|
||||
}
|
||||
|
||||
// Sort
|
||||
@@ -887,7 +887,7 @@ class App extends React.Component {
|
||||
});
|
||||
}
|
||||
default:
|
||||
throw new Error('Switch statement should be exhaustive');
|
||||
throw new Error('Switch statement should be exhuastive');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
3
fixtures/dom/.gitignore
vendored
3
fixtures/dom/.gitignore
vendored
@@ -9,11 +9,8 @@ coverage
|
||||
# production
|
||||
build
|
||||
public/react.development.js
|
||||
public/react.production.min.js
|
||||
public/react-dom.development.js
|
||||
public/react-dom.production.min.js
|
||||
public/react-dom-server.browser.development.js
|
||||
public/react-dom-server.browser.production.min.js
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
},
|
||||
"scripts": {
|
||||
"start": "react-scripts start",
|
||||
"prestart": "cp ../../build/node_modules/react/umd/react.development.js ../../build/node_modules/react-dom/umd/react-dom.development.js ../../build/node_modules/react/umd/react.production.min.js ../../build/node_modules/react-dom/umd/react-dom.production.min.js ../../build/node_modules/react-dom/umd/react-dom-server.browser.development.js ../../build/node_modules/react-dom/umd/react-dom-server.browser.production.min.js public/",
|
||||
"prestart": "cp ../../build/dist/react.development.js ../../build/dist/react-dom.development.js ../../build/dist/react-dom-server.browser.development.js public/",
|
||||
"build": "react-scripts build && cp build/index.html build/200.html",
|
||||
"test": "react-scripts test --env=jsdom",
|
||||
"eject": "react-scripts eject"
|
||||
|
||||
@@ -7,9 +7,8 @@ class Header extends React.Component {
|
||||
super(props, context);
|
||||
const query = parse(window.location.search);
|
||||
const version = query.version || 'local';
|
||||
const production = query.production || false;
|
||||
const versions = [version];
|
||||
this.state = {version, versions, production};
|
||||
this.state = {version, versions};
|
||||
}
|
||||
componentWillMount() {
|
||||
getVersionTags().then(tags => {
|
||||
@@ -26,14 +25,6 @@ class Header extends React.Component {
|
||||
}
|
||||
window.location.search = stringify(query);
|
||||
}
|
||||
handleProductionChange(event) {
|
||||
const query = parse(window.location.search);
|
||||
query.production = event.target.checked;
|
||||
if (!query.production) {
|
||||
delete query.production;
|
||||
}
|
||||
window.location.search = stringify(query);
|
||||
}
|
||||
handleFixtureChange(event) {
|
||||
window.location.pathname = event.target.value;
|
||||
}
|
||||
@@ -52,16 +43,6 @@ class Header extends React.Component {
|
||||
</span>
|
||||
|
||||
<div className="header-controls">
|
||||
<input
|
||||
id="react_production"
|
||||
className="header__checkbox"
|
||||
type="checkbox"
|
||||
checked={this.state.production}
|
||||
onChange={this.handleProductionChange}
|
||||
/>
|
||||
<label htmlFor="react_production" className="header__label">
|
||||
Production
|
||||
</label>
|
||||
<label htmlFor="example">
|
||||
<span className="sr-only">Select an example</span>
|
||||
<select
|
||||
|
||||
@@ -5,7 +5,7 @@ import TestCase from '../../TestCase';
|
||||
const React = window.React;
|
||||
const ReactDOM = window.ReactDOM;
|
||||
|
||||
const Suspense = React.Suspense;
|
||||
const Suspense = React.unstable_Suspense;
|
||||
|
||||
let cache = new Set();
|
||||
|
||||
|
||||
36
fixtures/dom/src/react-loader.js
vendored
36
fixtures/dom/src/react-loader.js
vendored
@@ -37,15 +37,12 @@ function loadScript(src) {
|
||||
}
|
||||
|
||||
export function reactPaths() {
|
||||
let reactPath = 'react.development.js';
|
||||
let reactDOMPath = 'react-dom.development.js';
|
||||
let reactDOMServerPath = 'react-dom-server.browser.development.js';
|
||||
|
||||
let query = parseQuery(window.location.search);
|
||||
let version = query.version || 'local';
|
||||
let isProduction = query.production === 'true';
|
||||
|
||||
let environment = isProduction ? 'production.min' : 'development';
|
||||
|
||||
let reactPath = 'react.' + environment + '.js';
|
||||
let reactDOMPath = 'react-dom.' + environment + '.js';
|
||||
let reactDOMServerPath = 'react-dom-server.browser.' + environment + '.js';
|
||||
|
||||
if (version !== 'local') {
|
||||
const {major, minor, prerelease} = semver(version);
|
||||
@@ -54,34 +51,21 @@ export function reactPaths() {
|
||||
// Load the old module location for anything less than 16 RC
|
||||
if (major >= 16 && !(minor === 0 && preReleaseStage === 'alpha')) {
|
||||
reactPath =
|
||||
'https://unpkg.com/react@' +
|
||||
version +
|
||||
'/umd/react.' +
|
||||
environment +
|
||||
'.js';
|
||||
'https://unpkg.com/react@' + version + '/umd/react.development.js';
|
||||
reactDOMPath =
|
||||
'https://unpkg.com/react-dom@' +
|
||||
version +
|
||||
'/umd/react-dom.' +
|
||||
environment +
|
||||
'.js';
|
||||
'/umd/react-dom.development.js';
|
||||
reactDOMServerPath =
|
||||
'https://unpkg.com/react-dom@' +
|
||||
version +
|
||||
'/umd/react-dom-server.browser.' +
|
||||
environment +
|
||||
'.js';
|
||||
'/umd/react-dom-server.browser.development';
|
||||
} else {
|
||||
let suffix = isProduction ? '.min.js' : '.js';
|
||||
|
||||
reactPath = 'https://unpkg.com/react@' + version + '/dist/react' + suffix;
|
||||
reactPath = 'https://unpkg.com/react@' + version + '/dist/react.js';
|
||||
reactDOMPath =
|
||||
'https://unpkg.com/react-dom@' + version + '/dist/react-dom' + suffix;
|
||||
'https://unpkg.com/react-dom@' + version + '/dist/react-dom.js';
|
||||
reactDOMServerPath =
|
||||
'https://unpkg.com/react-dom@' +
|
||||
version +
|
||||
'/dist/react-dom-server' +
|
||||
suffix;
|
||||
'https://unpkg.com/react-dom@' + version + '/dist/react-dom-server.js';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@ h3 {
|
||||
margin: 8px 0 16px;
|
||||
}
|
||||
|
||||
h4, h5, h6 {
|
||||
h4, h4, h5, h6 {
|
||||
font-size: 16px;
|
||||
margin: 0 0 16px;
|
||||
}
|
||||
@@ -126,15 +126,6 @@ textarea {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.header__checkbox {
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.header__label {
|
||||
font-size: 12px;
|
||||
color: #ccc;
|
||||
}
|
||||
|
||||
.sr-only {
|
||||
clip: rect(0, 0, 0, 0);
|
||||
height: 0;
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
},
|
||||
"scripts": {
|
||||
"prestart":
|
||||
"cp ../../build/node_modules/react/umd/react.development.js public/ && cp ../../build/node_modules/react-dom/umd/react-dom.development.js public/",
|
||||
"cp ../../build/dist/react.development.js public/ && cp ../../build/dist/react-dom.development.js public/",
|
||||
"start": "react-scripts start",
|
||||
"build": "react-scripts build",
|
||||
"test": "react-scripts test --env=jsdom",
|
||||
|
||||
@@ -90,17 +90,17 @@ export default function describeFibers(rootFiber, workInProgress) {
|
||||
const workInProgressID = acknowledgeFiber(workInProgress);
|
||||
|
||||
let currentIDs = new Set();
|
||||
function markAsCurrent(id) {
|
||||
function markAsCurent(id) {
|
||||
currentIDs.add(id);
|
||||
const fiber = descriptions[id];
|
||||
if (fiber.sibling) {
|
||||
markAsCurrent(fiber.sibling);
|
||||
markAsCurent(fiber.sibling);
|
||||
}
|
||||
if (fiber.child) {
|
||||
markAsCurrent(fiber.child);
|
||||
markAsCurent(fiber.child);
|
||||
}
|
||||
}
|
||||
markAsCurrent(rootID);
|
||||
markAsCurent(rootID);
|
||||
|
||||
return {
|
||||
descriptions,
|
||||
|
||||
@@ -16,8 +16,8 @@
|
||||
If you checked out the source from GitHub make sure to run <code>npm run build</code>.
|
||||
</p>
|
||||
</div>
|
||||
<script src="../../build/node_modules/react/umd/react.development.js"></script>
|
||||
<script src="../../build/node_modules/react-dom/umd/react-dom.development.js"></script>
|
||||
<script src="../../build/dist/react.development.js"></script>
|
||||
<script src="../../build/dist/react-dom.development.js"></script>
|
||||
<script src="https://unpkg.com/babel-standalone@6/babel.js"></script>
|
||||
<script type="text/babel">
|
||||
var dotStyle = {
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html style="width: 100%; height: 100%; overflow: hidden">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Fizz Example</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Fizz Example</h1>
|
||||
<div id="container">
|
||||
<p>
|
||||
To install React, follow the instructions on
|
||||
<a href="https://github.com/facebook/react/">GitHub</a>.
|
||||
</p>
|
||||
<p>
|
||||
If you can see this, React is <strong>not</strong> working right.
|
||||
If you checked out the source from GitHub make sure to run <code>npm run build</code>.
|
||||
</p>
|
||||
</div>
|
||||
<script src="../../build/dist/react.development.js"></script>
|
||||
<script src="../../build/dist/react-dom-unstable-fizz.browser.development.js"></script>
|
||||
<script src="https://unpkg.com/babel-standalone@6/babel.js"></script>
|
||||
<script type="text/babel">
|
||||
let stream = ReactDOMFizzServer.renderToReadableStream(<body>Success</body>);
|
||||
let response = new Response(stream, {
|
||||
headers: {'Content-Type': 'text/html'},
|
||||
});
|
||||
display(response);
|
||||
|
||||
async function display(responseToDisplay) {
|
||||
let blob = await responseToDisplay.blob();
|
||||
let url = URL.createObjectURL(blob);
|
||||
let iframe = document.createElement('iframe');
|
||||
iframe.src = url;
|
||||
let container = document.getElementById('container');
|
||||
container.innerHTML = '';
|
||||
container.appendChild(iframe);
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -15,18 +15,28 @@ First, build React and the fixtures:
|
||||
```
|
||||
cd react
|
||||
npm run build
|
||||
node fixtures/packaging/build-all.js
|
||||
|
||||
cd fixtures/packaging
|
||||
node build-all.js
|
||||
```
|
||||
|
||||
Then run a local server, e.g.
|
||||
Then run a local server at the root of the repo, e.g.
|
||||
|
||||
```
|
||||
npx pushstate-server .
|
||||
npm i -g pushstate-server
|
||||
cd ../..
|
||||
pushstate-server .
|
||||
```
|
||||
|
||||
and open the following URL in your browser: [http://localhost:9000/fixtures/packaging/index.html](http://localhost:9000/fixtures/packaging/index.html)
|
||||
(Too complicated? Send a PR to simplify this :-)).
|
||||
|
||||
Then open the following URL in your browser:
|
||||
|
||||
```
|
||||
open http://localhost:9000/fixtures/packaging/index.html
|
||||
```
|
||||
|
||||
You should see two things:
|
||||
|
||||
* A number of iframes (corresponding to various builds), with "Hello World" rendered in each iframe.
|
||||
* "Hello World" is rendered in each iframe.
|
||||
* No errors in the console.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<html>
|
||||
<body>
|
||||
<script src="../../../build/node_modules/react/umd/react.development.js"></script>
|
||||
<script src="../../../build/node_modules/react-dom/umd/react-dom.development.js"></script>
|
||||
<script src="../../../build/dist/react.development.js"></script>
|
||||
<script src="../../../build/dist/react-dom.development.js"></script>
|
||||
<script src="https://unpkg.com/babel-standalone@6/babel.js"></script>
|
||||
<div id="container"></div>
|
||||
<script type="text/babel">
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<html>
|
||||
<body>
|
||||
<script src="../../../build/node_modules/react/umd/react.development.js"></script>
|
||||
<script src="../../../build/node_modules/react-dom/umd/react-dom.development.js"></script>
|
||||
<script src="../../../build/dist/react.development.js"></script>
|
||||
<script src="../../../build/dist/react-dom.development.js"></script>
|
||||
<div id="container"></div>
|
||||
<script>
|
||||
ReactDOM.render(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<html>
|
||||
<body>
|
||||
<script src="../../../build/node_modules/react/umd/react.production.min.js"></script>
|
||||
<script src="../../../build/node_modules/react-dom/umd/react-dom.production.min.js"></script>
|
||||
<script src="../../../build/dist/react.production.min.js"></script>
|
||||
<script src="../../../build/dist/react-dom.production.min.js"></script>
|
||||
<div id="container"></div>
|
||||
<script>
|
||||
ReactDOM.render(
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
<script>
|
||||
requirejs.config({
|
||||
paths: {
|
||||
react: '../../../build/node_modules/react/umd/react.development',
|
||||
'react-dom': '../../../build/node_modules/react-dom/umd/react-dom.development'
|
||||
react: '../../../build/dist/react.development',
|
||||
'react-dom': '../../../build/dist/react-dom.development'
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
<script>
|
||||
requirejs.config({
|
||||
paths: {
|
||||
react: '../../../build/node_modules/react/umd/react.production.min',
|
||||
'react-dom': '../../../build/node_modules/react-dom/umd/react-dom.production.min'
|
||||
react: '../../../build/dist/react.production.min',
|
||||
'react-dom': '../../../build/dist/react-dom.production.min'
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -4,9 +4,8 @@ module.exports = {
|
||||
out: 'output.js',
|
||||
optimize: 'none',
|
||||
paths: {
|
||||
react: '../../../../build/node_modules/react/umd/react.development',
|
||||
'react-dom':
|
||||
'../../../../build/node_modules/react-dom/umd/react-dom.development',
|
||||
react: '../../../../build/dist/react.development',
|
||||
'react-dom': '../../../../build/dist/react-dom.development',
|
||||
schedule: '../../../../build/dist/schedule.development',
|
||||
},
|
||||
};
|
||||
|
||||
@@ -4,9 +4,8 @@ module.exports = {
|
||||
out: 'output.js',
|
||||
optimize: 'none',
|
||||
paths: {
|
||||
react: '../../../../build/node_modules/react/umd/react.production.min',
|
||||
'react-dom':
|
||||
'../../../../build/node_modules/react-dom/umd/react-dom.production.min',
|
||||
react: '../../../../build/dist/react.production.min',
|
||||
'react-dom': '../../../../build/dist/react-dom.production.min',
|
||||
schedule: '../../../../build/dist/schedule.development',
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
System.config({
|
||||
paths: {
|
||||
react: '../../../../build/node_modules/react/umd/react.development.js',
|
||||
'react-dom':
|
||||
'../../../../build/node_modules/react-dom/umd/react-dom.development.js',
|
||||
react: '../../../../build/dist/react.development.js',
|
||||
'react-dom': '../../../../build/dist/react-dom.development.js',
|
||||
schedule: '../../../../build/dist/schedule.development',
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
System.config({
|
||||
paths: {
|
||||
react: '../../../../build/node_modules/react/umd/react.production.min.js',
|
||||
'react-dom':
|
||||
'../../../../build/node_modules/react-dom/umd/react-dom.production.min.js',
|
||||
react: '../../../../build/dist/react.production.min.js',
|
||||
'react-dom': '../../../../build/dist/react-dom.production.min.js',
|
||||
schedule: '../../../../build/dist/schedule.development',
|
||||
},
|
||||
});
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
<script>
|
||||
System.config({
|
||||
paths: {
|
||||
react: '../../../build/node_modules/react/umd/react.development.js',
|
||||
'react-dom': '../../../build/node_modules/react-dom/umd/react-dom.development.js'
|
||||
react: '../../../build/dist/react.development.js',
|
||||
'react-dom': '../../../build/dist/react-dom.development.js'
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
<script>
|
||||
System.config({
|
||||
paths: {
|
||||
react: '../../../build/node_modules/react/umd/react.production.min.js',
|
||||
'react-dom': '../../../build/node_modules/react-dom/umd/react-dom.production.min.js'
|
||||
react: '../../../build/dist/react.production.min.js',
|
||||
'react-dom': '../../../build/dist/react-dom.production.min.js'
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -48,7 +48,7 @@
|
||||
<div id="test-2"></div>
|
||||
</li>
|
||||
<li>
|
||||
<p>Schedules callbacks in correct order when they use scheduleCallback to schedule themselves</p>
|
||||
<p>Schedules callbacks in correct order when they use scheduleWork to schedule themselves</p>
|
||||
<button onClick="runTestThree()">Run Test 3</button>
|
||||
<div><b>Expected:</b></div>
|
||||
<div id="test-3-expected">
|
||||
@@ -90,33 +90,15 @@
|
||||
</div>
|
||||
<div> If the counter advanced while you were away from this tab, it's correct.</div>
|
||||
</li>
|
||||
<li>
|
||||
<p>Can pause execution, dump scheduled callbacks, and continue where it left off</p>
|
||||
<button onClick="runTestEight()">Run Test 8</button>
|
||||
<div><b>Click the button above, press "continue" to finish the test after it pauses:</b></div>
|
||||
<button onClick="continueTestEight()">continue</button>
|
||||
<div><b>Expected:</b></div>
|
||||
<div id="test-8-expected">
|
||||
</div>
|
||||
<div> -------------------------------------------------</div>
|
||||
<div> If the test didn't progress until you hit "continue" and </div>
|
||||
<div> you see the same above and below afterwards it's correct.
|
||||
<div> -------------------------------------------------</div>
|
||||
<div><b>Actual:</b></div>
|
||||
<div id="test-8"></div>
|
||||
</li>
|
||||
</ol>
|
||||
<script src="../../build/node_modules/react/umd/react.development.js"></script>
|
||||
<script src="../../build/dist/react.development.js"></script>
|
||||
<script src="../../build/node_modules/scheduler/umd/scheduler.development.js"></script>
|
||||
<script src="https://unpkg.com/babel-standalone@6/babel.js"></script>
|
||||
<script type="text/babel">
|
||||
const {
|
||||
unstable_scheduleCallback: scheduleCallback,
|
||||
unstable_cancelCallback: cancelCallback,
|
||||
unstable_now: now,
|
||||
unstable_getFirstCallbackNode: getFirstCallbackNode,
|
||||
unstable_pauseExecution: pauseExecution,
|
||||
unstable_continueExecution: continueExecution,
|
||||
unstable_now: now
|
||||
} = Scheduler;
|
||||
function displayTestResult(testNumber) {
|
||||
const expectationNode = document.getElementById('test-' + testNumber + '-expected');
|
||||
@@ -233,16 +215,6 @@ const expectedResults = [
|
||||
[
|
||||
// ... TODO
|
||||
],
|
||||
[],
|
||||
[],
|
||||
// Test 8
|
||||
[
|
||||
'Queue size: 0.',
|
||||
'Pausing... press continue to resume.',
|
||||
'Queue size: 2.',
|
||||
'Finishing...',
|
||||
'Done!',
|
||||
],
|
||||
];
|
||||
function runTestOne() {
|
||||
// Test 1
|
||||
@@ -253,7 +225,7 @@ function runTestOne() {
|
||||
const cb1 = (x) => {
|
||||
updateTestResult(1, 'cb1 called with argument of ' + JSON.stringify(x));
|
||||
}
|
||||
scheduleCallback(cb1);
|
||||
scheduleWork(cb1);
|
||||
updateTestResult(1, 'scheduled Cb1');
|
||||
logWhenFramesStart(1, () => {
|
||||
displayTestResult(1);
|
||||
@@ -271,9 +243,9 @@ function runTestTwo() {
|
||||
const cbB = (x) => {
|
||||
updateTestResult(2, 'cbB called with argument of ' + JSON.stringify(x));
|
||||
}
|
||||
scheduleCallback(cbA);
|
||||
scheduleWork(cbA);
|
||||
updateTestResult(2, 'scheduled CbA');
|
||||
scheduleCallback(cbB);
|
||||
scheduleWork(cbB);
|
||||
updateTestResult(2, 'scheduled CbB');
|
||||
logWhenFramesStart(2, () => {
|
||||
displayTestResult(2);
|
||||
@@ -283,12 +255,12 @@ function runTestTwo() {
|
||||
|
||||
function runTestThree() {
|
||||
// Test 3
|
||||
// Schedules callbacks in correct order when they use scheduleCallback to schedule themselves
|
||||
// Schedules callbacks in correct order when they use scheduleWork to schedule themselves
|
||||
clearTestResult(3);
|
||||
let callbackAIterations = 0;
|
||||
const cbA = (x) => {
|
||||
if (callbackAIterations < 1) {
|
||||
scheduleCallback(cbA);
|
||||
scheduleWork(cbA);
|
||||
updateTestResult(3, 'scheduled CbA again');
|
||||
}
|
||||
updateTestResult(3, 'cbA' + callbackAIterations + ' called with argument of ' + JSON.stringify(x));
|
||||
@@ -297,9 +269,9 @@ function runTestThree() {
|
||||
const cbB = (x) => {
|
||||
updateTestResult(3, 'cbB called with argument of ' + JSON.stringify(x));
|
||||
}
|
||||
scheduleCallback(cbA);
|
||||
scheduleWork(cbA);
|
||||
updateTestResult(3, 'scheduled CbA');
|
||||
scheduleCallback(cbB);
|
||||
scheduleWork(cbB);
|
||||
updateTestResult(3, 'scheduled CbB');
|
||||
logWhenFramesStart(3, () => {
|
||||
displayTestResult(3);
|
||||
@@ -333,13 +305,13 @@ function runTestFour() {
|
||||
const cbD = (x) => {
|
||||
updateTestResult(4, 'cbD called with argument of ' + JSON.stringify(x));
|
||||
}
|
||||
scheduleCallback(cbA); // won't time out
|
||||
scheduleWork(cbA); // won't time out
|
||||
updateTestResult(4, 'scheduled cbA');
|
||||
scheduleCallback(cbB, {timeout: 100}); // times out later
|
||||
scheduleWork(cbB, {timeout: 100}); // times out later
|
||||
updateTestResult(4, 'scheduled cbB');
|
||||
scheduleCallback(cbC, {timeout: 1}); // will time out fast
|
||||
scheduleWork(cbC, {timeout: 1}); // will time out fast
|
||||
updateTestResult(4, 'scheduled cbC');
|
||||
scheduleCallback(cbD); // won't time out
|
||||
scheduleWork(cbD); // won't time out
|
||||
updateTestResult(4, 'scheduled cbD');
|
||||
|
||||
// should have run in order of C, A, B, D
|
||||
@@ -418,15 +390,15 @@ function runTestFive() {
|
||||
});
|
||||
});
|
||||
});
|
||||
scheduleCallback(cbA);
|
||||
scheduleWork(cbA);
|
||||
console.log('scheduled cbA');
|
||||
scheduleCallback(cbB); // will throw error
|
||||
scheduleWork(cbB); // will throw error
|
||||
console.log('scheduled cbB');
|
||||
scheduleCallback(cbC);
|
||||
scheduleWork(cbC);
|
||||
console.log('scheduled cbC');
|
||||
scheduleCallback(cbD); // will throw error
|
||||
scheduleWork(cbD); // will throw error
|
||||
console.log('scheduled cbD');
|
||||
scheduleCallback(cbE);
|
||||
scheduleWork(cbE);
|
||||
console.log('scheduled cbE');
|
||||
};
|
||||
}
|
||||
@@ -496,15 +468,15 @@ function runTestSix() {
|
||||
});
|
||||
});
|
||||
});
|
||||
scheduleCallback(cbA);
|
||||
scheduleWork(cbA);
|
||||
console.log('scheduled cbA');
|
||||
scheduleCallback(cbB); // will throw error
|
||||
scheduleWork(cbB); // will throw error
|
||||
console.log('scheduled cbB');
|
||||
scheduleCallback(cbC, {timeout: 1});
|
||||
scheduleWork(cbC, {timeout: 1});
|
||||
console.log('scheduled cbC');
|
||||
scheduleCallback(cbD, {timeout: 1}); // will throw error
|
||||
scheduleWork(cbD, {timeout: 1}); // will throw error
|
||||
console.log('scheduled cbD');
|
||||
scheduleCallback(cbE, {timeout: 1});
|
||||
scheduleWork(cbE, {timeout: 1});
|
||||
console.log('scheduled cbE');
|
||||
};
|
||||
}
|
||||
@@ -520,55 +492,10 @@ function runTestSeven() {
|
||||
counter++;
|
||||
counterNode.innerHTML = counter;
|
||||
waitForTimeToPass(100);
|
||||
scheduleCallback(incrementCounterAndScheduleNextCallback);
|
||||
scheduleWork(incrementCounterAndScheduleNextCallback);
|
||||
}
|
||||
scheduleCallback(incrementCounterAndScheduleNextCallback);
|
||||
scheduleWork(incrementCounterAndScheduleNextCallback);
|
||||
}
|
||||
|
||||
function runTestEight() {
|
||||
// Test 8
|
||||
// Pauses execution, dumps the queue, and continues execution
|
||||
clearTestResult(8);
|
||||
|
||||
function countNodesInStack(firstCallbackNode) {
|
||||
var node = firstCallbackNode;
|
||||
var count = 0;
|
||||
if (node !== null) {
|
||||
do {
|
||||
count = count + 1;
|
||||
node = node.next;
|
||||
} while (node !== firstCallbackNode);
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
scheduleCallback(() => {
|
||||
|
||||
// size should be 0
|
||||
updateTestResult(8, `Queue size: ${countNodesInStack(getFirstCallbackNode())}.`);
|
||||
updateTestResult(8, 'Pausing... press continue to resume.');
|
||||
pauseExecution();
|
||||
|
||||
scheduleCallback(function () {
|
||||
updateTestResult(8, 'Finishing...');
|
||||
displayTestResult(8);
|
||||
})
|
||||
scheduleCallback(function () {
|
||||
updateTestResult(8, 'Done!');
|
||||
displayTestResult(8);
|
||||
checkTestResult(8);
|
||||
})
|
||||
|
||||
// new size should be 2 now
|
||||
updateTestResult(8, `Queue size: ${countNodesInStack(getFirstCallbackNode())}.`);
|
||||
displayTestResult(8);
|
||||
});
|
||||
}
|
||||
|
||||
function continueTestEight() {
|
||||
continueExecution();
|
||||
}
|
||||
|
||||
</script type="text/babel">
|
||||
</body>
|
||||
</html>
|
||||
@@ -46,7 +46,7 @@
|
||||
</p>
|
||||
<h3>
|
||||
Tests
|
||||
<button id="run-test-button" onClick="runAllTests()">Run all tests</button>
|
||||
<button onClick="runAllTests()">Run all tests</button>
|
||||
</h3>
|
||||
<ol>
|
||||
<li id="checkSchedulerAPI" data-value="...">
|
||||
@@ -62,17 +62,6 @@
|
||||
<strong>Test end-to-end integration</strong>
|
||||
</li>
|
||||
</ol>
|
||||
|
||||
<script>
|
||||
if (window.location.search.includes('puppeteer=true')) {
|
||||
// Colocated calls to performance.now() often yield different values in Puppeteer.
|
||||
// This causes the Scheduler API test to fail.
|
||||
// For the purposes of our automated release scripts,
|
||||
// Coerce tests to use Date.now() instead to reduce the chances of a false positive.
|
||||
window.performance = {now: Date.now};
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- Load the tracing API before react to test that it's lazily evaluated -->
|
||||
<script src="../../build/node_modules/scheduler/umd/scheduler.development.js"></script>
|
||||
<script src="../../build/node_modules/scheduler/umd/scheduler-tracing.development.js"></script>
|
||||
|
||||
@@ -20,7 +20,7 @@ Follow these steps:
|
||||
# 1: Build react from source
|
||||
cd /path/to/react
|
||||
yarn
|
||||
yarn build react-dom/index,react/index,react-cache,scheduler --type=NODE
|
||||
yarn build dom-client,core,react-cache,scheduler --type=NODE
|
||||
|
||||
# 2: Install fixture dependencies
|
||||
cd fixtures/unstable-async/suspense/
|
||||
|
||||
7
fixtures/unstable-async/suspense/src/cache.js
Normal file
7
fixtures/unstable-async/suspense/src/cache.js
Normal file
@@ -0,0 +1,7 @@
|
||||
import {createCache} from 'react-cache';
|
||||
|
||||
export let cache;
|
||||
function initCache() {
|
||||
cache = createCache(initCache);
|
||||
}
|
||||
initCache();
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, {lazy, Suspense, PureComponent} from 'react';
|
||||
import React, {lazy, unstable_Suspense as Suspense, PureComponent} from 'react';
|
||||
import {unstable_scheduleCallback} from 'scheduler';
|
||||
import {
|
||||
unstable_trace as trace,
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import React, {Fragment} from 'react';
|
||||
import {unstable_createResource} from 'react-cache';
|
||||
import {createResource} from 'react-cache';
|
||||
import {cache} from '../cache';
|
||||
import Spinner from './Spinner';
|
||||
import {fetchCoreContributorListJSON} from '../api';
|
||||
|
||||
const ContributorListResource = unstable_createResource(
|
||||
fetchCoreContributorListJSON
|
||||
);
|
||||
const ContributorListResource = createResource(fetchCoreContributorListJSON);
|
||||
|
||||
const ContributorListPage = ({loadingId, onUserClick}) => (
|
||||
<Fragment>
|
||||
@@ -18,7 +17,7 @@ const ContributorListPage = ({loadingId, onUserClick}) => (
|
||||
padding: 0,
|
||||
margin: 0,
|
||||
}}>
|
||||
{ContributorListResource.read().map(user => (
|
||||
{ContributorListResource.read(cache).map(user => (
|
||||
<ContributorListItem
|
||||
key={user.id}
|
||||
onClick={() => onUserClick(user.id)}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import React, {Suspense} from 'react';
|
||||
import {unstable_createResource} from 'react-cache';
|
||||
import React, {unstable_Suspense as Suspense} from 'react';
|
||||
import {createResource} from 'react-cache';
|
||||
import Spinner from './Spinner';
|
||||
import {cache} from '../cache';
|
||||
import {fetchUserProfileJSON, fetchUserRepositoriesListJSON} from '../api';
|
||||
|
||||
export default function UserPage({id}) {
|
||||
@@ -20,10 +21,10 @@ export default function UserPage({id}) {
|
||||
);
|
||||
}
|
||||
|
||||
const UserDetailsResource = unstable_createResource(fetchUserProfileJSON);
|
||||
const UserDetailsResource = createResource(fetchUserProfileJSON);
|
||||
|
||||
function UserDetails({id}) {
|
||||
const user = UserDetailsResource.read(id);
|
||||
const user = UserDetailsResource.read(cache, id);
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
@@ -102,7 +103,7 @@ const Email = ({email}) => (
|
||||
</div>
|
||||
);
|
||||
|
||||
const ImageResource = unstable_createResource(
|
||||
const ImageResource = createResource(
|
||||
src =>
|
||||
new Promise(resolve => {
|
||||
const img = new Image();
|
||||
@@ -112,7 +113,7 @@ const ImageResource = unstable_createResource(
|
||||
);
|
||||
|
||||
function Img({src, alt, ...rest}) {
|
||||
return <img src={ImageResource.read(src)} alt={alt} {...rest} />;
|
||||
return <img src={ImageResource.read(cache, src)} alt={alt} {...rest} />;
|
||||
}
|
||||
|
||||
function UserPicture({source}) {
|
||||
@@ -131,12 +132,10 @@ function UserPicture({source}) {
|
||||
);
|
||||
}
|
||||
|
||||
const UserRepositoriesResource = unstable_createResource(
|
||||
fetchUserRepositoriesListJSON
|
||||
);
|
||||
const UserRepositoriesResource = createResource(fetchUserRepositoriesListJSON);
|
||||
|
||||
function Repositories({id}) {
|
||||
const repos = UserRepositoriesResource.read(id);
|
||||
const repos = UserRepositoriesResource.read(cache, id);
|
||||
return (
|
||||
<ul
|
||||
style={{
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import React, {Fragment, PureComponent} from 'react';
|
||||
import {unstable_createRoot, render} from 'react-dom';
|
||||
import {unstable_trace as trace} from 'scheduler/tracing';
|
||||
import {cache} from './cache';
|
||||
import {
|
||||
setFakeRequestTime,
|
||||
setPaused,
|
||||
@@ -64,9 +65,8 @@ class Debugger extends PureComponent {
|
||||
}
|
||||
|
||||
handleReset = () => {
|
||||
trace('Clear cache', performance.now(), () => {
|
||||
// TODO: this is not implemented.
|
||||
// cache.invalidate();
|
||||
trace('Clear cache', () => {
|
||||
cache.invalidate();
|
||||
this.setState(state => ({
|
||||
requests: {},
|
||||
}));
|
||||
|
||||
@@ -18,7 +18,7 @@ There are also known bugs and inefficiencies in master so **don't use this fixtu
|
||||
# 1: Build react from source
|
||||
cd /path/to/react
|
||||
yarn
|
||||
yarn build react-dom/index,react/index,react-cache,scheduler --type=NODE
|
||||
yarn build dom-client,core,react-cache,scheduler --type=NODE
|
||||
|
||||
# 2: Install fixture dependencies
|
||||
cd fixtures/unstable-async/time-slicing/
|
||||
|
||||
@@ -124,7 +124,7 @@ class App extends PureComponent {
|
||||
<div className="rendering">
|
||||
{this.renderOption('sync', 'Synchronous')}
|
||||
{this.renderOption('debounced', 'Debounced')}
|
||||
{this.renderOption('async', 'Concurrent')}
|
||||
{this.renderOption('async', 'Asynchronous')}
|
||||
</div>
|
||||
<input
|
||||
className={'input ' + this.state.strategy}
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
<html>
|
||||
<body>
|
||||
<script src="../../build/node_modules/react/umd/react.development.js"></script>
|
||||
<script src="../../build/node_modules/react-dom/umd/react-dom-unstable-fire.development.js"></script>
|
||||
<script src="https://unpkg.com/babel-standalone@6/babel.js"></script>
|
||||
<div id="container"></div>
|
||||
<script type="text/babel">
|
||||
ReactFire.render(
|
||||
<h1>Hello World!</h1>,
|
||||
document.getElementById('container')
|
||||
);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"private": true,
|
||||
"version": "16.6.1",
|
||||
"version": "16.6.0-alpha.8af6728",
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
],
|
||||
@@ -44,7 +44,6 @@
|
||||
"create-react-class": "^15.6.3",
|
||||
"cross-env": "^5.1.1",
|
||||
"danger": "^3.0.4",
|
||||
"error-stack-parser": "^2.0.2",
|
||||
"eslint": "^4.1.0",
|
||||
"eslint-config-fbjs": "^1.1.1",
|
||||
"eslint-plugin-babel": "^3.3.0",
|
||||
@@ -84,8 +83,7 @@
|
||||
"targz": "^1.0.1",
|
||||
"through2": "^2.0.0",
|
||||
"tmp": "~0.0.28",
|
||||
"typescript": "~1.8.10",
|
||||
"@mattiasbuelens/web-streams-polyfill": "0.1.0"
|
||||
"typescript": "~1.8.10"
|
||||
},
|
||||
"devEngines": {
|
||||
"node": "8.x || 9.x || 10.x"
|
||||
@@ -94,7 +92,7 @@
|
||||
"testRegex": "/scripts/jest/dont-run-jest-directly\\.js$"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "node ./scripts/rollup/build.js",
|
||||
"build": "npm run version-check && node ./scripts/rollup/build.js",
|
||||
"linc": "node ./scripts/tasks/linc.js",
|
||||
"lint": "node ./scripts/tasks/eslint.js",
|
||||
"lint-build": "node ./scripts/rollup/validate/index.js",
|
||||
|
||||
@@ -81,7 +81,7 @@ import React from "react";
|
||||
import { createSubscription } from "create-subscription";
|
||||
|
||||
// Start with a simple component.
|
||||
// In this case, it's a function component, but it could have been a class.
|
||||
// In this case, it's a functional component, but it could have been a class.
|
||||
function FollowerComponent({ followersCount }) {
|
||||
return <div>You have {followersCount} followers!</div>;
|
||||
}
|
||||
@@ -164,7 +164,7 @@ function LoadingComponent({ loadingStatus }) {
|
||||
}
|
||||
}
|
||||
|
||||
// Wrap the function component with a subscriber HOC.
|
||||
// Wrap the functional component with a subscriber HOC.
|
||||
// This HOC will manage subscriptions and pass values to the decorated component.
|
||||
// It will add and remove subscriptions in an async-safe way when props change.
|
||||
const PromiseSubscription = createSubscription({
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
{
|
||||
"name": "create-subscription",
|
||||
"description": "utility for subscribing to external data sources inside React components",
|
||||
"version": "16.6.1",
|
||||
"version": "16.6.0-alpha.8af6728",
|
||||
"repository": "facebook/react",
|
||||
"files": [
|
||||
"LICENSE",
|
||||
"README.md",
|
||||
"build-info.json",
|
||||
"index.js",
|
||||
"cjs/"
|
||||
],
|
||||
"peerDependencies": {
|
||||
"react": "^16.3.0"
|
||||
"react": "^16.3.0 || 16.6.0-alpha.8af6728"
|
||||
},
|
||||
"devDependencies": {
|
||||
"rxjs": "^5.5.6"
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
# `eslint-plugin-react-hooks`
|
||||
|
||||
This ESLint plugin enforces the [Rules of Hooks](https://reactjs.org/docs/hooks-rules.html).
|
||||
|
||||
It is a part of the [Hooks proposal](https://reactjs.org/docs/hooks-intro.html) for React.
|
||||
|
||||
## Experimental Status
|
||||
|
||||
This is an experimental release and is intended to be used for testing the Hooks proposal with React 16.7 alpha. The exact heuristics it uses may be adjusted.
|
||||
|
||||
The [Rules of Hooks](https://reactjs.org/docs/hooks-rules.html) documentation contains a link to the technical RFC. Please leave a comment on the RFC if you have concerns or ideas about how this plugin should work.
|
||||
|
||||
## Installation
|
||||
|
||||
**Note: If you're using Create React App, please wait for a corresponding experimental release of `react-scripts` that includes this rule instead of adding it directly.**
|
||||
|
||||
Assuming you already have ESLint installed, run:
|
||||
|
||||
```sh
|
||||
# npm
|
||||
npm install eslint-plugin-react-hooks@next --save-dev
|
||||
|
||||
# yarn
|
||||
yarn add eslint-plugin-react-hooks@next --dev
|
||||
```
|
||||
|
||||
Then add it to your ESLint configuration:
|
||||
|
||||
```js
|
||||
{
|
||||
"plugins": [
|
||||
// ...
|
||||
"react-hooks"
|
||||
],
|
||||
"rules": {
|
||||
// ...
|
||||
"react-hooks/rules-of-hooks": "error"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Valid and Invalid Examples
|
||||
|
||||
Please refer to the [Rules of Hooks](https://reactjs.org/docs/hooks-rules.html) documentation and the [Hooks FAQ](https://reactjs.org/docs/hooks-faq.html#what-exactly-do-the-lint-rules-enforce) to learn more about this rule.
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
@@ -1,641 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) Facebook, Inc. and its affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
const ESLintTester = require('eslint').RuleTester;
|
||||
const ReactHooksESLintPlugin = require('eslint-plugin-react-hooks');
|
||||
const ReactHooksESLintRule = ReactHooksESLintPlugin.rules['rules-of-hooks'];
|
||||
|
||||
ESLintTester.setDefaultConfig({
|
||||
parser: 'babel-eslint',
|
||||
parserOptions: {
|
||||
ecmaVersion: 6,
|
||||
sourceType: 'module',
|
||||
},
|
||||
});
|
||||
|
||||
const eslintTester = new ESLintTester();
|
||||
eslintTester.run('react-hooks', ReactHooksESLintRule, {
|
||||
valid: [
|
||||
`
|
||||
// Valid because components can use hooks.
|
||||
function ComponentWithHook() {
|
||||
useHook();
|
||||
}
|
||||
`,
|
||||
`
|
||||
// Valid because components can use hooks.
|
||||
function createComponentWithHook() {
|
||||
return function ComponentWithHook() {
|
||||
useHook();
|
||||
};
|
||||
}
|
||||
`,
|
||||
`
|
||||
// Valid because hooks can use hooks.
|
||||
function useHookWithHook() {
|
||||
useHook();
|
||||
}
|
||||
`,
|
||||
`
|
||||
// Valid because hooks can use hooks.
|
||||
function createHook() {
|
||||
return function useHookWithHook() {
|
||||
useHook();
|
||||
}
|
||||
}
|
||||
`,
|
||||
`
|
||||
// Valid because components can call functions.
|
||||
function ComponentWithNormalFunction() {
|
||||
doSomething();
|
||||
}
|
||||
`,
|
||||
`
|
||||
// Valid because functions can call functions.
|
||||
function normalFunctionWithNormalFunction() {
|
||||
doSomething();
|
||||
}
|
||||
`,
|
||||
`
|
||||
// Valid because functions can call functions.
|
||||
function normalFunctionWithConditionalFunction() {
|
||||
if (cond) {
|
||||
doSomething();
|
||||
}
|
||||
}
|
||||
`,
|
||||
`
|
||||
// Valid because functions can call functions.
|
||||
function functionThatStartsWithUseButIsntAHook() {
|
||||
if (cond) {
|
||||
userFetch();
|
||||
}
|
||||
}
|
||||
`,
|
||||
`
|
||||
// Valid although unconditional return doesn't make sense and would fail other rules.
|
||||
// We could make it invalid but it doesn't matter.
|
||||
function useUnreachable() {
|
||||
return;
|
||||
useHook();
|
||||
}
|
||||
`,
|
||||
`
|
||||
// Valid because hooks can call hooks.
|
||||
function useHook() { useState(); }
|
||||
const whatever = function useHook() { useState(); };
|
||||
const useHook1 = () => { useState(); };
|
||||
let useHook2 = () => useState();
|
||||
useHook2 = () => { useState(); };
|
||||
({useHook: () => { useState(); }});
|
||||
({useHook() { useState(); }});
|
||||
const {useHook = () => { useState(); }} = {};
|
||||
({useHook = () => { useState(); }} = {});
|
||||
`,
|
||||
`
|
||||
// Valid because hooks can call hooks.
|
||||
function useHook() {
|
||||
useHook1();
|
||||
useHook2();
|
||||
}
|
||||
`,
|
||||
`
|
||||
// Valid because hooks can call hooks.
|
||||
function createHook() {
|
||||
return function useHook() {
|
||||
useHook1();
|
||||
useHook2();
|
||||
};
|
||||
}
|
||||
`,
|
||||
`
|
||||
// Valid because hooks can call hooks.
|
||||
function useHook() {
|
||||
useState() && a;
|
||||
}
|
||||
`,
|
||||
`
|
||||
// Valid because hooks can call hooks.
|
||||
function useHook() {
|
||||
return useHook1() + useHook2();
|
||||
}
|
||||
`,
|
||||
`
|
||||
// Valid because hooks can call hooks.
|
||||
function useHook() {
|
||||
return useHook1(useHook2());
|
||||
}
|
||||
`,
|
||||
`
|
||||
// Valid because classes can call functions.
|
||||
// We don't consider these to be hooks.
|
||||
class C {
|
||||
m() {
|
||||
this.useHook();
|
||||
super.useHook();
|
||||
}
|
||||
}
|
||||
`,
|
||||
`
|
||||
// Currently valid.
|
||||
// We *could* make this invalid if we want, but it creates false positives
|
||||
// (see the FooStore case).
|
||||
class C {
|
||||
m() {
|
||||
This.useHook();
|
||||
Super.useHook();
|
||||
}
|
||||
}
|
||||
`,
|
||||
`
|
||||
// Valid although we *could* consider these invalid.
|
||||
// But it doesn't bring much benefit since it's an immediate runtime error anyway.
|
||||
// So might as well allow it.
|
||||
Hook.use();
|
||||
Hook._use();
|
||||
Hook.useState();
|
||||
Hook._useState();
|
||||
Hook.use42();
|
||||
Hook.useHook();
|
||||
Hook.use_hook();
|
||||
`,
|
||||
`
|
||||
// Valid -- this is a regression test.
|
||||
jest.useFakeTimers();
|
||||
beforeEach(() => {
|
||||
jest.useRealTimers();
|
||||
})
|
||||
`,
|
||||
`
|
||||
// Valid because that's a false positive we've seen quite a bit.
|
||||
// This is a regression test.
|
||||
class Foo extends Component {
|
||||
render() {
|
||||
if (cond) {
|
||||
FooStore.useFeatureFlag();
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
`
|
||||
// Currently valid because we found this to be a common pattern
|
||||
// for feature flag checks in existing components.
|
||||
// We *could* make it invalid but that produces quite a few false positives.
|
||||
// Why does it make sense to ignore it? Firstly, because using
|
||||
// hooks in a class would cause a runtime error anyway.
|
||||
// But why don't we care about the same kind of false positive in a functional
|
||||
// component? Because even if it was a false positive, it would be confusing
|
||||
// anyway. So it might make sense to rename a feature flag check in that case.
|
||||
class ClassComponentWithFeatureFlag extends React.Component {
|
||||
render() {
|
||||
if (foo) {
|
||||
useFeatureFlag();
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
`
|
||||
// Currently valid because we don't check for hooks in classes.
|
||||
// See ClassComponentWithFeatureFlag for rationale.
|
||||
// We *could* make it invalid if we don't regress that false positive.
|
||||
class ClassComponentWithHook extends React.Component {
|
||||
render() {
|
||||
React.useState();
|
||||
}
|
||||
}
|
||||
`,
|
||||
`
|
||||
// Currently valid.
|
||||
// These are variations capturing the current heuristic--
|
||||
// we only allow hooks in PascalCase, useFoo functions,
|
||||
// or classes (due to common false positives and because they error anyway).
|
||||
// We *could* make some of these invalid.
|
||||
// They probably don't matter much.
|
||||
(class {useHook = () => { useState(); }});
|
||||
(class {useHook() { useState(); }});
|
||||
(class {h = () => { useState(); }});
|
||||
(class {i() { useState(); }});
|
||||
`,
|
||||
`
|
||||
// Currently valid although we *could* consider these invalid.
|
||||
// It doesn't make a lot of difference because it would crash early.
|
||||
use();
|
||||
_use();
|
||||
useState();
|
||||
_useState();
|
||||
use42();
|
||||
useHook();
|
||||
use_hook();
|
||||
React.useState();
|
||||
`,
|
||||
`
|
||||
// Regression test for the popular "history" library
|
||||
const {createHistory, useBasename} = require('history-2.1.2');
|
||||
const browserHistory = useBasename(createHistory)({
|
||||
basename: '/',
|
||||
});
|
||||
`,
|
||||
`
|
||||
// Regression test for some internal code.
|
||||
// This shows how the "callback rule" is more relaxed,
|
||||
// and doesn't kick in unless we're confident we're in
|
||||
// a component or a hook.
|
||||
function makeListener(instance) {
|
||||
each(pixelsWithInferredEvents, pixel => {
|
||||
if (useExtendedSelector(pixel.id) && extendedButton) {
|
||||
foo();
|
||||
}
|
||||
});
|
||||
}
|
||||
`,
|
||||
`
|
||||
// Regression test for incorrectly flagged valid code.
|
||||
function RegressionTest() {
|
||||
const foo = cond ? a : b;
|
||||
useState();
|
||||
}
|
||||
`,
|
||||
`
|
||||
// Valid because exceptions abort rendering
|
||||
function RegressionTest() {
|
||||
if (page == null) {
|
||||
throw new Error('oh no!');
|
||||
}
|
||||
useState();
|
||||
}
|
||||
`,
|
||||
],
|
||||
invalid: [
|
||||
{
|
||||
code: `
|
||||
// Invalid because it's dangerous and might not warn otherwise.
|
||||
// This *must* be invalid.
|
||||
function ComponentWithConditionalHook() {
|
||||
if (cond) {
|
||||
useConditionalHook();
|
||||
}
|
||||
}
|
||||
`,
|
||||
errors: [conditionalError('useConditionalHook')],
|
||||
},
|
||||
{
|
||||
code: `
|
||||
// Invalid because it's dangerous and might not warn otherwise.
|
||||
// This *must* be invalid.
|
||||
function createComponent() {
|
||||
return function ComponentWithConditionalHook() {
|
||||
if (cond) {
|
||||
useConditionalHook();
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
errors: [conditionalError('useConditionalHook')],
|
||||
},
|
||||
{
|
||||
code: `
|
||||
// Invalid because it's dangerous and might not warn otherwise.
|
||||
// This *must* be invalid.
|
||||
function useHookWithConditionalHook() {
|
||||
if (cond) {
|
||||
useConditionalHook();
|
||||
}
|
||||
}
|
||||
`,
|
||||
errors: [conditionalError('useConditionalHook')],
|
||||
},
|
||||
{
|
||||
code: `
|
||||
// Invalid because it's dangerous and might not warn otherwise.
|
||||
// This *must* be invalid.
|
||||
function createHook() {
|
||||
return function useHookWithConditionalHook() {
|
||||
if (cond) {
|
||||
useConditionalHook();
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
errors: [conditionalError('useConditionalHook')],
|
||||
},
|
||||
{
|
||||
code: `
|
||||
// Invalid because it's dangerous and might not warn otherwise.
|
||||
// This *must* be invalid.
|
||||
function ComponentWithTernaryHook() {
|
||||
cond ? useTernaryHook() : null;
|
||||
}
|
||||
`,
|
||||
errors: [conditionalError('useTernaryHook')],
|
||||
},
|
||||
{
|
||||
code: `
|
||||
// Invalid because it's a common misunderstanding.
|
||||
// We *could* make it valid but the runtime error could be confusing.
|
||||
function ComponentWithHookInsideCallback() {
|
||||
useEffect(() => {
|
||||
useHookInsideCallback();
|
||||
});
|
||||
}
|
||||
`,
|
||||
errors: [genericError('useHookInsideCallback')],
|
||||
},
|
||||
{
|
||||
code: `
|
||||
// Invalid because it's a common misunderstanding.
|
||||
// We *could* make it valid but the runtime error could be confusing.
|
||||
function createComponent() {
|
||||
return function ComponentWithHookInsideCallback() {
|
||||
useEffect(() => {
|
||||
useHookInsideCallback();
|
||||
});
|
||||
}
|
||||
}
|
||||
`,
|
||||
errors: [genericError('useHookInsideCallback')],
|
||||
},
|
||||
{
|
||||
code: `
|
||||
// Invalid because it's a common misunderstanding.
|
||||
// We *could* make it valid but the runtime error could be confusing.
|
||||
function ComponentWithHookInsideCallback() {
|
||||
function handleClick() {
|
||||
useState();
|
||||
}
|
||||
}
|
||||
`,
|
||||
errors: [functionError('useState', 'handleClick')],
|
||||
},
|
||||
{
|
||||
code: `
|
||||
// Invalid because it's a common misunderstanding.
|
||||
// We *could* make it valid but the runtime error could be confusing.
|
||||
function createComponent() {
|
||||
return function ComponentWithHookInsideCallback() {
|
||||
function handleClick() {
|
||||
useState();
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
errors: [functionError('useState', 'handleClick')],
|
||||
},
|
||||
{
|
||||
code: `
|
||||
// Invalid because it's dangerous and might not warn otherwise.
|
||||
// This *must* be invalid.
|
||||
function ComponentWithHookInsideLoop() {
|
||||
while (cond) {
|
||||
useHookInsideLoop();
|
||||
}
|
||||
}
|
||||
`,
|
||||
errors: [loopError('useHookInsideLoop')],
|
||||
},
|
||||
{
|
||||
code: `
|
||||
// Invalid because it's dangerous and might not warn otherwise.
|
||||
// This *must* be invalid.
|
||||
function renderItem() {
|
||||
useState();
|
||||
}
|
||||
|
||||
function List(props) {
|
||||
return props.items.map(renderItem);
|
||||
}
|
||||
`,
|
||||
errors: [functionError('useState', 'renderItem')],
|
||||
},
|
||||
{
|
||||
code: `
|
||||
// Currently invalid because it violates the convention and removes the "taint"
|
||||
// from a hook. We *could* make it valid to avoid some false positives but let's
|
||||
// ensure that we don't break the "renderItem" and "normalFunctionWithConditionalHook"
|
||||
// cases which must remain invalid.
|
||||
function normalFunctionWithHook() {
|
||||
useHookInsideNormalFunction();
|
||||
}
|
||||
`,
|
||||
errors: [
|
||||
functionError('useHookInsideNormalFunction', 'normalFunctionWithHook'),
|
||||
],
|
||||
},
|
||||
{
|
||||
code: `
|
||||
// Invalid because it's dangerous and might not warn otherwise.
|
||||
// This *must* be invalid.
|
||||
function normalFunctionWithConditionalHook() {
|
||||
if (cond) {
|
||||
useHookInsideNormalFunction();
|
||||
}
|
||||
}
|
||||
`,
|
||||
errors: [
|
||||
functionError(
|
||||
'useHookInsideNormalFunction',
|
||||
'normalFunctionWithConditionalHook'
|
||||
),
|
||||
],
|
||||
},
|
||||
{
|
||||
code: `
|
||||
// Invalid because it's dangerous and might not warn otherwise.
|
||||
// This *must* be invalid.
|
||||
function useHookInLoops() {
|
||||
while (a) {
|
||||
useHook1();
|
||||
if (b) return;
|
||||
useHook2();
|
||||
}
|
||||
while (c) {
|
||||
useHook3();
|
||||
if (d) return;
|
||||
useHook4();
|
||||
}
|
||||
}
|
||||
`,
|
||||
errors: [
|
||||
loopError('useHook1'),
|
||||
loopError('useHook2'),
|
||||
loopError('useHook3'),
|
||||
loopError('useHook4'),
|
||||
],
|
||||
},
|
||||
{
|
||||
code: `
|
||||
// Invalid because it's dangerous and might not warn otherwise.
|
||||
// This *must* be invalid.
|
||||
function useHookInLoops() {
|
||||
while (a) {
|
||||
useHook1();
|
||||
if (b) continue;
|
||||
useHook2();
|
||||
}
|
||||
}
|
||||
`,
|
||||
errors: [
|
||||
loopError('useHook1'),
|
||||
|
||||
// NOTE: Small imprecision in error reporting due to caching means we
|
||||
// have a conditional error here instead of a loop error. However,
|
||||
// we will always get an error so this is acceptable.
|
||||
conditionalError('useHook2', true),
|
||||
],
|
||||
},
|
||||
{
|
||||
code: `
|
||||
// Invalid because it's dangerous and might not warn otherwise.
|
||||
// This *must* be invalid.
|
||||
function useLabeledBlock() {
|
||||
label: {
|
||||
if (a) break label;
|
||||
useHook();
|
||||
}
|
||||
}
|
||||
`,
|
||||
errors: [conditionalError('useHook')],
|
||||
},
|
||||
{
|
||||
code: `
|
||||
// Currently invalid.
|
||||
// These are variations capturing the current heuristic--
|
||||
// we only allow hooks in PascalCase or useFoo functions.
|
||||
// We *could* make some of these valid. But before doing it,
|
||||
// consider specific cases documented above that contain reasoning.
|
||||
function a() { useState(); }
|
||||
const whatever = function b() { useState(); };
|
||||
const c = () => { useState(); };
|
||||
let d = () => useState();
|
||||
e = () => { useState(); };
|
||||
({f: () => { useState(); }});
|
||||
({g() { useState(); }});
|
||||
const {j = () => { useState(); }} = {};
|
||||
({k = () => { useState(); }} = {});
|
||||
`,
|
||||
errors: [
|
||||
functionError('useState', 'a'),
|
||||
functionError('useState', 'b'),
|
||||
functionError('useState', 'c'),
|
||||
functionError('useState', 'd'),
|
||||
functionError('useState', 'e'),
|
||||
functionError('useState', 'f'),
|
||||
functionError('useState', 'g'),
|
||||
functionError('useState', 'j'),
|
||||
functionError('useState', 'k'),
|
||||
],
|
||||
},
|
||||
{
|
||||
code: `
|
||||
// Invalid because it's dangerous and might not warn otherwise.
|
||||
// This *must* be invalid.
|
||||
function useHook() {
|
||||
if (a) return;
|
||||
useState();
|
||||
}
|
||||
`,
|
||||
errors: [conditionalError('useState', true)],
|
||||
},
|
||||
{
|
||||
code: `
|
||||
// Invalid because it's dangerous and might not warn otherwise.
|
||||
// This *must* be invalid.
|
||||
function useHook() {
|
||||
if (a) return;
|
||||
if (b) {
|
||||
console.log('true');
|
||||
} else {
|
||||
console.log('false');
|
||||
}
|
||||
useState();
|
||||
}
|
||||
`,
|
||||
errors: [conditionalError('useState', true)],
|
||||
},
|
||||
{
|
||||
code: `
|
||||
// Invalid because it's dangerous and might not warn otherwise.
|
||||
// This *must* be invalid.
|
||||
function useHook() {
|
||||
if (b) {
|
||||
console.log('true');
|
||||
} else {
|
||||
console.log('false');
|
||||
}
|
||||
if (a) return;
|
||||
useState();
|
||||
}
|
||||
`,
|
||||
errors: [conditionalError('useState', true)],
|
||||
},
|
||||
{
|
||||
code: `
|
||||
// Invalid because it's dangerous and might not warn otherwise.
|
||||
// This *must* be invalid.
|
||||
function useHook() {
|
||||
a && useHook1();
|
||||
b && useHook2();
|
||||
}
|
||||
`,
|
||||
errors: [conditionalError('useHook1'), conditionalError('useHook2')],
|
||||
},
|
||||
{
|
||||
code: `
|
||||
// Invalid because it's dangerous and might not warn otherwise.
|
||||
// This *must* be invalid.
|
||||
function useHook() {
|
||||
try {
|
||||
f();
|
||||
useState();
|
||||
} catch {}
|
||||
}
|
||||
`,
|
||||
errors: [
|
||||
// NOTE: This is an error since `f()` could possibly throw.
|
||||
conditionalError('useState'),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
function conditionalError(hook, hasPreviousFinalizer = false) {
|
||||
return {
|
||||
message:
|
||||
`React Hook "${hook}" is called conditionally. React Hooks must be ` +
|
||||
'called in the exact same order in every component render.' +
|
||||
(hasPreviousFinalizer
|
||||
? ' Did you accidentally call a React Hook after an early return?'
|
||||
: ''),
|
||||
};
|
||||
}
|
||||
|
||||
function loopError(hook) {
|
||||
return {
|
||||
message:
|
||||
`React Hook "${hook}" may be executed more than once. Possibly ` +
|
||||
'because it is called in a loop. React Hooks must be called in the ' +
|
||||
'exact same order in every component render.',
|
||||
};
|
||||
}
|
||||
|
||||
function functionError(hook, fn) {
|
||||
return {
|
||||
message:
|
||||
`React Hook "${hook}" is called in function "${fn}" which is neither ` +
|
||||
'a React function component or a custom React Hook function.',
|
||||
};
|
||||
}
|
||||
|
||||
function genericError(hook) {
|
||||
return {
|
||||
message:
|
||||
`React Hook "${hook}" cannot be called inside a callback. React Hooks ` +
|
||||
'must be called in a React function component or a custom React ' +
|
||||
'Hook function.',
|
||||
};
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) Facebook, Inc. and its affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
module.exports = require('./src/index');
|
||||
@@ -1,9 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
// TODO: this doesn't make sense for an ESLint rule.
|
||||
// We need to fix our build process to not create bundles for "raw" packages like this.
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
module.exports = require('./cjs/eslint-plugin-react-hooks.production.min.js');
|
||||
} else {
|
||||
module.exports = require('./cjs/eslint-plugin-react-hooks.development.js');
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "eslint-plugin-react-hooks",
|
||||
"description": "ESLint rules for React Hooks",
|
||||
"version": "0.0.0",
|
||||
"repository": "facebook/react",
|
||||
"files": [
|
||||
"LICENSE",
|
||||
"README.md",
|
||||
"build-info.json",
|
||||
"index.js",
|
||||
"cjs"
|
||||
],
|
||||
"keywords": [
|
||||
"eslint",
|
||||
"eslint-plugin",
|
||||
"eslintplugin",
|
||||
"react"
|
||||
],
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/facebook/react/issues"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
},
|
||||
"homepage": "https://reactjs.org/",
|
||||
"peerDependencies": {
|
||||
"eslint": "^3.0.0 || ^4.0.0 || ^5.0.0"
|
||||
}
|
||||
}
|
||||
@@ -1,549 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) Facebook, Inc. and its affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
/* eslint-disable no-for-of-loops/no-for-of-loops */
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Catch all identifiers that begin with "use" followed by an uppercase Latin
|
||||
* character to exclude identifiers like "user".
|
||||
*/
|
||||
|
||||
function isHookName(s) {
|
||||
return /^use[A-Z0-9].*$/.test(s);
|
||||
}
|
||||
|
||||
/**
|
||||
* We consider hooks to be a hook name identifier or a member expression
|
||||
* containing a hook name.
|
||||
*/
|
||||
|
||||
function isHook(node) {
|
||||
if (node.type === 'Identifier') {
|
||||
return isHookName(node.name);
|
||||
} else if (
|
||||
node.type === 'MemberExpression' &&
|
||||
!node.computed &&
|
||||
isHook(node.property)
|
||||
) {
|
||||
// Only consider React.useFoo() to be namespace hooks for now to avoid false positives.
|
||||
// We can expand this check later.
|
||||
const obj = node.object;
|
||||
return obj.type === 'Identifier' && obj.name === 'React';
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the node is a React component name. React component names must
|
||||
* always start with a non-lowercase letter. So `MyComponent` or `_MyComponent`
|
||||
* are valid component names for instance.
|
||||
*/
|
||||
|
||||
function isComponentName(node) {
|
||||
if (node.type === 'Identifier') {
|
||||
return !/^[a-z]/.test(node.name);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isInsideComponentOrHook(node) {
|
||||
while (node) {
|
||||
const functionName = getFunctionName(node);
|
||||
if (functionName) {
|
||||
if (isComponentName(functionName) || isHook(functionName)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
node = node.parent;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export default {
|
||||
create(context) {
|
||||
const codePathReactHooksMapStack = [];
|
||||
const codePathSegmentStack = [];
|
||||
return {
|
||||
// Maintain code segment path stack as we traverse.
|
||||
onCodePathSegmentStart: segment => codePathSegmentStack.push(segment),
|
||||
onCodePathSegmentEnd: () => codePathSegmentStack.pop(),
|
||||
|
||||
// Maintain code path stack as we traverse.
|
||||
onCodePathStart: () => codePathReactHooksMapStack.push(new Map()),
|
||||
|
||||
// Process our code path.
|
||||
//
|
||||
// Everything is ok if all React Hooks are both reachable from the initial
|
||||
// segment and reachable from every final segment.
|
||||
onCodePathEnd(codePath, codePathNode) {
|
||||
const reactHooksMap = codePathReactHooksMapStack.pop();
|
||||
if (reactHooksMap.size === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// All of the segments which are cyclic are recorded in this set.
|
||||
const cyclic = new Set();
|
||||
|
||||
/**
|
||||
* Count the number of code paths from the start of the function to this
|
||||
* segment. For example:
|
||||
*
|
||||
* ```js
|
||||
* function MyComponent() {
|
||||
* if (condition) {
|
||||
* // Segment 1
|
||||
* } else {
|
||||
* // Segment 2
|
||||
* }
|
||||
* // Segment 3
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Segments 1 and 2 have one path to the beginning of `MyComponent` and
|
||||
* segment 3 has two paths to the beginning of `MyComponent` since we
|
||||
* could have either taken the path of segment 1 or segment 2.
|
||||
*
|
||||
* Populates `cyclic` with cyclic segments.
|
||||
*/
|
||||
|
||||
function countPathsFromStart(segment) {
|
||||
const {cache} = countPathsFromStart;
|
||||
let paths = cache.get(segment.id);
|
||||
|
||||
// If `paths` is null then we've found a cycle! Add it to `cyclic` and
|
||||
// any other segments which are a part of this cycle.
|
||||
if (paths === null) {
|
||||
if (cyclic.has(segment.id)) {
|
||||
return 0;
|
||||
} else {
|
||||
cyclic.add(segment.id);
|
||||
for (const prevSegment of segment.prevSegments) {
|
||||
countPathsFromStart(prevSegment);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// We have a cached `paths`. Return it.
|
||||
if (paths !== undefined) {
|
||||
return paths;
|
||||
}
|
||||
|
||||
// Compute `paths` and cache it. Guarding against cycles.
|
||||
cache.set(segment.id, null);
|
||||
if (codePath.thrownSegments.includes(segment)) {
|
||||
paths = 0;
|
||||
} else if (segment.prevSegments.length === 0) {
|
||||
paths = 1;
|
||||
} else {
|
||||
paths = 0;
|
||||
for (const prevSegment of segment.prevSegments) {
|
||||
paths += countPathsFromStart(prevSegment);
|
||||
}
|
||||
}
|
||||
cache.set(segment.id, paths);
|
||||
|
||||
return paths;
|
||||
}
|
||||
|
||||
/**
|
||||
* Count the number of code paths from this segment to the end of the
|
||||
* function. For example:
|
||||
*
|
||||
* ```js
|
||||
* function MyComponent() {
|
||||
* // Segment 1
|
||||
* if (condition) {
|
||||
* // Segment 2
|
||||
* } else {
|
||||
* // Segment 3
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Segments 2 and 3 have one path to the end of `MyComponent` and
|
||||
* segment 1 has two paths to the end of `MyComponent` since we could
|
||||
* either take the path of segment 1 or segment 2.
|
||||
*
|
||||
* Populates `cyclic` with cyclic segments.
|
||||
*/
|
||||
|
||||
function countPathsToEnd(segment) {
|
||||
const {cache} = countPathsToEnd;
|
||||
let paths = cache.get(segment.id);
|
||||
|
||||
// If `paths` is null then we've found a cycle! Add it to `cyclic` and
|
||||
// any other segments which are a part of this cycle.
|
||||
if (paths === null) {
|
||||
if (cyclic.has(segment.id)) {
|
||||
return 0;
|
||||
} else {
|
||||
cyclic.add(segment.id);
|
||||
for (const nextSegment of segment.nextSegments) {
|
||||
countPathsToEnd(nextSegment);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// We have a cached `paths`. Return it.
|
||||
if (paths !== undefined) {
|
||||
return paths;
|
||||
}
|
||||
|
||||
// Compute `paths` and cache it. Guarding against cycles.
|
||||
cache.set(segment.id, null);
|
||||
if (codePath.thrownSegments.includes(segment)) {
|
||||
paths = 0;
|
||||
} else if (segment.nextSegments.length === 0) {
|
||||
paths = 1;
|
||||
} else {
|
||||
paths = 0;
|
||||
for (const nextSegment of segment.nextSegments) {
|
||||
paths += countPathsToEnd(nextSegment);
|
||||
}
|
||||
}
|
||||
cache.set(segment.id, paths);
|
||||
|
||||
return paths;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the shortest path length to the start of a code path.
|
||||
* For example:
|
||||
*
|
||||
* ```js
|
||||
* function MyComponent() {
|
||||
* if (condition) {
|
||||
* // Segment 1
|
||||
* }
|
||||
* // Segment 2
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* There is only one path from segment 1 to the code path start. Its
|
||||
* length is one so that is the shortest path.
|
||||
*
|
||||
* There are two paths from segment 2 to the code path start. One
|
||||
* through segment 1 with a length of two and another directly to the
|
||||
* start with a length of one. The shortest path has a length of one
|
||||
* so we would return that.
|
||||
*/
|
||||
|
||||
function shortestPathLengthToStart(segment) {
|
||||
const {cache} = shortestPathLengthToStart;
|
||||
let length = cache.get(segment.id);
|
||||
|
||||
// If `length` is null then we found a cycle! Return infinity since
|
||||
// the shortest path is definitely not the one where we looped.
|
||||
if (length === null) {
|
||||
return Infinity;
|
||||
}
|
||||
|
||||
// We have a cached `length`. Return it.
|
||||
if (length !== undefined) {
|
||||
return length;
|
||||
}
|
||||
|
||||
// Compute `length` and cache it. Guarding against cycles.
|
||||
cache.set(segment.id, null);
|
||||
if (segment.prevSegments.length === 0) {
|
||||
length = 1;
|
||||
} else {
|
||||
length = Infinity;
|
||||
for (const prevSegment of segment.prevSegments) {
|
||||
const prevLength = shortestPathLengthToStart(prevSegment);
|
||||
if (prevLength < length) {
|
||||
length = prevLength;
|
||||
}
|
||||
}
|
||||
length += 1;
|
||||
}
|
||||
cache.set(segment.id, length);
|
||||
return length;
|
||||
}
|
||||
|
||||
countPathsFromStart.cache = new Map();
|
||||
countPathsToEnd.cache = new Map();
|
||||
shortestPathLengthToStart.cache = new Map();
|
||||
|
||||
// Count all code paths to the end of our component/hook. Also primes
|
||||
// the `countPathsToEnd` cache.
|
||||
const allPathsFromStartToEnd = countPathsToEnd(codePath.initialSegment);
|
||||
|
||||
// Gets the function name for our code path. If the function name is
|
||||
// `undefined` then we know either that we have an anonymous function
|
||||
// expression or our code path is not in a function. In both cases we
|
||||
// will want to error since neither are React function components or
|
||||
// hook functions.
|
||||
const codePathFunctionName = getFunctionName(codePathNode);
|
||||
|
||||
// This is a valid code path for React hooks if we are direcly in a React
|
||||
// function component or we are in a hook function.
|
||||
const isSomewhereInsideComponentOrHook = isInsideComponentOrHook(
|
||||
codePathNode,
|
||||
);
|
||||
const isDirectlyInsideComponentOrHook = codePathFunctionName
|
||||
? isComponentName(codePathFunctionName) ||
|
||||
isHook(codePathFunctionName)
|
||||
: false;
|
||||
|
||||
// Compute the earliest finalizer level using information from the
|
||||
// cache. We expect all reachable final segments to have a cache entry
|
||||
// after calling `visitSegment()`.
|
||||
let shortestFinalPathLength = Infinity;
|
||||
for (const finalSegment of codePath.finalSegments) {
|
||||
if (!finalSegment.reachable) {
|
||||
continue;
|
||||
}
|
||||
const length = shortestPathLengthToStart(finalSegment);
|
||||
if (length < shortestFinalPathLength) {
|
||||
shortestFinalPathLength = length;
|
||||
}
|
||||
}
|
||||
|
||||
// Make sure all React Hooks pass our lint invariants. Log warnings
|
||||
// if not.
|
||||
for (const [segment, reactHooks] of reactHooksMap) {
|
||||
// NOTE: We could report here that the hook is not reachable, but
|
||||
// that would be redundant with more general "no unreachable"
|
||||
// lint rules.
|
||||
if (!segment.reachable) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// If there are any final segments with a shorter path to start then
|
||||
// we possibly have an early return.
|
||||
//
|
||||
// If our segment is a final segment itself then siblings could
|
||||
// possibly be early returns.
|
||||
const possiblyHasEarlyReturn =
|
||||
segment.nextSegments.length === 0
|
||||
? shortestFinalPathLength <= shortestPathLengthToStart(segment)
|
||||
: shortestFinalPathLength < shortestPathLengthToStart(segment);
|
||||
|
||||
// Count all the paths from the start of our code path to the end of
|
||||
// our code path that go _through_ this segment. The critical piece
|
||||
// of this is _through_. If we just call `countPathsToEnd(segment)`
|
||||
// then we neglect that we may have gone through multiple paths to get
|
||||
// to this point! Consider:
|
||||
//
|
||||
// ```js
|
||||
// function MyComponent() {
|
||||
// if (a) {
|
||||
// // Segment 1
|
||||
// } else {
|
||||
// // Segment 2
|
||||
// }
|
||||
// // Segment 3
|
||||
// if (b) {
|
||||
// // Segment 4
|
||||
// } else {
|
||||
// // Segment 5
|
||||
// }
|
||||
// }
|
||||
// ```
|
||||
//
|
||||
// In this component we have four code paths:
|
||||
//
|
||||
// 1. `a = true; b = true`
|
||||
// 2. `a = true; b = false`
|
||||
// 3. `a = false; b = true`
|
||||
// 4. `a = false; b = false`
|
||||
//
|
||||
// From segment 3 there are two code paths to the end through segment
|
||||
// 4 and segment 5. However, we took two paths to get here through
|
||||
// segment 1 and segment 2.
|
||||
//
|
||||
// If we multiply the paths from start (two) by the paths to end (two)
|
||||
// for segment 3 we get four. Which is our desired count.
|
||||
const pathsFromStartToEnd =
|
||||
countPathsFromStart(segment) * countPathsToEnd(segment);
|
||||
|
||||
// Is this hook a part of a cyclic segment?
|
||||
const cycled = cyclic.has(segment.id);
|
||||
|
||||
for (const hook of reactHooks) {
|
||||
// Report an error if a hook may be called more then once.
|
||||
if (cycled) {
|
||||
context.report(
|
||||
hook,
|
||||
`React Hook "${context.getSource(hook)}" may be executed ` +
|
||||
'more than once. Possibly because it is called in a loop. ' +
|
||||
'React Hooks must be called in the exact same order in ' +
|
||||
'every component render.',
|
||||
);
|
||||
}
|
||||
|
||||
// If this is not a valid code path for React hooks then we need to
|
||||
// log a warning for every hook in this code path.
|
||||
//
|
||||
// Pick a special message depending on the scope this hook was
|
||||
// called in.
|
||||
if (isDirectlyInsideComponentOrHook) {
|
||||
// Report an error if a hook does not reach all finalizing code
|
||||
// path segments.
|
||||
//
|
||||
// Special case when we think there might be an early return.
|
||||
if (!cycled && pathsFromStartToEnd !== allPathsFromStartToEnd) {
|
||||
context.report(
|
||||
hook,
|
||||
`React Hook "${context.getSource(hook)}" is called ` +
|
||||
'conditionally. React Hooks must be called in the exact ' +
|
||||
'same order in every component render.' +
|
||||
(possiblyHasEarlyReturn
|
||||
? ' Did you accidentally call a React Hook after an' +
|
||||
' early return?'
|
||||
: ''),
|
||||
);
|
||||
}
|
||||
} else if (
|
||||
codePathNode.parent &&
|
||||
(codePathNode.parent.type === 'MethodDefinition' ||
|
||||
codePathNode.parent.type === 'ClassProperty') &&
|
||||
codePathNode.parent.value === codePathNode
|
||||
) {
|
||||
// Ignore class methods for now because they produce too many
|
||||
// false positives due to feature flag checks. We're less
|
||||
// sensitive to them in classes because hooks would produce
|
||||
// runtime errors in classes anyway, and because a use*()
|
||||
// call in a class, if it works, is unambigously *not* a hook.
|
||||
} else if (codePathFunctionName) {
|
||||
// Custom message if we found an invalid function name.
|
||||
context.report(
|
||||
hook,
|
||||
`React Hook "${context.getSource(hook)}" is called in ` +
|
||||
`function "${context.getSource(codePathFunctionName)}" ` +
|
||||
'which is neither a React function component or a custom ' +
|
||||
'React Hook function.',
|
||||
);
|
||||
} else if (codePathNode.type === 'Program') {
|
||||
// For now, ignore if it's in top level scope.
|
||||
// We could warn here but there are false positives related
|
||||
// configuring libraries like `history`.
|
||||
} else {
|
||||
// Assume in all other cases the user called a hook in some
|
||||
// random function callback. This should usually be true for
|
||||
// anonymous function expressions. Hopefully this is clarifying
|
||||
// enough in the common case that the incorrect message in
|
||||
// uncommon cases doesn't matter.
|
||||
if (isSomewhereInsideComponentOrHook) {
|
||||
context.report(
|
||||
hook,
|
||||
`React Hook "${context.getSource(hook)}" cannot be called ` +
|
||||
'inside a callback. React Hooks must be called in a ' +
|
||||
'React function component or a custom React Hook function.',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// Missed opportunity...We could visit all `Identifier`s instead of all
|
||||
// `CallExpression`s and check that _every use_ of a hook name is valid.
|
||||
// But that gets complicated and enters type-system territory, so we're
|
||||
// only being strict about hook calls for now.
|
||||
CallExpression(node) {
|
||||
if (isHook(node.callee)) {
|
||||
// Add the hook node to a map keyed by the code path segment. We will
|
||||
// do full code path analysis at the end of our code path.
|
||||
const reactHooksMap = last(codePathReactHooksMapStack);
|
||||
const codePathSegment = last(codePathSegmentStack);
|
||||
let reactHooks = reactHooksMap.get(codePathSegment);
|
||||
if (!reactHooks) {
|
||||
reactHooks = [];
|
||||
reactHooksMap.set(codePathSegment, reactHooks);
|
||||
}
|
||||
reactHooks.push(node.callee);
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets tbe static name of a function AST node. For function declarations it is
|
||||
* easy. For anonymous function expressions it is much harder. If you search for
|
||||
* `IsAnonymousFunctionDefinition()` in the ECMAScript spec you'll find places
|
||||
* where JS gives anonymous function expressions names. We roughly detect the
|
||||
* same AST nodes with some exceptions to better fit our usecase.
|
||||
*/
|
||||
|
||||
function getFunctionName(node) {
|
||||
if (
|
||||
node.type === 'FunctionDeclaration' ||
|
||||
(node.type === 'FunctionExpression' && node.id)
|
||||
) {
|
||||
// function useHook() {}
|
||||
// const whatever = function useHook() {};
|
||||
//
|
||||
// Function declaration or function expression names win over any
|
||||
// assignment statements or other renames.
|
||||
return node.id;
|
||||
} else if (
|
||||
node.type === 'FunctionExpression' ||
|
||||
node.type === 'ArrowFunctionExpression'
|
||||
) {
|
||||
if (
|
||||
node.parent.type === 'VariableDeclarator' &&
|
||||
node.parent.init === node
|
||||
) {
|
||||
// const useHook = () => {};
|
||||
return node.parent.id;
|
||||
} else if (
|
||||
node.parent.type === 'AssignmentExpression' &&
|
||||
node.parent.right === node &&
|
||||
node.parent.operator === '='
|
||||
) {
|
||||
// useHook = () => {};
|
||||
return node.parent.left;
|
||||
} else if (
|
||||
node.parent.type === 'Property' &&
|
||||
node.parent.value === node &&
|
||||
!node.parent.computed
|
||||
) {
|
||||
// {useHook: () => {}}
|
||||
// {useHook() {}}
|
||||
return node.parent.key;
|
||||
|
||||
// NOTE: We could also support `ClassProperty` and `MethodDefinition`
|
||||
// here to be pedantic. However, hooks in a class are an anti-pattern. So
|
||||
// we don't allow it to error early.
|
||||
//
|
||||
// class {useHook = () => {}}
|
||||
// class {useHook() {}}
|
||||
} else if (
|
||||
node.parent.type === 'AssignmentPattern' &&
|
||||
node.parent.right === node &&
|
||||
!node.parent.computed
|
||||
) {
|
||||
// const {useHook = () => {}} = {};
|
||||
// ({useHook = () => {}} = {});
|
||||
//
|
||||
// Kinda clowny, but we'd said we'd follow spec convention for
|
||||
// `IsAnonymousFunctionDefinition()` usage.
|
||||
return node.parent.left;
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience function for peeking the last item in a stack.
|
||||
*/
|
||||
|
||||
function last(array) {
|
||||
return array[array.length - 1];
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) Facebook, Inc. and its affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
import RuleOfHooks from './RulesOfHooks';
|
||||
|
||||
export const rules = {
|
||||
'rules-of-hooks': RuleOfHooks,
|
||||
};
|
||||
@@ -37,19 +37,26 @@ let eventQueue: ?(Array<ReactSyntheticEvent> | ReactSyntheticEvent) = null;
|
||||
* Dispatches an event and releases it back into the pool, unless persistent.
|
||||
*
|
||||
* @param {?object} event Synthetic event to be dispatched.
|
||||
* @param {boolean} simulated If the event is simulated (changes exn behavior)
|
||||
* @private
|
||||
*/
|
||||
const executeDispatchesAndRelease = function(event: ReactSyntheticEvent) {
|
||||
const executeDispatchesAndRelease = function(
|
||||
event: ReactSyntheticEvent,
|
||||
simulated: boolean,
|
||||
) {
|
||||
if (event) {
|
||||
executeDispatchesInOrder(event);
|
||||
executeDispatchesInOrder(event, simulated);
|
||||
|
||||
if (!event.isPersistent()) {
|
||||
event.constructor.release(event);
|
||||
}
|
||||
}
|
||||
};
|
||||
const executeDispatchesAndReleaseSimulated = function(e) {
|
||||
return executeDispatchesAndRelease(e, true);
|
||||
};
|
||||
const executeDispatchesAndReleaseTopLevel = function(e) {
|
||||
return executeDispatchesAndRelease(e);
|
||||
return executeDispatchesAndRelease(e, false);
|
||||
};
|
||||
|
||||
function isInteractive(tag) {
|
||||
@@ -185,6 +192,7 @@ function extractEvents(
|
||||
|
||||
export function runEventsInBatch(
|
||||
events: Array<ReactSyntheticEvent> | ReactSyntheticEvent | null,
|
||||
simulated: boolean,
|
||||
) {
|
||||
if (events !== null) {
|
||||
eventQueue = accumulateInto(eventQueue, events);
|
||||
@@ -199,7 +207,17 @@ export function runEventsInBatch(
|
||||
return;
|
||||
}
|
||||
|
||||
forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel);
|
||||
if (simulated) {
|
||||
forEachAccumulated(
|
||||
processingEventQueue,
|
||||
executeDispatchesAndReleaseSimulated,
|
||||
);
|
||||
} else {
|
||||
forEachAccumulated(
|
||||
processingEventQueue,
|
||||
executeDispatchesAndReleaseTopLevel,
|
||||
);
|
||||
}
|
||||
invariant(
|
||||
!eventQueue,
|
||||
'processEventQueue(): Additional events were enqueued while processing ' +
|
||||
@@ -221,5 +239,5 @@ export function runExtractedEventsInBatch(
|
||||
nativeEvent,
|
||||
nativeEventTarget,
|
||||
);
|
||||
runEventsInBatch(events);
|
||||
runEventsInBatch(events, false);
|
||||
}
|
||||
|
||||
@@ -60,10 +60,11 @@ if (__DEV__) {
|
||||
/**
|
||||
* Dispatch the event to the listener.
|
||||
* @param {SyntheticEvent} event SyntheticEvent to handle
|
||||
* @param {boolean} simulated If the event is simulated (changes exn behavior)
|
||||
* @param {function} listener Application-level callback
|
||||
* @param {*} inst Internal component instance
|
||||
*/
|
||||
function executeDispatch(event, listener, inst) {
|
||||
function executeDispatch(event, simulated, listener, inst) {
|
||||
const type = event.type || 'unknown-event';
|
||||
event.currentTarget = getNodeFromInstance(inst);
|
||||
invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);
|
||||
@@ -73,7 +74,7 @@ function executeDispatch(event, listener, inst) {
|
||||
/**
|
||||
* Standard/simple iteration through an event's collected dispatches.
|
||||
*/
|
||||
export function executeDispatchesInOrder(event) {
|
||||
export function executeDispatchesInOrder(event, simulated) {
|
||||
const dispatchListeners = event._dispatchListeners;
|
||||
const dispatchInstances = event._dispatchInstances;
|
||||
if (__DEV__) {
|
||||
@@ -85,10 +86,15 @@ export function executeDispatchesInOrder(event) {
|
||||
break;
|
||||
}
|
||||
// Listeners and Instances are two parallel arrays that are always in sync.
|
||||
executeDispatch(event, dispatchListeners[i], dispatchInstances[i]);
|
||||
executeDispatch(
|
||||
event,
|
||||
simulated,
|
||||
dispatchListeners[i],
|
||||
dispatchInstances[i],
|
||||
);
|
||||
}
|
||||
} else if (dispatchListeners) {
|
||||
executeDispatch(event, dispatchListeners, dispatchInstances);
|
||||
executeDispatch(event, simulated, dispatchListeners, dispatchInstances);
|
||||
}
|
||||
event._dispatchListeners = null;
|
||||
event._dispatchInstances = null;
|
||||
|
||||
@@ -3,8 +3,6 @@
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow
|
||||
*/
|
||||
|
||||
import invariant from 'shared/invariant';
|
||||
@@ -37,13 +35,11 @@ function restoreStateOfTarget(target) {
|
||||
restoreImpl(internalInstance.stateNode, internalInstance.type, props);
|
||||
}
|
||||
|
||||
export function setRestoreImplementation(
|
||||
impl: (domElement: Element, tag: string, props: Object) => void,
|
||||
): void {
|
||||
export function setRestoreImplementation(impl) {
|
||||
restoreImpl = impl;
|
||||
}
|
||||
|
||||
export function enqueueStateRestore(target: EventTarget): void {
|
||||
export function enqueueStateRestore(target) {
|
||||
if (restoreTarget) {
|
||||
if (restoreQueue) {
|
||||
restoreQueue.push(target);
|
||||
|
||||
@@ -321,7 +321,7 @@ const run = function(config, hierarchyConfig, nativeEventConfig) {
|
||||
// At this point the negotiation events have been dispatched as part of the
|
||||
// extraction process, but not the side effectful events. Below, we dispatch
|
||||
// side effectful events.
|
||||
EventPluginHub.runEventsInBatch(extractedEvents);
|
||||
EventPluginHub.runEventsInBatch(extractedEvents, true);
|
||||
|
||||
// Ensure that every event that declared an `order`, was actually dispatched.
|
||||
expect('number of events dispatched:' + runData.dispatchCount).toBe(
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
# `jest-mock-scheduler`
|
||||
|
||||
Jest matchers and utilities for testing the `scheduler` package.
|
||||
|
||||
This package is experimental. APIs may change between releases.
|
||||
@@ -1,8 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) Facebook, Inc. and its affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
export * from './src/JestMockScheduler';
|
||||
@@ -1,7 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
module.exports = require('./cjs/jest-mock-scheduler.production.min.js');
|
||||
} else {
|
||||
module.exports = require('./cjs/jest-mock-scheduler.development.js');
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
{
|
||||
"name": "jest-mock-scheduler",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"description": "Jest matchers and utilities for testing the scheduler package.",
|
||||
"main": "index.js",
|
||||
"repository": "facebook/react",
|
||||
"keywords": [
|
||||
"jest",
|
||||
"scheduler"
|
||||
],
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/facebook/react/issues"
|
||||
},
|
||||
"homepage": "https://reactjs.org/",
|
||||
"peerDependencies": {
|
||||
"jest": "^23.0.1",
|
||||
"scheduler": "^0.11.0"
|
||||
},
|
||||
"files": [
|
||||
"LICENSE",
|
||||
"README.md",
|
||||
"build-info.json",
|
||||
"index.js",
|
||||
"cjs/"
|
||||
]
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) Facebook, Inc. and its affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
// Max 31 bit integer. The max integer size in V8 for 32-bit systems.
|
||||
// Math.pow(2, 30) - 1
|
||||
// 0b111111111111111111111111111111
|
||||
const maxSigned31BitInt = 1073741823;
|
||||
|
||||
export function mockRestore() {
|
||||
delete global._schedMock;
|
||||
}
|
||||
|
||||
let callback = null;
|
||||
let currentTime = -1;
|
||||
|
||||
function flushCallback(didTimeout, ms) {
|
||||
if (callback !== null) {
|
||||
let cb = callback;
|
||||
callback = null;
|
||||
try {
|
||||
currentTime = ms;
|
||||
cb(didTimeout);
|
||||
} finally {
|
||||
currentTime = -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function requestHostCallback(cb, ms) {
|
||||
if (currentTime !== -1) {
|
||||
// Protect against re-entrancy.
|
||||
setTimeout(requestHostCallback, 0, cb, ms);
|
||||
} else {
|
||||
callback = cb;
|
||||
setTimeout(flushCallback, ms, true, ms);
|
||||
setTimeout(flushCallback, maxSigned31BitInt, false, maxSigned31BitInt);
|
||||
}
|
||||
}
|
||||
|
||||
function cancelHostCallback() {
|
||||
callback = null;
|
||||
}
|
||||
|
||||
function shouldYieldToHost() {
|
||||
return false;
|
||||
}
|
||||
|
||||
function getCurrentTime() {
|
||||
return currentTime === -1 ? 0 : currentTime;
|
||||
}
|
||||
|
||||
global._schedMock = [
|
||||
requestHostCallback,
|
||||
cancelHostCallback,
|
||||
shouldYieldToHost,
|
||||
getCurrentTime,
|
||||
];
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "jest-react",
|
||||
"version": "0.4.0",
|
||||
"version": "0.3.0-alpha.8af6728",
|
||||
"description": "Jest matchers and utilities for testing React components.",
|
||||
"main": "index.js",
|
||||
"repository": "facebook/react",
|
||||
@@ -16,13 +16,12 @@
|
||||
"homepage": "https://reactjs.org/",
|
||||
"peerDependencies": {
|
||||
"jest": "^23.0.1",
|
||||
"react": "^16.0.0",
|
||||
"react": "^16.0.0 || 16.6.0-alpha.8af6728",
|
||||
"react-test-renderer": "^16.0.0"
|
||||
},
|
||||
"files": [
|
||||
"LICENSE",
|
||||
"README.md",
|
||||
"build-info.json",
|
||||
"index.js",
|
||||
"cjs/"
|
||||
]
|
||||
|
||||
@@ -30,31 +30,33 @@ function assertYieldsWereCleared(root) {
|
||||
invariant(
|
||||
actualYields.length === 0,
|
||||
'Log of yielded values is not empty. ' +
|
||||
'Call expect(ReactTestRenderer).unstable_toHaveYielded(...) first.',
|
||||
'Call expect(ReactTestRenderer).toHaveYielded(...) first.',
|
||||
);
|
||||
}
|
||||
|
||||
export function unstable_toFlushAndYield(root, expectedYields) {
|
||||
assertYieldsWereCleared(root);
|
||||
const actualYields = root.unstable_flushAll();
|
||||
export function toFlushAndYield(root, expectedYields) {
|
||||
return captureAssertion(() => {
|
||||
assertYieldsWereCleared(root);
|
||||
const actualYields = root.unstable_flushAll();
|
||||
expect(actualYields).toEqual(expectedYields);
|
||||
});
|
||||
}
|
||||
|
||||
export function unstable_toFlushAndYieldThrough(root, expectedYields) {
|
||||
assertYieldsWereCleared(root);
|
||||
const actualYields = root.unstable_flushNumberOfYields(expectedYields.length);
|
||||
export function toFlushAndYieldThrough(root, expectedYields) {
|
||||
return captureAssertion(() => {
|
||||
assertYieldsWereCleared(root);
|
||||
const actualYields = root.unstable_flushNumberOfYields(
|
||||
expectedYields.length,
|
||||
);
|
||||
expect(actualYields).toEqual(expectedYields);
|
||||
});
|
||||
}
|
||||
|
||||
export function unstable_toFlushWithoutYielding(root) {
|
||||
return unstable_toFlushAndYield(root, []);
|
||||
export function toFlushWithoutYielding(root) {
|
||||
return toFlushAndYield(root, []);
|
||||
}
|
||||
|
||||
export function unstable_toHaveYielded(ReactTestRenderer, expectedYields) {
|
||||
export function toHaveYielded(ReactTestRenderer, expectedYields) {
|
||||
return captureAssertion(() => {
|
||||
if (
|
||||
ReactTestRenderer === null ||
|
||||
@@ -63,9 +65,9 @@ export function unstable_toHaveYielded(ReactTestRenderer, expectedYields) {
|
||||
) {
|
||||
invariant(
|
||||
false,
|
||||
'The matcher `unstable_toHaveYielded` expects an instance of React Test ' +
|
||||
'The matcher `toHaveYielded` expects an instance of React Test ' +
|
||||
'Renderer.\n\nTry: ' +
|
||||
'expect(ReactTestRenderer).unstable_toHaveYielded(expectedYields)',
|
||||
'expect(ReactTestRenderer).toHaveYielded(expectedYields)',
|
||||
);
|
||||
}
|
||||
const actualYields = ReactTestRenderer.unstable_clearYields();
|
||||
@@ -73,16 +75,16 @@ export function unstable_toHaveYielded(ReactTestRenderer, expectedYields) {
|
||||
});
|
||||
}
|
||||
|
||||
export function unstable_toFlushAndThrow(root, ...rest) {
|
||||
assertYieldsWereCleared(root);
|
||||
export function toFlushAndThrow(root, ...rest) {
|
||||
return captureAssertion(() => {
|
||||
assertYieldsWereCleared(root);
|
||||
expect(() => {
|
||||
root.unstable_flushAll();
|
||||
}).toThrow(...rest);
|
||||
});
|
||||
}
|
||||
|
||||
export function unstable_toMatchRenderedOutput(root, expectedJSX) {
|
||||
export function toMatchRenderedOutput(root, expectedJSX) {
|
||||
assertYieldsWereCleared(root);
|
||||
const actualJSON = root.toJSON();
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "react-art",
|
||||
"description": "React ART is a JavaScript library for drawing vector graphics using React. It provides declarative and reactive bindings to the ART library. Using the same declarative API you can render the output to either Canvas, SVG or VML (IE8).",
|
||||
"version": "16.6.1",
|
||||
"version": "16.6.0-alpha.8af6728",
|
||||
"main": "index.js",
|
||||
"repository": "facebook/react",
|
||||
"keywords": [
|
||||
@@ -23,15 +23,14 @@
|
||||
"loose-envify": "^1.1.0",
|
||||
"object-assign": "^4.1.1",
|
||||
"prop-types": "^15.6.2",
|
||||
"scheduler": "^0.11.0"
|
||||
"scheduler": "^0.10.0-alpha.8af6728"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^16.0.0"
|
||||
"react": "^16.0.0 || 16.6.0-alpha.8af6728"
|
||||
},
|
||||
"files": [
|
||||
"LICENSE",
|
||||
"README.md",
|
||||
"build-info.json",
|
||||
"index.js",
|
||||
"cjs/",
|
||||
"umd/",
|
||||
|
||||
16
packages/react-art/src/ReactART.js
vendored
16
packages/react-art/src/ReactART.js
vendored
@@ -7,11 +7,7 @@
|
||||
|
||||
import React from 'react';
|
||||
import ReactVersion from 'shared/ReactVersion';
|
||||
import {
|
||||
createContainer,
|
||||
updateContainer,
|
||||
injectIntoDevTools,
|
||||
} from 'react-reconciler/inline.art';
|
||||
import * as ARTRenderer from 'react-reconciler/inline.art';
|
||||
import Transform from 'art/core/transform';
|
||||
import Mode from 'art/modes/current';
|
||||
import FastNoSideEffects from 'art/modes/fast-noSideEffects';
|
||||
@@ -65,8 +61,8 @@ class Surface extends React.Component {
|
||||
|
||||
this._surface = Mode.Surface(+width, +height, this._tagRef);
|
||||
|
||||
this._mountNode = createContainer(this._surface);
|
||||
updateContainer(this.props.children, this._mountNode, this);
|
||||
this._mountNode = ARTRenderer.createContainer(this._surface);
|
||||
ARTRenderer.updateContainer(this.props.children, this._mountNode, this);
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps, prevState) {
|
||||
@@ -76,7 +72,7 @@ class Surface extends React.Component {
|
||||
this._surface.resize(+props.width, +props.height);
|
||||
}
|
||||
|
||||
updateContainer(this.props.children, this._mountNode, this);
|
||||
ARTRenderer.updateContainer(this.props.children, this._mountNode, this);
|
||||
|
||||
if (this._surface.render) {
|
||||
this._surface.render();
|
||||
@@ -84,7 +80,7 @@ class Surface extends React.Component {
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
updateContainer(null, this._mountNode, this);
|
||||
ARTRenderer.updateContainer(null, this._mountNode, this);
|
||||
}
|
||||
|
||||
render() {
|
||||
@@ -136,7 +132,7 @@ class Text extends React.Component {
|
||||
}
|
||||
}
|
||||
|
||||
injectIntoDevTools({
|
||||
ARTRenderer.injectIntoDevTools({
|
||||
findFiberByHostInstance: () => null,
|
||||
bundleType: __DEV__ ? 1 : 0,
|
||||
version: ReactVersion,
|
||||
|
||||
1
packages/react-art/src/ReactARTHostConfig.js
vendored
1
packages/react-art/src/ReactARTHostConfig.js
vendored
@@ -8,7 +8,6 @@
|
||||
export {
|
||||
unstable_now as now,
|
||||
unstable_scheduleCallback as scheduleDeferredCallback,
|
||||
unstable_shouldYield as shouldYield,
|
||||
unstable_cancelCallback as cancelDeferredCallback,
|
||||
} from 'scheduler';
|
||||
import Transform from 'art/core/transform';
|
||||
|
||||
@@ -1,18 +1,15 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "react-cache",
|
||||
"description": "A basic cache for React applications",
|
||||
"version": "2.0.0-alpha.0",
|
||||
"version": "16.6.0-alpha.8af6728",
|
||||
"repository": "facebook/react",
|
||||
"files": [
|
||||
"LICENSE",
|
||||
"README.md",
|
||||
"build-info.json",
|
||||
"index.js",
|
||||
"cjs/",
|
||||
"umd/"
|
||||
"cjs/"
|
||||
],
|
||||
"peerDependencies": {
|
||||
"react": "^16.3.0-alpha.1"
|
||||
"react": "^16.3.0-alpha.1 || 16.6.0-alpha.8af6728"
|
||||
}
|
||||
}
|
||||
|
||||
142
packages/react-cache/src/LRU.js
vendored
142
packages/react-cache/src/LRU.js
vendored
@@ -1,142 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) 2014-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow
|
||||
*/
|
||||
|
||||
import {unstable_scheduleCallback as scheduleCallback} from 'scheduler';
|
||||
|
||||
type Entry<T> = {|
|
||||
value: T,
|
||||
onDelete: () => mixed,
|
||||
previous: Entry<T>,
|
||||
next: Entry<T>,
|
||||
|};
|
||||
|
||||
export function createLRU<T>(limit: number) {
|
||||
let LIMIT = limit;
|
||||
|
||||
// Circular, doubly-linked list
|
||||
let first: Entry<T> | null = null;
|
||||
let size: number = 0;
|
||||
|
||||
let cleanUpIsScheduled: boolean = false;
|
||||
|
||||
function scheduleCleanUp() {
|
||||
if (cleanUpIsScheduled === false && size > LIMIT) {
|
||||
// The cache size exceeds the limit. Schedule a callback to delete the
|
||||
// least recently used entries.
|
||||
cleanUpIsScheduled = true;
|
||||
scheduleCallback(cleanUp);
|
||||
}
|
||||
}
|
||||
|
||||
function cleanUp() {
|
||||
cleanUpIsScheduled = false;
|
||||
deleteLeastRecentlyUsedEntries(LIMIT);
|
||||
}
|
||||
|
||||
function deleteLeastRecentlyUsedEntries(targetSize: number) {
|
||||
// Delete entries from the cache, starting from the end of the list.
|
||||
if (first !== null) {
|
||||
const resolvedFirst: Entry<T> = (first: any);
|
||||
let last = resolvedFirst.previous;
|
||||
while (size > targetSize && last !== null) {
|
||||
const onDelete = last.onDelete;
|
||||
const previous = last.previous;
|
||||
last.onDelete = (null: any);
|
||||
|
||||
// Remove from the list
|
||||
last.previous = last.next = (null: any);
|
||||
if (last === first) {
|
||||
// Reached the head of the list.
|
||||
first = last = null;
|
||||
} else {
|
||||
(first: any).previous = previous;
|
||||
previous.next = (first: any);
|
||||
last = previous;
|
||||
}
|
||||
|
||||
size -= 1;
|
||||
|
||||
// Call the destroy method after removing the entry from the list. If it
|
||||
// throws, the rest of cache will not be deleted, but it will be in a
|
||||
// valid state.
|
||||
onDelete();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function add(value: T, onDelete: () => mixed): Entry<T> {
|
||||
const entry = {
|
||||
value,
|
||||
onDelete,
|
||||
next: (null: any),
|
||||
previous: (null: any),
|
||||
};
|
||||
if (first === null) {
|
||||
entry.previous = entry.next = entry;
|
||||
first = entry;
|
||||
} else {
|
||||
// Append to head
|
||||
const last = first.previous;
|
||||
last.next = entry;
|
||||
entry.previous = last;
|
||||
|
||||
first.previous = entry;
|
||||
entry.next = first;
|
||||
|
||||
first = entry;
|
||||
}
|
||||
size += 1;
|
||||
return entry;
|
||||
}
|
||||
|
||||
function update(entry: Entry<T>, newValue: T): void {
|
||||
entry.value = newValue;
|
||||
}
|
||||
|
||||
function access(entry: Entry<T>): T {
|
||||
const next = entry.next;
|
||||
if (next !== null) {
|
||||
// Entry already cached
|
||||
const resolvedFirst: Entry<T> = (first: any);
|
||||
if (first !== entry) {
|
||||
// Remove from current position
|
||||
const previous = entry.previous;
|
||||
previous.next = next;
|
||||
next.previous = previous;
|
||||
|
||||
// Append to head
|
||||
const last = resolvedFirst.previous;
|
||||
last.next = entry;
|
||||
entry.previous = last;
|
||||
|
||||
resolvedFirst.previous = entry;
|
||||
entry.next = resolvedFirst;
|
||||
|
||||
first = entry;
|
||||
}
|
||||
} else {
|
||||
// Cannot access a deleted entry
|
||||
// TODO: Error? Warning?
|
||||
}
|
||||
scheduleCleanUp();
|
||||
return entry.value;
|
||||
}
|
||||
|
||||
function setLimit(newLimit: number) {
|
||||
LIMIT = newLimit;
|
||||
scheduleCleanUp();
|
||||
}
|
||||
|
||||
return {
|
||||
add,
|
||||
update,
|
||||
access,
|
||||
setLimit,
|
||||
};
|
||||
}
|
||||
492
packages/react-cache/src/ReactCache.js
vendored
492
packages/react-cache/src/ReactCache.js
vendored
@@ -10,178 +10,394 @@
|
||||
import React from 'react';
|
||||
import warningWithoutStack from 'shared/warningWithoutStack';
|
||||
|
||||
import {createLRU} from './LRU';
|
||||
function noop() {}
|
||||
|
||||
type Thenable<T> = {
|
||||
then(resolve: (T) => mixed, reject: (mixed) => mixed): mixed,
|
||||
};
|
||||
const Empty = 0;
|
||||
const Pending = 1;
|
||||
const Resolved = 2;
|
||||
const Rejected = 3;
|
||||
|
||||
type Suspender = {
|
||||
then(resolve: () => mixed, reject: () => mixed): mixed,
|
||||
};
|
||||
|
||||
type PendingResult = {|
|
||||
type EmptyRecord<K> = {|
|
||||
status: 0,
|
||||
value: Suspender,
|
||||
suspender: null,
|
||||
key: K,
|
||||
value: null,
|
||||
error: null,
|
||||
next: any, // TODO: (issue #12941)
|
||||
previous: any, // TODO: (issue #12941)
|
||||
/**
|
||||
* Proper types would be something like this:
|
||||
* next: Record<K, V> | null,
|
||||
* previous: Record<K, V> | null,
|
||||
*/
|
||||
|};
|
||||
|
||||
type ResolvedResult<V> = {|
|
||||
type PendingRecord<K, V> = {|
|
||||
status: 1,
|
||||
value: V,
|
||||
suspender: Promise<V>,
|
||||
key: K,
|
||||
value: null,
|
||||
error: null,
|
||||
next: any, // TODO: (issue #12941)
|
||||
previous: any, // TODO: (issue #12941)
|
||||
/**
|
||||
* Proper types would be something like this:
|
||||
* next: Record<K, V> | null,
|
||||
* previous: Record<K, V> | null,
|
||||
*/
|
||||
|};
|
||||
|
||||
type RejectedResult = {|
|
||||
type ResolvedRecord<K, V> = {|
|
||||
status: 2,
|
||||
value: mixed,
|
||||
suspender: null,
|
||||
key: K,
|
||||
value: V,
|
||||
error: null,
|
||||
next: any, // TODO: (issue #12941)
|
||||
previous: any, // TODO: (issue #12941)
|
||||
/**
|
||||
* Proper types would be something like this:
|
||||
* next: Record<K, V> | null,
|
||||
* previous: Record<K, V> | null,
|
||||
*/
|
||||
|};
|
||||
|
||||
type Result<V> = PendingResult | ResolvedResult<V> | RejectedResult;
|
||||
type RejectedRecord<K> = {|
|
||||
status: 3,
|
||||
suspender: null,
|
||||
key: K,
|
||||
value: null,
|
||||
error: Error,
|
||||
next: any, // TODO: (issue #12941)
|
||||
previous: any, // TODO: (issue #12941)
|
||||
/**
|
||||
* Proper types would be something like this:
|
||||
* next: Record<K, V> | null,
|
||||
* previous: Record<K, V> | null,
|
||||
*/
|
||||
|};
|
||||
|
||||
type Resource<I, V> = {
|
||||
read(I): V,
|
||||
preload(I): void,
|
||||
type Record<K, V> =
|
||||
| EmptyRecord<K>
|
||||
| PendingRecord<K, V>
|
||||
| ResolvedRecord<K, V>
|
||||
| RejectedRecord<K>;
|
||||
|
||||
type RecordCache<K, V> = {|
|
||||
map: Map<K, Record<K, V>>,
|
||||
head: Record<K, V> | null,
|
||||
tail: Record<K, V> | null,
|
||||
size: number,
|
||||
|};
|
||||
|
||||
// TODO: How do you express this type with Flow?
|
||||
type ResourceMap = Map<any, RecordCache<any, any>>;
|
||||
type Cache = {
|
||||
invalidate(): void,
|
||||
read<K, V, A>(
|
||||
resourceType: mixed,
|
||||
key: K,
|
||||
miss: (A) => Promise<V>,
|
||||
missArg: A,
|
||||
): V,
|
||||
preload<K, V, A>(
|
||||
resourceType: mixed,
|
||||
key: K,
|
||||
miss: (A) => Promise<V>,
|
||||
missArg: A,
|
||||
): void,
|
||||
|
||||
// DEV-only
|
||||
$$typeof?: Symbol | number,
|
||||
};
|
||||
|
||||
const Pending = 0;
|
||||
const Resolved = 1;
|
||||
const Rejected = 2;
|
||||
|
||||
const currentOwner =
|
||||
React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner;
|
||||
|
||||
function readContext(Context, observedBits) {
|
||||
const dispatcher = currentOwner.currentDispatcher;
|
||||
if (dispatcher === null) {
|
||||
throw new Error(
|
||||
'react-cache: read and preload may only be called from within a ' +
|
||||
"component's render. They are not supported in event handlers or " +
|
||||
'lifecycle methods.',
|
||||
);
|
||||
}
|
||||
return dispatcher.readContext(Context, observedBits);
|
||||
let CACHE_TYPE;
|
||||
if (__DEV__) {
|
||||
CACHE_TYPE = 0xcac4e;
|
||||
}
|
||||
|
||||
function identityHashFn(input) {
|
||||
let isCache;
|
||||
if (__DEV__) {
|
||||
isCache = value =>
|
||||
value !== null &&
|
||||
typeof value === 'object' &&
|
||||
value.$$typeof === CACHE_TYPE;
|
||||
}
|
||||
|
||||
// TODO: Make this configurable per resource
|
||||
const MAX_SIZE = 500;
|
||||
const PAGE_SIZE = 50;
|
||||
|
||||
function createRecord<K>(key: K): EmptyRecord<K> {
|
||||
return {
|
||||
status: Empty,
|
||||
suspender: null,
|
||||
key,
|
||||
value: null,
|
||||
error: null,
|
||||
next: null,
|
||||
previous: null,
|
||||
};
|
||||
}
|
||||
|
||||
function createRecordCache<K, V>(): RecordCache<K, V> {
|
||||
return {
|
||||
map: new Map(),
|
||||
head: null,
|
||||
tail: null,
|
||||
size: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export function createCache(invalidator: () => mixed): Cache {
|
||||
const resourceMap: ResourceMap = new Map();
|
||||
|
||||
function accessRecord<K, V>(resourceType: any, key: K): Record<K, V> {
|
||||
if (__DEV__) {
|
||||
warningWithoutStack(
|
||||
typeof resourceType !== 'string' && typeof resourceType !== 'number',
|
||||
'Invalid resourceType: Expected a symbol, object, or function, but ' +
|
||||
'instead received: %s. Strings and numbers are not permitted as ' +
|
||||
'resource types.',
|
||||
resourceType,
|
||||
);
|
||||
}
|
||||
|
||||
let recordCache = resourceMap.get(resourceType);
|
||||
if (recordCache === undefined) {
|
||||
recordCache = createRecordCache();
|
||||
resourceMap.set(resourceType, recordCache);
|
||||
}
|
||||
const map = recordCache.map;
|
||||
|
||||
let record = map.get(key);
|
||||
if (record === undefined) {
|
||||
// This record does not already exist. Create a new one.
|
||||
record = createRecord(key);
|
||||
map.set(key, record);
|
||||
if (recordCache.size >= MAX_SIZE) {
|
||||
// The cache is already at maximum capacity. Remove PAGE_SIZE least
|
||||
// recently used records.
|
||||
// TODO: We assume the max capcity is greater than zero. Otherwise warn.
|
||||
const tail = recordCache.tail;
|
||||
if (tail !== null) {
|
||||
let newTail = tail;
|
||||
for (let i = 0; i < PAGE_SIZE && newTail !== null; i++) {
|
||||
recordCache.size -= 1;
|
||||
map.delete(newTail.key);
|
||||
newTail = newTail.previous;
|
||||
}
|
||||
recordCache.tail = newTail;
|
||||
if (newTail !== null) {
|
||||
newTail.next = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// This record is already cached. Remove it from its current position in
|
||||
// the list. We'll add it to the front below.
|
||||
const previous = record.previous;
|
||||
const next = record.next;
|
||||
if (previous !== null) {
|
||||
previous.next = next;
|
||||
} else {
|
||||
recordCache.head = next;
|
||||
}
|
||||
if (next !== null) {
|
||||
next.previous = previous;
|
||||
} else {
|
||||
recordCache.tail = previous;
|
||||
}
|
||||
recordCache.size -= 1;
|
||||
}
|
||||
|
||||
// Add the record to the front of the list.
|
||||
const head = recordCache.head;
|
||||
const newHead = record;
|
||||
recordCache.head = newHead;
|
||||
newHead.previous = null;
|
||||
newHead.next = head;
|
||||
if (head !== null) {
|
||||
head.previous = newHead;
|
||||
} else {
|
||||
recordCache.tail = newHead;
|
||||
}
|
||||
recordCache.size += 1;
|
||||
|
||||
return newHead;
|
||||
}
|
||||
|
||||
function load<K, V>(emptyRecord: EmptyRecord<K>, suspender: Promise<V>) {
|
||||
const pendingRecord: PendingRecord<K, V> = (emptyRecord: any);
|
||||
pendingRecord.status = Pending;
|
||||
pendingRecord.suspender = suspender;
|
||||
suspender.then(
|
||||
value => {
|
||||
// Resource loaded successfully.
|
||||
const resolvedRecord: ResolvedRecord<K, V> = (pendingRecord: any);
|
||||
resolvedRecord.status = Resolved;
|
||||
resolvedRecord.suspender = null;
|
||||
resolvedRecord.value = value;
|
||||
},
|
||||
error => {
|
||||
// Resource failed to load. Stash the error for later so we can throw it
|
||||
// the next time it's requested.
|
||||
const rejectedRecord: RejectedRecord<K> = (pendingRecord: any);
|
||||
rejectedRecord.status = Rejected;
|
||||
rejectedRecord.suspender = null;
|
||||
rejectedRecord.error = error;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const cache: Cache = {
|
||||
invalidate() {
|
||||
invalidator();
|
||||
},
|
||||
preload<K, V, A>(
|
||||
resourceType: any,
|
||||
key: K,
|
||||
miss: A => Promise<V>,
|
||||
missArg: A,
|
||||
): void {
|
||||
const record: Record<K, V> = accessRecord(resourceType, key);
|
||||
switch (record.status) {
|
||||
case Empty:
|
||||
// Warm the cache.
|
||||
const suspender = miss(missArg);
|
||||
load(record, suspender);
|
||||
return;
|
||||
case Pending:
|
||||
// There's already a pending request.
|
||||
return;
|
||||
case Resolved:
|
||||
// The resource is already in the cache.
|
||||
return;
|
||||
case Rejected:
|
||||
// The request failed.
|
||||
return;
|
||||
}
|
||||
},
|
||||
read<K, V, A>(
|
||||
resourceType: any,
|
||||
key: K,
|
||||
miss: A => Promise<V>,
|
||||
missArg: A,
|
||||
): V {
|
||||
const record: Record<K, V> = accessRecord(resourceType, key);
|
||||
switch (record.status) {
|
||||
case Empty:
|
||||
// Load the requested resource.
|
||||
const suspender = miss(missArg);
|
||||
load(record, suspender);
|
||||
throw suspender;
|
||||
case Pending:
|
||||
// There's already a pending request.
|
||||
throw record.suspender;
|
||||
case Resolved:
|
||||
return record.value;
|
||||
case Rejected:
|
||||
default:
|
||||
// The requested resource previously failed loading.
|
||||
const error = record.error;
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
if (__DEV__) {
|
||||
cache.$$typeof = CACHE_TYPE;
|
||||
}
|
||||
return cache;
|
||||
}
|
||||
|
||||
let warnIfNonPrimitiveKey;
|
||||
if (__DEV__) {
|
||||
warnIfNonPrimitiveKey = (key, methodName) => {
|
||||
warningWithoutStack(
|
||||
typeof input === 'string' ||
|
||||
typeof input === 'number' ||
|
||||
typeof input === 'boolean' ||
|
||||
input === undefined ||
|
||||
input === null,
|
||||
'Invalid key type. Expected a string, number, symbol, or boolean, ' +
|
||||
typeof key === 'string' ||
|
||||
typeof key === 'number' ||
|
||||
typeof key === 'boolean' ||
|
||||
key === undefined ||
|
||||
key === null,
|
||||
'%s: Invalid key type. Expected a string, number, symbol, or boolean, ' +
|
||||
'but instead received: %s' +
|
||||
'\n\nTo use non-primitive values as keys, you must pass a hash ' +
|
||||
'function as the second argument to createResource().',
|
||||
input,
|
||||
methodName,
|
||||
key,
|
||||
);
|
||||
}
|
||||
return input;
|
||||
};
|
||||
}
|
||||
|
||||
const CACHE_LIMIT = 500;
|
||||
const lru = createLRU(CACHE_LIMIT);
|
||||
type primitive = string | number | boolean | void | null;
|
||||
|
||||
const entries: Map<Resource<any, any>, Map<any, any>> = new Map();
|
||||
type Resource<K, V> = {|
|
||||
read(Cache, K): V,
|
||||
preload(cache: Cache, key: K): void,
|
||||
|};
|
||||
|
||||
const CacheContext = React.createContext(null);
|
||||
// These declarations are used to express function overloading. I wish there
|
||||
// were a more elegant way to do this in the function definition itself.
|
||||
|
||||
function accessResult<I, K, V>(
|
||||
resource: any,
|
||||
fetch: I => Thenable<V>,
|
||||
input: I,
|
||||
key: K,
|
||||
): Result<V> {
|
||||
let entriesForResource = entries.get(resource);
|
||||
if (entriesForResource === undefined) {
|
||||
entriesForResource = new Map();
|
||||
entries.set(resource, entriesForResource);
|
||||
}
|
||||
let entry = entriesForResource.get(key);
|
||||
if (entry === undefined) {
|
||||
const thenable = fetch(input);
|
||||
thenable.then(
|
||||
value => {
|
||||
if (newResult.status === Pending) {
|
||||
const resolvedResult: ResolvedResult<V> = (newResult: any);
|
||||
resolvedResult.status = Resolved;
|
||||
resolvedResult.value = value;
|
||||
}
|
||||
},
|
||||
error => {
|
||||
if (newResult.status === Pending) {
|
||||
const rejectedResult: RejectedResult = (newResult: any);
|
||||
rejectedResult.status = Rejected;
|
||||
rejectedResult.value = error;
|
||||
}
|
||||
},
|
||||
);
|
||||
const newResult: PendingResult = {
|
||||
status: Pending,
|
||||
value: thenable,
|
||||
};
|
||||
const newEntry = lru.add(newResult, deleteEntry.bind(null, resource, key));
|
||||
entriesForResource.set(key, newEntry);
|
||||
return newResult;
|
||||
} else {
|
||||
return (lru.access(entry): any);
|
||||
}
|
||||
}
|
||||
// Primitive keys do not request a hash function.
|
||||
declare function createResource<V, K: primitive, H: primitive>(
|
||||
loadResource: (K) => Promise<V>,
|
||||
hash?: (K) => H,
|
||||
): Resource<K, V>;
|
||||
|
||||
function deleteEntry(resource, key) {
|
||||
const entriesForResource = entries.get(resource);
|
||||
if (entriesForResource !== undefined) {
|
||||
entriesForResource.delete(key);
|
||||
if (entriesForResource.size === 0) {
|
||||
entries.delete(resource);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function unstable_createResource<I, K: string | number, V>(
|
||||
fetch: I => Thenable<V>,
|
||||
maybeHashInput?: I => K,
|
||||
): Resource<I, V> {
|
||||
const hashInput: I => K =
|
||||
maybeHashInput !== undefined ? maybeHashInput : (identityHashFn: any);
|
||||
// Non-primitive keys *do* require a hash function.
|
||||
// eslint-disable-next-line no-redeclare
|
||||
declare function createResource<V, K: mixed, H: primitive>(
|
||||
loadResource: (K) => Promise<V>,
|
||||
hash: (K) => H,
|
||||
): Resource<K, V>;
|
||||
|
||||
// eslint-disable-next-line no-redeclare
|
||||
export function createResource<V, K, H: primitive>(
|
||||
loadResource: K => Promise<V>,
|
||||
hash: K => H,
|
||||
): Resource<K, V> {
|
||||
const resource = {
|
||||
read(input: I): V {
|
||||
// react-cache currently doesn't rely on context, but it may in the
|
||||
// future, so we read anyway to prevent access outside of render.
|
||||
readContext(CacheContext);
|
||||
const key = hashInput(input);
|
||||
const result: Result<V> = accessResult(resource, fetch, input, key);
|
||||
switch (result.status) {
|
||||
case Pending: {
|
||||
const suspender = result.value;
|
||||
throw suspender;
|
||||
}
|
||||
case Resolved: {
|
||||
const value = result.value;
|
||||
return value;
|
||||
}
|
||||
case Rejected: {
|
||||
const error = result.value;
|
||||
throw error;
|
||||
}
|
||||
default:
|
||||
// Should be unreachable
|
||||
return (undefined: any);
|
||||
read(cache, key) {
|
||||
if (__DEV__) {
|
||||
warningWithoutStack(
|
||||
isCache(cache),
|
||||
'read(): The first argument must be a cache. Instead received: %s',
|
||||
cache,
|
||||
);
|
||||
}
|
||||
if (hash === undefined) {
|
||||
if (__DEV__) {
|
||||
warnIfNonPrimitiveKey(key, 'read');
|
||||
}
|
||||
return cache.read(resource, key, loadResource, key);
|
||||
}
|
||||
const hashedKey = hash(key);
|
||||
return cache.read(resource, hashedKey, loadResource, key);
|
||||
},
|
||||
|
||||
preload(input: I): void {
|
||||
// react-cache currently doesn't rely on context, but it may in the
|
||||
// future, so we read anyway to prevent access outside of render.
|
||||
readContext(CacheContext);
|
||||
const key = hashInput(input);
|
||||
accessResult(resource, fetch, input, key);
|
||||
preload(cache, key) {
|
||||
if (__DEV__) {
|
||||
warningWithoutStack(
|
||||
isCache(cache),
|
||||
'preload(): The first argument must be a cache. Instead received: %s',
|
||||
cache,
|
||||
);
|
||||
}
|
||||
if (hash === undefined) {
|
||||
if (__DEV__) {
|
||||
warnIfNonPrimitiveKey(key, 'preload');
|
||||
}
|
||||
cache.preload(resource, key, loadResource, key);
|
||||
return;
|
||||
}
|
||||
const hashedKey = hash(key);
|
||||
cache.preload(resource, hashedKey, loadResource, key);
|
||||
},
|
||||
};
|
||||
return resource;
|
||||
}
|
||||
|
||||
export function unstable_setGlobalCacheLimit(limit: number) {
|
||||
lru.setLimit(limit);
|
||||
}
|
||||
// Global cache has no eviction policy (except for, ya know, a browser refresh).
|
||||
const globalCache = createCache(noop);
|
||||
export const ReactCache = React.createContext(globalCache);
|
||||
|
||||
@@ -1,402 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) 2013-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @emails react-core
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
let ReactCache;
|
||||
let createResource;
|
||||
let React;
|
||||
let ReactFeatureFlags;
|
||||
let ReactTestRenderer;
|
||||
let Suspense;
|
||||
let TextResource;
|
||||
let textResourceShouldFail;
|
||||
let flushScheduledWork;
|
||||
let evictLRU;
|
||||
|
||||
describe('ReactCache', () => {
|
||||
beforeEach(() => {
|
||||
jest.resetModules();
|
||||
|
||||
jest.mock('scheduler', () => {
|
||||
let callbacks = [];
|
||||
return {
|
||||
unstable_scheduleCallback(callback) {
|
||||
const callbackIndex = callbacks.length;
|
||||
callbacks.push(callback);
|
||||
return {callbackIndex};
|
||||
},
|
||||
flushScheduledWork() {
|
||||
while (callbacks.length) {
|
||||
const callback = callbacks.pop();
|
||||
callback();
|
||||
}
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
ReactFeatureFlags = require('shared/ReactFeatureFlags');
|
||||
ReactFeatureFlags.debugRenderPhaseSideEffectsForStrictMode = false;
|
||||
ReactFeatureFlags.replayFailedUnitOfWorkWithInvokeGuardedCallback = false;
|
||||
React = require('react');
|
||||
Suspense = React.Suspense;
|
||||
ReactCache = require('react-cache');
|
||||
createResource = ReactCache.unstable_createResource;
|
||||
ReactTestRenderer = require('react-test-renderer');
|
||||
flushScheduledWork = require('scheduler').flushScheduledWork;
|
||||
evictLRU = flushScheduledWork;
|
||||
|
||||
TextResource = createResource(([text, ms = 0]) => {
|
||||
let listeners = null;
|
||||
let status = 'pending';
|
||||
let value = null;
|
||||
return {
|
||||
then(resolve, reject) {
|
||||
switch (status) {
|
||||
case 'pending': {
|
||||
if (listeners === null) {
|
||||
listeners = [{resolve, reject}];
|
||||
setTimeout(() => {
|
||||
if (textResourceShouldFail) {
|
||||
ReactTestRenderer.unstable_yield(
|
||||
`Promise rejected [${text}]`,
|
||||
);
|
||||
status = 'rejected';
|
||||
value = new Error('Failed to load: ' + text);
|
||||
listeners.forEach(listener => listener.reject(value));
|
||||
} else {
|
||||
ReactTestRenderer.unstable_yield(
|
||||
`Promise resolved [${text}]`,
|
||||
);
|
||||
status = 'resolved';
|
||||
value = text;
|
||||
listeners.forEach(listener => listener.resolve(value));
|
||||
}
|
||||
}, ms);
|
||||
} else {
|
||||
listeners.push({resolve, reject});
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'resolved': {
|
||||
resolve(value);
|
||||
break;
|
||||
}
|
||||
case 'rejected': {
|
||||
reject(value);
|
||||
break;
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
}, ([text, ms]) => text);
|
||||
|
||||
textResourceShouldFail = false;
|
||||
});
|
||||
|
||||
function Text(props) {
|
||||
ReactTestRenderer.unstable_yield(props.text);
|
||||
return props.text;
|
||||
}
|
||||
|
||||
function AsyncText(props) {
|
||||
const text = props.text;
|
||||
try {
|
||||
TextResource.read([props.text, props.ms]);
|
||||
ReactTestRenderer.unstable_yield(text);
|
||||
return text;
|
||||
} catch (promise) {
|
||||
if (typeof promise.then === 'function') {
|
||||
ReactTestRenderer.unstable_yield(`Suspend! [${text}]`);
|
||||
} else {
|
||||
ReactTestRenderer.unstable_yield(`Error! [${text}]`);
|
||||
}
|
||||
throw promise;
|
||||
}
|
||||
}
|
||||
|
||||
it('throws a promise if the requested value is not in the cache', () => {
|
||||
function App() {
|
||||
return (
|
||||
<Suspense fallback={<Text text="Loading..." />}>
|
||||
<AsyncText ms={100} text="Hi" />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
const root = ReactTestRenderer.create(<App />, {
|
||||
unstable_isConcurrent: true,
|
||||
});
|
||||
|
||||
expect(root).toFlushAndYield(['Suspend! [Hi]', 'Loading...']);
|
||||
|
||||
jest.advanceTimersByTime(100);
|
||||
expect(ReactTestRenderer).toHaveYielded(['Promise resolved [Hi]']);
|
||||
expect(root).toFlushAndYield(['Hi']);
|
||||
});
|
||||
|
||||
it('throws an error on the subsequent read if the promise is rejected', async () => {
|
||||
function App() {
|
||||
return (
|
||||
<Suspense fallback={<Text text="Loading..." />}>
|
||||
<AsyncText ms={100} text="Hi" />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
const root = ReactTestRenderer.create(<App />, {
|
||||
unstable_isConcurrent: true,
|
||||
});
|
||||
|
||||
expect(root).toFlushAndYield(['Suspend! [Hi]', 'Loading...']);
|
||||
|
||||
textResourceShouldFail = true;
|
||||
jest.advanceTimersByTime(100);
|
||||
expect(ReactTestRenderer).toHaveYielded(['Promise rejected [Hi]']);
|
||||
|
||||
expect(root).toFlushAndThrow('Failed to load: Hi');
|
||||
expect(ReactTestRenderer).toHaveYielded(['Error! [Hi]', 'Error! [Hi]']);
|
||||
|
||||
// Should throw again on a subsequent read
|
||||
root.update(<App />);
|
||||
expect(root).toFlushAndThrow('Failed to load: Hi');
|
||||
expect(ReactTestRenderer).toHaveYielded(['Error! [Hi]', 'Error! [Hi]']);
|
||||
});
|
||||
|
||||
it('warns if non-primitive key is passed to a resource without a hash function', () => {
|
||||
const BadTextResource = createResource(([text, ms = 0]) => {
|
||||
return new Promise((resolve, reject) =>
|
||||
setTimeout(() => {
|
||||
resolve(text);
|
||||
}, ms),
|
||||
);
|
||||
});
|
||||
|
||||
function App() {
|
||||
ReactTestRenderer.unstable_yield('App');
|
||||
return BadTextResource.read(['Hi', 100]);
|
||||
}
|
||||
|
||||
const root = ReactTestRenderer.create(
|
||||
<Suspense fallback={<Text text="Loading..." />}>
|
||||
<App />
|
||||
</Suspense>,
|
||||
{
|
||||
unstable_isConcurrent: true,
|
||||
},
|
||||
);
|
||||
|
||||
if (__DEV__) {
|
||||
expect(() => {
|
||||
expect(root).toFlushAndYield(['App', 'Loading...']);
|
||||
}).toWarnDev(
|
||||
[
|
||||
'Invalid key type. Expected a string, number, symbol, or ' +
|
||||
'boolean, but instead received: Hi,100\n\n' +
|
||||
'To use non-primitive values as keys, you must pass a hash ' +
|
||||
'function as the second argument to createResource().',
|
||||
],
|
||||
{withoutStack: true},
|
||||
);
|
||||
} else {
|
||||
expect(root).toFlushAndYield(['App', 'Loading...']);
|
||||
}
|
||||
});
|
||||
|
||||
it('evicts least recently used values', async () => {
|
||||
ReactCache.unstable_setGlobalCacheLimit(3);
|
||||
|
||||
// Render 1, 2, and 3
|
||||
const root = ReactTestRenderer.create(
|
||||
<Suspense fallback={<Text text="Loading..." />}>
|
||||
<AsyncText ms={100} text={1} />
|
||||
<AsyncText ms={100} text={2} />
|
||||
<AsyncText ms={100} text={3} />
|
||||
</Suspense>,
|
||||
{
|
||||
unstable_isConcurrent: true,
|
||||
},
|
||||
);
|
||||
expect(root).toFlushAndYield([
|
||||
'Suspend! [1]',
|
||||
'Suspend! [2]',
|
||||
'Suspend! [3]',
|
||||
'Loading...',
|
||||
]);
|
||||
jest.advanceTimersByTime(100);
|
||||
expect(ReactTestRenderer).toHaveYielded([
|
||||
'Promise resolved [1]',
|
||||
'Promise resolved [2]',
|
||||
'Promise resolved [3]',
|
||||
]);
|
||||
expect(root).toFlushAndYield([1, 2, 3]);
|
||||
expect(root).toMatchRenderedOutput('123');
|
||||
|
||||
// Render 1, 4, 5
|
||||
root.update(
|
||||
<Suspense fallback={<Text text="Loading..." />}>
|
||||
<AsyncText ms={100} text={1} />
|
||||
<AsyncText ms={100} text={4} />
|
||||
<AsyncText ms={100} text={5} />
|
||||
</Suspense>,
|
||||
);
|
||||
|
||||
expect(root).toFlushAndYield([
|
||||
1,
|
||||
'Suspend! [4]',
|
||||
'Suspend! [5]',
|
||||
'Loading...',
|
||||
]);
|
||||
jest.advanceTimersByTime(100);
|
||||
expect(ReactTestRenderer).toHaveYielded([
|
||||
'Promise resolved [4]',
|
||||
'Promise resolved [5]',
|
||||
]);
|
||||
expect(root).toFlushAndYield([1, 4, 5]);
|
||||
expect(root).toMatchRenderedOutput('145');
|
||||
|
||||
// We've now rendered values 1, 2, 3, 4, 5, over our limit of 3. The least
|
||||
// recently used values are 2 and 3. They will be evicted during the
|
||||
// next sweep.
|
||||
evictLRU();
|
||||
|
||||
root.update(
|
||||
<Suspense fallback={<Text text="Loading..." />}>
|
||||
<AsyncText ms={100} text={1} />
|
||||
<AsyncText ms={100} text={2} />
|
||||
<AsyncText ms={100} text={3} />
|
||||
</Suspense>,
|
||||
);
|
||||
|
||||
expect(root).toFlushAndYield([
|
||||
// 1 is still cached
|
||||
1,
|
||||
// 2 and 3 suspend because they were evicted from the cache
|
||||
'Suspend! [2]',
|
||||
'Suspend! [3]',
|
||||
'Loading...',
|
||||
]);
|
||||
jest.advanceTimersByTime(100);
|
||||
expect(ReactTestRenderer).toHaveYielded([
|
||||
'Promise resolved [2]',
|
||||
'Promise resolved [3]',
|
||||
]);
|
||||
expect(root).toFlushAndYield([1, 2, 3]);
|
||||
expect(root).toMatchRenderedOutput('123');
|
||||
});
|
||||
|
||||
it('preloads during the render phase', async () => {
|
||||
function App() {
|
||||
TextResource.preload(['B', 1000]);
|
||||
TextResource.read(['A', 1000]);
|
||||
TextResource.read(['B', 1000]);
|
||||
return <Text text="Result" />;
|
||||
}
|
||||
|
||||
const root = ReactTestRenderer.create(
|
||||
<Suspense fallback={<Text text="Loading..." />}>
|
||||
<App />
|
||||
</Suspense>,
|
||||
{
|
||||
unstable_isConcurrent: true,
|
||||
},
|
||||
);
|
||||
|
||||
expect(root).toFlushAndYield(['Loading...']);
|
||||
|
||||
jest.advanceTimersByTime(1000);
|
||||
expect(ReactTestRenderer).toHaveYielded([
|
||||
'Promise resolved [B]',
|
||||
'Promise resolved [A]',
|
||||
]);
|
||||
expect(root).toFlushAndYield(['Result']);
|
||||
expect(root).toMatchRenderedOutput('Result');
|
||||
});
|
||||
|
||||
it('if a thenable resolves multiple times, does not update the first cached value', () => {
|
||||
let resolveThenable;
|
||||
const BadTextResource = createResource(([text, ms = 0]) => {
|
||||
let listeners = null;
|
||||
let value = null;
|
||||
return {
|
||||
then(resolve, reject) {
|
||||
if (value !== null) {
|
||||
resolve(value);
|
||||
} else {
|
||||
if (listeners === null) {
|
||||
listeners = [resolve];
|
||||
resolveThenable = v => {
|
||||
listeners.forEach(listener => listener(v));
|
||||
};
|
||||
} else {
|
||||
listeners.push(resolve);
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
}, ([text, ms]) => text);
|
||||
|
||||
function BadAsyncText(props) {
|
||||
const text = props.text;
|
||||
try {
|
||||
const actualText = BadTextResource.read([props.text, props.ms]);
|
||||
ReactTestRenderer.unstable_yield(actualText);
|
||||
return actualText;
|
||||
} catch (promise) {
|
||||
if (typeof promise.then === 'function') {
|
||||
ReactTestRenderer.unstable_yield(`Suspend! [${text}]`);
|
||||
} else {
|
||||
ReactTestRenderer.unstable_yield(`Error! [${text}]`);
|
||||
}
|
||||
throw promise;
|
||||
}
|
||||
}
|
||||
|
||||
const root = ReactTestRenderer.create(
|
||||
<Suspense fallback={<Text text="Loading..." />}>
|
||||
<BadAsyncText text="Hi" />
|
||||
</Suspense>,
|
||||
{
|
||||
unstable_isConcurrent: true,
|
||||
},
|
||||
);
|
||||
|
||||
expect(root).toFlushAndYield(['Suspend! [Hi]', 'Loading...']);
|
||||
|
||||
resolveThenable('Hi');
|
||||
// This thenable improperly resolves twice. We should not update the
|
||||
// cached value.
|
||||
resolveThenable('Hi muahahaha I am different');
|
||||
|
||||
root.update(
|
||||
<Suspense fallback={<Text text="Loading..." />}>
|
||||
<BadAsyncText text="Hi" />
|
||||
</Suspense>,
|
||||
{
|
||||
unstable_isConcurrent: true,
|
||||
},
|
||||
);
|
||||
|
||||
expect(ReactTestRenderer).toHaveYielded([]);
|
||||
expect(root).toFlushAndYield(['Hi']);
|
||||
expect(root).toMatchRenderedOutput('Hi');
|
||||
});
|
||||
|
||||
it('throws if read is called outside render', () => {
|
||||
expect(() => TextResource.read(['A', 1000])).toThrow(
|
||||
"read and preload may only be called from within a component's render",
|
||||
);
|
||||
});
|
||||
|
||||
it('throws if preload is called outside render', () => {
|
||||
expect(() => TextResource.preload(['A', 1000])).toThrow(
|
||||
"read and preload may only be called from within a component's render",
|
||||
);
|
||||
});
|
||||
});
|
||||
235
packages/react-cache/src/__tests__/ReactCache-test.js
vendored
Normal file
235
packages/react-cache/src/__tests__/ReactCache-test.js
vendored
Normal file
@@ -0,0 +1,235 @@
|
||||
/**
|
||||
* Copyright (c) Facebook, Inc. and its affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @emails react-core
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
let ReactCache;
|
||||
|
||||
describe('ReactCache', () => {
|
||||
beforeEach(() => {
|
||||
jest.resetModules();
|
||||
ReactCache = require('react-cache');
|
||||
});
|
||||
|
||||
it('throws a promise if the requested value is not in the cache', async () => {
|
||||
const {createCache, createResource} = ReactCache;
|
||||
|
||||
function loadUpperCase(text) {
|
||||
return Promise.resolve(text.toUpperCase());
|
||||
}
|
||||
const UpperCase = createResource(loadUpperCase);
|
||||
const cache = createCache();
|
||||
|
||||
let suspender;
|
||||
try {
|
||||
UpperCase.read(cache, 'hello');
|
||||
} catch (v) {
|
||||
suspender = v;
|
||||
}
|
||||
|
||||
await suspender;
|
||||
const result = UpperCase.read(cache, 'hello');
|
||||
expect(result).toBe('HELLO');
|
||||
});
|
||||
|
||||
it('throws an error on the subsequent read if the promise is rejected', async () => {
|
||||
const {createCache, createResource} = ReactCache;
|
||||
|
||||
let shouldFail = true;
|
||||
function loadUpperCase(text) {
|
||||
if (shouldFail) {
|
||||
// Rejects on the first try
|
||||
shouldFail = false;
|
||||
return Promise.reject(new Error('oh no'));
|
||||
} else {
|
||||
// Succeeds the second time
|
||||
return Promise.resolve(text.toUpperCase());
|
||||
}
|
||||
}
|
||||
const UpperCase = createResource(loadUpperCase);
|
||||
const cache = createCache();
|
||||
|
||||
let suspender;
|
||||
try {
|
||||
UpperCase.read(cache, 'hello');
|
||||
} catch (v) {
|
||||
suspender = v;
|
||||
}
|
||||
|
||||
let error;
|
||||
try {
|
||||
await suspender;
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(() => UpperCase.read(cache, 'hello')).toThrow(error);
|
||||
expect(error.message).toBe('oh no');
|
||||
|
||||
// On a subsequent read, it should still throw.
|
||||
try {
|
||||
UpperCase.read(cache, 'hello');
|
||||
} catch (v) {
|
||||
suspender = v;
|
||||
}
|
||||
await suspender;
|
||||
expect(() => UpperCase.read(cache, 'hello')).toThrow(error);
|
||||
expect(error.message).toBe('oh no');
|
||||
});
|
||||
|
||||
it('can preload data ahead of time', async () => {
|
||||
const {createCache, createResource} = ReactCache;
|
||||
|
||||
function loadUpperCase(text) {
|
||||
return Promise.resolve(text.toUpperCase());
|
||||
}
|
||||
const UpperCase = createResource(loadUpperCase);
|
||||
const cache = createCache();
|
||||
|
||||
UpperCase.preload(cache, 'hello');
|
||||
// Wait for next tick
|
||||
await Promise.resolve();
|
||||
const result = UpperCase.read(cache, 'hello');
|
||||
expect(result).toBe('HELLO');
|
||||
});
|
||||
|
||||
it('does not throw if preloaded promise rejects', async () => {
|
||||
const {createCache, createResource} = ReactCache;
|
||||
|
||||
function loadUpperCase(text) {
|
||||
return Promise.reject(new Error('uh oh'));
|
||||
}
|
||||
const UpperCase = createResource(loadUpperCase);
|
||||
const cache = createCache();
|
||||
|
||||
UpperCase.preload(cache, 'hello');
|
||||
// Wait for next tick
|
||||
await Promise.resolve();
|
||||
|
||||
expect(() => UpperCase.read(cache, 'hello')).toThrow('uh oh');
|
||||
});
|
||||
|
||||
it('accepts custom hash function', async () => {
|
||||
const {createCache, createResource} = ReactCache;
|
||||
|
||||
function loadSum([a, b]) {
|
||||
return Promise.resolve(a + b);
|
||||
}
|
||||
function hash([a, b]) {
|
||||
return `${a + b}`;
|
||||
}
|
||||
const Sum = createResource(loadSum, hash);
|
||||
const cache = createCache();
|
||||
|
||||
Sum.preload(cache, [5, 5]);
|
||||
Sum.preload(cache, [1, 2]);
|
||||
await Promise.resolve();
|
||||
|
||||
expect(Sum.read(cache, [5, 5])).toEqual(10);
|
||||
expect(Sum.read(cache, [1, 2])).toEqual(3);
|
||||
// The fact that the next line returns synchronously and doesn't throw, even
|
||||
// though [3, 7] was not preloaded, proves that the hashing function works.
|
||||
expect(Sum.read(cache, [3, 7])).toEqual(10);
|
||||
});
|
||||
|
||||
it('warns if resourceType is a string or number', () => {
|
||||
const {createCache} = ReactCache;
|
||||
|
||||
spyOnDev(console, 'error');
|
||||
const cache = createCache();
|
||||
|
||||
function fn() {
|
||||
cache.preload('foo', 'uppercaseA', () => Promise.resolve('A'));
|
||||
cache.preload(123, 'productOf9And2', () => Promise.resolve(18));
|
||||
}
|
||||
|
||||
if (__DEV__) {
|
||||
expect(fn).toWarnDev(
|
||||
[
|
||||
'Invalid resourceType: Expected a symbol, object, or function, but ' +
|
||||
'instead received: foo. Strings and numbers are not permitted as ' +
|
||||
'resource types.',
|
||||
'Invalid resourceType: Expected a symbol, object, or function, but ' +
|
||||
'instead received: 123. Strings and numbers are not permitted as ' +
|
||||
'resource types.',
|
||||
],
|
||||
{withoutStack: true},
|
||||
);
|
||||
} else {
|
||||
fn();
|
||||
}
|
||||
});
|
||||
|
||||
it('warns if non-primitive key is passed to a resource without a hash function', () => {
|
||||
const {createCache, createResource} = ReactCache;
|
||||
|
||||
spyOnDev(console, 'error');
|
||||
|
||||
function loadSum([a, b]) {
|
||||
return Promise.resolve(a + b);
|
||||
}
|
||||
|
||||
const Sum = createResource(loadSum);
|
||||
const cache = createCache();
|
||||
|
||||
function fn() {
|
||||
Sum.preload(cache, [5, 5]);
|
||||
}
|
||||
|
||||
if (__DEV__) {
|
||||
expect(fn).toWarnDev(
|
||||
[
|
||||
'preload: Invalid key type. Expected a string, number, symbol, or ' +
|
||||
'boolean, but instead received: 5,5\n\n' +
|
||||
'To use non-primitive values as keys, you must pass a hash ' +
|
||||
'function as the second argument to createResource().',
|
||||
],
|
||||
{withoutStack: true},
|
||||
);
|
||||
} else {
|
||||
fn();
|
||||
}
|
||||
});
|
||||
|
||||
it('stays within maximum capacity by evicting the least recently used record', async () => {
|
||||
const {createCache, createResource} = ReactCache;
|
||||
|
||||
function loadIntegerString(int) {
|
||||
return Promise.resolve(int + '');
|
||||
}
|
||||
const IntegerStringResource = createResource(loadIntegerString);
|
||||
const cache = createCache();
|
||||
|
||||
// TODO: This is hard-coded to a maximum size of 500. Make this configurable
|
||||
// per resource.
|
||||
for (let n = 1; n <= 500; n++) {
|
||||
IntegerStringResource.preload(cache, n);
|
||||
}
|
||||
|
||||
// Access 1, 2, and 3 again. The least recently used integer is now 4.
|
||||
IntegerStringResource.preload(cache, 3);
|
||||
IntegerStringResource.preload(cache, 2);
|
||||
IntegerStringResource.preload(cache, 1);
|
||||
|
||||
// Evict older integers from the cache by adding new ones.
|
||||
IntegerStringResource.preload(cache, 501);
|
||||
IntegerStringResource.preload(cache, 502);
|
||||
IntegerStringResource.preload(cache, 503);
|
||||
|
||||
await Promise.resolve();
|
||||
|
||||
// 1, 2, and 3 should be in the cache. 4, 5, and 6 should have been evicted.
|
||||
expect(IntegerStringResource.read(cache, 1)).toEqual('1');
|
||||
expect(IntegerStringResource.read(cache, 2)).toEqual('2');
|
||||
expect(IntegerStringResource.read(cache, 3)).toEqual('3');
|
||||
|
||||
expect(() => IntegerStringResource.read(cache, 4)).toThrow(Promise);
|
||||
expect(() => IntegerStringResource.read(cache, 5)).toThrow(Promise);
|
||||
expect(() => IntegerStringResource.read(cache, 6)).toThrow(Promise);
|
||||
});
|
||||
});
|
||||
@@ -1,7 +0,0 @@
|
||||
# react-debug-tools
|
||||
|
||||
This is an experimental package for debugging React renderers.
|
||||
|
||||
**Its API is not as stable as that of React, React Native, or React DOM, and does not follow the common versioning scheme.**
|
||||
|
||||
**Use it at your own risk.**
|
||||
13
packages/react-debug-tools/index.js
vendored
13
packages/react-debug-tools/index.js
vendored
@@ -1,13 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) Facebook, Inc. and its affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
const ReactDebugTools = require('./src/ReactDebugTools');
|
||||
|
||||
// This is hacky but makes it work with both Rollup and Jest.
|
||||
module.exports = ReactDebugTools.default || ReactDebugTools;
|
||||
7
packages/react-debug-tools/npm/index.js
vendored
7
packages/react-debug-tools/npm/index.js
vendored
@@ -1,7 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
module.exports = require('./cjs/react-debug-tools.production.min.js');
|
||||
} else {
|
||||
module.exports = require('./cjs/react-debug-tools.development.js');
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "react-debug-tools",
|
||||
"description": "React package for debugging React trees.",
|
||||
"version": "0.16.0",
|
||||
"keywords": [
|
||||
"react"
|
||||
],
|
||||
"homepage": "https://reactjs.org/",
|
||||
"bugs": "https://github.com/facebook/react/issues",
|
||||
"license": "MIT",
|
||||
"files": [
|
||||
"LICENSE",
|
||||
"README.md",
|
||||
"build-info.json",
|
||||
"index.js",
|
||||
"cjs/"
|
||||
],
|
||||
"main": "index.js",
|
||||
"repository": "facebook/react",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^16.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"error-stack-parser": "^2.0.2"
|
||||
}
|
||||
}
|
||||
516
packages/react-debug-tools/src/ReactDebugHooks.js
vendored
516
packages/react-debug-tools/src/ReactDebugHooks.js
vendored
@@ -1,516 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) Facebook, Inc. and its affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow
|
||||
*/
|
||||
|
||||
import type {ReactContext, ReactProviderType} from 'shared/ReactTypes';
|
||||
import type {Fiber} from 'react-reconciler/src/ReactFiber';
|
||||
import type {Hook} from 'react-reconciler/src/ReactFiberHooks';
|
||||
|
||||
import ErrorStackParser from 'error-stack-parser';
|
||||
import ReactSharedInternals from 'shared/ReactSharedInternals';
|
||||
import {
|
||||
FunctionComponent,
|
||||
SimpleMemoComponent,
|
||||
ContextProvider,
|
||||
ForwardRef,
|
||||
} from 'shared/ReactWorkTags';
|
||||
|
||||
const ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
|
||||
|
||||
// Used to track hooks called during a render
|
||||
|
||||
type HookLogEntry = {
|
||||
primitive: string,
|
||||
stackError: Error,
|
||||
value: mixed,
|
||||
};
|
||||
|
||||
let hookLog: Array<HookLogEntry> = [];
|
||||
|
||||
// Primitives
|
||||
|
||||
type BasicStateAction<S> = (S => S) | S;
|
||||
|
||||
type Dispatch<A> = A => void;
|
||||
|
||||
let primitiveStackCache: null | Map<string, Array<any>> = null;
|
||||
|
||||
function getPrimitiveStackCache(): Map<string, Array<any>> {
|
||||
// This initializes a cache of all primitive hooks so that the top
|
||||
// most stack frames added by calling the primitive hook can be removed.
|
||||
if (primitiveStackCache === null) {
|
||||
let cache = new Map();
|
||||
let readHookLog;
|
||||
try {
|
||||
// Use all hooks here to add them to the hook log.
|
||||
Dispatcher.useContext(({_currentValue: null}: any));
|
||||
Dispatcher.useState(null);
|
||||
Dispatcher.useReducer((s, a) => s, null);
|
||||
Dispatcher.useRef(null);
|
||||
Dispatcher.useLayoutEffect(() => {});
|
||||
Dispatcher.useEffect(() => {});
|
||||
Dispatcher.useImperativeMethods(undefined, () => null);
|
||||
Dispatcher.useCallback(() => {});
|
||||
Dispatcher.useMemo(() => null);
|
||||
} finally {
|
||||
readHookLog = hookLog;
|
||||
hookLog = [];
|
||||
}
|
||||
for (let i = 0; i < readHookLog.length; i++) {
|
||||
let hook = readHookLog[i];
|
||||
cache.set(hook.primitive, ErrorStackParser.parse(hook.stackError));
|
||||
}
|
||||
primitiveStackCache = cache;
|
||||
}
|
||||
return primitiveStackCache;
|
||||
}
|
||||
|
||||
let currentHook: null | Hook = null;
|
||||
function nextHook(): null | Hook {
|
||||
let hook = currentHook;
|
||||
if (hook !== null) {
|
||||
currentHook = hook.next;
|
||||
}
|
||||
return hook;
|
||||
}
|
||||
|
||||
function readContext<T>(
|
||||
context: ReactContext<T>,
|
||||
observedBits: void | number | boolean,
|
||||
): T {
|
||||
// For now we don't expose readContext usage in the hooks debugging info.
|
||||
return context._currentValue;
|
||||
}
|
||||
|
||||
function useContext<T>(
|
||||
context: ReactContext<T>,
|
||||
observedBits: void | number | boolean,
|
||||
): T {
|
||||
hookLog.push({
|
||||
primitive: 'Context',
|
||||
stackError: new Error(),
|
||||
value: context._currentValue,
|
||||
});
|
||||
return context._currentValue;
|
||||
}
|
||||
|
||||
function useState<S>(
|
||||
initialState: (() => S) | S,
|
||||
): [S, Dispatch<BasicStateAction<S>>] {
|
||||
let hook = nextHook();
|
||||
let state: S =
|
||||
hook !== null
|
||||
? hook.memoizedState
|
||||
: typeof initialState === 'function'
|
||||
? initialState()
|
||||
: initialState;
|
||||
hookLog.push({primitive: 'State', stackError: new Error(), value: state});
|
||||
return [state, (action: BasicStateAction<S>) => {}];
|
||||
}
|
||||
|
||||
function useReducer<S, A>(
|
||||
reducer: (S, A) => S,
|
||||
initialState: S,
|
||||
initialAction: A | void | null,
|
||||
): [S, Dispatch<A>] {
|
||||
let hook = nextHook();
|
||||
let state = hook !== null ? hook.memoizedState : initialState;
|
||||
hookLog.push({
|
||||
primitive: 'Reducer',
|
||||
stackError: new Error(),
|
||||
value: state,
|
||||
});
|
||||
return [state, (action: A) => {}];
|
||||
}
|
||||
|
||||
function useRef<T>(initialValue: T): {current: T} {
|
||||
let hook = nextHook();
|
||||
let ref = hook !== null ? hook.memoizedState : {current: initialValue};
|
||||
hookLog.push({
|
||||
primitive: 'Ref',
|
||||
stackError: new Error(),
|
||||
value: ref.current,
|
||||
});
|
||||
return ref;
|
||||
}
|
||||
|
||||
function useLayoutEffect(
|
||||
create: () => mixed,
|
||||
inputs: Array<mixed> | void | null,
|
||||
): void {
|
||||
nextHook();
|
||||
hookLog.push({
|
||||
primitive: 'LayoutEffect',
|
||||
stackError: new Error(),
|
||||
value: create,
|
||||
});
|
||||
}
|
||||
|
||||
function useEffect(
|
||||
create: () => mixed,
|
||||
inputs: Array<mixed> | void | null,
|
||||
): void {
|
||||
nextHook();
|
||||
hookLog.push({primitive: 'Effect', stackError: new Error(), value: create});
|
||||
}
|
||||
|
||||
function useImperativeMethods<T>(
|
||||
ref: {current: T | null} | ((inst: T | null) => mixed) | null | void,
|
||||
create: () => T,
|
||||
inputs: Array<mixed> | void | null,
|
||||
): void {
|
||||
nextHook();
|
||||
// We don't actually store the instance anywhere if there is no ref callback
|
||||
// and if there is a ref callback it might not store it but if it does we
|
||||
// have no way of knowing where. So let's only enable introspection of the
|
||||
// ref itself if it is using the object form.
|
||||
let instance = undefined;
|
||||
if (ref !== null && typeof ref === 'object') {
|
||||
instance = ref.current;
|
||||
}
|
||||
hookLog.push({
|
||||
primitive: 'ImperativeMethods',
|
||||
stackError: new Error(),
|
||||
value: instance,
|
||||
});
|
||||
}
|
||||
|
||||
function useCallback<T>(callback: T, inputs: Array<mixed> | void | null): T {
|
||||
let hook = nextHook();
|
||||
hookLog.push({
|
||||
primitive: 'Callback',
|
||||
stackError: new Error(),
|
||||
value: hook !== null ? hook.memoizedState[0] : callback,
|
||||
});
|
||||
return callback;
|
||||
}
|
||||
|
||||
function useMemo<T>(
|
||||
nextCreate: () => T,
|
||||
inputs: Array<mixed> | void | null,
|
||||
): T {
|
||||
let hook = nextHook();
|
||||
let value = hook !== null ? hook.memoizedState[0] : nextCreate();
|
||||
hookLog.push({primitive: 'Memo', stackError: new Error(), value});
|
||||
return value;
|
||||
}
|
||||
|
||||
const Dispatcher = {
|
||||
readContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useImperativeMethods,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useReducer,
|
||||
useRef,
|
||||
useState,
|
||||
};
|
||||
|
||||
// Inspect
|
||||
|
||||
type HooksNode = {
|
||||
name: string,
|
||||
value: mixed,
|
||||
subHooks: Array<HooksNode>,
|
||||
};
|
||||
type HooksTree = Array<HooksNode>;
|
||||
|
||||
// Don't assume
|
||||
//
|
||||
// We can't assume that stack frames are nth steps away from anything.
|
||||
// E.g. we can't assume that the root call shares all frames with the stack
|
||||
// of a hook call. A simple way to demonstrate this is wrapping `new Error()`
|
||||
// in a wrapper constructor like a polyfill. That'll add an extra frame.
|
||||
// Similar things can happen with the call to the dispatcher. The top frame
|
||||
// may not be the primitive. Likewise the primitive can have fewer stack frames
|
||||
// such as when a call to useState got inlined to use dispatcher.useState.
|
||||
//
|
||||
// We also can't assume that the last frame of the root call is the same
|
||||
// frame as the last frame of the hook call because long stack traces can be
|
||||
// truncated to a stack trace limit.
|
||||
|
||||
let mostLikelyAncestorIndex = 0;
|
||||
|
||||
function findSharedIndex(hookStack, rootStack, rootIndex) {
|
||||
let source = rootStack[rootIndex].source;
|
||||
hookSearch: for (let i = 0; i < hookStack.length; i++) {
|
||||
if (hookStack[i].source === source) {
|
||||
// This looks like a match. Validate that the rest of both stack match up.
|
||||
for (
|
||||
let a = rootIndex + 1, b = i + 1;
|
||||
a < rootStack.length && b < hookStack.length;
|
||||
a++, b++
|
||||
) {
|
||||
if (hookStack[b].source !== rootStack[a].source) {
|
||||
// If not, give up and try a different match.
|
||||
continue hookSearch;
|
||||
}
|
||||
}
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function findCommonAncestorIndex(rootStack, hookStack) {
|
||||
let rootIndex = findSharedIndex(
|
||||
hookStack,
|
||||
rootStack,
|
||||
mostLikelyAncestorIndex,
|
||||
);
|
||||
if (rootIndex !== -1) {
|
||||
return rootIndex;
|
||||
}
|
||||
// If the most likely one wasn't a hit, try any other frame to see if it is shared.
|
||||
// If that takes more than 5 frames, something probably went wrong.
|
||||
for (let i = 0; i < rootStack.length && i < 5; i++) {
|
||||
rootIndex = findSharedIndex(hookStack, rootStack, i);
|
||||
if (rootIndex !== -1) {
|
||||
mostLikelyAncestorIndex = i;
|
||||
return rootIndex;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function isReactWrapper(functionName, primitiveName) {
|
||||
if (!functionName) {
|
||||
return false;
|
||||
}
|
||||
let expectedPrimitiveName = 'use' + primitiveName;
|
||||
if (functionName.length < expectedPrimitiveName.length) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
functionName.lastIndexOf(expectedPrimitiveName) ===
|
||||
functionName.length - expectedPrimitiveName.length
|
||||
);
|
||||
}
|
||||
|
||||
function findPrimitiveIndex(hookStack, hook) {
|
||||
let stackCache = getPrimitiveStackCache();
|
||||
let primitiveStack = stackCache.get(hook.primitive);
|
||||
if (primitiveStack === undefined) {
|
||||
return -1;
|
||||
}
|
||||
for (let i = 0; i < primitiveStack.length && i < hookStack.length; i++) {
|
||||
if (primitiveStack[i].source !== hookStack[i].source) {
|
||||
// If the next two frames are functions called `useX` then we assume that they're part of the
|
||||
// wrappers that the React packager or other packages adds around the dispatcher.
|
||||
if (
|
||||
i < hookStack.length - 1 &&
|
||||
isReactWrapper(hookStack[i].functionName, hook.primitive)
|
||||
) {
|
||||
i++;
|
||||
}
|
||||
if (
|
||||
i < hookStack.length - 1 &&
|
||||
isReactWrapper(hookStack[i].functionName, hook.primitive)
|
||||
) {
|
||||
i++;
|
||||
}
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function parseTrimmedStack(rootStack, hook) {
|
||||
// Get the stack trace between the primitive hook function and
|
||||
// the root function call. I.e. the stack frames of custom hooks.
|
||||
let hookStack = ErrorStackParser.parse(hook.stackError);
|
||||
let rootIndex = findCommonAncestorIndex(rootStack, hookStack);
|
||||
let primitiveIndex = findPrimitiveIndex(hookStack, hook);
|
||||
if (
|
||||
rootIndex === -1 ||
|
||||
primitiveIndex === -1 ||
|
||||
rootIndex - primitiveIndex < 2
|
||||
) {
|
||||
// Something went wrong. Give up.
|
||||
return null;
|
||||
}
|
||||
return hookStack.slice(primitiveIndex, rootIndex - 1);
|
||||
}
|
||||
|
||||
function parseCustomHookName(functionName: void | string): string {
|
||||
if (!functionName) {
|
||||
return '';
|
||||
}
|
||||
let startIndex = functionName.lastIndexOf('.');
|
||||
if (startIndex === -1) {
|
||||
startIndex = 0;
|
||||
}
|
||||
if (functionName.substr(startIndex, 3) === 'use') {
|
||||
startIndex += 3;
|
||||
}
|
||||
return functionName.substr(startIndex);
|
||||
}
|
||||
|
||||
function buildTree(rootStack, readHookLog): HooksTree {
|
||||
let rootChildren = [];
|
||||
let prevStack = null;
|
||||
let levelChildren = rootChildren;
|
||||
let stackOfChildren = [];
|
||||
for (let i = 0; i < readHookLog.length; i++) {
|
||||
let hook = readHookLog[i];
|
||||
let stack = parseTrimmedStack(rootStack, hook);
|
||||
if (stack !== null) {
|
||||
// Note: The indices 0 <= n < length-1 will contain the names.
|
||||
// The indices 1 <= n < length will contain the source locations.
|
||||
// That's why we get the name from n - 1 and don't check the source
|
||||
// of index 0.
|
||||
let commonSteps = 0;
|
||||
if (prevStack !== null) {
|
||||
// Compare the current level's stack to the new stack.
|
||||
while (commonSteps < stack.length && commonSteps < prevStack.length) {
|
||||
let stackSource = stack[stack.length - commonSteps - 1].source;
|
||||
let prevSource = prevStack[prevStack.length - commonSteps - 1].source;
|
||||
if (stackSource !== prevSource) {
|
||||
break;
|
||||
}
|
||||
commonSteps++;
|
||||
}
|
||||
// Pop back the stack as many steps as were not common.
|
||||
for (let j = prevStack.length - 1; j > commonSteps; j--) {
|
||||
levelChildren = stackOfChildren.pop();
|
||||
}
|
||||
}
|
||||
// The remaining part of the new stack are custom hooks. Push them
|
||||
// to the tree.
|
||||
for (let j = stack.length - commonSteps - 1; j >= 1; j--) {
|
||||
let children = [];
|
||||
levelChildren.push({
|
||||
name: parseCustomHookName(stack[j - 1].functionName),
|
||||
value: undefined, // TODO: Support custom inspectable values.
|
||||
subHooks: children,
|
||||
});
|
||||
stackOfChildren.push(levelChildren);
|
||||
levelChildren = children;
|
||||
}
|
||||
prevStack = stack;
|
||||
}
|
||||
levelChildren.push({
|
||||
name: hook.primitive,
|
||||
value: hook.value,
|
||||
subHooks: [],
|
||||
});
|
||||
}
|
||||
return rootChildren;
|
||||
}
|
||||
|
||||
export function inspectHooks<Props>(
|
||||
renderFunction: Props => React$Node,
|
||||
props: Props,
|
||||
): HooksTree {
|
||||
let previousDispatcher = ReactCurrentOwner.currentDispatcher;
|
||||
let readHookLog;
|
||||
ReactCurrentOwner.currentDispatcher = Dispatcher;
|
||||
let ancestorStackError;
|
||||
try {
|
||||
ancestorStackError = new Error();
|
||||
renderFunction(props);
|
||||
} finally {
|
||||
readHookLog = hookLog;
|
||||
hookLog = [];
|
||||
ReactCurrentOwner.currentDispatcher = previousDispatcher;
|
||||
}
|
||||
let rootStack = ErrorStackParser.parse(ancestorStackError);
|
||||
return buildTree(rootStack, readHookLog);
|
||||
}
|
||||
|
||||
function setupContexts(contextMap: Map<ReactContext<any>, any>, fiber: Fiber) {
|
||||
let current = fiber;
|
||||
while (current) {
|
||||
if (current.tag === ContextProvider) {
|
||||
const providerType: ReactProviderType<any> = current.type;
|
||||
const context: ReactContext<any> = providerType._context;
|
||||
if (!contextMap.has(context)) {
|
||||
// Store the current value that we're going to restore later.
|
||||
contextMap.set(context, context._currentValue);
|
||||
// Set the inner most provider value on the context.
|
||||
context._currentValue = current.memoizedProps.value;
|
||||
}
|
||||
}
|
||||
current = current.return;
|
||||
}
|
||||
}
|
||||
|
||||
function restoreContexts(contextMap: Map<ReactContext<any>, any>) {
|
||||
contextMap.forEach((value, context) => (context._currentValue = value));
|
||||
}
|
||||
|
||||
function inspectHooksOfForwardRef<Props, Ref>(
|
||||
renderFunction: (Props, Ref) => React$Node,
|
||||
props: Props,
|
||||
ref: Ref,
|
||||
): HooksTree {
|
||||
let previousDispatcher = ReactCurrentOwner.currentDispatcher;
|
||||
let readHookLog;
|
||||
ReactCurrentOwner.currentDispatcher = Dispatcher;
|
||||
let ancestorStackError;
|
||||
try {
|
||||
ancestorStackError = new Error();
|
||||
renderFunction(props, ref);
|
||||
} finally {
|
||||
readHookLog = hookLog;
|
||||
hookLog = [];
|
||||
ReactCurrentOwner.currentDispatcher = previousDispatcher;
|
||||
}
|
||||
let rootStack = ErrorStackParser.parse(ancestorStackError);
|
||||
return buildTree(rootStack, readHookLog);
|
||||
}
|
||||
|
||||
function resolveDefaultProps(Component, baseProps) {
|
||||
if (Component && Component.defaultProps) {
|
||||
// Resolve default props. Taken from ReactElement
|
||||
const props = Object.assign({}, baseProps);
|
||||
const defaultProps = Component.defaultProps;
|
||||
for (let propName in defaultProps) {
|
||||
if (props[propName] === undefined) {
|
||||
props[propName] = defaultProps[propName];
|
||||
}
|
||||
}
|
||||
return props;
|
||||
}
|
||||
return baseProps;
|
||||
}
|
||||
|
||||
export function inspectHooksOfFiber(fiber: Fiber) {
|
||||
if (
|
||||
fiber.tag !== FunctionComponent &&
|
||||
fiber.tag !== SimpleMemoComponent &&
|
||||
fiber.tag !== ForwardRef
|
||||
) {
|
||||
throw new Error(
|
||||
'Unknown Fiber. Needs to be a function component to inspect hooks.',
|
||||
);
|
||||
}
|
||||
// Warm up the cache so that it doesn't consume the currentHook.
|
||||
getPrimitiveStackCache();
|
||||
let type = fiber.type;
|
||||
let props = fiber.memoizedProps;
|
||||
if (type !== fiber.elementType) {
|
||||
props = resolveDefaultProps(type, props);
|
||||
}
|
||||
// Set up the current hook so that we can step through and read the
|
||||
// current state from them.
|
||||
currentHook = (fiber.memoizedState: Hook);
|
||||
let contextMap = new Map();
|
||||
try {
|
||||
setupContexts(contextMap, fiber);
|
||||
if (fiber.tag === ForwardRef) {
|
||||
return inspectHooksOfForwardRef(type.render, props, fiber.ref);
|
||||
}
|
||||
return inspectHooks(type, props);
|
||||
} finally {
|
||||
currentHook = null;
|
||||
restoreContexts(contextMap);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) Facebook, Inc. and its affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow
|
||||
*/
|
||||
|
||||
import {inspectHooks, inspectHooksOfFiber} from './ReactDebugHooks';
|
||||
|
||||
export {inspectHooks, inspectHooksOfFiber};
|
||||
@@ -1,219 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) Facebook, Inc. and its affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @emails react-core
|
||||
* @jest-environment node
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
let React;
|
||||
let ReactDebugTools;
|
||||
|
||||
describe('ReactHooksInspection', () => {
|
||||
beforeEach(() => {
|
||||
jest.resetModules();
|
||||
let ReactFeatureFlags = require('shared/ReactFeatureFlags');
|
||||
// TODO: Switch this test to non-internal once the flag is on by default.
|
||||
ReactFeatureFlags.enableHooks = true;
|
||||
React = require('react');
|
||||
ReactDebugTools = require('react-debug-tools');
|
||||
});
|
||||
|
||||
it('should inspect a simple useState hook', () => {
|
||||
function Foo(props) {
|
||||
let [state] = React.useState('hello world');
|
||||
return <div>{state}</div>;
|
||||
}
|
||||
let tree = ReactDebugTools.inspectHooks(Foo, {});
|
||||
expect(tree).toEqual([
|
||||
{
|
||||
name: 'State',
|
||||
value: 'hello world',
|
||||
subHooks: [],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('should inspect a simple custom hook', () => {
|
||||
function useCustom(value) {
|
||||
let [state] = React.useState(value);
|
||||
return state;
|
||||
}
|
||||
function Foo(props) {
|
||||
let value = useCustom('hello world');
|
||||
return <div>{value}</div>;
|
||||
}
|
||||
let tree = ReactDebugTools.inspectHooks(Foo, {});
|
||||
expect(tree).toEqual([
|
||||
{
|
||||
name: 'Custom',
|
||||
value: undefined,
|
||||
subHooks: [
|
||||
{
|
||||
name: 'State',
|
||||
value: 'hello world',
|
||||
subHooks: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('should inspect a tree of multiple hooks', () => {
|
||||
function effect() {}
|
||||
function useCustom(value) {
|
||||
let [state] = React.useState(value);
|
||||
React.useEffect(effect);
|
||||
return state;
|
||||
}
|
||||
function Foo(props) {
|
||||
let value1 = useCustom('hello');
|
||||
let value2 = useCustom('world');
|
||||
return (
|
||||
<div>
|
||||
{value1} {value2}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
let tree = ReactDebugTools.inspectHooks(Foo, {});
|
||||
expect(tree).toEqual([
|
||||
{
|
||||
name: 'Custom',
|
||||
value: undefined,
|
||||
subHooks: [
|
||||
{
|
||||
name: 'State',
|
||||
subHooks: [],
|
||||
value: 'hello',
|
||||
},
|
||||
{
|
||||
name: 'Effect',
|
||||
subHooks: [],
|
||||
value: effect,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Custom',
|
||||
value: undefined,
|
||||
subHooks: [
|
||||
{
|
||||
name: 'State',
|
||||
value: 'world',
|
||||
subHooks: [],
|
||||
},
|
||||
{
|
||||
name: 'Effect',
|
||||
value: effect,
|
||||
subHooks: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('should inspect a tree of multiple levels of hooks', () => {
|
||||
function effect() {}
|
||||
function useCustom(value) {
|
||||
let [state] = React.useReducer((s, a) => s, value);
|
||||
React.useEffect(effect);
|
||||
return state;
|
||||
}
|
||||
function useBar(value) {
|
||||
let result = useCustom(value);
|
||||
React.useLayoutEffect(effect);
|
||||
return result;
|
||||
}
|
||||
function useBaz(value) {
|
||||
React.useLayoutEffect(effect);
|
||||
let result = useCustom(value);
|
||||
return result;
|
||||
}
|
||||
function Foo(props) {
|
||||
let value1 = useBar('hello');
|
||||
let value2 = useBaz('world');
|
||||
return (
|
||||
<div>
|
||||
{value1} {value2}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
let tree = ReactDebugTools.inspectHooks(Foo, {});
|
||||
expect(tree).toEqual([
|
||||
{
|
||||
name: 'Bar',
|
||||
value: undefined,
|
||||
subHooks: [
|
||||
{
|
||||
name: 'Custom',
|
||||
value: undefined,
|
||||
subHooks: [
|
||||
{
|
||||
name: 'Reducer',
|
||||
value: 'hello',
|
||||
subHooks: [],
|
||||
},
|
||||
{
|
||||
name: 'Effect',
|
||||
value: effect,
|
||||
subHooks: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'LayoutEffect',
|
||||
value: effect,
|
||||
subHooks: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Baz',
|
||||
value: undefined,
|
||||
subHooks: [
|
||||
{
|
||||
name: 'LayoutEffect',
|
||||
value: effect,
|
||||
subHooks: [],
|
||||
},
|
||||
{
|
||||
name: 'Custom',
|
||||
subHooks: [
|
||||
{
|
||||
name: 'Reducer',
|
||||
subHooks: [],
|
||||
value: 'world',
|
||||
},
|
||||
{
|
||||
name: 'Effect',
|
||||
subHooks: [],
|
||||
value: effect,
|
||||
},
|
||||
],
|
||||
value: undefined,
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('should inspect the default value using the useContext hook', () => {
|
||||
let MyContext = React.createContext('default');
|
||||
function Foo(props) {
|
||||
let value = React.useContext(MyContext);
|
||||
return <div>{value}</div>;
|
||||
}
|
||||
let tree = ReactDebugTools.inspectHooks(Foo, {});
|
||||
expect(tree).toEqual([
|
||||
{
|
||||
name: 'Context',
|
||||
value: 'default',
|
||||
subHooks: [],
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,244 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) Facebook, Inc. and its affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @emails react-core
|
||||
* @jest-environment node
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
let React;
|
||||
let ReactTestRenderer;
|
||||
let ReactDebugTools;
|
||||
|
||||
describe('ReactHooksInspectionIntergration', () => {
|
||||
beforeEach(() => {
|
||||
jest.resetModules();
|
||||
let ReactFeatureFlags = require('shared/ReactFeatureFlags');
|
||||
// TODO: Switch this test to non-internal once the flag is on by default.
|
||||
ReactFeatureFlags.enableHooks = true;
|
||||
React = require('react');
|
||||
ReactTestRenderer = require('react-test-renderer');
|
||||
ReactDebugTools = require('react-debug-tools');
|
||||
});
|
||||
|
||||
it('should inspect the current state of useState hooks', () => {
|
||||
let useState = React.useState;
|
||||
function Foo(props) {
|
||||
let [state1, setState1] = useState('hello');
|
||||
let [state2, setState2] = useState('world');
|
||||
return (
|
||||
<div onMouseDown={setState1} onMouseUp={setState2}>
|
||||
{state1} {state2}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
let renderer = ReactTestRenderer.create(<Foo prop="prop" />);
|
||||
|
||||
let childFiber = renderer.root.findByType(Foo)._currentFiber();
|
||||
let tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
|
||||
expect(tree).toEqual([
|
||||
{name: 'State', value: 'hello', subHooks: []},
|
||||
{name: 'State', value: 'world', subHooks: []},
|
||||
]);
|
||||
|
||||
let {
|
||||
onMouseDown: setStateA,
|
||||
onMouseUp: setStateB,
|
||||
} = renderer.root.findByType('div').props;
|
||||
|
||||
setStateA('Hi');
|
||||
|
||||
childFiber = renderer.root.findByType(Foo)._currentFiber();
|
||||
tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
|
||||
|
||||
expect(tree).toEqual([
|
||||
{name: 'State', value: 'Hi', subHooks: []},
|
||||
{name: 'State', value: 'world', subHooks: []},
|
||||
]);
|
||||
|
||||
setStateB('world!');
|
||||
|
||||
childFiber = renderer.root.findByType(Foo)._currentFiber();
|
||||
tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
|
||||
|
||||
expect(tree).toEqual([
|
||||
{name: 'State', value: 'Hi', subHooks: []},
|
||||
{name: 'State', value: 'world!', subHooks: []},
|
||||
]);
|
||||
});
|
||||
|
||||
it('should inspect the current state of all stateful hooks', () => {
|
||||
let outsideRef = React.createRef();
|
||||
function effect() {}
|
||||
function Foo(props) {
|
||||
let [state1, setState] = React.useState('a');
|
||||
let [state2, dispatch] = React.useReducer((s, a) => a.value, 'b');
|
||||
let ref = React.useRef('c');
|
||||
|
||||
React.useLayoutEffect(effect);
|
||||
React.useEffect(effect);
|
||||
|
||||
React.useImperativeMethods(
|
||||
outsideRef,
|
||||
() => {
|
||||
// Return a function so that jest treats them as non-equal.
|
||||
return function Instance() {};
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
React.useMemo(() => state1 + state2, [state1]);
|
||||
|
||||
function update() {
|
||||
setState('A');
|
||||
dispatch({value: 'B'});
|
||||
ref.current = 'C';
|
||||
}
|
||||
let memoizedUpdate = React.useCallback(update, []);
|
||||
return (
|
||||
<div onClick={memoizedUpdate}>
|
||||
{state1} {state2}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
let renderer = ReactTestRenderer.create(<Foo prop="prop" />);
|
||||
|
||||
let childFiber = renderer.root.findByType(Foo)._currentFiber();
|
||||
|
||||
let {onClick: updateStates} = renderer.root.findByType('div').props;
|
||||
|
||||
let tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
|
||||
expect(tree).toEqual([
|
||||
{name: 'State', value: 'a', subHooks: []},
|
||||
{name: 'Reducer', value: 'b', subHooks: []},
|
||||
{name: 'Ref', value: 'c', subHooks: []},
|
||||
{name: 'LayoutEffect', value: effect, subHooks: []},
|
||||
{name: 'Effect', value: effect, subHooks: []},
|
||||
{name: 'ImperativeMethods', value: outsideRef.current, subHooks: []},
|
||||
{name: 'Memo', value: 'ab', subHooks: []},
|
||||
{name: 'Callback', value: updateStates, subHooks: []},
|
||||
]);
|
||||
|
||||
updateStates();
|
||||
|
||||
childFiber = renderer.root.findByType(Foo)._currentFiber();
|
||||
tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
|
||||
|
||||
expect(tree).toEqual([
|
||||
{name: 'State', value: 'A', subHooks: []},
|
||||
{name: 'Reducer', value: 'B', subHooks: []},
|
||||
{name: 'Ref', value: 'C', subHooks: []},
|
||||
{name: 'LayoutEffect', value: effect, subHooks: []},
|
||||
{name: 'Effect', value: effect, subHooks: []},
|
||||
{name: 'ImperativeMethods', value: outsideRef.current, subHooks: []},
|
||||
{name: 'Memo', value: 'Ab', subHooks: []},
|
||||
{name: 'Callback', value: updateStates, subHooks: []},
|
||||
]);
|
||||
});
|
||||
|
||||
it('should inspect the value of the current provider in useContext', () => {
|
||||
let MyContext = React.createContext('default');
|
||||
function Foo(props) {
|
||||
let value = React.useContext(MyContext);
|
||||
return <div>{value}</div>;
|
||||
}
|
||||
let renderer = ReactTestRenderer.create(
|
||||
<MyContext.Provider value="contextual">
|
||||
<Foo prop="prop" />
|
||||
</MyContext.Provider>,
|
||||
);
|
||||
let childFiber = renderer.root.findByType(Foo)._currentFiber();
|
||||
let tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
|
||||
expect(tree).toEqual([
|
||||
{
|
||||
name: 'Context',
|
||||
value: 'contextual',
|
||||
subHooks: [],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('should inspect forwardRef', () => {
|
||||
let obj = function() {};
|
||||
let Foo = React.forwardRef(function(props, ref) {
|
||||
React.useImperativeMethods(ref, () => obj);
|
||||
return <div />;
|
||||
});
|
||||
let ref = React.createRef();
|
||||
let renderer = ReactTestRenderer.create(<Foo ref={ref} />);
|
||||
|
||||
let childFiber = renderer.root.findByType(Foo)._currentFiber();
|
||||
let tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
|
||||
expect(tree).toEqual([
|
||||
{name: 'ImperativeMethods', value: obj, subHooks: []},
|
||||
]);
|
||||
});
|
||||
|
||||
it('should inspect memo', () => {
|
||||
function InnerFoo(props) {
|
||||
let [value] = React.useState('hello');
|
||||
return <div>{value}</div>;
|
||||
}
|
||||
let Foo = React.memo(InnerFoo);
|
||||
let renderer = ReactTestRenderer.create(<Foo />);
|
||||
// TODO: Test renderer findByType is broken for memo. Have to search for the inner.
|
||||
let childFiber = renderer.root.findByType(InnerFoo)._currentFiber();
|
||||
let tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
|
||||
expect(tree).toEqual([{name: 'State', value: 'hello', subHooks: []}]);
|
||||
});
|
||||
|
||||
it('should inspect custom hooks', () => {
|
||||
function useCustom() {
|
||||
let [value] = React.useState('hello');
|
||||
return value;
|
||||
}
|
||||
function Foo(props) {
|
||||
let value = useCustom();
|
||||
return <div>{value}</div>;
|
||||
}
|
||||
let renderer = ReactTestRenderer.create(<Foo />);
|
||||
let childFiber = renderer.root.findByType(Foo)._currentFiber();
|
||||
let tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
|
||||
expect(tree).toEqual([
|
||||
{
|
||||
name: 'Custom',
|
||||
value: undefined,
|
||||
subHooks: [{name: 'State', value: 'hello', subHooks: []}],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('should support defaultProps and lazy', async () => {
|
||||
let Suspense = React.Suspense;
|
||||
|
||||
function Foo(props) {
|
||||
let [value] = React.useState(props.defaultValue.substr(0, 3));
|
||||
return <div>{value}</div>;
|
||||
}
|
||||
Foo.defaultProps = {
|
||||
defaultValue: 'default',
|
||||
};
|
||||
|
||||
async function fakeImport(result) {
|
||||
return {default: result};
|
||||
}
|
||||
|
||||
let LazyFoo = React.lazy(() => fakeImport(Foo));
|
||||
|
||||
let renderer = ReactTestRenderer.create(
|
||||
<Suspense fallback="Loading...">
|
||||
<LazyFoo />
|
||||
</Suspense>,
|
||||
);
|
||||
|
||||
await LazyFoo;
|
||||
|
||||
let childFiber = renderer.root._currentFiber();
|
||||
let tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
|
||||
expect(tree).toEqual([{name: 'State', value: 'def', subHooks: []}]);
|
||||
});
|
||||
});
|
||||
@@ -1,7 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
module.exports = require('./cjs/react-dom-unstable-fizz.browser.production.min.js');
|
||||
} else {
|
||||
module.exports = require('./cjs/react-dom-unstable-fizz.browser.development.js');
|
||||
}
|
||||
3
packages/react-dom/npm/unstable-fizz.js
vendored
3
packages/react-dom/npm/unstable-fizz.js
vendored
@@ -1,3 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = require('./unstable-fizz.node');
|
||||
@@ -1,7 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
module.exports = require('./cjs/react-dom-unstable-fizz.node.production.min.js');
|
||||
} else {
|
||||
module.exports = require('./cjs/react-dom-unstable-fizz.node.development.js');
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "react-dom",
|
||||
"version": "16.6.1",
|
||||
"version": "16.6.0-alpha.8af6728",
|
||||
"description": "React package for working with the DOM.",
|
||||
"main": "index.js",
|
||||
"repository": "facebook/react",
|
||||
@@ -16,32 +16,26 @@
|
||||
"loose-envify": "^1.1.0",
|
||||
"object-assign": "^4.1.1",
|
||||
"prop-types": "^15.6.2",
|
||||
"scheduler": "^0.11.0"
|
||||
"scheduler": "^0.10.0-alpha.8af6728"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^16.0.0"
|
||||
"react": "^16.0.0 || 16.6.0-alpha.8af6728"
|
||||
},
|
||||
"files": [
|
||||
"LICENSE",
|
||||
"README.md",
|
||||
"build-info.json",
|
||||
"index.js",
|
||||
"profiling.js",
|
||||
"server.js",
|
||||
"server.browser.js",
|
||||
"server.node.js",
|
||||
"test-utils.js",
|
||||
"unstable-fire.js",
|
||||
"unstable-fizz.js",
|
||||
"unstable-fizz.browser.js",
|
||||
"unstable-fizz.node.js",
|
||||
"unstable-native-dependencies.js",
|
||||
"cjs/",
|
||||
"umd/"
|
||||
],
|
||||
"browser": {
|
||||
"./server.js": "./server.browser.js",
|
||||
"./unstable-fizz.js": "./unstable-fizz.browser.js"
|
||||
"./server.js": "./server.browser.js"
|
||||
},
|
||||
"browserify": {
|
||||
"transform": [
|
||||
|
||||
@@ -332,7 +332,7 @@ describe('ReactCompositeComponent', () => {
|
||||
ReactDOM.unmountComponentAtNode(container);
|
||||
|
||||
expect(() => instance.forceUpdate()).toWarnDev(
|
||||
"Warning: Can't perform a React state update on an unmounted " +
|
||||
"Warning: Can't call setState (or forceUpdate) on an unmounted " +
|
||||
'component. This is a no-op, but it indicates a memory leak in your ' +
|
||||
'application. To fix, cancel all subscriptions and asynchronous ' +
|
||||
'tasks in the componentWillUnmount method.\n' +
|
||||
@@ -379,7 +379,7 @@ describe('ReactCompositeComponent', () => {
|
||||
expect(() => {
|
||||
instance.setState({value: 2});
|
||||
}).toWarnDev(
|
||||
"Warning: Can't perform a React state update on an unmounted " +
|
||||
"Warning: Can't call setState (or forceUpdate) on an unmounted " +
|
||||
'component. This is a no-op, but it indicates a memory leak in your ' +
|
||||
'application. To fix, cancel all subscriptions and asynchronous ' +
|
||||
'tasks in the componentWillUnmount method.\n' +
|
||||
@@ -1743,25 +1743,6 @@ describe('ReactCompositeComponent', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('should warn about reassigning this.props while rendering', () => {
|
||||
class Bad extends React.Component {
|
||||
componentDidMount() {}
|
||||
componentDidUpdate() {}
|
||||
render() {
|
||||
this.props = {...this.props};
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const container = document.createElement('div');
|
||||
expect(() => {
|
||||
ReactDOM.render(<Bad />, container);
|
||||
}).toWarnDev(
|
||||
'It looks like Bad is reassigning its own `this.props` while rendering. ' +
|
||||
'This is not supported and can lead to confusing bugs.',
|
||||
);
|
||||
});
|
||||
|
||||
it('should return error if render is not defined', () => {
|
||||
class RenderTestUndefinedRender extends React.Component {}
|
||||
|
||||
|
||||
@@ -450,6 +450,22 @@ describe('ReactDOM', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('warns when requestAnimationFrame is not polyfilled', () => {
|
||||
const previousRAF = global.requestAnimationFrame;
|
||||
try {
|
||||
delete global.requestAnimationFrame;
|
||||
jest.resetModules();
|
||||
spyOnDevAndProd(console, 'error');
|
||||
require('react-dom');
|
||||
expect(console.error.calls.count()).toEqual(1);
|
||||
expect(console.error.calls.argsFor(0)[0]).toMatch(
|
||||
"This browser doesn't support requestAnimationFrame.",
|
||||
);
|
||||
} finally {
|
||||
global.requestAnimationFrame = previousRAF;
|
||||
}
|
||||
});
|
||||
|
||||
it('reports stacks with re-entrant renderToString() calls on the client', () => {
|
||||
function Child2(props) {
|
||||
return <span ariaTypo3="no">{props.children}</span>;
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) Facebook, Inc. and its affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @emails react-core
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
// Polyfills for test environment
|
||||
global.ReadableStream = require('@mattiasbuelens/web-streams-polyfill/ponyfill/es6').ReadableStream;
|
||||
global.TextEncoder = require('util').TextEncoder;
|
||||
|
||||
let React;
|
||||
let ReactDOMFizzServer;
|
||||
|
||||
describe('ReactDOMFizzServer', () => {
|
||||
beforeEach(() => {
|
||||
jest.resetModules();
|
||||
React = require('react');
|
||||
ReactDOMFizzServer = require('react-dom/unstable-fizz.browser');
|
||||
});
|
||||
|
||||
async function readResult(stream) {
|
||||
let reader = stream.getReader();
|
||||
let result = '';
|
||||
while (true) {
|
||||
let {done, value} = await reader.read();
|
||||
if (done) {
|
||||
return result;
|
||||
}
|
||||
result += Buffer.from(value).toString('utf8');
|
||||
}
|
||||
}
|
||||
|
||||
it('should call renderToReadableStream', async () => {
|
||||
let stream = ReactDOMFizzServer.renderToReadableStream(
|
||||
<div>hello world</div>,
|
||||
);
|
||||
let result = await readResult(stream);
|
||||
expect(result).toBe('<div>hello world</div>');
|
||||
});
|
||||
});
|
||||
@@ -1,39 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) Facebook, Inc. and its affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @emails react-core
|
||||
* @jest-environment node
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
let Stream;
|
||||
let React;
|
||||
let ReactDOMFizzServer;
|
||||
|
||||
describe('ReactDOMFizzServer', () => {
|
||||
beforeEach(() => {
|
||||
jest.resetModules();
|
||||
React = require('react');
|
||||
ReactDOMFizzServer = require('react-dom/unstable-fizz');
|
||||
Stream = require('stream');
|
||||
});
|
||||
|
||||
function getTestWritable() {
|
||||
let writable = new Stream.PassThrough();
|
||||
writable.setEncoding('utf8');
|
||||
writable.result = '';
|
||||
writable.on('data', chunk => (writable.result += chunk));
|
||||
return writable;
|
||||
}
|
||||
|
||||
it('should call pipeToNodeWritable', () => {
|
||||
let writable = getTestWritable();
|
||||
ReactDOMFizzServer.pipeToNodeWritable(<div>hello world</div>, writable);
|
||||
jest.runAllTimers();
|
||||
expect(writable.result).toBe('<div>hello world</div>');
|
||||
});
|
||||
});
|
||||
@@ -1,661 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) 2013-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @emails react-core
|
||||
*/
|
||||
|
||||
/* eslint-disable no-func-assign */
|
||||
|
||||
'use strict';
|
||||
|
||||
const ReactDOMServerIntegrationUtils = require('./utils/ReactDOMServerIntegrationTestUtils');
|
||||
|
||||
let React;
|
||||
let ReactFeatureFlags;
|
||||
let ReactDOM;
|
||||
let ReactDOMServer;
|
||||
let useState;
|
||||
let useReducer;
|
||||
let useEffect;
|
||||
let useContext;
|
||||
let useCallback;
|
||||
let useMemo;
|
||||
let useRef;
|
||||
let useImperativeMethods;
|
||||
let useLayoutEffect;
|
||||
let forwardRef;
|
||||
let yieldedValues;
|
||||
let yieldValue;
|
||||
let clearYields;
|
||||
|
||||
function initModules() {
|
||||
// Reset warning cache.
|
||||
jest.resetModuleRegistry();
|
||||
|
||||
ReactFeatureFlags = require('shared/ReactFeatureFlags');
|
||||
ReactFeatureFlags.debugRenderPhaseSideEffectsForStrictMode = false;
|
||||
ReactFeatureFlags.enableHooks = true;
|
||||
React = require('react');
|
||||
ReactDOM = require('react-dom');
|
||||
ReactDOMServer = require('react-dom/server');
|
||||
useState = React.useState;
|
||||
useReducer = React.useReducer;
|
||||
useEffect = React.useEffect;
|
||||
useContext = React.useContext;
|
||||
useCallback = React.useCallback;
|
||||
useMemo = React.useMemo;
|
||||
useRef = React.useRef;
|
||||
useImperativeMethods = React.useImperativeMethods;
|
||||
useLayoutEffect = React.useLayoutEffect;
|
||||
forwardRef = React.forwardRef;
|
||||
|
||||
yieldedValues = [];
|
||||
yieldValue = value => {
|
||||
yieldedValues.push(value);
|
||||
};
|
||||
clearYields = () => {
|
||||
const ret = yieldedValues;
|
||||
yieldedValues = [];
|
||||
return ret;
|
||||
};
|
||||
|
||||
// Make them available to the helpers.
|
||||
return {
|
||||
ReactDOM,
|
||||
ReactDOMServer,
|
||||
};
|
||||
}
|
||||
|
||||
const {
|
||||
resetModules,
|
||||
itRenders,
|
||||
itThrowsWhenRendering,
|
||||
serverRender,
|
||||
} = ReactDOMServerIntegrationUtils(initModules);
|
||||
|
||||
describe('ReactDOMServerHooks', () => {
|
||||
beforeEach(() => {
|
||||
resetModules();
|
||||
});
|
||||
|
||||
function Text(props) {
|
||||
yieldValue(props.text);
|
||||
return <span>{props.text}</span>;
|
||||
}
|
||||
|
||||
describe('useState', () => {
|
||||
itRenders('basic render', async render => {
|
||||
function Counter(props) {
|
||||
const [count] = useState(0);
|
||||
return <span>Count: {count}</span>;
|
||||
}
|
||||
|
||||
const domNode = await render(<Counter />);
|
||||
expect(domNode.textContent).toEqual('Count: 0');
|
||||
});
|
||||
|
||||
itRenders('lazy state initialization', async render => {
|
||||
function Counter(props) {
|
||||
const [count] = useState(() => {
|
||||
return 0;
|
||||
});
|
||||
return <span>Count: {count}</span>;
|
||||
}
|
||||
|
||||
const domNode = await render(<Counter />);
|
||||
expect(domNode.textContent).toEqual('Count: 0');
|
||||
});
|
||||
|
||||
it('does not trigger a re-renders when updater is invoked outside current render function', async () => {
|
||||
function UpdateCount({setCount, count, children}) {
|
||||
if (count < 3) {
|
||||
setCount(c => c + 1);
|
||||
}
|
||||
return <span>{children}</span>;
|
||||
}
|
||||
function Counter() {
|
||||
let [count, setCount] = useState(0);
|
||||
return (
|
||||
<div>
|
||||
<UpdateCount setCount={setCount} count={count}>
|
||||
Count: {count}
|
||||
</UpdateCount>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const domNode = await serverRender(<Counter />);
|
||||
expect(domNode.textContent).toEqual('Count: 0');
|
||||
});
|
||||
|
||||
itThrowsWhenRendering(
|
||||
'if used inside a class component',
|
||||
async render => {
|
||||
class Counter extends React.Component {
|
||||
render() {
|
||||
let [count] = useState(0);
|
||||
return <Text text={count} />;
|
||||
}
|
||||
}
|
||||
|
||||
return render(<Counter />);
|
||||
},
|
||||
'Hooks can only be called inside the body of a function component.',
|
||||
);
|
||||
|
||||
itRenders('multiple times when an updater is called', async render => {
|
||||
function Counter() {
|
||||
let [count, setCount] = useState(0);
|
||||
if (count < 12) {
|
||||
setCount(c => c + 1);
|
||||
setCount(c => c + 1);
|
||||
setCount(c => c + 1);
|
||||
}
|
||||
return <Text text={'Count: ' + count} />;
|
||||
}
|
||||
|
||||
const domNode = await render(<Counter />);
|
||||
expect(domNode.textContent).toEqual('Count: 12');
|
||||
});
|
||||
|
||||
itRenders('until there are no more new updates', async render => {
|
||||
function Counter() {
|
||||
let [count, setCount] = useState(0);
|
||||
if (count < 3) {
|
||||
setCount(count + 1);
|
||||
}
|
||||
return <span>Count: {count}</span>;
|
||||
}
|
||||
|
||||
const domNode = await render(<Counter />);
|
||||
expect(domNode.textContent).toEqual('Count: 3');
|
||||
});
|
||||
|
||||
itThrowsWhenRendering(
|
||||
'after too many iterations',
|
||||
async render => {
|
||||
function Counter() {
|
||||
let [count, setCount] = useState(0);
|
||||
setCount(count + 1);
|
||||
return <span>{count}</span>;
|
||||
}
|
||||
return render(<Counter />);
|
||||
},
|
||||
'Too many re-renders. React limits the number of renders to prevent ' +
|
||||
'an infinite loop.',
|
||||
);
|
||||
});
|
||||
|
||||
describe('useReducer', () => {
|
||||
itRenders('with initial state', async render => {
|
||||
function reducer(state, action) {
|
||||
return action === 'increment' ? state + 1 : state;
|
||||
}
|
||||
function Counter() {
|
||||
let [count] = useReducer(reducer, 0);
|
||||
yieldValue('Render: ' + count);
|
||||
return <Text text={count} />;
|
||||
}
|
||||
|
||||
const domNode = await render(<Counter />);
|
||||
|
||||
expect(clearYields()).toEqual(['Render: 0', 0]);
|
||||
expect(domNode.tagName).toEqual('SPAN');
|
||||
expect(domNode.textContent).toEqual('0');
|
||||
});
|
||||
|
||||
itRenders('lazy initialization with initialAction', async render => {
|
||||
function reducer(state, action) {
|
||||
return action === 'increment' ? state + 1 : state;
|
||||
}
|
||||
function Counter() {
|
||||
let [count] = useReducer(reducer, 0, 'increment');
|
||||
yieldValue('Render: ' + count);
|
||||
return <Text text={count} />;
|
||||
}
|
||||
|
||||
const domNode = await render(<Counter />);
|
||||
|
||||
expect(clearYields()).toEqual(['Render: 1', 1]);
|
||||
expect(domNode.tagName).toEqual('SPAN');
|
||||
expect(domNode.textContent).toEqual('1');
|
||||
});
|
||||
|
||||
itRenders(
|
||||
'multiple times when updates happen during the render phase',
|
||||
async render => {
|
||||
function reducer(state, action) {
|
||||
return action === 'increment' ? state + 1 : state;
|
||||
}
|
||||
function Counter() {
|
||||
let [count, dispatch] = useReducer(reducer, 0);
|
||||
if (count < 3) {
|
||||
dispatch('increment');
|
||||
}
|
||||
yieldValue('Render: ' + count);
|
||||
return <Text text={count} />;
|
||||
}
|
||||
|
||||
const domNode = await render(<Counter />);
|
||||
|
||||
expect(clearYields()).toEqual([
|
||||
'Render: 0',
|
||||
'Render: 1',
|
||||
'Render: 2',
|
||||
'Render: 3',
|
||||
3,
|
||||
]);
|
||||
expect(domNode.tagName).toEqual('SPAN');
|
||||
expect(domNode.textContent).toEqual('3');
|
||||
},
|
||||
);
|
||||
|
||||
itRenders(
|
||||
'using reducer passed at time of render, not time of dispatch',
|
||||
async render => {
|
||||
// This test is a bit contrived but it demonstrates a subtle edge case.
|
||||
|
||||
// Reducer A increments by 1. Reducer B increments by 10.
|
||||
function reducerA(state, action) {
|
||||
switch (action) {
|
||||
case 'increment':
|
||||
return state + 1;
|
||||
case 'reset':
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
function reducerB(state, action) {
|
||||
switch (action) {
|
||||
case 'increment':
|
||||
return state + 10;
|
||||
case 'reset':
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
function Counter() {
|
||||
let [reducer, setReducer] = useState(() => reducerA);
|
||||
let [count, dispatch] = useReducer(reducer, 0);
|
||||
if (count < 20) {
|
||||
dispatch('increment');
|
||||
// Swap reducers each time we increment
|
||||
if (reducer === reducerA) {
|
||||
setReducer(() => reducerB);
|
||||
} else {
|
||||
setReducer(() => reducerA);
|
||||
}
|
||||
}
|
||||
yieldValue('Render: ' + count);
|
||||
return <Text text={count} />;
|
||||
}
|
||||
|
||||
const domNode = await render(<Counter />);
|
||||
|
||||
expect(clearYields()).toEqual([
|
||||
// The count should increase by alternating amounts of 10 and 1
|
||||
// until we reach 21.
|
||||
'Render: 0',
|
||||
'Render: 10',
|
||||
'Render: 11',
|
||||
'Render: 21',
|
||||
21,
|
||||
]);
|
||||
expect(domNode.tagName).toEqual('SPAN');
|
||||
expect(domNode.textContent).toEqual('21');
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe('useMemo', () => {
|
||||
itRenders('basic render', async render => {
|
||||
function CapitalizedText(props) {
|
||||
const text = props.text;
|
||||
const capitalizedText = useMemo(
|
||||
() => {
|
||||
yieldValue(`Capitalize '${text}'`);
|
||||
return text.toUpperCase();
|
||||
},
|
||||
[text],
|
||||
);
|
||||
return <Text text={capitalizedText} />;
|
||||
}
|
||||
|
||||
const domNode = await render(<CapitalizedText text="hello" />);
|
||||
expect(clearYields()).toEqual(["Capitalize 'hello'", 'HELLO']);
|
||||
expect(domNode.tagName).toEqual('SPAN');
|
||||
expect(domNode.textContent).toEqual('HELLO');
|
||||
});
|
||||
|
||||
itRenders('if no inputs are provided', async render => {
|
||||
function LazyCompute(props) {
|
||||
const computed = useMemo(props.compute);
|
||||
return <Text text={computed} />;
|
||||
}
|
||||
|
||||
function computeA() {
|
||||
yieldValue('compute A');
|
||||
return 'A';
|
||||
}
|
||||
|
||||
const domNode = await render(<LazyCompute compute={computeA} />);
|
||||
expect(clearYields()).toEqual(['compute A', 'A']);
|
||||
expect(domNode.tagName).toEqual('SPAN');
|
||||
expect(domNode.textContent).toEqual('A');
|
||||
});
|
||||
|
||||
itRenders(
|
||||
'multiple times when updates happen during the render phase',
|
||||
async render => {
|
||||
function CapitalizedText(props) {
|
||||
const [text, setText] = useState(props.text);
|
||||
const capitalizedText = useMemo(
|
||||
() => {
|
||||
yieldValue(`Capitalize '${text}'`);
|
||||
return text.toUpperCase();
|
||||
},
|
||||
[text],
|
||||
);
|
||||
|
||||
if (text === 'hello') {
|
||||
setText('hello, world.');
|
||||
}
|
||||
return <Text text={capitalizedText} />;
|
||||
}
|
||||
|
||||
const domNode = await render(<CapitalizedText text="hello" />);
|
||||
expect(clearYields()).toEqual([
|
||||
"Capitalize 'hello'",
|
||||
"Capitalize 'hello, world.'",
|
||||
'HELLO, WORLD.',
|
||||
]);
|
||||
expect(domNode.tagName).toEqual('SPAN');
|
||||
expect(domNode.textContent).toEqual('HELLO, WORLD.');
|
||||
},
|
||||
);
|
||||
|
||||
itRenders(
|
||||
'should only invoke the memoized function when the inputs change',
|
||||
async render => {
|
||||
function CapitalizedText(props) {
|
||||
const [text, setText] = useState(props.text);
|
||||
const [count, setCount] = useState(0);
|
||||
const capitalizedText = useMemo(
|
||||
() => {
|
||||
yieldValue(`Capitalize '${text}'`);
|
||||
return text.toUpperCase();
|
||||
},
|
||||
[text],
|
||||
);
|
||||
|
||||
yieldValue(count);
|
||||
|
||||
if (count < 3) {
|
||||
setCount(count + 1);
|
||||
}
|
||||
|
||||
if (text === 'hello' && count === 2) {
|
||||
setText('hello, world.');
|
||||
}
|
||||
return <Text text={capitalizedText} />;
|
||||
}
|
||||
|
||||
const domNode = await render(<CapitalizedText text="hello" />);
|
||||
expect(clearYields()).toEqual([
|
||||
"Capitalize 'hello'",
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
// `capitalizedText` only recomputes when the text has changed
|
||||
"Capitalize 'hello, world.'",
|
||||
3,
|
||||
'HELLO, WORLD.',
|
||||
]);
|
||||
expect(domNode.tagName).toEqual('SPAN');
|
||||
expect(domNode.textContent).toEqual('HELLO, WORLD.');
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe('useRef', () => {
|
||||
itRenders('basic render', async render => {
|
||||
function Counter(props) {
|
||||
const count = useRef(0);
|
||||
return <span>Count: {count.current}</span>;
|
||||
}
|
||||
|
||||
const domNode = await render(<Counter />);
|
||||
expect(domNode.textContent).toEqual('Count: 0');
|
||||
});
|
||||
|
||||
itRenders(
|
||||
'multiple times when updates happen during the render phase',
|
||||
async render => {
|
||||
function Counter(props) {
|
||||
const [count, setCount] = useState(0);
|
||||
const ref = useRef(count);
|
||||
|
||||
if (count < 3) {
|
||||
const newCount = count + 1;
|
||||
|
||||
ref.current = newCount;
|
||||
setCount(newCount);
|
||||
}
|
||||
|
||||
yieldValue(count);
|
||||
|
||||
return <span>Count: {ref.current}</span>;
|
||||
}
|
||||
|
||||
const domNode = await render(<Counter />);
|
||||
expect(clearYields()).toEqual([0, 1, 2, 3]);
|
||||
expect(domNode.textContent).toEqual('Count: 3');
|
||||
},
|
||||
);
|
||||
|
||||
itRenders(
|
||||
'always return the same reference through multiple renders',
|
||||
async render => {
|
||||
let firstRef = null;
|
||||
function Counter(props) {
|
||||
const [count, setCount] = useState(0);
|
||||
const ref = useRef(count);
|
||||
if (firstRef === null) {
|
||||
firstRef = ref;
|
||||
} else if (firstRef !== ref) {
|
||||
throw new Error('should never change');
|
||||
}
|
||||
|
||||
if (count < 3) {
|
||||
setCount(count + 1);
|
||||
} else {
|
||||
firstRef = null;
|
||||
}
|
||||
|
||||
yieldValue(count);
|
||||
|
||||
return <span>Count: {ref.current}</span>;
|
||||
}
|
||||
|
||||
const domNode = await render(<Counter />);
|
||||
expect(clearYields()).toEqual([0, 1, 2, 3]);
|
||||
expect(domNode.textContent).toEqual('Count: 0');
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe('useEffect', () => {
|
||||
itRenders('should ignore effects on the server', async render => {
|
||||
function Counter(props) {
|
||||
useEffect(() => {
|
||||
yieldValue('should not be invoked');
|
||||
});
|
||||
return <Text text={'Count: ' + props.count} />;
|
||||
}
|
||||
const domNode = await render(<Counter count={0} />);
|
||||
expect(clearYields()).toEqual(['Count: 0']);
|
||||
expect(domNode.tagName).toEqual('SPAN');
|
||||
expect(domNode.textContent).toEqual('Count: 0');
|
||||
});
|
||||
});
|
||||
|
||||
describe('useCallback', () => {
|
||||
itRenders('should ignore callbacks on the server', async render => {
|
||||
function Counter(props) {
|
||||
useCallback(() => {
|
||||
yieldValue('should not be invoked');
|
||||
});
|
||||
return <Text text={'Count: ' + props.count} />;
|
||||
}
|
||||
const domNode = await render(<Counter count={0} />);
|
||||
expect(clearYields()).toEqual(['Count: 0']);
|
||||
expect(domNode.tagName).toEqual('SPAN');
|
||||
expect(domNode.textContent).toEqual('Count: 0');
|
||||
});
|
||||
|
||||
itRenders('should support render time callbacks', async render => {
|
||||
function Counter(props) {
|
||||
const renderCount = useCallback(increment => {
|
||||
return 'Count: ' + (props.count + increment);
|
||||
});
|
||||
return <Text text={renderCount(3)} />;
|
||||
}
|
||||
const domNode = await render(<Counter count={2} />);
|
||||
expect(clearYields()).toEqual(['Count: 5']);
|
||||
expect(domNode.tagName).toEqual('SPAN');
|
||||
expect(domNode.textContent).toEqual('Count: 5');
|
||||
});
|
||||
});
|
||||
|
||||
describe('useImperativeMethods', () => {
|
||||
it('should not be invoked on the server', async () => {
|
||||
function Counter(props, ref) {
|
||||
useImperativeMethods(ref, () => {
|
||||
throw new Error('should not be invoked');
|
||||
});
|
||||
return <Text text={props.label + ': ' + ref.current} />;
|
||||
}
|
||||
Counter = forwardRef(Counter);
|
||||
const counter = React.createRef();
|
||||
counter.current = 0;
|
||||
const domNode = await serverRender(
|
||||
<Counter label="Count" ref={counter} />,
|
||||
);
|
||||
expect(clearYields()).toEqual(['Count: 0']);
|
||||
expect(domNode.tagName).toEqual('SPAN');
|
||||
expect(domNode.textContent).toEqual('Count: 0');
|
||||
});
|
||||
});
|
||||
|
||||
describe('useLayoutEffect', () => {
|
||||
it('should warn when invoked during render', async () => {
|
||||
function Counter() {
|
||||
useLayoutEffect(() => {
|
||||
throw new Error('should not be invoked');
|
||||
});
|
||||
|
||||
return <Text text="Count: 0" />;
|
||||
}
|
||||
const domNode = await serverRender(<Counter />, 1);
|
||||
expect(clearYields()).toEqual(['Count: 0']);
|
||||
expect(domNode.tagName).toEqual('SPAN');
|
||||
expect(domNode.textContent).toEqual('Count: 0');
|
||||
});
|
||||
});
|
||||
|
||||
describe('useContext', () => {
|
||||
itRenders(
|
||||
'can use the same context multiple times in the same function',
|
||||
async render => {
|
||||
const Context = React.createContext(
|
||||
{foo: 0, bar: 0, baz: 0},
|
||||
(a, b) => {
|
||||
let result = 0;
|
||||
if (a.foo !== b.foo) {
|
||||
result |= 0b001;
|
||||
}
|
||||
if (a.bar !== b.bar) {
|
||||
result |= 0b010;
|
||||
}
|
||||
if (a.baz !== b.baz) {
|
||||
result |= 0b100;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
);
|
||||
|
||||
function Provider(props) {
|
||||
return (
|
||||
<Context.Provider
|
||||
value={{foo: props.foo, bar: props.bar, baz: props.baz}}>
|
||||
{props.children}
|
||||
</Context.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
function FooAndBar() {
|
||||
const {foo} = useContext(Context, 0b001);
|
||||
const {bar} = useContext(Context, 0b010);
|
||||
return <Text text={`Foo: ${foo}, Bar: ${bar}`} />;
|
||||
}
|
||||
|
||||
function Baz() {
|
||||
const {baz} = useContext(Context, 0b100);
|
||||
return <Text text={'Baz: ' + baz} />;
|
||||
}
|
||||
|
||||
class Indirection extends React.Component {
|
||||
shouldComponentUpdate() {
|
||||
return false;
|
||||
}
|
||||
render() {
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
|
||||
function App(props) {
|
||||
return (
|
||||
<div>
|
||||
<Provider foo={props.foo} bar={props.bar} baz={props.baz}>
|
||||
<Indirection>
|
||||
<Indirection>
|
||||
<FooAndBar />
|
||||
</Indirection>
|
||||
<Indirection>
|
||||
<Baz />
|
||||
</Indirection>
|
||||
</Indirection>
|
||||
</Provider>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const domNode = await render(<App foo={1} bar={3} baz={5} />);
|
||||
expect(clearYields()).toEqual(['Foo: 1, Bar: 3', 'Baz: 5']);
|
||||
expect(domNode.childNodes.length).toBe(2);
|
||||
expect(domNode.firstChild.tagName).toEqual('SPAN');
|
||||
expect(domNode.firstChild.textContent).toEqual('Foo: 1, Bar: 3');
|
||||
expect(domNode.lastChild.tagName).toEqual('SPAN');
|
||||
expect(domNode.lastChild.textContent).toEqual('Baz: 5');
|
||||
},
|
||||
);
|
||||
|
||||
itThrowsWhenRendering(
|
||||
'if used inside a class component',
|
||||
async render => {
|
||||
const Context = React.createContext({}, () => {});
|
||||
class Counter extends React.Component {
|
||||
render() {
|
||||
let [count] = useContext(Context);
|
||||
return <Text text={count} />;
|
||||
}
|
||||
}
|
||||
|
||||
return render(<Counter />);
|
||||
},
|
||||
'Hooks can only be called inside the body of a function component.',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -249,195 +249,5 @@ describe('ReactDOMServerIntegration', () => {
|
||||
expect(e.querySelector('#language2').textContent).toBe('sanskrit');
|
||||
expect(e.querySelector('#language3').textContent).toBe('french');
|
||||
});
|
||||
|
||||
itRenders(
|
||||
'should warn with an error message when using Context as consumer in DEV',
|
||||
async render => {
|
||||
const Theme = React.createContext('dark');
|
||||
const Language = React.createContext('french');
|
||||
|
||||
const App = () => (
|
||||
<div>
|
||||
<Theme.Provider value="light">
|
||||
<Language.Provider value="english">
|
||||
<Theme.Provider value="dark">
|
||||
<Theme>{theme => <div id="theme1">{theme}</div>}</Theme>
|
||||
</Theme.Provider>
|
||||
</Language.Provider>
|
||||
</Theme.Provider>
|
||||
</div>
|
||||
);
|
||||
// We expect 1 error.
|
||||
await render(<App />, 1);
|
||||
},
|
||||
);
|
||||
|
||||
// False positive regression test.
|
||||
itRenders(
|
||||
'should not warn when using Consumer from React < 16.6 with newer renderer',
|
||||
async render => {
|
||||
const Theme = React.createContext('dark');
|
||||
const Language = React.createContext('french');
|
||||
// React 16.5 and earlier didn't have a separate object.
|
||||
Theme.Consumer = Theme;
|
||||
|
||||
const App = () => (
|
||||
<div>
|
||||
<Theme.Provider value="light">
|
||||
<Language.Provider value="english">
|
||||
<Theme.Provider value="dark">
|
||||
<Theme>{theme => <div id="theme1">{theme}</div>}</Theme>
|
||||
</Theme.Provider>
|
||||
</Language.Provider>
|
||||
</Theme.Provider>
|
||||
</div>
|
||||
);
|
||||
// We expect 0 errors.
|
||||
await render(<App />, 0);
|
||||
},
|
||||
);
|
||||
|
||||
itRenders(
|
||||
'should warn with an error message when using nested context consumers in DEV',
|
||||
async render => {
|
||||
const App = () => {
|
||||
const Theme = React.createContext('dark');
|
||||
const Language = React.createContext('french');
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Theme.Provider value="light">
|
||||
<Language.Provider value="english">
|
||||
<Theme.Provider value="dark">
|
||||
<Theme.Consumer.Consumer>
|
||||
{theme => <div id="theme1">{theme}</div>}
|
||||
</Theme.Consumer.Consumer>
|
||||
</Theme.Provider>
|
||||
</Language.Provider>
|
||||
</Theme.Provider>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
// We expect 1 error.
|
||||
await render(<App />, 1);
|
||||
},
|
||||
);
|
||||
|
||||
itRenders(
|
||||
'should warn with an error message when using Context.Consumer.Provider DEV',
|
||||
async render => {
|
||||
const App = () => {
|
||||
const Theme = React.createContext('dark');
|
||||
const Language = React.createContext('french');
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Theme.Provider value="light">
|
||||
<Language.Provider value="english">
|
||||
<Theme.Consumer.Provider value="dark">
|
||||
<Theme.Consumer>
|
||||
{theme => <div id="theme1">{theme}</div>}
|
||||
</Theme.Consumer>
|
||||
</Theme.Consumer.Provider>
|
||||
</Language.Provider>
|
||||
</Theme.Provider>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
// We expect 1 error.
|
||||
await render(<App />, 1);
|
||||
},
|
||||
);
|
||||
|
||||
it('does not pollute parallel node streams', () => {
|
||||
const LoggedInUser = React.createContext();
|
||||
|
||||
const AppWithUser = user => (
|
||||
<LoggedInUser.Provider value={user}>
|
||||
<header>
|
||||
<LoggedInUser.Consumer>{whoAmI => whoAmI}</LoggedInUser.Consumer>
|
||||
</header>
|
||||
<footer>
|
||||
<LoggedInUser.Consumer>{whoAmI => whoAmI}</LoggedInUser.Consumer>
|
||||
</footer>
|
||||
</LoggedInUser.Provider>
|
||||
);
|
||||
|
||||
const streamAmy = ReactDOMServer.renderToNodeStream(
|
||||
AppWithUser('Amy'),
|
||||
).setEncoding('utf8');
|
||||
const streamBob = ReactDOMServer.renderToNodeStream(
|
||||
AppWithUser('Bob'),
|
||||
).setEncoding('utf8');
|
||||
|
||||
// Testing by filling the buffer using internal _read() with a small
|
||||
// number of bytes to avoid a test case which needs to align to a
|
||||
// highWaterMark boundary of 2^14 chars.
|
||||
streamAmy._read(20);
|
||||
streamBob._read(20);
|
||||
streamAmy._read(20);
|
||||
streamBob._read(20);
|
||||
|
||||
expect(streamAmy.read()).toBe('<header>Amy</header><footer>Amy</footer>');
|
||||
expect(streamBob.read()).toBe('<header>Bob</header><footer>Bob</footer>');
|
||||
});
|
||||
|
||||
it('does not pollute parallel node streams when many are used', () => {
|
||||
const CurrentIndex = React.createContext();
|
||||
|
||||
const NthRender = index => (
|
||||
<CurrentIndex.Provider value={index}>
|
||||
<header>
|
||||
<CurrentIndex.Consumer>{idx => idx}</CurrentIndex.Consumer>
|
||||
</header>
|
||||
<footer>
|
||||
<CurrentIndex.Consumer>{idx => idx}</CurrentIndex.Consumer>
|
||||
</footer>
|
||||
</CurrentIndex.Provider>
|
||||
);
|
||||
|
||||
let streams = [];
|
||||
|
||||
// Test with more than 32 streams to test that growing the thread count
|
||||
// works properly.
|
||||
let streamCount = 34;
|
||||
|
||||
for (let i = 0; i < streamCount; i++) {
|
||||
streams[i] = ReactDOMServer.renderToNodeStream(
|
||||
NthRender(i % 2 === 0 ? 'Expected to be recreated' : i),
|
||||
).setEncoding('utf8');
|
||||
}
|
||||
|
||||
// Testing by filling the buffer using internal _read() with a small
|
||||
// number of bytes to avoid a test case which needs to align to a
|
||||
// highWaterMark boundary of 2^14 chars.
|
||||
for (let i = 0; i < streamCount; i++) {
|
||||
streams[i]._read(20);
|
||||
}
|
||||
|
||||
// Early destroy every other stream
|
||||
for (let i = 0; i < streamCount; i += 2) {
|
||||
streams[i].destroy();
|
||||
}
|
||||
|
||||
// Recreate those same streams.
|
||||
for (let i = 0; i < streamCount; i += 2) {
|
||||
streams[i] = ReactDOMServer.renderToNodeStream(
|
||||
NthRender(i),
|
||||
).setEncoding('utf8');
|
||||
}
|
||||
|
||||
// Read a bit from all streams again.
|
||||
for (let i = 0; i < streamCount; i++) {
|
||||
streams[i]._read(20);
|
||||
}
|
||||
|
||||
// Assert that all stream rendered the expected output.
|
||||
for (let i = 0; i < streamCount; i++) {
|
||||
expect(streams[i].read()).toBe(
|
||||
'<header>' + i + '</header><footer>' + i + '</footer>',
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -14,11 +14,6 @@ const ReactDOMServerIntegrationUtils = require('./utils/ReactDOMServerIntegratio
|
||||
let React;
|
||||
let ReactDOM;
|
||||
let ReactDOMServer;
|
||||
let forwardRef;
|
||||
let memo;
|
||||
let yieldedValues;
|
||||
let yieldValue;
|
||||
let clearYields;
|
||||
|
||||
function initModules() {
|
||||
// Reset warning cache.
|
||||
@@ -26,18 +21,6 @@ function initModules() {
|
||||
React = require('react');
|
||||
ReactDOM = require('react-dom');
|
||||
ReactDOMServer = require('react-dom/server');
|
||||
forwardRef = React.forwardRef;
|
||||
memo = React.memo;
|
||||
|
||||
yieldedValues = [];
|
||||
yieldValue = value => {
|
||||
yieldedValues.push(value);
|
||||
};
|
||||
clearYields = () => {
|
||||
const ret = yieldedValues;
|
||||
yieldedValues = [];
|
||||
return ret;
|
||||
};
|
||||
|
||||
// Make them available to the helpers.
|
||||
return {
|
||||
@@ -57,7 +40,7 @@ describe('ReactDOMServerIntegration', () => {
|
||||
const FunctionComponent = ({label, forwardedRef}) => (
|
||||
<div ref={forwardedRef}>{label}</div>
|
||||
);
|
||||
const WrappedFunctionComponent = forwardRef((props, ref) => (
|
||||
const WrappedFunctionComponent = React.forwardRef((props, ref) => (
|
||||
<FunctionComponent {...props} forwardedRef={ref} />
|
||||
));
|
||||
|
||||
@@ -82,57 +65,4 @@ describe('ReactDOMServerIntegration', () => {
|
||||
expect(div.tagName).toBe('DIV');
|
||||
expect(div.textContent).toBe('Test');
|
||||
});
|
||||
|
||||
describe('memoized function components', () => {
|
||||
beforeEach(() => {
|
||||
resetModules();
|
||||
});
|
||||
|
||||
function Text({text}) {
|
||||
yieldValue(text);
|
||||
return <span>{text}</span>;
|
||||
}
|
||||
|
||||
function Counter({count}) {
|
||||
return <Text text={'Count: ' + count} />;
|
||||
}
|
||||
|
||||
itRenders('basic render', async render => {
|
||||
const MemoCounter = memo(Counter);
|
||||
const domNode = await render(<MemoCounter count={0} />);
|
||||
expect(domNode.textContent).toEqual('Count: 0');
|
||||
});
|
||||
|
||||
itRenders('composition with forwardRef', async render => {
|
||||
const RefCounter = (props, ref) => <Counter count={ref.current} />;
|
||||
const MemoRefCounter = memo(forwardRef(RefCounter));
|
||||
|
||||
const ref = React.createRef();
|
||||
ref.current = 0;
|
||||
await render(<MemoRefCounter ref={ref} />);
|
||||
|
||||
expect(clearYields()).toEqual(['Count: 0']);
|
||||
});
|
||||
|
||||
itRenders('with comparator', async render => {
|
||||
const MemoCounter = memo(Counter, (oldProps, newProps) => false);
|
||||
await render(<MemoCounter count={0} />);
|
||||
expect(clearYields()).toEqual(['Count: 0']);
|
||||
});
|
||||
|
||||
itRenders(
|
||||
'comparator functions are not invoked on the server',
|
||||
async render => {
|
||||
const MemoCounter = React.memo(Counter, (oldProps, newProps) => {
|
||||
yieldValue(
|
||||
`Old count: ${oldProps.count}, New count: ${newProps.count}`,
|
||||
);
|
||||
return oldProps.count === newProps.count;
|
||||
});
|
||||
|
||||
await render(<MemoCounter count={0} />);
|
||||
expect(clearYields()).toEqual(['Count: 0']);
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -43,48 +43,16 @@ describe('ReactDOMServerSuspense', () => {
|
||||
resetModules();
|
||||
});
|
||||
|
||||
function Text(props) {
|
||||
return <div>{props.text}</div>;
|
||||
}
|
||||
|
||||
function AsyncText(props) {
|
||||
throw new Promise(() => {});
|
||||
}
|
||||
|
||||
it('should render the children when no promise is thrown', async () => {
|
||||
it('should always render the fallback when a placeholder is encountered', async () => {
|
||||
const Suspended = props => {
|
||||
throw new Promise(() => {});
|
||||
};
|
||||
const e = await serverRender(
|
||||
<React.Suspense fallback={<Text text="Fallback" />}>
|
||||
<Text text="Children" />
|
||||
</React.Suspense>,
|
||||
<React.unstable_Suspense fallback={<div />}>
|
||||
<Suspended />
|
||||
</React.unstable_Suspense>,
|
||||
);
|
||||
|
||||
expect(e.tagName).toBe('DIV');
|
||||
expect(e.textContent).toBe('Children');
|
||||
});
|
||||
|
||||
it('should render the fallback when a promise thrown', async () => {
|
||||
const e = await serverRender(
|
||||
<React.Suspense fallback={<Text text="Fallback" />}>
|
||||
<AsyncText text="Children" />
|
||||
</React.Suspense>,
|
||||
);
|
||||
|
||||
expect(e.tagName).toBe('DIV');
|
||||
expect(e.textContent).toBe('Fallback');
|
||||
});
|
||||
|
||||
it('should work with nested suspense components', async () => {
|
||||
const e = await serverRender(
|
||||
<React.Suspense fallback={<Text text="Fallback" />}>
|
||||
<div>
|
||||
<Text text="Children" />
|
||||
<React.Suspense fallback={<Text text="Fallback" />}>
|
||||
<AsyncText text="Children" />
|
||||
</React.Suspense>
|
||||
</div>
|
||||
</React.Suspense>,
|
||||
);
|
||||
|
||||
expect(e.innerHTML).toBe('<div>Children</div><div>Fallback</div>');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,147 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) Facebook, Inc. and its affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @emails react-core
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
describe('ReactDOMShorthandCSSPropertyCollision', () => {
|
||||
let ReactFeatureFlags;
|
||||
let React;
|
||||
let ReactDOM;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetModules();
|
||||
ReactFeatureFlags = require('shared/ReactFeatureFlags');
|
||||
ReactFeatureFlags.warnAboutShorthandPropertyCollision = true;
|
||||
React = require('react');
|
||||
ReactDOM = require('react-dom');
|
||||
});
|
||||
|
||||
it('should warn for conflicting CSS shorthand updates', () => {
|
||||
const container = document.createElement('div');
|
||||
ReactDOM.render(<div style={{font: 'foo', fontStyle: 'bar'}} />, container);
|
||||
expect(() =>
|
||||
ReactDOM.render(<div style={{font: 'foo'}} />, container),
|
||||
).toWarnDev(
|
||||
'Warning: Removing a style property during rerender (fontStyle) ' +
|
||||
'when a conflicting property is set (font) can lead to styling ' +
|
||||
"bugs. To avoid this, don't mix shorthand and non-shorthand " +
|
||||
'properties for the same value; instead, replace the shorthand ' +
|
||||
'with separate values.' +
|
||||
'\n in div (at **)',
|
||||
);
|
||||
|
||||
// These updates are OK and don't warn:
|
||||
ReactDOM.render(<div style={{font: 'qux', fontStyle: 'bar'}} />, container);
|
||||
ReactDOM.render(<div style={{font: 'foo', fontStyle: 'baz'}} />, container);
|
||||
|
||||
expect(() =>
|
||||
ReactDOM.render(
|
||||
<div style={{font: 'qux', fontStyle: 'baz'}} />,
|
||||
container,
|
||||
),
|
||||
).toWarnDev(
|
||||
'Warning: Updating a style property during rerender (font) when ' +
|
||||
'a conflicting property is set (fontStyle) can lead to styling ' +
|
||||
"bugs. To avoid this, don't mix shorthand and non-shorthand " +
|
||||
'properties for the same value; instead, replace the shorthand ' +
|
||||
'with separate values.' +
|
||||
'\n in div (at **)',
|
||||
);
|
||||
expect(() =>
|
||||
ReactDOM.render(<div style={{fontStyle: 'baz'}} />, container),
|
||||
).toWarnDev(
|
||||
'Warning: Removing a style property during rerender (font) when ' +
|
||||
'a conflicting property is set (fontStyle) can lead to styling ' +
|
||||
"bugs. To avoid this, don't mix shorthand and non-shorthand " +
|
||||
'properties for the same value; instead, replace the shorthand ' +
|
||||
'with separate values.' +
|
||||
'\n in div (at **)',
|
||||
);
|
||||
|
||||
// A bit of a special case: backgroundPosition isn't technically longhand
|
||||
// (it expands to backgroundPosition{X,Y} but so does background)
|
||||
ReactDOM.render(
|
||||
<div style={{background: 'yellow', backgroundPosition: 'center'}} />,
|
||||
container,
|
||||
);
|
||||
expect(() =>
|
||||
ReactDOM.render(<div style={{background: 'yellow'}} />, container),
|
||||
).toWarnDev(
|
||||
'Warning: Removing a style property during rerender ' +
|
||||
'(backgroundPosition) when a conflicting property is set ' +
|
||||
"(background) can lead to styling bugs. To avoid this, don't mix " +
|
||||
'shorthand and non-shorthand properties for the same value; ' +
|
||||
'instead, replace the shorthand with separate values.' +
|
||||
'\n in div (at **)',
|
||||
);
|
||||
ReactDOM.render(
|
||||
<div style={{background: 'yellow', backgroundPosition: 'center'}} />,
|
||||
container,
|
||||
);
|
||||
// But setting them at the same time is OK:
|
||||
ReactDOM.render(
|
||||
<div style={{background: 'green', backgroundPosition: 'top'}} />,
|
||||
container,
|
||||
);
|
||||
expect(() =>
|
||||
ReactDOM.render(<div style={{backgroundPosition: 'top'}} />, container),
|
||||
).toWarnDev(
|
||||
'Warning: Removing a style property during rerender (background) ' +
|
||||
'when a conflicting property is set (backgroundPosition) can lead ' +
|
||||
"to styling bugs. To avoid this, don't mix shorthand and " +
|
||||
'non-shorthand properties for the same value; instead, replace the ' +
|
||||
'shorthand with separate values.' +
|
||||
'\n in div (at **)',
|
||||
);
|
||||
|
||||
// A bit of an even more special case: borderLeft and borderStyle overlap.
|
||||
ReactDOM.render(
|
||||
<div style={{borderStyle: 'dotted', borderLeft: '1px solid red'}} />,
|
||||
container,
|
||||
);
|
||||
expect(() =>
|
||||
ReactDOM.render(<div style={{borderLeft: '1px solid red'}} />, container),
|
||||
).toWarnDev(
|
||||
'Warning: Removing a style property during rerender (borderStyle) ' +
|
||||
'when a conflicting property is set (borderLeft) can lead to ' +
|
||||
"styling bugs. To avoid this, don't mix shorthand and " +
|
||||
'non-shorthand properties for the same value; instead, replace the ' +
|
||||
'shorthand with separate values.' +
|
||||
'\n in div (at **)',
|
||||
);
|
||||
expect(() =>
|
||||
ReactDOM.render(
|
||||
<div style={{borderStyle: 'dashed', borderLeft: '1px solid red'}} />,
|
||||
container,
|
||||
),
|
||||
).toWarnDev(
|
||||
'Warning: Updating a style property during rerender (borderStyle) ' +
|
||||
'when a conflicting property is set (borderLeft) can lead to ' +
|
||||
"styling bugs. To avoid this, don't mix shorthand and " +
|
||||
'non-shorthand properties for the same value; instead, replace the ' +
|
||||
'shorthand with separate values.' +
|
||||
'\n in div (at **)',
|
||||
);
|
||||
// But setting them at the same time is OK:
|
||||
ReactDOM.render(
|
||||
<div style={{borderStyle: 'dotted', borderLeft: '2px solid red'}} />,
|
||||
container,
|
||||
);
|
||||
expect(() =>
|
||||
ReactDOM.render(<div style={{borderStyle: 'dotted'}} />, container),
|
||||
).toWarnDev(
|
||||
'Warning: Removing a style property during rerender (borderLeft) ' +
|
||||
'when a conflicting property is set (borderStyle) can lead to ' +
|
||||
"styling bugs. To avoid this, don't mix shorthand and " +
|
||||
'non-shorthand properties for the same value; instead, replace the ' +
|
||||
'shorthand with separate values.' +
|
||||
'\n in div (at **)',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -14,6 +14,7 @@ let React;
|
||||
let ReactDOM;
|
||||
let Suspense;
|
||||
let ReactCache;
|
||||
let cache;
|
||||
let TextResource;
|
||||
|
||||
describe('ReactDOMSuspensePlaceholder', () => {
|
||||
@@ -22,15 +23,18 @@ describe('ReactDOMSuspensePlaceholder', () => {
|
||||
beforeEach(() => {
|
||||
jest.resetModules();
|
||||
ReactFeatureFlags = require('shared/ReactFeatureFlags');
|
||||
ReactFeatureFlags.enableHooks = true;
|
||||
ReactFeatureFlags.enableSuspense = true;
|
||||
React = require('react');
|
||||
ReactDOM = require('react-dom');
|
||||
ReactCache = require('react-cache');
|
||||
Suspense = React.Suspense;
|
||||
Suspense = React.unstable_Suspense;
|
||||
container = document.createElement('div');
|
||||
document.body.appendChild(container);
|
||||
|
||||
TextResource = ReactCache.unstable_createResource(([text, ms = 0]) => {
|
||||
function invalidateCache() {
|
||||
cache = ReactCache.createCache(invalidateCache);
|
||||
}
|
||||
invalidateCache();
|
||||
TextResource = ReactCache.createResource(([text, ms = 0]) => {
|
||||
return new Promise((resolve, reject) =>
|
||||
setTimeout(() => {
|
||||
resolve(text);
|
||||
@@ -39,10 +43,6 @@ describe('ReactDOMSuspensePlaceholder', () => {
|
||||
}, ([text, ms]) => text);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
document.body.removeChild(container);
|
||||
});
|
||||
|
||||
function advanceTimers(ms) {
|
||||
// Note: This advances Jest's virtual time but not React's. Use
|
||||
// ReactNoop.expire for that.
|
||||
@@ -51,8 +51,9 @@ describe('ReactDOMSuspensePlaceholder', () => {
|
||||
}
|
||||
jest.advanceTimersByTime(ms);
|
||||
// Wait until the end of the current tick
|
||||
// We cannot use a timer since we're faking them
|
||||
return Promise.resolve().then(() => {});
|
||||
return new Promise(resolve => {
|
||||
setImmediate(resolve);
|
||||
});
|
||||
}
|
||||
|
||||
function Text(props) {
|
||||
@@ -61,7 +62,7 @@ describe('ReactDOMSuspensePlaceholder', () => {
|
||||
|
||||
function AsyncText(props) {
|
||||
const text = props.text;
|
||||
TextResource.read([props.text, props.ms]);
|
||||
TextResource.read(cache, [props.text, props.ms]);
|
||||
return text;
|
||||
}
|
||||
|
||||
@@ -116,110 +117,4 @@ describe('ReactDOMSuspensePlaceholder', () => {
|
||||
|
||||
expect(container.textContent).toEqual('ABC');
|
||||
});
|
||||
|
||||
it(
|
||||
'outside concurrent mode, re-hides children if their display is updated ' +
|
||||
'but the boundary is still showing the fallback',
|
||||
async () => {
|
||||
const {useState} = React;
|
||||
|
||||
let setIsVisible;
|
||||
function Sibling({children}) {
|
||||
const [isVisible, _setIsVisible] = useState(false);
|
||||
setIsVisible = _setIsVisible;
|
||||
return (
|
||||
<span style={{display: isVisible ? 'inline' : 'none'}}>
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<Suspense maxDuration={500} fallback={<Text text="Loading..." />}>
|
||||
<Sibling>Sibling</Sibling>
|
||||
<span>
|
||||
<AsyncText ms={1000} text="Async" />
|
||||
</span>
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
ReactDOM.render(<App />, container);
|
||||
expect(container.innerHTML).toEqual(
|
||||
'<span style="display: none;">Sibling</span><span style="display: none;"></span>Loading...',
|
||||
);
|
||||
|
||||
setIsVisible(true);
|
||||
expect(container.innerHTML).toEqual(
|
||||
'<span style="display: none;">Sibling</span><span style="display: none;"></span>Loading...',
|
||||
);
|
||||
|
||||
await advanceTimers(1000);
|
||||
|
||||
expect(container.innerHTML).toEqual(
|
||||
'<span style="display: inline;">Sibling</span><span style="">Async</span>',
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
// Regression test for https://github.com/facebook/react/issues/14188
|
||||
it('can call findDOMNode() in a suspended component commit phase', async () => {
|
||||
const log = [];
|
||||
const Lazy = React.lazy(
|
||||
() =>
|
||||
new Promise(resolve =>
|
||||
resolve({
|
||||
default() {
|
||||
return 'lazy';
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
class Child extends React.Component {
|
||||
componentDidMount() {
|
||||
log.push('cDM ' + this.props.id);
|
||||
ReactDOM.findDOMNode(this);
|
||||
}
|
||||
componentDidUpdate() {
|
||||
log.push('cDU ' + this.props.id);
|
||||
ReactDOM.findDOMNode(this);
|
||||
}
|
||||
render() {
|
||||
return 'child';
|
||||
}
|
||||
}
|
||||
|
||||
const buttonRef = React.createRef();
|
||||
class App extends React.Component {
|
||||
state = {
|
||||
suspend: false,
|
||||
};
|
||||
handleClick = () => {
|
||||
this.setState({suspend: true});
|
||||
};
|
||||
render() {
|
||||
return (
|
||||
<React.Suspense fallback="Loading">
|
||||
<Child id="first" />
|
||||
<button ref={buttonRef} onClick={this.handleClick}>
|
||||
Suspend
|
||||
</button>
|
||||
<Child id="second" />
|
||||
{this.state.suspend && <Lazy />}
|
||||
</React.Suspense>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
ReactDOM.render(<App />, container);
|
||||
|
||||
expect(log).toEqual(['cDM first', 'cDM second']);
|
||||
log.length = 0;
|
||||
|
||||
buttonRef.current.dispatchEvent(new MouseEvent('click', {bubbles: true}));
|
||||
await Lazy;
|
||||
expect(log).toEqual(['cDU first', 'cDU second']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -28,8 +28,6 @@ describe('ReactErrorBoundaries', () => {
|
||||
let BrokenComponentWillMountErrorBoundary;
|
||||
let BrokenComponentDidMountErrorBoundary;
|
||||
let BrokenRender;
|
||||
let BrokenUseEffect;
|
||||
let BrokenUseLayoutEffect;
|
||||
let ErrorBoundary;
|
||||
let ErrorMessage;
|
||||
let NoopErrorBoundary;
|
||||
@@ -37,11 +35,9 @@ describe('ReactErrorBoundaries', () => {
|
||||
let Normal;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers();
|
||||
jest.resetModules();
|
||||
PropTypes = require('prop-types');
|
||||
ReactFeatureFlags = require('shared/ReactFeatureFlags');
|
||||
ReactFeatureFlags.enableHooks = true;
|
||||
ReactFeatureFlags.replayFailedUnitOfWorkWithInvokeGuardedCallback = false;
|
||||
ReactDOM = require('react-dom');
|
||||
React = require('react');
|
||||
@@ -390,28 +386,6 @@ describe('ReactErrorBoundaries', () => {
|
||||
}
|
||||
};
|
||||
|
||||
BrokenUseEffect = props => {
|
||||
log.push('BrokenUseEffect render');
|
||||
|
||||
React.useEffect(() => {
|
||||
log.push('BrokenUseEffect useEffect [!]');
|
||||
throw new Error('Hello');
|
||||
});
|
||||
|
||||
return props.children;
|
||||
};
|
||||
|
||||
BrokenUseLayoutEffect = props => {
|
||||
log.push('BrokenUseLayoutEffect render');
|
||||
|
||||
React.useLayoutEffect(() => {
|
||||
log.push('BrokenUseLayoutEffect useLayoutEffect [!]');
|
||||
throw new Error('Hello');
|
||||
});
|
||||
|
||||
return props.children;
|
||||
};
|
||||
|
||||
NoopErrorBoundary = class extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
@@ -1821,67 +1795,6 @@ describe('ReactErrorBoundaries', () => {
|
||||
expect(log).toEqual(['ErrorBoundary componentWillUnmount']);
|
||||
});
|
||||
|
||||
it('catches errors in useEffect', () => {
|
||||
const container = document.createElement('div');
|
||||
ReactDOM.render(
|
||||
<ErrorBoundary>
|
||||
<BrokenUseEffect>Initial value</BrokenUseEffect>
|
||||
</ErrorBoundary>,
|
||||
container,
|
||||
);
|
||||
expect(log).toEqual([
|
||||
'ErrorBoundary constructor',
|
||||
'ErrorBoundary componentWillMount',
|
||||
'ErrorBoundary render success',
|
||||
'BrokenUseEffect render',
|
||||
'ErrorBoundary componentDidMount',
|
||||
]);
|
||||
|
||||
expect(container.firstChild.textContent).toBe('Initial value');
|
||||
log.length = 0;
|
||||
|
||||
jest.runAllTimers();
|
||||
|
||||
// Flush passive effects and handle the error
|
||||
expect(log).toEqual([
|
||||
'BrokenUseEffect useEffect [!]',
|
||||
// Handle the error
|
||||
'ErrorBoundary static getDerivedStateFromError',
|
||||
'ErrorBoundary componentWillUpdate',
|
||||
'ErrorBoundary render error',
|
||||
'ErrorBoundary componentDidUpdate',
|
||||
]);
|
||||
|
||||
expect(container.firstChild.textContent).toBe('Caught an error: Hello.');
|
||||
});
|
||||
|
||||
it('catches errors in useLayoutEffect', () => {
|
||||
const container = document.createElement('div');
|
||||
ReactDOM.render(
|
||||
<ErrorBoundary>
|
||||
<BrokenUseLayoutEffect>Initial value</BrokenUseLayoutEffect>
|
||||
</ErrorBoundary>,
|
||||
container,
|
||||
);
|
||||
expect(log).toEqual([
|
||||
'ErrorBoundary constructor',
|
||||
'ErrorBoundary componentWillMount',
|
||||
'ErrorBoundary render success',
|
||||
'BrokenUseLayoutEffect render',
|
||||
'BrokenUseLayoutEffect useLayoutEffect [!]',
|
||||
// Fiber proceeds with the hooks
|
||||
'ErrorBoundary componentDidMount',
|
||||
// The error propagates to the higher boundary
|
||||
'ErrorBoundary static getDerivedStateFromError',
|
||||
// Fiber retries from the root
|
||||
'ErrorBoundary componentWillUpdate',
|
||||
'ErrorBoundary render error',
|
||||
'ErrorBoundary componentDidUpdate',
|
||||
]);
|
||||
|
||||
expect(container.firstChild.textContent).toBe('Caught an error: Hello.');
|
||||
});
|
||||
|
||||
it('propagates errors inside boundary during componentDidMount', () => {
|
||||
const container = document.createElement('div');
|
||||
ReactDOM.render(
|
||||
@@ -2236,19 +2149,4 @@ describe('ReactErrorBoundaries', () => {
|
||||
expect(componentDidCatchError).toBe(thrownError);
|
||||
expect(getDerivedStateFromErrorError).toBe(thrownError);
|
||||
});
|
||||
|
||||
it('should catch errors from invariants in completion phase', () => {
|
||||
const container = document.createElement('div');
|
||||
ReactDOM.render(
|
||||
<ErrorBoundary>
|
||||
<input>
|
||||
<div />
|
||||
</input>
|
||||
</ErrorBoundary>,
|
||||
container,
|
||||
);
|
||||
expect(container.textContent).toContain(
|
||||
'Caught an error: input is a void element tag',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -556,52 +556,6 @@ describe('ReactDOMServer', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('renderToNodeStream', () => {
|
||||
it('should generate simple markup', () => {
|
||||
const SuccessfulElement = React.createElement(() => <img />);
|
||||
const response = ReactDOMServer.renderToNodeStream(SuccessfulElement);
|
||||
expect(response.read().toString()).toMatch(
|
||||
new RegExp('<img data-reactroot=""' + '/>'),
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle errors correctly', () => {
|
||||
const FailingElement = React.createElement(() => {
|
||||
throw new Error('An Error');
|
||||
});
|
||||
const response = ReactDOMServer.renderToNodeStream(FailingElement);
|
||||
return new Promise(resolve => {
|
||||
response.once('error', () => {
|
||||
resolve();
|
||||
});
|
||||
expect(response.read()).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('renderToStaticNodeStream', () => {
|
||||
it('should generate simple markup', () => {
|
||||
const SuccessfulElement = React.createElement(() => <img />);
|
||||
const response = ReactDOMServer.renderToStaticNodeStream(
|
||||
SuccessfulElement,
|
||||
);
|
||||
expect(response.read().toString()).toMatch(new RegExp('<img' + '/>'));
|
||||
});
|
||||
|
||||
it('should handle errors correctly', () => {
|
||||
const FailingElement = React.createElement(() => {
|
||||
throw new Error('An Error');
|
||||
});
|
||||
const response = ReactDOMServer.renderToStaticNodeStream(FailingElement);
|
||||
return new Promise(resolve => {
|
||||
response.once('error', () => {
|
||||
resolve();
|
||||
});
|
||||
expect(response.read()).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('warns with a no-op when an async setState is triggered', () => {
|
||||
class Foo extends React.Component {
|
||||
UNSAFE_componentWillMount() {
|
||||
@@ -656,7 +610,7 @@ describe('ReactDOMServer', () => {
|
||||
|
||||
it('throws for unsupported types on the server', () => {
|
||||
expect(() => {
|
||||
ReactDOMServer.renderToString(<React.Suspense />);
|
||||
ReactDOMServer.renderToString(<React.unstable_Suspense />);
|
||||
}).toThrow('ReactDOMServer does not yet support Suspense.');
|
||||
|
||||
async function fakeImport(result) {
|
||||
|
||||
@@ -444,16 +444,20 @@ describe('ReactDOMServerHydration', () => {
|
||||
});
|
||||
|
||||
it('should be able to use lazy components after hydrating', async () => {
|
||||
async function fakeImport(result) {
|
||||
return {default: result};
|
||||
}
|
||||
|
||||
const Lazy = React.lazy(
|
||||
() =>
|
||||
new Promise(resolve => {
|
||||
setTimeout(
|
||||
() =>
|
||||
resolve({
|
||||
default: function World() {
|
||||
resolve(
|
||||
fakeImport(function World() {
|
||||
return 'world';
|
||||
},
|
||||
}),
|
||||
}),
|
||||
),
|
||||
1000,
|
||||
);
|
||||
}),
|
||||
@@ -470,9 +474,9 @@ describe('ReactDOMServerHydration', () => {
|
||||
<div>
|
||||
Hello{' '}
|
||||
{this.state.isClient && (
|
||||
<React.Suspense fallback="loading">
|
||||
<React.unstable_Suspense fallback="loading">
|
||||
<Lazy />
|
||||
</React.Suspense>
|
||||
</React.unstable_Suspense>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
@@ -487,7 +491,7 @@ describe('ReactDOMServerHydration', () => {
|
||||
expect(element.textContent).toBe('Hello loading');
|
||||
|
||||
jest.runAllTimers();
|
||||
await Promise.resolve();
|
||||
await Lazy;
|
||||
expect(element.textContent).toBe('Hello world');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -41,7 +41,7 @@ module.exports = function(initModules) {
|
||||
if (console.error.calls && console.error.calls.reset) {
|
||||
console.error.calls.reset();
|
||||
} else {
|
||||
// TODO: Rewrite tests that use this helper to enumerate expected errors.
|
||||
// TODO: Rewrite tests that use this helper to enumerate expeceted errors.
|
||||
// This will enable the helper to use the .toWarnDev() matcher instead of spying.
|
||||
spyOnDev(console, 'error');
|
||||
}
|
||||
|
||||
166
packages/react-dom/src/client/ReactDOM.js
vendored
166
packages/react-dom/src/client/ReactDOM.js
vendored
@@ -19,58 +19,25 @@ import type {Container} from './ReactDOMHostConfig';
|
||||
import '../shared/checkReact';
|
||||
import './ReactDOMClientInjection';
|
||||
|
||||
import {
|
||||
computeUniqueAsyncExpiration,
|
||||
findHostInstanceWithNoPortals,
|
||||
updateContainerAtExpirationTime,
|
||||
flushRoot,
|
||||
createContainer,
|
||||
updateContainer,
|
||||
batchedUpdates,
|
||||
unbatchedUpdates,
|
||||
interactiveUpdates,
|
||||
flushInteractiveUpdates,
|
||||
flushSync,
|
||||
flushControlled,
|
||||
injectIntoDevTools,
|
||||
getPublicRootInstance,
|
||||
findHostInstance,
|
||||
findHostInstanceWithWarning,
|
||||
} from 'react-reconciler/inline.dom';
|
||||
import {createPortal as createPortalImpl} from 'shared/ReactPortal';
|
||||
import * as DOMRenderer from 'react-reconciler/inline.dom';
|
||||
import * as ReactPortal from 'shared/ReactPortal';
|
||||
import {canUseDOM} from 'shared/ExecutionEnvironment';
|
||||
import {setBatchingImplementation} from 'events/ReactGenericBatching';
|
||||
import {
|
||||
setRestoreImplementation,
|
||||
enqueueStateRestore,
|
||||
restoreStateIfNeeded,
|
||||
} from 'events/ReactControlledComponent';
|
||||
import {
|
||||
injection as EventPluginHubInjection,
|
||||
runEventsInBatch,
|
||||
} from 'events/EventPluginHub';
|
||||
import {eventNameDispatchConfigs} from 'events/EventPluginRegistry';
|
||||
import {
|
||||
accumulateTwoPhaseDispatches,
|
||||
accumulateDirectDispatches,
|
||||
} from 'events/EventPropagators';
|
||||
import {has as hasInstance} from 'shared/ReactInstanceMap';
|
||||
import * as ReactGenericBatching from 'events/ReactGenericBatching';
|
||||
import * as ReactControlledComponent from 'events/ReactControlledComponent';
|
||||
import * as EventPluginHub from 'events/EventPluginHub';
|
||||
import * as EventPluginRegistry from 'events/EventPluginRegistry';
|
||||
import * as EventPropagators from 'events/EventPropagators';
|
||||
import * as ReactInstanceMap from 'shared/ReactInstanceMap';
|
||||
import ReactVersion from 'shared/ReactVersion';
|
||||
import ReactSharedInternals from 'shared/ReactSharedInternals';
|
||||
import getComponentName from 'shared/getComponentName';
|
||||
import invariant from 'shared/invariant';
|
||||
import lowPriorityWarning from 'shared/lowPriorityWarning';
|
||||
import warningWithoutStack from 'shared/warningWithoutStack';
|
||||
import {enableStableConcurrentModeAPIs} from 'shared/ReactFeatureFlags';
|
||||
|
||||
import {
|
||||
getInstanceFromNode,
|
||||
getNodeFromInstance,
|
||||
getFiberCurrentPropsFromNode,
|
||||
getClosestInstanceFromNode,
|
||||
} from './ReactDOMComponentTree';
|
||||
import * as ReactDOMComponentTree from './ReactDOMComponentTree';
|
||||
import {restoreControlledState} from './ReactDOMComponent';
|
||||
import {dispatchEvent} from '../events/ReactDOMEventListener';
|
||||
import * as ReactDOMEventListener from '../events/ReactDOMEventListener';
|
||||
import {
|
||||
ELEMENT_NODE,
|
||||
COMMENT_NODE,
|
||||
@@ -106,7 +73,7 @@ if (__DEV__) {
|
||||
|
||||
topLevelUpdateWarnings = (container: DOMContainer) => {
|
||||
if (container._reactRootContainer && container.nodeType !== COMMENT_NODE) {
|
||||
const hostInstance = findHostInstanceWithNoPortals(
|
||||
const hostInstance = DOMRenderer.findHostInstanceWithNoPortals(
|
||||
container._reactRootContainer._internalRoot.current,
|
||||
);
|
||||
if (hostInstance) {
|
||||
@@ -122,7 +89,9 @@ if (__DEV__) {
|
||||
|
||||
const isRootRenderedBySomeReact = !!container._reactRootContainer;
|
||||
const rootEl = getReactRootElementInContainer(container);
|
||||
const hasNonRootReactChild = !!(rootEl && getInstanceFromNode(rootEl));
|
||||
const hasNonRootReactChild = !!(
|
||||
rootEl && ReactDOMComponentTree.getInstanceFromNode(rootEl)
|
||||
);
|
||||
|
||||
warningWithoutStack(
|
||||
!hasNonRootReactChild || isRootRenderedBySomeReact,
|
||||
@@ -155,7 +124,7 @@ if (__DEV__) {
|
||||
};
|
||||
}
|
||||
|
||||
setRestoreImplementation(restoreControlledState);
|
||||
ReactControlledComponent.setRestoreImplementation(restoreControlledState);
|
||||
|
||||
export type DOMContainer =
|
||||
| (Element & {
|
||||
@@ -195,7 +164,7 @@ type Root = {
|
||||
};
|
||||
|
||||
function ReactBatch(root: ReactRoot) {
|
||||
const expirationTime = computeUniqueAsyncExpiration();
|
||||
const expirationTime = DOMRenderer.computeUniqueAsyncExpiration();
|
||||
this._expirationTime = expirationTime;
|
||||
this._root = root;
|
||||
this._next = null;
|
||||
@@ -215,7 +184,7 @@ ReactBatch.prototype.render = function(children: ReactNodeList) {
|
||||
const internalRoot = this._root._internalRoot;
|
||||
const expirationTime = this._expirationTime;
|
||||
const work = new ReactWork();
|
||||
updateContainerAtExpirationTime(
|
||||
DOMRenderer.updateContainerAtExpirationTime(
|
||||
children,
|
||||
internalRoot,
|
||||
null,
|
||||
@@ -286,7 +255,7 @@ ReactBatch.prototype.commit = function() {
|
||||
|
||||
// Synchronously flush all the work up to this batch's expiration time.
|
||||
this._defer = false;
|
||||
flushRoot(internalRoot, expirationTime);
|
||||
DOMRenderer.flushRoot(internalRoot, expirationTime);
|
||||
|
||||
// Pop the batch from the list.
|
||||
const next = this._next;
|
||||
@@ -366,7 +335,7 @@ function ReactRoot(
|
||||
isConcurrent: boolean,
|
||||
hydrate: boolean,
|
||||
) {
|
||||
const root = createContainer(container, isConcurrent, hydrate);
|
||||
const root = DOMRenderer.createContainer(container, isConcurrent, hydrate);
|
||||
this._internalRoot = root;
|
||||
}
|
||||
ReactRoot.prototype.render = function(
|
||||
@@ -382,7 +351,7 @@ ReactRoot.prototype.render = function(
|
||||
if (callback !== null) {
|
||||
work.then(callback);
|
||||
}
|
||||
updateContainer(children, root, null, work._onCommit);
|
||||
DOMRenderer.updateContainer(children, root, null, work._onCommit);
|
||||
return work;
|
||||
};
|
||||
ReactRoot.prototype.unmount = function(callback: ?() => mixed): Work {
|
||||
@@ -395,7 +364,7 @@ ReactRoot.prototype.unmount = function(callback: ?() => mixed): Work {
|
||||
if (callback !== null) {
|
||||
work.then(callback);
|
||||
}
|
||||
updateContainer(null, root, null, work._onCommit);
|
||||
DOMRenderer.updateContainer(null, root, null, work._onCommit);
|
||||
return work;
|
||||
};
|
||||
ReactRoot.prototype.legacy_renderSubtreeIntoContainer = function(
|
||||
@@ -412,7 +381,7 @@ ReactRoot.prototype.legacy_renderSubtreeIntoContainer = function(
|
||||
if (callback !== null) {
|
||||
work.then(callback);
|
||||
}
|
||||
updateContainer(children, root, parentComponent, work._onCommit);
|
||||
DOMRenderer.updateContainer(children, root, parentComponent, work._onCommit);
|
||||
return work;
|
||||
};
|
||||
ReactRoot.prototype.createBatch = function(): Batch {
|
||||
@@ -430,7 +399,7 @@ ReactRoot.prototype.createBatch = function(): Batch {
|
||||
let insertBefore = firstBatch;
|
||||
while (
|
||||
insertBefore !== null &&
|
||||
insertBefore._expirationTime >= expirationTime
|
||||
insertBefore._expirationTime <= expirationTime
|
||||
) {
|
||||
insertAfter = insertBefore;
|
||||
insertBefore = insertBefore._next;
|
||||
@@ -483,10 +452,10 @@ function shouldHydrateDueToLegacyHeuristic(container) {
|
||||
);
|
||||
}
|
||||
|
||||
setBatchingImplementation(
|
||||
batchedUpdates,
|
||||
interactiveUpdates,
|
||||
flushInteractiveUpdates,
|
||||
ReactGenericBatching.setBatchingImplementation(
|
||||
DOMRenderer.batchedUpdates,
|
||||
DOMRenderer.interactiveUpdates,
|
||||
DOMRenderer.flushInteractiveUpdates,
|
||||
);
|
||||
|
||||
let warnedAboutHydrateAPI = false;
|
||||
@@ -565,12 +534,12 @@ function legacyRenderSubtreeIntoContainer(
|
||||
if (typeof callback === 'function') {
|
||||
const originalCallback = callback;
|
||||
callback = function() {
|
||||
const instance = getPublicRootInstance(root._internalRoot);
|
||||
const instance = DOMRenderer.getPublicRootInstance(root._internalRoot);
|
||||
originalCallback.call(instance);
|
||||
};
|
||||
}
|
||||
// Initial mount should not be batched.
|
||||
unbatchedUpdates(() => {
|
||||
DOMRenderer.unbatchedUpdates(() => {
|
||||
if (parentComponent != null) {
|
||||
root.legacy_renderSubtreeIntoContainer(
|
||||
parentComponent,
|
||||
@@ -585,7 +554,7 @@ function legacyRenderSubtreeIntoContainer(
|
||||
if (typeof callback === 'function') {
|
||||
const originalCallback = callback;
|
||||
callback = function() {
|
||||
const instance = getPublicRootInstance(root._internalRoot);
|
||||
const instance = DOMRenderer.getPublicRootInstance(root._internalRoot);
|
||||
originalCallback.call(instance);
|
||||
};
|
||||
}
|
||||
@@ -600,7 +569,7 @@ function legacyRenderSubtreeIntoContainer(
|
||||
root.render(children, callback);
|
||||
}
|
||||
}
|
||||
return getPublicRootInstance(root._internalRoot);
|
||||
return DOMRenderer.getPublicRootInstance(root._internalRoot);
|
||||
}
|
||||
|
||||
function createPortal(
|
||||
@@ -613,7 +582,7 @@ function createPortal(
|
||||
'Target container is not a DOM element.',
|
||||
);
|
||||
// TODO: pass ReactDOM portal implementation as third argument
|
||||
return createPortalImpl(children, container, null, key);
|
||||
return ReactPortal.createPortal(children, container, null, key);
|
||||
}
|
||||
|
||||
const ReactDOM: Object = {
|
||||
@@ -646,9 +615,12 @@ const ReactDOM: Object = {
|
||||
return (componentOrElement: any);
|
||||
}
|
||||
if (__DEV__) {
|
||||
return findHostInstanceWithWarning(componentOrElement, 'findDOMNode');
|
||||
return DOMRenderer.findHostInstanceWithWarning(
|
||||
componentOrElement,
|
||||
'findDOMNode',
|
||||
);
|
||||
}
|
||||
return findHostInstance(componentOrElement);
|
||||
return DOMRenderer.findHostInstance(componentOrElement);
|
||||
},
|
||||
|
||||
hydrate(element: React$Node, container: DOMContainer, callback: ?Function) {
|
||||
@@ -683,7 +655,7 @@ const ReactDOM: Object = {
|
||||
callback: ?Function,
|
||||
) {
|
||||
invariant(
|
||||
parentComponent != null && hasInstance(parentComponent),
|
||||
parentComponent != null && ReactInstanceMap.has(parentComponent),
|
||||
'parentComponent must be a valid React Component',
|
||||
);
|
||||
return legacyRenderSubtreeIntoContainer(
|
||||
@@ -704,7 +676,8 @@ const ReactDOM: Object = {
|
||||
if (container._reactRootContainer) {
|
||||
if (__DEV__) {
|
||||
const rootEl = getReactRootElementInContainer(container);
|
||||
const renderedByDifferentReact = rootEl && !getInstanceFromNode(rootEl);
|
||||
const renderedByDifferentReact =
|
||||
rootEl && !ReactDOMComponentTree.getInstanceFromNode(rootEl);
|
||||
warningWithoutStack(
|
||||
!renderedByDifferentReact,
|
||||
"unmountComponentAtNode(): The node you're attempting to unmount " +
|
||||
@@ -713,7 +686,7 @@ const ReactDOM: Object = {
|
||||
}
|
||||
|
||||
// Unmount should not be batched.
|
||||
unbatchedUpdates(() => {
|
||||
DOMRenderer.unbatchedUpdates(() => {
|
||||
legacyRenderSubtreeIntoContainer(null, null, container, false, () => {
|
||||
container._reactRootContainer = null;
|
||||
});
|
||||
@@ -724,7 +697,9 @@ const ReactDOM: Object = {
|
||||
} else {
|
||||
if (__DEV__) {
|
||||
const rootEl = getReactRootElementInContainer(container);
|
||||
const hasNonRootReactChild = !!(rootEl && getInstanceFromNode(rootEl));
|
||||
const hasNonRootReactChild = !!(
|
||||
rootEl && ReactDOMComponentTree.getInstanceFromNode(rootEl)
|
||||
);
|
||||
|
||||
// Check if the container itself is a React root node.
|
||||
const isContainerReactRoot =
|
||||
@@ -764,30 +739,29 @@ const ReactDOM: Object = {
|
||||
return createPortal(...args);
|
||||
},
|
||||
|
||||
unstable_batchedUpdates: batchedUpdates,
|
||||
unstable_batchedUpdates: DOMRenderer.batchedUpdates,
|
||||
|
||||
unstable_interactiveUpdates: interactiveUpdates,
|
||||
unstable_interactiveUpdates: DOMRenderer.interactiveUpdates,
|
||||
|
||||
flushSync: flushSync,
|
||||
flushSync: DOMRenderer.flushSync,
|
||||
|
||||
unstable_createRoot: createRoot,
|
||||
unstable_flushControlled: flushControlled,
|
||||
unstable_flushControlled: DOMRenderer.flushControlled,
|
||||
|
||||
__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: {
|
||||
// Keep in sync with ReactDOMUnstableNativeDependencies.js
|
||||
// and ReactTestUtils.js. This is an array for better minification.
|
||||
Events: [
|
||||
getInstanceFromNode,
|
||||
getNodeFromInstance,
|
||||
getFiberCurrentPropsFromNode,
|
||||
EventPluginHubInjection.injectEventPluginsByName,
|
||||
eventNameDispatchConfigs,
|
||||
accumulateTwoPhaseDispatches,
|
||||
accumulateDirectDispatches,
|
||||
enqueueStateRestore,
|
||||
restoreStateIfNeeded,
|
||||
dispatchEvent,
|
||||
runEventsInBatch,
|
||||
ReactDOMComponentTree.getInstanceFromNode,
|
||||
ReactDOMComponentTree.getNodeFromInstance,
|
||||
ReactDOMComponentTree.getFiberCurrentPropsFromNode,
|
||||
EventPluginHub.injection.injectEventPluginsByName,
|
||||
EventPluginRegistry.eventNameDispatchConfigs,
|
||||
EventPropagators.accumulateTwoPhaseDispatches,
|
||||
EventPropagators.accumulateDirectDispatches,
|
||||
ReactControlledComponent.enqueueStateRestore,
|
||||
ReactControlledComponent.restoreStateIfNeeded,
|
||||
ReactDOMEventListener.dispatchEvent,
|
||||
EventPluginHub.runEventsInBatch,
|
||||
],
|
||||
},
|
||||
};
|
||||
@@ -796,26 +770,20 @@ type RootOptions = {
|
||||
hydrate?: boolean,
|
||||
};
|
||||
|
||||
function createRoot(container: DOMContainer, options?: RootOptions): ReactRoot {
|
||||
const functionName = enableStableConcurrentModeAPIs
|
||||
? 'createRoot'
|
||||
: 'unstable_createRoot';
|
||||
ReactDOM.unstable_createRoot = function createRoot(
|
||||
container: DOMContainer,
|
||||
options?: RootOptions,
|
||||
): ReactRoot {
|
||||
invariant(
|
||||
isValidContainer(container),
|
||||
'%s(...): Target container is not a DOM element.',
|
||||
functionName,
|
||||
'unstable_createRoot(...): Target container is not a DOM element.',
|
||||
);
|
||||
const hydrate = options != null && options.hydrate === true;
|
||||
return new ReactRoot(container, true, hydrate);
|
||||
}
|
||||
};
|
||||
|
||||
if (enableStableConcurrentModeAPIs) {
|
||||
ReactDOM.createRoot = createRoot;
|
||||
ReactDOM.unstable_createRoot = undefined;
|
||||
}
|
||||
|
||||
const foundDevTools = injectIntoDevTools({
|
||||
findFiberByHostInstance: getClosestInstanceFromNode,
|
||||
const foundDevTools = DOMRenderer.injectIntoDevTools({
|
||||
findFiberByHostInstance: ReactDOMComponentTree.getClosestInstanceFromNode,
|
||||
bundleType: __DEV__ ? 1 : 0,
|
||||
version: ReactVersion,
|
||||
rendererPackageName: 'react-dom',
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import {injection as EventPluginHubInjection} from 'events/EventPluginHub';
|
||||
import {setComponentTree} from 'events/EventPluginUtils';
|
||||
import * as EventPluginHub from 'events/EventPluginHub';
|
||||
import * as EventPluginUtils from 'events/EventPluginUtils';
|
||||
|
||||
import {
|
||||
getFiberCurrentPropsFromNode,
|
||||
@@ -23,8 +23,8 @@ import SimpleEventPlugin from '../events/SimpleEventPlugin';
|
||||
/**
|
||||
* Inject modules for resolving DOM hierarchy and plugin ordering.
|
||||
*/
|
||||
EventPluginHubInjection.injectEventPluginOrder(DOMEventPluginOrder);
|
||||
setComponentTree(
|
||||
EventPluginHub.injection.injectEventPluginOrder(DOMEventPluginOrder);
|
||||
EventPluginUtils.setComponentTree(
|
||||
getFiberCurrentPropsFromNode,
|
||||
getInstanceFromNode,
|
||||
getNodeFromInstance,
|
||||
@@ -34,7 +34,7 @@ setComponentTree(
|
||||
* Some important event plugins included by default (without having to require
|
||||
* them).
|
||||
*/
|
||||
EventPluginHubInjection.injectEventPluginsByName({
|
||||
EventPluginHub.injection.injectEventPluginsByName({
|
||||
SimpleEventPlugin: SimpleEventPlugin,
|
||||
EnterLeaveEventPlugin: EnterLeaveEventPlugin,
|
||||
ChangeEventPlugin: ChangeEventPlugin,
|
||||
|
||||
158
packages/react-dom/src/client/ReactDOMComponent.js
vendored
158
packages/react-dom/src/client/ReactDOMComponent.js
vendored
@@ -14,39 +14,12 @@ import warning from 'shared/warning';
|
||||
import {canUseDOM} from 'shared/ExecutionEnvironment';
|
||||
import warningWithoutStack from 'shared/warningWithoutStack';
|
||||
|
||||
import {
|
||||
getValueForAttribute,
|
||||
getValueForProperty,
|
||||
setValueForProperty,
|
||||
} from './DOMPropertyOperations';
|
||||
import {
|
||||
initWrapperState as ReactDOMInputInitWrapperState,
|
||||
getHostProps as ReactDOMInputGetHostProps,
|
||||
postMountWrapper as ReactDOMInputPostMountWrapper,
|
||||
updateChecked as ReactDOMInputUpdateChecked,
|
||||
updateWrapper as ReactDOMInputUpdateWrapper,
|
||||
restoreControlledState as ReactDOMInputRestoreControlledState,
|
||||
} from './ReactDOMInput';
|
||||
import {
|
||||
getHostProps as ReactDOMOptionGetHostProps,
|
||||
postMountWrapper as ReactDOMOptionPostMountWrapper,
|
||||
validateProps as ReactDOMOptionValidateProps,
|
||||
} from './ReactDOMOption';
|
||||
import {
|
||||
initWrapperState as ReactDOMSelectInitWrapperState,
|
||||
getHostProps as ReactDOMSelectGetHostProps,
|
||||
postMountWrapper as ReactDOMSelectPostMountWrapper,
|
||||
restoreControlledState as ReactDOMSelectRestoreControlledState,
|
||||
postUpdateWrapper as ReactDOMSelectPostUpdateWrapper,
|
||||
} from './ReactDOMSelect';
|
||||
import {
|
||||
initWrapperState as ReactDOMTextareaInitWrapperState,
|
||||
getHostProps as ReactDOMTextareaGetHostProps,
|
||||
postMountWrapper as ReactDOMTextareaPostMountWrapper,
|
||||
updateWrapper as ReactDOMTextareaUpdateWrapper,
|
||||
restoreControlledState as ReactDOMTextareaRestoreControlledState,
|
||||
} from './ReactDOMTextarea';
|
||||
import {track} from './inputValueTracking';
|
||||
import * as DOMPropertyOperations from './DOMPropertyOperations';
|
||||
import * as ReactDOMInput from './ReactDOMInput';
|
||||
import * as ReactDOMOption from './ReactDOMOption';
|
||||
import * as ReactDOMSelect from './ReactDOMSelect';
|
||||
import * as ReactDOMTextarea from './ReactDOMTextarea';
|
||||
import * as inputValueTracking from './inputValueTracking';
|
||||
import setInnerHTML from './setInnerHTML';
|
||||
import setTextContent from './setTextContent';
|
||||
import {
|
||||
@@ -59,11 +32,7 @@ import {
|
||||
} from '../events/DOMTopLevelEventTypes';
|
||||
import {listenTo, trapBubbledEvent} from '../events/ReactBrowserEventEmitter';
|
||||
import {mediaEventTypes} from '../events/DOMTopLevelEventTypes';
|
||||
import {
|
||||
createDangerousStringForStyles,
|
||||
setValueForStyles,
|
||||
validateShorthandPropertyCollisionInDev,
|
||||
} from '../shared/CSSPropertyOperations';
|
||||
import * as CSSPropertyOperations from '../shared/CSSPropertyOperations';
|
||||
import {Namespaces, getIntrinsicNamespace} from '../shared/DOMNamespaces';
|
||||
import {
|
||||
getPropertyInfo,
|
||||
@@ -307,7 +276,7 @@ function setInitialDOMProperties(
|
||||
}
|
||||
}
|
||||
// Relies on `updateStylesByID` not mutating `styleUpdates`.
|
||||
setValueForStyles(domElement, nextProp);
|
||||
CSSPropertyOperations.setValueForStyles(domElement, nextProp);
|
||||
} else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
|
||||
const nextHtml = nextProp ? nextProp[HTML] : undefined;
|
||||
if (nextHtml != null) {
|
||||
@@ -344,7 +313,12 @@ function setInitialDOMProperties(
|
||||
ensureListeningTo(rootContainerElement, propKey);
|
||||
}
|
||||
} else if (nextProp != null) {
|
||||
setValueForProperty(domElement, propKey, nextProp, isCustomComponentTag);
|
||||
DOMPropertyOperations.setValueForProperty(
|
||||
domElement,
|
||||
propKey,
|
||||
nextProp,
|
||||
isCustomComponentTag,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -360,13 +334,18 @@ function updateDOMProperties(
|
||||
const propKey = updatePayload[i];
|
||||
const propValue = updatePayload[i + 1];
|
||||
if (propKey === STYLE) {
|
||||
setValueForStyles(domElement, propValue);
|
||||
CSSPropertyOperations.setValueForStyles(domElement, propValue);
|
||||
} else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
|
||||
setInnerHTML(domElement, propValue);
|
||||
} else if (propKey === CHILDREN) {
|
||||
setTextContent(domElement, propValue);
|
||||
} else {
|
||||
setValueForProperty(domElement, propKey, propValue, isCustomComponentTag);
|
||||
DOMPropertyOperations.setValueForProperty(
|
||||
domElement,
|
||||
propKey,
|
||||
propValue,
|
||||
isCustomComponentTag,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -526,28 +505,28 @@ export function setInitialProperties(
|
||||
props = rawProps;
|
||||
break;
|
||||
case 'input':
|
||||
ReactDOMInputInitWrapperState(domElement, rawProps);
|
||||
props = ReactDOMInputGetHostProps(domElement, rawProps);
|
||||
ReactDOMInput.initWrapperState(domElement, rawProps);
|
||||
props = ReactDOMInput.getHostProps(domElement, rawProps);
|
||||
trapBubbledEvent(TOP_INVALID, domElement);
|
||||
// For controlled components we always need to ensure we're listening
|
||||
// to onChange. Even if there is no listener.
|
||||
ensureListeningTo(rootContainerElement, 'onChange');
|
||||
break;
|
||||
case 'option':
|
||||
ReactDOMOptionValidateProps(domElement, rawProps);
|
||||
props = ReactDOMOptionGetHostProps(domElement, rawProps);
|
||||
ReactDOMOption.validateProps(domElement, rawProps);
|
||||
props = ReactDOMOption.getHostProps(domElement, rawProps);
|
||||
break;
|
||||
case 'select':
|
||||
ReactDOMSelectInitWrapperState(domElement, rawProps);
|
||||
props = ReactDOMSelectGetHostProps(domElement, rawProps);
|
||||
ReactDOMSelect.initWrapperState(domElement, rawProps);
|
||||
props = ReactDOMSelect.getHostProps(domElement, rawProps);
|
||||
trapBubbledEvent(TOP_INVALID, domElement);
|
||||
// For controlled components we always need to ensure we're listening
|
||||
// to onChange. Even if there is no listener.
|
||||
ensureListeningTo(rootContainerElement, 'onChange');
|
||||
break;
|
||||
case 'textarea':
|
||||
ReactDOMTextareaInitWrapperState(domElement, rawProps);
|
||||
props = ReactDOMTextareaGetHostProps(domElement, rawProps);
|
||||
ReactDOMTextarea.initWrapperState(domElement, rawProps);
|
||||
props = ReactDOMTextarea.getHostProps(domElement, rawProps);
|
||||
trapBubbledEvent(TOP_INVALID, domElement);
|
||||
// For controlled components we always need to ensure we're listening
|
||||
// to onChange. Even if there is no listener.
|
||||
@@ -571,20 +550,20 @@ export function setInitialProperties(
|
||||
case 'input':
|
||||
// TODO: Make sure we check if this is still unmounted or do any clean
|
||||
// up necessary since we never stop tracking anymore.
|
||||
track((domElement: any));
|
||||
ReactDOMInputPostMountWrapper(domElement, rawProps, false);
|
||||
inputValueTracking.track((domElement: any));
|
||||
ReactDOMInput.postMountWrapper(domElement, rawProps, false);
|
||||
break;
|
||||
case 'textarea':
|
||||
// TODO: Make sure we check if this is still unmounted or do any clean
|
||||
// up necessary since we never stop tracking anymore.
|
||||
track((domElement: any));
|
||||
ReactDOMTextareaPostMountWrapper(domElement, rawProps);
|
||||
inputValueTracking.track((domElement: any));
|
||||
ReactDOMTextarea.postMountWrapper(domElement, rawProps);
|
||||
break;
|
||||
case 'option':
|
||||
ReactDOMOptionPostMountWrapper(domElement, rawProps);
|
||||
ReactDOMOption.postMountWrapper(domElement, rawProps);
|
||||
break;
|
||||
case 'select':
|
||||
ReactDOMSelectPostMountWrapper(domElement, rawProps);
|
||||
ReactDOMSelect.postMountWrapper(domElement, rawProps);
|
||||
break;
|
||||
default:
|
||||
if (typeof props.onClick === 'function') {
|
||||
@@ -613,23 +592,23 @@ export function diffProperties(
|
||||
let nextProps: Object;
|
||||
switch (tag) {
|
||||
case 'input':
|
||||
lastProps = ReactDOMInputGetHostProps(domElement, lastRawProps);
|
||||
nextProps = ReactDOMInputGetHostProps(domElement, nextRawProps);
|
||||
lastProps = ReactDOMInput.getHostProps(domElement, lastRawProps);
|
||||
nextProps = ReactDOMInput.getHostProps(domElement, nextRawProps);
|
||||
updatePayload = [];
|
||||
break;
|
||||
case 'option':
|
||||
lastProps = ReactDOMOptionGetHostProps(domElement, lastRawProps);
|
||||
nextProps = ReactDOMOptionGetHostProps(domElement, nextRawProps);
|
||||
lastProps = ReactDOMOption.getHostProps(domElement, lastRawProps);
|
||||
nextProps = ReactDOMOption.getHostProps(domElement, nextRawProps);
|
||||
updatePayload = [];
|
||||
break;
|
||||
case 'select':
|
||||
lastProps = ReactDOMSelectGetHostProps(domElement, lastRawProps);
|
||||
nextProps = ReactDOMSelectGetHostProps(domElement, nextRawProps);
|
||||
lastProps = ReactDOMSelect.getHostProps(domElement, lastRawProps);
|
||||
nextProps = ReactDOMSelect.getHostProps(domElement, nextRawProps);
|
||||
updatePayload = [];
|
||||
break;
|
||||
case 'textarea':
|
||||
lastProps = ReactDOMTextareaGetHostProps(domElement, lastRawProps);
|
||||
nextProps = ReactDOMTextareaGetHostProps(domElement, nextRawProps);
|
||||
lastProps = ReactDOMTextarea.getHostProps(domElement, lastRawProps);
|
||||
nextProps = ReactDOMTextarea.getHostProps(domElement, nextRawProps);
|
||||
updatePayload = [];
|
||||
break;
|
||||
default:
|
||||
@@ -787,9 +766,6 @@ export function diffProperties(
|
||||
}
|
||||
}
|
||||
if (styleUpdates) {
|
||||
if (__DEV__) {
|
||||
validateShorthandPropertyCollisionInDev(styleUpdates, nextProps[STYLE]);
|
||||
}
|
||||
(updatePayload = updatePayload || []).push(STYLE, styleUpdates);
|
||||
}
|
||||
return updatePayload;
|
||||
@@ -811,7 +787,7 @@ export function updateProperties(
|
||||
nextRawProps.type === 'radio' &&
|
||||
nextRawProps.name != null
|
||||
) {
|
||||
ReactDOMInputUpdateChecked(domElement, nextRawProps);
|
||||
ReactDOMInput.updateChecked(domElement, nextRawProps);
|
||||
}
|
||||
|
||||
const wasCustomComponentTag = isCustomComponent(tag, lastRawProps);
|
||||
@@ -831,15 +807,15 @@ export function updateProperties(
|
||||
// Update the wrapper around inputs *after* updating props. This has to
|
||||
// happen after `updateDOMProperties`. Otherwise HTML5 input validations
|
||||
// raise warnings and prevent the new value from being assigned.
|
||||
ReactDOMInputUpdateWrapper(domElement, nextRawProps);
|
||||
ReactDOMInput.updateWrapper(domElement, nextRawProps);
|
||||
break;
|
||||
case 'textarea':
|
||||
ReactDOMTextareaUpdateWrapper(domElement, nextRawProps);
|
||||
ReactDOMTextarea.updateWrapper(domElement, nextRawProps);
|
||||
break;
|
||||
case 'select':
|
||||
// <select> value update needs to occur after <option> children
|
||||
// reconciliation
|
||||
ReactDOMSelectPostUpdateWrapper(domElement, nextRawProps);
|
||||
ReactDOMSelect.postUpdateWrapper(domElement, nextRawProps);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -914,24 +890,24 @@ export function diffHydratedProperties(
|
||||
trapBubbledEvent(TOP_TOGGLE, domElement);
|
||||
break;
|
||||
case 'input':
|
||||
ReactDOMInputInitWrapperState(domElement, rawProps);
|
||||
ReactDOMInput.initWrapperState(domElement, rawProps);
|
||||
trapBubbledEvent(TOP_INVALID, domElement);
|
||||
// For controlled components we always need to ensure we're listening
|
||||
// to onChange. Even if there is no listener.
|
||||
ensureListeningTo(rootContainerElement, 'onChange');
|
||||
break;
|
||||
case 'option':
|
||||
ReactDOMOptionValidateProps(domElement, rawProps);
|
||||
ReactDOMOption.validateProps(domElement, rawProps);
|
||||
break;
|
||||
case 'select':
|
||||
ReactDOMSelectInitWrapperState(domElement, rawProps);
|
||||
ReactDOMSelect.initWrapperState(domElement, rawProps);
|
||||
trapBubbledEvent(TOP_INVALID, domElement);
|
||||
// For controlled components we always need to ensure we're listening
|
||||
// to onChange. Even if there is no listener.
|
||||
ensureListeningTo(rootContainerElement, 'onChange');
|
||||
break;
|
||||
case 'textarea':
|
||||
ReactDOMTextareaInitWrapperState(domElement, rawProps);
|
||||
ReactDOMTextarea.initWrapperState(domElement, rawProps);
|
||||
trapBubbledEvent(TOP_INVALID, domElement);
|
||||
// For controlled components we always need to ensure we're listening
|
||||
// to onChange. Even if there is no listener.
|
||||
@@ -1039,7 +1015,9 @@ export function diffHydratedProperties(
|
||||
extraAttributeNames.delete(propKey);
|
||||
|
||||
if (canDiffStyleForHydrationWarning) {
|
||||
const expectedStyle = createDangerousStringForStyles(nextProp);
|
||||
const expectedStyle = CSSPropertyOperations.createDangerousStringForStyles(
|
||||
nextProp,
|
||||
);
|
||||
serverValue = domElement.getAttribute('style');
|
||||
if (expectedStyle !== serverValue) {
|
||||
warnForPropDifference(propKey, serverValue, expectedStyle);
|
||||
@@ -1048,7 +1026,11 @@ export function diffHydratedProperties(
|
||||
} else if (isCustomComponentTag) {
|
||||
// $FlowFixMe - Should be inferred as not undefined.
|
||||
extraAttributeNames.delete(propKey.toLowerCase());
|
||||
serverValue = getValueForAttribute(domElement, propKey, nextProp);
|
||||
serverValue = DOMPropertyOperations.getValueForAttribute(
|
||||
domElement,
|
||||
propKey,
|
||||
nextProp,
|
||||
);
|
||||
|
||||
if (nextProp !== serverValue) {
|
||||
warnForPropDifference(propKey, serverValue, nextProp);
|
||||
@@ -1066,7 +1048,7 @@ export function diffHydratedProperties(
|
||||
if (propertyInfo !== null) {
|
||||
// $FlowFixMe - Should be inferred as not undefined.
|
||||
extraAttributeNames.delete(propertyInfo.attributeName);
|
||||
serverValue = getValueForProperty(
|
||||
serverValue = DOMPropertyOperations.getValueForProperty(
|
||||
domElement,
|
||||
propKey,
|
||||
nextProp,
|
||||
@@ -1095,7 +1077,11 @@ export function diffHydratedProperties(
|
||||
// $FlowFixMe - Should be inferred as not undefined.
|
||||
extraAttributeNames.delete(propKey);
|
||||
}
|
||||
serverValue = getValueForAttribute(domElement, propKey, nextProp);
|
||||
serverValue = DOMPropertyOperations.getValueForAttribute(
|
||||
domElement,
|
||||
propKey,
|
||||
nextProp,
|
||||
);
|
||||
}
|
||||
|
||||
if (nextProp !== serverValue && !isMismatchDueToBadCasing) {
|
||||
@@ -1117,14 +1103,14 @@ export function diffHydratedProperties(
|
||||
case 'input':
|
||||
// TODO: Make sure we check if this is still unmounted or do any clean
|
||||
// up necessary since we never stop tracking anymore.
|
||||
track((domElement: any));
|
||||
ReactDOMInputPostMountWrapper(domElement, rawProps, true);
|
||||
inputValueTracking.track((domElement: any));
|
||||
ReactDOMInput.postMountWrapper(domElement, rawProps, true);
|
||||
break;
|
||||
case 'textarea':
|
||||
// TODO: Make sure we check if this is still unmounted or do any clean
|
||||
// up necessary since we never stop tracking anymore.
|
||||
track((domElement: any));
|
||||
ReactDOMTextareaPostMountWrapper(domElement, rawProps);
|
||||
inputValueTracking.track((domElement: any));
|
||||
ReactDOMTextarea.postMountWrapper(domElement, rawProps);
|
||||
break;
|
||||
case 'select':
|
||||
case 'option':
|
||||
@@ -1243,13 +1229,13 @@ export function restoreControlledState(
|
||||
): void {
|
||||
switch (tag) {
|
||||
case 'input':
|
||||
ReactDOMInputRestoreControlledState(domElement, props);
|
||||
ReactDOMInput.restoreControlledState(domElement, props);
|
||||
return;
|
||||
case 'textarea':
|
||||
ReactDOMTextareaRestoreControlledState(domElement, props);
|
||||
ReactDOMTextarea.restoreControlledState(domElement, props);
|
||||
return;
|
||||
case 'select':
|
||||
ReactDOMSelectRestoreControlledState(domElement, props);
|
||||
ReactDOMSelect.restoreControlledState(domElement, props);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
24
packages/react-dom/src/client/ReactDOMFB.js
vendored
24
packages/react-dom/src/client/ReactDOMFB.js
vendored
@@ -7,30 +7,22 @@
|
||||
* @flow
|
||||
*/
|
||||
|
||||
import {findCurrentFiberUsingSlowPath} from 'react-reconciler/reflection';
|
||||
import {get as getInstance} from 'shared/ReactInstanceMap';
|
||||
import * as ReactFiberTreeReflection from 'react-reconciler/reflection';
|
||||
import * as ReactInstanceMap from 'shared/ReactInstanceMap';
|
||||
import {addUserTimingListener} from 'shared/ReactFeatureFlags';
|
||||
|
||||
import ReactDOM from './ReactDOM';
|
||||
import {isEnabled} from '../events/ReactBrowserEventEmitter';
|
||||
import {getClosestInstanceFromNode} from './ReactDOMComponentTree';
|
||||
import * as ReactBrowserEventEmitter from '../events/ReactBrowserEventEmitter';
|
||||
import * as ReactDOMComponentTree from './ReactDOMComponentTree';
|
||||
|
||||
Object.assign(
|
||||
(ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: any),
|
||||
{
|
||||
// These are real internal dependencies that are trickier to remove:
|
||||
ReactBrowserEventEmitter: {
|
||||
isEnabled,
|
||||
},
|
||||
ReactFiberTreeReflection: {
|
||||
findCurrentFiberUsingSlowPath,
|
||||
},
|
||||
ReactDOMComponentTree: {
|
||||
getClosestInstanceFromNode,
|
||||
},
|
||||
ReactInstanceMap: {
|
||||
get: getInstance,
|
||||
},
|
||||
ReactBrowserEventEmitter,
|
||||
ReactFiberTreeReflection,
|
||||
ReactDOMComponentTree,
|
||||
ReactInstanceMap,
|
||||
// Perf experiment
|
||||
addUserTimingListener,
|
||||
},
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user