Commit Graph

216 Commits

Author SHA1 Message Date
Dan Abramov
71a60ddb16
Add link to another article about React renderers 2018-06-26 16:45:03 +01:00
Nathan Quarles
a960d18bc7 eliminate unnecessary do-while loop in renderRoot() (#13087) 2018-06-21 18:52:26 +01:00
Brian Vaughn
b0f60895f7
Automatically Profile roots when DevTools is present (#13058)
* 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
2018-06-20 09:24:52 -07:00
Nathan Quarles
ae8c6dd534 remove some redundant lines (#13077)
* remove another couple of redundant lines

* a few more
2018-06-20 16:35:03 +01:00
Dan Abramov
0fcf92d06d
Add a link to custom renderer intro article 2018-06-20 14:46:18 +01:00
Andrew Clark
97af3e1f3a
Do not add additional work to a batch that is already rendering (#13072)
* 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
2018-06-19 10:36:56 -07:00
Andrew Clark
4fe6eec15b
Always batch updates of like priority within the same event (#13071)
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.
2018-06-19 10:34:19 -07:00
Dan Abramov
8e87c139b4
Remove transitive dependency on fbjs (#13075) 2018-06-19 17:52:37 +01:00
Dan Abramov
aeda7b745d
Remove fbjs dependency (#13069)
* Inline fbjs/lib/invariant

* Inline fbjs/lib/warning

* Remove remaining usage of fbjs in packages/*.js

* Fix lint

* Remove fbjs from dependencies

* Protect against accidental fbjs imports

* Fix broken test mocks

* Allow transitive deps on fbjs/ for UMD bundles

* Remove fbjs from release script
2018-06-19 16:03:45 +01:00
Dan Abramov
b1b3acbd6b
Inline fbjs/lib/emptyObject (#13055)
* 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
2018-06-19 13:41:42 +01:00
Dan Abramov
72434a7686
Remove or inline some fbjs dependencies (#13046) 2018-06-15 18:12:45 +01:00
Andrew Clark
9bd4d1fae2
Synchronously restart when an error is thrown during async rendering (#13041)
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.)
2018-06-14 16:37:30 -07:00
Andrew Clark
9bda7b28f3
Suspended high pri work forces lower priority work to expire early (#12965)
* 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.
2018-06-14 15:29:27 -07:00
Andrew Clark
e0c78344e2
Retry on error if there's lower priority pending work (#12957)
* 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).
2018-06-13 10:47:14 -07:00
Dan Abramov
0b87b27906 Updating package versions for release 16.4.1 2018-06-13 17:16:10 +01:00
Flarnie Marchan
392530104c
Remove feature flag around 'getDerivedStateFromProps' bug fix (#13022)
**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.
2018-06-11 16:31:07 -07:00
Philipp Spieß
d480782c41 Don’t error when returning an empty Fragment (#12966)
* 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
2018-06-11 14:43:30 +01:00
Nathan Quarles
bfb12ebb52 delete a couple of redundant lines in performWorkOnRoot() in ReactFiberScheduler.js (#13003) 2018-06-09 22:56:21 +01:00
Dan Abramov
394b17eede
Update custom renderer docs 2018-06-09 22:19:12 +01:00
Nathan Quarles
9cf3733a9a update comment in computeAsyncExpiration() to reflect code (#12994) 2018-06-07 21:12:08 +01:00
Simen Bekkhus
aa85b0fd5f Upgrade to Jest 23 (#12894)
* Upgrade to Jest 23 beta

* prefer `.toHaveBeenCalledTimes`

* 23 stable
2018-05-28 23:03:15 +01:00
Flarnie Marchan
61777a78f6
[scheduler] 3/n Use a linked list instead of map and queue for callback storage (#12893)
* [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
2018-05-26 15:55:57 -07:00
Brian Vaughn
5578700671
Record "actual" times for all Fibers within a Profiler tree (alt) (#12910)
* 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
2018-05-25 14:51:13 -07:00
Andrew Clark
d427a563d5 Updating package versions for release 16.4.0 2018-05-23 17:30:33 -07:00
Chang Yan
53852a887b
add functional components warning about legacy context api (#12892) 2018-05-23 14:16:39 -07:00
Chang Yan
c601f7a646
add siblings Timeout components test case (#12862) 2018-05-22 15:39:40 -07:00
Chang Yan
7350358374
add legacy context API warning in strict mode (#12849)
* 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
2018-05-22 15:38:02 -07:00
Dan Abramov
dd5fad2961
Update Flow to 0.70 (#12875)
* Update Flow to 0.70

* Remove unnecessary condition

* Fix wrong assertion

* Strict check
2018-05-21 17:54:48 +01:00
Brian Vaughn
13003654e7
Pass "start time" and "commit time" to Profiler callback (#12852)
* Added start time parameter to Profiler onRender callback
* Profiler also captures commit time
* Only init Profiler stateNode if enableProfilerTimer feature flag enabled
2018-05-21 09:49:22 -07:00
Kevin (Kun) "Kassimo" Qian
d7b9b4921b Fix react native example links in README of 'react-reconciler' (#12871) 2018-05-20 12:01:00 +01:00
Dan Abramov
47b003a828
Resolve host configs at build time (#12792)
* 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
2018-05-19 11:29:11 +01:00
Dan Abramov
b245795de3
Re-enable Flow for ReactFiber and fix Flow issues (#12842)
* 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
2018-05-17 17:14:12 +01:00
Sebastian Markbåge
d4123b4784
Relax current renderer warning (#12838)
If you use an older version of `react` this won't get initialized to null. We don't really need it to be initialized to work.
2018-05-16 17:31:56 -07:00
Brian Vaughn
de84d5c107
Enable Profiler timing for DOM and RN dev bundles (#12823)
* Enable Profiler timing for DOM and RN dev bundles
* Disable enableProfilerTimer feature flag for ReactIncrementalPerf-test
2018-05-15 15:26:46 -07:00
Brian Vaughn
103503eb69
Only measure "base" times within ProfileMode (#12821)
* Conditionally start/stop base timer only within Profile mode tree
* Added test to ensure ProfilerTimer not called outside of Profiler root
2018-05-15 12:43:42 -07:00
Dan Abramov
9097f3cdf0
Delete React Call/Return experiment (#12820) 2018-05-15 19:16:29 +01:00
Andrew Clark
73f59e6f31
Use global state for hasForceUpdate instead of persisting to queue (#12808)
* 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
2018-05-14 19:18:47 -07:00
Andrew Clark
c5d3104fc0
Do not fire getDerivedStateFromProps unless props or state have changed (#12802)
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.
2018-05-14 14:56:48 -07:00
Sophie Alpert
2a4d2ca7fc
Set owner correctly inside forwardRef and context consumer (#12777)
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.
2018-05-14 10:07:31 -07:00
Dan Abramov
0470854f55
Split ReactNoop into normal and persistent exports (#12793)
* Copy-paste ReactNoop into ReactNoopPersistent

* Split ReactNoop into normal and persistent exports

* ReactNoopShared -> createReactNoop
2018-05-14 13:57:33 +01:00
Andrew Clark
4b2e65d32e
Put recent change to getDerivedStateFromProps behind a feature flag (#12788)
This will allow us to safely ship it at Facebook and get a better idea
for if/how it breaks existing product code.
2018-05-11 18:45:00 -07:00
Andrew Clark
b0726e9947
Support sharing context objects between concurrent renderers (#12779)
* 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
2018-05-10 18:34:01 -07:00
Andrew Clark
6565795377
Suspense (#12279)
* 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
2018-05-10 18:09:10 -07:00
Brian Vaughn
fc3777b1fe
Add Profiler component for collecting new render timing info (#12745)
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).
2018-05-10 15:25:32 -07:00
Dan Abramov
25dda90c1e
Mark context consumers with PerformedWork effect on render (#12729)
* 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.
2018-05-02 16:35:16 +01:00
Dan Abramov
ad7cd68667
Rename internal property to fix React DevTools (#12727) 2018-05-01 21:04:20 +01:00
Dan Abramov
045d4f166d
Fix a context propagation bug (#12708)
* Fix a context propagation bug

* Add a regression test
2018-04-28 01:52:48 +01:00
Dan Abramov
7c39328571
Don't bail on new context Provider if a legacy provider rendered above (#12586)
* Don't bail on new context Provider if a legacy provider rendered above

* Avoid an extra variable
2018-04-26 20:59:17 +01:00
Dan Abramov
d883d59863
forwardRef() components should not re-render on deep setState() (#12690)
* 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
2018-04-26 19:47:34 +01:00
Andrew Clark
b548b3cd64
Decouple update queue from Fiber type (#12600)
* 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
2018-04-22 23:05:28 -07:00