* react-test-renderer injects itself into DevTools if present
* Fibers are always opted into ProfileMode if DevTools is present
* Added simple test for DevTools + always profiling behavior
* Do not add additional work to a batch that is already rendering.
Otherwise, the part of the tree that hasn't rendered yet will receive
the latest state, but the already rendered part will show the state
as it was before the intervening update.
* Reduce non-helpfulness of comments
Expiration times are computed by adding to the current time (the start
time). However, if two updates are scheduled within the same event, we
should treat their start times as simultaneous, even if the actual clock
time has advanced between the first and second call.
In other words, because expiration times determine how updates are
batched, we want all updates of like priority that occur within the same
event to receive the same expiration time. Otherwise we get tearing.
We keep track of two separate times: the current "renderer" time and the
current "scheduler" time. The renderer time can be updated whenever; it
only exists to minimize the calls performance.now.
But the scheduler time can only be updated if there's no pending work,
or if we know for certain that we're not in the middle of an event.
* Inline fbjs/lib/emptyObject
* Explicit naming
* Compare to undefined
* Another approach for detecting whether we can mutate
Each renderer would have its own local LegacyRefsObject function.
While in general we don't want `instanceof`, here it lets us do a simple check: did *we* create the refs object?
Then we can mutate it.
If the check didn't pass, either we're attaching ref for the first time (so we know to use the constructor),
or (unlikely) we're attaching a ref to a component owned by another renderer. In this case, to avoid "losing"
refs, we assign them onto the new object. Even in that case it shouldn't "hop" between renderers anymore.
* Clearer naming
* Add test case for strings refs across renderers
* Use a shared empty object for refs by reading it from React
* Remove string refs from ReactART test
It's not currently possible to resetModules() between several renderers
without also resetting the `React` module. However, that leads to losing
the referential identity of the empty ref object, and thus subsequent
checks in the renderers for whether it is pooled fail (and cause assignments
to a frozen object).
This has always been the case, but we used to work around it by shimming
fbjs/lib/emptyObject in tests and preserving its referential identity.
This won't work anymore because we've inlined it. And preserving referential
identity of React itself wouldn't be great because it could be confusing during
testing (although we might want to revisit this in the future by moving its
stateful parts into a separate package).
For now, I'm removing string ref usage from this test because only this is
the only place in our tests where we hit this problem, and it's only
related to string refs, and not just ref mechanism in general.
* Simplify the condition
In async mode, events are interleaved with rendering. If one of those
events mutates state that is later accessed during render, it can lead
to inconsistencies/tearing.
Restarting the render from the root is often sufficient to fix the
inconsistency. We'll flush the restart synchronously to prevent yet
another mutation from happening during an interleaved event.
We'll only restart during an async render. Sync renders are already
sync, so there's no benefit in restarting. (Unless a mutation happens
during the render phase, but we don't support that.)
* onFatal, onComplete, onSuspend, onYield
For every call to renderRoot, one of onFatal, onComplete, onSuspend,
and onYield is called upon exiting. We use these in lieu of returning a
tuple. I've also chosen not to inline them into renderRoot because these
will eventually be lifted into the renderer.
* Suspended high pri work forces lower priority work to expire early
If an error is thrown, and there is lower priority pending work, we
retry at the lower priority. The lower priority work should expire
at the same time at which the high priority work would have expired.
Effectively, this increases the priority of the low priority work.
Simple example: If an error is thrown during a synchronous render, and
there's an async update, the async update should flush synchronously in
case it's able to fix the error. I've added a unit test for
this scenario.
User provided timeouts should have the same behavior, but I'll leave
that for a future PR.
* Remove enableSuspense flag from PendingPriority module
We're going to use this for suspending on error, too.
* Retry on error if there's lower priority pending work
If an error is thrown, and there's lower priority work, it's possible
the lower priority work will fix the error. Retry at the lower priority.
If an error is thrown and there's no more work to try, handle the error
like we normally do (trigger the nearest error boundary).
**what is the change?:**
Basically undoes 4b2e65d32e (diff-904ceabd8a1e9a07ab1d876d843d62e1)
**why make this change?:**
We rolled out this fix internally and in open source weeks ago, and now
we're cleaning up.
**test plan:**
Ran tests and lint, and really we have been testing this because the
flag is open internally as of last week or so.
**issue:**
Internal task T29948812 has some info.
* Don’t error when returning an empty Fragment
When a fragment is reconciled, we directly move onto it’s children.
Since an empty `<React.Fragment/>` will have children of `undefined`,
this would always throw.
To fix this, we bail out in those cases.
* Test the update path as well
* Reuse existing code path
* An even more explicit solution that also fixes Flow
* [schedule] Use linked list instead of queue and map for storing cbs
NOTE: This PR depends on https://github.com/facebook/react/pull/12880
and https://github.com/facebook/react/pull/12884
Please review those first, and after they land Flarnie will rebase on
top of them.
---
**what is the change?:**
See title
**why make this change?:**
This seems to make the code simpler, and potentially saves space of
having an array and object around holding references to the callbacks.
**test plan:**
Run existing tests
* minor style improvements
* refactor conditionals in cancelScheduledWork for increased clarity
* Remove 'canUseDOM' condition and fix some flow issues w/callbackID type
**what is the change?:**
- Removed conditional which fell back to 'setTimeout' when the
environment doesn't have DOM. This appears to be an old polyfill used
for test environments and we don't use it any more.
- Fixed type definitions around the callbackID to be more accurate in
the scheduler itself, and more loose in the React code.
**why make this change?:**
To get Flow passing, simplify the scheduler code, make things accurate.
**test plan:**
Run tests and flow.
* Rewrite 'cancelScheduledWork' so that Flow accepts it
**what is the change?:**
Adding verification that 'previousCallbackConfig' and
'nextCallbackConfig' are not null before accessing properties on them.
Slightly concerned because this implementation relies on these
properties being untouched and correct on the config which is passed to
'cancelScheduledWork' but I guess we already rely heavily on that for
this whole approach. :\
**why make this change?:**
To get Flow passing.
Not sure why it passed earlier and in CI, but now it's not.
**test plan:**
`yarn flow dom` and other flow tests, lint, tests, etc.
* ran prettier
* Put back the fallback implementation of scheduler for node environment
**what is the change?:**
We had tried removing the fallback implementation of `scheduler` but
tests reminded us that this is important for supporting isomorphic uses
of React.
Long term we will move this out of the `schedule` module but for now
let's keep things simple.
**why make this change?:**
Keep things working!
**test plan:**
Ran tests and flow
* Shorten properties stored in objects by sheduler
**what is the change?:**
`previousScheduledCallback` -> `prev`
`nextScheduledCallback` -> `next`
**why make this change?:**
We want this package to be smaller, and less letters means less code
means smaller!
**test plan:**
ran existing tests
* further remove extra lines in scheduler
* Moved actual time fields from Profiler stateNode to Fiber
* Record actual time for all Fibers within a ProfileMode tree
* Changed how profiler accumulates time
This change gives up on accumulating time across renders of different priority, but in exchange- simplifies how the commit phase (reset) code works, and perhaps also makes the profiling code more compatible with future resuming behavior
* add legacy context APIs warning in strict mode
* refactor if statement and the warning message
* add other flags for type check
* add component stack tree and refactor wording
* fix the nits
* Added start time parameter to Profiler onRender callback
* Profiler also captures commit time
* Only init Profiler stateNode if enableProfilerTimer feature flag enabled
* Extract base Jest config
This makes it easier to change the source config without affecting the build test config.
* Statically import the host config
This changes react-reconciler to import HostConfig instead of getting it through a function argument.
Rather than start with packages like ReactDOM that want to inline it, I started with React Noop and ensured that *custom* renderers using react-reconciler package still work. To do this, I'm making HostConfig module in the reconciler look at a global variable by default (which, in case of the react-reconciler npm package, ends up being the host config argument in the top-level scope).
This is still very broken.
* Add scaffolding for importing an inlined renderer
* Fix the build
* ES exports for renderer methods
* ES modules for host configs
* Remove closures from the reconciler
* Check each renderer's config with Flow
* Fix uncovered Flow issue
We know nextHydratableInstance doesn't get mutated inside this function, but Flow doesn't so it thinks it may be null.
Help Flow.
* Prettier
* Get rid of enable*Reconciler flags
They are not as useful anymore because for almost all cases (except third party renderers) we *know* whether it supports mutation or persistence.
This refactoring means react-reconciler and react-reconciler/persistent third-party packages now ship the same thing.
Not ideal, but this seems worth how simpler the code becomes. We can later look into addressing it by having a single toggle instead.
* Prettier again
* Fix Flow config creation issue
* Fix imprecise Flow typing
* Revert accidental changes
* Lint for untyped imports and enable Flow typing in ReactFiber
* Re-enable Flow for ReactFiber and fix Flow issues
* Avoid an invariant in DEV-only code
I just introduced it, but on a second thought, it's better to keep it as a warning.
* Address review
* Use global state for `hasForceUpdate` instead of persisting to queue
Fixes a bug where `hasForceUpdate` was not reset on commit.
Ideally we'd use a tuple and return `hasForceUpdate` from
`processUpdateQueue`.
* Remove underscore and add comment
* Remove temporary variables
Fixes an oversight from #12600. getDerivedStateFromProps should fire
if either props *or* state have changed, but not if *neither* have
changed. This prevents a parent from re-rendering if a deep child
receives an update.
Previously, _owner would be null if you create an element inside forwardRef or inside a context consumer. This is used by ReactNativeFiberInspector when traversing the hierarchy and also to give more info in some warning texts. This also means you'll now correctly get a warning if you call setState inside one of these.
Test Plan: Tim tried it in the RN inspector.
* Support concurrent primary and secondary renderers.
As a workaround to support multiple concurrent renderers, we categorize
some renderers as primary and others as secondary. We only expect
there to be two concurrent renderers at most: React Native (primary) and
Fabric (secondary); React DOM (primary) and React ART (secondary).
Secondary renderers store their context values on separate fields.
* Add back concurrent renderer warning
Only warn for two concurrent primary or two concurrent secondary renderers.
* Change "_secondary" suffix to "2"
#EveryBitCounts
* Timeout component
Adds Timeout component. If a promise is thrown from inside a Timeout component,
React will suspend the in-progress render from committing. When the promise
resolves, React will retry. If the render is suspended for longer than the
maximum threshold, the Timeout switches to a placeholder state.
The timeout threshold is defined as the minimum of:
- The expiration time of the current render
- The `ms` prop given to each Timeout component in the ancestor path of the
thrown promise.
* Add a test for nested fallbacks
Co-authored-by: Andrew Clark <acdlite@fb.com>
* Resume on promise rejection
React should resume rendering regardless of whether it resolves
or rejects.
* Wrap Suspense code in feature flag
* Children of a Timeout must be strict mode compatible
Async is not required for Suspense, but strict mode is.
* Simplify list of pending work
Some of this was added with "soft expiration" in mind, but now with our revised
model for how soft expiration will work, this isn't necessary.
It would be nice to remove more of this, but I think the list itself is inherent
because we need a way to track the start times, for <Timeout ms={ms} />.
* Only use the Timeout update queue to store promises, not for state
It already worked this way in practice.
* Wrap more Suspense-only paths in the feature flag
* Attach promise listener immediately on suspend
Instead of waiting for commit phase.
* Infer approximate start time using expiration time
* Remove list of pending priority levels
We can replicate almost all the functionality by tracking just five
separate levels: the highest/lowest priority pending levels, the
highest/lowest priority suspended levels, and the lowest pinged level.
We lose a bit of granularity, in that if there are multiple levels of
pending updates, only the first and last ones are known. But in practice
this likely isn't a big deal.
These heuristics are almost entirely isolated to a single module and
can be adjusted later, without API changes, if necessary.
Non-IO-bound work is not affected at all.
* ReactFiberPendingWork -> ReactFiberPendingPriority
* Renaming method names from "pending work" to "pending priority"
* Get rid of SuspenseThenable module
Idk why I thought this was neccessary
* Nits based on Sebastian's feedback
* More naming nits + comments
* Add test for hiding a suspended tree to unblock
* Revert change to expiration time rounding
This means you have to account for the start time approximation
heuristic when writing Suspense tests, but that's going to be
true regardless.
When updating the tests, I also made a fix related to offscreen
priority. We should never timeout inside a hidden tree.
* palceholder -> placeholder
Add a new component type, Profiler, that can be used to collect new render time metrics. Since this is a new, experimental API, it will be exported as React.unstable_Profiler initially.
Most of the functionality for this component has been added behind a feature flag, enableProfileModeMetrics. When the feature flag is disabled, the component will just render its children with no additional behavior. When the flag is enabled, React will also collect timing information and pass it to the onRender function (as described below).
* Mark new component types with PerformedWork effect
* Don't do it for ForwardRef
Since this has some overhead and ForwardRef is likely going to be used around context, let's skip it.
We don't highlight ForwardRef alone in DevTools anyway.
* Add a failing test for forwardRef memoization
* Memoize forwardRef props and bail out on strict equality
* Bail out only when ref matches the current ref
* Decouple update queue from Fiber type
The update queue is in need of a refactor. Recent bugfixes (#12528) have
exposed some flaws in how it's modeled. Upcoming features like Suspense
and [redacted] also rely on the update queue in ways that weren't
anticipated in the original design.
Major changes:
- Instead of boolean flags for `isReplace` and `isForceUpdate`, updates
have a `tag` field (like Fiber). This lowers the cost for adding new
types of updates.
- Render phase updates are special cased. Updates scheduled during
the render phase are dropped if the work-in-progress does not commit.
This is used for `getDerivedStateFrom{Props,Catch}`.
- `callbackList` has been replaced with a generic effect list. Aside
from callbacks, this is also used for `componentDidCatch`.
* Remove first class UpdateQueue types and use closures instead
I tried to avoid this at first, since we avoid it everywhere else in the Fiber
codebase, but since updates are not in a hot path, the trade off with file size
seems worth it.
* Store captured errors on a separate part of the update queue
This way they can be reused independently of updates like
getDerivedStateFromProps. This will be important for resuming.
* Revert back to storing hasForceUpdate on the update queue
Instead of using the effect tag. Ideally, this would be part of the
return type of processUpdateQueue.
* Rename UpdateQueue effect type back to Callback
I don't love this name either, but it's less confusing than UpdateQueue
I suppose. Conceptually, this is usually a callback: setState callbacks,
componentDidCatch. The only case that feels a bit weird is Timeouts,
which use this effect to attach a promise listener. I guess that kinda
fits, too.
* Call getDerivedStateFromProps every render, even if props did not change
Rather than enqueue a new setState updater for every props change, we
can skip the update queue entirely and merge the result into state at
the end. This makes more sense, since "receiving props" is not an event
that should be observed. It's still a bit weird, since eventually we do
persist the derived state (in other words, it accumulates).
* Store captured effects on separate list from "own" effects (callbacks)
For resuming, we need the ability to discard the "own" effects while
reusing the captured effects.
* Optimize for class components
Change `process` and `callback` to match the expected payload types
for class components. I had intended for the update queue to be reusable
for both class components and a future React API, but we'll likely have
to fork anyway.
* Only double-invoke render phase lifecycles functions in DEV
* Use global state to track currently processing queue in DEV