Commit Graph

402 Commits

Author SHA1 Message Date
Mengdi Chen
f7b44539ca [DevTools] enable "reload & profile" button for timeline view (#24702) 2022-06-10 10:38:33 -04:00
Mengdi Chen
3e92eb0fce [DevTools] find best renderer when inspecting (#24665)
* [DevTools] find best renderer when inspecting

* fix lint

* fix test

* fix lint

* move logic to agent

* fix lint

* style improvements per review comments

* fix lint & flow

* re-add try catch for safety
2022-06-08 16:01:06 -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
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
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
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
Mengdi "Monday" Chen
852f10b5cf fix a bug in console.log with non-string args (#24546) 2022-05-12 10:29:36 -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
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
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
d4acbe85d5 Fixed possible undefined error in TreeContext reducer (#24501) 2022-05-05 08:46:57 -07: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
Brian Vaughn
6c36aee944 Fixed wrong method call for LRU cache (#24477) 2022-05-02 21:17:01 -04:00
Billy Janitsch
726ba80298 Synchronize implementations of second render logging (#24381)
Minor followup to #24373. The fix for #24373 (comment) didn't get synchronized to the hook implementation.
2022-04-15 10:35:35 -05:00
Luna Ruan
d63cd97245 don't stringify objects for console log second render (#24373)
Fixes #24302 based on #24306.
---

The current implementation for strict mode double logging stringiness and dims the second log. However, because we stringify everything, including objects, this causes objects to be logged as `[object Object]` etc.

This PR creates a new function that formats console log arguments with a specified style. It does this by:
1. The first param is a string that contains %c: Bail out and return the args without modifying the styles. We don't want to affect styles that the developer deliberately set.
2. The first param is a string that doesn't contain %c but contains string formatting: `[`%c${args[0]}`, style, ...args.slice(1)]` Note: we assume that the string formatting that the developer uses is correct.
3. The first param is a string that doesn't contain string formatting OR is not a string: Create a formatting string where:
   -  boolean, string, symbol -> %s
   -  number -> %f OR %i depending on if it's an int or float
   -  default -> %o
---
Co-authored-by: Billy Janitsch <billy@kensho.com>
2022-04-14 11:30:04 -05:00
Andrew Clark
f993ffc514 Fix infinite update loop that happens when an unmemoized value is passed to useDeferredValue (#24247)
* Fix infinite loop if unmemoized val passed to uDV

The current implementation of useDeferredValue will spawn a new
render any time the input value is different from the previous one. So
if you pass an unmemoized value (like an inline object), it will never
stop spawning new renders.

The fix is to only defer during an urgent render. If we're already
inside a transition, retry, offscreen, or other non-urgen render, then
we can use the latest value.

* Temporarily disable "long nested update" warning

DevTools' timeline profiler warns if an update inside a layout effect
results in an expensive re-render. However, it misattributes renders
that are spawned from a sync render at lower priority. This affects the
new implementation of useDeferredValue but it would also apply to things
like Offscreen.

It's not obvious to me how to fix this given how DevTools models the
idea of a "nested update" so I'm disabling the warning for now to
unblock the bugfix for useDeferredValue.
2022-04-11 12:34:03 -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
Brian Vaughn
8b95ea2cba Inline DevTools test snapshots and cleaned up tests (#24199) 2022-03-30 11:02:51 -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
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
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
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
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
Brian Vaughn
8fce116998 Update DevTools READMEs (#24105) 2022-03-16 11:37:10 -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
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
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
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
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
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
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
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
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
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
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
d504824780 Enable scheduling profiler flag in react-dom/testing builds (#23142) 2022-01-19 11:20:42 -05:00
Brian Vaughn
51947a14bb Refactored how React/DevTools log Timeline performance data (#23102)
Until now, DEV and PROFILING builds of React recorded Timeline profiling data using the User Timing API. This commit changes things so that React records this data by calling methods on the DevTools hook. (For now, DevTools still records that data using the User Timing API, to match previous behavior.)

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

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

Relates to #22529.
2022-01-13 14:55:54 -05:00
Borja Paz Rodríguez
42c30e8b12 Correct typing errors detected in several files (#22965)
* Correct spelling errors in several files
* Correct typos in devtools-shared package files
2022-01-04 10:30:07 -05:00
BIKI DAS
a8e9bbe0fe Made the variable name more meaningful (#23017) 2021-12-22 15:58:06 -05:00