rebase on "[compiler] Optimize emission in normal (non-value) blocks"

In #29863 I tried to find a clean way to share code for emitting instructions between value blocks and regular blocks. The catch is that value blocks have special meaning for their final instruction — that's the value of the block — so reordering can't change the last instruction. However, in finding a clean way to share code for these two categories of code, i also inadvertently reduced the effectiveness of the optimization.

This PR updates to use different strategies for these two kinds of blocks: value blocks use the code from #29863 where we first emit all non-reorderable instructions in their original order, _then_ try to emit reorderable values. The reason this is suboptimal, though, is that we want to move instructions closer to their dependencies so that they can invalidate (merge) together. Emitting the reorderable values last prevents this.

So for normal blocks, we now emit terminal operands first. This will invariably cause _some_ of the non-reorderable instructions to be emitted, but it will intersperse reoderable instructions in between, right after their dependencies. This maximizes our ability to merge scopes.

I think the complexity cost of two strategies is worth the benefit, though i still need to double-check all the output changes.

[ghstack-poisoned]
This commit is contained in:
Joe Savona committed 2024-06-20 19:03:10 -07:00
commit a9e95fa7fb
76 files changed
+1807 -591

No files matched your search

+5 -1
View File
@@ -484,7 +484,11 @@ module.exports = {
},
},
{
files: ['packages/react-devtools-extensions/**/*.js'],
files: [
'packages/react-devtools-extensions/**/*.js',
'packages/react-devtools-shared/src/hook.js',
'packages/react-devtools-shared/src/backend/console.js',
],
globals: {
__IS_CHROME__: 'readonly',
__IS_FIREFOX__: 'readonly',
-1
View File
@@ -1,6 +1,5 @@
build
compiler
packages/react-devtools-core/dist
packages/react-devtools-extensions/chrome/build
packages/react-devtools-extensions/firefox/build
@@ -104,7 +104,7 @@ async function tabify(source: string, compilerOutput: CompilerOutput) {
passName,
<TextTabContent
output={text}
diff={lastPassOutput ?? null}
diff={passName !== "HIR" ? lastPassOutput : null}
showInfoPanel={true}
></TextTabContent>
);
@@ -195,7 +195,7 @@ function Output({ store, compilerOutput }: Props) {
if (result.kind === "hir" || result.kind === "reactive") {
currResult += `function ${result.fnName}\n\n${result.value}`;
}
if (currResult !== lastResult) {
if (passName !== "HIR" && currResult !== lastResult) {
changedPasses.add(passName);
}
lastResult = currResult;
@@ -254,7 +254,7 @@ function* runWithEnvironment(
memoizeFbtOperandsInSameScope(hir);
yield log({
kind: "hir",
name: "MemoizeFbtOperandsInSameScope",
name: "MemoizeFbtAndMacroOperandsInSameScope",
value: hir,
});
@@ -407,6 +407,23 @@ const EnvironmentConfigSchema = z.object({
* and identifiers have been changed.
*/
hookPattern: z.string().nullable().default(null),
/**
* If enabled, this will treat objects named as `ref` or if their names end with the substring `Ref`,
* and contain a property named `current`, as React refs.
*
* ```
* const ref = useMyRef();
* const myRef = useMyRef2();
* useEffect(() => {
* ref.current = ...;
* myRef.current = ...;
* })
* ```
*
* Here the variables `ref` and `myRef` will be typed as Refs.
*/
enableTreatRefLikeIdentifiersAsRefs: z.boolean().nullable().default(false),
});
export type EnvironmentConfig = z.infer<typeof EnvironmentConfigSchema>;
@@ -9,6 +9,7 @@ import { Effect, ValueKind, ValueReason } from "./HIR";
import {
BUILTIN_SHAPES,
BuiltInArrayId,
BuiltInUseActionStateId,
BuiltInUseEffectHookId,
BuiltInUseInsertionEffectHookId,
BuiltInUseLayoutEffectHookId,
@@ -266,6 +267,18 @@ const REACT_APIS: Array<[string, BuiltInType]> = [
returnValueReason: ValueReason.State,
}),
],
[
"useActionState",
addHook(DEFAULT_SHAPES, {
positionalParams: [],
restParam: Effect.Freeze,
returnType: { kind: "Object", shapeId: BuiltInUseActionStateId },
calleeEffect: Effect.Read,
hookKind: "useActionState",
returnValueKind: ValueKind.Frozen,
returnValueReason: ValueReason.State,
}),
],
[
"useReducer",
addHook(DEFAULT_SHAPES, {
@@ -1543,6 +1543,18 @@ export function isSetStateType(id: Identifier): boolean {
return id.type.kind === "Function" && id.type.shapeId === "BuiltInSetState";
}
export function isUseActionStateType(id: Identifier): boolean {
return (
id.type.kind === "Object" && id.type.shapeId === "BuiltInUseActionState"
);
}
export function isSetActionStateType(id: Identifier): boolean {
return (
id.type.kind === "Function" && id.type.shapeId === "BuiltInSetActionState"
);
}
export function isUseReducerType(id: Identifier): boolean {
return id.type.kind === "Function" && id.type.shapeId === "BuiltInUseReducer";
}
@@ -1551,6 +1563,10 @@ export function isDispatcherType(id: Identifier): boolean {
return id.type.kind === "Function" && id.type.shapeId === "BuiltInDispatch";
}
export function isStableType(id: Identifier): boolean {
return isSetStateType(id) || isSetActionStateType(id) || isDispatcherType(id);
}
export function isUseEffectHookType(id: Identifier): boolean {
return (
id.type.kind === "Function" && id.type.shapeId === "BuiltInUseEffectHook"
@@ -118,6 +118,7 @@ function addShape(
export type HookKind =
| "useContext"
| "useState"
| "useActionState"
| "useReducer"
| "useRef"
| "useEffect"
@@ -195,6 +196,8 @@ export const BuiltInJsxId = "BuiltInJsx";
export const BuiltInObjectId = "BuiltInObject";
export const BuiltInUseStateId = "BuiltInUseState";
export const BuiltInSetStateId = "BuiltInSetState";
export const BuiltInUseActionStateId = "BuiltInUseActionState";
export const BuiltInSetActionStateId = "BuiltInSetActionState";
export const BuiltInUseRefId = "BuiltInUseRefId";
export const BuiltInRefValueId = "BuiltInRefValue";
export const BuiltInMixedReadonlyId = "BuiltInMixedReadonly";
@@ -396,6 +399,25 @@ addObject(BUILTIN_SHAPES, BuiltInUseStateId, [
],
]);
addObject(BUILTIN_SHAPES, BuiltInUseActionStateId, [
["0", { kind: "Poly" }],
[
"1",
addFunction(
BUILTIN_SHAPES,
[],
{
positionalParams: [],
restParam: Effect.Freeze,
returnType: PRIMITIVE_TYPE,
calleeEffect: Effect.Read,
returnValueKind: ValueKind.Primitive,
},
BuiltInSetActionStateId
),
],
]);
addObject(BUILTIN_SHAPES, BuiltInUseReducerId, [
["0", { kind: "Poly" }],
[
@@ -57,7 +57,8 @@ export type PhiType = {
};
export type PropType = {
kind: "Property";
object: Type;
objectType: Type;
objectName: string;
propertyName: string;
};
@@ -124,7 +125,8 @@ export function duplicateType(type: Type): Type {
case "Property": {
return {
kind: "Property",
object: duplicateType(type.object),
objectType: duplicateType(type.objectType),
objectName: type.objectName,
propertyName: type.propertyName,
};
}
@@ -165,11 +167,13 @@ function objectMethodTypeEquals(tA: Type, tB: Type): boolean {
function propTypeEquals(tA: Type, tB: Type): boolean {
if (tA.kind === "Property" && tB.kind === "Property") {
if (!typeEquals(tA.object, tB.object)) {
if (!typeEquals(tA.objectType, tB.objectType)) {
return false;
}
return tA.propertyName === tB.propertyName;
return (
tA.propertyName === tB.propertyName && tA.objectName === tB.objectName
);
}
return false;
@@ -15,8 +15,7 @@ import {
Place,
computePostDominatorTree,
getHookKind,
isDispatcherType,
isSetStateType,
isStableType,
isUseOperator,
} from "../HIR";
import { PostDominator } from "../HIR/Dominator";
@@ -220,10 +219,7 @@ export function inferReactivePlaces(fn: HIRFunction): void {
if (hasReactiveInput) {
for (const lvalue of eachInstructionLValue(instruction)) {
if (
isSetStateType(lvalue.identifier) ||
isDispatcherType(lvalue.identifier)
) {
if (isStableType(lvalue.identifier)) {
continue;
}
reactiveIdentifiers.markReactive(lvalue);
@@ -15,7 +15,6 @@ import {
import { eachReactiveValueOperand } from "./visitors";
/**
* This pass supports the
* This pass supports the `fbt` translation system (https://facebook.github.io/fbt/)
* as well as similar user-configurable macro-like APIs where it's important that
* the name of the function not be changed, and it's literal arguments not be turned
@@ -75,7 +74,7 @@ function visit(
for (const instruction of block.instructions) {
const { lvalue, value } = instruction;
if (lvalue === null) {
return;
continue;
}
if (
value.kind === "Primitive" &&
@@ -96,7 +95,7 @@ function visit(
} else if (isFbtCallExpression(fbtValues, value)) {
const fbtScope = lvalue.identifier.scope;
if (fbtScope === null) {
return;
continue;
}
/*
@@ -122,7 +121,7 @@ function visit(
) {
const fbtScope = lvalue.identifier.scope;
if (fbtScope === null) {
return;
continue;
}
/*
@@ -10,8 +10,7 @@ import {
ReactiveFunction,
ReactiveInstruction,
ReactiveScopeBlock,
isDispatcherType,
isSetStateType,
isStableType,
} from "../HIR";
import { eachPatternOperand } from "../HIR/visitors";
import { collectReactiveIdentifiers } from "./CollectReactiveIdentifiers";
@@ -57,10 +56,7 @@ class Visitor extends ReactiveFunctionVisitor<ReactiveIdentifiers> {
case "Destructure": {
if (state.has(value.value.identifier.id)) {
for (const lvalue of eachPatternOperand(value.lvalue.pattern)) {
if (
isSetStateType(lvalue.identifier) ||
isDispatcherType(lvalue.identifier)
) {
if (isStableType(lvalue.identifier)) {
continue;
}
state.add(lvalue.identifier.id);
@@ -75,7 +71,7 @@ class Visitor extends ReactiveFunctionVisitor<ReactiveIdentifiers> {
if (
lvalue !== null &&
state.has(value.object.identifier.id) &&
!isSetStateType(lvalue.identifier)
!isStableType(lvalue.identifier)
) {
state.add(lvalue.identifier.id);
}
@@ -11,8 +11,11 @@ import { Environment } from "../HIR";
import { lowerType } from "../HIR/BuildHIR";
import {
HIRFunction,
Identifier,
IdentifierId,
Instruction,
makeType,
PropType,
Type,
typeEquals,
TypeId,
@@ -24,6 +27,7 @@ import {
BuiltInJsxId,
BuiltInObjectId,
BuiltInPropsId,
BuiltInRefValueId,
BuiltInUseRefId,
} from "../HIR/ObjectShape";
import { eachInstructionLValue, eachInstructionOperand } from "../HIR/visitors";
@@ -117,6 +121,7 @@ function* generate(
}
}
const names = new Map();
for (const [_, block] of func.body.blocks) {
for (const phi of block.phis) {
yield equation(phi.type, {
@@ -126,13 +131,28 @@ function* generate(
}
for (const instr of block.instructions) {
yield* generateInstructionTypes(func.env, instr);
yield* generateInstructionTypes(func.env, names, instr);
}
}
}
function setName(
names: Map<IdentifierId, string>,
id: IdentifierId,
name: Identifier
): void {
if (name.name?.kind === "named") {
names.set(id, name.name.value);
}
}
function getName(names: Map<IdentifierId, string>, id: IdentifierId): string {
return names.get(id) ?? "";
}
function* generateInstructionTypes(
env: Environment,
names: Map<IdentifierId, string>,
instr: Instruction
): Generator<TypeEquation, void, undefined> {
const { lvalue, value } = instr;
@@ -152,6 +172,7 @@ function* generateInstructionTypes(
}
case "LoadLocal": {
setName(names, lvalue.identifier.id, value.place.identifier);
yield equation(left, value.place.identifier.type);
break;
}
@@ -250,7 +271,8 @@ function* generateInstructionTypes(
case "PropertyLoad": {
yield equation(left, {
kind: "Property",
object: value.object.identifier.type,
objectType: value.object.identifier.type,
objectName: getName(names, value.object.identifier.id),
propertyName: value.property,
});
break;
@@ -278,7 +300,8 @@ function* generateInstructionTypes(
const propertyName = String(i);
yield equation(item.identifier.type, {
kind: "Property",
object: value.value.identifier.type,
objectType: value.value.identifier.type,
objectName: getName(names, value.value.identifier.id),
propertyName,
});
} else {
@@ -294,7 +317,8 @@ function* generateInstructionTypes(
) {
yield equation(property.place.identifier.type, {
kind: "Property",
object: value.value.identifier.type,
objectType: value.value.identifier.type,
objectName: getName(names, value.value.identifier.id),
propertyName: property.key.name,
});
}
@@ -342,11 +366,11 @@ function* generateInstructionTypes(
yield equation(left, { kind: "Object", shapeId: BuiltInJsxId });
break;
}
case "PropertyStore":
case "DeclareLocal":
case "NewExpression":
case "RegExpLiteral":
case "MetaProperty":
case "PropertyStore":
case "ComputedStore":
case "ComputedLoad":
case "TaggedTemplateExpression":
@@ -375,7 +399,21 @@ class Unifier {
unify(tA: Type, tB: Type): void {
if (tB.kind === "Property") {
const objectType = this.get(tB.object);
if (
this.env.config.enableTreatRefLikeIdentifiersAsRefs &&
isRefLikeName(tB)
) {
this.unify(tB.objectType, {
kind: "Object",
shapeId: BuiltInUseRefId,
});
this.unify(tA, {
kind: "Object",
shapeId: BuiltInRefValueId,
});
return;
}
const objectType = this.get(tB.objectType);
const propertyType = this.env.getPropertyType(
objectType,
tB.propertyName
@@ -483,3 +521,9 @@ class Unifier {
return type;
}
}
const RefLikeNameRE = /^(?:[a-zA-Z$_][a-zA-Z$_0-9]*)Ref$|^ref$/;
function isRefLikeName(t: PropType): boolean {
return RefLikeNameRE.test(t.objectName) && t.propertyName === "current";
}
@@ -0,0 +1,47 @@
## Input
```javascript
// @validatePreserveExistingMemoizationGuarantees
import { useCallback, useRef } from "react";
function useCustomRef() {
return useRef({ click: () => {} });
}
function Foo() {
const Ref = useCustomRef();
const onClick = useCallback(() => {
Ref.current?.click();
}, []);
return <button onClick={onClick} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Foo,
params: [],
isComponent: true,
};
```
## Error
```
9 | const Ref = useCustomRef();
10 |
> 11 | const onClick = useCallback(() => {
| ^^^^^^^
> 12 | Ref.current?.click();
| ^^^^^^^^^^^^^^^^^^^^^^^^^
> 13 | }, []);
| ^^^^ CannotPreserveMemoization: React Compiler has skipped optimizing this component because the existing manual memoization could not be preserved. The inferred dependencies did not match the manually specified dependencies, which could cause the value to change more or less frequently than expected (11:13)
14 |
15 | return <button onClick={onClick} />;
16 | }
```
@@ -0,0 +1,22 @@
// @validatePreserveExistingMemoizationGuarantees
import { useCallback, useRef } from "react";
function useCustomRef() {
return useRef({ click: () => {} });
}
function Foo() {
const Ref = useCustomRef();
const onClick = useCallback(() => {
Ref.current?.click();
}, []);
return <button onClick={onClick} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Foo,
params: [],
isComponent: true,
};
@@ -0,0 +1,47 @@
## Input
```javascript
// @validatePreserveExistingMemoizationGuarantees
import { useCallback, useRef } from "react";
function useCustomRef() {
return useRef({ click: () => {} });
}
function Foo() {
const notaref = useCustomRef();
const onClick = useCallback(() => {
notaref.current?.click();
}, []);
return <button onClick={onClick} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Foo,
params: [],
isComponent: true,
};
```
## Error
```
9 | const notaref = useCustomRef();
10 |
> 11 | const onClick = useCallback(() => {
| ^^^^^^^
> 12 | notaref.current?.click();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
> 13 | }, []);
| ^^^^ CannotPreserveMemoization: React Compiler has skipped optimizing this component because the existing manual memoization could not be preserved. The inferred dependencies did not match the manually specified dependencies, which could cause the value to change more or less frequently than expected (11:13)
14 |
15 | return <button onClick={onClick} />;
16 | }
```
@@ -0,0 +1,22 @@
// @validatePreserveExistingMemoizationGuarantees
import { useCallback, useRef } from "react";
function useCustomRef() {
return useRef({ click: () => {} });
}
function Foo() {
const notaref = useCustomRef();
const onClick = useCallback(() => {
notaref.current?.click();
}, []);
return <button onClick={onClick} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Foo,
params: [],
isComponent: true,
};
@@ -0,0 +1,100 @@
## Input
```javascript
// @compilationMode(infer) @enableAssumeHooksFollowRulesOfReact:false @customMacros(cx)
import { identity } from "shared-runtime";
const DARK = "dark";
function Component() {
const theme = useTheme();
return (
<div
className={cx.foo({
"styles/light": true,
"styles/dark": identity([theme.getTheme()]),
})}
/>
);
}
function cx(obj) {
const classes = [];
for (const [key, value] of Object.entries(obj)) {
if (value) {
classes.push(key);
}
}
return classes.join(" ");
}
function useTheme() {
return {
getTheme() {
return DARK;
},
};
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{}],
};
```
## Code
```javascript
import { c as _c } from "react/compiler-runtime"; // @compilationMode(infer) @enableAssumeHooksFollowRulesOfReact:false @customMacros(cx)
import { identity } from "shared-runtime";
const DARK = "dark";
function Component() {
const $ = _c(2);
const theme = useTheme();
const t0 = cx.foo({
"styles/light": true,
"styles/dark": identity([theme.getTheme()]),
});
let t1;
if ($[0] !== t0) {
t1 = <div className={t0} />;
$[0] = t0;
$[1] = t1;
} else {
t1 = $[1];
}
return t1;
}
function cx(obj) {
const classes = [];
for (const [key, value] of Object.entries(obj)) {
if (value) {
classes.push(key);
}
}
return classes.join(" ");
}
function useTheme() {
return {
getTheme() {
return DARK;
},
};
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{}],
};
```
### Eval output
(kind: exception) cx.foo is not a function
@@ -0,0 +1,39 @@
// @compilationMode(infer) @enableAssumeHooksFollowRulesOfReact:false @customMacros(cx)
import { identity } from "shared-runtime";
const DARK = "dark";
function Component() {
const theme = useTheme();
return (
<div
className={cx.foo({
"styles/light": true,
"styles/dark": identity([theme.getTheme()]),
})}
/>
);
}
function cx(obj) {
const classes = [];
for (const [key, value] of Object.entries(obj)) {
if (value) {
classes.push(key);
}
}
return classes.join(" ");
}
function useTheme() {
return {
getTheme() {
return DARK;
},
};
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{}],
};
@@ -0,0 +1,68 @@
## Input
```javascript
import { makeArray } from "shared-runtime";
function Component() {
const items = makeArray("foo", "bar", "", null, "baz", false, "merp");
const classname = cx.namespace(...items.filter(isNonEmptyString));
return <div className={classname}>Ok</div>;
}
function isNonEmptyString(s) {
return typeof s === "string" && s.trim().length !== 0;
}
const cx = {
namespace(...items) {
return items.join(" ");
},
};
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{}],
};
```
## Code
```javascript
import { c as _c } from "react/compiler-runtime";
import { makeArray } from "shared-runtime";
function Component() {
const $ = _c(1);
let t0;
if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
const items = makeArray("foo", "bar", "", null, "baz", false, "merp");
const classname = cx.namespace(...items.filter(isNonEmptyString));
t0 = <div className={classname}>Ok</div>;
$[0] = t0;
} else {
t0 = $[0];
}
return t0;
}
function isNonEmptyString(s) {
return typeof s === "string" && s.trim().length !== 0;
}
const cx = {
namespace(...items) {
return items.join(" ");
},
};
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{}],
};
```
### Eval output
(kind: ok) <div class="foo bar baz merp">Ok</div>
@@ -0,0 +1,22 @@
import { makeArray } from "shared-runtime";
function Component() {
const items = makeArray("foo", "bar", "", null, "baz", false, "merp");
const classname = cx.namespace(...items.filter(isNonEmptyString));
return <div className={classname}>Ok</div>;
}
function isNonEmptyString(s) {
return typeof s === "string" && s.trim().length !== 0;
}
const cx = {
namespace(...items) {
return items.join(" ");
},
};
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{}],
};
@@ -0,0 +1,84 @@
## Input
```javascript
// @enableTreatRefLikeIdentifiersAsRefs @validatePreserveExistingMemoizationGuarantees
import { useRef, useEffect } from "react";
function useCustomRef() {
return useRef({ click: () => {} });
}
function Foo() {
const ref = useCustomRef();
useEffect(() => {
ref.current?.click();
}, []);
return <div>foo</div>;
}
export const FIXTURE_ENTRYPOINT = {
fn: Foo,
params: [],
isComponent: true,
};
```
## Code
```javascript
import { c as _c } from "react/compiler-runtime"; // @enableTreatRefLikeIdentifiersAsRefs @validatePreserveExistingMemoizationGuarantees
import { useRef, useEffect } from "react";
function useCustomRef() {
const $ = _c(1);
let t0;
if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
t0 = { click: () => {} };
$[0] = t0;
} else {
t0 = $[0];
}
return useRef(t0);
}
function Foo() {
const $ = _c(3);
const ref = useCustomRef();
let t0;
let t1;
if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
t0 = () => {
ref.current?.click();
};
t1 = [];
$[0] = t0;
$[1] = t1;
} else {
t0 = $[0];
t1 = $[1];
}
useEffect(t0, t1);
let t2;
if ($[2] === Symbol.for("react.memo_cache_sentinel")) {
t2 = <div>foo</div>;
$[2] = t2;
} else {
t2 = $[2];
}
return t2;
}
export const FIXTURE_ENTRYPOINT = {
fn: Foo,
params: [],
isComponent: true,
};
```
### Eval output
(kind: ok) <div>foo</div>
@@ -0,0 +1,22 @@
// @enableTreatRefLikeIdentifiersAsRefs @validatePreserveExistingMemoizationGuarantees
import { useRef, useEffect } from "react";
function useCustomRef() {
return useRef({ click: () => {} });
}
function Foo() {
const ref = useCustomRef();
useEffect(() => {
ref.current?.click();
}, []);
return <div>foo</div>;
}
export const FIXTURE_ENTRYPOINT = {
fn: Foo,
params: [],
isComponent: true,
};
@@ -0,0 +1,81 @@
## Input
```javascript
// @enableTreatRefLikeIdentifiersAsRefs @validatePreserveExistingMemoizationGuarantees
import { useRef, useCallback } from "react";
function useCustomRef() {
return useRef({ click: () => {} });
}
function Foo() {
const ref = useCustomRef();
const onClick = useCallback(() => {
ref.current?.click();
}, []);
return <button onClick={onClick} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Foo,
params: [],
isComponent: true,
};
```
## Code
```javascript
import { c as _c } from "react/compiler-runtime"; // @enableTreatRefLikeIdentifiersAsRefs @validatePreserveExistingMemoizationGuarantees
import { useRef, useCallback } from "react";
function useCustomRef() {
const $ = _c(1);
let t0;
if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
t0 = { click: () => {} };
$[0] = t0;
} else {
t0 = $[0];
}
return useRef(t0);
}
function Foo() {
const $ = _c(3);
const ref = useCustomRef();
let t0;
if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
t0 = () => {
ref.current?.click();
};
$[0] = t0;
} else {
t0 = $[0];
}
const onClick = t0;
let t1;
if ($[1] !== onClick) {
t1 = <button onClick={onClick} />;
$[1] = onClick;
$[2] = t1;
} else {
t1 = $[2];
}
return t1;
}
export const FIXTURE_ENTRYPOINT = {
fn: Foo,
params: [],
isComponent: true,
};
```
### Eval output
(kind: ok) <button></button>
@@ -0,0 +1,22 @@
// @enableTreatRefLikeIdentifiersAsRefs @validatePreserveExistingMemoizationGuarantees
import { useRef, useCallback } from "react";
function useCustomRef() {
return useRef({ click: () => {} });
}
function Foo() {
const ref = useCustomRef();
const onClick = useCallback(() => {
ref.current?.click();
}, []);
return <button onClick={onClick} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Foo,
params: [],
isComponent: true,
};
@@ -0,0 +1,81 @@
## Input
```javascript
// @enableTreatRefLikeIdentifiersAsRefs @validatePreserveExistingMemoizationGuarantees
import { useRef, useCallback } from "react";
function useCustomRef() {
return useRef({ click: () => {} });
}
function Foo() {
const customRef = useCustomRef();
const onClick = useCallback(() => {
customRef.current?.click();
}, []);
return <button onClick={onClick} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Foo,
params: [],
isComponent: true,
};
```
## Code
```javascript
import { c as _c } from "react/compiler-runtime"; // @enableTreatRefLikeIdentifiersAsRefs @validatePreserveExistingMemoizationGuarantees
import { useRef, useCallback } from "react";
function useCustomRef() {
const $ = _c(1);
let t0;
if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
t0 = { click: () => {} };
$[0] = t0;
} else {
t0 = $[0];
}
return useRef(t0);
}
function Foo() {
const $ = _c(3);
const customRef = useCustomRef();
let t0;
if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
t0 = () => {
customRef.current?.click();
};
$[0] = t0;
} else {
t0 = $[0];
}
const onClick = t0;
let t1;
if ($[1] !== onClick) {
t1 = <button onClick={onClick} />;
$[1] = onClick;
$[2] = t1;
} else {
t1 = $[2];
}
return t1;
}
export const FIXTURE_ENTRYPOINT = {
fn: Foo,
params: [],
isComponent: true,
};
```
### Eval output
(kind: ok) <button></button>
@@ -0,0 +1,22 @@
// @enableTreatRefLikeIdentifiersAsRefs @validatePreserveExistingMemoizationGuarantees
import { useRef, useCallback } from "react";
function useCustomRef() {
return useRef({ click: () => {} });
}
function Foo() {
const customRef = useCustomRef();
const onClick = useCallback(() => {
customRef.current?.click();
}, []);
return <button onClick={onClick} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Foo,
params: [],
isComponent: true,
};
@@ -0,0 +1,57 @@
## Input
```javascript
import { useActionState } from "react";
function Component() {
const [actionState, dispatchAction] = useActionState();
const onSubmitAction = () => {
dispatchAction();
};
return <Foo onSubmitAction={onSubmitAction} />;
}
function Foo() {}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [],
};
```
## Code
```javascript
import { c as _c } from "react/compiler-runtime";
import { useActionState } from "react";
function Component() {
const $ = _c(1);
const [actionState, dispatchAction] = useActionState();
let t0;
if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
const onSubmitAction = () => {
dispatchAction();
};
t0 = <Foo onSubmitAction={onSubmitAction} />;
$[0] = t0;
} else {
t0 = $[0];
}
return t0;
}
function Foo() {}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [],
};
```
### Eval output
(kind: ok)
@@ -0,0 +1,16 @@
import { useActionState } from "react";
function Component() {
const [actionState, dispatchAction] = useActionState();
const onSubmitAction = () => {
dispatchAction();
};
return <Foo onSubmitAction={onSubmitAction} />;
}
function Foo() {}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [],
};
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "react-devtools-core",
"version": "5.2.0",
"version": "5.3.0",
"description": "Use react-devtools outside of the browser",
"license": "MIT",
"main": "./dist/backend.js",
@@ -1,12 +1,6 @@
const {resolve} = require('path');
const Webpack = require('webpack');
const {
DARK_MODE_DIMMED_WARNING_COLOR,
DARK_MODE_DIMMED_ERROR_COLOR,
DARK_MODE_DIMMED_LOG_COLOR,
LIGHT_MODE_DIMMED_WARNING_COLOR,
LIGHT_MODE_DIMMED_ERROR_COLOR,
LIGHT_MODE_DIMMED_LOG_COLOR,
GITHUB_URL,
getVersionString,
} = require('react-devtools-extensions/utils');
@@ -74,15 +68,10 @@ module.exports = {
__EXTENSION__: false,
__PROFILE__: false,
__TEST__: NODE_ENV === 'test',
__IS_FIREFOX__: false,
'process.env.DEVTOOLS_PACKAGE': `"react-devtools-core"`,
'process.env.DEVTOOLS_VERSION': `"${DEVTOOLS_VERSION}"`,
'process.env.GITHUB_URL': `"${GITHUB_URL}"`,
'process.env.DARK_MODE_DIMMED_WARNING_COLOR': `"${DARK_MODE_DIMMED_WARNING_COLOR}"`,
'process.env.DARK_MODE_DIMMED_ERROR_COLOR': `"${DARK_MODE_DIMMED_ERROR_COLOR}"`,
'process.env.DARK_MODE_DIMMED_LOG_COLOR': `"${DARK_MODE_DIMMED_LOG_COLOR}"`,
'process.env.LIGHT_MODE_DIMMED_WARNING_COLOR': `"${LIGHT_MODE_DIMMED_WARNING_COLOR}"`,
'process.env.LIGHT_MODE_DIMMED_ERROR_COLOR': `"${LIGHT_MODE_DIMMED_ERROR_COLOR}"`,
'process.env.LIGHT_MODE_DIMMED_LOG_COLOR': `"${LIGHT_MODE_DIMMED_LOG_COLOR}"`,
}),
],
optimization: {
@@ -1,12 +1,6 @@
const {resolve} = require('path');
const Webpack = require('webpack');
const {
DARK_MODE_DIMMED_WARNING_COLOR,
DARK_MODE_DIMMED_ERROR_COLOR,
DARK_MODE_DIMMED_LOG_COLOR,
LIGHT_MODE_DIMMED_WARNING_COLOR,
LIGHT_MODE_DIMMED_ERROR_COLOR,
LIGHT_MODE_DIMMED_LOG_COLOR,
GITHUB_URL,
getVersionString,
} = require('react-devtools-extensions/utils');
@@ -99,12 +93,6 @@ module.exports = {
'process.env.GITHUB_URL': `"${GITHUB_URL}"`,
'process.env.LOGGING_URL': `"${LOGGING_URL}"`,
'process.env.NODE_ENV': `"${NODE_ENV}"`,
'process.env.DARK_MODE_DIMMED_WARNING_COLOR': `"${DARK_MODE_DIMMED_WARNING_COLOR}"`,
'process.env.DARK_MODE_DIMMED_ERROR_COLOR': `"${DARK_MODE_DIMMED_ERROR_COLOR}"`,
'process.env.DARK_MODE_DIMMED_LOG_COLOR': `"${DARK_MODE_DIMMED_LOG_COLOR}"`,
'process.env.LIGHT_MODE_DIMMED_WARNING_COLOR': `"${LIGHT_MODE_DIMMED_WARNING_COLOR}"`,
'process.env.LIGHT_MODE_DIMMED_ERROR_COLOR': `"${LIGHT_MODE_DIMMED_ERROR_COLOR}"`,
'process.env.LIGHT_MODE_DIMMED_LOG_COLOR': `"${LIGHT_MODE_DIMMED_LOG_COLOR}"`,
}),
],
module: {
@@ -2,8 +2,8 @@
"manifest_version": 3,
"name": "React Developer Tools",
"description": "Adds React debugging tools to the Chrome Developer Tools.",
"version": "5.2.0",
"version_name": "5.2.0",
"version": "5.3.0",
"version_name": "5.3.0",
"minimum_chrome_version": "102",
"icons": {
"16": "icons/16-production.png",
@@ -2,8 +2,8 @@
"manifest_version": 3,
"name": "React Developer Tools",
"description": "Adds React debugging tools to the Microsoft Edge Developer Tools.",
"version": "5.2.0",
"version_name": "5.2.0",
"version": "5.3.0",
"version_name": "5.3.0",
"minimum_chrome_version": "102",
"icons": {
"16": "icons/16-production.png",
@@ -2,7 +2,7 @@
"manifest_version": 2,
"name": "React Developer Tools",
"description": "Adds React debugging tools to the Firefox Developer Tools.",
"version": "5.2.0",
"version": "5.3.0",
"applications": {
"gecko": {
"id": "@react-devtools",
-13
View File
@@ -9,13 +9,6 @@ const {execSync} = require('child_process');
const {readFileSync} = require('fs');
const {resolve} = require('path');
const DARK_MODE_DIMMED_WARNING_COLOR = 'rgba(250, 180, 50, 0.5)';
const DARK_MODE_DIMMED_ERROR_COLOR = 'rgba(250, 123, 130, 0.5)';
const DARK_MODE_DIMMED_LOG_COLOR = 'rgba(125, 125, 125, 0.5)';
const LIGHT_MODE_DIMMED_WARNING_COLOR = 'rgba(250, 180, 50, 0.75)';
const LIGHT_MODE_DIMMED_ERROR_COLOR = 'rgba(250, 123, 130, 0.75)';
const LIGHT_MODE_DIMMED_LOG_COLOR = 'rgba(125, 125, 125, 0.75)';
const GITHUB_URL = 'https://github.com/facebook/react';
function getGitCommit() {
@@ -45,12 +38,6 @@ function getVersionString(packageVersion = null) {
}
module.exports = {
DARK_MODE_DIMMED_WARNING_COLOR,
DARK_MODE_DIMMED_ERROR_COLOR,
DARK_MODE_DIMMED_LOG_COLOR,
LIGHT_MODE_DIMMED_WARNING_COLOR,
LIGHT_MODE_DIMMED_ERROR_COLOR,
LIGHT_MODE_DIMMED_LOG_COLOR,
GITHUB_URL,
getGitCommit,
getVersionString,
@@ -1,21 +1,12 @@
'use strict';
const {resolve} = require('path');
const {resolve, isAbsolute, relative} = require('path');
const Webpack = require('webpack');
const {resolveFeatureFlags} = require('react-devtools-shared/buildUtils');
const SourceMapIgnoreListPlugin = require('react-devtools-shared/SourceMapIgnoreListPlugin');
const {
DARK_MODE_DIMMED_WARNING_COLOR,
DARK_MODE_DIMMED_ERROR_COLOR,
DARK_MODE_DIMMED_LOG_COLOR,
LIGHT_MODE_DIMMED_WARNING_COLOR,
LIGHT_MODE_DIMMED_ERROR_COLOR,
LIGHT_MODE_DIMMED_LOG_COLOR,
GITHUB_URL,
getVersionString,
} = require('./utils');
const {GITHUB_URL, getVersionString} = require('./utils');
const NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV) {
@@ -80,19 +71,27 @@ module.exports = {
'process.env.DEVTOOLS_PACKAGE': `"react-devtools-extensions"`,
'process.env.DEVTOOLS_VERSION': `"${DEVTOOLS_VERSION}"`,
'process.env.GITHUB_URL': `"${GITHUB_URL}"`,
'process.env.DARK_MODE_DIMMED_WARNING_COLOR': `"${DARK_MODE_DIMMED_WARNING_COLOR}"`,
'process.env.DARK_MODE_DIMMED_ERROR_COLOR': `"${DARK_MODE_DIMMED_ERROR_COLOR}"`,
'process.env.DARK_MODE_DIMMED_LOG_COLOR': `"${DARK_MODE_DIMMED_LOG_COLOR}"`,
'process.env.LIGHT_MODE_DIMMED_WARNING_COLOR': `"${LIGHT_MODE_DIMMED_WARNING_COLOR}"`,
'process.env.LIGHT_MODE_DIMMED_ERROR_COLOR': `"${LIGHT_MODE_DIMMED_ERROR_COLOR}"`,
'process.env.LIGHT_MODE_DIMMED_LOG_COLOR': `"${LIGHT_MODE_DIMMED_LOG_COLOR}"`,
'process.env.IS_CHROME': IS_CHROME,
'process.env.IS_FIREFOX': IS_FIREFOX,
'process.env.IS_EDGE': IS_EDGE,
__IS_CHROME__: IS_CHROME,
__IS_FIREFOX__: IS_FIREFOX,
__IS_EDGE__: IS_EDGE,
}),
new Webpack.SourceMapDevToolPlugin({
filename: '[file].map',
noSources: !__DEV__,
// https://github.com/webpack/webpack/issues/3603#issuecomment-1743147144
moduleFilenameTemplate(info) {
const {absoluteResourcePath, namespace, resourcePath} = info;
if (isAbsolute(absoluteResourcePath)) {
return relative(__dirname + '/build', absoluteResourcePath);
}
// Mimic Webpack's default behavior:
return `webpack://${namespace}/${resourcePath}`;
},
}),
new SourceMapIgnoreListPlugin({
shouldIgnoreSource: () => !__DEV__,
@@ -1,18 +1,9 @@
'use strict';
const {resolve} = require('path');
const {resolve, isAbsolute, relative} = require('path');
const Webpack = require('webpack');
const TerserPlugin = require('terser-webpack-plugin');
const {
DARK_MODE_DIMMED_WARNING_COLOR,
DARK_MODE_DIMMED_ERROR_COLOR,
DARK_MODE_DIMMED_LOG_COLOR,
LIGHT_MODE_DIMMED_WARNING_COLOR,
LIGHT_MODE_DIMMED_ERROR_COLOR,
LIGHT_MODE_DIMMED_LOG_COLOR,
GITHUB_URL,
getVersionString,
} = require('./utils');
const {GITHUB_URL, getVersionString} = require('./utils');
const {resolveFeatureFlags} = require('react-devtools-shared/buildUtils');
const SourceMapIgnoreListPlugin = require('react-devtools-shared/SourceMapIgnoreListPlugin');
@@ -128,16 +119,22 @@ module.exports = {
'process.env.GITHUB_URL': `"${GITHUB_URL}"`,
'process.env.LOGGING_URL': `"${LOGGING_URL}"`,
'process.env.NODE_ENV': `"${NODE_ENV}"`,
'process.env.DARK_MODE_DIMMED_WARNING_COLOR': `"${DARK_MODE_DIMMED_WARNING_COLOR}"`,
'process.env.DARK_MODE_DIMMED_ERROR_COLOR': `"${DARK_MODE_DIMMED_ERROR_COLOR}"`,
'process.env.DARK_MODE_DIMMED_LOG_COLOR': `"${DARK_MODE_DIMMED_LOG_COLOR}"`,
'process.env.LIGHT_MODE_DIMMED_WARNING_COLOR': `"${LIGHT_MODE_DIMMED_WARNING_COLOR}"`,
'process.env.LIGHT_MODE_DIMMED_ERROR_COLOR': `"${LIGHT_MODE_DIMMED_ERROR_COLOR}"`,
'process.env.LIGHT_MODE_DIMMED_LOG_COLOR': `"${LIGHT_MODE_DIMMED_LOG_COLOR}"`,
}),
new Webpack.SourceMapDevToolPlugin({
filename: '[file].map',
include: 'installHook.js',
noSources: !__DEV__,
// https://github.com/webpack/webpack/issues/3603#issuecomment-1743147144
moduleFilenameTemplate(info) {
const {absoluteResourcePath, namespace, resourcePath} = info;
if (isAbsolute(absoluteResourcePath)) {
return relative(__dirname + '/build', absoluteResourcePath);
}
// Mimic Webpack's default behavior:
return `webpack://${namespace}/${resourcePath}`;
},
}),
new SourceMapIgnoreListPlugin({
shouldIgnoreSource: (assetName, _source) => {
@@ -1,12 +1,6 @@
const {resolve} = require('path');
const Webpack = require('webpack');
const {
DARK_MODE_DIMMED_WARNING_COLOR,
DARK_MODE_DIMMED_ERROR_COLOR,
DARK_MODE_DIMMED_LOG_COLOR,
LIGHT_MODE_DIMMED_WARNING_COLOR,
LIGHT_MODE_DIMMED_ERROR_COLOR,
LIGHT_MODE_DIMMED_LOG_COLOR,
GITHUB_URL,
getVersionString,
} = require('react-devtools-extensions/utils');
@@ -93,12 +87,6 @@ module.exports = {
'process.env.EDITOR_URL': EDITOR_URL != null ? `"${EDITOR_URL}"` : null,
'process.env.GITHUB_URL': `"${GITHUB_URL}"`,
'process.env.NODE_ENV': `"${NODE_ENV}"`,
'process.env.DARK_MODE_DIMMED_WARNING_COLOR': `"${DARK_MODE_DIMMED_WARNING_COLOR}"`,
'process.env.DARK_MODE_DIMMED_ERROR_COLOR': `"${DARK_MODE_DIMMED_ERROR_COLOR}"`,
'process.env.DARK_MODE_DIMMED_LOG_COLOR': `"${DARK_MODE_DIMMED_LOG_COLOR}"`,
'process.env.LIGHT_MODE_DIMMED_WARNING_COLOR': `"${LIGHT_MODE_DIMMED_WARNING_COLOR}"`,
'process.env.LIGHT_MODE_DIMMED_ERROR_COLOR': `"${LIGHT_MODE_DIMMED_ERROR_COLOR}"`,
'process.env.LIGHT_MODE_DIMMED_LOG_COLOR': `"${LIGHT_MODE_DIMMED_LOG_COLOR}"`,
}),
],
module: {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "react-devtools-inline",
"version": "5.2.0",
"version": "5.3.0",
"description": "Embed react-devtools within a website",
"license": "MIT",
"main": "./dist/backend.js",
@@ -1,12 +1,6 @@
const {resolve} = require('path');
const Webpack = require('webpack');
const {
DARK_MODE_DIMMED_WARNING_COLOR,
DARK_MODE_DIMMED_ERROR_COLOR,
DARK_MODE_DIMMED_LOG_COLOR,
LIGHT_MODE_DIMMED_WARNING_COLOR,
LIGHT_MODE_DIMMED_ERROR_COLOR,
LIGHT_MODE_DIMMED_LOG_COLOR,
GITHUB_URL,
getVersionString,
} = require('react-devtools-extensions/utils');
@@ -84,12 +78,6 @@ module.exports = {
'process.env.EDITOR_URL': EDITOR_URL != null ? `"${EDITOR_URL}"` : null,
'process.env.GITHUB_URL': `"${GITHUB_URL}"`,
'process.env.NODE_ENV': `"${NODE_ENV}"`,
'process.env.DARK_MODE_DIMMED_WARNING_COLOR': `"${DARK_MODE_DIMMED_WARNING_COLOR}"`,
'process.env.DARK_MODE_DIMMED_ERROR_COLOR': `"${DARK_MODE_DIMMED_ERROR_COLOR}"`,
'process.env.DARK_MODE_DIMMED_LOG_COLOR': `"${DARK_MODE_DIMMED_LOG_COLOR}"`,
'process.env.LIGHT_MODE_DIMMED_WARNING_COLOR': `"${LIGHT_MODE_DIMMED_WARNING_COLOR}"`,
'process.env.LIGHT_MODE_DIMMED_ERROR_COLOR': `"${LIGHT_MODE_DIMMED_ERROR_COLOR}"`,
'process.env.LIGHT_MODE_DIMMED_LOG_COLOR': `"${LIGHT_MODE_DIMMED_LOG_COLOR}"`,
}),
],
module: {
@@ -36,16 +36,16 @@ describe('Timeline profiler', () => {
});
describe('User Timing API', () => {
let clearedMarks;
let currentlyNotClearedMarks;
let registeredMarks;
let featureDetectionMarkName = null;
let marks;
let setPerformanceMock;
function createUserTimingPolyfill() {
featureDetectionMarkName = null;
clearedMarks = [];
marks = [];
currentlyNotClearedMarks = [];
registeredMarks = [];
// Remove file-system specific bits or version-specific bits of information from the module range marks.
function filterMarkData(markName) {
@@ -66,8 +66,9 @@ describe('Timeline profiler', () => {
clearMarks(markName) {
markName = filterMarkData(markName);
clearedMarks.push(markName);
marks = marks.filter(mark => mark !== markName);
currentlyNotClearedMarks = currentlyNotClearedMarks.filter(
mark => mark !== markName,
);
},
mark(markName, markOptions) {
markName = filterMarkData(markName);
@@ -76,7 +77,8 @@ describe('Timeline profiler', () => {
featureDetectionMarkName = markName;
}
marks.push(markName);
registeredMarks.push(markName);
currentlyNotClearedMarks.push(markName);
if (markOptions != null) {
// This is triggers the feature detection.
@@ -86,8 +88,8 @@ describe('Timeline profiler', () => {
};
}
function clearPendingMarks() {
clearedMarks.splice(0);
function eraseRegisteredMarks() {
registeredMarks.splice(0);
}
function dispatchAndSetCurrentEvent(element, event) {
@@ -107,7 +109,7 @@ describe('Timeline profiler', () => {
afterEach(() => {
// Verify all logged marks also get cleared.
expect(marks).toHaveLength(0);
expect(currentlyNotClearedMarks).toHaveLength(0);
setPerformanceMock(null);
});
@@ -120,7 +122,7 @@ describe('Timeline profiler', () => {
it('should mark sync render without suspends or state updates', () => {
legacyRender(<div />);
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--schedule-render-1",
"--render-start-1",
@@ -154,7 +156,7 @@ describe('Timeline profiler', () => {
</React.Suspense>,
);
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--schedule-render-2",
"--render-start-2",
@@ -174,10 +176,10 @@ describe('Timeline profiler', () => {
]
`);
clearPendingMarks();
eraseRegisteredMarks();
await fakeSuspensePromise;
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--suspense-resolved-0-Example",
]
@@ -200,7 +202,7 @@ describe('Timeline profiler', () => {
</React.Suspense>,
);
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--schedule-render-2",
"--render-start-2",
@@ -220,10 +222,10 @@ describe('Timeline profiler', () => {
]
`);
clearPendingMarks();
eraseRegisteredMarks();
await expect(fakeSuspensePromise).rejects.toThrow();
expect(clearedMarks).toContain(`--suspense-rejected-0-Example`);
expect(registeredMarks).toContain(`--suspense-rejected-0-Example`);
});
// @reactVersion <= 18.2
@@ -254,7 +256,7 @@ describe('Timeline profiler', () => {
</ErrorBoundary>,
);
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--schedule-render-1",
"--render-start-1",
@@ -310,17 +312,17 @@ describe('Timeline profiler', () => {
it('should mark concurrent render without suspends or state updates', async () => {
modernRender(<div />);
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--schedule-render-32",
]
`);
clearPendingMarks();
eraseRegisteredMarks();
await waitForPaint([]);
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--render-start-32",
"--render-stop",
@@ -356,7 +358,7 @@ describe('Timeline profiler', () => {
await waitFor(['Foo']);
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--schedule-render-128",
"--render-start-128",
@@ -383,17 +385,17 @@ describe('Timeline profiler', () => {
</React.Suspense>,
);
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--schedule-render-32",
]
`);
clearPendingMarks();
eraseRegisteredMarks();
await waitForPaint([]);
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--render-start-32",
"--component-render-start-Example",
@@ -414,10 +416,10 @@ describe('Timeline profiler', () => {
]
`);
clearPendingMarks();
eraseRegisteredMarks();
await resolveFakePromise();
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--suspense-resolved-0-Example",
]
@@ -440,17 +442,17 @@ describe('Timeline profiler', () => {
</React.Suspense>,
);
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--schedule-render-32",
]
`);
clearPendingMarks();
eraseRegisteredMarks();
await waitForPaint([]);
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--render-start-32",
"--component-render-start-Example",
@@ -471,13 +473,13 @@ describe('Timeline profiler', () => {
]
`);
clearPendingMarks();
eraseRegisteredMarks();
await expect(() => {
rejectFakePromise(new Error('error'));
return fakeSuspensePromise;
}).rejects.toThrow();
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--suspense-rejected-0-Example",
]
@@ -497,17 +499,17 @@ describe('Timeline profiler', () => {
modernRender(<Example />);
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--schedule-render-32",
]
`);
clearPendingMarks();
eraseRegisteredMarks();
await waitForPaint([]);
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--render-start-32",
"--component-render-start-Example",
@@ -554,17 +556,17 @@ describe('Timeline profiler', () => {
modernRender(<Example />);
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--schedule-render-32",
]
`);
clearPendingMarks();
eraseRegisteredMarks();
await waitForPaint([]);
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--render-start-32",
"--component-render-start-Example",
@@ -612,13 +614,13 @@ describe('Timeline profiler', () => {
modernRender(<Example />);
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--schedule-render-32",
]
`);
clearPendingMarks();
eraseRegisteredMarks();
let errorMessage;
jest.spyOn(console, 'error').mockImplementation(message => {
@@ -632,7 +634,7 @@ describe('Timeline profiler', () => {
'Cannot update during an existing state transition',
);
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--render-start-32",
"--component-render-start-Example",
@@ -668,13 +670,13 @@ describe('Timeline profiler', () => {
modernRender(<Example />);
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--schedule-render-32",
]
`);
clearPendingMarks();
eraseRegisteredMarks();
let errorMessage;
jest.spyOn(console, 'error').mockImplementation(message => {
@@ -688,7 +690,7 @@ describe('Timeline profiler', () => {
'Cannot update during an existing state transition',
);
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--render-start-32",
"--component-render-start-Example",
@@ -721,17 +723,17 @@ describe('Timeline profiler', () => {
modernRender(<Example />);
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--schedule-render-32",
]
`);
clearPendingMarks();
eraseRegisteredMarks();
await waitForPaint([]);
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--render-start-32",
"--component-render-start-Example",
@@ -781,7 +783,7 @@ describe('Timeline profiler', () => {
await waitForAll([]);
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--schedule-render-32",
"--render-start-32",
@@ -834,7 +836,7 @@ describe('Timeline profiler', () => {
await waitForAll([]);
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--schedule-render-32",
"--render-start-32",
@@ -884,17 +886,17 @@ describe('Timeline profiler', () => {
</ErrorBoundary>,
);
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--schedule-render-32",
]
`);
clearPendingMarks();
eraseRegisteredMarks();
await waitForPaint([]);
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--render-start-32",
"--component-render-start-ErrorBoundary",
@@ -983,7 +985,7 @@ describe('Timeline profiler', () => {
await waitForPaint(['layout 1 mount', 'layout 2 mount']);
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--schedule-render-32",
"--render-start-32",
@@ -1008,7 +1010,7 @@ describe('Timeline profiler', () => {
]
`);
clearPendingMarks();
eraseRegisteredMarks();
await waitForAll([
'passive 1 mount',
@@ -1016,7 +1018,7 @@ describe('Timeline profiler', () => {
'passive 3 mount',
]);
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--passive-effects-start-32",
"--component-passive-effect-mount-start-ComponentWithEffects",
@@ -1029,7 +1031,7 @@ describe('Timeline profiler', () => {
]
`);
clearPendingMarks();
eraseRegisteredMarks();
await waitForAll([]);
@@ -1043,7 +1045,7 @@ describe('Timeline profiler', () => {
'passive 3 unmount',
]);
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--schedule-render-2",
"--render-start-2",
@@ -1085,7 +1087,7 @@ describe('Timeline profiler', () => {
it('regression test SyncLane', () => {
legacyRender(<div />);
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--schedule-render-1",
"--render-start-1",
@@ -1116,7 +1118,7 @@ describe('Timeline profiler', () => {
it('regression test DefaultLane', () => {
modernRender(<div />);
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--schedule-render-32",
]
@@ -1137,14 +1139,14 @@ describe('Timeline profiler', () => {
modernRender(<App />);
await waitForAll([]);
clearedMarks.splice(0);
eraseRegisteredMarks();
targetRef.current.click();
// Wait a frame, for React to process the "click" update.
await Promise.resolve();
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--schedule-state-update-2-App",
"--render-start-2",
@@ -1178,7 +1180,7 @@ describe('Timeline profiler', () => {
modernRender(<App />);
await waitForAll([]);
clearedMarks.splice(0);
eraseRegisteredMarks();
const event = document.createEvent('MouseEvents');
event.initEvent('mouseover', true, true);
@@ -1186,7 +1188,7 @@ describe('Timeline profiler', () => {
await waitForAll([]);
expect(clearedMarks).toMatchInlineSnapshot(`
expect(registeredMarks).toMatchInlineSnapshot(`
[
"--schedule-state-update-8-App",
"--render-start-8",
+52 -113
View File
@@ -515,58 +515,52 @@ describe('console', () => {
expect(mockLog.mock.calls[0]).toHaveLength(1);
expect(mockLog.mock.calls[0][0]).toBe('log');
expect(mockLog.mock.calls[1]).toEqual([
'%c%s',
`color: ${process.env.DARK_MODE_DIMMED_LOG_COLOR}`,
'\x1b[2;38;2;124;124;124m%s\x1b[0m',
'log',
]);
expect(mockWarn).toHaveBeenCalledTimes(2);
expect(mockWarn.mock.calls[0]).toHaveLength(1);
expect(mockWarn.mock.calls[0][0]).toBe('warn');
expect(mockWarn.mock.calls[1]).toHaveLength(3);
expect(mockWarn.mock.calls[1]).toHaveLength(2);
expect(mockWarn.mock.calls[1]).toEqual([
'%c%s',
`color: ${process.env.DARK_MODE_DIMMED_WARNING_COLOR}`,
'\x1b[2;38;2;124;124;124m%s\x1b[0m',
'warn',
]);
expect(mockError).toHaveBeenCalledTimes(2);
expect(mockError.mock.calls[0]).toHaveLength(1);
expect(mockError.mock.calls[0][0]).toBe('error');
expect(mockError.mock.calls[1]).toHaveLength(3);
expect(mockError.mock.calls[1]).toHaveLength(2);
expect(mockError.mock.calls[1]).toEqual([
'%c%s',
`color: ${process.env.DARK_MODE_DIMMED_ERROR_COLOR}`,
'\x1b[2;38;2;124;124;124m%s\x1b[0m',
'error',
]);
expect(mockInfo).toHaveBeenCalledTimes(2);
expect(mockInfo.mock.calls[0]).toHaveLength(1);
expect(mockInfo.mock.calls[0][0]).toBe('info');
expect(mockInfo.mock.calls[1]).toHaveLength(3);
expect(mockInfo.mock.calls[1]).toHaveLength(2);
expect(mockInfo.mock.calls[1]).toEqual([
'%c%s',
`color: ${process.env.DARK_MODE_DIMMED_LOG_COLOR}`,
'\x1b[2;38;2;124;124;124m%s\x1b[0m',
'info',
]);
expect(mockGroup).toHaveBeenCalledTimes(2);
expect(mockGroup.mock.calls[0]).toHaveLength(1);
expect(mockGroup.mock.calls[0][0]).toBe('group');
expect(mockGroup.mock.calls[1]).toHaveLength(3);
expect(mockGroup.mock.calls[1]).toHaveLength(2);
expect(mockGroup.mock.calls[1]).toEqual([
'%c%s',
`color: ${process.env.DARK_MODE_DIMMED_LOG_COLOR}`,
'\x1b[2;38;2;124;124;124m%s\x1b[0m',
'group',
]);
expect(mockGroupCollapsed).toHaveBeenCalledTimes(2);
expect(mockGroupCollapsed.mock.calls[0]).toHaveLength(1);
expect(mockGroupCollapsed.mock.calls[0][0]).toBe('groupCollapsed');
expect(mockGroupCollapsed.mock.calls[1]).toHaveLength(3);
expect(mockGroupCollapsed.mock.calls[1]).toHaveLength(2);
expect(mockGroupCollapsed.mock.calls[1]).toEqual([
'%c%s',
`color: ${process.env.DARK_MODE_DIMMED_LOG_COLOR}`,
'\x1b[2;38;2;124;124;124m%s\x1b[0m',
'groupCollapsed',
]);
});
@@ -663,81 +657,33 @@ describe('console', () => {
);
expect(mockLog.mock.calls).toEqual([
['log effect create'],
[
'%c%s',
`color: ${process.env.DARK_MODE_DIMMED_LOG_COLOR}`,
'log effect cleanup',
],
[
'%c%s',
`color: ${process.env.DARK_MODE_DIMMED_LOG_COLOR}`,
'log effect create',
],
['\x1b[2;38;2;124;124;124m%s\x1b[0m', 'log effect cleanup'],
['\x1b[2;38;2;124;124;124m%s\x1b[0m', 'log effect create'],
]);
expect(mockWarn.mock.calls).toEqual([
['warn effect create'],
[
'%c%s',
`color: ${process.env.DARK_MODE_DIMMED_WARNING_COLOR}`,
'warn effect cleanup',
],
[
'%c%s',
`color: ${process.env.DARK_MODE_DIMMED_WARNING_COLOR}`,
'warn effect create',
],
['\x1b[2;38;2;124;124;124m%s\x1b[0m', 'warn effect cleanup'],
['\x1b[2;38;2;124;124;124m%s\x1b[0m', 'warn effect create'],
]);
expect(mockError.mock.calls).toEqual([
['error effect create'],
[
'%c%s',
`color: ${process.env.DARK_MODE_DIMMED_ERROR_COLOR}`,
'error effect cleanup',
],
[
'%c%s',
`color: ${process.env.DARK_MODE_DIMMED_ERROR_COLOR}`,
'error effect create',
],
['\x1b[2;38;2;124;124;124m%s\x1b[0m', 'error effect cleanup'],
['\x1b[2;38;2;124;124;124m%s\x1b[0m', 'error effect create'],
]);
expect(mockInfo.mock.calls).toEqual([
['info effect create'],
[
'%c%s',
`color: ${process.env.DARK_MODE_DIMMED_LOG_COLOR}`,
'info effect cleanup',
],
[
'%c%s',
`color: ${process.env.DARK_MODE_DIMMED_LOG_COLOR}`,
'info effect create',
],
['\x1b[2;38;2;124;124;124m%s\x1b[0m', 'info effect cleanup'],
['\x1b[2;38;2;124;124;124m%s\x1b[0m', 'info effect create'],
]);
expect(mockGroup.mock.calls).toEqual([
['group effect create'],
[
'%c%s',
`color: ${process.env.DARK_MODE_DIMMED_LOG_COLOR}`,
'group effect cleanup',
],
[
'%c%s',
`color: ${process.env.DARK_MODE_DIMMED_LOG_COLOR}`,
'group effect create',
],
['\x1b[2;38;2;124;124;124m%s\x1b[0m', 'group effect cleanup'],
['\x1b[2;38;2;124;124;124m%s\x1b[0m', 'group effect create'],
]);
expect(mockGroupCollapsed.mock.calls).toEqual([
['groupCollapsed effect create'],
[
'%c%s',
`color: ${process.env.DARK_MODE_DIMMED_LOG_COLOR}`,
'groupCollapsed effect cleanup',
],
[
'%c%s',
`color: ${process.env.DARK_MODE_DIMMED_LOG_COLOR}`,
'groupCollapsed effect create',
],
['\x1b[2;38;2;124;124;124m%s\x1b[0m', 'groupCollapsed effect cleanup'],
['\x1b[2;38;2;124;124;124m%s\x1b[0m', 'groupCollapsed effect create'],
]);
});
@@ -816,58 +762,52 @@ describe('console', () => {
expect(mockLog.mock.calls[0]).toHaveLength(1);
expect(mockLog.mock.calls[0][0]).toBe('log');
expect(mockLog.mock.calls[1]).toEqual([
'%c%s',
`color: ${process.env.DARK_MODE_DIMMED_LOG_COLOR}`,
'\x1b[2;38;2;124;124;124m%s\x1b[0m',
'log',
]);
expect(mockWarn).toHaveBeenCalledTimes(2);
expect(mockWarn.mock.calls[0]).toHaveLength(1);
expect(mockWarn.mock.calls[0][0]).toBe('warn');
expect(mockWarn.mock.calls[1]).toHaveLength(3);
expect(mockWarn.mock.calls[1]).toHaveLength(2);
expect(mockWarn.mock.calls[1]).toEqual([
'%c%s',
`color: ${process.env.DARK_MODE_DIMMED_WARNING_COLOR}`,
'\x1b[2;38;2;124;124;124m%s\x1b[0m',
'warn',
]);
expect(mockError).toHaveBeenCalledTimes(2);
expect(mockError.mock.calls[0]).toHaveLength(1);
expect(mockError.mock.calls[0][0]).toBe('error');
expect(mockError.mock.calls[1]).toHaveLength(3);
expect(mockError.mock.calls[1]).toHaveLength(2);
expect(mockError.mock.calls[1]).toEqual([
'%c%s',
`color: ${process.env.DARK_MODE_DIMMED_ERROR_COLOR}`,
'\x1b[2;38;2;124;124;124m%s\x1b[0m',
'error',
]);
expect(mockInfo).toHaveBeenCalledTimes(2);
expect(mockInfo.mock.calls[0]).toHaveLength(1);
expect(mockInfo.mock.calls[0][0]).toBe('info');
expect(mockInfo.mock.calls[1]).toHaveLength(3);
expect(mockInfo.mock.calls[1]).toHaveLength(2);
expect(mockInfo.mock.calls[1]).toEqual([
'%c%s',
`color: ${process.env.DARK_MODE_DIMMED_LOG_COLOR}`,
'\x1b[2;38;2;124;124;124m%s\x1b[0m',
'info',
]);
expect(mockGroup).toHaveBeenCalledTimes(2);
expect(mockGroup.mock.calls[0]).toHaveLength(1);
expect(mockGroup.mock.calls[0][0]).toBe('group');
expect(mockGroup.mock.calls[1]).toHaveLength(3);
expect(mockGroup.mock.calls[1]).toHaveLength(2);
expect(mockGroup.mock.calls[1]).toEqual([
'%c%s',
`color: ${process.env.DARK_MODE_DIMMED_LOG_COLOR}`,
'\x1b[2;38;2;124;124;124m%s\x1b[0m',
'group',
]);
expect(mockGroupCollapsed).toHaveBeenCalledTimes(2);
expect(mockGroupCollapsed.mock.calls[0]).toHaveLength(1);
expect(mockGroupCollapsed.mock.calls[0][0]).toBe('groupCollapsed');
expect(mockGroupCollapsed.mock.calls[1]).toHaveLength(3);
expect(mockGroupCollapsed.mock.calls[1]).toHaveLength(2);
expect(mockGroupCollapsed.mock.calls[1]).toEqual([
'%c%s',
`color: ${process.env.DARK_MODE_DIMMED_LOG_COLOR}`,
'\x1b[2;38;2;124;124;124m%s\x1b[0m',
'groupCollapsed',
]);
});
@@ -960,30 +900,27 @@ describe('console', () => {
expect(mockLog).toHaveBeenCalledTimes(2);
expect(mockLog.mock.calls[0]).toHaveLength(1);
expect(mockLog.mock.calls[0][0]).toBe('log');
expect(mockLog.mock.calls[1]).toHaveLength(3);
expect(mockLog.mock.calls[1]).toHaveLength(2);
expect(mockLog.mock.calls[1]).toEqual([
'%c%s',
`color: ${process.env.DARK_MODE_DIMMED_LOG_COLOR}`,
'\x1b[2;38;2;124;124;124m%s\x1b[0m',
'log',
]);
expect(mockWarn).toHaveBeenCalledTimes(2);
expect(mockWarn.mock.calls[0]).toHaveLength(1);
expect(mockWarn.mock.calls[0][0]).toBe('warn');
expect(mockWarn.mock.calls[1]).toHaveLength(3);
expect(mockWarn.mock.calls[1]).toHaveLength(2);
expect(mockWarn.mock.calls[1]).toEqual([
'%c%s',
`color: ${process.env.DARK_MODE_DIMMED_WARNING_COLOR}`,
'\x1b[2;38;2;124;124;124m%s\x1b[0m',
'warn',
]);
expect(mockError).toHaveBeenCalledTimes(2);
expect(mockError.mock.calls[0]).toHaveLength(1);
expect(mockError.mock.calls[0][0]).toBe('error');
expect(mockError.mock.calls[1]).toHaveLength(3);
expect(mockError.mock.calls[1]).toHaveLength(2);
expect(mockError.mock.calls[1]).toEqual([
'%c%s',
`color: ${process.env.DARK_MODE_DIMMED_ERROR_COLOR}`,
'\x1b[2;38;2;124;124;124m%s\x1b[0m',
'error',
]);
});
@@ -1061,11 +998,12 @@ describe('console', () => {
expect(normalizeCodeLocInfo(mockWarn.mock.calls[0][1])).toEqual(
'\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)',
);
expect(mockWarn.mock.calls[1]).toHaveLength(4);
expect(mockWarn.mock.calls[1][0]).toEqual('%c%s %s');
expect(mockWarn.mock.calls[1][1]).toMatch('color: rgba(');
expect(mockWarn.mock.calls[1][2]).toEqual('warn');
expect(normalizeCodeLocInfo(mockWarn.mock.calls[1][3]).trim()).toEqual(
expect(mockWarn.mock.calls[1]).toHaveLength(3);
expect(mockWarn.mock.calls[1][0]).toEqual(
'\x1b[2;38;2;124;124;124m%s %s\x1b[0m',
);
expect(mockWarn.mock.calls[1][1]).toMatch('warn');
expect(normalizeCodeLocInfo(mockWarn.mock.calls[1][2]).trim()).toEqual(
'in Child (at **)\n in Intermediate (at **)\n in Parent (at **)',
);
@@ -1074,11 +1012,12 @@ describe('console', () => {
expect(normalizeCodeLocInfo(mockError.mock.calls[0][1])).toEqual(
'\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)',
);
expect(mockError.mock.calls[1]).toHaveLength(4);
expect(mockError.mock.calls[1][0]).toEqual('%c%s %s');
expect(mockError.mock.calls[1][1]).toMatch('color: rgba(');
expect(mockError.mock.calls[1][2]).toEqual('error');
expect(normalizeCodeLocInfo(mockError.mock.calls[1][3]).trim()).toEqual(
expect(mockError.mock.calls[1]).toHaveLength(3);
expect(mockError.mock.calls[1][0]).toEqual(
'\x1b[2;38;2;124;124;124m%s %s\x1b[0m',
);
expect(mockError.mock.calls[1][1]).toEqual('error');
expect(normalizeCodeLocInfo(mockError.mock.calls[1][2]).trim()).toEqual(
'in Child (at **)\n in Intermediate (at **)\n in Parent (at **)',
);
});
@@ -26,16 +26,16 @@ describe('Timeline profiler', () => {
let waitFor;
describe('User Timing API', () => {
let clearedMarks;
let currentlyNotClearedMarks;
let registeredMarks;
let featureDetectionMarkName = null;
let marks;
let setPerformanceMock;
function createUserTimingPolyfill() {
featureDetectionMarkName = null;
clearedMarks = [];
marks = [];
currentlyNotClearedMarks = [];
registeredMarks = [];
// Remove file-system specific bits or version-specific bits of information from the module range marks.
function filterMarkData(markName) {
@@ -56,8 +56,9 @@ describe('Timeline profiler', () => {
clearMarks(markName) {
markName = filterMarkData(markName);
clearedMarks.push(markName);
marks = marks.filter(mark => mark !== markName);
currentlyNotClearedMarks = currentlyNotClearedMarks.filter(
mark => mark !== markName,
);
},
mark(markName, markOptions) {
markName = filterMarkData(markName);
@@ -66,7 +67,8 @@ describe('Timeline profiler', () => {
featureDetectionMarkName = markName;
}
marks.push(markName);
registeredMarks.push(markName);
currentlyNotClearedMarks.push(markName);
if (markOptions != null) {
// This is triggers the feature detection.
@@ -76,8 +78,8 @@ describe('Timeline profiler', () => {
};
}
function clearPendingMarks() {
clearedMarks.splice(0);
function eraseRegisteredMarks() {
registeredMarks.splice(0);
}
beforeEach(() => {
@@ -114,8 +116,9 @@ describe('Timeline profiler', () => {
afterEach(() => {
// Verify all logged marks also get cleared.
expect(marks).toHaveLength(0);
expect(currentlyNotClearedMarks).toHaveLength(0);
eraseRegisteredMarks();
setPerformanceMock(null);
});
@@ -635,7 +638,7 @@ describe('Timeline profiler', () => {
const data = await preprocessData([
...createBoilerplateEntries(),
...createUserTimingData(clearedMarks),
...createUserTimingData(registeredMarks),
]);
expect(data).toMatchInlineSnapshot(`
{
@@ -832,7 +835,7 @@ describe('Timeline profiler', () => {
const data = await preprocessData([
...createBoilerplateEntries(),
...createUserTimingData(clearedMarks),
...createUserTimingData(registeredMarks),
]);
expect(data).toMatchInlineSnapshot(`
{
@@ -1152,7 +1155,7 @@ describe('Timeline profiler', () => {
it('should error if events and measures are incomplete', async () => {
legacyRender(<div />);
const invalidMarks = clearedMarks.filter(
const invalidMarks = registeredMarks.filter(
mark => !mark.includes('render-stop'),
);
const invalidUserTimingData = createUserTimingData(invalidMarks);
@@ -1170,7 +1173,7 @@ describe('Timeline profiler', () => {
it('should error if work is completed without being started', async () => {
legacyRender(<div />);
const invalidMarks = clearedMarks.filter(
const invalidMarks = registeredMarks.filter(
mark => !mark.includes('render-start'),
);
const invalidUserTimingData = createUserTimingData(invalidMarks);
@@ -1265,7 +1268,7 @@ describe('Timeline profiler', () => {
),
);
testMarks.push(...createUserTimingData(clearedMarks));
testMarks.push(...createUserTimingData(registeredMarks));
let data;
await utils.actAsync(async () => {
@@ -1290,11 +1293,10 @@ describe('Timeline profiler', () => {
createNativeEventEntry('click', 5),
];
clearPendingMarks();
eraseRegisteredMarks();
legacyRender(<App />);
testMarks.push(...createUserTimingData(clearedMarks));
testMarks.push(...createUserTimingData(registeredMarks));
const data = await preprocessData(testMarks);
const event = data.nativeEvents.find(({type}) => type === 'click');
@@ -1316,11 +1318,10 @@ describe('Timeline profiler', () => {
startTime += 2000;
clearPendingMarks();
eraseRegisteredMarks();
legacyRender(<App />);
testMarks.push(...createUserTimingData(clearedMarks));
testMarks.push(...createUserTimingData(registeredMarks));
const data = await preprocessData(testMarks);
const event = data.nativeEvents.find(({type}) => type === 'click');
@@ -1340,11 +1341,10 @@ describe('Timeline profiler', () => {
createNativeEventEntry('click', 25000),
];
clearPendingMarks();
eraseRegisteredMarks();
legacyRender(<App />);
clearedMarks.forEach(markName => {
registeredMarks.forEach(markName => {
if (markName === '--render-stop') {
// Fake a long running render
startTime += 20000;
@@ -1401,8 +1401,8 @@ describe('Timeline profiler', () => {
await waitFor(['A:1']);
testMarks.push(...createUserTimingData(clearedMarks));
clearPendingMarks();
testMarks.push(...createUserTimingData(registeredMarks));
eraseRegisteredMarks();
// Advance the clock some more to make the pending React update seem long.
startTime += 20000;
@@ -1421,7 +1421,7 @@ describe('Timeline profiler', () => {
assertLog(['A:2', 'B:2']);
testMarks.push(...createUserTimingData(clearedMarks));
testMarks.push(...createUserTimingData(registeredMarks));
const data = await preprocessData(testMarks);
const event = data.nativeEvents.find(({type}) => type === 'click');
@@ -1452,7 +1452,7 @@ describe('Timeline profiler', () => {
const data = await preprocessData([
...createBoilerplateEntries(),
...createUserTimingData(clearedMarks),
...createUserTimingData(registeredMarks),
]);
const event = data.schedulingEvents.find(
@@ -1488,7 +1488,7 @@ describe('Timeline profiler', () => {
const data = await preprocessData([
...createBoilerplateEntries(),
...createUserTimingData(clearedMarks),
...createUserTimingData(registeredMarks),
]);
const event = data.schedulingEvents.find(
@@ -1524,7 +1524,7 @@ describe('Timeline profiler', () => {
assertLog(['Component mount', 'Component update']);
const testMarks = [];
clearedMarks.forEach(markName => {
registeredMarks.forEach(markName => {
if (markName === '--component-render-start-Component') {
// Fake a long running render
startTime += 20000;
@@ -1585,7 +1585,7 @@ describe('Timeline profiler', () => {
assertLog(['Component mount', 'Component update']);
const testMarks = [];
clearedMarks.forEach(markName => {
registeredMarks.forEach(markName => {
if (markName === '--component-render-start-Component') {
// Fake a long running render
startTime += 20000;
@@ -1657,7 +1657,7 @@ describe('Timeline profiler', () => {
]);
const testMarks = [];
clearedMarks.forEach(markName => {
registeredMarks.forEach(markName => {
if (markName === '--component-render-start-Component') {
// Fake a long running render
startTime += 20000;
@@ -1727,7 +1727,7 @@ describe('Timeline profiler', () => {
]);
const testMarks = [];
clearedMarks.forEach(markName => {
registeredMarks.forEach(markName => {
if (markName === '--component-render-start-Component') {
// Fake a long running render
startTime += 20000;
@@ -1792,7 +1792,7 @@ describe('Timeline profiler', () => {
),
);
testMarks.push(...createUserTimingData(clearedMarks));
testMarks.push(...createUserTimingData(registeredMarks));
const data = await preprocessData(testMarks);
expect(data.thrownErrors).toHaveLength(2);
@@ -1851,7 +1851,7 @@ describe('Timeline profiler', () => {
),
);
testMarks.push(...createUserTimingData(clearedMarks));
testMarks.push(...createUserTimingData(registeredMarks));
let data;
await utils.actAsync(async () => {
@@ -1911,7 +1911,7 @@ describe('Timeline profiler', () => {
),
);
testMarks.push(...createUserTimingData(clearedMarks));
testMarks.push(...createUserTimingData(registeredMarks));
let data;
await utils.actAsync(async () => {
+77 -29
View File
@@ -14,7 +14,8 @@ import {
} from 'react-devtools-shared/src/utils';
import {stackToComponentSources} from 'react-devtools-shared/src/devtools/utils';
import {
format,
formatConsoleArguments,
formatConsoleArgumentsToSingleString,
formatWithStyles,
gt,
gte,
@@ -123,51 +124,51 @@ describe('utils', () => {
});
});
describe('format', () => {
// @reactVersion >= 16.0
describe('formatConsoleArgumentsToSingleString', () => {
it('should format simple strings', () => {
expect(format('a', 'b', 'c')).toEqual('a b c');
});
// @reactVersion >= 16.0
it('should format multiple argument types', () => {
expect(format('abc', 123, true)).toEqual('abc 123 true');
});
// @reactVersion >= 16.0
it('should support string substitutions', () => {
expect(format('a %s b %s c', 123, true)).toEqual('a 123 b true c');
});
// @reactVersion >= 16.0
it('should gracefully handle Symbol types', () => {
expect(format(Symbol('a'), 'b', Symbol('c'))).toEqual(
'Symbol(a) b Symbol(c)',
expect(formatConsoleArgumentsToSingleString('a', 'b', 'c')).toEqual(
'a b c',
);
});
// @reactVersion >= 16.0
it('should format multiple argument types', () => {
expect(formatConsoleArgumentsToSingleString('abc', 123, true)).toEqual(
'abc 123 true',
);
});
it('should support string substitutions', () => {
expect(
formatConsoleArgumentsToSingleString('a %s b %s c', 123, true),
).toEqual('a 123 b true c');
});
it('should gracefully handle Symbol types', () => {
expect(
formatConsoleArgumentsToSingleString(Symbol('a'), 'b', Symbol('c')),
).toEqual('Symbol(a) b Symbol(c)');
});
it('should gracefully handle Symbol type for the first argument', () => {
expect(format(Symbol('abc'), 123)).toEqual('Symbol(abc) 123');
expect(formatConsoleArgumentsToSingleString(Symbol('abc'), 123)).toEqual(
'Symbol(abc) 123',
);
});
});
describe('formatWithStyles', () => {
// @reactVersion >= 16.0
it('should format empty arrays', () => {
expect(formatWithStyles([])).toEqual([]);
expect(formatWithStyles([], 'gray')).toEqual([]);
expect(formatWithStyles(undefined)).toEqual(undefined);
});
// @reactVersion >= 16.0
it('should bail out of strings with styles', () => {
expect(
formatWithStyles(['%ca', 'color: green', 'b', 'c'], 'color: gray'),
).toEqual(['%ca', 'color: green', 'b', 'c']);
});
// @reactVersion >= 16.0
it('should format simple strings', () => {
expect(formatWithStyles(['a'])).toEqual(['a']);
@@ -186,7 +187,6 @@ describe('utils', () => {
]);
});
// @reactVersion >= 16.0
it('should format string substituions', () => {
expect(
formatWithStyles(['%s %s %s', 'a', 'b', 'c'], 'color: gray'),
@@ -199,7 +199,6 @@ describe('utils', () => {
);
});
// @reactVersion >= 16.0
it('should support multiple argument types', () => {
const symbol = Symbol('a');
expect(
@@ -219,7 +218,6 @@ describe('utils', () => {
]);
});
// @reactVersion >= 16.0
it('should properly format escaped string substituions', () => {
expect(formatWithStyles(['%%s'], 'color: gray')).toEqual([
'%c%s',
@@ -234,7 +232,6 @@ describe('utils', () => {
expect(formatWithStyles(['%%c%c'], 'color: gray')).toEqual(['%%c%c']);
});
// @reactVersion >= 16.0
it('should format non string inputs as the first argument', () => {
expect(formatWithStyles([{foo: 'bar'}])).toEqual([{foo: 'bar'}]);
expect(formatWithStyles([[1, 2, 3]])).toEqual([[1, 2, 3]]);
@@ -387,4 +384,55 @@ describe('utils', () => {
});
});
});
describe('formatConsoleArguments', () => {
it('works with empty arguments list', () => {
expect(formatConsoleArguments(...[])).toEqual([]);
});
it('works for string without escape sequences', () => {
expect(
formatConsoleArguments('This is the template', 'And another string'),
).toEqual(['This is the template', 'And another string']);
});
it('works with strings templates', () => {
expect(formatConsoleArguments('This is %s template', 'the')).toEqual([
'This is the template',
]);
});
it('skips %%s', () => {
expect(formatConsoleArguments('This %%s is %s template', 'the')).toEqual([
'This %%s is the template',
]);
});
it('works with %%%s', () => {
expect(
formatConsoleArguments('This %%%s is %s template', 'test', 'the'),
).toEqual(['This %%test is the template']);
});
it("doesn't inline objects", () => {
expect(
formatConsoleArguments('This is %s template with object %o', 'the', {}),
).toEqual(['This is the template with object %o', {}]);
});
it("doesn't inline css", () => {
expect(
formatConsoleArguments(
'This is template with %c %s object %o',
'color: rgba(...)',
'the',
{},
),
).toEqual([
'This is template with %c the object %o',
'color: rgba(...)',
{},
]);
});
});
});
+87 -98
View File
@@ -15,18 +15,24 @@ import type {
WorkTagMap,
ConsolePatchSettings,
} from './types';
import {format, formatWithStyles} from './utils';
import {
formatConsoleArguments,
formatWithStyles,
} from 'react-devtools-shared/src/backend/utils';
import {
FIREFOX_CONSOLE_DIMMING_COLOR,
ANSI_STYLE_DIMMING_TEMPLATE,
ANSI_STYLE_DIMMING_TEMPLATE_WITH_COMPONENT_STACK,
} from 'react-devtools-shared/src/constants';
import {getInternalReactConstants, getDispatcherRef} from './renderer';
import {
getStackByFiberInDevAndProd,
supportsNativeConsoleTasks,
} from './DevToolsFiberComponentStack';
import {consoleManagedByDevToolsDuringStrictMode} from 'react-devtools-feature-flags';
import {castBool, castBrowserTheme} from '../utils';
const OVERRIDE_CONSOLE_METHODS = ['error', 'trace', 'warn'];
const DIMMED_NODE_CONSOLE_COLOR = '\x1b[2m%s\x1b[0m';
// React's custom built component stack strings match "\s{4}in"
// Chrome's prefix matches "\s{4}at"
@@ -45,31 +51,18 @@ 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>, method: string): boolean {
return (
args.length >= 2 &&
STYLE_DIRECTIVE_REGEX.test(args[0]) &&
args[1] === `color: ${getConsoleColor(method) || ''}`
);
}
function getConsoleColor(method: string): ?string {
switch (method) {
case 'warn':
return consoleSettingsRef.browserTheme === 'light'
? process.env.LIGHT_MODE_DIMMED_WARNING_COLOR
: process.env.DARK_MODE_DIMMED_WARNING_COLOR;
case 'error':
return consoleSettingsRef.browserTheme === 'light'
? process.env.LIGHT_MODE_DIMMED_ERROR_COLOR
: process.env.DARK_MODE_DIMMED_ERROR_COLOR;
case 'log':
default:
return consoleSettingsRef.browserTheme === 'light'
? process.env.LIGHT_MODE_DIMMED_LOG_COLOR
: process.env.DARK_MODE_DIMMED_LOG_COLOR;
function isStrictModeOverride(args: Array<string>): boolean {
if (__IS_FIREFOX__) {
return (
args.length >= 2 &&
STYLE_DIRECTIVE_REGEX.test(args[0]) &&
args[1] === FIREFOX_CONSOLE_DIMMING_COLOR
);
} else {
return args.length >= 2 && args[0] === ANSI_STYLE_DIMMING_TEMPLATE;
}
}
type OnErrorOrWarning = (
fiber: Fiber,
type: 'error' | 'warn',
@@ -94,11 +87,6 @@ for (const method in console) {
let unpatchFn: null | (() => void) = null;
let isNode = false;
try {
isNode = this === global;
} catch (error) {}
// Enables e.g. Jest tests to inject a mock console object.
export function dangerous_setTargetConsoleForTesting(
targetConsoleForTesting: Object,
@@ -248,9 +236,15 @@ export function patch({
(currentDispatcherRef: any),
);
if (componentStack !== '') {
if (isStrictModeOverride(args, method)) {
args[0] = `${args[0]} %s`;
args.push(componentStack);
if (isStrictModeOverride(args)) {
if (__IS_FIREFOX__) {
args[0] = `${args[0]} %s`;
args.push(componentStack);
} else {
args[0] =
ANSI_STYLE_DIMMING_TEMPLATE_WITH_COMPONENT_STACK;
args.push(componentStack);
}
} else {
args.push(componentStack);
}
@@ -302,76 +296,71 @@ let unpatchForStrictModeFn: null | (() => void) = null;
// NOTE: KEEP IN SYNC with src/hook.js:patchConsoleForInitialCommitInStrictMode
export function patchForStrictMode() {
if (consoleManagedByDevToolsDuringStrictMode) {
const overrideConsoleMethods = [
'error',
'group',
'groupCollapsed',
'info',
'log',
'trace',
'warn',
];
const overrideConsoleMethods = [
'error',
'group',
'groupCollapsed',
'info',
'log',
'trace',
'warn',
];
if (unpatchForStrictModeFn !== null) {
// Don't patch twice.
return;
}
const originalConsoleMethods: {[string]: $FlowFixMe} = {};
unpatchForStrictModeFn = () => {
for (const method in originalConsoleMethods) {
try {
targetConsole[method] = originalConsoleMethods[method];
} catch (error) {}
}
};
overrideConsoleMethods.forEach(method => {
try {
const originalMethod = (originalConsoleMethods[method] = targetConsole[
method
].__REACT_DEVTOOLS_STRICT_MODE_ORIGINAL_METHOD__
? targetConsole[method].__REACT_DEVTOOLS_STRICT_MODE_ORIGINAL_METHOD__
: targetConsole[method]);
// $FlowFixMe[missing-local-annot]
const overrideMethod = (...args) => {
if (!consoleSettingsRef.hideConsoleLogsInStrictMode) {
// Dim the text color of the double logs if we're not
// hiding them.
if (isNode) {
originalMethod(DIMMED_NODE_CONSOLE_COLOR, format(...args));
} else {
const color = getConsoleColor(method);
if (color) {
originalMethod(...formatWithStyles(args, `color: ${color}`));
} else {
throw Error('Console color is not defined');
}
}
}
};
overrideMethod.__REACT_DEVTOOLS_STRICT_MODE_ORIGINAL_METHOD__ =
originalMethod;
originalMethod.__REACT_DEVTOOLS_STRICT_MODE_OVERRIDE_METHOD__ =
overrideMethod;
targetConsole[method] = overrideMethod;
} catch (error) {}
});
if (unpatchForStrictModeFn !== null) {
// Don't patch twice.
return;
}
const originalConsoleMethods: {[string]: $FlowFixMe} = {};
unpatchForStrictModeFn = () => {
for (const method in originalConsoleMethods) {
try {
targetConsole[method] = originalConsoleMethods[method];
} catch (error) {}
}
};
overrideConsoleMethods.forEach(method => {
try {
const originalMethod = (originalConsoleMethods[method] = targetConsole[
method
].__REACT_DEVTOOLS_STRICT_MODE_ORIGINAL_METHOD__
? targetConsole[method].__REACT_DEVTOOLS_STRICT_MODE_ORIGINAL_METHOD__
: targetConsole[method]);
// $FlowFixMe[missing-local-annot]
const overrideMethod = (...args) => {
if (!consoleSettingsRef.hideConsoleLogsInStrictMode) {
// Dim the text color of the double logs if we're not hiding them.
if (__IS_FIREFOX__) {
originalMethod(
...formatWithStyles(args, FIREFOX_CONSOLE_DIMMING_COLOR),
);
} else {
originalMethod(
ANSI_STYLE_DIMMING_TEMPLATE,
...formatConsoleArguments(...args),
);
}
}
};
overrideMethod.__REACT_DEVTOOLS_STRICT_MODE_ORIGINAL_METHOD__ =
originalMethod;
originalMethod.__REACT_DEVTOOLS_STRICT_MODE_OVERRIDE_METHOD__ =
overrideMethod;
targetConsole[method] = overrideMethod;
} catch (error) {}
});
}
// NOTE: KEEP IN SYNC with src/hook.js:unpatchConsoleForInitialCommitInStrictMode
export function unpatchForStrictMode(): void {
if (consoleManagedByDevToolsDuringStrictMode) {
if (unpatchForStrictModeFn !== null) {
unpatchForStrictModeFn();
unpatchForStrictModeFn = null;
}
if (unpatchForStrictModeFn !== null) {
unpatchForStrictModeFn();
unpatchForStrictModeFn = null;
}
}
+9 -2
View File
@@ -40,6 +40,7 @@ import {
} from 'react-devtools-shared/src/utils';
import {sessionStorageGetItem} from 'react-devtools-shared/src/storage';
import {
formatConsoleArgumentsToSingleString,
gt,
gte,
parseSourceFromComponentStack,
@@ -95,7 +96,6 @@ import {
MEMO_SYMBOL_STRING,
SERVER_CONTEXT_SYMBOL_STRING,
} from './ReactSymbols';
import {format} from './utils';
import {enableStyleXFeatures} from 'react-devtools-feature-flags';
import is from 'shared/objectIs';
import hasOwnProperty from 'shared/hasOwnProperty';
@@ -851,7 +851,14 @@ export function attach(
return;
}
}
const message = format(...args);
// We can't really use this message as a unique key, since we can't distinguish
// different objects in this implementation. We have to delegate displaying of the objects
// to the environment, the browser console, for example, so this is why this should be kept
// as an array of arguments, instead of the plain string.
// [Warning: %o, {...}] and [Warning: %o, {...}] will be considered as the same message,
// even if objects are different
const message = formatConsoleArgumentsToSingleString(...args);
if (__DEBUG__) {
debug('onErrorOrWarning', fiber, null, `${type}: "${message}"`);
}
+64 -2
View File
@@ -164,6 +164,7 @@ export function serializeToString(data: any): string {
);
}
// NOTE: KEEP IN SYNC with src/hook.js
// Formats an array of args with a style for console methods, using
// the following algorithm:
// 1. The first param is a string that contains %c
@@ -220,11 +221,72 @@ export function formatWithStyles(
}
}
// NOTE: KEEP IN SYNC with src/hook.js
// Skips CSS and object arguments, inlines other in the first argument as a template string
export function formatConsoleArguments(
maybeMessage: any,
...inputArgs: $ReadOnlyArray<any>
): $ReadOnlyArray<any> {
if (inputArgs.length === 0 || typeof maybeMessage !== 'string') {
return [maybeMessage, ...inputArgs];
}
const args = inputArgs.slice();
let template = '';
let argumentsPointer = 0;
for (let i = 0; i < maybeMessage.length; ++i) {
const currentChar = maybeMessage[i];
if (currentChar !== '%') {
template += currentChar;
continue;
}
const nextChar = maybeMessage[i + 1];
++i;
// Only keep CSS and objects, inline other arguments
switch (nextChar) {
case 'c':
case 'O':
case 'o': {
++argumentsPointer;
template += `%${nextChar}`;
break;
}
case 'd':
case 'i': {
const [arg] = args.splice(argumentsPointer, 1);
template += parseInt(arg, 10).toString();
break;
}
case 'f': {
const [arg] = args.splice(argumentsPointer, 1);
template += parseFloat(arg).toString();
break;
}
case 's': {
const [arg] = args.splice(argumentsPointer, 1);
template += arg.toString();
break;
}
default:
template += `%${nextChar}`;
}
}
return [template, ...args];
}
// based on https://github.com/tmpfs/format-util/blob/0e62d430efb0a1c51448709abd3e2406c14d8401/format.js#L1
// based on https://developer.mozilla.org/en-US/docs/Web/API/console#Using_string_substitutions
// Implements s, d, i and f placeholders
// NOTE: KEEP IN SYNC with src/hook.js
export function format(
export function formatConsoleArgumentsToSingleString(
maybeMessage: any,
...inputArgs: $ReadOnlyArray<any>
): string {
@@ -13,7 +13,6 @@
* It should always be imported from "react-devtools-feature-flags".
************************************************************************/
export const consoleManagedByDevToolsDuringStrictMode = false;
export const enableLogger = true;
export const enableStyleXFeatures = true;
export const isInternalFacebookBuild = true;
@@ -13,7 +13,6 @@
* It should always be imported from "react-devtools-feature-flags".
************************************************************************/
export const consoleManagedByDevToolsDuringStrictMode = false;
export const enableLogger = false;
export const enableStyleXFeatures = false;
export const isInternalFacebookBuild = false;
@@ -13,7 +13,6 @@
* It should always be imported from "react-devtools-feature-flags".
************************************************************************/
export const consoleManagedByDevToolsDuringStrictMode = true;
export const enableLogger = false;
export const enableStyleXFeatures = false;
export const isInternalFacebookBuild = false;
@@ -13,7 +13,6 @@
* It should always be imported from "react-devtools-feature-flags".
************************************************************************/
export const consoleManagedByDevToolsDuringStrictMode = true;
export const enableLogger = true;
export const enableStyleXFeatures = true;
export const isInternalFacebookBuild = true;
@@ -13,7 +13,6 @@
* It should always be imported from "react-devtools-feature-flags".
************************************************************************/
export const consoleManagedByDevToolsDuringStrictMode = true;
export const enableLogger = false;
export const enableStyleXFeatures = false;
export const isInternalFacebookBuild = false;
+5 -14
View File
@@ -29,46 +29,37 @@ export const PROFILING_FLAG_BASIC_SUPPORT = 0b01;
export const PROFILING_FLAG_TIMELINE_SUPPORT = 0b10;
export const LOCAL_STORAGE_DEFAULT_TAB_KEY = 'React::DevTools::defaultTab';
export const LOCAL_STORAGE_COMPONENT_FILTER_PREFERENCES_KEY =
'React::DevTools::componentFilters';
export const SESSION_STORAGE_LAST_SELECTION_KEY =
'React::DevTools::lastSelection';
export const LOCAL_STORAGE_OPEN_IN_EDITOR_URL =
'React::DevTools::openInEditorUrl';
export const LOCAL_STORAGE_OPEN_IN_EDITOR_URL_PRESET =
'React::DevTools::openInEditorUrlPreset';
export const LOCAL_STORAGE_PARSE_HOOK_NAMES_KEY =
'React::DevTools::parseHookNames';
export const SESSION_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY =
'React::DevTools::recordChangeDescriptions';
export const SESSION_STORAGE_RELOAD_AND_PROFILE_KEY =
'React::DevTools::reloadAndProfile';
export const LOCAL_STORAGE_SHOULD_BREAK_ON_CONSOLE_ERRORS =
'React::DevTools::breakOnConsoleErrors';
export const LOCAL_STORAGE_BROWSER_THEME = 'React::DevTools::theme';
export const LOCAL_STORAGE_SHOULD_APPEND_COMPONENT_STACK_KEY =
'React::DevTools::appendComponentStack';
export const LOCAL_STORAGE_SHOW_INLINE_WARNINGS_AND_ERRORS_KEY =
'React::DevTools::showInlineWarningsAndErrors';
export const LOCAL_STORAGE_TRACE_UPDATES_ENABLED_KEY =
'React::DevTools::traceUpdatesEnabled';
export const LOCAL_STORAGE_HIDE_CONSOLE_LOGS_IN_STRICT_MODE =
'React::DevTools::hideConsoleLogsInStrictMode';
export const LOCAL_STORAGE_SUPPORTS_PROFILING_KEY =
'React::DevTools::supportsProfiling';
export const PROFILER_EXPORT_VERSION = 5;
export const FIREFOX_CONSOLE_DIMMING_COLOR = 'color: rgba(124, 124, 124, 0.75)';
export const ANSI_STYLE_DIMMING_TEMPLATE = '\x1b[2;38;2;124;124;124m%s\x1b[0m';
export const ANSI_STYLE_DIMMING_TEMPLATE_WITH_COMPONENT_STACK =
'\x1b[2;38;2;124;124;124m%s %s\x1b[0m';
+73 -40
View File
@@ -8,7 +8,6 @@
* @flow
*/
import type {BrowserTheme} from './frontend/types';
import type {
DevToolsHook,
Handler,
@@ -18,6 +17,11 @@ import type {
DevToolsBackend,
} from './backend/types';
import {
FIREFOX_CONSOLE_DIMMING_COLOR,
ANSI_STYLE_DIMMING_TEMPLATE,
} from 'react-devtools-shared/src/constants';
declare var window: any;
export function installHook(target: any): DevToolsHook | null {
@@ -216,6 +220,61 @@ export function installHook(target: any): DevToolsHook | null {
return [firstArg, style, ...inputArgs];
}
}
// NOTE: KEEP IN SYNC with src/backend/utils.js
function formatConsoleArguments(
maybeMessage: any,
...inputArgs: $ReadOnlyArray<any>
): $ReadOnlyArray<any> {
if (inputArgs.length === 0 || typeof maybeMessage !== 'string') {
return [maybeMessage, ...inputArgs];
}
const args = inputArgs.slice();
let template = '';
let argumentsPointer = 0;
for (let i = 0; i < maybeMessage.length; ++i) {
const currentChar = maybeMessage[i];
if (currentChar !== '%') {
template += currentChar;
continue;
}
const nextChar = maybeMessage[i + 1];
++i;
// Only keep CSS and objects, inline other arguments
switch (nextChar) {
case 'c':
case 'O':
case 'o': {
++argumentsPointer;
template += `%${nextChar}`;
break;
}
case 'd':
case 'i': {
const [arg] = args.splice(argumentsPointer, 1);
template += parseInt(arg, 10).toString();
break;
}
case 'f': {
const [arg] = args.splice(argumentsPointer, 1);
template += parseFloat(arg).toString();
break;
}
case 's': {
const [arg] = args.splice(argumentsPointer, 1);
template += arg.toString();
}
}
}
return [template, ...args];
}
let unpatchFn = null;
@@ -225,13 +284,9 @@ export function installHook(target: any): DevToolsHook | null {
// React and DevTools are connecting and the renderer interface isn't avaiable
// and we want to be able to have consistent logging behavior for double logs
// during the initial renderer.
function patchConsoleForInitialCommitInStrictMode({
hideConsoleLogsInStrictMode,
browserTheme,
}: {
function patchConsoleForInitialCommitInStrictMode(
hideConsoleLogsInStrictMode: boolean,
browserTheme: BrowserTheme,
}) {
) {
const overrideConsoleMethods = [
'error',
'group',
@@ -266,36 +321,18 @@ export function installHook(target: any): DevToolsHook | null {
: targetConsole[method]);
const overrideMethod = (...args: $ReadOnlyArray<any>) => {
// Dim the text color of the double logs if we're not hiding them.
if (!hideConsoleLogsInStrictMode) {
// Dim the text color of the double logs if we're not
// hiding them.
let color;
switch (method) {
case 'warn':
color =
browserTheme === 'light'
? process.env.LIGHT_MODE_DIMMED_WARNING_COLOR
: process.env.DARK_MODE_DIMMED_WARNING_COLOR;
break;
case 'error':
color =
browserTheme === 'light'
? process.env.LIGHT_MODE_DIMMED_ERROR_COLOR
: process.env.DARK_MODE_DIMMED_ERROR_COLOR;
break;
case 'log':
default:
color =
browserTheme === 'light'
? process.env.LIGHT_MODE_DIMMED_LOG_COLOR
: process.env.DARK_MODE_DIMMED_LOG_COLOR;
break;
}
if (color) {
originalMethod(...formatWithStyles(args, `color: ${color}`));
// Firefox doesn't support ANSI escape sequences
if (__IS_FIREFOX__) {
originalMethod(
...formatWithStyles(args, FIREFOX_CONSOLE_DIMMING_COLOR),
);
} else {
throw Error('Console color is not defined');
originalMethod(
ANSI_STYLE_DIMMING_TEMPLATE,
...formatConsoleArguments(...args),
);
}
}
};
@@ -456,12 +493,8 @@ export function installHook(target: any): DevToolsHook | null {
if (isStrictMode) {
const hideConsoleLogsInStrictMode =
window.__REACT_DEVTOOLS_HIDE_CONSOLE_LOGS_IN_STRICT_MODE__ === true;
const browserTheme = window.__REACT_DEVTOOLS_BROWSER_THEME__;
patchConsoleForInitialCommitInStrictMode({
hideConsoleLogsInStrictMode,
browserTheme,
});
patchConsoleForInitialCommitInStrictMode(hideConsoleLogsInStrictMode);
} else {
unpatchConsoleForInitialCommitInStrictMode();
}
-12
View File
@@ -2,12 +2,6 @@ const {resolve} = require('path');
const Webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const {
DARK_MODE_DIMMED_WARNING_COLOR,
DARK_MODE_DIMMED_ERROR_COLOR,
DARK_MODE_DIMMED_LOG_COLOR,
LIGHT_MODE_DIMMED_WARNING_COLOR,
LIGHT_MODE_DIMMED_ERROR_COLOR,
LIGHT_MODE_DIMMED_LOG_COLOR,
GITHUB_URL,
getVersionString,
} = require('react-devtools-extensions/utils');
@@ -81,12 +75,6 @@ const makeConfig = (entry, alias) => ({
'process.env.EDITOR_URL': EDITOR_URL != null ? `"${EDITOR_URL}"` : null,
'process.env.DEVTOOLS_PACKAGE': `"react-devtools-shell"`,
'process.env.DEVTOOLS_VERSION': `"${DEVTOOLS_VERSION}"`,
'process.env.DARK_MODE_DIMMED_WARNING_COLOR': `"${DARK_MODE_DIMMED_WARNING_COLOR}"`,
'process.env.DARK_MODE_DIMMED_ERROR_COLOR': `"${DARK_MODE_DIMMED_ERROR_COLOR}"`,
'process.env.DARK_MODE_DIMMED_LOG_COLOR': `"${DARK_MODE_DIMMED_LOG_COLOR}"`,
'process.env.LIGHT_MODE_DIMMED_WARNING_COLOR': `"${LIGHT_MODE_DIMMED_WARNING_COLOR}"`,
'process.env.LIGHT_MODE_DIMMED_ERROR_COLOR': `"${LIGHT_MODE_DIMMED_ERROR_COLOR}"`,
'process.env.LIGHT_MODE_DIMMED_LOG_COLOR': `"${LIGHT_MODE_DIMMED_LOG_COLOR}"`,
'process.env.E2E_APP_REACT_VERSION': `"${REACT_VERSION}"`,
}),
],
@@ -1,7 +1,7 @@
{
"private": true,
"name": "react-devtools-timeline",
"version": "5.2.0",
"version": "5.3.0",
"license": "MIT",
"dependencies": {
"@elg/speedscope": "1.9.0-a6f84db",
+16
View File
@@ -4,6 +4,22 @@
---
### 5.3.0
June 17, 2024
* chore[react-devtools]: improve console arguments formatting before passing it to original console ([hoxyq](https://github.com/hoxyq) in [#29873](https://github.com/facebook/react/pull/29873))
* chore[react-devtools]: unify console patching and default to ansi escape symbols ([hoxyq](https://github.com/hoxyq) in [#29869](https://github.com/facebook/react/pull/29869))
* chore[react-devtools/extensions]: make source maps url relative ([hoxyq](https://github.com/hoxyq) in [#29886](https://github.com/facebook/react/pull/29886))
* fix[react-devtools] divided inspecting elements between inspecting do… ([vzaidman](https://github.com/vzaidman) in [#29885](https://github.com/facebook/react/pull/29885))
* fix[react-devtools] component badge in light mode is now not invisible ([vzaidman](https://github.com/vzaidman) in [#29852](https://github.com/facebook/react/pull/29852))
* fix[react-devtools] remove native inspection button when it can't be used ([vzaidman](https://github.com/vzaidman) in [#29779](https://github.com/facebook/react/pull/29779))
* chore[react-devtools]: ip => internal-ip ([hoxyq](https://github.com/hoxyq) in [#29772](https://github.com/facebook/react/pull/29772))
* Fix #29724: `ip` dependency update for CVE-2024-29415 ([Rekl0w](https://github.com/Rekl0w) in [#29725](https://github.com/facebook/react/pull/29725))
* Dim `console` calls on additional Effect invocations due to `StrictMode` ([eps1lon](https://github.com/eps1lon) in [#29007](https://github.com/facebook/react/pull/29007))
* refactor[react-devtools]: rewrite context menus ([hoxyq](https://github.com/hoxyq) in [#29049](https://github.com/facebook/react/pull/29049))
---
### 5.2.0
May 8, 2024
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "react-devtools",
"version": "5.2.0",
"version": "5.3.0",
"description": "Use react-devtools outside of the browser",
"license": "MIT",
"repository": {
@@ -27,7 +27,7 @@
"electron": "^23.1.2",
"internal-ip": "^6.2.0",
"minimist": "^1.2.3",
"react-devtools-core": "5.2.0",
"react-devtools-core": "5.3.0",
"update-notifier": "^2.1.0"
}
}
+1 -1
View File
@@ -44,7 +44,7 @@ export function getCurrentParentStackInDev(): string {
return '';
}
function getCurrentFiberStackInDev(stack: Error): string {
function getCurrentFiberStackInDev(stack: null | Error): string {
if (__DEV__) {
if (current === null) {
return '';
@@ -0,0 +1,65 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
* @jest-environment node
*/
'use strict';
let React;
let ReactNoop;
let act;
describe('ReactOwnerStacks', () => {
beforeEach(function () {
jest.resetModules();
React = require('react');
ReactNoop = require('react-noop-renderer');
act = require('internal-test-utils').act;
});
function normalizeCodeLocInfo(str) {
return (
str &&
str.replace(/\n +(?:at|in) ([\S]+)[^\n]*/g, function (m, name) {
return '\n in ' + name + ' (at **)';
})
);
}
// @gate __DEV__ && enableOwnerStacks
it('can get the component owner stacks during rendering in dev', async () => {
let stack;
function Foo() {
return <Bar />;
}
function Bar() {
return (
<div>
<Baz />
</div>
);
}
function Baz() {
stack = React.captureOwnerStack();
return <span>hi</span>;
}
await act(() => {
ReactNoop.render(
<div>
<Foo />
</div>,
);
});
expect(normalizeCodeLocInfo(stack)).toBe(
'\n in Bar (at **)' + '\n in Foo (at **)',
);
});
});
+1
View File
@@ -61,6 +61,7 @@ import {
disableLegacyMode,
} from 'shared/ReactFeatureFlags';
// $FlowFixMe[prop-missing]: This is only in the development export.
const act = React.act;
// TODO: Remove from public bundle
+80
View File
@@ -0,0 +1,80 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
// Keep in sync with https://github.com/facebook/flow/blob/main/lib/react.js
export type ComponentType<-P> = React$ComponentType<P>;
export type AbstractComponent<
-Config,
+Instance = mixed,
> = React$AbstractComponent<Config, Instance>;
export type ElementType = React$ElementType;
export type Element<+C> = React$Element<C>;
export type Key = React$Key;
export type Ref<C> = React$Ref<C>;
export type Node = React$Node;
export type Context<T> = React$Context<T>;
export type Portal = React$Portal;
export type ElementProps<C> = React$ElementProps<C>;
export type ElementConfig<C> = React$ElementConfig<C>;
export type ElementRef<C> = React$ElementRef<C>;
export type Config<Props, DefaultProps> = React$Config<Props, DefaultProps>;
export type ChildrenArray<+T> = $ReadOnlyArray<ChildrenArray<T>> | T;
// Export all exports so that they're available in tests.
// We can't use export * from in Flow for some reason.
export {
__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,
Children,
Component,
Fragment,
Profiler,
PureComponent,
StrictMode,
Suspense,
cloneElement,
createContext,
createElement,
createRef,
use,
forwardRef,
isValidElement,
lazy,
memo,
cache,
startTransition,
unstable_DebugTracingMode,
unstable_LegacyHidden,
unstable_Activity,
unstable_Scope,
unstable_SuspenseList,
unstable_TracingMarker,
unstable_getCacheForType,
unstable_useCacheRefresh,
useId,
useCallback,
useContext,
useDebugValue,
useDeferredValue,
useEffect,
experimental_useEffectEvent,
useImperativeHandle,
useInsertionEffect,
useLayoutEffect,
useMemo,
useOptimistic,
useSyncExternalStore,
useReducer,
useRef,
useState,
useTransition,
useActionState,
version,
act, // DEV-only
captureOwnerStack, // DEV-only
} from './src/ReactClient';
@@ -0,0 +1,72 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
export {
__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,
Children,
Component,
Fragment,
Profiler,
PureComponent,
StrictMode,
Suspense,
cloneElement,
createContext,
createElement,
createRef,
use,
forwardRef,
isValidElement,
lazy,
memo,
cache,
startTransition,
unstable_DebugTracingMode,
unstable_Activity,
unstable_postpone,
unstable_getCacheForType,
unstable_SuspenseList,
unstable_useCacheRefresh,
useId,
useCallback,
useContext,
useDebugValue,
useDeferredValue,
useEffect,
experimental_useEffectEvent,
useImperativeHandle,
useInsertionEffect,
useLayoutEffect,
useMemo,
useOptimistic,
useReducer,
useRef,
useState,
useSyncExternalStore,
useTransition,
useActionState,
version,
act, // DEV-only
captureOwnerStack, // DEV-only
} from './src/ReactClient';
import {useOptimistic} from './src/ReactClient';
export function experimental_useOptimistic<S, A>(
passthrough: S,
reducer: ?(S, A) => S,
): [S, (A) => void] {
if (__DEV__) {
console.error(
'useOptimistic is now in canary. Remove the experimental_ prefix. ' +
'The prefixed alias will be removed in an upcoming release.',
);
}
return useOptimistic(passthrough, reducer);
}
-1
View File
@@ -9,7 +9,6 @@
export {
__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,
act,
Children,
Component,
Fragment,
-1
View File
@@ -30,7 +30,6 @@ export type ChildrenArray<+T> = $ReadOnlyArray<ChildrenArray<T>> | T;
// We can't use export * from in Flow for some reason.
export {
__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,
act,
Children,
Component,
Fragment,
+3 -1
View File
@@ -61,6 +61,7 @@ import {
import ReactSharedInternals from './ReactSharedInternalsClient';
import {startTransition} from './ReactStartTransition';
import {act} from './ReactAct';
import {captureOwnerStack} from './ReactOwnerStack';
const Children = {
map,
@@ -121,5 +122,6 @@ export {
// enableTransitionTracing
REACT_TRACING_MARKER_TYPE as unstable_TracingMarker,
useId,
act,
act, // DEV-only
captureOwnerStack, // DEV-only
};
+24
View File
@@ -0,0 +1,24 @@
/**
* Copyright (c) Meta Platforms, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import {enableOwnerStacks} from 'shared/ReactFeatureFlags';
import ReactSharedInternals from 'shared/ReactSharedInternals';
export function captureOwnerStack(): null | string {
if (!enableOwnerStacks || !__DEV__) {
return null;
}
const getCurrentStack = ReactSharedInternals.getCurrentStack;
if (getCurrentStack === null) {
return null;
}
// The current stack will be the owner stack if enableOwnerStacks is true
// which it is always here. Otherwise it's the parent stack.
return getCurrentStack(null);
}
@@ -0,0 +1,85 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
export {default as __SERVER_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE} from './ReactSharedInternalsServer';
import {forEach, map, count, toArray, only} from './ReactChildren';
import {
REACT_FRAGMENT_TYPE,
REACT_PROFILER_TYPE,
REACT_STRICT_MODE_TYPE,
REACT_SUSPENSE_TYPE,
REACT_DEBUG_TRACING_MODE_TYPE,
} from 'shared/ReactSymbols';
import {
cloneElement,
createElement,
isValidElement,
} from './jsx/ReactJSXElement';
import {createRef} from './ReactCreateRef';
import {
use,
useId,
useCallback,
useDebugValue,
useMemo,
useActionState,
getCacheForType,
} from './ReactHooks';
import {forwardRef} from './ReactForwardRef';
import {lazy} from './ReactLazy';
import {memo} from './ReactMemo';
import {cache} from './ReactCacheServer';
import {startTransition} from './ReactStartTransition';
import {postpone} from './ReactPostpone';
import {captureOwnerStack} from './ReactOwnerStack';
import version from 'shared/ReactVersion';
const Children = {
map,
forEach,
count,
toArray,
only,
};
// These are server-only
export {
taintUniqueValue as experimental_taintUniqueValue,
taintObjectReference as experimental_taintObjectReference,
} from './ReactTaint';
export {
Children,
REACT_FRAGMENT_TYPE as Fragment,
REACT_PROFILER_TYPE as Profiler,
REACT_STRICT_MODE_TYPE as StrictMode,
REACT_SUSPENSE_TYPE as Suspense,
cloneElement,
createElement,
createRef,
use,
forwardRef,
isValidElement,
lazy,
memo,
cache,
startTransition,
REACT_DEBUG_TRACING_MODE_TYPE as unstable_DebugTracingMode,
REACT_SUSPENSE_TYPE as unstable_SuspenseList,
getCacheForType as unstable_getCacheForType,
postpone as unstable_postpone,
useId,
useCallback,
useDebugValue,
useMemo,
useActionState,
version,
captureOwnerStack, // DEV-only
};
@@ -35,7 +35,7 @@ export type SharedStateClient = {
thrownErrors: Array<mixed>,
// ReactDebugCurrentFrame
getCurrentStack: null | ((stack: Error) => string),
getCurrentStack: null | ((stack: null | Error) => string),
};
export type RendererTask = boolean => RendererTask | null;
@@ -56,7 +56,7 @@ if (__DEV__) {
// Stack implementation injected by the current renderer.
ReactSharedInternals.getCurrentStack = (null:
| null
| ((stack: Error) => string));
| ((stack: null | Error) => string));
}
export default ReactSharedInternals;
@@ -38,7 +38,7 @@ export type SharedStateServer = {
// DEV-only
// ReactDebugCurrentFrame
getCurrentStack: null | ((stack: Error) => string),
getCurrentStack: null | ((stack: null | Error) => string),
};
export type RendererTask = boolean => RendererTask | null;
@@ -60,7 +60,7 @@ if (__DEV__) {
// Stack implementation injected by the current renderer.
ReactSharedInternals.getCurrentStack = (null:
| null
| ((stack: Error) => string));
| ((stack: null | Error) => string));
}
export default ReactSharedInternals;
+1 -6
View File
@@ -12,9 +12,4 @@
declare const __EXTENSION__: boolean;
declare const __TEST__: boolean;
declare const DARK_MODE_DIMMED_WARNING_COLOR: string;
declare const DARK_MODE_DIMMED_ERROR_COLOR: string;
declare const DARK_MODE_DIMMED_LOG_COLOR: string;
declare const LIGHT_MODE_DIMMED_WARNING_COLOR: string;
declare const LIGHT_MODE_DIMMED_ERROR_COLOR: string;
declare const LIGHT_MODE_DIMMED_LOG_COLOR: string;
declare const __IS_FIREFOX__: boolean;
+1 -19
View File
@@ -3,15 +3,6 @@
const semver = require('semver');
const {ReactVersion} = require('../../../ReactVersions');
const {
DARK_MODE_DIMMED_WARNING_COLOR,
DARK_MODE_DIMMED_ERROR_COLOR,
DARK_MODE_DIMMED_LOG_COLOR,
LIGHT_MODE_DIMMED_WARNING_COLOR,
LIGHT_MODE_DIMMED_ERROR_COLOR,
LIGHT_MODE_DIMMED_LOG_COLOR,
} = require('react-devtools-extensions/utils');
// DevTools stores preferences between sessions in localStorage
if (!global.hasOwnProperty('localStorage')) {
global.localStorage = require('local-storage-fallback').default;
@@ -20,16 +11,7 @@ if (!global.hasOwnProperty('localStorage')) {
// Mimic the global we set with Webpack's DefinePlugin
global.__DEV__ = process.env.NODE_ENV !== 'production';
global.__TEST__ = true;
global.process.env.DARK_MODE_DIMMED_WARNING_COLOR =
DARK_MODE_DIMMED_WARNING_COLOR;
global.process.env.DARK_MODE_DIMMED_ERROR_COLOR = DARK_MODE_DIMMED_ERROR_COLOR;
global.process.env.DARK_MODE_DIMMED_LOG_COLOR = DARK_MODE_DIMMED_LOG_COLOR;
global.process.env.LIGHT_MODE_DIMMED_WARNING_COLOR =
LIGHT_MODE_DIMMED_WARNING_COLOR;
global.process.env.LIGHT_MODE_DIMMED_ERROR_COLOR =
LIGHT_MODE_DIMMED_ERROR_COLOR;
global.process.env.LIGHT_MODE_DIMMED_LOG_COLOR = LIGHT_MODE_DIMMED_LOG_COLOR;
global.__IS_FIREFOX__ = false;
const ReactVersionTestingAgainst = process.env.REACT_VERSION || ReactVersion;
+24 -3
View File
@@ -12,6 +12,8 @@ function resolveEntryFork(resolvedEntry, isFBBundle) {
// .stable.js
// .experimental.js
// .js
// or any of those plus .development.js
if (isFBBundle) {
// FB builds for react-dom need to alias both react-dom and react-dom/client to the same
// entrypoint since there is only a single build for them.
@@ -41,6 +43,10 @@ function resolveEntryFork(resolvedEntry, isFBBundle) {
}
resolvedEntry = nodePath.join(resolvedEntry, '..', entrypoint);
const developmentEntry = resolvedEntry.replace('.js', '.development.js');
if (fs.existsSync(developmentEntry)) {
return developmentEntry;
}
if (fs.existsSync(resolvedEntry)) {
return resolvedEntry;
}
@@ -53,6 +59,10 @@ function resolveEntryFork(resolvedEntry, isFBBundle) {
'.js',
__EXPERIMENTAL__ ? '.modern.fb.js' : '.classic.fb.js'
);
const devFBEntry = resolvedFBEntry.replace('.js', '.development.js');
if (fs.existsSync(devFBEntry)) {
return devFBEntry;
}
if (fs.existsSync(resolvedFBEntry)) {
return resolvedFBEntry;
}
@@ -66,9 +76,17 @@ function resolveEntryFork(resolvedEntry, isFBBundle) {
'.js',
__EXPERIMENTAL__ ? '.experimental.js' : '.stable.js'
);
const devForkedEntry = resolvedForkedEntry.replace('.js', '.development.js');
if (fs.existsSync(devForkedEntry)) {
return devForkedEntry;
}
if (fs.existsSync(resolvedForkedEntry)) {
return resolvedForkedEntry;
}
const plainDevEntry = resolvedEntry.replace('.js', '.development.js');
if (fs.existsSync(plainDevEntry)) {
return plainDevEntry;
}
// Just use the plain .js one.
return resolvedEntry;
}
@@ -77,7 +95,8 @@ function mockReact() {
jest.mock('react', () => {
const resolvedEntryPoint = resolveEntryFork(
require.resolve('react'),
global.__WWW__ || global.__XPLAT__
global.__WWW__ || global.__XPLAT__,
global.__DEV__
);
return jest.requireActual(resolvedEntryPoint);
});
@@ -100,7 +119,8 @@ jest.mock('react/react.react-server', () => {
});
const resolvedEntryPoint = resolveEntryFork(
require.resolve('react/src/ReactServer'),
global.__WWW__ || global.__XPLAT__
global.__WWW__ || global.__XPLAT__,
global.__DEV__
);
return jest.requireActual(resolvedEntryPoint);
});
@@ -198,7 +218,8 @@ inlinedHostConfigs.forEach(rendererInfo => {
mockAllConfigs(rendererInfo);
const resolvedEntryPoint = resolveEntryFork(
require.resolve(entryPoint),
global.__WWW__ || global.__XPLAT__
global.__WWW__ || global.__XPLAT__,
global.__DEV__
);
return jest.requireActual(resolvedEntryPoint);
});
+1
View File
@@ -55,6 +55,7 @@ const files = glob
ignore: [
'**/node_modules/**',
'**/cjs/**',
'compiler/**',
...ignoredPathsListedInPrettierIgnoreInGlobFormat,
],
})
+26 -4
View File
@@ -85,9 +85,11 @@ function parseRequestedNames(names, toCase) {
return result;
}
const argvType = Array.isArray(argv.type) ? argv.type : [argv.type];
const requestedBundleTypes = argv.type
? parseRequestedNames([argv.type], 'uppercase')
? parseRequestedNames(argvType, 'uppercase')
: [];
const requestedBundleNames = parseRequestedNames(argv._, 'lowercase');
const forcePrettyOutput = argv.pretty;
const isWatchMode = argv.watch;
@@ -528,8 +530,8 @@ function shouldSkipBundle(bundle, bundleType) {
return true;
}
if (requestedBundleTypes.length > 0) {
const isAskingForDifferentType = requestedBundleTypes.every(
requestedType => bundleType.indexOf(requestedType) === -1
const isAskingForDifferentType = requestedBundleTypes.some(
requestedType => !bundleType.includes(requestedType)
);
if (isAskingForDifferentType) {
return true;
@@ -567,16 +569,31 @@ function resolveEntryFork(resolvedEntry, isFBBundle) {
// .stable.js
// .experimental.js
// .js
// or any of those plus .development.js
if (isFBBundle) {
const resolvedFBEntry = resolvedEntry.replace(
'.js',
__EXPERIMENTAL__ ? '.modern.fb.js' : '.classic.fb.js'
);
const developmentFBEntry = resolvedFBEntry.replace(
'.js',
'.development.js'
);
if (fs.existsSync(developmentFBEntry)) {
return developmentFBEntry;
}
if (fs.existsSync(resolvedFBEntry)) {
return resolvedFBEntry;
}
const resolvedGenericFBEntry = resolvedEntry.replace('.js', '.fb.js');
const developmentGenericFBEntry = resolvedGenericFBEntry.replace(
'.js',
'.development.js'
);
if (fs.existsSync(developmentGenericFBEntry)) {
return developmentGenericFBEntry;
}
if (fs.existsSync(resolvedGenericFBEntry)) {
return resolvedGenericFBEntry;
}
@@ -586,6 +603,10 @@ function resolveEntryFork(resolvedEntry, isFBBundle) {
'.js',
__EXPERIMENTAL__ ? '.experimental.js' : '.stable.js'
);
const devForkedEntry = resolvedForkedEntry.replace('.js', '.development.js');
if (fs.existsSync(devForkedEntry)) {
return devForkedEntry;
}
if (fs.existsSync(resolvedForkedEntry)) {
return resolvedForkedEntry;
}
@@ -604,7 +625,8 @@ async function createBundle(bundle, bundleType) {
let resolvedEntry = resolveEntryFork(
require.resolve(bundle.entry),
isFBWWWBundle || isFBRNBundle
isFBWWWBundle || isFBRNBundle,
!isProductionBundleType(bundleType)
);
const peerGlobals = Modules.getPeerGlobals(bundle.externals, bundleType);