From ed215634bea3030b9fd19c2929fcd13ab412f8fe Mon Sep 17 00:00:00 2001 From: Sebastian Markbage Date: Tue, 7 Jun 2016 17:12:41 -0700 Subject: [PATCH 01/19] Get rid of ugly and difficult to follow breaks in switch Because pattern matching or something. --- src/renderers/shared/fiber/ReactFiberCompleteWork.js | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/renderers/shared/fiber/ReactFiberCompleteWork.js b/src/renderers/shared/fiber/ReactFiberCompleteWork.js index f4d72e3d10..179e050848 100644 --- a/src/renderers/shared/fiber/ReactFiberCompleteWork.js +++ b/src/renderers/shared/fiber/ReactFiberCompleteWork.js @@ -95,14 +95,14 @@ exports.completeWork = function(current : ?Fiber, workInProgress : Fiber) : ?Fib case FunctionalComponent: console.log('/functional component', workInProgress.type.name); transferOutput(workInProgress.child, workInProgress); - break; + return null; case ClassComponent: console.log('/class component', workInProgress.type.name); transferOutput(workInProgress.child, workInProgress); - break; + return null; case HostComponent: console.log('/host component', workInProgress.type); - break; + return null; case CoroutineComponent: console.log('/coroutine component', workInProgress.input.handler.name); return moveCoroutineToHandlerPhase(current, workInProgress); @@ -110,10 +110,10 @@ exports.completeWork = function(current : ?Fiber, workInProgress : Fiber) : ?Fib transferOutput(workInProgress.stateNode, workInProgress); // Reset the tag to now be a first phase coroutine. workInProgress.tag = CoroutineComponent; - break; + return null; case YieldComponent: // Does nothing. - break; + return null; // Error cases case IndeterminateComponent: @@ -121,5 +121,4 @@ exports.completeWork = function(current : ?Fiber, workInProgress : Fiber) : ?Fib default: throw new Error('Unknown unit of work tag'); } - return null; }; From 5e0ff5f966fa1bb2bf2d4a46fe6b8c80faf5bc87 Mon Sep 17 00:00:00 2001 From: Sebastian Markbage Date: Tue, 7 Jun 2016 18:36:04 -0700 Subject: [PATCH 02/19] Add Priority Levels Enum This flag on fibers will be used to track what priority of work is needed by that subtree, if any at all. Also fix up the TypeOfWork to have consistent naming and typing. --- src/renderers/shared/fiber/ReactFiber.js | 15 +++++++----- .../shared/fiber/ReactFiberBeginWork.js | 4 ++-- .../shared/fiber/ReactFiberCompleteWork.js | 4 ++-- .../shared/fiber/ReactPriorityLevel.js | 24 +++++++++++++++++++ ...ReactTypesOfWork.js => ReactTypeOfWork.js} | 8 +++---- 5 files changed, 41 insertions(+), 14 deletions(-) create mode 100644 src/renderers/shared/fiber/ReactPriorityLevel.js rename src/renderers/shared/fiber/{ReactTypesOfWork.js => ReactTypeOfWork.js} (84%) diff --git a/src/renderers/shared/fiber/ReactFiber.js b/src/renderers/shared/fiber/ReactFiber.js index 86e5cbaed1..9961d7a1bc 100644 --- a/src/renderers/shared/fiber/ReactFiber.js +++ b/src/renderers/shared/fiber/ReactFiber.js @@ -12,14 +12,17 @@ 'use strict'; -var ReactTypesOfWork = require('ReactTypesOfWork'); +import type { TypeOfWork } from 'ReactTypeOfWork'; +import type { PriorityLevel } from 'ReactPriorityLevel'; + +var ReactTypeOfWork = require('ReactTypeOfWork'); var { IndeterminateComponent, ClassComponent, HostComponent, CoroutineComponent, YieldComponent, -} = ReactTypesOfWork; +} = ReactTypeOfWork; var ReactElement = require('ReactElement'); @@ -32,7 +35,7 @@ import type { ReactCoroutine, ReactYield } from 'ReactCoroutine'; type Instance = { // Tag identifying the type of fiber. - tag: number, + tag: TypeOfWork, // The parent Fiber used to create this one. The type is constrained to the // Instance part of the Fiber since it is not safe to traverse the tree from @@ -71,7 +74,7 @@ export type Fiber = Instance & { output: any, // This type will be more specific once we overload the tag. // This will be used to quickly determine if a subtree has no pending changes. - hasPendingChanges: bool, + pendingWorkPriority: PriorityLevel, // This is a pooled version of a Fiber. Every fiber that gets updated will // eventually have a pair. There are cases when we can clean up pairs to save @@ -80,7 +83,7 @@ export type Fiber = Instance & { }; -var createFiber = function(tag : number, key : null | string) : Fiber { +var createFiber = function(tag : TypeOfWork, key : null | string) : Fiber { return { // Instance @@ -106,7 +109,7 @@ var createFiber = function(tag : number, key : null | string) : Fiber { memoizedInput: null, output: null, - hasPendingChanges: true, + pendingWorkPriority: 0, alternate: null, diff --git a/src/renderers/shared/fiber/ReactFiberBeginWork.js b/src/renderers/shared/fiber/ReactFiberBeginWork.js index 24ec08db90..0035d37e25 100644 --- a/src/renderers/shared/fiber/ReactFiberBeginWork.js +++ b/src/renderers/shared/fiber/ReactFiberBeginWork.js @@ -16,7 +16,7 @@ import type { ReactCoroutine } from 'ReactCoroutine'; import type { Fiber } from 'ReactFiber'; var ReactChildFiber = require('ReactChildFiber'); -var ReactTypesOfWork = require('ReactTypesOfWork'); +var ReactTypeOfWork = require('ReactTypeOfWork'); var { IndeterminateComponent, FunctionalComponent, @@ -25,7 +25,7 @@ var { CoroutineComponent, CoroutineHandlerPhase, YieldComponent, -} = ReactTypesOfWork; +} = ReactTypeOfWork; function reconcileChildren(current, workInProgress, nextChildren) { workInProgress.child = ReactChildFiber.reconcileChildFibers( diff --git a/src/renderers/shared/fiber/ReactFiberCompleteWork.js b/src/renderers/shared/fiber/ReactFiberCompleteWork.js index 179e050848..052331cb2e 100644 --- a/src/renderers/shared/fiber/ReactFiberCompleteWork.js +++ b/src/renderers/shared/fiber/ReactFiberCompleteWork.js @@ -18,7 +18,7 @@ import type { Fiber } from 'ReactFiber'; import type { ReifiedYield } from 'ReactReifiedYield'; var ReactChildFiber = require('ReactChildFiber'); -var ReactTypesOfWork = require('ReactTypesOfWork'); +var ReactTypeOfWork = require('ReactTypeOfWork'); var { IndeterminateComponent, FunctionalComponent, @@ -27,7 +27,7 @@ var { CoroutineComponent, CoroutineHandlerPhase, YieldComponent, -} = ReactTypesOfWork; +} = ReactTypeOfWork; function transferOutput(child : ?Fiber, parent : Fiber) { // If we have a single result, we just pass that through as the output to diff --git a/src/renderers/shared/fiber/ReactPriorityLevel.js b/src/renderers/shared/fiber/ReactPriorityLevel.js new file mode 100644 index 0000000000..b6930c2900 --- /dev/null +++ b/src/renderers/shared/fiber/ReactPriorityLevel.js @@ -0,0 +1,24 @@ +/** + * 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 ReactPriorityLevel + * @flow + */ + +'use strict'; + +export type PriorityLevel = 0 | 1 | 2 | 3 | 4 | 5; + +module.exports = { + NoWork: 0, // No work is pending. + SynchronousPriority: 1, // For controlled text inputs. Synchronous side-effects. + AnimationPriority: 2, // Needs to complete before the next frame. + HighPriority: 3, // Interaction that needs to complete pretty soon to feel responsive. + LowPriority: 4, // Data fetching, or result from updating stores. + OffscreenPriority: 5, // Won't be visible but do the work in case it becomes visible. +}; diff --git a/src/renderers/shared/fiber/ReactTypesOfWork.js b/src/renderers/shared/fiber/ReactTypeOfWork.js similarity index 84% rename from src/renderers/shared/fiber/ReactTypesOfWork.js rename to src/renderers/shared/fiber/ReactTypeOfWork.js index d54dc16807..915084416f 100644 --- a/src/renderers/shared/fiber/ReactTypesOfWork.js +++ b/src/renderers/shared/fiber/ReactTypeOfWork.js @@ -6,13 +6,15 @@ * 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 ReactTypesOfWork + * @providesModule ReactTypeOfWork * @flow */ 'use strict'; -var TypesOfWork = { +export type TypeOfWork = 0 | 1 | 2 | 3 | 4 | 5 | 6; + +module.exports = { IndeterminateComponent: 0, // Before we know whether it is functional or class FunctionalComponent: 1, ClassComponent: 2, @@ -21,5 +23,3 @@ var TypesOfWork = { CoroutineHandlerPhase: 5, YieldComponent: 6, }; - -module.exports = TypesOfWork; From 81537c3e511c9e35200b39c1f61a6bef79afbc8a Mon Sep 17 00:00:00 2001 From: Sebastian Markbage Date: Sat, 11 Jun 2016 16:22:35 -0700 Subject: [PATCH 03/19] Rename input -> props I tried to be clever and generalize it but this is currently only props and there are other assumptions that might break down if it isn't. --- src/renderers/shared/fiber/ReactChildFiber.js | 4 ++-- src/renderers/shared/fiber/ReactFiber.js | 14 ++++++------- .../shared/fiber/ReactFiberBeginWork.js | 20 +++++++++---------- .../shared/fiber/ReactFiberCompleteWork.js | 6 +++--- .../shared/fiber/ReactFiberReconciler.js | 2 +- 5 files changed, 23 insertions(+), 23 deletions(-) diff --git a/src/renderers/shared/fiber/ReactChildFiber.js b/src/renderers/shared/fiber/ReactChildFiber.js index 8921b9f188..93ddfbc6c8 100644 --- a/src/renderers/shared/fiber/ReactChildFiber.js +++ b/src/renderers/shared/fiber/ReactChildFiber.js @@ -42,7 +42,7 @@ function createSubsequentChild(parent : Fiber, existingChild : ?Fiber, previousS // TODO: This is not sufficient since previous siblings could be new. // Will fix reconciliation properly later. const clone = ReactFiber.cloneFiber(existingChild); - clone.input = element.props; + clone.pendingProps = element.props; clone.child = existingChild.child; clone.sibling = null; previousSibling.sibling = clone; @@ -104,7 +104,7 @@ function createFirstChild(parent, existingChild, newChildren) { element.key === existingChild.key) { // Get the clone of the existing fiber. const clone = ReactFiber.cloneFiber(existingChild); - clone.input = element.props; + clone.pendingProps = element.props; clone.child = existingChild.child; clone.sibling = null; return clone; diff --git a/src/renderers/shared/fiber/ReactFiber.js b/src/renderers/shared/fiber/ReactFiber.js index 9961d7a1bc..c157bf1c21 100644 --- a/src/renderers/shared/fiber/ReactFiber.js +++ b/src/renderers/shared/fiber/ReactFiber.js @@ -66,9 +66,9 @@ export type Fiber = Instance & { ref: null | (handle : ?Object) => void, // Input is the data coming into process this fiber. Arguments. Props. - input: any, // This type will be more specific once we overload the tag. - // TODO: I think that there is a way to merge input and memoizedInput somehow. - memoizedInput: any, // The input used to create the output. + pendingProps: any, // This type will be more specific once we overload the tag. + // TODO: I think that there is a way to merge input and memoizedProps somehow. + memoizedProps: any, // The input used to create the output. // Output is the return value of this fiber, or a linked list of return values // if this returns multiple values. Such as a fragment. output: any, // This type will be more specific once we overload the tag. @@ -105,8 +105,8 @@ var createFiber = function(tag : TypeOfWork, key : null | string) : Fiber { ref: null, - input: null, - memoizedInput: null, + pendingProps: null, + memoizedProps: null, output: null, pendingWorkPriority: 0, @@ -149,7 +149,7 @@ exports.cloneFiber = function(fiber : Fiber) : Fiber { exports.createFiberFromElement = function(element : ReactElement) { const fiber = exports.createFiberFromElementType(element.type, element.key); - fiber.input = element.props; + fiber.pendingProps = element.props; return fiber; }; @@ -175,7 +175,7 @@ exports.createFiberFromElementType = function(type : mixed, key : null | string) exports.createFiberFromCoroutine = function(coroutine : ReactCoroutine) { const fiber = createFiber(CoroutineComponent, coroutine.key); fiber.type = coroutine.handler; - fiber.input = coroutine; + fiber.pendingProps = coroutine; return fiber; }; diff --git a/src/renderers/shared/fiber/ReactFiberBeginWork.js b/src/renderers/shared/fiber/ReactFiberBeginWork.js index 0035d37e25..11e753230f 100644 --- a/src/renderers/shared/fiber/ReactFiberBeginWork.js +++ b/src/renderers/shared/fiber/ReactFiberBeginWork.js @@ -37,22 +37,22 @@ function reconcileChildren(current, workInProgress, nextChildren) { function updateFunctionalComponent(current, workInProgress) { var fn = workInProgress.type; - var props = workInProgress.input; + var props = workInProgress.pendingProps; console.log('update fn:', fn.name); var nextChildren = fn(props); reconcileChildren(current, workInProgress, nextChildren); } function updateHostComponent(current, workInProgress) { - console.log('host component', workInProgress.type, typeof workInProgress.input.children === 'string' ? workInProgress.input.children : ''); + console.log('host component', workInProgress.type, typeof workInProgress.pendingProps.children === 'string' ? workInProgress.pendingProps.children : ''); - var nextChildren = workInProgress.input.children; + var nextChildren = workInProgress.pendingProps.children; reconcileChildren(current, workInProgress, nextChildren); } function mountIndeterminateComponent(current, workInProgress) { var fn = workInProgress.type; - var props = workInProgress.input; + 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); @@ -67,7 +67,7 @@ function mountIndeterminateComponent(current, workInProgress) { } function updateCoroutineComponent(current, workInProgress) { - var coroutine = (workInProgress.input : ?ReactCoroutine); + var coroutine = (workInProgress.pendingProps : ?ReactCoroutine); if (!coroutine) { throw new Error('Should be resolved by now'); } @@ -80,18 +80,18 @@ function beginWork(current : ?Fiber, workInProgress : Fiber) : ?Fiber { // 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.input === current.memoizedInput) { + if (current && workInProgress.pendingProps === current.memoizedProps) { // The most likely scenario is that the previous copy of the tree contains - // the same input as the new one. In that case, we can just copy the output + // the same props as the new one. In that case, we can just copy the output // and children from that node. workInProgress.output = current.output; workInProgress.child = current.child; workInProgress.stateNode = current.stateNode; return null; } - if (workInProgress.input === workInProgress.memoizedInput) { + if (workInProgress.pendingProps === workInProgress.memoizedProps) { // In a ping-pong scenario, this version could actually contain the - // old input. In that case, we can just bail out. + // old props. In that case, we can just bail out. return null; } switch (workInProgress.tag) { @@ -102,7 +102,7 @@ function beginWork(current : ?Fiber, workInProgress : Fiber) : ?Fiber { updateFunctionalComponent(current, workInProgress); return workInProgress.child; case ClassComponent: - console.log('class component', workInProgress.input.type.name); + console.log('class component', workInProgress.pendingProps.type.name); return workInProgress.child; case HostComponent: updateHostComponent(current, workInProgress); diff --git a/src/renderers/shared/fiber/ReactFiberCompleteWork.js b/src/renderers/shared/fiber/ReactFiberCompleteWork.js index 052331cb2e..6cdc42d440 100644 --- a/src/renderers/shared/fiber/ReactFiberCompleteWork.js +++ b/src/renderers/shared/fiber/ReactFiberCompleteWork.js @@ -34,7 +34,7 @@ function transferOutput(child : ?Fiber, parent : Fiber) { // avoid unnecessary traversal. When we have multiple output, we just pass // the linked list of fibers that has the individual output values. parent.output = (child && !child.sibling) ? child.output : child; - parent.memoizedInput = parent.input; + parent.memoizedProps = parent.pendingProps; } function recursivelyFillYields(yields, output : ?Fiber | ?ReifiedYield) { @@ -55,7 +55,7 @@ function recursivelyFillYields(yields, output : ?Fiber | ?ReifiedYield) { } function moveCoroutineToHandlerPhase(current : ?Fiber, workInProgress : Fiber) { - var coroutine = (workInProgress.input : ?ReactCoroutine); + var coroutine = (workInProgress.pendingProps : ?ReactCoroutine); if (!coroutine) { throw new Error('Should be resolved by now'); } @@ -104,7 +104,7 @@ exports.completeWork = function(current : ?Fiber, workInProgress : Fiber) : ?Fib console.log('/host component', workInProgress.type); return null; case CoroutineComponent: - console.log('/coroutine component', workInProgress.input.handler.name); + 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/ReactFiberReconciler.js b/src/renderers/shared/fiber/ReactFiberReconciler.js index e7f0e2a441..658640d5cc 100644 --- a/src/renderers/shared/fiber/ReactFiberReconciler.js +++ b/src/renderers/shared/fiber/ReactFiberReconciler.js @@ -134,7 +134,7 @@ module.exports = function(config : HostConfig) : Reconciler { // is passed. Should be doable though. Might require a wrapper don't know. if (rootFiber && rootFiber.type === element.type && rootFiber.key === element.key) { nextUnitOfWork = ReactFiber.cloneFiber(rootFiber); - nextUnitOfWork.input = element.props; + nextUnitOfWork.pendingProps = element.props; return {}; } From 61fe5e11dc44b73f5ab9b11a3670e4cab761c64f Mon Sep 17 00:00:00 2001 From: Sebastian Markbage Date: Sat, 11 Jun 2016 20:32:57 -0700 Subject: [PATCH 04/19] Test ability to abort work --- .../fiber/__tests__/ReactIncremental-test.js | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js b/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js index 5d1af26bcf..224c44dfbf 100644 --- a/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js +++ b/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js @@ -115,4 +115,54 @@ describe('ReactIncremental', function() { }); + it('can cancel partially rendered work and restart', function() { + + var ops = []; + + function Bar(props) { + ops.push('Bar'); + return
{props.children}
; + } + + function Foo(props) { + ops.push('Foo'); + return ( +
+ {props.text} + {props.text} +
+ ); + } + + // Init + ReactNoop.render(); + ReactNoop.flush(); + + ops = []; + + ReactNoop.render(); + // Flush part of the work + ReactNoop.flushLowPri(20); + + expect(ops).toEqual(['Foo', 'Bar']); + + ops = []; + + // This will abort the previous work and restart + ReactNoop.render(); + + // Flush part of the new work + ReactNoop.flushLowPri(20); + + expect(ops).toEqual(['Foo', 'Bar']); + + // Flush the rest of the work which now includes the low priority + ReactNoop.flush(20); + + expect(ops).toEqual(['Foo', 'Bar', 'Bar']); + + // TODO: Test the ability for a subtree to resume if it has lower priority. + + }); + }); From f04c38ed656a513fe5515e54d7645883767a177e Mon Sep 17 00:00:00 2001 From: Sebastian Markbage Date: Mon, 13 Jun 2016 19:43:33 -0700 Subject: [PATCH 05/19] Create HostContainer Component Type This is essentially equivalent to the current top level wrappers. They contain the next children to be mounted into a container node from the host. It is the responsibility of the host to retain references to them for updates. I expect them to be able to exist in the middle of the tree in the future, for renderSubtreeIntoContainer. --- src/renderers/noop/ReactNoop.js | 10 +- src/renderers/shared/fiber/ReactChildFiber.js | 2 + src/renderers/shared/fiber/ReactFiber.js | 7 + .../shared/fiber/ReactFiberBeginWork.js | 12 ++ .../shared/fiber/ReactFiberCompleteWork.js | 3 + .../shared/fiber/ReactFiberReconciler.js | 143 +++++++++++++++--- src/renderers/shared/fiber/ReactTypeOfWork.js | 11 +- 7 files changed, 161 insertions(+), 27 deletions(-) diff --git a/src/renderers/noop/ReactNoop.js b/src/renderers/noop/ReactNoop.js index 1b411a2f3f..723f7fad98 100644 --- a/src/renderers/noop/ReactNoop.js +++ b/src/renderers/noop/ReactNoop.js @@ -38,12 +38,16 @@ var NoopRenderer = ReactFiberReconciler({ }); +var root = null; + var ReactNoop = { render(element : ReactElement) { - - NoopRenderer.mountNewRoot(element); - + if (!root) { + root = NoopRenderer.mountContainer(element, null); + } else { + NoopRenderer.updateContainer(element, root); + } }, flushHighPri() { diff --git a/src/renderers/shared/fiber/ReactChildFiber.js b/src/renderers/shared/fiber/ReactChildFiber.js index 93ddfbc6c8..3e515ba729 100644 --- a/src/renderers/shared/fiber/ReactChildFiber.js +++ b/src/renderers/shared/fiber/ReactChildFiber.js @@ -158,6 +158,8 @@ function createFirstChild(parent, existingChild, newChildren) { } } +// TODO: This API won't work because we'll need to transfer the side-effects of +// unmounting children to the parent. exports.reconcileChildFibers = function(parent : Fiber, currentFirstChild : ?Fiber, newChildren : ReactNodeList) : ?Fiber { return createFirstChild(parent, currentFirstChild, newChildren); }; diff --git a/src/renderers/shared/fiber/ReactFiber.js b/src/renderers/shared/fiber/ReactFiber.js index c157bf1c21..61e52ca8f2 100644 --- a/src/renderers/shared/fiber/ReactFiber.js +++ b/src/renderers/shared/fiber/ReactFiber.js @@ -19,6 +19,7 @@ var ReactTypeOfWork = require('ReactTypeOfWork'); var { IndeterminateComponent, ClassComponent, + HostContainer, HostComponent, CoroutineComponent, YieldComponent, @@ -147,6 +148,12 @@ exports.cloneFiber = function(fiber : Fiber) : Fiber { return alt; }; +exports.createHostContainerFiber = function(containerInfo : ?Object) { + const fiber = createFiber(HostContainer, null); + fiber.stateNode = containerInfo; + return fiber; +}; + exports.createFiberFromElement = function(element : ReactElement) { const fiber = exports.createFiberFromElementType(element.type, element.key); fiber.pendingProps = element.props; diff --git a/src/renderers/shared/fiber/ReactFiberBeginWork.js b/src/renderers/shared/fiber/ReactFiberBeginWork.js index 11e753230f..e7cd180031 100644 --- a/src/renderers/shared/fiber/ReactFiberBeginWork.js +++ b/src/renderers/shared/fiber/ReactFiberBeginWork.js @@ -21,6 +21,7 @@ var { IndeterminateComponent, FunctionalComponent, ClassComponent, + HostContainer, HostComponent, CoroutineComponent, CoroutineHandlerPhase, @@ -104,6 +105,17 @@ function beginWork(current : ?Fiber, workInProgress : Fiber) : ?Fiber { case ClassComponent: console.log('class component', workInProgress.pendingProps.type.name); return workInProgress.child; + case HostContainer: + reconcileChildren(current, workInProgress, workInProgress.pendingProps); + // A yield component is just a placeholder, we can just run through the + // next one immediately. + if (workInProgress.child) { + return beginWork( + workInProgress.child.alternate, + workInProgress.child + ); + } + return null; case HostComponent: updateHostComponent(current, workInProgress); return workInProgress.child; diff --git a/src/renderers/shared/fiber/ReactFiberCompleteWork.js b/src/renderers/shared/fiber/ReactFiberCompleteWork.js index 6cdc42d440..d3347c3f18 100644 --- a/src/renderers/shared/fiber/ReactFiberCompleteWork.js +++ b/src/renderers/shared/fiber/ReactFiberCompleteWork.js @@ -23,6 +23,7 @@ var { IndeterminateComponent, FunctionalComponent, ClassComponent, + HostContainer, HostComponent, CoroutineComponent, CoroutineHandlerPhase, @@ -100,6 +101,8 @@ exports.completeWork = function(current : ?Fiber, workInProgress : Fiber) : ?Fib console.log('/class component', workInProgress.type.name); transferOutput(workInProgress.child, workInProgress); return null; + case HostContainer: + return null; case HostComponent: console.log('/host component', workInProgress.type); return null; diff --git a/src/renderers/shared/fiber/ReactFiberReconciler.js b/src/renderers/shared/fiber/ReactFiberReconciler.js index 658640d5cc..5c134bb03b 100644 --- a/src/renderers/shared/fiber/ReactFiberReconciler.js +++ b/src/renderers/shared/fiber/ReactFiberReconciler.js @@ -13,10 +13,19 @@ 'use strict'; import type { Fiber } from 'ReactFiber'; +import type { PriorityLevel } from 'ReactPriorityLevel'; + var ReactFiber = require('ReactFiber'); var { beginWork } = require('ReactFiberBeginWork'); var { completeWork } = require('ReactFiberCompleteWork'); +var { + NoWork, + HighPriority, + LowPriority, + OffscreenPriority, +} = require('ReactPriorityLevel'); + type ReactHostElement = { type: T, props: P @@ -36,10 +45,15 @@ export type HostConfig = { }; -type OpaqueID = {}; +type OpaqueNode = Fiber; export type Reconciler = { - mountNewRoot(element : ReactElement) : OpaqueID; + mountContainer(element : ReactElement, containerInfo : ?Object) : OpaqueNode, + updateContainer(element : ReactElement, container : OpaqueNode) : void, + unmountContainer(container : OpaqueNode) : void, + + // Used to extract the return value from the initial render. Legacy API. + getPublicRootInstance(container : OpaqueNode) : ?Object, }; module.exports = function(config : HostConfig) : Reconciler { @@ -49,6 +63,49 @@ module.exports = function(config : HostConfig) : Reconciler { let nextUnitOfWork : ?Fiber = null; + let currentRootsWithPendingWork : ?Fiber = null; + + function findNextUnitOfWork(priorityLevel : PriorityLevel) : ?Fiber { + let current = currentRootsWithPendingWork; + while (current) { + if (current.pendingWorkPriority !== 0 && + current.pendingWorkPriority <= priorityLevel) { + // This node has work to do that fits our priority level criteria. + if (current.pendingProps !== null) { + // We found some work to do. We need to return the "work in progress" + // of this node which will be the alternate. + return current.alternate; + } + // 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. + if (current.child) { + current = current.child; + continue; + } + // If we match the priority but has no child and no work to do, + // then we can safely reset the flag. + current.pendingWorkPriority = NoWork; + } + while (!current.sibling) { + // TODO: Stop using parent here. See below. + // $FlowFixMe: This downcast is not safe. It is intentionally an error. + current = current.parent; + if (!current) { + return null; + } + if (current.pendingWorkPriority <= priorityLevel) { + // If this subtree had work left to do, we would have returned it by + // now. This could happen if a child with pending work gets cleaned up + // but we don't clear the flag then. It is safe to reset it now. + current.pendingWorkPriority = NoWork; + } + } + current = current.sibling; + } + return null; + } + function completeUnitOfWork(workInProgress : Fiber) : ?Fiber { while (true) { // The current, flushed, state of this fiber is the alternate. @@ -73,6 +130,7 @@ module.exports = function(config : HostConfig) : Reconciler { workInProgress = workInProgress.parent; } else { // If we're at the root, there's no more work to do. + currentRootsWithPendingWork = null; return null; } } @@ -95,6 +153,19 @@ module.exports = function(config : HostConfig) : Reconciler { } function performLowPriWork(deadline : Deadline) { + if (!nextUnitOfWork) { + // Find the highest possible priority work to do. + // This loop is unrolled just to satisfy Flow's enum constraint. + // We could make arbitrary many idle priority levels but having + // too many just means flushing changes too often. + nextUnitOfWork = findNextUnitOfWork(HighPriority); + if (!nextUnitOfWork) { + nextUnitOfWork = findNextUnitOfWork(LowPriority); + if (!nextUnitOfWork) { + nextUnitOfWork = findNextUnitOfWork(OffscreenPriority); + } + } + } while (nextUnitOfWork) { if (deadline.timeRemaining() > timeHeuristicForUnitOfWork) { nextUnitOfWork = performUnitOfWork(nextUnitOfWork); @@ -105,11 +176,34 @@ module.exports = function(config : HostConfig) : Reconciler { } } - function ensureLowPriIsScheduled() { - if (nextUnitOfWork) { - return; + function scheduleLowPriWork(root : Fiber) { + // We must reset the current unit of work pointer so that we restart the + // search from the root during the next tick. + nextUnitOfWork = null; + + if (currentRootsWithPendingWork) { + if (root === currentRootsWithPendingWork) { + // We're already scheduled. + return; + } + // We already have some work pending in another root. Add this to the + // linked list. + let previousSibling = currentRootsWithPendingWork; + while (previousSibling.sibling) { + previousSibling = previousSibling.sibling; + if (root === previousSibling) { + // We're already scheduled. + return; + } + } + previousSibling.sibling = root; + } else { + // We're the first and only root with new changes. + currentRootsWithPendingWork = root; + root.sibling = null; + // Ensure we will get another callback to process the work. + scheduleLowPriCallback(performLowPriWork); } - scheduleLowPriCallback(performLowPriWork); } /* @@ -122,26 +216,37 @@ module.exports = function(config : HostConfig) : Reconciler { } */ - let rootFiber : ?Fiber = null; - return { - mountNewRoot(element : ReactElement) : OpaqueID { + mountContainer(element : ReactElement, containerInfo : ?Object) : OpaqueNode { + const container = ReactFiber.createHostContainerFiber(containerInfo); + container.alternate = container; + container.pendingProps = element; + container.pendingWorkPriority = LowPriority; - ensureLowPriIsScheduled(); + scheduleLowPriWork(container); - // TODO: Unify this with ReactChildFiber. We can't now because the parent - // is passed. Should be doable though. Might require a wrapper don't know. - if (rootFiber && rootFiber.type === element.type && rootFiber.key === element.key) { - nextUnitOfWork = ReactFiber.cloneFiber(rootFiber); - nextUnitOfWork.pendingProps = element.props; - return {}; - } + return container; + }, - nextUnitOfWork = rootFiber = ReactFiber.createFiberFromElement(element); + updateContainer(element : ReactElement, container : OpaqueNode) : void { + container.pendingProps = element; + container.pendingWorkPriority = LowPriority; - return {}; + scheduleLowPriWork(container); + }, + + unmountContainer(container : OpaqueNode) : void { + container.pendingProps = null; + container.pendingWorkPriority = LowPriority; + + scheduleLowPriWork(container); + }, + + getPublicRootInstance(container : OpaqueNode) : ?Object { + return null; }, }; + }; diff --git a/src/renderers/shared/fiber/ReactTypeOfWork.js b/src/renderers/shared/fiber/ReactTypeOfWork.js index 915084416f..b63813b1d5 100644 --- a/src/renderers/shared/fiber/ReactTypeOfWork.js +++ b/src/renderers/shared/fiber/ReactTypeOfWork.js @@ -12,14 +12,15 @@ 'use strict'; -export type TypeOfWork = 0 | 1 | 2 | 3 | 4 | 5 | 6; +export type TypeOfWork = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7; module.exports = { IndeterminateComponent: 0, // Before we know whether it is functional or class FunctionalComponent: 1, ClassComponent: 2, - HostComponent: 3, - CoroutineComponent: 4, - CoroutineHandlerPhase: 5, - YieldComponent: 6, + HostContainer: 3, // Root of a host tree. Could be nested inside another node. + HostComponent: 4, + CoroutineComponent: 5, + CoroutineHandlerPhase: 6, + YieldComponent: 7, }; From e53f0dc4b44f08b354f24acb2e22ce1349dfc76f Mon Sep 17 00:00:00 2001 From: Sebastian Markbage Date: Tue, 14 Jun 2016 13:40:43 -0700 Subject: [PATCH 06/19] Pass the priority level along to children --- src/renderers/shared/fiber/ReactChildFiber.js | 31 ++++++++++--------- src/renderers/shared/fiber/ReactFiber.js | 15 ++++++--- .../shared/fiber/ReactFiberBeginWork.js | 4 ++- .../shared/fiber/ReactFiberCompleteWork.js | 5 ++- .../shared/fiber/ReactFiberReconciler.js | 3 +- 5 files changed, 34 insertions(+), 24 deletions(-) diff --git a/src/renderers/shared/fiber/ReactChildFiber.js b/src/renderers/shared/fiber/ReactChildFiber.js index 3e515ba729..f0966e518c 100644 --- a/src/renderers/shared/fiber/ReactChildFiber.js +++ b/src/renderers/shared/fiber/ReactChildFiber.js @@ -14,6 +14,7 @@ import type { ReactCoroutine, ReactYield } from 'ReactCoroutine'; import type { Fiber } from 'ReactFiber'; +import type { PriorityLevel } from 'ReactPriorityLevel'; import type { ReactNodeList } from 'ReactTypes'; @@ -28,7 +29,7 @@ var { var ReactFiber = require('ReactFiber'); var ReactReifiedYield = require('ReactReifiedYield'); -function createSubsequentChild(parent : Fiber, existingChild : ?Fiber, previousSibling : Fiber, newChildren) : Fiber { +function createSubsequentChild(parent : Fiber, existingChild : ?Fiber, previousSibling : Fiber, newChildren, priority : PriorityLevel) : Fiber { if (typeof newChildren !== 'object' || newChildren === null) { return previousSibling; } @@ -41,14 +42,14 @@ function createSubsequentChild(parent : Fiber, existingChild : ?Fiber, previousS 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); + const clone = ReactFiber.cloneFiber(existingChild, priority); clone.pendingProps = element.props; clone.child = existingChild.child; clone.sibling = null; previousSibling.sibling = clone; return clone; } - const child = ReactFiber.createFiberFromElement(element); + const child = ReactFiber.createFiberFromElement(element, priority); previousSibling.sibling = child; child.parent = parent; return child; @@ -56,7 +57,7 @@ function createSubsequentChild(parent : Fiber, existingChild : ?Fiber, previousS case REACT_COROUTINE_TYPE: { const coroutine = (newChildren : ReactCoroutine); - const child = ReactFiber.createFiberFromCoroutine(coroutine); + const child = ReactFiber.createFiberFromCoroutine(coroutine, priority); previousSibling.sibling = child; child.parent = parent; return child; @@ -65,7 +66,7 @@ function createSubsequentChild(parent : Fiber, existingChild : ?Fiber, previousS case REACT_YIELD_TYPE: { const yieldNode = (newChildren : ReactYield); const reifiedYield = ReactReifiedYield.createReifiedYield(yieldNode); - const child = ReactFiber.createFiberFromYield(yieldNode); + const child = ReactFiber.createFiberFromYield(yieldNode, priority); child.output = reifiedYield; previousSibling.sibling = child; child.parent = parent; @@ -77,7 +78,7 @@ function createSubsequentChild(parent : Fiber, existingChild : ?Fiber, previousS let prev : Fiber = previousSibling; let existing : ?Fiber = existingChild; for (var i = 0; i < newChildren.length; i++) { - prev = createSubsequentChild(parent, existing, prev, newChildren[i]); + prev = createSubsequentChild(parent, 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. @@ -91,7 +92,7 @@ function createSubsequentChild(parent : Fiber, existingChild : ?Fiber, previousS } } -function createFirstChild(parent, existingChild, newChildren) { +function createFirstChild(parent, existingChild, newChildren, priority) { if (typeof newChildren !== 'object' || newChildren === null) { return null; } @@ -103,20 +104,20 @@ function createFirstChild(parent, existingChild, newChildren) { element.type === existingChild.type && element.key === existingChild.key) { // Get the clone of the existing fiber. - const clone = ReactFiber.cloneFiber(existingChild); + const clone = ReactFiber.cloneFiber(existingChild, priority); clone.pendingProps = element.props; clone.child = existingChild.child; clone.sibling = null; return clone; } - const child = ReactFiber.createFiberFromElement(element); + const child = ReactFiber.createFiberFromElement(element, priority); child.parent = parent; return child; } case REACT_COROUTINE_TYPE: { const coroutine = (newChildren : ReactCoroutine); - const child = ReactFiber.createFiberFromCoroutine(coroutine); + const child = ReactFiber.createFiberFromCoroutine(coroutine, priority); child.parent = parent; return child; } @@ -127,7 +128,7 @@ function createFirstChild(parent, existingChild, newChildren) { // the fragment. const yieldNode = (newChildren : ReactYield); const reifiedYield = ReactReifiedYield.createReifiedYield(yieldNode); - const child = ReactFiber.createFiberFromYield(yieldNode); + const child = ReactFiber.createFiberFromYield(yieldNode, priority); child.output = reifiedYield; child.parent = parent; return child; @@ -140,10 +141,10 @@ function createFirstChild(parent, existingChild, newChildren) { var existing : ?Fiber = existingChild; for (var i = 0; i < newChildren.length; i++) { if (prev == null) { - prev = createFirstChild(parent, existing, newChildren[i]); + prev = createFirstChild(parent, existing, newChildren[i], priority); first = prev; } else { - prev = createSubsequentChild(parent, existing, prev, newChildren[i]); + prev = createSubsequentChild(parent, existing, prev, newChildren[i], priority); } if (prev && existing) { // TODO: This is not correct because there could've been more @@ -160,6 +161,6 @@ function createFirstChild(parent, existingChild, newChildren) { // TODO: This API won't work because we'll need to transfer the side-effects of // unmounting children to the parent. -exports.reconcileChildFibers = function(parent : Fiber, currentFirstChild : ?Fiber, newChildren : ReactNodeList) : ?Fiber { - return createFirstChild(parent, currentFirstChild, newChildren); +exports.reconcileChildFibers = function(parent : Fiber, currentFirstChild : ?Fiber, newChildren : ReactNodeList, priority : PriorityLevel) : ?Fiber { + return createFirstChild(parent, currentFirstChild, newChildren, priority); }; diff --git a/src/renderers/shared/fiber/ReactFiber.js b/src/renderers/shared/fiber/ReactFiber.js index 61e52ca8f2..0dd16c38a0 100644 --- a/src/renderers/shared/fiber/ReactFiber.js +++ b/src/renderers/shared/fiber/ReactFiber.js @@ -122,13 +122,14 @@ function shouldConstruct(Component) { } // This is used to create an alternate fiber to do work on. -exports.cloneFiber = function(fiber : Fiber) : Fiber { +exports.cloneFiber = function(fiber : Fiber, priorityLevel : PriorityLevel) : Fiber { // We use a double buffering pooling technique because we know that we'll only // ever need at most two versions of a tree. We pool the "other" unused node // that we're free to reuse. This is lazily created to avoid allocating extra // objects for things that are never updated. It also allow us to reclaim the // extra memory if needed. if (fiber.alternate) { + fiber.alternate.pendingWorkPriority = priorityLevel; return fiber.alternate; } // This should not have an alternate already @@ -144,19 +145,22 @@ exports.cloneFiber = function(fiber : Fiber) : Fiber { alt.type = fiber.type; alt.stateNode = fiber.stateNode; alt.alternate = fiber; + alt.pendingWorkPriority = priorityLevel; fiber.alternate = alt; return alt; }; -exports.createHostContainerFiber = function(containerInfo : ?Object) { +exports.createHostContainerFiber = function(containerInfo : ?Object, priorityLevel : PriorityLevel) { const fiber = createFiber(HostContainer, null); fiber.stateNode = containerInfo; + fiber.pendingWorkPriority = priorityLevel; return fiber; }; -exports.createFiberFromElement = function(element : ReactElement) { +exports.createFiberFromElement = function(element : ReactElement, priorityLevel : PriorityLevel) { const fiber = exports.createFiberFromElementType(element.type, element.key); fiber.pendingProps = element.props; + fiber.pendingWorkPriority = priorityLevel; return fiber; }; @@ -179,14 +183,15 @@ exports.createFiberFromElementType = function(type : mixed, key : null | string) return fiber; }; -exports.createFiberFromCoroutine = function(coroutine : ReactCoroutine) { +exports.createFiberFromCoroutine = function(coroutine : ReactCoroutine, priorityLevel : PriorityLevel) { const fiber = createFiber(CoroutineComponent, coroutine.key); fiber.type = coroutine.handler; fiber.pendingProps = coroutine; + fiber.pendingWorkPriority = priorityLevel; return fiber; }; -exports.createFiberFromYield = function(yieldNode : ReactYield) { +exports.createFiberFromYield = function(yieldNode : ReactYield, priorityLevel : PriorityLevel) { const fiber = createFiber(YieldComponent, yieldNode.key); return fiber; }; diff --git a/src/renderers/shared/fiber/ReactFiberBeginWork.js b/src/renderers/shared/fiber/ReactFiberBeginWork.js index e7cd180031..07e6c13227 100644 --- a/src/renderers/shared/fiber/ReactFiberBeginWork.js +++ b/src/renderers/shared/fiber/ReactFiberBeginWork.js @@ -29,10 +29,12 @@ var { } = ReactTypeOfWork; function reconcileChildren(current, workInProgress, nextChildren) { + const priority = workInProgress.pendingWorkPriority; workInProgress.child = ReactChildFiber.reconcileChildFibers( workInProgress, current ? current.child : null, - nextChildren + nextChildren, + priority ); } diff --git a/src/renderers/shared/fiber/ReactFiberCompleteWork.js b/src/renderers/shared/fiber/ReactFiberCompleteWork.js index d3347c3f18..49ad5c1b2c 100644 --- a/src/renderers/shared/fiber/ReactFiberCompleteWork.js +++ b/src/renderers/shared/fiber/ReactFiberCompleteWork.js @@ -83,10 +83,13 @@ function moveCoroutineToHandlerPhase(current : ?Fiber, workInProgress : Fiber) { var nextChildren = fn(props, yields); var currentFirstChild = current ? current.stateNode : null; + // Inherit the priority of the parent. + const priority = workInProgress.pendingWorkPriority; workInProgress.stateNode = ReactChildFiber.reconcileChildFibers( workInProgress, currentFirstChild, - nextChildren + nextChildren, + priority ); return workInProgress.stateNode; } diff --git a/src/renderers/shared/fiber/ReactFiberReconciler.js b/src/renderers/shared/fiber/ReactFiberReconciler.js index 5c134bb03b..5a60767613 100644 --- a/src/renderers/shared/fiber/ReactFiberReconciler.js +++ b/src/renderers/shared/fiber/ReactFiberReconciler.js @@ -219,10 +219,9 @@ module.exports = function(config : HostConfig) : Reconciler { return { mountContainer(element : ReactElement, containerInfo : ?Object) : OpaqueNode { - const container = ReactFiber.createHostContainerFiber(containerInfo); + const container = ReactFiber.createHostContainerFiber(containerInfo, LowPriority); container.alternate = container; container.pendingProps = element; - container.pendingWorkPriority = LowPriority; scheduleLowPriWork(container); From 8ad8bd193986e9bd0942f6c8c6ed816a3c58e520 Mon Sep 17 00:00:00 2001 From: Sebastian Markbage Date: Tue, 14 Jun 2016 13:54:54 -0700 Subject: [PATCH 07/19] Automatically downgrade an update to a hidden node This automatically downgrades the priority of a hidden node. Its children won't be reconciled until they come around the next time. --- .../shared/fiber/ReactFiberBeginWork.js | 29 +++++++++++++++++-- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/src/renderers/shared/fiber/ReactFiberBeginWork.js b/src/renderers/shared/fiber/ReactFiberBeginWork.js index 07e6c13227..192a77e4ba 100644 --- a/src/renderers/shared/fiber/ReactFiberBeginWork.js +++ b/src/renderers/shared/fiber/ReactFiberBeginWork.js @@ -27,6 +27,9 @@ var { CoroutineHandlerPhase, YieldComponent, } = ReactTypeOfWork; +var { + OffscreenPriority, +} = require('ReactPriorityLevel'); function reconcileChildren(current, workInProgress, nextChildren) { const priority = workInProgress.pendingWorkPriority; @@ -50,7 +53,28 @@ function updateHostComponent(current, workInProgress) { console.log('host component', workInProgress.type, typeof workInProgress.pendingProps.children === 'string' ? workInProgress.pendingProps.children : ''); var nextChildren = workInProgress.pendingProps.children; - reconcileChildren(current, workInProgress, nextChildren); + + let priority = workInProgress.pendingWorkPriority; + if (workInProgress.pendingProps.hidden && priority !== OffscreenPriority) { + // If this host component is hidden, we can reconcile its children at + // the lowest priority and bail out from this particular pass. Unless, we're + // currently reconciling the lowest priority. + workInProgress.child = ReactChildFiber.reconcileChildFibers( + workInProgress, + current ? current.child : null, + nextChildren, + OffscreenPriority + ); + return null; + } else { + workInProgress.child = ReactChildFiber.reconcileChildFibers( + workInProgress, + current ? current.child : null, + nextChildren, + priority + ); + return workInProgress.child; + } } function mountIndeterminateComponent(current, workInProgress) { @@ -119,8 +143,7 @@ function beginWork(current : ?Fiber, workInProgress : Fiber) : ?Fiber { } return null; case HostComponent: - updateHostComponent(current, workInProgress); - return workInProgress.child; + return updateHostComponent(current, workInProgress); case CoroutineHandlerPhase: // This is a restart. Reset the tag to the initial phase. workInProgress.tag = CoroutineComponent; From 5e65f2f622d2e136a005d6254c84fdb3d4f95cca Mon Sep 17 00:00:00 2001 From: Sebastian Markbage Date: Tue, 14 Jun 2016 19:19:33 -0700 Subject: [PATCH 08/19] Bubble up pending work priority to the top level This is a bit poorly structured. I'll restructure when the pieces are better in place. Basically we reset the priority of a node before work on the children. The children then bump their parent if they end up having work left. This is the first time we're seeing deep updates happening. The new unit test demonstrates this. There is an interesting case that happens when we fall back out of a deep update. We end up "completing" a node that we didn't begin. This probably breaks in coroutines. When that completes, it'll try to render the sibling next but that should bail out so we check for any pending work on the sibling. That one I'm not sure about. --- src/renderers/shared/fiber/ReactFiber.js | 1 + .../shared/fiber/ReactFiberBeginWork.js | 15 ++++ .../shared/fiber/ReactFiberReconciler.js | 88 ++++++++++++++----- .../fiber/__tests__/ReactIncremental-test.js | 51 ++++++++++- 4 files changed, 131 insertions(+), 24 deletions(-) diff --git a/src/renderers/shared/fiber/ReactFiber.js b/src/renderers/shared/fiber/ReactFiber.js index 0dd16c38a0..b7a4d90255 100644 --- a/src/renderers/shared/fiber/ReactFiber.js +++ b/src/renderers/shared/fiber/ReactFiber.js @@ -193,5 +193,6 @@ exports.createFiberFromCoroutine = function(coroutine : ReactCoroutine, priority exports.createFiberFromYield = function(yieldNode : ReactYield, priorityLevel : PriorityLevel) { const fiber = createFiber(YieldComponent, yieldNode.key); + fiber.pendingProps = {}; return fiber; }; diff --git a/src/renderers/shared/fiber/ReactFiberBeginWork.js b/src/renderers/shared/fiber/ReactFiberBeginWork.js index 192a77e4ba..263c5d4899 100644 --- a/src/renderers/shared/fiber/ReactFiberBeginWork.js +++ b/src/renderers/shared/fiber/ReactFiberBeginWork.js @@ -28,6 +28,7 @@ var { YieldComponent, } = ReactTypeOfWork; var { + NoWork, OffscreenPriority, } = require('ReactPriorityLevel'); @@ -47,6 +48,7 @@ function updateFunctionalComponent(current, workInProgress) { console.log('update fn:', fn.name); var nextChildren = fn(props); reconcileChildren(current, workInProgress, nextChildren); + workInProgress.pendingWorkPriority = NoWork; } function updateHostComponent(current, workInProgress) { @@ -65,6 +67,7 @@ function updateHostComponent(current, workInProgress) { nextChildren, OffscreenPriority ); + workInProgress.pendingWorkPriority = OffscreenPriority; return null; } else { workInProgress.child = ReactChildFiber.reconcileChildFibers( @@ -73,6 +76,7 @@ function updateHostComponent(current, workInProgress) { nextChildren, priority ); + workInProgress.pendingWorkPriority = NoWork; return workInProgress.child; } } @@ -85,12 +89,19 @@ function mountIndeterminateComponent(current, workInProgress) { 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; + } } else { console.log('performed work on fn:', fn.name); // Proceed under the assumption that this is a functional component workInProgress.tag = FunctionalComponent; + if (workInProgress.alternate) { + workInProgress.alternate.tag = FunctionalComponent; + } } reconcileChildren(current, workInProgress, value); + workInProgress.pendingWorkPriority = NoWork; } function updateCoroutineComponent(current, workInProgress) { @@ -100,6 +111,7 @@ function updateCoroutineComponent(current, workInProgress) { } console.log('begin coroutine', workInProgress.type.name); reconcileChildren(current, workInProgress, coroutine.children); + workInProgress.pendingWorkPriority = NoWork; } function beginWork(current : ?Fiber, workInProgress : Fiber) : ?Fiber { @@ -114,6 +126,7 @@ function beginWork(current : ?Fiber, workInProgress : Fiber) : ?Fiber { workInProgress.output = current.output; workInProgress.child = current.child; workInProgress.stateNode = current.stateNode; + workInProgress.pendingWorkPriority = NoWork; return null; } if (workInProgress.pendingProps === workInProgress.memoizedProps) { @@ -135,6 +148,7 @@ function beginWork(current : ?Fiber, workInProgress : Fiber) : ?Fiber { reconcileChildren(current, workInProgress, workInProgress.pendingProps); // A yield component is just a placeholder, we can just run through the // next one immediately. + workInProgress.pendingWorkPriority = NoWork; if (workInProgress.child) { return beginWork( workInProgress.child.alternate, @@ -162,6 +176,7 @@ function beginWork(current : ?Fiber, workInProgress : Fiber) : ?Fiber { case YieldComponent: // A yield component is just a placeholder, we can just run through the // next one immediately. + workInProgress.pendingWorkPriority = NoWork; if (workInProgress.sibling) { return beginWork( workInProgress.sibling.alternate, diff --git a/src/renderers/shared/fiber/ReactFiberReconciler.js b/src/renderers/shared/fiber/ReactFiberReconciler.js index 5a60767613..275570c79d 100644 --- a/src/renderers/shared/fiber/ReactFiberReconciler.js +++ b/src/renderers/shared/fiber/ReactFiberReconciler.js @@ -65,7 +65,7 @@ module.exports = function(config : HostConfig) : Reconciler { let currentRootsWithPendingWork : ?Fiber = null; - function findNextUnitOfWork(priorityLevel : PriorityLevel) : ?Fiber { + function findNextUnitOfWorkAtPriority(priorityLevel : PriorityLevel) : ?Fiber { let current = currentRootsWithPendingWork; while (current) { if (current.pendingWorkPriority !== 0 && @@ -74,11 +74,15 @@ module.exports = function(config : HostConfig) : Reconciler { if (current.pendingProps !== null) { // We found some work to do. We need to return the "work in progress" // of this node which will be the alternate. - return current.alternate; + const clone = ReactFiber.cloneFiber(current, current.pendingWorkPriority); + clone.pendingProps = current.pendingProps; + return clone; } // 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) { current = current.child; continue; @@ -106,6 +110,21 @@ module.exports = function(config : HostConfig) : Reconciler { return null; } + function findNextUnitOfWork() { + // Find the highest possible priority work to do. + // This loop is unrolled just to satisfy Flow's enum constraint. + // We could make arbitrary many idle priority levels but having + // too many just means flushing changes too often. + let work = findNextUnitOfWorkAtPriority(HighPriority); + if (!work) { + work = findNextUnitOfWorkAtPriority(LowPriority); + if (!work) { + work = findNextUnitOfWorkAtPriority(OffscreenPriority); + } + } + return work; + } + function completeUnitOfWork(workInProgress : Fiber) : ?Fiber { while (true) { // The current, flushed, state of this fiber is the alternate. @@ -114,29 +133,62 @@ module.exports = function(config : HostConfig) : Reconciler { // progress. const current = workInProgress.alternate; const next = completeWork(current, workInProgress); + + // The work is now done. We don't need this anymore. This flags + // to the system not to redo any work here. + workInProgress.pendingProps = null; + + // TODO: Stop using the parent for this purpose. I think this will break + // down in edge cases because when nodes are reused during bailouts, we + // don't know which of two parents was used. Instead we should maintain + // a temporary manual stack. + // $FlowFixMe: This downcast is not safe. It is intentionally an error. + const parent = workInProgress.parent; + + // Ensure that remaining work priority bubbles up. + if (parent && workInProgress.pendingWorkPriority !== NoWork && + (parent.pendingWorkPriority === NoWork || + parent.pendingWorkPriority > workInProgress.pendingWorkPriority)) { + parent.pendingWorkPriority = workInProgress.pendingWorkPriority; + } + if (next) { // If completing this work spawned new work, do that next. return next; } else if (workInProgress.sibling) { // If there is more work to do in this parent, do that next. return workInProgress.sibling; - } else if (workInProgress.parent) { + } else if (parent) { // If there's no more work in this parent. Complete the parent. - // TODO: Stop using the parent for this purpose. I think this will break - // down in edge cases because when nodes are reused during bailouts, we - // don't know which of two parents was used. Instead we should maintain - // a temporary manual stack. - // $FlowFixMe: This downcast is not safe. It is intentionally an error. - workInProgress = workInProgress.parent; + workInProgress = parent; } else { // If we're at the root, there's no more work to do. - currentRootsWithPendingWork = null; - return null; + console.log('completed flush with remaining work at priority', workInProgress.pendingWorkPriority); + if (workInProgress.pendingWorkPriority !== NoWork) { + // TODO: This removes all but one node. Broken. + currentRootsWithPendingWork = workInProgress; + const nextWork = findNextUnitOfWork(); + if (!nextWork) { + // Something went wrong and there wasn't actually any more work. + // TODO: This currently fails because of the parent/root hacks. + // throw new Error('Should never finish with a priority level unless there is work.'); + currentRootsWithPendingWork = null; + return null; + } + return nextWork; + } else { + currentRootsWithPendingWork = null; + return null; + } } } } function performUnitOfWork(workInProgress : Fiber) : ?Fiber { + // Ignore work if there is nothing to do. + if (workInProgress.pendingProps === null) { + return null; + } // 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 @@ -154,17 +206,7 @@ module.exports = function(config : HostConfig) : Reconciler { function performLowPriWork(deadline : Deadline) { if (!nextUnitOfWork) { - // Find the highest possible priority work to do. - // This loop is unrolled just to satisfy Flow's enum constraint. - // We could make arbitrary many idle priority levels but having - // too many just means flushing changes too often. - nextUnitOfWork = findNextUnitOfWork(HighPriority); - if (!nextUnitOfWork) { - nextUnitOfWork = findNextUnitOfWork(LowPriority); - if (!nextUnitOfWork) { - nextUnitOfWork = findNextUnitOfWork(OffscreenPriority); - } - } + nextUnitOfWork = findNextUnitOfWork(); } while (nextUnitOfWork) { if (deadline.timeRemaining() > timeHeuristicForUnitOfWork) { @@ -236,7 +278,7 @@ module.exports = function(config : HostConfig) : Reconciler { }, unmountContainer(container : OpaqueNode) : void { - container.pendingProps = null; + container.pendingProps = []; container.pendingWorkPriority = LowPriority; scheduleLowPriWork(container); diff --git a/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js b/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js index 224c44dfbf..8b6f537822 100644 --- a/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js +++ b/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js @@ -161,7 +161,56 @@ describe('ReactIncremental', function() { expect(ops).toEqual(['Foo', 'Bar', 'Bar']); - // TODO: Test the ability for a subtree to resume if it has lower priority. + }); + + it('can deprioritize unfinished work and resume it later', function() { + + var ops = []; + + function Bar(props) { + ops.push('Bar'); + return
{props.children}
; + } + + function Middle(props) { + ops.push('Middle'); + return {props.children}; + } + + function Foo(props) { + ops.push('Foo'); + return ( +
+ {props.text} + + {props.text} +
+ ); + } + + // Init + ReactNoop.render(); + ReactNoop.flush(); + + ops = []; + + // Render part of the work. This should be enough to flush everything except + // the middle which has lower priority. + ReactNoop.render(); + ReactNoop.flushLowPri(40); + + expect(ops).toEqual(['Foo', 'Bar', 'Bar']); + + ops = []; + + // Flush only the remaining work + ReactNoop.flush(); + + expect(ops).toEqual(['Middle']); }); From 7d028fd8cc047f4ae3739f9d380bf59640ea8129 Mon Sep 17 00:00:00 2001 From: Sebastian Markbage Date: Wed, 15 Jun 2016 16:06:45 -0700 Subject: [PATCH 09/19] Reorganize the top level around a FiberRoot We need a canonical stateful root for each. I don't really want to overload the HostContainer for this purpose since it makes the fiber code more specialized. Instead I create a root which represents an actual stateful root. When these get scheduled they get chained together in a linked list. However, we don't hold onto anything that doesn't have scheduled work. This will help us release everything automatically in the GC, as long as there are no subscriptions nor scheduled work. --- src/renderers/shared/fiber/ReactFiber.js | 9 +- .../shared/fiber/ReactFiberReconciler.js | 154 +++++++++++------- src/renderers/shared/fiber/ReactFiberRoot.js | 42 +++++ .../fiber/__tests__/ReactIncremental-test.js | 2 + 4 files changed, 142 insertions(+), 65 deletions(-) create mode 100644 src/renderers/shared/fiber/ReactFiberRoot.js diff --git a/src/renderers/shared/fiber/ReactFiber.js b/src/renderers/shared/fiber/ReactFiber.js index b7a4d90255..4bd19709a1 100644 --- a/src/renderers/shared/fiber/ReactFiber.js +++ b/src/renderers/shared/fiber/ReactFiber.js @@ -140,6 +140,11 @@ exports.cloneFiber = function(fiber : Fiber, priorityLevel : PriorityLevel) : Fi // Stop using the alternates of parents once we have a parent stack. // $FlowFixMe: This downcast is not safe. It is intentionally an error. alt.parent = fiber.parent.alternate; + if (!alt.parent) { + // TODO: There needs to be a "work in progress" tree all the way up to + // the final root. + throw new Error('The parent must have an alternate already.'); + } } alt.type = fiber.type; @@ -150,10 +155,8 @@ exports.cloneFiber = function(fiber : Fiber, priorityLevel : PriorityLevel) : Fi return alt; }; -exports.createHostContainerFiber = function(containerInfo : ?Object, priorityLevel : PriorityLevel) { +exports.createHostContainerFiber = function() { const fiber = createFiber(HostContainer, null); - fiber.stateNode = containerInfo; - fiber.pendingWorkPriority = priorityLevel; return fiber; }; diff --git a/src/renderers/shared/fiber/ReactFiberReconciler.js b/src/renderers/shared/fiber/ReactFiberReconciler.js index 275570c79d..07e23fad71 100644 --- a/src/renderers/shared/fiber/ReactFiberReconciler.js +++ b/src/renderers/shared/fiber/ReactFiberReconciler.js @@ -14,10 +14,12 @@ import type { Fiber } from 'ReactFiber'; import type { PriorityLevel } from 'ReactPriorityLevel'; +import type { FiberRoot } from 'ReactFiberRoot'; var ReactFiber = require('ReactFiber'); var { beginWork } = require('ReactFiberBeginWork'); var { completeWork } = require('ReactFiberCompleteWork'); +var { createFiberRoot } = require('ReactFiberRoot'); var { NoWork, @@ -61,12 +63,15 @@ module.exports = function(config : HostConfig) : Reconciler { // const scheduleHighPriCallback = config.scheduleHighPriCallback; const scheduleLowPriCallback = config.scheduleLowPriCallback; + // The next work in progress fiber that we're currently working on. let nextUnitOfWork : ?Fiber = null; - let currentRootsWithPendingWork : ?Fiber = null; + // Linked list of roots with scheduled work on them. + let nextScheduledRoot : ?FiberRoot = null; + let lastScheduledRoot : ?FiberRoot = null; - function findNextUnitOfWorkAtPriority(priorityLevel : PriorityLevel) : ?Fiber { - let current = currentRootsWithPendingWork; + function findNextUnitOfWorkAtPriority(root : FiberRoot, priorityLevel : PriorityLevel) : ?Fiber { + let current = root.current; while (current) { if (current.pendingWorkPriority !== 0 && current.pendingWorkPriority <= priorityLevel) { @@ -84,6 +89,8 @@ module.exports = function(config : HostConfig) : Reconciler { // 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. + ReactFiber.cloneFiber(current, NoWork); current = current.child; continue; } @@ -111,18 +118,38 @@ module.exports = function(config : HostConfig) : Reconciler { } function findNextUnitOfWork() { - // Find the highest possible priority work to do. - // This loop is unrolled just to satisfy Flow's enum constraint. - // We could make arbitrary many idle priority levels but having - // too many just means flushing changes too often. - let work = findNextUnitOfWorkAtPriority(HighPriority); - if (!work) { - work = findNextUnitOfWorkAtPriority(LowPriority); - if (!work) { - work = findNextUnitOfWorkAtPriority(OffscreenPriority); + // Clear out roots with no more work on them. + while (nextScheduledRoot && nextScheduledRoot.current.pendingWorkPriority === NoWork) { + nextScheduledRoot.isScheduled = false; + if (nextScheduledRoot === lastScheduledRoot) { + nextScheduledRoot = null; + lastScheduledRoot = null; + return null; } + nextScheduledRoot = nextScheduledRoot.nextScheduledRoot; } - return work; + let root = nextScheduledRoot; + while (root) { + // Find the highest possible priority work to do. + // This loop is unrolled just to satisfy Flow's enum constraint. + // We could make arbitrary many idle priority levels but having + // too many just means flushing changes too often. + let work = findNextUnitOfWorkAtPriority(root, HighPriority); + if (work) { + return work; + } + work = findNextUnitOfWorkAtPriority(root, LowPriority); + if (work) { + return work; + } + work = findNextUnitOfWorkAtPriority(root, OffscreenPriority); + if (work) { + return work; + } + // We didn't find anything to do in this root, so let's try the next one. + root = root.nextScheduledRoot; + } + return null; } function completeUnitOfWork(workInProgress : Fiber) : ?Fiber { @@ -162,24 +189,19 @@ module.exports = function(config : HostConfig) : Reconciler { // If there's no more work in this parent. Complete the parent. workInProgress = parent; } else { - // If we're at the root, there's no more work to do. - console.log('completed flush with remaining work at priority', workInProgress.pendingWorkPriority); - if (workInProgress.pendingWorkPriority !== NoWork) { - // TODO: This removes all but one node. Broken. - currentRootsWithPendingWork = workInProgress; - const nextWork = findNextUnitOfWork(); - if (!nextWork) { - // Something went wrong and there wasn't actually any more work. - // TODO: This currently fails because of the parent/root hacks. - // throw new Error('Should never finish with a priority level unless there is work.'); - currentRootsWithPendingWork = null; - return null; - } - return nextWork; - } else { - currentRootsWithPendingWork = null; - return null; + // If we're at the root, there's no more work to do. We can flush it. + const root : FiberRoot = (workInProgress.stateNode : any); + root.current = workInProgress; + console.log('completed one root flush with remaining work at priority', workInProgress.pendingWorkPriority); + const hasMoreWork = workInProgress.pendingWorkPriority !== NoWork; + // TODO: We can be smarter here and only look for more work in the + // "next" scheduled work since we've already scanned passed. That + // also ensures that work scheduled during reconciliation gets deferred. + const nextWork = findNextUnitOfWork(); + if (!nextWork && hasMoreWork) { + throw new Error('FiberRoots should not have flagged more work if there is none.'); } + return nextWork; } } } @@ -211,39 +233,36 @@ module.exports = function(config : HostConfig) : Reconciler { while (nextUnitOfWork) { if (deadline.timeRemaining() > timeHeuristicForUnitOfWork) { nextUnitOfWork = performUnitOfWork(nextUnitOfWork); + if (!nextUnitOfWork) { + // Find more work. We might have time to complete some more. + nextUnitOfWork = findNextUnitOfWork(); + } } else { scheduleLowPriCallback(performLowPriWork); - break; + return; } } } - function scheduleLowPriWork(root : Fiber) { + function scheduleLowPriWork(root : FiberRoot) { // We must reset the current unit of work pointer so that we restart the - // search from the root during the next tick. + // search from the root during the next tick, in case there is now higher + // priority work somewhere earlier than before. nextUnitOfWork = null; - if (currentRootsWithPendingWork) { - if (root === currentRootsWithPendingWork) { - // We're already scheduled. - return; - } - // We already have some work pending in another root. Add this to the - // linked list. - let previousSibling = currentRootsWithPendingWork; - while (previousSibling.sibling) { - previousSibling = previousSibling.sibling; - if (root === previousSibling) { - // We're already scheduled. - return; - } - } - previousSibling.sibling = root; + if (root.isScheduled) { + // If we're already scheduled, we can bail out. + return; + } + root.isScheduled = true; + if (lastScheduledRoot) { + // Schedule ourselves to the end. + lastScheduledRoot.nextScheduledRoot = root; + lastScheduledRoot = root; } else { - // We're the first and only root with new changes. - currentRootsWithPendingWork = root; - root.sibling = null; - // Ensure we will get another callback to process the work. + // We're the only work scheduled. + nextScheduledRoot = root; + lastScheduledRoot = root; scheduleLowPriCallback(performLowPriWork); } } @@ -261,27 +280,38 @@ module.exports = function(config : HostConfig) : Reconciler { return { mountContainer(element : ReactElement, containerInfo : ?Object) : OpaqueNode { - const container = ReactFiber.createHostContainerFiber(containerInfo, LowPriority); - container.alternate = container; + const root = createFiberRoot(containerInfo); + const container = root.current; + // TODO: Use pending work/state instead of props. container.pendingProps = element; + container.pendingWorkPriority = LowPriority; - scheduleLowPriWork(container); + scheduleLowPriWork(root); + // It may seem strange that we don't return the root here, but that will + // allow us to have containers that are in the middle of the tree instead + // of being roots. return container; }, updateContainer(element : ReactElement, container : OpaqueNode) : void { - container.pendingProps = element; - container.pendingWorkPriority = LowPriority; + // TODO: If this is a nested container, this won't be the root. + const root : FiberRoot = (container.stateNode : any); + // TODO: Use pending work/state instead of props. + root.current.pendingProps = element; + root.current.pendingWorkPriority = LowPriority; - scheduleLowPriWork(container); + scheduleLowPriWork(root); }, unmountContainer(container : OpaqueNode) : void { - container.pendingProps = []; - container.pendingWorkPriority = LowPriority; + // TODO: If this is a nested container, this won't be the root. + const root : FiberRoot = (container.stateNode : any); + // TODO: Use pending work/state instead of props. + root.current.pendingProps = []; + root.current.pendingWorkPriority = LowPriority; - scheduleLowPriWork(container); + scheduleLowPriWork(root); }, getPublicRootInstance(container : OpaqueNode) : ?Object { diff --git a/src/renderers/shared/fiber/ReactFiberRoot.js b/src/renderers/shared/fiber/ReactFiberRoot.js new file mode 100644 index 0000000000..ce186c3fce --- /dev/null +++ b/src/renderers/shared/fiber/ReactFiberRoot.js @@ -0,0 +1,42 @@ +/** + * 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 ReactFiberRoot + * @flow + */ + +'use strict'; + +import type { Fiber } from 'ReactFiber'; + +const { createHostContainerFiber } = require('ReactFiber'); + +export type FiberRoot = { + // Any additional information from the host associated with this root. + containerInfo: ?Object, + // The currently active root fiber. This is the mutable root of the tree. + current: Fiber, + // Determines if this root has already been added to the schedule for work. + isScheduled: bool, + // The work schedule is a linked list. + nextScheduledRoot: ?FiberRoot, +}; + +exports.createFiberRoot = function(containerInfo : ?Object) : FiberRoot { + // Cyclic construction. This cheats the type system right now because + // stateNode is any. + const uninitializedFiber = createHostContainerFiber(); + const root = { + current: uninitializedFiber, + containerInfo: containerInfo, + isScheduled: false, + nextScheduledRoot: null, + }; + uninitializedFiber.stateNode = root; + return root; +}; diff --git a/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js b/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js index 8b6f537822..c39b06b862 100644 --- a/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js +++ b/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js @@ -196,6 +196,8 @@ describe('ReactIncremental', function() { ReactNoop.render(); ReactNoop.flush(); + expect(ops).toEqual(['Foo', 'Bar', 'Bar', 'Middle']); + ops = []; // Render part of the work. This should be enough to flush everything except From 986c63c6d4a808f0f3108bb9610803c11f04ed47 Mon Sep 17 00:00:00 2001 From: Sebastian Markbage Date: Wed, 15 Jun 2016 16:30:59 -0700 Subject: [PATCH 10/19] Extract scheduler into its own module The scheduler is getting quite complicated. I'll extract it into its own module. --- .../shared/fiber/ReactFiberReconciler.js | 227 +--------------- .../shared/fiber/ReactFiberScheduler.js | 255 ++++++++++++++++++ 2 files changed, 257 insertions(+), 225 deletions(-) create mode 100644 src/renderers/shared/fiber/ReactFiberScheduler.js diff --git a/src/renderers/shared/fiber/ReactFiberReconciler.js b/src/renderers/shared/fiber/ReactFiberReconciler.js index 07e23fad71..3fde615cf0 100644 --- a/src/renderers/shared/fiber/ReactFiberReconciler.js +++ b/src/renderers/shared/fiber/ReactFiberReconciler.js @@ -13,19 +13,13 @@ 'use strict'; import type { Fiber } from 'ReactFiber'; -import type { PriorityLevel } from 'ReactPriorityLevel'; import type { FiberRoot } from 'ReactFiberRoot'; -var ReactFiber = require('ReactFiber'); -var { beginWork } = require('ReactFiberBeginWork'); -var { completeWork } = require('ReactFiberCompleteWork'); var { createFiberRoot } = require('ReactFiberRoot'); +var ReactFiberScheduler = require('ReactFiberScheduler'); var { - NoWork, - HighPriority, LowPriority, - OffscreenPriority, } = require('ReactPriorityLevel'); type ReactHostElement = { @@ -37,8 +31,6 @@ type Deadline = { timeRemaining : () => number }; -var timeHeuristicForUnitOfWork = 1; - export type HostConfig = { createHostInstance(element : ReactHostElement) : I, @@ -60,222 +52,7 @@ export type Reconciler = { module.exports = function(config : HostConfig) : Reconciler { - // const scheduleHighPriCallback = config.scheduleHighPriCallback; - const scheduleLowPriCallback = config.scheduleLowPriCallback; - - // The next work in progress fiber that we're currently working on. - let nextUnitOfWork : ?Fiber = null; - - // Linked list of roots with scheduled work on them. - let nextScheduledRoot : ?FiberRoot = null; - let lastScheduledRoot : ?FiberRoot = null; - - function findNextUnitOfWorkAtPriority(root : FiberRoot, priorityLevel : PriorityLevel) : ?Fiber { - let current = root.current; - while (current) { - if (current.pendingWorkPriority !== 0 && - current.pendingWorkPriority <= priorityLevel) { - // This node has work to do that fits our priority level criteria. - if (current.pendingProps !== null) { - // We found some work to do. We need to return the "work in progress" - // of this node which will be the alternate. - const clone = ReactFiber.cloneFiber(current, current.pendingWorkPriority); - clone.pendingProps = current.pendingProps; - return clone; - } - // 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. - ReactFiber.cloneFiber(current, NoWork); - current = current.child; - continue; - } - // If we match the priority but has no child and no work to do, - // then we can safely reset the flag. - current.pendingWorkPriority = NoWork; - } - while (!current.sibling) { - // TODO: Stop using parent here. See below. - // $FlowFixMe: This downcast is not safe. It is intentionally an error. - current = current.parent; - if (!current) { - return null; - } - if (current.pendingWorkPriority <= priorityLevel) { - // If this subtree had work left to do, we would have returned it by - // now. This could happen if a child with pending work gets cleaned up - // but we don't clear the flag then. It is safe to reset it now. - current.pendingWorkPriority = NoWork; - } - } - current = current.sibling; - } - return null; - } - - function findNextUnitOfWork() { - // Clear out roots with no more work on them. - while (nextScheduledRoot && nextScheduledRoot.current.pendingWorkPriority === NoWork) { - nextScheduledRoot.isScheduled = false; - if (nextScheduledRoot === lastScheduledRoot) { - nextScheduledRoot = null; - lastScheduledRoot = null; - return null; - } - nextScheduledRoot = nextScheduledRoot.nextScheduledRoot; - } - let root = nextScheduledRoot; - while (root) { - // Find the highest possible priority work to do. - // This loop is unrolled just to satisfy Flow's enum constraint. - // We could make arbitrary many idle priority levels but having - // too many just means flushing changes too often. - let work = findNextUnitOfWorkAtPriority(root, HighPriority); - if (work) { - return work; - } - work = findNextUnitOfWorkAtPriority(root, LowPriority); - if (work) { - return work; - } - work = findNextUnitOfWorkAtPriority(root, OffscreenPriority); - if (work) { - return work; - } - // We didn't find anything to do in this root, so let's try the next one. - root = root.nextScheduledRoot; - } - return null; - } - - function completeUnitOfWork(workInProgress : Fiber) : ?Fiber { - while (true) { - // The current, flushed, state of this fiber is the alternate. - // Ideally nothing should rely on this, but relying on it here - // means that we don't need an additional field on the work in - // progress. - const current = workInProgress.alternate; - const next = completeWork(current, workInProgress); - - // The work is now done. We don't need this anymore. This flags - // to the system not to redo any work here. - workInProgress.pendingProps = null; - - // TODO: Stop using the parent for this purpose. I think this will break - // down in edge cases because when nodes are reused during bailouts, we - // don't know which of two parents was used. Instead we should maintain - // a temporary manual stack. - // $FlowFixMe: This downcast is not safe. It is intentionally an error. - const parent = workInProgress.parent; - - // Ensure that remaining work priority bubbles up. - if (parent && workInProgress.pendingWorkPriority !== NoWork && - (parent.pendingWorkPriority === NoWork || - parent.pendingWorkPriority > workInProgress.pendingWorkPriority)) { - parent.pendingWorkPriority = workInProgress.pendingWorkPriority; - } - - if (next) { - // If completing this work spawned new work, do that next. - return next; - } else if (workInProgress.sibling) { - // If there is more work to do in this parent, do that next. - return workInProgress.sibling; - } else if (parent) { - // If there's no more work in this parent. Complete the parent. - workInProgress = parent; - } else { - // If we're at the root, there's no more work to do. We can flush it. - const root : FiberRoot = (workInProgress.stateNode : any); - root.current = workInProgress; - console.log('completed one root flush with remaining work at priority', workInProgress.pendingWorkPriority); - const hasMoreWork = workInProgress.pendingWorkPriority !== NoWork; - // TODO: We can be smarter here and only look for more work in the - // "next" scheduled work since we've already scanned passed. That - // also ensures that work scheduled during reconciliation gets deferred. - const nextWork = findNextUnitOfWork(); - if (!nextWork && hasMoreWork) { - throw new Error('FiberRoots should not have flagged more work if there is none.'); - } - return nextWork; - } - } - } - - function performUnitOfWork(workInProgress : Fiber) : ?Fiber { - // Ignore work if there is nothing to do. - if (workInProgress.pendingProps === null) { - return null; - } - // The current, flushed, state of this fiber is the alternate. - // Ideally nothing should rely on this, but relying on it here - // means that we don't need an additional field on the work in - // progress. - const current = workInProgress.alternate; - const next = beginWork(current, workInProgress); - if (next) { - // If this spawns new work, do that next. - return next; - } else { - // Otherwise, complete the current work. - return completeUnitOfWork(workInProgress); - } - } - - function performLowPriWork(deadline : Deadline) { - if (!nextUnitOfWork) { - nextUnitOfWork = findNextUnitOfWork(); - } - while (nextUnitOfWork) { - if (deadline.timeRemaining() > timeHeuristicForUnitOfWork) { - nextUnitOfWork = performUnitOfWork(nextUnitOfWork); - if (!nextUnitOfWork) { - // Find more work. We might have time to complete some more. - nextUnitOfWork = findNextUnitOfWork(); - } - } else { - scheduleLowPriCallback(performLowPriWork); - return; - } - } - } - - function scheduleLowPriWork(root : FiberRoot) { - // 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 (root.isScheduled) { - // If we're already scheduled, we can bail out. - return; - } - root.isScheduled = true; - if (lastScheduledRoot) { - // Schedule ourselves to the end. - lastScheduledRoot.nextScheduledRoot = root; - lastScheduledRoot = root; - } else { - // We're the only work scheduled. - nextScheduledRoot = root; - lastScheduledRoot = root; - scheduleLowPriCallback(performLowPriWork); - } - } - - /* - function performHighPriWork() { - // There is no such thing as high pri work yet. - } - - function ensureHighPriIsScheduled() { - scheduleHighPriCallback(performHighPriWork); - } - */ + var { scheduleLowPriWork } = ReactFiberScheduler(config); return { diff --git a/src/renderers/shared/fiber/ReactFiberScheduler.js b/src/renderers/shared/fiber/ReactFiberScheduler.js new file mode 100644 index 0000000000..c11d9b382e --- /dev/null +++ b/src/renderers/shared/fiber/ReactFiberScheduler.js @@ -0,0 +1,255 @@ +/** + * 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 ReactFiberScheduler + * @flow + */ + +'use strict'; + +import type { Fiber } from 'ReactFiber'; +import type { PriorityLevel } from 'ReactPriorityLevel'; +import type { FiberRoot } from 'ReactFiberRoot'; +import type { HostConfig } from 'ReactFiberReconciler'; + +var ReactFiber = require('ReactFiber'); +var { beginWork } = require('ReactFiberBeginWork'); +var { completeWork } = require('ReactFiberCompleteWork'); + +var { + NoWork, + HighPriority, + LowPriority, + OffscreenPriority, +} = require('ReactPriorityLevel'); + +var timeHeuristicForUnitOfWork = 1; + +module.exports = function(config : HostConfig) { + + // const scheduleHighPriCallback = config.scheduleHighPriCallback; + const scheduleLowPriCallback = config.scheduleLowPriCallback; + + // The next work in progress fiber that we're currently working on. + let nextUnitOfWork : ?Fiber = null; + + // Linked list of roots with scheduled work on them. + let nextScheduledRoot : ?FiberRoot = null; + let lastScheduledRoot : ?FiberRoot = null; + + function findNextUnitOfWorkAtPriority(root : FiberRoot, priorityLevel : PriorityLevel) : ?Fiber { + let current = root.current; + while (current) { + if (current.pendingWorkPriority !== 0 && + current.pendingWorkPriority <= priorityLevel) { + // This node has work to do that fits our priority level criteria. + if (current.pendingProps !== null) { + // We found some work to do. We need to return the "work in progress" + // of this node which will be the alternate. + const clone = ReactFiber.cloneFiber(current, current.pendingWorkPriority); + clone.pendingProps = current.pendingProps; + return clone; + } + // 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. + ReactFiber.cloneFiber(current, NoWork); + current = current.child; + continue; + } + // If we match the priority but has no child and no work to do, + // then we can safely reset the flag. + current.pendingWorkPriority = NoWork; + } + while (!current.sibling) { + // TODO: Stop using parent here. See below. + // $FlowFixMe: This downcast is not safe. It is intentionally an error. + current = current.parent; + if (!current) { + return null; + } + if (current.pendingWorkPriority <= priorityLevel) { + // If this subtree had work left to do, we would have returned it by + // now. This could happen if a child with pending work gets cleaned up + // but we don't clear the flag then. It is safe to reset it now. + current.pendingWorkPriority = NoWork; + } + } + current = current.sibling; + } + return null; + } + + function findNextUnitOfWork() { + // Clear out roots with no more work on them. + while (nextScheduledRoot && nextScheduledRoot.current.pendingWorkPriority === NoWork) { + nextScheduledRoot.isScheduled = false; + if (nextScheduledRoot === lastScheduledRoot) { + nextScheduledRoot = null; + lastScheduledRoot = null; + return null; + } + nextScheduledRoot = nextScheduledRoot.nextScheduledRoot; + } + let root = nextScheduledRoot; + while (root) { + // Find the highest possible priority work to do. + // This loop is unrolled just to satisfy Flow's enum constraint. + // We could make arbitrary many idle priority levels but having + // too many just means flushing changes too often. + let work = findNextUnitOfWorkAtPriority(root, HighPriority); + if (work) { + return work; + } + work = findNextUnitOfWorkAtPriority(root, LowPriority); + if (work) { + return work; + } + work = findNextUnitOfWorkAtPriority(root, OffscreenPriority); + if (work) { + return work; + } + // We didn't find anything to do in this root, so let's try the next one. + root = root.nextScheduledRoot; + } + return null; + } + + function completeUnitOfWork(workInProgress : Fiber) : ?Fiber { + while (true) { + // The current, flushed, state of this fiber is the alternate. + // Ideally nothing should rely on this, but relying on it here + // means that we don't need an additional field on the work in + // progress. + const current = workInProgress.alternate; + const next = completeWork(current, workInProgress); + + // The work is now done. We don't need this anymore. This flags + // to the system not to redo any work here. + workInProgress.pendingProps = null; + + // TODO: Stop using the parent for this purpose. I think this will break + // down in edge cases because when nodes are reused during bailouts, we + // don't know which of two parents was used. Instead we should maintain + // a temporary manual stack. + // $FlowFixMe: This downcast is not safe. It is intentionally an error. + const parent = workInProgress.parent; + + // Ensure that remaining work priority bubbles up. + if (parent && workInProgress.pendingWorkPriority !== NoWork && + (parent.pendingWorkPriority === NoWork || + parent.pendingWorkPriority > workInProgress.pendingWorkPriority)) { + parent.pendingWorkPriority = workInProgress.pendingWorkPriority; + } + + if (next) { + // If completing this work spawned new work, do that next. + return next; + } else if (workInProgress.sibling) { + // If there is more work to do in this parent, do that next. + return workInProgress.sibling; + } else if (parent) { + // If there's no more work in this parent. Complete the parent. + workInProgress = parent; + } else { + // If we're at the root, there's no more work to do. We can flush it. + const root : FiberRoot = (workInProgress.stateNode : any); + root.current = workInProgress; + console.log('completed one root flush with remaining work at priority', workInProgress.pendingWorkPriority); + const hasMoreWork = workInProgress.pendingWorkPriority !== NoWork; + // TODO: We can be smarter here and only look for more work in the + // "next" scheduled work since we've already scanned passed. That + // also ensures that work scheduled during reconciliation gets deferred. + const nextWork = findNextUnitOfWork(); + if (!nextWork && hasMoreWork) { + throw new Error('FiberRoots should not have flagged more work if there is none.'); + } + return nextWork; + } + } + } + + function performUnitOfWork(workInProgress : Fiber) : ?Fiber { + // Ignore work if there is nothing to do. + if (workInProgress.pendingProps === null) { + return null; + } + // The current, flushed, state of this fiber is the alternate. + // Ideally nothing should rely on this, but relying on it here + // means that we don't need an additional field on the work in + // progress. + const current = workInProgress.alternate; + const next = beginWork(current, workInProgress); + if (next) { + // If this spawns new work, do that next. + return next; + } else { + // Otherwise, complete the current work. + return completeUnitOfWork(workInProgress); + } + } + + function performLowPriWork(deadline) { + if (!nextUnitOfWork) { + nextUnitOfWork = findNextUnitOfWork(); + } + while (nextUnitOfWork) { + if (deadline.timeRemaining() > timeHeuristicForUnitOfWork) { + nextUnitOfWork = performUnitOfWork(nextUnitOfWork); + if (!nextUnitOfWork) { + // Find more work. We might have time to complete some more. + nextUnitOfWork = findNextUnitOfWork(); + } + } else { + scheduleLowPriCallback(performLowPriWork); + return; + } + } + } + + function scheduleLowPriWork(root : FiberRoot) { + // 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 (root.isScheduled) { + // If we're already scheduled, we can bail out. + return; + } + root.isScheduled = true; + if (lastScheduledRoot) { + // Schedule ourselves to the end. + lastScheduledRoot.nextScheduledRoot = root; + lastScheduledRoot = root; + } else { + // We're the only work scheduled. + nextScheduledRoot = root; + lastScheduledRoot = root; + scheduleLowPriCallback(performLowPriWork); + } + } + + /* + function performHighPriWork() { + // There is no such thing as high pri work yet. + } + + function ensureHighPriIsScheduled() { + scheduleHighPriCallback(performHighPriWork); + } + */ + + return { + scheduleLowPriWork: scheduleLowPriWork, + }; +}; From 97cd8e179aea9a12e343af6864e0e5994e40a8fc Mon Sep 17 00:00:00 2001 From: Sebastian Markbage Date: Thu, 16 Jun 2016 18:21:22 -0700 Subject: [PATCH 11/19] Attack of the Clones! This fixes some bugs with the clones and traversing backwards through them. It is important that we maintain the correct parent at all times and that clones have the correct values. We need to carefully clone everything on the way up to the the fiber with the next work to do. This code is a bit messy and fragile now. I'm sure I didn't get it all right but I want to get the basics in place first. Then we can structure this part better. I think the general algorithm is sound though. --- src/renderers/shared/fiber/ReactChildFiber.js | 2 + src/renderers/shared/fiber/ReactFiber.js | 38 ++++++++------- .../shared/fiber/ReactFiberBeginWork.js | 3 ++ .../shared/fiber/ReactFiberScheduler.js | 47 +++++++++++++++---- .../fiber/__tests__/ReactIncremental-test.js | 13 ++--- 5 files changed, 69 insertions(+), 34 deletions(-) diff --git a/src/renderers/shared/fiber/ReactChildFiber.js b/src/renderers/shared/fiber/ReactChildFiber.js index f0966e518c..ce853c5a54 100644 --- a/src/renderers/shared/fiber/ReactChildFiber.js +++ b/src/renderers/shared/fiber/ReactChildFiber.js @@ -46,6 +46,7 @@ function createSubsequentChild(parent : Fiber, existingChild : ?Fiber, previousS clone.pendingProps = element.props; clone.child = existingChild.child; clone.sibling = null; + clone.parent = parent; previousSibling.sibling = clone; return clone; } @@ -108,6 +109,7 @@ function createFirstChild(parent, existingChild, newChildren, priority) { clone.pendingProps = element.props; clone.child = existingChild.child; clone.sibling = null; + clone.parent = parent; return clone; } const child = ReactFiber.createFiberFromElement(element, priority); diff --git a/src/renderers/shared/fiber/ReactFiber.js b/src/renderers/shared/fiber/ReactFiber.js index 4bd19709a1..024d1e5c78 100644 --- a/src/renderers/shared/fiber/ReactFiber.js +++ b/src/renderers/shared/fiber/ReactFiber.js @@ -82,6 +82,10 @@ export type Fiber = Instance & { // memory if we need to. alternate: ?Fiber, + // Conceptual aliases + // parent : Instance -> returnFiber The parent happens to be the same as the return fiber. + // workInProgress : Fiber -> alternate The alternate used for reuse happens to be the same as work in progress. + }; var createFiber = function(tag : TypeOfWork, key : null | string) : Fiber { @@ -128,29 +132,27 @@ exports.cloneFiber = function(fiber : Fiber, priorityLevel : PriorityLevel) : Fi // that we're free to reuse. This is lazily created to avoid allocating extra // objects for things that are never updated. It also allow us to reclaim the // extra memory if needed. - if (fiber.alternate) { - fiber.alternate.pendingWorkPriority = priorityLevel; - return fiber.alternate; + let alt = fiber.alternate; + if (alt) { + alt.stateNode = fiber.stateNode; + alt.child = fiber.child; + alt.sibling = fiber.sibling; + alt.ref = alt.ref; + alt.pendingProps = fiber.pendingProps; + alt.pendingWorkPriority = priorityLevel; + return alt; } + // This should not have an alternate already - var alt = createFiber(fiber.tag, fiber.key); - - if (fiber.parent) { - // TODO: This assumes the parent's alternate is already created. - // Stop using the alternates of parents once we have a parent stack. - // $FlowFixMe: This downcast is not safe. It is intentionally an error. - alt.parent = fiber.parent.alternate; - if (!alt.parent) { - // TODO: There needs to be a "work in progress" tree all the way up to - // the final root. - throw new Error('The parent must have an alternate already.'); - } - } - + alt = createFiber(fiber.tag, fiber.key); alt.type = fiber.type; alt.stateNode = fiber.stateNode; - alt.alternate = fiber; + alt.child = fiber.child; + alt.sibling = fiber.sibling; + alt.ref = alt.ref; alt.pendingWorkPriority = priorityLevel; + + alt.alternate = fiber; fiber.alternate = alt; return alt; }; diff --git a/src/renderers/shared/fiber/ReactFiberBeginWork.js b/src/renderers/shared/fiber/ReactFiberBeginWork.js index 263c5d4899..91d63ef481 100644 --- a/src/renderers/shared/fiber/ReactFiberBeginWork.js +++ b/src/renderers/shared/fiber/ReactFiberBeginWork.js @@ -125,6 +125,9 @@ function beginWork(current : ?Fiber, workInProgress : Fiber) : ?Fiber { // and children from that node. workInProgress.output = current.output; workInProgress.child = current.child; + if (workInProgress.child) { + workInProgress.child.parent = workInProgress; + } workInProgress.stateNode = current.stateNode; workInProgress.pendingWorkPriority = NoWork; return null; diff --git a/src/renderers/shared/fiber/ReactFiberScheduler.js b/src/renderers/shared/fiber/ReactFiberScheduler.js index c11d9b382e..eb8dcae0d6 100644 --- a/src/renderers/shared/fiber/ReactFiberScheduler.js +++ b/src/renderers/shared/fiber/ReactFiberScheduler.js @@ -42,8 +42,21 @@ module.exports = function(config : HostConfig) { let nextScheduledRoot : ?FiberRoot = null; let lastScheduledRoot : ?FiberRoot = null; + function cloneSiblings(current : Fiber, workInProgress : Fiber, parent : Fiber) { + while (current.sibling) { + current = current.sibling; + workInProgress = workInProgress.sibling = ReactFiber.cloneFiber( + current, + current.pendingWorkPriority + ); + workInProgress.parent = parent; + } + workInProgress.sibling = null; + } + function findNextUnitOfWorkAtPriority(root : FiberRoot, priorityLevel : PriorityLevel) : ?Fiber { let current = root.current; + ReactFiber.cloneFiber(current, current.pendingWorkPriority); while (current) { if (current.pendingWorkPriority !== 0 && current.pendingWorkPriority <= priorityLevel) { @@ -51,9 +64,12 @@ module.exports = function(config : HostConfig) { if (current.pendingProps !== null) { // We found some work to do. We need to return the "work in progress" // of this node which will be the alternate. - const clone = ReactFiber.cloneFiber(current, current.pendingWorkPriority); - clone.pendingProps = current.pendingProps; - return clone; + const workInProgress = current.alternate; + if (!workInProgress) { + throw new Error('Should have wip now'); + } + workInProgress.pendingProps = current.pendingProps; + return workInProgress; } // If we have a child let's see if any of our children has work to do. // Only bother doing this at all if the current priority level matches @@ -62,7 +78,15 @@ module.exports = function(config : HostConfig) { // type of child that needs to be searched for work. if (current.child) { // Ensure we have a work in progress copy to backtrack through. - ReactFiber.cloneFiber(current, NoWork); + let currentChild = current.child; + let workInProgress = current.alternate; + if (!workInProgress) { + throw new Error('Should have wip now'); + } + workInProgress.pendingWorkPriority = current.pendingWorkPriority; + workInProgress.child = ReactFiber.cloneFiber(currentChild, NoWork); + workInProgress.child.parent = workInProgress; + cloneSiblings(currentChild, workInProgress.child, workInProgress); current = current.child; continue; } @@ -164,15 +188,18 @@ module.exports = function(config : HostConfig) { // If we're at the root, there's no more work to do. We can flush it. const root : FiberRoot = (workInProgress.stateNode : any); root.current = workInProgress; - console.log('completed one root flush with remaining work at priority', workInProgress.pendingWorkPriority); - const hasMoreWork = workInProgress.pendingWorkPriority !== NoWork; // TODO: We can be smarter here and only look for more work in the // "next" scheduled work since we've already scanned passed. That // also ensures that work scheduled during reconciliation gets deferred. + // const hasMoreWork = workInProgress.pendingWorkPriority !== NoWork; const nextWork = findNextUnitOfWork(); - if (!nextWork && hasMoreWork) { - throw new Error('FiberRoots should not have flagged more work if there is none.'); - } + // if (!nextWork && hasMoreWork) { + // TODO: This can happen when some deep work completes and we don't + // know if this was the last one. We should be able to keep track of + // the highest priority still in the tree for one pass. But if we + // terminate an update we don't know. + // throw new Error('FiberRoots should not have flagged more work if there is none.'); + // } return nextWork; } } @@ -181,7 +208,7 @@ module.exports = function(config : HostConfig) { function performUnitOfWork(workInProgress : Fiber) : ?Fiber { // Ignore work if there is nothing to do. if (workInProgress.pendingProps === null) { - return null; + return completeUnitOfWork(workInProgress); } // The current, flushed, state of this fiber is the alternate. // Ideally nothing should rely on this, but relying on it here diff --git a/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js b/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js index c39b06b862..1ae92c3af2 100644 --- a/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js +++ b/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js @@ -182,12 +182,13 @@ describe('ReactIncremental', function() { return (
{props.text} - + {props.text} +
+ Footer +
); } @@ -196,7 +197,7 @@ describe('ReactIncremental', function() { ReactNoop.render(); ReactNoop.flush(); - expect(ops).toEqual(['Foo', 'Bar', 'Bar', 'Middle']); + expect(ops).toEqual(['Foo', 'Bar', 'Bar', 'Middle', 'Middle']); ops = []; @@ -212,7 +213,7 @@ describe('ReactIncremental', function() { // Flush only the remaining work ReactNoop.flush(); - expect(ops).toEqual(['Middle']); + expect(ops).toEqual(['Middle', 'Middle']); }); From 285e661757899efca112ae30a6e7d529abf58d54 Mon Sep 17 00:00:00 2001 From: Sebastian Markbage Date: Sat, 18 Jun 2016 21:39:20 -0700 Subject: [PATCH 12/19] dumpTree helper for debugging It is helpful to be able to dump information about the current tree for debugging issues in unit tests. --- src/renderers/noop/ReactNoop.js | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/src/renderers/noop/ReactNoop.js b/src/renderers/noop/ReactNoop.js index 723f7fad98..311fd5a198 100644 --- a/src/renderers/noop/ReactNoop.js +++ b/src/renderers/noop/ReactNoop.js @@ -19,6 +19,8 @@ 'use strict'; +import type { Fiber } from 'ReactFiber'; + var ReactFiberReconciler = require('ReactFiberReconciler'); var scheduledHighPriCallback = null; @@ -83,6 +85,35 @@ var ReactNoop = { ReactNoop.flushLowPri(); }, + // Logs the current state of the tree. + dumpTree() { + if (!root) { + console.log('Nothing rendered yet.'); + return; + } + let fiber : Fiber = (root.stateNode : any).current; + let depth = 0; + while (fiber) { + console.log(' '.repeat(depth) + '- ' + (fiber.type ? fiber.type.name || fiber.type : '[root]'), '[' + fiber.pendingWorkPriority + (fiber.pendingProps ? '*' : '') + ']'); + if (fiber.child) { + fiber = fiber.child; + depth++; + continue; + } else { + while (!fiber.sibling) { + if (!fiber.parent) { + return; + } else { + // $FlowFixMe: This downcast is not safe. It is intentionally an error. + fiber = fiber.parent; + } + depth--; + } + fiber = fiber.sibling; + } + } + }, + }; module.exports = ReactNoop; From 5971411e873ac777adb6e3c458720ba1499f9dce Mon Sep 17 00:00:00 2001 From: Sebastian Markbage Date: Sun, 19 Jun 2016 00:02:01 -0700 Subject: [PATCH 13/19] Don't block deep low pri updates when bailing out First I fix a bug where host components didn't properly bail out although this was unobservable. When we bail out, we need to ensure that we preserve the highest remaining priority work that is left to do for that subtree. This still isn't properly handling the case when that work has the *same* priority as the current one. That work will be flushed the *next* tick instead of the current pass. I can't create a test for that yet since I need setState to get to that state. --- .../shared/fiber/ReactFiberBeginWork.js | 33 +++++++-- .../shared/fiber/ReactFiberCompleteWork.js | 1 + .../shared/fiber/ReactFiberScheduler.js | 5 ++ .../fiber/__tests__/ReactIncremental-test.js | 70 ++++++++++++++++++- 4 files changed, 103 insertions(+), 6 deletions(-) diff --git a/src/renderers/shared/fiber/ReactFiberBeginWork.js b/src/renderers/shared/fiber/ReactFiberBeginWork.js index 91d63ef481..6c16a503c6 100644 --- a/src/renderers/shared/fiber/ReactFiberBeginWork.js +++ b/src/renderers/shared/fiber/ReactFiberBeginWork.js @@ -114,6 +114,26 @@ function updateCoroutineComponent(current, workInProgress) { workInProgress.pendingWorkPriority = NoWork; } +function reuseChildren(newParent : Fiber, firstChild : Fiber) { + // TODO: None of this should be necessary if structured better. + // The parent pointer only needs to be updated when we walk into this child + // which we don't do right now. If the pending work priority indicated only + // if a child has work rather than if the node has work, then we would know + // by a single lookup on workInProgress rather than having to go through + // each child. + let child = firstChild; + do { + // Update the parent of the child to the newest fiber. + child.parent = newParent; + // Retain the priority if there's any work left to do in the children. + if (child.pendingWorkPriority !== NoWork && + (newParent.pendingWorkPriority === NoWork || + newParent.pendingWorkPriority > child.pendingWorkPriority)) { + newParent.pendingWorkPriority = child.pendingWorkPriority; + } + } while (child = child.sibling); +} + function beginWork(current : ?Fiber, workInProgress : Fiber) : ?Fiber { // The current, flushed, state of this fiber is the alternate. // Ideally nothing should rely on this, but relying on it here @@ -123,18 +143,23 @@ function beginWork(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; - workInProgress.child = current.child; - if (workInProgress.child) { - workInProgress.child.parent = workInProgress; + workInProgress.pendingWorkPriority = NoWork; + if (current.child) { + workInProgress.child = current.child; + reuseChildren(workInProgress, workInProgress.child); + } else { + workInProgress.child = null; } workInProgress.stateNode = current.stateNode; - workInProgress.pendingWorkPriority = NoWork; return null; } if (workInProgress.pendingProps === workInProgress.memoizedProps) { // In a ping-pong scenario, this version could actually contain the // old props. In that case, we can just bail out. + // TODO: I don't yet quite understand what should happen on the + // reused node here. return null; } switch (workInProgress.tag) { diff --git a/src/renderers/shared/fiber/ReactFiberCompleteWork.js b/src/renderers/shared/fiber/ReactFiberCompleteWork.js index 49ad5c1b2c..d59caa79c3 100644 --- a/src/renderers/shared/fiber/ReactFiberCompleteWork.js +++ b/src/renderers/shared/fiber/ReactFiberCompleteWork.js @@ -107,6 +107,7 @@ exports.completeWork = function(current : ?Fiber, workInProgress : Fiber) : ?Fib case HostContainer: return null; case HostComponent: + transferOutput(workInProgress.child, workInProgress); console.log('/host component', workInProgress.type); return null; case CoroutineComponent: diff --git a/src/renderers/shared/fiber/ReactFiberScheduler.js b/src/renderers/shared/fiber/ReactFiberScheduler.js index eb8dcae0d6..4b5217b611 100644 --- a/src/renderers/shared/fiber/ReactFiberScheduler.js +++ b/src/renderers/shared/fiber/ReactFiberScheduler.js @@ -157,6 +157,10 @@ module.exports = function(config : HostConfig) { const current = workInProgress.alternate; const next = completeWork(current, workInProgress); + // TODO: If workInProgress returns null but still has work with the + // current priority in its subtree, we need to go find it right now. + // If we don't, we won't flush it until the next tick. + // 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; @@ -192,6 +196,7 @@ 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); const nextWork = findNextUnitOfWork(); // if (!nextWork && hasMoreWork) { // TODO: This can happen when some deep work completes and we don't diff --git a/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js b/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js index 1ae92c3af2..daf81f54ec 100644 --- a/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js +++ b/src/renderers/shared/fiber/__tests__/ReactIncremental-test.js @@ -109,6 +109,8 @@ describe('ReactIncremental', function() { ReactNoop.render(); ReactNoop.flush(); + // TODO: Test bail out of host components. This is currently unobservable. + // Since this is an update, it should bail out and reuse the work from // Header and Content. expect(ops).toEqual(['Foo', 'Content']); @@ -182,9 +184,9 @@ describe('ReactIncremental', function() { return (
{props.text} -