Commit Graph

285 Commits

Author SHA1 Message Date
Andrew Clark 8f05f2bd6d
Land Lanes implementation in old fork (#19108)
* Add autofix to cross-fork lint rule

* replace-fork: Replaces old fork contents with new

For each file in the new fork, copies the contents into the
corresponding file of the old fork, replacing what was already there.

In contrast to merge-fork, which performs a three-way merge.

* Replace old fork contents with new fork

First I ran  `yarn replace-fork`.

Then I ran `yarn lint` with autofix enabled. There's currently no way to
do that from the command line (we should fix that), so I had to edit the
lint script file.

* Manual fix-ups

Removes dead branches, removes prefixes from internal fields.  Stuff
like that.

* Fix DevTools tests

DevTools tests only run against the old fork, which is why I didn't
catch these earlier.

There is one test that is still failing. I'm fairly certain it's related
to the layout of the Suspense fiber: we no longer conditionally wrap the
primary children. They are always wrapped in an extra fiber.

Since this has been running in www for weeks without major issues, I'll
defer fixing the remaining test to a follow up.
2020-06-11 20:05:15 -07:00
Andrew Clark 03e6b8ba2f
Make LegacyHidden match semantics of old fork (#18998)
Facebook currently relies on being able to hydrate hidden HTML. So
skipping those trees is a regression.

We don't have a proper solution for this in the new API yet. So I'm
reverting it to match the old behavior.

Now the server renderer will treat LegacyHidden the same as a fragment,
with no other special behavior. We can only get away with this because
we assume that every instance of LegacyHidden is accompanied by a host
component wrapper. In the hidden mode, the host component is given a
`hidden` attribute, which ensures that the initial HTML is not visible.
To support the use of LegacyHidden as a true fragment, without an extra
DOM node, we will have to hide the initial HTML in some other way.
2020-05-25 18:16:53 -07:00
Andrew Clark 8b9c4d1688
Expose LegacyHidden type and disable <div hidden /> API in new fork (#18891)
* Expose LegacyHidden type

I will use this internally at Facebook to migrate away from
<div hidden />. The end goal is to migrate to the Offscreen type, but
that has different semantics. This is an incremental step.

* Disable <div hidden /> API in new fork

Migrates to the unstable_LegacyHidden type instead. The old fork does
not support the new component type, so I updated the tests to use an
indirection that picks the correct API. I will remove this once the
LegacyHidden (and/or Offscreen) type has landed in both implementations.

* Add gated warning for `<div hidden />` API

Only exists so we can detect callers in www and migrate them to the new
API. Should not visible to anyone outside React Core team.
2020-05-11 20:02:08 -07:00
Brian Vaughn 36cab2720a
DevTools: Improved "native" component stacks (#18656)
* DevTools console override handles new component stack format

DevTools does not attempt to mimic the default browser console format for its component stacks but it does properly detect the new format for Chrome, Firefox, and Safari.
2020-04-21 11:46:11 -07:00
Sebastian Markbåge 940f48b999
Avoid passing custom stacks to console.error (#18685)
* Detect double stacks in the new format in tests

* Remove unnecessary uses of getStackByFiberInDevAndProd

These all execute in the right execution context already.

* Set the debug fiber around the cases that don't have an execution context

* Remove stack detection in our console log overrides

We never pass custom stacks as part of the args anymore.

* Bonus: Don't append getStackAddendum to invariants

We print component stacks for every error anyway so this is just duplicate
information.
2020-04-21 09:22:46 -07:00
Andrew Clark cbafbf4f32 Fix typo in TestFlags
Copypasta when setting up `old` and `new` aliases. `old` should mean
that `enableNewReconciler` is off.
2020-04-14 23:32:53 -07:00
Andrew Clark bec7599067
Migrate conditional tests to gate pragma (#18585)
* Migrate conditional tests to gate pragma

I searched through the codebase for this pattern:

```js
describe('test suite', () => {
  if (!__EXPERIMENTAL__) { // or some other condition
    test("empty test so Jest doesn't complain", () => {});
    return;
  }

  // Unless we're in experimental mode, none of the tests in this block
  // will run.
})
```

and converted them to the `@gate` pragma instead.

The reason this pattern isn't preferred is because you end up disabling
more tests than you need to.

* Add flag for www release channels

Using a heuristic where I check a flag that is known to only be enabled
in www. I left a TODO to instead set the release channel explicitly in
each test config.
2020-04-13 14:45:52 -07:00
Andrew Clark 0c3c27a718
Fix "missing flag" error for non-boolean types (#18592)
Not all test flags are booleans, e.g. the build type
2020-04-13 12:57:31 -07:00
Andrew Clark 65237a237e
Codemod it.experimental to gate pragma (#18582)
* Codemod it.experimental to gate pragma

Find-and-replace followed by Prettier

* Delete it.experimental

Removes the API from our test setup script
2020-04-13 10:28:59 -07:00
Andrew Clark 42d7c2e8f7
Add pragma for feature testing: @gate (#18581)
* Add pragma for feature testing: @gate

The `@gate` pragma declares under which conditions a test is expected to
pass.

If the gate condition passes, then the test runs normally (same as if
there were no pragma).

If the conditional fails, then the test runs and is *expected to fail*.

An alternative to `it.experimental` and similar proposals.

Examples
--------

Basic:

```js
// @gate enableBlocksAPI
test('passes only if Blocks API is available', () => {/*...*/})
```

Negation:

```js
// @gate !disableLegacyContext
test('depends on a deprecated feature', () => {/*...*/})
```

Multiple flags:

```js
// @gate enableNewReconciler
// @gate experimental
test('needs both useEvent and Blocks', () => {/*...*/})
```

Logical operators (yes, I'm sorry):

```js
// @gate experimental && (enableNewReconciler || disableSchedulerTimeoutBasedOnReactExpirationTime)
test('concurrent mode, doesn\'t work in old fork unless Scheduler timeout flag is disabled', () => {/*...*/})
```

Strings, and comparion operators

No use case yet but I figure eventually we'd use this to gate on
different release channels:

```js
// @gate channel ===  "experimental" || channel === "modern"
test('works in OSS experimental or www modern', () => {/*...*/})
```

How does it work?

I'm guessing those last two examples might be controversial. Supporting
those cases did require implementing a mini-parser.

The output of the transform is very straightforward, though.

Input:
```js
// @gate a && (b || c)
test('some test', () => {/*...*/})
```

Output:

```js
_test_gate(ctx => ctx.a && (ctx.b || ctx.c, 'some test'), () => {/*...*/});
```

It also works  with `it`, `it.only`, and `fit`. It leaves `it.skip` and
`xit` alone because those tests are disabled anyway.

`_test_gate` is a global method that I set up in our Jest config. It
works about the same as the existing `it.experimental` helper.

The context (`ctx`) argument is whatever we want it to be. I set it up
so that it throws if you try to access a flag that doesn't exist. I also
added some shortcuts for common gating conditions, like `old`
and `new`:

```js
// @gate experimental
test('experimental feature', () => {/*...*/})

// @gate new
test('only passes in new reconciler', () => {/*...*/})
```

Why implement this as a pragma instead of a runtime API?

- Doesn't require monkey patching built-in Jest methods. Instead it
  compiles to a runtime function that composes Jest's API.
- Will be easy to upgrade if Jest ever overhauls their API or we switch
  to a different testing framework (unlikely but who knows).
- It feels lightweight so hopefully people won't feel gross using it.
  For example, adding or removing a gate pragma will never affect the
  indentation of the test, unlike if you wrapped the test in a
  conditional block.

* Compatibility with console error/warning tracking

We patch console.error and console.warning to track unexpected calls
in our tests. If there's an unexpected call, we usually throw inside
an `afterEach` hook. However, that's too late for tests that we
expect to fail, because our `_test_gate` runtime can't capture the
error. So I also check for unexpected calls inside `_test_gate`.

* Move test flags to dedicated file

Added some instructions for how the flags are set up and how to
use them.

* Add dynamic version of gate API

Receives same flags as the pragma.

If we ever decide to revert the pragma, we can codemod them to use
this instead.
2020-04-13 10:14:34 -07:00
Sebastian Markbåge 98d410f500
Build Component Stacks from Native Stack Frames (#18561)
* Implement component stack extraction hack

* Normalize errors in tests

This drops the requirement to include owner to pass the test.

* Special case tests

* Add destructuring to force toObject which throws before the side-effects

This ensures that we don't double call yieldValue or advanceTime in tests.

Ideally we could use empty destructuring but ES lint doesn't like it.

* Cache the result in DEV

In DEV it's somewhat likely that we'll see many logs that add component
stacks. This could be slow so we cache the results of previous components.

* Fixture

* Add Reflect to lint

* Log if out of range.

* Fix special case when the function call throws in V8

In V8 we need to ignore the first line. Normally we would never get there
because the stacks would differ before that, but the stacks are the same if
we end up throwing at the same place as the control.
2020-04-10 13:32:12 -07:00
Andrew Clark 4c6470cb3b Point ReactDOMForked to the new implementation
Updates Rollup, Jest, and Flow configuration to point to the new
entry points.
2020-04-09 00:03:35 -07:00
Dan Abramov a8f2165e83
Update to Jest 25 (#18480)
* Revert "Revert "Upgrade to jest 25 (#17896)" (#18376)"

This reverts commit fc7835c657.

* Other fixes

* Fix a broken test
2020-04-03 16:37:36 +01:00
Brian Vaughn 5ee0efe832
Remove state update warning for passive effect cleanup functions (#18453) 2020-04-01 10:49:24 -07:00
Dan Abramov d8d2b6e89c
Disable module components dynamically for WWW (#18446)
* Make disableModulePatternComponents dynamic for WWW

* Run both flags and tests and respect the flag in SSR
2020-04-01 18:31:59 +01:00
Dan Abramov bf30e370a5
Remove User Timings (#18417) 2020-03-31 00:29:53 +01:00
Andrew Clark fc7835c657
Revert "Upgrade to jest 25 (#17896)" (#18376)
This reverts commit cf0081263c.

The changes to the test code relate to changes in JSDOM that come with Jest 25:

* Several JSDOM workarounds are no longer needed.
* Several tests made assertions to match incorrect JSDOM behavior (e.g. setAttribute calls) that JSDOM has now patched to match browsers.
  * https://codesandbox.io/s/resets-value-of-datetime-input-to-fix-bugs-in-ios-safari-1ppwh
* JSDOM no longer triggers default actions when dispatching click events.
  * https://codesandbox.io/s/beautiful-cdn-ugn8f
* JSDOM fixed (jsdom/jsdom#2700) a bug so that calling focus() on an already focused element does not dispatch a FocusEvent.
* JSDOM now supports passive events.
* JSDOM has improved support for custom CSS properties.
  * But requires jsdom/cssstyle#112 to land to support webkit prefixed properties.
2020-03-24 10:51:48 -07:00
Sebastian Markbåge 8206b4b864
Wire up bundler configs (#18334)
This allows different flight server and clients to have different configs
depending on bundler to serialize and resolve modules.
2020-03-18 12:18:34 -07:00
Andrew Clark cd48a06547
Set up infra for react-reconciler fork (#18285)
* ReactFiberReconciler -> ReactFiberReconciler.old

* Set up infra for react-reconciler fork

We're planning to land some significant refactors of the reconciler.
We want to be able to gradually roll out the new implementation side-by-
side with the existing one. So we'll create a short lived fork of the
react-reconciler package. Once the new implementation has stabilized,
we'll delete the old implementation and promote the new one.

This means, for as long as the fork exists, we'll need to maintain two
separate implementations. This sounds painful, but since the forks will
still be largely the same, most changes will not require two separate
implementations. In practice, you'll implement the change in the old
fork and then copy paste it to the new one.

This commit only sets up the build and testing infrastructure. It does
not actually fork any modules. I'll do that in subsequent PRs.

The forked version of the reconciler will be used to build a special
version of React DOM. I've called this build ReactDOMForked. It's only
built for www; there's no open source version.

The new reconciler is disabled by default. It's enabled in the
`yarn test-www-variant` command. The reconciler fork isn't really
related to the "variant" feature of the www builds, but I'm piggy
backing on that concept to avoid having to add yet another
testing dimension.
2020-03-12 11:38:32 -07:00
Sebastian Markbåge 99d7371863
[Flight] Split Streaming from Relay Implemenation (#18260)
* Add ReactFlightServerConfig intermediate

This just forwards to the stream version of Flight which is itself forked
between Node and W3C streams.

The dom-relay goes directly to the Relay config though which allows it to
avoid the stream part of Flight.

* Separate streaming protocol into the Stream config

* Split streaming parts into the ReactFlightServerConfigStream

This decouples it so that the Relay implementation doesn't have to encode
the JSON to strings. Instead it can be fed the values as JSON objects and
do its own encoding.

* Split FlightClient into a basic part and a stream part

Same split as the server.

* Expose lower level async hooks to Relay

This requires an external helper file that we'll wire up internally.
2020-03-10 14:55:04 -07:00
Sebastian Markbåge bdc5cc4635
Add Relay Flight Build (#18242)
* Rename to clarify that it's client-only

* Rename FizzStreamer to FizzServer for consistency

* Rename react-flight to react-client/flight

For consistency with react-server. Currently this just includes flight
but it could be expanded to include the whole reconciler.

* Add Relay Flight Build

* Rename ReactServerHostConfig to ReactServerStreamConfig

This will be the config specifically for streaming purposes.
There will be other configs for other purposes.
2020-03-07 11:23:30 -08: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
Andrew Clark 5fbb165602
Hard-code disableModulePatternComponents (#18239)
Hard-coding this until tests are fixed, to unblock master.
2020-03-06 11:09:36 -08:00
Andrew Clark 115cd12d9b
Add test run that uses www feature flags (#18234)
In CI, we run our test suite against multiple build configurations. For
example, we run our tests in both dev and prod, and in both the
experimental and stable release channels. This is to prevent accidental
deviations in behavior between the different builds. If there's an
intentional deviation in behavior, the test author must account
for them.

However, we currently don't run tests against the www builds. That's
a problem, because it's common for features to land in www before they
land anywhere else, including the experimental release channel.
Typically we do this so we can gradually roll out the feature behind
a flag before deciding to enable it.

The way we test those features today is by mutating the
`shared/ReactFeatureFlags` module. There are a few downsides to this
approach, though. The flag is only overridden for the specific tests or
test suites where you apply the override. But usually what you want is
to run *all* tests with the flag enabled, to protect against unexpected
regressions.

Also, mutating the feature flags module only works when running the
tests against source, not against the final build artifacts, because the
ReactFeatureFlags module is inlined by the build script.

Instead, we should run the test suite against the www configuration,
just like we do for prod, experimental, and so on. I've added a new
command, `yarn test-www`. It automatically runs in CI.

Some of the www feature flags are dynamic; that is, they depend on
a runtime condition (i.e. a GK). These flags are imported from an
external module that lives in www. Those flags will be enabled for some
clients and disabled for others, so we should run the tests against
*both* modes.

So I've added a new global `__VARIANT__`, and a new test command `yarn
test-www-variant`. `__VARIANT__` is set to false by default; when
running `test-www-variant`, it's set to true.

If we were going for *really* comprehensive coverage, we would run the
tests against every possible configuration of feature flags: 2 ^
numberOfFlags total combinations. That's not practical, though, so
instead we only run against two combinations: once with `__VARIANT__`
set to `true`, and once with it set to `false`. We generally assume that
flags can be toggled independently, so in practice this should
be enough.

You can also refer to `__VARIANT__` in tests to detect which mode you're
running in. Or, you can import `shared/ReactFeatureFlags` and read the
specific flag you can about. However, we should stop mutating that
module going forward. Treat it as read-only.

In this commit, I have only setup the www tests to run against source.
I'll leave running against build for a follow up.

Many of our tests currently assume they run only in the default
configuration, and break when certain flags are toggled. Rather than fix
these all up front, I've hard-coded the relevant flags to the default
values. We can incrementally migrate those tests later.
2020-03-06 09:29:05 -08:00
Sebastian Markbåge 60016c448b
Export React as Named Exports instead of CommonJS (#18106)
* Add options for forked entry points

We currently fork .fb.js entry points. This adds a few more options.

.modern.fb.js - experimental FB builds
.classic.fb.js - stable FB builds
.fb.js - if no other FB build, use this for FB builds
.experimental.js - experimental builds
.stable.js - stable builds
.js - used if no other override exists

This will be used to have different ES exports for different builds.

* Switch React to named exports

* Export named exports from the export point itself

We need to re-export the Flow exported types so we can use them in our code.

We don't want to use the Flow types from upstream since it doesn't have the non-public APIs that we have.

This should be able to use export * but I don't know why it doesn't work.

This actually enables Flow typing of React which was just "any" before.
This exposed some Flow errors that needs fixing.

* Create forks for the react entrypoint

None of our builds expose all exports and they all differ in at least one
way, so we need four forks.

* Set esModule flag to false

We don't want to emit the esModule compatibility flag on our CommonJS
output. For now we treat our named exports as if they're CommonJS.

This is a potentially breaking change for scheduler (but all those apis
are unstable), react-is and use-subscription. However, it seems unlikely
that anyone would rely on this since these only have named exports.

* Remove unused Feature Flags

* Let jest observe the stable fork for stable tests

This lets it do the negative test by ensuring that the right tests fail.

However, this in turn will make other tests that are not behind
__EXPERIMENTAL__ fail. So I need to do that next.

* Put all tests that depend on exports behind __EXPERIMENTAL__

Since there's no way to override the exports using feature flags
in .intern.js anymore we can't use these APIs in stable.

The tradeoff here is that we can either enable the negative tests on
"stable" that means experimental are expected to fail, or we can disable
tests on stable. This is unfortunate since some of these APIs now run on
a "stable" config at FB instead of the experimental.

* Switch ReactDOM to named exports

Same strategy as React.

I moved the ReactDOMFB runtime injection to classic.fb.js

Since we only fork the entrypoint, the `/testing` entrypoint needs to
be forked too to re-export the same things plus `act`. This is a bit
unfortunate. If it becomes a pattern we can consider forking in the
module resolution deeply.

fix flow

* Fix ReactDOM Flow Types

Now that ReactDOM is Flow type checked we need to fix up its types.

* Configure jest to use stable entry for ReactDOM in non-experimental

* Remove additional FeatureFlags that are no longer needed

These are only flagging the exports and no implementation details so we
can control them fully through the export overrides.
2020-02-25 13:54:27 -08:00
Dan Abramov a8fce06d3e
Fix Jest diff call (#17921) 2020-01-29 14:38:22 +00:00
Simen Bekkhus cf0081263c Upgrade to jest 25 (#17896)
The changes to the test code relate to changes in JSDOM that come with Jest 25:

* Several JSDOM workarounds are no longer needed.
* Several tests made assertions to match incorrect JSDOM behavior (e.g. setAttribute calls) that JSDOM has now patched to match browsers.
  * https://codesandbox.io/s/resets-value-of-datetime-input-to-fix-bugs-in-ios-safari-1ppwh
* JSDOM no longer triggers default actions when dispatching click events.
  * https://codesandbox.io/s/beautiful-cdn-ugn8f
* JSDOM fixed (jsdom/jsdom#2700) a bug so that calling focus() on an already focused element does not dispatch a FocusEvent.
* JSDOM now supports passive events.
* JSDOM has improved support for custom CSS properties.
  * But requires jsdom/cssstyle#112 to land to support webkit prefixed properties.
2020-01-25 08:43:02 -08:00
Nicolas Gallagher 3bd6adceda
Update typescript package and jest preprocessor (#17839) 2020-01-14 13:52:52 -08:00
Dan Abramov b979db4e72
Bump Prettier (#17811)
* Bump Prettier

* Reformat

* Use non-deprecated option
2020-01-09 13:54:11 +00:00
Dan Abramov 0253ee9a2e
Additional test infra changes for toErrorDev rename (#17632) 2019-12-17 13:31:47 +00:00
Dan Abramov 36a6e29bb3 Fix test_build_devtools CI job to run test-build-devtools (#17631)
* Skip abandoned project folders in Jest config

This fixes a problem that occurs after renaming a package.

* Fix test_build_devtools to run test-build-devtools

* Exclude console.error plugin for DevTools packages

* Use correct release channel for DevTools tests

This should fix the createRoot error.

* Fix TZ dependent test

* Change DT job dependencies
2019-12-16 16:03:12 -08: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
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
Sebastian Markbåge f4e974d26e
Add Experimental Flight Infrastructure (#16398)
* Add Flight Build and Unify HostFormat Config between Flight and Fizz

* Add basic resolution of models

* Add basic Flight fixture

Demonstrates the streaming protocol.

* Rename to flight-server to distinguish from the client parts

* Add Flight Client package and entry point

* Fix fixture
2019-10-29 14:45:47 -07:00
Andrew Clark 349cf5acc3
Experimental test helper: `it.experimental` (#17149)
Special version of Jest's `it` for experimental tests. Tests marked as
experimental will run **both** stable and experimental modes. In
experimental mode, they work the same as the normal Jest methods. In
stable mode, they are **expected to fail**. This means we can detect
when a test previously marked as experimental can be un-marked when the
feature becomes stable. It also reduces the chances that we accidentally
add experimental APIs to the stable builds before we intend.

I added corresponding methods for the focus and skip APIs:

- `fit` -> `fit.experimental`
- `it.only` -> `it.only.experimental` or `it.experimental.only`
- `xit` -> `xit.experimental`
- `it.skip` -> `it.skip.experimental` or `it.experimental.skip`

Since `it` is an alias of `test`, `test.experimental` works, too.
2019-10-19 16:08:08 -07:00
Andrew Clark 30c5daf943
Remove concurrent apis from stable (#17088)
* Tests run in experimental mode by default

For local development, you usually want experiments enabled. Unless
the release channel is set with an environment variable, tests will
run with __EXPERIMENTAL__ set to `true`.

* Remove concurrent APIs from stable builds

Those who want to try concurrent mode should use the experimental
builds instead.

I've left the `unstable_` prefixed APIs in the Facebook build so we
can continue experimenting with them internally without blessing them
for widespread use.

* Turn on SSR flags in experimental build

* Remove prefixed concurrent APIs from www build

Instead we'll use the experimental builds when syncing to www.

* Remove "canary" from internal React version string
2019-10-15 15:09:19 -07:00
Andrew Clark d364d8555f
Set up experimental builds (#17071)
* Don't bother including `unstable_` in error

The method names don't get stripped out of the production bundles
because they are passed as arguments to the error decoder.

Let's just always use the unprefixed APIs in the messages.

* Set up experimental builds

The experimental builds are packaged exactly like builds in the stable
release channel: same file structure, entry points, and npm package
names. The goal is to match what will eventually be released in stable
as closely as possible, but with additional features turned on.

Versioning and Releasing
------------------------

The experimental builds will be published to the same registry and
package names as the stable ones. However, they will be versioned using
a separate scheme. Instead of semver versions, experimental releases
will receive arbitrary version strings based on their content hashes.
The motivation is to thwart attempts to use a version range to match
against future experimental releases. The only way to install or depend
on an experimental release is to refer to the specific version number.

Building
--------

I did not use the existing feature flag infra to configure the
experimental builds. The reason is because feature flags are designed
to configure a single package. They're not designed to generate multiple
forks of the same package; for each set of feature flags, you must
create a separate package configuration.

Instead, I've added a new build dimension called the **release
channel**. By default, builds use the **stable** channel. There's
also an **experimental** release channel. We have the option to add more
in the future.

There are now two dimensions per artifact: build type (production,
development, or profiling), and release channel (stable or
experimental). These are separate dimensions because they are
combinatorial: there are stable and experimental production builds,
stable and experimental developmenet builds, and so on.

You can add something to an experimental build by gating on
`__EXPERIMENTAL__`, similar to how we use `__DEV__`. Anything inside
these branches will be excluded from the stable builds.
This gives us a low effort way to add experimental behavior in any
package without setting up feature flags or configuring a new package.
2019-10-14 10:46:42 -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
Jessica Franco 18d2e0c03e Warning system refactoring (part 1) (#16799)
* Rename lowPriorityWarning to lowPriorityWarningWithoutStack

This maintains parity with the other warning-like functions.

* Duplicate the toWarnDev tests to test toLowPriorityWarnDev

* Make a lowPriorityWarning version of warning.js

* Extract both variants in print-warning

Avoids parsing lowPriorityWarning.js itself as the way it forwards the
call to lowPriorityWarningWithoutStack is not analyzable.
2019-09-24 13:45:38 +01:00
Andrew Clark 8b580a89d6
Idle updates should not be blocked by hidden work (#16871)
* Idle updates should not be blocked by hidden work

Use the special `Idle` expiration time for updates that are triggered at
Scheduler's `IdlePriority`, instead of `Never`.

The key difference between Idle and Never¹ is that Never work can be
committed in an inconsistent state without tearing the UI. The main
example is offscreen content, like a hidden subtree.

¹ "Never" isn't the best name. I originally called it that because it
"never" expires, but neither does Idle. Since it's mostly used for
offscreen subtrees, we could call it "Offscreen." However, it's also
used for dehydrated Suspense boundaries, which are inconsistent in the
sense that they haven't finished yet, but aren't visibly inconsistent
because the server rendered HTML matches what the hydrated tree would
look like.

* Reset as early as possible using local variable

* Updates in a hidden effect should be Idle

I had made them Never to avoid an extra render when a hidden effect
updates the hidden component -- if they are Idle, we have to render once
at Idle, which bails out on the hidden subtree, then again at Never to
actually process the update -- but the problem of needing an extra
render pass to bail out hidden updates already exists and we should fix
that properly instead of adding yet another special case.
2019-09-23 20:52:48 -07:00
Andrew Clark 45898d0be0
[Scheduler] Prevent event log from growing unbounded (#16781)
If a Scheduler profile runs without stopping, the event log will grow
unbounded. Eventually it will run out of memory and the VM will throw
an error.

To prevent this from happening, let's automatically stop the profiler
once the log exceeds a certain limit. We'll also print a warning with
advice to call `stopLoggingProfilingEvents` explicitly.
2019-09-13 15:50:25 -07:00
Brian Vaughn 892ca8137e Disabled DevTools tests from yarn-build target 2019-08-27 09:08:49 -07:00
Brian Vaughn a48593a8d3 Iterating on DevTools tests: Trying to run tests against pre-build react-dom and react-test-renderers 2019-08-26 13:43:09 -07:00
Brian Vaughn 13a93e7b82 Configured CI to run DevTools tests. Updated other test configs not to include DevTools tests. 2019-08-26 09:58:28 -07:00
Brian Vaughn 79bda69d88 Renamed DevTools Jest config to be more concistent with others 2019-08-21 13:40:24 -07:00
Brian Vaughn 7ce229d3b0 Made some incremental progress on Jest tests 2019-08-15 09:53:22 -07:00
Brian Vaughn 4c4f5fd27f Disable @babel/plugin-transform-block-scoping "throwIfClosureRequired" option for tests 2019-08-14 19:04:43 -07:00
Brian Vaughn b1a03dfdc8
Rename legacy "events" package to "legacy-events" (#16388)
* Renamed 'events' package to 'legacy-events'
* Updated 'events' references to point to 'legacy-events'
2019-08-14 07:32:42 -07:00
Simen Bekkhus e308a037be chore: make tests compatible with Jest 24 (#15779)
* chore: make tests compatible with Jest 24

* remove fake rafs

* rollback jsdom for localstorage compat

* Apply suggestions from code review

Co-Authored-By: Sunil Pai <threepointone@oculus.com>

* chore: cleanup lockfile
2019-08-14 12:32:26 +01:00
lunaruan 89bbffed6e Cleanup Babel PR (ReactFreshPlugin) (#16340)
* fix babel 7 issues

* fix babel 7 issues
2019-08-13 21:18:40 +01:00
lunaruan b12a982062
Babel 7 (#16297)
Upgraded from Babel 6 to Babel 7.

The only significant change seems to be the way `@babel/plugin-transform-classes` handles classes differently from `babel-plugin-transform-es2015-classes`. In regular mode, the former injects a `_createClass` function that increases the bundle size, and in the latter it removes the safeguard checks. However, this is okay because we don't all classes in new features, and we want to deprecate class usage in the future in the react repo.

Co-authored-by: Luna Ruan <luna@fb.com>
Co-authored-by: Abdul Rauf <abdulraufmujahid@gmail.com>
Co-authored-by: Maksim Markelov <maks-markel@mail.ru>
2019-08-08 17:46:35 -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 b365ee2816
[Fire] Remove unused React fire fork (#16046) 2019-07-03 11:05:28 +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
Ricky 20da1dae4b Fix error logging in getDerivedStateFromProps (#15797)
* Fix error logging in getDerivedStateFromProps

* Update tests, don't log for both error boundary methods

* Re-add change lost in rebase
2019-06-25 18:02:27 +01:00
Moti Zilberman 98454371a9 Construct Error at invariant call site for clearer stack traces (#15877) 2019-06-18 11:38:33 -07:00
Brian Vaughn 801feed95c
Interaction tracing works across hidden and SSR hydration boundaries (#15872)
* Interaction tracing works across hidden and SSR hydration boundaries
2019-06-14 18:08:23 -07:00
Simen Bekkhus fa1e8df116 chore: use jest-serializer-raw for react-fresh snapshots (#15806) 2019-06-03 12:46:33 -07:00
Andrew Clark 9055e31e5c
Replace old Fiber Scheduler with new one (#15387)
The new Fiber Scheduler has been running in Facebook for several days
without issues. Let's switch to it.
2019-04-11 19:15:34 -07:00
Andrew Clark 875d05d553
Include full error messages in React Native build (#15363)
The React Native build does not minify error messages in production,
but it still needs to run the error messages transform to compile
`invariant` calls to `ReactError`. To do this, I added a `noMinify`
option to the Babel plugin. I also renamed it from
`minify-error-messages` to the more generic `transform-error-messages`.
2019-04-09 16:40:19 -07: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
Andrew Clark b1a56abd6a Fork ReactFiberScheduler with feature flag
Adds a feature flag `enableNewScheduler` that toggles between two
implementations of ReactFiberScheduler. This will let us land changes in
master while preserving the ability to quickly rollback.

Ideally this will be a short-lived fork. Once we've tested the new
scheduler for a week or so without issues, we will get rid of it. Until
then, we'll need to maintain two parallel implementations and run tests
against both of them. We rarely land changes to ReactFiberScheduler, so
I don't expect this will be a huge burden.

This commit does not implement anything new. The flag is still off and
tests run against the existing implementation.

Use `yarn test-new-scheduler` to run tests against the new one.
2019-03-20 16:28:33 -07:00
Andrew Clark 42c3c967d1
Compile invariant directly to throw expressions (#15071)
* Transform invariant to custom error type

This transforms calls to the invariant module:

```js
invariant(condition, 'A %s message that contains %s', adj, noun);
```

Into throw statements:

```js
if (!condition) {
  if (__DEV__) {
    throw ReactError(`A ${adj} message that contains ${noun}`);
  } else {
    throw ReactErrorProd(ERR_CODE, adj, noun);
  }
}
```

The only thing ReactError does is return an error whose name is set
to "Invariant Violation" to match the existing behavior.

ReactErrorProd is a special version used in production that throws
a minified error code, with a link to see to expanded form. This
replaces the reactProdInvariant module.

As a next step, I would like to replace our use of the invariant module
for user facing errors by transforming normal Error constructors to
ReactError and ReactErrorProd. (We can continue using invariant for
internal React errors that are meant to be unreachable, which was the
original purpose of invariant.)

* Use numbers instead of strings for error codes

* Use arguments instead of an array

I wasn't sure about this part so I asked Sebastian, and his rationale
was that using arguments will make ReactErrorProd slightly slower, but
using an array will likely make all the functions that throw slightly
slower to compile, so it's hard to say which way is better. But since
ReactErrorProd is in an error path, and fewer bytes is generally better,
no array is good.

* Casing nit
2019-03-18 13:58:03 -07:00
Andrew Clark bc8bd24c14
Run persistent mode tests in CI (#15029)
* Add command to run tests in persistent mode

* Convert Suspense fuzz tester to use noop renderer

So we can run it in persistent mode, too.

* Don't mutate stateNode in appendAllChildren

We can't mutate the stateNode in appendAllChildren because the children
could be current.

This is a bit weird because now the child that we append is different
from the one on the fiber stateNode. I think this makes conceptual
sense, but I suspect this likely breaks an assumption in Fabric.

With this approach, we no longer need to clone to unhide the children,
so I removed those host config methods.

Fixes bug surfaced by fuzz tester. (The test case that failed was the
one that's already hard coded.)

* In persistent mode, disable test that reads a ref

Refs behave differently in persistent mode. I added a TODO to write
a persistent mode version of this test.

* Run persistent mode tests in CI

* test-persistent should skip files without noop

If a file doesn't reference react-noop-renderer, we shouldn't bother
running it in persistent mode, since the results will be identical to
the normal test run.

* Remove module constructor from placeholder tests

We don't need this now that we have the ability to run any test file in
either mutation or persistent mode.

* Revert "test-persistent should skip files without noop"

Seb objected to adding shelljs as a dep and I'm too lazy to worry about
Windows support so whatever I'll just revert this.

* Delete duplicate file
2019-03-11 10:56:34 -07: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 53e787b45f
Replace noop's fake Scheduler implementation with mock Scheduler build (#14969)
* Replace noop's fake Scheduler implementation with mock Scheduler build

The noop 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.

Most of the existing noop tests were unaffected, but I did have to make
some changes. The biggest one involved passive effects: previously, they
were scheduled on a separate queue from the queue that handles
rendering. After this change, both rendering and effects are scheduled
in the Scheduler queue. I think this is a better approach because tests
no longer have to worry about the difference; if you call `flushAll`,
all the work is flushed, both rendering and effects. But for those few
tests that do care to flush the rendering without the effects, that's
still possible using the `yieldValue` API.

Follow-up: Do the same for test renderer.

* Fix import to scheduler/unstable_mock
2019-02-28 10:30:46 -08:00
Andrew Clark 00748c53e1
Add new mock build of Scheduler with flush, yield API (#14964)
* Add new mock build of Scheduler with flush, yield API

Test environments need a way to take control of the Scheduler queue and
incrementally flush work. Our current tests accomplish this either using
dynamic injection, or by using Jest's fake timers feature. Both of these
options are fragile and rely too much on implementation details.

In this new approach, we have a separate build of Scheduler that is
specifically designed for test environments. We mock the default
implementation like we would any other module; in our case, via Jest.
This special build has methods like `flushAll` and `yieldValue` that
control when work is flushed. These methods are based on equivalent
methods we've been using to write incremental React tests. Eventually
we may want to migrate the React tests to interact with the mock
Scheduler directly, instead of going through the host config like we
currently do.

For now, I'm using our custom static injection infrastructure to create
the two builds of Scheduler — a default build for DOM (which falls back
to a naive timer based implementation), and the new mock build. I did it
this way because it allows me to share most of the implementation, which
isn't specific to a host environment — e.g. everything related to the
priority queue. It may be better to duplicate the shared code instead,
especially considering that future environments (like React Native) may
have entirely forked implementations. I'd prefer to wait until the
implementation stabilizes before worrying about that, but I'm open to
changing this now if we decide it's important enough.

* Mock Scheduler in bundle tests, too

* Remove special case by making regex more restrictive
2019-02-26 20:51:17 -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
Brian Vaughn 52bea95cfc
Fixed scheduler setTimeout fallback (#14358)
* Fixed scheduler setTimeout fallback
* Moved unit-test-specific setTimeout code into a new NPM package, jest-mock-scheduler.
2018-12-01 13:03:19 -08:00
Sebastian Markbåge 1d25aa5787
[Fizz] New Server Rendering Infra (#14144)
* [Fizz] Add Flow/Jest/Rollup build infra

Add a new package for react-stream which allows for custom server renderer
outputs. I picked the name because it's a reasonable name but also
because the npm name is currently owned by a friend of the project.

The react-dom build has its own inlined server renderer under the
name `react-dom/fizz`.

There is also a noop renderer to be used for testing. At some point
we might add a public one to test-renderer but for now I don't want to have
to think about public API design for the tests.

* Add FormatConfig too

We need to separate the format (DOM, React Native, etc) from the host
running the server (Node, Browser, etc).

* Basic wiring between Node, Noop and DOM configs

The Node DOM API is pipeToNodeStream which accepts a writable stream.

* Merge host and format config in dynamic react-stream entry point

Simpler API this way but also avoids having to fork the wrapper config.

Fixes noop builds.

* Add setImmediate/Buffer globals to lint config

Used by the server renderer

* Properly include fizz.node.js

Also use forwarding to it from fizz.js in builds so that tests covers
this.

* Make react-stream private since we're not ready to publish

or even name it yet

* Rename Renderer -> Streamer

* Prefix react-dom/fizz with react-dom/unstable-fizz

* Add Fizz Browser host config

This lets Fizz render to WHATWG streams. E.g. for rendering in a
Service Worker.

I added react-dom/unstable-fizz.browser as the entry point for this.

Since we now have two configurations of DOM. I had to add another
inlinedHostConfigs configuration called `dom-browser`. The reconciler
treats this configuration the same as `dom`. For stream it checks
against the ReactFizzHostConfigBrowser instead of the Node one.

* Add Fizz Browser Fixture

This is for testing server rendering - on the client.

* Lower version number to detach it from react-reconciler version
2018-11-30 11:38:22 -08:00
Dan Abramov 16e120438c
[Fire] Add initial build infrastructure (#14359) 2018-11-30 11:52:34 +00:00
chun shang 48f1e5b3ce Add a null type test for memo (#14325) 2018-11-27 13:25:24 +00:00
Brian Vaughn 915e4eab53
Add "unstable_" prefix to react-cache and jest-react (#13929)
* Add "unstable_" prefix to react-cache createResource and jest-react matchers
* Reverted accidental change to error-codes JSON
* Remove unstable_ prefix from internal React tests for jest-test
2018-10-23 13:55:37 -07: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
Brian Vaughn 4bcee56210
Rename "tracking" API to "tracing" (#13641)
* Replaced "tracking" with "tracing" in all directory and file names
* Global rename of track/tracking/tracked to trace/tracing/traced
2018-09-13 14:23:16 -07:00
Nathan Hunzaker a079011f95 🔥 Stop syncing the value attribute on inputs (behind a feature flag) (#13526)
* 🔥 Stop syncing the value attribute on inputs

* Eliminate some additional checks

* Remove initialValue and initialWrapper from wrapperState flow type

* Update tests with new sync logic, reduce some operations

* Update tests, add some caveats for SSR mismatches

* Revert newline change

* Remove unused type

* Call toString to safely type string values

* Add disableInputAttributeSyncing feature flag

Reverts tests to original state, adds attribute sync feature flag,
then moves all affected tests to ReactFire-test.js.

* Revert position of types in toStringValues

* Invert flag on number input blur

* Add clarification why double blur is necessary

* Update ReactFire number cases to be more explicite about blur

* Move comments to reduce diff size

* Add comments to clarify behavior in each branch

* There is no need to assign a different checked behavior in Fire

* Use checked reference

* Format

* Avoid precomputing stringable values

* Revert getToStringValue comment

* Revert placement of undefined in getToStringValue

* Do not eagerly stringify value

* Unify Fire test cases with normal ones

* Revert toString change. Only assign unsynced values when not nully
2018-09-12 19:29:23 +01:00
Dan Abramov a7bd7c3c04
Allow reading default feature flags from bundle tests (#13629) 2018-09-12 16:56:04 +01:00
Dan Abramov 7204b636ee
Run tests for Fire feature flags (#13628)
* Run tests for Fire feature flags

* Only run ReactDOM tests for Fire
2018-09-12 16:17:36 +01:00
Dan 8a8d973d3c Use clearer wording
Fixes #13604
2018-09-09 16:54:31 +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 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
Brian Vaughn e106b8c44f
Warn about unsafe toWarnDev() nesting in tests (#12457)
* Add lint run to warn about improperly nested toWarnDev matchers
* Updated tests to avoid invalid nesting
2018-08-21 07:43:02 -07:00
Brian Vaughn 5e0f073d50
interaction-tracking package (#13234)
Add new interaction-tracking package/bundle
2018-08-17 10:16:05 -06:00
Dan Abramov b2adcfba32
Don't suppress jsdom error reporting in our tests (#13401)
* Don't suppress jsdom error reporting

* Address review
2018-08-15 17:44:46 +01:00
Dan Abramov 46d5afc54d
Replace console.error() with a throw in setTimeout() as last resort exception logging (#13310)
* Add a regression test for #13188

* Replace console.error() with a throw in setTimeout() as last resort

* Fix lint and comment

* Fix tests to check we throw after all

* Fix build tests
2018-08-02 18:16:47 +01: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
Dan Abramov 2a1bc3f74c Format messages in unexpected console.error() test failure 2018-07-19 12:15:01 +01:00
Dan Abramov 236f608723
Fail tests if toWarnDev() does not wrap warnings in array (#13227)
* Fail tests if toWarn() does not wrap warnings in array

* Fix newly failing tests

* Another fix
2018-07-18 02:38:39 +01:00
Dan Abramov fd410f43fc Protect against passing component stack twice
This is a leftover from #13161 that I forgot to include.
It ensures we don't accidentally write code in the old way and end up passing the stack twice.
2018-07-16 22:47:41 +01:00
Dan Abramov f9358c51c8
Change warning() to automatically inject the stack, and add warningWithoutStack() as opt-out (#13161)
* Use %s in the console calls

* Add shared/warningWithStack

* Convert some warning callsites to warningWithStack

* Use warningInStack in shared utilities and remove unnecessary checks

* Replace more warning() calls with warningWithStack()

* Fixes after rebase + use warningWithStack in react

* Make warning have stack by default; warningWithoutStack opts out

* Forbid builds that may not use internals

* Revert newly added stacks

I changed my mind and want to keep this PR without functional changes. So we won't "fix" any warnings that are already missing stacks. We'll do it in follow-ups instead.

* Fix silly find/replace mistake

* Reorder imports

* Add protection against warning argument count mismatches

* Address review
2018-07-16 22:31:59 +01:00
Dan Abramov 854c953905 Fix matcher tests to be DEV-only 2018-07-16 20:35:43 +01:00
Dan Abramov 467d139101
Enforce presence or absence of component stack in tests (#13215)
* Enforce presence or absence of stack in tests

* Rename expectNoStack to withoutStack

* Fix lint

* Add some tests for toWarnDev()
2018-07-16 20:20:18 +01:00
Dan Abramov 659a29cecf
Reorganize how shared internals are accessed (#13201)
* Reorganize how shared internals are accessed

* Update forks.js
2018-07-13 02:45:37 +01:00
Dan Abramov f762b3abb1
Run react-dom SSR import test in jsdom-less environment (#13157) 2018-07-06 16:43:43 +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
Brian Vaughn d5c11193e2
Added production profiling bundle type (#12886)
* Added profiling bundle
* Turned profiling on for React Fabric OSS profiling and dev bundles
* Added new global var "__PROFILE__" for profiling DCE
2018-06-11 13:16:27 -07:00
Ivan Babak d3e0a3aaf3 Fix jest/matchers/toWarnDev expected, actual order for jest-diff (#12285) (#12288)
`toWarnDev` calls `jestDiff(a, b)` which calls `diffStrings(a, b)` where by default `a` is annotated as `'Expected'` (green), `b` as `'Received'` (red).

So the first argument passed into `jestDiff` should be the expected message, the second should be the actual message.
It was vice versa previously.

- 457776b288/packages/jest-diff/src/index.js (L54)
- 457776b288/packages/jest-diff/src/index.js (L93)
- 457776b288/packages/jest-diff/src/diff_strings.js (L249-L251)
2018-06-08 13:18:22 +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
Dan Abramov 0442e8275f
Add a clear error when renderers clash in tests (#12867) 2018-05-21 15:38:35 +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
Sophie Alpert 200357596a
Add error when running jest directly (#12726)
```
$ jest
 FAIL  scripts/jest/dont-run-jest-directly.js
  ● Test suite failed to run

    Don't run `jest` directly. Run `yarn test` instead.

    > 1 | throw new Error("Don't run `jest` directly. Run `yarn test` instead.");
      2 |

      at Object.<anonymous> (scripts/jest/dont-run-jest-directly.js:1:96)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.866s
Ran all test suites.
```
2018-05-01 12:46:17 -07:00
Dan Abramov b05e67e36a
Bump Prettier (#12622) 2018-04-17 01:43:55 +01:00
Dan Abramov 1c2876d5b5
Add a build step to hoist warning conditions (#12537) 2018-04-04 17:04:40 +01:00
Brian Vaughn e9ba8ec866
Workaround jest-diff single line string limitation (#12456) 2018-03-26 10:48:36 -07:00
Brian Vaughn d0e75dcfe2
Improve toWarnDev matcher DX for unexpected warnings (#12082)
Use jest-diff to format the warnings in a way that makes it easier to spot the differences.
2018-01-23 14:46:58 -08:00
Brian Vaughn 098745b2d1
Improved toWarnDev matcher to avoid swallowing errors (#12081)
While writing tests for unsafe async warnings, I noticed that in certain cases, errors were swallowed by the toWarnDev matcher and resulted in confusing test failures. For example, if an error prevented the code being tested from logging an expected warning- the test would fail saying that the warning hadn't been logged rather than reporting the unexpected error. I think a better approach for this is to always treat caught errors as the highest-priority reason for failing a test.

I reran all of the test cases for this matcher that I originally ran with PR #11786 and ensured they all still pass.
2018-01-23 14:46:50 -08:00
Rick Hanlon II 4f309f86df Plug ~100 test leaks (#12020) 2018-01-15 11:15:19 +00:00
Brian Vaughn c94b4b8b86
Fixed potential false-positive in toWarnDev matcher (#11898)
* Warn about spying on the console

* Added suppress warning flag for spyOn(console)

* Nits

* Removed spy-on-console guard

* Fixed a potential source of false-positives in toWarnDev() matcher
Also updated (most of) ReactIncrementalErrorLogging-test.internal to use the new matcher

* Removed unused third param to spyOn

* Improved clarity of inline comments

* Removed unused normalizeCodeLocInfo() method
2018-01-05 09:44:45 -08:00
Dan Abramov 1ebeb0542f
Move npm output from build/packages/* to build/node_modules/* (#11962)
* Move build/packages/* to build/node_modules/*

This fixes Node resolution in that folder and lets us require() packages in it in Node shell for manual testing.

* Link fixtures to packages/node_modules

This updates the location and also uses link: instead of file: to avoid Yarn caching the folder contents.
2018-01-04 19:01:31 +00:00
Dan Abramov d289d4b634
Update to Jest 22 (#11956)
* Bump deps to Jest 22

* Prevent jsdom from logging intentionally thrown errors

This relies on our existing special field that we use to mute errors.
Perhaps, it would be better to instead rely on preventDefault() directly.
I outlined a possible strategy here: https://github.com/facebook/react/issues/11098#issuecomment-355032539

* Update snapshots

* Mock out a method called by ReactART that now throws

* Calling .click() no longer works, dispatch event instead

* Fix incorrect SVG element creation in test

* Render SVG elements inside <svg> to avoid extra warnings

* Fix range input test to use numeric value

* Fix creating SVG element in test

* Replace brittle test that relied on jsdom behavior

The test passed in jsdom due to its implementation details.

The original intention was to test the mutation method, but it was removed a while ago.

Following @nhunzaker's suggestion, I moved the tests to ReactDOMInput and adjusted them to not rely on implementation details.

* Add a workaround for the expected extra client-side warning

This is a bit ugly but it's just two places. I think we can live with this.

* Only warn once for mismatches caused by bad attribute casing

We used to warn both about bad casing and about a mismatch.
The mismatch warning was a bit confusing. We didn't know we warned twice because jsdom didn't faithfully emulate SVG.

This changes the behavior to only leave the warning about bad casing if that's what caused the mismatch.
It also adjusts the test to have an expectation that matches the real world behavior.

* Add an expected warning per comment in the same test
2018-01-04 18:57:30 +00:00
Brian Vaughn bb881f2de7
Updated toWarnDev matcher so that ReactFiberScheduler won't suppress its errors (#11958) 2018-01-03 15:23:05 -08:00
Brian Vaughn b5334a44e9
toWarnInDev matcher; throw on unexpected console.error (#11786)
* Added toWarnInDev matcher and connected to 1 test
* Added .toLowPriorityWarnDev() matcher
* Reply Jest spy with custom spy. Unregister spy after toWarnDev() so unexpected console.error/warn calls will fail tests.
* console warn/error throws immediately in tests by default (if not spied on)
* Pass-thru console message before erroring to make it easier to identify
* More robustly handle unexpected warnings within try/catch
* Error message includes remaining expected warnings in addition to unexpected warning
2018-01-02 11:06:41 -08:00
Dan Abramov 0deea32667
Run some tests in Node environment (#11948)
* Run some tests in Node environment

* Separate SSR tests that require DOM

This allow us to run others with Node environment.
2018-01-02 18:42:18 +00:00
Jack Hou e8e62ebb59 use different eslint config for es6 and es5 (#11794)
* use different eslint config for es6 and es5

* remove confusing eslint/baseConfig.js & add more eslint setting for es5, es6

* more clear way to run eslint on es5 & es6 file

* seperate ESNext, ES6, ES6 path, and use different lint config

* rename eslint config file & update eslint rules

* Undo yarn.lock changes

* Rename a file

* Remove unnecessary exceptions

* Refactor a little bit

* Refactor and tweak the logic

* Minor issues
2017-12-11 15:52:46 +00:00
Dan Abramov 41f920e430
Add a test-only transform to catch infinite loops (#11790)
* Add a test-only transform to catch infinite loops

* Only track iteration count, not time

This makes the detection dramatically faster, and is okay in our case because we don't have tests that iterate so much.

* Use clearer naming

* Set different limits for tests

* Fail tests with infinite loops even if the error was caught

* Add a test
2017-12-07 20:53:13 +00:00
Brian Vaughn 53ab1948b5
Blacklist spyOn(). Add explicit spyOnProd() and spyOnDevAndProd() (#11691)
* Blacklist spyOn(). Add explicit spyOnProd() and spyOnDevAndProd()

* Wording tweak.

* Fixed lint no-shadow warning
2017-11-28 14:06:26 -08:00
Dan Abramov 575982b96d
Forbid Haste in Jest (#11647) 2017-11-23 18:02:47 +00:00
Dan Abramov fa7a97fc46
Run 90% of tests on compiled bundles (both development and production) (#11633)
* Extract Jest config into a separate file

* Refactor Jest scripts directory structure

Introduces a more consistent naming scheme.

* Add yarn test-bundles and yarn test-prod-bundles

Only files ending with -test.public.js are opted in (so far we don't have any).

* Fix error decoding for production bundles

GCC seems to remove `new` from `new Error()` which broke our proxy.

* Build production version of react-noop-renderer

This lets us test more bundles.

* Switch to blacklist (exclude .private.js tests)

* Rename tests that are currently broken against bundles to *-test.internal.js

Some of these are using private APIs. Some have other issues.

* Add bundle tests to CI

* Split private and public ReactJSXElementValidator tests

* Remove internal deps from ReactServerRendering-test and make it public

* Only run tests directly in __tests__

This lets us share code between test files by placing them in __tests__/utils.

* Remove ExecutionEnvironment dependency from DOMServerIntegrationTest

It's not necessary since Stack.

* Split up ReactDOMServerIntegration into test suite and utilities

This enables us to further split it down. Good both for parallelization and extracting public parts.

* Split Fragment tests from other DOMServerIntegration tests

This enables them to opt other DOMServerIntegration tests into bundle testing.

* Split ReactDOMServerIntegration into different test files

It was way too slow to run all these in sequence.

* Don't reset the cache twice in DOMServerIntegration tests

We used to do this to simulate testing separate bundles.
But now we actually *do* test bundles. So there is no need for this, as it makes tests slower.

* Rename test-bundles* commands to test-build*

Also add test-prod-build as alias for test-build-prod because I keep messing them up.

* Use regenerator polyfill for react-noop

This fixes other issues and finally lets us run ReactNoop tests against a prod bundle.

* Run most Incremental tests against bundles

Now that GCC generator issue is fixed, we can do this.
I split ErrorLogging test separately because it does mocking. Other error handling tests don't need it.

* Update sizes

* Fix ReactMount test

* Enable ReactDOMComponent test

* Fix a warning issue uncovered by flat bundle testing

With flat bundles, we couldn't produce a good warning for <div onclick={}> on SSR
because it doesn't use the event system. However the issue was not visible in normal
Jest runs because the event plugins have been injected by the time the test ran.

To solve this, I am explicitly passing whether event system is available as an argument
to the hook. This makes the behavior consistent between source and bundle tests. Then
I change the tests to document the actual logic and _attempt_ to show a nice message
(e.g. we know for sure `onclick` is a bad event but we don't know the right name for it
on the server so we just say a generic message about camelCase naming convention).
2017-11-23 17:44:58 +00:00
Dan Abramov e949d57508
Remove global mocks by adding support for "suppressReactErrorLogging" property (#11636)
* Remove global mocks

They are making it harder to test compiled bundles.

One of them (FeatureFlags) is not used. It is mocked in some specific test files (and that's fine).

The other (FiberErrorLogger) is mocked to silence its output. I'll look if there's some other way to achieve this.

* Add error.suppressReactErrorLogging and use it in tests

This adds an escape hatch to *not* log errors that go through React to the console.
We will enable it for our own tests.
2017-11-23 01:15:22 +00:00
Dan Abramov 6041f481b7
Run Jest in production mode (#11616)
* Move Jest setup files to /dev/ subdirectory

* Clone Jest /dev/ files into /prod/

* Move shared code into scripts/jest

* Move Jest config into the scripts folder

* Fix the equivalence test

It fails because the config is now passed to Jest explicitly.
But the test doesn't know about the config.

To fix this, we just run it via `yarn test` (which includes the config).
We already depend on Yarn for development anyway.

* Add yarn test-prod to run Jest with production environment

* Actually flip the production tests to run in prod environment

This produces a bunch of errors:

Test Suites: 64 failed, 58 passed, 122 total
Tests:       740 failed, 26 skipped, 1809 passed, 2575 total
Snapshots:   16 failed, 4 passed, 20 total

* Ignore expectDev() calls in production

Down from 740 to 175 failed.

Test Suites: 44 failed, 78 passed, 122 total
Tests:       175 failed, 26 skipped, 2374 passed, 2575 total
Snapshots:   16 failed, 4 passed, 20 total

* Decode errors so tests can assert on their messages

Down from 175 to 129.

Test Suites: 33 failed, 89 passed, 122 total
Tests:       129 failed, 1029 skipped, 1417 passed, 2575 total
Snapshots:   16 failed, 4 passed, 20 total

* Remove ReactDOMProduction-test

There is no need for it now. The only test that was special is moved into ReactDOM-test.

* Remove production switches from ReactErrorUtils

The tests now run in production in a separate pass.

* Add and use spyOnDev() for warnings

This ensures that by default we expect no warnings in production bundles.
If the warning *is* expected, use the regular spyOn() method.

This currently breaks all expectDev() assertions without __DEV__ blocks so we go back to:

Test Suites: 56 failed, 65 passed, 121 total
Tests:       379 failed, 1029 skipped, 1148 passed, 2556 total
Snapshots:   16 failed, 4 passed, 20 total

* Replace expectDev() with expect() in __DEV__ blocks

We started using spyOnDev() for console warnings to ensure we don't *expect* them to occur in production. As a consequence, expectDev() assertions on console.error.calls fail because console.error.calls doesn't exist. This is actually good because it would help catch accidental warnings in production.

To solve this, we are getting rid of expectDev() altogether, and instead introduce explicit expectation branches. We'd need them anyway for testing intentional behavior differences.

This commit replaces all expectDev() calls with expect() calls in __DEV__ blocks. It also removes a few unnecessary expect() checks that no warnings were produced (by also removing the corresponding spyOnDev() calls).

Some DEV-only assertions used plain expect(). Those were also moved into __DEV__ blocks.

ReactFiberErrorLogger was special because it console.error()'s in production too. So in that case I intentionally used spyOn() instead of spyOnDev(), and added extra assertions.

This gets us down to:

Test Suites: 21 failed, 100 passed, 121 total
Tests:       72 failed, 26 skipped, 2458 passed, 2556 total
Snapshots:   16 failed, 4 passed, 20 total

* Enable User Timing API for production testing

We could've disabled it, but seems like a good idea to test since we use it at FB.

* Test for explicit Object.freeze() differences between PROD and DEV

This is one of the few places where DEV and PROD behavior differs for performance reasons.
Now we explicitly test both branches.

* Run Jest via "yarn test" on CI

* Remove unused variable

* Assert different error messages

* Fix error handling tests

This logic is really complicated because of the global ReactFiberErrorLogger mock.
I understand it now, so I added TODOs for later.

It can be much simpler if we change the rest of the tests that assert uncaught errors to also assert they are logged as warnings.
Which mirrors what happens in practice anyway.

* Fix more assertions

* Change tests to document the DEV/PROD difference for state invariant

It is very likely unintentional but I don't want to change behavior in this PR.
Filed a follow up as https://github.com/facebook/react/issues/11618.

* Remove unnecessary split between DEV/PROD ref tests

* Fix more test message assertions

* Make validateDOMNesting tests DEV-only

* Fix error message assertions

* Document existing DEV/PROD message difference (possible bug)

* Change mocking assertions to be DEV-only

* Fix the error code test

* Fix more error message assertions

* Fix the last failing test due to known issue

* Run production tests on CI

* Unify configuration

* Fix coverage script

* Remove expectDev from eslintrc

* Run everything in band

We used to before, too. I just forgot to add the arguments after deleting the script.
2017-11-22 13:02:26 +00:00
Dan Abramov 7e7127387b
Run Jest tests with "development" environment (#11612) 2017-11-21 16:28:42 +00:00
Dan Abramov 40a176d859
Remove mentions of module map in Jest config (#11611) 2017-11-21 16:01:10 +00:00
Andrew Clark 9b36df86c6
Use requestIdleCallback timeout to force expiration (#11548)
* Don't call idle callback unless there's time remaining

* Expiration fixture

Fixture that demonstrates how async work expires after a certain interval.
The fixture clogs the main thread with animation work, so it only works if the
`timeout` option is provided to `requestIdleCallback`.

* Pass timeout option to requestIdleCallback

Forces `requestIdleCallback` to fire if too much time has elapsed, even if the
main thread is busy. Required to make expiration times work properly. Otherwise,
async work can expire, but React never has a chance to flush it because the
browser never calls into React.
2017-11-15 13:46:17 -08:00
Dan Abramov 46f7b0d945
Fix dead code elimination for feature flags (#11453)
* Fix dead code elimination for feature flags

Turning flags into named exports fixes dead code elimination.

This required some restructuring of how we verify that flag types match up. I used the Check<> trick combined with import typeof, as suggested by @calebmer.

For www, we can no longer re-export `require('ReactFeatureFlags')` directly, and instead destructure it. This means flags have to be known at init time. This is already the case so it's not a problem. In fact it may be better since it removes extra property access in tight paths.

For things that we *want* to be dynamic on www (currently, only performance flag) we can export a function to toggle it, and then put it on the secret exports. In fact this is better than just letting everyone mutate the flag at arbitrary times since we can provide, e.g., a ref counting interface to it.

* Record sizes
2017-11-06 14:14:48 +00:00
Dan Abramov 21d0c11523
Convert the Source to ES Modules (#11389)
* Update transforms to handle ES modules

* Update Jest to handle ES modules

* Convert react package to ES modules

* Convert react-art package to ES Modules

* Convert react-call-return package to ES Modules

* Convert react-test-renderer package to ES Modules

* Convert react-cs-renderer package to ES Modules

* Convert react-rt-renderer package to ES Modules

* Convert react-noop-renderer package to ES Modules

* Convert react-dom/server to ES modules

* Convert react-dom/{client,events,test-utils} to ES modules

* Convert react-dom/shared to ES modules

* Convert react-native-renderer to ES modules

* Convert react-reconciler to ES modules

* Convert events to ES modules

* Convert shared to ES modules

* Remove CommonJS support from transforms

* Move ReactDOMFB entry point code into react-dom/src

This is clearer because we can use ES imports in it.

* Fix Rollup shim configuration to work with ESM

* Fix incorrect comment

* Exclude external imports without side effects

* Fix ReactDOM FB build

* Remove TODOs I don’t intend to fix yet
2017-11-02 19:50:03 +00:00
Dan Abramov 707ca7f492 Update Jest and remove hacks (#11372)
* Update Jest

* Remove hacks for Jest + Workspace integration

They were fixed by https://github.com/facebook/jest/pull/4761.

* Use relative requires in tests relying on private APIs

I changed them to absolute to work around a Jest bug.
The bug has been fixed so I can revert my past changes now.
2017-10-26 15:15:24 +01:00
Dan Abramov 1eed302d34 Drop Haste (#11303)
* Use relative paths in packages/react

* Use relative paths in packages/react-art

* Use relative paths in packages/react-cs

* Use relative paths in other packages

* Fix as many issues as I can

This uncovered an interesting problem where ./b from package/src/a would resolve to a different instantiation of package/src/b in Jest.

Either this is a showstopper or we can solve it by completely fobbidding remaining /src/.

* Fix all tests

It seems we can't use relative requires in tests anymore. Otherwise Jest becomes confused between real file and symlink.
https://github.com/facebook/jest/issues/3830

This seems bad... Except that we already *don't* want people to create tests that import individual source files.
All existing cases of us doing so are actually TODOs waiting to be fixed.

So perhaps this requirement isn't too bad because it makes bad code looks bad.

Of course, if we go with this, we'll have to lint against relative requires in tests.
It also makes moving things more painful.

* Prettier

* Remove @providesModule

* Fix remaining Haste imports I missed earlier

* Fix up paths to reflect new flat structure

* Fix Flow

* Fix CJS and UMD builds

* Fix FB bundles

* Fix RN bundles

* Prettier

* Fix lint

* Fix warning printing and error codes

* Fix buggy return

* Fix lint and Flow

* Use Yarn on CI

* Unbreak Jest

* Fix lint

* Fix aliased originals getting included in DEV

Shouldn't affect correctness (they were ignored) but fixes DEV size regression.

* Record sizes

* Fix weird version in package.json

* Tweak bundle labels

* Get rid of output option by introducing react-dom/server.node

* Reconciler should depend on prop-types

* Update sizes last time
2017-10-25 02:55:00 +03:00
Dan Abramov d9c1dbd617 Use Yarn Workspaces (#11252)
* Enable Yarn workspaces for packages/*

* Move src/isomorphic/* into packages/react/src/*

* Create index.js stubs for all packages in packages/*

This makes the test pass again, but breaks the build because npm/ folders aren't used yet.
I'm not sure if we'll keep this structure--I'll just keep working and fix the build after it settles down.

* Put FB entry point for react-dom into packages/*

* Move src/renderers/testing/* into packages/react-test-renderer/src/*

Note that this is currently broken because Jest ignores node_modules,
and so Yarn linking makes Jest skip React source when transforming.

* Remove src/node_modules

It is now unnecessary. Some tests fail though.

* Add a hacky workaround for Jest/Workspaces issue

Jest sees node_modules and thinks it's third party code.

This is a hacky way to teach Jest to still transform anything in node_modules/react*
if it resolves outside of node_modules (such as to our packages/*) folder.

I'm not very happy with this and we should revisit.

* Add a fake react-native package

* Move src/renderers/art/* into packages/react-art/src/*

* Move src/renderers/noop/* into packages/react-noop-renderer/src/*

* Move src/renderers/dom/* into packages/react-dom/src/*

* Move src/renderers/shared/fiber/* into packages/react-reconciler/src/*

* Move DOM/reconciler tests I previously forgot to move

* Move src/renderers/native-*/* into packages/react-native-*/src/*

* Move shared code into packages/shared

It's not super clear how to organize this properly yet.

* Add back files that somehow got lost

* Fix the build

* Prettier

* Add missing license headers

* Fix an issue that caused mocks to get included into build

* Update other references to src/

* Re-run Prettier

* Fix lint

* Fix weird Flow violation

I didn't change this file but Flow started complaining.
Caleb said this annotation was unnecessarily using $Abstract though so I removed it.

* Update sizes

* Fix stats script

* Fix packaging fixtures

Use file: instead of NODE_PATH since NODE_PATH.
NODE_PATH trick only worked because we had no react/react-dom in root node_modules, but now we do.

file: dependency only works as I expect in Yarn, so I moved the packaging fixtures to use Yarn and committed lockfiles.
Verified that the page shows up.

* Fix art fixture

* Fix reconciler fixture

* Fix SSR fixture

* Rename native packages
2017-10-19 00:22:21 +01:00
Andrew Clark 3ffb5d0876 Deterministic updates (#10715)
* Deterministic updates

High priority updates typically require less work to render than
low priority ones. It's beneficial to flush those first, in their own
batch, before working on more expensive low priority ones. We do this
even if a high priority is scheduled after a low priority one.

However, we don't want this reordering of updates to affect the terminal
state. State should be deterministic: once all work has been flushed,
the final state should be the same regardless of how they were
scheduled.

To get both properties, we store updates on the queue in insertion
order instead of priority order (always append). Then, when processing
the queue, we skip over updates with insufficient priority. Instead of
removing updates from the queue right after processing them, we only
remove them if there are no unprocessed updates before it in the list.

This means that updates may be processed more than once.

As a bonus, the new implementation is simpler and requires less code.

* Fix ceiling function

Mixed up the operators.

* Remove addUpdate, addReplaceState, et al

These functions don't really do anything. Simpler to use a single
insertUpdateIntoFiber function.

Also splits scheduleUpdate into two functions:

- scheduleWork traverses a fiber's ancestor path and updates their
  expiration times.
- scheduleUpdate inserts an update into a fiber's update queue, then
  calls scheduleWork.

* Remove getExpirationTime

The last remaining use for getExpirationTime was for top-level async
updates. I moved that check to scheduleUpdate instead.

* Move UpdateQueue insertions back to class module

Moves UpdateQueue related functions out of the scheduler and back into
the class component module. It's a bit awkward that now we need to pass
around createUpdateExpirationForFiber, too. But we can still do without
addUpdate, replaceUpdate, et al.

* Store callbacks as an array of Updates

Simpler this way.

Also moves commitCallbacks back to UpdateQueue module.

* beginUpdateQueue -> processUpdateQueue

* Updates should never have an expiration of NoWork

* Rename expiration related functions

* Fix update queue Flow types

Gets rid of an unneccessary null check
2017-10-13 17:21:25 -07:00
Dan Abramov aad0970192 Remove Stack (part 1, safe: unused files and tests) (#10794)
* Remove Fiber Jest project

* Remove Stack reconciler and ReactDOMStack code

* Fix tests depending on Stack internals

* Fix Flow
2017-09-27 15:15:20 +01:00
Sophie Alpert d63249d034 Update license headers BSD+Patents -> MIT
Did find and replace in TextMate.

```
find: (?:( \*)( ))?Copyright (?:\(c\) )?(\d{4})\b.+Facebook[\s\S]+(?:this source tree|the same directory)\.$
replace: $1$2Copyright (c) $3-present, Facebook, Inc.\n$1\n$1$2This source code is licensed under the MIT license found in the\n$1$2LICENSE file in the root directory of this source tree.
```
2017-09-25 18:17:44 -07:00
Brian Vaughn 2fa38ac1cc Delete ReactNativeStack 🎉 🎉 🎉 (#10511)
* Removed createReactNativeComponentClassStack and renamed createReactNativeComponentClassFiber => createReactNativeComponentClass

* Removed findNumericNodeHandleStack and renamed findNumericNodeHandleFiber => findNumericNodeHandle

* Renamed ReactNativeFiberEntry => ReactNativeEntry

* Removed all references to ReactNativeFeatureFlags and RN stack

* Removed severl RN modules that are no longer used

* Renamed ReactNativeEntry => ReactNativeFiberEntry for now. We'll probably remove 'fiber' references later

* Update build results json

* Deleted snapshot

* Re-add accidentally deleted test

* Remove now-unnecessary hack in test

* Fix lint

* RN findNodeHandle no longer adds props directly to read-only owner (#10520)

* Added ReactNativeMount-test snapshot for 'renders and reorders children' test
2017-08-23 15:53:55 -07:00
Brian Vaughn f3e502c613 FB bundles wrap warning() calls in __DEV__ (#10314)
FB bundles wrap warning() calls in __DEV__

Split dev-mode transforms into separate parts:
1) umd+cjs+fb: Wrap warning calls with process.env checks
2) umd+cjs: Replace error messages with minified codes

Also updated transforms to use __DEV__ since it transforms to smaller code after stripEnvVariables is run.

Also renamed 'scripts/error-codes/dev-expression-with-codes.js' -> 'scripts/error-codes/replace-invariant-error-codes.js'
2017-08-02 14:14:26 -07:00
Dan Abramov a2ed7a6d96 Make unexpected console.warn() calls fail tests (#10341)
* Make console.warn() calls fail tests

* Replace matchers with a more straightforward cleanup
2017-08-01 19:53:37 +01:00
Andrew Clark 6c66d38d25 Remove feature test from invokeGuardedCallbackDev (#10283)
The critical semantics are resilient to browser flakiness, so we don't
need this feature test.

Also added comments explaining how invokeGuardedCallback dev works.
2017-07-26 10:01:31 -07:00
Andrew Clark 4fcc25a229 Support throwing null (#10213)
* Support throwing null

In JavaScript, you can throw values of any type, not just errors. That
includes null. We currently rely on null checks to determine if a user-
provided function has thrown. This refactors our error handling code to
keep track of an explicit boolean flag instead.

* Add DOM fixture test case for break on exception behavior

* preventDefault error events during feature test

We call invokeGuardedCallbackDev at startup as part of a feature test.
But we don't want those errors to log to the console.

* Add throwing null test case

* Use ReactFeatureFlags instead of ReactDOMFeatureFlags

React ART uses this, too.

* Non-errors in error logger

If a non-error is thrown, we'll coerce the value to a string and use
that as the message.
2017-07-21 15:34:41 -07:00
Sebastian Markbåge 7b9f64307d Fix lint (#10222) 2017-07-19 11:12:47 -07:00
Sebastian Markbåge 9011182c55 Configure Jest with Stack and Fiber as separate projects (#10214)
* Disable Fiber specific test run in CI

This disables the comparison against previously recorded test. Instead,
we'll rely on jest failures to fail tests.

* Extract jest config into two separate projects for Fiber and Stack

Allows us to run both in the same jest run. The setupMocks file is forked into
specific environment configuration for each project. This replaces the
environment variable.

I used copy pasta here to make it clear. We can abstract this later. It's clear
to me that simply extracting shared stuff is not the best way to abstract this.
setupMocks for example didn't need all the code in both branches.

I think that some of the stuff that is shared such as error message extracting
etc. should probably be lifted out into a stand-alone jest project instead of
being shared.

* Fix class equivalence test

There's a behavior change when projects are used which makes
setupTestFrameworkScriptFile not override the normal config.

This test should probably just move to a separate CI script or something
less hacky.

* Only run Fiber tests with scripts/fiber/record-tests
2017-07-19 10:35:45 -07:00
Sebastian Markbåge 12d5c7a842 Upgrade jest to 20.1.0-delta.1 (#10211)
* Upgrade jest to 20.1.0-delta.1

This includes multi-project support.

* Use isSpy polyfill that is not available in jest 20

* Remove use of jasmine.createSpyObj

We don't really need this and it's not in jest 20.

* Upgrade record-tests script to use the new jest 20 APIs
2017-07-18 17:24:54 -07:00
Dan Abramov 7dc27d35c1 Streamline Fiber/Stack testing and bundling setup a little bit (#9964)
* Remove internal forwarding modules for /lib/

* Add *Entry suffix to all entry points

* Don't bundle ReactNativeFeatureFlags since it's shimmed

* Delete TestRendererStack

* Switch tests at forwarding modules rather than via Jest

* Share mocks between regular and equivalence fixtures

* Rename environment flag to be more generic

* Remove accidental variable name change

* Minor naming changes for consistency

Files that have two versions get the engine in variable name.
2017-06-14 22:10:33 +01:00
Sebastian Markbåge e5e874d0e8 Add package builds for new server renderer and enable tests (#9710)
* Adjust some expectations of the server markup format of Fiber

Currently this case is using the stack renderer.

* Ensure debug hooks are injected into the Stack server renderer

In our tests this normally happens because ReactDOM.js injects them into
the shared module, but when Fiber is enabled or this is its own flat
bundle, that doesn't happen.

* Add package builds for new server renderer and enable tests

ReactServer -> ReactDOMServerStream

This file is going to be the replacement for ReactDOMServer.

I mock ReactDOMServer and user ReactDOMServerStream when we have
the fiber flag enabled. I'm now also enabling this as the default for
distributions builds (react-dom/server on npm and
react-dom-server.production.min.js as umd bundle).

I'm using traverseStackChildren instead of traverseAllChildren because
traverseAllChildren is now only in the isomorphic package and we don't
want to build all of that that into the server package.

I also have to require lower case react for the builds to work.
2017-05-17 17:19:11 -07:00
Ben Alpert b1768b5a48 Prettier 1.2 (#9462) 2017-04-20 11:18:33 -07:00
Brian Vaughn 2beec2f308 createClass + PropTypes + checkPropTypes warnings (#9399)
(Temporarily) re-adds getters with deprecation warnings for React.PropTypes, React.checkPropTypes, and React.createClass.

* 08bd020: Replace all references to React.PropTypes with prop-types to avoid triggering our own warning message.
* ef5b5c6: Removed several references to React.createClass that appeared after rebasing this branch. (reviewed by @flarnie)
* 524ce20: Added getters for createClass and PropTypes to the main React isomorphic object, behind one-time warning messages. (reviewed by @spicyj)
* db48f54: Fixed Rollup bundles to inline 'prop-types' and 'create-react-class' for UMD builds only. (reviewed by @spicyj, @trueadm )
* cf49cfd: Updated tests-passing.txt to remove tests that were deleted in this branch.
* d34109a: Responses to PR feedback from @spicyj. (Added package.json dependencies to packages/react and packages/react-dom. Renamed a var. Expanded on an inline comment.)
* 488c8d2: Added warning for moved package to React.checkPropTypes accessor too and updated build script.
* 83bcb29: Wordsmithing for deprecation notices (added fb.me links).
* afdc9d2: Tweaked legacy module inlining to remove order-of-deps constraint
* d1348b9: Removed $FlowFixMe.
* 7dbc3e7: More wordsmithing of deprecation notices based on Dan's feedback.
2017-04-11 14:28:03 -07:00
Dominic Gannaway 4b2eac3de7 Convert current build system to Rollup and adopt flat bundles (#9327)
* WIP

* fbjs support

* WIP

* dev/prod mode WIP

* More WIP

* builds a cjs bundle

* adding forwarding modules

* more progress on forwarding modules and FB config

* improved how certain modules get inlined for fb and cjs

* more forwarding modules

* added comments to the module aliasing code

* made ReactPerf and ReactTestUtils bundle again

* Use -core suffix for all bundles

This makes it easier to override things in www.

* Add a lazy shim for ReactPerf

This prevents a circular dependency between ReactGKJSModule and ReactDOM

* Fix forwarding module for ReactCurrentOwner

* Revert "Add a lazy shim for ReactPerf"

This reverts commit 723b402c07.

* Rename -core suffix to -fb for clarity

* Change forwarding modules to import from -fb

This is another, more direct fix for ReactPerf circular dependency

* should fix fb and cjs bundles for ReactCurrentOwner

* added provides module for ReactCurrentOwner

* should improve console output

* fixed typo with argument passing on functon call

* Revert "should improve console output"

This breaks the FB bundles.

This reverts commit 65f11ee64f.

* Work around internal FB transform require() issue

* moved  ReactInstanceMap out of React and into ReactDOM and ReactDOMFiber

* Expose more internal modules to www

* Add missing modules to Stack ReactDOM to fix UFI

* Fix onlyChild module

* improved the build tool

* Add a rollup npm script

* Rename ReactDOM-fb to ReactDOMStack-fb

* Fix circular dependencies now that ReactDOM-fb is a GK switch

* Revert "Work around internal FB transform require() issue"

This reverts commit 0a50b6a90b.

* Bump rollup-plugin-commonjs to include a fix for rollup/rollup-plugin-commonjs#176

* Add more forwarding modules that are used on www

* Add even more forwarding modules that are used on www

* Add DOMProperty to hidden exports

* Externalize feature flags

This lets www specify them dynamically.

* Remove forwarding modules with implementations

Instead I'm adding them to react-fb in my diff.

* Add all injection necessary for error logging

* Add missing forwarding module (oops)

* Add ReactART builds

* Add ReactDOMServer bundle

* Fix UMD build of ReactDOMFiber

* Work in progress: start adding ReactNative bundle

* tidied up the options for bundles, so they can define what types they output and exclude

* Add a working RN build

* further improved and tidied up build process

* improved how bundles are built by exposing externals and making the process less "magical", also tidied up code and added more comments

* better handling of bundling ReactCurrentOwner and accessing it from renderer modules

* added NODE_DEV and NODE_PROD

* added NPM package creation and copying into build chain

* Improved UMD bundles, added better fixture testing and doc plus prod builds

* updated internal modules (WIP)

* removed all react/lib/* dependencies from appearing in bundles created on build

* added react-test-renderer bundles

* renamed bundles and paths

* fixed fixture path changes

* added extract-errors support

* added extractErrors warning

* moved shims to shims directory in rollup scripts

* changed pathing to use build rather than build/rollup

* updated release doc to reflect some rollup changes

* Updated ReactNative findNodeHandle() to handle number case (#9238)

* Add dynamic injection to ReactErrorUtils (#9246)

* Fix ReactErrorUtils injection (#9247)

* Fix Haste name

* Move files around

* More descriptive filenames

* Add missing ReactErrorUtils shim

* Tweak reactComponentExpect to make it standalone-ish in www

* Unflowify shims

* facebook-www shims now get copied over correctly to build

* removed unnecessary resolve

* building facebook-www/build is now all sync to prevent IO issues plus handles extra facebook-www src assets

* removed react-native-renderer package and made build make a react-native build dir instead

* 😭😭😭

* Add more SSR unit tests for elements and children. (#9221)

* Adding more SSR unit tests for elements and children.

* Some of my SSR tests were testing for react-text and react-empty elements that no longer exist in Fiber. Fixed the tests so that they expect correct markup in Fiber.

* Tweaked some test names after @gaearon review comment https://github.com/facebook/react/pull/9221#discussion_r107045673 . Also realized that one of the tests was essentially a direct copy of another, so deleted it.

* Responding to code review https://github.com/facebook/react/pull/9221#pullrequestreview-28996315 . Thanks @spicyj!

* ReactElementValidator uses temporary ReactNative View propTypes getter (#9256)

* Updating packages for 16.0.0-alpha.6 release

* Revert "😭😭😭"

This reverts commit 7dba33b2cf.

* Work around Jest issue with CurrentOwner shared state in www

* updated error codes

* splits FB into FB_DEV and FB_PROD

* Remove deps on specific builds from shims

* should no longer mangle FB_PROD output

* Added init() dev block to ReactTestUtils

* added shims for DEV only code so it does not get included in prod bundles

* added a __DEV__ wrapping code to FB_DEV

* added __DEV__ flag behind a footer/header

* Use right haste names

* keeps comments in prod

* added external babel helpers plugin

* fixed fixtures and updated cjs/umd paths

* Fixes Jest so it run tests correctly

* fixed an issue with stubbed modules not properly being replaced due to greedy replacement

* added a WIP solution for ReactCurrentOwner on FB DEV

* adds a FB_TEST bundle

* allows both ReactCurrentOwner and react/lib/ReactCurrentOwner

* adds -test to provides module name

* Remove TEST env

* Ensure requires stay at the top

* added basic mangle support (disbaled by default)

* per bundle property mangling added

* moved around plugin order to try and fix deadcode requires as per https://github.com/rollup/rollup/issues/855

* Fix flow issues

* removed gulp and grunt and moved tasks to standalone node script

* configured circleci to use new paths

* Fix lint

* removed gulp-extract-errors

* added test_build.sh back in

* added missing newline to flow.js

* fixed test coverage command

* changed permissions on test_build.sh

* fixed test_html_generations.sh

* temp removed html render test

* removed the warning output from test_build, the build should do this instead

* fixed test_build

* fixed broken npm script

* Remove unused ViewportMetrics shim

* better error output

* updated circleci to node 7 for async/await

* Fixes

* removed coverage test from circleci run

* circleci run tets

* removed build from circlci

* made a dedicated jest script in a new process

* moved order around of circlci tasks

* changing path to jest in more circleci tests

* re-enabled code coverage

* Add file header to prod bundles

* Remove react-dom/server.js (WIP: decide on the plan)

* Only UMD bundles need version header

* Merge with master

* disabled const evaluation by uglify for <script></script> string literal

* deal with ART modules for UMD bundles

* improved how bundle output gets printed

* fixed filesize difference reporting

* added filesize dep

* Update yarn lockfile for some reason

* now compares against the last run branch built on

* added react-dom-server

* removed un-needed comment

* results only get saved on full builds

* moved the rollup sized plugin into a plugins directory

* added a missing commonjs()

* fixed missing ignore

* Hack around to fix RN bundle

* Partially fix RN bundles

* added react-art bundle and a fixture for it

* Point UMD bundle to Fiber and add EventPluginHub to exported internals

* Make it build on Node 4

* fixed eslint error with resolve being defined in outer scope

* Tweak how build results are calculated and stored

* Tweak fixtures build to work on Node 4

* Include LICENSE/PATENTS and fix up package.json files

* Add Node bundle for react-test-renderer

* Revert "Hack around to fix RN bundle"

We'll do this later.

This reverts commit 59445a6259.

* Revert more RN changes

We'll do them separately later

* Revert more unintentional changes

* Revert changes to error codes

* Add accidentally deleted RN externals

* added RN_DEV/RN_PROD bundles

* fixed typo where RN_DEV and RN_PROD were the wrong way around

* Delete/ignore fixture build outputs

* Format scripts/ with Prettier

* tidied up the Rollup build process and split functions into various different files to improve readability

* Copy folder before files

* updated yarn.lock

* updated results and yarn dependencies to the latest versions
2017-04-05 16:47:29 +01:00
Ben Alpert 19c2649e02 Use fiber by default (#9155)
Affects our builds. But not in tests yet.
2017-03-10 17:06:02 -08:00
Sasha Aickin fcf41e7ca2 Add async/await to unit tests; modify server rendering tests to use async/await. (#9089) 2017-03-03 10:34:14 -08:00
Sebastian Markbåge 13e05b4237 Use separate feature flag for ReactTestRenderer (#8965)
The ReactDOMFeatureFlags is not reachable from the npm package since it is
in a separate build so we need a separate one.
2017-02-09 16:00:59 +00:00