Compare commits
130 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0c756fb33f | ||
|
|
6c22b6cad9 | ||
|
|
b545546ccb | ||
|
|
d5e1bf07d0 | ||
|
|
2dd4ba11e0 | ||
|
|
9cc631a539 | ||
|
|
1034e26fe5 | ||
|
|
5618da49d8 | ||
|
|
9fb9199455 | ||
|
|
c174f85924 | ||
|
|
02e4848e3a | ||
|
|
4b163fee1c | ||
|
|
e58ecda9a2 | ||
|
|
7fd1661f80 | ||
|
|
f9e9913f0e | ||
|
|
7c560131bf | ||
|
|
3d8bda70e5 | ||
|
|
051272f201 | ||
|
|
3ff2c7ccd4 | ||
|
|
5afa1c4eda | ||
|
|
be63473004 | ||
|
|
e27720d7f5 | ||
|
|
aa1ffe4e77 | ||
|
|
e3a7b96455 | ||
|
|
ff29de4029 | ||
|
|
ba19844236 | ||
|
|
a24d510287 | ||
|
|
b50e63ef53 | ||
|
|
fd4527dbcd | ||
|
|
bd5a6d3914 | ||
|
|
8f2c89e963 | ||
|
|
2aecbcd6f1 | ||
|
|
b4608dd24c | ||
|
|
3c69a18814 | ||
|
|
b020fb1148 | ||
|
|
b67c1a2ee1 | ||
|
|
f777d196e0 | ||
|
|
e4512991c9 | ||
|
|
affb2b50ca | ||
|
|
0a0f503d57 | ||
|
|
600651e68e | ||
|
|
e9a2ec9156 | ||
|
|
9d47143e85 | ||
|
|
ebdb47d2c1 | ||
|
|
8b87ebf5b0 | ||
|
|
da04058a91 | ||
|
|
fd1256a561 | ||
|
|
b305c4e034 | ||
|
|
ce90ffd045 | ||
|
|
d34d1c3bae | ||
|
|
6c404d82aa | ||
|
|
8eca0eff87 | ||
|
|
293fed8993 | ||
|
|
ae196e84b6 | ||
|
|
c898020e01 | ||
|
|
c84b9bf828 | ||
|
|
595b4f945b | ||
|
|
d5d10d140e | ||
|
|
cdbfa6b5dd | ||
|
|
1ae3f29c20 | ||
|
|
3db8b80e15 | ||
|
|
169f935f78 | ||
|
|
bf9fadfcf4 | ||
|
|
8c67bbf183 | ||
|
|
e02086bfcc | ||
|
|
b92cdef641 | ||
|
|
6efbbe0685 | ||
|
|
5045763064 | ||
|
|
ddbfe2ed50 | ||
|
|
acb4899637 | ||
|
|
933b64710a | ||
|
|
5fc84efacc | ||
|
|
9f34eb79a3 | ||
|
|
f7cb9d2b22 | ||
|
|
63cc7d2b31 | ||
|
|
3a7c6da8d4 | ||
|
|
75a1c2e72a | ||
|
|
55a4b1f377 | ||
|
|
30aa4ad554 | ||
|
|
b772e0e26b | ||
|
|
9e9e3970e4 | ||
|
|
6514697f0c | ||
|
|
dd019d34db | ||
|
|
11d0781eea | ||
|
|
105f2de545 | ||
|
|
7bee9fbdd4 | ||
|
|
37c7fe0a5f | ||
|
|
ae4f3f07e5 | ||
|
|
95f98a1873 | ||
|
|
e217f2f1ac | ||
|
|
275e76e83b | ||
|
|
b5539ad628 | ||
|
|
0cc50b675a | ||
|
|
8b97a9c36f | ||
|
|
c8ade996e9 | ||
|
|
6c29eabf78 | ||
|
|
d520b358d6 | ||
|
|
8f1ec7649e | ||
|
|
5055a83fa4 | ||
|
|
3e8b4a5b8b | ||
|
|
ff5efb0390 | ||
|
|
f4488bee51 | ||
|
|
d42ed60026 | ||
|
|
d8e03de4aa | ||
|
|
fefa1269e2 | ||
|
|
80a0c05ce3 | ||
|
|
915e4eab53 | ||
|
|
508b5fba0e | ||
|
|
c285ea2700 | ||
|
|
eac092ecac | ||
|
|
cbbc2b6c4d | ||
|
|
4947fcd762 | ||
|
|
d75c69e0cf | ||
|
|
c8ef2feda9 | ||
|
|
55444a6f49 | ||
|
|
04c4f2fcea | ||
|
|
409e472fca | ||
|
|
663835a43a | ||
|
|
82710097f6 | ||
|
|
7ebd90c2c3 | ||
|
|
420001cb4e | ||
|
|
b753f76a74 | ||
|
|
d37f595595 | ||
|
|
b5c0852fdd | ||
|
|
769b1f270e | ||
|
|
8ecd4bd4f0 | ||
|
|
15b11d23f9 | ||
|
|
e770af7a3a | ||
|
|
95a313ec0b | ||
|
|
e16cdd5b17 |
48
.eslintrc.js
48
.eslintrc.js
@@ -1,5 +1,10 @@
|
||||
'use strict';
|
||||
|
||||
const {
|
||||
es5Paths,
|
||||
esNextPaths,
|
||||
} = require('./scripts/shared/pathsByLanguageVersion');
|
||||
|
||||
const OFF = 0;
|
||||
const ERROR = 2;
|
||||
|
||||
@@ -16,6 +21,15 @@ 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: {
|
||||
@@ -44,6 +58,13 @@ 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'],
|
||||
@@ -71,6 +92,33 @@ 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,3 +1,5 @@
|
||||
'use strict';
|
||||
|
||||
const {esNextPaths} = require('./scripts/shared/pathsByLanguageVersion');
|
||||
|
||||
module.exports = {
|
||||
|
||||
49
CHANGELOG.md
49
CHANGELOG.md
@@ -4,9 +4,56 @@
|
||||
Changes that have landed in master but are not yet released.
|
||||
Click to see more.
|
||||
</summary>
|
||||
|
||||
</details>
|
||||
|
||||
## 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
|
||||
|
||||
@@ -860,7 +860,7 @@ class App extends React.Component {
|
||||
});
|
||||
break;
|
||||
default:
|
||||
throw new Error('Switch statement should be exhuastive');
|
||||
throw new Error('Switch statement should be exhaustive');
|
||||
}
|
||||
|
||||
// Sort
|
||||
@@ -887,7 +887,7 @@ class App extends React.Component {
|
||||
});
|
||||
}
|
||||
default:
|
||||
throw new Error('Switch statement should be exhuastive');
|
||||
throw new Error('Switch statement should be exhaustive');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import TestCase from '../../TestCase';
|
||||
const React = window.React;
|
||||
const ReactDOM = window.ReactDOM;
|
||||
|
||||
const Suspense = React.unstable_Suspense;
|
||||
const Suspense = React.Suspense;
|
||||
|
||||
let cache = new Set();
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@ h3 {
|
||||
margin: 8px 0 16px;
|
||||
}
|
||||
|
||||
h4, h4, h5, h6 {
|
||||
h4, h5, h6 {
|
||||
font-size: 16px;
|
||||
margin: 0 0 16px;
|
||||
}
|
||||
|
||||
@@ -90,17 +90,17 @@ export default function describeFibers(rootFiber, workInProgress) {
|
||||
const workInProgressID = acknowledgeFiber(workInProgress);
|
||||
|
||||
let currentIDs = new Set();
|
||||
function markAsCurent(id) {
|
||||
function markAsCurrent(id) {
|
||||
currentIDs.add(id);
|
||||
const fiber = descriptions[id];
|
||||
if (fiber.sibling) {
|
||||
markAsCurent(fiber.sibling);
|
||||
markAsCurrent(fiber.sibling);
|
||||
}
|
||||
if (fiber.child) {
|
||||
markAsCurent(fiber.child);
|
||||
markAsCurrent(fiber.child);
|
||||
}
|
||||
}
|
||||
markAsCurent(rootID);
|
||||
markAsCurrent(rootID);
|
||||
|
||||
return {
|
||||
descriptions,
|
||||
|
||||
@@ -48,7 +48,7 @@
|
||||
<div id="test-2"></div>
|
||||
</li>
|
||||
<li>
|
||||
<p>Schedules callbacks in correct order when they use scheduleWork to schedule themselves</p>
|
||||
<p>Schedules callbacks in correct order when they use scheduleCallback to schedule themselves</p>
|
||||
<button onClick="runTestThree()">Run Test 3</button>
|
||||
<div><b>Expected:</b></div>
|
||||
<div id="test-3-expected">
|
||||
@@ -225,7 +225,7 @@ function runTestOne() {
|
||||
const cb1 = (x) => {
|
||||
updateTestResult(1, 'cb1 called with argument of ' + JSON.stringify(x));
|
||||
}
|
||||
scheduleWork(cb1);
|
||||
scheduleCallback(cb1);
|
||||
updateTestResult(1, 'scheduled Cb1');
|
||||
logWhenFramesStart(1, () => {
|
||||
displayTestResult(1);
|
||||
@@ -243,9 +243,9 @@ function runTestTwo() {
|
||||
const cbB = (x) => {
|
||||
updateTestResult(2, 'cbB called with argument of ' + JSON.stringify(x));
|
||||
}
|
||||
scheduleWork(cbA);
|
||||
scheduleCallback(cbA);
|
||||
updateTestResult(2, 'scheduled CbA');
|
||||
scheduleWork(cbB);
|
||||
scheduleCallback(cbB);
|
||||
updateTestResult(2, 'scheduled CbB');
|
||||
logWhenFramesStart(2, () => {
|
||||
displayTestResult(2);
|
||||
@@ -255,12 +255,12 @@ function runTestTwo() {
|
||||
|
||||
function runTestThree() {
|
||||
// Test 3
|
||||
// Schedules callbacks in correct order when they use scheduleWork to schedule themselves
|
||||
// Schedules callbacks in correct order when they use scheduleCallback to schedule themselves
|
||||
clearTestResult(3);
|
||||
let callbackAIterations = 0;
|
||||
const cbA = (x) => {
|
||||
if (callbackAIterations < 1) {
|
||||
scheduleWork(cbA);
|
||||
scheduleCallback(cbA);
|
||||
updateTestResult(3, 'scheduled CbA again');
|
||||
}
|
||||
updateTestResult(3, 'cbA' + callbackAIterations + ' called with argument of ' + JSON.stringify(x));
|
||||
@@ -269,9 +269,9 @@ function runTestThree() {
|
||||
const cbB = (x) => {
|
||||
updateTestResult(3, 'cbB called with argument of ' + JSON.stringify(x));
|
||||
}
|
||||
scheduleWork(cbA);
|
||||
scheduleCallback(cbA);
|
||||
updateTestResult(3, 'scheduled CbA');
|
||||
scheduleWork(cbB);
|
||||
scheduleCallback(cbB);
|
||||
updateTestResult(3, 'scheduled CbB');
|
||||
logWhenFramesStart(3, () => {
|
||||
displayTestResult(3);
|
||||
@@ -305,13 +305,13 @@ function runTestFour() {
|
||||
const cbD = (x) => {
|
||||
updateTestResult(4, 'cbD called with argument of ' + JSON.stringify(x));
|
||||
}
|
||||
scheduleWork(cbA); // won't time out
|
||||
scheduleCallback(cbA); // won't time out
|
||||
updateTestResult(4, 'scheduled cbA');
|
||||
scheduleWork(cbB, {timeout: 100}); // times out later
|
||||
scheduleCallback(cbB, {timeout: 100}); // times out later
|
||||
updateTestResult(4, 'scheduled cbB');
|
||||
scheduleWork(cbC, {timeout: 1}); // will time out fast
|
||||
scheduleCallback(cbC, {timeout: 1}); // will time out fast
|
||||
updateTestResult(4, 'scheduled cbC');
|
||||
scheduleWork(cbD); // won't time out
|
||||
scheduleCallback(cbD); // won't time out
|
||||
updateTestResult(4, 'scheduled cbD');
|
||||
|
||||
// should have run in order of C, A, B, D
|
||||
@@ -390,15 +390,15 @@ function runTestFive() {
|
||||
});
|
||||
});
|
||||
});
|
||||
scheduleWork(cbA);
|
||||
scheduleCallback(cbA);
|
||||
console.log('scheduled cbA');
|
||||
scheduleWork(cbB); // will throw error
|
||||
scheduleCallback(cbB); // will throw error
|
||||
console.log('scheduled cbB');
|
||||
scheduleWork(cbC);
|
||||
scheduleCallback(cbC);
|
||||
console.log('scheduled cbC');
|
||||
scheduleWork(cbD); // will throw error
|
||||
scheduleCallback(cbD); // will throw error
|
||||
console.log('scheduled cbD');
|
||||
scheduleWork(cbE);
|
||||
scheduleCallback(cbE);
|
||||
console.log('scheduled cbE');
|
||||
};
|
||||
}
|
||||
@@ -468,15 +468,15 @@ function runTestSix() {
|
||||
});
|
||||
});
|
||||
});
|
||||
scheduleWork(cbA);
|
||||
scheduleCallback(cbA);
|
||||
console.log('scheduled cbA');
|
||||
scheduleWork(cbB); // will throw error
|
||||
scheduleCallback(cbB); // will throw error
|
||||
console.log('scheduled cbB');
|
||||
scheduleWork(cbC, {timeout: 1});
|
||||
scheduleCallback(cbC, {timeout: 1});
|
||||
console.log('scheduled cbC');
|
||||
scheduleWork(cbD, {timeout: 1}); // will throw error
|
||||
scheduleCallback(cbD, {timeout: 1}); // will throw error
|
||||
console.log('scheduled cbD');
|
||||
scheduleWork(cbE, {timeout: 1});
|
||||
scheduleCallback(cbE, {timeout: 1});
|
||||
console.log('scheduled cbE');
|
||||
};
|
||||
}
|
||||
@@ -492,9 +492,9 @@ function runTestSeven() {
|
||||
counter++;
|
||||
counterNode.innerHTML = counter;
|
||||
waitForTimeToPass(100);
|
||||
scheduleWork(incrementCounterAndScheduleNextCallback);
|
||||
scheduleCallback(incrementCounterAndScheduleNextCallback);
|
||||
}
|
||||
scheduleWork(incrementCounterAndScheduleNextCallback);
|
||||
scheduleCallback(incrementCounterAndScheduleNextCallback);
|
||||
}
|
||||
</script type="text/babel">
|
||||
</body>
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
import {createCache} from 'react-cache';
|
||||
|
||||
export let cache;
|
||||
function initCache() {
|
||||
cache = createCache(initCache);
|
||||
}
|
||||
initCache();
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, {lazy, unstable_Suspense as Suspense, PureComponent} from 'react';
|
||||
import React, {lazy, Suspense, PureComponent} from 'react';
|
||||
import {unstable_scheduleCallback} from 'scheduler';
|
||||
import {
|
||||
unstable_trace as trace,
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import React, {Fragment} from 'react';
|
||||
import {createResource} from 'react-cache';
|
||||
import {cache} from '../cache';
|
||||
import {unstable_createResource} from 'react-cache';
|
||||
import Spinner from './Spinner';
|
||||
import {fetchCoreContributorListJSON} from '../api';
|
||||
|
||||
const ContributorListResource = createResource(fetchCoreContributorListJSON);
|
||||
const ContributorListResource = unstable_createResource(
|
||||
fetchCoreContributorListJSON
|
||||
);
|
||||
|
||||
const ContributorListPage = ({loadingId, onUserClick}) => (
|
||||
<Fragment>
|
||||
@@ -17,7 +18,7 @@ const ContributorListPage = ({loadingId, onUserClick}) => (
|
||||
padding: 0,
|
||||
margin: 0,
|
||||
}}>
|
||||
{ContributorListResource.read(cache).map(user => (
|
||||
{ContributorListResource.read().map(user => (
|
||||
<ContributorListItem
|
||||
key={user.id}
|
||||
onClick={() => onUserClick(user.id)}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import React, {unstable_Suspense as Suspense} from 'react';
|
||||
import {createResource} from 'react-cache';
|
||||
import React, {Suspense} from 'react';
|
||||
import {unstable_createResource} from 'react-cache';
|
||||
import Spinner from './Spinner';
|
||||
import {cache} from '../cache';
|
||||
import {fetchUserProfileJSON, fetchUserRepositoriesListJSON} from '../api';
|
||||
|
||||
export default function UserPage({id}) {
|
||||
@@ -21,10 +20,10 @@ export default function UserPage({id}) {
|
||||
);
|
||||
}
|
||||
|
||||
const UserDetailsResource = createResource(fetchUserProfileJSON);
|
||||
const UserDetailsResource = unstable_createResource(fetchUserProfileJSON);
|
||||
|
||||
function UserDetails({id}) {
|
||||
const user = UserDetailsResource.read(cache, id);
|
||||
const user = UserDetailsResource.read(id);
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
@@ -103,7 +102,7 @@ const Email = ({email}) => (
|
||||
</div>
|
||||
);
|
||||
|
||||
const ImageResource = createResource(
|
||||
const ImageResource = unstable_createResource(
|
||||
src =>
|
||||
new Promise(resolve => {
|
||||
const img = new Image();
|
||||
@@ -113,7 +112,7 @@ const ImageResource = createResource(
|
||||
);
|
||||
|
||||
function Img({src, alt, ...rest}) {
|
||||
return <img src={ImageResource.read(cache, src)} alt={alt} {...rest} />;
|
||||
return <img src={ImageResource.read(src)} alt={alt} {...rest} />;
|
||||
}
|
||||
|
||||
function UserPicture({source}) {
|
||||
@@ -132,10 +131,12 @@ function UserPicture({source}) {
|
||||
);
|
||||
}
|
||||
|
||||
const UserRepositoriesResource = createResource(fetchUserRepositoriesListJSON);
|
||||
const UserRepositoriesResource = unstable_createResource(
|
||||
fetchUserRepositoriesListJSON
|
||||
);
|
||||
|
||||
function Repositories({id}) {
|
||||
const repos = UserRepositoriesResource.read(cache, id);
|
||||
const repos = UserRepositoriesResource.read(id);
|
||||
return (
|
||||
<ul
|
||||
style={{
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
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,
|
||||
@@ -65,8 +64,9 @@ class Debugger extends PureComponent {
|
||||
}
|
||||
|
||||
handleReset = () => {
|
||||
trace('Clear cache', () => {
|
||||
cache.invalidate();
|
||||
trace('Clear cache', performance.now(), () => {
|
||||
// TODO: this is not implemented.
|
||||
// cache.invalidate();
|
||||
this.setState(state => ({
|
||||
requests: {},
|
||||
}));
|
||||
|
||||
@@ -124,7 +124,7 @@ class App extends PureComponent {
|
||||
<div className="rendering">
|
||||
{this.renderOption('sync', 'Synchronous')}
|
||||
{this.renderOption('debounced', 'Debounced')}
|
||||
{this.renderOption('async', 'Asynchronous')}
|
||||
{this.renderOption('async', 'Concurrent')}
|
||||
</div>
|
||||
<input
|
||||
className={'input ' + this.state.strategy}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"private": true,
|
||||
"version": "16.6.0-alpha.8af6728",
|
||||
"version": "16.6.1",
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
],
|
||||
@@ -44,6 +44,7 @@
|
||||
"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",
|
||||
|
||||
@@ -81,7 +81,7 @@ import React from "react";
|
||||
import { createSubscription } from "create-subscription";
|
||||
|
||||
// Start with a simple component.
|
||||
// In this case, it's a functional component, but it could have been a class.
|
||||
// In this case, it's a function 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 functional component with a subscriber HOC.
|
||||
// Wrap the function 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,7 +1,7 @@
|
||||
{
|
||||
"name": "create-subscription",
|
||||
"description": "utility for subscribing to external data sources inside React components",
|
||||
"version": "16.6.0-alpha.8af6728",
|
||||
"version": "16.6.1",
|
||||
"repository": "facebook/react",
|
||||
"files": [
|
||||
"LICENSE",
|
||||
@@ -10,7 +10,7 @@
|
||||
"cjs/"
|
||||
],
|
||||
"peerDependencies": {
|
||||
"react": "^16.3.0 || 16.6.0-alpha.8af6728"
|
||||
"react": "^16.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"rxjs": "^5.5.6"
|
||||
|
||||
48
packages/eslint-plugin-react-hooks/README.md
Normal file
48
packages/eslint-plugin-react-hooks/README.md
Normal file
@@ -0,0 +1,48 @@
|
||||
# `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
|
||||
@@ -0,0 +1,641 @@
|
||||
/**
|
||||
* 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.',
|
||||
};
|
||||
}
|
||||
10
packages/eslint-plugin-react-hooks/index.js
Normal file
10
packages/eslint-plugin-react-hooks/index.js
Normal file
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* 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');
|
||||
9
packages/eslint-plugin-react-hooks/npm/index.js
Normal file
9
packages/eslint-plugin-react-hooks/npm/index.js
Normal file
@@ -0,0 +1,9 @@
|
||||
'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');
|
||||
}
|
||||
30
packages/eslint-plugin-react-hooks/package.json
Normal file
30
packages/eslint-plugin-react-hooks/package.json
Normal file
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "eslint-plugin-react-hooks",
|
||||
"description": "ESLint rules for React Hooks",
|
||||
"version": "0.0.0",
|
||||
"repository": "facebook/react",
|
||||
"files": [
|
||||
"LICENSE",
|
||||
"README.md",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
549
packages/eslint-plugin-react-hooks/src/RulesOfHooks.js
Normal file
549
packages/eslint-plugin-react-hooks/src/RulesOfHooks.js
Normal file
@@ -0,0 +1,549 @@
|
||||
/**
|
||||
* 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];
|
||||
}
|
||||
14
packages/eslint-plugin-react-hooks/src/index.js
Normal file
14
packages/eslint-plugin-react-hooks/src/index.js
Normal file
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* 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,26 +37,19 @@ 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,
|
||||
simulated: boolean,
|
||||
) {
|
||||
const executeDispatchesAndRelease = function(event: ReactSyntheticEvent) {
|
||||
if (event) {
|
||||
executeDispatchesInOrder(event, simulated);
|
||||
executeDispatchesInOrder(event);
|
||||
|
||||
if (!event.isPersistent()) {
|
||||
event.constructor.release(event);
|
||||
}
|
||||
}
|
||||
};
|
||||
const executeDispatchesAndReleaseSimulated = function(e) {
|
||||
return executeDispatchesAndRelease(e, true);
|
||||
};
|
||||
const executeDispatchesAndReleaseTopLevel = function(e) {
|
||||
return executeDispatchesAndRelease(e, false);
|
||||
return executeDispatchesAndRelease(e);
|
||||
};
|
||||
|
||||
function isInteractive(tag) {
|
||||
@@ -192,7 +185,6 @@ function extractEvents(
|
||||
|
||||
export function runEventsInBatch(
|
||||
events: Array<ReactSyntheticEvent> | ReactSyntheticEvent | null,
|
||||
simulated: boolean,
|
||||
) {
|
||||
if (events !== null) {
|
||||
eventQueue = accumulateInto(eventQueue, events);
|
||||
@@ -207,17 +199,7 @@ export function runEventsInBatch(
|
||||
return;
|
||||
}
|
||||
|
||||
if (simulated) {
|
||||
forEachAccumulated(
|
||||
processingEventQueue,
|
||||
executeDispatchesAndReleaseSimulated,
|
||||
);
|
||||
} else {
|
||||
forEachAccumulated(
|
||||
processingEventQueue,
|
||||
executeDispatchesAndReleaseTopLevel,
|
||||
);
|
||||
}
|
||||
forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel);
|
||||
invariant(
|
||||
!eventQueue,
|
||||
'processEventQueue(): Additional events were enqueued while processing ' +
|
||||
@@ -239,5 +221,5 @@ export function runExtractedEventsInBatch(
|
||||
nativeEvent,
|
||||
nativeEventTarget,
|
||||
);
|
||||
runEventsInBatch(events, false);
|
||||
runEventsInBatch(events);
|
||||
}
|
||||
|
||||
@@ -60,11 +60,10 @@ 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, simulated, listener, inst) {
|
||||
function executeDispatch(event, listener, inst) {
|
||||
const type = event.type || 'unknown-event';
|
||||
event.currentTarget = getNodeFromInstance(inst);
|
||||
invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);
|
||||
@@ -74,7 +73,7 @@ function executeDispatch(event, simulated, listener, inst) {
|
||||
/**
|
||||
* Standard/simple iteration through an event's collected dispatches.
|
||||
*/
|
||||
export function executeDispatchesInOrder(event, simulated) {
|
||||
export function executeDispatchesInOrder(event) {
|
||||
const dispatchListeners = event._dispatchListeners;
|
||||
const dispatchInstances = event._dispatchInstances;
|
||||
if (__DEV__) {
|
||||
@@ -86,15 +85,10 @@ export function executeDispatchesInOrder(event, simulated) {
|
||||
break;
|
||||
}
|
||||
// Listeners and Instances are two parallel arrays that are always in sync.
|
||||
executeDispatch(
|
||||
event,
|
||||
simulated,
|
||||
dispatchListeners[i],
|
||||
dispatchInstances[i],
|
||||
);
|
||||
executeDispatch(event, dispatchListeners[i], dispatchInstances[i]);
|
||||
}
|
||||
} else if (dispatchListeners) {
|
||||
executeDispatch(event, simulated, dispatchListeners, dispatchInstances);
|
||||
executeDispatch(event, dispatchListeners, dispatchInstances);
|
||||
}
|
||||
event._dispatchListeners = null;
|
||||
event._dispatchInstances = null;
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
*
|
||||
* 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';
|
||||
@@ -35,11 +37,13 @@ function restoreStateOfTarget(target) {
|
||||
restoreImpl(internalInstance.stateNode, internalInstance.type, props);
|
||||
}
|
||||
|
||||
export function setRestoreImplementation(impl) {
|
||||
export function setRestoreImplementation(
|
||||
impl: (domElement: Element, tag: string, props: Object) => void,
|
||||
): void {
|
||||
restoreImpl = impl;
|
||||
}
|
||||
|
||||
export function enqueueStateRestore(target) {
|
||||
export function enqueueStateRestore(target: EventTarget): void {
|
||||
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, true);
|
||||
EventPluginHub.runEventsInBatch(extractedEvents);
|
||||
|
||||
// Ensure that every event that declared an `order`, was actually dispatched.
|
||||
expect('number of events dispatched:' + runData.dispatchCount).toBe(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "jest-react",
|
||||
"version": "0.3.0-alpha.8af6728",
|
||||
"version": "0.4.0",
|
||||
"description": "Jest matchers and utilities for testing React components.",
|
||||
"main": "index.js",
|
||||
"repository": "facebook/react",
|
||||
@@ -16,7 +16,7 @@
|
||||
"homepage": "https://reactjs.org/",
|
||||
"peerDependencies": {
|
||||
"jest": "^23.0.1",
|
||||
"react": "^16.0.0 || 16.6.0-alpha.8af6728",
|
||||
"react": "^16.0.0",
|
||||
"react-test-renderer": "^16.0.0"
|
||||
},
|
||||
"files": [
|
||||
|
||||
@@ -30,33 +30,31 @@ function assertYieldsWereCleared(root) {
|
||||
invariant(
|
||||
actualYields.length === 0,
|
||||
'Log of yielded values is not empty. ' +
|
||||
'Call expect(ReactTestRenderer).toHaveYielded(...) first.',
|
||||
'Call expect(ReactTestRenderer).unstable_toHaveYielded(...) first.',
|
||||
);
|
||||
}
|
||||
|
||||
export function toFlushAndYield(root, expectedYields) {
|
||||
export function unstable_toFlushAndYield(root, expectedYields) {
|
||||
assertYieldsWereCleared(root);
|
||||
const actualYields = root.unstable_flushAll();
|
||||
return captureAssertion(() => {
|
||||
assertYieldsWereCleared(root);
|
||||
const actualYields = root.unstable_flushAll();
|
||||
expect(actualYields).toEqual(expectedYields);
|
||||
});
|
||||
}
|
||||
|
||||
export function toFlushAndYieldThrough(root, expectedYields) {
|
||||
export function unstable_toFlushAndYieldThrough(root, expectedYields) {
|
||||
assertYieldsWereCleared(root);
|
||||
const actualYields = root.unstable_flushNumberOfYields(expectedYields.length);
|
||||
return captureAssertion(() => {
|
||||
assertYieldsWereCleared(root);
|
||||
const actualYields = root.unstable_flushNumberOfYields(
|
||||
expectedYields.length,
|
||||
);
|
||||
expect(actualYields).toEqual(expectedYields);
|
||||
});
|
||||
}
|
||||
|
||||
export function toFlushWithoutYielding(root) {
|
||||
return toFlushAndYield(root, []);
|
||||
export function unstable_toFlushWithoutYielding(root) {
|
||||
return unstable_toFlushAndYield(root, []);
|
||||
}
|
||||
|
||||
export function toHaveYielded(ReactTestRenderer, expectedYields) {
|
||||
export function unstable_toHaveYielded(ReactTestRenderer, expectedYields) {
|
||||
return captureAssertion(() => {
|
||||
if (
|
||||
ReactTestRenderer === null ||
|
||||
@@ -65,9 +63,9 @@ export function toHaveYielded(ReactTestRenderer, expectedYields) {
|
||||
) {
|
||||
invariant(
|
||||
false,
|
||||
'The matcher `toHaveYielded` expects an instance of React Test ' +
|
||||
'The matcher `unstable_toHaveYielded` expects an instance of React Test ' +
|
||||
'Renderer.\n\nTry: ' +
|
||||
'expect(ReactTestRenderer).toHaveYielded(expectedYields)',
|
||||
'expect(ReactTestRenderer).unstable_toHaveYielded(expectedYields)',
|
||||
);
|
||||
}
|
||||
const actualYields = ReactTestRenderer.unstable_clearYields();
|
||||
@@ -75,16 +73,16 @@ export function toHaveYielded(ReactTestRenderer, expectedYields) {
|
||||
});
|
||||
}
|
||||
|
||||
export function toFlushAndThrow(root, ...rest) {
|
||||
export function unstable_toFlushAndThrow(root, ...rest) {
|
||||
assertYieldsWereCleared(root);
|
||||
return captureAssertion(() => {
|
||||
assertYieldsWereCleared(root);
|
||||
expect(() => {
|
||||
root.unstable_flushAll();
|
||||
}).toThrow(...rest);
|
||||
});
|
||||
}
|
||||
|
||||
export function toMatchRenderedOutput(root, expectedJSX) {
|
||||
export function unstable_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.0-alpha.8af6728",
|
||||
"version": "16.6.1",
|
||||
"main": "index.js",
|
||||
"repository": "facebook/react",
|
||||
"keywords": [
|
||||
@@ -23,10 +23,10 @@
|
||||
"loose-envify": "^1.1.0",
|
||||
"object-assign": "^4.1.1",
|
||||
"prop-types": "^15.6.2",
|
||||
"scheduler": "^0.10.0-alpha.8af6728"
|
||||
"scheduler": "^0.11.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^16.0.0 || 16.6.0-alpha.8af6728"
|
||||
"react": "^16.0.0"
|
||||
},
|
||||
"files": [
|
||||
"LICENSE",
|
||||
|
||||
1
packages/react-art/src/ReactARTHostConfig.js
vendored
1
packages/react-art/src/ReactARTHostConfig.js
vendored
@@ -8,6 +8,7 @@
|
||||
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,15 +1,17 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "react-cache",
|
||||
"description": "A basic cache for React applications",
|
||||
"version": "16.6.0-alpha.8af6728",
|
||||
"version": "2.0.0-alpha.0",
|
||||
"repository": "facebook/react",
|
||||
"files": [
|
||||
"LICENSE",
|
||||
"README.md",
|
||||
"index.js",
|
||||
"cjs/"
|
||||
"cjs/",
|
||||
"umd/"
|
||||
],
|
||||
"peerDependencies": {
|
||||
"react": "^16.3.0-alpha.1 || 16.6.0-alpha.8af6728"
|
||||
"react": "^16.3.0-alpha.1"
|
||||
}
|
||||
}
|
||||
|
||||
142
packages/react-cache/src/LRU.js
vendored
Normal file
142
packages/react-cache/src/LRU.js
vendored
Normal file
@@ -0,0 +1,142 @@
|
||||
/**
|
||||
* 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,
|
||||
};
|
||||
}
|
||||
494
packages/react-cache/src/ReactCache.js
vendored
494
packages/react-cache/src/ReactCache.js
vendored
@@ -10,394 +10,178 @@
|
||||
import React from 'react';
|
||||
import warningWithoutStack from 'shared/warningWithoutStack';
|
||||
|
||||
function noop() {}
|
||||
import {createLRU} from './LRU';
|
||||
|
||||
const Empty = 0;
|
||||
const Pending = 1;
|
||||
const Resolved = 2;
|
||||
const Rejected = 3;
|
||||
|
||||
type EmptyRecord<K> = {|
|
||||
status: 0,
|
||||
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 PendingRecord<K, V> = {|
|
||||
status: 1,
|
||||
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 ResolvedRecord<K, V> = {|
|
||||
status: 2,
|
||||
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 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 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,
|
||||
type Thenable<T> = {
|
||||
then(resolve: (T) => mixed, reject: (mixed) => mixed): mixed,
|
||||
};
|
||||
|
||||
let CACHE_TYPE;
|
||||
if (__DEV__) {
|
||||
CACHE_TYPE = 0xcac4e;
|
||||
}
|
||||
type Suspender = {
|
||||
then(resolve: () => mixed, reject: () => mixed): mixed,
|
||||
};
|
||||
|
||||
let isCache;
|
||||
if (__DEV__) {
|
||||
isCache = value =>
|
||||
value !== null &&
|
||||
typeof value === 'object' &&
|
||||
value.$$typeof === CACHE_TYPE;
|
||||
}
|
||||
type PendingResult = {|
|
||||
status: 0,
|
||||
value: Suspender,
|
||||
|};
|
||||
|
||||
// TODO: Make this configurable per resource
|
||||
const MAX_SIZE = 500;
|
||||
const PAGE_SIZE = 50;
|
||||
type ResolvedResult<V> = {|
|
||||
status: 1,
|
||||
value: V,
|
||||
|};
|
||||
|
||||
function createRecord<K>(key: K): EmptyRecord<K> {
|
||||
return {
|
||||
status: Empty,
|
||||
suspender: null,
|
||||
key,
|
||||
value: null,
|
||||
error: null,
|
||||
next: null,
|
||||
previous: null,
|
||||
};
|
||||
}
|
||||
type RejectedResult = {|
|
||||
status: 2,
|
||||
value: mixed,
|
||||
|};
|
||||
|
||||
function createRecordCache<K, V>(): RecordCache<K, V> {
|
||||
return {
|
||||
map: new Map(),
|
||||
head: null,
|
||||
tail: null,
|
||||
size: 0,
|
||||
};
|
||||
}
|
||||
type Result<V> = PendingResult | ResolvedResult<V> | RejectedResult;
|
||||
|
||||
export function createCache(invalidator: () => mixed): Cache {
|
||||
const resourceMap: ResourceMap = new Map();
|
||||
type Resource<I, V> = {
|
||||
read(I): V,
|
||||
preload(I): void,
|
||||
};
|
||||
|
||||
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,
|
||||
);
|
||||
}
|
||||
const Pending = 0;
|
||||
const Resolved = 1;
|
||||
const Rejected = 2;
|
||||
|
||||
let recordCache = resourceMap.get(resourceType);
|
||||
if (recordCache === undefined) {
|
||||
recordCache = createRecordCache();
|
||||
resourceMap.set(resourceType, recordCache);
|
||||
}
|
||||
const map = recordCache.map;
|
||||
const currentOwner =
|
||||
React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner;
|
||||
|
||||
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;
|
||||
},
|
||||
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.',
|
||||
);
|
||||
}
|
||||
|
||||
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;
|
||||
return dispatcher.readContext(Context, observedBits);
|
||||
}
|
||||
|
||||
let warnIfNonPrimitiveKey;
|
||||
if (__DEV__) {
|
||||
warnIfNonPrimitiveKey = (key, methodName) => {
|
||||
function identityHashFn(input) {
|
||||
if (__DEV__) {
|
||||
warningWithoutStack(
|
||||
typeof key === 'string' ||
|
||||
typeof key === 'number' ||
|
||||
typeof key === 'boolean' ||
|
||||
key === undefined ||
|
||||
key === null,
|
||||
'%s: Invalid key type. Expected a string, number, symbol, or boolean, ' +
|
||||
typeof input === 'string' ||
|
||||
typeof input === 'number' ||
|
||||
typeof input === 'boolean' ||
|
||||
input === undefined ||
|
||||
input === null,
|
||||
'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().',
|
||||
methodName,
|
||||
key,
|
||||
input,
|
||||
);
|
||||
};
|
||||
}
|
||||
return input;
|
||||
}
|
||||
|
||||
type primitive = string | number | boolean | void | null;
|
||||
const CACHE_LIMIT = 500;
|
||||
const lru = createLRU(CACHE_LIMIT);
|
||||
|
||||
type Resource<K, V> = {|
|
||||
read(Cache, K): V,
|
||||
preload(cache: Cache, key: K): void,
|
||||
|};
|
||||
const entries: Map<Resource<any, any>, Map<any, any>> = new Map();
|
||||
|
||||
// These declarations are used to express function overloading. I wish there
|
||||
// were a more elegant way to do this in the function definition itself.
|
||||
const CacheContext = React.createContext(null);
|
||||
|
||||
// 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 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);
|
||||
}
|
||||
}
|
||||
|
||||
// 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>;
|
||||
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);
|
||||
|
||||
// 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(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');
|
||||
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;
|
||||
}
|
||||
return cache.read(resource, key, loadResource, key);
|
||||
case Resolved: {
|
||||
const value = result.value;
|
||||
return value;
|
||||
}
|
||||
case Rejected: {
|
||||
const error = result.value;
|
||||
throw error;
|
||||
}
|
||||
default:
|
||||
// Should be unreachable
|
||||
return (undefined: any);
|
||||
}
|
||||
const hashedKey = hash(key);
|
||||
return cache.read(resource, hashedKey, loadResource, 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);
|
||||
|
||||
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);
|
||||
},
|
||||
};
|
||||
return resource;
|
||||
}
|
||||
|
||||
// Global cache has no eviction policy (except for, ya know, a browser refresh).
|
||||
const globalCache = createCache(noop);
|
||||
export const ReactCache = React.createContext(globalCache);
|
||||
export function unstable_setGlobalCacheLimit(limit: number) {
|
||||
lru.setLimit(limit);
|
||||
}
|
||||
|
||||
402
packages/react-cache/src/__tests__/ReactCache-test.internal.js
Normal file
402
packages/react-cache/src/__tests__/ReactCache-test.internal.js
Normal file
@@ -0,0 +1,402 @@
|
||||
/**
|
||||
* 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",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,235 +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';
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
7
packages/react-debug-tools/README.md
Normal file
7
packages/react-debug-tools/README.md
Normal file
@@ -0,0 +1,7 @@
|
||||
# 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
Normal file
13
packages/react-debug-tools/index.js
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* 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
Normal file
7
packages/react-debug-tools/npm/index.js
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
'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');
|
||||
}
|
||||
29
packages/react-debug-tools/package.json
Normal file
29
packages/react-debug-tools/package.json
Normal file
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"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",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
530
packages/react-debug-tools/src/ReactDebugHooks.js
vendored
Normal file
530
packages/react-debug-tools/src/ReactDebugHooks.js
vendored
Normal file
@@ -0,0 +1,530 @@
|
||||
/**
|
||||
* 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.useMutationEffect(() => {});
|
||||
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 useMutationEffect(
|
||||
create: () => mixed,
|
||||
inputs: Array<mixed> | void | null,
|
||||
): void {
|
||||
nextHook();
|
||||
hookLog.push({
|
||||
primitive: 'MutationEffect',
|
||||
stackError: new Error(),
|
||||
value: create,
|
||||
});
|
||||
}
|
||||
|
||||
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,
|
||||
useMutationEffect,
|
||||
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);
|
||||
}
|
||||
}
|
||||
12
packages/react-debug-tools/src/ReactDebugTools.js
vendored
Normal file
12
packages/react-debug-tools/src/ReactDebugTools.js
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* 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};
|
||||
@@ -0,0 +1,219 @@
|
||||
/**
|
||||
* 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.useMutationEffect(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: 'MutationEffect',
|
||||
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: [],
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,247 @@
|
||||
/**
|
||||
* 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.useMutationEffect(effect);
|
||||
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: 'MutationEffect', value: effect, 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: 'MutationEffect', value: effect, 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,6 +1,6 @@
|
||||
{
|
||||
"name": "react-dom",
|
||||
"version": "16.6.0-alpha.8af6728",
|
||||
"version": "16.6.1",
|
||||
"description": "React package for working with the DOM.",
|
||||
"main": "index.js",
|
||||
"repository": "facebook/react",
|
||||
@@ -16,10 +16,10 @@
|
||||
"loose-envify": "^1.1.0",
|
||||
"object-assign": "^4.1.1",
|
||||
"prop-types": "^15.6.2",
|
||||
"scheduler": "^0.10.0-alpha.8af6728"
|
||||
"scheduler": "^0.11.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^16.0.0 || 16.6.0-alpha.8af6728"
|
||||
"react": "^16.0.0"
|
||||
},
|
||||
"files": [
|
||||
"LICENSE",
|
||||
|
||||
@@ -332,7 +332,7 @@ describe('ReactCompositeComponent', () => {
|
||||
ReactDOM.unmountComponentAtNode(container);
|
||||
|
||||
expect(() => instance.forceUpdate()).toWarnDev(
|
||||
"Warning: Can't call setState (or forceUpdate) on an unmounted " +
|
||||
"Warning: Can't perform a React state update 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 call setState (or forceUpdate) on an unmounted " +
|
||||
"Warning: Can't perform a React state update 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' +
|
||||
|
||||
@@ -0,0 +1,666 @@
|
||||
/**
|
||||
* 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 useMutationEffect;
|
||||
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;
|
||||
useMutationEffect = React.useMutationEffect;
|
||||
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');
|
||||
});
|
||||
});
|
||||
|
||||
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('useMutationEffect', () => {
|
||||
it('should warn when invoked during render', async () => {
|
||||
function Counter() {
|
||||
useMutationEffect(() => {
|
||||
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('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,5 +249,195 @@ 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,6 +14,11 @@ 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.
|
||||
@@ -21,6 +26,18 @@ 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 {
|
||||
@@ -40,7 +57,7 @@ describe('ReactDOMServerIntegration', () => {
|
||||
const FunctionComponent = ({label, forwardedRef}) => (
|
||||
<div ref={forwardedRef}>{label}</div>
|
||||
);
|
||||
const WrappedFunctionComponent = React.forwardRef((props, ref) => (
|
||||
const WrappedFunctionComponent = forwardRef((props, ref) => (
|
||||
<FunctionComponent {...props} forwardedRef={ref} />
|
||||
));
|
||||
|
||||
@@ -65,4 +82,57 @@ 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,16 +43,48 @@ describe('ReactDOMServerSuspense', () => {
|
||||
resetModules();
|
||||
});
|
||||
|
||||
it('should always render the fallback when a placeholder is encountered', async () => {
|
||||
const Suspended = props => {
|
||||
throw new Promise(() => {});
|
||||
};
|
||||
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 () => {
|
||||
const e = await serverRender(
|
||||
<React.unstable_Suspense fallback={<div />}>
|
||||
<Suspended />
|
||||
</React.unstable_Suspense>,
|
||||
<React.Suspense fallback={<Text text="Fallback" />}>
|
||||
<Text text="Children" />
|
||||
</React.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>');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -14,7 +14,6 @@ let React;
|
||||
let ReactDOM;
|
||||
let Suspense;
|
||||
let ReactCache;
|
||||
let cache;
|
||||
let TextResource;
|
||||
|
||||
describe('ReactDOMSuspensePlaceholder', () => {
|
||||
@@ -23,18 +22,14 @@ describe('ReactDOMSuspensePlaceholder', () => {
|
||||
beforeEach(() => {
|
||||
jest.resetModules();
|
||||
ReactFeatureFlags = require('shared/ReactFeatureFlags');
|
||||
ReactFeatureFlags.enableSuspense = true;
|
||||
ReactFeatureFlags.enableHooks = true;
|
||||
React = require('react');
|
||||
ReactDOM = require('react-dom');
|
||||
ReactCache = require('react-cache');
|
||||
Suspense = React.unstable_Suspense;
|
||||
Suspense = React.Suspense;
|
||||
container = document.createElement('div');
|
||||
|
||||
function invalidateCache() {
|
||||
cache = ReactCache.createCache(invalidateCache);
|
||||
}
|
||||
invalidateCache();
|
||||
TextResource = ReactCache.createResource(([text, ms = 0]) => {
|
||||
TextResource = ReactCache.unstable_createResource(([text, ms = 0]) => {
|
||||
return new Promise((resolve, reject) =>
|
||||
setTimeout(() => {
|
||||
resolve(text);
|
||||
@@ -51,9 +46,8 @@ describe('ReactDOMSuspensePlaceholder', () => {
|
||||
}
|
||||
jest.advanceTimersByTime(ms);
|
||||
// Wait until the end of the current tick
|
||||
return new Promise(resolve => {
|
||||
setImmediate(resolve);
|
||||
});
|
||||
// We cannot use a timer since we're faking them
|
||||
return Promise.resolve().then(() => {});
|
||||
}
|
||||
|
||||
function Text(props) {
|
||||
@@ -62,7 +56,7 @@ describe('ReactDOMSuspensePlaceholder', () => {
|
||||
|
||||
function AsyncText(props) {
|
||||
const text = props.text;
|
||||
TextResource.read(cache, [props.text, props.ms]);
|
||||
TextResource.read([props.text, props.ms]);
|
||||
return text;
|
||||
}
|
||||
|
||||
@@ -117,4 +111,50 @@ 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>',
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -2149,4 +2149,19 @@ 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',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -610,7 +610,7 @@ describe('ReactDOMServer', () => {
|
||||
|
||||
it('throws for unsupported types on the server', () => {
|
||||
expect(() => {
|
||||
ReactDOMServer.renderToString(<React.unstable_Suspense />);
|
||||
ReactDOMServer.renderToString(<React.Suspense />);
|
||||
}).toThrow('ReactDOMServer does not yet support Suspense.');
|
||||
|
||||
async function fakeImport(result) {
|
||||
|
||||
@@ -444,20 +444,16 @@ 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(
|
||||
fakeImport(function World() {
|
||||
resolve({
|
||||
default: function World() {
|
||||
return 'world';
|
||||
}),
|
||||
),
|
||||
},
|
||||
}),
|
||||
1000,
|
||||
);
|
||||
}),
|
||||
@@ -474,9 +470,9 @@ describe('ReactDOMServerHydration', () => {
|
||||
<div>
|
||||
Hello{' '}
|
||||
{this.state.isClient && (
|
||||
<React.unstable_Suspense fallback="loading">
|
||||
<React.Suspense fallback="loading">
|
||||
<Lazy />
|
||||
</React.unstable_Suspense>
|
||||
</React.Suspense>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
@@ -491,7 +487,7 @@ describe('ReactDOMServerHydration', () => {
|
||||
expect(element.textContent).toBe('Hello loading');
|
||||
|
||||
jest.runAllTimers();
|
||||
await Lazy;
|
||||
await Promise.resolve();
|
||||
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 expeceted errors.
|
||||
// TODO: Rewrite tests that use this helper to enumerate expected errors.
|
||||
// This will enable the helper to use the .toWarnDev() matcher instead of spying.
|
||||
spyOnDev(console, 'error');
|
||||
}
|
||||
|
||||
22
packages/react-dom/src/client/ReactDOM.js
vendored
22
packages/react-dom/src/client/ReactDOM.js
vendored
@@ -34,6 +34,7 @@ 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 * as ReactDOMComponentTree from './ReactDOMComponentTree';
|
||||
import {restoreControlledState} from './ReactDOMComponent';
|
||||
@@ -399,7 +400,7 @@ ReactRoot.prototype.createBatch = function(): Batch {
|
||||
let insertBefore = firstBatch;
|
||||
while (
|
||||
insertBefore !== null &&
|
||||
insertBefore._expirationTime <= expirationTime
|
||||
insertBefore._expirationTime >= expirationTime
|
||||
) {
|
||||
insertAfter = insertBefore;
|
||||
insertBefore = insertBefore._next;
|
||||
@@ -770,17 +771,24 @@ type RootOptions = {
|
||||
hydrate?: boolean,
|
||||
};
|
||||
|
||||
ReactDOM.unstable_createRoot = function createRoot(
|
||||
container: DOMContainer,
|
||||
options?: RootOptions,
|
||||
): ReactRoot {
|
||||
function createRoot(container: DOMContainer, options?: RootOptions): ReactRoot {
|
||||
const functionName = enableStableConcurrentModeAPIs
|
||||
? 'createRoot'
|
||||
: 'unstable_createRoot';
|
||||
invariant(
|
||||
isValidContainer(container),
|
||||
'unstable_createRoot(...): Target container is not a DOM element.',
|
||||
'%s(...): Target container is not a DOM element.',
|
||||
functionName,
|
||||
);
|
||||
const hydrate = options != null && options.hydrate === true;
|
||||
return new ReactRoot(container, true, hydrate);
|
||||
};
|
||||
}
|
||||
|
||||
if (enableStableConcurrentModeAPIs) {
|
||||
ReactDOM.createRoot = createRoot;
|
||||
} else {
|
||||
ReactDOM.unstable_createRoot = createRoot;
|
||||
}
|
||||
|
||||
const foundDevTools = DOMRenderer.injectIntoDevTools({
|
||||
findFiberByHostInstance: ReactDOMComponentTree.getClosestInstanceFromNode,
|
||||
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
DOCUMENT_NODE,
|
||||
DOCUMENT_FRAGMENT_NODE,
|
||||
} from '../shared/HTMLNodeType';
|
||||
import dangerousStyleValue from '../shared/dangerousStyleValue';
|
||||
|
||||
import type {DOMContainer} from './ReactDOM';
|
||||
|
||||
@@ -68,6 +69,7 @@ export type NoTimeout = -1;
|
||||
export {
|
||||
unstable_now as now,
|
||||
unstable_scheduleCallback as scheduleDeferredCallback,
|
||||
unstable_shouldYield as shouldYield,
|
||||
unstable_cancelCallback as cancelDeferredCallback,
|
||||
} from 'scheduler';
|
||||
|
||||
@@ -283,8 +285,13 @@ export function createTextInstance(
|
||||
}
|
||||
|
||||
export const isPrimaryRenderer = true;
|
||||
export const scheduleTimeout = setTimeout;
|
||||
export const cancelTimeout = clearTimeout;
|
||||
// This initialization code may run even on server environments
|
||||
// if a component just imports ReactDOM (e.g. for findDOMNode).
|
||||
// Some environments might not have setTimeout or clearTimeout.
|
||||
export const scheduleTimeout =
|
||||
typeof setTimeout === 'function' ? setTimeout : (undefined: any);
|
||||
export const cancelTimeout =
|
||||
typeof clearTimeout === 'function' ? clearTimeout : (undefined: any);
|
||||
export const noTimeout = -1;
|
||||
|
||||
// -------------------
|
||||
@@ -436,8 +443,7 @@ export function unhideInstance(instance: Instance, props: Props): void {
|
||||
styleProp.hasOwnProperty('display')
|
||||
? styleProp.display
|
||||
: null;
|
||||
// $FlowFixMe Setting a style property to null is the valid way to reset it.
|
||||
instance.style.display = display;
|
||||
instance.style.display = dangerousStyleValue('display', display);
|
||||
}
|
||||
|
||||
export function unhideTextInstance(
|
||||
|
||||
@@ -277,7 +277,7 @@ export function postMountWrapper(
|
||||
}
|
||||
} else {
|
||||
// When syncing the value attribute, the value property should use
|
||||
// the the wrapperState._initialValue property. This uses:
|
||||
// the wrapperState._initialValue property. This uses:
|
||||
//
|
||||
// 1. The value React property when present
|
||||
// 2. The defaultValue React property when present
|
||||
@@ -330,7 +330,7 @@ export function postMountWrapper(
|
||||
node.defaultChecked = !!props.defaultChecked;
|
||||
}
|
||||
} else {
|
||||
// When syncing the checked attribute, both the the checked property and
|
||||
// When syncing the checked attribute, both the checked property and
|
||||
// attribute are assigned at the same time using defaultChecked. This uses:
|
||||
//
|
||||
// 1. The checked React property when present
|
||||
|
||||
@@ -153,6 +153,14 @@ export function getModernOffsetsFromPoints(
|
||||
export function setOffsets(node, offsets) {
|
||||
const doc = node.ownerDocument || document;
|
||||
const win = (doc && doc.defaultView) || window;
|
||||
|
||||
// Edge fails with "Object expected" in some scenarios.
|
||||
// (For instance: TinyMCE editor used in a list component that supports pasting to add more,
|
||||
// fails when pasting 100+ items)
|
||||
if (!win.getSelection) {
|
||||
return;
|
||||
}
|
||||
|
||||
const selection = win.getSelection();
|
||||
const length = node.textContent.length;
|
||||
let start = Math.min(offsets.start, length);
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow
|
||||
*/
|
||||
|
||||
import {TEXT_NODE} from '../shared/HTMLNodeType';
|
||||
@@ -43,7 +45,7 @@ function getSiblingNode(node) {
|
||||
* @param {number} offset
|
||||
* @return {?object}
|
||||
*/
|
||||
function getNodeForCharacterOffset(root, offset) {
|
||||
function getNodeForCharacterOffset(root: Element, offset: number): ?Object {
|
||||
let node = getLeafNode(root);
|
||||
let nodeStart = 0;
|
||||
let nodeEnd = 0;
|
||||
|
||||
@@ -100,7 +100,7 @@ function manualDispatchChangeEvent(nativeEvent) {
|
||||
}
|
||||
|
||||
function runEventInBatch(event) {
|
||||
EventPluginHub.runEventsInBatch(event, false);
|
||||
EventPluginHub.runEventsInBatch(event);
|
||||
}
|
||||
|
||||
function getInstIfValueChanged(targetInst) {
|
||||
|
||||
@@ -661,7 +661,7 @@ describe('ChangeEventPlugin', () => {
|
||||
type="text"
|
||||
value={controlledValue}
|
||||
onChange={() => {
|
||||
// Does nothing. Parent handler is reponsible for updating.
|
||||
// Does nothing. Parent handler is responsible for updating.
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow
|
||||
*/
|
||||
|
||||
/**
|
||||
@@ -10,6 +12,8 @@
|
||||
* @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
|
||||
*/
|
||||
|
||||
import type {AnyNativeEvent} from 'events/PluginModuleType';
|
||||
|
||||
const modifierKeyToProp = {
|
||||
Alt: 'altKey',
|
||||
Control: 'ctrlKey',
|
||||
@@ -17,10 +21,10 @@ const modifierKeyToProp = {
|
||||
Shift: 'shiftKey',
|
||||
};
|
||||
|
||||
// IE8 does not implement getModifierState so we simply map it to the only
|
||||
// modifier keys exposed by the event itself, does not support Lock-keys.
|
||||
// Currently, all major browsers except Chrome seems to support Lock-keys.
|
||||
function modifierStateGetter(keyArg) {
|
||||
// Older browsers (Safari <= 10, iOS Safari <= 10.2) do not support
|
||||
// getModifierState. If getModifierState is not supported, we map it to a set of
|
||||
// modifier keys exposed by the event. In this case, Lock-keys are not supported.
|
||||
function modifierStateGetter(keyArg: string): boolean {
|
||||
const syntheticEvent = this;
|
||||
const nativeEvent = syntheticEvent.nativeEvent;
|
||||
if (nativeEvent.getModifierState) {
|
||||
@@ -30,7 +34,9 @@ function modifierStateGetter(keyArg) {
|
||||
return keyProp ? !!nativeEvent[keyProp] : false;
|
||||
}
|
||||
|
||||
function getEventModifierState(nativeEvent) {
|
||||
function getEventModifierState(
|
||||
nativeEvent: AnyNativeEvent,
|
||||
): (keyArg: string) => boolean {
|
||||
return modifierStateGetter;
|
||||
}
|
||||
|
||||
|
||||
@@ -18,11 +18,15 @@ class ReactMarkupReadableStream extends Readable {
|
||||
this.partialRenderer = new ReactPartialRenderer(element, makeStaticMarkup);
|
||||
}
|
||||
|
||||
_destroy() {
|
||||
this.partialRenderer.destroy();
|
||||
}
|
||||
|
||||
_read(size) {
|
||||
try {
|
||||
this.push(this.partialRenderer.read(size));
|
||||
} catch (err) {
|
||||
this.emit('error', err);
|
||||
this.destroy(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,8 +14,12 @@ import ReactPartialRenderer from './ReactPartialRenderer';
|
||||
*/
|
||||
export function renderToString(element) {
|
||||
const renderer = new ReactPartialRenderer(element, false);
|
||||
const markup = renderer.read(Infinity);
|
||||
return markup;
|
||||
try {
|
||||
const markup = renderer.read(Infinity);
|
||||
return markup;
|
||||
} finally {
|
||||
renderer.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -25,6 +29,10 @@ export function renderToString(element) {
|
||||
*/
|
||||
export function renderToStaticMarkup(element) {
|
||||
const renderer = new ReactPartialRenderer(element, true);
|
||||
const markup = renderer.read(Infinity);
|
||||
return markup;
|
||||
try {
|
||||
const markup = renderer.read(Infinity);
|
||||
return markup;
|
||||
} finally {
|
||||
renderer.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,12 +7,9 @@
|
||||
* @flow
|
||||
*/
|
||||
|
||||
import type {ThreadID} from './ReactThreadIDAllocator';
|
||||
import type {ReactElement} from 'shared/ReactElementType';
|
||||
import type {
|
||||
ReactProvider,
|
||||
ReactConsumer,
|
||||
ReactContext,
|
||||
} from 'shared/ReactTypes';
|
||||
import type {ReactProvider, ReactContext} from 'shared/ReactTypes';
|
||||
|
||||
import React from 'react';
|
||||
import invariant from 'shared/invariant';
|
||||
@@ -20,11 +17,11 @@ import getComponentName from 'shared/getComponentName';
|
||||
import lowPriorityWarning from 'shared/lowPriorityWarning';
|
||||
import warning from 'shared/warning';
|
||||
import warningWithoutStack from 'shared/warningWithoutStack';
|
||||
import checkPropTypes from 'prop-types/checkPropTypes';
|
||||
import describeComponentFrame from 'shared/describeComponentFrame';
|
||||
import ReactSharedInternals from 'shared/ReactSharedInternals';
|
||||
import {
|
||||
warnAboutDeprecatedLifecycles,
|
||||
enableHooks,
|
||||
enableSuspenseServerRenderer,
|
||||
} from 'shared/ReactFeatureFlags';
|
||||
|
||||
@@ -39,14 +36,29 @@ import {
|
||||
REACT_PROVIDER_TYPE,
|
||||
REACT_CONTEXT_TYPE,
|
||||
REACT_LAZY_TYPE,
|
||||
REACT_MEMO_TYPE,
|
||||
} from 'shared/ReactSymbols';
|
||||
|
||||
import {
|
||||
emptyObject,
|
||||
processContext,
|
||||
validateContextBounds,
|
||||
} from './ReactPartialRendererContext';
|
||||
import {allocThreadID, freeThreadID} from './ReactThreadIDAllocator';
|
||||
import {
|
||||
createMarkupForCustomAttribute,
|
||||
createMarkupForProperty,
|
||||
createMarkupForRoot,
|
||||
} from './DOMMarkupOperations';
|
||||
import escapeTextForBrowser from './escapeTextForBrowser';
|
||||
import {
|
||||
prepareToUseHooks,
|
||||
finishHooks,
|
||||
Dispatcher,
|
||||
DispatcherWithoutHooks,
|
||||
currentThreadID,
|
||||
setCurrentThreadID,
|
||||
} from './ReactPartialRendererHooks';
|
||||
import {
|
||||
Namespaces,
|
||||
getIntrinsicNamespace,
|
||||
@@ -85,15 +97,7 @@ let validatePropertiesInDevelopment = (type, props) => {};
|
||||
let pushCurrentDebugStack = (stack: Array<Frame>) => {};
|
||||
let pushElementToDebugStack = (element: ReactElement) => {};
|
||||
let popCurrentDebugStack = () => {};
|
||||
|
||||
let Dispatcher = {
|
||||
readContext<T>(
|
||||
context: ReactContext<T>,
|
||||
observedBits: void | number | boolean,
|
||||
): T {
|
||||
return context._currentValue;
|
||||
},
|
||||
};
|
||||
let hasWarnedAboutUsingContextAsConsumer = false;
|
||||
|
||||
if (__DEV__) {
|
||||
ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
|
||||
@@ -180,7 +184,6 @@ const didWarnAboutBadClass = {};
|
||||
const didWarnAboutDeprecatedWillMount = {};
|
||||
const didWarnAboutUndefinedDerivedState = {};
|
||||
const didWarnAboutUninitializedState = {};
|
||||
const didWarnAboutInvalidateContextType = {};
|
||||
const valuePropNames = ['value', 'defaultValue'];
|
||||
const newlineEatingTags = {
|
||||
listing: true,
|
||||
@@ -328,65 +331,6 @@ function flattenOptionChildren(children: mixed): ?string {
|
||||
return content;
|
||||
}
|
||||
|
||||
const emptyObject = {};
|
||||
if (__DEV__) {
|
||||
Object.freeze(emptyObject);
|
||||
}
|
||||
|
||||
function maskContext(type, context) {
|
||||
const contextTypes = type.contextTypes;
|
||||
if (!contextTypes) {
|
||||
return emptyObject;
|
||||
}
|
||||
const maskedContext = {};
|
||||
for (const contextName in contextTypes) {
|
||||
maskedContext[contextName] = context[contextName];
|
||||
}
|
||||
return maskedContext;
|
||||
}
|
||||
|
||||
function checkContextTypes(typeSpecs, values, location: string) {
|
||||
if (__DEV__) {
|
||||
checkPropTypes(
|
||||
typeSpecs,
|
||||
values,
|
||||
location,
|
||||
'Component',
|
||||
getCurrentServerStackImpl,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function processContext(type, context) {
|
||||
const contextType = type.contextType;
|
||||
if (typeof contextType === 'object' && contextType !== null) {
|
||||
if (__DEV__) {
|
||||
if (contextType.$$typeof !== REACT_CONTEXT_TYPE) {
|
||||
let name = getComponentName(type) || 'Component';
|
||||
if (!didWarnAboutInvalidateContextType[name]) {
|
||||
didWarnAboutInvalidateContextType[type] = true;
|
||||
warningWithoutStack(
|
||||
false,
|
||||
'%s defines an invalid contextType. ' +
|
||||
'contextType should point to the Context object returned by React.createContext(). ' +
|
||||
'Did you accidentally pass the Context.Provider instead?',
|
||||
name,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return contextType._currentValue;
|
||||
} else {
|
||||
const maskedContext = maskContext(type, context);
|
||||
if (__DEV__) {
|
||||
if (type.contextTypes) {
|
||||
checkContextTypes(type.contextTypes, maskedContext, 'context');
|
||||
}
|
||||
}
|
||||
return maskedContext;
|
||||
}
|
||||
}
|
||||
|
||||
const hasOwnProperty = Object.prototype.hasOwnProperty;
|
||||
const STYLE = 'style';
|
||||
const RESERVED_PROPS = {
|
||||
@@ -457,6 +401,7 @@ function validateRenderResult(child, type) {
|
||||
function resolve(
|
||||
child: mixed,
|
||||
context: Object,
|
||||
threadID: ThreadID,
|
||||
): {|
|
||||
child: mixed,
|
||||
context: Object,
|
||||
@@ -476,7 +421,7 @@ function resolve(
|
||||
|
||||
// Extra closure so queue and replace can be captured properly
|
||||
function processChild(element, Component) {
|
||||
let publicContext = processContext(Component, context);
|
||||
let publicContext = processContext(Component, context, threadID);
|
||||
|
||||
let queue = [];
|
||||
let replace = false;
|
||||
@@ -572,7 +517,11 @@ function resolve(
|
||||
}
|
||||
}
|
||||
}
|
||||
const componentIdentity = {};
|
||||
prepareToUseHooks(componentIdentity);
|
||||
inst = Component(element.props, publicContext, updater);
|
||||
inst = finishHooks(Component, element.props, inst, publicContext);
|
||||
|
||||
if (inst == null || inst.render == null) {
|
||||
child = inst;
|
||||
validateRenderResult(child, Component);
|
||||
@@ -707,6 +656,7 @@ type Frame = {
|
||||
type: mixed,
|
||||
domNamespace: string,
|
||||
children: FlatReactChildren,
|
||||
fallbackFrame?: Frame,
|
||||
childIndex: number,
|
||||
context: Object,
|
||||
footer: string,
|
||||
@@ -717,12 +667,14 @@ type FrameDev = Frame & {
|
||||
};
|
||||
|
||||
class ReactDOMServerRenderer {
|
||||
threadID: ThreadID;
|
||||
stack: Array<Frame>;
|
||||
exhausted: boolean;
|
||||
// TODO: type this more strictly:
|
||||
currentSelectValue: any;
|
||||
previousWasTextNode: boolean;
|
||||
makeStaticMarkup: boolean;
|
||||
suspenseDepth: number;
|
||||
|
||||
contextIndex: number;
|
||||
contextStack: Array<ReactContext<any>>;
|
||||
@@ -745,11 +697,13 @@ class ReactDOMServerRenderer {
|
||||
if (__DEV__) {
|
||||
((topFrame: any): FrameDev).debugElementStack = [];
|
||||
}
|
||||
this.threadID = allocThreadID();
|
||||
this.stack = [topFrame];
|
||||
this.exhausted = false;
|
||||
this.currentSelectValue = null;
|
||||
this.previousWasTextNode = false;
|
||||
this.makeStaticMarkup = makeStaticMarkup;
|
||||
this.suspenseDepth = 0;
|
||||
|
||||
// Context (new API)
|
||||
this.contextIndex = -1;
|
||||
@@ -760,6 +714,13 @@ class ReactDOMServerRenderer {
|
||||
}
|
||||
}
|
||||
|
||||
destroy() {
|
||||
if (!this.exhausted) {
|
||||
this.exhausted = true;
|
||||
freeThreadID(this.threadID);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Note: We use just two stacks regardless of how many context providers you have.
|
||||
* Providers are always popped in the reverse order to how they were pushed
|
||||
@@ -773,7 +734,9 @@ class ReactDOMServerRenderer {
|
||||
pushProvider<T>(provider: ReactProvider<T>): void {
|
||||
const index = ++this.contextIndex;
|
||||
const context: ReactContext<any> = provider.type._context;
|
||||
const previousValue = context._currentValue;
|
||||
const threadID = this.threadID;
|
||||
validateContextBounds(context, threadID);
|
||||
const previousValue = context[threadID];
|
||||
|
||||
// Remember which value to restore this context to on our way up.
|
||||
this.contextStack[index] = context;
|
||||
@@ -784,7 +747,7 @@ class ReactDOMServerRenderer {
|
||||
}
|
||||
|
||||
// Mutate the current value.
|
||||
context._currentValue = provider.props.value;
|
||||
context[threadID] = provider.props.value;
|
||||
}
|
||||
|
||||
popProvider<T>(provider: ReactProvider<T>): void {
|
||||
@@ -810,7 +773,9 @@ class ReactDOMServerRenderer {
|
||||
this.contextIndex--;
|
||||
|
||||
// Restore to the previous value we stored as we were walking down.
|
||||
context._currentValue = previousValue;
|
||||
// We've already verified that this context has been expanded to accommodate
|
||||
// this thread id, so we don't need to do it again.
|
||||
context[this.threadID] = previousValue;
|
||||
}
|
||||
|
||||
read(bytes: number): string | null {
|
||||
@@ -818,18 +783,28 @@ class ReactDOMServerRenderer {
|
||||
return null;
|
||||
}
|
||||
|
||||
ReactCurrentOwner.currentDispatcher = Dispatcher;
|
||||
const prevThreadID = currentThreadID;
|
||||
setCurrentThreadID(this.threadID);
|
||||
const prevDispatcher = ReactCurrentOwner.currentDispatcher;
|
||||
if (enableHooks) {
|
||||
ReactCurrentOwner.currentDispatcher = Dispatcher;
|
||||
} else {
|
||||
ReactCurrentOwner.currentDispatcher = DispatcherWithoutHooks;
|
||||
}
|
||||
try {
|
||||
let out = '';
|
||||
while (out.length < bytes) {
|
||||
// Markup generated within <Suspense> ends up buffered until we know
|
||||
// nothing in that boundary suspended
|
||||
let out = [''];
|
||||
let suspended = false;
|
||||
while (out[0].length < bytes) {
|
||||
if (this.stack.length === 0) {
|
||||
this.exhausted = true;
|
||||
freeThreadID(this.threadID);
|
||||
break;
|
||||
}
|
||||
const frame: Frame = this.stack[this.stack.length - 1];
|
||||
if (frame.childIndex >= frame.children.length) {
|
||||
if (suspended || frame.childIndex >= frame.children.length) {
|
||||
const footer = frame.footer;
|
||||
out += footer;
|
||||
if (footer !== '') {
|
||||
this.previousWasTextNode = false;
|
||||
}
|
||||
@@ -843,28 +818,60 @@ class ReactDOMServerRenderer {
|
||||
) {
|
||||
const provider: ReactProvider<any> = (frame.type: any);
|
||||
this.popProvider(provider);
|
||||
} else if (frame.type === REACT_SUSPENSE_TYPE) {
|
||||
this.suspenseDepth--;
|
||||
const buffered = out.pop();
|
||||
|
||||
if (suspended) {
|
||||
suspended = false;
|
||||
// If rendering was suspended at this boundary, render the fallbackFrame
|
||||
const fallbackFrame = frame.fallbackFrame;
|
||||
invariant(
|
||||
fallbackFrame,
|
||||
'suspense fallback not found, something is broken',
|
||||
);
|
||||
this.stack.push(fallbackFrame);
|
||||
// Skip flushing output since we're switching to the fallback
|
||||
continue;
|
||||
} else {
|
||||
out[this.suspenseDepth] += buffered;
|
||||
}
|
||||
}
|
||||
|
||||
// Flush output
|
||||
out[this.suspenseDepth] += footer;
|
||||
continue;
|
||||
}
|
||||
const child = frame.children[frame.childIndex++];
|
||||
|
||||
let outBuffer = '';
|
||||
if (__DEV__) {
|
||||
pushCurrentDebugStack(this.stack);
|
||||
// We're starting work on this frame, so reset its inner stack.
|
||||
((frame: any): FrameDev).debugElementStack.length = 0;
|
||||
try {
|
||||
// Be careful! Make sure this matches the PROD path below.
|
||||
out += this.render(child, frame.context, frame.domNamespace);
|
||||
} finally {
|
||||
}
|
||||
try {
|
||||
outBuffer += this.render(child, frame.context, frame.domNamespace);
|
||||
} catch (err) {
|
||||
if (enableSuspenseServerRenderer && typeof err.then === 'function') {
|
||||
suspended = true;
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
} finally {
|
||||
if (__DEV__) {
|
||||
popCurrentDebugStack();
|
||||
}
|
||||
} else {
|
||||
// Be careful! Make sure this matches the DEV path above.
|
||||
out += this.render(child, frame.context, frame.domNamespace);
|
||||
}
|
||||
if (out.length <= this.suspenseDepth) {
|
||||
out.push('');
|
||||
}
|
||||
out[this.suspenseDepth] += outBuffer;
|
||||
}
|
||||
return out;
|
||||
return out[0];
|
||||
} finally {
|
||||
ReactCurrentOwner.currentDispatcher = null;
|
||||
ReactCurrentOwner.currentDispatcher = prevDispatcher;
|
||||
setCurrentThreadID(prevThreadID);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -888,7 +895,7 @@ class ReactDOMServerRenderer {
|
||||
return escapeTextForBrowser(text);
|
||||
} else {
|
||||
let nextChild;
|
||||
({child: nextChild, context} = resolve(child, context));
|
||||
({child: nextChild, context} = resolve(child, context, this.threadID));
|
||||
if (nextChild === null || nextChild === false) {
|
||||
return '';
|
||||
} else if (!React.isValidElement(nextChild)) {
|
||||
@@ -955,13 +962,25 @@ class ReactDOMServerRenderer {
|
||||
}
|
||||
case REACT_SUSPENSE_TYPE: {
|
||||
if (enableSuspenseServerRenderer) {
|
||||
const nextChildren = toArray(
|
||||
// Always use the fallback when synchronously rendering to string.
|
||||
const fallbackChildren = toArray(
|
||||
((nextChild: any): ReactElement).props.fallback,
|
||||
);
|
||||
const frame: Frame = {
|
||||
const nextChildren = toArray(
|
||||
((nextChild: any): ReactElement).props.children,
|
||||
);
|
||||
const fallbackFrame: Frame = {
|
||||
type: null,
|
||||
domNamespace: parentNamespace,
|
||||
children: fallbackChildren,
|
||||
childIndex: 0,
|
||||
context: context,
|
||||
footer: '',
|
||||
out: '',
|
||||
};
|
||||
const frame: Frame = {
|
||||
fallbackFrame,
|
||||
type: REACT_SUSPENSE_TYPE,
|
||||
domNamespace: parentNamespace,
|
||||
children: nextChildren,
|
||||
childIndex: 0,
|
||||
context: context,
|
||||
@@ -969,8 +988,10 @@ class ReactDOMServerRenderer {
|
||||
};
|
||||
if (__DEV__) {
|
||||
((frame: any): FrameDev).debugElementStack = [];
|
||||
((fallbackFrame: any): FrameDev).debugElementStack = [];
|
||||
}
|
||||
this.stack.push(frame);
|
||||
this.suspenseDepth++;
|
||||
return '';
|
||||
} else {
|
||||
invariant(false, 'ReactDOMServer does not yet support Suspense.');
|
||||
@@ -984,9 +1005,39 @@ class ReactDOMServerRenderer {
|
||||
switch (elementType.$$typeof) {
|
||||
case REACT_FORWARD_REF_TYPE: {
|
||||
const element: ReactElement = ((nextChild: any): ReactElement);
|
||||
const nextChildren = toArray(
|
||||
elementType.render(element.props, element.ref),
|
||||
let nextChildren;
|
||||
const componentIdentity = {};
|
||||
prepareToUseHooks(componentIdentity);
|
||||
nextChildren = elementType.render(element.props, element.ref);
|
||||
nextChildren = finishHooks(
|
||||
elementType.render,
|
||||
element.props,
|
||||
nextChildren,
|
||||
element.ref,
|
||||
);
|
||||
nextChildren = toArray(nextChildren);
|
||||
const frame: Frame = {
|
||||
type: null,
|
||||
domNamespace: parentNamespace,
|
||||
children: nextChildren,
|
||||
childIndex: 0,
|
||||
context: context,
|
||||
footer: '',
|
||||
};
|
||||
if (__DEV__) {
|
||||
((frame: any): FrameDev).debugElementStack = [];
|
||||
}
|
||||
this.stack.push(frame);
|
||||
return '';
|
||||
}
|
||||
case REACT_MEMO_TYPE: {
|
||||
const element: ReactElement = ((nextChild: any): ReactElement);
|
||||
let nextChildren = [
|
||||
React.createElement(
|
||||
elementType.type,
|
||||
Object.assign({ref: element.ref}, element.props),
|
||||
),
|
||||
];
|
||||
const frame: Frame = {
|
||||
type: null,
|
||||
domNamespace: parentNamespace,
|
||||
@@ -1023,9 +1074,37 @@ class ReactDOMServerRenderer {
|
||||
return '';
|
||||
}
|
||||
case REACT_CONTEXT_TYPE: {
|
||||
const consumer: ReactConsumer<any> = (nextChild: any);
|
||||
const nextProps: any = consumer.props;
|
||||
const nextValue = consumer.type._currentValue;
|
||||
let reactContext = (nextChild: any).type;
|
||||
// The logic below for Context differs depending on PROD or DEV mode. In
|
||||
// DEV mode, we create a separate object for Context.Consumer that acts
|
||||
// like a proxy to Context. This proxy object adds unnecessary code in PROD
|
||||
// so we use the old behaviour (Context.Consumer references Context) to
|
||||
// reduce size and overhead. The separate object references context via
|
||||
// a property called "_context", which also gives us the ability to check
|
||||
// in DEV mode if this property exists or not and warn if it does not.
|
||||
if (__DEV__) {
|
||||
if ((reactContext: any)._context === undefined) {
|
||||
// This may be because it's a Context (rather than a Consumer).
|
||||
// Or it may be because it's older React where they're the same thing.
|
||||
// We only want to warn if we're sure it's a new React.
|
||||
if (reactContext !== reactContext.Consumer) {
|
||||
if (!hasWarnedAboutUsingContextAsConsumer) {
|
||||
hasWarnedAboutUsingContextAsConsumer = true;
|
||||
warning(
|
||||
false,
|
||||
'Rendering <Context> directly is not supported and will be removed in ' +
|
||||
'a future major release. Did you mean to render <Context.Consumer> instead?',
|
||||
);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
reactContext = (reactContext: any)._context;
|
||||
}
|
||||
}
|
||||
const nextProps: any = (nextChild: any).props;
|
||||
const threadID = this.threadID;
|
||||
validateContextBounds(reactContext, threadID);
|
||||
const nextValue = reactContext[threadID];
|
||||
|
||||
const nextChildren = toArray(nextProps.children(nextValue));
|
||||
const frame: Frame = {
|
||||
|
||||
104
packages/react-dom/src/server/ReactPartialRendererContext.js
vendored
Normal file
104
packages/react-dom/src/server/ReactPartialRendererContext.js
vendored
Normal file
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* 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 {ThreadID} from './ReactThreadIDAllocator';
|
||||
import type {ReactContext} from 'shared/ReactTypes';
|
||||
|
||||
import {REACT_CONTEXT_TYPE} from 'shared/ReactSymbols';
|
||||
import ReactSharedInternals from 'shared/ReactSharedInternals';
|
||||
import getComponentName from 'shared/getComponentName';
|
||||
import warningWithoutStack from 'shared/warningWithoutStack';
|
||||
import checkPropTypes from 'prop-types/checkPropTypes';
|
||||
|
||||
let ReactDebugCurrentFrame;
|
||||
if (__DEV__) {
|
||||
ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
|
||||
}
|
||||
|
||||
const didWarnAboutInvalidateContextType = {};
|
||||
|
||||
export const emptyObject = {};
|
||||
if (__DEV__) {
|
||||
Object.freeze(emptyObject);
|
||||
}
|
||||
|
||||
function maskContext(type, context) {
|
||||
const contextTypes = type.contextTypes;
|
||||
if (!contextTypes) {
|
||||
return emptyObject;
|
||||
}
|
||||
const maskedContext = {};
|
||||
for (const contextName in contextTypes) {
|
||||
maskedContext[contextName] = context[contextName];
|
||||
}
|
||||
return maskedContext;
|
||||
}
|
||||
|
||||
function checkContextTypes(typeSpecs, values, location: string) {
|
||||
if (__DEV__) {
|
||||
checkPropTypes(
|
||||
typeSpecs,
|
||||
values,
|
||||
location,
|
||||
'Component',
|
||||
ReactDebugCurrentFrame.getCurrentStack,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function validateContextBounds(
|
||||
context: ReactContext<any>,
|
||||
threadID: ThreadID,
|
||||
) {
|
||||
// If we don't have enough slots in this context to store this threadID,
|
||||
// fill it in without leaving any holes to ensure that the VM optimizes
|
||||
// this as non-holey index properties.
|
||||
for (let i = context._threadCount; i <= threadID; i++) {
|
||||
// We assume that this is the same as the defaultValue which might not be
|
||||
// true if we're rendering inside a secondary renderer but they are
|
||||
// secondary because these use cases are very rare.
|
||||
context[i] = context._currentValue2;
|
||||
context._threadCount = i + 1;
|
||||
}
|
||||
}
|
||||
|
||||
export function processContext(
|
||||
type: Function,
|
||||
context: Object,
|
||||
threadID: ThreadID,
|
||||
) {
|
||||
const contextType = type.contextType;
|
||||
if (typeof contextType === 'object' && contextType !== null) {
|
||||
if (__DEV__) {
|
||||
if (contextType.$$typeof !== REACT_CONTEXT_TYPE) {
|
||||
let name = getComponentName(type) || 'Component';
|
||||
if (!didWarnAboutInvalidateContextType[name]) {
|
||||
didWarnAboutInvalidateContextType[name] = true;
|
||||
warningWithoutStack(
|
||||
false,
|
||||
'%s defines an invalid contextType. ' +
|
||||
'contextType should point to the Context object returned by React.createContext(). ' +
|
||||
'Did you accidentally pass the Context.Provider instead?',
|
||||
name,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
validateContextBounds(contextType, threadID);
|
||||
return contextType[threadID];
|
||||
} else {
|
||||
const maskedContext = maskContext(type, context);
|
||||
if (__DEV__) {
|
||||
if (type.contextTypes) {
|
||||
checkContextTypes(type.contextTypes, maskedContext, 'context');
|
||||
}
|
||||
}
|
||||
return maskedContext;
|
||||
}
|
||||
}
|
||||
369
packages/react-dom/src/server/ReactPartialRendererHooks.js
vendored
Normal file
369
packages/react-dom/src/server/ReactPartialRendererHooks.js
vendored
Normal file
@@ -0,0 +1,369 @@
|
||||
/**
|
||||
* 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 {ThreadID} from './ReactThreadIDAllocator';
|
||||
import type {ReactContext} from 'shared/ReactTypes';
|
||||
import areHookInputsEqual from 'shared/areHookInputsEqual';
|
||||
|
||||
import {validateContextBounds} from './ReactPartialRendererContext';
|
||||
|
||||
import invariant from 'shared/invariant';
|
||||
import warning from 'shared/warning';
|
||||
|
||||
type BasicStateAction<S> = (S => S) | S;
|
||||
type Dispatch<A> = A => void;
|
||||
|
||||
type Update<A> = {
|
||||
action: A,
|
||||
next: Update<A> | null,
|
||||
};
|
||||
|
||||
type UpdateQueue<A> = {
|
||||
last: Update<A> | null,
|
||||
dispatch: any,
|
||||
};
|
||||
|
||||
type Hook = {
|
||||
memoizedState: any,
|
||||
queue: UpdateQueue<any> | null,
|
||||
next: Hook | null,
|
||||
};
|
||||
|
||||
let currentlyRenderingComponent: Object | null = null;
|
||||
let firstWorkInProgressHook: Hook | null = null;
|
||||
let workInProgressHook: Hook | null = null;
|
||||
// Whether the work-in-progress hook is a re-rendered hook
|
||||
let isReRender: boolean = false;
|
||||
// Whether an update was scheduled during the currently executing render pass.
|
||||
let didScheduleRenderPhaseUpdate: boolean = false;
|
||||
// Lazily created map of render-phase updates
|
||||
let renderPhaseUpdates: Map<UpdateQueue<any>, Update<any>> | null = null;
|
||||
// Counter to prevent infinite loops.
|
||||
let numberOfReRenders: number = 0;
|
||||
const RE_RENDER_LIMIT = 25;
|
||||
|
||||
function resolveCurrentlyRenderingComponent(): Object {
|
||||
invariant(
|
||||
currentlyRenderingComponent !== null,
|
||||
'Hooks can only be called inside the body of a function component.',
|
||||
);
|
||||
return currentlyRenderingComponent;
|
||||
}
|
||||
|
||||
function createHook(): Hook {
|
||||
return {
|
||||
memoizedState: null,
|
||||
queue: null,
|
||||
next: null,
|
||||
};
|
||||
}
|
||||
|
||||
function createWorkInProgressHook(): Hook {
|
||||
if (workInProgressHook === null) {
|
||||
// This is the first hook in the list
|
||||
if (firstWorkInProgressHook === null) {
|
||||
isReRender = false;
|
||||
firstWorkInProgressHook = workInProgressHook = createHook();
|
||||
} else {
|
||||
// There's already a work-in-progress. Reuse it.
|
||||
isReRender = true;
|
||||
workInProgressHook = firstWorkInProgressHook;
|
||||
}
|
||||
} else {
|
||||
if (workInProgressHook.next === null) {
|
||||
isReRender = false;
|
||||
// Append to the end of the list
|
||||
workInProgressHook = workInProgressHook.next = createHook();
|
||||
} else {
|
||||
// There's already a work-in-progress. Reuse it.
|
||||
isReRender = true;
|
||||
workInProgressHook = workInProgressHook.next;
|
||||
}
|
||||
}
|
||||
return workInProgressHook;
|
||||
}
|
||||
|
||||
export function prepareToUseHooks(componentIdentity: Object): void {
|
||||
currentlyRenderingComponent = componentIdentity;
|
||||
|
||||
// The following should have already been reset
|
||||
// didScheduleRenderPhaseUpdate = false;
|
||||
// firstWorkInProgressHook = null;
|
||||
// numberOfReRenders = 0;
|
||||
// renderPhaseUpdates = null;
|
||||
// workInProgressHook = null;
|
||||
}
|
||||
|
||||
export function finishHooks(
|
||||
Component: any,
|
||||
props: any,
|
||||
children: any,
|
||||
refOrContext: any,
|
||||
): any {
|
||||
// This must be called after every function component to prevent hooks from
|
||||
// being used in classes.
|
||||
|
||||
while (didScheduleRenderPhaseUpdate) {
|
||||
// Updates were scheduled during the render phase. They are stored in
|
||||
// the `renderPhaseUpdates` map. Call the component again, reusing the
|
||||
// work-in-progress hooks and applying the additional updates on top. Keep
|
||||
// restarting until no more updates are scheduled.
|
||||
didScheduleRenderPhaseUpdate = false;
|
||||
numberOfReRenders += 1;
|
||||
|
||||
// Start over from the beginning of the list
|
||||
workInProgressHook = null;
|
||||
|
||||
children = Component(props, refOrContext);
|
||||
}
|
||||
currentlyRenderingComponent = null;
|
||||
firstWorkInProgressHook = null;
|
||||
numberOfReRenders = 0;
|
||||
renderPhaseUpdates = null;
|
||||
workInProgressHook = null;
|
||||
|
||||
// These were reset above
|
||||
// currentlyRenderingComponent = null;
|
||||
// didScheduleRenderPhaseUpdate = false;
|
||||
// firstWorkInProgressHook = null;
|
||||
// numberOfReRenders = 0;
|
||||
// renderPhaseUpdates = null;
|
||||
// workInProgressHook = null;
|
||||
|
||||
return children;
|
||||
}
|
||||
|
||||
function readContext<T>(
|
||||
context: ReactContext<T>,
|
||||
observedBits: void | number | boolean,
|
||||
): T {
|
||||
let threadID = currentThreadID;
|
||||
validateContextBounds(context, threadID);
|
||||
return context[threadID];
|
||||
}
|
||||
|
||||
function useContext<T>(
|
||||
context: ReactContext<T>,
|
||||
observedBits: void | number | boolean,
|
||||
): T {
|
||||
resolveCurrentlyRenderingComponent();
|
||||
let threadID = currentThreadID;
|
||||
validateContextBounds(context, threadID);
|
||||
return context[threadID];
|
||||
}
|
||||
|
||||
function basicStateReducer<S>(state: S, action: BasicStateAction<S>): S {
|
||||
return typeof action === 'function' ? action(state) : action;
|
||||
}
|
||||
|
||||
export function useState<S>(
|
||||
initialState: (() => S) | S,
|
||||
): [S, Dispatch<BasicStateAction<S>>] {
|
||||
return useReducer(
|
||||
basicStateReducer,
|
||||
// useReducer has a special case to support lazy useState initializers
|
||||
(initialState: any),
|
||||
);
|
||||
}
|
||||
|
||||
export function useReducer<S, A>(
|
||||
reducer: (S, A) => S,
|
||||
initialState: S,
|
||||
initialAction: A | void | null,
|
||||
): [S, Dispatch<A>] {
|
||||
currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
|
||||
workInProgressHook = createWorkInProgressHook();
|
||||
if (isReRender) {
|
||||
// This is a re-render. Apply the new render phase updates to the previous
|
||||
// current hook.
|
||||
const queue: UpdateQueue<A> = (workInProgressHook.queue: any);
|
||||
const dispatch: Dispatch<A> = (queue.dispatch: any);
|
||||
if (renderPhaseUpdates !== null) {
|
||||
// Render phase updates are stored in a map of queue -> linked list
|
||||
const firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
|
||||
if (firstRenderPhaseUpdate !== undefined) {
|
||||
renderPhaseUpdates.delete(queue);
|
||||
let newState = workInProgressHook.memoizedState;
|
||||
let update = firstRenderPhaseUpdate;
|
||||
do {
|
||||
// Process this render phase update. We don't have to check the
|
||||
// priority because it will always be the same as the current
|
||||
// render's.
|
||||
const action = update.action;
|
||||
newState = reducer(newState, action);
|
||||
update = update.next;
|
||||
} while (update !== null);
|
||||
|
||||
workInProgressHook.memoizedState = newState;
|
||||
|
||||
return [newState, dispatch];
|
||||
}
|
||||
}
|
||||
return [workInProgressHook.memoizedState, dispatch];
|
||||
} else {
|
||||
if (reducer === basicStateReducer) {
|
||||
// Special case for `useState`.
|
||||
if (typeof initialState === 'function') {
|
||||
initialState = initialState();
|
||||
}
|
||||
} else if (initialAction !== undefined && initialAction !== null) {
|
||||
initialState = reducer(initialState, initialAction);
|
||||
}
|
||||
workInProgressHook.memoizedState = initialState;
|
||||
const queue: UpdateQueue<A> = (workInProgressHook.queue = {
|
||||
last: null,
|
||||
dispatch: null,
|
||||
});
|
||||
const dispatch: Dispatch<A> = (queue.dispatch = (dispatchAction.bind(
|
||||
null,
|
||||
currentlyRenderingComponent,
|
||||
queue,
|
||||
): any));
|
||||
return [workInProgressHook.memoizedState, dispatch];
|
||||
}
|
||||
}
|
||||
|
||||
function useMemo<T>(
|
||||
nextCreate: () => T,
|
||||
inputs: Array<mixed> | void | null,
|
||||
): T {
|
||||
currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
|
||||
workInProgressHook = createWorkInProgressHook();
|
||||
|
||||
const nextInputs =
|
||||
inputs !== undefined && inputs !== null ? inputs : [nextCreate];
|
||||
|
||||
if (
|
||||
workInProgressHook !== null &&
|
||||
workInProgressHook.memoizedState !== null
|
||||
) {
|
||||
const prevState = workInProgressHook.memoizedState;
|
||||
const prevInputs = prevState[1];
|
||||
if (areHookInputsEqual(nextInputs, prevInputs)) {
|
||||
return prevState[0];
|
||||
}
|
||||
}
|
||||
|
||||
const nextValue = nextCreate();
|
||||
workInProgressHook.memoizedState = [nextValue, nextInputs];
|
||||
return nextValue;
|
||||
}
|
||||
|
||||
function useRef<T>(initialValue: T): {current: T} {
|
||||
currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
|
||||
workInProgressHook = createWorkInProgressHook();
|
||||
const previousRef = workInProgressHook.memoizedState;
|
||||
if (previousRef === null) {
|
||||
const ref = {current: initialValue};
|
||||
if (__DEV__) {
|
||||
Object.seal(ref);
|
||||
}
|
||||
workInProgressHook.memoizedState = ref;
|
||||
return ref;
|
||||
} else {
|
||||
return previousRef;
|
||||
}
|
||||
}
|
||||
|
||||
function useMutationEffect(
|
||||
create: () => mixed,
|
||||
inputs: Array<mixed> | void | null,
|
||||
) {
|
||||
warning(
|
||||
false,
|
||||
'useMutationEffect does nothing on the server, because its effect cannot ' +
|
||||
"be encoded into the server renderer's output format. This will lead " +
|
||||
'to a mismatch between the initial, non-hydrated UI and the intended ' +
|
||||
'UI. To avoid this, useMutationEffect should only be used in ' +
|
||||
'components that render exclusively on the client.',
|
||||
);
|
||||
}
|
||||
|
||||
export function useLayoutEffect(
|
||||
create: () => mixed,
|
||||
inputs: Array<mixed> | void | null,
|
||||
) {
|
||||
warning(
|
||||
false,
|
||||
'useLayoutEffect does nothing on the server, because its effect cannot ' +
|
||||
"be encoded into the server renderer's output format. This will lead " +
|
||||
'to a mismatch between the initial, non-hydrated UI and the intended ' +
|
||||
'UI. To avoid this, useLayoutEffect should only be used in ' +
|
||||
'components that render exclusively on the client.',
|
||||
);
|
||||
}
|
||||
|
||||
function dispatchAction<A>(
|
||||
componentIdentity: Object,
|
||||
queue: UpdateQueue<A>,
|
||||
action: A,
|
||||
) {
|
||||
invariant(
|
||||
numberOfReRenders < RE_RENDER_LIMIT,
|
||||
'Too many re-renders. React limits the number of renders to prevent ' +
|
||||
'an infinite loop.',
|
||||
);
|
||||
|
||||
if (componentIdentity === currentlyRenderingComponent) {
|
||||
// This is a render phase update. Stash it in a lazily-created map of
|
||||
// queue -> linked list of updates. After this render pass, we'll restart
|
||||
// and apply the stashed updates on top of the work-in-progress hook.
|
||||
didScheduleRenderPhaseUpdate = true;
|
||||
const update: Update<A> = {
|
||||
action,
|
||||
next: null,
|
||||
};
|
||||
if (renderPhaseUpdates === null) {
|
||||
renderPhaseUpdates = new Map();
|
||||
}
|
||||
const firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
|
||||
if (firstRenderPhaseUpdate === undefined) {
|
||||
renderPhaseUpdates.set(queue, update);
|
||||
} else {
|
||||
// Append the update to the end of the list.
|
||||
let lastRenderPhaseUpdate = firstRenderPhaseUpdate;
|
||||
while (lastRenderPhaseUpdate.next !== null) {
|
||||
lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
|
||||
}
|
||||
lastRenderPhaseUpdate.next = update;
|
||||
}
|
||||
} else {
|
||||
// This means an update has happened after the function component has
|
||||
// returned. On the server this is a no-op. In React Fiber, the update
|
||||
// would be scheduled for a future render.
|
||||
}
|
||||
}
|
||||
|
||||
function noop(): void {}
|
||||
|
||||
export let currentThreadID: ThreadID = 0;
|
||||
|
||||
export function setCurrentThreadID(threadID: ThreadID) {
|
||||
currentThreadID = threadID;
|
||||
}
|
||||
|
||||
export const Dispatcher = {
|
||||
readContext,
|
||||
useContext,
|
||||
useMemo,
|
||||
useReducer,
|
||||
useRef,
|
||||
useState,
|
||||
useMutationEffect,
|
||||
useLayoutEffect,
|
||||
// useImperativeMethods is not run in the server environment
|
||||
useImperativeMethods: noop,
|
||||
// Callbacks are not run in the server environment.
|
||||
useCallback: noop,
|
||||
// Effects are not run in the server environment.
|
||||
useEffect: noop,
|
||||
};
|
||||
export const DispatcherWithoutHooks = {
|
||||
readContext,
|
||||
};
|
||||
58
packages/react-dom/src/server/ReactThreadIDAllocator.js
vendored
Normal file
58
packages/react-dom/src/server/ReactThreadIDAllocator.js
vendored
Normal file
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
|
||||
// Allocates a new index for each request. Tries to stay as compact as possible so that these
|
||||
// indices can be used to reference a tightly packaged array. As opposed to being used in a Map.
|
||||
// The first allocated index is 1.
|
||||
|
||||
import invariant from 'shared/invariant';
|
||||
|
||||
export type ThreadID = number;
|
||||
|
||||
let nextAvailableThreadIDs = new Uint16Array(16);
|
||||
for (let i = 0; i < 15; i++) {
|
||||
nextAvailableThreadIDs[i] = i + 1;
|
||||
}
|
||||
nextAvailableThreadIDs[15] = 0;
|
||||
|
||||
function growThreadCountAndReturnNextAvailable() {
|
||||
let oldArray = nextAvailableThreadIDs;
|
||||
let oldSize = oldArray.length;
|
||||
let newSize = oldSize * 2;
|
||||
invariant(
|
||||
newSize <= 0x10000,
|
||||
'Maximum number of concurrent React renderers exceeded. ' +
|
||||
'This can happen if you are not properly destroying the Readable provided by React. ' +
|
||||
'Ensure that you call .destroy() on it if you no longer want to read from it, ' +
|
||||
'and did not read to the end. If you use .pipe() this should be automatic.',
|
||||
);
|
||||
let newArray = new Uint16Array(newSize);
|
||||
newArray.set(oldArray);
|
||||
nextAvailableThreadIDs = newArray;
|
||||
nextAvailableThreadIDs[0] = oldSize + 1;
|
||||
for (let i = oldSize; i < newSize - 1; i++) {
|
||||
nextAvailableThreadIDs[i] = i + 1;
|
||||
}
|
||||
nextAvailableThreadIDs[newSize - 1] = 0;
|
||||
return oldSize;
|
||||
}
|
||||
|
||||
export function allocThreadID(): ThreadID {
|
||||
let nextID = nextAvailableThreadIDs[0];
|
||||
if (nextID === 0) {
|
||||
return growThreadCountAndReturnNextAvailable();
|
||||
}
|
||||
nextAvailableThreadIDs[0] = nextAvailableThreadIDs[nextID];
|
||||
return nextID;
|
||||
}
|
||||
|
||||
export function freeThreadID(id: ThreadID) {
|
||||
nextAvailableThreadIDs[id] = nextAvailableThreadIDs[0];
|
||||
nextAvailableThreadIDs[0] = id;
|
||||
}
|
||||
@@ -56,7 +56,7 @@ function escapeHtml(string) {
|
||||
|
||||
let escape;
|
||||
let html = '';
|
||||
let index = 0;
|
||||
let index;
|
||||
let lastIndex = 0;
|
||||
|
||||
for (index = match.index; index < str.length; index++) {
|
||||
|
||||
@@ -11,9 +11,7 @@ import {findCurrentFiberUsingSlowPath} from 'react-reconciler/reflection';
|
||||
import * as ReactInstanceMap from 'shared/ReactInstanceMap';
|
||||
import {
|
||||
ClassComponent,
|
||||
ClassComponentLazy,
|
||||
FunctionComponent,
|
||||
FunctionComponentLazy,
|
||||
HostComponent,
|
||||
HostText,
|
||||
} from 'shared/ReactWorkTags';
|
||||
@@ -92,9 +90,7 @@ function findAllInRenderedFiberTreeInternal(fiber, test) {
|
||||
node.tag === HostComponent ||
|
||||
node.tag === HostText ||
|
||||
node.tag === ClassComponent ||
|
||||
node.tag === ClassComponentLazy ||
|
||||
node.tag === FunctionComponent ||
|
||||
node.tag === FunctionComponentLazy
|
||||
node.tag === FunctionComponent
|
||||
) {
|
||||
const publicInst = node.stateNode;
|
||||
if (test(publicInst)) {
|
||||
@@ -439,7 +435,7 @@ function makeSimulator(eventType) {
|
||||
// Normally extractEvent enqueues a state restore, but we'll just always
|
||||
// do that since we we're by-passing it here.
|
||||
enqueueStateRestore(domNode);
|
||||
runEventsInBatch(event, true);
|
||||
runEventsInBatch(event);
|
||||
});
|
||||
restoreStateIfNeeded();
|
||||
};
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "react-is",
|
||||
"version": "16.6.0-alpha.8af6728",
|
||||
"version": "16.6.1",
|
||||
"description": "Brand checking of React Elements.",
|
||||
"main": "index.js",
|
||||
"repository": "facebook/react",
|
||||
|
||||
8
packages/react-is/src/ReactIs.js
vendored
8
packages/react-is/src/ReactIs.js
vendored
@@ -10,6 +10,7 @@
|
||||
'use strict';
|
||||
|
||||
import {
|
||||
REACT_ASYNC_MODE_TYPE,
|
||||
REACT_CONCURRENT_MODE_TYPE,
|
||||
REACT_CONTEXT_TYPE,
|
||||
REACT_ELEMENT_TYPE,
|
||||
@@ -32,6 +33,7 @@ export function typeOf(object: any) {
|
||||
const type = object.type;
|
||||
|
||||
switch (type) {
|
||||
case REACT_ASYNC_MODE_TYPE:
|
||||
case REACT_CONCURRENT_MODE_TYPE:
|
||||
case REACT_FRAGMENT_TYPE:
|
||||
case REACT_PROFILER_TYPE:
|
||||
@@ -57,8 +59,8 @@ export function typeOf(object: any) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// AsyncMode alias is deprecated along with isAsyncMode
|
||||
export const AsyncMode = REACT_CONCURRENT_MODE_TYPE;
|
||||
// AsyncMode is deprecated along with isAsyncMode
|
||||
export const AsyncMode = REACT_ASYNC_MODE_TYPE;
|
||||
export const ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;
|
||||
export const ContextConsumer = REACT_CONTEXT_TYPE;
|
||||
export const ContextProvider = REACT_PROVIDER_TYPE;
|
||||
@@ -86,7 +88,7 @@ export function isAsyncMode(object: any) {
|
||||
);
|
||||
}
|
||||
}
|
||||
return isConcurrentMode(object);
|
||||
return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE;
|
||||
}
|
||||
export function isConcurrentMode(object: any) {
|
||||
return typeOf(object) === REACT_CONCURRENT_MODE_TYPE;
|
||||
|
||||
@@ -69,7 +69,7 @@ describe('ReactIs', () => {
|
||||
expect(ReactIs.isValidElementType({type: 'div', props: {}})).toEqual(false);
|
||||
});
|
||||
|
||||
it('should identify async mode', () => {
|
||||
it('should identify concurrent mode', () => {
|
||||
expect(ReactIs.typeOf(<React.unstable_ConcurrentMode />)).toBe(
|
||||
ReactIs.ConcurrentMode,
|
||||
);
|
||||
|
||||
@@ -6,9 +6,9 @@
|
||||
"dependencies": {
|
||||
"object-assign": "^4.1.1",
|
||||
"prop-types": "^15.6.2",
|
||||
"scheduler": "^0.10.0-alpha.8af6728"
|
||||
"scheduler": "^0.11.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^16.0.0 || 16.6.0-alpha.8af6728"
|
||||
"react": "^16.0.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -332,6 +332,7 @@ export const scheduleDeferredCallback =
|
||||
ReactNativeFrameScheduling.scheduleDeferredCallback;
|
||||
export const cancelDeferredCallback =
|
||||
ReactNativeFrameScheduling.cancelDeferredCallback;
|
||||
export const shouldYield = ReactNativeFrameScheduling.shouldYield;
|
||||
|
||||
export const scheduleTimeout = setTimeout;
|
||||
export const cancelTimeout = clearTimeout;
|
||||
@@ -380,7 +381,16 @@ export function cloneHiddenInstance(
|
||||
props: Props,
|
||||
internalInstanceHandle: Object,
|
||||
): Instance {
|
||||
throw new Error('Not yet implemented.');
|
||||
const viewConfig = instance.canonical.viewConfig;
|
||||
const node = instance.node;
|
||||
const updatePayload = ReactNativeAttributePayload.create(
|
||||
{style: {display: 'none'}},
|
||||
viewConfig.validAttributes,
|
||||
);
|
||||
return {
|
||||
node: cloneNodeWithNewProps(node, updatePayload),
|
||||
canonical: instance.canonical,
|
||||
};
|
||||
}
|
||||
|
||||
export function cloneUnhiddenInstance(
|
||||
@@ -389,7 +399,17 @@ export function cloneUnhiddenInstance(
|
||||
props: Props,
|
||||
internalInstanceHandle: Object,
|
||||
): Instance {
|
||||
throw new Error('Not yet implemented.');
|
||||
const viewConfig = instance.canonical.viewConfig;
|
||||
const node = instance.node;
|
||||
const updatePayload = ReactNativeAttributePayload.diff(
|
||||
{...props, style: [props.style, {display: 'none'}]},
|
||||
props,
|
||||
viewConfig.validAttributes,
|
||||
);
|
||||
return {
|
||||
node: cloneNodeWithNewProps(node, updatePayload),
|
||||
canonical: instance.canonical,
|
||||
};
|
||||
}
|
||||
|
||||
export function createHiddenTextInstance(
|
||||
|
||||
@@ -7,8 +7,6 @@
|
||||
* @flow
|
||||
*/
|
||||
|
||||
import type {Deadline} from 'react-reconciler/src/ReactFiberScheduler';
|
||||
|
||||
const hasNativePerformanceNow =
|
||||
typeof performance === 'object' && typeof performance.now === 'function';
|
||||
|
||||
@@ -16,16 +14,9 @@ const now = hasNativePerformanceNow
|
||||
? () => performance.now()
|
||||
: () => Date.now();
|
||||
|
||||
type Callback = (deadline: Deadline) => void;
|
||||
|
||||
let scheduledCallback: Callback | null = null;
|
||||
let scheduledCallback: (() => mixed) | null = null;
|
||||
let frameDeadline: number = 0;
|
||||
|
||||
const frameDeadlineObject: Deadline = {
|
||||
timeRemaining: () => frameDeadline - now(),
|
||||
didTimeout: false,
|
||||
};
|
||||
|
||||
function setTimeoutCallback() {
|
||||
// TODO (bvaughn) Hard-coded 5ms unblocks initial async testing.
|
||||
// React API probably changing to boolean rather than time remaining.
|
||||
@@ -36,7 +27,7 @@ function setTimeoutCallback() {
|
||||
const callback = scheduledCallback;
|
||||
scheduledCallback = null;
|
||||
if (callback !== null) {
|
||||
callback(frameDeadlineObject);
|
||||
callback();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,7 +35,7 @@ function setTimeoutCallback() {
|
||||
// This implementation is only intended for short-term use anyway.
|
||||
// We also don't implement cancel functionality b'c Fiber doesn't currently need it.
|
||||
function scheduleDeferredCallback(
|
||||
callback: Callback,
|
||||
callback: () => mixed,
|
||||
options?: {timeout: number},
|
||||
): number {
|
||||
// We assume only one callback is scheduled at a time b'c that's how Fiber works.
|
||||
@@ -58,4 +49,8 @@ function cancelDeferredCallback(callbackID: number) {
|
||||
clearTimeout((callbackID: any)); // Timeouts are always numbers on RN
|
||||
}
|
||||
|
||||
export {now, scheduleDeferredCallback, cancelDeferredCallback};
|
||||
function shouldYield() {
|
||||
return frameDeadline <= now();
|
||||
}
|
||||
|
||||
export {now, scheduleDeferredCallback, cancelDeferredCallback, shouldYield};
|
||||
|
||||
@@ -238,6 +238,7 @@ export const scheduleDeferredCallback =
|
||||
ReactNativeFrameScheduling.scheduleDeferredCallback;
|
||||
export const cancelDeferredCallback =
|
||||
ReactNativeFrameScheduling.cancelDeferredCallback;
|
||||
export const shouldYield = ReactNativeFrameScheduling.shouldYield;
|
||||
|
||||
export const scheduleTimeout = setTimeout;
|
||||
export const cancelTimeout = clearTimeout;
|
||||
@@ -453,7 +454,16 @@ export function resetTextContent(instance: Instance): void {
|
||||
}
|
||||
|
||||
export function hideInstance(instance: Instance): void {
|
||||
throw new Error('Not yet implemented.');
|
||||
const viewConfig = instance.viewConfig;
|
||||
const updatePayload = ReactNativeAttributePayload.create(
|
||||
{style: {display: 'none'}},
|
||||
viewConfig.validAttributes,
|
||||
);
|
||||
UIManager.updateView(
|
||||
instance._nativeTag,
|
||||
viewConfig.uiViewClassName,
|
||||
updatePayload,
|
||||
);
|
||||
}
|
||||
|
||||
export function hideTextInstance(textInstance: TextInstance): void {
|
||||
@@ -461,7 +471,17 @@ export function hideTextInstance(textInstance: TextInstance): void {
|
||||
}
|
||||
|
||||
export function unhideInstance(instance: Instance, props: Props): void {
|
||||
throw new Error('Not yet implemented.');
|
||||
const viewConfig = instance.viewConfig;
|
||||
const updatePayload = ReactNativeAttributePayload.diff(
|
||||
{...props, style: [props.style, {display: 'none'}]},
|
||||
props,
|
||||
viewConfig.validAttributes,
|
||||
);
|
||||
UIManager.updateView(
|
||||
instance._nativeTag,
|
||||
viewConfig.uiViewClassName,
|
||||
updatePayload,
|
||||
);
|
||||
}
|
||||
|
||||
export function unhideTextInstance(
|
||||
|
||||
@@ -10,10 +10,10 @@
|
||||
"object-assign": "^4.1.1",
|
||||
"prop-types": "^15.6.2",
|
||||
"regenerator-runtime": "^0.11.0",
|
||||
"react-reconciler": "* || 0.16.0-alpha.8af6728"
|
||||
"react-reconciler": "*"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^16.0.0 || 16.6.0-alpha.8af6728"
|
||||
"react": "^16.0.0"
|
||||
},
|
||||
"files": [
|
||||
"LICENSE",
|
||||
|
||||
@@ -319,7 +319,7 @@ function createReactNoop(reconciler: Function, useMutation: boolean) {
|
||||
scheduledCallbackTimeout === -1 ||
|
||||
scheduledCallbackTimeout > newTimeout
|
||||
) {
|
||||
scheduledCallbackTimeout = newTimeout;
|
||||
scheduledCallbackTimeout = elapsedTimeInMs + newTimeout;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
@@ -333,6 +333,8 @@ function createReactNoop(reconciler: Function, useMutation: boolean) {
|
||||
scheduledCallbackTimeout = -1;
|
||||
},
|
||||
|
||||
shouldYield,
|
||||
|
||||
scheduleTimeout: setTimeout,
|
||||
cancelTimeout: clearTimeout,
|
||||
noTimeout: -1,
|
||||
@@ -512,35 +514,44 @@ function createReactNoop(reconciler: Function, useMutation: boolean) {
|
||||
|
||||
let yieldedValues = null;
|
||||
|
||||
let didYield;
|
||||
let unitsRemaining;
|
||||
|
||||
function* flushUnitsOfWork(n: number): Generator<Array<mixed>, void, void> {
|
||||
let didStop = false;
|
||||
while (!didStop && scheduledCallback !== null) {
|
||||
let cb = scheduledCallback;
|
||||
scheduledCallback = null;
|
||||
unitsRemaining = n;
|
||||
cb({
|
||||
timeRemaining() {
|
||||
if (yieldedValues !== null) {
|
||||
return 0;
|
||||
}
|
||||
if (unitsRemaining-- > 0) {
|
||||
return 999;
|
||||
}
|
||||
didStop = true;
|
||||
return 0;
|
||||
},
|
||||
didTimeout:
|
||||
scheduledCallbackTimeout !== -1 &&
|
||||
elapsedTimeInMs > scheduledCallbackTimeout,
|
||||
});
|
||||
|
||||
if (yieldedValues !== null) {
|
||||
const values = yieldedValues;
|
||||
yieldedValues = null;
|
||||
yield values;
|
||||
function shouldYield() {
|
||||
if (
|
||||
scheduledCallbackTimeout === -1 ||
|
||||
elapsedTimeInMs > scheduledCallbackTimeout
|
||||
) {
|
||||
return false;
|
||||
} else {
|
||||
if (didYield || yieldedValues !== null) {
|
||||
return true;
|
||||
}
|
||||
if (unitsRemaining-- > 0) {
|
||||
return false;
|
||||
}
|
||||
didYield = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
function* flushUnitsOfWork(n: number): Generator<Array<mixed>, void, void> {
|
||||
unitsRemaining = n + 1;
|
||||
didYield = false;
|
||||
try {
|
||||
while (!didYield && scheduledCallback !== null) {
|
||||
let cb = scheduledCallback;
|
||||
scheduledCallback = null;
|
||||
cb();
|
||||
if (yieldedValues !== null) {
|
||||
const values = yieldedValues;
|
||||
yieldedValues = null;
|
||||
yield values;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
unitsRemaining = -1;
|
||||
didYield = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -945,9 +956,10 @@ function createReactNoop(reconciler: Function, useMutation: boolean) {
|
||||
rootID: string = DEFAULT_ROOT_ID,
|
||||
) {
|
||||
const root: any = roots.get(rootID);
|
||||
const expiration = NoopRenderer.computeUniqueAsyncExpiration();
|
||||
const batch = {
|
||||
_defer: true,
|
||||
_expirationTime: 1,
|
||||
_expirationTime: expiration,
|
||||
_onComplete: () => {
|
||||
root.firstBatch = null;
|
||||
},
|
||||
@@ -958,7 +970,7 @@ function createReactNoop(reconciler: Function, useMutation: boolean) {
|
||||
expect(actual).toEqual(expectedFlush);
|
||||
return (expectedCommit: Array<mixed>) => {
|
||||
batch._defer = false;
|
||||
NoopRenderer.flushRoot(root, 1);
|
||||
NoopRenderer.flushRoot(root, expiration);
|
||||
expect(yieldedValues).toEqual(expectedCommit);
|
||||
};
|
||||
},
|
||||
|
||||
@@ -9,16 +9,16 @@ This is an experimental package for creating custom React renderers.
|
||||
## API
|
||||
|
||||
```js
|
||||
var Reconciler = require('react-reconciler');
|
||||
const Reconciler = require('react-reconciler');
|
||||
|
||||
var HostConfig = {
|
||||
const HostConfig = {
|
||||
// You'll need to implement some methods here.
|
||||
// See below for more information and examples.
|
||||
};
|
||||
|
||||
var MyRenderer = Reconciler(HostConfig);
|
||||
const MyRenderer = Reconciler(HostConfig);
|
||||
|
||||
var RendererPublicAPI = {
|
||||
const RendererPublicAPI = {
|
||||
render(element, container, callback) {
|
||||
// Call MyRenderer.updateContainer() to schedule changes on the roots.
|
||||
// See ReactDOM, React Native, or React ART for practical examples.
|
||||
@@ -33,7 +33,7 @@ module.exports = RendererPublicAPI;
|
||||
A "host config" is an object that you need to provide, and that describes how to make something happen in the "host" environment (e.g. DOM, canvas, console, or whatever your rendering target is). It looks like this:
|
||||
|
||||
```js
|
||||
var HostConfig = {
|
||||
const HostConfig = {
|
||||
createInstance(type, props) {
|
||||
// e.g. DOM renderer returns a DOM node
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "react-reconciler",
|
||||
"description": "React package for creating custom renderers.",
|
||||
"version": "0.16.0-alpha.8af6728",
|
||||
"version": "0.17.0",
|
||||
"keywords": [
|
||||
"react"
|
||||
],
|
||||
@@ -22,13 +22,13 @@
|
||||
"node": ">=0.10.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^16.0.0 || 16.6.0-alpha.8af6728"
|
||||
"react": "^16.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.1.0",
|
||||
"object-assign": "^4.1.1",
|
||||
"prop-types": "^15.6.2",
|
||||
"scheduler": "^0.10.0-alpha.8af6728"
|
||||
"scheduler": "^0.11.0"
|
||||
},
|
||||
"browserify": {
|
||||
"transform": [
|
||||
|
||||
15
packages/react-reconciler/src/ReactChildFiber.js
vendored
15
packages/react-reconciler/src/ReactChildFiber.js
vendored
@@ -9,8 +9,8 @@
|
||||
|
||||
import type {ReactElement} from 'shared/ReactElementType';
|
||||
import type {ReactPortal} from 'shared/ReactTypes';
|
||||
import type {Fiber} from 'react-reconciler/src/ReactFiber';
|
||||
import type {ExpirationTime} from 'react-reconciler/src/ReactFiberExpirationTime';
|
||||
import type {Fiber} from './ReactFiber';
|
||||
import type {ExpirationTime} from './ReactFiberExpirationTime';
|
||||
|
||||
import getComponentName from 'shared/getComponentName';
|
||||
import {Placement, Deletion} from 'shared/ReactSideEffectTags';
|
||||
@@ -23,7 +23,6 @@ import {
|
||||
import {
|
||||
FunctionComponent,
|
||||
ClassComponent,
|
||||
ClassComponentLazy,
|
||||
HostText,
|
||||
HostPortal,
|
||||
Fragment,
|
||||
@@ -138,8 +137,7 @@ function coerceRef(
|
||||
if (owner) {
|
||||
const ownerFiber = ((owner: any): Fiber);
|
||||
invariant(
|
||||
ownerFiber.tag === ClassComponent ||
|
||||
ownerFiber.tag === ClassComponentLazy,
|
||||
ownerFiber.tag === ClassComponent,
|
||||
'Function components cannot have refs.',
|
||||
);
|
||||
inst = ownerFiber.stateNode;
|
||||
@@ -379,7 +377,7 @@ function ChildReconciler(shouldTrackSideEffects) {
|
||||
element: ReactElement,
|
||||
expirationTime: ExpirationTime,
|
||||
): Fiber {
|
||||
if (current !== null && current.type === element.type) {
|
||||
if (current !== null && current.elementType === element.type) {
|
||||
// Move based on index
|
||||
const existing = useFiber(current, element.props, expirationTime);
|
||||
existing.ref = coerceRef(returnFiber, current, element);
|
||||
@@ -1122,7 +1120,7 @@ function ChildReconciler(shouldTrackSideEffects) {
|
||||
if (
|
||||
child.tag === Fragment
|
||||
? element.type === REACT_FRAGMENT_TYPE
|
||||
: child.type === element.type
|
||||
: child.elementType === element.type
|
||||
) {
|
||||
deleteRemainingChildren(returnFiber, child.sibling);
|
||||
const existing = useFiber(
|
||||
@@ -1309,8 +1307,7 @@ function ChildReconciler(shouldTrackSideEffects) {
|
||||
// component, throw an error. If Fiber return types are disabled,
|
||||
// we already threw above.
|
||||
switch (returnFiber.tag) {
|
||||
case ClassComponent:
|
||||
case ClassComponentLazy: {
|
||||
case ClassComponent: {
|
||||
if (__DEV__) {
|
||||
const instance = returnFiber.stateNode;
|
||||
if (instance.render._isMockFunction) {
|
||||
|
||||
@@ -7,34 +7,34 @@
|
||||
* @flow
|
||||
*/
|
||||
|
||||
import type {Fiber} from './ReactFiber';
|
||||
|
||||
import ReactSharedInternals from 'shared/ReactSharedInternals';
|
||||
import {
|
||||
IndeterminateComponent,
|
||||
FunctionComponent,
|
||||
FunctionComponentLazy,
|
||||
ClassComponent,
|
||||
ClassComponentLazy,
|
||||
HostComponent,
|
||||
Mode,
|
||||
LazyComponent,
|
||||
SuspenseComponent,
|
||||
} from 'shared/ReactWorkTags';
|
||||
import describeComponentFrame from 'shared/describeComponentFrame';
|
||||
import getComponentName from 'shared/getComponentName';
|
||||
|
||||
const ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
|
||||
|
||||
import type {Fiber} from './ReactFiber';
|
||||
|
||||
type LifeCyclePhase = 'render' | 'getChildContext';
|
||||
|
||||
function describeFiber(fiber: Fiber): string {
|
||||
switch (fiber.tag) {
|
||||
case IndeterminateComponent:
|
||||
case LazyComponent:
|
||||
case FunctionComponent:
|
||||
case FunctionComponentLazy:
|
||||
case ClassComponent:
|
||||
case ClassComponentLazy:
|
||||
case HostComponent:
|
||||
case Mode:
|
||||
case SuspenseComponent:
|
||||
const owner = fiber._debugOwner;
|
||||
const source = fiber._debugSource;
|
||||
const name = getComponentName(fiber.type);
|
||||
|
||||
163
packages/react-reconciler/src/ReactFiber.js
vendored
163
packages/react-reconciler/src/ReactFiber.js
vendored
@@ -34,11 +34,9 @@ import {
|
||||
ContextConsumer,
|
||||
Profiler,
|
||||
SuspenseComponent,
|
||||
FunctionComponentLazy,
|
||||
ClassComponentLazy,
|
||||
ForwardRefLazy,
|
||||
PureComponent,
|
||||
PureComponentLazy,
|
||||
FunctionComponent,
|
||||
MemoComponent,
|
||||
LazyComponent,
|
||||
} from 'shared/ReactWorkTags';
|
||||
import getComponentName from 'shared/getComponentName';
|
||||
|
||||
@@ -59,7 +57,7 @@ import {
|
||||
REACT_CONTEXT_TYPE,
|
||||
REACT_CONCURRENT_MODE_TYPE,
|
||||
REACT_SUSPENSE_TYPE,
|
||||
REACT_PURE_TYPE,
|
||||
REACT_MEMO_TYPE,
|
||||
REACT_LAZY_TYPE,
|
||||
} from 'shared/ReactSymbols';
|
||||
|
||||
@@ -101,7 +99,11 @@ export type Fiber = {|
|
||||
// Unique identifier of this child.
|
||||
key: null | string,
|
||||
|
||||
// The function/class/module associated with this fiber.
|
||||
// The value of element.type which is used to preserve the identity during
|
||||
// reconciliation of this child.
|
||||
elementType: any,
|
||||
|
||||
// The resolved function/class/ associated with this fiber.
|
||||
type: any,
|
||||
|
||||
// The local state associated with this fiber.
|
||||
@@ -219,6 +221,7 @@ function FiberNode(
|
||||
// Instance
|
||||
this.tag = tag;
|
||||
this.key = key;
|
||||
this.elementType = null;
|
||||
this.type = null;
|
||||
this.stateNode = null;
|
||||
|
||||
@@ -296,21 +299,24 @@ function shouldConstruct(Component: Function) {
|
||||
return !!(prototype && prototype.isReactComponent);
|
||||
}
|
||||
|
||||
export function resolveLazyComponentTag(
|
||||
fiber: Fiber,
|
||||
Component: Function,
|
||||
): WorkTag {
|
||||
export function isSimpleFunctionComponent(type: any) {
|
||||
return (
|
||||
typeof type === 'function' &&
|
||||
!shouldConstruct(type) &&
|
||||
type.defaultProps === undefined
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveLazyComponentTag(Component: Function): WorkTag {
|
||||
if (typeof Component === 'function') {
|
||||
return shouldConstruct(Component)
|
||||
? ClassComponentLazy
|
||||
: FunctionComponentLazy;
|
||||
return shouldConstruct(Component) ? ClassComponent : FunctionComponent;
|
||||
} else if (Component !== undefined && Component !== null) {
|
||||
const $$typeof = Component.$$typeof;
|
||||
if ($$typeof === REACT_FORWARD_REF_TYPE) {
|
||||
return ForwardRefLazy;
|
||||
return ForwardRef;
|
||||
}
|
||||
if ($$typeof === REACT_PURE_TYPE) {
|
||||
return PureComponentLazy;
|
||||
if ($$typeof === REACT_MEMO_TYPE) {
|
||||
return MemoComponent;
|
||||
}
|
||||
}
|
||||
return IndeterminateComponent;
|
||||
@@ -335,6 +341,7 @@ export function createWorkInProgress(
|
||||
current.key,
|
||||
current.mode,
|
||||
);
|
||||
workInProgress.elementType = current.elementType;
|
||||
workInProgress.type = current.type;
|
||||
workInProgress.stateNode = current.stateNode;
|
||||
|
||||
@@ -404,24 +411,23 @@ export function createHostRootFiber(isConcurrent: boolean): Fiber {
|
||||
return createFiber(HostRoot, null, null, mode);
|
||||
}
|
||||
|
||||
export function createFiberFromElement(
|
||||
element: ReactElement,
|
||||
export function createFiberFromTypeAndProps(
|
||||
type: any, // React$ElementType
|
||||
key: null | string,
|
||||
pendingProps: any,
|
||||
owner: null | Fiber,
|
||||
mode: TypeOfMode,
|
||||
expirationTime: ExpirationTime,
|
||||
): Fiber {
|
||||
let owner = null;
|
||||
if (__DEV__) {
|
||||
owner = element._owner;
|
||||
}
|
||||
|
||||
let fiber;
|
||||
const type = element.type;
|
||||
const key = element.key;
|
||||
const pendingProps = element.props;
|
||||
|
||||
let fiberTag;
|
||||
let fiberTag = IndeterminateComponent;
|
||||
// The resolved type is set if we know what the final type will be. I.e. it's not lazy.
|
||||
let resolvedType = type;
|
||||
if (typeof type === 'function') {
|
||||
fiberTag = shouldConstruct(type) ? ClassComponent : IndeterminateComponent;
|
||||
if (shouldConstruct(type)) {
|
||||
fiberTag = ClassComponent;
|
||||
}
|
||||
} else if (typeof type === 'string') {
|
||||
fiberTag = HostComponent;
|
||||
} else {
|
||||
@@ -434,18 +440,23 @@ export function createFiberFromElement(
|
||||
key,
|
||||
);
|
||||
case REACT_CONCURRENT_MODE_TYPE:
|
||||
fiberTag = Mode;
|
||||
mode |= ConcurrentMode | StrictMode;
|
||||
break;
|
||||
return createFiberFromMode(
|
||||
pendingProps,
|
||||
mode | ConcurrentMode | StrictMode,
|
||||
expirationTime,
|
||||
key,
|
||||
);
|
||||
case REACT_STRICT_MODE_TYPE:
|
||||
fiberTag = Mode;
|
||||
mode |= StrictMode;
|
||||
break;
|
||||
return createFiberFromMode(
|
||||
pendingProps,
|
||||
mode | StrictMode,
|
||||
expirationTime,
|
||||
key,
|
||||
);
|
||||
case REACT_PROFILER_TYPE:
|
||||
return createFiberFromProfiler(pendingProps, mode, expirationTime, key);
|
||||
case REACT_SUSPENSE_TYPE:
|
||||
fiberTag = SuspenseComponent;
|
||||
break;
|
||||
return createFiberFromSuspense(pendingProps, mode, expirationTime, key);
|
||||
default: {
|
||||
if (typeof type === 'object' && type !== null) {
|
||||
switch (type.$$typeof) {
|
||||
@@ -459,11 +470,12 @@ export function createFiberFromElement(
|
||||
case REACT_FORWARD_REF_TYPE:
|
||||
fiberTag = ForwardRef;
|
||||
break getTag;
|
||||
case REACT_PURE_TYPE:
|
||||
fiberTag = PureComponent;
|
||||
case REACT_MEMO_TYPE:
|
||||
fiberTag = MemoComponent;
|
||||
break getTag;
|
||||
case REACT_LAZY_TYPE:
|
||||
fiberTag = IndeterminateComponent;
|
||||
fiberTag = LazyComponent;
|
||||
resolvedType = null;
|
||||
break getTag;
|
||||
}
|
||||
}
|
||||
@@ -498,14 +510,37 @@ export function createFiberFromElement(
|
||||
}
|
||||
|
||||
fiber = createFiber(fiberTag, pendingProps, key, mode);
|
||||
fiber.type = type;
|
||||
fiber.elementType = type;
|
||||
fiber.type = resolvedType;
|
||||
fiber.expirationTime = expirationTime;
|
||||
|
||||
return fiber;
|
||||
}
|
||||
|
||||
export function createFiberFromElement(
|
||||
element: ReactElement,
|
||||
mode: TypeOfMode,
|
||||
expirationTime: ExpirationTime,
|
||||
): Fiber {
|
||||
let owner = null;
|
||||
if (__DEV__) {
|
||||
owner = element._owner;
|
||||
}
|
||||
const type = element.type;
|
||||
const key = element.key;
|
||||
const pendingProps = element.props;
|
||||
const fiber = createFiberFromTypeAndProps(
|
||||
type,
|
||||
key,
|
||||
pendingProps,
|
||||
owner,
|
||||
mode,
|
||||
expirationTime,
|
||||
);
|
||||
if (__DEV__) {
|
||||
fiber._debugSource = element._source;
|
||||
fiber._debugOwner = element._owner;
|
||||
}
|
||||
|
||||
return fiber;
|
||||
}
|
||||
|
||||
@@ -520,7 +555,7 @@ export function createFiberFromFragment(
|
||||
return fiber;
|
||||
}
|
||||
|
||||
export function createFiberFromProfiler(
|
||||
function createFiberFromProfiler(
|
||||
pendingProps: any,
|
||||
mode: TypeOfMode,
|
||||
expirationTime: ExpirationTime,
|
||||
@@ -539,12 +574,51 @@ export function createFiberFromProfiler(
|
||||
}
|
||||
|
||||
const fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode);
|
||||
// TODO: The Profiler fiber shouldn't have a type. It has a tag.
|
||||
fiber.elementType = REACT_PROFILER_TYPE;
|
||||
fiber.type = REACT_PROFILER_TYPE;
|
||||
fiber.expirationTime = expirationTime;
|
||||
|
||||
return fiber;
|
||||
}
|
||||
|
||||
function createFiberFromMode(
|
||||
pendingProps: any,
|
||||
mode: TypeOfMode,
|
||||
expirationTime: ExpirationTime,
|
||||
key: null | string,
|
||||
): Fiber {
|
||||
const fiber = createFiber(Mode, pendingProps, key, mode);
|
||||
|
||||
// TODO: The Mode fiber shouldn't have a type. It has a tag.
|
||||
const type =
|
||||
(mode & ConcurrentMode) === NoContext
|
||||
? REACT_STRICT_MODE_TYPE
|
||||
: REACT_CONCURRENT_MODE_TYPE;
|
||||
fiber.elementType = type;
|
||||
fiber.type = type;
|
||||
|
||||
fiber.expirationTime = expirationTime;
|
||||
return fiber;
|
||||
}
|
||||
|
||||
export function createFiberFromSuspense(
|
||||
pendingProps: any,
|
||||
mode: TypeOfMode,
|
||||
expirationTime: ExpirationTime,
|
||||
key: null | string,
|
||||
) {
|
||||
const fiber = createFiber(SuspenseComponent, pendingProps, key, mode);
|
||||
|
||||
// TODO: The SuspenseComponent fiber shouldn't have a type. It has a tag.
|
||||
const type = REACT_SUSPENSE_TYPE;
|
||||
fiber.elementType = type;
|
||||
fiber.type = type;
|
||||
|
||||
fiber.expirationTime = expirationTime;
|
||||
return fiber;
|
||||
}
|
||||
|
||||
export function createFiberFromText(
|
||||
content: string,
|
||||
mode: TypeOfMode,
|
||||
@@ -557,6 +631,8 @@ export function createFiberFromText(
|
||||
|
||||
export function createFiberFromHostInstanceForDeletion(): Fiber {
|
||||
const fiber = createFiber(HostComponent, null, null, NoContext);
|
||||
// TODO: These should not need a type.
|
||||
fiber.elementType = 'DELETED';
|
||||
fiber.type = 'DELETED';
|
||||
return fiber;
|
||||
}
|
||||
@@ -596,6 +672,7 @@ export function assignFiberPropertiesInDEV(
|
||||
|
||||
target.tag = source.tag;
|
||||
target.key = source.key;
|
||||
target.elementType = source.elementType;
|
||||
target.type = source.type;
|
||||
target.stateNode = source.stateNode;
|
||||
target.return = source.return;
|
||||
|
||||
752
packages/react-reconciler/src/ReactFiberBeginWork.js
vendored
752
packages/react-reconciler/src/ReactFiberBeginWork.js
vendored
File diff suppressed because it is too large
Load Diff
@@ -28,6 +28,7 @@ import warningWithoutStack from 'shared/warningWithoutStack';
|
||||
import {REACT_CONTEXT_TYPE} from 'shared/ReactSymbols';
|
||||
|
||||
import {startPhaseTimer, stopPhaseTimer} from './ReactDebugFiberPerf';
|
||||
import {resolveDefaultProps} from './ReactFiberLazyComponent';
|
||||
import {StrictMode} from './ReactTypeOfMode';
|
||||
|
||||
import {
|
||||
@@ -51,6 +52,7 @@ import {
|
||||
requestCurrentTime,
|
||||
computeExpirationForFiber,
|
||||
scheduleWork,
|
||||
flushPassiveEffects,
|
||||
} from './ReactFiberScheduler';
|
||||
|
||||
const ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
|
||||
@@ -199,6 +201,7 @@ const classComponentUpdater = {
|
||||
update.callback = callback;
|
||||
}
|
||||
|
||||
flushPassiveEffects();
|
||||
enqueueUpdate(fiber, update);
|
||||
scheduleWork(fiber, expirationTime);
|
||||
},
|
||||
@@ -218,6 +221,7 @@ const classComponentUpdater = {
|
||||
update.callback = callback;
|
||||
}
|
||||
|
||||
flushPassiveEffects();
|
||||
enqueueUpdate(fiber, update);
|
||||
scheduleWork(fiber, expirationTime);
|
||||
},
|
||||
@@ -236,6 +240,7 @@ const classComponentUpdater = {
|
||||
update.callback = callback;
|
||||
}
|
||||
|
||||
flushPassiveEffects();
|
||||
enqueueUpdate(fiber, update);
|
||||
scheduleWork(fiber, expirationTime);
|
||||
},
|
||||
@@ -983,7 +988,10 @@ function updateClassInstance(
|
||||
const instance = workInProgress.stateNode;
|
||||
|
||||
const oldProps = workInProgress.memoizedProps;
|
||||
instance.props = oldProps;
|
||||
instance.props =
|
||||
workInProgress.type === workInProgress.elementType
|
||||
? oldProps
|
||||
: resolveDefaultProps(workInProgress.type, oldProps);
|
||||
|
||||
const oldContext = instance.context;
|
||||
const contextType = ctor.contextType;
|
||||
|
||||
@@ -19,20 +19,26 @@ import type {FiberRoot} from './ReactFiberRoot';
|
||||
import type {ExpirationTime} from './ReactFiberExpirationTime';
|
||||
import type {CapturedValue, CapturedError} from './ReactCapturedValue';
|
||||
import type {SuspenseState} from './ReactFiberSuspenseComponent';
|
||||
import type {FunctionComponentUpdateQueue} from './ReactFiberHooks';
|
||||
|
||||
import {
|
||||
enableHooks,
|
||||
enableSchedulerTracing,
|
||||
enableProfilerTimer,
|
||||
} from 'shared/ReactFeatureFlags';
|
||||
import {
|
||||
FunctionComponent,
|
||||
ForwardRef,
|
||||
ClassComponent,
|
||||
ClassComponentLazy,
|
||||
HostRoot,
|
||||
HostComponent,
|
||||
HostText,
|
||||
HostPortal,
|
||||
Profiler,
|
||||
SuspenseComponent,
|
||||
IncompleteClassComponent,
|
||||
MemoComponent,
|
||||
SimpleMemoComponent,
|
||||
} from 'shared/ReactWorkTags';
|
||||
import {
|
||||
invokeGuardedCallback,
|
||||
@@ -44,17 +50,18 @@ import {
|
||||
Placement,
|
||||
Snapshot,
|
||||
Update,
|
||||
Callback,
|
||||
} from 'shared/ReactSideEffectTags';
|
||||
import getComponentName from 'shared/getComponentName';
|
||||
import invariant from 'shared/invariant';
|
||||
import warningWithoutStack from 'shared/warningWithoutStack';
|
||||
import warning from 'shared/warning';
|
||||
|
||||
import {NoWork, Sync} from './ReactFiberExpirationTime';
|
||||
import {NoWork} from './ReactFiberExpirationTime';
|
||||
import {onCommitUnmount} from './ReactFiberDevToolsHook';
|
||||
import {startPhaseTimer, stopPhaseTimer} from './ReactDebugFiberPerf';
|
||||
import {getStackByFiberInDevAndProd} from './ReactCurrentFiber';
|
||||
import {logCapturedError} from './ReactFiberErrorLogger';
|
||||
import {resolveDefaultProps} from './ReactFiberLazyComponent';
|
||||
import {getCommitTime} from './ReactProfilerTimer';
|
||||
import {commitUpdateQueue} from './ReactUpdateQueue';
|
||||
import {
|
||||
@@ -81,8 +88,17 @@ import {
|
||||
import {
|
||||
captureCommitPhaseError,
|
||||
requestCurrentTime,
|
||||
scheduleWork,
|
||||
} from './ReactFiberScheduler';
|
||||
import {
|
||||
NoEffect as NoHookEffect,
|
||||
UnmountSnapshot,
|
||||
UnmountMutation,
|
||||
MountMutation,
|
||||
UnmountLayout,
|
||||
MountLayout,
|
||||
UnmountPassive,
|
||||
MountPassive,
|
||||
} from './ReactHookEffectTags';
|
||||
|
||||
let didWarnAboutUndefinedSnapshotBeforeUpdate: Set<mixed> | null = null;
|
||||
if (__DEV__) {
|
||||
@@ -180,23 +196,63 @@ function safelyDetachRef(current: Fiber) {
|
||||
}
|
||||
}
|
||||
|
||||
function safelyCallDestroy(current, destroy) {
|
||||
if (__DEV__) {
|
||||
invokeGuardedCallback(null, destroy, null);
|
||||
if (hasCaughtError()) {
|
||||
const error = clearCaughtError();
|
||||
captureCommitPhaseError(current, error);
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
destroy();
|
||||
} catch (error) {
|
||||
captureCommitPhaseError(current, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function commitBeforeMutationLifeCycles(
|
||||
current: Fiber | null,
|
||||
finishedWork: Fiber,
|
||||
): void {
|
||||
switch (finishedWork.tag) {
|
||||
case ClassComponent:
|
||||
case ClassComponentLazy: {
|
||||
case FunctionComponent:
|
||||
case ForwardRef:
|
||||
case SimpleMemoComponent: {
|
||||
commitHookEffectList(UnmountSnapshot, NoHookEffect, finishedWork);
|
||||
return;
|
||||
}
|
||||
case ClassComponent: {
|
||||
if (finishedWork.effectTag & Snapshot) {
|
||||
if (current !== null) {
|
||||
const prevProps = current.memoizedProps;
|
||||
const prevState = current.memoizedState;
|
||||
startPhaseTimer(finishedWork, 'getSnapshotBeforeUpdate');
|
||||
const instance = finishedWork.stateNode;
|
||||
instance.props = finishedWork.memoizedProps;
|
||||
instance.state = finishedWork.memoizedState;
|
||||
// We could update instance props and state here,
|
||||
// but instead we rely on them being set during last render.
|
||||
// TODO: revisit this when we implement resuming.
|
||||
if (__DEV__) {
|
||||
if (finishedWork.type === finishedWork.elementType) {
|
||||
warning(
|
||||
instance.props === finishedWork.memoizedProps,
|
||||
'Expected instance props to match memoized props before ' +
|
||||
'getSnapshotBeforeUpdate. This is likely due to a bug in React. ' +
|
||||
'Please file an issue.',
|
||||
);
|
||||
warning(
|
||||
instance.state === finishedWork.memoizedState,
|
||||
'Expected instance state to match memoized state before ' +
|
||||
'getSnapshotBeforeUpdate. This is likely due to a bug in React. ' +
|
||||
'Please file an issue.',
|
||||
);
|
||||
}
|
||||
}
|
||||
const snapshot = instance.getSnapshotBeforeUpdate(
|
||||
prevProps,
|
||||
finishedWork.elementType === finishedWork.type
|
||||
? prevProps
|
||||
: resolveDefaultProps(finishedWork.type, prevProps),
|
||||
prevState,
|
||||
);
|
||||
if (__DEV__) {
|
||||
@@ -223,6 +279,7 @@ function commitBeforeMutationLifeCycles(
|
||||
case HostComponent:
|
||||
case HostText:
|
||||
case HostPortal:
|
||||
case IncompleteClassComponent:
|
||||
// Nothing to do for these component types
|
||||
return;
|
||||
default: {
|
||||
@@ -235,6 +292,62 @@ function commitBeforeMutationLifeCycles(
|
||||
}
|
||||
}
|
||||
|
||||
function commitHookEffectList(
|
||||
unmountTag: number,
|
||||
mountTag: number,
|
||||
finishedWork: Fiber,
|
||||
) {
|
||||
if (!enableHooks) {
|
||||
return;
|
||||
}
|
||||
const updateQueue: FunctionComponentUpdateQueue | null = (finishedWork.updateQueue: any);
|
||||
let lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
|
||||
if (lastEffect !== null) {
|
||||
const firstEffect = lastEffect.next;
|
||||
let effect = firstEffect;
|
||||
do {
|
||||
if ((effect.tag & unmountTag) !== NoHookEffect) {
|
||||
// Unmount
|
||||
const destroy = effect.destroy;
|
||||
effect.destroy = null;
|
||||
if (destroy !== null) {
|
||||
destroy();
|
||||
}
|
||||
}
|
||||
if ((effect.tag & mountTag) !== NoHookEffect) {
|
||||
// Mount
|
||||
const create = effect.create;
|
||||
let destroy = create();
|
||||
if (typeof destroy !== 'function') {
|
||||
if (__DEV__) {
|
||||
if (destroy !== null && destroy !== undefined) {
|
||||
warningWithoutStack(
|
||||
false,
|
||||
'useEffect function must return a cleanup function or ' +
|
||||
'nothing.%s%s',
|
||||
typeof destroy.then === 'function'
|
||||
? ' Promises and useEffect(async () => ...) are not ' +
|
||||
'supported, but you can call an async function inside an ' +
|
||||
'effect.'
|
||||
: '',
|
||||
getStackByFiberInDevAndProd(finishedWork),
|
||||
);
|
||||
}
|
||||
}
|
||||
destroy = null;
|
||||
}
|
||||
effect.destroy = destroy;
|
||||
}
|
||||
effect = effect.next;
|
||||
} while (effect !== firstEffect);
|
||||
}
|
||||
}
|
||||
|
||||
export function commitPassiveHookEffects(finishedWork: Fiber): void {
|
||||
commitHookEffectList(UnmountPassive, NoHookEffect, finishedWork);
|
||||
commitHookEffectList(NoHookEffect, MountPassive, finishedWork);
|
||||
}
|
||||
|
||||
function commitLifeCycles(
|
||||
finishedRoot: FiberRoot,
|
||||
current: Fiber | null,
|
||||
@@ -242,22 +355,64 @@ function commitLifeCycles(
|
||||
committedExpirationTime: ExpirationTime,
|
||||
): void {
|
||||
switch (finishedWork.tag) {
|
||||
case ClassComponent:
|
||||
case ClassComponentLazy: {
|
||||
case FunctionComponent:
|
||||
case ForwardRef:
|
||||
case SimpleMemoComponent: {
|
||||
commitHookEffectList(UnmountLayout, MountLayout, finishedWork);
|
||||
break;
|
||||
}
|
||||
case ClassComponent: {
|
||||
const instance = finishedWork.stateNode;
|
||||
if (finishedWork.effectTag & Update) {
|
||||
if (current === null) {
|
||||
startPhaseTimer(finishedWork, 'componentDidMount');
|
||||
instance.props = finishedWork.memoizedProps;
|
||||
instance.state = finishedWork.memoizedState;
|
||||
// We could update instance props and state here,
|
||||
// but instead we rely on them being set during last render.
|
||||
// TODO: revisit this when we implement resuming.
|
||||
if (__DEV__) {
|
||||
if (finishedWork.type === finishedWork.elementType) {
|
||||
warning(
|
||||
instance.props === finishedWork.memoizedProps,
|
||||
'Expected instance props to match memoized props before ' +
|
||||
'componentDidMount. This is likely due to a bug in React. ' +
|
||||
'Please file an issue.',
|
||||
);
|
||||
warning(
|
||||
instance.state === finishedWork.memoizedState,
|
||||
'Expected instance state to match memoized state before ' +
|
||||
'componentDidMount. This is likely due to a bug in React. ' +
|
||||
'Please file an issue.',
|
||||
);
|
||||
}
|
||||
}
|
||||
instance.componentDidMount();
|
||||
stopPhaseTimer();
|
||||
} else {
|
||||
const prevProps = current.memoizedProps;
|
||||
const prevProps =
|
||||
finishedWork.elementType === finishedWork.type
|
||||
? current.memoizedProps
|
||||
: resolveDefaultProps(finishedWork.type, current.memoizedProps);
|
||||
const prevState = current.memoizedState;
|
||||
startPhaseTimer(finishedWork, 'componentDidUpdate');
|
||||
instance.props = finishedWork.memoizedProps;
|
||||
instance.state = finishedWork.memoizedState;
|
||||
// We could update instance props and state here,
|
||||
// but instead we rely on them being set during last render.
|
||||
// TODO: revisit this when we implement resuming.
|
||||
if (__DEV__) {
|
||||
if (finishedWork.type === finishedWork.elementType) {
|
||||
warning(
|
||||
instance.props === finishedWork.memoizedProps,
|
||||
'Expected instance props to match memoized props before ' +
|
||||
'componentDidUpdate. This is likely due to a bug in React. ' +
|
||||
'Please file an issue.',
|
||||
);
|
||||
warning(
|
||||
instance.state === finishedWork.memoizedState,
|
||||
'Expected instance state to match memoized state before ' +
|
||||
'componentDidUpdate. This is likely due to a bug in React. ' +
|
||||
'Please file an issue.',
|
||||
);
|
||||
}
|
||||
}
|
||||
instance.componentDidUpdate(
|
||||
prevProps,
|
||||
prevState,
|
||||
@@ -268,8 +423,25 @@ function commitLifeCycles(
|
||||
}
|
||||
const updateQueue = finishedWork.updateQueue;
|
||||
if (updateQueue !== null) {
|
||||
instance.props = finishedWork.memoizedProps;
|
||||
instance.state = finishedWork.memoizedState;
|
||||
if (__DEV__) {
|
||||
if (finishedWork.type === finishedWork.elementType) {
|
||||
warning(
|
||||
instance.props === finishedWork.memoizedProps,
|
||||
'Expected instance props to match memoized props before ' +
|
||||
'processing the update queue. This is likely due to a bug in React. ' +
|
||||
'Please file an issue.',
|
||||
);
|
||||
warning(
|
||||
instance.state === finishedWork.memoizedState,
|
||||
'Expected instance state to match memoized state before ' +
|
||||
'processing the update queue. This is likely due to a bug in React. ' +
|
||||
'Please file an issue.',
|
||||
);
|
||||
}
|
||||
}
|
||||
// We could update instance props and state here,
|
||||
// but instead we rely on them being set during last render.
|
||||
// TODO: revisit this when we implement resuming.
|
||||
commitUpdateQueue(
|
||||
finishedWork,
|
||||
updateQueue,
|
||||
@@ -289,7 +461,6 @@ function commitLifeCycles(
|
||||
instance = getPublicInstance(finishedWork.child.stateNode);
|
||||
break;
|
||||
case ClassComponent:
|
||||
case ClassComponentLazy:
|
||||
instance = finishedWork.child.stateNode;
|
||||
break;
|
||||
}
|
||||
@@ -353,49 +524,10 @@ function commitLifeCycles(
|
||||
}
|
||||
return;
|
||||
}
|
||||
case SuspenseComponent: {
|
||||
if (finishedWork.effectTag & Callback) {
|
||||
// In non-strict mode, a suspense boundary times out by commiting
|
||||
// twice: first, by committing the children in an inconsistent state,
|
||||
// then hiding them and showing the fallback children in a subsequent
|
||||
// commit.
|
||||
const newState: SuspenseState = {
|
||||
alreadyCaptured: true,
|
||||
didTimeout: false,
|
||||
timedOutAt: NoWork,
|
||||
};
|
||||
finishedWork.memoizedState = newState;
|
||||
scheduleWork(finishedWork, Sync);
|
||||
return;
|
||||
}
|
||||
let oldState: SuspenseState | null =
|
||||
current !== null ? current.memoizedState : null;
|
||||
let newState: SuspenseState | null = finishedWork.memoizedState;
|
||||
let oldDidTimeout = oldState !== null ? oldState.didTimeout : false;
|
||||
|
||||
let newDidTimeout;
|
||||
let primaryChildParent = finishedWork;
|
||||
if (newState === null) {
|
||||
newDidTimeout = false;
|
||||
} else {
|
||||
newDidTimeout = newState.didTimeout;
|
||||
if (newDidTimeout) {
|
||||
primaryChildParent = finishedWork.child;
|
||||
newState.alreadyCaptured = false;
|
||||
if (newState.timedOutAt === NoWork) {
|
||||
// If the children had not already timed out, record the time.
|
||||
// This is used to compute the elapsed time during subsequent
|
||||
// attempts to render the children.
|
||||
newState.timedOutAt = requestCurrentTime();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (newDidTimeout !== oldDidTimeout && primaryChildParent !== null) {
|
||||
hideOrUnhideAllChildren(primaryChildParent, newDidTimeout);
|
||||
}
|
||||
return;
|
||||
}
|
||||
case SuspenseComponent:
|
||||
break;
|
||||
case IncompleteClassComponent:
|
||||
break;
|
||||
default: {
|
||||
invariant(
|
||||
false,
|
||||
@@ -426,6 +558,16 @@ function hideOrUnhideAllChildren(finishedWork, isHidden) {
|
||||
} else {
|
||||
unhideTextInstance(instance, node.memoizedProps);
|
||||
}
|
||||
} else if (
|
||||
node.tag === SuspenseComponent &&
|
||||
node.memoizedState !== null
|
||||
) {
|
||||
// Found a nested Suspense component that timed out. Skip over the
|
||||
// primary child fragment, which should remain hidden.
|
||||
const fallbackChildFragment: Fiber = (node.child: any).sibling;
|
||||
fallbackChildFragment.return = node;
|
||||
node = fallbackChildFragment;
|
||||
continue;
|
||||
} else if (node.child !== null) {
|
||||
node.child.return = node;
|
||||
node = node.child;
|
||||
@@ -496,8 +638,28 @@ function commitUnmount(current: Fiber): void {
|
||||
onCommitUnmount(current);
|
||||
|
||||
switch (current.tag) {
|
||||
case ClassComponent:
|
||||
case ClassComponentLazy: {
|
||||
case FunctionComponent:
|
||||
case ForwardRef:
|
||||
case MemoComponent:
|
||||
case SimpleMemoComponent: {
|
||||
const updateQueue: FunctionComponentUpdateQueue | null = (current.updateQueue: any);
|
||||
if (updateQueue !== null) {
|
||||
const lastEffect = updateQueue.lastEffect;
|
||||
if (lastEffect !== null) {
|
||||
const firstEffect = lastEffect.next;
|
||||
let effect = firstEffect;
|
||||
do {
|
||||
const destroy = effect.destroy;
|
||||
if (destroy !== null) {
|
||||
safelyCallDestroy(current, destroy);
|
||||
}
|
||||
effect = effect.next;
|
||||
} while (effect !== firstEffect);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case ClassComponent: {
|
||||
safelyDetachRef(current);
|
||||
const instance = current.stateNode;
|
||||
if (typeof instance.componentWillUnmount === 'function') {
|
||||
@@ -590,8 +752,7 @@ function commitContainer(finishedWork: Fiber) {
|
||||
}
|
||||
|
||||
switch (finishedWork.tag) {
|
||||
case ClassComponent:
|
||||
case ClassComponentLazy: {
|
||||
case ClassComponent: {
|
||||
return;
|
||||
}
|
||||
case HostComponent: {
|
||||
@@ -871,13 +1032,29 @@ function commitDeletion(current: Fiber): void {
|
||||
|
||||
function commitWork(current: Fiber | null, finishedWork: Fiber): void {
|
||||
if (!supportsMutation) {
|
||||
switch (finishedWork.tag) {
|
||||
case FunctionComponent:
|
||||
case ForwardRef:
|
||||
case MemoComponent:
|
||||
case SimpleMemoComponent: {
|
||||
commitHookEffectList(UnmountMutation, MountMutation, finishedWork);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
commitContainer(finishedWork);
|
||||
return;
|
||||
}
|
||||
|
||||
switch (finishedWork.tag) {
|
||||
case ClassComponent:
|
||||
case ClassComponentLazy: {
|
||||
case FunctionComponent:
|
||||
case ForwardRef:
|
||||
case MemoComponent:
|
||||
case SimpleMemoComponent: {
|
||||
commitHookEffectList(UnmountMutation, MountMutation, finishedWork);
|
||||
return;
|
||||
}
|
||||
case ClassComponent: {
|
||||
return;
|
||||
}
|
||||
case HostComponent: {
|
||||
@@ -929,6 +1106,29 @@ function commitWork(current: Fiber | null, finishedWork: Fiber): void {
|
||||
return;
|
||||
}
|
||||
case SuspenseComponent: {
|
||||
let newState: SuspenseState | null = finishedWork.memoizedState;
|
||||
|
||||
let newDidTimeout;
|
||||
let primaryChildParent = finishedWork;
|
||||
if (newState === null) {
|
||||
newDidTimeout = false;
|
||||
} else {
|
||||
newDidTimeout = true;
|
||||
primaryChildParent = finishedWork.child;
|
||||
if (newState.timedOutAt === NoWork) {
|
||||
// If the children had not already timed out, record the time.
|
||||
// This is used to compute the elapsed time during subsequent
|
||||
// attempts to render the children.
|
||||
newState.timedOutAt = requestCurrentTime();
|
||||
}
|
||||
}
|
||||
|
||||
if (primaryChildParent !== null) {
|
||||
hideOrUnhideAllChildren(primaryChildParent, newDidTimeout);
|
||||
}
|
||||
return;
|
||||
}
|
||||
case IncompleteClassComponent: {
|
||||
return;
|
||||
}
|
||||
default: {
|
||||
|
||||
@@ -22,9 +22,7 @@ import type {SuspenseState} from './ReactFiberSuspenseComponent';
|
||||
import {
|
||||
IndeterminateComponent,
|
||||
FunctionComponent,
|
||||
FunctionComponentLazy,
|
||||
ClassComponent,
|
||||
ClassComponentLazy,
|
||||
HostRoot,
|
||||
HostComponent,
|
||||
HostText,
|
||||
@@ -36,13 +34,20 @@ import {
|
||||
Mode,
|
||||
Profiler,
|
||||
SuspenseComponent,
|
||||
ForwardRefLazy,
|
||||
PureComponent,
|
||||
PureComponentLazy,
|
||||
MemoComponent,
|
||||
SimpleMemoComponent,
|
||||
LazyComponent,
|
||||
IncompleteClassComponent,
|
||||
} from 'shared/ReactWorkTags';
|
||||
import {Placement, Ref, Update} from 'shared/ReactSideEffectTags';
|
||||
import {
|
||||
Placement,
|
||||
Ref,
|
||||
Update,
|
||||
NoEffect,
|
||||
DidCapture,
|
||||
Deletion,
|
||||
} from 'shared/ReactSideEffectTags';
|
||||
import invariant from 'shared/invariant';
|
||||
import {getResultFromResolvedLazyComponent} from 'shared/ReactLazyComponent';
|
||||
|
||||
import {
|
||||
createInstance,
|
||||
@@ -77,6 +82,7 @@ import {
|
||||
prepareToHydrateHostTextInstance,
|
||||
popHydrationState,
|
||||
} from './ReactFiberHydrationContext';
|
||||
import {ConcurrentMode, NoContext} from './ReactTypeOfMode';
|
||||
|
||||
function markUpdate(workInProgress: Fiber) {
|
||||
// Tag the fiber with an update effect. This turns a Placement into
|
||||
@@ -249,8 +255,8 @@ if (supportsMutation) {
|
||||
if (current !== null) {
|
||||
const oldState: SuspenseState = current.memoizedState;
|
||||
const newState: SuspenseState = node.memoizedState;
|
||||
const oldIsHidden = oldState !== null && oldState.didTimeout;
|
||||
const newIsHidden = newState !== null && newState.didTimeout;
|
||||
const oldIsHidden = oldState !== null;
|
||||
const newIsHidden = newState !== null;
|
||||
if (oldIsHidden !== newIsHidden) {
|
||||
// The placeholder either just timed out or switched back to the normal
|
||||
// children after having previously timed out. Toggle the visibility of
|
||||
@@ -352,8 +358,8 @@ if (supportsMutation) {
|
||||
if (current !== null) {
|
||||
const oldState: SuspenseState = current.memoizedState;
|
||||
const newState: SuspenseState = node.memoizedState;
|
||||
const oldIsHidden = oldState !== null && oldState.didTimeout;
|
||||
const newIsHidden = newState !== null && newState.didTimeout;
|
||||
const oldIsHidden = oldState !== null;
|
||||
const newIsHidden = newState !== null;
|
||||
if (oldIsHidden !== newIsHidden) {
|
||||
// The placeholder either just timed out or switched back to the normal
|
||||
// children after having previously timed out. Toggle the visibility of
|
||||
@@ -541,8 +547,10 @@ function completeWork(
|
||||
switch (workInProgress.tag) {
|
||||
case IndeterminateComponent:
|
||||
break;
|
||||
case LazyComponent:
|
||||
break;
|
||||
case SimpleMemoComponent:
|
||||
case FunctionComponent:
|
||||
case FunctionComponentLazy:
|
||||
break;
|
||||
case ClassComponent: {
|
||||
const Component = workInProgress.type;
|
||||
@@ -551,13 +559,6 @@ function completeWork(
|
||||
}
|
||||
break;
|
||||
}
|
||||
case ClassComponentLazy: {
|
||||
const Component = getResultFromResolvedLazyComponent(workInProgress.type);
|
||||
if (isLegacyContextProvider(Component)) {
|
||||
popLegacyContext(workInProgress);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case HostRoot: {
|
||||
popHostContainer(workInProgress);
|
||||
popTopLevelLegacyContextObject(workInProgress);
|
||||
@@ -694,16 +695,51 @@ function completeWork(
|
||||
break;
|
||||
}
|
||||
case ForwardRef:
|
||||
case ForwardRefLazy:
|
||||
break;
|
||||
case SuspenseComponent: {
|
||||
const nextState = workInProgress.memoizedState;
|
||||
const prevState = current !== null ? current.memoizedState : null;
|
||||
const nextDidTimeout = nextState !== null && nextState.didTimeout;
|
||||
const prevDidTimeout = prevState !== null && prevState.didTimeout;
|
||||
if (nextDidTimeout !== prevDidTimeout) {
|
||||
// If this render commits, and it switches between the normal state
|
||||
// and the timed-out state, schedule an effect.
|
||||
if ((workInProgress.effectTag & DidCapture) !== NoEffect) {
|
||||
// Something suspended. Re-render with the fallback children.
|
||||
workInProgress.expirationTime = renderExpirationTime;
|
||||
// Do not reset the effect list.
|
||||
return workInProgress;
|
||||
}
|
||||
|
||||
const nextDidTimeout = nextState !== null;
|
||||
const prevDidTimeout = current !== null && current.memoizedState !== null;
|
||||
|
||||
if (current !== null && !nextDidTimeout && prevDidTimeout) {
|
||||
// We just switched from the fallback to the normal children. Delete
|
||||
// the fallback.
|
||||
// TODO: Would it be better to store the fallback fragment on
|
||||
// the stateNode during the begin phase?
|
||||
const currentFallbackChild: Fiber | null = (current.child: any).sibling;
|
||||
if (currentFallbackChild !== null) {
|
||||
// Deletions go at the beginning of the return fiber's effect list
|
||||
const first = workInProgress.firstEffect;
|
||||
if (first !== null) {
|
||||
workInProgress.firstEffect = currentFallbackChild;
|
||||
currentFallbackChild.nextEffect = first;
|
||||
} else {
|
||||
workInProgress.firstEffect = workInProgress.lastEffect = currentFallbackChild;
|
||||
currentFallbackChild.nextEffect = null;
|
||||
}
|
||||
currentFallbackChild.effectTag = Deletion;
|
||||
}
|
||||
}
|
||||
|
||||
// The children either timed out after previously being visible, or
|
||||
// were restored after previously being hidden. Schedule an effect
|
||||
// to update their visiblity.
|
||||
if (
|
||||
//
|
||||
nextDidTimeout !== prevDidTimeout ||
|
||||
// Outside concurrent mode, the primary children commit in an
|
||||
// inconsistent state, even if they are hidden. So if they are hidden,
|
||||
// we need to schedule an effect to re-hide them, just in case.
|
||||
((workInProgress.effectTag & ConcurrentMode) === NoContext &&
|
||||
nextDidTimeout)
|
||||
) {
|
||||
workInProgress.effectTag |= Update;
|
||||
}
|
||||
break;
|
||||
@@ -724,9 +760,17 @@ function completeWork(
|
||||
break;
|
||||
case ContextConsumer:
|
||||
break;
|
||||
case PureComponent:
|
||||
case PureComponentLazy:
|
||||
case MemoComponent:
|
||||
break;
|
||||
case IncompleteClassComponent: {
|
||||
// Same as class component case. I put it down here so that the tags are
|
||||
// sequential to ensure this switch is compiled to a jump table.
|
||||
const Component = workInProgress.type;
|
||||
if (isLegacyContextProvider(Component)) {
|
||||
popLegacyContext(workInProgress);
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
invariant(
|
||||
false,
|
||||
|
||||
@@ -11,16 +11,11 @@ import type {Fiber} from './ReactFiber';
|
||||
import type {StackCursor} from './ReactFiberStack';
|
||||
|
||||
import {isFiberMounted} from 'react-reconciler/reflection';
|
||||
import {
|
||||
ClassComponent,
|
||||
HostRoot,
|
||||
ClassComponentLazy,
|
||||
} from 'shared/ReactWorkTags';
|
||||
import {ClassComponent, HostRoot} from 'shared/ReactWorkTags';
|
||||
import getComponentName from 'shared/getComponentName';
|
||||
import invariant from 'shared/invariant';
|
||||
import warningWithoutStack from 'shared/warningWithoutStack';
|
||||
import checkPropTypes from 'prop-types/checkPropTypes';
|
||||
import {getResultFromResolvedLazyComponent} from 'shared/ReactLazyComponent';
|
||||
|
||||
import * as ReactCurrentFiber from './ReactCurrentFiber';
|
||||
import {startPhaseTimer, stopPhaseTimer} from './ReactDebugFiberPerf';
|
||||
@@ -279,8 +274,7 @@ function findCurrentUnmaskedContext(fiber: Fiber): Object {
|
||||
// Currently this is only used with renderSubtreeIntoContainer; not sure if it
|
||||
// makes sense elsewhere
|
||||
invariant(
|
||||
isFiberMounted(fiber) &&
|
||||
(fiber.tag === ClassComponent || fiber.tag === ClassComponentLazy),
|
||||
isFiberMounted(fiber) && fiber.tag === ClassComponent,
|
||||
'Expected subtree parent to be a mounted class component. ' +
|
||||
'This error is likely caused by a bug in React. Please file an issue.',
|
||||
);
|
||||
@@ -297,13 +291,6 @@ function findCurrentUnmaskedContext(fiber: Fiber): Object {
|
||||
}
|
||||
break;
|
||||
}
|
||||
case ClassComponentLazy: {
|
||||
const Component = getResultFromResolvedLazyComponent(node.type);
|
||||
if (isContextProvider(Component)) {
|
||||
return node.stateNode.__reactInternalMemoizedMergedChildContext;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
node = node.return;
|
||||
} while (node !== null);
|
||||
|
||||
@@ -8,7 +8,32 @@
|
||||
*/
|
||||
|
||||
import {readContext} from './ReactFiberNewContext';
|
||||
import {
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useImperativeMethods,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useMutationEffect,
|
||||
useReducer,
|
||||
useRef,
|
||||
useState,
|
||||
} from './ReactFiberHooks';
|
||||
|
||||
export const Dispatcher = {
|
||||
readContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useImperativeMethods,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useMutationEffect,
|
||||
useReducer,
|
||||
useRef,
|
||||
useState,
|
||||
};
|
||||
export const DispatcherWithoutHooks = {
|
||||
readContext,
|
||||
};
|
||||
|
||||
@@ -12,20 +12,20 @@ import MAX_SIGNED_31_BIT_INT from './maxSigned31BitInt';
|
||||
export type ExpirationTime = number;
|
||||
|
||||
export const NoWork = 0;
|
||||
export const Sync = 1;
|
||||
export const Never = MAX_SIGNED_31_BIT_INT;
|
||||
export const Never = 1;
|
||||
export const Sync = MAX_SIGNED_31_BIT_INT;
|
||||
|
||||
const UNIT_SIZE = 10;
|
||||
const MAGIC_NUMBER_OFFSET = 2;
|
||||
const MAGIC_NUMBER_OFFSET = MAX_SIGNED_31_BIT_INT - 1;
|
||||
|
||||
// 1 unit of expiration time represents 10ms.
|
||||
export function msToExpirationTime(ms: number): ExpirationTime {
|
||||
// Always add an offset so that we don't clash with the magic number for NoWork.
|
||||
return ((ms / UNIT_SIZE) | 0) + MAGIC_NUMBER_OFFSET;
|
||||
return MAGIC_NUMBER_OFFSET - ((ms / UNIT_SIZE) | 0);
|
||||
}
|
||||
|
||||
export function expirationTimeToMs(expirationTime: ExpirationTime): number {
|
||||
return (expirationTime - MAGIC_NUMBER_OFFSET) * UNIT_SIZE;
|
||||
return (MAGIC_NUMBER_OFFSET - expirationTime) * UNIT_SIZE;
|
||||
}
|
||||
|
||||
function ceiling(num: number, precision: number): number {
|
||||
@@ -38,9 +38,9 @@ function computeExpirationBucket(
|
||||
bucketSizeMs,
|
||||
): ExpirationTime {
|
||||
return (
|
||||
MAGIC_NUMBER_OFFSET +
|
||||
MAGIC_NUMBER_OFFSET -
|
||||
ceiling(
|
||||
currentTime - MAGIC_NUMBER_OFFSET + expirationInMs / UNIT_SIZE,
|
||||
MAGIC_NUMBER_OFFSET - currentTime + expirationInMs / UNIT_SIZE,
|
||||
bucketSizeMs / UNIT_SIZE,
|
||||
)
|
||||
);
|
||||
|
||||
715
packages/react-reconciler/src/ReactFiberHooks.js
vendored
Normal file
715
packages/react-reconciler/src/ReactFiberHooks.js
vendored
Normal file
@@ -0,0 +1,715 @@
|
||||
/**
|
||||
* Copyright (c) 2013-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root direcreatey of this source tree.
|
||||
*
|
||||
* @flow
|
||||
*/
|
||||
|
||||
import type {ReactContext} from 'shared/ReactTypes';
|
||||
import type {Fiber} from './ReactFiber';
|
||||
import type {ExpirationTime} from './ReactFiberExpirationTime';
|
||||
import type {HookEffectTag} from './ReactHookEffectTags';
|
||||
|
||||
import {NoWork} from './ReactFiberExpirationTime';
|
||||
import {enableHooks} from 'shared/ReactFeatureFlags';
|
||||
import {readContext} from './ReactFiberNewContext';
|
||||
import {
|
||||
Snapshot as SnapshotEffect,
|
||||
Update as UpdateEffect,
|
||||
Passive as PassiveEffect,
|
||||
} from 'shared/ReactSideEffectTags';
|
||||
import {
|
||||
NoEffect as NoHookEffect,
|
||||
UnmountSnapshot,
|
||||
UnmountMutation,
|
||||
MountMutation,
|
||||
MountLayout,
|
||||
UnmountPassive,
|
||||
MountPassive,
|
||||
} from './ReactHookEffectTags';
|
||||
import {
|
||||
scheduleWork,
|
||||
computeExpirationForFiber,
|
||||
flushPassiveEffects,
|
||||
requestCurrentTime,
|
||||
} from './ReactFiberScheduler';
|
||||
|
||||
import invariant from 'shared/invariant';
|
||||
import areHookInputsEqual from 'shared/areHookInputsEqual';
|
||||
|
||||
type Update<A> = {
|
||||
expirationTime: ExpirationTime,
|
||||
action: A,
|
||||
next: Update<A> | null,
|
||||
};
|
||||
|
||||
type UpdateQueue<A> = {
|
||||
last: Update<A> | null,
|
||||
dispatch: any,
|
||||
};
|
||||
|
||||
export type Hook = {
|
||||
memoizedState: any,
|
||||
|
||||
baseState: any,
|
||||
baseUpdate: Update<any> | null,
|
||||
queue: UpdateQueue<any> | null,
|
||||
|
||||
next: Hook | null,
|
||||
};
|
||||
|
||||
type Effect = {
|
||||
tag: HookEffectTag,
|
||||
create: () => mixed,
|
||||
destroy: (() => mixed) | null,
|
||||
inputs: Array<mixed>,
|
||||
next: Effect,
|
||||
};
|
||||
|
||||
export type FunctionComponentUpdateQueue = {
|
||||
lastEffect: Effect | null,
|
||||
};
|
||||
|
||||
type BasicStateAction<S> = (S => S) | S;
|
||||
|
||||
type Dispatch<A> = A => void;
|
||||
|
||||
// These are set right before calling the component.
|
||||
let renderExpirationTime: ExpirationTime = NoWork;
|
||||
// The work-in-progress fiber. I've named it differently to distinguish it from
|
||||
// the work-in-progress hook.
|
||||
let currentlyRenderingFiber: Fiber | null = null;
|
||||
|
||||
// Hooks are stored as a linked list on the fiber's memoizedState field. The
|
||||
// current hook list is the list that belongs to the current fiber. The
|
||||
// work-in-progress hook list is a new list that will be added to the
|
||||
// work-in-progress fiber.
|
||||
let firstCurrentHook: Hook | null = null;
|
||||
let currentHook: Hook | null = null;
|
||||
let firstWorkInProgressHook: Hook | null = null;
|
||||
let workInProgressHook: Hook | null = null;
|
||||
|
||||
let remainingExpirationTime: ExpirationTime = NoWork;
|
||||
let componentUpdateQueue: FunctionComponentUpdateQueue | null = null;
|
||||
|
||||
// Updates scheduled during render will trigger an immediate re-render at the
|
||||
// end of the current pass. We can't store these updates on the normal queue,
|
||||
// because if the work is aborted, they should be discarded. Because this is
|
||||
// a relatively rare case, we also don't want to add an additional field to
|
||||
// either the hook or queue object types. So we store them in a lazily create
|
||||
// map of queue -> render-phase updates, which are discarded once the component
|
||||
// completes without re-rendering.
|
||||
|
||||
// Whether the work-in-progress hook is a re-rendered hook
|
||||
let isReRender: boolean = false;
|
||||
// Whether an update was scheduled during the currently executing render pass.
|
||||
let didScheduleRenderPhaseUpdate: boolean = false;
|
||||
// Lazily created map of render-phase updates
|
||||
let renderPhaseUpdates: Map<UpdateQueue<any>, Update<any>> | null = null;
|
||||
// Counter to prevent infinite loops.
|
||||
let numberOfReRenders: number = 0;
|
||||
const RE_RENDER_LIMIT = 25;
|
||||
|
||||
function resolveCurrentlyRenderingFiber(): Fiber {
|
||||
invariant(
|
||||
currentlyRenderingFiber !== null,
|
||||
'Hooks can only be called inside the body of a function component.',
|
||||
);
|
||||
return currentlyRenderingFiber;
|
||||
}
|
||||
|
||||
export function prepareToUseHooks(
|
||||
current: Fiber | null,
|
||||
workInProgress: Fiber,
|
||||
nextRenderExpirationTime: ExpirationTime,
|
||||
): void {
|
||||
if (!enableHooks) {
|
||||
return;
|
||||
}
|
||||
renderExpirationTime = nextRenderExpirationTime;
|
||||
currentlyRenderingFiber = workInProgress;
|
||||
firstCurrentHook = current !== null ? current.memoizedState : null;
|
||||
|
||||
// The following should have already been reset
|
||||
// currentHook = null;
|
||||
// workInProgressHook = null;
|
||||
|
||||
// remainingExpirationTime = NoWork;
|
||||
// componentUpdateQueue = null;
|
||||
|
||||
// isReRender = false;
|
||||
// didScheduleRenderPhaseUpdate = false;
|
||||
// renderPhaseUpdates = null;
|
||||
// numberOfReRenders = 0;
|
||||
}
|
||||
|
||||
export function finishHooks(
|
||||
Component: any,
|
||||
props: any,
|
||||
children: any,
|
||||
refOrContext: any,
|
||||
): any {
|
||||
if (!enableHooks) {
|
||||
return children;
|
||||
}
|
||||
|
||||
// This must be called after every function component to prevent hooks from
|
||||
// being used in classes.
|
||||
|
||||
while (didScheduleRenderPhaseUpdate) {
|
||||
// Updates were scheduled during the render phase. They are stored in
|
||||
// the `renderPhaseUpdates` map. Call the component again, reusing the
|
||||
// work-in-progress hooks and applying the additional updates on top. Keep
|
||||
// restarting until no more updates are scheduled.
|
||||
didScheduleRenderPhaseUpdate = false;
|
||||
numberOfReRenders += 1;
|
||||
|
||||
// Start over from the beginning of the list
|
||||
currentHook = null;
|
||||
workInProgressHook = null;
|
||||
componentUpdateQueue = null;
|
||||
|
||||
children = Component(props, refOrContext);
|
||||
}
|
||||
renderPhaseUpdates = null;
|
||||
numberOfReRenders = 0;
|
||||
|
||||
const renderedWork: Fiber = (currentlyRenderingFiber: any);
|
||||
|
||||
renderedWork.memoizedState = firstWorkInProgressHook;
|
||||
renderedWork.expirationTime = remainingExpirationTime;
|
||||
renderedWork.updateQueue = (componentUpdateQueue: any);
|
||||
|
||||
const didRenderTooFewHooks =
|
||||
currentHook !== null && currentHook.next !== null;
|
||||
|
||||
renderExpirationTime = NoWork;
|
||||
currentlyRenderingFiber = null;
|
||||
|
||||
firstCurrentHook = null;
|
||||
currentHook = null;
|
||||
firstWorkInProgressHook = null;
|
||||
workInProgressHook = null;
|
||||
|
||||
remainingExpirationTime = NoWork;
|
||||
componentUpdateQueue = null;
|
||||
|
||||
// Always set during createWorkInProgress
|
||||
// isReRender = false;
|
||||
|
||||
// These were reset above
|
||||
// didScheduleRenderPhaseUpdate = false;
|
||||
// renderPhaseUpdates = null;
|
||||
// numberOfReRenders = 0;
|
||||
|
||||
invariant(
|
||||
!didRenderTooFewHooks,
|
||||
'Rendered fewer hooks than expected. This may be caused by an accidental ' +
|
||||
'early return statement.',
|
||||
);
|
||||
|
||||
return children;
|
||||
}
|
||||
|
||||
export function resetHooks(): void {
|
||||
if (!enableHooks) {
|
||||
return;
|
||||
}
|
||||
|
||||
// This is called instead of `finishHooks` if the component throws. It's also
|
||||
// called inside mountIndeterminateComponent if we determine the component
|
||||
// is a module-style component.
|
||||
renderExpirationTime = NoWork;
|
||||
currentlyRenderingFiber = null;
|
||||
|
||||
firstCurrentHook = null;
|
||||
currentHook = null;
|
||||
firstWorkInProgressHook = null;
|
||||
workInProgressHook = null;
|
||||
|
||||
remainingExpirationTime = NoWork;
|
||||
componentUpdateQueue = null;
|
||||
|
||||
// Always set during createWorkInProgress
|
||||
// isReRender = false;
|
||||
|
||||
didScheduleRenderPhaseUpdate = false;
|
||||
renderPhaseUpdates = null;
|
||||
numberOfReRenders = 0;
|
||||
}
|
||||
|
||||
function createHook(): Hook {
|
||||
return {
|
||||
memoizedState: null,
|
||||
|
||||
baseState: null,
|
||||
queue: null,
|
||||
baseUpdate: null,
|
||||
|
||||
next: null,
|
||||
};
|
||||
}
|
||||
|
||||
function cloneHook(hook: Hook): Hook {
|
||||
return {
|
||||
memoizedState: hook.memoizedState,
|
||||
|
||||
baseState: hook.memoizedState,
|
||||
queue: hook.queue,
|
||||
baseUpdate: hook.baseUpdate,
|
||||
|
||||
next: null,
|
||||
};
|
||||
}
|
||||
|
||||
function createWorkInProgressHook(): Hook {
|
||||
if (workInProgressHook === null) {
|
||||
// This is the first hook in the list
|
||||
if (firstWorkInProgressHook === null) {
|
||||
isReRender = false;
|
||||
currentHook = firstCurrentHook;
|
||||
if (currentHook === null) {
|
||||
// This is a newly mounted hook
|
||||
workInProgressHook = createHook();
|
||||
} else {
|
||||
// Clone the current hook.
|
||||
workInProgressHook = cloneHook(currentHook);
|
||||
}
|
||||
firstWorkInProgressHook = workInProgressHook;
|
||||
} else {
|
||||
// There's already a work-in-progress. Reuse it.
|
||||
isReRender = true;
|
||||
currentHook = firstCurrentHook;
|
||||
workInProgressHook = firstWorkInProgressHook;
|
||||
}
|
||||
} else {
|
||||
if (workInProgressHook.next === null) {
|
||||
isReRender = false;
|
||||
let hook;
|
||||
if (currentHook === null) {
|
||||
// This is a newly mounted hook
|
||||
hook = createHook();
|
||||
} else {
|
||||
currentHook = currentHook.next;
|
||||
if (currentHook === null) {
|
||||
// This is a newly mounted hook
|
||||
hook = createHook();
|
||||
} else {
|
||||
// Clone the current hook.
|
||||
hook = cloneHook(currentHook);
|
||||
}
|
||||
}
|
||||
// Append to the end of the list
|
||||
workInProgressHook = workInProgressHook.next = hook;
|
||||
} else {
|
||||
// There's already a work-in-progress. Reuse it.
|
||||
isReRender = true;
|
||||
workInProgressHook = workInProgressHook.next;
|
||||
currentHook = currentHook !== null ? currentHook.next : null;
|
||||
}
|
||||
}
|
||||
return workInProgressHook;
|
||||
}
|
||||
|
||||
function createFunctionComponentUpdateQueue(): FunctionComponentUpdateQueue {
|
||||
return {
|
||||
lastEffect: null,
|
||||
};
|
||||
}
|
||||
|
||||
function basicStateReducer<S>(state: S, action: BasicStateAction<S>): S {
|
||||
return typeof action === 'function' ? action(state) : action;
|
||||
}
|
||||
|
||||
export function useContext<T>(
|
||||
context: ReactContext<T>,
|
||||
observedBits: void | number | boolean,
|
||||
): T {
|
||||
// Ensure we're in a function component (class components support only the
|
||||
// .unstable_read() form)
|
||||
resolveCurrentlyRenderingFiber();
|
||||
return readContext(context, observedBits);
|
||||
}
|
||||
|
||||
export function useState<S>(
|
||||
initialState: (() => S) | S,
|
||||
): [S, Dispatch<BasicStateAction<S>>] {
|
||||
return useReducer(
|
||||
basicStateReducer,
|
||||
// useReducer has a special case to support lazy useState initializers
|
||||
(initialState: any),
|
||||
);
|
||||
}
|
||||
|
||||
export function useReducer<S, A>(
|
||||
reducer: (S, A) => S,
|
||||
initialState: S,
|
||||
initialAction: A | void | null,
|
||||
): [S, Dispatch<A>] {
|
||||
currentlyRenderingFiber = resolveCurrentlyRenderingFiber();
|
||||
workInProgressHook = createWorkInProgressHook();
|
||||
let queue: UpdateQueue<A> | null = (workInProgressHook.queue: any);
|
||||
if (queue !== null) {
|
||||
// Already have a queue, so this is an update.
|
||||
if (isReRender) {
|
||||
// This is a re-render. Apply the new render phase updates to the previous
|
||||
// work-in-progress hook.
|
||||
const dispatch: Dispatch<A> = (queue.dispatch: any);
|
||||
if (renderPhaseUpdates !== null) {
|
||||
// Render phase updates are stored in a map of queue -> linked list
|
||||
const firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
|
||||
if (firstRenderPhaseUpdate !== undefined) {
|
||||
renderPhaseUpdates.delete(queue);
|
||||
let newState = workInProgressHook.memoizedState;
|
||||
let update = firstRenderPhaseUpdate;
|
||||
do {
|
||||
// Process this render phase update. We don't have to check the
|
||||
// priority because it will always be the same as the current
|
||||
// render's.
|
||||
const action = update.action;
|
||||
newState = reducer(newState, action);
|
||||
update = update.next;
|
||||
} while (update !== null);
|
||||
|
||||
workInProgressHook.memoizedState = newState;
|
||||
|
||||
// Don't persist the state accumlated from the render phase updates to
|
||||
// the base state unless the queue is empty.
|
||||
// TODO: Not sure if this is the desired semantics, but it's what we
|
||||
// do for gDSFP. I can't remember why.
|
||||
if (workInProgressHook.baseUpdate === queue.last) {
|
||||
workInProgressHook.baseState = newState;
|
||||
}
|
||||
|
||||
return [newState, dispatch];
|
||||
}
|
||||
}
|
||||
return [workInProgressHook.memoizedState, dispatch];
|
||||
}
|
||||
|
||||
// The last update in the entire queue
|
||||
const last = queue.last;
|
||||
// The last update that is part of the base state.
|
||||
const baseUpdate = workInProgressHook.baseUpdate;
|
||||
|
||||
// Find the first unprocessed update.
|
||||
let first;
|
||||
if (baseUpdate !== null) {
|
||||
if (last !== null) {
|
||||
// For the first update, the queue is a circular linked list where
|
||||
// `queue.last.next = queue.first`. Once the first update commits, and
|
||||
// the `baseUpdate` is no longer empty, we can unravel the list.
|
||||
last.next = null;
|
||||
}
|
||||
first = baseUpdate.next;
|
||||
} else {
|
||||
first = last !== null ? last.next : null;
|
||||
}
|
||||
if (first !== null) {
|
||||
let newState = workInProgressHook.baseState;
|
||||
let newBaseState = null;
|
||||
let newBaseUpdate = null;
|
||||
let prevUpdate = baseUpdate;
|
||||
let update = first;
|
||||
let didSkip = false;
|
||||
do {
|
||||
const updateExpirationTime = update.expirationTime;
|
||||
if (updateExpirationTime < renderExpirationTime) {
|
||||
// Priority is insufficient. Skip this update. If this is the first
|
||||
// skipped update, the previous update/state is the new base
|
||||
// update/state.
|
||||
if (!didSkip) {
|
||||
didSkip = true;
|
||||
newBaseUpdate = prevUpdate;
|
||||
newBaseState = newState;
|
||||
}
|
||||
// Update the remaining priority in the queue.
|
||||
if (updateExpirationTime > remainingExpirationTime) {
|
||||
remainingExpirationTime = updateExpirationTime;
|
||||
}
|
||||
} else {
|
||||
// Process this update.
|
||||
const action = update.action;
|
||||
newState = reducer(newState, action);
|
||||
}
|
||||
prevUpdate = update;
|
||||
update = update.next;
|
||||
} while (update !== null && update !== first);
|
||||
|
||||
if (!didSkip) {
|
||||
newBaseUpdate = prevUpdate;
|
||||
newBaseState = newState;
|
||||
}
|
||||
|
||||
workInProgressHook.memoizedState = newState;
|
||||
workInProgressHook.baseUpdate = newBaseUpdate;
|
||||
workInProgressHook.baseState = newBaseState;
|
||||
}
|
||||
|
||||
const dispatch: Dispatch<A> = (queue.dispatch: any);
|
||||
return [workInProgressHook.memoizedState, dispatch];
|
||||
}
|
||||
|
||||
// There's no existing queue, so this is the initial render.
|
||||
if (reducer === basicStateReducer) {
|
||||
// Special case for `useState`.
|
||||
if (typeof initialState === 'function') {
|
||||
initialState = initialState();
|
||||
}
|
||||
} else if (initialAction !== undefined && initialAction !== null) {
|
||||
initialState = reducer(initialState, initialAction);
|
||||
}
|
||||
workInProgressHook.memoizedState = workInProgressHook.baseState = initialState;
|
||||
queue = workInProgressHook.queue = {
|
||||
last: null,
|
||||
dispatch: null,
|
||||
};
|
||||
const dispatch: Dispatch<A> = (queue.dispatch = (dispatchAction.bind(
|
||||
null,
|
||||
currentlyRenderingFiber,
|
||||
queue,
|
||||
): any));
|
||||
return [workInProgressHook.memoizedState, dispatch];
|
||||
}
|
||||
|
||||
function pushEffect(tag, create, destroy, inputs) {
|
||||
const effect: Effect = {
|
||||
tag,
|
||||
create,
|
||||
destroy,
|
||||
inputs,
|
||||
// Circular
|
||||
next: (null: any),
|
||||
};
|
||||
if (componentUpdateQueue === null) {
|
||||
componentUpdateQueue = createFunctionComponentUpdateQueue();
|
||||
componentUpdateQueue.lastEffect = effect.next = effect;
|
||||
} else {
|
||||
const lastEffect = componentUpdateQueue.lastEffect;
|
||||
if (lastEffect === null) {
|
||||
componentUpdateQueue.lastEffect = effect.next = effect;
|
||||
} else {
|
||||
const firstEffect = lastEffect.next;
|
||||
lastEffect.next = effect;
|
||||
effect.next = firstEffect;
|
||||
componentUpdateQueue.lastEffect = effect;
|
||||
}
|
||||
}
|
||||
return effect;
|
||||
}
|
||||
|
||||
export function useRef<T>(initialValue: T): {current: T} {
|
||||
currentlyRenderingFiber = resolveCurrentlyRenderingFiber();
|
||||
workInProgressHook = createWorkInProgressHook();
|
||||
let ref;
|
||||
|
||||
if (workInProgressHook.memoizedState === null) {
|
||||
ref = {current: initialValue};
|
||||
if (__DEV__) {
|
||||
Object.seal(ref);
|
||||
}
|
||||
workInProgressHook.memoizedState = ref;
|
||||
} else {
|
||||
ref = workInProgressHook.memoizedState;
|
||||
}
|
||||
return ref;
|
||||
}
|
||||
|
||||
export function useMutationEffect(
|
||||
create: () => mixed,
|
||||
inputs: Array<mixed> | void | null,
|
||||
): void {
|
||||
useEffectImpl(
|
||||
SnapshotEffect | UpdateEffect,
|
||||
UnmountSnapshot | MountMutation,
|
||||
create,
|
||||
inputs,
|
||||
);
|
||||
}
|
||||
|
||||
export function useLayoutEffect(
|
||||
create: () => mixed,
|
||||
inputs: Array<mixed> | void | null,
|
||||
): void {
|
||||
useEffectImpl(UpdateEffect, UnmountMutation | MountLayout, create, inputs);
|
||||
}
|
||||
|
||||
export function useEffect(
|
||||
create: () => mixed,
|
||||
inputs: Array<mixed> | void | null,
|
||||
): void {
|
||||
useEffectImpl(
|
||||
UpdateEffect | PassiveEffect,
|
||||
UnmountPassive | MountPassive,
|
||||
create,
|
||||
inputs,
|
||||
);
|
||||
}
|
||||
|
||||
function useEffectImpl(fiberEffectTag, hookEffectTag, create, inputs): void {
|
||||
currentlyRenderingFiber = resolveCurrentlyRenderingFiber();
|
||||
workInProgressHook = createWorkInProgressHook();
|
||||
|
||||
let nextInputs = inputs !== undefined && inputs !== null ? inputs : [create];
|
||||
let destroy = null;
|
||||
if (currentHook !== null) {
|
||||
const prevEffect = currentHook.memoizedState;
|
||||
destroy = prevEffect.destroy;
|
||||
if (areHookInputsEqual(nextInputs, prevEffect.inputs)) {
|
||||
pushEffect(NoHookEffect, create, destroy, nextInputs);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
currentlyRenderingFiber.effectTag |= fiberEffectTag;
|
||||
workInProgressHook.memoizedState = pushEffect(
|
||||
hookEffectTag,
|
||||
create,
|
||||
destroy,
|
||||
nextInputs,
|
||||
);
|
||||
}
|
||||
|
||||
export function useImperativeMethods<T>(
|
||||
ref: {current: T | null} | ((inst: T | null) => mixed) | null | void,
|
||||
create: () => T,
|
||||
inputs: Array<mixed> | void | null,
|
||||
): void {
|
||||
// TODO: If inputs are provided, should we skip comparing the ref itself?
|
||||
const nextInputs =
|
||||
inputs !== null && inputs !== undefined
|
||||
? inputs.concat([ref])
|
||||
: [ref, create];
|
||||
|
||||
// TODO: I've implemented this on top of useEffect because it's almost the
|
||||
// same thing, and it would require an equal amount of code. It doesn't seem
|
||||
// like a common enough use case to justify the additional size.
|
||||
useEffectImpl(
|
||||
UpdateEffect,
|
||||
UnmountMutation | MountLayout,
|
||||
() => {
|
||||
if (typeof ref === 'function') {
|
||||
const refCallback = ref;
|
||||
const inst = create();
|
||||
refCallback(inst);
|
||||
return () => refCallback(null);
|
||||
} else if (ref !== null && ref !== undefined) {
|
||||
const refObject = ref;
|
||||
const inst = create();
|
||||
refObject.current = inst;
|
||||
return () => {
|
||||
refObject.current = null;
|
||||
};
|
||||
}
|
||||
},
|
||||
nextInputs,
|
||||
);
|
||||
}
|
||||
|
||||
export function useCallback<T>(
|
||||
callback: T,
|
||||
inputs: Array<mixed> | void | null,
|
||||
): T {
|
||||
currentlyRenderingFiber = resolveCurrentlyRenderingFiber();
|
||||
workInProgressHook = createWorkInProgressHook();
|
||||
|
||||
const nextInputs =
|
||||
inputs !== undefined && inputs !== null ? inputs : [callback];
|
||||
|
||||
const prevState = workInProgressHook.memoizedState;
|
||||
if (prevState !== null) {
|
||||
const prevInputs = prevState[1];
|
||||
if (areHookInputsEqual(nextInputs, prevInputs)) {
|
||||
return prevState[0];
|
||||
}
|
||||
}
|
||||
workInProgressHook.memoizedState = [callback, nextInputs];
|
||||
return callback;
|
||||
}
|
||||
|
||||
export function useMemo<T>(
|
||||
nextCreate: () => T,
|
||||
inputs: Array<mixed> | void | null,
|
||||
): T {
|
||||
currentlyRenderingFiber = resolveCurrentlyRenderingFiber();
|
||||
workInProgressHook = createWorkInProgressHook();
|
||||
|
||||
const nextInputs =
|
||||
inputs !== undefined && inputs !== null ? inputs : [nextCreate];
|
||||
|
||||
const prevState = workInProgressHook.memoizedState;
|
||||
if (prevState !== null) {
|
||||
const prevInputs = prevState[1];
|
||||
if (areHookInputsEqual(nextInputs, prevInputs)) {
|
||||
return prevState[0];
|
||||
}
|
||||
}
|
||||
|
||||
const nextValue = nextCreate();
|
||||
workInProgressHook.memoizedState = [nextValue, nextInputs];
|
||||
return nextValue;
|
||||
}
|
||||
|
||||
function dispatchAction<A>(fiber: Fiber, queue: UpdateQueue<A>, action: A) {
|
||||
invariant(
|
||||
numberOfReRenders < RE_RENDER_LIMIT,
|
||||
'Too many re-renders. React limits the number of renders to prevent ' +
|
||||
'an infinite loop.',
|
||||
);
|
||||
|
||||
const alternate = fiber.alternate;
|
||||
if (
|
||||
fiber === currentlyRenderingFiber ||
|
||||
(alternate !== null && alternate === currentlyRenderingFiber)
|
||||
) {
|
||||
// This is a render phase update. Stash it in a lazily-created map of
|
||||
// queue -> linked list of updates. After this render pass, we'll restart
|
||||
// and apply the stashed updates on top of the work-in-progress hook.
|
||||
didScheduleRenderPhaseUpdate = true;
|
||||
const update: Update<A> = {
|
||||
expirationTime: renderExpirationTime,
|
||||
action,
|
||||
next: null,
|
||||
};
|
||||
if (renderPhaseUpdates === null) {
|
||||
renderPhaseUpdates = new Map();
|
||||
}
|
||||
const firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
|
||||
if (firstRenderPhaseUpdate === undefined) {
|
||||
renderPhaseUpdates.set(queue, update);
|
||||
} else {
|
||||
// Append the update to the end of the list.
|
||||
let lastRenderPhaseUpdate = firstRenderPhaseUpdate;
|
||||
while (lastRenderPhaseUpdate.next !== null) {
|
||||
lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
|
||||
}
|
||||
lastRenderPhaseUpdate.next = update;
|
||||
}
|
||||
} else {
|
||||
const currentTime = requestCurrentTime();
|
||||
const expirationTime = computeExpirationForFiber(currentTime, fiber);
|
||||
const update: Update<A> = {
|
||||
expirationTime,
|
||||
action,
|
||||
next: null,
|
||||
};
|
||||
flushPassiveEffects();
|
||||
// Append the update to the end of the list.
|
||||
const last = queue.last;
|
||||
if (last === null) {
|
||||
// This is the first update. Create a circular list.
|
||||
update.next = update;
|
||||
} else {
|
||||
const first = last.next;
|
||||
if (first !== null) {
|
||||
// Still circular.
|
||||
update.next = first;
|
||||
}
|
||||
last.next = update;
|
||||
}
|
||||
queue.last = update;
|
||||
scheduleWork(fiber, expirationTime);
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,21 @@ import type {LazyComponent, Thenable} from 'shared/ReactLazyComponent';
|
||||
import {Resolved, Rejected, Pending} from 'shared/ReactLazyComponent';
|
||||
import warning from 'shared/warning';
|
||||
|
||||
export function resolveDefaultProps(Component: any, baseProps: Object): Object {
|
||||
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 readLazyComponentType<T>(lazyComponent: LazyComponent<T>): T {
|
||||
const status = lazyComponent._status;
|
||||
const result = lazyComponent._result;
|
||||
|
||||
@@ -21,13 +21,8 @@ export type ContextDependency<T> = {
|
||||
import warningWithoutStack from 'shared/warningWithoutStack';
|
||||
import {isPrimaryRenderer} from './ReactFiberHostConfig';
|
||||
import {createCursor, push, pop} from './ReactFiberStack';
|
||||
import maxSigned31BitInt from './maxSigned31BitInt';
|
||||
import {NoWork} from './ReactFiberExpirationTime';
|
||||
import {
|
||||
ContextProvider,
|
||||
ClassComponent,
|
||||
ClassComponentLazy,
|
||||
} from 'shared/ReactWorkTags';
|
||||
import MAX_SIGNED_31_BIT_INT from './maxSigned31BitInt';
|
||||
import {ContextProvider, ClassComponent} from 'shared/ReactWorkTags';
|
||||
|
||||
import invariant from 'shared/invariant';
|
||||
import warning from 'shared/warning';
|
||||
@@ -37,7 +32,6 @@ import {
|
||||
ForceUpdate,
|
||||
} from 'react-reconciler/src/ReactUpdateQueue';
|
||||
|
||||
import MAX_SIGNED_31_BIT_INT from './maxSigned31BitInt';
|
||||
const valueCursor: StackCursor<mixed> = createCursor(null);
|
||||
|
||||
let rendererSigil;
|
||||
@@ -163,10 +157,7 @@ export function propagateContextChange(
|
||||
) {
|
||||
// Match! Schedule an update on this fiber.
|
||||
|
||||
if (
|
||||
fiber.tag === ClassComponent ||
|
||||
fiber.tag === ClassComponentLazy
|
||||
) {
|
||||
if (fiber.tag === ClassComponent) {
|
||||
// Schedule a force update on the work-in-progress.
|
||||
const update = createUpdate(renderExpirationTime);
|
||||
update.tag = ForceUpdate;
|
||||
@@ -177,17 +168,13 @@ export function propagateContextChange(
|
||||
enqueueUpdate(fiber, update);
|
||||
}
|
||||
|
||||
if (
|
||||
fiber.expirationTime === NoWork ||
|
||||
fiber.expirationTime > renderExpirationTime
|
||||
) {
|
||||
if (fiber.expirationTime < renderExpirationTime) {
|
||||
fiber.expirationTime = renderExpirationTime;
|
||||
}
|
||||
let alternate = fiber.alternate;
|
||||
if (
|
||||
alternate !== null &&
|
||||
(alternate.expirationTime === NoWork ||
|
||||
alternate.expirationTime > renderExpirationTime)
|
||||
alternate.expirationTime < renderExpirationTime
|
||||
) {
|
||||
alternate.expirationTime = renderExpirationTime;
|
||||
}
|
||||
@@ -196,22 +183,17 @@ export function propagateContextChange(
|
||||
let node = fiber.return;
|
||||
while (node !== null) {
|
||||
alternate = node.alternate;
|
||||
if (
|
||||
node.childExpirationTime === NoWork ||
|
||||
node.childExpirationTime > renderExpirationTime
|
||||
) {
|
||||
if (node.childExpirationTime < renderExpirationTime) {
|
||||
node.childExpirationTime = renderExpirationTime;
|
||||
if (
|
||||
alternate !== null &&
|
||||
(alternate.childExpirationTime === NoWork ||
|
||||
alternate.childExpirationTime > renderExpirationTime)
|
||||
alternate.childExpirationTime < renderExpirationTime
|
||||
) {
|
||||
alternate.childExpirationTime = renderExpirationTime;
|
||||
}
|
||||
} else if (
|
||||
alternate !== null &&
|
||||
(alternate.childExpirationTime === NoWork ||
|
||||
alternate.childExpirationTime > renderExpirationTime)
|
||||
alternate.childExpirationTime < renderExpirationTime
|
||||
) {
|
||||
alternate.childExpirationTime = renderExpirationTime;
|
||||
} else {
|
||||
@@ -284,11 +266,11 @@ export function readContext<T>(
|
||||
let resolvedObservedBits; // Avoid deopting on observable arguments or heterogeneous types.
|
||||
if (
|
||||
typeof observedBits !== 'number' ||
|
||||
observedBits === maxSigned31BitInt
|
||||
observedBits === MAX_SIGNED_31_BIT_INT
|
||||
) {
|
||||
// Observe all updates.
|
||||
lastContextWithAllBitsObserved = ((context: any): ReactContext<mixed>);
|
||||
resolvedObservedBits = maxSigned31BitInt;
|
||||
resolvedObservedBits = MAX_SIGNED_31_BIT_INT;
|
||||
} else {
|
||||
resolvedObservedBits = observedBits;
|
||||
}
|
||||
|
||||
@@ -31,12 +31,12 @@ export function markPendingPriorityLevel(
|
||||
// No other pending updates.
|
||||
root.earliestPendingTime = root.latestPendingTime = expirationTime;
|
||||
} else {
|
||||
if (earliestPendingTime > expirationTime) {
|
||||
if (earliestPendingTime < expirationTime) {
|
||||
// This is the earliest pending update.
|
||||
root.earliestPendingTime = expirationTime;
|
||||
} else {
|
||||
const latestPendingTime = root.latestPendingTime;
|
||||
if (latestPendingTime < expirationTime) {
|
||||
if (latestPendingTime > expirationTime) {
|
||||
// This is the latest pending update
|
||||
root.latestPendingTime = expirationTime;
|
||||
}
|
||||
@@ -65,12 +65,12 @@ export function markCommittedPriorityLevels(
|
||||
// Let's see if the previous latest known pending level was just flushed.
|
||||
const latestPendingTime = root.latestPendingTime;
|
||||
if (latestPendingTime !== NoWork) {
|
||||
if (latestPendingTime < earliestRemainingTime) {
|
||||
if (latestPendingTime > earliestRemainingTime) {
|
||||
// We've flushed all the known pending levels.
|
||||
root.earliestPendingTime = root.latestPendingTime = NoWork;
|
||||
} else {
|
||||
const earliestPendingTime = root.earliestPendingTime;
|
||||
if (earliestPendingTime < earliestRemainingTime) {
|
||||
if (earliestPendingTime > earliestRemainingTime) {
|
||||
// We've flushed the earliest known pending level. Set this to the
|
||||
// latest pending time.
|
||||
root.earliestPendingTime = root.latestPendingTime;
|
||||
@@ -92,7 +92,7 @@ export function markCommittedPriorityLevels(
|
||||
}
|
||||
|
||||
const latestSuspendedTime = root.latestSuspendedTime;
|
||||
if (earliestRemainingTime > latestSuspendedTime) {
|
||||
if (earliestRemainingTime < latestSuspendedTime) {
|
||||
// The earliest remaining level is later than all the suspended work. That
|
||||
// means we've flushed all the suspended work.
|
||||
root.earliestSuspendedTime = NoWork;
|
||||
@@ -106,7 +106,7 @@ export function markCommittedPriorityLevels(
|
||||
return;
|
||||
}
|
||||
|
||||
if (earliestRemainingTime < earliestSuspendedTime) {
|
||||
if (earliestRemainingTime > earliestSuspendedTime) {
|
||||
// The earliest remaining time is earlier than all the suspended work.
|
||||
// Treat it as a pending update.
|
||||
markPendingPriorityLevel(root, earliestRemainingTime);
|
||||
@@ -128,10 +128,10 @@ export function hasLowerPriorityWork(
|
||||
const latestPingedTime = root.latestPingedTime;
|
||||
return (
|
||||
(latestPendingTime !== NoWork &&
|
||||
latestPendingTime > erroredExpirationTime) ||
|
||||
latestPendingTime < erroredExpirationTime) ||
|
||||
(latestSuspendedTime !== NoWork &&
|
||||
latestSuspendedTime > erroredExpirationTime) ||
|
||||
(latestPingedTime !== NoWork && latestPingedTime > erroredExpirationTime)
|
||||
latestSuspendedTime < erroredExpirationTime) ||
|
||||
(latestPingedTime !== NoWork && latestPingedTime < erroredExpirationTime)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -143,8 +143,8 @@ export function isPriorityLevelSuspended(
|
||||
const latestSuspendedTime = root.latestSuspendedTime;
|
||||
return (
|
||||
earliestSuspendedTime !== NoWork &&
|
||||
expirationTime >= earliestSuspendedTime &&
|
||||
expirationTime <= latestSuspendedTime
|
||||
expirationTime <= earliestSuspendedTime &&
|
||||
expirationTime >= latestSuspendedTime
|
||||
);
|
||||
}
|
||||
|
||||
@@ -180,10 +180,10 @@ export function markSuspendedPriorityLevel(
|
||||
// No other suspended levels.
|
||||
root.earliestSuspendedTime = root.latestSuspendedTime = suspendedTime;
|
||||
} else {
|
||||
if (earliestSuspendedTime > suspendedTime) {
|
||||
if (earliestSuspendedTime < suspendedTime) {
|
||||
// This is the earliest suspended level.
|
||||
root.earliestSuspendedTime = suspendedTime;
|
||||
} else if (latestSuspendedTime < suspendedTime) {
|
||||
} else if (latestSuspendedTime > suspendedTime) {
|
||||
// This is the latest suspended level
|
||||
root.latestSuspendedTime = suspendedTime;
|
||||
}
|
||||
@@ -202,7 +202,7 @@ export function markPingedPriorityLevel(
|
||||
// is thrown out and not reused during the restarted render. One way to
|
||||
// invalidate the progressed work is to restart at expirationTime + 1.
|
||||
const latestPingedTime = root.latestPingedTime;
|
||||
if (latestPingedTime === NoWork || latestPingedTime < pingedTime) {
|
||||
if (latestPingedTime === NoWork || latestPingedTime > pingedTime) {
|
||||
root.latestPingedTime = pingedTime;
|
||||
}
|
||||
findNextExpirationTimeToWorkOn(pingedTime, root);
|
||||
@@ -212,7 +212,7 @@ function clearPing(root, completedTime) {
|
||||
// TODO: Track whether the root was pinged during the render phase. If so,
|
||||
// we need to make sure we don't lose track of it.
|
||||
const latestPingedTime = root.latestPingedTime;
|
||||
if (latestPingedTime !== NoWork && latestPingedTime <= completedTime) {
|
||||
if (latestPingedTime !== NoWork && latestPingedTime >= completedTime) {
|
||||
root.latestPingedTime = NoWork;
|
||||
}
|
||||
}
|
||||
@@ -225,18 +225,10 @@ export function findEarliestOutstandingPriorityLevel(
|
||||
|
||||
const earliestPendingTime = root.earliestPendingTime;
|
||||
const earliestSuspendedTime = root.earliestSuspendedTime;
|
||||
if (
|
||||
earliestExpirationTime === NoWork ||
|
||||
(earliestPendingTime !== NoWork &&
|
||||
earliestPendingTime < earliestExpirationTime)
|
||||
) {
|
||||
if (earliestPendingTime > earliestExpirationTime) {
|
||||
earliestExpirationTime = earliestPendingTime;
|
||||
}
|
||||
if (
|
||||
earliestExpirationTime === NoWork ||
|
||||
(earliestSuspendedTime !== NoWork &&
|
||||
earliestSuspendedTime < earliestExpirationTime)
|
||||
) {
|
||||
if (earliestSuspendedTime > earliestExpirationTime) {
|
||||
earliestExpirationTime = earliestSuspendedTime;
|
||||
}
|
||||
return earliestExpirationTime;
|
||||
@@ -247,7 +239,7 @@ export function didExpireAtExpirationTime(
|
||||
currentTime: ExpirationTime,
|
||||
): void {
|
||||
const expirationTime = root.expirationTime;
|
||||
if (expirationTime !== NoWork && currentTime >= expirationTime) {
|
||||
if (expirationTime !== NoWork && currentTime <= expirationTime) {
|
||||
// The root has expired. Flush all work up to the current time.
|
||||
root.nextExpirationTimeToWorkOn = currentTime;
|
||||
}
|
||||
@@ -269,7 +261,7 @@ function findNextExpirationTimeToWorkOn(completedExpirationTime, root) {
|
||||
if (
|
||||
nextExpirationTimeToWorkOn === NoWork &&
|
||||
(completedExpirationTime === NoWork ||
|
||||
latestSuspendedTime > completedExpirationTime)
|
||||
latestSuspendedTime < completedExpirationTime)
|
||||
) {
|
||||
// The lowest priority suspended work is the work most likely to be
|
||||
// committed next. Let's start rendering it again, so that if it times out,
|
||||
@@ -278,11 +270,7 @@ function findNextExpirationTimeToWorkOn(completedExpirationTime, root) {
|
||||
}
|
||||
|
||||
let expirationTime = nextExpirationTimeToWorkOn;
|
||||
if (
|
||||
expirationTime !== NoWork &&
|
||||
earliestSuspendedTime !== NoWork &&
|
||||
earliestSuspendedTime < expirationTime
|
||||
) {
|
||||
if (expirationTime !== NoWork && earliestSuspendedTime > expirationTime) {
|
||||
// Expire using the earliest known expiration time.
|
||||
expirationTime = earliestSuspendedTime;
|
||||
}
|
||||
|
||||
@@ -23,15 +23,10 @@ import {
|
||||
findCurrentHostFiberWithNoPortals,
|
||||
} from 'react-reconciler/reflection';
|
||||
import * as ReactInstanceMap from 'shared/ReactInstanceMap';
|
||||
import {
|
||||
HostComponent,
|
||||
ClassComponent,
|
||||
ClassComponentLazy,
|
||||
} from 'shared/ReactWorkTags';
|
||||
import {HostComponent, ClassComponent} from 'shared/ReactWorkTags';
|
||||
import getComponentName from 'shared/getComponentName';
|
||||
import invariant from 'shared/invariant';
|
||||
import warningWithoutStack from 'shared/warningWithoutStack';
|
||||
import {getResultFromResolvedLazyComponent} from 'shared/ReactLazyComponent';
|
||||
|
||||
import {getPublicInstance} from './ReactFiberHostConfig';
|
||||
import {
|
||||
@@ -57,6 +52,7 @@ import {
|
||||
syncUpdates,
|
||||
interactiveUpdates,
|
||||
flushInteractiveUpdates,
|
||||
flushPassiveEffects,
|
||||
} from './ReactFiberScheduler';
|
||||
import {createUpdate, enqueueUpdate} from './ReactUpdateQueue';
|
||||
import ReactFiberInstrumentation from './ReactFiberInstrumentation';
|
||||
@@ -106,11 +102,6 @@ function getContextForSubtree(
|
||||
if (isLegacyContextProvider(Component)) {
|
||||
return processChildContext(fiber, Component, parentContext);
|
||||
}
|
||||
} else if (fiber.tag === ClassComponentLazy) {
|
||||
const Component = getResultFromResolvedLazyComponent(fiber.type);
|
||||
if (isLegacyContextProvider(Component)) {
|
||||
return processChildContext(fiber, Component, parentContext);
|
||||
}
|
||||
}
|
||||
|
||||
return parentContext;
|
||||
@@ -155,9 +146,11 @@ function scheduleRootUpdate(
|
||||
);
|
||||
update.callback = callback;
|
||||
}
|
||||
enqueueUpdate(current, update);
|
||||
|
||||
flushPassiveEffects();
|
||||
enqueueUpdate(current, update);
|
||||
scheduleWork(current, expirationTime);
|
||||
|
||||
return expirationTime;
|
||||
}
|
||||
|
||||
|
||||
573
packages/react-reconciler/src/ReactFiberScheduler.js
vendored
573
packages/react-reconciler/src/ReactFiberScheduler.js
vendored
File diff suppressed because it is too large
Load Diff
@@ -7,19 +7,23 @@
|
||||
* @flow
|
||||
*/
|
||||
|
||||
import type {Fiber} from './ReactFiber';
|
||||
import type {ExpirationTime} from './ReactFiberExpirationTime';
|
||||
|
||||
export type SuspenseState = {|
|
||||
// Whether a component in the child subtree already suspended. If true,
|
||||
// subsequent suspends should bubble up to the next boundary.
|
||||
alreadyCaptured: boolean,
|
||||
// Whether the boundary renders the primary or fallback children. This is
|
||||
// separate from `alreadyCaptured` because outside of strict mode, when a
|
||||
// boundary times out, the first commit renders the primary children in an
|
||||
// incomplete state, then performs a second commit to switch the fallback.
|
||||
// In that first commit, `alreadyCaptured` is false and `didTimeout` is true.
|
||||
didTimeout: boolean,
|
||||
// The time at which the boundary timed out. This is separate from
|
||||
// `didTimeout` because it's not set unless the boundary actually commits.
|
||||
timedOutAt: ExpirationTime,
|
||||
|};
|
||||
|
||||
export function shouldCaptureSuspense(
|
||||
current: Fiber | null,
|
||||
workInProgress: Fiber,
|
||||
): boolean {
|
||||
// In order to capture, the Suspense component must have a fallback prop.
|
||||
if (workInProgress.memoizedProps.fallback === undefined) {
|
||||
return false;
|
||||
}
|
||||
// If it was the primary children that just suspended, capture and render the
|
||||
// fallback. Otherwise, don't capture and bubble to the next boundary.
|
||||
const nextState: SuspenseState | null = workInProgress.memoizedState;
|
||||
return nextState === null;
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user