Commit Graph

4073 Commits

Author SHA1 Message Date
dan 3e8c91c5f8
Fix import in README 2022-04-07 13:46:36 +01:00
dan bb49abea23
Update some READMEs (#24290)
* Update some READMEs

* Update README.md
2022-04-07 02:35:01 +01:00
Sebastian Markbåge 4bc465a16f
Rename Controls to PipeableStream (#24286)
This type isn't exported so it's technically not public.

This object mimics a ReadableStream.

Currently this is safe to destructure and call separately but I'm not sure
that's even guaranteed. It should probably be treated as a class in docs.
2022-04-06 19:27:38 -04:00
zhoulixiang ece5295e5a
Remove unnecessary flag check (#24284) 2022-04-06 17:42:53 +01:00
alireza molaee 1d1fa94a66
Fix false positive warning about react-dom/client with UMD builds (#24274) 2022-04-05 02:56:18 +01:00
dan 9ededef945
Don't mute hydration errors forcing client render (#24276)
* Don't mute hydration errors forcing client render

* Nits
2022-04-05 02:11:22 +01:00
dan 5f7f528083
Add more tests for suppressHydrationWarning (#24275)
* More tests for suppressHydrationWarning

* Move suppressHydration tests to new file

* Extract more tests

* Test name

* Test legacy behavior too
2022-04-05 00:04:15 +01:00
dan fc47cb1b61
Fix suppressHydrationWarning not working in production (#24271) 2022-04-04 16:23:58 +01:00
Hikari Hayashi 985272e268
Fix name mismatch in react-reconciler custom build. (#24272) 2022-04-04 09:47:36 +01:00
Luna Ruan b8cfda15e1
changed Transitions type to Array<Transition> (#24249)
Changed the Transitions type to Array<Transition> because Transitions was confusing
2022-04-01 17:02:28 -04:00
Mengdi "Monday" Chen c89a15c716
[ReactDebugTools] wrap uncaught error from rendering user's component (#24216)
* [ReactDebugTools] wrap uncaught error from rendering user's component

* fix lint

* make error names more package specific

* update per review comments

* fix tests

* fix lint

* fix tests

* fix lint

* fix error name & nits

* try catch instead of mocking error

* fix test for older node.js version

* avoid false positive from try-catch in tests
2022-04-01 14:38:11 -04:00
dan ebd7ff65b6
Don't recreate the same fallback on the client if hydrating suspends (#24236)
* Delay showing fallback if hydrating suspends

* Fix up

* Include all non-urgent lanes

* Moar tests

* Add test for transitions
2022-04-01 02:49:54 +01:00
dan 4db3ff6c1a
Test suite for hydration diff warnings (#24229)
* Test suite for hydration diff warnings

* Test both variants

* Add more edge cases
2022-03-31 17:35:51 +01:00
Brian Vaughn aa05e73150
Add 4.4.0 release to eslint rules CHANGELOG (#24234) 2022-03-31 10:43:08 -04:00
Sebastian Silbermann 7e3121e1cf
Remove unstable_createMutableSource from experimental build (#24209) 2022-03-30 17:05:07 +01:00
Mengdi "Monday" Chen 0415b18a10
[ReactDebugTools] add custom error type for future new hooks (#24168)
* [ReactDebugTools] add custom error type for future new hooks

* update per review comments

* remove unused argument
2022-03-30 11:07:12 -04:00
Brian Vaughn 8b95ea2cba
Inline DevTools test snapshots and cleaned up tests (#24199) 2022-03-30 11:02:51 -04:00
Mengdi "Monday" Chen adb8ebc927
React DevTools 4.24.2 -> 4.24.3 (#24198) 2022-03-29 14:44:32 -04:00
Andrew Clark 34aa5cfe0d Update local package.jsons for 18 2022-03-29 12:07:33 -04:00
Brian Vaughn eaa493e532
Profiler should only report stateful hooks that change between renders (#24189)
The Profiler has an advanced feature that shows why a component re-rendered. In the case of props and (class) state, it shows the names of props/state values that changed between renders. For hooks, DevTools tries to detect which ones may been related to the update by comparing prev/next internal hook structures.

My initial implementation tried to detect all changed hooks. In hindsight this is confusing, because only stateful hooks (e.g. useState, useReducer, and useSyncExternalStore) can schedule an update. (Other types of hooks can change between renders, but in a reactive way.) This PR changes the behavior to only report hooks that scheduled the update.
2022-03-29 11:11:31 -04:00
Yash Srivastav fe6e074128
Fix usage of console.error to prevent transform (#24188)
We were suppressing the `react-internals/warning-args` lint rule
for the call to `console.error` in `defaultOnRecoverableError`.

As far as I could tell, the lint rule exists because on dev builds,
we replace all calls to `console.error` with [this error
function](https://github.com/facebook/react/blob/main/packages/shared/consoleWithStackDev.js#L31-L37)
which expects a format string + args and nothing else. We were trying
to pass in an `Error` object directly. After this commit's change,
we will still be passing an `Error` but the transform won't occur.
2022-03-29 10:45:14 +01:00
Brian Vaughn ba0aee5d71
DevTools bugfix: Ignore duplicate welcome "message" events (#24186) 2022-03-28 14:25:30 -04:00
salazarm e7d0053e65
[fizz] Fix validateIterable call (#24166)
* fix validate iterable call

* supports iterable

* gate test by experimental
2022-03-25 14:03:06 -04:00
Brian Vaughn a6bdb882b7
Attach DevTools Tree keyboard events to the Tree container (not the document) (#24164)
We used to listen to at the document level for this event. That allowed us to listen to up/down arrow key events while another section
of DevTools (like the search input) was focused. This was a minor UX positive.

(We had to use ownerDocument rather than document for this, because the DevTools extension renders the Components and Profiler tabs into portals.)

This approach caused a problem though: it meant that a react-devtools-inline instance could steal (and prevent/block) keyboard events from other JavaScript on the page– which could even include other react-devtools-inline instances. This is a potential major UX negative.

Given the above trade offs, we now listen on the root of the Tree itself.
2022-03-25 12:41:13 -04:00
Brian Vaughn 033fe52b48
DevTools imports (#24163)
* Update DevTools imports: react-dom -> react-dom/client
* Silence ReactDOM.render warning in DevTools test shell
2022-03-25 12:02:39 -04:00
salazarm 6b85823b35
Clean up Selective Hydration / Event Replay flag (#24156)
* clean up selective hydration / replay flag

* dont export return_targetInst
2022-03-24 14:12:43 -04:00
Mengdi "Monday" Chen 1159ff6193
Add details in READMEs for react-devtools local developement (#24148)
* Add details in READMEs for react-devtools local developement

* typo

* update yarn for release script
2022-03-24 10:04:12 -04:00
Brian Vaughn 8df8a57edd
React DevTools 4.24.1 -> 4.24.2 (#24150) 2022-03-24 09:06:10 -04:00
Brian Vaughn e62a8d7545
Store throws a specific Error type (UnsupportedBridgeOperationError) (#24147)
When this Error type is detected, DevTools shows a custom error overlay with upgrade/downgrade instructions.
2022-03-23 17:04:54 -04:00
Sebastian Silbermann 3f89908983
Fix test-build-devtools if build was generated by build-for-devtools (#24088)
Co-authored-by: Brian Vaughn <brian.david.vaughn@gmail.com>
2022-03-23 09:51:59 -04:00
David McCabe 577f2de46c
enableCacheElement flag (#24131)
* enableCacheElement flag

* Update packages/shared/forks/ReactFeatureFlags.testing.js

Co-authored-by: Ricky <rickhanlonii@gmail.com>

* Update packages/shared/forks/ReactFeatureFlags.test-renderer.js

Co-authored-by: Ricky <rickhanlonii@gmail.com>

* Update packages/shared/forks/ReactFeatureFlags.native-oss.js

Co-authored-by: Ricky <rickhanlonii@gmail.com>

* Update packages/shared/ReactFeatureFlags.js

Co-authored-by: Ricky <rickhanlonii@gmail.com>

Co-authored-by: Dave McCabe <davemccabe@fb.com>
Co-authored-by: Ricky <rickhanlonii@gmail.com>
2022-03-20 20:41:02 -07:00
Andrew Clark 2e0d86d221
Allow updating dehydrated root at lower priority without forcing client render (#24082)
* Pass children to hydration root constructor

I already made this change for the concurrent root API in #23309. This
does the same thing for the legacy API.

Doesn't change any behavior, but I will use this in the next steps.

* Add isRootDehydrated function

Currently this does nothing except read a boolean field, but I'm about
to change this logic.

Since this is accessed by React DOM, too, I put the function in a
separate module that can be deep imported. Previously, it was accessing
the FiberRoot directly. The reason it's a separate module is to break a
circular dependency between React DOM and the reconciler.

* Allow updates at lower pri without forcing client render

Currently, if a root is updated before the shell has finished hydrating
(for example, due to a top-level navigation), we immediately revert to
client rendering. This is rare because the root is expected is finish
quickly, but not exceedingly rare because the root may be suspended.

This adds support for updating the root without forcing a client render
as long as the update has lower priority than the initial hydration,
i.e. if the update is wrapped in startTransition.

To implement this, I had to do some refactoring. The main idea here is
to make it closer to how we implement hydration in Suspense boundaries:

- I moved isDehydrated from the shared FiberRoot object to the
HostRoot's state object.
- In the begin phase, I check if the root has received an by comparing
the new children to the initial children. If they are different, we
revert to client rendering, and set isDehydrated to false using a
derived state update (a la getDerivedStateFromProps).
- There are a few places where we used to set root.isDehydrated to false
as a way to force a client render. Instead, I set the ForceClientRender
flag on the root work-in-progress fiber.
- Whenever we fall back to client rendering, I log a recoverable error.

The overall code structure is almost identical to the corresponding
logic for Suspense components.

The reason this works is because if the update has lower priority than
the initial hydration, it won't be processed during the hydration
render, so the children will be the same.

We can go even further and allow updates at _higher_ priority (though
not sync) by implementing selective hydration at the root, like we do
for Suspense boundaries: interrupt the current render, attempt hydration
at slightly higher priority than the update, then continue rendering the
update. I haven't implemented this yet, but I've structured the code in
anticipation of adding this later.

* Wrap useMutableSource logic in feature flag
2022-03-20 16:18:51 -04:00
Sebastian Markbåge dbe9e732af
Avoid conditions where control flow is sufficient (#24126)
This also fixes a type error since resetTextContent can only be called
on Instances.
2022-03-18 16:51:40 -04:00
Luna Ruan 645ec5d6fc
fix inspecting an element in a nested renderer bug (#24116)
Fixes this issue, where inspecting components in nested renderers results in an error. The reason for this is because we have different fiberToIDMap instances for each renderer, and owners of a component could be in different renderers.

This fix moves the fiberToIDMap and idToArbitraryFiberMap out of the attach method so there's only one instance of each for all renderers.
2022-03-17 15:40:03 -04:00
Sebastian Markbåge 1c44437355
Fix createRoot container signature (#24110)
The internal Container type represents the types of containers that React
can support in its internals that deal with containers.

This didn't include DocumentFragment which we support specifically for
rendering into shadow roots.

However, not all types makes sense to pass into the createRoot API.

One of those is comment nodes that is deprecated and we don't really fully
support. It really only exists for FB legacy.

For createRoot it doesn't make sense to pass a Document since that will try
to empty the document which removes the HTML tag which doesn't work.
Documents can only be passed to hydrateRoot.

Conversely I'm not sure we actually support hydrating a shadow root properly
so I excluded DocumentFragment from hydrateRoot.
2022-03-16 20:06:00 -04:00
Luna b075f97422
Fix dispatch config type for skipBubbling (#24109) 2022-03-16 12:05:57 -07:00
Brian Vaughn 8fce116998
Update DevTools READMEs (#24105) 2022-03-16 11:37:10 -04:00
salazarm ef23a9ee81
Flag for text hydration mismatch (#24107)
* flag for text hydration mismatch

* rm unused import
2022-03-16 10:12:59 -04:00
Luna Ruan 0412f0c1a4
add offscreen state node (#24026)
Add state node on Offscreen fibers with id (in preparation for transition tracing)
2022-03-15 13:28:50 -07:00
Brian Vaughn d9677e3492
Update CHANGELOG.md 2022-03-15 14:21:21 -04:00
Luna Ruan ac574d6883
React DevTools 4.24.0 -> 4.24.1 (#24100) 2022-03-15 14:13:00 -04:00
Brian Vaughn 63b86e1995
Disable unsupported Bridge protocol version dialog and add workaround for old protocol operations format (#24093)
Rationale: The only case where the unsupported dialog really matters is React Naive. That's the case where the frontend and backend versions are most likely to mismatch. In React Native, the backend is likely to send the bridge protocol version before sending operations– since the agent does this proactively during initialization.

I've tested the React Native starter app– after forcefully downgrading the backend version to 4.19.1 (see #23307 (comment)) and verified that this change "fixes" things. Not only does DevTools no longer throw an error that causes the UI to be hidden– it works (meaning that the Components tree can be inspected and interacted with).
2022-03-15 13:48:26 -04:00
Luna 43eb28339a
Add skipBubbling property to dispatch config (#23366) 2022-03-14 10:59:21 -07:00
Sebastian Silbermann 2bf7c02f0e
Don't hide console error|warn in inspectedElement-test (#24086) 2022-03-14 09:17:37 -04:00
Andrew Clark 061ac27bc9
Fix use of hydrateRoot in DevTools test (#24084)
I noticed while working on a different PR that this test was not
using hydrateRoot correctly. You're meant to pass the initial children
as the second argument.
2022-03-12 19:21:58 -05:00
Sebastian Markbåge 796724086a
Match select value against primitives to string but not undefined (#24077) 2022-03-12 13:34:55 -05:00
Andrew Clark 832e2987e0
Revert accdientally merged PR (#24081) 2022-03-11 21:31:23 -05:00
Andrew Clark 02b65fd8c5 Allow updates at lower pri without forcing client render
Currently, if a root is updated before the shell has finished hydrating
(for example, due to a top-level navigation), we immediately revert to
client rendering. This is rare because the root is expected is finish
quickly, but not exceedingly rare because the root may be suspended.

This adds support for updating the root without forcing a client render
as long as the update has lower priority than the initial hydration,
i.e. if the update is wrapped in startTransition.

To implement this, I had to do some refactoring. The main idea here is
to make it closer to how we implement hydration in Suspense boundaries:

- I moved isDehydrated from the shared FiberRoot object to the
HostRoot's state object.
- In the begin phase, I check if the root has received an by comparing
the new children to the initial children. If they are different, we
revert to client rendering, and set isDehydrated to false using a
derived state update (a la getDerivedStateFromProps).
- There are a few places where we used to set root.isDehydrated to false
as a way to force a client render. Instead, I set the ForceClientRender
flag on the root work-in-progress fiber.
- Whenever we fall back to client rendering, I log a recoverable error.

The overall code structure is almost identical to the corresponding
logic for Suspense components.

The reason this works is because if the update has lower priority than
the initial hydration, it won't be processed during the hydration
render, so the children will be the same.

We can go even further and allow updates at _higher_ priority (though
not sync) by implementing selective hydration at the root, like we do
for Suspense boundaries: interrupt the current render, attempt hydration
at slightly higher priority than the update, then continue rendering the
update. I haven't implemented this yet, but I've structured the code in
anticipation of adding this later.
2022-03-11 20:44:32 -05:00
Andrew Clark 83b941a519 Add isRootDehydrated function
Currently this does nothing except read a boolean field, but I'm about
to change this logic.

Since this is accessed by React DOM, too, I put the function in a
separate module that can be deep imported. Previously, it was accessing
the FiberRoot directly. The reason it's a separate module is to break a
circular dependency between React DOM and the reconciler.
2022-03-11 20:44:28 -05:00
Andrew Clark c8e4789e21 Pass children to hydration root constructor
I already made this change for the concurrent root API in #23309. This
does the same thing for the legacy API.

Doesn't change any behavior, but I will use this in the next steps.
2022-03-11 20:44:25 -05:00
Josh Story 581f0c42ed
[Flight] add support for Lazy components in Flight server (#24068)
* [Flight] add support for Lazy components in Flight server

Lazy components suspend until resolved just like in Fizz. Add tests to confirm Lazy works with Shared Components and Client Component references.

* Support Lazy elements

React.Lazy can now return an element instead of a Component. This commit implements support for Lazy elements when server rendering.

* add lazy initialization to resolveModelToJson

adding lazying initialization toResolveModelToJson means we use attemptResolveElement's full logic on whatever the resolved type ends up being. This better aligns handling of misued Lazy types like a lazy element being used as a Component or a lazy Component being used as an element.
2022-03-10 11:18:54 -08:00
Brian Vaughn 82762bea55
React DevTools 4.23.0 -> 4.24.0 (#24066)
* Revert "React DevTools 4.23.0 -> 4.24.0 (#23400)"

This reverts commit f6c130f614.

* React DevTools 4.23.0 -> 4.24.0

* Added additional, pending bugfixes to CHANGELOG

* Updated DevTools build and release script to fix header format
2022-03-10 13:37:01 -05:00
Brian Vaughn 4a87fb5211
Better handle undefined Error stacks in DevTools error boundary (#24065) 2022-03-10 13:36:47 -05:00
Brian Vaughn 48a8574a68
Fixed edge case bug in Profiler (#24031) 2022-03-10 13:35:52 -05:00
Sebastian Markbåge 72a933d289
Gate legacy hidden (#24047)
* Gate legacy hidden

* Gate tests

* Remove export from experimental
2022-03-09 11:48:03 -05:00
Sebastian Markbåge b9de50d2f9
Update test to reset modules instead of using private state (#24055) 2022-03-08 23:13:32 -05:00
Sebastian Markbåge c91892ec3c
[Fizz] Don't flush empty segments (#24054)
Before this change, we would sometimes write segments without any content
in them. For example for a Suspense boundary that immediately suspends
we might emit something like:

<div hidden id="123">
  <template id="456"></template>
</div>

Where the outer div is just a temporary wrapper and the inner one is a
placeholder for something to be added later.

This serves no purpose.

We should ideally have a heuristic that holds back segments based on byte
size and time. However, this is a straight forward clear win for now.
2022-03-08 23:12:50 -05:00
Sebastian Silbermann a59f53a603
Fizz: Prevent UnhandledPromiseRejection if shell errors (#24043) 2022-03-08 09:13:47 -05:00
salazarm d5f1b067c8
[ServerContext] Flight support for ServerContext (#23244)
* Flight side of server context

* 1 more test

* rm unused function

* flow+prettier

* flow again =)

* duplicate ReactServerContext across packages

* store default value when lazily initializing server context

* .

* better comment

* derp... missing import

* rm optional chaining

* missed feature flag

* React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED ??

* add warning if non ServerContext passed into useServerContext

* pass context in as array of arrays

* make importServerContext nott pollute the global context state

* merge main

* remove useServerContext

* dont rely on object getters in ReactServerContext and disallow JSX

* add symbols to devtools + rename globalServerContextRegistry to just ContextRegistry

* gate test case as experimental

* feedback

* remove unions

* Lint

* fix oopsies (tests/lint/mismatching arguments/signatures

* lint again

* replace-fork

* remove extraneous change

* rebase

* 1 more test

* rm unused function

* flow+prettier

* flow again =)

* duplicate ReactServerContext across packages

* store default value when lazily initializing server context

* .

* better comment

* derp... missing import

* rm optional chaining

* missed feature flag

* React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED ??

* add warning if non ServerContext passed into useServerContext

* pass context in as array of arrays

* make importServerContext nott pollute the global context state

* merge main

* remove useServerContext

* dont rely on object getters in ReactServerContext and disallow JSX

* add symbols to devtools + rename globalServerContextRegistry to just ContextRegistry

* gate test case as experimental

* feedback

* remove unions

* Lint

* fix oopsies (tests/lint/mismatching arguments/signatures

* lint again

* replace-fork

* remove extraneous change

* rebase

* reinline

* rebase

* add back changes lost due to rebase being hard

* emit chunk for provider

* remove case for React provider type

* update type for SomeChunk

* enable flag with experimental

* add missing types

* fix flow type

* missing type

* t: any

* revert extraneous type change

* better type

* better type

* feedback

* change import to type import

* test?

* test?

* remove react-dom

* remove react-native-renderer from react-server-native-relay/package.json

* gate change in FiberNewContext, getComponentNameFromType, use switch statement in FlightServer

* getComponentNameFromTpe: server context type gated and use displayName if available

* fallthrough

* lint....

* POP

* lint
2022-03-08 07:55:32 -05:00
Sebastian Markbåge 6edd55a3ff
Gate unstable_expectedLoadTime on enableCPUSuspense (#24038) 2022-03-08 01:33:52 -05:00
Sebastian Markbåge 57799b912d
Add more feature flag checks (#24037) 2022-03-08 00:13:22 -05:00
Josh Story e09518e5bb
[Fizz] write chunks to a buffer with no re-use (#24034)
* write chunks to a buffer with no re-use

chunks were previously enqueued to a ReadableStream as they were written. We now write them to a view over an ArrayBuffer
and enqueue them only when writing has completed or the buffer's size is exceeded. In addition this copy now ensures
we don't attempt to re-send buffers that have already been transferred.

* refactor writeChunk to be more defensive and efficient

We now defend against overflows using the next views length instead of the current one. this protects us against a future where we use byobRequest and we get longer initial views than we might create after overflowing the first time. Additionally we add in an optimization when we have completely filled up the currentView where we avoid creating subarrays of the chunk to write since it lands exactly on a view boundary. Finally we move the view creation to beginWriting to avoid a runtime check on each write and because we want to reset the view on each beginWriting call in case a throw elsewhere in the program leaves the currentView in an unfinished state

* add tests to exercise codepaths dealing with buffer overlows
2022-03-07 10:34:11 -08:00
Sebastian Markbåge 14c2be8dac
Rename Node SSR Callbacks to onShellReady/onAllReady and Other Fixes (#24030)
* I forgot to call onFatalError

I can't figure out how to write a test for this because it only happens
when there is a bug in React itself which would then be fixed if we found
it.

We're also covered by the protection of ReadableStream which doesn't leak
other errors to us.

* Abort requests if the reader cancels

No need to continue computing at this point.

* Abort requests if node streams get destroyed

This is if the downstream cancels is for example.

* Rename Node APIs for Parity with allReady

The "Complete" terminology is a little misleading because not everything
has been written yet. It's just "Ready" to be written now.

onShellReady
onShellError
onAllReady

* 'close' should be enough
2022-03-04 14:38:46 -05:00
Sebastian Markbåge cb1e7b1c6c
Move onCompleteAll to .allReady Promise (#24025)
* Move onCompleteAll to .allReady Promise

The onCompleteAll callback can sometimes resolve before the promise that
returns the stream which is tough to coordinate. A more idiomatic API
for a one shot event is a Promise.

That way the way you render for SEO or SSG is:

const stream = await renderToReadableStream(...);
await stream.readyAll;
respondWith(stream);

Ideally this should be a sub-class of ReadableStream but we don't yet
compile these to ES6 and they'd had to be to native class to subclass
a native stream.

I have other ideas for overriding the .tee() method in a subclass anyway.
So this is inline with that strategy.

* Reject the Promise on fatal errors
2022-03-03 12:46:12 -05:00
salazarm 5662857616
[Fizz] Export debug function for FB (#24024)
* export debug function for FB

* silence flow
2022-03-03 12:02:37 -05:00
Joshua Gross 05c283c3c3
Fabric HostComponent as EventEmitter: support add/removeEventListener (unstable only) (#23386)
* Implement addEventListener and removeEventListener on Fabric HostComponent

* add files

* re-add CustomEvent

* fix flow

* Need to get CustomEvent from an import since it won't exist on the global scope by default

* yarn prettier-all

* use a mangled name consistently to refer to imperatively registered event handlers

* yarn prettier-all

* fuzzy null check

* fix capture phase event listener logic

* early exit from getEventListeners more often

* make some optimizations to getEventListeners and the bridge plugin

* fix accumulateInto logic

* fix accumulateInto

* Simplifying getListeners at the expense of perf for the non-hot path

* feedback

* fix impl of getListeners to correctly remove function

* pass all args in to event listeners
2022-03-02 12:00:08 -08:00
BIKI DAS 08644348b6
Added unit Tests in the ReactART, increasing the code coverage (#23195) 2022-03-02 14:10:06 -05:00
Brian Vaughn f6c130f614
React DevTools 4.23.0 -> 4.24.0 (#23400)
* React DevTools 4.23.0 -> 4.24.0

* Fixed CHANGELOG header format

* Add separator line beween header version numbers
2022-03-02 13:28:42 -05:00
Brian Vaughn 0e0b1a45fa
Show DevTools backend and frontend versions in UI (#23399)
This information can help with bug investigation for renderers (like React Native) that embed the DevTools backend into their source (separately from the DevTools frontend, which gets run by the user).

If the DevTools backend is too old to report a version, or if the version reported is the same as the frontend (as will be the case with the browser extension) then only a single version string will be shown, as before. If a different version is reported, then both will be shown separately.
2022-03-02 12:26:48 -05:00
Josh Story f0dd459e0d
reassign src from props not the dom element src property (#23395)
The src property on the dom element will return a fully qualified name and this does not match the dom
src attribute or the props provided to react. instead of reading from the element and re-assigning the property we
assign the property from props which is how it was initially assigned during the render

Co-authored-by: Josh Story <story@hey.com>
2022-03-01 18:23:16 -05:00
Luna Ruan feefe437fe
Refactor Cache Code (#23393)
This PR refactors the cache code by moving it out of ReactFiberCacheComponent to ReactFiberTransitionPool in anticipation of it being reused by multiple stacks (ie. transition tracing)
2022-03-01 12:39:51 -08:00
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
Sebastian Markbåge 75662d6a7d
Remove hacky stream.locked check, declare as byte stream instead (#23387)
We used to check for stream.locked in pull to see if we've been passed to
something that reads yet.

This was a bad hack because it won't actually call pull again if that changes.

The source of this is because the default for "highWaterMark" is 1 on some
streams. So it always wants to add one "chunk" (of size 1).

If we leave our high water mark as 0, we won't fill up any buffers unless we're
asked for more.

This web API is somewhat odd because it would be way more efficient if it
just told us how much the recipient wants instead of calling us once per
chunk.

Anyway, I turns out that if we define ourselves as a "bytes" type of
stream, the default also happens to be a high water mark of 0 so we can
just use that instead.
2022-02-28 21:35:00 -05:00
Josh Story 086fa8ee2f
re-trigger load events for img elements on commit (#23316)
early load events will be missed by onLoad handlers if they trigger before the tree is committed
to avoid this we reset the src property on the img element to cause the browser to re-load
the img.

Co-authored-by: Josh Story <story@hey.com>
2022-02-28 18:07:39 -05:00
Sebastian Markbåge a232744215
Remove flushControlled from experimental releases (#23384)
This brings the exports on npm to parity which simplifies things a bit.

We also don't plan to release this. It is used by Draft.js but that caller
will need to switch to flushSync.
2022-02-28 14:38:13 -05:00
Andrew Clark a82ef6d40b
Add back skipUnmountedBoundaries flag only for www (#23383)
There are a few internal tests that still need to be updated, so I'm
adding this flag back for www only.

The desired behavior rolled out to 10% public, so we're confident there
are no issues.

The open source behavior remains (skipUnmountedBoundaries = true).
2022-02-28 11:14:30 -05:00
Andrew Clark f468816ef1
Fix false positive hydration warnings (#23364)
* Failing test for react#23331

* Don't warn on hydration mismatch if suspended

When something suspends during hydration, we continue rendering the
siblings to warm up the cache and fire off any lazy network requests.
However, if there are any mismatches while rendering the siblings, it's
likely a false positive caused by the earlier suspended component. So
we should suppress any hydration warnings until the tree no
longer suspends.

Fixes #23332

Co-authored-by: Marcel Laverdet <marcel@laverdet.com>
2022-02-25 18:10:10 -05:00
Andrew Clark 5d08a24c21
useId: Use 'H' to separate main id from hook index (#23363)
No id should be a subset of any other id. Currently, this is not true
when there are multiple hooks in the same component. We append the
hook index to the end of the id, except for the first one. So you get
this pattern.

Before this change:

- 1st hook's id: :R0:
- 2nd hook's id: :R0:1:

The first hook's id is a subset of all the other ids in the
same component.

The fix for this is to use a different character to separate the main
id from the hook index. I've chosen a captial 'H' for this because
capital letters are not part of the base 32 character set when encoding
with `toString(32)`.

After this change:

- 1st hook's id: :R0:
- 2nd hook's id: :R0H1:
2022-02-25 15:46:59 -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
Sebastian Markbåge 8d0d0e9a8a
Deprecate renderToNodeStream (and fix textarea bug) (#23359)
* Deprecate renderToNodeStream

* Use renderToPipeableStream in tests instead of renderToNodeStream

This is the equivalent API. This means that we have way less test coverage
of this API but I feel like that's fine since it has a deprecation warning
in it and we have coverage on renderToString that is mostly the same.

* Fix textarea bug

The test changes revealed a bug with textarea. It happens because we
currently always insert trailing comment nodes. We should optimize that
away. However, we also don't really support complex children so we
should toString it anyway which is what partial renderer used to do.

* Update tests that assert number of nodes

These tests are unnecessarily specific about number of nodes.

I special case these, which these tests already do, because they're good
tests to test that the optimization actually works later when we do
fix it.
2022-02-24 20:09:03 -05:00
Andrew Clark efe4121ee2
Add : to beginning and end of every useId (#23360)
The ids generated by useId are unique per React root. You can create
additional ids by concatenating them with locally unique strings.

To support this pattern, no id will ever be a subset of another id. We
achieve this by adding a special character to the beginning and end.

We use a colon (":") because it's uncommon — even if you don't prefix
the ids using the `identifierPrefix` option, collisions are unlikely.

One downside of a colon is that it's not a valid character in DOM
selectors, like `querySelectorAll`. We think this is probably
fine because it's not a common use case in React, and there are
workarounds or alternative solutions. But we're open to reconsidering
this in the future if there's a compelling argument.
2022-02-24 20:07:41 -05:00
Luna Ruan 42f15b324f
[DevTools][Transition Tracing] onTransitionComplete and onTransitionStart implmentation (#23313)
* add transition name to startTransition

Add a transitionName to start transition, store the transition start time and name in the batch config, and pass it to the root on render

* Transition Tracing Types and Consts

* Root begin work

The root operates as a tracing marker that has all transitions on it. This PR only tested the root with one transition so far

- Store transitions in memoizedState. Do this in updateHostRoot AND attemptEarlyBailoutIfNoScheduledUpdate. We need to do this in the latter part because even if the root itself doesn't have an update, it could still have new transitions in its transitionLanes map that we need to process.

* Transition Tracing commit phase

- adds a module scoped pending transition callbacks object that contains all transition callbacks that have not yet been processed. This  contains all callbacks before the next paint occurs.
- Add code in the mutation phase to:
        * For the root, if there are transitions that were initialized during this commit in the root transition lanes map, add a transition start call to the pending transition callbacks object. Then, remove the transitions from the root transition lanes map.
        * For roots, in the commit phase, add a transition complete call

We add this code in the mutation phase because we can't add it to the passive phase because then the paint might have occurred before we even know which callbacks to call

* Process Callbacks after paint

At the end of the commit phase, call scheduleTransitionCallbacks to schedule all pending transition callbacks to be called after paint. Then clear the callbacks
2022-02-24 14:28:18 -08:00
Sebastian Markbåge 68cb55f262
Add more warnings for second argument to root.render. (#23358)
We already had one for callbacks but containers is also an easy mistake.
2022-02-24 16:31:48 -05:00
Andrew Clark 8c4cd65cfa
Add warnings for common root API mistakes (#23356)
For createRoot, a common mistake is to pass JSX as the second argument,
instead of calling root.render.

For hydrateRoot, a common mistake is to forget to pass children as
the second argument.

The type system will enforce correct usage, but since not everyone uses
types we'll log a helpful warning, too.
2022-02-24 10:57:37 -05:00
Andrew Clark a5b22155c8
Warn if renderSubtreeIntoContainer is called (#23355)
We already warn for all the other legacy APIs. Forgot to enable
this one.
2022-02-24 01:42:22 -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 b3f3da205b
Land warnOnSubscriptionInsideStartTransition flag (#23353)
We're including this in 18. The feature was already enabled — this just
removes the flag.
2022-02-23 18:52:08 -05:00
Andrew Clark 990098f88a
Re-arrange main ReactFeatureFlags module (#23350)
@sebmarkbage and I audited the feature flags file to review the status
of each feature or experiment. Based on that, I've added some more
comments to the main ReactFeatureFlags module and rearranged them
into groups.

I haven't changed the value of any flags, yet. There are a few we're
going to land but I'll do them as separate PRs.
2022-02-23 18:49:16 -05:00
Andrew Clark 1f3f6db73c
Remove createMutableSource from stable exports (#23352)
I removed useMutableSource in a previous PR but forgot this one.

We still export it in the FB builds until we can migrate the internal
callers (Recoil).
2022-02-23 18:11:22 -05:00
Sebastian Markbåge 587e759302
Remove Numeric Fallback of Symbols (#23348)
This was already defeating the XSS issue that Symbols was meant to protect
against. So you were already supposed to use a polyfill for security.

We rely on real Symbol.for in Flight for Server Components so those require
real symbols anyway.

We also don't really support IE without additional polyfills anyway.
2022-02-23 18:08:30 -05:00
Sebastian Markbåge 40351575d3
Split writeChunk into void and return value (#23343)
This function was modeled after Node streams where write returns a boolean
whether to keep writing or not. I think we should probably switch this
up and read desired size explicitly in appropriate places.

However, in the meantime, we don't have to return a value where we're
not going to use it. So I split this so that we call writeChunkAndReturn
if we're going to return the boolean.

This should help with the compilation so that they can be inlined.
2022-02-23 11:35:21 -05:00
Sebastian Markbåge 2c693b2dee
Re-add reentrancy avoidance (#23342)
* tests: add failing test to demonstrate bug in ReadableStream implementation

* Re-add reentrancy avoidance

I removed the equivalency of this in #22446. However, I didn't fully
understand the intended semantics of the spec but I understand this better
now.

The spec is not actually recursive. It won't call pull again inside of a
pull. It might not call it inside startWork neither which the original
issue avoided. However, it will call pull if you enqueue to the controller
without filling up the desired size outside any call.

We could avoid that by returning a Promise from pull that we wait to
resolve until we've performed all our pending tasks. That would be the
more idiomatic solution. That's a bit more involved but since we know
understand it, we can readd the reentrancy hack since we have an easy place
to detect it. If anything, it should probably throw or log here otherwise.

I believe this fixes #22772.

This includes the test from #22889 but should ideally have one for Fizz.

Co-authored-by: Josh Larson <josh.larson@shopify.com>
2022-02-23 00:33:41 -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
OGURA Daiki 4de99b3ca6
fix getSnapshot warning when a selector returns NaN (#23333)
* fix getSnapshot warning when a selector returns NaN

useSyncExternalStoreWithSelector delegate a selector as
getSnapshot of useSyncExternalStore.

* Fiber's use sync external store has a same issue

* Small nits

We use Object.is to check whether the snapshot value has been updated,
so we should also use it to check whether the value is cached.

Co-authored-by: Andrew Clark <git@andrewclark.io>
2022-02-21 01:07:41 -05:00
Luna Ruan 40eaa22d9a
Remove dependency on Offscreen Fiber updateQueue for React Cache (#23229)
We need to use the Offscreen Fiber's update queue for interaction tracing. This PR removes the optimization that React Cache uses to not need to push and pop the cache in special circumstances and defaults to always pushing and popping the cache as long as there was a previous cache.
2022-02-19 10:25:27 -05:00
David McCabe caf6d47077
Enable enableCache on Test Renderer native (#23314)
Co-authored-by: Dave McCabe <davemccabe@fb.com>
2022-02-18 10:44:10 -08:00
Andrew Clark 419ccc2b19
Land skipUnmountedBoundaries experiment (#23322)
This has been rolled out to 10% of Facebook users for months without
any issues.
2022-02-17 21:43:25 -05:00
Andrew Clark 54f785bc51
Disallow comments as DOM containers for createRoot (#23321)
This is an old feature that we no longer support. `hydrateRoot` already
throws if you pass a comment node; this change makes `createRoot`
throw, too.

Still enabled in the Facebook build until we migrate the callers.
2022-02-17 16:44:22 -05:00
Luna Ruan e9aa9592c1
change ReactBatchConfig.transition
Previously, ReactBatchConfig.transition was an number (1 = there is a transition, 0 = there isn't one). This PR changes this to a transition object (object = there is a transition, null = there isn't one) in preparation for transition tracing changes.
2022-02-17 13:13:27 -08: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 79ed5e18fd
Delete vestigial RetryAfterError logic (#23312)
This code was originally added to force a client render after receiving
an error during hydration. Later we added the ForceClientRender to
implement the same behavior, but scoped to an individual Suspense
boundary instead of all the boundaries in the entire root. So it's
now redudant.

We had some test coverage already but I added another test specifically
for the case of throwing a recoverable hydration error in the shell.
2022-02-17 10:24:03 -05:00
Andrew Clark 80059bb730
Switch to client rendering if root receives update (#23309)
If a hydration root receives an update before the outermost shell has
finished hydrating, we should give up hydrating and switch to
client rendering.

Since the shell is expected to commit quickly, this doesn't happen that
often. The most common sequence is something in the shell suspends, and
then the user quickly navigates to a different screen, triggering a
top-level update.

Instead of immediately switching to client rendering, we could first
attempt to hydration at higher priority, like we do for updates that
occur inside nested dehydrated trees.

But since this case is expected to be rare, and mainly only happens when
the shell is suspended, an attempt at higher priority would likely end
up suspending again anyway, so it would be wasted effort. Implementing
it this way would also require us to add a new lane especially for root
hydration. For simplicity's sake, we'll immediately switch to client
rendering. In the future, if we find another use case for a root
hydration lane, we'll reconsider.
2022-02-16 13:15:25 -05:00
Andrew Clark f7f7ed089e
Allow suspending in the shell during hydration (#23304)
* Allow suspending in the shell during hydration

Builds on behavior added in #23267.

Initial hydration should be allowed to suspend in the shell. In
practice, this happens because the code for the outer shell hasn't
loaded yet.

Currently if you try to do this, it errors because it expects there to
be a parent Suspense boundary, because without a fallback we can't
produce a consistent tree. However, for non-sync updates, we don't need
to produce a consistent tree immediately — we can delay the commit
until the data resolves.

In #23267, I added support for suspending without a parent boundary if
the update was wrapped with `startTransition`. Here, I've expanded this
to include hydration, too.

I wonder if we should expand this even further to include all non-sync/
discrete updates.

* Allow suspending in shell for all non-sync updates

Instead of erroring, we can delay the commit.

The only time we'll continue to error when there's no parent Suspense
boundary is during sync/discrete updates, because those are expected to
produce a complete tree synchronously to maintain consistency with
external state.
2022-02-16 12:47:50 -05:00
Andrew Clark 27b5699694
Simplify cache pool contexts (#23280)
The `pooledCache` variable always points to either `root.pooledCache`
or the stack cursor that is used to track caches that were resumed from
a previous render. We can get rid of it by reading from those instead.
This simplifies the code a lot and is harder to mess up, I think.
2022-02-11 17:51:57 -05:00
Luna Ruan 08fce6208e
Gracefully handle empty "xstyle" prop values (Part 2) (#23279)
#23190 misses if entry is undefined or null. This fixes this issue.
2022-02-11 14:36:36 -05:00
Luna Ruan 1fb0d06878
[Devtools][Transition Tracing] Add Transition callbacks to createRoot (#23276)
- Add the type of transition tracing callbacks
- Add transition tracing callbacks as an option to `createRoot`
- Add transition tracing callbacks on the root
- Add option to pass transition tracing callbacks to createReactNoop
2022-02-11 10:15:10 -08:00
Luna Ruan a6987bee73
add <TracingMarker> component boilerplate (#23275)
- Add Tracing Marker component type to React exports
- Add reconciler work tag
- Add devtools work tag
- Add boilerplate for the cache to render children

No functionality yet
2022-02-11 08:42:55 -08:00
Andrew Clark 796fff5483
Allow suspending outside a Suspense boundary (#23267)
(If the update is wrapped in startTransition)

Currently you're not allowed to suspend outside of a Suspense boundary.
We throw an error:

> A React component suspended while rendering, but no fallback UI
was specified

We treat this case like an error because discrete renders are expected
to finish synchronously to maintain consistency with external state.
However, during a concurrent transition (startTransition), what we can
do instead is treat this case like a refresh transition: suspend the
commit without showing a fallback.

The behavior is roughly as if there were a built-in Suspense boundary
at the root of the app with unstable_avoidThisFallback enabled.
Conceptually it's very similar because during hydration you're already
showing server-rendered UI; there's no need to replace that with
a fallback when something suspends.
2022-02-11 11:26:00 -05:00
Andrew Clark 64223fed82
Fix: Multiple hydration errors in same render (#23273)
I made a minor mistake in the original onRecoverableError PR that
only surfaces if there are hydration errors in two different Suspense
boundaries in the same render. This fixes it and adds a unit test.
2022-02-10 08:40:00 -08:00
Andrew Clark efd8f6442d
Resolve default onRecoverableError at root init (#23264)
Minor follow up to initial onRecoverableError PR.

When onRecoverableError is not provided to `createRoot`, the
renderer falls back to a default implementation. Originally I
implemented this with a host config method, but what we can do instead
is pass the default implementation the root constructor as if it were
a user provided one.
2022-02-10 07:59:10 -08:00
Andrew Clark e0af1aabec
Fix wrong context argument to `apply`
The context argument should be the array, not null.

I wrote a test that I'll include in the next PR.
2022-02-09 20:50:32 -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
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
Sebastian Markbåge 5690932765
Add onErrorShell Callback (#23247)
This indicates that an error has happened before the shell completed and
there's no point in emitting the result of this stream.

This is not quite the same as other fatal errors that can happen even
after streaming as started.

It's also not quite the same as onError before onCompleteShell because
onError can be called for an error inside a Suspense boundary before the
shell completes.

Implement shell error handling in Node SSR fixtures

Instead of hanging indefinitely.

Update Browser Fixture

Expose onErrorShell to the Node build

This API is not Promisified so it's just a separate callback instead.

Promisify the Browser Fizz API

It's now a Promise of a readable stream. The Promise resolves when the
shell completes. If the shell errors, the Promise is rejected.
2022-02-08 22:38:14 -05:00
Sebastian Markbåge 0dedfcc681
Update the exports field (#23257)
* Add .browser and .node explicit entry points

This can be useful when the automatic selection doesn't work properly.

* Remove react/index

I'm not sure why I added this in the first place. Perhaps due to how our
builds work somehow.

* Remove build-info.json from files field
2022-02-08 21:07:26 -05:00
Sebastian Markbåge 7b541a980d
Add exports field to react-dom (#23252)
This configures the exports field for react-dom.

Notably there are some conditions for the /server entry point where we pick
the export based on environments. Most environments now support Web Streams
which is preferred in those environments.

We already do this using the "browser" field so the "browser" condition
applies here too.

I don't think it's necessary, but I also specified "worker" explicitly
since this is for Service Workers and those are often targeted with
Web Pack's "webworker" target, which is also what Cloudflare currently
recommends.

I also added "deno" but deno is a bit special because this only works if
you run with the node compatibility since otherwise you have to specify
absolute URLs for the imports.
2022-02-08 17:19:52 -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
salazarm 1dece52350
Add back warning with component stack on Hydration mismatch (#23241)
* add back warning

* wrapper errorMock in __DEV__ flag

* lint
2022-02-07 17:25:33 -05:00
dan cd4eb116cf
Revert "update node.js version for CI (#23236)" (#23239)
This reverts commit 1d7728bf9d.
2022-02-07 03:55:57 +00:00
sunderls 1d7728bf9d
update node.js version for CI (#23236) 2022-02-07 01:10:37 +00: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
Andrew Clark 5318971f50
Remove logic for multiple error recovery attempts (#23227)
This deletes some internal behavior that was only used by
useOpaqueIdentifier, as an implementation detail: if an update is
scheduled during the render phase, and something threw an error, we
would try rendering again, either until there were no more errors or
until there were no more render phase updates. This was not a publicly
defined behavior — regular render phase updates are accompanied by
a warning.

Because useOpaqueIdentifier has been replaced by useId, and does not
rely on this implementation detail, we can delete this code.
2022-02-02 13:14:20 -08:00
salazarm 3a44621296
Disable avoidThisFallback support in Fizz (#23224)
* disable fizz avoidThisFallback support

* true
2022-02-01 18:22:04 -05:00
Ricky 0318ac2c41
Revert 4f5449 2022-02-01 15:36:49 -05:00
Ricky 4f5449eb4b
Remove main from scheduler `index.js` 2022-02-01 15:05:18 -05:00
salazarm 3f5ff16c1a
[Hydration] Fallback to client render if server rendered extra nodes (#23176)
* rename

* rename

* replace-fork

* rename

* warn in a loop
2022-02-01 14:52:01 -05: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 3d1e7e7278
Suppress act() warnings in DevTools tests (#23192)
These warnings are not useful for DevTools tests– and sometimes may mask other, important warnings. This commit disables them.
2022-01-26 15:18:21 -05:00
Brian Vaughn 934f72221d
Gracefully handle empty "xstyle" prop values (#23190) 2022-01-26 13:54:44 -05:00
Fran Dios 529dc3ce84
Fix context providers in SSR when handling multiple requests (#23171)
* add failing test for renderToPipeableStream

* Fix context providers in SSR when handling multiple requests. Closes #23089

* Add sibling regression test

Co-authored-by: zhuyi01 <zhuyi01@ke.com>
Co-authored-by: Dan Abramov <dan.abramov@me.com>
2022-01-24 17:52:51 +00:00
Brian Vaughn e28a0db224 React DevTools 4.22.1 -> 4.23.0 2022-01-24 09:29:18 -05:00
Brian Vaughn 13036bfbc8
DevTools should not crawl unmounted subtrees when profiling starts (#23162)
Previously we crawled all subtrees, even not-yet-mounted ones, to initialize context values. This was not only unecessary, but it also caused an error to be thrown. This commit adds a test and fixes that behavior.
2022-01-21 11:05:49 -05:00
Andrew Clark ca143e18d8
Prettier 2022-01-21 09:59:11 -05:00
Behnam Mohammadi 26baf6a174
styles: replace Array.isArray with module isArray (#23154) 2022-01-21 09:33:00 -05:00
Luna Ruan 7bee1379b7
Filter out deleted components that are added to the updaters list (#23156)
There was a bug that occurred when a destroy effect is called that causes an update. The update would be added to the updaters list even though the fiber that was calling the destroy effect was unmounted and no longer exists. This PR:

* Adds a patch to Devtools to filter out all in the update list that aren't in the fiberToIDMap (which contains all fibers currently on screen)
2022-01-20 13:29:43 -08: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 505c15c9ef
Don't inject timeline hooks unless React supports profiling (#23151)
This gives DevTools a way to detect whether the current React renderer supports Timeline profiling. (Version alone isn't enough to detect this, neither is general profiling support– since these two are controlled by different feature flags.)
2022-01-20 11:11:26 -05:00
Douglas Armstrong e12a9dfc96
Fix production-only updateSyncExternalStore() crash when doing setState in render (#23150)
* Update ReactFiberHooks.new.js

* Add regression test + replace-fork

* Prettier

Co-authored-by: Dan Abramov <dan.abramov@me.com>
2022-01-20 15:22:17 +00:00
Dan Abramov e489402557
Warn when a callback ref returns a function (#23145) 2022-01-20 15:18:38 +00:00
Joey Arhar 05a55a4b09
Fix change events for custom elements (#22938)
* Bypass react event system for custom elements

* Going to try fixing react event system instead

* finally got it to call onChange, but perhaps too many times

* update test

* Removed ReactDOMComponent changes, now works but still doubles for bubbles

* Maybe i should only support bubbling events

* removed some old stuff

* cleaned up changeeventplugin stuff

* prettier, lint

* removed changeeventplugin stuff

* remove unneeded gate for onInput test

* Go back to using ChangeEventPlugin

* Add input+change test

* lint

* Move logic to shouldUseChangeEvent

* use memoizedProps instead of pendingProps

* Run form control behavior before custom element behavior

* add bubbling test

* forgot to append container to body

* add child event target test

* expand <input is=...> test expectations

* Make tests more realistic

* Add extra test

* Add missing gating

* Actually fix gating

Co-authored-by: Dan Abramov <dan.abramov@me.com>
2022-01-19 19:34:07 +00:00
Dan Abramov d8cfeaf221
Fix context propagation for offscreen/fallback trees (#23095)
* Failing test for Context.Consumer in suspended Suspense

See issue #19701.

* Fix context propagation for offscreen trees

* Address nits

* Specify propagation root for Suspense too

* Pass correct propagation root

* Harden test coverage

This test will fail if we remove propagation, or if we propagate with a root node like fiber.return or fiber.return.return. The additional DEV-only error helps detect a different kind of mistake, like if the thing being passed hasn't actually been encountered on the way up. However, we still leave the actual production loop to check against null so that there is no way we loop forever if the propagation root is wrong.

* Remove superfluous warning

Co-authored-by: overlookmotel <theoverlookmotel@gmail.com>
2022-01-19 16:30:34 +00:00
Brian Vaughn d504824780
Enable scheduling profiler flag in react-dom/testing builds (#23142) 2022-01-19 11:20:42 -05:00
Dan Abramov 790b5246f6
Fix setState ignored in Safari when iframe is added to DOM in the same commit (#23111)
* Fix setState being ignored in Safari

* Add a regression test

* Add comment
2022-01-18 18:25:34 +00: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
Joey Arhar a87adefecd
Allow functions to be passed to custom element setters (#23042)
This is part of the new custom element features that were implemented
here:
24dd07bd26

When a custom element has a setter for a property and passes the `in`
heuristic, the value passed to the react property should be assigned
directly to the custom element's property, regardless of the type of the
value. However, it was discovered that this isn't working with
functions. This patch makes it work with functions.

Fixes https://github.com/facebook/react/issues/23041
2022-01-12 20:12:07 +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
Gray Zhang 2f26eb85d6
Add exports field to react-refresh's package.json (#23087)
* Add exports field to react-refresh's package.json

* Update package.json

* Add runtime to exports
2022-01-11 16:48:09 +00:00
Luna Ruan 811634762a
add enableTransitionTracing feature flag (#23079)
This PR adds the enableTransitionTracing feature flag
2022-01-10 12:32:40 -08:00
Jack Works fe905f152f
Update package.json (#22954) 2022-01-07 12:59:47 -08:00