-
Notifications
You must be signed in to change notification settings - Fork 47.2k
/
ReactDebugHooks.js
707 lines (647 loc) · 20.3 KB
/
ReactDebugHooks.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
/**
* Copyright (c) Facebook, 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 type {
MutableSource,
MutableSourceGetSnapshotFn,
MutableSourceSubscribeFn,
ReactContext,
ReactProviderType,
} from 'shared/ReactTypes';
import type {
Fiber,
Dispatcher as DispatcherType,
} from 'react-reconciler/src/ReactInternalTypes';
import type {OpaqueIDType} from 'react-reconciler/src/ReactFiberHostConfig';
import {NoMode} from 'react-reconciler/src/ReactTypeOfMode';
import ErrorStackParser from 'error-stack-parser';
import invariant from 'shared/invariant';
import ReactSharedInternals from 'shared/ReactSharedInternals';
import {REACT_OPAQUE_ID_TYPE} from 'shared/ReactSymbols';
import {
FunctionComponent,
SimpleMemoComponent,
ContextProvider,
ForwardRef,
} from 'react-reconciler/src/ReactWorkTags';
type CurrentDispatcherRef = typeof ReactSharedInternals.ReactCurrentDispatcher;
// Used to track hooks called during a render
type HookLogEntry = {
primitive: string,
stackError: Error,
value: mixed,
...
};
let hookLog: Array<HookLogEntry> = [];
// Primitives
type BasicStateAction<S> = (S => S) | S;
type Dispatch<A> = A => void;
let primitiveStackCache: null | Map<string, Array<any>> = null;
let currentFiber: Fiber | null = null;
type Hook = {
memoizedState: any,
next: Hook | null,
};
function getPrimitiveStackCache(): Map<string, Array<any>> {
// This initializes a cache of all primitive hooks so that the top
// most stack frames added by calling the primitive hook can be removed.
if (primitiveStackCache === null) {
const cache = new Map();
let readHookLog;
try {
// Use all hooks here to add them to the hook log.
Dispatcher.useContext(({_currentValue: null}: any));
Dispatcher.useState(null);
Dispatcher.useReducer((s, a) => s, null);
Dispatcher.useRef(null);
Dispatcher.useLayoutEffect(() => {});
Dispatcher.useEffect(() => {});
Dispatcher.useImperativeHandle(undefined, () => null);
Dispatcher.useDebugValue(null);
Dispatcher.useCallback(() => {});
Dispatcher.useMemo(() => null);
} finally {
readHookLog = hookLog;
hookLog = [];
}
for (let i = 0; i < readHookLog.length; i++) {
const hook = readHookLog[i];
cache.set(hook.primitive, ErrorStackParser.parse(hook.stackError));
}
primitiveStackCache = cache;
}
return primitiveStackCache;
}
let currentHook: null | Hook = null;
function nextHook(): null | Hook {
const hook = currentHook;
if (hook !== null) {
currentHook = hook.next;
}
return hook;
}
function getCacheForType<T>(resourceType: () => T): T {
invariant(false, 'Not implemented.');
}
function readContext<T>(
context: ReactContext<T>,
observedBits: void | number | boolean,
): T {
// For now we don't expose readContext usage in the hooks debugging info.
return context._currentValue;
}
function useContext<T>(
context: ReactContext<T>,
observedBits: void | number | boolean,
): T {
hookLog.push({
primitive: 'Context',
stackError: new Error(),
value: context._currentValue,
});
return context._currentValue;
}
function useState<S>(
initialState: (() => S) | S,
): [S, Dispatch<BasicStateAction<S>>] {
const hook = nextHook();
const state: S =
hook !== null
? hook.memoizedState
: typeof initialState === 'function'
? // $FlowFixMe: Flow doesn't like mixed types
initialState()
: initialState;
hookLog.push({primitive: 'State', stackError: new Error(), value: state});
return [state, (action: BasicStateAction<S>) => {}];
}
function useReducer<S, I, A>(
reducer: (S, A) => S,
initialArg: I,
init?: I => S,
): [S, Dispatch<A>] {
const hook = nextHook();
let state;
if (hook !== null) {
state = hook.memoizedState;
} else {
state = init !== undefined ? init(initialArg) : ((initialArg: any): S);
}
hookLog.push({
primitive: 'Reducer',
stackError: new Error(),
value: state,
});
return [state, (action: A) => {}];
}
function useRef<T>(initialValue: T): {|current: T|} {
const hook = nextHook();
const ref = hook !== null ? hook.memoizedState : {current: initialValue};
hookLog.push({
primitive: 'Ref',
stackError: new Error(),
value: ref.current,
});
return ref;
}
function useLayoutEffect(
create: () => (() => void) | void,
inputs: Array<mixed> | void | null,
): void {
nextHook();
hookLog.push({
primitive: 'LayoutEffect',
stackError: new Error(),
value: create,
});
}
function useEffect(
create: () => (() => void) | void,
inputs: Array<mixed> | void | null,
): void {
nextHook();
hookLog.push({primitive: 'Effect', stackError: new Error(), value: create});
}
function useImperativeHandle<T>(
ref: {|current: T | null|} | ((inst: T | null) => mixed) | null | void,
create: () => T,
inputs: Array<mixed> | void | null,
): void {
nextHook();
// We don't actually store the instance anywhere if there is no ref callback
// and if there is a ref callback it might not store it but if it does we
// have no way of knowing where. So let's only enable introspection of the
// ref itself if it is using the object form.
let instance = undefined;
if (ref !== null && typeof ref === 'object') {
instance = ref.current;
}
hookLog.push({
primitive: 'ImperativeHandle',
stackError: new Error(),
value: instance,
});
}
function useDebugValue(value: any, formatterFn: ?(value: any) => any) {
hookLog.push({
primitive: 'DebugValue',
stackError: new Error(),
value: typeof formatterFn === 'function' ? formatterFn(value) : value,
});
}
function useCallback<T>(callback: T, inputs: Array<mixed> | void | null): T {
const hook = nextHook();
hookLog.push({
primitive: 'Callback',
stackError: new Error(),
value: hook !== null ? hook.memoizedState[0] : callback,
});
return callback;
}
function useMemo<T>(
nextCreate: () => T,
inputs: Array<mixed> | void | null,
): T {
const hook = nextHook();
const value = hook !== null ? hook.memoizedState[0] : nextCreate();
hookLog.push({primitive: 'Memo', stackError: new Error(), value});
return value;
}
function useMutableSource<Source, Snapshot>(
source: MutableSource<Source>,
getSnapshot: MutableSourceGetSnapshotFn<Source, Snapshot>,
subscribe: MutableSourceSubscribeFn<Source, Snapshot>,
): Snapshot {
// useMutableSource() composes multiple hooks internally.
// Advance the current hook index the same number of times
// so that subsequent hooks have the right memoized state.
nextHook(); // MutableSource
nextHook(); // State
nextHook(); // Effect
nextHook(); // Effect
const value = getSnapshot(source._source);
hookLog.push({primitive: 'MutableSource', stackError: new Error(), value});
return value;
}
function useTransition(): [(() => void) => void, boolean] {
// useTransition() composes multiple hooks internally.
// Advance the current hook index the same number of times
// so that subsequent hooks have the right memoized state.
nextHook(); // State
nextHook(); // Callback
hookLog.push({
primitive: 'Transition',
stackError: new Error(),
value: undefined,
});
return [callback => {}, false];
}
function useDeferredValue<T>(value: T): T {
// useDeferredValue() composes multiple hooks internally.
// Advance the current hook index the same number of times
// so that subsequent hooks have the right memoized state.
nextHook(); // State
nextHook(); // Effect
hookLog.push({
primitive: 'DeferredValue',
stackError: new Error(),
value,
});
return value;
}
function useOpaqueIdentifier(): OpaqueIDType | void {
const hook = nextHook(); // State
if (currentFiber && currentFiber.mode === NoMode) {
nextHook(); // Effect
}
let value = hook === null ? undefined : hook.memoizedState;
if (value && value.$$typeof === REACT_OPAQUE_ID_TYPE) {
value = undefined;
}
hookLog.push({
primitive: 'OpaqueIdentifier',
stackError: new Error(),
value,
});
return value;
}
const Dispatcher: DispatcherType = {
getCacheForType,
readContext,
useCallback,
useContext,
useEffect,
useImperativeHandle,
useDebugValue,
useLayoutEffect,
useMemo,
useReducer,
useRef,
useState,
useTransition,
useMutableSource,
useDeferredValue,
useOpaqueIdentifier,
};
// Inspect
export type HooksNode = {
id: number | null,
isStateEditable: boolean,
name: string,
value: mixed,
subHooks: Array<HooksNode>,
...
};
export type HooksTree = Array<HooksNode>;
// Don't assume
//
// We can't assume that stack frames are nth steps away from anything.
// E.g. we can't assume that the root call shares all frames with the stack
// of a hook call. A simple way to demonstrate this is wrapping `new Error()`
// in a wrapper constructor like a polyfill. That'll add an extra frame.
// Similar things can happen with the call to the dispatcher. The top frame
// may not be the primitive. Likewise the primitive can have fewer stack frames
// such as when a call to useState got inlined to use dispatcher.useState.
//
// We also can't assume that the last frame of the root call is the same
// frame as the last frame of the hook call because long stack traces can be
// truncated to a stack trace limit.
let mostLikelyAncestorIndex = 0;
function findSharedIndex(hookStack, rootStack, rootIndex) {
const source = rootStack[rootIndex].source;
hookSearch: for (let i = 0; i < hookStack.length; i++) {
if (hookStack[i].source === source) {
// This looks like a match. Validate that the rest of both stack match up.
for (
let a = rootIndex + 1, b = i + 1;
a < rootStack.length && b < hookStack.length;
a++, b++
) {
if (hookStack[b].source !== rootStack[a].source) {
// If not, give up and try a different match.
continue hookSearch;
}
}
return i;
}
}
return -1;
}
function findCommonAncestorIndex(rootStack, hookStack) {
let rootIndex = findSharedIndex(
hookStack,
rootStack,
mostLikelyAncestorIndex,
);
if (rootIndex !== -1) {
return rootIndex;
}
// If the most likely one wasn't a hit, try any other frame to see if it is shared.
// If that takes more than 5 frames, something probably went wrong.
for (let i = 0; i < rootStack.length && i < 5; i++) {
rootIndex = findSharedIndex(hookStack, rootStack, i);
if (rootIndex !== -1) {
mostLikelyAncestorIndex = i;
return rootIndex;
}
}
return -1;
}
function isReactWrapper(functionName, primitiveName) {
if (!functionName) {
return false;
}
const expectedPrimitiveName = 'use' + primitiveName;
if (functionName.length < expectedPrimitiveName.length) {
return false;
}
return (
functionName.lastIndexOf(expectedPrimitiveName) ===
functionName.length - expectedPrimitiveName.length
);
}
function findPrimitiveIndex(hookStack, hook) {
const stackCache = getPrimitiveStackCache();
const primitiveStack = stackCache.get(hook.primitive);
if (primitiveStack === undefined) {
return -1;
}
for (let i = 0; i < primitiveStack.length && i < hookStack.length; i++) {
if (primitiveStack[i].source !== hookStack[i].source) {
// If the next two frames are functions called `useX` then we assume that they're part of the
// wrappers that the React packager or other packages adds around the dispatcher.
if (
i < hookStack.length - 1 &&
isReactWrapper(hookStack[i].functionName, hook.primitive)
) {
i++;
}
if (
i < hookStack.length - 1 &&
isReactWrapper(hookStack[i].functionName, hook.primitive)
) {
i++;
}
return i;
}
}
return -1;
}
function parseTrimmedStack(rootStack, hook) {
// Get the stack trace between the primitive hook function and
// the root function call. I.e. the stack frames of custom hooks.
const hookStack = ErrorStackParser.parse(hook.stackError);
const rootIndex = findCommonAncestorIndex(rootStack, hookStack);
const primitiveIndex = findPrimitiveIndex(hookStack, hook);
if (
rootIndex === -1 ||
primitiveIndex === -1 ||
rootIndex - primitiveIndex < 2
) {
// Something went wrong. Give up.
return null;
}
return hookStack.slice(primitiveIndex, rootIndex - 1);
}
function parseCustomHookName(functionName: void | string): string {
if (!functionName) {
return '';
}
let startIndex = functionName.lastIndexOf('.');
if (startIndex === -1) {
startIndex = 0;
}
if (functionName.substr(startIndex, 3) === 'use') {
startIndex += 3;
}
return functionName.substr(startIndex);
}
function buildTree(rootStack, readHookLog): HooksTree {
const rootChildren = [];
let prevStack = null;
let levelChildren = rootChildren;
let nativeHookID = 0;
const stackOfChildren = [];
for (let i = 0; i < readHookLog.length; i++) {
const hook = readHookLog[i];
const stack = parseTrimmedStack(rootStack, hook);
if (stack !== null) {
// Note: The indices 0 <= n < length-1 will contain the names.
// The indices 1 <= n < length will contain the source locations.
// That's why we get the name from n - 1 and don't check the source
// of index 0.
let commonSteps = 0;
if (prevStack !== null) {
// Compare the current level's stack to the new stack.
while (commonSteps < stack.length && commonSteps < prevStack.length) {
const stackSource = stack[stack.length - commonSteps - 1].source;
const prevSource =
prevStack[prevStack.length - commonSteps - 1].source;
if (stackSource !== prevSource) {
break;
}
commonSteps++;
}
// Pop back the stack as many steps as were not common.
for (let j = prevStack.length - 1; j > commonSteps; j--) {
levelChildren = stackOfChildren.pop();
}
}
// The remaining part of the new stack are custom hooks. Push them
// to the tree.
for (let j = stack.length - commonSteps - 1; j >= 1; j--) {
const children = [];
levelChildren.push({
id: null,
isStateEditable: false,
name: parseCustomHookName(stack[j - 1].functionName),
value: undefined,
subHooks: children,
});
stackOfChildren.push(levelChildren);
levelChildren = children;
}
prevStack = stack;
}
const {primitive} = hook;
// For now, the "id" of stateful hooks is just the stateful hook index.
// Custom hooks have no ids, nor do non-stateful native hooks (e.g. Context, DebugValue).
const id =
primitive === 'Context' || primitive === 'DebugValue'
? null
: nativeHookID++;
// For the time being, only State and Reducer hooks support runtime overrides.
const isStateEditable = primitive === 'Reducer' || primitive === 'State';
levelChildren.push({
id,
isStateEditable,
name: primitive,
value: hook.value,
subHooks: [],
});
}
// Associate custom hook values (useDebugValue() hook entries) with the correct hooks.
processDebugValues(rootChildren, null);
return rootChildren;
}
// Custom hooks support user-configurable labels (via the special useDebugValue() hook).
// That hook adds user-provided values to the hooks tree,
// but these values aren't intended to appear alongside of the other hooks.
// Instead they should be attributed to their parent custom hook.
// This method walks the tree and assigns debug values to their custom hook owners.
function processDebugValues(
hooksTree: HooksTree,
parentHooksNode: HooksNode | null,
): void {
const debugValueHooksNodes: Array<HooksNode> = [];
for (let i = 0; i < hooksTree.length; i++) {
const hooksNode = hooksTree[i];
if (hooksNode.name === 'DebugValue' && hooksNode.subHooks.length === 0) {
hooksTree.splice(i, 1);
i--;
debugValueHooksNodes.push(hooksNode);
} else {
processDebugValues(hooksNode.subHooks, hooksNode);
}
}
// Bubble debug value labels to their custom hook owner.
// If there is no parent hook, just ignore them for now.
// (We may warn about this in the future.)
if (parentHooksNode !== null) {
if (debugValueHooksNodes.length === 1) {
parentHooksNode.value = debugValueHooksNodes[0].value;
} else if (debugValueHooksNodes.length > 1) {
parentHooksNode.value = debugValueHooksNodes.map(({value}) => value);
}
}
}
export function inspectHooks<Props>(
renderFunction: Props => React$Node,
props: Props,
currentDispatcher: ?CurrentDispatcherRef,
): HooksTree {
// DevTools will pass the current renderer's injected dispatcher.
// Other apps might compile debug hooks as part of their app though.
if (currentDispatcher == null) {
currentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
}
const previousDispatcher = currentDispatcher.current;
let readHookLog;
currentDispatcher.current = Dispatcher;
let ancestorStackError;
try {
ancestorStackError = new Error();
renderFunction(props);
} finally {
readHookLog = hookLog;
hookLog = [];
currentDispatcher.current = previousDispatcher;
}
const rootStack = ErrorStackParser.parse(ancestorStackError);
return buildTree(rootStack, readHookLog);
}
function setupContexts(contextMap: Map<ReactContext<any>, any>, fiber: Fiber) {
let current = fiber;
while (current) {
if (current.tag === ContextProvider) {
const providerType: ReactProviderType<any> = current.type;
const context: ReactContext<any> = providerType._context;
if (!contextMap.has(context)) {
// Store the current value that we're going to restore later.
contextMap.set(context, context._currentValue);
// Set the inner most provider value on the context.
context._currentValue = current.memoizedProps.value;
}
}
current = current.return;
}
}
function restoreContexts(contextMap: Map<ReactContext<any>, any>) {
contextMap.forEach((value, context) => (context._currentValue = value));
}
function inspectHooksOfForwardRef<Props, Ref>(
renderFunction: (Props, Ref) => React$Node,
props: Props,
ref: Ref,
currentDispatcher: CurrentDispatcherRef,
): HooksTree {
const previousDispatcher = currentDispatcher.current;
let readHookLog;
currentDispatcher.current = Dispatcher;
let ancestorStackError;
try {
ancestorStackError = new Error();
renderFunction(props, ref);
} finally {
readHookLog = hookLog;
hookLog = [];
currentDispatcher.current = previousDispatcher;
}
const rootStack = ErrorStackParser.parse(ancestorStackError);
return buildTree(rootStack, readHookLog);
}
function resolveDefaultProps(Component, baseProps) {
if (Component && Component.defaultProps) {
// Resolve default props. Taken from ReactElement
const props = Object.assign({}, baseProps);
const defaultProps = Component.defaultProps;
for (const propName in defaultProps) {
if (props[propName] === undefined) {
props[propName] = defaultProps[propName];
}
}
return props;
}
return baseProps;
}
export function inspectHooksOfFiber(
fiber: Fiber,
currentDispatcher: ?CurrentDispatcherRef,
) {
// DevTools will pass the current renderer's injected dispatcher.
// Other apps might compile debug hooks as part of their app though.
if (currentDispatcher == null) {
currentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
}
currentFiber = fiber;
if (
fiber.tag !== FunctionComponent &&
fiber.tag !== SimpleMemoComponent &&
fiber.tag !== ForwardRef
) {
throw new Error(
'Unknown Fiber. Needs to be a function component to inspect hooks.',
);
}
// Warm up the cache so that it doesn't consume the currentHook.
getPrimitiveStackCache();
const type = fiber.type;
let props = fiber.memoizedProps;
if (type !== fiber.elementType) {
props = resolveDefaultProps(type, props);
}
// Set up the current hook so that we can step through and read the
// current state from them.
currentHook = (fiber.memoizedState: Hook);
const contextMap = new Map();
try {
setupContexts(contextMap, fiber);
if (fiber.tag === ForwardRef) {
return inspectHooksOfForwardRef(
type.render,
props,
fiber.ref,
currentDispatcher,
);
}
return inspectHooks(type, props, currentDispatcher);
} finally {
currentHook = null;
restoreContexts(contextMap);
}
}