Skip to content

Commit

Permalink
fix[react-devtools]: restore original args when recording errors (#30091
Browse files Browse the repository at this point in the history
)

## Summary

When DevTools frontend and backend are connected, we patch console in 2
places:
- `patch()`, when renderer is attached to:
  - listen to any errors / warnings emitted
  - append component stack if requested by the user
- `patchForStrictMode()`, when React notifies about that the next
invocation is about to happed during StrictMode

`patchForStrictMode()` will always be at the top of the patch stack,
because it is called at runtime when React notifies React DevTools,
because of this, `patch()` may receive already modified arguments (with
stylings for dimming), we should attempt to restore the original
arguments

## How did you test this change?

Look at yellow warnings on the element view:
| Before | After |
| --- | --- |
| ![Screenshot 2024-06-25 at 14 38
26](https://github.com/facebook/react/assets/28902667/6b0ec512-f0c9-4557-a524-d7f31b03464d)
| ![Screenshot 2024-06-25 at 17 26
23](https://github.com/facebook/react/assets/28902667/60ff5d80-06ea-4447-bbe8-b57bc0c63f6d)
|
  • Loading branch information
hoxyq authored Jun 26, 2024
1 parent d878489 commit a8b465c
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions packages/react-devtools-shared/src/backend/console.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ const STYLE_DIRECTIVE_REGEX = /^%c/;
// method has been overridden by the patchForStrictMode function.
// If it has we'll need to do some special formatting of the arguments
// so the console color stays consistent
function isStrictModeOverride(args: Array<string>): boolean {
function isStrictModeOverride(args: Array<any>): boolean {
if (__IS_FIREFOX__) {
return (
args.length >= 2 &&
Expand All @@ -63,6 +63,21 @@ function isStrictModeOverride(args: Array<string>): boolean {
}
}

function restorePotentiallyModifiedArgs(args: Array<any>): Array<any> {
// If the arguments don't have any styles applied, then just copy
if (!isStrictModeOverride(args)) {
return args.slice();
}

if (__IS_FIREFOX__) {
// Filter out %c from the start of the first argument and color as a second argument
return [args[0].slice(2)].concat(args.slice(2));
} else {
// Filter out the `\x1b...%s\x1b` template
return args.slice(1);
}
}

type OnErrorOrWarning = (
fiber: Fiber,
type: 'error' | 'warn',
Expand Down Expand Up @@ -220,8 +235,8 @@ export function patch({
onErrorOrWarning(
current,
((method: any): 'error' | 'warn'),
// Copy args before we mutate them (e.g. adding the component stack)
args.slice(),
// Restore and copy args before we mutate them (e.g. adding the component stack)
restorePotentiallyModifiedArgs(args),
);
}
}
Expand Down

0 comments on commit a8b465c

Please sign in to comment.