Commit Graph

1609 Commits

Author SHA1 Message Date
Sebastian Markbåge 17806594cc
Move createRoot/hydrateRoot to react-dom/client (#23385)
* Move createRoot/hydrateRoot to /client

We want these APIs ideally to be imported separately from things you
might use in arbitrary components (like flushSync). Those other methods
are "isomorphic" to how the ReactDOM tree is rendered. Similar to hooks.

E.g. importing flushSync into a component that only uses it on the client
should ideally not also pull in the entry client implementation on the
server.

This also creates a nicer parity with /server where the roots are in a
separate entry point.

Unfortunately, I can't quite do this yet because we have some legacy APIs
that we plan on removing (like findDOMNode) and we also haven't implemented
flushSync using a flag like startTransition does yet.

Another problem is that we currently encourage these APIs to be aliased by
/profiling (or unstable_testing). In the future you don't have to alias
them because you can just change your roots to just import those APIs and
they'll still work with the isomorphic forms. Although we might also just
use export conditions for them.

For that all to work, I went with a different strategy for now where the
real API is in / but it comes with a warning if you use it. If you instead
import /client it disables the warning in a wrapper. That means that if you
alias / then import /client that will inturn import the alias and it'll
just work.

In a future breaking changes (likely when we switch to ESM) we can just
remove createRoot/hydrateRoot from / and move away from the aliasing
strategy.

* Update tests to import from react-dom/client

* Fix fixtures

* Update warnings

* Add test for the warning

* Update devtools

* Change order of react-dom, react-dom/client alias

I think the order matters here. The first one takes precedence.

* Require react-dom through client so it can be aliased

Co-authored-by: Andrew Clark <git@andrewclark.io>
2022-03-01 00:13:28 -05:00
Andrew Clark 3a60844a0f
Update error message for suspending at sync priority (#23361)
Instead of adding a new Suspense boundary, the default recommendation
is to wrap the suspending update with startTransition.
2022-02-24 21:02:06 -05:00
Andrew Clark 52c393b5d2
Revert to client render on text mismatch (#23354)
* Refactor warnForTextDifference

We're going to fork the behavior of this function between concurrent
roots and legacy roots.

The legacy behavior is to warn in dev when the text mismatches during
hydration. In concurrent roots, we'll log a recoverable error and revert
to client rendering. That means this is no longer a development-only
function — it affects the prod behavior, too.

I haven't changed any behavior in this commit. I only rearranged the
code slightly so that the dev environment check is inside the body
instead of around the function call. I also threaded through an
isConcurrentMode argument.

* Revert to client render on text content mismatch

Expands the behavior of enableClientRenderFallbackOnHydrationMismatch to
check text content, too.

If the text is different from what was rendered on the server, we will
recover the UI by falling back to client rendering, up to the nearest
Suspense boundary.
2022-02-24 00:23:56 -05:00
Sebastian Markbåge 1ad8d81292
Remove object-assign polyfill (#23351)
* Remove object-assign polyfill

We really rely on a more modern environment where this is typically
polyfilled anyway and we don't officially support IE with more extensive
polyfilling anyway. So all environments should have the native version
by now.

* Use shared/assign instead of Object.assign in code

This is so that we have one cached local instance in the bundle.

Ideally we should have a compile do this for us but we already follow
this pattern with hasOwnProperty, isArray, Object.is etc.

* Transform Object.assign to now use shared/assign

We need this to use the shared instance when Object.spread is used.
2022-02-23 19:34:24 -05:00
Andrew Clark 1760b27c02
Remove ./src/* export from public build (#23262)
We only export the source directory so Jest and Rollup can access them
during local development and at build time. The files don't exist in the
public builds, so we don't need the export entry, either.
2022-02-22 20:13:33 -05:00
Andrew Clark 552c067bb1
Remove public export for unstable-shared-subset.js (#23261)
The unstable-shared-subset.js file is not a public module — it's a
private module that the "react" package maps to when it's accessed from
the "react-server" package.

We originally added it because it was required to make our Rollup
configuration work, because at the time only "public" modules could act
as the entry point for a build artifact — that's why it's prefixed with
"unstable". We've since updated our Rollup config to support private
entry points, so we can remove the extra indirection.
2022-02-22 20:03:51 -05:00
Andrew Clark 51c8411d9d
Log a recoverable error whenever hydration fails (#23319)
There are several cases where hydration fails, server-rendered HTML is
discarded, and we fall back to client rendering. Whenever this happens,
we will now log an error with onRecoverableError, with a message
explaining why.

In some of these scenarios, this is not the only recoverable error that
is logged. For example, an error during hydration will cause hydration
to fail, which is itself an error. So we end up logging two separate
errors: the original error, and one that explains why hydration failed.

I've made sure that the original error always gets logged first, to
preserve the causal sequence.

Another thing we could do is aggregate the errors with the Error "cause"
feature and AggregateError. Since these are new-ish features in
JavaScript, we'd need a fallback behavior. I'll leave this for a
follow up.
2022-02-17 15:16:17 -05:00
Andrew Clark 9b5e0517b4
Remove deprecated wildcard folder mapping (#23256)
* Remove deprecated folder mapping

Node v16 deprecated the use of trailing "/" to define subpath folder
mappings in the "exports" field of package.json.

The recommendation is to explicitly list all our exports. We already do
that for all our public modules. I believe the only reason we have a
wildcard pattern is because our package.json files are also used at
build time (by Rollup) to resolve internal source modules that don't
appear in the final npm artifact.

Changing trailing "/" to "/*" fixes the warnings. See
https://nodejs.org/api/packages.html#subpath-patterns for more info.

Since the wildcard pattern only exists so our build script has access to
internal at build time, I've scoped the wildcard to "/src/*". Because
our public modules are located outside the "src" directory, this means
deep imports of our modules will no longer work: only packages that are
listed in the "exports" field.

The only two affected packages are react-dom and react. We need to be
sure that all our public modules are still reachable. I audited the
exports by comparing the entries to the "files" field in package.json,
which represents a complete list of the files that are included in the
final release artifact.

At some point, we should add an e2e packaging test to prevent
regressions; for now, we should have decent coverage because in CI we
run our Jest test suite against the release artifacts.

* Remove umd from exports

Our expectation is that if you're using the UMD builds, you're not
loading them through a normal module system like require or import.
Instead you're probably copying the files directly or loading them from
a CDN like unpkg.
2022-02-09 11:37:17 -08:00
Andrew Clark 274b9fb168
Remove path resolution from internal forks plugin (#23255)
Alternative to #23254

Our build script has a custom plugin to resolve internal module forks.
Currently, it uses require.resolve to resolve the path to a real file
on disk.

Instead, I've updated all the forked module paths to match their
location on disk, relative to the project root, to remove the need to
resolve them in the build script's runtime.

The main motivation is because require.resolve doesn't work with ESM
modules, but aside from that, hardcoding the relative paths is more
predictable — the Node module resolution algorithm is complicated, and
we don't really need its features for this purpose.
2022-02-09 08:44:02 -08:00
Sebastian Markbåge a3bde7974c
Exclude react-dom/unstable_testing entry point from stable releases (#23258)
* Use consistent naming for unstable_testing entry point

* Exclude the testing build from non-experimental builds except at FB

* FB builds shouldn't contribute to whether we include the npm files

* Exclude exports fields if we delete the files entry

* Move test to no longer be internal so we can test against the build

* Update the bundle artifact names since they've now changed

* Gate import since it doesn't exist
2022-02-08 23:12:31 -05:00
Joshua Gross 9d4e8e84f7
React Native raw event EventEmitter - intended for app-specific perf listeners and debugging (#23232)
* RawEventEmitter: new event perf profiling mechanism outside of Pressability to capture all touch events, and other event types

* sync

* concise notation

* Move event telemetry event emitter call from Plugin to ReactFabricEventEmitter, to reduce reliance on the plugin system and move the emit call further into the core

* Backout changes to ReactNativeEventPluginOrder

* Properly flow typing event emitter, and emit event to two channels: named and catchall

* fix typing for event name string

* fix typing for event name string

* fix flow

* Add more comments about how the event telemetry system works

* Add more comments about how the event telemetry system works

* rename to RawEventTelemetryEventEmitterOffByDefault

* yarn prettier-all

* rename event

* comments

* improve flow types

* renamed file
2022-02-07 18:34:01 -08:00
Andrew Clark 848e802d20
Add onRecoverableError option to hydrateRoot, createRoot (#23207)
* [RFC] Add onHydrationError option to hydrateRoot

This is not the final API but I'm pushing it for discussion purposes.

When an error is thrown during hydration, we fallback to client
rendering, without triggering an error boundary. This is good because,
in many cases, the UI will recover and the user won't even notice that
something has gone wrong behind the scenes.

However, we shouldn't recover from these errors silently, because the
underlying cause might be pretty serious. Server-client mismatches are
not supposed to happen, even if UI doesn't break from the users
perspective. Ignoring them could lead to worse problems later. De-opting
from server to client rendering could also be a significant performance
regression, depending on the scope of the UI it affects.

So we need a way to log when hydration errors occur.

This adds a new option for `hydrateRoot` called `onHydrationError`. It's
symmetrical to the server renderer's `onError` option, and serves the
same purpose.

When no option is provided, the default behavior is to schedule a
browser task and rethrow the error. This will trigger the normal browser
behavior for errors, including dispatching an error event. If the app
already has error monitoring, this likely will just work as expected
without additional configuration.

However, we can also expose additional metadata about these errors, like
which Suspense boundaries were affected by the de-opt to client
rendering. (I have not exposed any metadata in this commit; API needs
more design work.)

There are other situations besides hydration where we recover from an
error without surfacing it to the user, or notifying an error boundary.
For example, if an error occurs during a concurrent render, it could be
due to a data race, so we try again synchronously in case that fixes it.
We should probably expose a way to log these types of errors, too. (Also
not implemented in this commit.)

* Log all recoverable errors

This expands the scope of onHydrationError to include all errors that
are not surfaced to the UI (an error boundary). In addition to errors
that occur during hydration, this also includes errors that recoverable
by de-opting to synchronous rendering. Typically (or really, by
definition) these errors are the result of a concurrent data race;
blocking the main thread fixes them by prevents subsequent races.

The logic for de-opting to synchronous rendering already existed. The
only thing that has changed is that we now log the errors instead of
silently proceeding.

The logging API has been renamed from onHydrationError
to onRecoverableError.

* Don't log recoverable errors until commit phase

If the render is interrupted and restarts, we don't want to log the
errors multiple times.

This change only affects errors that are recovered by de-opting to
synchronous rendering; we'll have to do something else for errors
during hydration, since they use a different recovery path.

* Only log hydration error if client render succeeds

Similar to previous step.

When an error occurs during hydration, we only want to log it if falling
back to client rendering _succeeds_. If client rendering fails,
the error will get reported to the nearest error boundary, so there's
no need for a duplicate log.

To implement this, I added a list of errors to the hydration context.
If the Suspense boundary successfully completes, they are added to
the main recoverable errors queue (the one I added in the
previous step.)

* Log error with queueMicrotask instead of Scheduler

If onRecoverableError is not provided, we default to rethrowing the
error in a separate task. Originally, I scheduled the task with
idle priority, but @sebmarkbage made the good point that if there are
multiple errors logs, we want to preserve the original order. So I've
switched it to a microtask. The priority can be lowered in userspace
by scheduling an additional task inside onRecoverableError.

* Only use host config method for default behavior

Redefines the contract of the host config's logRecoverableError method
to be a default implementation for onRecoverableError if a user-provided
one is not provided when the root is created.

* Log with reportError instead of rethrowing

In modern browsers, reportError will dispatch an error event, emulating
an uncaught JavaScript error. We can do this instead of rethrowing
recoverable errors in a microtask, which is nice because it avoids any
subtle ordering issues.

In older browsers and test environments, we'll fall back
to console.error.

* Naming nits

queueRecoverableHydrationErrors -> upgradeHydrationErrorsToRecoverable
2022-02-04 07:57:33 -08:00
Brian Vaughn fa816be7f0
DevTools: Timeline profiler refactor
Refactor DevTools to record Timeline data (in memory) while profiling. Updated the Profiler UI to import/export Timeline data along with legacy profiler data.

Relates to issue #22529
2022-01-28 13:09:28 -05:00
Brian Vaughn a637084320
DevTools: Add Jest snapshot serializer for number formatting (#23139)
Numbers in JavaScript can have precision issues due to how they are encoded. This shows up in snapshot tests sometimes with values like 0.0009999999999999992, which makes the tests hard to read and visually diff.

This PR adds a new snapshot serializers which clamps numbers at 3 decimal points (e.g. the above number 0.0009999999999999992 is serialized as 0.001). This new serializer does not impact non-numeric values, integers, and special numbers like NaN and Infinity.
2022-01-20 15:52:17 -05:00
Brian Vaughn 51947a14bb
Refactored how React/DevTools log Timeline performance data (#23102)
Until now, DEV and PROFILING builds of React recorded Timeline profiling data using the User Timing API. This commit changes things so that React records this data by calling methods on the DevTools hook. (For now, DevTools still records that data using the User Timing API, to match previous behavior.)

This commit is large but most of it is just moving things around:

* New methods have been added to the DevTools hook (in "backend/profilingHooks") for recording the Timeline performance events.
* Reconciler's "ReactFiberDevToolsHook" has been updated to call these new methods (when they're present).
* User Timing method calls in "SchedulingProfiler" have been moved to DevTools "backend/profilingHooks" (to match previous behavior, for now).
* The old reconciler tests, "SchedulingProfiler-test" and "SchedulingProfilerLabels-test", have been moved into DevTools "TimelineProfiler-test" to ensure behavior didn't change unexpectedly.
* Two new methods have been added to the injected renderer interface: injectProfilingHooks() and getLaneLabelMap().

Relates to #22529.
2022-01-13 14:55:54 -05:00
Moti Zilberman c09596cc60
Add RN_FB bundles for react-is (#23101)
* Add RN_FB bundles for react-is

* Update packaging.js

* Add ReactNativeInternalFeatureFlags to externals
2022-01-12 21:53:50 +00:00
Stefan Sundin 9a7e6bf0d0
Add --no-show-signature to "git show" commands (#23038)
* Add --no-show-signature to "git show" commands.

This fixes errors if the user has configured the following in their ~/.gitconfig:
[log]
showSignature = true

* yarn prettier-all
2022-01-11 12:14:08 -05:00
Andrew Covenant fe419346da
Console message fixed for devtools (#23067) 2022-01-05 11:45:45 -05:00
Brian Vaughn 9724e18004
Run DevTools e2e tests on Circle CI (#23019) 2022-01-04 10:28:03 -05:00
Vitalie bd0a5dd682
#22988 - Fix Bug: @license header in React 18 bundles contains vundefined (#23004)
* Fix Bug: @license header in React 18 bundles contains vundefined
* Remove React version from the header comment
2021-12-21 12:27:59 -05:00
Sebastian Markbåge cd1a3e9b55
Build both a partial renderer and fizz renderer of the legacy API for FB (#22933)
This lets us test how the new architecture performs without comparing it to
other infra changes related to streaming.

I renamed the streaming one to ReactDOMServerStreaming so the references
in www need to be updated.

I'll open an adhoc sync with just those files.
2021-12-14 16:19:19 -08:00
Andrew Clark 72e48b8e16
Fix: Don't skip writing updated package.json
Another fix to previous commit. The special case for
use-sync-external-store still needs to write out the updated
package.json, because we also use that branch to update the
version field.
2021-12-08 02:56:43 -05:00
Andrew Clark e39b2c8998
Fix peer deps for use-sync-external-store
Merged last PR too quickly
2021-12-08 02:45:57 -05:00
Andrew Clark ec78b135fb
Don't override use-sync-external-store peerDeps (#22882)
Usually the build script updates transitive React dependencies so that
they refer to the corresponding release version.

For use-sync-external-store, though, we also want to support older
versions of React, too. So the normal behavior of the build script
isn't sufficient.

For now, to unblock, I hardcoded a special case, but we should consider
a better way to handle this in the future.
2021-12-07 23:26:12 -08:00
Andrew Clark 06f403481f
Add CI job to check npm dependencies (#22881)
Checks that if one React package depends on another, the current
version satisfies the given dependency range.

That way we don't forget to bump dependencies when we release a
new version.
2021-12-07 23:09:00 -08:00
Esteban 09d9b17757
Update deprecated features in ESLint configuration files. (#22767) 2021-11-23 22:53:26 +00:00
Esteban b32b67706f
Migrate from CLIEngine to the new ESLint class. (#22756)
* Migrate from CLIEngine to the new ESLint class.

* fix output property
2021-11-18 21:12:18 +00:00
Brian Vaughn aa19d569b2
Add test selectors to experimental build (#22760)
This change adds a new "react-dom/unstable_testing" entry point but I believe its contents will exactly match "react-dom/index" for the stable build. (The experimental build will have the added new selector APIs.)
2021-11-16 16:27:10 -05:00
Jiachi Liu 520ffc77a3
Use globalThis if possible for native fetch in browser build (#22777) 2021-11-16 21:24:54 +00:00
Esteban afbc2d08f4
Remove unused react-internal/invariant-args ESLint rule. (#22778) 2021-11-16 20:11:20 +00:00
Andrew Clark 96ca8d9155
Allow publishing with `beta` tag (#22768) 2021-11-15 10:43:40 -08:00
Andrew Clark 83564712b6
Move SuspenseList to experimental channel (#22765)
There's more work to be done to implement this correctly on the server,
so we're going to wait to release it until an 18.x minor.
2021-11-15 10:12:56 -08:00
MalikIdreesHasanKhan 489b4bdcca
Fixed typos (#22763)
* Fixed typos

* Update ReactFiberWorkLoop.new.js

* Update ReactFiberWorkLoop.old.js
2021-11-15 12:31:35 -05:00
180909 e6f60d2add
fix typos (#22715) 2021-11-15 10:58:21 -05:00
salazarm 0ddd69d122
Throw on hydration mismatch and force client rendering if boundary hasn't suspended within concurrent root (#22629)
* Throw on hydration mismatch

* remove debugger

* update error message

* update error message part2...

* fix test?

* test? :(

* tests 4real

* remove useRefAccessWarning gating

* split markSuspenseBoundary and getNearestBoundary

* also assert html is correct

* replace-fork

* also remove client render flag on suspend

* replace-fork

* fix mismerge????
2021-11-09 13:40:50 -05:00
Esteban 327d5c4845
Delete unused Circle CI scripts. (#22710) 2021-11-06 14:16:49 +00:00
Konstantin Popov 54f6ae9b1c
Fix small typos (#22701) 2021-11-04 19:49:06 -04:00
Brian Vaughn 8ca3f567bc
Fix module-boundary wrappers (#22688) 2021-11-04 10:40:35 -04:00
Brian Vaughn 1bf6deb865
Renamed packages/react-devtools-scheduling-profiler to packages/react-devtools-timeline (#22691) 2021-11-04 10:02:06 -04:00
Brian Vaughn 51c558aeb6
Rename (some) "scheduling profiler" references to "timeline" (#22690) 2021-11-03 15:10:29 -04:00
Andrew Clark 75f3ddebfa
Remove experimental useOpaqueIdentifier API (#22672)
useId is the updated version of this API.
2021-11-01 15:02:39 -07:00
Andrew Clark 6bce0355c3
Upgrade useSyncExternalStore to alpha channel (#22662)
* Move useSyncExternalStore shim to a nested entrypoint

Also renames `useSyncExternalStoreExtra` to
`useSyncExternalStoreWithSelector`.

- 'use-sync-external-store/shim' -> A shim for `useSyncExternalStore`
  that works in React 16 and 17 (any release that supports hooks). The
  module will first check if the built-in React API exists, before
  falling back to the shim.
- 'use-sync-external-store/with-selector' -> An extended version of
  `useSyncExternalStore` that also supports `selector` and `isEqual`
  options. It does _not_ shim `use-sync-external-store`; it composes the
  built-in React API. **Use this if you only support 18+.**
- 'use-sync-external-store/shim/with-selector' -> Same API, but it
  composes `use-sync-external-store/shim` instead. **Use this for
  compatibility with 16 and 17.**
- 'use-sync-external-store' -> Re-exports React's built-in API. Not
  meant to be used. It will warn and direct users to either the shim or
  the built-in API.

* Upgrade useSyncExternalStore to alpha channel
2021-10-31 15:38:03 -07:00
Andrew Clark 7034408ff7
Follow-up improvements to error code extraction infra (#22516)
* Output FIXME during build for unminified errors

The invariant Babel transform used to output a FIXME comment if it
could not find a matching error code. This could happen if there were
a configuration mistake that caused an unminified message to
slip through.

Linting the compiled bundles is the most reliable way to do it because
there's not a one-to-one mapping between source modules and bundles. For
example, the same source module may appear in multiple bundles, some
which are minified and others which aren't.

This updates the transform to output the same messages for Error calls.

The source lint rule is still useful for catching mistakes during
development, to prompt you to update the error codes map before pushing
the PR to CI.

* Don't run error transform in development

We used to run the error transform in both production and development,
because in development it was used to convert `invariant` calls into
throw statements.

Now that don't use `invariant` anymore, we only have to run the
transform for production builds.

* Add ! to FIXME comment so Closure doesn't strip it

Don't love this solution because Closure could change this heuristic,
or we could switch to a differnt compiler that doesn't support it. But
it works.

Could add a bundle that contains an unminified error solely for the
purpose of testing it, but that seems like overkill.

* Alternate extract-errors that scrapes artifacts

The build script outputs a special FIXME comment when it fails to minify
an error message. CI will detect these comments and fail the workflow.

The comments also include the expected error message. So I added an
alternate extract-errors that scrapes unminified messages from the
build artifacts and updates `codes.json`.

This is nice because it works on partial builds. And you can also run it
after the fact, instead of needing build all over again.

* Disable error minification in more bundles

Not worth it because the number of errors does not outweight the size
of the formatProdErrorMessage runtime.

* Run extract-errors script in CI

The lint_build job already checks for unminified errors, but the output
isn't super helpful.

Instead I've added a new job that runs the extract-errors script and
fails the build if `codes.json` changes. It also outputs the expected
diff so you can easily see which messages were missing from the map.

* Replace old extract-errors script with new one

Deletes the old extract-errors in favor of extract-errors2
2021-10-31 15:37:32 -07:00
Joseph Savona fa9bea0c41
Initial implementation of cache cleanup (#22510)
This is an initial, partial implementation of a cleanup mechanism for the experimental Cache API. The idea is that consumers of the Cache API can register to be informed when a given Cache instance is no longer needed so that they can perform associated cleanup tasks to free resources stored in the cache. A canonical example would be cancelling pending network requests.

An overview of the high-level changes:

* Changes the `Cache` type from a Map of cache instances to be an object with the original Map of instances, a reference count (to count roughly "active references" to the cache instances - more below), and an AbortController.
* Adds a new public API, `unstable_getCacheSignal(): AbortSignal`, which is callable during render. It returns an AbortSignal tied to the lifetime of the cache - developers can listen for the 'abort' event on the signal, which React now triggers when a given cache instance is no longer referenced. 
  * Note that `AbortSignal` is a web standard that is supported by other platform APIs; for example a signal can be passed to `fetch()` to trigger cancellation of an HTTP request.
* Implements the above - triggering the 'abort' event - by handling passive mount/unmount for HostRoot and CacheComponent fiber nodes.

Cases handled:
* Aborted transitions: we clean up a new cache created for an aborted transition
* Suspense: we retain a fresh cache instance until a suspended tree resolves

For follow-ups:
* When a subsequent cache refresh is issued before a previous refresh completes, the refreshes are queued. Fresh cache instances for previous refreshes in the queue should be cleared, retaining only the most recent cache. I plan to address this in a follow-up PR.
* If a refresh is cancelled, the fresh cache should be cleaned up.
2021-10-21 14:11:42 -07:00
Brian Vaughn 4ba20579da
Scheduling Profiler: De-emphasize React internal frames (#22588)
This commit adds code to all React bundles to explicitly register the beginning and ending of the module. This is done by creating Error objects (which capture the file name, line number, and column number) and passing them explicitly to a DevTools hook (when present).

Next, as the Scheduling Profiler logs metadata to the User Timing API, it prints these module ranges along with other metadata (like Lane values and profiler version number).

Lastly, the Scheduling Profiler UI compares stack frames to these ranges when drawing the flame graph and dims or de-emphasizes frames that fall within an internal module.

The net effect of this is that user code (and 3rd party code) stands out clearly in the flame graph while React internal modules are dimmed.

Internal module ranges are completely optional. Older profiling samples, or ones recorded without the React DevTools extension installed, will simply not dim the internal frames.
2021-10-21 14:40:41 -04:00
Andrew Clark 163e81c1f8
Support disabling spurious act warnings with a global environment flag (#22561)
* Extract `act` environment check into function

`act` checks the environment to determine whether to fire a warning.
We're changing how this check works in React 18. As a first step, this
refactors the logic into a single function. No behavior changes yet.

* Use IS_REACT_ACT_ENVIRONMENT to disable warnings

If `IS_REACT_ACT_ENVIRONMENT` is set to `false`, we will suppress
any `act` warnings. Otherwise, the behavior of `act` is the same as in
React 17: if `jest` is defined, it warns.

In concurrent mode, the plan is to remove the `jest` check and only warn
if `IS_REACT_ACT_ENVIRONMENT` is true. I have not implemented that
part yet.
2021-10-18 08:27:26 -07:00
Juan e5f486b5a8
React DevTools 4.19.2 -> 4.20.2 (#22569) 2021-10-15 12:50:17 -04:00
Juan 1def0a4244
DevTools prepare release script resets patch version when bumping minor (#22568) 2021-10-15 12:50:00 -04:00
Brian Vaughn c16b005f2d
Update test and stack frame code to support newer V8 stack formats (#22477) 2021-10-11 18:40:42 -04:00
Sebastian Markbåge 579c008a75
[Fizz/Flight] pipeToNodeWritable(..., writable).startWriting() -> renderToPipeableStream(...).pipe(writable) (#22450)
* Rename pipeToNodeWritable to renderToNodePipe

* Add startWriting API to Flight

We don't really need it in this case because there's way less reason to
delay the stream in Flight.

* Pass the destination to startWriting instead of renderToNode

* Rename startWriting to pipe

This mirrors the ReadableStream API in Node

* Error codes

* Rename to renderToPipeableStream

This mimics the renderToReadableStream API for the browser.
2021-10-06 00:31:06 -04:00
Sebastian Markbåge 6485ef7472
Remove duplicate error code (#22513) 2021-10-05 19:59:46 -07:00
Brian Vaughn cadf94df1f
Add new Jest --compact-console flag for DevTools tests (#22495) 2021-10-05 11:58:54 -04:00
Andrew Clark a724a3b578
[RFC] Codemod invariant -> throw new Error (#22435)
* Hoist error codes import to module scope

When this code was written, the error codes map (`codes.json`) was
created on-the-fly, so we had to lazily require from inside the visitor.

Because `codes.json` is now checked into source, we can import it a
single time in module scope.

* Minify error constructors in production

We use a script to minify our error messages in production. Each message
is assigned an error code, defined in `scripts/error-codes/codes.json`.
Then our build script replaces the messages with a link to our
error decoder page, e.g. https://reactjs.org/docs/error-decoder.html/?invariant=92

This enables us to write helpful error messages without increasing the
bundle size.

Right now, the script only works for `invariant` calls. It does not work
if you throw an Error object. This is an old Facebookism that we don't
really need, other than the fact that our error minification script
relies on it.

So, I've updated the script to minify error constructors, too:

Input:
  Error(`A ${adj} message that contains ${noun}`);
Output:
  Error(formatProdErrorMessage(ERR_CODE, adj, noun));

It only works for constructors that are literally named Error, though we
could add support for other names, too.

As a next step, I will add a lint rule to enforce that errors written
this way must have a corresponding error code.

* Minify "no fallback UI specified" error in prod

This error message wasn't being minified because it doesn't use
invariant. The reason it didn't use invariant is because this particular
error is created without begin thrown — it doesn't need to be thrown
because it's located inside the error handling part of the runtime.

Now that the error minification script supports Error constructors, we
can minify it by assigning it a production error code in
`scripts/error-codes/codes.json`.

To support the use of Error constructors more generally, I will add a
lint rule that enforces each message has a corresponding error code.

* Lint rule to detect unminified errors

Adds a lint rule that detects when an Error constructor is used without
a corresponding production error code.

We already have this for `invariant`, but not for regular errors, i.e.
`throw new Error(msg)`. There's also nothing that enforces the use of
`invariant` besides convention.

There are some packages where we don't care to minify errors. These are
packages that run in environments where bundle size is not a concern,
like react-pg. I added an override in the ESLint config to ignore these.

* Temporarily add invariant codemod script

I'm adding this codemod to the repo temporarily, but I'll revert it
in the same PR. That way we don't have to check it in but it's still
accessible (via the PR) if we need it later.

* [Automated] Codemod invariant -> Error

This commit contains only automated changes:

npx jscodeshift -t scripts/codemod-invariant.js packages --ignore-pattern="node_modules/**/*"
yarn linc --fix
yarn prettier

I will do any manual touch ups in separate commits so they're easier
to review.

* Remove temporary codemod script

This reverts the codemod script and ESLint config I added temporarily
in order to perform the invariant codemod.

* Manual touch ups

A few manual changes I made after the codemod ran.

* Enable error code transform per package

Currently we're not consistent about which packages should have their
errors minified in production and which ones should.

This adds a field to the bundle configuration to control whether to
apply the transform. We should decide what the criteria is going
forward. I think it's probably a good idea to minify any package that
gets sent over the network. So yes to modules that run in the browser,
and no to modules that run on the server and during development only.
2021-09-30 12:01:28 -07:00
Andrew Clark d3e0869324
Make root.unmount() synchronous (#22444)
* Move flushSync warning to React DOM

When you call in `flushSync` from an effect, React fires a warning. I've
moved the implementation of this warning out of the reconciler and into
React DOM.

`flushSync` is a renderer API, not an isomorphic API, because it has
behavior that was designed specifically for the constraints of React
DOM. The equivalent API in a different renderer may not be the same.
For example, React Native has a different threading model than the
browser, so it might not make sense to expose a `flushSync` API to the
JavaScript thread.

* Make root.unmount() synchronous

When you unmount a root, the internal state that React stores on the
DOM node is immediately cleared. So, we should also synchronously
delete the React tree. You should be able to create a new root using
the same container.
2021-09-27 14:04:39 -07:00
Justin Grant c88fb49d37
Improve DEV errors if string coercion throws (Temporal.*, Symbol, etc.) (#22064)
* Revise ESLint rules for string coercion

Currently, react uses `'' + value` to coerce mixed values to strings.
This code will throw for Temporal objects or symbols.

To make string-coercion safer and to improve user-facing error messages,
This commit adds a new ESLint rule called `safe-string-coercion`.

This rule has two modes: a production mode and a non-production mode.
* If the `isProductionUserAppCode` option is true, then `'' + value`
  coercions are allowed (because they're faster, although they may
  throw) and `String(value)` coercions are disallowed. Exception:
  when building error messages or running DEV-only code in prod
  files, `String()` should be used because it won't throw.
* If the `isProductionUserAppCode` option is false, then `'' + value`
  coercions are disallowed (because they may throw, and in non-prod
  code it's not worth the risk) and `String(value)` are allowed.

Production mode is used for all files which will be bundled with
developers' userland apps. Non-prod mode is used for all other React
code: tests, DEV blocks, devtools extension, etc.

In production mode, in addiiton to flagging `String(value)` calls,
the rule will also flag `'' + value` or `value + ''` coercions that may
throw. The rule is smart enough to silence itself in the following
"will never throw" cases:
* When the coercion is wrapped in a `typeof` test that restricts to safe
  (non-symbol, non-object) types. Example:
    if (typeof value === 'string' || typeof value === 'number') {
      thisWontReport('' + value);
    }
* When what's being coerced is a unary function result, because unary
   functions never return an object or a symbol.
* When the coerced value is a commonly-used numeric identifier:
  `i`, `idx`, or `lineNumber`.
* When the statement immeidately before the coercion is a DEV-only
  call to a function from shared/CheckStringCoercion.js. This call is a
  no-op in production, but in DEV it will show a console error
  explaining the problem, then will throw right after a long explanatory
  code comment so that debugger users will have an idea what's going on.
  The check function call must be in the following format:
    if (__DEV__) {
      checkXxxxxStringCoercion(value);
    };

Manually disabling the rule is usually not necessary because almost all
prod use of the `'' + value` pattern falls into one of the categories
above. But in the rare cases where the rule isn't smart enough to detect
safe usage (e.g. when a coercion is inside a nested ternary operator),
manually disabling the rule will be needed.

The rule should also be manually disabled in prod error handling code
where `String(value)` should be used for coercions, because it'd be
bad to throw while building an error message or stack trace!

The prod and non-prod modes have differentiated error messages to
explain how to do a proper coercion in that mode.

If a production check call is needed but is missing or incorrect
(e.g. not in a DEV block or not immediately before the coercion), then
a context-sensitive error message will be reported so that developers
can figure out what's wrong and how to fix the problem.

Because string coercions are now handled by the `safe-string-coercion`
rule, the `no-primitive-constructor` rule no longer flags `String()`
usage. It still flags `new String(value)` because that usage is almost
always a bug.

* Add DEV-only string coercion check functions

This commit adds DEV-only functions to check whether coercing
values to strings using the `'' + value` pattern will throw. If it will
throw, these functions will:
1. Display a console error with a friendly error message describing
   the problem and the developer can fix it.
2. Perform the coercion, which will throw. Right before the line where
   the throwing happens, there's a long code comment that will help
   debugger users (or others looking at the exception call stack) figure
   out what happened and how to fix the problem.

One of these check functions should be called before all string coercion
of user-provided values, except when the the coercion is guaranteed not
to throw, e.g.
* if inside a typeof check like `if (typeof value === 'string')`
* if coercing the result of a unary function like `+value` or `value++`
* if coercing a variable named in a whitelist of numeric identifiers:
  `i`, `idx`, or `lineNumber`.

The new `safe-string-coercion` internal ESLint rule enforces that
these check functions are called when they are required.

Only use these check functions in production code that will be bundled
with user apps.  For non-prod code (and for production error-handling
code), use `String(value)` instead which may be a little slower but will
never throw.

* Add failing tests for string coercion

Added failing tests to verify:
* That input, select, and textarea elements with value and defaultValue
  set to Temporal-like objects which will throw when coerced to string
  using the `'' + value` pattern.
* That text elements will throw for Temporal-like objects
* That dangerouslySetInnerHTML will *not* throw for Temporal-like
  objects because this value is not cast to a string before passing to
  the DOM.
* That keys that are Temporal-like objects will throw

All tests above validate the friendly error messages thrown.

* Use `String(value)` for coercion in non-prod files

This commit switches non-production code from `'' + value` (which
throws for Temporal objects and symbols) to instead use `String(value)`
which won't throw for these or other future plus-phobic types.

"Non-produciton code" includes anything not bundled into user apps:
* Tests and test utilities. Note that I didn't change legacy React
  test fixtures because I assumed it was good for those files to
  act just like old React, including coercion behavior.
* Build scripts
* Dev tools package - In addition to switching to `String`, I also
  removed special-case code for coercing symbols which is now
  unnecessary.

* Add DEV-only string coercion checks to prod files

This commit adds DEV-only function calls to to check if string coercion
using `'' + value` will throw, which it will if the value is a Temporal
object or a symbol because those types can't be added with `+`.

If it will throw, then in DEV these checks will show a console error
to help the user undertsand what went wrong and how to fix the
problem. After emitting the console error, the check functions will
retry the coercion which will throw with a call stack that's easy (or
at least easier!) to troubleshoot because the exception happens right
after a long comment explaining the issue. So whether the user is in
a debugger, looking at the browser console, or viewing the in-browser
DEV call stack, it should be easy to understand and fix the problem.

In most cases, the safe-string-coercion ESLint rule is smart enough to
detect when a coercion is safe. But in rare cases (e.g. when a coercion
is inside a ternary) this rule will have to be manually disabled.

This commit also switches error-handling code to use `String(value)`
for coercion, because it's bad to crash when you're trying to build
an error message or a call stack!  Because `String()` is usually
disallowed by the `safe-string-coercion` ESLint rule in production
code, the rule must be disabled when `String()` is used.
2021-09-27 10:05:07 -07:00
Andrew Clark d56947eb2c
Increase polling threshold for publish-prereleases (#22392)
The publish-preleases command prints the URL of the publish workflow
so that you can visit the page and follow along.

But it can take a few seconds before the workflow ID is available, after
you create the pipeline. So the script polls the workflow endpoint
until it's available.

The current polling limit is too low so I increased it.

I also updated the error message to provide more info.
2021-09-21 18:43:59 -07:00
Andrew Clark cf07c3df12
Delete all but one `build2` reference (#22391)
This removes all the remaining references to the `build2` directory
except for the CI job that stores the artifacts. We'll keep the
`build2` artifact until downstream scripts are migrated to `build`.
2021-09-21 13:15:41 -07:00
Andrew Clark bb0d069359
[build2 -> build] Local scripts
Update all our local scripts to use `build` instead of `build2`.

There are still downstream scripts that depend on `build2`, though, so
we can't remove it yet.
2021-09-21 15:14:09 -04:00
Andrew Clark f35287dda4 [build2 -> build] -> download-build-artifacts 2021-09-21 13:47:40 -04:00
Andrew Clark 0c81d347b6 Write artifacts to `build` instead of `build2`
Now that all the CI jobs have been migrated to the new build script,
we can start renaming the `build2` directory to `build`.

Since there are lots of scripts that reference `build2`, including
downstream scripts that live outside this repo, I'm going to keep
the `build2` directory around as a copy of `build`.

Then once all the references are updated, I will delete the copy.
2021-09-21 12:23:48 -04:00
salazarm 4da03c9fbd
useSyncExternalStore React Native version (#22367) 2021-09-21 11:07:56 -04:00
Andrew Clark 79b8fc6670
Implement getServerSnapshot in userspace shim (#22359)
* Convert useSES shim tests to use React DOM

Idea is that eventually we'll run these tests against an actual build of
React DOM 17 to test backwards compatibility.

* Implement getServerSnapshot in userspace shim

If the DOM is not present, we assume that we are running in a server
environment and return the result of `getServerSnapshot`.

This heuristic doesn't work in React Native, so we'll need to provide
a separate native build (using the `.native` extension). I've left this
for a follow-up.

We can't call `getServerSnapshot` on the client, because in versions of
React before 18, there's no built-in mechanism to detect whether we're
hydrating. To avoid a server mismatch warning, users must account for
this themselves and return the correct value inside `getSnapshot`.

Note that none of this is relevant to the built-in API that is being
added in 18. This only affects the userspace shim that is provided
for backwards compatibility with versions 16 and 17.
2021-09-20 08:32:13 -07:00
Andrew Clark 86b3e2461d
Implement useSyncExternalStore on server (#22347)
Adds a third argument called `getServerSnapshot`.

On the server, React calls this one instead of the normal `getSnapshot`.
We also call it during hydration.

So it represents the snapshot that is used to generate the initial,
server-rendered HTML. The purpose is to avoid server-client mismatches.
What we render during hydration needs to match up exactly with what we
render on the server.

The pattern is for the server to send down a serialized copy of the
store that was used to generate the initial HTML. On the client, React
will call either `getSnapshot` or `getServerSnapshot` on the client as
appropriate, depending on whether it's currently hydrating.

The argument is optional for fully client rendered use cases. If the
user does attempt to omit `getServerSnapshot`, and the hook is called
on the server, React will abort that subtree on the server and
revert to client rendering, up to the nearest Suspense boundary.

For the userspace shim, we will need to use a heuristic (canUseDOM)
to determine whether we are in a server environment. I'll do that in
a follow up.
2021-09-20 08:31:02 -07:00
Brian Vaughn 57e4d6872f
replace-fork: Cleanup after failure if no unstaged changes (#22364) 2021-09-20 11:10:17 -04:00
Andrew Clark 293059e52b
replace-fork should not clear uncommitted changes (#22348)
The replace-fork script depends on ESLint to fix the reconciler imports
— `.old` -> `.new` or vice versa. If ESLint crashes, it can leave the
imports in an incorrect state.

As a convenience, @bvaughn updated the script to automatically run
`git checkout -- .` if the ESLint command fails. An unintended
consequence of the strategy is that if the working directory is not
clean, then any uncommitted changes will be lost.

We need a better strategy for this that prevents the accidental loss of
work. One option is to exit early if the working directory is not clean
before you run the script, though that affects the usability of
the script.

An ideal solution would reset the working directory back to whatever
state it was in before the script ran, perhaps by stashing all the
changes and restoring them if the script aborts.

Until we think of something better, I've commmented out the branch.
2021-09-20 10:07:25 -04:00
Brian Vaughn f4ac680c7a
Fixed broken build script --unsafe-partial flag (#22324)
This flag was broken due to a buggy race case in the ncp() command. The fix is amittedly a hack but improves on the existing behavior (of leaving the workspace in a broken state).
2021-09-15 13:32:09 -04:00
Andrew Clark 33226fadaa
Check for store mutations before commit (#22290)
* [useSyncExternalStore] Remove extra hook object

Because we already track `getSnapshot` and `value` on the store
instance, we don't need to also track them as effect dependencies. And
because the effect doesn't require any clean-up, we don't need to track
a `destroy` function.

So, we don't need to store any additional state for this effect. We can
call `pushEffect` directly, and only during renders where something
has changed.

This saves some memory, but my main motivation is because I plan to use
this same logic to schedule a pre-commit consistency check. (See the
inline comments for more details.)

* Split shouldTimeSlice into two separate functions

Lanes that are blocking (SyncLane, and DefaultLane inside a blocking-
by-default root) are always blocking for a given root. Whereas expired
lanes can expire while the render phase is already in progress.

I want to check if a lane is blocking without checking whether it
expired, so I split `shouldTimeSlice` into two separate functions.

I'll use this in the next step.

* Check for store mutations before commit

When a store is read for the first time, or when `subscribe` or
`getSnapshot` changes, during a concurrent render, we have to check
at the end of the render phase whether the store was mutated by
an concurrent event.

In the userspace shim, we perform this check in a layout effect, and
patch up any inconsistencies by scheduling another render + commit.
However, even though we patch them up in the next render, the parent
layout effects that fire in the original render will still observe an
inconsistent tree.

In the native implementation, we can instead check for inconsistencies
right after the root is completed, before entering the commit phase. If
we do detect a mutaiton, we can discard the tree and re-render before
firing any effects. The re-render is synchronous to block further
concurrent mutations (which is also what we do to recover from tearing
bugs that result in an error). After the synchronous re-render, we can
assume the tree the tree is consistent and continue with the normal
algorithm for finishing a completed root (i.e. either suspend
or commit).

The result is that layout effects will always observe a consistent tree.
2021-09-13 08:07:46 -07:00
Ricky e73911e715
Clean up my "hard to read" code (#22295) 2021-09-11 15:05:54 -04:00
Andrew Clark 77912d9a05
Wire up the native API for useSyncExternalStore (#22237)
Adds useSyncExternalStore to the internal dispatcher, and exports
the native API from the React package without yet implementing it.
2021-09-07 10:20:24 -07:00
Brian Vaughn e07039bb61
Moved named hooks code (and tests) from react-devtools-extensions to react-devtools-shared (#22260) 2021-09-07 11:44:49 -04:00
Michaël De Boey b394c38e88
feat(eslint-plugin-react-internal): support ESLint 8.x (#22249)
Co-authored-by: Dan Abramov <dan.abramov@gmail.com>
2021-09-06 20:42:40 +01:00
Andrew Clark 1314299c7f
Initial shim of useSyncExternalStore (#22211)
This sets up an initial shim implementation of useSyncExternalStore,
via the use-sync-external-store package. It's designed to mimic the
behavior of the built-in API, but is backwards compatible to any version
of React that supports hooks.

I have not yet implemented the built-in API, but once it exists, the
use-sync-external-store package will always prefer that one. Library
authors can depend on the shim and trust that their users get the
correct implementation.

See https://github.com/reactwg/react-18/discussions/86 for background
on the API.

The tests I've added here are designed to run against both the shim and
built-in implementation, using our variant test flag feature. Tests that
only apply to concurrent roots will live in a separate suite.
2021-09-01 17:52:38 -07:00
Luna Ruan 2b7214033e
[DevTools] Fix Issue in release script where commits for the last DevTools release are undefined #22233 2021-09-01 12:56:39 -07:00
Luna Ruan ac8fc34e61
remove dist folder in release script for standalone and inline before building (#22232) 2021-09-01 12:16:00 -07:00
Andrew Clark 46a0f050aa
Set up use-sync-external-store package (#22202)
This package will be a shim for the built-in useSyncExternalStore API
(not yet implemented).
2021-08-28 13:57:47 -07:00
Luna Ruan 60a30cf32e
Console Logging for StrictMode Double Rendering (#22030)
React currently suppress console logs in StrictMode during double rendering. However, this causes a lot of confusion. This PR moves the console suppression logic from React into React Devtools. Now by default, we no longer suppress console logs. Instead, we gray out the logs in console during double render. We also add a setting in React Devtools to allow developers to hide console logs during double render if they choose.
2021-08-25 15:35:38 -07:00
Brian Vaughn b9964684bd
DevTools release script updates: (#22170) 2021-08-24 18:59:34 -04:00
Brian Vaughn b5fbf5464b
Automated DevTools release process (#22161) 2021-08-24 14:05:50 -04:00
Brian Vaughn 4df10c5871
Yarn replace-fork should not silently error (#22156) 2021-08-22 16:53:07 -04:00
Andrew Clark d54be90be6
Set up test infra for dynamic Scheduler flags (#22139)
I copied the set up we use for React.

In the www-variant test job, the Scheduler `__VARIANT__` flags will be
`true`. When writing a test, we can read the value of the flag with the
`gate` pragma and method.

Note: Since these packages are currently released in lockstep, maybe we
should remove SchedulerFeatureFlags and use ReactFeatureFlags for both.
2021-08-20 06:56:20 -07:00
Juan 88d121899a
[DevTools] Support extended source maps with named hooks information (#22010)
## Summary

Adds support for statically extracting names for hook calls from source code, and extending source maps with that information so that DevTools does not have to directly parse source code at runtime, which will speed up the Named Hooks feature and allow it to be enabled by default.

Specifically, this PR includes the following parts:

- [x] Adding logic to statically extract relevant hook names from the parsed source code (i.e. the babel ast). Note that this logic differs slightly from the existing logic in that the existing logic also uses runtime information from DevTools (such as whether given hooks are a custom hook) to extract names for hooks, whereas this code is meant to run entirely at build time, so it does not rely on that information.
- [x] Generating an encoded "hook map", which encodes the information about a hooks *original* source location, and it's corresponding name. This "hook map" will be used to generate extended source maps, included tentatively under an extra `x_react_hook_map` field. The map itself is formatted and encoded in a very similar way as how the `names` and `mappings` fields of a standard source map are encoded ( = Base64 VLQ delta coding representing offsets into a string array), and how the "function map" in Metro is encoded, as suggested in #21782. Note that this initial version uses a very basic format, and we are not implementing our own custom encoding, but reusing the `encode` function from `sourcemap-codec`.
- [x] Updating the logic in `parseHookNames` to check if the source maps have been extended with the hook map information, and if so use that information to extract the hook names without loading the original source code. In this PR we are manually generating extended source maps in our tests in order to test that this functionality works as expected, even though we are not actually generating the extended source maps in production.

The second stage of this work, which will likely need to occur outside this repo, is to update bundlers such as Metro to use these new primitives to actually generate source maps that DevTools can use.

### Follow-ups

- Enable named hooks by default when extended source maps are present
- Support looking up hook names when column numbers are not present in source map.
- Measure performance improvement of using extended source maps (manual testing suggests ~4 to 5x faster)
- Update relevant bundlers to generate extended source maps.

## Test Plan

- yarn flow
- Tests still pass
  - yarn test
  - yarn test-build-devtools
- Named hooks still work on manual test of browser extension on a few different apps (code sandbox, create-react-app, facebook).
- For new functionality:
  - New tests for statically extracting hook names.
  - New tests for using extended source maps to look up hook names at runtime.
2021-08-11 10:46:19 -04:00
Andrew Clark 19092ac8c3
Re-add old Fabric Offscreen impl behind flag (#22018)
* Re-add old Fabric Offscreen impl behind flag

There's a chance that #21960 will affect layout in a way that we don't
expect, so I'm adding back the old implementation so we can toggle the
feature with a flag.

The flag should read from the ReactNativeFeatureFlags shim so that we
can change it at runtime. I'll do that separately.

* Import dynamic RN flags from external module

Internal feature flags that we wish to control with a GK can now be
imported from an external module, which I've called
"ReactNativeInternalFeatureFlags".

We'll need to add this module to the downstream repo.

We can't yet use this in our tests, because we don't have a test
configuration that runs against the React Native feature flags fork. We
should set up that up the same way we did for www.
2021-08-03 19:30:20 -07:00
Shubham Pandey 6f3fcbd6fa
Some remaining instances of master to main (#21982)
Co-authored-by: Shubham Pandey <shubham.pandey@mfine.co>
2021-07-30 08:56:55 -04:00
Sebastian Markbåge 321087d134
[Fizz] Don't add aborted segments to the completedSegments list (#21976)
* Don't add aborted segments to the completedSegments list

* Update error message to include aborted status
2021-07-27 21:53:37 -04:00
Andrew Clark f0efb7b70f
Add comment support to `@gate` pragma (#21881)
So you can more easily comment on why a test is gated.
2021-07-14 10:36:24 -07:00
Andrew Clark 81346764bb
Run persistent tests in more configurations in CI (#21880)
I noticed that `enableSuspenseLayoutEffectSemantics` is not fully
implemented in persistent mode. I believe this was an oversight
because we don't have a CI job that runs tests in persistent mode and
with experimental flags enabled.

This adds additional test configurations to the CI job so we don't miss
stuff like this again. It doesn't fix the failing tests — I'll address
that separately.
2021-07-14 08:40:20 -07:00
Ehsan Hosseini b03293faaa
Fix link to fbjs (#21863)
`fbjs` doesn't have the `main` branch and it is `master`
2021-07-13 10:55:33 -04:00
Brian Vaughn f52b73f9d0
DevTools: Update named hooks match to use column number also (#21833)
This prevents edge cases where AST nodes are incorrectly matched.
2021-07-08 16:12:22 -04:00
Brian Vaughn c5cfa71948
DevTools: Show hook names based on variable usage (#21641)
Co-authored-by: Brian Vaughn <brian.david.vaughn@gmail.com>
Co-authored-by: Saphal Patro <saphal1998@gmail.com>
Co-authored-by: VibhorCodecianGupta <vibhordelgupta@gmail.com>
2021-07-01 14:39:18 -04:00
dependabot[bot] 2442d988ef
Bump ws from 6.1.2 to 6.2.2 in /scripts/release (#21628)
Bumps [ws](https://github.com/websockets/ws) from 6.1.2 to 6.2.2.
- [Release notes](https://github.com/websockets/ws/releases)
- [Commits](https://github.com/websockets/ws/commits)

---
updated-dependencies:
- dependency-name: ws
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-06-29 16:53:39 -04:00
dependabot[bot] 83f38d0768
Bump ecstatic from 2.2.1 to 2.2.2 in /scripts/bench (#20468)
Bumps [ecstatic](https://github.com/jfhbrook/node-ecstatic) from 2.2.1 to 2.2.2.
- [Release notes](https://github.com/jfhbrook/node-ecstatic/releases)
- [Changelog](https://github.com/jfhbrook/node-ecstatic/blob/2.2.2/CHANGELOG.md)
- [Commits](https://github.com/jfhbrook/node-ecstatic/compare/2.2.1...2.2.2)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-06-29 16:53:31 -04:00
Brian Vaughn d483463bc8
Updated scripts and config to replace "master" with "main" branch (#21768) 2021-06-29 14:26:24 -04:00
Brian Vaughn 8426bb6956
Pass Jest useStderr flag when debugging (#21741)
This prevents it from buffering adn suppressing all console logs until a test has completed running (When debugging in Chrome).
2021-06-23 16:58:46 -04:00
Brian Vaughn 355591add4
Next/experimental release versions include commit date (#21700)
Change format of @next and @experimental release versions from <number>-<sha> to <number>-<sha>-<date> to make them more human readable. This format still preserves the ability for us to easily map a version number to the changes it contains, while also being able to more easily know at a glance how recent a release is.
2021-06-23 13:50:09 -04:00
Andrew Clark d7dce572c7
Remove internal `act` builds from public modules (#21721)
* Move internal version of act to shared module

No reason to have three different copies of this anymore.

I've left the the renderer-specific `act` entry points because legacy
mode tests need to also be wrapped in `batchedUpdates`. Next, I'll update
the tests to use `batchedUpdates` manually when needed.

* Migrates tests to use internal module directly

Instead of the `unstable_concurrentAct` exports. Now we can drop those
from the public builds.

I put it in the jest-react package since that's where we put our other
testing utilities (like `toFlushAndYield`). Not so much so it can be
consumed publicly (nobody uses that package except us), but so it works
with our build tests.

* Remove unused internal fields

These were used by the old act implementation. No longer needed.
2021-06-22 14:29:35 -07:00
Andrew Clark 06f7b4f43a
`act` should work without mock Scheduler (#21714)
Currently, in a React 18 root, `act` only works if you mock the
Scheduler package. This was because we didn't want to add additional
checks at runtime.

But now that the `act` testing API is dev-only, we can simplify its
implementation.

Now when an update is wrapped with `act`, React will bypass Scheduler
entirely and push its tasks onto a special internal queue. Then, when
the outermost `act` scope exists, we'll flush that queue.

I also removed the "wrong act" warning, because the plan is to move
`act` to an isomorphic entry point, simlar to `startTransition`. That's
not directly related to this PR, but I didn't want to bother
re-implementing that warning only to immediately remove it.

I'll add the isomorphic API in a follow up.

Note that the internal version of `act` that we use in our own tests
still depends on mocking the Scheduler package, because it needs to work
in production. I'm planning to move that implementation to a shared
(internal) module, too.
2021-06-22 14:25:07 -07:00
Andrew Clark bd0a963445
Throw when `act` is used in production (#21686)
Upgrades the deprecation warning to a runtime error.

I did it this way instead of removing the export so the type is the same
in both builds. It will get dead code eliminated regardless.
2021-06-16 16:29:51 -04:00
Sebastian Markbåge 7ec4c55971
createRoot(..., {hydrate:true}) -> hydrateRoot(...) (#21687)
This adds a new top level API for hydrating a root. It takes the initial
children as part of its constructor. These are unlike other render calls
in that they have to represent what the server sent and they can't be
batched with other updates.

I also changed the options to move the hydrationOptions to the top level
since now these options are all hydration options.

I kept the createRoot one just temporarily to make it easier to codemod
internally but I'm doing a follow up to delete.

As part of this I un-dried a couple of paths. ReactDOMLegacy was intended
to be built on top of the new API but it didn't actually use those root
APIs because there are special paths. It also doesn't actually use most of
the commmon paths since all the options are ignored. It also made it hard
to add only warnings for legacy only or new only code paths.

I also forked the create/hydrate paths because they're subtly different
since now the options are different. The containers are also different
because I now error for comment nodes during hydration which just doesn't
work at all but eventually we'll error for all createRoot calls.

After some iteration it might make sense to break out some common paths but
for now it's easier to iterate on the duplicates.
2021-06-15 13:37:53 -07:00
Sebastian Markbåge 9212d994ba
Merge /unstable-fizz entry point into /server (#21684) 2021-06-14 18:37:44 -07:00
Sebastian Markbåge 9343f87203
Use the server src files as entry points for the builds/tests (#21683)
* Use the server src files as entry points for the builds/tests

We need one top level entry point to target two builds so we can't have
the top level one be the entry point for the builds.

* Same thing but with the modern entry point
2021-06-14 16:23:19 -07:00