Commit Graph

463 Commits

Author SHA1 Message Date
Sebastian Markbåge
56e9feead0
Remove Blocks (#20138)
* Remove Blocks

* Remove Flight Server Runtime

There's no need for this now that the JSResource is part of the bundler
protocol. Might need something for Webpack plugin specifically later.

* Devtools
2020-10-30 23:03:45 -07:00
Dan Abramov
eaaf4cbce7 17.0.1 2020-10-22 13:24:46 +01:00
Dan Abramov
f021a983aa
Bump versions for 17 (#20062) 2020-10-20 21:41:18 +01:00
Dominic Gannaway
d95c4938df
[EventSystem] Revise onBeforeBlur propagation mechanics (#20020) 2020-10-14 23:38:57 +01:00
Saikat Guha
f46a80ae11
Update outdated links and fix two broken links (#19985)
* update all facebook.github.io links

* facebookincubator links : update some outdated links and fix two other broken links where they are actually the latest updated ones
2020-10-09 02:56:30 +01:00
Andrew Clark
e7b255341b
Internal act: Flush timers at end of scope (#19788)
If there are any suspended fallbacks at the end of the `act` scope,
force them to display by running the pending timers (i.e. `setTimeout`).

The public implementation of `act` achieves the same behavior with an
extra check in the work loop (`shouldForceFlushFallbacks`). Since our
internal `act` needs to work in both development and production, without
additional runtime checks, we instead rely on Jest's mock timers.

This doesn't not affect refresh transitions, which are meant to delay
indefinitely, because in that case we exit the work loop without
posting a timer.
2020-09-08 21:55:23 -07:00
Andrew Clark
d17086c7c8
Decouple public, internal act implementation (#19745)
In the next major release, we intend to drop support for using the `act`
testing helper in production. (It already fires a warning.) The
rationale is that, in order for `act` to work, you must either mock the
testing environment or add extra logic at runtime. Mocking the testing
environment isn't ideal because it requires extra set up for the user.
Extra logic at runtime is fine only in development mode — we don't want
to slow down the production builds.

Since most people only run their tests in development mode, dropping
support for production should be fine; if there's demand, we can add it
back later using a special testing build that is identical to the
production build except for the additional testing logic.

One blocker for removing production support is that we currently use
`act` to test React itself. We must test React in both development and
production modes.

So, the solution is to fork `act` into separate public and
internal implementations:

- *public implementation of `act`* – exposed to users, only works in
  development mode, uses special runtime logic, does not support partial
  rendering
- *internal implementation of `act`* – private, works in both
  development and productionm modes, only used by the React Core test
  suite, uses no special runtime logic, supports partial rendering (i.e.
  `toFlushAndYieldThrough`)

The internal implementation should mostly match the public
implementation's behavior, but since it's a private API, it doesn't have
to match exactly. It works by mocking the test environment: it uses a
mock build of Scheduler to flush rendering tasks, and Jest's mock timers
to flush Suspense placeholders.

---

In this first commit, I've added the internal forks of `act` and
migrated our tests to use them. The public `act` implementation is
unaffected for now; I will leave refactoring/clean-up for a later step.
2020-09-08 08:11:45 -07:00
Dan Abramov
ce37bfad5f
Remove resolutions from test renderer package.json (#19577) 2020-08-10 20:45:12 +01:00
Dominic Gannaway
b61174fb7b
Remove the deprecated React Flare event system (#19520) 2020-08-05 15:13:29 +01:00
Brian Vaughn
a89854bc93
Fix Suspense-wrapping heuristic (and bump version numbers) (#19373)
* Fixed suspense wrapping heuristic

* Bump package numbers 16.13.1 -> 17.0.0-alpha.0 to fix DevTools Suspense heuristic
2020-07-15 12:25:27 -04:00
Dominic Gannaway
4eb9b1d2b4
Refactor createEventHandle signature (#19174) 2020-07-07 13:05:06 +01:00
Shailendra Gupta
f4097c1aef
Added warning to <Context.Provider> in case no value prop is provided (#19054)
* added warning to context.provider in case no value prop

* update message

* updated message and pass undefined
2020-06-30 19:50:55 +01:00
Ricky
30b47103d4
Fix spelling errors and typos (#19138) 2020-06-15 19:59:44 -04:00
Andrew Clark
103ed08c46
Remove shouldDeprioritizeSubtree from host config (#19124)
No longer being used.
2020-06-12 12:57:20 -07:00
Dominic Gannaway
80c4dea0d1
Modern Event System: Add scaffolding for createEventHandle (#18898) 2020-05-12 19:01:12 +01:00
Luna Ruan
df14b5bcc1
add new IDs for each each server renderer instance and prefixes to distinguish between each server render (#18576)
There is a worry that `useOpaqueIdentifier` might run out of unique IDs if running for long enough. This PR moves the unique ID counter so it's generated per server renderer object instead. For people who render different subtrees, this PR adds a prefix option to `renderToString`, `renderToStaticMarkup`, `renderToNodeStream`, and `renderToStaticNodeStream` so identifiers can be differentiated for each individual subtree.
2020-05-07 20:46:27 -07:00
Brian Vaughn
3cde22a84e
Experimental test selector API (#18607)
Adds several new experimental APIs to aid with automated testing.

Each of the methods below accepts an array of "selectors" that identifies a path (or paths) through a React tree. There are four basic selector types:

* Component: Matches Fibers with the specified React component type
* Role: Matches Host Instances matching the (explicit or implicit) accessibility role.
* Test name: Matches Host Instances with a data-testname attribute.
* Text: Matches Host Instances that directly contain the specified text.
* There is also a special lookahead selector type that enables further matching within a path (without actually including the path in the result). This selector type was inspired by the :has() CSS pseudo-class. It enables e.g. matching a <section> that contained a specific header text, then finding a like button within that <section>.

API
* findAllNodes(): Finds all Host Instances (e.g. HTMLElement) within a host subtree that match the specified selector criteria.
* getFindAllNodesFailureDescription(): Returns an error string describing the matched and unmatched portions of the selector query.
* findBoundingRects(): For all React components within a host subtree that match the specified selector criteria, return a set of bounding boxes that covers the bounds of the nearest (shallowed) Host Instances within those trees.
* observeVisibleRects(): For all React components within a host subtree that match the specified selector criteria, observe if it’s bounding rect is visible in the viewport and is not occluded.
* focusWithin(): For all React components within a host subtree that match the specified selector criteria, set focus within the first focusable Host Instance (as if you started before this component in the tree and moved focus forwards one step).
2020-05-05 10:37:46 -07:00
Dominic Gannaway
aa88589d0b
Refine experimental Scopes API (#18778)
* Refine experimental Scopes API
2020-05-01 19:01:43 +01:00
Brian Vaughn
ea2af878cc
Root API should clear non-empty roots before mounting (#18730)
* Root API should clear non-empty roots before mounting

Legacy render-into-subtree API removes children from a container before rendering into it. The root API did not do this previously, but just left the children around in the document.

This commit adds a new FiberRoot flag to clear a container's contents before mounting. This is done during the commit phase, to avoid multiple, observable mutations.
2020-04-28 13:07:42 -07:00
Dominic Gannaway
30cee2f4c7
Modern Event System: register onMouseEnter for portals (#18720) 2020-04-23 20:57:52 +01:00
Dominic Gannaway
ff431b7fc4
Remove ReactDOM.useEvent and associated types+tests (#18689) 2020-04-21 16:40:44 +01:00
Dominic Gannaway
a152827ef6
Refine the heuristics around beforeblur/afterblur (#18668)
* Refine the heuristics around beforeblur/afterblur
2020-04-20 19:32:22 +01:00
Andrew Clark
376d5c1b5a Split cross-package types from implementation
Some of our internal reconciler types have leaked into other packages.
Usually, these types are treated as opaque; we don't read and write
to its fields. This is good.

However, the type is often passed back to a reconciler method. For
example, React DOM creates a FiberRoot with `createContainer`, then
passes that root to `updateContainer`. It doesn't do anything with the
root except pass it through, but because `updateContainer` expects a
full FiberRoot, React DOM is still coupled to all its fields.

I don't know if there's an idiomatic way to handle this in Flow. Opaque
types are simlar, but those only work within a single file. AFAIK,
there's no way to use a package as the boundary for opaqueness.

The immediate problem this presents is that the reconciler refactor will
involve changes to our internal data structures. I don't want to have to
fork every single package that happens to pass through a Fiber or
FiberRoot, or access any one of its fields. So my current plan is to
share the same Flow type across both forks. The shared type will be a
superset of each implementation's type, e.g. Fiber will have both an
`expirationTime` field and a `lanes` field. The implementations will
diverge, but not the types.

To do this, I lifted the type definitions into a separate module.
2020-04-08 23:49:23 -07:00
Andrew Clark
d686f3f16a Add .old prefix to reconciler modules 2020-04-08 23:49:19 -07:00
Sebastian Markbåge
147bdef11b
Port more tests to the Scheduler.unstable_yieldValue pattern and drop internal.js (#18549)
* Drop the .internal.js suffix on some files that don't need it anymore

* Port some ops patterns to scheduler yield

* Fix triangle test to avoid side-effects in constructor

* Move replaying of setState updaters until after the effect

Otherwise any warnings get silenced if they're deduped.

* Drop .internal.js in more files

* Don't check propTypes on a simple memo component unless it's lazy

Comparing the elementType doesn't work for this because it will never be
the same for a simple element.

This caused us to double validate these. This was covered up because in
internal tests this was deduped since they shared the prop types cache
but since we now inline it, it doesn't get deduped.
2020-04-08 20:54:54 -07:00
Sebastian Markbåge
5474a83e25
Disable console.logs in the second render pass of DEV mode double render (#18547)
* Disable console log during the second rerender

* Use the disabled log to avoid double yielding values in scheduler mock

* Reenable debugRenderPhaseSideEffectsForStrictMode in tests that can
2020-04-08 16:43:51 -07:00
Luna Ruan
3278d24218
Add useOpaqueIdentifier Hook (#17322)
* Add useOpaqueIdentifier Hook

We currently use unique IDs in a lot of places. Examples are:
  * `<label for="ID">`
  * `aria-labelledby`

This can cause some issues:
  1. If we server side render and then hydrate, this could cause an
     hydration ID mismatch
  2. If we server side render one part of the page and client side
     render another part of the page, the ID for one part could be
     different than the ID for another part even though they are
     supposed to be the same
  3. If we conditionally render something with an ID ,  this might also
     cause an ID mismatch because the ID will be different on other
     parts of the page

This PR creates a new hook `useUniqueId` that generates a different
unique ID based on whether the hook was called on the server or client.
If the hook is called during hydration, it generates an opaque object
that will rerender the hook so that the IDs match.

Co-authored-by: Andrew Clark <git@andrewclark.io>
2020-04-06 17:17:27 -07:00
Sebastian Markbåge
3e94bce765
Enable prefer-const lint rules (#18451)
* Enable prefer-const rule

Stylistically I don't like this but Closure Compiler takes advantage of
this information.

* Auto-fix lints

* Manually fix the remaining callsites
2020-04-01 12:35:52 -07:00
Ricky
dd7e5e4f5a
Add getInspectorDataForViewAtPoint (take two) (#18388)
* Add getInspectorDataForViewAtPoint (take two)

* Updates from review

* Add DEV to dev-only variable

* Missed this rename
2020-03-30 15:42:41 -04:00
Sebastian Silbermann
ba31ad40a9
feat(StrictMode): Double-invoke render for every component (#18430)
* feat(StrictMode): Double-invoke render for every component

* fix: Mark ReactTestRendererAsync as internal
2020-03-29 23:13:46 +01:00
Sebastian Markbåge
c5d2fc7127
Move some files out of /shared and rename to upper case (#18363)
* Rename lower case isomorphic default exports modules to upper case named exports

We're somewhat inconsistent here between e.g. ReactLazy and memo.

Let's pick one.

This also moves the responder, fundamental, scope creators from shared
since they're isomorphic and same as the other creators.

* Move some files that are specific to the react-reconciler from shared

Individual renderers are allowed to deep require into the reconciler.

* Move files specific to react-dom from shared

react-interactions is right now dom specific (it wasn't before) so we can
type check it together with other dom stuff. Avoids the need for
a shared ReactDOMTypes to be checked by RN for example.

* Move ReactWorkTags to the reconciler

* Move createPortal to export from reconciler

Otherwise Noop can't access it since it's not allowed deep requires.
2020-03-21 15:22:01 -07:00
Andrew Clark
6818a2aa01
Revert accidental changes to package.json (#18348)
The publish script was written before we switched to running patch
releases out-of-band, so when updating the local package.json version
numbers, it accidentally reverted other changes that have landed to
master since 16.13 was released.
2020-03-19 13:16:37 -07:00
Andrew Clark
ad445b127e Update package.jsons for 16.13.1 patch relase 2020-03-19 12:58:31 -07:00
Dan Abramov
26666427d6
Don't support older isomorphic React with newer renderers (#18329)
* Don't support older isomorphic React with newer renderers

* Remove the lazy hack
2020-03-17 19:30:10 +00:00
Minh Nguyen
9240918536
Bump react-shallow-renderer to 16.13.1 (#18187) 2020-03-17 00:35:28 +00:00
Dominic Gannaway
c804f9aebb
ReactDOM.useEvent: wire to event system to the hook (#18304) 2020-03-16 21:46:17 +00:00
Dominic Gannaway
99d271228d
ReactDOM.useEvent: more scaffolding changes (#18282) 2020-03-12 09:12:06 +00:00
Dominic Gannaway
160505b0ca
ReactDOM.useEvent: Add more scaffolding for useEvent hook (#18271) 2020-03-10 20:31:12 +00:00
Sebastian Markbåge
7a1691cdff
Refactor Host Config Infra (getting rid of .inline*.js) (#18240)
* Require deep for reconcilers

* Delete inline* files

* Delete react-reconciler/persistent

This no longer makes any sense because it react-reconciler takes
supportsMutation or supportsPersistence as options. It's no longer based
on feature flags.

* Fix jest mocking

* Fix Flow strategy

We now explicitly list which paths we want to be checked by a renderer.
For every other renderer config we ignore those paths.

Nothing is "any" typed. So if some transitive dependency isn't reachable
it won't be accidentally "any" that leaks.
2020-03-06 16:20:42 -08:00
Minh Nguyen
c26506a7d2
Update react-shallow-renderer from 16.12.0 to 16.13.0 (#18185) 2020-02-28 16:35:52 -08:00
Henry Q. Dineen
053347e6bc
react-test-renderer: improve findByType() error message (#17439)
* improve findByType error message

* fix flow typing

* Adding a test for the "Unknown" branch when `getComponentName()` returns a falsy value. The error message in this case not the most descriptive but seems consistent with the `getComponentName(type) || 'Unknown'` pattern seen in multiple places in this code base.
2020-02-28 17:55:33 +00:00
Dan Abramov
d72700ff5a
Remove runtime dependency on prop-types (#18127)
* Remove runtime dep on prop-types

* Fix test
2020-02-28 01:21:54 +00:00
Sebastian Markbåge
739f20beda
Remove Node shallow builds (#18157)
This is just a forwarding module. We can hardcode it.
2020-02-27 14:11:40 -08:00
Minh Nguyen
293878e079
Replace ReactShallowRenderer with a dependency (#18144)
Closes #17321.
2020-02-27 18:10:25 +00:00
Sebastian Markbåge
f9c0a45441
Convert the rest of react-dom and react-test-renderer to Named Exports (#18145)
Nothing interesting here except that ReactShallowRenderer currently exports
a class with a static method instead of an object.

I think the public API is probably just meant to be createRenderer but
currently the whole class is exposed. So this means that we have to keep
it as default export. We could potentially also expose a named export for
createRenderer but that's going to cause compatibility issues.

So I'm just going to make that export default.

Unfortunately Rollup and Babel (which powers Jest) disagree on how to
import this. So to make it work I had to move the jest tests to imports.

This doesn't work with module resetting. Some tests weren't doing that
anyway and the rest is just testing ReactShallowRenderer so meh.
2020-02-26 18:04:32 -08:00
Sunil Pai
c1c5499cc3
update version numbers for 16.13 (#18143)
also includes a bugfix when downloading error codes from circleci.
2020-02-26 20:33:29 +00:00
Sebastian Markbåge
09348798a9
Codemod to import * as React from "react"; (#18102)
* import * as React from "react";

This is the correct way to import React from an ES module since the ES
module will not have a default export. Only named exports.

* import * as ReactDOM from "react-dom"
2020-02-21 19:45:20 -08:00
Sebastian Markbåge
65bbda7f16
Rename Chunks API to Blocks (#18086)
Sounds like this is the name we're going with. This also helps us
distinguish it from other "chunking" implementation details.
2020-02-20 23:56:40 -08:00
Sunil Pai
3e9251d605
make testing builds for React/ReactDOM (#17915)
This PR introduces adds `react/testing` and `react-dom/testing`.
- changes infra to generate these builds
- exports act on ReactDOM in these testing builds
- uses the new test builds in fixtures/dom

In the next PR -

- I'll use the new builds for all our own tests
- I'll replace usages of TestUtils.act with ReactDOM.act.
2020-02-03 23:31:31 +00:00
Nicolas Gallagher
6faf6f5eb1
Update to flow 0.97 (#17892) 2020-01-24 10:52:38 -08:00
Nicolas Gallagher
6c00c5bba4
Update to flow-bin@0.89 (#17842) 2020-01-22 10:02:30 -08:00
Dan Abramov
e706721490
Update Flow to 0.84 (#17805)
* Update Flow to 0.84

* Fix violations

* Use inexact object syntax in files from fbsource

* Fix warning extraction to use a modern parser

* Codemod inexact objects to new syntax

* Tighten types that can be exact

* Revert unintentional formatting changes from codemod
2020-01-09 14:50:44 +00:00
Dan Abramov
b979db4e72
Bump Prettier (#17811)
* Bump Prettier

* Reformat

* Use non-deprecated option
2020-01-09 13:54:11 +00:00
Sebastian Markbåge
7dc9745427
[Flight] Chunks API (#17398)
* Add feature flags

* Add Chunk type and constructor

* Wire up Chunk support in the reconciler

* Update reconciler to reconcile Chunks against the render method

This allows the query and args to be updated.

* Drop the ref. Chunks cannot have refs anyway.

* Add Chunk checks in more missing cases

* Rename secondArg

* Add test and fix lazy chunks

Not really a supported use case but for consistency I guess.

* Fix fragment test
2019-12-18 18:25:43 +00:00
Dominic Gannaway
9fe1031244
[react-interactions] Rename Flare APIs to deprecated and remove from RN (#17644) 2019-12-18 10:24:46 +00:00
Dan Abramov
0b5a26a489
Rename toWarnDev -> toErrorDev, toLowPriorityWarnDev -> toWarnDev (#17605)
* Rename toWarnDev -> toErrorDev in tests

* Rename toWarnDev matcher implementation to toErrorDev

* Rename toLowPriorityWarnDev -> toWarnDev in tests and implementation
2019-12-16 12:48:16 +00:00
Dan Abramov
0cf22a56a1
Use console directly instead of warning() modules (#17599)
* Replace all warning/lowPriWarning with console calls

* Replace console.warn/error with a custom wrapper at build time

* Fail the build for console.error/warn() where we can't read the stack
2019-12-14 18:09:25 +00:00
Dan Abramov
b15bf36750
Add component stacks to (almost) all warnings (#17586) 2019-12-12 23:47:55 +00:00
Laura buns
9ac42dd074 Remove the condition argument from warning() (#17568)
* prep for codemod

* prep warnings

* rename lint rules

* codemod for ifs

* shim www functions

* Handle more cases in the transform

* Thanks De Morgan

* Run the codemod

* Delete the transform

* Fix up confusing conditions manually

* Fix up www shims to match expected API

* Also check for low-pri warning in the lint rule
2019-12-11 03:28:14 +00:00
Laura buns
b43eec7eaa Replace wrap-warning-with-env-check with an eslint plugin (#17540)
* Replace Babel plugin with an ESLint plugin

* Fix ESLint rule violations

* Move shared conditions higher

* Test formatting nits

* Tweak ESLint rule

* Bugfix: inside else branch, 'if' tests are not satisfactory

* Use a stricter check for exactly if (__DEV__)

This makes it easier to see what's going on and matches dominant style in the codebase.

* Fix remaining files after stricter check
2019-12-06 18:25:54 +00:00
Dominic Gannaway
a7d07ff24d
[react-interactions] Rename Flare listeners prop to DEPRECATED_flareListeners (#17394) 2019-11-18 13:32:50 +00:00
Luna Ruan
9a5f28dbed update version numbers for 16.12 2019-11-14 16:02:18 -08:00
Dominic Gannaway
a61886b16b
[react-interactions] Refine custom active element blur logic (#17354) 2019-11-13 20:46:00 +00:00
Brian Vaughn
053cf0fedc
Fix react-is memo and lazy type checks (#17278) 2019-11-05 10:37:12 -08:00
Andrew Clark
8075c8505b Update local package versions for 16.10 release 2019-10-22 14:30:06 -07:00
Luna Ruan
685ed561f2
Migrate useDeferredValue and useTransition (#17058)
Migrated useDeferredValue and useTransition from Facebook's www repo into ReactFiberHooks.
2019-10-18 12:48:43 -07:00
Dominic Gannaway
0ac8e563d0
[react-interactions] Add getInstanceFromNode support to TestHostRenderer (#17065)
Fix bad WeakMap key case

Fix bad WeakMap key case
2019-10-11 16:58:27 +02:00
Dominic Gannaway
b71ab61c8f
[react-interactions] Adds more experimental Scope API methods (#17042) 2019-10-08 19:32:53 +02:00
Andrew Clark
d256f88ac6 Update local version numbers for 16.10.2 release 2019-10-03 14:14:10 -07:00
Simen Bekkhus
e09097a75d chore: upgrade to jest 24 (#15778)
* chore: upgrade to jest 24

* download react-is from npm manually
2019-10-03 22:44:18 +05:30
Andrew Clark
2a264a9dbe Update local version numbers for 16.10.1 release 2019-09-28 21:41:42 -07:00
Andrew Clark
93f5f11b79 Update local version numbers for 16.10 release 2019-09-27 13:31:35 -07:00
Dominic Gannaway
46f912fd57
[react-core] Add more support for experimental React Scope API (#16621) 2019-08-30 18:27:14 +01:00
Dominic Gannaway
fc80772078
[react-events] Ensure updateEventListeners updates in commit phase (#16540) 2019-08-22 23:58:16 +01:00
Sebastian Markbåge
c80678c760
Add "hydrationOptions" behind the enableSuspenseCallback flag (#16434)
This gets invoked when a boundary is either hydrated or if it is deleted
because it updated or got deleted before it mounted.
2019-08-19 13:26:39 -07:00
Andrew Clark
0bd0c5269f
Upgrade ESLint so we can use JSX Fragment syntax (#16328)
Now that we're using Babel 7, this is the last blocker.
2019-08-09 12:59:02 -07:00
Sunil Pai
b9faa3b092
[act] remove obsolete container element (#16312)
In a previous version of act(), we used a dummy dom element to flush effects. This doesn't need to exist anymore, and this PR removes it. The warning doesn't need to be there either (React will fire a wrong renderer act warning if needed).
2019-08-09 14:26:47 +01:00
Andrew Clark
95767acf83
Bump deps in packages/**/package.json (#16325) 2019-08-08 14:50:11 -07:00
Andrew Clark
85d05b3a4d Bump package.json versions 2019-08-08 14:24:39 -07:00
Sunil Pai
a1dbb852c2 warn if you try to use act() in prod (#16282)
We have behaviour divergence for act() between prod and dev (specifically, act() + concurrent mode does not flush fallbacks in prod. This doesn't affect anyone in OSS yet)

We also don't have a good story for writing tests in prod (and what from what I gather, nobody really writes tests in prod mode).

We could have wiped out act() in prod builds, except that _we_ ourselves use act() for our tests when we run them in prod mode.

This PR is a compromise to all of this. We will log a warning if you try to use act() in prod mode, and we silence it in our test suites.
2019-08-05 13:01:05 -07:00
Dominic Gannaway
42794557ca
[Flare] Tweaks to Flare system design and API (#16264) 2019-08-01 19:08:54 +01:00
Sunil Pai
e6a0473c3c
Warn when rendering tests in concurrent/batched mode without a mocked scheduler (#16207)
Concurrent/Batched mode tests should always be run with a mocked scheduler (v17 or not). This PR adds a warning for the same. I'll put up a separate PR to the docs with a page detailing how to mock the scheduler.
2019-07-30 19:00:18 +01:00
Sunil Pai
d412eec839
[act] flush work correctly without a mocked scheduler (#16223)
Not returning the value of flushPassiveEffects() in flushWork() meant that with async act, we wouldn't flush all work with cascading effects. This PR fixes that oversight, and adds some tests to catch this in the future.
2019-07-26 17:48:42 +01:00
Dominic Gannaway
7ad221126f
[Flare] Ensure Flare components are no-ops for TestRenderer (#16192) 2019-07-24 11:31:33 +01:00
Sunil Pai
c73e1f236f
flush work on exiting outermost act(), with nested act()s from different renderers (#16181)
Given this snippet:
```jsx
    TestRenderer.act(() => {
      TestUtils.act(() => {
        TestRenderer.create(<Effecty />);
      });
    });
```
We want to make sure that all work is only flushed on exiting the outermost act().

Now, naively doing this based on actingScopeDepth would work with a mocked scheduler, where flushAll() would flush all work across renderers.

This doesn't work without mocking the scheduler though; and where flushing work only works per renderer. So we disable this behaviour for a non-mocked scenario. This seems like an ok tradeoff.
2019-07-24 00:20:28 +01:00
Dominic Gannaway
5098891193
[Flare] Redesign core event system (#16163) 2019-07-23 23:46:44 +01:00
Dominic Gannaway
2c4d61e102
Adds experimental fundamental interface (#16049) 2019-07-19 22:20:28 +01:00
Dominic Gannaway
67e3f3fb6e
[Flare] Revise responder event types (#16081) 2019-07-08 14:35:59 +01:00
Sunil Pai
b8f91e6649
[fail] reset IsThisRendererActing correctly (#16042)
* [fail] reset IsThisRendererActing correctly

I missed this in https://github.com/facebook/react/pull/16039. I'd pointed at the wrong previous state, corrupting it in further use. This PR fixes that, and adds a test to make sure it doesn't happen again.

* warn for unacted effects only in strict mode
2019-07-03 03:04:22 +01:00
Sunil Pai
a457e02ae3
allow nested act()s from different renderers (#16039)
* allow nested `act()`s from different renderers

There are usecases where multiple renderers need to oprate inside an act() scope
- ReactDOM.render being used inside another component tree. The parent component will be rendered using ReactTestRenderer.create for a snapshot test or something.
- a ReactDOM instance interacting with a ReactTestRenderer instance (like for the new devtools)

This PR changes the way the acting sigils operate to allow for this. It keeps 2 booleans, one attached to React, one attached to the renderer. act() changes these values, and the workloop reads them to decide what warning to trigger.

I also renamed shouldWarnUnactedUpdates to warnsIfNotActing

* s/ReactIsActing/IsSomeRendererActing and s/ReactRendererIsActing/IsThisRendererActing
2019-07-02 22:20:17 +01:00
Dominic Gannaway
9b0bd43550
[Flare] Re-label Flare flag (#16014) 2019-06-28 01:11:11 +01:00
Dominic Gannaway
8b88ac2592
[Flare] Remove event targets including TouchHitTarget (#16011) 2019-06-27 23:58:48 +01:00
Andrew Clark
4d307de458
Prefix mock Scheduler APIs with _unstable (#15999)
For now this is only meant to be consumed via `act`.
2019-06-26 12:16:08 -07:00
Sunil Pai
fce15f14d3
don't fire missing act() warnings for react-art (#15975)
* use toWarnDev for dom fixture tests

forks toWarnDev from root into fixture/dom, updates tes tests to use it

* disable act() warnings for react-art()

- For 'secondary' renderers like react-act, we don't want to fire missing act() warnings; the wrapping renderer will fire warnings anyway, and when it flushes, it flushes effects *across* renderers.

- I could have used isPrimaryRenderer as the flag, but this is marked as false for react-test-renderer, and we *do* want the warning to fire for it. Hence a new flag.

* add missing dependency `art` to fixtures/dom
2019-06-24 19:18:26 +01:00
Dominic Gannaway
34ce57ae75
[Flare] Refine flow type annotations (#15950) 2019-06-21 12:32:43 +01:00
Dominic Gannaway
720db4cbe6 [Flare] Add useEvent hook implementation (#15927)
* [Flare] Add useEvent hook implementation

Validate hooks have decendent event components

Few fixes and displayName changes

Fix more responder bugs

Update error codes

* Add another test

* Address feedback
2019-06-20 19:12:40 -07:00
Sunil Pai
ff91bfa58c
[act] reset scope depth on synchronous errors (#15937)
* reset scope depth on synchronous errors

we weren't resetting the acting scope depth on sync errors thrown in the callback. this fixes that.

* typos

* add a test to make sure sync error propagate
2019-06-20 13:50:53 +01:00
Dominic Gannaway
689beef6f5
[Flare] Move unstable_createEventComponent to ReactDOM (#15890) 2019-06-18 23:41:00 +01:00
Sunil Pai
9aad17d60c
using the wrong renderer's act() should warn (#15756)
* warn when using the wrong renderer's act around another renderer's updates

like it says. it uses a real object as the sigil (instead of just a boolean). specifically, it uses a renderer's flushPassiveEffects as the sigil. We also run tests for this separate from our main suite (which doesn't allow loading multiple renderers in a suite), but makes sure to run this in CI as well.

* unneeded (and wrong) comment

* run the dom fixture on CI

* update the sigil only in __DEV__

* remove the obnoxious comment

* use an explicit export for the sigil
2019-05-29 22:56:04 +01:00
Sebastian Markbåge
8af1f87929 Rename ReactFiberScheduler -> ReactFiberWorkLoop and extract throwException from Unwind (#15725)
* Rename ReactFiberScheduler to ReactFiberWorkLoop

The scheduling part is mostly extracted out to the scheduler package.

What's remaining is mostly around the loop around each section of work.
I name it something with Work in it because it's very related to the
BeginWork, CompleteWork and UnwindWork sections.

* Extract throwException from UnwindWork

Our throwing works more like algebraic effects in that it's a separate
phase where we find a handler and we later unwind.
2019-05-23 14:24:18 -07:00
Sunil Pai
9c9ea94852
flush only on exiting outermost act() (#15682) 2019-05-21 10:41:24 +01:00
Sunil Pai
d278a3ff8b
act() - s / flushPassiveEffects / Scheduler.unstable_flushWithoutYielding (#15591)
* s/flushPassiveEffects/unstable_flushWithoutYielding

a first crack at flushing the scheduler manually from inside act(). uses unstable_flushWithoutYielding(). The tests that changed, mostly replaced toFlushAndYield(...) with toHaveYielded(). For some tests that tested the state of the tree before flushing effects (but still after updates), I replaced act() with bacthedUpdates().

* ugh lint

* pass build, flushPassiveEffects returns nothing now

* pass test-fire

* flush all work (not just effects), add a compatibility mode

of note, unstable_flushWithoutYielding now returns a boolean much like flushPassiveEffects

* umd build for scheduler/unstable_mock, pass the fixture with it

* add a comment to Shcduler.umd.js for why we're exporting unstable_flushWithoutYielding

* run testsutilsact tests in both sync/concurrent modes

* augh lint

* use a feature flag for the missing mock scheduler warning

I also tried writing a test for it, but couldn't get the scheduler to unmock. included the failing test.

* Update ReactTestUtilsAct-test.js

- pass the mock scheduler warning test,
- rewrite some tests to use Scheduler.yieldValue
- structure concurrent/legacy suites neatly

* pass failing tests in batchedmode-test

* fix pretty/lint/import errors

* pass test-build

* nit: pull .create(null) out of the act() call
2019-05-16 17:12:36 +01:00
Andrew Clark
862f499fac
Add Batched Mode (#15502)
* Add Batched Mode

React has an unfortunate quirk where updates are sometimes synchronous
-- where React starts rendering immediately within the call stack of
`setState` — and sometimes batched, where updates are flushed at the
end of the current event. Any update that originates within the call
stack of the React event system is batched. This encompasses most
updates, since most updates originate from an event handler like
`onClick` or `onChange`. It also includes updates triggered by lifecycle
methods or effects. But there are also updates that originate outside
React's event system, like timer events, network events, and microtasks
(promise resolution handlers). These are not batched, which results in
both worse performance (multiple render passes instead of single one)
and confusing semantics.

Ideally all updates would be batched by default. Unfortunately, it's
easy for components to accidentally rely on this behavior, so changing
it could break existing apps in subtle ways.

One way to move to a batched-by-default model is to opt into Concurrent
Mode (still experimental). But Concurrent Mode introduces additional
semantic changes that apps may not be ready to adopt.

This commit introduces an additional mode called Batched Mode. Batched
Mode enables a batched-by-default model that defers all updates to the
next React event. Once it begins rendering, React will not yield to
the browser until the entire render is finished.

Batched Mode is superset of Strict Mode. It fires all the same warnings.
It also drops the forked Suspense behavior used by Legacy Mode, in favor
of the proper semantics used by Concurrent Mode.

I have not added any public APIs that expose the new mode yet. I'll do
that in subsequent commits.

* Suspense in Batched Mode

Should have same semantics as Concurrent Mode.

* Use RootTag field to configure type of root

There are three types of roots: Legacy, Batched, and Concurrent.

* flushSync should not flush batched work

Treat Sync and Batched expiration times separately. Only Sync updates
are pushed to our internal queue of synchronous callbacks.

Renamed `flushImmediateQueue` to `flushSyncCallbackQueue` for clarity.
2019-05-13 14:30:39 -07:00
Andrew Clark
72ca3c60e7
Bump scheduler version to 0.14.0 (#15395) 2019-04-29 18:10:11 -07:00
Dominic Gannaway
aece8119cf
Refactor EventComponent logic + add onOwnershipChange callback (#15354) 2019-04-09 12:47:32 +01:00
Dominic Gannaway
4064ea9fa6
Experimental event API: Support EventComponent onUnmount responder callback (#15335) 2019-04-06 08:16:57 +01:00
Dominic Gannaway
4fbbae8afa
Add full TouchHitTarget hit slop (experimental event API) to ReactDOM (#15308) 2019-04-06 07:51:21 +01:00
Andrew Clark
4d5cb64aa2
Rewrite ReactFiberScheduler for better integration with Scheduler package (#15151)
* Rewrite ReactFiberScheduler

Adds a new implementation of ReactFiberScheduler behind a feature flag.
We will maintain both implementations in parallel until the new one
is proven stable enough to replace the old one.

The main difference between the implementations is that the new one is
integrated with the Scheduler package's priority levels.

* Conditionally add fields to FiberRoot

Some fields only used by the old scheduler, and some by the new.

* Add separate build that enables new scheduler

* Re-enable skipped test

If synchronous updates are scheduled by a passive effect, that work
should be flushed synchronously, even if flushPassiveEffects is
called inside batchedUpdates.

* Passive effects have same priority as render

* Revert ability to cancel the current callback

React doesn't need this anyway because it never schedules callbacks if
it's already rendering.

* Revert change to FiberDebugPerf

Turns out this isn't neccessary.

* Fix ReactFiberScheduler dead code elimination

Should initialize to nothing, then assign the exports conditionally,
instead of initializing to the old exports and then reassigning to the
new ones.

* Don't yield before commit during sync error retry

* Call Scheduler.flushAll unconditionally in tests

Instead of wrapping in enableNewScheduler flag.
2019-04-02 15:49:07 -07:00
Sunil Pai
aed0e1c30c
await act(async () => ...) (#14853)
This took a while, but I'm happy I went through it. Some key moments - recursively flushing effects, flushing microtasks on each async turn, and my team's uncompromising philosophy on code reuse. Really happy with this. I still want to expand test coverage, and I have some more small related todos, but this is good to land. On to the next one. 

Soundtrack to landing this - https://open.spotify.com/track/0MF8I8OUo8kytiOo8aSHYq?si=gSWqUheKQbiQDXzptCXHTg

* hacked up act(async () => {...})

* move stuff around

* merge changes

* abstract .act warnings and stuff. all renderers. pass all tests.

* move testutils.act back into testutils

* move into scheduler, rename some bits

* smaller bundle

* a comment for why we don't do typeof === 'function'

* fix test

* pass tests - fire, prod

* lose actContainerElement

* tighter

* write a test for TestRenderer

it's an odd one, because not only does sync act not flush effects correctly, but the async one does (wut). verified it's fine with the dom version.

* lint

* rewrote to move flushing logic closer to the renderer

the scheduler's `flushPassiveEffects` didn't work as expected for the test renderer, so I decided to go back to the hack (rendering a dumb container) This also makes reactdom not as heavy (by a few bytes, but still).

* move it around so the delta isn't too bad

* cleanups

fix promise chaining
propagate errors correctly
test for thenable the 'right' way
more tests!
tidier!
ponies!

* Stray comment

* recursively flush effects

* fixed tests

* lint, move noop.act into react-reconciler

* microtasks when checking if called, s/called/calledLog, cleanup

* pass fb lint

we could have globally changed our eslint config to assume Promise is available, but that means we expect a promise polyfill on the page, and we don't yet. this code is triggered only in jest anyway, and we're fairly certain Promise will be available there. hence, the once-off disable for the check

* shorter timers, fix a test, test for Promise

* use global.Promise for existence check

* flush microtasks

* a version that works in browsers (that support postMessage)

I also added a sanity fixture inside fixtures/dom/ mostly for me.

* hoist flushEffectsAndMicroTasks

* pull out tick logic from ReactFiberScheduler

* fix await act (...sync) hanging

- fix a hang when awaiting sync logic
- a better async/await test for test renderer

* feedback changes

- use node's setImmediate if available
- a warning if MessageChannel isn't available
- rename some functions

* pass lint/flow checks (without requiring a Promise polyfill/exclusion)

* prettier

the prettiest, even.

* use globalPromise for the missed await warning

* __DEV__ check for didWarnAboutMessageChannel

* thenables and callbacks instead of promises, pass flow/lint

* tinier. better.

- pulled most bits out of FiberScheduler
- actedUpdates uses callbacks now

* pass build validation

* augh prettier

* golfing 7 more chars

* Test that effects are not flushed without also flushing microtasks

* export doesHavePendingPassiveEffects, nits

* createAct()

* dead code

* missed in merge?

* lose the preflushing bits

* ugh prettier

* removed `actedUpdates()`, created shared/actingUpdatesScopeDepth

* rearrange imports so builds work, remove the hack versions of flushPassiveEffects

* represent actingUpdatesScopeDepth as a tuple [number]

* use a shared flag on React.__SECRET...

* remove createAct, setup act for all relevant renderers

* review feedback

shared/enqueueTask

import ReactSharedInternals from 'shared/ReactSharedInternals';

simpler act() internals

ReactSharedInternals.ReactShouldWarnActingUpdates

* move act() implementation into createReactNoop

* warnIfNotCurrentlyActingUpdatesInDev condition check order
2019-04-02 22:33:31 +01:00
Dominic Gannaway
6a1e6b2f78
Experimental event API: loosen EventTarget constraints and warnings (#15292)
* Remove warning for event targets being direct children of event component

* Addressed feedback and added more test coverage + warnings
2019-04-02 19:49:28 +01:00
Dominic Gannaway
9444a54720
Warn on nested EventTragets in experimental event API (#15287) 2019-04-01 15:47:03 +01:00
Dan Abramov
fb6b50871b Update versions for 16.8.6 2019-03-27 23:58:16 -07:00
Dan Abramov
8e9a013c07 Release 16.8.5 2019-03-22 16:47:59 +00:00
Brian Vaughn
56035dac64
unstable_Profiler -> Profiler (#15172) 2019-03-21 09:18:34 -07:00
Dominic Gannaway
b83e01cade
Adds more scaffolding for experimental event API (#15112)
* Adds more scaffolding for experimental event API
2019-03-20 11:20:17 +00:00
Jared Palmer
2b93d686e3 Add more info to invalid hook call error message (#15139)
* Add more info to invalid hook call error message

* Update other renderers + change call to action

* Update related tests for new hooks error message

* Fix lint errors
2019-03-18 18:22:38 +00:00
Dan Abramov
8d60bd4dc2
[Shallow] Implement setState for Hooks and remount on type change (#15120)
* Throw away old shallow renderer state on type change

This worked in function components but was broken for classes. It incorrectly retained the old instance even if the type was different.

* Remove _previousComponentIdentity

We only needed this because we didn't correctly reset based on type. Now we do so this can go away.

* Use _reset when unmounting

* Use arbitrary componentIdentity

There was no particular reason it was set to element.type. We just wanted to check if something is a render phase update.

* Support Hook state updates in shallow renderer
2019-03-15 22:30:32 +00:00
Brandon Dail
b283d75c17 Support React.memo in ReactShallowRenderer (#14816)
* Support React.memo in ReactShallowRenderer

ReactShallowRenderer uses element.type frequently, but with React.memo
elements the actual type is element.type.type. This updates
ReactShallowRenderer so it uses the correct element type for Memo
components and also validates the inner props for the wrapped
components.

* Allow Rect.memo to prevent re-renders

* Support memo(forwardRef())

* Dont call memo comparison function on initial render

* Fix test

* Small tweaks
2019-03-15 22:17:09 +00:00
Sebastian Silbermann
52c870c8d9 Fix shallow renderer not allowing hooks in forwardRef render functions (#15100)
* test: Add test for shallow + forwardRef + hook

* fix(react-test-renderer): shallow forwardRef hooks
2019-03-15 15:28:34 +00:00
Dominic Gannaway
0c03a47436
Adds experimental event API scaffolding (#15108)
* Adds experimental event API scaffolding
2019-03-14 17:02:42 +00:00
Andrew Clark
1e3b6192b5
Import Scheduler directly, not via host config (#14984)
* Import Scheduler directly, not via host config

We currently schedule asynchronous tasks via the host config. (The host
config is a static/build-time dependency injection system that varies
across different renderers — DOM, native, test, and so on.) Instead of
calling platform APIs like `requestIdleCallback` directly, each renderer
implements a method called `scheduleDeferredCallback`.

We've since discovered that when scheduling tasks, it's crucial that
React work is placed in the same queue as other, non-React work on the
main thread. Otherwise, you easily end up in a starvation scenario where
rendering is constantly interrupted by less important tasks. You need a
centralized coordinator that is used both by React and by other
frameworks and application code. This coordinator must also have a
consistent API across all the different host environments, for
convention's sake and so product code is portable — e.g. so the same
component can work in both React Native and React Native Web.

This turned into the Scheduler package. We will have different builds of
Scheduler for each of our target platforms. With this approach, we treat
Scheduler like a built-in platform primitive that exists wherever React
is supported.

Now that we have this consistent interface, the indirection of the host
config no longer makes sense for the purpose of scheduling tasks. In
fact, we explicitly do not want renderers to scheduled task via any
system except the Scheduler package.

So, this PR removes `scheduleDeferredCallback` and its associated
methods from the host config in favor of directly importing Scheduler.

* Missed an extraneous export
2019-03-06 14:41:45 -08:00
Brian Vaughn
a9aa24ed8d 16.8.4 and changelog 2019-03-05 15:17:42 -08:00
Andrew Clark
69060e1da6
Swap expect(ReactNoop) for expect(Scheduler) (#14971)
* Swap expect(ReactNoop) for expect(Scheduler)

In the previous commits, I upgraded our custom Jest matchers for the
noop and test renderers to use Scheduler under the hood.

Now that all these matchers are using Scheduler, we can drop
support for passing ReactNoop and test roots and always pass
Scheduler directly.

* Externalize Scheduler in noop and test bundles

I also noticed we don't need to regenerator runtime in noop anymore.
2019-02-28 12:54:47 -08:00
Andrew Clark
ccb2a8a44e
Replace test renderer's fake Scheduler implementation with mock build (#14970)
* Replace test renderer's fake Scheduler implementation with mock build

The test renderer has its own mock implementation of the Scheduler
interface, with the ability to partially render work in tests. Now that
this functionality has been lifted into a proper mock Scheduler build,
we can use that instead.

* Fix Profiler tests in prod
2019-02-28 10:50:38 -08:00
Andrew Clark
8e25ed20bd
Unify noop and test renderer assertion APIs (#14952)
* Throw in tests if work is done before emptying log

Test renderer already does this. Makes it harder to miss unexpected
behavior by forcing you to assert on every logged value.

* Convert ReactNoop tests to use jest matchers

The matchers warn if work is flushed while the log is empty. This is
the pattern we already follow for test renderer. I've used the same APIs
as test renderer, so it should be easy to switch between the two.
2019-02-25 19:01:45 -08:00
Dan Abramov
8c1966590a Release 16.8.3 2019-02-21 18:09:18 +00:00
Dan Abramov
3e55560438 Release 16.8.2 2019-02-14 19:13:15 +00:00
Dan Abramov
0e4135e8c2
Revert "[ShallowRenderer] Queue/rerender on dispatched action after render component with hooks (#14802)" (#14839)
This reverts commit 6d4038f0a6.
2019-02-13 16:52:14 +00:00
Rodrigo Ribeiro
6d4038f0a6 [ShallowRenderer] Queue/rerender on dispatched action after render component with hooks (#14802)
* [shallow-renderer] Rerender on dispatched action out of render
2019-02-13 15:59:02 +00:00
Brian Vaughn
45fc46bfa0 16.8.1 packages 2019-02-06 18:21:33 +00:00
Sunil Pai
1107b9673c
[TestUtils.act] warn when using TestUtils.act in node (#14768)
* warn when using TestUtils.act in node

* s/warns/throws

* s/throw/warn

* consistent ellipses
2019-02-06 16:25:26 +00:00
Brian Vaughn
008a2ab9cd 16.8.0 2019-02-06 08:04:00 +00:00
Sunil Pai
d1326f466a
[TestUtils.act] fix return result checking (#14758)
* fix .act return value testing when result === null

* nit
2019-02-05 17:34:21 +00:00
Sunil Pai
267ed98146
expose TestUtils.act() for batching actions in tests (#14744)
* expose unstable_interact for batching actions in tests

* move to TestUtils

* move it all into testutils

* s/interact/act

* warn when calling hook-like setState outside batching mode

* pass tests

* merge-temp

* move jsdom test to callsite

* mark failing tests

* pass most tests (except one)

* augh IE

* pass fuzz tests

* better warning, expose the right batchedUpdates on TestRenderer for www

* move it into hooks, test for dom

* expose a flag on the host config, move stuff around

* rename, pass flow

* pass flow... again

* tweak .act() type

* enable for all jest environments/renderers; pass (most) tests.

* pass all tests

* expose just the warning from the scheduler

* don't return values

* a bunch of changes.

can't return values from .act
don't try to await .act calls
pass tests

* fixes and nits

* "fire events that udpates state"

* nit

* 🙄

* my bad

* hi andrew

(prettier fix)
2019-02-05 16:10:16 +00:00
Andrew Clark
fb3f7bfde9
Avoid importing Scheduler directly (#14757)
* Avoid importing Scheduler directly

The reconciler should not depend directly on Scheduler. This adds it to
the host config for the renderer instead.

(Except for `scheduler/tracing` imports, which are used only by the
profiling build. I've left those imports as-is, though I'm open to
directing those through the host config, too.)

* Make throwaway root id longer to appease Brian
2019-02-05 03:21:25 -08:00
Dan Abramov
c21c41ecfa
Tweak invalid Hook warning and error (#14747) 2019-02-01 21:05:13 +00:00
Andrew Clark
ba6477aa3c
Improve Reducer Hook's lazy init API (#14723)
* Improve Reducer Hook's lazy init API

* Use generic type for initilizer input

Still requires an `any` cast in the case where `init` function is
not provided.
2019-01-29 17:39:24 -08:00
Andrew Clark
cb1ff430e8 Phased dispatcher (#14701)
* Move DEV-only function right above where it's used

I don't like looking at this top-level function #petty

* Use different dispatchers for functions & classes

Classes support readContext, but not any of the other dispatcher
methods. Function support all methods.

This is a more robust version of our previous strategy of checking
whether `currentlyRenderingFiber` is null.

As a next step, we can use a separate dispatcher for each phase of the
render cycle (mount versus update).

* Use separate dispatchers for mount and update

* Remove mount code from update path

Deletes mount-specific code from the update path, since it should be
unreachable. To continue supporting progressive enhancement (mounting
new hooks at the end of the list), we detect when there are no more
current hooks and switch back to the mount dispatcher. Progressive
enhancement isn't officially supported yet, so it will continue to warn.

* Factoring nits

* Fix Flow

Had to cheat more than I would like

* More Flow nits

* Switch back to using a special dispatcher for nested hooks in DEV

In order for this strategy to work, I had to revert progressive
enhancement support (appending hooks to the end). It was previously a
warning but now it results in an error. We'll reconsider later.

* Always pass args to updateState and updateReducer

Even though the extra args are only used on mount, to ensure
type consistency.
2019-01-29 16:32:15 -08:00
Brian Vaughn
6cb26774e2
Enable hooks! (#14679)
* Turned enableHooks feature flag on everywhere
* Removed useHooks feature flag from tests (now that it's on by default)
* Remove useHooks feature flag entirely
2019-01-23 13:28:09 -08:00
Dan Abramov
baa6d40fc8
Mention forwardRef() in <Fn ref={...} /> errors and warnings (#14644) 2019-01-21 16:01:48 +00:00
Grey Baker
b66e6e41e6 Add directory details to the package.json of all packages (#14628)
Specifying the directory as part of the `repository` field in a `package.json`
allows third party tools to provide better support when working with monorepos.
For example, it allows them to correctly construct a commit diff for a specific
package.

This format was accepted by npm in https://github.com/npm/rfcs/pull/19.
2019-01-18 20:21:12 +00:00
Yi-Shan, Chen
4f332885a2 Fix shallow renderer set instance state after gDSFP before calling sCU (#14613)
* Fix shallow renderer set instance state after gDSFP before calling sCU

* Update ReactShallowRenderer.js

* Unwind abstraction

* Fewer names
2019-01-18 02:31:14 +00:00
Dan Abramov
be457ca685
Small tweaks to SSR to match #14594 (#14618)
* Small tweaks to SSR to match #14594

* Remove unnecessary comparison
2019-01-18 00:52:13 +00:00
Dominic Gannaway
4feab7fc92
Add hooks support to ReactShallowRenderer (#14567)
* Add hook support to ReactShallowRenderer
2019-01-17 17:42:27 +00:00
Andrew Clark
c695b2384f React v16.7.0 2018-12-19 17:23:14 -08:00
Brian Vaughn
98eb5ae531
TestRenderer toJSON should not expose the Array wrapper Suspense uses for hidden trees (#14392) 2018-12-05 11:09:51 -08:00
Brian Vaughn
686f1060ad
Publish a local release (canary or stable) to NPM (#14260)
New release scripts.

Learn more at https://github.com/facebook/react/blob/master/scripts/release/README.md
2018-11-23 12:37:18 -08:00
Sebastian Markbåge
c954efa70f
Remove import * as pattern from the codebase (#14282)
Whenever we do this, Rollup needs to materialize this as an object.
This causes it to also add the Babel compatibility property which is
unnecessary bloat. However, since when we use these, we leak the object
this often also deopts any compiler optimizations.

If we really need an object we should export default an object.

Currently there is an exception for DOMTopLevelEventTypes since
listing out the imports is a PITA and it doesn't escape so it should
get properly inlined. We should probably move to a different pattern
to avoid this for consistency though.
2018-11-19 15:32:54 -08:00
Andrew Clark
b50e63ef53 Updating package versions for release 16.6.1 2018-11-06 18:19:57 -08:00
Sebastian Markbåge
fd1256a561
Add Debug Tools Package for Introspection of Hooks (#14085)
* Add debug tools package

* Add basic implementation

* Implement inspection of the current state of hooks using the fiber tree

* Support useContext hooks inspection by backtracking from the Fiber

I'm not sure this is safe because the return fibers may not be current
but close enough and it's fast.

We use this to set up the current values of the providers.

* rm copypasta

* Use lastIndexOf

Just in case. I don't know of any scenario where this can happen.

* Support ForwardRef

* Add test for memo and custom hooks

* Support defaultProps resolution
2018-11-05 10:02:59 -08:00
Andrew Clark
8c67bbf183
[scheduler] Deadline object -> shouldYield (#14025)
* [scheduler] Deadline object -> shouldYield

Instead of using a requestIdleCallback-style deadline object, expose a
method Scheduler.shouldYield that returns true if there's a higher
priority event in the queue.

* Nits
2018-10-30 13:47:51 -07:00
Dan Abramov
6c29eabf78 Updating package versions for release 16.6.0 2018-10-23 16:23:41 -07:00
Dan Abramov
d520b358d6 Revert all package versions to 16.5.2 state
Our release script is getting really confused so I'm resetting to last working state.
2018-10-23 16:18:28 -07:00
Dan Abramov
8f1ec7649e Bump versions to beta.0 2018-10-23 16:01:57 -07:00
Andrew Clark
cbbc2b6c4d
[Synchronous Suspense] Suspending a class outside concurrent mode (#13926)
* [Synchronous Suspense] Suspending a class outside concurrent mode

When a class component suspends during mount outside concurrent mode,
change the tag so it's not mistaken for a completed component. For
example, we should not call componentWillUnmount if it is deleted.

* PR nits
2018-10-23 11:36:56 -07:00
Dan Abramov
b5c0852fdd
Bump version to 16.6.0-beta.0 (#13906)
* Bump version to 16.6.0-beta.0

* Root too
2018-10-20 13:03:15 -04:00
Dan Abramov
769b1f270e
pure -> memo (#13905) 2018-10-20 12:46:23 -04:00
Sebastian Markbåge
15b11d23f9
Allow arbitrary types to be wrapped in pure (#13903)
* Allow arbitrary types to be wrapped in pure

This creates an outer fiber that container the pure check and an inner
fiber that represents which ever type of component.

* Add optimized fast path for simple pure function components

Special cased when there are no defaultProps and it's a simple function
component instead of class. This doesn't require an extra fiber.

We could make it so that this also works with custom comparer but that
means we have to go through one extra indirection to get to it.
Maybe it's worth it, donno.
2018-10-20 00:32:16 -07:00
Sebastian Markbåge
95a313ec0b Unfork Lazy Component Branches (#13902)
* Introduce elementType field

This will be used to store the wrapped type of an element. E.g. pure and
lazy.

The existing type field will be used for the unwrapped type within them.

* Store the unwrapped type on the type field of lazy components

* Use the raw tags for lazy components

Instead, we check if the elementType and type are equal to test if
we need to resolve props. This is slightly slower in the normal case
but will yield less code and branching.

* Clean up lazy branches

* Collapse work tag numbering

* Split IndeterminateComponent out from Lazy

This way we don't have to check the type in a hacky way in the
indeterminate path. Also, lets us deal with lazy that resolves to
indeterminate and such.

* Missing clean up in rebase
2018-10-19 22:22:45 -07:00
Andrew Clark
dac9202a9c
Hide timed-out children instead of deleting them so their state is preserved (#13823)
* Store the start time on `updateQueue` instead of `stateNode`

Originally I did this to free the `stateNode` field to store a second
set of children. I don't we'll need this anymore, since we use fragment
fibers instead. But I still think using `updateQueue` makes more sense
so I'll leave this in.

* Use fragment fibers to keep the primary and fallback children separate

If the children timeout, we switch to showing the fallback children in
place of the "primary" children. However, we don't want to delete the
primary children because then their state will be lost (both the React
state and the host state, e.g. uncontrolled form inputs). Instead we
keep them mounted and hide them. Both the fallback children AND the
primary children are rendered at the same time. Once the primary
children are un-suspended, we can delete the fallback children — don't
need to preserve their state.

The two sets of children are siblings in the host environment, but
semantically, for purposes of reconciliation, they are two separate
sets. So we store them using two fragment fibers.

However, we want to avoid allocating extra fibers for every placeholder.
They're only necessary when the children time out, because that's the
only time when both sets are mounted.

So, the extra fragment fibers are only used if the children time out.
Otherwise, we render the primary children directly. This requires some
custom reconciliation logic to preserve the state of the primary
children. It's essentially a very basic form of re-parenting.

* Use `memoizedState` to store various pieces of SuspenseComponent's state

SuspenseComponent has three pieces of state:

- alreadyCaptured: Whether a component in the child subtree already
suspended. If true, subsequent suspends should bubble up to the
next boundary.
- didTimeout: Whether the boundary renders the primary or fallback
children. This is separate from `alreadyCaptured` because outside of
strict mode, when a boundary times out, the first commit renders the
primary children in an incomplete state, then performs a second commit
to switch the fallback. In that first commit, `alreadyCaptured` is
false and `didTimeout` is true.
- timedOutAt: The time at which the boundary timed out. This is separate
from `didTimeout` because it's not set unless the boundary
actually commits.


These were previously spread across several fields.

This happens to make the non-strict case a bit less hacky; the logic for
that special case is now mostly localized to the UnwindWork module.

* Hide timed-out Suspense children

When a subtree takes too long to load, we swap its contents out for
a fallback to unblock the rest of the tree. Because we don't want
to lose the state of the timed out view, we shouldn't actually delete
the nodes from the tree. Instead, we'll keep them mounted and hide
them visually. When the subtree is unblocked, we un-hide it, having
preserved the existing state.

Adds additional host config methods. For mutation mode:

- hideInstance
- hideTextInstance
- unhideInstance
- unhideTextInstance

For persistent mode:

- cloneHiddenInstance
- cloneUnhiddenInstance
- createHiddenTextInstance

I've only implemented the new methods in the noop and test renderers.
I'll implement them in the other renderers in subsequent commits.

* Include `hidden` prop in noop renderer's output

This will be used in subsequent commits to test that timed-out children
are properly hidden.

Also adds getChildrenAsJSX() method as an alternative to using
getChildren(). (Ideally all our tests would use test renderer #oneday.)

* Implement hide/unhide host config methods for DOM renderer

For DOM nodes, we hide using `el.style.display = 'none'`.

Text nodes don't have style, so we hide using `text.textContent = ''`.

* Implement hide/unhide host config methods for Art renderer

* Create DOM fixture that tests state preservation of timed out content

* Account for class components that suspend outside concurrent mode

Need to distinguish mount from update. An unfortunate edge case :(

* Fork appendAllChildren between persistent and mutation mode

* Remove redundant check for existence of el.style

* Schedule placement effect on indeterminate components

In non-concurrent mode, indeterminate fibers may commit in an
inconsistent state. But when they update, we should throw out the
old fiber and start fresh. Which means the new fiber needs a
placement effect.

* Pass null instead of current everywhere in mountIndeterminateComponent
2018-10-18 15:37:16 -07:00
Dan Abramov
77f8dfd81e Updating package versions for release 16.6.0-alpha.8af6728 2018-10-10 17:12:05 +01:00
Dan Abramov
40a521aa72
Terminology: Functional -> Function Component (#13775)
* Terminology: Functional -> Function Component

* Drop the "stateless" (functions are already stateless, right?)
2018-10-04 22:44:46 +01:00
Andrew Clark
96bcae9d50
Jest + test renderer helpers for concurrent mode (#13751)
* Jest + test renderer helpers for concurrent mode

Most of our concurrent React tests use the noop renderer. But most
of those tests don't test the renderer API, and could instead be
written with the test renderer. We should switch to using the test
renderer whenever possible, because that's what we expect product devs
and library authors to do. If test renderer is sufficient for writing
most React core tests, it should be sufficient for others, too. (The
converse isn't true but we should aim to dogfood test renderer as much
as possible.)

This PR adds a new package, jest-react (thanks @cpojer). I've moved
our existing Jest matchers into that package and added some new ones.

I'm not expecting to figure out the final API in this PR. My goal is
to land something good enough that we can start dogfooding in www.

TODO: Continue migrating Suspense tests, decide on better API names

* Add additional invariants to prevent common errors

- Errors if user attempts to flush when log of yields is not empty
- Throws if argument passed to toClearYields is not ReactTestRenderer

* Better method names

- toFlushAll -> toFlushAndYield
- toFlushAndYieldThrough ->
- toClearYields -> toHaveYielded

Also added toFlushWithoutYielding

* Fix jest-react exports

* Tweak README
2018-10-03 18:37:41 -06:00
Andrew Clark
a0733fe13d
pure (#13748)
* pure

A higher-order component version of the `React.PureComponent` class.
During an update, the previous props are compared to the new props. If
they are the same, React will skip rendering the component and
its children.

Unlike userspace implementations, `pure` will not add an additional
fiber to the tree.

The first argument must be a functional component; it does not work
with classes.

`pure` uses shallow comparison by default, like `React.PureComponent`.
A custom comparison can be passed as the second argument.

Co-authored-by: Andrew Clark <acdlite@fb.com>
Co-authored-by: Sophie Alpert <sophiebits@fb.com>

* Warn if first argument is not a functional component
2018-09-27 15:25:38 -07:00
Dominic Gannaway
0dc0ddc1ef
Rename AsyncMode -> ConcurrentMode (#13732)
* Rename AsyncMode -> ConcurrentMode
2018-09-26 17:13:02 +01:00
Brian Ng
970a34baed Bump babel-eslint and remove flow supressions (#13727) 2018-09-25 22:48:31 +01:00
Dan Abramov
7ea3ca1d13
Rename schedule to scheduler (#13683) 2018-09-19 01:26:28 +01:00
Brian Vaughn
4269fafb0a Updating package versions for release 16.5.2 2018-09-18 11:24:33 -07:00
Brian Vaughn
4380f9ba17 Revert "Updating package versions for release 16.6.0-alpha.0"
This reverts commit 351c9015c8.
2018-09-18 11:00:13 -07:00
Brian Vaughn
351c9015c8 Updating package versions for release 16.6.0-alpha.0 2018-09-17 14:59:57 -07:00
Dan Abramov
8b93a60c5e Updating package versions for release 16.5.1 2018-09-13 19:31:18 +01:00
Dan Abramov
144328fe81
Enable no-use-before-define rule (#13606) 2018-09-10 16:15:18 +01:00
Héctor Ramos
b87aabdfe1
Drop the year from Facebook copyright headers and the LICENSE file. (#13593) 2018-09-07 15:11:23 -07:00
Brian Vaughn
6255cc3949 Updating package versions for release 16.5.0 2018-09-06 09:29:36 -07:00
Brian Vaughn
b92f947af1 Rename "react-scheduler" package to "schedule" (#13543)
* Git moved packages/react-scheduler -> packages/schedule

* Global find+replace 'react-scheduler' -> 'schedule'

* Global find+replace 'ReactScheduler' -> 'Scheduler'

* Renamed remaining files "ReactScheduler" -> "Schedule"

* Add thank-you note to schedule package README

* Replaced schedule package versions 0.1.0-alpha-1 -> 0.2.0

* Patched our local fixtures to work around Yarn install issue

* Removed some fixture hacks
2018-09-03 19:27:50 +01:00
Brian Vaughn
46950a3dfc
Interaction tracking follow up (#13509)
* Merged interaction-tracking package into react-scheduler
* Add tracking API to FB+www builds
* Added Rollup plugin to strip no-side-effect imports from Rollup bundles
* Re-bundle tracking and scheduling APIs on SECRET_INTERNALS object for UMD build (and provide lazy forwarding methods)
* Added some additional tests and fixtures
* Fixed broken UMD fixture in master (#13512)
2018-09-01 12:00:00 -07:00
Sophie Alpert
340bfd9393
Rename ReactTypeOfWork to ReactWorkTags, ReactTypeOfSideEffect to ReactSideEffectTags (#13476)
* Rename ReactTypeOfWork to ReactWorkTags

And `type TypeOfWork` to `type WorkTag`.

* Rename ReactTypeOfSideEffect too
2018-08-26 13:40:27 -07:00
Dan Abramov
90c92c7007 Fix warning message 2018-08-21 18:44:34 +01:00
Brian Vaughn
026aa9c978
Bumped version to 16.4.3-alpha.0 (#13448)
* Bumped version to 16.4.3-alpha.0
* Bump react-is peer dep version in react-test-renderer
2018-08-20 14:28:43 -07:00
Brian Vaughn
d670bdc6b1
Warn about ReactDOM.createPortal usage within ReactTestRenderer (#12895) 2018-08-20 10:03:22 -07:00
Joseph
004cb21bbb Short circuit the logic for exporting a module (#13392)
* short circuit some logic

* revert back to ternary operator
2018-08-20 12:29:40 +01:00
Andrew Clark
5031ebf6be
Accept promise as element type (#13397)
* Accept promise as element type

On the initial render, the element will suspend as if a promise were
thrown from inside the body of the unresolved component. Siblings should
continue rendering and if the parent is a Placeholder, the promise
should be captured by that Placeholder.

When the promise resolves, rendering resumes. If the resolved value
has a `default` property, it is assumed to be the default export of
an ES module, and we use that as the component type. If it does not have
a `default` property, we use the resolved value itself.

The resolved value is stored as an expando on the promise/thenable.

* Use special types of work for lazy components

Because reconciliation is a hot path, this adds ClassComponentLazy,
FunctionalComponentLazy, and ForwardRefLazy as special types of work.
The other types are not supported, but wouldn't be placed into a
separate module regardless.

* Resolve defaultProps for lazy types

* Remove some calls to isContextProvider

isContextProvider checks the fiber tag, but it's typically called after
we've already refined the type of work. We should get rid of it. I
removed some of them in the previous commit, and deleted a few more
in this one. I left a few behind because the remaining ones would
require additional refactoring that feels outside the scope of this PR.

* Remove getLazyComponentTypeIfResolved

* Return baseProps instead of null

The caller compares the result to baseProps to see if anything changed.

* Avoid redundant checks by inlining getFiberTagFromObjectType

* Move tag resolution to ReactFiber module

* Pass next props to update* functions

We should do this with all types of work in the future.

* Refine component type before pushing/popping context

Removes unnecessary checks.

* Replace all occurrences of _reactResult with helper

* Move shared thenable logic to `shared` package

* Check type of wrapper object before resolving to `default` export

* Return resolved tag instead of reassigning
2018-08-16 09:21:59 -07:00
Andrew Clark
71b4e99901
[react-test-renderer] Jest matchers for async tests (#13236)
Adds custom Jest matchers that help with writing async tests:

- `toFlushThrough`
- `toFlushAll`
- `toFlushAndThrow`
- `toClearYields`

Each one accepts an array of expected yielded values, to prevent
false negatives.

Eventually I imagine we'll want to publish this on npm.
2018-07-19 10:26:24 -07:00
Andrew Clark
e4e58343e4
Move unstable_yield to main export (#13232)
The `yield` method isn't tied to any specific root. Putting this
on the main export enables test components that are not within scope
to yield even if they don't have access to the currently rendering
root instance. This follows the pattern established by ReactNoop.

Added a `clearYields` method, too, for reading values that were yielded
out of band. This is also based on ReactNoop.
2018-07-18 16:10:56 -07:00
Johan Henriksson
9f78913b20 Update prettier (#13205)
* Update Prettier to 1.13.7

* Apply Prettier changes

* Pin prettier version

* EOL
2018-07-17 20:18:34 +01:00
Dan Abramov
e6076ecf48 Remove ad-hoc forks of getComponentName() and fix it (#13197)
* Fix getComponentName() for types with nested $$typeof

* Temporarily remove Profiler ID from messages

* Change getComponentName() signature to take just type

It doesn't actually need the whole Fiber.

* Remove getComponentName() forks in isomorphic and SSR

* Remove unnecessary .type access where we already have a type

* Remove unused type
2018-07-12 07:32:06 -07:00
Brian Vaughn
1f32d3c6dc
Test renderer flushAll method verifies an array of expected yields (#13174) 2018-07-09 09:05:13 -07:00
Brian Vaughn
095dd5049c
Add DEV warning if forwardRef function doesn't use the ref param (#13168)
* Add DEV warning if forwardRef function doesn't use the ref param
* Fixed a forwardRef arity warning in another test
2018-07-07 08:11:30 -07:00
Brandon Dail
ebbd221432
Configure react-test-renderer as a secondary (#13164) 2018-07-06 16:04:45 -07:00
Andrew Clark
aa8266c4f7
Prepare placeholders before timing out (#13092)
* Prepare placeholders before timing out

While a tree is suspended, prepare for the timeout by pre-rendering the
placeholder state.

This simplifies the implementation a bit because every render now
results in a completed tree.

* Suspend inside an already timed out Placeholder

A component should be able to suspend inside an already timed out
placeholder. The time at which the placeholder committed is used as 
the start time for a subsequent suspend.

So, if a placeholder times out after 3 seconds, and an inner
placeholder has a threshold of 2 seconds, the inner placeholder will
not time out until 5 seconds total have elapsed.
2018-07-03 19:22:41 -07:00
Toru Kobayashi
c039c16f21 Fix this in a functional component for ShallowRenderer (#13144) 2018-07-03 17:47:40 +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
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
Dan Abramov
0b87b27906 Updating package versions for release 16.4.1 2018-06-13 17:16:10 +01:00
Rafał Ruciński
945fc1bfce Call gDSFP with the right state in react-test-render (#13030)
* Call gDSFP with the right state in react-test-render

* Change the test
2018-06-12 23:36:50 +01:00
Dan Abramov
30bc8ef792
Allow multiple root children in test renderer traversal API (#13017) 2018-06-11 20:03:51 +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