Commit Graph

4073 Commits

Author SHA1 Message Date
Mengdi Chen d300cebde2
[DevTools] only polyfill requestAnimationFrame when necessary (#24651) 2022-06-01 13:04:09 -04:00
Luna Ruan b1858b110d
[DevTools] devtools-test-shell Regression App fixes (#24644)
Made a couple of fixes to the `devtools-test-shell`
* test selectors aren't available in > React v18.0 either, so we'll need to mock the test selector functions there as well
* `react-dom/client` should map to `react-dom/client` and not `react-dom`
2022-05-31 16:13:41 -07:00
Josh Story dd4950c90e
[Flight] Implement useId hook (#24172)
* Implements useId hook for Flight server.

The approach for ids for Flight is different from Fizz/Client where there is a need for determinancy. Flight rendered elements will not be rendered on the client and as such the ids generated in a request only need to be unique. However since FLight does support refetching subtrees it is possible a client will need to patch up a part of the tree rather than replacing the entire thing so it is not safe to use a simple incrementing counter. To solve for this we allow the caller to specify a prefix. On an initial fetch it is likely this will be empty but on refetches or subtrees we expect to have a client `useId` provide the prefix since it will guaranteed be unique for that subtree and thus for the entire tree. It is also possible that we will automatically provide prefixes based on a client/Fizz useId on refetches

in addition to the core change I also modified the structure of options for renderToReadableStream where `onError`, `context`, and the new `identifierPrefix` are properties of an Options object argument to avoid the clumsiness of a growing list of optional function arguments.

* defend against useId call outside of rendering

* switch to S from F for Server Component ids

* default to empty string identifier prefix

* Add a test demonstrating that there is no warning when double rendering on the client a server component that used useId

* lints and gates
2022-05-31 14:53:32 -07:00
Josh Larson 26a5b3c7f7
Explicitly set `highWaterMark` to 0 for `ReadableStream` (#24641)
* Explicitly set highWaterMark to 0 for ReadableStreams

This is because not all streaming implementations respect the
default behavior of settings highWaterMark to 0 for byte streams.
Being explicit guarantees the intended behavior across runtimes.

* Remove size methods and add FlowFixMe instead
2022-05-31 16:20:36 -04:00
Luna Ruan 25837acfee
React DevTools 4.24.6 -> 4.24.7 (#24646) 2022-05-31 16:16:07 -04:00
Mengdi Chen be1fd48e96
[DevTools] mock requestAnimationFrame with setTimeout as a temporary fix for #24626 (#24633)
* mock requestAnimationFrame as a temp workaround for #24626

* give name to constant variable
2022-05-31 15:32:21 -04:00
Josh Story aec575914a
[Fizz] Send errors down to client (#24551)
* use return from onError

* export getSuspenseInstanceFallbackError

* stringToChunk

* return string from onError in downstream type signatures

* 1 more type

* support encoding errors in html stream and escape user input

This commit adds another way to get errors to the suspense instance by encoding them as dataset properties of a template element at the head of the boundary. Previously if there was an error before the boundary flushed there was no way to stream the error to the client because there would never be a client render instruction.

Additionally the error is sent in 3 parts

1) error hash - this is always sent (dev or prod) if one is provided
2) error message - Dev only
3) error component stack - Dev only, this now captures the stack at the point of error

Another item addressed in this commit is the escaping of potentially unsafe data. all error components are escaped as test for browers when written into the html and as javascript strings when written into a client render instruction.

* nits

Co-authored-by: Marco Salazar <salazarm@fb.com>
2022-05-29 23:07:10 -07:00
Josh Story a2766387ef
[Fizz] Improve text separator byte efficiency (#24630)
* [Fizz] Improve text separator byte efficiency

Previously text separators were inserted following any Text node in Fizz. This increases bytes sent when streaming and in some cases such as title elements these separators are not interpreted as comment nodes and leak into the visual aspects of a page as escaped text.

The reason simple tracking on the last pushed type doesn't work is that Segments can be filled in asynchronously later and so you cannot know in a single pass whether the preceding content was a text node or not. This commit adds a concept of TextEmbedding which provides a best effort signal to Segments on whether they are embedded within text. This allows the later resolution of that Segment to add text separators when possibly necessary but avoid them when they are surely not.

The current implementation can only "peek" head if the segment is a the Root Segment or a Suspense Boundary Segment. In these cases we know there is no trailing text embedding and we can eliminate the separator at the end of the segment if the last emitted element was Text. In normal Segments we cannot peek and thus have to assume there might be a trailing text embedding and we issue a separator defensively. This should be rare in practice as it is assumed most components that will cause segment creation will also emit some markup at the edges.

* [Fizz] Improve separator efficiency when flushing delayed segments

The method by which we get segment markup into the DOM differs depending on when the Segment resolves.

If a Segment resolves before flushing begins for it's parent it will be emitted inline with the parent markup. In these cases separators may be necessary because they are how we clue the browser into breakup up text into distinct nodes that will later match up with what will be hydrated on the client.

If a Segment resolves after flushing has happened a script will be used to patch up the DOM in the client. when this happens if there are any text nodes on the boundary of the patch they won't be "merged" and thus will continue to have distinct representation as Nodes in the DOM. Thus we can avoid doing any separators at the boundaries in these cases.

After applying these changes the only time you will get text separators as follows

* in between serial text nodes that emit at the same time - these are necessary and cannot be eliminated unless we stop relying on the browser to automatically parse the correct text nodes when processing this HTML
* after a final text node in a non-boundary segment that resolves before it's parent has flushed - these are sometimes extraneous, like when the next emitted thing is a non-Text node.

In all other cases text separators should be omitted which means the general byte efficiency of this approach should be pretty good
2022-05-28 08:30:38 -07:00
François Chalifour f7860538a6
Fix typo in useSyncExternalStore main entry point error (#24631) 2022-05-27 22:16:51 +01:00
Sebastian Markbåge 1bed20731f
Add a module map option to the Webpack Flight Client (#24629)
On the server we have a similar translation map from the file path that the
loader uses to the refer to the original module and to the bundled module ID.

The Flight server is optimized to emit the smallest format for the client.
However during SSR, the same client component might go by a different
module ID since it's a different bundle than the client bundle.

This provides an option to add a translation map from client ID to SSR ID
when reading the Flight stream.

Ideally we should have a special SSR Flight Client that takes this option
but for now we only have one Client for both.
2022-05-27 16:16:24 -04:00
Luna Ruan 3133dfa6ee
DevTools] e2e Regression Testing App (#24619)
This PR adds an e2e regression app to the react-devtools-shell package. This app:

* Has an app.js and an appLegacy.js entrypoint because apps prior to React 18 need to use ReactDOM.render. These files will create and render multiple test apps (though they currently only render the List)
* Moved the ListApp out of the e2e folder and into an e2e-apps folder so that both e2e and e2e-regression can use the same test apps
* Creates a ListAppLegacy app because prior to React 16.8 hooks didn't exist.
* Added a devtools file for the e2e-regression
* Modifies the webpack config so that the e2e-regression React app can use different a different React version than DevTools
2022-05-26 11:36:00 -04:00
Luna Ruan 1328ff70cd
[DevTools] Regression-proof e2e Tests (#24620)
This PR:

* Increases test retry count to 2 so that flaky tests have more of a chance to pass
* Ideally most e2e tests will run for all React versions (and ensure DevTools elegantly fails if React doesn't support its features). However, some features aren't supported in older React versions at all (ex. Profiling) Add runOnlyForReactRange function in these cases to skip tests that don't satisfy the correct React semver range
* Fix should allow searching for component by name test, which was flaky because sometimes the Searchbox would be unfocused the second time we try to type in it
* Edited test Should allow elements to be inspected to check that element inspect gracefully fails in older React versions
* Updated config to add a config.use.url field and a config.use.react_version field, which change depending on the React Version (and whether it's specified)
2022-05-25 20:53:44 -04:00
Josh Story 05c34dea91
[Test] Outer boundary should not report errors from an inner boundary (#24618)
* Test to assert that hydration errors of an inner suspended boundary are not retained by an unsuspended outer boundary

* lints
2022-05-25 14:10:50 -07:00
Andrew Clark b2763d3eaa
Move hydration code out of normal Suspense path (#24532)
* Move hydration code out of normal Suspense path

Shuffling some code around to make it easier to follow. The logic for
updating a dehydrated Suspense boundary is significantly different
from the logic for a client-rendered Suspense boundary. Most of it was
already lifted out into a separate function; this moves the remaining
hydration-specific logic out of updateSuspenseComponent and into
updateDehydratedSuspenseComponent instead.

No expected changes to program behavior.

* Extract hydration logic in complete phase, too

Same as previous step but for the complete phase. This is a separate
commit to make bisecting easier in case something breaks. The logic
is very subtle but mostly all I've done is extract it to
another function.
2022-05-25 15:42:02 -04:00
Luna Ruan 1e98682dd3
[DevTools] Fix moduleNameMapper Order in DevTools Config #24602)
We need the regression config moduleNameMapper to come before the current moduleNameMapper so when it tries to map "/^react-dom\/([^/]+)$/ it doesn't get confused. The reason is because order in which the mappings are defined matters. Patterns are checked one by one until one fits, and the most specific rule should be listed first.
2022-05-23 14:18:17 -07:00
Sebastian Silbermann 82c64e1a49
Match Preact behavior for boolean props on custom elements (#24541)
* Log unexpected warnings when testing with ReactDOMServerIntegrationTestUtils

* Add test

Following https://github.com/facebook/react/issues/9230#issuecomment-322007671 except that `foo={true}` renders an empty string.
See https://github.com/facebook/react/issues/9230#issuecomment-1123464720 for rationale.

* Match Preact behavior for boolean props on custom elements

* Poke CircleCI
2022-05-20 18:10:43 +01:00
Luna Ruan d89657bc8f
[DevTools] Use Inline Snapshots for storeStressTestSync (#24583)
Change storeStressTestSync to use inline snapshots instead of a snapshot file. We want to do this because some tests are gated and not called in regression tests, and if snapshot tests are not called when there is a corresponding .snap file, that test will fail.

Arguably inline snapshots are a better pattern anyway, so enforcing this in DevTools tests IMO makes sense
2022-05-19 07:52:30 -07:00
Luna Ruan b77c12576d
[DevTools] Add React Version Pragma to Tests (#24576)
This PR adds the reactVersion pragma to tests.

Tests without the reactVersion pragma won't be run if the reactVersion pragma isn't specified.

Tested each React version manually with the pragma to make sure the tests pass
2022-05-18 12:37:17 -04:00
Luna Ruan 357a61324f
[DevTools][Transition Tracing] Added support for Suspense Boundaries (#23365)
This PR:

* During the passive effect complete phase for Offscreen, we add all the transitions that were added to the update queue in the render phase to the transitions set on the memoziedState. We also add the stateNode for the Offscreen component to the root pendingSuspenseBoundaries map if the suspense boundary has gone from shown to fallback. We remove the stateNode if the boundary goes from fallback to shown.
* During the passive effect complete phase for the HostRoot, for each transition that was initiated during this commit, we add a pending transitionStart callback. We also add them to the transition set on the memoizedState for the HostRoot. If the root pendingSuspenseBoundaries is empty, we add a pending transitionComplete callback.
2022-05-16 13:23:46 -04:00
Luna Ruan 4c03bb6ed0
[DevTools] ignore tests without reactVersion pragma if REACT_VERSION specified (#24555)
In DevTools tests, if the REACT_VERSION specified, we know this is a regression test (testing older React Versions). Because a lot of tests test the DevTools front end and we don't want to run them in the regression test scenario, we decided to only run tests that have the // @reactVersion pragma defined.

Because if there are no tests specified, jest will fail, we also opt to use jest.skip to skip all the tests that we don't want to run for a specific React version istead.

This PR makes this change.
2022-05-14 00:54:50 -04:00
Luna Ruan 0ecb77d4c5
[DevTools] Fix formatWithStyles not styling the results if the first argument is an object + Added unit tests (#24554)
formatWithStyles currently doesn't style the array argument if the first argument is an object. This PR fixes this and also adds unit tests.
2022-05-13 15:34:33 -07:00
dan 2c8a1452b8
Fix ignored setState in Safari when iframe is touched (#24459) 2022-05-12 17:58:18 +01:00
Ricky 62662633d1
Remove enableFlipOffscreenUnhideOrder (#24545) 2022-05-12 12:40:17 -04:00
Mengdi "Monday" Chen 52c434be1d
React DevTools 4.24.5 -> 4.24.6 (#24547) 2022-05-12 10:52:55 -04:00
Mengdi "Monday" Chen 852f10b5cf
fix a bug in console.log with non-string args (#24546) 2022-05-12 10:29:36 -04:00
Ricky 34da5aa69b
Only treat updates to lazy as a new mount in legacy mode (#24530)
* Only treat updates to lazy as a new mount in legacy mode

* Update name and swap current check

* Flip order back
2022-05-12 08:51:32 -04:00
Luna Ruan 7d9e17a982
[DevTools] Add Pragma to Only Run Tests if Version Requirement Satisfied (#24533)
This PR:

Adds a transform-react-version-pragma that transforms // @reactVersion SEMVER_VERSION into _test_react_version(...) and _test_react_version_focus(...) that lets us only run a test if it satisfies the right react version.
Adds _test_react_version and _test_react_version_focus to the devtools setupEnv file
Add a devtools preprocessor file for devtools specific plugins
2022-05-11 12:01:05 -04:00
Josh Story 8197c73ec3
Support document rendering (#24523)
* Support Document as a container for hydration and rendering

Previously Document was not handled effectively as a container. in particual when hydrating if there was a fallback to client rendering React would attempt to append a new <html> element into the document before clearing out the existing one which errored leaving the application in brokent state.

The initial approach I took was to recycle the documentElement and never remove or append it, always just moving it to the right fiber and appending the right children (heady/body) as needed. However in testing a simple approach in modern browsers it seems like treating the documentElement like any other element works fine. This change modifies the clearContainer method to remove the documentElement if the container is a DOCUMENT_NODE. Once the container is cleared React can append a new documentElement via normal means.

* Allow Document as container for createRoot

previously rendering into Document was broken and only hydration worked because React did not properly deal with the documentElement and would error in a broken state if used that way. With the previous commit addressing this limitation this change re-adds Document as a valid container for createRoot.

It should be noted that if you use document with createRoot it will drop anything a 3rd party scripts adds the page before rendering for the first time.
2022-05-10 10:17:36 -07:00
Luna Ruan d20c3af9d1
[DevTools][Bug] Fix Race Condition When Unmounting Fibers (#24510)
When we delete fibers, we will call onCommitFiberUnmount on every deleted fiber to also remove them from the element tree. However, there are some cases where fibers aren't deleted but we still want to remove them from the element tree (ex. offscreen). In the second case, we recursively remove these children during handleCommitFiberRoot.

When we remove an element, we will untrack its corresponding fiber ID. However, because of fast refresh, we don't do this immediately, opting to instead add the value to a set to process later. However, before the set has been processed, we unmount that fiber again, we will get duplicate unmounts.

To fix this, handleCommitFiberRoot explicitly flushes all the fibers in the set before starting the deletion process. We also need to do this in handleCommitFiberUnmount in case handleCommitFiberRoot gets called first.
2022-05-06 15:36:03 -04:00
Timothy Yung 46a6d77e32
Unify JSResourceReference Interfaces (#24507) 2022-05-06 11:24:04 -07:00
Mengdi "Monday" Chen e531a4a62d
[React DevTools] Improve DevTools UI when Inspecting a user Component that Throws an Error (#24248)
* [ReactDevTools] custom view for errors occur in user's code

* [ReactDevTools] show message for unsupported feature

* fix bad import

* fix typo

* fix issues from rebasing

* prettier

* sync error names

* sync error name with upstream

* fix lint & better comment

* fix error message for test

* better error message per review

* add missing file

* remove dead enum & provide component name in error message

* better error message

* better user facing error message
2022-05-05 20:17:23 -04:00
Brian Vaughn 547b707493
React DevTools 4.24.4 -> 4.24.5 (#24503) 2022-05-05 10:19:08 -07:00
Brian Vaughn d4acbe85d5
Fixed possible undefined error in TreeContext reducer (#24501) 2022-05-05 08:46:57 -07:00
Sebastian Markbåge 024a7274fb
Constrain the container type of createPortal (#24496)
We already constrained the type of createRoot (can't take document) and hydrateRoot (can't take fragments).
2022-05-04 23:05:37 -04:00
Luna Ruan 3dc9a8af05
fix forward ref (#24494)
Resolves #24428

---

For fiber types that render user code, we check the PerformedWork flag rather than the props, ref, and state to see if the fiber rendered (rather than bailing out/etc.) so we know whether we need to do things like record profile durations. ForwardRef wasn't added to this list, which caused #24428.
2022-05-04 13:25:27 -07:00
Luna Ruan c7e494b553
[React DevTools] Fix regex for formateWithStyles function (#24486)
The previous regex to detect string substitutions is not quite right, this PR fixes it by:

Check to make sure we are starting either at the beginning of the line or we match a character that's not % to make sure we capture all the % in a row.
Make sure there are an odd number of % (the first X pairs are escaped % characters. The odd % followed by a letter is the string substitution)
2022-05-03 15:52:56 -07:00
Ricky 6cbf0f7fac
Fork ReactSymbols (#24484)
* Fork ReactSymbols

* Fix tests

* Update jest config
2022-05-03 17:12:23 -04:00
Ricky a10a9a6b5b
Add test for hiding children after layout destroy (#24483) 2022-05-03 14:24:23 -04:00
Josh Story b4eb0ad71f
Do not replay erroring beginWork with invokeGuardedCallback when suspended or previously errored (#24480)
When hydrating a suspense boundary an error or a suspending fiber can often lead to a cascade of hydration errors. While in many cases these errors are simply discarded (e.g. when teh root does not commit and we fall back to client rendering) the use of invokeGuardedCallback can lead to many of these errors appearing as uncaught in the browser console. This change avoids error replaying using invokeGuardedCallback when we are hydrating a suspense boundary and have either already suspended or we have one previous error which was replayed.
2022-05-03 11:07:47 -07:00
Ricky 99eef9e2df
Hide children of Offscreen after destroy effects (#24446) 2022-05-03 10:16:53 -04:00
Brian Vaughn 6c36aee944
Fixed wrong method call for LRU cache (#24477) 2022-05-02 21:17:01 -04:00
Andrew Clark ce13860281
Remove enablePersistentOffscreenHostContainer flag (#24460)
This was a Fabric-related experiment that we ended up not shipping.
2022-04-28 15:05:41 -04:00
Andrew Clark 72b7462fe7
Bump local package.json versions for 18.1 release (#24447) 2022-04-26 16:58:44 -04:00
Andrew Clark 22edb9f777
React `version` field should match package.json (#24445)
The `version` field exported by the React package currently corresponds
to the `@next` release for that build. This updates the build script
to output the same version that is used in the package.json file.

It works by doing a find-and-replace of the React version after the
build has completed. This is a bit weird but it saves us from having
to build the `@next` and `@latest` releases separately; they are
identical except for the version numbers.
2022-04-26 16:28:48 -04:00
Michael サイトー 中村 Bashurov 6bf3deef59
Upgrade react-shallow-renderer to support react 18 (#24442)
To a minimum version that support react 18
2022-04-26 19:45:04 +01:00
dan bd4784c8f8
Revert #24236 (Don't recreate the same fallback on the client if hydrating suspends) (#24434)
* Revert #24236 (Don't recreate the same fallback on the client if hydrating suspends)

* Use @gate FIXME
2022-04-25 16:16:32 +01:00
Andrew Clark 6d3b6d0f40
forwardRef et al shouldn't affect if props reused (#24421)
We don't have strong guarantees that the props object is referentially
equal during updates where we can't bail out anyway — like if the props
are shallowly equal, but there's a local state or context update in the
same batch.

However, as a principle, we should aim to make the behavior consistent
across different ways of memoizing a component. For example, React.memo
has a different internal Fiber layout if you pass a normal function
component (SimpleMemoComponent) versus if you pass a different type like
forwardRef (MemoComponent). But this is an implementation detail.
Wrapping a component in forwardRef (or React.lazy, etc) shouldn't affect
whether the props object is reused during a bailout.

Co-authored-by: Mateusz Burzyński <mateuszburzynski@gmail.com>
2022-04-22 14:23:26 -04:00
Andrew Clark bd08137666
Fix: useDeferredValue should reuse previous value (#24413)
During an urgent update, useDeferredValue should reuse the previous
value. The regression test I added shows that it was reverting to
the initial value instead.

The cause of the bug was trivial: the update path doesn't update the
hook's `memoizedState` field. Only the mount path.

None of the existing tests happened to catch this because to trigger the
bug, you have to do an urgent update that isn't the first update after
initial render. In all of the existing tests that included an urgent
update, it was the first update, so the "previous" value and the initial
value happened to be the same thing.
2022-04-20 23:30:46 -04:00
Josh Story 9ae80d6a2b
Suppress hydration warnings when a preceding sibling suspends (#24404)
* Add failing test case for #24384

If a components suspends during hydration we expect there to be mismatches with server rendered HTML but we were not always supressing warning messages related to these expected mismatches

* Mark hydration as suspending on every thrownException

previously hydration would only be marked as supsending when a genuine error was thrown. This created an opportunity for a hydration mismatch that would warn after which later hydration mismatches would not lead to warnings. By moving the marker check earlier in the thrownException function we get the hydration context to enter the didSuspend state on both error and thrown promise cases which eliminates this gap.

* Fix failing test related to client render fallbacks

This test was actually subject to the project identified in the issue fixed in this branch. After fixing the underlying issue the assertion logic needed to change to pick the right warning which now emits after hydration successfully completes on promise resolution. I changed the container type to 'section' to make the error message slightly easier to read/understand (for me)

* Only mark didSuspend on suspense path

For unknown reasons the didSuspend was being set only on the error path and nto the suspense path. The original change hoisted this to happen on both paths. This change moves the didSuspend call to the suspense path only. This appears to be a noop because if the error path marked didSuspend it would suppress later warnings but if it does not the warning functions themsevles do that suppression (after the first one which necessarily already happened)

* gate test on hydration fallback flags

* refactor didSuspend to didSuspendOrError

the orignial behavior applied the hydration warning bailout to error paths only. originally I moved it to Suspense paths only but this commit restores it to both paths and renames the marker function as didThrow rather than didSuspend

The logic here is that for either case if we get a mismatch in hydration we want to warm up components but effectively consider the hydration for this boundary halted

* factor tests to assert different behavior between prod and dev

* add DEV suffix to didSuspendOrError to better indicate this feature should only affect dev behavior

* move tests back to ReactDOMFizzServer-test

* fix comment casing

* drop extra flag gates in tests

* add test for user error case

* remove unnecessary gate

* Make test better

it now has an intentional client mismatch that would error if there wasn't suppression brought about by the earlier error. when it client renders it has the updated value not found in the server response but we do not see a hydration warning because it was superseded by the thrown error in that render
2022-04-20 14:52:54 -07:00
Andrew Clark 0dc4e6663d
Land enableClientRenderFallbackOnHydrationMismatch (#24410)
This flag is already enabled on all relevant surfaces. We can remove it.
2022-04-20 14:09:11 -04:00