diff --git a/.flowconfig b/.flowconfig index d15db1c9ab..bad57bc52f 100644 --- a/.flowconfig +++ b/.flowconfig @@ -1,13 +1,13 @@ [ignore] -.*/examples/.* -.*/build/.* -.*/node_modules/y18n/.* -.*/__mocks__/.* -.*/__tests__/.* +/examples/.* +/build/.* +/.*/node_modules/y18n/.* +/.*/__mocks__/.* +/.*/__tests__/.* # Ignore Docs -.*/docs/.* +/.*/docs/.* [include] @@ -21,17 +21,17 @@ module.system=haste esproposal.class_static_fields=enable esproposal.class_instance_fields=enable -experimental.strict_type_args=true - munge_underscores=false suppress_type=$FlowIssue suppress_type=$FlowFixMe suppress_type=$FixMe +suppress_type=$FlowExpectedError -suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(>=0\\.\\(2[0-4]\\|1[0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*\\)?)\\) -suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(>=0\\.\\(2[0-4]\\|1[0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*\\)?)\\)? #[0-9]+ +suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(>=0\\.\\(3[0-1]\\|[1-2][0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*www[a-z,_]*\\)?)\\) +suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(>=0\\.\\(3[0-1]\\|[1-2][0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*www[a-z,_]*\\)?)\\)?:? #[0-9]+ suppress_comment=\\(.\\|\n\\)*\\$FlowFixedInNextDeploy +suppress_comment=\\(.\\|\n\\)*\\$FlowExpectedError [version] -^0.27.0 +^0.31.0 diff --git a/.gitignore b/.gitignore index 2fbbce71ea..21728725b2 100644 --- a/.gitignore +++ b/.gitignore @@ -18,6 +18,7 @@ docs/js/* docs/downloads/*.zip docs/vendor/bundle examples/shared/*.js +examples/**/bundle.js test/the-files-to-test.generated.js *.log* chrome-user-data diff --git a/.travis.yml b/.travis.yml index e1188bf3f3..82ecf2cc87 100644 --- a/.travis.yml +++ b/.travis.yml @@ -28,8 +28,8 @@ script: GH_PAGES_DIR="$TRAVIS_BUILD_DIR"/../react-gh-pages echo "machine github.com login reactjs-bot password $GITHUB_TOKEN" >~/.netrc - git config --global user.name "Travis CI" - git config --global user.email "travis@reactjs.org" + git config --global user.name "$GITHUB_USER_NAME" + git config --global user.email "$GITHUB_USER_EMAIL" git clone --branch gh-pages --depth=50 \ https://reactjs-bot@github.com/facebook/react.git \ @@ -71,20 +71,40 @@ script: fi elif [ "$TEST_TYPE" = test ]; then set -e - # Disabling coverage because it's broken: - # https://travis-ci.org/facebook/react/jobs/128163922 - if false; then - ./node_modules/.bin/grunt jest:coverage - cat ./coverage/lcov.info | ./node_modules/.bin/coveralls - else - ./node_modules/.bin/grunt jest:normal - fi + ./node_modules/.bin/grunt jest:coverage + cat ./coverage/lcov.info | ./node_modules/.bin/coveralls + echo 'Testing in server-render (HTML generation) mode...' printf '\nmodule.exports.useCreateElement = false;\n' \ >> src/renderers/dom/shared/ReactDOMFeatureFlags.js ./node_modules/.bin/grunt jest:normal git checkout -- src/renderers/dom/shared/ReactDOMFeatureFlags.js + + echo 'Testing in fiber mode...' + printf '\nmodule.exports.useFiber = true;\n' \ + >> src/renderers/dom/shared/ReactDOMFeatureFlags.js + FIBER_TESTS=`\ + NODE_ENV=test node node_modules/jest/bin/jest --json | \ + node -e "\ + var data = JSON.parse(require('fs').readFileSync('/dev/stdin', 'utf8')); \ + console.log(data.numPassedTests + '/' + data.numTotalTests)\ + "\ + ` + git checkout -- src/renderers/dom/shared/ReactDOMFeatureFlags.js + node scripts/facts-tracker/index.js \ + "fiber-tests" "$FIBER_TESTS" + ./node_modules/.bin/gulp react:extract-errors + elif [ "$TEST_TYPE" = flow ]; then + set -e + ./node_modules/.bin/grunt flow + + ALL_FILES=`find src -name '*.js' | grep -v umd/ | grep -v __tests__ | grep -v __mocks__` + COUNT_ALL_FILES=`echo "$ALL_FILES" | wc -l` + COUNT_WITH_FLOW=`grep '@flow' $ALL_FILES | perl -pe 's/:.+//' | wc -l` + node scripts/facts-tracker/index.js \ + "flow-files" "$COUNT_WITH_FLOW/$COUNT_ALL_FILES" + else ./node_modules/.bin/grunt $TEST_TYPE fi diff --git a/Gruntfile.js b/Gruntfile.js index 0932add89c..71f3ffd258 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -117,12 +117,41 @@ module.exports = function(grunt) { 'build-modules', 'browserify:addonsMin', ]); + grunt.registerTask('build:dom', [ + 'build-modules', + 'version-check', + 'browserify:dom', + ]); + grunt.registerTask('build:dom-min', [ + 'build-modules', + 'version-check', + 'browserify:domMin', + ]); + grunt.registerTask('build:dom-server', [ + 'build-modules', + 'version-check', + 'browserify:domServer', + ]); + grunt.registerTask('build:dom-server-min', [ + 'build-modules', + 'version-check', + 'browserify:domServerMin', + ]); + grunt.registerTask('build:dom-fiber', [ + 'build-modules', + 'version-check', + 'browserify:domFiber', + ]); + grunt.registerTask('build:dom-fiber-min', [ + 'build-modules', + 'version-check', + 'browserify:domFiberMin', + ]); grunt.registerTask('build:npm-react', [ 'version-check', 'build-modules', 'npm-react:release', ]); - grunt.registerTask('build:react-dom', require('./grunt/tasks/react-dom')); var jestTasks = require('./grunt/tasks/jest'); grunt.registerTask('jest:normal', jestTasks.normal); @@ -141,7 +170,12 @@ module.exports = function(grunt) { 'browserify:addons', 'browserify:min', 'browserify:addonsMin', - 'build:react-dom', + 'browserify:dom', + 'browserify:domMin', + 'browserify:domServer', + 'browserify:domServerMin', + 'browserify:domFiber', + 'browserify:domFiberMin', 'npm-react:release', 'npm-react:pack', 'npm-react-dom:release', diff --git a/docs/warnings/invalid-aria-prop.md b/docs/warnings/invalid-aria-prop.md new file mode 100644 index 0000000000..53ebdd9bc4 --- /dev/null +++ b/docs/warnings/invalid-aria-prop.md @@ -0,0 +1,11 @@ +--- +title: Invalid ARIA Prop Warning +layout: single +permalink: warnings/invalid-aria-prop.html +--- + +The invalid-aria-prop warning will fire if you attempt to render a DOM element with an aria-* prop that does not exist in the Web Accessibility Initiative (WAI) Accessible Rich Internet Application (ARIA) [specification](https://www.w3.org/TR/wai-aria-1.1/#states_and_properties). + +1. If you feel that you are using a valid prop, check the spelling carefully. `aria-labelledby` and `aria-activedescendant` are often misspelled. + +2. React does not yet recognize the attribute you specified. This will likely be fixed in a future version of React. However, React currently strips all unknown attributes, so specifying them in your React app will not cause them to be rendered \ No newline at end of file diff --git a/examples/fiber/index.html b/examples/fiber/index.html index c507993794..c90e7ce246 100644 --- a/examples/fiber/index.html +++ b/examples/fiber/index.html @@ -18,7 +18,7 @@

- + '); expect(escaped).not.toContain('<'); expect(escaped).not.toContain('>'); diff --git a/src/renderers/dom/shared/__tests__/quoteAttributeValueForBrowser-test.js b/src/renderers/dom/shared/__tests__/quoteAttributeValueForBrowser-test.js index 5d7bc86016..aeba0bc4f7 100644 --- a/src/renderers/dom/shared/__tests__/quoteAttributeValueForBrowser-test.js +++ b/src/renderers/dom/shared/__tests__/quoteAttributeValueForBrowser-test.js @@ -11,16 +11,16 @@ 'use strict'; -describe('quoteAttributeValueForBrowser', function() { +describe('quoteAttributeValueForBrowser', () => { var quoteAttributeValueForBrowser = require('quoteAttributeValueForBrowser'); - it('should escape boolean to string', function() { + it('should escape boolean to string', () => { expect(quoteAttributeValueForBrowser(true)).toBe('"true"'); expect(quoteAttributeValueForBrowser(false)).toBe('"false"'); }); - it('should escape object to string', function() { + it('should escape object to string', () => { var escaped = quoteAttributeValueForBrowser({ toString: function() { return 'ponys'; @@ -30,11 +30,11 @@ describe('quoteAttributeValueForBrowser', function() { expect(escaped).toBe('"ponys"'); }); - it('should escape number to string', function() { + it('should escape number to string', () => { expect(quoteAttributeValueForBrowser(42)).toBe('"42"'); }); - it('should escape string', function() { + it('should escape string', () => { var escaped = quoteAttributeValueForBrowser(''); expect(escaped).not.toContain('<'); expect(escaped).not.toContain('>'); diff --git a/src/renderers/dom/shared/hooks/ReactDOMInvalidARIAHook.js b/src/renderers/dom/shared/hooks/ReactDOMInvalidARIAHook.js new file mode 100644 index 0000000000..6e2fdcfa36 --- /dev/null +++ b/src/renderers/dom/shared/hooks/ReactDOMInvalidARIAHook.js @@ -0,0 +1,119 @@ +/** + * Copyright 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactDOMInvalidARIAHook + */ + +'use strict'; + +var DOMProperty = require('DOMProperty'); +var ReactComponentTreeHook = require('ReactComponentTreeHook'); + +var warning = require('warning'); + +var warnedProperties = {}; +var rARIA = new RegExp('^(aria)-[' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$'); + +function validateProperty(tagName, name, debugID) { + if ( + warnedProperties.hasOwnProperty(name) + && warnedProperties[name] + ) { + return true; + } + + if (rARIA.test(name)) { + var lowerCasedName = name.toLowerCase(); + var standardName = + DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? + DOMProperty.getPossibleStandardName[lowerCasedName] : + null; + + // If this is an aria-* attribute, but is not listed in the known DOM + // DOM properties, then it is an invalid aria-* attribute. + if (standardName == null) { + warnedProperties[name] = true; + return false; + } + // aria-* attributes should be lowercase; suggest the lowercase version. + if (name !== standardName) { + warning( + false, + 'Unknown ARIA attribute %s. Did you mean %s?%s', + name, + standardName, + ReactComponentTreeHook.getStackAddendumByID(debugID) + ); + warnedProperties[name] = true; + return true; + } + } + + return true; +} + +function warnInvalidARIAProps(debugID, element) { + const invalidProps = []; + + for (var key in element.props) { + var isValid = validateProperty(element.type, key, debugID); + if (!isValid) { + invalidProps.push(key); + } + } + + const unknownPropString = invalidProps + .map(prop => '`' + prop + '`') + .join(', '); + + if (invalidProps.length === 1) { + warning( + false, + 'Invalid aria prop %s on <%s> tag. ' + + 'For details, see https://fb.me/invalid-aria-prop%s', + unknownPropString, + element.type, + ReactComponentTreeHook.getStackAddendumByID(debugID) + ); + } else if (invalidProps.length > 1) { + warning( + false, + 'Invalid aria props %s on <%s> tag. ' + + 'For details, see https://fb.me/invalid-aria-prop%s', + unknownPropString, + element.type, + ReactComponentTreeHook.getStackAddendumByID(debugID) + ); + } +} + +function handleElement(debugID, element) { + if (element == null || typeof element.type !== 'string') { + return; + } + if (element.type.indexOf('-') >= 0 || element.props.is) { + return; + } + + warnInvalidARIAProps(debugID, element); +} + +var ReactDOMInvalidARIAHook = { + onBeforeMountComponent(debugID, element) { + if (__DEV__) { + handleElement(debugID, element); + } + }, + onBeforeUpdateComponent(debugID, element) { + if (__DEV__) { + handleElement(debugID, element); + } + }, +}; + +module.exports = ReactDOMInvalidARIAHook; diff --git a/src/renderers/native/ReactNative.js b/src/renderers/native/ReactNative.js index 0305ff2447..23648da925 100644 --- a/src/renderers/native/ReactNative.js +++ b/src/renderers/native/ReactNative.js @@ -16,7 +16,6 @@ var ReactNativeComponentTree = require('ReactNativeComponentTree'); var ReactNativeDefaultInjection = require('ReactNativeDefaultInjection'); -var ReactElement = require('ReactElement'); var ReactNativeMount = require('ReactNativeMount'); var ReactUpdates = require('ReactUpdates'); @@ -25,7 +24,7 @@ var findNodeHandle = require('findNodeHandle'); ReactNativeDefaultInjection.inject(); var render = function( - element: ReactElement, + element: ReactElement, mountInto: number, callback?: ?(() => void) ): ?ReactComponent { diff --git a/src/renderers/native/ReactNativeDOMIDOperations.js b/src/renderers/native/ReactNativeDOMIDOperations.js index 0d3755be3b..4c38f3c576 100644 --- a/src/renderers/native/ReactNativeDOMIDOperations.js +++ b/src/renderers/native/ReactNativeDOMIDOperations.js @@ -11,7 +11,6 @@ 'use strict'; var ReactNativeComponentTree = require('ReactNativeComponentTree'); -var ReactMultiChildUpdateTypes = require('ReactMultiChildUpdateTypes'); var UIManager = require('UIManager'); /** @@ -41,12 +40,12 @@ var dangerouslyProcessChildrenUpdates = function(inst, childrenUpdates) { for (var i = 0; i < childrenUpdates.length; i++) { var update = childrenUpdates[i]; - if (update.type === ReactMultiChildUpdateTypes.MOVE_EXISTING) { + if (update.type === 'MOVE_EXISTING') { (moveFromIndices || (moveFromIndices = [])).push(update.fromIndex); (moveToIndices || (moveToIndices = [])).push(update.toIndex); - } else if (update.type === ReactMultiChildUpdateTypes.REMOVE_NODE) { + } else if (update.type === 'REMOVE_NODE') { (removeAtIndices || (removeAtIndices = [])).push(update.fromIndex); - } else if (update.type === ReactMultiChildUpdateTypes.INSERT_MARKUP) { + } else if (update.type === 'INSERT_MARKUP') { var mountImage = update.content; var tag = mountImage; (addAtIndices || (addAtIndices = [])).push(update.toIndex); diff --git a/src/renderers/native/ReactNativeDefaultInjection.js b/src/renderers/native/ReactNativeDefaultInjection.js index 42f3d115b4..4d15ab5771 100644 --- a/src/renderers/native/ReactNativeDefaultInjection.js +++ b/src/renderers/native/ReactNativeDefaultInjection.js @@ -22,9 +22,9 @@ require('InitializeJavaScriptAppEngine'); var EventPluginHub = require('EventPluginHub'); var EventPluginUtils = require('EventPluginUtils'); var RCTEventEmitter = require('RCTEventEmitter'); +var React = require('React'); var ReactComponentEnvironment = require('ReactComponentEnvironment'); var ReactDefaultBatchingStrategy = require('ReactDefaultBatchingStrategy'); -var ReactElement = require('ReactElement'); var ReactEmptyComponent = require('ReactEmptyComponent'); var ReactNativeBridgeEventPlugin = require('ReactNativeBridgeEventPlugin'); var ReactHostComponent = require('ReactHostComponent'); @@ -83,7 +83,7 @@ function inject() { // Can't import View at the top because it depends on React to make its composite var View = require('View'); return new ReactSimpleEmptyComponent( - ReactElement.createElement(View, { + React.createElement(View, { collapsable: true, style: { position: 'absolute' }, }), diff --git a/src/renderers/native/ReactNativeEventEmitter.js b/src/renderers/native/ReactNativeEventEmitter.js index 699b092697..0c4c3a7da1 100644 --- a/src/renderers/native/ReactNativeEventEmitter.js +++ b/src/renderers/native/ReactNativeEventEmitter.js @@ -11,7 +11,6 @@ */ 'use strict'; -var EventConstants = require('EventConstants'); var EventPluginHub = require('EventPluginHub'); var EventPluginRegistry = require('EventPluginRegistry'); var ReactEventEmitterMixin = require('ReactEventEmitterMixin'); @@ -21,8 +20,6 @@ var ReactUpdates = require('ReactUpdates'); var warning = require('warning'); -var topLevelTypes = EventConstants.topLevelTypes; - /** * Version of `ReactBrowserEventEmitter` that works on the receiving side of a * serialized worker boundary. @@ -186,8 +183,8 @@ var ReactNativeEventEmitter = { changedIndices: Array ) { var changedTouches = - eventTopLevelType === topLevelTypes.topTouchEnd || - eventTopLevelType === topLevelTypes.topTouchCancel ? + eventTopLevelType === 'topTouchEnd' || + eventTopLevelType === 'topTouchCancel' ? removeTouchesAtIndices(touches, changedIndices) : touchSubsequence(touches, changedIndices); diff --git a/src/renderers/native/ReactNativeMount.js b/src/renderers/native/ReactNativeMount.js index 080fe428f4..2d508631ab 100644 --- a/src/renderers/native/ReactNativeMount.js +++ b/src/renderers/native/ReactNativeMount.js @@ -11,7 +11,7 @@ */ 'use strict'; -var ReactElement = require('ReactElement'); +var React = require('React'); var ReactInstrumentation = require('ReactInstrumentation'); var ReactNativeContainerInfo = require('ReactNativeContainerInfo'); var ReactNativeTagHandles = require('ReactNativeTagHandles'); @@ -35,9 +35,9 @@ if (__DEV__) { TopLevelWrapper.displayName = 'TopLevelWrapper'; } TopLevelWrapper.prototype.render = function() { - // this.props is actually a ReactElement - return this.props; + return this.props.child; }; +TopLevelWrapper.isReactTopLevelWrapper = true; /** * Mounts this component and inserts it into the DOM. @@ -99,25 +99,20 @@ var ReactNativeMount = { * @param {containerTag} containerView Handle to native view tag */ renderComponent: function( - nextElement: ReactElement, + nextElement: ReactElement<*>, containerTag: number, callback?: ?(() => void) ): ?ReactComponent { - var nextWrappedElement = new ReactElement( + var nextWrappedElement = React.createElement( TopLevelWrapper, - null, - null, - null, - null, - null, - nextElement + { child: nextElement } ); var topRootNodeID = containerTag; var prevComponent = ReactNativeMount._instancesByContainerID[topRootNodeID]; if (prevComponent) { var prevWrappedElement = prevComponent._currentElement; - var prevElement = prevWrappedElement.props; + var prevElement = prevWrappedElement.props.child; if (shouldUpdateReactComponent(prevElement, nextElement)) { ReactUpdateQueue.enqueueElementInternal(prevComponent, nextWrappedElement, emptyObject); if (callback) { diff --git a/src/renderers/native/ReactNativeReconcileTransaction.js b/src/renderers/native/ReactNativeReconcileTransaction.js index 9f758fd909..de34a657b5 100644 --- a/src/renderers/native/ReactNativeReconcileTransaction.js +++ b/src/renderers/native/ReactNativeReconcileTransaction.js @@ -122,7 +122,7 @@ var Mixin = { Object.assign( ReactNativeReconcileTransaction.prototype, - Transaction.Mixin, + Transaction, ReactNativeReconcileTransaction, Mixin ); diff --git a/src/renderers/native/ReactNativeTagHandles.js b/src/renderers/native/ReactNativeTagHandles.js index 2a4d7bd010..d0c7bb2685 100644 --- a/src/renderers/native/ReactNativeTagHandles.js +++ b/src/renderers/native/ReactNativeTagHandles.js @@ -48,7 +48,7 @@ var ReactNativeTagHandles = { ); }, - reactTagIsNativeTopRootID: function(reactTag: number): bool { + reactTagIsNativeTopRootID: function(reactTag: number): boolean { // We reserve all tags that are 1 mod 10 for native root views return reactTag % 10 === 1; }, diff --git a/src/renderers/native/ReactNativeTreeTraversal.js b/src/renderers/native/ReactNativeTreeTraversal.js index 52bc9f882a..4e98fa8950 100644 --- a/src/renderers/native/ReactNativeTreeTraversal.js +++ b/src/renderers/native/ReactNativeTreeTraversal.js @@ -82,10 +82,10 @@ function traverseTwoPhase(inst, fn, arg) { } var i; for (i = path.length; i-- > 0;) { - fn(path[i], false, arg); + fn(path[i], 'captured', arg); } for (i = 0; i < path.length; i++) { - fn(path[i], true, arg); + fn(path[i], 'bubbled', arg); } } @@ -110,10 +110,10 @@ function traverseEnterLeave(from, to, fn, argFrom, argTo) { } var i; for (i = 0; i < pathFrom.length; i++) { - fn(pathFrom[i], true, argFrom); + fn(pathFrom[i], 'bubbled', argFrom); } for (i = pathTo.length; i-- > 0;) { - fn(pathTo[i], false, argTo); + fn(pathTo[i], 'captured', argTo); } } diff --git a/src/renderers/native/__mocks__/UIManager.js b/src/renderers/native/__mocks__/UIManager.js index ddcba12ca0..dffb8fd9f6 100644 --- a/src/renderers/native/__mocks__/UIManager.js +++ b/src/renderers/native/__mocks__/UIManager.js @@ -18,6 +18,52 @@ var RCTUIManager = { updateView: jest.fn(), removeSubviewsFromContainerWithID: jest.fn(), replaceExistingNonRootView: jest.fn(), + customBubblingEventTypes: { + topBlur: { + phasedRegistrationNames: { + bubbled: 'onBlur', + captured: 'onBlurCapture', + }, + }, + topFocus: { + phasedRegistrationNames: { + bubbled: 'onFocus', + captured: 'onFocusCapture', + }, + }, + topTouchCancel: { + phasedRegistrationNames: { + bubbled: 'onTouchCancel', + captured: 'onTouchCancelCapture', + }, + }, + topTouchEnd: { + phasedRegistrationNames: { + bubbled: 'onTouchEnd', + captured: 'onTouchEndCapture', + }, + }, + topTouchMove: { + phasedRegistrationNames: { + bubbled: 'onTouchMove', + captured: 'onTouchMoveCapture', + }, + }, + topTouchStart: { + phasedRegistrationNames: { + bubbled: 'onTouchStart', + captured: 'onTouchStartCapture', + }, + }, + }, + customDirectEventTypes: { + topAccessibilityTap: { + registrationName: 'onAccessibilityTap', + }, + topTextLayout: { + registrationName: 'onTextLayout', + }, + }, }; module.exports = RCTUIManager; diff --git a/src/renderers/native/__mocks__/deepDiffer.js b/src/renderers/native/__mocks__/deepDiffer.js index cc58e4b328..34e4da74a0 100644 --- a/src/renderers/native/__mocks__/deepDiffer.js +++ b/src/renderers/native/__mocks__/deepDiffer.js @@ -11,7 +11,7 @@ // TODO: Move deepDiffer into react -var deepDiffer = function(one: any, two: any): bool { +var deepDiffer = function(one: any, two: any): boolean { if (one === two) { // Short circuit on identical object references instead of traversing them. return false; diff --git a/src/renderers/native/__tests__/ReactNativeAttributePayload-test.js b/src/renderers/native/__tests__/ReactNativeAttributePayload-test.js index 85d4283d13..568764dc0a 100644 --- a/src/renderers/native/__tests__/ReactNativeAttributePayload-test.js +++ b/src/renderers/native/__tests__/ReactNativeAttributePayload-test.js @@ -9,17 +9,12 @@ */ 'use strict'; -jest.unmock('ReactNativeAttributePayload'); -jest.unmock('ReactNativePropRegistry'); -// jest.dontMock('deepDiffer'); -// jest.dontMock('flattenStyle'); - var ReactNativeAttributePayload = require('ReactNativeAttributePayload'); var ReactNativePropRegistry = require('ReactNativePropRegistry'); var diff = ReactNativeAttributePayload.diff; -describe('ReactNativeAttributePayload', function() { +describe('ReactNativeAttributePayload', () => { it('should work with simple example', () => { expect(diff( diff --git a/src/renderers/native/__tests__/ReactNativeEvents-test.js b/src/renderers/native/__tests__/ReactNativeEvents-test.js new file mode 100644 index 0000000000..8110dcff20 --- /dev/null +++ b/src/renderers/native/__tests__/ReactNativeEvents-test.js @@ -0,0 +1,89 @@ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @emails react-core + */ + +'use strict'; + +var RCTEventEmitter; +var React; +var ReactErrorUtils; +var ReactNative; +var UIManager; +var createReactNativeComponentClass; + +beforeEach(() => { + jest.resetModuleRegistry(); + + RCTEventEmitter = require('RCTEventEmitter'); + React = require('React'); + ReactErrorUtils = require('ReactErrorUtils'); + ReactNative = require('ReactNative'); + UIManager = require('UIManager'); + createReactNativeComponentClass = require('createReactNativeComponentClass'); + + // Ensure errors from event callbacks are properly surfaced (otherwise, + // jest/jsdom swallows them when we do the .dispatchEvent call) + ReactErrorUtils.invokeGuardedCallback = + ReactErrorUtils.invokeGuardedCallbackWithCatch; +}); + +it('handles events', () => { + expect(RCTEventEmitter.register.mock.calls.length).toBe(1); + var EventEmitter = RCTEventEmitter.register.mock.calls[0][0]; + var View = createReactNativeComponentClass({ + validAttributes: { foo: true }, + uiViewClassName: 'View', + }); + + + var log = []; + ReactNative.render( + log.push('outer touchend')} + onTouchEndCapture={() => log.push('outer touchend capture')} + onTouchStart={() => log.push('outer touchstart')} + onTouchStartCapture={() => log.push('outer touchstart capture')}> + log.push('inner touchend capture')} + onTouchEnd={() => log.push('inner touchend')} + onTouchStartCapture={() => log.push('inner touchstart capture')} + onTouchStart={() => log.push('inner touchstart')} + /> + , + 1 + ); + + expect(UIManager.createView.mock.calls.length).toBe(2); + var innerTag = UIManager.createView.mock.calls[1][0]; + + EventEmitter.receiveTouches( + 'topTouchStart', + [{target: innerTag, identifier: 17}], + [0] + ); + EventEmitter.receiveTouches( + 'topTouchEnd', + [{target: innerTag, identifier: 17}], + [0] + ); + + expect(log).toEqual([ + 'outer touchstart capture', + 'inner touchstart capture', + 'inner touchstart', + 'outer touchstart', + 'outer touchend capture', + 'inner touchend capture', + 'inner touchend', + 'outer touchend', + ]); +}); diff --git a/src/renderers/native/__tests__/ReactNativeMount-test.js b/src/renderers/native/__tests__/ReactNativeMount-test.js index 74f4f7f57f..aa433e45e9 100644 --- a/src/renderers/native/__tests__/ReactNativeMount-test.js +++ b/src/renderers/native/__tests__/ReactNativeMount-test.js @@ -16,15 +16,15 @@ var ReactNative; var createReactNativeComponentClass; var UIManager; -describe('ReactNative', function() { - beforeEach(function() { +describe('ReactNative', () => { + beforeEach(() => { React = require('React'); ReactNative = require('ReactNative'); UIManager = require('UIManager'); createReactNativeComponentClass = require('createReactNativeComponentClass'); }); - it('should be able to create and render a native component', function() { + it('should be able to create and render a native component', () => { var View = createReactNativeComponentClass({ validAttributes: { foo: true }, uiViewClassName: 'View', @@ -37,7 +37,7 @@ describe('ReactNative', function() { expect(UIManager.updateView).not.toBeCalled(); }); - it('should be able to create and update a native component', function() { + it('should be able to create and update a native component', () => { var View = createReactNativeComponentClass({ validAttributes: { foo: true }, uiViewClassName: 'View', diff --git a/src/renderers/noop/ReactNoop.js b/src/renderers/noop/ReactNoop.js index 8404cf159b..ff316945ec 100644 --- a/src/renderers/noop/ReactNoop.js +++ b/src/renderers/noop/ReactNoop.js @@ -20,18 +20,22 @@ 'use strict'; import type { Fiber } from 'ReactFiber'; +import type { UpdateQueue } from 'ReactFiberUpdateQueue'; import type { HostChildren } from 'ReactFiberReconciler'; var ReactFiberReconciler = require('ReactFiberReconciler'); +var { + AnimationPriority, +} = require('ReactPriorityLevel'); -var scheduledHighPriCallback = null; -var scheduledLowPriCallback = null; +var scheduledAnimationCallback = null; +var scheduledDeferredCallback = null; const TERMINAL_TAG = 99; type Container = { rootID: number, children: Array }; -type Props = { }; -type Instance = { tag: 99, type: string, id: number, children: Array }; +type Props = { prop: any }; +type Instance = { tag: 99, type: string, id: number, children: Array, prop: any }; var instanceCounter = 0; @@ -58,17 +62,16 @@ function flattenChildren(children : HostChildren) { var NoopRenderer = ReactFiberReconciler({ updateContainer(containerInfo : Container, children : HostChildren) : void { - console.log('Update container #' + containerInfo.rootID); containerInfo.children = flattenChildren(children); }, createInstance(type : string, props : Props, children : HostChildren) : Instance { - console.log('Create instance #' + instanceCounter); const inst = { tag: TERMINAL_TAG, id: instanceCounter++, type: type, children: flattenChildren(children), + prop: props.prop, }; // Hide from unit tests Object.defineProperty(inst, 'tag', { value: inst.tag, enumerable: false }); @@ -77,25 +80,23 @@ var NoopRenderer = ReactFiberReconciler({ }, prepareUpdate(instance : Instance, oldProps : Props, newProps : Props, children : HostChildren) : boolean { - console.log('Prepare for update on #' + instance.id); return true; }, commitUpdate(instance : Instance, oldProps : Props, newProps : Props, children : HostChildren) : void { - console.log('Commit update on #' + instance.id); instance.children = flattenChildren(children); + instance.prop = newProps.prop; }, deleteInstance(instance : Instance) : void { - console.log('Delete #' + instance.id); }, - scheduleHighPriCallback(callback) { - scheduledHighPriCallback = callback; + scheduleAnimationCallback(callback) { + scheduledAnimationCallback = callback; }, - scheduleLowPriCallback(callback) { - scheduledLowPriCallback = callback; + scheduleDeferredCallback(callback) { + scheduledDeferredCallback = callback; }, }); @@ -116,21 +117,21 @@ var ReactNoop = { } }, - flushHighPri() { - var cb = scheduledHighPriCallback; + flushAnimationPri() { + var cb = scheduledAnimationCallback; if (cb === null) { return; } - scheduledHighPriCallback = null; + scheduledAnimationCallback = null; cb(); }, - flushLowPri(timeout : number = Infinity) { - var cb = scheduledLowPriCallback; + flushDeferredPri(timeout : number = Infinity) { + var cb = scheduledDeferredCallback; if (cb === null) { return; } - scheduledLowPriCallback = null; + scheduledDeferredCallback = null; var timeRemaining = timeout; cb({ timeRemaining() { @@ -145,8 +146,12 @@ var ReactNoop = { }, flush() { - ReactNoop.flushHighPri(); - ReactNoop.flushLowPri(); + ReactNoop.flushAnimationPri(); + ReactNoop.flushDeferredPri(); + }, + + performAnimationWork(fn: Function) { + NoopRenderer.performWithPriority(AnimationPriority, fn); }, // Logs the current state of the tree. @@ -156,23 +161,62 @@ var ReactNoop = { return; } + var bufferedLog = []; + function log(...args) { + bufferedLog.push(...args, '\n'); + } + function logHostInstances(children: Array, depth) { for (var i = 0; i < children.length; i++) { var child = children[i]; - console.log(' '.repeat(depth) + '- ' + child.type + '#' + child.id); + log(' '.repeat(depth) + '- ' + child.type + '#' + child.id); logHostInstances(child.children, depth + 1); } } function logContainer(container : Container, depth) { - console.log(' '.repeat(depth) + '- [root#' + container.rootID + ']'); + log(' '.repeat(depth) + '- [root#' + container.rootID + ']'); logHostInstances(container.children, depth + 1); } + function logUpdateQueue(updateQueue : UpdateQueue, depth) { + log( + ' '.repeat(depth + 1) + 'QUEUED UPDATES', + updateQueue.isReplace ? 'is replace' : '', + updateQueue.isForced ? 'is forced' : '' + ); + log( + ' '.repeat(depth + 1) + '~', + updateQueue.partialState, + updateQueue.callback ? 'with callback' : '' + ); + var next; + while (next = updateQueue.next) { + log( + ' '.repeat(depth + 1) + '~', + next.partialState, + next.callback ? 'with callback' : '' + ); + } + } + function logFiber(fiber : Fiber, depth) { - console.log( - ' '.repeat(depth) + '- ' + (fiber.type ? fiber.type.name || fiber.type : '[root]'), + log( + ' '.repeat(depth) + '- ' + (fiber.type ? fiber.type.name || fiber.type : '[root]'), '[' + fiber.pendingWorkPriority + (fiber.pendingProps ? '*' : '') + ']' ); + if (fiber.updateQueue) { + logUpdateQueue(fiber.updateQueue, depth); + } + const childInProgress = fiber.progressedChild; + if (childInProgress && childInProgress !== fiber.child) { + log(' '.repeat(depth + 1) + 'IN PROGRESS: ' + fiber.progressedPriority); + logFiber(childInProgress, depth + 1); + if (fiber.child) { + log(' '.repeat(depth + 1) + 'CURRENT'); + } + } else if (fiber.child && fiber.updateQueue) { + log(' '.repeat(depth + 1) + 'CHILDREN'); + } if (fiber.child) { logFiber(fiber.child, depth + 1); } @@ -181,10 +225,12 @@ var ReactNoop = { } } - console.log('HOST INSTANCES:'); + log('HOST INSTANCES:'); logContainer(rootContainer, 0); - console.log('FIBERS:'); + log('FIBERS:'); logFiber((root.stateNode : any).current, 0); + + console.log(...bufferedLog); }, }; diff --git a/src/renderers/shared/ReactDebugTool.js b/src/renderers/shared/ReactDebugTool.js index a59053d3a3..0f59612460 100644 --- a/src/renderers/shared/ReactDebugTool.js +++ b/src/renderers/shared/ReactDebugTool.js @@ -7,6 +7,7 @@ * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDebugTool + * @flow */ 'use strict'; @@ -14,12 +15,54 @@ var ReactInvalidSetStateWarningHook = require('ReactInvalidSetStateWarningHook'); var ReactHostOperationHistoryHook = require('ReactHostOperationHistoryHook'); var ReactComponentTreeHook = require('ReactComponentTreeHook'); -var ReactChildrenMutationWarningHook = require('ReactChildrenMutationWarningHook'); var ExecutionEnvironment = require('ExecutionEnvironment'); var performanceNow = require('performanceNow'); var warning = require('warning'); +import type { ReactElement } from 'ReactElementType'; +import type { DebugID } from 'ReactInstanceType'; +import type { Operation } from 'ReactHostOperationHistoryHook'; + +type Hook = any; + +type TimerType = + 'ctor' | + 'render' | + 'componentWillMount' | + 'componentWillUnmount' | + 'componentWillReceiveProps' | + 'shouldComponentUpdate' | + 'componentWillUpdate' | + 'componentDidUpdate' | + 'componentDidMount'; + +type Measurement = { + timerType: TimerType, + instanceID: DebugID, + duration: number, +}; + +type TreeSnapshot = { + [key: DebugID]: { + displayName: string, + text: string, + updateCount: number, + childIDs: Array, + ownerID: DebugID, + parentID: DebugID, + } +}; + +type HistoryItem = { + duration: number, + measurements: Array, + operations: Array, + treeSnapshot: TreeSnapshot, +}; + +export type FlushHistory = Array; + var hooks = []; var didHookThrowForEvent = {}; @@ -51,11 +94,11 @@ var isProfiling = false; var flushHistory = []; var lifeCycleTimerStack = []; var currentFlushNesting = 0; -var currentFlushMeasurements = null; -var currentFlushStartTime = null; +var currentFlushMeasurements = []; +var currentFlushStartTime = 0; var currentTimerDebugID = null; -var currentTimerStartTime = null; -var currentTimerNestedFlushDuration = null; +var currentTimerStartTime = 0; +var currentTimerNestedFlushDuration = 0; var currentTimerType = null; var lifeCycleTimerHasWarned = false; @@ -75,7 +118,9 @@ function getTreeSnapshot(registeredIDs) { updateCount: ReactComponentTreeHook.getUpdateCount(id), childIDs: ReactComponentTreeHook.getChildIDs(id), // Text nodes don't have owners but this is close enough. - ownerID: ownerID || ReactComponentTreeHook.getOwnerID(parentID), + ownerID: ownerID || + parentID && ReactComponentTreeHook.getOwnerID(parentID) || + 0, parentID, }; return tree; @@ -84,12 +129,12 @@ function getTreeSnapshot(registeredIDs) { function resetMeasurements() { var previousStartTime = currentFlushStartTime; - var previousMeasurements = currentFlushMeasurements || []; + var previousMeasurements = currentFlushMeasurements; var previousOperations = ReactHostOperationHistoryHook.getHistory(); if (currentFlushNesting === 0) { - currentFlushStartTime = null; - currentFlushMeasurements = null; + currentFlushStartTime = 0; + currentFlushMeasurements = []; clearHistory(); return; } @@ -163,8 +208,8 @@ function endLifeCycleTimer(debugID, timerType) { duration: performanceNow() - currentTimerStartTime - currentTimerNestedFlushDuration, }); } - currentTimerStartTime = null; - currentTimerNestedFlushDuration = null; + currentTimerStartTime = 0; + currentTimerNestedFlushDuration = 0; currentTimerDebugID = null; currentTimerType = null; } @@ -177,8 +222,8 @@ function pauseCurrentLifeCycleTimer() { timerType: currentTimerType, }; lifeCycleTimerStack.push(currentTimer); - currentTimerStartTime = null; - currentTimerNestedFlushDuration = null; + currentTimerStartTime = 0; + currentTimerNestedFlushDuration = 0; currentTimerDebugID = null; currentTimerType = null; } @@ -192,11 +237,69 @@ function resumeCurrentLifeCycleTimer() { currentTimerType = timerType; } +var lastMarkTimeStamp = 0; +var canUsePerformanceMeasure: boolean = +// $FlowFixMe https://github.com/facebook/flow/issues/2345 + typeof performance !== 'undefined' && + typeof performance.mark === 'function' && + typeof performance.clearMarks === 'function' && + typeof performance.measure === 'function' && + typeof performance.clearMeasures === 'function'; + +function shouldMark(debugID) { + if (!isProfiling || !canUsePerformanceMeasure) { + return false; + } + var element = ReactComponentTreeHook.getElement(debugID); + if (element == null || typeof element !== 'object') { + return false; + } + var isHostElement = typeof element.type === 'string'; + if (isHostElement) { + return false; + } + return true; +} + +function markBegin(debugID, markType) { + if (!shouldMark(debugID)) { + return; + } + + var markName = `${debugID}::${markType}`; + lastMarkTimeStamp = performanceNow(); + performance.mark(markName); +} + +function markEnd(debugID, markType) { + if (!shouldMark(debugID)) { + return; + } + + var markName = `${debugID}::${markType}`; + var displayName = ReactComponentTreeHook.getDisplayName(debugID) || 'Unknown'; + + // Chrome has an issue of dropping markers recorded too fast: + // https://bugs.chromium.org/p/chromium/issues/detail?id=640652 + // To work around this, we will not report very small measurements. + // I determined the magic number by tweaking it back and forth. + // 0.05ms was enough to prevent the issue, but I set it to 0.1ms to be safe. + // When the bug is fixed, we can `measure()` unconditionally if we want to. + var timeStamp = performanceNow(); + if (timeStamp - lastMarkTimeStamp > 0.1) { + var measurementName = `${displayName} [${markType}]`; + performance.measure(measurementName, markName); + } + + performance.clearMarks(markName); + performance.clearMeasures(measurementName); +} + var ReactDebugTool = { - addHook(hook) { + addHook(hook: Hook): void { hooks.push(hook); }, - removeHook(hook) { + removeHook(hook: Hook): void { for (var i = 0; i < hooks.length; i++) { if (hooks[i] === hook) { hooks.splice(i, 1); @@ -204,10 +307,10 @@ var ReactDebugTool = { } } }, - isProfiling() { + isProfiling(): boolean { return isProfiling; }, - beginProfiling() { + beginProfiling(): void { if (isProfiling) { return; } @@ -217,7 +320,7 @@ var ReactDebugTool = { resetMeasurements(); ReactDebugTool.addHook(ReactHostOperationHistoryHook); }, - endProfiling() { + endProfiling(): void { if (!isProfiling) { return; } @@ -226,86 +329,93 @@ var ReactDebugTool = { resetMeasurements(); ReactDebugTool.removeHook(ReactHostOperationHistoryHook); }, - getFlushHistory() { + getFlushHistory(): FlushHistory { return flushHistory; }, - onBeginFlush() { + onBeginFlush(): void { currentFlushNesting++; resetMeasurements(); pauseCurrentLifeCycleTimer(); emitEvent('onBeginFlush'); }, - onEndFlush() { + onEndFlush(): void { resetMeasurements(); currentFlushNesting--; resumeCurrentLifeCycleTimer(); emitEvent('onEndFlush'); }, - onBeginLifeCycleTimer(debugID, timerType) { + onBeginLifeCycleTimer(debugID: DebugID, timerType: TimerType): void { checkDebugID(debugID); emitEvent('onBeginLifeCycleTimer', debugID, timerType); + markBegin(debugID, timerType); beginLifeCycleTimer(debugID, timerType); }, - onEndLifeCycleTimer(debugID, timerType) { + onEndLifeCycleTimer(debugID: DebugID, timerType: TimerType): void { checkDebugID(debugID); endLifeCycleTimer(debugID, timerType); + markEnd(debugID, timerType); emitEvent('onEndLifeCycleTimer', debugID, timerType); }, - onBeginProcessingChildContext() { + onBeginProcessingChildContext(): void { emitEvent('onBeginProcessingChildContext'); }, - onEndProcessingChildContext() { + onEndProcessingChildContext(): void { emitEvent('onEndProcessingChildContext'); }, - onHostOperation(debugID, type, payload) { - checkDebugID(debugID); - emitEvent('onHostOperation', debugID, type, payload); + onHostOperation(operation: Operation) { + checkDebugID(operation.instanceID); + emitEvent('onHostOperation', operation); }, - onSetState() { + onSetState(): void { emitEvent('onSetState'); }, - onSetChildren(debugID, childDebugIDs) { + onSetChildren(debugID: DebugID, childDebugIDs: Array) { checkDebugID(debugID); childDebugIDs.forEach(checkDebugID); emitEvent('onSetChildren', debugID, childDebugIDs); }, - onBeforeMountComponent(debugID, element, parentDebugID) { + onBeforeMountComponent(debugID: DebugID, element: ReactElement, parentDebugID: DebugID): void { checkDebugID(debugID); checkDebugID(parentDebugID, true); emitEvent('onBeforeMountComponent', debugID, element, parentDebugID); + markBegin(debugID, 'mount'); }, - onMountComponent(debugID) { + onMountComponent(debugID: DebugID): void { checkDebugID(debugID); + markEnd(debugID, 'mount'); emitEvent('onMountComponent', debugID); }, - onBeforeUpdateComponent(debugID, element) { + onBeforeUpdateComponent(debugID: DebugID, element: ReactElement): void { checkDebugID(debugID); emitEvent('onBeforeUpdateComponent', debugID, element); + markBegin(debugID, 'update'); }, - onUpdateComponent(debugID) { + onUpdateComponent(debugID: DebugID): void { checkDebugID(debugID); + markEnd(debugID, 'update'); emitEvent('onUpdateComponent', debugID); }, - onBeforeUnmountComponent(debugID) { + onBeforeUnmountComponent(debugID: DebugID): void { checkDebugID(debugID); emitEvent('onBeforeUnmountComponent', debugID); + markBegin(debugID, 'unmount'); }, - onUnmountComponent(debugID) { + onUnmountComponent(debugID: DebugID): void { checkDebugID(debugID); + markEnd(debugID, 'unmount'); emitEvent('onUnmountComponent', debugID); }, - onTestEvent() { + onTestEvent(): void { emitEvent('onTestEvent'); }, }; // TODO remove these when RN/www gets updated -ReactDebugTool.addDevtool = ReactDebugTool.addHook; -ReactDebugTool.removeDevtool = ReactDebugTool.removeHook; +(ReactDebugTool: any).addDevtool = ReactDebugTool.addHook; +(ReactDebugTool: any).removeDevtool = ReactDebugTool.removeHook; ReactDebugTool.addHook(ReactInvalidSetStateWarningHook); ReactDebugTool.addHook(ReactComponentTreeHook); -ReactDebugTool.addHook(ReactChildrenMutationWarningHook); var url = (ExecutionEnvironment.canUseDOM && window.location.href) || ''; if ((/[?&]react_perf\b/).test(url)) { ReactDebugTool.beginProfiling(); diff --git a/src/renderers/shared/ReactInstrumentation.js b/src/renderers/shared/ReactInstrumentation.js index 08419bc0e2..a5de36d00e 100644 --- a/src/renderers/shared/ReactInstrumentation.js +++ b/src/renderers/shared/ReactInstrumentation.js @@ -7,11 +7,13 @@ * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInstrumentation + * @flow */ 'use strict'; -var debugTool = null; +// Trust the developer to only use ReactInstrumentation with a __DEV__ check +var debugTool = ((null: any): typeof ReactDebugTool); if (__DEV__) { var ReactDebugTool = require('ReactDebugTool'); diff --git a/src/renderers/shared/ReactPerf.js b/src/renderers/shared/ReactPerf.js index 9307ace3af..0f3886f69f 100644 --- a/src/renderers/shared/ReactPerf.js +++ b/src/renderers/shared/ReactPerf.js @@ -7,6 +7,7 @@ * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPerf + * @flow */ 'use strict'; @@ -15,11 +16,19 @@ var ReactDebugTool = require('ReactDebugTool'); var warning = require('warning'); var alreadyWarned = false; +import type { FlushHistory } from 'ReactDebugTool'; + function roundFloat(val, base = 2) { var n = Math.pow(10, base); return Math.floor(val * n) / n; } +// Flow type definition of console.table is too strict right now, see +// https://github.com/facebook/flow/pull/2353 for updates +function consoleTable(table: Array<{[key: string]: any}>): void { + console.table((table: any)); +} + function warnInProduction() { if (alreadyWarned) { return; @@ -296,7 +305,7 @@ function getOperations(flushHistory = getLastMeasurements()) { return stats; } -function printExclusive(flushHistory) { +function printExclusive(flushHistory?: FlushHistory) { if (!__DEV__) { warnInProduction(); return; @@ -319,10 +328,10 @@ function printExclusive(flushHistory) { 'Total lifecycle time (ms)': roundFloat(totalDuration - renderDuration), }; }); - console.table(table); + consoleTable(table); } -function printInclusive(flushHistory) { +function printInclusive(flushHistory?: FlushHistory) { if (!__DEV__) { warnInProduction(); return; @@ -338,10 +347,10 @@ function printInclusive(flushHistory) { 'Render count': renderCount, }; }); - console.table(table); + consoleTable(table); } -function printWasted(flushHistory) { +function printWasted(flushHistory?: FlushHistory) { if (!__DEV__) { warnInProduction(); return; @@ -357,10 +366,10 @@ function printWasted(flushHistory) { 'Render count': renderCount, }; }); - console.table(table); + consoleTable(table); } -function printOperations(flushHistory) { +function printOperations(flushHistory?: FlushHistory) { if (!__DEV__) { warnInProduction(); return; @@ -377,11 +386,11 @@ function printOperations(flushHistory) { 'Owner Component ID': stat.ownerID, 'DOM Component ID': stat.instanceID, })); - console.table(table); + consoleTable(table); } var warnedAboutPrintDOM = false; -function printDOM(measurements) { +function printDOM(measurements: FlushHistory) { warning( warnedAboutPrintDOM, '`ReactPerf.printDOM(...)` is deprecated. Use ' + @@ -392,7 +401,7 @@ function printDOM(measurements) { } var warnedAboutGetMeasurementsSummaryMap = false; -function getMeasurementsSummaryMap(measurements) { +function getMeasurementsSummaryMap(measurements: FlushHistory) { warning( warnedAboutGetMeasurementsSummaryMap, '`ReactPerf.getMeasurementsSummaryMap(...)` is deprecated. Use ' + diff --git a/src/renderers/shared/__tests__/ReactDebugTool-test.js b/src/renderers/shared/__tests__/ReactDebugTool-test.js index 332290bf96..6f849c62f6 100644 --- a/src/renderers/shared/__tests__/ReactDebugTool-test.js +++ b/src/renderers/shared/__tests__/ReactDebugTool-test.js @@ -11,10 +11,10 @@ 'use strict'; -describe('ReactDebugTool', function() { +describe('ReactDebugTool', () => { var ReactDebugTool; - beforeEach(function() { + beforeEach(() => { jest.resetModuleRegistry(); ReactDebugTool = require('ReactDebugTool'); }); diff --git a/src/renderers/shared/__tests__/ReactPerf-test.js b/src/renderers/shared/__tests__/ReactPerf-test.js index 70e5cd5f53..dfd1e517fc 100644 --- a/src/renderers/shared/__tests__/ReactPerf-test.js +++ b/src/renderers/shared/__tests__/ReactPerf-test.js @@ -11,7 +11,7 @@ 'use strict'; -describe('ReactPerf', function() { +describe('ReactPerf', () => { var React; var ReactDOM; var ReactPerf; @@ -23,7 +23,7 @@ describe('ReactPerf', function() { var Div; var LifeCycle; - beforeEach(function() { + beforeEach(() => { var now = 0; jest.setMock('fbjs/lib/performanceNow', function() { return now++; @@ -71,7 +71,7 @@ describe('ReactPerf', function() { }); }); - afterEach(function() { + afterEach(() => { if (console.table.isFake) { delete console.table; } @@ -91,7 +91,7 @@ describe('ReactPerf', function() { return ReactPerf.getLastMeasurements(); } - it('should count no-op update as waste', function() { + it('should count no-op update as waste', () => { var container = document.createElement('div'); ReactDOM.render(, container); var measurements = measure(() => { @@ -112,7 +112,7 @@ describe('ReactPerf', function() { }]); }); - it('should count no-op update in child as waste', function() { + it('should count no-op update in child as waste', () => { var container = document.createElement('div'); ReactDOM.render(, container); @@ -137,13 +137,13 @@ describe('ReactPerf', function() { expect(summary).toEqual([]); } - it('should not count initial render as waste', function() { + it('should not count initial render as waste', () => { expectNoWaste(() => { ReactTestUtils.renderIntoDocument(); }); }); - it('should not count unmount as waste', function() { + it('should not count unmount as waste', () => { var container = document.createElement('div'); ReactDOM.render(
hello
, container); expectNoWaste(() => { @@ -151,7 +151,7 @@ describe('ReactPerf', function() { }); }); - it('should not count content update as waste', function() { + it('should not count content update as waste', () => { var container = document.createElement('div'); ReactDOM.render(
hello
, container); expectNoWaste(() => { @@ -159,7 +159,7 @@ describe('ReactPerf', function() { }); }); - it('should not count child addition as waste', function() { + it('should not count child addition as waste', () => { var container = document.createElement('div'); ReactDOM.render(
, container); expectNoWaste(() => { @@ -167,7 +167,7 @@ describe('ReactPerf', function() { }); }); - it('should not count child removal as waste', function() { + it('should not count child removal as waste', () => { var container = document.createElement('div'); ReactDOM.render(
, container); expectNoWaste(() => { @@ -175,7 +175,7 @@ describe('ReactPerf', function() { }); }); - it('should not count property update as waste', function() { + it('should not count property update as waste', () => { var container = document.createElement('div'); ReactDOM.render(
hey
, container); expectNoWaste(() => { @@ -183,7 +183,7 @@ describe('ReactPerf', function() { }); }); - it('should not count style update as waste', function() { + it('should not count style update as waste', () => { var container = document.createElement('div'); ReactDOM.render(
hey
, container); expectNoWaste(() => { @@ -191,7 +191,7 @@ describe('ReactPerf', function() { }); }); - it('should not count property removal as waste', function() { + it('should not count property removal as waste', () => { var container = document.createElement('div'); ReactDOM.render(
hey
, container); expectNoWaste(() => { @@ -199,7 +199,7 @@ describe('ReactPerf', function() { }); }); - it('should not count raw HTML update as waste', function() { + it('should not count raw HTML update as waste', () => { var container = document.createElement('div'); ReactDOM.render(
, @@ -213,7 +213,7 @@ describe('ReactPerf', function() { }); }); - it('should not count child reordering as waste', function() { + it('should not count child reordering as waste', () => { var container = document.createElement('div'); ReactDOM.render(
, container); expectNoWaste(() => { @@ -221,7 +221,7 @@ describe('ReactPerf', function() { }); }); - it('should not count text update as waste', function() { + it('should not count text update as waste', () => { var container = document.createElement('div'); ReactDOM.render(
{'hello'}{'world'}
, container); expectNoWaste(() => { @@ -229,7 +229,7 @@ describe('ReactPerf', function() { }); }); - it('should not count replacing null with a host as waste', function() { + it('should not count replacing null with a host as waste', () => { var element = null; function Foo() { return element; @@ -242,7 +242,7 @@ describe('ReactPerf', function() { }); }); - it('should not count replacing a host with null as waste', function() { + it('should not count replacing a host with null as waste', () => { var element =
; function Foo() { return element; @@ -255,7 +255,7 @@ describe('ReactPerf', function() { }); }); - it('should include stats for components unmounted during measurement', function() { + it('should include stats for components unmounted during measurement', () => { var container = document.createElement('div'); var measurements = measure(() => { ReactDOM.render(
, container); @@ -270,7 +270,7 @@ describe('ReactPerf', function() { }]); }); - it('should include lifecycle methods in measurements', function() { + it('should include lifecycle methods in measurements', () => { var container = document.createElement('div'); var measurements = measure(() => { var instance = ReactDOM.render(, container); @@ -307,7 +307,7 @@ describe('ReactPerf', function() { }]); }); - it('should include render time of functional components', function() { + it('should include render time of functional components', () => { function Foo() { return null; } @@ -329,7 +329,7 @@ describe('ReactPerf', function() { }]); }); - it('should not count time in a portal towards lifecycle method', function() { + it('should not count time in a portal towards lifecycle method', () => { function Foo() { return null; } @@ -385,7 +385,7 @@ describe('ReactPerf', function() { }]); }); - it('warns once when using getMeasurementsSummaryMap', function() { + it('warns once when using getMeasurementsSummaryMap', () => { var measurements = measure(() => {}); spyOn(console, 'error'); ReactPerf.getMeasurementsSummaryMap(measurements); @@ -399,7 +399,7 @@ describe('ReactPerf', function() { expect(console.error.calls.count()).toBe(1); }); - it('warns once when using printDOM', function() { + it('warns once when using printDOM', () => { var measurements = measure(() => {}); spyOn(console, 'error'); ReactPerf.printDOM(measurements); diff --git a/src/renderers/shared/fiber/ReactChildFiber.js b/src/renderers/shared/fiber/ReactChildFiber.js index ddf4725a02..93839caed5 100644 --- a/src/renderers/shared/fiber/ReactChildFiber.js +++ b/src/renderers/shared/fiber/ReactChildFiber.js @@ -18,9 +18,7 @@ import type { PriorityLevel } from 'ReactPriorityLevel'; import type { ReactNodeList } from 'ReactTypes'; -var { - REACT_ELEMENT_TYPE, -} = require('ReactElement'); +var REACT_ELEMENT_TYPE = require('ReactElementSymbol'); var { REACT_COROUTINE_TYPE, REACT_YIELD_TYPE, @@ -29,151 +27,241 @@ var { var ReactFiber = require('ReactFiber'); var ReactReifiedYield = require('ReactReifiedYield'); -function createSubsequentChild( - returnFiber : Fiber, - existingChild : ?Fiber, - previousSibling : Fiber, - newChildren, - priority : PriorityLevel -) : Fiber { - if (typeof newChildren !== 'object' || newChildren === null) { - return previousSibling; - } +const { + cloneFiber, + createFiberFromElement, + createFiberFromCoroutine, + createFiberFromYield, +} = ReactFiber; - switch (newChildren.$$typeof) { - case REACT_ELEMENT_TYPE: { - const element = (newChildren : ReactElement); - if (existingChild && - element.type === existingChild.type && - element.key === existingChild.key) { - // TODO: This is not sufficient since previous siblings could be new. - // Will fix reconciliation properly later. - const clone = ReactFiber.cloneFiber(existingChild, priority); - clone.pendingProps = element.props; - clone.child = existingChild.child; - clone.sibling = null; - clone.return = returnFiber; - previousSibling.sibling = clone; - return clone; +const { + createReifiedYield, +} = ReactReifiedYield; + +const isArray = Array.isArray; + +function ChildReconciler(shouldClone) { + + function createSubsequentChild( + returnFiber : Fiber, + existingChild : ?Fiber, + previousSibling : Fiber, + newChildren, + priority : PriorityLevel + ) : Fiber { + if (typeof newChildren !== 'object' || newChildren === null) { + return previousSibling; + } + + switch (newChildren.$$typeof) { + case REACT_ELEMENT_TYPE: { + const element = (newChildren : ReactElement); + if (existingChild && + element.type === existingChild.type && + element.key === existingChild.key) { + // TODO: This is not sufficient since previous siblings could be new. + // Will fix reconciliation properly later. + const clone = shouldClone ? cloneFiber(existingChild, priority) : existingChild; + if (!shouldClone) { + // TODO: This might be lowering the priority of nested unfinished work. + clone.pendingWorkPriority = priority; + } + clone.pendingProps = element.props; + clone.sibling = null; + clone.return = returnFiber; + previousSibling.sibling = clone; + return clone; + } + const child = createFiberFromElement(element, priority); + previousSibling.sibling = child; + child.return = returnFiber; + return child; } - const child = ReactFiber.createFiberFromElement(element, priority); - previousSibling.sibling = child; - child.return = returnFiber; - return child; - } - case REACT_COROUTINE_TYPE: { - const coroutine = (newChildren : ReactCoroutine); - const child = ReactFiber.createFiberFromCoroutine(coroutine, priority); - previousSibling.sibling = child; - child.return = returnFiber; - return child; - } + case REACT_COROUTINE_TYPE: { + const coroutine = (newChildren : ReactCoroutine); + const child = createFiberFromCoroutine(coroutine, priority); + previousSibling.sibling = child; + child.return = returnFiber; + return child; + } - case REACT_YIELD_TYPE: { - const yieldNode = (newChildren : ReactYield); - const reifiedYield = ReactReifiedYield.createReifiedYield(yieldNode); - const child = ReactFiber.createFiberFromYield(yieldNode, priority); - child.output = reifiedYield; - previousSibling.sibling = child; - child.return = returnFiber; - return child; - } - } - - if (Array.isArray(newChildren)) { - let prev : Fiber = previousSibling; - let existing : ?Fiber = existingChild; - for (var i = 0; i < newChildren.length; i++) { - prev = createSubsequentChild(returnFiber, existing, prev, newChildren[i], priority); - if (prev && existing) { - // TODO: This is not correct because there could've been more - // than one sibling consumed but I don't want to return a tuple. - existing = existing.sibling; + case REACT_YIELD_TYPE: { + const yieldNode = (newChildren : ReactYield); + const reifiedYield = createReifiedYield(yieldNode); + const child = createFiberFromYield(yieldNode, priority); + child.output = reifiedYield; + previousSibling.sibling = child; + child.return = returnFiber; + return child; } } - return prev; - } else { - console.log('Unknown child', newChildren); - return previousSibling; - } -} -function createFirstChild(returnFiber, existingChild, newChildren, priority) { - if (typeof newChildren !== 'object' || newChildren === null) { - return null; - } - - switch (newChildren.$$typeof) { - case REACT_ELEMENT_TYPE: { - const element = (newChildren : ReactElement); - if (existingChild && - element.type === existingChild.type && - element.key === existingChild.key) { - // Get the clone of the existing fiber. - const clone = ReactFiber.cloneFiber(existingChild, priority); - clone.pendingProps = element.props; - clone.child = existingChild.child; - clone.sibling = null; - clone.return = returnFiber; - return clone; - } - const child = ReactFiber.createFiberFromElement(element, priority); - child.return = returnFiber; - return child; - } - - case REACT_COROUTINE_TYPE: { - const coroutine = (newChildren : ReactCoroutine); - const child = ReactFiber.createFiberFromCoroutine(coroutine, priority); - child.return = returnFiber; - return child; - } - - case REACT_YIELD_TYPE: { - // A yield results in a fragment fiber whose output is the continuation. - // TODO: When there is only a single child, we can optimize this to avoid - // the fragment. - const yieldNode = (newChildren : ReactYield); - const reifiedYield = ReactReifiedYield.createReifiedYield(yieldNode); - const child = ReactFiber.createFiberFromYield(yieldNode, priority); - child.output = reifiedYield; - child.return = returnFiber; - return child; - } - } - - if (Array.isArray(newChildren)) { - var first : ?Fiber = null; - var prev : ?Fiber = null; - var existing : ?Fiber = existingChild; - for (var i = 0; i < newChildren.length; i++) { - if (prev == null) { - prev = createFirstChild(returnFiber, existing, newChildren[i], priority); - first = prev; - } else { + if (isArray(newChildren)) { + let prev : Fiber = previousSibling; + let existing : ?Fiber = existingChild; + for (var i = 0; i < newChildren.length; i++) { + var nextExisting = existing && existing.sibling; prev = createSubsequentChild(returnFiber, existing, prev, newChildren[i], priority); + if (prev && existing) { + // TODO: This is not correct because there could've been more + // than one sibling consumed but I don't want to return a tuple. + existing = nextExisting; + } } - if (prev && existing) { - // TODO: This is not correct because there could've been more - // than one sibling consumed but I don't want to return a tuple. - existing = existing.sibling; + return prev; + } else { + // TODO: Throw for unknown children. + return previousSibling; + } + } + + function createFirstChild(returnFiber, existingChild, newChildren, priority) { + if (typeof newChildren !== 'object' || newChildren === null) { + return null; + } + + switch (newChildren.$$typeof) { + case REACT_ELEMENT_TYPE: { + /* $FlowFixMe(>=0.31.0): This is an unsafe cast. Consider adding a type + * annotation to the `newChildren` param of this + * function. + */ + const element = (newChildren : ReactElement); + if (existingChild && + element.type === existingChild.type && + element.key === existingChild.key) { + // Get the clone of the existing fiber. + const clone = shouldClone ? cloneFiber(existingChild, priority) : existingChild; + if (!shouldClone) { + // TODO: This might be lowering the priority of nested unfinished work. + clone.pendingWorkPriority = priority; + } + clone.pendingProps = element.props; + clone.sibling = null; + clone.return = returnFiber; + return clone; + } + const child = createFiberFromElement(element, priority); + child.return = returnFiber; + return child; + } + + case REACT_COROUTINE_TYPE: { + /* $FlowFixMe(>=0.31.0): No 'handler' property found in object type + */ + const coroutine = (newChildren : ReactCoroutine); + const child = createFiberFromCoroutine(coroutine, priority); + child.return = returnFiber; + return child; + } + + case REACT_YIELD_TYPE: { + // A yield results in a fragment fiber whose output is the continuation. + // TODO: When there is only a single child, we can optimize this to avoid + // the fragment. + /* $FlowFixMe(>=0.31.0): No 'continuation' property found in object + * type + */ + const yieldNode = (newChildren : ReactYield); + const reifiedYield = createReifiedYield(yieldNode); + const child = createFiberFromYield(yieldNode, priority); + child.output = reifiedYield; + child.return = returnFiber; + return child; } } - return first; - } else { - console.log('Unknown child', newChildren); - return null; + + if (isArray(newChildren)) { + var first : ?Fiber = null; + var prev : ?Fiber = null; + var existing : ?Fiber = existingChild; + /* $FlowIssue(>=0.31.0) #12747709 + * + * `Array.isArray` is matched syntactically for now until predicate + * support is complete. + */ + for (var i = 0; i < newChildren.length; i++) { + var nextExisting = existing && existing.sibling; + if (prev == null) { + prev = createFirstChild(returnFiber, existing, newChildren[i], priority); + first = prev; + } else { + prev = createSubsequentChild(returnFiber, existing, prev, newChildren[i], priority); + } + if (prev && existing) { + // TODO: This is not correct because there could've been more + // than one sibling consumed but I don't want to return a tuple. + existing = nextExisting; + } + } + return first; + } else { + // TODO: Throw for unknown children. + return null; + } } + + // TODO: This API won't work because we'll need to transfer the side-effects of + // unmounting children to the returnFiber. + function reconcileChildFibers( + returnFiber : Fiber, + currentFirstChild : ?Fiber, + newChildren : ReactNodeList, + priority : PriorityLevel + ) : ?Fiber { + return createFirstChild(returnFiber, currentFirstChild, newChildren, priority); + } + + return reconcileChildFibers; } -// TODO: This API won't work because we'll need to transfer the side-effects of -// unmounting children to the returnFiber. -exports.reconcileChildFibers = function( - returnFiber : Fiber, - currentFirstChild : ?Fiber, - newChildren : ReactNodeList, - priority : PriorityLevel -) : ?Fiber { - return createFirstChild(returnFiber, currentFirstChild, newChildren, priority); +exports.reconcileChildFibers = ChildReconciler(true); + +exports.reconcileChildFibersInPlace = ChildReconciler(false); + + +function cloneSiblings(current : Fiber, workInProgress : Fiber, returnFiber : Fiber) { + workInProgress.return = returnFiber; + while (current.sibling) { + current = current.sibling; + workInProgress = workInProgress.sibling = cloneFiber( + current, + current.pendingWorkPriority + ); + workInProgress.return = returnFiber; + } + workInProgress.sibling = null; +} + +exports.cloneChildFibers = function(current : ?Fiber, workInProgress : Fiber) { + if (!workInProgress.child) { + return; + } + if (current && workInProgress.child === current.child) { + // We use workInProgress.child since that lets Flow know that it can't be + // null since we validated that already. However, as the line above suggests + // they're actually the same thing. + const currentChild = workInProgress.child; + // TODO: This used to reset the pending priority. Not sure if that is needed. + // workInProgress.pendingWorkPriority = current.pendingWorkPriority; + // TODO: The below priority used to be set to NoWork which would've + // dropped work. This is currently unobservable but will become + // observable when the first sibling has lower priority work remaining + // than the next sibling. At that point we should add tests that catches + // this. + const newChild = cloneFiber(currentChild, currentChild.pendingWorkPriority); + workInProgress.child = newChild; + cloneSiblings(currentChild, newChild, workInProgress); + } + + // If there is no alternate, then we don't need to clone the children. + // If the children of the alternate fiber is a different set, then we don't + // need to clone. We need to reset the return fiber though since we'll + // traverse down into them. + let child = workInProgress.child; + while (child) { + child.return = workInProgress; + child = child.sibling; + } }; diff --git a/src/renderers/shared/fiber/ReactFiber.js b/src/renderers/shared/fiber/ReactFiber.js index 39683f001e..a733909551 100644 --- a/src/renderers/shared/fiber/ReactFiber.js +++ b/src/renderers/shared/fiber/ReactFiber.js @@ -15,6 +15,7 @@ import type { ReactCoroutine, ReactYield } from 'ReactCoroutine'; import type { TypeOfWork } from 'ReactTypeOfWork'; import type { PriorityLevel } from 'ReactPriorityLevel'; +import type { UpdateQueue } from 'ReactFiberUpdateQueue'; var ReactTypeOfWork = require('ReactTypeOfWork'); var { @@ -26,8 +27,6 @@ var { YieldComponent, } = ReactTypeOfWork; -var ReactElement = require('ReactElement'); - var { NoWork, } = require('ReactPriorityLevel'); @@ -78,6 +77,12 @@ export type Fiber = Instance & { pendingProps: any, // This type will be more specific once we overload the tag. // TODO: I think that there is a way to merge pendingProps and memoizedProps. memoizedProps: any, // The props used to create the output. + // A queue of local state updates. + updateQueue: ?UpdateQueue, + // The state used to create the output. This is a full state object. + memoizedState: any, + // Linked list of callbacks to call after updates are committed. + callbackList: ?UpdateQueue, // Output is the return value of this fiber, or a linked list of return values // if this returns multiple values. Such as a fragment. output: any, // This type will be more specific once we overload the tag. @@ -91,28 +96,44 @@ export type Fiber = Instance & { firstEffect: ?Fiber, lastEffect: ?Fiber, - // This will be used to quickly determine if a subtree has no pending changes. pendingWorkPriority: PriorityLevel, + // This value represents the priority level that was last used to process this + // component. This indicates whether it is better to continue from the + // progressed work or if it is better to continue from the current state. + progressedPriority: PriorityLevel, + + // If work bails out on a Fiber that already had some work started at a lower + // priority, then we need to store the progressed work somewhere. This holds + // the started child set until we need to get back to working on it. It may + // or may not be the same as the "current" child. + progressedChild: ?Fiber, + // This is a pooled version of a Fiber. Every fiber that gets updated will // eventually have a pair. There are cases when we can clean up pairs to save // memory if we need to. alternate: ?Fiber, - // Keeps track if we've completed this node or if we're currently in the - // middle of processing it. We really should know this based on pendingProps - // or something else. We could also reuse the tag for this purpose. However, - // I'm not really sure so I'll use a flag for now. - // TODO: Find another way to infer this flag. - hasWorkInProgress: bool, - // Conceptual aliases // workInProgress : Fiber -> alternate The alternate used for reuse happens // to be the same as work in progress. }; +// This is a constructor of a POJO instead of a constructor function for a few +// reasons: +// 1) Nobody should add any instance methods on this. Instance methods can be +// more difficult to predict when they get optimized and they are almost +// never inlined properly in static compilers. +// 2) Nobody should rely on `instanceof Fiber` for type testing. We should +// always know when it is a fiber. +// 3) We can easily go from a createFiber call to calling a constructor if that +// is faster. The opposite is not true. +// 4) We might want to experiment with using numeric keys since they are easier +// to optimize in a non-JIT environment. +// 5) It should be easy to port this to a C struct and keep a C implementation +// compatible. var createFiber = function(tag : TypeOfWork, key : null | string) : Fiber { return { @@ -137,6 +158,9 @@ var createFiber = function(tag : TypeOfWork, key : null | string) : Fiber { pendingProps: null, memoizedProps: null, + updateQueue: null, + memoizedState: null, + callbackList: null, output: null, nextEffect: null, @@ -144,8 +168,8 @@ var createFiber = function(tag : TypeOfWork, key : null | string) : Fiber { lastEffect: null, pendingWorkPriority: NoWork, - - hasWorkInProgress: false, + progressedPriority: NoWork, + progressedChild: null, alternate: null, @@ -157,7 +181,16 @@ function shouldConstruct(Component) { } // This is used to create an alternate fiber to do work on. +// TODO: Rename to createWorkInProgressFiber or something like that. exports.cloneFiber = function(fiber : Fiber, priorityLevel : PriorityLevel) : Fiber { + // We clone to get a work in progress. That means that this fiber is the + // current. To make it safe to reuse that fiber later on as work in progress + // we need to reset its work in progress flag now. We don't have an + // opportunity to do this earlier since we don't traverse the tree when + // the work in progress tree becomes the current tree. + // fiber.progressedPriority = NoWork; + // fiber.progressedChild = null; + // We use a double buffering pooling technique because we know that we'll only // ever need at most two versions of a tree. We pool the "other" unused node // that we're free to reuse. This is lazily created to avoid allocating extra @@ -165,33 +198,37 @@ exports.cloneFiber = function(fiber : Fiber, priorityLevel : PriorityLevel) : Fi // extra memory if needed. let alt = fiber.alternate; if (alt) { - alt.stateNode = fiber.stateNode; - alt.child = fiber.child; - alt.sibling = fiber.sibling; - alt.ref = alt.ref; - alt.pendingProps = fiber.pendingProps; - alt.pendingWorkPriority = priorityLevel; - // Whenever we clone, we do so to get a new work in progress. // This ensures that we've reset these in the new tree. alt.nextEffect = null; alt.firstEffect = null; alt.lastEffect = null; + } else { + // This should not have an alternate already + alt = createFiber(fiber.tag, fiber.key); + alt.type = fiber.type; - return alt; + alt.progressedChild = fiber.progressedChild; + alt.progressedPriority = fiber.progressedPriority; + + alt.alternate = fiber; + fiber.alternate = alt; } - // This should not have an alternate already - alt = createFiber(fiber.tag, fiber.key); - alt.type = fiber.type; alt.stateNode = fiber.stateNode; alt.child = fiber.child; - alt.sibling = fiber.sibling; - alt.ref = alt.ref; + alt.sibling = fiber.sibling; // This should always be overridden. TODO: null + alt.ref = fiber.ref; + // pendingProps is here for symmetry but is unnecessary in practice for now. + // TODO: Pass in the new pendingProps as an argument maybe? + alt.pendingProps = fiber.pendingProps; + alt.updateQueue = fiber.updateQueue; + alt.callbackList = fiber.callbackList; alt.pendingWorkPriority = priorityLevel; - alt.alternate = fiber; - fiber.alternate = alt; + alt.memoizedProps = fiber.memoizedProps; + alt.output = fiber.output; + return alt; }; @@ -200,14 +237,15 @@ exports.createHostContainerFiber = function() { return fiber; }; -exports.createFiberFromElement = function(element : ReactElement, priorityLevel : PriorityLevel) { - const fiber = exports.createFiberFromElementType(element.type, element.key); +exports.createFiberFromElement = function(element : ReactElement<*>, priorityLevel : PriorityLevel) { +// $FlowFixMe: ReactElement.key is currently defined as ?string but should be defined as null | string in Flow. + const fiber = createFiberFromElementType(element.type, element.key); fiber.pendingProps = element.props; fiber.pendingWorkPriority = priorityLevel; return fiber; }; -exports.createFiberFromElementType = function(type : mixed, key : null | string) { +function createFiberFromElementType(type : mixed, key : null | string) { let fiber; if (typeof type === 'function') { fiber = shouldConstruct(type) ? @@ -224,7 +262,9 @@ exports.createFiberFromElementType = function(type : mixed, key : null | string) throw new Error('Unknown component type: ' + typeof type); } return fiber; -}; +} + +exports.createFiberFromElementType = createFiberFromElementType; exports.createFiberFromCoroutine = function(coroutine : ReactCoroutine, priorityLevel : PriorityLevel) { const fiber = createFiber(CoroutineComponent, coroutine.key); diff --git a/src/renderers/shared/fiber/ReactFiberBeginWork.js b/src/renderers/shared/fiber/ReactFiberBeginWork.js index 0b28cd98cf..3d6266227c 100644 --- a/src/renderers/shared/fiber/ReactFiberBeginWork.js +++ b/src/renderers/shared/fiber/ReactFiberBeginWork.js @@ -14,9 +14,18 @@ import type { ReactCoroutine } from 'ReactCoroutine'; import type { Fiber } from 'ReactFiber'; +import type { FiberRoot } from 'ReactFiberRoot'; import type { HostConfig } from 'ReactFiberReconciler'; +import type { Scheduler } from 'ReactFiberScheduler'; +import type { PriorityLevel } from 'ReactPriorityLevel'; +import type { UpdateQueue } from 'ReactFiberUpdateQueue'; -var ReactChildFiber = require('ReactChildFiber'); +var { + reconcileChildFibers, + reconcileChildFibersInPlace, + cloneChildFibers, +} = require('ReactChildFiber'); +var { LowPriority } = require('ReactPriorityLevel'); var ReactTypeOfWork = require('ReactTypeOfWork'); var { IndeterminateComponent, @@ -32,58 +41,222 @@ var { NoWork, OffscreenPriority, } = require('ReactPriorityLevel'); -var { findNextUnitOfWorkAtPriority } = require('ReactFiberPendingWork'); +var { + createUpdateQueue, + addToQueue, + addCallbackToQueue, + mergeUpdateQueue, +} = require('ReactFiberUpdateQueue'); +var ReactInstanceMap = require('ReactInstanceMap'); -module.exports = function(config : HostConfig) { +module.exports = function(config : HostConfig, getScheduler : () => Scheduler) { + + function markChildAsProgressed(current, workInProgress, priorityLevel) { + // We now have clones. Let's store them as the currently progressed work. + workInProgress.progressedChild = workInProgress.child; + workInProgress.progressedPriority = priorityLevel; + if (current) { + // We also store it on the current. When the alternate swaps in we can + // continue from this point. + current.progressedChild = workInProgress.progressedChild; + current.progressedPriority = workInProgress.progressedPriority; + } + } function reconcileChildren(current, workInProgress, nextChildren) { - const priority = workInProgress.pendingWorkPriority; - workInProgress.child = ReactChildFiber.reconcileChildFibers( - workInProgress, - current ? current.child : null, - nextChildren, - priority - ); + const priorityLevel = workInProgress.pendingWorkPriority; + reconcileChildrenAtPriority(current, workInProgress, nextChildren, priorityLevel); + } + + function reconcileChildrenAtPriority(current, workInProgress, nextChildren, priorityLevel) { + // At this point any memoization is no longer valid since we'll have changed + // the children. + workInProgress.memoizedProps = null; + if (current && current.child === workInProgress.child) { + // If the current child is the same as the work in progress, it means that + // we haven't yet started any work on these children. Therefore, we use + // the clone algorithm to create a copy of all the current children. + workInProgress.child = reconcileChildFibers( + workInProgress, + workInProgress.child, + nextChildren, + priorityLevel + ); + } else { + // If, on the other hand, we don't have a current fiber or if it is + // already using a clone, that means we've already begun some work on this + // tree and we can continue where we left off by reconciling against the + // existing children. + workInProgress.child = reconcileChildFibersInPlace( + workInProgress, + workInProgress.child, + nextChildren, + priorityLevel + ); + } + markChildAsProgressed(current, workInProgress, priorityLevel); } function updateFunctionalComponent(current, workInProgress) { var fn = workInProgress.type; var props = workInProgress.pendingProps; - console.log('update fn:', fn.name); + + // TODO: Disable this before release, since it is not part of the public API + // I use this for testing to compare the relative overhead of classes. + if (typeof fn.shouldComponentUpdate === 'function') { + if (workInProgress.memoizedProps !== null) { + if (!fn.shouldComponentUpdate(workInProgress.memoizedProps, props)) { + return bailoutOnAlreadyFinishedWork(current, workInProgress); + } + } + } + var nextChildren = fn(props); reconcileChildren(current, workInProgress, nextChildren); - workInProgress.pendingWorkPriority = NoWork; + return workInProgress.child; + } + + function scheduleUpdate(fiber: Fiber, updateQueue: UpdateQueue, priorityLevel : PriorityLevel): void { + const { scheduleDeferredWork } = getScheduler(); + fiber.updateQueue = updateQueue; + // Schedule update on the alternate as well, since we don't know which tree + // is current. + if (fiber.alternate) { + fiber.alternate.updateQueue = updateQueue; + } + while (true) { + if (fiber.pendingWorkPriority === NoWork || + fiber.pendingWorkPriority >= priorityLevel) { + fiber.pendingWorkPriority = priorityLevel; + } + if (fiber.alternate) { + if (fiber.alternate.pendingWorkPriority === NoWork || + fiber.alternate.pendingWorkPriority >= priorityLevel) { + fiber.alternate.pendingWorkPriority = priorityLevel; + } + } + // Duck type root + if (fiber.stateNode && fiber.stateNode.containerInfo) { + const root : FiberRoot = (fiber.stateNode : any); + scheduleDeferredWork(root, priorityLevel); + return; + } + if (!fiber.return) { + throw new Error('No root!'); + } + fiber = fiber.return; + } + } + + // Class component state updater + const updater = { + enqueueSetState(instance, partialState) { + const fiber = ReactInstanceMap.get(instance); + const updateQueue = fiber.updateQueue ? + addToQueue(fiber.updateQueue, partialState) : + createUpdateQueue(partialState); + scheduleUpdate(fiber, updateQueue, LowPriority); + }, + enqueueReplaceState(instance, state) { + const fiber = ReactInstanceMap.get(instance); + const updateQueue = createUpdateQueue(state); + updateQueue.isReplace = true; + scheduleUpdate(fiber, updateQueue, LowPriority); + }, + enqueueForceUpdate(instance) { + const fiber = ReactInstanceMap.get(instance); + const updateQueue = fiber.updateQueue || createUpdateQueue(null); + updateQueue.isForced = true; + scheduleUpdate(fiber, updateQueue, LowPriority); + }, + enqueueCallback(instance, callback) { + const fiber = ReactInstanceMap.get(instance); + let updateQueue = fiber.updateQueue ? + fiber.updateQueue : + createUpdateQueue(null); + addCallbackToQueue(updateQueue, callback); + fiber.updateQueue = updateQueue; + if (fiber.alternate) { + fiber.alternate.updateQueue = updateQueue; + } + }, + }; + + function updateClassComponent(current : ?Fiber, workInProgress : Fiber) { + // A class component update is the result of either new props or new state. + // Account for the possibly of missing pending props by falling back to the + // memoized props. + var props = workInProgress.pendingProps; + if (!props && current) { + props = current.memoizedProps; + } + // Compute the state using the memoized state and the update queue. + var updateQueue = workInProgress.updateQueue; + var previousState = current ? current.memoizedState : null; + var state = updateQueue ? + mergeUpdateQueue(updateQueue, previousState, props) : + previousState; + + var instance = workInProgress.stateNode; + if (!instance) { + var ctor = workInProgress.type; + workInProgress.stateNode = instance = new ctor(props); + state = instance.state || null; + // The initial state must be added to the update queue in case + // setState is called before the initial render. + if (state !== null) { + workInProgress.updateQueue = createUpdateQueue(state); + } + // The instance needs access to the fiber so that it can schedule updates + ReactInstanceMap.set(instance, workInProgress); + instance.updater = updater; + } else if (typeof instance.shouldComponentUpdate === 'function' && + !(updateQueue && updateQueue.isForced)) { + if (workInProgress.memoizedProps !== null) { + // Reset the props, in case this is a ping-pong case rather than a + // completed update case. For the completed update case, the instance + // props will already be the memoizedProps. + instance.props = workInProgress.memoizedProps; + instance.state = workInProgress.memoizedState; + if (!instance.shouldComponentUpdate(props, state)) { + return bailoutOnAlreadyFinishedWork(current, workInProgress); + } + } + } + + instance.props = props; + instance.state = state; + var nextChildren = instance.render(); + reconcileChildren(current, workInProgress, nextChildren); + + return workInProgress.child; } function updateHostComponent(current, workInProgress) { - console.log( - 'host component', workInProgress.type, - typeof workInProgress.pendingProps.children === 'string' ? workInProgress.pendingProps.children : '' - ); + const nextChildren = workInProgress.pendingProps.children; + if (workInProgress.pendingProps.hidden && + workInProgress.pendingWorkPriority !== OffscreenPriority) { + // If this host component is hidden, we can bail out on the children. + // We'll rerender the children later at the lower priority. - var nextChildren = workInProgress.pendingProps.children; + // It is unfortunate that we have to do the reconciliation of these + // children already since that will add them to the tree even though + // they are not actually done yet. If this is a large set it is also + // confusing that this takes time to do right now instead of later. - let priority = workInProgress.pendingWorkPriority; - if (workInProgress.pendingProps.hidden && priority !== OffscreenPriority) { - // If this host component is hidden, we can reconcile its children at - // the lowest priority and bail out from this particular pass. Unless, we're - // currently reconciling the lowest priority. - workInProgress.child = ReactChildFiber.reconcileChildFibers( - workInProgress, - current ? current.child : null, - nextChildren, - OffscreenPriority - ); - workInProgress.pendingWorkPriority = OffscreenPriority; + if (workInProgress.progressedPriority === OffscreenPriority) { + // If we already made some progress on the offscreen priority before, + // then we should continue from where we left off. + workInProgress.child = workInProgress.progressedChild; + } + + // Reconcile the children and stash them for later work. + reconcileChildrenAtPriority(current, workInProgress, nextChildren, OffscreenPriority); + workInProgress.child = current ? current.child : null; + // Abort and don't process children yet. return null; } else { - workInProgress.child = ReactChildFiber.reconcileChildFibers( - workInProgress, - current ? current.child : null, - nextChildren, - priority - ); - workInProgress.pendingWorkPriority = NoWork; + reconcileChildren(current, workInProgress, nextChildren); return workInProgress.child; } } @@ -93,22 +266,21 @@ module.exports = function(config : HostConfig) { var props = workInProgress.pendingProps; var value = fn(props); if (typeof value === 'object' && value && typeof value.render === 'function') { - console.log('performed work on class:', fn.name); // Proceed under the assumption that this is a class instance workInProgress.tag = ClassComponent; - if (workInProgress.alternate) { - workInProgress.alternate.tag = ClassComponent; + if (current) { + current.tag = ClassComponent; } + value = value.render(); } else { - console.log('performed work on fn:', fn.name); // Proceed under the assumption that this is a functional component workInProgress.tag = FunctionalComponent; - if (workInProgress.alternate) { - workInProgress.alternate.tag = FunctionalComponent; + if (current) { + current.tag = FunctionalComponent; } } reconcileChildren(current, workInProgress, value); - workInProgress.pendingWorkPriority = NoWork; + return workInProgress.child; } function updateCoroutineComponent(current, workInProgress) { @@ -116,104 +288,102 @@ module.exports = function(config : HostConfig) { if (!coroutine) { throw new Error('Should be resolved by now'); } - console.log('begin coroutine', workInProgress.type.name); reconcileChildren(current, workInProgress, coroutine.children); - workInProgress.pendingWorkPriority = NoWork; } - function reuseChildren(returnFiber : Fiber, firstChild : Fiber) { - // TODO: None of this should be necessary if structured better. - // The returnFiber pointer only needs to be updated when we walk into this child - // which we don't do right now. If the pending work priority indicated only - // if a child has work rather than if the node has work, then we would know - // by a single lookup on workInProgress rather than having to go through - // each child. + /* + function reuseChildrenEffects(returnFiber : Fiber, firstChild : Fiber) { let child = firstChild; do { - // Update the returnFiber of the child to the newest fiber. - child.return = returnFiber; - // Retain the priority if there's any work left to do in the children. - if (child.pendingWorkPriority !== NoWork && - (returnFiber.pendingWorkPriority === NoWork || - returnFiber.pendingWorkPriority > child.pendingWorkPriority)) { - returnFiber.pendingWorkPriority = child.pendingWorkPriority; + // Ensure that the first and last effect of the parent corresponds + // to the children's first and last effect. + if (!returnFiber.firstEffect) { + returnFiber.firstEffect = child.firstEffect; + } + if (child.lastEffect) { + if (returnFiber.lastEffect) { + returnFiber.lastEffect.nextEffect = child.firstEffect; + } + returnFiber.lastEffect = child.lastEffect; } } while (child = child.sibling); } + */ - function beginWork(current : ?Fiber, workInProgress : Fiber) : ?Fiber { - // The current, flushed, state of this fiber is the alternate. - // Ideally nothing should rely on this, but relying on it here - // means that we don't need an additional field on the work in - // progress. - if (current && workInProgress.pendingProps === current.memoizedProps) { - // The most likely scenario is that the previous copy of the tree contains - // the same props as the new one. In that case, we can just copy the output - // and children from that node. - workInProgress.memoizedProps = workInProgress.pendingProps; + function bailoutOnAlreadyFinishedWork(current, workInProgress : Fiber) : ?Fiber { + const priorityLevel = workInProgress.pendingWorkPriority; + + // TODO: We should ideally be able to bail out early if the children have no + // more work to do. However, since we don't have a separation of this + // Fiber's priority and its children yet - we don't know without doing lots + // of the same work we do anyway. Once we have that separation we can just + // bail out here if the children has no more work at this priority level. + // if (workInProgress.priorityOfChildren <= priorityLevel) { + // // If there are side-effects in these children that have not yet been + // // committed we need to ensure that they get properly transferred up. + // if (current && current.child !== workInProgress.child) { + // reuseChildrenEffects(workInProgress, child); + // } + // return null; + // } + + cloneChildFibers(current, workInProgress); + markChildAsProgressed(current, workInProgress, priorityLevel); + return workInProgress.child; + } + + function bailoutOnLowPriority(current, workInProgress) { + if (current) { + workInProgress.child = current.child; + workInProgress.memoizedProps = current.memoizedProps; workInProgress.output = current.output; - const priorityLevel = workInProgress.pendingWorkPriority; - workInProgress.pendingProps = null; - workInProgress.pendingWorkPriority = NoWork; - workInProgress.stateNode = current.stateNode; - if (current.child) { - // If we bail out but still has work with the current priority in this - // subtree, we need to go find it right now. If we don't, we won't flush - // it until the next tick. - workInProgress.child = current.child; - reuseChildren(workInProgress, workInProgress.child); - if (workInProgress.pendingWorkPriority <= priorityLevel) { - // TODO: This passes the current node and reads the priority level and - // pending props from that. We want it to read our priority level and - // pending props from the work in progress. Needs restructuring. - return findNextUnitOfWorkAtPriority(workInProgress.alternate, priorityLevel); - } else { - return null; - } - } else { - workInProgress.child = null; - return null; - } + } + return null; + } + + function beginWork(current : ?Fiber, workInProgress : Fiber, priorityLevel : PriorityLevel) : ?Fiber { + if (workInProgress.pendingWorkPriority === NoWork || + workInProgress.pendingWorkPriority > priorityLevel) { + return bailoutOnLowPriority(current, workInProgress); } - if (!workInProgress.hasWorkInProgress && - workInProgress.pendingProps === workInProgress.memoizedProps && - workInProgress.pendingWorkPriority === NoWork) { - // If we started this work before, and finished it, or if we're in a - // ping-pong update scenario, this version could already be what we're - // looking for. In that case, we should be able to just bail out. - workInProgress.pendingProps = null; - // TODO: We should be able to bail out if there is remaining work at a lower - // priority too. However, I don't know if that is safe or even better since - // the other tree could've potentially finished that work. - return null; + if (workInProgress.progressedPriority === priorityLevel) { + // If we have progressed work on this priority level already, we can + // proceed this that as the child. + workInProgress.child = workInProgress.progressedChild; } - workInProgress.hasWorkInProgress = true; + if ((workInProgress.pendingProps === null || ( + workInProgress.memoizedProps !== null && + workInProgress.pendingProps === workInProgress.memoizedProps + )) && + workInProgress.updateQueue === null) { + return bailoutOnAlreadyFinishedWork(current, workInProgress); + } switch (workInProgress.tag) { case IndeterminateComponent: - mountIndeterminateComponent(current, workInProgress); - return workInProgress.child; + return mountIndeterminateComponent(current, workInProgress); case FunctionalComponent: - updateFunctionalComponent(current, workInProgress); - return workInProgress.child; + return updateFunctionalComponent(current, workInProgress); case ClassComponent: - console.log('class component', workInProgress.pendingProps.type.name); - return workInProgress.child; + return updateClassComponent(current, workInProgress); case HostContainer: reconcileChildren(current, workInProgress, workInProgress.pendingProps); // A yield component is just a placeholder, we can just run through the // next one immediately. - workInProgress.pendingWorkPriority = NoWork; if (workInProgress.child) { return beginWork( workInProgress.child.alternate, - workInProgress.child + workInProgress.child, + priorityLevel ); } return null; case HostComponent: + if (workInProgress.stateNode && config.beginUpdate) { + config.beginUpdate(workInProgress.stateNode); + } return updateHostComponent(current, workInProgress); case CoroutineHandlerPhase: // This is a restart. Reset the tag to the initial phase. @@ -226,18 +396,19 @@ module.exports = function(config : HostConfig) { if (workInProgress.child) { return beginWork( workInProgress.child.alternate, - workInProgress.child + workInProgress.child, + priorityLevel ); } return workInProgress.child; case YieldComponent: // A yield component is just a placeholder, we can just run through the // next one immediately. - workInProgress.pendingWorkPriority = NoWork; if (workInProgress.sibling) { return beginWork( workInProgress.sibling.alternate, - workInProgress.sibling + workInProgress.sibling, + priorityLevel ); } return null; diff --git a/src/renderers/shared/fiber/ReactFiberCommitWork.js b/src/renderers/shared/fiber/ReactFiberCommitWork.js index 7792be2102..beb773a2e7 100644 --- a/src/renderers/shared/fiber/ReactFiberCommitWork.js +++ b/src/renderers/shared/fiber/ReactFiberCommitWork.js @@ -22,15 +22,28 @@ var { HostContainer, HostComponent, } = ReactTypeOfWork; +var { callCallbacks } = require('ReactFiberUpdateQueue'); module.exports = function(config : HostConfig) { const updateContainer = config.updateContainer; const commitUpdate = config.commitUpdate; - function commitWork(finishedWork : Fiber) : void { + function commitWork(current : ?Fiber, finishedWork : Fiber) : void { switch (finishedWork.tag) { case ClassComponent: { + // Clear updates from current fiber. This must go before the callbacks + // are reset, in case an update is triggered from inside a callback. Is + // this safe? Relies on the assumption that work is only committed if + // the update queue is empty. + if (finishedWork.alternate) { + finishedWork.alternate.updateQueue = null; + } + if (finishedWork.callbackList) { + const { callbackList } = finishedWork; + finishedWork.callbackList = null; + callCallbacks(callbackList, finishedWork.stateNode); + } // TODO: Fire componentDidMount/componentDidUpdate, update refs return; } @@ -43,14 +56,13 @@ module.exports = function(config : HostConfig) { return; } case HostComponent: { - if (finishedWork.stateNode == null || !finishedWork.alternate) { + if (finishedWork.stateNode == null || !current) { throw new Error('This should only be done during updates.'); } // Commit the work prepared earlier. - const child = (finishedWork.child : ?Fiber); + const child = finishedWork.child; const children = (child && !child.sibling) ? (child.output : ?Fiber | I) : child; const newProps = finishedWork.memoizedProps; - const current = finishedWork.alternate; const oldProps = current.memoizedProps; const instance : I = finishedWork.stateNode; commitUpdate(instance, oldProps, newProps, children); diff --git a/src/renderers/shared/fiber/ReactFiberCompleteWork.js b/src/renderers/shared/fiber/ReactFiberCompleteWork.js index 9900a5b9fb..d4687f4574 100644 --- a/src/renderers/shared/fiber/ReactFiberCompleteWork.js +++ b/src/renderers/shared/fiber/ReactFiberCompleteWork.js @@ -17,7 +17,7 @@ import type { Fiber } from 'ReactFiber'; import type { HostConfig } from 'ReactFiberReconciler'; import type { ReifiedYield } from 'ReactReifiedYield'; -var ReactChildFiber = require('ReactChildFiber'); +var { reconcileChildFibers } = require('ReactChildFiber'); var ReactTypeOfWork = require('ReactTypeOfWork'); var { IndeterminateComponent, @@ -46,7 +46,9 @@ module.exports = function(config : HostConfig) { } } - /* + // TODO: It's possible this will create layout thrash issues because mutations + // of the DOM and life-cycles are interleaved. E.g. if a componentDidMount + // of a sibling reads, then the next sibling updates and reads etc. function markForPostEffect(workInProgress : Fiber) { // Schedule a side-effect on this fiber, AFTER the children's side-effects. if (workInProgress.lastEffect) { @@ -56,7 +58,6 @@ module.exports = function(config : HostConfig) { } workInProgress.lastEffect = workInProgress; } - */ function transferOutput(child : ?Fiber, returnFiber : Fiber) { // If we have a single result, we just pass that through as the output to @@ -113,7 +114,7 @@ module.exports = function(config : HostConfig) { var currentFirstChild = current ? current.stateNode : null; // Inherit the priority of the returnFiber. const priority = workInProgress.pendingWorkPriority; - workInProgress.stateNode = ReactChildFiber.reconcileChildFibers( + workInProgress.stateNode = reconcileChildFibers( workInProgress, currentFirstChild, nextChildren, @@ -125,12 +126,21 @@ module.exports = function(config : HostConfig) { function completeWork(current : ?Fiber, workInProgress : Fiber) : ?Fiber { switch (workInProgress.tag) { case FunctionalComponent: - console.log('/functional component', workInProgress.type.name); transferOutput(workInProgress.child, workInProgress); return null; case ClassComponent: - console.log('/class component', workInProgress.type.name); transferOutput(workInProgress.child, workInProgress); + // Don't use the state queue to compute the memoized state. We already + // merged it and assigned it to the instance. Transfer it from there. + // Also need to transfer the props, because pendingProps will be null + // in the case of an update + const { state, props } = workInProgress.stateNode; + workInProgress.memoizedState = state; + workInProgress.memoizedProps = props; + // Transfer update queue to callbackList field so callbacks can be + // called during commit phase. + workInProgress.callbackList = workInProgress.updateQueue; + markForPostEffect(workInProgress); return null; case HostContainer: transferOutput(workInProgress.child, workInProgress); @@ -142,30 +152,44 @@ module.exports = function(config : HostConfig) { markForPreEffect(workInProgress); return null; case HostComponent: - console.log('/host component', workInProgress.type); + let newProps = workInProgress.pendingProps; const child = workInProgress.child; const children = (child && !child.sibling) ? (child.output : ?Fiber | I) : child; - const newProps = workInProgress.pendingProps; - workInProgress.memoizedProps = newProps; if (current && workInProgress.stateNode != null) { // If we have an alternate, that means this is an update and we need to // schedule a side-effect to do the updates. const oldProps = current.memoizedProps; + // If we get updated because one of our children updated, we don't + // have newProps so we'll have to reuse them. + // TODO: Split the update API as separate for the props vs. children. + // Even better would be if children weren't special cased at all tho. + if (!newProps) { + newProps = oldProps; + } const instance : I = workInProgress.stateNode; if (prepareUpdate(instance, oldProps, newProps, children)) { // This returns true if there was something to update. markForPreEffect(workInProgress); } + // TODO: Is this actually ever going to change? Why set it every time? workInProgress.output = instance; } else { + if (!newProps) { + if (workInProgress.stateNode === null) { + throw new Error('We must have new props for new mounts.'); + } else { + // This can happen when we abort work. + return null; + } + } const instance = createInstance(workInProgress.type, newProps, children); // TODO: This seems like unnecessary duplication. workInProgress.stateNode = instance; workInProgress.output = instance; } + workInProgress.memoizedProps = newProps; return null; case CoroutineComponent: - console.log('/coroutine component', workInProgress.pendingProps.handler.name); return moveCoroutineToHandlerPhase(current, workInProgress); case CoroutineHandlerPhase: transferOutput(workInProgress.stateNode, workInProgress); diff --git a/src/renderers/shared/fiber/ReactFiberPendingWork.js b/src/renderers/shared/fiber/ReactFiberPendingWork.js deleted file mode 100644 index 15d1a10134..0000000000 --- a/src/renderers/shared/fiber/ReactFiberPendingWork.js +++ /dev/null @@ -1,93 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactFiberPendingWork - * @flow - */ - -'use strict'; - -import type { Fiber } from 'ReactFiber'; -import type { PriorityLevel } from 'ReactPriorityLevel'; - -var ReactFiber = require('ReactFiber'); - -var { - NoWork, -} = require('ReactPriorityLevel'); - -function cloneSiblings(current : Fiber, workInProgress : Fiber, returnFiber : Fiber) { - while (current.sibling) { - current = current.sibling; - workInProgress = workInProgress.sibling = ReactFiber.cloneFiber( - current, - current.pendingWorkPriority - ); - workInProgress.return = returnFiber; - } - workInProgress.sibling = null; -} - -exports.findNextUnitOfWorkAtPriority = function(currentRoot : Fiber, priorityLevel : PriorityLevel) : ?Fiber { - let current = currentRoot; - while (current) { - if (current.pendingWorkPriority !== NoWork && - current.pendingWorkPriority <= priorityLevel) { - // This node has work to do that fits our priority level criteria. - if (current.pendingProps !== null) { - // We found some work to do. We need to return the "work in progress" - // of this node which will be the alternate. - const workInProgress = current.alternate; - if (!workInProgress) { - throw new Error('Should have wip now'); - } - workInProgress.pendingProps = current.pendingProps; - return workInProgress; - } - // If we have a child let's see if any of our children has work to do. - // Only bother doing this at all if the current priority level matches - // because it is the highest priority for the whole subtree. - // TODO: Coroutines can have work in their stateNode which is another - // type of child that needs to be searched for work. - if (current.child) { - // Ensure we have a work in progress copy to backtrack through. - let currentChild = current.child; - let workInProgress = current.alternate; - if (!workInProgress) { - throw new Error('Should have wip now'); - } - workInProgress.pendingWorkPriority = current.pendingWorkPriority; - workInProgress.child = ReactFiber.cloneFiber(currentChild, NoWork); - workInProgress.child.return = workInProgress; - cloneSiblings(currentChild, workInProgress.child, workInProgress); - current = current.child; - continue; - } - // If we match the priority but has no child and no work to do, - // then we can safely reset the flag. - current.pendingWorkPriority = NoWork; - } - if (current === currentRoot) { - return null; - } - while (!current.sibling) { - current = current.return; - if (!current) { - return null; - } - if (current.pendingWorkPriority <= priorityLevel) { - // If this subtree had work left to do, we would have returned it by - // now. This could happen if a child with pending work gets cleaned up - // but we don't clear the flag then. It is safe to reset it now. - current.pendingWorkPriority = NoWork; - } - } - current = current.sibling; - } - return null; -}; diff --git a/src/renderers/shared/fiber/ReactFiberReconciler.js b/src/renderers/shared/fiber/ReactFiberReconciler.js index cb22e88421..f0443a43cc 100644 --- a/src/renderers/shared/fiber/ReactFiberReconciler.js +++ b/src/renderers/shared/fiber/ReactFiberReconciler.js @@ -15,14 +15,11 @@ import type { Fiber } from 'ReactFiber'; import type { FiberRoot } from 'ReactFiberRoot'; import type { TypeOfWork } from 'ReactTypeOfWork'; +import type { PriorityLevel } from 'ReactPriorityLevel'; var { createFiberRoot } = require('ReactFiberRoot'); var ReactFiberScheduler = require('ReactFiberScheduler'); -var { - LowPriority, -} = require('ReactPriorityLevel'); - type Deadline = { timeRemaining : () => number }; @@ -40,12 +37,12 @@ export type HostConfig = { updateContainer(containerInfo : C, children : HostChildren) : void; createInstance(type : T, props : P, children : HostChildren) : I, - prepareUpdate(instance : I, oldProps : P, newProps : P, children : HostChildren) : bool, + prepareUpdate(instance : I, oldProps : P, newProps : P, children : HostChildren) : boolean, commitUpdate(instance : I, oldProps : P, newProps : P, children : HostChildren) : void, deleteInstance(instance : I) : void, - scheduleHighPriCallback(callback : () => void) : void, - scheduleLowPriCallback(callback : (deadline : Deadline) => void) : void + scheduleAnimationCallback(callback : () => void) : void, + scheduleDeferredCallback(callback : (deadline : Deadline) => void) : void }; @@ -55,6 +52,7 @@ export type Reconciler = { mountContainer(element : ReactElement, containerInfo : C) : OpaqueNode, updateContainer(element : ReactElement, container : OpaqueNode) : void, unmountContainer(container : OpaqueNode) : void, + performWithPriority(priorityLevel : PriorityLevel, fn : Function) : void, // Used to extract the return value from the initial render. Legacy API. getPublicRootInstance(container : OpaqueNode) : (C | null), @@ -62,7 +60,7 @@ export type Reconciler = { module.exports = function(config : HostConfig) : Reconciler { - var { scheduleLowPriWork } = ReactFiberScheduler(config); + var { scheduleWork, performWithPriority } = ReactFiberScheduler(config); return { @@ -70,10 +68,11 @@ module.exports = function(config : HostConfig) : Reconci const root = createFiberRoot(containerInfo); const container = root.current; // TODO: Use pending work/state instead of props. + // TODO: This should not override the pendingWorkPriority if there is + // higher priority work in the subtree. container.pendingProps = element; - container.pendingWorkPriority = LowPriority; - scheduleLowPriWork(root); + scheduleWork(root); // It may seem strange that we don't return the root here, but that will // allow us to have containers that are in the middle of the tree instead @@ -86,9 +85,8 @@ module.exports = function(config : HostConfig) : Reconci const root : FiberRoot = (container.stateNode : any); // TODO: Use pending work/state instead of props. root.current.pendingProps = element; - root.current.pendingWorkPriority = LowPriority; - scheduleLowPriWork(root); + scheduleWork(root); }, unmountContainer(container : OpaqueNode) : void { @@ -96,11 +94,12 @@ module.exports = function(config : HostConfig) : Reconci const root : FiberRoot = (container.stateNode : any); // TODO: Use pending work/state instead of props. root.current.pendingProps = []; - root.current.pendingWorkPriority = LowPriority; - scheduleLowPriWork(root); + scheduleWork(root); }, + performWithPriority, + getPublicRootInstance(container : OpaqueNode) : (C | null) { return null; }, diff --git a/src/renderers/shared/fiber/ReactFiberRoot.js b/src/renderers/shared/fiber/ReactFiberRoot.js index c0b312253c..1c972700b0 100644 --- a/src/renderers/shared/fiber/ReactFiberRoot.js +++ b/src/renderers/shared/fiber/ReactFiberRoot.js @@ -22,7 +22,7 @@ export type FiberRoot = { // The currently active root fiber. This is the mutable root of the tree. current: Fiber, // Determines if this root has already been added to the schedule for work. - isScheduled: bool, + isScheduled: boolean, // The work schedule is a linked list. nextScheduledRoot: ?FiberRoot, }; diff --git a/src/renderers/shared/fiber/ReactFiberScheduler.js b/src/renderers/shared/fiber/ReactFiberScheduler.js index 6df6198f9f..5bc128f5e5 100644 --- a/src/renderers/shared/fiber/ReactFiberScheduler.js +++ b/src/renderers/shared/fiber/ReactFiberScheduler.js @@ -15,34 +15,48 @@ import type { Fiber } from 'ReactFiber'; import type { FiberRoot } from 'ReactFiberRoot'; import type { HostConfig } from 'ReactFiberReconciler'; +import type { PriorityLevel } from 'ReactPriorityLevel'; var ReactFiberBeginWork = require('ReactFiberBeginWork'); var ReactFiberCompleteWork = require('ReactFiberCompleteWork'); var ReactFiberCommitWork = require('ReactFiberCommitWork'); var { cloneFiber } = require('ReactFiber'); -var { findNextUnitOfWorkAtPriority } = require('ReactFiberPendingWork'); var { NoWork, - HighPriority, LowPriority, - OffscreenPriority, + AnimationPriority, + SynchronousPriority, } = require('ReactPriorityLevel'); var timeHeuristicForUnitOfWork = 1; -module.exports = function(config : HostConfig) { +export type Scheduler = { + scheduleDeferredWork: (root : FiberRoot, priority : PriorityLevel) => void +}; - const { beginWork } = ReactFiberBeginWork(config); +module.exports = function(config : HostConfig) { + // Use a closure to circumvent the circular dependency between the scheduler + // and ReactFiberBeginWork. Don't know if there's a better way to do this. + let scheduler; + function getScheduler(): Scheduler { + return scheduler; + } + + const { beginWork } = ReactFiberBeginWork(config, getScheduler); const { completeWork } = ReactFiberCompleteWork(config); const { commitWork } = ReactFiberCommitWork(config); - // const scheduleHighPriCallback = config.scheduleHighPriCallback; - const scheduleLowPriCallback = config.scheduleLowPriCallback; + const scheduleAnimationCallback = config.scheduleAnimationCallback; + const scheduleDeferredCallback = config.scheduleDeferredCallback; + + // The default priority to use for updates. + let defaultPriority : PriorityLevel = LowPriority; // The next work in progress fiber that we're currently working on. let nextUnitOfWork : ?Fiber = null; + let nextPriorityLevel : PriorityLevel = NoWork; // Linked list of roots with scheduled work on them. let nextScheduledRoot : ?FiberRoot = null; @@ -55,32 +69,34 @@ module.exports = function(config : HostConfig) { if (nextScheduledRoot === lastScheduledRoot) { nextScheduledRoot = null; lastScheduledRoot = null; + nextPriorityLevel = NoWork; return null; } nextScheduledRoot = nextScheduledRoot.nextScheduledRoot; } + // TODO: This is scanning one root at a time. It should be scanning all + // roots for high priority work before moving on to lower priorities. let root = nextScheduledRoot; + let highestPriorityRoot = null; + let highestPriorityLevel = NoWork; while (root) { - cloneFiber(root.current, root.current.pendingWorkPriority); - // Find the highest possible priority work to do. - // This loop is unrolled just to satisfy Flow's enum constraint. - // We could make arbitrary many idle priority levels but having - // too many just means flushing changes too often. - let work = findNextUnitOfWorkAtPriority(root.current, HighPriority); - if (work) { - return work; - } - work = findNextUnitOfWorkAtPriority(root.current, LowPriority); - if (work) { - return work; - } - work = findNextUnitOfWorkAtPriority(root.current, OffscreenPriority); - if (work) { - return work; + if (highestPriorityLevel === NoWork || + highestPriorityLevel > root.current.pendingWorkPriority) { + highestPriorityLevel = root.current.pendingWorkPriority; + highestPriorityRoot = root; } // We didn't find anything to do in this root, so let's try the next one. root = root.nextScheduledRoot; } + if (highestPriorityRoot) { + nextPriorityLevel = highestPriorityLevel; + return cloneFiber( + highestPriorityRoot.current, + highestPriorityLevel + ); + } + + nextPriorityLevel = NoWork; return null; } @@ -89,7 +105,8 @@ module.exports = function(config : HostConfig) { // TODO: Error handling. let effectfulFiber = finishedWork.firstEffect; while (effectfulFiber) { - commitWork(effectfulFiber); + const current = effectfulFiber.alternate; + commitWork(current, effectfulFiber); const next = effectfulFiber.nextEffect; // Ensure that we clean these up so that we don't accidentally keep them. // I'm not actually sure this matters because we can't reset firstEffect @@ -100,6 +117,24 @@ module.exports = function(config : HostConfig) { } } + function resetWorkPriority(workInProgress : Fiber) { + let newPriority = NoWork; + // progressedChild is going to be the child set with the highest priority. + // Either it is the same as child, or it just bailed out because it choose + // not to do the work. + let child = workInProgress.progressedChild; + while (child) { + // Ensure that remaining work priority bubbles up. + if (child.pendingWorkPriority !== NoWork && + (newPriority === NoWork || + newPriority > child.pendingWorkPriority)) { + newPriority = child.pendingWorkPriority; + } + child = child.sibling; + } + workInProgress.pendingWorkPriority = newPriority; + } + function completeUnitOfWork(workInProgress : Fiber) : ?Fiber { while (true) { // The current, flushed, state of this fiber is the alternate. @@ -109,22 +144,16 @@ module.exports = function(config : HostConfig) { const current = workInProgress.alternate; const next = completeWork(current, workInProgress); + resetWorkPriority(workInProgress); + // The work is now done. We don't need this anymore. This flags // to the system not to redo any work here. workInProgress.pendingProps = null; - if (workInProgress.pendingWorkPriority === NoWork) { - workInProgress.hasWorkInProgress = false; - } + workInProgress.updateQueue = null; const returnFiber = workInProgress.return; if (returnFiber) { - // Ensure that remaining work priority bubbles up. - if (workInProgress.pendingWorkPriority !== NoWork && - (returnFiber.pendingWorkPriority === NoWork || - returnFiber.pendingWorkPriority > workInProgress.pendingWorkPriority)) { - returnFiber.pendingWorkPriority = workInProgress.pendingWorkPriority; - } // Ensure that the first and last effect of the parent corresponds // to the children's first and last effect. This probably relies on // children completing in order. @@ -148,15 +177,21 @@ module.exports = function(config : HostConfig) { } else if (returnFiber) { // If there's no more work in this returnFiber. Complete the returnFiber. workInProgress = returnFiber; + continue; } else { // If we're at the root, there's no more work to do. We can flush it. const root : FiberRoot = (workInProgress.stateNode : any); + if (root.current === workInProgress) { + throw new Error( + 'Cannot commit the same tree as before. This is probably a bug ' + + 'related to the return field.' + ); + } root.current = workInProgress; // TODO: We can be smarter here and only look for more work in the // "next" scheduled work since we've already scanned passed. That // also ensures that work scheduled during reconciliation gets deferred. // const hasMoreWork = workInProgress.pendingWorkPriority !== NoWork; - console.log('----- COMPLETED with remaining work:', workInProgress.pendingWorkPriority); commitAllWork(workInProgress); const nextWork = findNextUnitOfWork(); // if (!nextWork && hasMoreWork) { @@ -172,16 +207,13 @@ module.exports = function(config : HostConfig) { } function performUnitOfWork(workInProgress : Fiber) : ?Fiber { - // Ignore work if there is nothing to do. - if (workInProgress.pendingProps === null) { - return completeUnitOfWork(workInProgress); - } // The current, flushed, state of this fiber is the alternate. // Ideally nothing should rely on this, but relying on it here // means that we don't need an additional field on the work in // progress. const current = workInProgress.alternate; - const next = beginWork(current, workInProgress); + const next = beginWork(current, workInProgress, nextPriorityLevel); + if (next) { // If this spawns new work, do that next. return next; @@ -191,7 +223,7 @@ module.exports = function(config : HostConfig) { } } - function performLowPriWork(deadline) { + function performDeferredWork(deadline) { if (!nextUnitOfWork) { nextUnitOfWork = findNextUnitOfWork(); } @@ -203,17 +235,25 @@ module.exports = function(config : HostConfig) { nextUnitOfWork = findNextUnitOfWork(); } } else { - scheduleLowPriCallback(performLowPriWork); + scheduleDeferredCallback(performDeferredWork); return; } } } - function scheduleLowPriWork(root : FiberRoot) { + function scheduleDeferredWork(root : FiberRoot, priority : PriorityLevel) { // We must reset the current unit of work pointer so that we restart the // search from the root during the next tick, in case there is now higher // priority work somewhere earlier than before. - nextUnitOfWork = null; + if (priority <= nextPriorityLevel) { + nextUnitOfWork = null; + } + + // Set the priority on the root, without deprioritizing + if (root.current.pendingWorkPriority === NoWork || + priority <= root.current.pendingWorkPriority) { + root.current.pendingWorkPriority = priority; + } if (root.isScheduled) { // If we're already scheduled, we can bail out. @@ -228,21 +268,81 @@ module.exports = function(config : HostConfig) { // We're the only work scheduled. nextScheduledRoot = root; lastScheduledRoot = root; - scheduleLowPriCallback(performLowPriWork); + scheduleDeferredCallback(performDeferredWork); } } - /* - function performHighPriWork() { - // There is no such thing as high pri work yet. + function performAnimationWork() { + // Always start from the root + nextUnitOfWork = findNextUnitOfWork(); + while (nextUnitOfWork && + nextPriorityLevel !== NoWork) { + nextUnitOfWork = performUnitOfWork(nextUnitOfWork); + if (!nextUnitOfWork) { + // Keep searching for animation work until there's no more left + nextUnitOfWork = findNextUnitOfWork(); + } + // Stop if the next unit of work is low priority + if (nextPriorityLevel > AnimationPriority) { + scheduleDeferredCallback(performDeferredWork); + return; + } + } } - function ensureHighPriIsScheduled() { - scheduleHighPriCallback(performHighPriWork); - } - */ + function scheduleAnimationWork(root: FiberRoot, priorityLevel : PriorityLevel) { + // Set the priority on the root, without deprioritizing + if (root.current.pendingWorkPriority === NoWork || + priorityLevel <= root.current.pendingWorkPriority) { + root.current.pendingWorkPriority = priorityLevel; + } - return { - scheduleLowPriWork: scheduleLowPriWork, + if (root.isScheduled) { + // If we're already scheduled, we can bail out. + return; + } + root.isScheduled = true; + if (lastScheduledRoot) { + // Schedule ourselves to the end. + lastScheduledRoot.nextScheduledRoot = root; + lastScheduledRoot = root; + } else { + // We're the only work scheduled. + nextScheduledRoot = root; + lastScheduledRoot = root; + scheduleAnimationCallback(performAnimationWork); + } + } + + function scheduleWork(root : FiberRoot) { + if (defaultPriority === SynchronousPriority) { + throw new Error('Not implemented yet'); + } + + if (defaultPriority === NoWork) { + return; + } + if (defaultPriority > AnimationPriority) { + scheduleDeferredWork(root, defaultPriority); + return; + } + scheduleAnimationWork(root, defaultPriority); + } + + function performWithPriority(priorityLevel : PriorityLevel, fn : Function) { + const previousDefaultPriority = defaultPriority; + defaultPriority = priorityLevel; + try { + fn(); + } finally { + defaultPriority = previousDefaultPriority; + } + } + + scheduler = { + scheduleWork: scheduleWork, + scheduleDeferredWork: scheduleDeferredWork, + performWithPriority: performWithPriority, }; + return scheduler; }; diff --git a/src/renderers/shared/fiber/ReactFiberUpdateQueue.js b/src/renderers/shared/fiber/ReactFiberUpdateQueue.js new file mode 100644 index 0000000000..aab252b655 --- /dev/null +++ b/src/renderers/shared/fiber/ReactFiberUpdateQueue.js @@ -0,0 +1,89 @@ +/** + * Copyright 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactFiberUpdateQueue + * @flow + */ + +'use strict'; + +type UpdateQueueNode = { + partialState: any, + callback: ?Function, + callbackWasCalled: boolean, + next: ?UpdateQueueNode, +}; + +export type UpdateQueue = UpdateQueueNode & { + isReplace: boolean, + isForced: boolean, + tail: UpdateQueueNode +}; + +exports.createUpdateQueue = function(partialState : mixed) : UpdateQueue { + const queue = { + partialState, + callback: null, + callbackWasCalled: false, + next: null, + isReplace: false, + isForced: false, + tail: (null : any), + }; + queue.tail = queue; + return queue; +}; + +exports.addToQueue = function(queue : UpdateQueue, partialState : mixed) : UpdateQueue { + const node = { + partialState, + callback: null, + callbackWasCalled: false, + next: null, + }; + queue.tail.next = node; + queue.tail = node; + return queue; +}; + +exports.addCallbackToQueue = function(queue : UpdateQueue, callback: Function) : UpdateQueue { + if (queue.tail.callback) { + // If the tail already as a callback, add an empty node to queue + exports.addToQueue(queue, null); + } + queue.tail.callback = callback; + return queue; +}; + +exports.callCallbacks = function(queue : UpdateQueue, context : any) { + let node : ?UpdateQueueNode = queue; + while (node) { + if (node.callback && !node.callbackWasCalled) { + node.callbackWasCalled = true; + node.callback.call(context); + } + node = node.next; + } +}; + +exports.mergeUpdateQueue = function(queue : UpdateQueue, prevState : any, props : any) : any { + let node : ?UpdateQueueNode = queue; + let state = queue.isReplace ? null : Object.assign({}, prevState); + while (node) { + let partialState; + if (typeof node.partialState === 'function') { + const updateFn = node.partialState; + partialState = updateFn(state, props); + } else { + partialState = node.partialState; + } + state = Object.assign(state || {}, partialState); + node = node.next; + } + return state; +}; diff --git a/src/renderers/shared/fiber/ReactReifiedYield.js b/src/renderers/shared/fiber/ReactReifiedYield.js index 3f0e8a62e5..41ef6b9218 100644 --- a/src/renderers/shared/fiber/ReactReifiedYield.js +++ b/src/renderers/shared/fiber/ReactReifiedYield.js @@ -15,12 +15,12 @@ import type { ReactYield } from 'ReactCoroutine'; import type { Fiber } from 'ReactFiber'; -var ReactFiber = require('ReactFiber'); +var { createFiberFromElementType } = require('ReactFiber'); export type ReifiedYield = { continuation: Fiber, props: Object }; exports.createReifiedYield = function(yieldNode : ReactYield) : ReifiedYield { - var fiber = ReactFiber.createFiberFromElementType( + var fiber = createFiberFromElementType( yieldNode.continuation, yieldNode.key ); diff --git a/src/renderers/shared/fiber/__tests__/ReactCoroutine-test.js b/src/renderers/shared/fiber/__tests__/ReactCoroutine-test.js index 24cddfec66..5f75c92807 100644 --- a/src/renderers/shared/fiber/__tests__/ReactCoroutine-test.js +++ b/src/renderers/shared/fiber/__tests__/ReactCoroutine-test.js @@ -15,15 +15,14 @@ var React; var ReactNoop; var ReactCoroutine; -describe('ReactCoroutine', function() { - beforeEach(function() { +describe('ReactCoroutine', () => { + beforeEach(() => { React = require('React'); ReactNoop = require('ReactNoop'); ReactCoroutine = require('ReactCoroutine'); - spyOn(console, 'log'); }); - xit('should render a coroutine', function() { + xit('should render a coroutine', () => { var ops = []; diff --git a/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js b/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js index 1fd0ac9fe9..f13573c91f 100644 --- a/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js +++ b/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js @@ -14,14 +14,13 @@ var React; var ReactNoop; -describe('ReactIncremental', function() { - beforeEach(function() { +describe('ReactIncremental', () => { + beforeEach(() => { React = require('React'); ReactNoop = require('ReactNoop'); - spyOn(console, 'log'); }); - it('should render a simple component', function() { + it('should render a simple component', () => { function Bar() { return
Hello World
; @@ -36,7 +35,7 @@ describe('ReactIncremental', function() { }); - it('should render a simple component, in steps if needed', function() { + it('should render a simple component, in steps if needed', () => { var barCalled = false; function Bar() { @@ -57,16 +56,16 @@ describe('ReactIncremental', function() { expect(fooCalled).toBe(false); expect(barCalled).toBe(false); // Do one step of work. - ReactNoop.flushLowPri(7); + ReactNoop.flushDeferredPri(7); expect(fooCalled).toBe(true); expect(barCalled).toBe(false); // Do the rest of the work. - ReactNoop.flushLowPri(50); + ReactNoop.flushDeferredPri(50); expect(fooCalled).toBe(true); expect(barCalled).toBe(true); }); - it('updates a previous render', function() { + it('updates a previous render', () => { var ops = []; @@ -117,7 +116,7 @@ describe('ReactIncremental', function() { }); - it('can cancel partially rendered work and restart', function() { + it('can cancel partially rendered work and restart', () => { var ops = []; @@ -144,7 +143,7 @@ describe('ReactIncremental', function() { ReactNoop.render(); // Flush part of the work - ReactNoop.flushLowPri(20); + ReactNoop.flushDeferredPri(20); expect(ops).toEqual(['Foo', 'Bar']); @@ -154,7 +153,7 @@ describe('ReactIncremental', function() { ReactNoop.render(); // Flush part of the new work - ReactNoop.flushLowPri(20); + ReactNoop.flushDeferredPri(20); expect(ops).toEqual(['Foo', 'Bar']); @@ -165,7 +164,7 @@ describe('ReactIncremental', function() { }); - it('can deprioritize unfinished work and resume it later', function() { + it('can deprioritize unfinished work and resume it later', () => { var ops = []; @@ -206,7 +205,7 @@ describe('ReactIncremental', function() { // Render part of the work. This should be enough to flush everything except // the middle which has lower priority. ReactNoop.render(); - ReactNoop.flushLowPri(40); + ReactNoop.flushDeferredPri(40); expect(ops).toEqual(['Foo', 'Bar', 'Bar']); @@ -219,7 +218,64 @@ describe('ReactIncremental', function() { }); - it('can resume work in a subtree even when a parent bails out', function() { + it('can deprioritize a tree from without dropping work', () => { + var ops = []; + + function Bar(props) { + ops.push('Bar'); + return
{props.children}
; + } + + function Middle(props) { + ops.push('Middle'); + return {props.children}; + } + + function Foo(props) { + ops.push('Foo'); + return ( +
+ {props.text} + + {props.text} +
+ Footer +
+
+ ); + } + + // Init + ReactNoop.performAnimationWork(() => { + ReactNoop.render(); + }); + ReactNoop.flush(); + + expect(ops).toEqual(['Foo', 'Bar', 'Bar', 'Middle', 'Middle']); + + ops = []; + + // Render the high priority work (everying except the hidden trees). + ReactNoop.performAnimationWork(() => { + ReactNoop.render(); + }); + ReactNoop.render(); + ReactNoop.flushAnimationPri(); + + expect(ops).toEqual(['Foo', 'Bar', 'Bar']); + + ops = []; + + // The hidden content was deprioritized from high to low priority. A low + // priority callback should have been scheduled. Flush it now. + ReactNoop.flushDeferredPri(); + + expect(ops).toEqual(['Middle', 'Middle']); + }); + + it('can resume work in a subtree even when a parent bails out', () => { var ops = []; @@ -264,7 +320,7 @@ describe('ReactIncremental', function() { // Init ReactNoop.render(); - ReactNoop.flushLowPri(52); + ReactNoop.flushDeferredPri(52); expect(ops).toEqual(['Foo', 'Bar', 'Tester', 'Bar']); @@ -272,7 +328,7 @@ describe('ReactIncremental', function() { // We're now rendering an update that will bail out on updating middle. ReactNoop.render(); - ReactNoop.flushLowPri(45); + ReactNoop.flushDeferredPri(45); expect(ops).toEqual(['Foo', 'Bar', 'Bar']); @@ -283,8 +339,7 @@ describe('ReactIncremental', function() { expect(ops).toEqual(['Middle']); }); - it('can resume work in a bailed subtree within one pass', function() { - + it('can resume work in a bailed subtree within one pass', () => { var ops = []; function Bar(props) { @@ -292,11 +347,16 @@ describe('ReactIncremental', function() { return
{props.children}
; } - function Tester() { - // This component is just here to ensure that the bail out is - // in fact in effect in the expected place for this test. - ops.push('Tester'); - return
; + class Tester extends React.Component { + shouldComponentUpdate() { + return false; + } + render() { + // This component is just here to ensure that the bail out is + // in fact in effect in the expected place for this test. + ops.push('Tester'); + return
; + } } function Middle(props) { @@ -304,23 +364,30 @@ describe('ReactIncremental', function() { return {props.children}; } - var middleContent = ( - - - - - ); + // Should content not just bail out on current, not workInProgress? + + class Content extends React.Component { + shouldComponentUpdate() { + return false; + } + render() { + return [ + , + , + ]; + } + } function Foo(props) { ops.push('Foo'); return ( ); @@ -328,7 +395,7 @@ describe('ReactIncremental', function() { // Init ReactNoop.render(); - ReactNoop.flushLowPri(52); + ReactNoop.flushDeferredPri(52); expect(ops).toEqual(['Foo', 'Bar', 'Tester', 'Bar']); @@ -337,7 +404,7 @@ describe('ReactIncremental', function() { // Make a quick update which will create a low pri tree on top of the // already low pri tree. ReactNoop.render(); - ReactNoop.flushLowPri(15); + ReactNoop.flushDeferredPri(15); expect(ops).toEqual(['Foo']); @@ -350,10 +417,9 @@ describe('ReactIncremental', function() { // after them which is not correct. ReactNoop.flush(); expect(ops).toEqual(['Bar', 'Middle', 'Bar']); - }); - it('can reuse work done after being preempted', function() { + it('can reuse work done after being preempted', () => { var ops = []; @@ -375,19 +441,23 @@ describe('ReactIncremental', function() {
); + var step0 = ( +
+ Hi + {'Foo'} + There +
+ ); + function Foo(props) { ops.push('Foo'); return (
- {props.text} + {props.text2} @@ -395,35 +465,46 @@ describe('ReactIncremental', function() { ); } - // Start rendering an update - // Init - ReactNoop.render(); + ReactNoop.render(); + ReactNoop.flushDeferredPri(55 + 25); + + // We only finish the higher priority work. So the low pri content + // has not yet finished mounting. + expect(ops).toEqual(['Foo', 'Bar', 'Middle', 'Bar']); + + ops = []; + + // Interupt the rendering with a quick update. This should not touch the + // middle content. + ReactNoop.render(); ReactNoop.flush(); - expect(ops).toEqual(['Foo', 'Bar', 'Middle', 'Bar', 'Middle']); + // We've now rendered the entire tree but we didn't have to redo the work + // done by the first Middle and Bar already. + expect(ops).toEqual(['Foo', 'Bar', 'Middle']); ops = []; // Make a quick update which will schedule low priority work to // update the middle content. - ReactNoop.render(); - ReactNoop.flushLowPri(30); + ReactNoop.render(); + ReactNoop.flushDeferredPri(30 + 25); expect(ops).toEqual(['Foo', 'Bar']); ops = []; // The middle content is now pending rendering... - ReactNoop.flushLowPri(30); + ReactNoop.flushDeferredPri(30); expect(ops).toEqual(['Middle', 'Bar']); ops = []; // but we'll interupt it to render some higher priority work. // The middle content will bailout so it remains untouched. - ReactNoop.render(); - ReactNoop.flushLowPri(30); + ReactNoop.render(); + ReactNoop.flushDeferredPri(30); expect(ops).toEqual(['Foo', 'Bar']); @@ -437,4 +518,303 @@ describe('ReactIncremental', function() { }); + it('can reuse work if shouldComponentUpdate is false, after being preempted', () => { + + var ops = []; + + function Bar(props) { + ops.push('Bar'); + return
{props.children}
; + } + + class Middle extends React.Component { + shouldComponentUpdate(nextProps) { + return this.props.children !== nextProps.children; + } + render() { + ops.push('Middle'); + return {this.props.children}; + } + } + + class Content extends React.Component { + shouldComponentUpdate(nextProps) { + return this.props.step !== nextProps.step; + } + render() { + ops.push('Content'); + return ( +
+ {this.props.step === 0 ? 'Hi' : 'Hello'} + {this.props.step === 0 ? this.props.text : '-'} + {this.props.step === 0 ? 'There' : 'World'} +
+ ); + } + } + + function Foo(props) { + ops.push('Foo'); + return ( +
+ {props.text} + +
+ ); + } + + // Init + ReactNoop.render(); + ReactNoop.flush(); + + expect(ops).toEqual(['Foo', 'Bar', 'Content', 'Middle', 'Bar', 'Middle']); + + ops = []; + + // Make a quick update which will schedule low priority work to + // update the middle content. + ReactNoop.render(); + ReactNoop.flushDeferredPri(30); + + expect(ops).toEqual(['Foo', 'Bar']); + + ops = []; + + // The middle content is now pending rendering... + ReactNoop.flushDeferredPri(30 + 25); + expect(ops).toEqual(['Content', 'Middle', 'Bar']); // One more Middle left. + + ops = []; + + // but we'll interupt it to render some higher priority work. + // The middle content will bailout so it remains untouched. + ReactNoop.render(); + ReactNoop.flushDeferredPri(30); + + expect(ops).toEqual(['Foo', 'Bar']); + + ops = []; + + // Since we did nothing to the middle subtree during the interuption, + // we should be able to reuse the reconciliation work that we already did + // without restarting. + ReactNoop.flush(); + // TODO: Content never fully completed its render so can't completely bail + // out on the entire subtree. However, we could do a shallow bail out and + // not rerender Content, but keep going down the incomplete tree. + // Normally shouldComponentUpdate->false is not enough to determine that we + // can safely reuse the old props, but I think in this case it would be ok, + // since it is a resume of already started work. + // Because of the above we can also not reuse the work of Bar because the + // rerender of Content will generate a new element which will mean we don't + // auto-bail out from Bar. + expect(ops).toEqual(['Content', 'Bar', 'Middle']); + + }); + + it('can update in the middle of a tree using setState', () => { + let instance; + class Bar extends React.Component { + constructor() { + super(); + this.state = { a: 'a' }; + instance = this; + } + render() { + return
{this.props.children}
; + } + } + + function Foo() { + return ( +
+ +
+ ); + } + + ReactNoop.render(); + ReactNoop.flush(); + expect(instance.state).toEqual({ a: 'a' }); + instance.setState({ b: 'b' }); + ReactNoop.flush(); + expect(instance.state).toEqual({ a: 'a', b: 'b' }); + }); + + it('can queue multiple state updates', () => { + let instance; + class Bar extends React.Component { + constructor() { + super(); + this.state = { a: 'a' }; + instance = this; + } + render() { + return
{this.props.children}
; + } + } + + function Foo() { + return ( +
+ +
+ ); + } + + ReactNoop.render(); + ReactNoop.flush(); + // Call setState multiple times before flushing + instance.setState({ b: 'b' }); + instance.setState({ c: 'c' }); + instance.setState({ d: 'd' }); + ReactNoop.flush(); + expect(instance.state).toEqual({ a: 'a', b: 'b', c: 'c', d: 'd' }); + }); + + it('can use updater form of setState', () => { + let instance; + class Bar extends React.Component { + constructor() { + super(); + this.state = { num: 1 }; + instance = this; + } + render() { + return
{this.props.children}
; + } + } + + function Foo({ multiplier }) { + return ( +
+ +
+ ); + } + + function updater(state, props) { + return { num: state.num * props.multiplier }; + } + + ReactNoop.render(); + ReactNoop.flush(); + expect(instance.state.num).toEqual(1); + instance.setState(updater); + ReactNoop.flush(); + expect(instance.state.num).toEqual(2); + instance.setState(updater); + ReactNoop.render(); + ReactNoop.flush(); + expect(instance.state.num).toEqual(6); + }); + + it('can call setState inside update callback', () => { + let instance; + class Bar extends React.Component { + constructor() { + super(); + this.state = { num: 1 }; + instance = this; + } + render() { + return
{this.props.children}
; + } + } + + function Foo({ multiplier }) { + return ( +
+ +
+ ); + } + + function updater(state, props) { + return { num: state.num * props.multiplier }; + } + + function callback() { + this.setState({ called: true }); + } + + ReactNoop.render(); + ReactNoop.flush(); + instance.setState(updater); + instance.setState(updater, callback); + ReactNoop.flush(); + expect(instance.state.num).toEqual(4); + expect(instance.state.called).toEqual(true); + }); + + it('can replaceState', () => { + let instance; + const Bar = React.createClass({ + getInitialState() { + instance = this; + return { a: 'a' }; + }, + render() { + return
{this.props.children}
; + }, + }); + + function Foo() { + return ( +
+ +
+ ); + } + + ReactNoop.render(); + ReactNoop.flush(); + instance.setState({ b: 'b' }); + instance.setState({ c: 'c' }); + instance.replaceState({ d: 'd' }); + ReactNoop.flush(); + expect(instance.state).toEqual({ d: 'd' }); + }); + + it('can forceUpdate', () => { + const ops = []; + + function Baz() { + ops.push('Baz'); + return
; + } + + let instance; + class Bar extends React.Component { + constructor() { + super(); + instance = this; + } + shouldComponentUpdate() { + return false; + } + render() { + ops.push('Bar'); + return ; + } + } + + function Foo() { + ops.push('Foo'); + return ( +
+ +
+ ); + } + + ReactNoop.render(); + ReactNoop.flush(); + expect(ops).toEqual(['Foo', 'Bar', 'Baz']); + instance.forceUpdate(); + ReactNoop.flush(); + expect(ops).toEqual(['Foo', 'Bar', 'Baz', 'Bar', 'Baz']); + }); }); diff --git a/src/renderers/shared/fiber/__tests__/ReactIncrementalSideEffects-test.js b/src/renderers/shared/fiber/__tests__/ReactIncrementalSideEffects-test.js index c59c12b97d..901b55f0df 100644 --- a/src/renderers/shared/fiber/__tests__/ReactIncrementalSideEffects-test.js +++ b/src/renderers/shared/fiber/__tests__/ReactIncrementalSideEffects-test.js @@ -14,22 +14,21 @@ var React; var ReactNoop; -describe('ReactIncremental', function() { - beforeEach(function() { +describe('ReactIncrementalSideEffects', () => { + beforeEach(() => { React = require('React'); ReactNoop = require('ReactNoop'); - spyOn(console, 'log'); }); function div(...children) { - return { type: 'div', children }; + return { type: 'div', children, prop: undefined }; } - function span(...children) { - return { type: 'span', children }; + function span(prop) { + return { type: 'span', children: [], prop }; } - it('can update child nodes of a host instance', function() { + it('can update child nodes of a host instance', () => { function Bar(props) { return {props.text}; @@ -58,10 +57,10 @@ describe('ReactIncremental', function() { }); - it('does not update child nodes if a flush is aborted', function() { + it('does not update child nodes if a flush is aborted', () => { function Bar(props) { - return {props.text}; + return ; } function Foo(props) { @@ -79,19 +78,310 @@ describe('ReactIncremental', function() { ReactNoop.render(); ReactNoop.flush(); expect(ReactNoop.root.children).toEqual([ - div(div(span(), span()), span()), + div(div(span('Hello'), span('Hello')), span('Yo')), ]); ReactNoop.render(); - ReactNoop.flushLowPri(35); + ReactNoop.flushDeferredPri(35); expect(ReactNoop.root.children).toEqual([ - div(div(span(), span()), span()), + div(div(span('Hello'), span('Hello')), span('Yo')), ]); }); + it('preserves a previously rendered node when deprioritized', () => { + + function Middle(props) { + return ; + } + + function Foo(props) { + return ( +
+ +
+ ); + } + + ReactNoop.render(); + ReactNoop.flush(); + + expect(ReactNoop.root.children).toEqual([ + div(div(span('foo'))), + ]); + + ReactNoop.render(); + ReactNoop.flushDeferredPri(20); + + expect(ReactNoop.root.children).toEqual([ + div(div(span('foo'))), + ]); + + ReactNoop.flush(); + + expect(ReactNoop.root.children).toEqual([ + div(div(span('bar'))), + ]); + + }); + + it('can reuse side-effects after being preempted', () => { + + function Bar(props) { + return ; + } + + var middleContent = ( +
+ Hello + World +
+ ); + + function Foo(props) { + return ( + + ); + } + + // Init + ReactNoop.render(); + ReactNoop.flush(); + + expect(ReactNoop.root.children).toEqual([ + div(div(span('Hi'), span('foo'))), + ]); + + // Make a quick update which will schedule low priority work to + // update the middle content. + ReactNoop.render(); + ReactNoop.flushDeferredPri(30); + + // The tree remains unchanged. + expect(ReactNoop.root.children).toEqual([ + div(div(span('Hi'), span('foo'))), + ]); + + // The first Bar has already completed its update but we'll interupt it to + // render some higher priority work. The middle content will bailout so + // it remains untouched which means that it should reuse it next time. + ReactNoop.render(); + ReactNoop.flush(); + + // Since we did nothing to the middle subtree during the interuption, + // we should be able to reuse the reconciliation work that we already did + // without restarting. The side-effects should still be replayed. + + expect(ReactNoop.root.children).toEqual([ + div(div(span('Hello'), span('World'))), + ]); + }); + + it('can reuse side-effects after being preempted, if shouldComponentUpdate is false', () => { + + class Bar extends React.Component { + shouldComponentUpdate(nextProps) { + return this.props.children !== nextProps.children; + } + render() { + return ; + } + } + + class Content extends React.Component { + shouldComponentUpdate(nextProps) { + return this.props.step !== nextProps.step; + } + render() { + return ( +
+ {this.props.step === 0 ? 'Hi' : 'Hello'} + {this.props.step === 0 ? this.props.text : 'World'} +
+ ); + } + } + + function Foo(props) { + return ( + + ); + } + + // Init + ReactNoop.render(); + ReactNoop.flush(); + + expect(ReactNoop.root.children).toEqual([ + div(div(span('Hi'), span('foo'))), + ]); + + // Make a quick update which will schedule low priority work to + // update the middle content. + ReactNoop.render(); + ReactNoop.flushDeferredPri(35); + + // The tree remains unchanged. + expect(ReactNoop.root.children).toEqual([ + div(div(span('Hi'), span('foo'))), + ]); + + // The first Bar has already completed its update but we'll interupt it to + // render some higher priority work. The middle content will bailout so + // it remains untouched which means that it should reuse it next time. + ReactNoop.render(); + ReactNoop.flush(30); + + // Since we did nothing to the middle subtree during the interuption, + // we should be able to reuse the reconciliation work that we already did + // without restarting. The side-effects should still be replayed. + + expect(ReactNoop.root.children).toEqual([ + div(div(span('Hello'), span('World'))), + ]); + }); + + it('updates a child even though the old props is empty', () => { + function Foo(props) { + return ( + + ); + } + + ReactNoop.render(); + ReactNoop.flush(); + expect(ReactNoop.root.children).toEqual([ + div(span(1)), + ]); + }); + + it('can defer side-effects and resume them later on', function() { + class Bar extends React.Component { + shouldComponentUpdate(nextProps) { + return this.props.idx !== nextProps; + } + render() { + return ; + } + } + function Foo(props) { + return ( +
+ + +
+ ); + } + ReactNoop.render(); + ReactNoop.flushDeferredPri(40 + 25); + expect(ReactNoop.root.children).toEqual([ + div( + span(0), + div(/*the spans are down-prioritized and not rendered yet*/) + ), + ]); + ReactNoop.render(); + ReactNoop.flushDeferredPri(35 + 25); + expect(ReactNoop.root.children).toEqual([ + div( + span(1), + div(/*still not rendered yet*/) + ), + ]); + ReactNoop.flushDeferredPri(30 + 25); + expect(ReactNoop.root.children).toEqual([ + div( + span(1), + div( + // Now we had enough time to finish the spans. + span(0), + span(1) + ) + ), + ]); + var innerSpanA = ReactNoop.root.children[0].children[1].children[1]; + ReactNoop.render(); + ReactNoop.flushDeferredPri(30 + 25); + expect(ReactNoop.root.children).toEqual([ + div( + span(2), + div( + // Still same old numbers. + span(0), + span(1) + ) + ), + ]); + ReactNoop.flushDeferredPri(30); + expect(ReactNoop.root.children).toEqual([ + div( + span(2), + div( + // New numbers. + span(1), + span(2) + ) + ), + ]); + + var innerSpanB = ReactNoop.root.children[0].children[1].children[1]; + // This should have been an update to an existing instance, not recreation. + // We verify that by ensuring that the child instance was the same as + // before. + expect(innerSpanA).toBe(innerSpanB); + }); + + // TODO: Test that side-effects are not cut off when a work in progress node // moves to "current" without flushing due to having lower priority. Does this // even happen? Maybe a child doesn't get processed because it is lower prio? + it('calls callback after update is flushed', () => { + let instance; + class Foo extends React.Component { + constructor() { + super(); + instance = this; + this.state = { text: 'foo' }; + } + render() { + return ; + } + } + + ReactNoop.render(); + ReactNoop.flush(); + expect(ReactNoop.root.children).toEqual([ + span('foo'), + ]); + let called = false; + instance.setState({ text: 'bar' }, () => { + expect(ReactNoop.root.children).toEqual([ + span('bar'), + ]); + called = true; + }); + ReactNoop.flush(); + expect(called).toBe(true); + }); + + // TODO: Test that callbacks are not lost if an update is preempted. }); diff --git a/src/renderers/shared/fiber/isomorphic/ReactCoroutine.js b/src/renderers/shared/fiber/isomorphic/ReactCoroutine.js index 0218269a9e..dda4ca1fb3 100644 --- a/src/renderers/shared/fiber/isomorphic/ReactCoroutine.js +++ b/src/renderers/shared/fiber/isomorphic/ReactCoroutine.js @@ -33,6 +33,9 @@ export type ReactCoroutine = { children: any, // This should be a more specific CoroutineHandler handler: (props: any, yields: Array) => ReactNodeList, + /* $FlowFixMe(>=0.31.0): Which is it? mixed? Or Object? Must match + * `ReactYield` type. + */ props: mixed, }; export type ReactYield = { diff --git a/src/renderers/shared/hooks/ReactChildrenMutationWarningHook.js b/src/renderers/shared/hooks/ReactChildrenMutationWarningHook.js deleted file mode 100644 index 0d4bd8767c..0000000000 --- a/src/renderers/shared/hooks/ReactChildrenMutationWarningHook.js +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactChildrenMutationWarningHook - */ - -'use strict'; - -var ReactComponentTreeHook = require('ReactComponentTreeHook'); - -var warning = require('warning'); - -function handleElement(debugID, element) { - if (element == null) { - return; - } - if (element._shadowChildren === undefined) { - return; - } - if (element._shadowChildren === element.props.children) { - return; - } - var isMutated = false; - if (Array.isArray(element._shadowChildren)) { - if (element._shadowChildren.length === element.props.children.length) { - for (var i = 0; i < element._shadowChildren.length; i++) { - if (element._shadowChildren[i] !== element.props.children[i]) { - isMutated = true; - } - } - } else { - isMutated = true; - } - } - if (!Array.isArray(element._shadowChildren) || isMutated) { - warning( - false, - 'Component\'s children should not be mutated.%s', - ReactComponentTreeHook.getStackAddendumByID(debugID), - ); - } -} - -var ReactChildrenMutationWarningHook = { - onMountComponent(debugID) { - handleElement(debugID, ReactComponentTreeHook.getElement(debugID)); - }, - onUpdateComponent(debugID) { - handleElement(debugID, ReactComponentTreeHook.getElement(debugID)); - }, -}; - -module.exports = ReactChildrenMutationWarningHook; diff --git a/src/renderers/shared/hooks/ReactHostOperationHistoryHook.js b/src/renderers/shared/hooks/ReactHostOperationHistoryHook.js index 48456caea9..675a00e732 100644 --- a/src/renderers/shared/hooks/ReactHostOperationHistoryHook.js +++ b/src/renderers/shared/hooks/ReactHostOperationHistoryHook.js @@ -7,22 +7,33 @@ * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactHostOperationHistoryHook + * @flow */ 'use strict'; -var history = []; +import type { DebugID } from 'ReactInstanceType'; + +export type Operation = {instanceID: DebugID} & ( + {type: 'mount', payload: string} | + {type: 'insert child', payload: {toIndex: number, content: string}} | + {type: 'move child', payload: {fromIndex: number, toIndex: number}} | + {type: 'replace children', payload: string} | + {type: 'replace text', payload: string} | + {type: 'replace with', payload: string} | + {type: 'update styles', payload: mixed /* Style Object */} | + {type: 'update attribute', payload: {[name: string]: string}} | + {type: 'remove attribute', payload: string} +); + +var history: Array = []; var ReactHostOperationHistoryHook = { - onHostOperation(debugID, type, payload) { - history.push({ - instanceID: debugID, - type, - payload, - }); + onHostOperation(operation: Operation) { + history.push(operation); }, - clearHistory() { + clearHistory(): void { if (ReactHostOperationHistoryHook._preventClearing) { // Should only be used for tests. return; @@ -31,7 +42,7 @@ var ReactHostOperationHistoryHook = { history = []; }, - getHistory() { + getHistory(): Array { return history; }, }; diff --git a/src/renderers/shared/hooks/ReactInvalidSetStateWarningHook.js b/src/renderers/shared/hooks/ReactInvalidSetStateWarningHook.js index 4e47ced0d4..66378b50df 100644 --- a/src/renderers/shared/hooks/ReactInvalidSetStateWarningHook.js +++ b/src/renderers/shared/hooks/ReactInvalidSetStateWarningHook.js @@ -7,6 +7,7 @@ * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInvalidSetStateWarningHook + * @flow */ 'use strict'; @@ -25,13 +26,13 @@ if (__DEV__) { } var ReactInvalidSetStateWarningHook = { - onBeginProcessingChildContext() { + onBeginProcessingChildContext(): void { processingChildContext = true; }, - onEndProcessingChildContext() { + onEndProcessingChildContext(): void { processingChildContext = false; }, - onSetState() { + onSetState(): void { warnInvalidSetState(); }, }; diff --git a/src/renderers/shared/stack/reconciler/ReactInstanceMap.js b/src/renderers/shared/shared/ReactInstanceMap.js similarity index 100% rename from src/renderers/shared/stack/reconciler/ReactInstanceMap.js rename to src/renderers/shared/shared/ReactInstanceMap.js diff --git a/src/renderers/shared/stack/event/EventConstants.js b/src/renderers/shared/stack/event/EventConstants.js index 84a9e9d486..385f353385 100644 --- a/src/renderers/shared/stack/event/EventConstants.js +++ b/src/renderers/shared/stack/event/EventConstants.js @@ -11,14 +11,12 @@ 'use strict'; -var keyMirror = require('keyMirror'); - -var PropagationPhases = keyMirror({bubbled: null, captured: null}); +export type PropagationPhases = 'bubbled' | 'captured'; /** * Types of raw signals from the browser caught at the top level. */ -var topLevelTypes = keyMirror({ +var topLevelTypes = { topAbort: null, topAnimationEnd: null, topAnimationIteration: null, @@ -87,11 +85,12 @@ var topLevelTypes = keyMirror({ topVolumeChange: null, topWaiting: null, topWheel: null, -}); +}; + +export type TopLevelTypes = $Enum; var EventConstants = { - topLevelTypes: topLevelTypes, - PropagationPhases: PropagationPhases, + topLevelTypes, }; module.exports = EventConstants; diff --git a/src/renderers/shared/stack/event/EventPluginRegistry.js b/src/renderers/shared/stack/event/EventPluginRegistry.js index cb3fdf2281..f44593eab8 100644 --- a/src/renderers/shared/stack/event/EventPluginRegistry.js +++ b/src/renderers/shared/stack/event/EventPluginRegistry.js @@ -7,62 +7,78 @@ * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPluginRegistry + * @flow */ 'use strict'; +import type { + DispatchConfig, + ReactSyntheticEvent, +} from 'ReactSyntheticEventType'; + +import type { + AnyNativeEvent, + PluginName, + PluginModule, +} from 'PluginModuleType'; + +type NamesToPlugins = {[key: PluginName]: PluginModule}; + +type EventPluginOrder = null | Array; + var invariant = require('invariant'); /** * Injectable ordering of event plugins. */ -var EventPluginOrder = null; +var eventPluginOrder: EventPluginOrder = null; /** * Injectable mapping from names to event plugin modules. */ -var namesToPlugins = {}; +var namesToPlugins: NamesToPlugins = {}; /** * Recomputes the plugin list using the injected plugins and plugin ordering. * * @private */ -function recomputePluginOrdering() { - if (!EventPluginOrder) { - // Wait until an `EventPluginOrder` is injected. +function recomputePluginOrdering(): void { + if (!eventPluginOrder) { + // Wait until an `eventPluginOrder` is injected. return; } for (var pluginName in namesToPlugins) { - var PluginModule = namesToPlugins[pluginName]; - var pluginIndex = EventPluginOrder.indexOf(pluginName); + var pluginModule = namesToPlugins[pluginName]; + var pluginIndex = eventPluginOrder.indexOf(pluginName); invariant( pluginIndex > -1, 'EventPluginRegistry: Cannot inject event plugins that do not exist in ' + 'the plugin ordering, `%s`.', - pluginName + pluginName, ); if (EventPluginRegistry.plugins[pluginIndex]) { continue; } invariant( - PluginModule.extractEvents, + pluginModule.extractEvents, 'EventPluginRegistry: Event plugins must implement an `extractEvents` ' + 'method, but `%s` does not.', - pluginName + pluginName, ); - EventPluginRegistry.plugins[pluginIndex] = PluginModule; - var publishedEvents = PluginModule.eventTypes; + EventPluginRegistry.plugins[pluginIndex] = pluginModule; + var publishedEvents = pluginModule.eventTypes; for (var eventName in publishedEvents) { invariant( publishEventForPlugin( publishedEvents[eventName], - PluginModule, - eventName + pluginModule, + eventName, ), 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, - pluginName + pluginName, ); } } @@ -76,12 +92,16 @@ function recomputePluginOrdering() { * @return {boolean} True if the event was successfully published. * @private */ -function publishEventForPlugin(dispatchConfig, PluginModule, eventName) { +function publishEventForPlugin( + dispatchConfig: DispatchConfig, + pluginModule: PluginModule, + eventName: string, +): boolean { invariant( !EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName), 'EventPluginHub: More than one plugin attempted to publish the same ' + 'event name, `%s`.', - eventName + eventName, ); EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig; @@ -92,8 +112,8 @@ function publishEventForPlugin(dispatchConfig, PluginModule, eventName) { var phasedRegistrationName = phasedRegistrationNames[phaseName]; publishRegistrationName( phasedRegistrationName, - PluginModule, - eventName + pluginModule, + eventName, ); } } @@ -101,8 +121,8 @@ function publishEventForPlugin(dispatchConfig, PluginModule, eventName) { } else if (dispatchConfig.registrationName) { publishRegistrationName( dispatchConfig.registrationName, - PluginModule, - eventName + pluginModule, + eventName, ); return true; } @@ -117,16 +137,20 @@ function publishEventForPlugin(dispatchConfig, PluginModule, eventName) { * @param {object} PluginModule Plugin publishing the event. * @private */ -function publishRegistrationName(registrationName, PluginModule, eventName) { +function publishRegistrationName( + registrationName: string, + pluginModule: PluginModule, + eventName: string, +): void { invariant( !EventPluginRegistry.registrationNameModules[registrationName], 'EventPluginHub: More than one plugin attempted to publish the same ' + 'registration name, `%s`.', - registrationName + registrationName, ); - EventPluginRegistry.registrationNameModules[registrationName] = PluginModule; + EventPluginRegistry.registrationNameModules[registrationName] = pluginModule; EventPluginRegistry.registrationNameDependencies[registrationName] = - PluginModule.eventTypes[eventName].dependencies; + pluginModule.eventTypes[eventName].dependencies; if (__DEV__) { var lowerCasedName = registrationName.toLowerCase(); @@ -173,7 +197,8 @@ var EventPluginRegistry = { * only in __DEV__. * @type {Object} */ - possibleRegistrationNames: __DEV__ ? {} : null, + possibleRegistrationNames: __DEV__ ? {} : (null: any), + // Trust the developer to only use possibleRegistrationNames in __DEV__ /** * Injects an ordering of plugins (by plugin name). This allows the ordering @@ -184,14 +209,16 @@ var EventPluginRegistry = { * @internal * @see {EventPluginHub.injection.injectEventPluginOrder} */ - injectEventPluginOrder: function(InjectedEventPluginOrder) { + injectEventPluginOrder: function( + injectedEventPluginOrder: EventPluginOrder, + ): void { invariant( - !EventPluginOrder, + !eventPluginOrder, 'EventPluginRegistry: Cannot inject event plugin ordering more than ' + - 'once. You are likely trying to load more than one copy of React.' + 'once. You are likely trying to load more than one copy of React.', ); // Clone the ordering so it cannot be dynamically mutated. - EventPluginOrder = Array.prototype.slice.call(InjectedEventPluginOrder); + eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder); recomputePluginOrdering(); }, @@ -205,22 +232,24 @@ var EventPluginRegistry = { * @internal * @see {EventPluginHub.injection.injectEventPluginsByName} */ - injectEventPluginsByName: function(injectedNamesToPlugins) { + injectEventPluginsByName: function( + injectedNamesToPlugins: NamesToPlugins + ): void { var isOrderingDirty = false; for (var pluginName in injectedNamesToPlugins) { if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) { continue; } - var PluginModule = injectedNamesToPlugins[pluginName]; + var pluginModule = injectedNamesToPlugins[pluginName]; if (!namesToPlugins.hasOwnProperty(pluginName) || - namesToPlugins[pluginName] !== PluginModule) { + namesToPlugins[pluginName] !== pluginModule) { invariant( !namesToPlugins[pluginName], 'EventPluginRegistry: Cannot inject two different event plugins ' + 'using the same name, `%s`.', - pluginName + pluginName, ); - namesToPlugins[pluginName] = PluginModule; + namesToPlugins[pluginName] = pluginModule; isOrderingDirty = true; } } @@ -236,22 +265,29 @@ var EventPluginRegistry = { * @return {?object} The plugin that created the supplied event. * @internal */ - getPluginModuleForEvent: function(event) { + getPluginModuleForEvent: function( + event: ReactSyntheticEvent, + ): null | PluginModule { var dispatchConfig = event.dispatchConfig; if (dispatchConfig.registrationName) { return EventPluginRegistry.registrationNameModules[ dispatchConfig.registrationName ] || null; } - for (var phase in dispatchConfig.phasedRegistrationNames) { - if (!dispatchConfig.phasedRegistrationNames.hasOwnProperty(phase)) { - continue; - } - var PluginModule = EventPluginRegistry.registrationNameModules[ - dispatchConfig.phasedRegistrationNames[phase] - ]; - if (PluginModule) { - return PluginModule; + if (dispatchConfig.phasedRegistrationNames !== undefined) { + // pulling phasedRegistrationNames out of dispatchConfig helps Flow see + // that it is not undefined. + var {phasedRegistrationNames} = dispatchConfig; + for (var phase in phasedRegistrationNames) { + if (!phasedRegistrationNames.hasOwnProperty(phase)) { + continue; + } + var pluginModule = EventPluginRegistry.registrationNameModules[ + phasedRegistrationNames[phase] + ]; + if (pluginModule) { + return pluginModule; + } } } return null; @@ -261,8 +297,8 @@ var EventPluginRegistry = { * Exposed for unit testing. * @private */ - _resetEventPlugins: function() { - EventPluginOrder = null; + _resetEventPlugins: function(): void { + eventPluginOrder = null; for (var pluginName in namesToPlugins) { if (namesToPlugins.hasOwnProperty(pluginName)) { delete namesToPlugins[pluginName]; diff --git a/src/renderers/shared/stack/event/EventPluginUtils.js b/src/renderers/shared/stack/event/EventPluginUtils.js index 33019d27d6..4bad7e316d 100644 --- a/src/renderers/shared/stack/event/EventPluginUtils.js +++ b/src/renderers/shared/stack/event/EventPluginUtils.js @@ -11,7 +11,6 @@ 'use strict'; -var EventConstants = require('EventConstants'); var ReactErrorUtils = require('ReactErrorUtils'); var invariant = require('invariant'); @@ -52,21 +51,19 @@ var injection = { }, }; -var topLevelTypes = EventConstants.topLevelTypes; - function isEndish(topLevelType) { - return topLevelType === topLevelTypes.topMouseUp || - topLevelType === topLevelTypes.topTouchEnd || - topLevelType === topLevelTypes.topTouchCancel; + return topLevelType === 'topMouseUp' || + topLevelType === 'topTouchEnd' || + topLevelType === 'topTouchCancel'; } function isMoveish(topLevelType) { - return topLevelType === topLevelTypes.topMouseMove || - topLevelType === topLevelTypes.topTouchMove; + return topLevelType === 'topMouseMove' || + topLevelType === 'topTouchMove'; } function isStartish(topLevelType) { - return topLevelType === topLevelTypes.topMouseDown || - topLevelType === topLevelTypes.topTouchStart; + return topLevelType === 'topMouseDown' || + topLevelType === 'topTouchStart'; } diff --git a/src/renderers/shared/stack/event/EventPropagators.js b/src/renderers/shared/stack/event/EventPropagators.js index 95cc188261..da1b238416 100644 --- a/src/renderers/shared/stack/event/EventPropagators.js +++ b/src/renderers/shared/stack/event/EventPropagators.js @@ -11,7 +11,6 @@ 'use strict'; -var EventConstants = require('EventConstants'); var EventPluginHub = require('EventPluginHub'); var EventPluginUtils = require('EventPluginUtils'); @@ -19,14 +18,15 @@ var accumulateInto = require('accumulateInto'); var forEachAccumulated = require('forEachAccumulated'); var warning = require('warning'); -var PropagationPhases = EventConstants.PropagationPhases; +import type { PropagationPhases } from 'EventConstants'; + var getListener = EventPluginHub.getListener; /** * Some event types have a notion of different registration names for different * "phases" of propagation. This finds listeners by a given phase. */ -function listenerAtPhase(inst, event, propagationPhase) { +function listenerAtPhase(inst, event, propagationPhase: PropagationPhases) { var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; return getListener(inst, registrationName); @@ -38,14 +38,13 @@ function listenerAtPhase(inst, event, propagationPhase) { * Mutating the event's members allows us to not have to create a wrapping * "dispatch" object that pairs the event with the listener. */ -function accumulateDirectionalDispatches(inst, upwards, event) { +function accumulateDirectionalDispatches(inst, phase, event) { if (__DEV__) { warning( inst, 'Dispatching inst must not be null' ); } - var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured; var listener = listenerAtPhase(inst, event, phase); if (listener) { event._dispatchListeners = diff --git a/src/renderers/shared/stack/event/PluginModuleType.js b/src/renderers/shared/stack/event/PluginModuleType.js new file mode 100644 index 0000000000..ce00d28f94 --- /dev/null +++ b/src/renderers/shared/stack/event/PluginModuleType.js @@ -0,0 +1,49 @@ +/** + * Copyright 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule PluginModuleType + * @flow + */ + +'use strict'; + +import type {ReactInstance} from 'ReactInstanceType'; +import type { + DispatchConfig, + ReactSyntheticEvent, +} from 'ReactSyntheticEventType'; + +export type EventTypes = {[key: string]: DispatchConfig}; + +export type AnyNativeEvent = + Event | + KeyboardEvent | + MouseEvent | + Touch; + +export type PluginName = string; + +export type PluginModule = { + eventTypes: EventTypes, + extractEvents: ( + topLevelType: string, + targetInst: ReactInstance, + nativeTarget: NativeEvent, + nativeEventTarget: EventTarget, + ) => null | ReactSyntheticEvent, + didPutListener?: ( + inst: ReactInstance, + registrationName: string, + listener: () => void, + ) => void, + willDeleteListener?: ( + inst: ReactInstance, + registrationName: string, + ) => void, + tapMoveThreshold?: number, +}; diff --git a/src/renderers/shared/stack/event/ReactSyntheticEventType.js b/src/renderers/shared/stack/event/ReactSyntheticEventType.js new file mode 100644 index 0000000000..b40c03fd94 --- /dev/null +++ b/src/renderers/shared/stack/event/ReactSyntheticEventType.js @@ -0,0 +1,36 @@ +/* + * Copyright 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * Flow type for SyntheticEvent class that includes private properties + * + * @providesModule ReactSyntheticEventType + * @flow + */ + +'use strict'; + +import type {ReactInstance} from 'ReactInstanceType'; + +export type DispatchConfig = { + dependencies: Array, + phasedRegistrationNames?: { + bubbled: string, + captured: string, + }, + registrationName?: string, +}; + +export type ReactSyntheticEvent = { + dispatchConfig: DispatchConfig; + getPooled: ( + dispatchConfig: DispatchConfig, + targetInst: ReactInstance, + nativeTarget: Event, + nativeEventTarget: EventTarget, + ) => ReactSyntheticEvent; +} & SyntheticEvent; diff --git a/src/renderers/dom/client/syntheticEvents/SyntheticEvent.js b/src/renderers/shared/stack/event/SyntheticEvent.js similarity index 100% rename from src/renderers/dom/client/syntheticEvents/SyntheticEvent.js rename to src/renderers/shared/stack/event/SyntheticEvent.js diff --git a/src/renderers/shared/stack/event/__tests__/EventPluginHub-test.js b/src/renderers/shared/stack/event/__tests__/EventPluginHub-test.js index 9583bccf97..2e49bc4f43 100644 --- a/src/renderers/shared/stack/event/__tests__/EventPluginHub-test.js +++ b/src/renderers/shared/stack/event/__tests__/EventPluginHub-test.js @@ -11,22 +11,20 @@ 'use strict'; -jest - .unmock('EventPluginHub') - .mock('isEventSupported'); +jest.mock('isEventSupported'); -describe('EventPluginHub', function() { +describe('EventPluginHub', () => { var EventPluginHub; var isEventSupported; - beforeEach(function() { + beforeEach(() => { jest.resetModuleRegistry(); EventPluginHub = require('EventPluginHub'); isEventSupported = require('isEventSupported'); isEventSupported.mockReturnValueOnce(false); }); - it('should prevent non-function listeners', function() { + it('should prevent non-function listeners', () => { expect(function() { EventPluginHub.putListener(1, 'onClick', 'not a function'); }).toThrowError( diff --git a/src/renderers/shared/stack/event/__tests__/EventPluginRegistry-test.js b/src/renderers/shared/stack/event/__tests__/EventPluginRegistry-test.js index 6cd2d52b7c..245e7bcc49 100644 --- a/src/renderers/shared/stack/event/__tests__/EventPluginRegistry-test.js +++ b/src/renderers/shared/stack/event/__tests__/EventPluginRegistry-test.js @@ -12,11 +12,11 @@ 'use strict'; -describe('EventPluginRegistry', function() { +describe('EventPluginRegistry', () => { var EventPluginRegistry; var createPlugin; - beforeEach(function() { + beforeEach(() => { EventPluginRegistry = require('EventPluginRegistry'); EventPluginRegistry._resetEventPlugins(); @@ -25,7 +25,7 @@ describe('EventPluginRegistry', function() { }; }); - it('should be able to inject ordering before plugins', function() { + it('should be able to inject ordering before plugins', () => { var OnePlugin = createPlugin(); var TwoPlugin = createPlugin(); var ThreePlugin = createPlugin(); @@ -45,7 +45,7 @@ describe('EventPluginRegistry', function() { expect(EventPluginRegistry.plugins[2]).toBe(ThreePlugin); }); - it('should be able to inject plugins before and after ordering', function() { + it('should be able to inject plugins before and after ordering', () => { var OnePlugin = createPlugin(); var TwoPlugin = createPlugin(); var ThreePlugin = createPlugin(); @@ -65,7 +65,7 @@ describe('EventPluginRegistry', function() { expect(EventPluginRegistry.plugins[2]).toBe(ThreePlugin); }); - it('should be able to inject repeated plugins and out-of-order', function() { + it('should be able to inject repeated plugins and out-of-order', () => { var OnePlugin = createPlugin(); var TwoPlugin = createPlugin(); var ThreePlugin = createPlugin(); @@ -86,7 +86,7 @@ describe('EventPluginRegistry', function() { expect(EventPluginRegistry.plugins[2]).toBe(ThreePlugin); }); - it('should throw if plugin does not implement `extractEvents`', function() { + it('should throw if plugin does not implement `extractEvents`', () => { var BadPlugin = {}; EventPluginRegistry.injectEventPluginOrder(['bad']); @@ -101,7 +101,7 @@ describe('EventPluginRegistry', function() { ); }); - it('should throw if plugin does not exist in ordering', function() { + it('should throw if plugin does not exist in ordering', () => { var OnePlugin = createPlugin(); var RandomPlugin = createPlugin(); @@ -118,7 +118,7 @@ describe('EventPluginRegistry', function() { ); }); - it('should throw if ordering is injected more than once', function() { + it('should throw if ordering is injected more than once', () => { var pluginOrdering = []; EventPluginRegistry.injectEventPluginOrder(pluginOrdering); @@ -131,7 +131,7 @@ describe('EventPluginRegistry', function() { ); }); - it('should throw if different plugins injected using same name', function() { + it('should throw if different plugins injected using same name', () => { var OnePlugin = createPlugin(); var TwoPlugin = createPlugin(); @@ -145,7 +145,7 @@ describe('EventPluginRegistry', function() { ); }); - it('should publish registration names of injected plugins', function() { + it('should publish registration names of injected plugins', () => { var OnePlugin = createPlugin({ eventTypes: { click: {registrationName: 'onClick'}, @@ -179,7 +179,7 @@ describe('EventPluginRegistry', function() { ).toBe(TwoPlugin); }); - it('should throw if multiple registration names collide', function() { + it('should throw if multiple registration names collide', () => { var OnePlugin = createPlugin({ eventTypes: { photoCapture: {registrationName: 'onPhotoCapture'}, @@ -209,7 +209,7 @@ describe('EventPluginRegistry', function() { ); }); - it('should throw if an invalid event is published', function() { + it('should throw if an invalid event is published', () => { var OnePlugin = createPlugin({ eventTypes: { badEvent: {/* missing configuration */}, @@ -226,7 +226,7 @@ describe('EventPluginRegistry', function() { ); }); - it('should be able to get the plugin from synthetic events', function() { + it('should be able to get the plugin from synthetic events', () => { var clickDispatchConfig = { registrationName: 'onClick', }; diff --git a/src/renderers/shared/stack/event/eventPlugins/ResponderEventPlugin.js b/src/renderers/shared/stack/event/eventPlugins/ResponderEventPlugin.js index 366bb93cf2..2f26f4f24c 100644 --- a/src/renderers/shared/stack/event/eventPlugins/ResponderEventPlugin.js +++ b/src/renderers/shared/stack/event/eventPlugins/ResponderEventPlugin.js @@ -11,14 +11,12 @@ 'use strict'; -var EventConstants = require('EventConstants'); var EventPluginUtils = require('EventPluginUtils'); var EventPropagators = require('EventPropagators'); var ResponderSyntheticEvent = require('ResponderSyntheticEvent'); var ResponderTouchHistoryStore = require('ResponderTouchHistoryStore'); var accumulate = require('accumulate'); -var keyOf = require('keyOf'); var isStartish = EventPluginUtils.isStartish; var isMoveish = EventPluginUtils.isMoveish; @@ -64,8 +62,8 @@ var eventTypes = { */ startShouldSetResponder: { phasedRegistrationNames: { - bubbled: keyOf({onStartShouldSetResponder: null}), - captured: keyOf({onStartShouldSetResponderCapture: null}), + bubbled: 'onStartShouldSetResponder', + captured: 'onStartShouldSetResponderCapture', }, }, @@ -80,8 +78,8 @@ var eventTypes = { */ scrollShouldSetResponder: { phasedRegistrationNames: { - bubbled: keyOf({onScrollShouldSetResponder: null}), - captured: keyOf({onScrollShouldSetResponderCapture: null}), + bubbled: 'onScrollShouldSetResponder', + captured: 'onScrollShouldSetResponderCapture', }, }, @@ -94,8 +92,8 @@ var eventTypes = { */ selectionChangeShouldSetResponder: { phasedRegistrationNames: { - bubbled: keyOf({onSelectionChangeShouldSetResponder: null}), - captured: keyOf({onSelectionChangeShouldSetResponderCapture: null}), + bubbled: 'onSelectionChangeShouldSetResponder', + captured: 'onSelectionChangeShouldSetResponderCapture', }, }, @@ -105,24 +103,24 @@ var eventTypes = { */ moveShouldSetResponder: { phasedRegistrationNames: { - bubbled: keyOf({onMoveShouldSetResponder: null}), - captured: keyOf({onMoveShouldSetResponderCapture: null}), + bubbled: 'onMoveShouldSetResponder', + captured: 'onMoveShouldSetResponderCapture', }, }, /** * Direct responder events dispatched directly to responder. Do not bubble. */ - responderStart: {registrationName: keyOf({onResponderStart: null})}, - responderMove: {registrationName: keyOf({onResponderMove: null})}, - responderEnd: {registrationName: keyOf({onResponderEnd: null})}, - responderRelease: {registrationName: keyOf({onResponderRelease: null})}, + responderStart: {registrationName: 'onResponderStart'}, + responderMove: {registrationName: 'onResponderMove'}, + responderEnd: {registrationName: 'onResponderEnd'}, + responderRelease: {registrationName: 'onResponderRelease'}, responderTerminationRequest: { - registrationName: keyOf({onResponderTerminationRequest: null}), + registrationName: 'onResponderTerminationRequest', }, - responderGrant: {registrationName: keyOf({onResponderGrant: null})}, - responderReject: {registrationName: keyOf({onResponderReject: null})}, - responderTerminate: {registrationName: keyOf({onResponderTerminate: null})}, + responderGrant: {registrationName: 'onResponderGrant'}, + responderReject: {registrationName: 'onResponderReject'}, + responderTerminate: {registrationName: 'onResponderTerminate'}, }; /** @@ -326,7 +324,7 @@ function setResponderAndExtractTransfer( var shouldSetEventType = isStartish(topLevelType) ? eventTypes.startShouldSetResponder : isMoveish(topLevelType) ? eventTypes.moveShouldSetResponder : - topLevelType === EventConstants.topLevelTypes.topSelectionChange ? + topLevelType === 'topSelectionChange' ? eventTypes.selectionChangeShouldSetResponder : eventTypes.scrollShouldSetResponder; @@ -429,10 +427,10 @@ function canTriggerTransfer(topLevelType, topLevelInst, nativeEvent) { // responderIgnoreScroll: We are trying to migrate away from specifically // tracking native scroll events here and responderIgnoreScroll indicates we // will send topTouchCancel to handle canceling touch events instead - (topLevelType === EventConstants.topLevelTypes.topScroll && + (topLevelType === 'topScroll' && !nativeEvent.responderIgnoreScroll) || (trackedTouchCount > 0 && - topLevelType === EventConstants.topLevelTypes.topSelectionChange) || + topLevelType === 'topSelectionChange') || isStartish(topLevelType) || isMoveish(topLevelType) ); @@ -541,7 +539,7 @@ var ResponderEventPlugin = { var isResponderTerminate = responderInst && - topLevelType === EventConstants.topLevelTypes.topTouchCancel; + topLevelType === 'topTouchCancel'; var isResponderRelease = responderInst && !isResponderTerminate && diff --git a/src/renderers/shared/stack/event/eventPlugins/__tests__/ResponderEventPlugin-test.js b/src/renderers/shared/stack/event/eventPlugins/__tests__/ResponderEventPlugin-test.js index 35e797d2fd..584863a10f 100644 --- a/src/renderers/shared/stack/event/eventPlugins/__tests__/ResponderEventPlugin-test.js +++ b/src/renderers/shared/stack/event/eventPlugins/__tests__/ResponderEventPlugin-test.js @@ -12,13 +12,9 @@ 'use strict'; var EventPluginHub; -var EventConstants; -var ReactInstanceHandles; var ResponderEventPlugin; var EventPluginUtils; -var topLevelTypes; - var touch = function(nodeHandle, i) { return {target: nodeHandle, identifier: i}; }; @@ -108,7 +104,7 @@ var _touchConfig = function( */ var startConfig = function(nodeHandle, allTouchHandles, changedIndices) { return _touchConfig( - topLevelTypes.topTouchStart, + 'topTouchStart', nodeHandle, allTouchHandles, changedIndices, @@ -121,7 +117,7 @@ var startConfig = function(nodeHandle, allTouchHandles, changedIndices) { */ var moveConfig = function(nodeHandle, allTouchHandles, changedIndices) { return _touchConfig( - topLevelTypes.topTouchMove, + 'topTouchMove', nodeHandle, allTouchHandles, changedIndices, @@ -134,7 +130,7 @@ var moveConfig = function(nodeHandle, allTouchHandles, changedIndices) { */ var endConfig = function(nodeHandle, allTouchHandles, changedIndices) { return _touchConfig( - topLevelTypes.topTouchEnd, + 'topTouchEnd', nodeHandle, allTouchHandles, changedIndices, @@ -330,14 +326,90 @@ var siblings = { childTwo: CHILD_ID2, }; -describe('ResponderEventPlugin', function() { - beforeEach(function() { +describe('ResponderEventPlugin', () => { + + // This test is written against React IDs such as 'root.a.b[10]' but we + // removed those. In order to make those tests still pass with minimum + // surgery, we are inlining the implementation of those IDs here as it + // is the only remaining call site. + + var SEPARATOR = '.'; + + function isBoundary(id, index) { + return id.charAt(index) === SEPARATOR || index === id.length; + } + + function isAncestorIDOf(ancestorID, descendantID) { + return ( + descendantID.indexOf(ancestorID) === 0 && + isBoundary(descendantID, ancestorID.length) + ); + } + + function getParentID(id) { + return id ? id.substr(0, id.lastIndexOf(SEPARATOR)) : ''; + } + + function getNextDescendantID(ancestorID, destinationID) { + if (ancestorID === destinationID) { + return ancestorID; + } + // Skip over the ancestor and the immediate separator. Traverse until we hit + // another separator or we reach the end of `destinationID`. + var start = ancestorID.length + SEPARATOR.length; + var i; + for (i = start; i < destinationID.length; i++) { + if (isBoundary(destinationID, i)) { + break; + } + } + return destinationID.substr(0, i); + } + + function getFirstCommonAncestorID(oneID, twoID) { + var minLength = Math.min(oneID.length, twoID.length); + if (minLength === 0) { + return ''; + } + var lastCommonMarkerIndex = 0; + // Use `<=` to traverse until the "EOL" of the shorter string. + for (var i = 0; i <= minLength; i++) { + if (isBoundary(oneID, i) && isBoundary(twoID, i)) { + lastCommonMarkerIndex = i; + } else if (oneID.charAt(i) !== twoID.charAt(i)) { + break; + } + } + return oneID.substr(0, lastCommonMarkerIndex); + } + + function traverseParentPath(start, stop, cb, arg, skipFirst, skipLast) { + var traverseUp = isAncestorIDOf(stop, start); + var traverse = traverseUp ? getParentID : getNextDescendantID; + for (var id = start; /* until break */; id = traverse(id, stop)) { + var ret; + if ((!skipFirst || id !== start) && (!skipLast || id !== stop)) { + ret = cb(id, traverseUp ? 'bubbled': 'captured', arg); + } + if (ret === false || id === stop) { + // Only break //after// visiting `stop`. + break; + } + } + } + + function traverseTwoPhase(targetID, cb, arg) { + traverseParentPath('', targetID, cb, arg, true, false); + traverseParentPath(targetID, '', cb, arg, false, true); + } + + // -- end of the React ID implementation + + beforeEach(() => { jest.resetModuleRegistry(); - EventConstants = require('EventConstants'); EventPluginHub = require('EventPluginHub'); EventPluginUtils = require('EventPluginUtils'); - ReactInstanceHandles = require('ReactInstanceHandles'); ResponderEventPlugin = require('ResponderEventPlugin'); EventPluginUtils.injection.injectComponentTree({ @@ -351,40 +423,29 @@ describe('ResponderEventPlugin', function() { EventPluginUtils.injection.injectTreeTraversal({ isAncestor: function(a, b) { - return ReactInstanceHandles.isAncestorIDOf( - a._rootNodeID, - b._rootNodeID - ); + return isAncestorIDOf(a._rootNodeID, b._rootNodeID); }, getLowestCommonAncestor: function(a, b) { - if (!a || !b) { - return null; - } - var commonID = ReactInstanceHandles.getFirstCommonAncestorID( - a._rootNodeID, - b._rootNodeID - ); + var commonID = getFirstCommonAncestorID(a._rootNodeID, b._rootNodeID); return idToInstance[commonID] || null; }, getParentInstance: function(inst) { var id = inst._rootNodeID; - var parentID = id.substr(0, id.lastIndexOf('.')); + var parentID = id.substr(0, id.lastIndexOf(SEPARATOR)); return idToInstance[parentID] || null; }, traverseTwoPhase: function(target, fn, arg) { - ReactInstanceHandles.traverseTwoPhase( + traverseTwoPhase( target._rootNodeID, - function(id, upwards) { - fn(idToInstance[id], upwards, arg); + function(id, phase) { + fn(idToInstance[id], phase, arg); } ); }, }); - - topLevelTypes = EventConstants.topLevelTypes; }); - it('should do nothing when no one wants to respond', function() { + it('should do nothing when no one wants to respond', () => { var config = oneEventLoopTestConfig(three); config.startShouldSetResponder.captured.grandParent = {order: 0, returnVal: false}; config.startShouldSetResponder.captured.parent = {order: 1, returnVal: false}; @@ -953,7 +1014,7 @@ describe('ResponderEventPlugin', function() { config.responderReject.parent = {order: 5}; run(config, three, { - topLevelType: topLevelTypes.topScroll, + topLevelType: 'topScroll', targetInst: idToInstance[three.parent], nativeEvent: {}, }); @@ -970,7 +1031,7 @@ describe('ResponderEventPlugin', function() { config.responderTerminate.child = {order: 5}; run(config, three, { - topLevelType: topLevelTypes.topScroll, + topLevelType: 'topScroll', targetInst: idToInstance[three.parent], nativeEvent: {}, }); @@ -997,7 +1058,7 @@ describe('ResponderEventPlugin', function() { config.responderTerminate.child = {order: 1}; var nativeEvent = _touchConfig( - topLevelTypes.topTouchCancel, + 'topTouchCancel', three.child, [three.child], [0] diff --git a/src/renderers/shared/stack/reconciler/ReactComponentEnvironment.js b/src/renderers/shared/stack/reconciler/ReactComponentEnvironment.js index 002f26459c..bb9835d5bc 100644 --- a/src/renderers/shared/stack/reconciler/ReactComponentEnvironment.js +++ b/src/renderers/shared/stack/reconciler/ReactComponentEnvironment.js @@ -7,12 +7,21 @@ * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponentEnvironment + * @flow */ 'use strict'; var invariant = require('invariant'); +type ReplaceNodeWithMarkup = (node: HTMLElement, markup: string) => void; +type ProcessChildrenUpdates = (instance: mixed, updates: mixed) => void; + +type Environment = { + replaceNodeWithMarkup: ReplaceNodeWithMarkup, + processChildrenUpdates: ProcessChildrenUpdates, +}; + var injected = false; var ReactComponentEnvironment = { @@ -21,16 +30,16 @@ var ReactComponentEnvironment = { * Optionally injectable hook for swapping out mount images in the middle of * the tree. */ - replaceNodeWithMarkup: null, + replaceNodeWithMarkup: (null: ?ReplaceNodeWithMarkup), /** * Optionally injectable hook for processing a queue of child updates. Will * later move into MultiChildComponents. */ - processChildrenUpdates: null, + processChildrenUpdates: (null: ?ReplaceNodeWithMarkup), injection: { - injectEnvironment: function(environment) { + injectEnvironment: function(environment: Environment) { invariant( !injected, 'ReactCompositeComponent: injectEnvironment() can only be called once.' diff --git a/src/renderers/shared/stack/reconciler/ReactCompositeComponent.js b/src/renderers/shared/stack/reconciler/ReactCompositeComponent.js index 6ee4e2aac7..388111d90e 100644 --- a/src/renderers/shared/stack/reconciler/ReactCompositeComponent.js +++ b/src/renderers/shared/stack/reconciler/ReactCompositeComponent.js @@ -11,23 +11,27 @@ 'use strict'; +var React = require('React'); var ReactComponentEnvironment = require('ReactComponentEnvironment'); var ReactCurrentOwner = require('ReactCurrentOwner'); -var ReactElement = require('ReactElement'); var ReactErrorUtils = require('ReactErrorUtils'); var ReactInstanceMap = require('ReactInstanceMap'); var ReactInstrumentation = require('ReactInstrumentation'); var ReactNodeTypes = require('ReactNodeTypes'); -var ReactPropTypeLocations = require('ReactPropTypeLocations'); var ReactReconciler = require('ReactReconciler'); -var checkReactTypeSpec = require('checkReactTypeSpec'); +if (__DEV__) { + var checkReactTypeSpec = require('checkReactTypeSpec'); +} + var emptyObject = require('emptyObject'); var invariant = require('invariant'); var shallowEqual = require('shallowEqual'); var shouldUpdateReactComponent = require('shouldUpdateReactComponent'); var warning = require('warning'); +import type { ReactPropTypeLocations } from 'ReactPropTypeLocations'; + var CompositeTypes = { ImpureClass: 0, PureClass: 1, @@ -46,7 +50,7 @@ StatelessComponent.prototype.render = function() { function warnIfInvalidElement(Component, element) { if (__DEV__) { warning( - element === null || element === false || ReactElement.isValidElement(element), + element === null || element === false || React.isValidElement(element), '%s(...): A valid React element (or null) must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', Component.displayName || Component.name || 'Component' @@ -122,7 +126,7 @@ var nextMountID = 1; /** * @lends {ReactCompositeComponent.prototype} */ -var ReactCompositeComponentMixin = { +var ReactCompositeComponent = { /** * Base constructor for all composite component. @@ -209,7 +213,7 @@ var ReactCompositeComponentMixin = { invariant( inst === null || inst === false || - ReactElement.isValidElement(inst), + React.isValidElement(inst), '%s(...): A valid React element (or null) must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', Component.displayName || Component.name || 'Component' @@ -614,7 +618,7 @@ var ReactCompositeComponentMixin = { this._checkContextTypes( Component.contextTypes, maskedContext, - ReactPropTypeLocations.context + 'context' ); } } @@ -655,7 +659,7 @@ var ReactCompositeComponentMixin = { this._checkContextTypes( Component.childContextTypes, childContext, - ReactPropTypeLocations.childContext + 'childContext' ); } for (var name in childContext) { @@ -679,15 +683,21 @@ var ReactCompositeComponentMixin = { * @param {string} location e.g. "prop", "context", "child context" * @private */ - _checkContextTypes: function(typeSpecs, values, location) { - checkReactTypeSpec( - typeSpecs, - values, - location, - this.getName(), - null, - this._debugID - ); + _checkContextTypes: function( + typeSpecs, + values, + location: ReactPropTypeLocations, + ) { + if (__DEV__) { + checkReactTypeSpec( + typeSpecs, + values, + location, + this.getName(), + null, + this._debugID + ); + } }, receiveComponent: function(nextElement, transaction, nextContext) { @@ -1028,58 +1038,58 @@ var ReactCompositeComponentMixin = { */ _renderValidatedComponentWithoutOwnerOrContext: function() { var inst = this._instance; - var renderedComponent; + var renderedElement; if (__DEV__) { - renderedComponent = measureLifeCyclePerf( + renderedElement = measureLifeCyclePerf( () => inst.render(), this._debugID, 'render' ); } else { - renderedComponent = inst.render(); + renderedElement = inst.render(); } if (__DEV__) { // We allow auto-mocks to proceed as if they're returning null. - if (renderedComponent === undefined && + if (renderedElement === undefined && inst.render._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. - renderedComponent = null; + renderedElement = null; } } - return renderedComponent; + return renderedElement; }, /** * @private */ _renderValidatedComponent: function() { - var renderedComponent; + var renderedElement; if (__DEV__ || this._compositeType !== CompositeTypes.StatelessFunctional) { ReactCurrentOwner.current = this; try { - renderedComponent = + renderedElement = this._renderValidatedComponentWithoutOwnerOrContext(); } finally { ReactCurrentOwner.current = null; } } else { - renderedComponent = + renderedElement = this._renderValidatedComponentWithoutOwnerOrContext(); } invariant( // TODO: An `isValidNode` function would probably be more appropriate - renderedComponent === null || renderedComponent === false || - ReactElement.isValidElement(renderedComponent), + renderedElement === null || renderedElement === false || + React.isValidElement(renderedElement), '%s.render(): A valid React element (or null) must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', this.getName() || 'ReactCompositeComponent' ); - return renderedComponent; + return renderedElement; }, /** @@ -1161,10 +1171,4 @@ var ReactCompositeComponentMixin = { }; -var ReactCompositeComponent = { - - Mixin: ReactCompositeComponentMixin, - -}; - module.exports = ReactCompositeComponent; diff --git a/src/renderers/shared/stack/reconciler/ReactDefaultBatchingStrategy.js b/src/renderers/shared/stack/reconciler/ReactDefaultBatchingStrategy.js index 904dc1f803..b5db558d40 100644 --- a/src/renderers/shared/stack/reconciler/ReactDefaultBatchingStrategy.js +++ b/src/renderers/shared/stack/reconciler/ReactDefaultBatchingStrategy.js @@ -36,7 +36,7 @@ function ReactDefaultBatchingStrategyTransaction() { Object.assign( ReactDefaultBatchingStrategyTransaction.prototype, - Transaction.Mixin, + Transaction, { getTransactionWrappers: function() { return TRANSACTION_WRAPPERS; @@ -60,9 +60,9 @@ var ReactDefaultBatchingStrategy = { // The code is written this way to avoid extra allocations if (alreadyBatchingUpdates) { - callback(a, b, c, d, e); + return callback(a, b, c, d, e); } else { - transaction.perform(callback, null, a, b, c, d, e); + return transaction.perform(callback, null, a, b, c, d, e); } }, }; diff --git a/src/renderers/shared/stack/reconciler/ReactInstanceHandles.js b/src/renderers/shared/stack/reconciler/ReactInstanceHandles.js deleted file mode 100644 index 11d4a3eea3..0000000000 --- a/src/renderers/shared/stack/reconciler/ReactInstanceHandles.js +++ /dev/null @@ -1,337 +0,0 @@ -/** - * Copyright 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - * - * @providesModule ReactInstanceHandles - */ - -'use strict'; - -var invariant = require('invariant'); - -var SEPARATOR = '.'; -var SEPARATOR_LENGTH = SEPARATOR.length; - -/** - * Maximum depth of traversals before we consider the possibility of a bad ID. - */ -var MAX_TREE_DEPTH = 10000; - -/** - * Creates a DOM ID prefix to use when mounting React components. - * - * @param {number} index A unique integer - * @return {string} React root ID. - * @internal - */ -function getReactRootIDString(index) { - return SEPARATOR + index.toString(36); -} - -/** - * Checks if a character in the supplied ID is a separator or the end. - * - * @param {string} id A React DOM ID. - * @param {number} index Index of the character to check. - * @return {boolean} True if the character is a separator or end of the ID. - * @private - */ -function isBoundary(id, index) { - return id.charAt(index) === SEPARATOR || index === id.length; -} - -/** - * Checks if the supplied string is a valid React DOM ID. - * - * @param {string} id A React DOM ID, maybe. - * @return {boolean} True if the string is a valid React DOM ID. - * @private - */ -function isValidID(id) { - return id === '' || ( - id.charAt(0) === SEPARATOR && id.charAt(id.length - 1) !== SEPARATOR - ); -} - -/** - * Checks if the first ID is an ancestor of or equal to the second ID. - * - * @param {string} ancestorID - * @param {string} descendantID - * @return {boolean} True if `ancestorID` is an ancestor of `descendantID`. - * @internal - */ -function isAncestorIDOf(ancestorID, descendantID) { - return ( - descendantID.indexOf(ancestorID) === 0 && - isBoundary(descendantID, ancestorID.length) - ); -} - -/** - * Gets the parent ID of the supplied React DOM ID, `id`. - * - * @param {string} id ID of a component. - * @return {string} ID of the parent, or an empty string. - * @private - */ -function getParentID(id) { - return id ? id.substr(0, id.lastIndexOf(SEPARATOR)) : ''; -} - -/** - * Gets the next DOM ID on the tree path from the supplied `ancestorID` to the - * supplied `destinationID`. If they are equal, the ID is returned. - * - * @param {string} ancestorID ID of an ancestor node of `destinationID`. - * @param {string} destinationID ID of the destination node. - * @return {string} Next ID on the path from `ancestorID` to `destinationID`. - * @private - */ -function getNextDescendantID(ancestorID, destinationID) { - invariant( - isValidID(ancestorID) && isValidID(destinationID), - 'getNextDescendantID(%s, %s): Received an invalid React DOM ID.', - ancestorID, - destinationID - ); - invariant( - isAncestorIDOf(ancestorID, destinationID), - 'getNextDescendantID(...): React has made an invalid assumption about ' + - 'the DOM hierarchy. Expected `%s` to be an ancestor of `%s`.', - ancestorID, - destinationID - ); - if (ancestorID === destinationID) { - return ancestorID; - } - // Skip over the ancestor and the immediate separator. Traverse until we hit - // another separator or we reach the end of `destinationID`. - var start = ancestorID.length + SEPARATOR_LENGTH; - var i; - for (i = start; i < destinationID.length; i++) { - if (isBoundary(destinationID, i)) { - break; - } - } - return destinationID.substr(0, i); -} - -/** - * Gets the nearest common ancestor ID of two IDs. - * - * Using this ID scheme, the nearest common ancestor ID is the longest common - * prefix of the two IDs that immediately preceded a "marker" in both strings. - * - * @param {string} oneID - * @param {string} twoID - * @return {string} Nearest common ancestor ID, or the empty string if none. - * @private - */ -function getFirstCommonAncestorID(oneID, twoID) { - var minLength = Math.min(oneID.length, twoID.length); - if (minLength === 0) { - return ''; - } - var lastCommonMarkerIndex = 0; - // Use `<=` to traverse until the "EOL" of the shorter string. - for (var i = 0; i <= minLength; i++) { - if (isBoundary(oneID, i) && isBoundary(twoID, i)) { - lastCommonMarkerIndex = i; - } else if (oneID.charAt(i) !== twoID.charAt(i)) { - break; - } - } - var longestCommonID = oneID.substr(0, lastCommonMarkerIndex); - invariant( - isValidID(longestCommonID), - 'getFirstCommonAncestorID(%s, %s): Expected a valid React DOM ID: %s', - oneID, - twoID, - longestCommonID - ); - return longestCommonID; -} - -/** - * Traverses the parent path between two IDs (either up or down). The IDs must - * not be the same, and there must exist a parent path between them. If the - * callback returns `false`, traversal is stopped. - * - * @param {?string} start ID at which to start traversal. - * @param {?string} stop ID at which to end traversal. - * @param {function} cb Callback to invoke each ID with. - * @param {*} arg Argument to invoke the callback with. - * @param {?boolean} skipFirst Whether or not to skip the first node. - * @param {?boolean} skipLast Whether or not to skip the last node. - * @private - */ -function traverseParentPath(start, stop, cb, arg, skipFirst, skipLast) { - start = start || ''; - stop = stop || ''; - invariant( - start !== stop, - 'traverseParentPath(...): Cannot traverse from and to the same ID, `%s`.', - start - ); - var traverseUp = isAncestorIDOf(stop, start); - invariant( - traverseUp || isAncestorIDOf(start, stop), - 'traverseParentPath(%s, %s, ...): Cannot traverse from two IDs that do ' + - 'not have a parent path.', - start, - stop - ); - // Traverse from `start` to `stop` one depth at a time. - var depth = 0; - var traverse = traverseUp ? getParentID : getNextDescendantID; - for (var id = start; /* until break */; id = traverse(id, stop)) { - var ret; - if ((!skipFirst || id !== start) && (!skipLast || id !== stop)) { - ret = cb(id, traverseUp, arg); - } - if (ret === false || id === stop) { - // Only break //after// visiting `stop`. - break; - } - invariant( - depth++ < MAX_TREE_DEPTH, - 'traverseParentPath(%s, %s, ...): Detected an infinite loop while ' + - 'traversing the React DOM ID tree. This may be due to malformed IDs: %s', - start, stop, id - ); - } -} - -/** - * Manages the IDs assigned to DOM representations of React components. This - * uses a specific scheme in order to traverse the DOM efficiently (e.g. in - * order to simulate events). - * - * @internal - */ -var ReactInstanceHandles = { - - /** - * Constructs a React root ID - * @param {number} index A unique integer - * @return {string} A React root ID. - */ - createReactRootID: function(index) { - return getReactRootIDString(index); - }, - - /** - * Constructs a React ID by joining a root ID with a name. - * - * @param {string} rootID Root ID of a parent component. - * @param {string} name A component's name (as flattened children). - * @return {string} A React ID. - * @internal - */ - createReactID: function(rootID, name) { - return rootID + name; - }, - - /** - * Gets the DOM ID of the React component that is the root of the tree that - * contains the React component with the supplied DOM ID. - * - * @param {string} id DOM ID of a React component. - * @return {?string} DOM ID of the React component that is the root. - * @internal - */ - getReactRootIDFromNodeID: function(id) { - if (id && id.charAt(0) === SEPARATOR && id.length > 1) { - var index = id.indexOf(SEPARATOR, 1); - return index > -1 ? id.substr(0, index) : id; - } - return null; - }, - - /** - * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that - * should would receive a `mouseEnter` or `mouseLeave` event. - * - * NOTE: Does not invoke the callback on the nearest common ancestor because - * nothing "entered" or "left" that element. - * - * @param {string} leaveID ID being left. - * @param {string} enterID ID being entered. - * @param {function} cb Callback to invoke on each entered/left ID. - * @param {*} upArg Argument to invoke the callback with on left IDs. - * @param {*} downArg Argument to invoke the callback with on entered IDs. - * @internal - */ - traverseEnterLeave: function(leaveID, enterID, cb, upArg, downArg) { - var ancestorID = getFirstCommonAncestorID(leaveID, enterID); - if (ancestorID !== leaveID) { - traverseParentPath(leaveID, ancestorID, cb, upArg, false, true); - } - if (ancestorID !== enterID) { - traverseParentPath(ancestorID, enterID, cb, downArg, true, false); - } - }, - - /** - * Simulates the traversal of a two-phase, capture/bubble event dispatch. - * - * NOTE: This traversal happens on IDs without touching the DOM. - * - * @param {string} targetID ID of the target node. - * @param {function} cb Callback to invoke. - * @param {*} arg Argument to invoke the callback with. - * @internal - */ - traverseTwoPhase: function(targetID, cb, arg) { - if (targetID) { - traverseParentPath('', targetID, cb, arg, true, false); - traverseParentPath(targetID, '', cb, arg, false, true); - } - }, - - /** - * Same as `traverseTwoPhase` but skips the `targetID`. - */ - traverseTwoPhaseSkipTarget: function(targetID, cb, arg) { - if (targetID) { - traverseParentPath('', targetID, cb, arg, true, true); - traverseParentPath(targetID, '', cb, arg, true, true); - } - }, - - /** - * Traverse a node ID, calling the supplied `cb` for each ancestor ID. For - * example, passing `.0.$row-0.1` would result in `cb` getting called - * with `.0`, `.0.$row-0`, and `.0.$row-0.1`. - * - * NOTE: This traversal happens on IDs without touching the DOM. - * - * @param {string} targetID ID of the target node. - * @param {function} cb Callback to invoke. - * @param {*} arg Argument to invoke the callback with. - * @internal - */ - traverseAncestors: function(targetID, cb, arg) { - traverseParentPath('', targetID, cb, arg, true, false); - }, - - getFirstCommonAncestorID: getFirstCommonAncestorID, - - /** - * Exposed for unit testing. - * @private - */ - _getNextDescendantID: getNextDescendantID, - - isAncestorIDOf: isAncestorIDOf, - - SEPARATOR: SEPARATOR, - -}; - -module.exports = ReactInstanceHandles; diff --git a/src/renderers/shared/stack/reconciler/ReactInstanceType.js b/src/renderers/shared/stack/reconciler/ReactInstanceType.js new file mode 100644 index 0000000000..bb213281b9 --- /dev/null +++ b/src/renderers/shared/stack/reconciler/ReactInstanceType.js @@ -0,0 +1,42 @@ +/** + * Copyright 2016-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactInstanceType + * @flow + */ + +'use strict'; + +export type DebugID = number; + +export type ReactInstance = { + // ReactCompositeComponent + mountComponent: any, + performInitialMountWithErrorHandling: any, + performInitialMount: any, + getHostNode: any, + unmountComponent: any, + receiveComponent: any, + performUpdateIfNecessary: any, + updateComponent: any, + attachRef: (ref: string, component: ReactInstance) => void, + detachRef: (ref: string) => void, + getName: () => string, + getPublicInstance: any, + _rootNodeID: number, + + // ReactDOMComponent + _tag: string, + + // instantiateReactComponent + _mountIndex: number, + _mountImage: any, + // __DEV__ + _debugID: DebugID, + _warnedAboutRefsInRender: boolean, +}; diff --git a/src/renderers/shared/stack/reconciler/ReactMultiChild.js b/src/renderers/shared/stack/reconciler/ReactMultiChild.js index 8796e92775..a0d05a76e6 100644 --- a/src/renderers/shared/stack/reconciler/ReactMultiChild.js +++ b/src/renderers/shared/stack/reconciler/ReactMultiChild.js @@ -14,7 +14,6 @@ var ReactComponentEnvironment = require('ReactComponentEnvironment'); var ReactInstanceMap = require('ReactInstanceMap'); var ReactInstrumentation = require('ReactInstrumentation'); -var ReactMultiChildUpdateTypes = require('ReactMultiChildUpdateTypes'); var ReactCurrentOwner = require('ReactCurrentOwner'); var ReactReconciler = require('ReactReconciler'); @@ -34,7 +33,7 @@ var invariant = require('invariant'); function makeInsertMarkup(markup, afterNode, toIndex) { // NOTE: Null values reduce hidden classes. return { - type: ReactMultiChildUpdateTypes.INSERT_MARKUP, + type: 'INSERT_MARKUP', content: markup, fromIndex: null, fromNode: null, @@ -53,7 +52,7 @@ function makeInsertMarkup(markup, afterNode, toIndex) { function makeMove(child, afterNode, toIndex) { // NOTE: Null values reduce hidden classes. return { - type: ReactMultiChildUpdateTypes.MOVE_EXISTING, + type: 'MOVE_EXISTING', content: null, fromIndex: child._mountIndex, fromNode: ReactReconciler.getHostNode(child), @@ -71,7 +70,7 @@ function makeMove(child, afterNode, toIndex) { function makeRemove(child, node) { // NOTE: Null values reduce hidden classes. return { - type: ReactMultiChildUpdateTypes.REMOVE_NODE, + type: 'REMOVE_NODE', content: null, fromIndex: child._mountIndex, fromNode: node, @@ -89,7 +88,7 @@ function makeRemove(child, node) { function makeSetMarkup(markup) { // NOTE: Null values reduce hidden classes. return { - type: ReactMultiChildUpdateTypes.SET_MARKUP, + type: 'SET_MARKUP', content: markup, fromIndex: null, fromNode: null, @@ -107,7 +106,7 @@ function makeSetMarkup(markup) { function makeTextContent(textContent) { // NOTE: Null values reduce hidden classes. return { - type: ReactMultiChildUpdateTypes.TEXT_CONTENT, + type: 'TEXT_CONTENT', content: textContent, fromIndex: null, fromNode: null, diff --git a/src/renderers/shared/stack/reconciler/ReactMultiChildUpdateTypes.js b/src/renderers/shared/stack/reconciler/ReactMultiChildUpdateTypes.js index 8e123549de..acccdc4972 100644 --- a/src/renderers/shared/stack/reconciler/ReactMultiChildUpdateTypes.js +++ b/src/renderers/shared/stack/reconciler/ReactMultiChildUpdateTypes.js @@ -11,22 +11,15 @@ 'use strict'; -var keyMirror = require('keyMirror'); - /** * When a component's children are updated, a series of update configuration * objects are created in order to batch and serialize the required changes. * * Enumerates all the possible types of update configurations. - * - * @internal */ -var ReactMultiChildUpdateTypes = keyMirror({ - INSERT_MARKUP: null, - MOVE_EXISTING: null, - REMOVE_NODE: null, - SET_MARKUP: null, - TEXT_CONTENT: null, -}); - -module.exports = ReactMultiChildUpdateTypes; +export type ReactMultiChildUpdateTypes = + 'INSERT_MARKUP' | + 'MOVE_EXISTING' | + 'REMOVE_NODE' | + 'SET_MARKUP' | + 'TEXT_CONTENT'; diff --git a/src/renderers/shared/stack/reconciler/ReactNodeTypes.js b/src/renderers/shared/stack/reconciler/ReactNodeTypes.js index 2b5e40376d..7b8d6f2094 100644 --- a/src/renderers/shared/stack/reconciler/ReactNodeTypes.js +++ b/src/renderers/shared/stack/reconciler/ReactNodeTypes.js @@ -14,7 +14,7 @@ type ReactNodeType = 0 | 1 | 2; -var ReactElement = require('ReactElement'); +var React = require('React'); var invariant = require('invariant'); @@ -26,7 +26,7 @@ var ReactNodeTypes = { getType: function(node: ReactElement): ReactNodeType { if (node === null || node === false) { return ReactNodeTypes.EMPTY; - } else if (ReactElement.isValidElement(node)) { + } else if (React.isValidElement(node)) { if (typeof node.type === 'function') { return ReactNodeTypes.COMPOSITE; } else { diff --git a/src/renderers/shared/stack/reconciler/ReactOwner.js b/src/renderers/shared/stack/reconciler/ReactOwner.js index df2bfb8d7b..c634dfb384 100644 --- a/src/renderers/shared/stack/reconciler/ReactOwner.js +++ b/src/renderers/shared/stack/reconciler/ReactOwner.js @@ -7,12 +7,28 @@ * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactOwner + * @flow */ 'use strict'; var invariant = require('invariant'); +import type { ReactInstance } from 'ReactInstanceType'; + +/** + * @param {?object} object + * @return {boolean} True if `object` is a valid owner. + * @final + */ +function isValidOwner(object: any): boolean { + return !!( + object && + typeof object.attachRef === 'function' && + typeof object.detachRef === 'function' + ); +} + /** * ReactOwners are capable of storing references to owned components. * @@ -44,20 +60,6 @@ var invariant = require('invariant'); * @class ReactOwner */ var ReactOwner = { - - /** - * @param {?object} object - * @return {boolean} True if `object` is a valid owner. - * @final - */ - isValidOwner: function(object) { - return !!( - object && - typeof object.attachRef === 'function' && - typeof object.detachRef === 'function' - ); - }, - /** * Adds a component by ref to an owner component. * @@ -67,9 +69,13 @@ var ReactOwner = { * @final * @internal */ - addComponentAsRefTo: function(component, ref, owner) { + addComponentAsRefTo: function( + component: ReactInstance, + ref: string, + owner: ReactInstance, + ): void { invariant( - ReactOwner.isValidOwner(owner), + isValidOwner(owner), 'addComponentAsRefTo(...): Only a ReactOwner can have refs. You might ' + 'be adding a ref to a component that was not created inside a component\'s ' + '`render` method, or you have multiple copies of React loaded ' + @@ -87,9 +93,13 @@ var ReactOwner = { * @final * @internal */ - removeComponentAsRefFrom: function(component, ref, owner) { + removeComponentAsRefFrom: function( + component: ReactInstance, + ref: string, + owner: ReactInstance, + ): void { invariant( - ReactOwner.isValidOwner(owner), + isValidOwner(owner), 'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. You might ' + 'be removing a ref to a component that was not created inside a component\'s ' + '`render` method, or you have multiple copies of React loaded ' + diff --git a/src/renderers/shared/stack/reconciler/ReactRef.js b/src/renderers/shared/stack/reconciler/ReactRef.js index a33ca13f1c..a7350cc6a8 100644 --- a/src/renderers/shared/stack/reconciler/ReactRef.js +++ b/src/renderers/shared/stack/reconciler/ReactRef.js @@ -7,12 +7,16 @@ * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactRef + * @flow */ 'use strict'; var ReactOwner = require('ReactOwner'); +import type { ReactInstance } from 'ReactInstanceType'; +import type { ReactElement } from 'ReactElementType'; + var ReactRef = {}; function attachRef(ref, component, owner) { @@ -20,7 +24,11 @@ function attachRef(ref, component, owner) { ref(component.getPublicInstance()); } else { // Legacy ref - ReactOwner.addComponentAsRefTo(component, ref, owner); + ReactOwner.addComponentAsRefTo( + component, + ref, + owner, + ); } } @@ -33,8 +41,11 @@ function detachRef(ref, component, owner) { } } -ReactRef.attachRefs = function(instance, element) { - if (element === null || element === false) { +ReactRef.attachRefs = function( + instance: ReactInstance, + element: ReactElement | string | number | null | false, +): void { + if (element === null || typeof element !== 'object') { return; } var ref = element.ref; @@ -43,7 +54,10 @@ ReactRef.attachRefs = function(instance, element) { } }; -ReactRef.shouldUpdateRefs = function(prevElement, nextElement) { +ReactRef.shouldUpdateRefs = function( + prevElement: ReactElement | string | number | null | false, + nextElement: ReactElement | string | number | null | false, +): boolean { // If either the owner or a `ref` has changed, make sure the newest owner // has stored a reference to `this`, and the previous owner (if different) // has forgotten the reference to `this`. We use the element instead @@ -56,21 +70,32 @@ ReactRef.shouldUpdateRefs = function(prevElement, nextElement) { // is made. It probably belongs where the key checking and // instantiateReactComponent is done. - var prevEmpty = prevElement === null || prevElement === false; - var nextEmpty = nextElement === null || nextElement === false; + var prevRef = null; + var prevOwner = null; + if (prevElement !== null && typeof prevElement === 'object') { + prevRef = prevElement.ref; + prevOwner = prevElement._owner; + } + + var nextRef = null; + var nextOwner = null; + if (nextElement !== null && typeof nextElement === 'object') { + nextRef = nextElement.ref; + nextOwner = nextElement._owner; + } return ( - // This has a few false positives w/r/t empty components. - prevEmpty || nextEmpty || - nextElement.ref !== prevElement.ref || + prevRef !== nextRef || // If owner changes but we have an unchanged function ref, don't update refs - (typeof nextElement.ref === 'string' && - nextElement._owner !== prevElement._owner) + (typeof nextRef === 'string' && nextOwner !== prevOwner) ); }; -ReactRef.detachRefs = function(instance, element) { - if (element === null || element === false) { +ReactRef.detachRefs = function( + instance: ReactInstance, + element: ReactElement | string | number | null | false, +): void { + if (element === null || typeof element !== 'object') { return; } var ref = element.ref; diff --git a/src/renderers/shared/stack/reconciler/ReactUpdates.js b/src/renderers/shared/stack/reconciler/ReactUpdates.js index 2009fb3134..d605c5881e 100644 --- a/src/renderers/shared/stack/reconciler/ReactUpdates.js +++ b/src/renderers/shared/stack/reconciler/ReactUpdates.js @@ -75,7 +75,7 @@ function ReactUpdatesFlushTransaction() { Object.assign( ReactUpdatesFlushTransaction.prototype, - Transaction.Mixin, + Transaction, { getTransactionWrappers: function() { return TRANSACTION_WRAPPERS; @@ -92,7 +92,7 @@ Object.assign( perform: function(method, scope, a) { // Essentially calls `this.reconcileTransaction.perform(method, scope, a)` // with this transaction's wrappers around it. - return Transaction.Mixin.perform.call( + return Transaction.perform.call( this, this.reconcileTransaction.perform, this.reconcileTransaction, @@ -108,7 +108,7 @@ PooledClass.addPoolingTo(ReactUpdatesFlushTransaction); function batchedUpdates(callback, a, b, c, d, e) { ensureInjected(); - batchingStrategy.batchedUpdates(callback, a, b, c, d, e); + return batchingStrategy.batchedUpdates(callback, a, b, c, d, e); } /** @@ -160,10 +160,7 @@ function runBatchedUpdates(transaction) { if (ReactFeatureFlags.logTopLevelRenders) { var namedComponent = component; // Duck type TopLevelWrapper. This is probably always true. - if ( - component._currentElement.props === - component._renderedComponent._currentElement - ) { + if (component._currentElement.type.isReactTopLevelWrapper) { namedComponent = component._renderedComponent; } markerName = 'React update: ' + namedComponent.getName(); diff --git a/src/renderers/shared/stack/reconciler/__tests__/ReactChildReconciler-test.js b/src/renderers/shared/stack/reconciler/__tests__/ReactChildReconciler-test.js index 3343b79b82..6cc5115a0c 100644 --- a/src/renderers/shared/stack/reconciler/__tests__/ReactChildReconciler-test.js +++ b/src/renderers/shared/stack/reconciler/__tests__/ReactChildReconciler-test.js @@ -17,19 +17,19 @@ var React; var ReactTestUtils; -describe('ReactChildReconciler', function() { +describe('ReactChildReconciler', () => { function normalizeCodeLocInfo(str) { return str.replace(/\(at .+?:\d+\)/g, '(at **)'); } - beforeEach(function() { + beforeEach(() => { jest.resetModuleRegistry(); React = require('React'); ReactTestUtils = require('ReactTestUtils'); }); - it('warns for duplicated keys', function() { + it('warns for duplicated keys', () => { spyOn(console, 'error'); class Component extends React.Component { @@ -46,7 +46,7 @@ describe('ReactChildReconciler', function() { ); }); - it('warns for duplicated keys with component stack info', function() { + it('warns for duplicated keys with component stack info', () => { spyOn(console, 'error'); class Component extends React.Component { diff --git a/src/renderers/shared/stack/reconciler/__tests__/ReactComponent-test.js b/src/renderers/shared/stack/reconciler/__tests__/ReactComponent-test.js index b5ae5c5829..769b2bafcc 100644 --- a/src/renderers/shared/stack/reconciler/__tests__/ReactComponent-test.js +++ b/src/renderers/shared/stack/reconciler/__tests__/ReactComponent-test.js @@ -15,18 +15,14 @@ var React; var ReactDOM; var ReactTestUtils; -function normalizeCodeLocInfo(str) { - return str.replace(/\(at .+?:\d+\)/g, '(at **)'); -} - -describe('ReactComponent', function() { - beforeEach(function() { +describe('ReactComponent', () => { + beforeEach(() => { React = require('React'); ReactDOM = require('ReactDOM'); ReactTestUtils = require('ReactTestUtils'); }); - it('should throw on invalid render targets', function() { + it('should throw on invalid render targets', () => { var container = document.createElement('div'); // jQuery objects are basically arrays; people often pass them in by mistake expect(function() { @@ -42,40 +38,56 @@ describe('ReactComponent', function() { ); }); - it('should throw when supplying a ref outside of render method', function() { + it('should throw when supplying a ref outside of render method', () => { var instance =
; expect(function() { instance = ReactTestUtils.renderIntoDocument(instance); }).toThrow(); }); - it('should warn when children are mutated before render', function() { + it('should warn when children are mutated during render', () => { spyOn(console, 'error'); - var children = [, , ]; - var element =
{children}
; - children[1] =

; // Mutation is illegal - ReactTestUtils.renderIntoDocument(element); - expect(console.error.calls.count()).toBe(1); - expect(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe( - 'Warning: Component\'s children should not be mutated.\n in div (at **)' - ); - }); - - it('should warn when children are mutated', function() { - spyOn(console, 'error'); - var children = [, , ]; function Wrapper(props) { props.children[1] =

; // Mutation is illegal return

{props.children}
; } - ReactTestUtils.renderIntoDocument({children}); - expect(console.error.calls.count()).toBe(1); - expect(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe( - 'Warning: Component\'s children should not be mutated.\n in Wrapper (at **)' - ); + expect(() => { + ReactTestUtils.renderIntoDocument( + + + + + + ); + }).toThrowError(/Cannot assign to read only property.*/); }); - it('should support refs on owned components', function() { + it('should warn when children are mutated during update', () => { + spyOn(console, 'error'); + + class Wrapper extends React.Component { + componentDidMount() { + this.props.children[1] =

; // Mutation is illegal + this.forceUpdate(); + } + + render() { + return

{this.props.children}
; + } + } + + expect(() => { + ReactTestUtils.renderIntoDocument( + + + + + + ); + }).toThrowError(/Cannot assign to read only property.*/); + }); + + it('should support refs on owned components', () => { var innerObj = {}; var outerObj = {}; @@ -106,7 +118,7 @@ describe('ReactComponent', function() { instance = ReactTestUtils.renderIntoDocument(instance); }); - it('should not have refs on unmounted components', function() { + it('should not have refs on unmounted components', () => { class Parent extends React.Component { render() { return
; @@ -127,7 +139,7 @@ describe('ReactComponent', function() { instance = ReactTestUtils.renderIntoDocument(instance); }); - it('should support new-style refs', function() { + it('should support new-style refs', () => { var innerObj = {}; var outerObj = {}; @@ -166,7 +178,7 @@ describe('ReactComponent', function() { expect(mounted).toBe(true); }); - it('should support new-style refs with mixed-up owners', function() { + it('should support new-style refs with mixed-up owners', () => { class Wrapper extends React.Component { getTitle = () => { return this.props.title; @@ -209,7 +221,7 @@ describe('ReactComponent', function() { expect(mounted).toBe(true); }); - it('should call refs at the correct time', function() { + it('should call refs at the correct time', () => { var log = []; class Inner extends React.Component { @@ -298,7 +310,7 @@ describe('ReactComponent', function() { /* eslint-enable indent */ }); - it('fires the callback after a component is rendered', function() { + it('fires the callback after a component is rendered', () => { var callback = jest.fn(); var container = document.createElement('div'); ReactDOM.render(
, container, callback); @@ -309,7 +321,7 @@ describe('ReactComponent', function() { expect(callback.mock.calls.length).toBe(3); }); - it('throws usefully when rendering badly-typed elements', function() { + it('throws usefully when rendering badly-typed elements', () => { spyOn(console, 'error'); var X = undefined; diff --git a/src/renderers/shared/stack/reconciler/__tests__/ReactComponentLifeCycle-test.js b/src/renderers/shared/stack/reconciler/__tests__/ReactComponentLifeCycle-test.js index 0b195ef20a..9c2f564675 100644 --- a/src/renderers/shared/stack/reconciler/__tests__/ReactComponentLifeCycle-test.js +++ b/src/renderers/shared/stack/reconciler/__tests__/ReactComponentLifeCycle-test.js @@ -11,8 +11,6 @@ 'use strict'; -var keyMirror = require('keyMirror'); - var React; var ReactDOM; var ReactInstanceMap; @@ -68,25 +66,24 @@ var POST_WILL_UNMOUNT_STATE = { /** * Every React component is in one of these life cycles. */ -var ComponentLifeCycle = keyMirror({ +type ComponentLifeCycle = /** * Mounted components have a DOM node representation and are capable of * receiving new props. */ - MOUNTED: null, + 'MOUNTED' | /** * Unmounted components are inactive and cannot receive new props. */ - UNMOUNTED: null, -}); + 'UNMOUNTED'; -function getLifeCycleState(instance) { +function getLifeCycleState(instance): ComponentLifeCycle { var internalInstance = ReactInstanceMap.get(instance); // Once a component gets mounted, it has an internal instance, once it // gets unmounted, it loses that internal instance. return internalInstance ? - ComponentLifeCycle.MOUNTED : - ComponentLifeCycle.UNMOUNTED; + 'MOUNTED' : + 'UNMOUNTED'; } /** @@ -96,8 +93,8 @@ function getLifeCycleState(instance) { * is *reused*, then that won't be the case and things will appear to work in * some cases. Better to just block all updates in initialization. */ -describe('ReactComponentLifeCycle', function() { - beforeEach(function() { +describe('ReactComponentLifeCycle', () => { + beforeEach(() => { jest.resetModuleRegistry(); React = require('React'); ReactDOM = require('ReactDOM'); @@ -105,7 +102,7 @@ describe('ReactComponentLifeCycle', function() { ReactInstanceMap = require('ReactInstanceMap'); }); - it('should not reuse an instance when it has been unmounted', function() { + it('should not reuse an instance when it has been unmounted', () => { var container = document.createElement('div'); class StatefulComponent extends React.Component { @@ -129,7 +126,7 @@ describe('ReactComponentLifeCycle', function() { * If a state update triggers rerendering that in turn fires an onDOMReady, * that second onDOMReady should not fail. */ - it('it should fire onDOMReady when already in onDOMReady', function() { + it('it should fire onDOMReady when already in onDOMReady', () => { var _testJournal = []; class Child extends React.Component { @@ -180,7 +177,7 @@ describe('ReactComponentLifeCycle', function() { // You could assign state here, but not access members of it, unless you // had provided a getInitialState method. - it('throws when accessing state in componentWillMount', function() { + it('throws when accessing state in componentWillMount', () => { class StatefulComponent extends React.Component { componentWillMount() { void this.state.yada; @@ -199,7 +196,7 @@ describe('ReactComponentLifeCycle', function() { }).toThrow(); }); - it('should allow update state inside of componentWillMount', function() { + it('should allow update state inside of componentWillMount', () => { class StatefulComponent extends React.Component { componentWillMount() { this.setState({stateField: 'something'}); @@ -218,7 +215,7 @@ describe('ReactComponentLifeCycle', function() { }).not.toThrow(); }); - it('should not allow update state inside of getInitialState', function() { + it('should not allow update state inside of getInitialState', () => { spyOn(console, 'error'); class StatefulComponent extends React.Component { @@ -246,7 +243,7 @@ describe('ReactComponentLifeCycle', function() { ); }); - it('should correctly determine if a component is mounted', function() { + it('should correctly determine if a component is mounted', () => { spyOn(console, 'error'); var Component = React.createClass({ componentWillMount: function() { @@ -272,7 +269,7 @@ describe('ReactComponentLifeCycle', function() { ); }); - it('should correctly determine if a null component is mounted', function() { + it('should correctly determine if a null component is mounted', () => { spyOn(console, 'error'); var Component = React.createClass({ componentWillMount: function() { @@ -298,7 +295,7 @@ describe('ReactComponentLifeCycle', function() { ); }); - it('isMounted should return false when unmounted', function() { + it('isMounted should return false when unmounted', () => { var Component = React.createClass({ render: function() { return
; @@ -315,7 +312,7 @@ describe('ReactComponentLifeCycle', function() { expect(instance.isMounted()).toBe(false); }); - it('warns if findDOMNode is used inside render', function() { + it('warns if findDOMNode is used inside render', () => { spyOn(console, 'error'); var Component = React.createClass({ getInitialState: function() { @@ -339,7 +336,7 @@ describe('ReactComponentLifeCycle', function() { ); }); - it('should carry through each of the phases of setup', function() { + it('should carry through each of the phases of setup', () => { class LifeCycleComponent extends React.Component { constructor(props, context) { super(props, context); @@ -407,30 +404,30 @@ describe('ReactComponentLifeCycle', function() { GET_INIT_STATE_RETURN_VAL ); expect(instance._testJournal.lifeCycleAtStartOfGetInitialState) - .toBe(ComponentLifeCycle.UNMOUNTED); + .toBe('UNMOUNTED'); // componentWillMount expect(instance._testJournal.stateAtStartOfWillMount).toEqual( instance._testJournal.returnedFromGetInitialState ); expect(instance._testJournal.lifeCycleAtStartOfWillMount) - .toBe(ComponentLifeCycle.MOUNTED); + .toBe('MOUNTED'); // componentDidMount expect(instance._testJournal.stateAtStartOfDidMount) .toEqual(DID_MOUNT_STATE); expect(instance._testJournal.lifeCycleAtStartOfDidMount).toBe( - ComponentLifeCycle.MOUNTED + 'MOUNTED' ); // render expect(instance._testJournal.stateInInitialRender) .toEqual(INIT_RENDER_STATE); expect(instance._testJournal.lifeCycleInInitialRender).toBe( - ComponentLifeCycle.MOUNTED + 'MOUNTED' ); - expect(getLifeCycleState(instance)).toBe(ComponentLifeCycle.MOUNTED); + expect(getLifeCycleState(instance)).toBe('MOUNTED'); // Now *update the component* instance.forceUpdate(); @@ -439,10 +436,10 @@ describe('ReactComponentLifeCycle', function() { expect(instance._testJournal.stateInLaterRender) .toEqual(NEXT_RENDER_STATE); expect(instance._testJournal.lifeCycleInLaterRender).toBe( - ComponentLifeCycle.MOUNTED + 'MOUNTED' ); - expect(getLifeCycleState(instance)).toBe(ComponentLifeCycle.MOUNTED); + expect(getLifeCycleState(instance)).toBe('MOUNTED'); ReactDOM.unmountComponentAtNode(container); @@ -450,15 +447,15 @@ describe('ReactComponentLifeCycle', function() { .toEqual(WILL_UNMOUNT_STATE); // componentWillUnmount called right before unmount. expect(instance._testJournal.lifeCycleAtStartOfWillUnmount).toBe( - ComponentLifeCycle.MOUNTED + 'MOUNTED' ); // But the current lifecycle of the component is unmounted. - expect(getLifeCycleState(instance)).toBe(ComponentLifeCycle.UNMOUNTED); + expect(getLifeCycleState(instance)).toBe('UNMOUNTED'); expect(instance.state).toEqual(POST_WILL_UNMOUNT_STATE); }); - it('should not throw when updating an auxiliary component', function() { + it('should not throw when updating an auxiliary component', () => { class Tooltip extends React.Component { render() { return
{this.props.children}
; @@ -506,7 +503,7 @@ describe('ReactComponentLifeCycle', function() { ); }); - it('should allow state updates in componentDidMount', function() { + it('should allow state updates in componentDidMount', () => { /** * calls setState in an componentDidMount. */ @@ -533,7 +530,7 @@ describe('ReactComponentLifeCycle', function() { expect(instance.state.stateField).toBe('goodbye'); }); - it('should call nested lifecycle methods in the right order', function() { + it('should call nested lifecycle methods in the right order', () => { var log; var logger = function(msg) { return function() { diff --git a/src/renderers/shared/stack/reconciler/__tests__/ReactCompositeComponent-test.js b/src/renderers/shared/stack/reconciler/__tests__/ReactCompositeComponent-test.js index e0bdb1957a..81777ace56 100644 --- a/src/renderers/shared/stack/reconciler/__tests__/ReactCompositeComponent-test.js +++ b/src/renderers/shared/stack/reconciler/__tests__/ReactCompositeComponent-test.js @@ -23,9 +23,9 @@ var ReactUpdates; var reactComponentExpect; -describe('ReactCompositeComponent', function() { +describe('ReactCompositeComponent', () => { - beforeEach(function() { + beforeEach(() => { jest.resetModuleRegistry(); reactComponentExpect = require('reactComponentExpect'); React = require('React'); @@ -69,7 +69,7 @@ describe('ReactCompositeComponent', function() { }; }); - it('should support module pattern components', function() { + it('should support module pattern components', () => { function Child({test}) { return { render() { @@ -84,7 +84,7 @@ describe('ReactCompositeComponent', function() { expect(el.textContent).toBe('test'); }); - it('should support rendering to different child types over time', function() { + it('should support rendering to different child types over time', () => { var instance = ; instance = ReactTestUtils.renderIntoDocument(instance); @@ -123,7 +123,7 @@ describe('ReactCompositeComponent', function() { ReactDOM.render(, container); }); - it('should react to state changes from callbacks', function() { + it('should react to state changes from callbacks', () => { var instance = ; instance = ReactTestUtils.renderIntoDocument(instance); @@ -137,7 +137,7 @@ describe('ReactCompositeComponent', function() { .toBeDOMComponentWithTag('b'); }); - it('should rewire refs when rendering to different child types', function() { + it('should rewire refs when rendering to different child types', () => { var instance = ; instance = ReactTestUtils.renderIntoDocument(instance); @@ -148,7 +148,7 @@ describe('ReactCompositeComponent', function() { expect(ReactDOM.findDOMNode(instance.refs.x).tagName).toBe('A'); }); - it('should not cache old DOM nodes when switching constructors', function() { + it('should not cache old DOM nodes when switching constructors', () => { var container = document.createElement('div'); var instance = ReactDOM.render( , @@ -169,7 +169,7 @@ describe('ReactCompositeComponent', function() { expect(instance.getAnchor().className).toBe(''); }); - it('should auto bind methods and values correctly', function() { + it('should auto bind methods and values correctly', () => { spyOn(console, 'error'); var ComponentClass = React.createClass({ @@ -215,7 +215,7 @@ describe('ReactCompositeComponent', function() { }); - it('should not pass this to getDefaultProps', function() { + it('should not pass this to getDefaultProps', () => { var Component = React.createClass({ getDefaultProps: function() { expect(this.render).not.toBeDefined(); @@ -228,7 +228,7 @@ describe('ReactCompositeComponent', function() { ReactTestUtils.renderIntoDocument(); }); - it('should use default values for undefined props', function() { + it('should use default values for undefined props', () => { class Component extends React.Component { static defaultProps = {prop: 'testKey'}; @@ -250,7 +250,7 @@ describe('ReactCompositeComponent', function() { reactComponentExpect(instance3).scalarPropsEqual({prop: null}); }); - it('should not mutate passed-in props object', function() { + it('should not mutate passed-in props object', () => { class Component extends React.Component { static defaultProps = {prop: 'testKey'}; @@ -269,7 +269,7 @@ describe('ReactCompositeComponent', function() { expect(inputProps.prop).not.toBeDefined(); }); - it('should warn about `forceUpdate` on unmounted components', function() { + it('should warn about `forceUpdate` on unmounted components', () => { spyOn(console, 'error'); var container = document.createElement('div'); @@ -301,7 +301,7 @@ describe('ReactCompositeComponent', function() { ); }); - it('should warn about `setState` on unmounted components', function() { + it('should warn about `setState` on unmounted components', () => { spyOn(console, 'error'); var container = document.createElement('div'); @@ -345,7 +345,7 @@ describe('ReactCompositeComponent', function() { ); }); - it('should silently allow `setState`, not call cb on unmounting components', function() { + it('should silently allow `setState`, not call cb on unmounting components', () => { var cbCalled = false; var container = document.createElement('div'); document.body.appendChild(container); @@ -374,7 +374,7 @@ describe('ReactCompositeComponent', function() { }); - it('should warn about `setState` in render', function() { + it('should warn about `setState` in render', () => { spyOn(console, 'error'); var container = document.createElement('div'); @@ -422,7 +422,7 @@ describe('ReactCompositeComponent', function() { expect(instance2.state.value).toBe(1); }); - it('should warn about `setState` in getChildContext', function() { + it('should warn about `setState` in getChildContext', () => { spyOn(console, 'error'); var container = document.createElement('div'); @@ -454,7 +454,7 @@ describe('ReactCompositeComponent', function() { ); }); - it('should cleanup even if render() fatals', function() { + it('should cleanup even if render() fatals', () => { class BadComponent extends React.Component { render() { throw new Error(); @@ -472,7 +472,7 @@ describe('ReactCompositeComponent', function() { expect(ReactCurrentOwner.current).toBe(null); }); - it('should call componentWillUnmount before unmounting', function() { + it('should call componentWillUnmount before unmounting', () => { var container = document.createElement('div'); var innerUnmounted = false; @@ -502,7 +502,7 @@ describe('ReactCompositeComponent', function() { expect(innerUnmounted).toBe(true); }); - it('should warn when shouldComponentUpdate() returns undefined', function() { + it('should warn when shouldComponentUpdate() returns undefined', () => { spyOn(console, 'error'); class Component extends React.Component { @@ -527,7 +527,7 @@ describe('ReactCompositeComponent', function() { ); }); - it('should warn when componentDidUnmount method is defined', function() { + it('should warn when componentDidUnmount method is defined', () => { spyOn(console, 'error'); class Component extends React.Component { @@ -549,7 +549,7 @@ describe('ReactCompositeComponent', function() { ); }); - it('should pass context to children when not owner', function() { + it('should pass context to children when not owner', () => { class Parent extends React.Component { render() { return ; @@ -586,7 +586,7 @@ describe('ReactCompositeComponent', function() { expect(ReactDOM.findDOMNode(component).innerHTML).toBe('bar'); }); - it('should skip update when rerendering element in container', function() { + it('should skip update when rerendering element in container', () => { class Parent extends React.Component { render() { return
{this.props.children}
; @@ -610,7 +610,7 @@ describe('ReactCompositeComponent', function() { expect(childRenders).toBe(1); }); - it('should pass context when re-rendered for static child', function() { + it('should pass context when re-rendered for static child', () => { var parentInstance = null; var childInstance = null; @@ -667,7 +667,7 @@ describe('ReactCompositeComponent', function() { reactComponentExpect(childInstance).scalarContextEqual({foo: 'bar', flag: true}); }); - it('should pass context when re-rendered for static child within a composite component', function() { + it('should pass context when re-rendered for static child within a composite component', () => { class Parent extends React.Component { static childContextTypes = { flag: ReactPropTypes.bool, @@ -723,7 +723,7 @@ describe('ReactCompositeComponent', function() { reactComponentExpect(wrapper.refs.child).scalarContextEqual({flag: false}); }); - it('should pass context transitively', function() { + it('should pass context transitively', () => { var childInstance = null; var grandchildInstance = null; @@ -784,7 +784,7 @@ describe('ReactCompositeComponent', function() { reactComponentExpect(grandchildInstance).scalarContextEqual({foo: 'bar', depth: 1}); }); - it('should pass context when re-rendered', function() { + it('should pass context when re-rendered', () => { var parentInstance = null; var childInstance = null; @@ -838,7 +838,7 @@ describe('ReactCompositeComponent', function() { reactComponentExpect(childInstance).scalarContextEqual({foo: 'bar', depth: 0}); }); - it('unmasked context propagates through updates', function() { + it('unmasked context propagates through updates', () => { class Leaf extends React.Component { static contextTypes = { foo: ReactPropTypes.string.isRequired, @@ -909,7 +909,7 @@ describe('ReactCompositeComponent', function() { expect(div.children[0].id).toBe('aliens'); }); - it('should trigger componentWillReceiveProps for context changes', function() { + it('should trigger componentWillReceiveProps for context changes', () => { var contextChanges = 0; var propChanges = 0; @@ -1024,7 +1024,7 @@ describe('ReactCompositeComponent', function() { expect(contextChanges).toBe(3); // ChildWithContext, GrandChild x 2 }); - it('should disallow nested render calls', function() { + it('should disallow nested render calls', () => { spyOn(console, 'error'); class Inner extends React.Component { @@ -1050,7 +1050,7 @@ describe('ReactCompositeComponent', function() { ); }); - it('only renders once if updated in componentWillReceiveProps', function() { + it('only renders once if updated in componentWillReceiveProps', () => { var renders = 0; class Component extends React.Component { @@ -1076,7 +1076,7 @@ describe('ReactCompositeComponent', function() { expect(instance.state.updated).toBe(true); }); - it('should update refs if shouldComponentUpdate gives false', function() { + it('should update refs if shouldComponentUpdate gives false', () => { class Static extends React.Component { shouldComponentUpdate() { return false; @@ -1119,7 +1119,7 @@ describe('ReactCompositeComponent', function() { expect(ReactDOM.findDOMNode(comp.refs.static1).textContent).toBe('A'); }); - it('should allow access to findDOMNode in componentWillUnmount', function() { + it('should allow access to findDOMNode in componentWillUnmount', () => { var a = null; var b = null; @@ -1146,7 +1146,7 @@ describe('ReactCompositeComponent', function() { expect(a).toBe(b); }); - it('context should be passed down from the parent', function() { + it('context should be passed down from the parent', () => { class Parent extends React.Component { static childContextTypes = { foo: ReactPropTypes.string, @@ -1177,7 +1177,7 @@ describe('ReactCompositeComponent', function() { ReactDOM.render(, div); }); - it('should replace state', function() { + it('should replace state', () => { var Moo = React.createClass({ getInitialState: function() { return {x: 1}; @@ -1193,7 +1193,7 @@ describe('ReactCompositeComponent', function() { expect(moo.state.y).toBe(2); }); - it('should support objects with prototypes as state', function() { + it('should support objects with prototypes as state', () => { var NotActuallyImmutable = function(str) { this.str = str; }; @@ -1242,7 +1242,7 @@ describe('ReactCompositeComponent', function() { expect(moo.state.amIImmutable).toBe(undefined); }); - it('should not warn about unmounting during unmounting', function() { + it('should not warn about unmounting during unmounting', () => { var container = document.createElement('div'); var layer = document.createElement('div'); @@ -1270,7 +1270,7 @@ describe('ReactCompositeComponent', function() { ReactDOM.render(, container); }); - it('should warn when mutated props are passed', function() { + it('should warn when mutated props are passed', () => { spyOn(console, 'error'); var container = document.createElement('div'); @@ -1298,7 +1298,7 @@ describe('ReactCompositeComponent', function() { }); - it('should only call componentWillUnmount once', function() { + it('should only call componentWillUnmount once', () => { var app; var count = 0; diff --git a/src/renderers/shared/stack/reconciler/__tests__/ReactCompositeComponentDOMMinimalism-test.js b/src/renderers/shared/stack/reconciler/__tests__/ReactCompositeComponentDOMMinimalism-test.js index 90726f808d..6e479e7005 100644 --- a/src/renderers/shared/stack/reconciler/__tests__/ReactCompositeComponentDOMMinimalism-test.js +++ b/src/renderers/shared/stack/reconciler/__tests__/ReactCompositeComponentDOMMinimalism-test.js @@ -27,9 +27,9 @@ var expectSingleChildlessDiv; * abstraction, `ReactCompositeComponent` does not ever add superfluous DOM * nodes. */ -describe('ReactCompositeComponentDOMMinimalism', function() { +describe('ReactCompositeComponentDOMMinimalism', () => { - beforeEach(function() { + beforeEach(() => { reactComponentExpect = require('reactComponentExpect'); React = require('React'); ReactTestUtils = require('ReactTestUtils'); @@ -64,7 +64,7 @@ describe('ReactCompositeComponentDOMMinimalism', function() { }; }); - it('should not render extra nodes for non-interpolated text', function() { + it('should not render extra nodes for non-interpolated text', () => { var instance = ( A string child @@ -74,7 +74,7 @@ describe('ReactCompositeComponentDOMMinimalism', function() { expectSingleChildlessDiv(instance); }); - it('should not render extra nodes for non-interpolated text', function() { + it('should not render extra nodes for non-interpolated text', () => { var instance = ( {'Interpolated String Child'} @@ -84,7 +84,7 @@ describe('ReactCompositeComponentDOMMinimalism', function() { expectSingleChildlessDiv(instance); }); - it('should not render extra nodes for non-interpolated text', function() { + it('should not render extra nodes for non-interpolated text', () => { var instance = (