From bed4c0595c611ce8c088b526e77a23330c253b8b Mon Sep 17 00:00:00 2001 From: Cheng Lou Date: Tue, 26 Jul 2016 16:26:51 -0700 Subject: [PATCH 001/101] PropTypes: distinguish nullable from optional object field (#7291) * PropTypes: distinguish nullable from optional object field This gives a more precise message (no type semantics change) to the case of passing a field in an object, but whose value is `null`: Before: ```js propTypes: { foo: React.PropTypes.number.isRequired } ``` Would scream "Required prop `foo` was not specified in `MyComp`". Now it'll be "Required prop `foo` was specified in `MyComp`, but its value is `null`.". Works as expected in nested objects. This fixes the issue of a component transitively passing a `null`, specifying the correct field to the child but have the child tell it that it didn't provide the prop. Optional field and nullable are two different things anyway. * Add missing test case. * Reword messages. (cherry picked from commit 0292d3404787b08b19267a3c951170a0dabd0e98) --- .../link/__tests__/ReactLinkPropTypes-test.js | 22 +-- .../__tests__/ReactContextValidator-test.js | 6 +- .../__tests__/ReactElementValidator-test.js | 11 +- .../classic/types/ReactPropTypes.js | 10 +- .../types/__tests__/ReactPropTypes-test.js | 130 ++++++++---------- .../ReactJSXElementValidator-test.js | 11 +- src/test/__tests__/ReactTestUtils-test.js | 4 +- 7 files changed, 98 insertions(+), 96 deletions(-) diff --git a/src/addons/link/__tests__/ReactLinkPropTypes-test.js b/src/addons/link/__tests__/ReactLinkPropTypes-test.js index 7171c7f553..560b94e0c6 100644 --- a/src/addons/link/__tests__/ReactLinkPropTypes-test.js +++ b/src/addons/link/__tests__/ReactLinkPropTypes-test.js @@ -18,8 +18,8 @@ var ReactPropTypeLocations = require('ReactPropTypeLocations'); var ReactPropTypesSecret = require('ReactPropTypesSecret'); var invalidMessage = 'Invalid prop `testProp` supplied to `testComponent`.'; -var requiredMessage = - 'Required prop `testProp` was not specified in `testComponent`.'; +var requiredMessage = 'The prop `testProp` is marked as required in ' + + '`testComponent`, but its value is `undefined`.'; function typeCheckFail(declaration, value, message) { var props = {testProp: value}; @@ -53,22 +53,26 @@ describe('ReactLink', function() { typeCheckFail( LinkPropTypes.link(React.PropTypes.any), {}, - 'Required prop `testProp.value` was not specified in `testComponent`.' + 'The prop `testProp.value` is marked as required in `testComponent`, ' + + 'but its value is `undefined`.' ); typeCheckFail( LinkPropTypes.link(React.PropTypes.any), {value: 123}, - 'Required prop `testProp.requestChange` was not specified in `testComponent`.' + 'The prop `testProp.requestChange` is marked as required in ' + + '`testComponent`, but its value is `undefined`.' ); typeCheckFail( LinkPropTypes.link(React.PropTypes.any), {requestChange: emptyFunction}, - 'Required prop `testProp.value` was not specified in `testComponent`.' + 'The prop `testProp.value` is marked as required in `testComponent`, ' + + 'but its value is `undefined`.' ); typeCheckFail( LinkPropTypes.link(React.PropTypes.any), {value: null, requestChange: null}, - 'Required prop `testProp.value` was not specified in `testComponent`.' + 'The prop `testProp.value` is marked as required in `testComponent`, ' + + 'but its value is `null`.' ); }); @@ -122,12 +126,14 @@ describe('ReactLink', function() { }); it('should warn for missing required values', function() { - typeCheckFail(LinkPropTypes.link().isRequired, null, requiredMessage); + var specifiedButIsNullMsg = 'The prop `testProp` is marked as required ' + + 'in `testComponent`, but its value is `null`.'; + typeCheckFail(LinkPropTypes.link().isRequired, null, specifiedButIsNullMsg); typeCheckFail(LinkPropTypes.link().isRequired, undefined, requiredMessage); typeCheckFail( LinkPropTypes.link(React.PropTypes.string).isRequired, null, - requiredMessage + specifiedButIsNullMsg ); typeCheckFail( LinkPropTypes.link(React.PropTypes.string).isRequired, diff --git a/src/isomorphic/classic/__tests__/ReactContextValidator-test.js b/src/isomorphic/classic/__tests__/ReactContextValidator-test.js index 37e77d7de8..10b0c22e35 100644 --- a/src/isomorphic/classic/__tests__/ReactContextValidator-test.js +++ b/src/isomorphic/classic/__tests__/ReactContextValidator-test.js @@ -152,7 +152,8 @@ describe('ReactContextValidator', function() { expect(console.error.calls.count()).toBe(1); expect(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe( 'Warning: Failed context type: ' + - 'Required context `foo` was not specified in `Component`.\n' + + 'The context `foo` is marked as required in `Component`, but its value ' + + 'is `undefined`.\n' + ' in Component (at **)' ); @@ -229,7 +230,8 @@ describe('ReactContextValidator', function() { expect(console.error.calls.count()).toBe(1); expect(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe( 'Warning: Failed childContext type: ' + - 'Required child context `foo` was not specified in `Component`.\n' + + 'The child context `foo` is marked as required in `Component`, but its ' + + 'value is `undefined`.\n' + ' in Component (at **)' ); diff --git a/src/isomorphic/classic/element/__tests__/ReactElementValidator-test.js b/src/isomorphic/classic/element/__tests__/ReactElementValidator-test.js index fe7acf3e60..d646e1ae98 100644 --- a/src/isomorphic/classic/element/__tests__/ReactElementValidator-test.js +++ b/src/isomorphic/classic/element/__tests__/ReactElementValidator-test.js @@ -360,8 +360,8 @@ describe('ReactElementValidator', function() { expect(console.error.calls.count()).toBe(1); expect(console.error.calls.argsFor(0)[0]).toBe( - 'Warning: Failed prop type: ' + - 'Required prop `prop` was not specified in `Component`.\n' + + 'Warning: Failed prop type: The prop `prop` is marked as required in ' + + '`Component`, but its value is `null`.\n' + ' in Component' ); }); @@ -385,8 +385,8 @@ describe('ReactElementValidator', function() { expect(console.error.calls.count()).toBe(1); expect(console.error.calls.argsFor(0)[0]).toBe( - 'Warning: Failed prop type: ' + - 'Required prop `prop` was not specified in `Component`.\n' + + 'Warning: Failed prop type: The prop `prop` is marked as required in ' + + '`Component`, but its value is `null`.\n' + ' in Component' ); }); @@ -413,7 +413,8 @@ describe('ReactElementValidator', function() { expect(console.error.calls.count()).toBe(2); expect(console.error.calls.argsFor(0)[0]).toBe( 'Warning: Failed prop type: ' + - 'Required prop `prop` was not specified in `Component`.\n' + + 'The prop `prop` is marked as required in `Component`, but its value ' + + 'is `undefined`.\n' + ' in Component' ); diff --git a/src/isomorphic/classic/types/ReactPropTypes.js b/src/isomorphic/classic/types/ReactPropTypes.js index 014a9b3753..7b026a7b05 100644 --- a/src/isomorphic/classic/types/ReactPropTypes.js +++ b/src/isomorphic/classic/types/ReactPropTypes.js @@ -158,9 +158,15 @@ function createChainableTypeChecker(validate) { if (props[propName] == null) { var locationName = ReactPropTypeLocationNames[location]; if (isRequired) { + if (props[propName] === null) { + return new PropTypeError( + `The ${locationName} \`${propFullName}\` is marked as required ` + + `in \`${componentName}\`, but its value is \`null\`.` + ); + } return new PropTypeError( - `Required ${locationName} \`${propFullName}\` was not specified in ` + - `\`${componentName}\`.` + `The ${locationName} \`${propFullName}\` is marked as required in ` + + `\`${componentName}\`, but its value is \`undefined\`.` ); } return null; diff --git a/src/isomorphic/classic/types/__tests__/ReactPropTypes-test.js b/src/isomorphic/classic/types/__tests__/ReactPropTypes-test.js index 5183aabe52..20b4f486b1 100644 --- a/src/isomorphic/classic/types/__tests__/ReactPropTypes-test.js +++ b/src/isomorphic/classic/types/__tests__/ReactPropTypes-test.js @@ -20,8 +20,6 @@ var ReactPropTypesSecret; var Component; var MyComponent; -var requiredMessage = - 'Required prop `testProp` was not specified in `testComponent`.'; function typeCheckFail(declaration, value, message) { var props = {testProp: value}; @@ -37,6 +35,46 @@ function typeCheckFail(declaration, value, message) { expect(error.message).toBe(message); } +function typeCheckFailRequiredValues(declaration) { + var specifiedButIsNullMsg = 'The prop `testProp` is marked as required in ' + + '`testComponent`, but its value is `null`.'; + var unspecifiedMsg = 'The prop `testProp` is marked as required in ' + + '`testComponent`, but its value is \`undefined\`.'; + var props1 = {testProp: null}; + var error1 = declaration( + props1, + 'testProp', + 'testComponent', + ReactPropTypeLocations.prop, + null, + ReactPropTypesSecret + ); + expect(error1 instanceof Error).toBe(true); + expect(error1.message).toBe(specifiedButIsNullMsg); + var props2 = {testProp: undefined}; + var error2 = declaration( + props2, + 'testProp', + 'testComponent', + ReactPropTypeLocations.prop, + null, + ReactPropTypesSecret + ); + expect(error2 instanceof Error).toBe(true); + expect(error2.message).toBe(unspecifiedMsg); + var props3 = {}; + var error3 = declaration( + props3, + 'testProp', + 'testComponent', + ReactPropTypeLocations.prop, + null, + ReactPropTypesSecret + ); + expect(error3 instanceof Error).toBe(true); + expect(error3.message).toBe(unspecifiedMsg); +} + function typeCheckPass(declaration, value) { var props = {testProp: value}; var error = declaration( @@ -146,8 +184,7 @@ describe('ReactPropTypes', function() { }); it('should warn for missing required values', function() { - typeCheckFail(PropTypes.string.isRequired, null, requiredMessage); - typeCheckFail(PropTypes.string.isRequired, undefined, requiredMessage); + typeCheckFailRequiredValues(PropTypes.string.isRequired); }); it('should warn if called manually in development', function() { @@ -211,8 +248,7 @@ describe('ReactPropTypes', function() { }); it('should warn for missing required values', function() { - typeCheckFail(PropTypes.any.isRequired, null, requiredMessage); - typeCheckFail(PropTypes.any.isRequired, undefined, requiredMessage); + typeCheckFailRequiredValues(PropTypes.any.isRequired); }); it('should warn if called manually in development', function() { @@ -304,15 +340,8 @@ describe('ReactPropTypes', function() { }); it('should warn for missing required values', function() { - typeCheckFail( - PropTypes.arrayOf(PropTypes.number).isRequired, - null, - requiredMessage - ); - typeCheckFail( - PropTypes.arrayOf(PropTypes.number).isRequired, - undefined, - requiredMessage + typeCheckFailRequiredValues( + PropTypes.arrayOf(PropTypes.number).isRequired ); }); @@ -403,8 +432,7 @@ describe('ReactPropTypes', function() { }); it('should warn for missing required values', function() { - typeCheckFail(PropTypes.element.isRequired, null, requiredMessage); - typeCheckFail(PropTypes.element.isRequired, undefined, requiredMessage); + typeCheckFailRequiredValues(PropTypes.element.isRequired); }); it('should warn if called manually in development', function() { @@ -490,12 +518,7 @@ describe('ReactPropTypes', function() { }); it('should warn for missing required values', function() { - typeCheckFail( - PropTypes.instanceOf(String).isRequired, null, requiredMessage - ); - typeCheckFail( - PropTypes.instanceOf(String).isRequired, undefined, requiredMessage - ); + typeCheckFailRequiredValues(PropTypes.instanceOf(String).isRequired); }); it('should warn if called manually in development', function() { @@ -598,16 +621,7 @@ describe('ReactPropTypes', function() { }); it('should warn for missing required values', function() { - typeCheckFail( - PropTypes.node.isRequired, - null, - 'Required prop `testProp` was not specified in `testComponent`.' - ); - typeCheckFail( - PropTypes.node.isRequired, - undefined, - 'Required prop `testProp` was not specified in `testComponent`.' - ); + typeCheckFailRequiredValues(PropTypes.node.isRequired); }); it('should accept empty array for required props', function() { @@ -721,15 +735,8 @@ describe('ReactPropTypes', function() { }); it('should warn for missing required values', function() { - typeCheckFail( - PropTypes.objectOf(PropTypes.number).isRequired, - null, - requiredMessage - ); - typeCheckFail( - PropTypes.objectOf(PropTypes.number).isRequired, - undefined, - requiredMessage + typeCheckFailRequiredValues( + PropTypes.objectOf(PropTypes.number).isRequired ); }); @@ -801,16 +808,7 @@ describe('ReactPropTypes', function() { }); it('should warn for missing required values', function() { - typeCheckFail( - PropTypes.oneOf(['red', 'blue']).isRequired, - null, - requiredMessage - ); - typeCheckFail( - PropTypes.oneOf(['red', 'blue']).isRequired, - undefined, - requiredMessage - ); + typeCheckFailRequiredValues(PropTypes.oneOf(['red', 'blue']).isRequired); }); it('should warn if called manually in development', function() { @@ -879,15 +877,8 @@ describe('ReactPropTypes', function() { }); it('should warn for missing required values', function() { - typeCheckFail( - PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired, - null, - requiredMessage - ); - typeCheckFail( - PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired, - undefined, - requiredMessage + typeCheckFailRequiredValues( + PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired ); }); @@ -947,7 +938,8 @@ describe('ReactPropTypes', function() { typeCheckFail( PropTypes.shape({key: PropTypes.number.isRequired}), {}, - 'Required prop `testProp.key` was not specified in `testComponent`.' + 'The prop `testProp.key` is marked as required in `testComponent`, ' + + 'but its value is `undefined`.' ); }); @@ -958,7 +950,8 @@ describe('ReactPropTypes', function() { secondKey: PropTypes.number.isRequired, }), {}, - 'Required prop `testProp.key` was not specified in `testComponent`.' + 'The prop `testProp.key` is marked as required in `testComponent`, ' + + 'but its value is `undefined`.' ); }); @@ -980,15 +973,8 @@ describe('ReactPropTypes', function() { }); it('should warn for missing required values', function() { - typeCheckFail( - PropTypes.shape({key: PropTypes.number}).isRequired, - null, - requiredMessage - ); - typeCheckFail( - PropTypes.shape({key: PropTypes.number}).isRequired, - undefined, - requiredMessage + typeCheckFailRequiredValues( + PropTypes.shape({key: PropTypes.number}).isRequired ); }); diff --git a/src/isomorphic/modern/element/__tests__/ReactJSXElementValidator-test.js b/src/isomorphic/modern/element/__tests__/ReactJSXElementValidator-test.js index 827ab73ee5..4f5417e084 100644 --- a/src/isomorphic/modern/element/__tests__/ReactJSXElementValidator-test.js +++ b/src/isomorphic/modern/element/__tests__/ReactJSXElementValidator-test.js @@ -249,8 +249,8 @@ describe('ReactJSXElementValidator', function() { expect( console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)') ).toBe( - 'Warning: Failed prop type: ' + - 'Required prop `prop` was not specified in `RequiredPropComponent`.\n' + + 'Warning: Failed prop type: The prop `prop` is marked as required in ' + + '`RequiredPropComponent`, but its value is `null`.\n' + ' in RequiredPropComponent (at **)' ); }); @@ -264,8 +264,8 @@ describe('ReactJSXElementValidator', function() { expect( console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)') ).toBe( - 'Warning: Failed prop type: ' + - 'Required prop `prop` was not specified in `RequiredPropComponent`.\n' + + 'Warning: Failed prop type: The prop `prop` is marked as required in ' + + '`RequiredPropComponent`, but its value is `null`.\n' + ' in RequiredPropComponent (at **)' ); }); @@ -281,7 +281,8 @@ describe('ReactJSXElementValidator', function() { console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)') ).toBe( 'Warning: Failed prop type: ' + - 'Required prop `prop` was not specified in `RequiredPropComponent`.\n' + + 'The prop `prop` is marked as required in `RequiredPropComponent`, but ' + + 'its value is `undefined`.\n' + ' in RequiredPropComponent (at **)' ); diff --git a/src/test/__tests__/ReactTestUtils-test.js b/src/test/__tests__/ReactTestUtils-test.js index 9ce01f665b..b4fb9d9b98 100644 --- a/src/test/__tests__/ReactTestUtils-test.js +++ b/src/test/__tests__/ReactTestUtils-test.js @@ -296,8 +296,8 @@ describe('ReactTestUtils', function() { expect( console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)') ).toBe( - 'Warning: Failed context type: Required context `name` was not ' + - 'specified in `SimpleComponent`.\n' + + 'Warning: Failed context type: The context `name` is marked as ' + + 'required in `SimpleComponent`, but its value is `undefined`.\n' + ' in SimpleComponent (at **)' ); }); From 5a540f778a0cafbd9d9c610af8c6814e00e9e53c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Markb=C3=A5ge?= Date: Fri, 5 Aug 2016 14:40:27 -0700 Subject: [PATCH 002/101] Merge pull request #7248 from sebmarkbage/fibercleanup [Fiber] Various minor tweaks and a few big ones (cherry picked from commit a8c81912646378ac6c0a1966b3f3f7cd5fcb6726) --- src/renderers/dom/fiber/ReactDOMFiber.js | 12 +- src/renderers/noop/ReactNoop.js | 25 +- src/renderers/shared/fiber/ReactChildFiber.js | 298 ++++++++++-------- src/renderers/shared/fiber/ReactFiber.js | 23 +- .../shared/fiber/ReactFiberBeginWork.js | 254 ++++++++++----- .../shared/fiber/ReactFiberCommitWork.js | 2 +- .../shared/fiber/ReactFiberCompleteWork.js | 25 +- .../shared/fiber/ReactFiberPendingWork.js | 47 ++- .../shared/fiber/ReactFiberReconciler.js | 6 +- .../shared/fiber/ReactFiberScheduler.js | 33 +- .../shared/fiber/ReactReifiedYield.js | 4 +- .../fiber/__tests__/ReactCoroutine-test.js | 1 - .../fiber/__tests__/ReactIncremental-test.js | 179 +++++++++-- .../ReactIncrementalSideEffects-test.js | 196 +++++++++++- 14 files changed, 806 insertions(+), 299 deletions(-) diff --git a/src/renderers/dom/fiber/ReactDOMFiber.js b/src/renderers/dom/fiber/ReactDOMFiber.js index 7be5e5cc87..175b274549 100644 --- a/src/renderers/dom/fiber/ReactDOMFiber.js +++ b/src/renderers/dom/fiber/ReactDOMFiber.js @@ -16,7 +16,7 @@ import type { HostChildren } from 'ReactFiberReconciler'; var ReactFiberReconciler = require('ReactFiberReconciler'); -type DOMContainerElement = Element & { _reactRootContainer: Object }; +type DOMContainerElement = Element & { _reactRootContainer: ?Object }; type Container = Element; type Props = { }; @@ -92,6 +92,16 @@ var ReactDOM = { } }, + unmountComponentAtNode(container : DOMContainerElement) { + const root = container._reactRootContainer; + if (root) { + // TODO: Is it safe to reset this now or should I wait since this + // unmount could be deferred? + container._reactRootContainer = null; + DOMRenderer.unmountContainer(root); + } + }, + }; module.exports = ReactDOM; diff --git a/src/renderers/noop/ReactNoop.js b/src/renderers/noop/ReactNoop.js index 8404cf159b..82e64b5357 100644 --- a/src/renderers/noop/ReactNoop.js +++ b/src/renderers/noop/ReactNoop.js @@ -30,8 +30,8 @@ var scheduledLowPriCallback = 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 +58,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,17 +76,15 @@ 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) { @@ -170,9 +167,21 @@ var ReactNoop = { function logFiber(fiber : Fiber, depth) { console.log( - ' '.repeat(depth) + '- ' + (fiber.type ? fiber.type.name || fiber.type : '[root]'), + ' '.repeat(depth) + '- ' + (fiber.type ? fiber.type.name || fiber.type : '[root]'), '[' + fiber.pendingWorkPriority + (fiber.pendingProps ? '*' : '') + ']' ); + const childInProgress = fiber.childInProgress; + if (childInProgress) { + if (childInProgress === fiber.child) { + console.log(' '.repeat(depth + 1) + 'ERROR: IN PROGRESS == CURRENT'); + } else { + console.log(' '.repeat(depth + 1) + 'IN PROGRESS'); + logFiber(childInProgress, depth + 1); + if (fiber.child) { + console.log(' '.repeat(depth + 1) + 'CURRENT'); + } + } + } if (fiber.child) { logFiber(fiber.child, depth + 1); } diff --git a/src/renderers/shared/fiber/ReactChildFiber.js b/src/renderers/shared/fiber/ReactChildFiber.js index ddf4725a02..c3621c30ad 100644 --- a/src/renderers/shared/fiber/ReactChildFiber.js +++ b/src/renderers/shared/fiber/ReactChildFiber.js @@ -29,151 +29,181 @@ 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) { + clone.pendingWorkPriority = priority; + } + clone.pendingProps = element.props; + clone.child = existingChild.child; + 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: { + 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) { + clone.pendingWorkPriority = priority; + } + clone.pendingProps = element.props; + clone.child = existingChild.child; + clone.sibling = null; + clone.return = returnFiber; + return clone; + } + const child = createFiberFromElement(element, priority); + child.return = returnFiber; + return child; + } + + case REACT_COROUTINE_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. + 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; + 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); diff --git a/src/renderers/shared/fiber/ReactFiber.js b/src/renderers/shared/fiber/ReactFiber.js index 39683f001e..2bcfe3f496 100644 --- a/src/renderers/shared/fiber/ReactFiber.js +++ b/src/renderers/shared/fiber/ReactFiber.js @@ -100,12 +100,9 @@ export type Fiber = Instance & { // 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, + // Keeps track of the children that are currently being processed but have not + // yet completed. + childInProgress: ?Fiber, // Conceptual aliases // workInProgress : Fiber -> alternate The alternate used for reuse happens @@ -145,7 +142,7 @@ var createFiber = function(tag : TypeOfWork, key : null | string) : Fiber { pendingWorkPriority: NoWork, - hasWorkInProgress: false, + childInProgress: null, alternate: null, @@ -167,6 +164,7 @@ exports.cloneFiber = function(fiber : Fiber, priorityLevel : PriorityLevel) : Fi if (alt) { alt.stateNode = fiber.stateNode; alt.child = fiber.child; + alt.childInProgress = fiber.childInProgress; alt.sibling = fiber.sibling; alt.ref = alt.ref; alt.pendingProps = fiber.pendingProps; @@ -186,8 +184,11 @@ exports.cloneFiber = function(fiber : Fiber, priorityLevel : PriorityLevel) : Fi alt.type = fiber.type; alt.stateNode = fiber.stateNode; alt.child = fiber.child; + alt.childInProgress = fiber.childInProgress; alt.sibling = fiber.sibling; alt.ref = alt.ref; + // pendingProps is here for symmetry but is unnecessary in practice for now. + alt.pendingProps = fiber.pendingProps; alt.pendingWorkPriority = priorityLevel; alt.alternate = fiber; @@ -201,13 +202,13 @@ exports.createHostContainerFiber = function() { }; exports.createFiberFromElement = function(element : ReactElement, priorityLevel : PriorityLevel) { - const fiber = exports.createFiberFromElementType(element.type, element.key); + 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 +225,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..6c664784f0 100644 --- a/src/renderers/shared/fiber/ReactFiberBeginWork.js +++ b/src/renderers/shared/fiber/ReactFiberBeginWork.js @@ -16,7 +16,10 @@ import type { ReactCoroutine } from 'ReactCoroutine'; import type { Fiber } from 'ReactFiber'; import type { HostConfig } from 'ReactFiberReconciler'; -var ReactChildFiber = require('ReactChildFiber'); +var { + reconcileChildFibers, + reconcileChildFibersInPlace, +} = require('ReactChildFiber'); var ReactTypeOfWork = require('ReactTypeOfWork'); var { IndeterminateComponent, @@ -38,29 +41,76 @@ module.exports = function(config : HostConfig) { function reconcileChildren(current, workInProgress, nextChildren) { const priority = workInProgress.pendingWorkPriority; - workInProgress.child = ReactChildFiber.reconcileChildFibers( - workInProgress, - current ? current.child : null, - nextChildren, - priority - ); + reconcileChildrenAtPriority(current, workInProgress, nextChildren, priority); + } + + function reconcileChildrenAtPriority(current, workInProgress, nextChildren, priorityLevel) { + if (current && current.childInProgress) { + workInProgress.childInProgress = reconcileChildFibersInPlace( + workInProgress, + current.childInProgress, + nextChildren, + priorityLevel + ); + // This is now invalid because we reused nodes. + current.childInProgress = null; + } else if (workInProgress.childInProgress) { + workInProgress.childInProgress = reconcileChildFibersInPlace( + workInProgress, + workInProgress.childInProgress, + nextChildren, + priorityLevel + ); + } else { + workInProgress.childInProgress = reconcileChildFibers( + workInProgress, + current ? current.child : null, + nextChildren, + priorityLevel + ); + } } function updateFunctionalComponent(current, workInProgress) { var fn = workInProgress.type; var props = workInProgress.pendingProps; - console.log('update fn:', fn.name); var nextChildren = fn(props); reconcileChildren(current, workInProgress, nextChildren); workInProgress.pendingWorkPriority = NoWork; } - function updateHostComponent(current, workInProgress) { - console.log( - 'host component', workInProgress.type, - typeof workInProgress.pendingProps.children === 'string' ? workInProgress.pendingProps.children : '' - ); + function updateClassComponent(current : ?Fiber, workInProgress : Fiber) { + var props = workInProgress.pendingProps; + var instance = workInProgress.stateNode; + if (!instance) { + var ctor = workInProgress.type; + workInProgress.stateNode = instance = new ctor(props); + } else if (typeof instance.shouldComponentUpdate === 'function') { + if (current && current.memoizedProps) { + // Revert to the last flushed props, incase we aborted an update. + instance.props = current.memoizedProps; + if (!instance.shouldComponentUpdate(props)) { + return bailoutOnCurrent(current, workInProgress); + } + } + if (!workInProgress.childInProgress && workInProgress.memoizedProps) { + // 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; + if (!instance.shouldComponentUpdate(props)) { + return bailoutOnAlreadyFinishedWork(current, workInProgress); + } + } + } + instance.props = props; + var nextChildren = instance.render(); + reconcileChildren(current, workInProgress, nextChildren); + workInProgress.pendingWorkPriority = NoWork; + return workInProgress.childInProgress; + } + function updateHostComponent(current, workInProgress) { var nextChildren = workInProgress.pendingProps.children; let priority = workInProgress.pendingWorkPriority; @@ -68,23 +118,19 @@ module.exports = function(config : HostConfig) { // 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 - ); + // If we have a child in progress already, we reconcile against that set + // to retain any work within it. We'll recreate any component that was in + // the current set and next set but not in the previous in progress set. + // TODO: This attaches a node that hasn't completed rendering so it + // becomes part of the render tree, even though it never completed. Its + // `output` property is unpredictable because of it. + reconcileChildrenAtPriority(current, workInProgress, nextChildren, OffscreenPriority); workInProgress.pendingWorkPriority = OffscreenPriority; return null; } else { - workInProgress.child = ReactChildFiber.reconcileChildFibers( - workInProgress, - current ? current.child : null, - nextChildren, - priority - ); + reconcileChildren(current, workInProgress, nextChildren); workInProgress.pendingWorkPriority = NoWork; - return workInProgress.child; + return workInProgress.childInProgress; } } @@ -93,14 +139,13 @@ 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; } + 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) { @@ -116,7 +161,6 @@ 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; } @@ -141,75 +185,125 @@ module.exports = function(config : HostConfig) { } while (child = child.sibling); } + function reuseChildrenEffects(returnFiber : Fiber, firstChild : Fiber) { + let child = firstChild; + do { + // 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 bailoutOnCurrent(current : Fiber, workInProgress : Fiber) : ?Fiber { + // 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; + workInProgress.output = current.output; + const priorityLevel = workInProgress.pendingWorkPriority; + workInProgress.pendingProps = null; + workInProgress.pendingWorkPriority = NoWork; + workInProgress.stateNode = current.stateNode; + workInProgress.childInProgress = current.childInProgress; + 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 !== NoWork && 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(current, priorityLevel); + } else { + return null; + } + } else { + workInProgress.child = null; + return null; + } + } + + function bailoutOnAlreadyFinishedWork(current, workInProgress : Fiber) : ?Fiber { + // 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. + const priorityLevel = workInProgress.pendingWorkPriority; + workInProgress.pendingProps = null; + workInProgress.pendingWorkPriority = NoWork; + + workInProgress.firstEffect = null; + workInProgress.nextEffect = null; + workInProgress.lastEffect = null; + + if (workInProgress.child) { + // On the way up here, we reset the child node to be the current one by + // cloning. However, it is really the original child that represents the + // already completed work. Therefore we have to reuse the alternate. + // But if we don't have a current, this was not cloned. This is super weird. + const child = !current ? workInProgress.child : workInProgress.child.alternate; + if (!child) { + throw new Error('We must have a current child to be able to use this.'); + } + workInProgress.child = child; + // Ensure that the effects of reused work are preserved. + reuseChildrenEffects(workInProgress, 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. + reuseChildren(workInProgress, child); + if (workInProgress.pendingWorkPriority !== NoWork && + 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, priorityLevel); + } + } + return null; + } + 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; - 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 bailoutOnCurrent(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.childInProgress && + workInProgress.pendingProps === workInProgress.memoizedProps) { + return bailoutOnAlreadyFinishedWork(current, workInProgress); } - workInProgress.hasWorkInProgress = true; - switch (workInProgress.tag) { case IndeterminateComponent: mountIndeterminateComponent(current, workInProgress); - return workInProgress.child; + return workInProgress.childInProgress; case FunctionalComponent: updateFunctionalComponent(current, workInProgress); - return workInProgress.child; + return workInProgress.childInProgress; 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) { + if (workInProgress.childInProgress) { return beginWork( - workInProgress.child.alternate, - workInProgress.child + workInProgress.childInProgress.alternate, + workInProgress.childInProgress ); } return null; @@ -223,13 +317,13 @@ module.exports = function(config : HostConfig) { updateCoroutineComponent(current, workInProgress); // This doesn't take arbitrary time so we could synchronously just begin // eagerly do the work of workInProgress.child as an optimization. - if (workInProgress.child) { + if (workInProgress.childInProgress) { return beginWork( - workInProgress.child.alternate, - workInProgress.child + workInProgress.childInProgress.alternate, + workInProgress.childInProgress ); } - return workInProgress.child; + return workInProgress.childInProgress; case YieldComponent: // A yield component is just a placeholder, we can just run through the // next one immediately. diff --git a/src/renderers/shared/fiber/ReactFiberCommitWork.js b/src/renderers/shared/fiber/ReactFiberCommitWork.js index 7792be2102..c7a9f2f710 100644 --- a/src/renderers/shared/fiber/ReactFiberCommitWork.js +++ b/src/renderers/shared/fiber/ReactFiberCommitWork.js @@ -47,7 +47,7 @@ module.exports = function(config : HostConfig) { 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; diff --git a/src/renderers/shared/fiber/ReactFiberCompleteWork.js b/src/renderers/shared/fiber/ReactFiberCompleteWork.js index 9900a5b9fb..53421116b4 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, @@ -47,6 +47,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) { @@ -113,7 +116,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,11 +128,9 @@ 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); return null; case HostContainer: @@ -142,15 +143,20 @@ 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. @@ -158,14 +164,17 @@ module.exports = function(config : HostConfig) { } workInProgress.output = instance; } else { + if (!newProps) { + throw new Error('We must have new props for new mounts.'); + } 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 index 15d1a10134..eb61c4595f 100644 --- a/src/renderers/shared/fiber/ReactFiberPendingWork.js +++ b/src/renderers/shared/fiber/ReactFiberPendingWork.js @@ -15,16 +15,17 @@ import type { Fiber } from 'ReactFiber'; import type { PriorityLevel } from 'ReactPriorityLevel'; -var ReactFiber = require('ReactFiber'); +var { cloneFiber } = require('ReactFiber'); var { NoWork, } = require('ReactPriorityLevel'); function cloneSiblings(current : Fiber, workInProgress : Fiber, returnFiber : Fiber) { + workInProgress.return = returnFiber; while (current.sibling) { current = current.sibling; - workInProgress = workInProgress.sibling = ReactFiber.cloneFiber( + workInProgress = workInProgress.sibling = cloneFiber( current, current.pendingWorkPriority ); @@ -49,23 +50,48 @@ exports.findNextUnitOfWorkAtPriority = function(currentRoot : Fiber, priorityLev 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. + if (current.childInProgress) { + let workInProgress = current.childInProgress; + while (workInProgress) { + workInProgress.return = current.alternate; + workInProgress = workInProgress.sibling; + } + workInProgress = current.childInProgress; + while (workInProgress) { + // Don't bother drilling further down this tree if there is no child. + if (workInProgress.pendingWorkPriority !== NoWork && + workInProgress.pendingWorkPriority <= priorityLevel && + workInProgress.pendingProps !== null) { + return workInProgress; + } + workInProgress = workInProgress.sibling; + } + } else if (current.child) { let currentChild = current.child; + currentChild.return = current; + // Ensure we have a work in progress copy to backtrack through. 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; + // 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. + workInProgress.child = cloneFiber( + currentChild, + currentChild.pendingWorkPriority + ); cloneSiblings(currentChild, workInProgress.child, workInProgress); - current = current.child; + current = currentChild; continue; } // If we match the priority but has no child and no work to do, @@ -73,6 +99,12 @@ exports.findNextUnitOfWorkAtPriority = function(currentRoot : Fiber, priorityLev current.pendingWorkPriority = NoWork; } if (current === currentRoot) { + 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; + } return null; } while (!current.sibling) { @@ -87,6 +119,7 @@ exports.findNextUnitOfWorkAtPriority = function(currentRoot : Fiber, priorityLev current.pendingWorkPriority = NoWork; } } + current.sibling.return = current.return; current = current.sibling; } return null; diff --git a/src/renderers/shared/fiber/ReactFiberReconciler.js b/src/renderers/shared/fiber/ReactFiberReconciler.js index cb22e88421..4ece60a0f2 100644 --- a/src/renderers/shared/fiber/ReactFiberReconciler.js +++ b/src/renderers/shared/fiber/ReactFiberReconciler.js @@ -73,7 +73,7 @@ module.exports = function(config : HostConfig) : Reconci container.pendingProps = element; container.pendingWorkPriority = LowPriority; - scheduleLowPriWork(root); + scheduleLowPriWork(root, LowPriority); // 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 @@ -88,7 +88,7 @@ module.exports = function(config : HostConfig) : Reconci root.current.pendingProps = element; root.current.pendingWorkPriority = LowPriority; - scheduleLowPriWork(root); + scheduleLowPriWork(root, LowPriority); }, unmountContainer(container : OpaqueNode) : void { @@ -98,7 +98,7 @@ module.exports = function(config : HostConfig) : Reconci root.current.pendingProps = []; root.current.pendingWorkPriority = LowPriority; - scheduleLowPriWork(root); + scheduleLowPriWork(root, LowPriority); }, getPublicRootInstance(container : OpaqueNode) : (C | null) { diff --git a/src/renderers/shared/fiber/ReactFiberScheduler.js b/src/renderers/shared/fiber/ReactFiberScheduler.js index 6df6198f9f..b6e7128968 100644 --- a/src/renderers/shared/fiber/ReactFiberScheduler.js +++ b/src/renderers/shared/fiber/ReactFiberScheduler.js @@ -15,6 +15,7 @@ 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'); @@ -43,6 +44,7 @@ module.exports = function(config : HostConfig) { // 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,10 +57,13 @@ 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; while (root) { cloneFiber(root.current, root.current.pendingWorkPriority); @@ -68,19 +73,28 @@ module.exports = function(config : HostConfig) { // too many just means flushing changes too often. let work = findNextUnitOfWorkAtPriority(root.current, HighPriority); if (work) { + nextPriorityLevel = HighPriority; return work; } work = findNextUnitOfWorkAtPriority(root.current, LowPriority); if (work) { + nextPriorityLevel = LowPriority; return work; } work = findNextUnitOfWorkAtPriority(root.current, OffscreenPriority); if (work) { + nextPriorityLevel = OffscreenPriority; return work; } // We didn't find anything to do in this root, so let's try the next one. root = root.nextScheduledRoot; } + root = nextScheduledRoot; + while (root) { + root = root.nextScheduledRoot; + } + + nextPriorityLevel = NoWork; return null; } @@ -112,9 +126,6 @@ module.exports = function(config : HostConfig) { // 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; - } const returnFiber = workInProgress.return; @@ -148,6 +159,15 @@ module.exports = function(config : HostConfig) { } else if (returnFiber) { // If there's no more work in this returnFiber. Complete the returnFiber. workInProgress = returnFiber; + // If we're stepping up through the child, that means we can now commit + // this work. We should only do this when we're stepping upwards because + // completing a downprioritized item is not the same as completing its + // children. + if (workInProgress.childInProgress) { + workInProgress.child = workInProgress.childInProgress; + workInProgress.childInProgress = null; + } + 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); @@ -156,7 +176,6 @@ module.exports = function(config : HostConfig) { // "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) { @@ -209,11 +228,13 @@ module.exports = function(config : HostConfig) { } } - function scheduleLowPriWork(root : FiberRoot) { + function scheduleLowPriWork(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; + } if (root.isScheduled) { // If we're already scheduled, we can bail out. 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..cf73133946 100644 --- a/src/renderers/shared/fiber/__tests__/ReactCoroutine-test.js +++ b/src/renderers/shared/fiber/__tests__/ReactCoroutine-test.js @@ -20,7 +20,6 @@ describe('ReactCoroutine', function() { React = require('React'); ReactNoop = require('ReactNoop'); ReactCoroutine = require('ReactCoroutine'); - spyOn(console, 'log'); }); xit('should render a coroutine', function() { diff --git a/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js b/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js index 1fd0ac9fe9..65d3b09e0a 100644 --- a/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js +++ b/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js @@ -18,7 +18,6 @@ describe('ReactIncremental', function() { beforeEach(function() { React = require('React'); ReactNoop = require('ReactNoop'); - spyOn(console, 'log'); }); it('should render a simple component', function() { @@ -284,7 +283,6 @@ describe('ReactIncremental', function() { }); it('can resume work in a bailed subtree within one pass', function() { - var ops = []; function Bar(props) { @@ -292,11 +290,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 +307,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 ( ); @@ -350,7 +360,6 @@ 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() { @@ -375,19 +384,23 @@ describe('ReactIncremental', function() {
); + var step0 = ( +
+ Hi + {'Foo'} + There +
+ ); + function Foo(props) { ops.push('Foo'); return (
- {props.text} + {props.text2} @@ -395,13 +408,111 @@ describe('ReactIncremental', function() { ); } - // Start rendering an update + // Init + ReactNoop.render(); + ReactNoop.flushLowPri(55); + + // 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(); + + // 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); + + expect(ops).toEqual(['Foo', 'Bar']); + + ops = []; + + // The middle content is now pending rendering... + ReactNoop.flushLowPri(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); + + 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(); + expect(ops).toEqual(['Middle']); + + }); + + it('can reuse work if shouldComponentUpdate is false, after being preempted', function() { + + 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', 'Middle', 'Bar', 'Middle']); + expect(ops).toEqual(['Foo', 'Bar', 'Content', 'Middle', 'Bar', 'Middle']); ops = []; @@ -416,7 +527,7 @@ describe('ReactIncremental', function() { // The middle content is now pending rendering... ReactNoop.flushLowPri(30); - expect(ops).toEqual(['Middle', 'Bar']); + expect(ops).toEqual(['Content', 'Middle', 'Bar']); // One more Middle left. ops = []; @@ -433,8 +544,16 @@ describe('ReactIncremental', function() { // we should be able to reuse the reconciliation work that we already did // without restarting. ReactNoop.flush(); - expect(ops).toEqual(['Middle']); + // 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']); }); - }); diff --git a/src/renderers/shared/fiber/__tests__/ReactIncrementalSideEffects-test.js b/src/renderers/shared/fiber/__tests__/ReactIncrementalSideEffects-test.js index c59c12b97d..c606885561 100644 --- a/src/renderers/shared/fiber/__tests__/ReactIncrementalSideEffects-test.js +++ b/src/renderers/shared/fiber/__tests__/ReactIncrementalSideEffects-test.js @@ -14,19 +14,18 @@ var React; var ReactNoop; -describe('ReactIncremental', function() { +describe('ReactIncrementalSideEffects', function() { beforeEach(function() { 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() { @@ -61,7 +60,7 @@ describe('ReactIncremental', function() { it('does not update child nodes if a flush is aborted', function() { function Bar(props) { - return {props.text}; + return ; } function Foo(props) { @@ -79,17 +78,198 @@ 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); 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() { + + function Middle(props) { + return ; + } + + function Foo(props) { + return ( +
+ +
+ ); + } + + ReactNoop.render(); + ReactNoop.flush(); + + expect(ReactNoop.root.children).toEqual([ + div(div(span('foo'))), + ]); + + ReactNoop.render(); + ReactNoop.flushLowPri(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() { + + 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.flushLowPri(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(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('can reuse side-effects after being preempted, if shouldComponentUpdate is false', function() { + + 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.flushLowPri(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() { + function Foo(props) { + return ( + + ); + } + + ReactNoop.render(); + ReactNoop.flush(); + expect(ReactNoop.root.children).toEqual([ + div(span(1)), + ]); + }); + // 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? From bada2988573e4f80c58f1c979e8933708d951f85 Mon Sep 17 00:00:00 2001 From: "B.Orlov" Date: Tue, 9 Aug 2016 21:26:29 +0400 Subject: [PATCH 003/101] Fix batchedUpdates return value (#7444) (cherry picked from commit 7d57c1f0c17eff5aa868791a7496cecd2f7ca392) --- .../shared/stack/reconciler/ReactDefaultBatchingStrategy.js | 4 ++-- src/renderers/shared/stack/reconciler/ReactUpdates.js | 2 +- .../shared/stack/reconciler/__tests__/ReactUpdates-test.js | 6 ++++++ 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/renderers/shared/stack/reconciler/ReactDefaultBatchingStrategy.js b/src/renderers/shared/stack/reconciler/ReactDefaultBatchingStrategy.js index 904dc1f803..4022775d0d 100644 --- a/src/renderers/shared/stack/reconciler/ReactDefaultBatchingStrategy.js +++ b/src/renderers/shared/stack/reconciler/ReactDefaultBatchingStrategy.js @@ -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/ReactUpdates.js b/src/renderers/shared/stack/reconciler/ReactUpdates.js index 2009fb3134..9dec2241bb 100644 --- a/src/renderers/shared/stack/reconciler/ReactUpdates.js +++ b/src/renderers/shared/stack/reconciler/ReactUpdates.js @@ -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); } /** diff --git a/src/renderers/shared/stack/reconciler/__tests__/ReactUpdates-test.js b/src/renderers/shared/stack/reconciler/__tests__/ReactUpdates-test.js index b94066f97e..11ff043980 100644 --- a/src/renderers/shared/stack/reconciler/__tests__/ReactUpdates-test.js +++ b/src/renderers/shared/stack/reconciler/__tests__/ReactUpdates-test.js @@ -1147,4 +1147,10 @@ describe('ReactUpdates', function() { ReactDOM.render(, document.createElement('div')); }); + it('unstable_batchedUpdates should return value from a callback', function() { + var result = ReactDOM.unstable_batchedUpdates(function() { + return 42; + }); + expect(result).toEqual(42); + }); }); From 7ae3bbee258ea29a99aae277a31c860360990b02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Markb=C3=A5ge?= Date: Tue, 9 Aug 2016 12:39:03 -0700 Subject: [PATCH 004/101] Bundle DOM renderers into their individual UMD bundles (#7164) * Cut out isomorphic dependencies from the renderers These files reaches into isomorphic files. The ReactElement functions are exposed on the React object anyway so I can just use those instead. I also found some files that are not shared that should be in renderers shared. * Found a few more shared dependencies renderSubtreeIntoContainer is only used by the DOM renderer. It's not an addon. ReactClass isn't needed as a dependency since injection doesn't happen anymore. * Use a shim file to load addons' dependencies on DOM By replacing this intermediate file we can do the lazy loading without needing any lazy requires. This set up works with ES modules. We could also replace the globalShim thing with aliased files instead for consistency. * Bundle DOM renderers into their individual UMD bundles Instead of exposing the entire DOM renderer on the react.js package, I only expose CurrentOwner and ComponentTreeDevtool which are currently the only two modules that share __state__ with the renderers. Then I package each renderer in its own package. That could allow us to drop more server dependencies from the client package. It will also allow us to ship fiber as a separate renderer. Unminified DEV after before react.js 123kb 696kb react-with-addons.js 227kb 774kb react-dom.js 668kb 1kb react-dom-server.js 638kb 1kb Minified PROD after before react.min.js 24kb 154kb react-with-addons.min.js 37kb 166kb react-dom.min.js 149kb 1kb react-dom-server.min.js 144kb 1kb The total size for react.min.js + react-dom.min.js is +19kb larger because of the overlap between them right now. I'd like to see what an optimizing compiler can do to this. Some of that is fbjs stuff. There shouldn't need to be that much overlap so that's something we can hunt. We should keep isomorphic absolutely minimal so there's no reason for other React clones not to use it. There will be less overlap with Fiber. However, another strategy that we could do is package the isomorphic package into each renderer bundle and conditionally initialize it if it hasn't already been initialized. That way you only pay an overlap tax when there are two renderers on the page but not without it. It's also easier to just pull in one package. The downside is the versioning stuff that the separate npm package would solve. That applies to CDNs as well. ReactWithAddons is a bit weird because it is packaged into the isomorphic package but has a bunch of DOM dependencies. So we have to load them lazily since the DOM package gets initialized after. (cherry picked from commit 8ef00dbb7de944da0e7b14438baffd37df01bf37) --- Gruntfile.js | 26 +++++- grunt/config/browserify.js | 91 ++++++++++++++++++- grunt/tasks/react-dom.js | 30 ------ package.json | 2 + src/addons/ReactAddonsDOMDependencies.js | 36 ++++++++ src/addons/ReactWithAddons.js | 17 +++- .../ReactCSSTransitionGroupChild.js | 4 +- .../transitions/ReactTransitionGroup.js | 10 +- src/renderers/dom/client/ReactMount.js | 16 +--- .../dom/client}/renderSubtreeIntoContainer.js | 0 src/renderers/dom/shared/ReactInjection.js | 2 - .../reconciler/ReactCompositeComponent.js | 25 +++-- .../shared/stack/reconciler/ReactUpdates.js | 2 +- src/umd/ReactDOMServerUMDEntry.js | 16 ++++ src/umd/ReactDOMUMDEntry.js | 34 +++++++ src/umd/ReactUMDEntry.js | 11 +-- src/umd/ReactWithAddonsUMDEntry.js | 11 +-- .../ReactAddonsDOMDependenciesUMDShim.js | 32 +++++++ vendor/react-dom-server.js | 31 ------- vendor/react-dom.js | 31 ------- 20 files changed, 287 insertions(+), 140 deletions(-) delete mode 100644 grunt/tasks/react-dom.js create mode 100644 src/addons/ReactAddonsDOMDependencies.js rename src/{addons => renderers/dom/client}/renderSubtreeIntoContainer.js (100%) create mode 100644 src/umd/ReactDOMServerUMDEntry.js create mode 100644 src/umd/ReactDOMUMDEntry.js create mode 100644 src/umd/shims/ReactAddonsDOMDependenciesUMDShim.js delete mode 100644 vendor/react-dom-server.js delete mode 100644 vendor/react-dom.js diff --git a/Gruntfile.js b/Gruntfile.js index 0932add89c..20df7c9b85 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -117,12 +117,31 @@ 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: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 +160,10 @@ module.exports = function(grunt) { 'browserify:addons', 'browserify:min', 'browserify:addonsMin', - 'build:react-dom', + 'browserify:dom', + 'browserify:domMin', + 'browserify:domServer', + 'browserify:domServerMin', 'npm-react:release', 'npm-react:pack', 'npm-react-dom:release', diff --git a/grunt/config/browserify.js b/grunt/config/browserify.js index bfcb01ddda..e61fba9bc9 100644 --- a/grunt/config/browserify.js +++ b/grunt/config/browserify.js @@ -7,11 +7,30 @@ var grunt = require('grunt'); var UglifyJS = require('uglify-js'); var uglifyify = require('uglifyify'); var derequire = require('derequire'); +var aliasify = require('aliasify'); +var globalShim = require('browserify-global-shim'); var collapser = require('bundle-collapser/plugin'); var envifyDev = envify({NODE_ENV: process.env.NODE_ENV || 'development'}); var envifyProd = envify({NODE_ENV: process.env.NODE_ENV || 'production'}); +var SECRET_INTERNALS_NAME = 'React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED'; + +var shimSharedModules = globalShim.configure({ + './ReactCurrentOwner': SECRET_INTERNALS_NAME + '.ReactCurrentOwner', + './ReactComponentTreeHook': SECRET_INTERNALS_NAME + '.ReactComponentTreeHook', + // All these methods are shared are exposed. + './ReactElement': 'React', + './ReactPropTypes': 'React.PropTypes', + './ReactChildren': 'React.Children', +}); + +var shimDOMModules = aliasify.configure({ + 'aliases': { + './ReactAddonsDOMDependencies': './build/modules/ReactAddonsDOMDependenciesUMDShim.js', + }, +}); + var SIMPLE_TEMPLATE = grunt.file.read('./grunt/data/header-template-short.txt'); @@ -87,6 +106,7 @@ var addons = { debug: false, standalone: 'React', packageName: 'React (with addons)', + transforms: [shimDOMModules], globalTransforms: [envifyDev], plugins: [collapser], after: [derequire, simpleBannerify], @@ -100,7 +120,72 @@ var addonsMin = { debug: false, standalone: 'React', packageName: 'React (with addons)', - transforms: [envifyProd, uglifyify], + transforms: [shimDOMModules, envifyProd, uglifyify], + globalTransforms: [envifyProd], + plugins: [collapser], + // No need to derequire because the minifier will mangle + // the "require" calls. + + after: [minify, bannerify], +}; + +// The DOM Builds +var dom = { + entries: [ + './build/modules/ReactDOMUMDEntry.js', + ], + outfile: './build/react-dom.js', + debug: false, + standalone: 'ReactDOM', + // Apply as global transform so that we also envify fbjs and any other deps + transforms: [shimSharedModules], + globalTransforms: [envifyDev], + plugins: [collapser], + after: [derequire, simpleBannerify], +}; + +var domMin = { + entries: [ + './build/modules/ReactDOMUMDEntry.js', + ], + outfile: './build/react-dom.min.js', + debug: false, + standalone: 'ReactDOM', + // Envify twice. The first ensures that when we uglifyify, we have the right + // conditions to exclude requires. The global transform runs on deps. + transforms: [shimSharedModules, envifyProd, uglifyify], + globalTransforms: [envifyProd], + plugins: [collapser], + // No need to derequire because the minifier will mangle + // the "require" calls. + + after: [minify, bannerify], +}; + +var domServer = { + entries: [ + './build/modules/ReactDOMServerUMDEntry.js', + ], + outfile: './build/react-dom-server.js', + debug: false, + standalone: 'ReactDOMServer', + // Apply as global transform so that we also envify fbjs and any other deps + transforms: [shimSharedModules], + globalTransforms: [envifyDev], + plugins: [collapser], + after: [derequire, simpleBannerify], +}; + +var domServerMin = { + entries: [ + './build/modules/ReactDOMServerUMDEntry.js', + ], + outfile: './build/react-dom-server.min.js', + debug: false, + standalone: 'ReactDOMServer', + // Envify twice. The first ensures that when we uglifyify, we have the right + // conditions to exclude requires. The global transform runs on deps. + transforms: [shimSharedModules, envifyProd, uglifyify], globalTransforms: [envifyProd], plugins: [collapser], // No need to derequire because the minifier will mangle @@ -114,4 +199,8 @@ module.exports = { min: min, addons: addons, addonsMin: addonsMin, + dom: dom, + domMin: domMin, + domServer: domServer, + domServerMin: domServerMin, }; diff --git a/grunt/tasks/react-dom.js b/grunt/tasks/react-dom.js deleted file mode 100644 index 77a68d0656..0000000000 --- a/grunt/tasks/react-dom.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -var grunt = require('grunt'); -var UglifyJS = require('uglify-js'); - -var LICENSE_TEMPLATE = - grunt.file.read('./grunt/data/header-template-extended.txt'); - -function build(name, filename) { - var srcFile = `vendor/${filename}.js`; - var destFile = `build/${filename}.js`; - var destFileMin = `build/${filename}.min.js`; - var templateData = { - package: name, - version: grunt.config.data.pkg.version, - }; - var header = grunt.template.process( - LICENSE_TEMPLATE, - {data: templateData} - ); - var src = grunt.file.read(srcFile); - var srcMin = UglifyJS.minify(src, {fromString: true}).code; - grunt.file.write(destFile, header + src); - grunt.file.write(destFileMin, header + srcMin); -} - -module.exports = function() { - build('ReactDOM', 'react-dom'); - build('ReactDOMServer', 'react-dom-server'); -}; diff --git a/package.json b/package.json index 10d5dfc742..6ee654a5e5 100644 --- a/package.json +++ b/package.json @@ -3,6 +3,7 @@ "private": true, "version": "15.3.2", "devDependencies": { + "aliasify": "^2.0.0", "art": "^0.10.1", "async": "^1.5.0", "babel-cli": "^6.6.5", @@ -33,6 +34,7 @@ "babel-traverse": "^6.9.0", "babylon": "6.8.0", "browserify": "^13.0.0", + "browserify-global-shim": "^1.0.3", "bundle-collapser": "^1.1.1", "coffee-script": "^1.8.0", "core-js": "^2.2.1", diff --git a/src/addons/ReactAddonsDOMDependencies.js b/src/addons/ReactAddonsDOMDependencies.js new file mode 100644 index 0000000000..e0b5eb45a5 --- /dev/null +++ b/src/addons/ReactAddonsDOMDependencies.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. + * + * @providesModule ReactAddonsDOMDependencies + */ + +'use strict'; + +var ReactDOM = require('ReactDOM'); +var ReactInstanceMap = require('ReactInstanceMap'); + +exports.getReactDOM = function() { + return ReactDOM; +}; + +exports.getReactInstanceMap = function() { + return ReactInstanceMap; +}; + +if (__DEV__) { + var ReactPerf = require('ReactPerf'); + var ReactTestUtils = require('ReactTestUtils'); + + exports.getReactPerf = function() { + return ReactPerf; + }; + + exports.getReactTestUtils = function() { + return ReactTestUtils; + }; +} diff --git a/src/addons/ReactWithAddons.js b/src/addons/ReactWithAddons.js index 94102c5c2e..4d556e9223 100644 --- a/src/addons/ReactWithAddons.js +++ b/src/addons/ReactWithAddons.js @@ -13,6 +13,7 @@ var LinkedStateMixin = require('LinkedStateMixin'); var React = require('React'); +var ReactAddonsDOMDependencies = require('ReactAddonsDOMDependencies'); var ReactComponentWithPureRenderMixin = require('ReactComponentWithPureRenderMixin'); var ReactCSSTransitionGroup = require('ReactCSSTransitionGroup'); @@ -34,8 +35,20 @@ React.addons = { }; if (__DEV__) { - React.addons.Perf = require('ReactPerf'); - React.addons.TestUtils = require('ReactTestUtils'); + // For the UMD build we get these lazily from the global since they're tied + // to the DOM renderer and it hasn't loaded yet. + Object.defineProperty(React.addons, 'Perf', { + enumerable: true, + get: function() { + return ReactAddonsDOMDependencies.getReactPerf(); + }, + }); + Object.defineProperty(React.addons, 'TestUtils', { + enumerable: true, + get: function() { + return ReactAddonsDOMDependencies.getReactTestUtils(); + }, + }); } module.exports = React; diff --git a/src/addons/transitions/ReactCSSTransitionGroupChild.js b/src/addons/transitions/ReactCSSTransitionGroupChild.js index 0412895ba4..4ac8233f68 100644 --- a/src/addons/transitions/ReactCSSTransitionGroupChild.js +++ b/src/addons/transitions/ReactCSSTransitionGroupChild.js @@ -12,7 +12,7 @@ 'use strict'; var React = require('React'); -var ReactDOM = require('ReactDOM'); +var ReactAddonsDOMDependencies = require('ReactAddonsDOMDependencies'); var CSSCore = require('CSSCore'); var ReactTransitionEvents = require('ReactTransitionEvents'); @@ -54,7 +54,7 @@ var ReactCSSTransitionGroupChild = React.createClass({ }, transition: function(animationType, finishCallback, userSpecifiedDelay) { - var node = ReactDOM.findDOMNode(this); + var node = ReactAddonsDOMDependencies.getReactDOM().findDOMNode(this); if (!node) { if (finishCallback) { diff --git a/src/addons/transitions/ReactTransitionGroup.js b/src/addons/transitions/ReactTransitionGroup.js index f33a8f3d5d..23121a334a 100644 --- a/src/addons/transitions/ReactTransitionGroup.js +++ b/src/addons/transitions/ReactTransitionGroup.js @@ -12,7 +12,7 @@ 'use strict'; var React = require('React'); -var ReactInstanceMap = require('ReactInstanceMap'); +var ReactAddonsDOMDependencies = require('ReactAddonsDOMDependencies'); var ReactTransitionChildMapping = require('ReactTransitionChildMapping'); var emptyFunction = require('emptyFunction'); @@ -64,7 +64,7 @@ var ReactTransitionGroup = React.createClass({ if (__DEV__) { nextChildMapping = ReactTransitionChildMapping.getChildMapping( nextProps.children, - ReactInstanceMap.get(this)._debugID + ReactAddonsDOMDependencies.getReactInstanceMap().get(this)._debugID ); } else { nextChildMapping = ReactTransitionChildMapping.getChildMapping( @@ -137,7 +137,7 @@ var ReactTransitionGroup = React.createClass({ if (__DEV__) { currentChildMapping = ReactTransitionChildMapping.getChildMapping( this.props.children, - ReactInstanceMap.get(this)._debugID + ReactAddonsDOMDependencies.getReactInstanceMap().get(this)._debugID ); } else { currentChildMapping = ReactTransitionChildMapping.getChildMapping( @@ -177,7 +177,7 @@ var ReactTransitionGroup = React.createClass({ if (__DEV__) { currentChildMapping = ReactTransitionChildMapping.getChildMapping( this.props.children, - ReactInstanceMap.get(this)._debugID + ReactAddonsDOMDependencies.getReactInstanceMap().get(this)._debugID ); } else { currentChildMapping = ReactTransitionChildMapping.getChildMapping( @@ -218,7 +218,7 @@ var ReactTransitionGroup = React.createClass({ if (__DEV__) { currentChildMapping = ReactTransitionChildMapping.getChildMapping( this.props.children, - ReactInstanceMap.get(this)._debugID + ReactAddonsDOMDependencies.getReactInstanceMap().get(this)._debugID ); } else { currentChildMapping = ReactTransitionChildMapping.getChildMapping( diff --git a/src/renderers/dom/client/ReactMount.js b/src/renderers/dom/client/ReactMount.js index 60ebe80069..7333f9a73d 100644 --- a/src/renderers/dom/client/ReactMount.js +++ b/src/renderers/dom/client/ReactMount.js @@ -100,7 +100,7 @@ function mountComponentIntoNode( ) { var markerName; if (ReactFeatureFlags.logTopLevelRenders) { - var wrappedElement = wrapperInstance._currentElement.props; + var wrappedElement = wrapperInstance._currentElement.props.child; var type = wrappedElement.type; markerName = 'React mount: ' + ( typeof type === 'string' ? type : @@ -275,8 +275,7 @@ if (__DEV__) { TopLevelWrapper.displayName = 'TopLevelWrapper'; } TopLevelWrapper.prototype.render = function() { - // this.props is actually a ReactElement - return this.props; + return this.props.child; }; /** @@ -450,14 +449,9 @@ var ReactMount = { 'for your app.' ); - var nextWrappedElement = ReactElement( + var nextWrappedElement = ReactElement.createElement( TopLevelWrapper, - null, - null, - null, - null, - null, - nextElement + { child: nextElement } ); var nextContext; @@ -472,7 +466,7 @@ var ReactMount = { if (prevComponent) { var prevWrappedElement = prevComponent._currentElement; - var prevElement = prevWrappedElement.props; + var prevElement = prevWrappedElement.props.child; if (shouldUpdateReactComponent(prevElement, nextElement)) { var publicInst = prevComponent._renderedComponent.getPublicInstance(); var updatedCallback = callback && function() { diff --git a/src/addons/renderSubtreeIntoContainer.js b/src/renderers/dom/client/renderSubtreeIntoContainer.js similarity index 100% rename from src/addons/renderSubtreeIntoContainer.js rename to src/renderers/dom/client/renderSubtreeIntoContainer.js diff --git a/src/renderers/dom/shared/ReactInjection.js b/src/renderers/dom/shared/ReactInjection.js index bd9d1a527d..25ef6325b9 100644 --- a/src/renderers/dom/shared/ReactInjection.js +++ b/src/renderers/dom/shared/ReactInjection.js @@ -15,7 +15,6 @@ var DOMProperty = require('DOMProperty'); var EventPluginHub = require('EventPluginHub'); var EventPluginUtils = require('EventPluginUtils'); var ReactComponentEnvironment = require('ReactComponentEnvironment'); -var ReactClass = require('ReactClass'); var ReactEmptyComponent = require('ReactEmptyComponent'); var ReactBrowserEventEmitter = require('ReactBrowserEventEmitter'); var ReactHostComponent = require('ReactHostComponent'); @@ -23,7 +22,6 @@ var ReactUpdates = require('ReactUpdates'); var ReactInjection = { Component: ReactComponentEnvironment.injection, - Class: ReactClass.injection, DOMProperty: DOMProperty.injection, EmptyComponent: ReactEmptyComponent.injection, EventPluginHub: EventPluginHub.injection, diff --git a/src/renderers/shared/stack/reconciler/ReactCompositeComponent.js b/src/renderers/shared/stack/reconciler/ReactCompositeComponent.js index 6ee4e2aac7..ec3f31d41a 100644 --- a/src/renderers/shared/stack/reconciler/ReactCompositeComponent.js +++ b/src/renderers/shared/stack/reconciler/ReactCompositeComponent.js @@ -18,10 +18,13 @@ 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 ReactPropTypeLocations = require('ReactPropTypeLocations'); + var checkReactTypeSpec = require('checkReactTypeSpec'); +} + var emptyObject = require('emptyObject'); var invariant = require('invariant'); var shallowEqual = require('shallowEqual'); @@ -680,14 +683,16 @@ var ReactCompositeComponentMixin = { * @private */ _checkContextTypes: function(typeSpecs, values, location) { - checkReactTypeSpec( - typeSpecs, - values, - location, - this.getName(), - null, - this._debugID - ); + if (__DEV__) { + checkReactTypeSpec( + typeSpecs, + values, + location, + this.getName(), + null, + this._debugID + ); + } }, receiveComponent: function(nextElement, transaction, nextContext) { diff --git a/src/renderers/shared/stack/reconciler/ReactUpdates.js b/src/renderers/shared/stack/reconciler/ReactUpdates.js index 9dec2241bb..ea2235aa00 100644 --- a/src/renderers/shared/stack/reconciler/ReactUpdates.js +++ b/src/renderers/shared/stack/reconciler/ReactUpdates.js @@ -161,7 +161,7 @@ function runBatchedUpdates(transaction) { var namedComponent = component; // Duck type TopLevelWrapper. This is probably always true. if ( - component._currentElement.props === + component._currentElement.props.child === component._renderedComponent._currentElement ) { namedComponent = component._renderedComponent; diff --git a/src/umd/ReactDOMServerUMDEntry.js b/src/umd/ReactDOMServerUMDEntry.js new file mode 100644 index 0000000000..7a55540e2b --- /dev/null +++ b/src/umd/ReactDOMServerUMDEntry.js @@ -0,0 +1,16 @@ +/** + * 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 ReactDOMServerUMDEntry + */ + +'use strict'; + +var ReactDOMServer = require('ReactDOMServer'); + +module.exports = ReactDOMServer; diff --git a/src/umd/ReactDOMUMDEntry.js b/src/umd/ReactDOMUMDEntry.js new file mode 100644 index 0000000000..59daf4bef9 --- /dev/null +++ b/src/umd/ReactDOMUMDEntry.js @@ -0,0 +1,34 @@ +/** + * 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 ReactDOMUMDEntry + */ + +'use strict'; + +var ReactDOM = require('ReactDOM'); + +var ReactDOMUMDEntry = Object.assign({ + __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: { + ReactInstanceMap: require('ReactInstanceMap'), + }, +}, ReactDOM); + +if (__DEV__) { + Object.assign( + ReactDOMUMDEntry.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, + { + // ReactPerf and ReactTestUtils currently only work with the DOM renderer + // so we expose them from here, but only in DEV mode. + ReactPerf: require('ReactPerf'), + ReactTestUtils: require('ReactTestUtils'), + } + ); +} + +module.exports = ReactDOMUMDEntry; diff --git a/src/umd/ReactUMDEntry.js b/src/umd/ReactUMDEntry.js index dda6487594..4984d842d4 100644 --- a/src/umd/ReactUMDEntry.js +++ b/src/umd/ReactUMDEntry.js @@ -11,15 +11,14 @@ 'use strict'; -var ReactDOM = require('ReactDOM'); -var ReactDOMServer = require('ReactDOMServer'); var React = require('React'); - -// `version` will be added here by ReactIsomorphic. +// `version` will be added here by the React module. var ReactUMDEntry = Object.assign({ - __SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: ReactDOM, - __SECRET_DOM_SERVER_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: ReactDOMServer, + __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: { + ReactCurrentOwner: require('ReactCurrentOwner'), + ReactComponentTreeHook: require('ReactComponentTreeHook'), + }, }, React); module.exports = ReactUMDEntry; diff --git a/src/umd/ReactWithAddonsUMDEntry.js b/src/umd/ReactWithAddonsUMDEntry.js index cf59eb9c85..a2828fa700 100644 --- a/src/umd/ReactWithAddonsUMDEntry.js +++ b/src/umd/ReactWithAddonsUMDEntry.js @@ -11,15 +11,14 @@ 'use strict'; -var ReactDOM = require('ReactDOM'); -var ReactDOMServer = require('ReactDOMServer'); var ReactWithAddons = require('ReactWithAddons'); - -// `version` will be added here by ReactIsomorphic. +// `version` will be added here by the React module. var ReactWithAddonsUMDEntry = Object.assign({ - __SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: ReactDOM, - __SECRET_DOM_SERVER_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: ReactDOMServer, + __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: { + ReactCurrentOwner: require('ReactCurrentOwner'), + ReactComponentTreeHook: require('ReactComponentTreeHook'), + }, }, ReactWithAddons); module.exports = ReactWithAddonsUMDEntry; diff --git a/src/umd/shims/ReactAddonsDOMDependenciesUMDShim.js b/src/umd/shims/ReactAddonsDOMDependenciesUMDShim.js new file mode 100644 index 0000000000..2aa7b886b5 --- /dev/null +++ b/src/umd/shims/ReactAddonsDOMDependenciesUMDShim.js @@ -0,0 +1,32 @@ +/** + * Copyright 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule ReactAddonsDOMDependenciesUMDShim + */ + +/* globals ReactDOM */ + +'use strict'; + +exports.getReactDOM = function() { + return ReactDOM; +}; + +exports.getReactInstanceMap = function() { + return ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactInstanceMap; +}; + +if (__DEV__) { + exports.getReactPerf = function() { + return ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactPerf; + }; + + exports.getReactTestUtils = function() { + return ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactTestUtils; + }; +} diff --git a/vendor/react-dom-server.js b/vendor/react-dom-server.js deleted file mode 100644 index 783456c54b..0000000000 --- a/vendor/react-dom-server.js +++ /dev/null @@ -1,31 +0,0 @@ -// Based off https://github.com/ForbesLindesay/umd/blob/master/template.js -;(function(f) { - // CommonJS - if (typeof exports === "object" && typeof module !== "undefined") { - module.exports = f(require('react')); - - // RequireJS - } else if (typeof define === "function" && define.amd) { - define(['react'], f); - - // - + '); 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/native/__tests__/ReactNativeAttributePayload-test.js b/src/renderers/native/__tests__/ReactNativeAttributePayload-test.js index d85396394b..568764dc0a 100644 --- a/src/renderers/native/__tests__/ReactNativeAttributePayload-test.js +++ b/src/renderers/native/__tests__/ReactNativeAttributePayload-test.js @@ -14,7 +14,7 @@ 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__/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/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/__tests__/ReactCoroutine-test.js b/src/renderers/shared/fiber/__tests__/ReactCoroutine-test.js index cf73133946..5f75c92807 100644 --- a/src/renderers/shared/fiber/__tests__/ReactCoroutine-test.js +++ b/src/renderers/shared/fiber/__tests__/ReactCoroutine-test.js @@ -15,14 +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'); }); - 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 65d3b09e0a..f69f84691b 100644 --- a/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js +++ b/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js @@ -14,13 +14,13 @@ var React; var ReactNoop; -describe('ReactIncremental', function() { - beforeEach(function() { +describe('ReactIncremental', () => { + beforeEach(() => { React = require('React'); ReactNoop = require('ReactNoop'); }); - it('should render a simple component', function() { + it('should render a simple component', () => { function Bar() { return
Hello World
; @@ -35,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() { @@ -65,7 +65,7 @@ describe('ReactIncremental', function() { expect(barCalled).toBe(true); }); - it('updates a previous render', function() { + it('updates a previous render', () => { var ops = []; @@ -116,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 = []; @@ -164,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 = []; @@ -218,7 +218,7 @@ describe('ReactIncremental', function() { }); - it('can resume work in a subtree even when a parent bails out', function() { + it('can resume work in a subtree even when a parent bails out', () => { var ops = []; @@ -282,7 +282,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) { @@ -362,7 +362,7 @@ describe('ReactIncremental', function() { 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 = []; @@ -461,7 +461,7 @@ describe('ReactIncremental', function() { }); - it('can reuse work if shouldComponentUpdate is false, after being preempted', function() { + it('can reuse work if shouldComponentUpdate is false, after being preempted', () => { var ops = []; diff --git a/src/renderers/shared/fiber/__tests__/ReactIncrementalSideEffects-test.js b/src/renderers/shared/fiber/__tests__/ReactIncrementalSideEffects-test.js index c606885561..fbf6d0a712 100644 --- a/src/renderers/shared/fiber/__tests__/ReactIncrementalSideEffects-test.js +++ b/src/renderers/shared/fiber/__tests__/ReactIncrementalSideEffects-test.js @@ -14,8 +14,8 @@ var React; var ReactNoop; -describe('ReactIncrementalSideEffects', function() { - beforeEach(function() { +describe('ReactIncrementalSideEffects', () => { + beforeEach(() => { React = require('React'); ReactNoop = require('ReactNoop'); }); @@ -28,7 +28,7 @@ describe('ReactIncrementalSideEffects', function() { 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}; @@ -57,7 +57,7 @@ describe('ReactIncrementalSideEffects', 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 ; @@ -89,7 +89,7 @@ describe('ReactIncrementalSideEffects', function() { }); - it('preserves a previously rendered node when deprioritized', function() { + it('preserves a previously rendered node when deprioritized', () => { function Middle(props) { return ; @@ -127,7 +127,7 @@ describe('ReactIncrementalSideEffects', function() { }); - it('can reuse side-effects after being preempted', function() { + it('can reuse side-effects after being preempted', () => { function Bar(props) { return ; @@ -188,7 +188,7 @@ describe('ReactIncrementalSideEffects', function() { ]); }); - it('can reuse side-effects after being preempted, if shouldComponentUpdate is false', function() { + it('can reuse side-effects after being preempted, if shouldComponentUpdate is false', () => { class Bar extends React.Component { shouldComponentUpdate(nextProps) { @@ -254,7 +254,7 @@ describe('ReactIncrementalSideEffects', function() { ]); }); - it('updates a child even though the old props is empty', function() { + it('updates a child even though the old props is empty', () => { function Foo(props) { return (