-
Notifications
You must be signed in to change notification settings - Fork 47.7k
/
Copy pathReactDebugHooks.js
1370 lines (1251 loc) · 39.9 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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* 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
*/
import type {
Awaited,
ReactContext,
StartTransitionOptions,
Usable,
Thenable,
ReactDebugInfo,
StartGesture,
} from 'shared/ReactTypes';
import type {
ContextDependency,
Dependencies,
Fiber,
Dispatcher as DispatcherType,
} from 'react-reconciler/src/ReactInternalTypes';
import type {TransitionStatus} from 'react-reconciler/src/ReactFiberConfig';
import ErrorStackParser from 'error-stack-parser';
import assign from 'shared/assign';
import ReactSharedInternals from 'shared/ReactSharedInternals';
import {
FunctionComponent,
SimpleMemoComponent,
ContextProvider,
ForwardRef,
} from 'react-reconciler/src/ReactWorkTags';
import {
REACT_MEMO_CACHE_SENTINEL,
REACT_CONTEXT_TYPE,
} from 'shared/ReactSymbols';
import hasOwnProperty from 'shared/hasOwnProperty';
type CurrentDispatcherRef = typeof ReactSharedInternals;
// Used to track hooks called during a render
type HookLogEntry = {
displayName: string | null,
primitive: string,
stackError: Error,
value: mixed,
debugInfo: ReactDebugInfo | null,
dispatcherHookName: string,
};
let hookLog: Array<HookLogEntry> = [];
// Primitives
type BasicStateAction<S> = (S => S) | S;
type Dispatch<A> = A => void;
let primitiveStackCache: null | Map<string, Array<any>> = 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<string, Array<any>>();
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: mixed, a: mixed) => s, null);
Dispatcher.useRef(null);
if (typeof Dispatcher.useCacheRefresh === 'function') {
// This type check is for Flow only.
Dispatcher.useCacheRefresh();
}
Dispatcher.useLayoutEffect(() => {});
Dispatcher.useInsertionEffect(() => {});
Dispatcher.useEffect(() => {});
Dispatcher.useImperativeHandle(undefined, () => null);
Dispatcher.useDebugValue(null);
Dispatcher.useCallback(() => {});
Dispatcher.useTransition();
Dispatcher.useSyncExternalStore(
() => () => {},
() => null,
() => null,
);
Dispatcher.useDeferredValue(null);
Dispatcher.useMemo(() => null);
Dispatcher.useOptimistic(null, (s: mixed, a: mixed) => s);
Dispatcher.useFormState((s: mixed, p: mixed) => s, null);
Dispatcher.useActionState((s: mixed, p: mixed) => s, null);
Dispatcher.useHostTransitionStatus();
if (typeof Dispatcher.useMemoCache === 'function') {
// This type check is for Flow only.
Dispatcher.useMemoCache(0);
}
if (typeof Dispatcher.use === 'function') {
// This type check is for Flow only.
Dispatcher.use(
({
$$typeof: REACT_CONTEXT_TYPE,
_currentValue: null,
}: any),
);
Dispatcher.use({
then() {},
status: 'fulfilled',
value: null,
});
try {
Dispatcher.use(
({
then() {},
}: any),
);
} catch (x) {}
}
Dispatcher.useId();
if (typeof Dispatcher.useEffectEvent === 'function') {
Dispatcher.useEffectEvent((args: empty) => {});
}
if (typeof Dispatcher.useSwipeTransition === 'function') {
Dispatcher.useSwipeTransition(null, null, 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 currentFiber: null | Fiber = null;
let currentHook: null | Hook = null;
let currentContextDependency: null | ContextDependency<mixed> = null;
function nextHook(): null | Hook {
const hook = currentHook;
if (hook !== null) {
currentHook = hook.next;
}
return hook;
}
function readContext<T>(context: ReactContext<T>): T {
if (currentFiber === null) {
// Hook inspection without access to the Fiber tree
// e.g. when warming up the primitive stack cache or during `ReactDebugTools.inspectHooks()`.
return context._currentValue;
} else {
if (currentContextDependency === null) {
throw new Error(
'Context reads do not line up with context dependencies. This is a bug in React Debug Tools.',
);
}
let value: T;
// For now we don't expose readContext usage in the hooks debugging info.
if (hasOwnProperty.call(currentContextDependency, 'memoizedValue')) {
// $FlowFixMe[incompatible-use] Flow thinks `hasOwnProperty` mutates `currentContextDependency`
value = ((currentContextDependency.memoizedValue: any): T);
// $FlowFixMe[incompatible-use] Flow thinks `hasOwnProperty` mutates `currentContextDependency`
currentContextDependency = currentContextDependency.next;
} else {
// Before React 18, we did not have `memoizedValue` so we rely on `setupContexts` in those versions.
// Multiple reads of the same context were also only tracked as a single dependency.
// We just give up on advancing context dependencies and solely rely on `setupContexts`.
value = context._currentValue;
}
return value;
}
}
const SuspenseException: mixed = new Error(
"Suspense Exception: This is not a real error! It's an implementation " +
'detail of `use` to interrupt the current render. You must either ' +
'rethrow it immediately, or move the `use` call outside of the ' +
'`try/catch` block. Capturing without rethrowing will lead to ' +
'unexpected behavior.\n\n' +
'To handle async errors, wrap your component in an error boundary, or ' +
"call the promise's `.catch` method and pass the result to `use`.",
);
function use<T>(usable: Usable<T>): T {
if (usable !== null && typeof usable === 'object') {
// $FlowFixMe[method-unbinding]
if (typeof usable.then === 'function') {
const thenable: Thenable<any> = (usable: any);
switch (thenable.status) {
case 'fulfilled': {
const fulfilledValue: T = thenable.value;
hookLog.push({
displayName: null,
primitive: 'Promise',
stackError: new Error(),
value: fulfilledValue,
debugInfo:
thenable._debugInfo === undefined ? null : thenable._debugInfo,
dispatcherHookName: 'Use',
});
return fulfilledValue;
}
case 'rejected': {
const rejectedError = thenable.reason;
throw rejectedError;
}
}
// If this was an uncached Promise we have to abandon this attempt
// but we can still emit anything up until this point.
hookLog.push({
displayName: null,
primitive: 'Unresolved',
stackError: new Error(),
value: thenable,
debugInfo:
thenable._debugInfo === undefined ? null : thenable._debugInfo,
dispatcherHookName: 'Use',
});
throw SuspenseException;
} else if (usable.$$typeof === REACT_CONTEXT_TYPE) {
const context: ReactContext<T> = (usable: any);
const value = readContext(context);
hookLog.push({
displayName: context.displayName || 'Context',
primitive: 'Context (use)',
stackError: new Error(),
value,
debugInfo: null,
dispatcherHookName: 'Use',
});
return value;
}
}
// eslint-disable-next-line react-internal/safe-string-coercion
throw new Error('An unsupported type was passed to use(): ' + String(usable));
}
function useContext<T>(context: ReactContext<T>): T {
const value = readContext(context);
hookLog.push({
displayName: context.displayName || null,
primitive: 'Context',
stackError: new Error(),
value: value,
debugInfo: null,
dispatcherHookName: 'Context',
});
return value;
}
function useState<S>(
initialState: (() => S) | S,
): [S, Dispatch<BasicStateAction<S>>] {
const hook = nextHook();
const state: S =
hook !== null
? hook.memoizedState
: typeof initialState === 'function'
? // $FlowFixMe[incompatible-use]: Flow doesn't like mixed types
initialState()
: initialState;
hookLog.push({
displayName: null,
primitive: 'State',
stackError: new Error(),
value: state,
debugInfo: null,
dispatcherHookName: '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({
displayName: null,
primitive: 'Reducer',
stackError: new Error(),
value: state,
debugInfo: null,
dispatcherHookName: 'Reducer',
});
return [state, (action: A) => {}];
}
function useRef<T>(initialValue: T): {current: T} {
const hook = nextHook();
const ref = hook !== null ? hook.memoizedState : {current: initialValue};
hookLog.push({
displayName: null,
primitive: 'Ref',
stackError: new Error(),
value: ref.current,
debugInfo: null,
dispatcherHookName: 'Ref',
});
return ref;
}
function useCacheRefresh(): () => void {
const hook = nextHook();
hookLog.push({
displayName: null,
primitive: 'CacheRefresh',
stackError: new Error(),
value: hook !== null ? hook.memoizedState : function refresh() {},
debugInfo: null,
dispatcherHookName: 'CacheRefresh',
});
return () => {};
}
function useLayoutEffect(
create: () => (() => void) | void,
inputs: Array<mixed> | void | null,
): void {
nextHook();
hookLog.push({
displayName: null,
primitive: 'LayoutEffect',
stackError: new Error(),
value: create,
debugInfo: null,
dispatcherHookName: 'LayoutEffect',
});
}
function useInsertionEffect(
create: () => mixed,
inputs: Array<mixed> | void | null,
): void {
nextHook();
hookLog.push({
displayName: null,
primitive: 'InsertionEffect',
stackError: new Error(),
value: create,
debugInfo: null,
dispatcherHookName: 'InsertionEffect',
});
}
function useEffect(
create: (() => (() => void) | void) | (() => {...} | void | null),
createDeps: Array<mixed> | void | null,
update?: ((resource: {...} | void | null) => void) | void,
updateDeps?: Array<mixed> | void | null,
destroy?: ((resource: {...} | void | null) => void) | void,
): void {
nextHook();
hookLog.push({
displayName: null,
primitive: 'Effect',
stackError: new Error(),
value: create,
debugInfo: null,
dispatcherHookName: 'Effect',
});
}
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: ?T = undefined;
if (ref !== null && typeof ref === 'object') {
instance = ref.current;
}
hookLog.push({
displayName: null,
primitive: 'ImperativeHandle',
stackError: new Error(),
value: instance,
debugInfo: null,
dispatcherHookName: 'ImperativeHandle',
});
}
function useDebugValue(value: any, formatterFn: ?(value: any) => any) {
hookLog.push({
displayName: null,
primitive: 'DebugValue',
stackError: new Error(),
value: typeof formatterFn === 'function' ? formatterFn(value) : value,
debugInfo: null,
dispatcherHookName: 'DebugValue',
});
}
function useCallback<T>(callback: T, inputs: Array<mixed> | void | null): T {
const hook = nextHook();
hookLog.push({
displayName: null,
primitive: 'Callback',
stackError: new Error(),
value: hook !== null ? hook.memoizedState[0] : callback,
debugInfo: null,
dispatcherHookName: '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({
displayName: null,
primitive: 'Memo',
stackError: new Error(),
value,
debugInfo: null,
dispatcherHookName: 'Memo',
});
return value;
}
function useSyncExternalStore<T>(
subscribe: (() => void) => () => void,
getSnapshot: () => T,
getServerSnapshot?: () => T,
): T {
// useSyncExternalStore() composes multiple hooks internally.
// Advance the current hook index the same number of times
// so that subsequent hooks have the right memoized state.
nextHook(); // SyncExternalStore
nextHook(); // Effect
const value = getSnapshot();
hookLog.push({
displayName: null,
primitive: 'SyncExternalStore',
stackError: new Error(),
value,
debugInfo: null,
dispatcherHookName: 'SyncExternalStore',
});
return value;
}
function useTransition(): [
boolean,
(callback: () => void, options?: StartTransitionOptions) => void,
] {
// useTransition() composes multiple hooks internally.
// Advance the current hook index the same number of times
// so that subsequent hooks have the right memoized state.
const stateHook = nextHook();
nextHook(); // Callback
const isPending = stateHook !== null ? stateHook.memoizedState : false;
hookLog.push({
displayName: null,
primitive: 'Transition',
stackError: new Error(),
value: isPending,
debugInfo: null,
dispatcherHookName: 'Transition',
});
return [isPending, () => {}];
}
function useDeferredValue<T>(value: T, initialValue?: T): T {
const hook = nextHook();
const prevValue = hook !== null ? hook.memoizedState : value;
hookLog.push({
displayName: null,
primitive: 'DeferredValue',
stackError: new Error(),
value: prevValue,
debugInfo: null,
dispatcherHookName: 'DeferredValue',
});
return prevValue;
}
function useId(): string {
const hook = nextHook();
const id = hook !== null ? hook.memoizedState : '';
hookLog.push({
displayName: null,
primitive: 'Id',
stackError: new Error(),
value: id,
debugInfo: null,
dispatcherHookName: 'Id',
});
return id;
}
// useMemoCache is an implementation detail of Forget's memoization
// it should not be called directly in user-generated code
function useMemoCache(size: number): Array<mixed> {
const fiber = currentFiber;
// Don't throw, in case this is called from getPrimitiveStackCache
if (fiber == null) {
return [];
}
const memoCache =
// $FlowFixMe[incompatible-use]: updateQueue is mixed
fiber.updateQueue != null ? fiber.updateQueue.memoCache : null;
if (memoCache == null) {
return [];
}
let data = memoCache.data[memoCache.index];
if (data === undefined) {
data = memoCache.data[memoCache.index] = new Array(size);
for (let i = 0; i < size; i++) {
data[i] = REACT_MEMO_CACHE_SENTINEL;
}
}
// We don't write anything to hookLog on purpose, so this hook remains invisible to users.
memoCache.index++;
return data;
}
function useOptimistic<S, A>(
passthrough: S,
reducer: ?(S, A) => S,
): [S, (A) => void] {
const hook = nextHook();
let state;
if (hook !== null) {
state = hook.memoizedState;
} else {
state = passthrough;
}
hookLog.push({
displayName: null,
primitive: 'Optimistic',
stackError: new Error(),
value: state,
debugInfo: null,
dispatcherHookName: 'Optimistic',
});
return [state, (action: A) => {}];
}
function useFormState<S, P>(
action: (Awaited<S>, P) => S,
initialState: Awaited<S>,
permalink?: string,
): [Awaited<S>, (P) => void, boolean] {
const hook = nextHook(); // FormState
nextHook(); // PendingState
nextHook(); // ActionQueue
const stackError = new Error();
let value;
let debugInfo = null;
let error = null;
if (hook !== null) {
const actionResult = hook.memoizedState;
if (
typeof actionResult === 'object' &&
actionResult !== null &&
// $FlowFixMe[method-unbinding]
typeof actionResult.then === 'function'
) {
const thenable: Thenable<Awaited<S>> = (actionResult: any);
switch (thenable.status) {
case 'fulfilled': {
value = thenable.value;
debugInfo =
thenable._debugInfo === undefined ? null : thenable._debugInfo;
break;
}
case 'rejected': {
const rejectedError = thenable.reason;
error = rejectedError;
break;
}
default:
// If this was an uncached Promise we have to abandon this attempt
// but we can still emit anything up until this point.
error = SuspenseException;
debugInfo =
thenable._debugInfo === undefined ? null : thenable._debugInfo;
value = thenable;
}
} else {
value = (actionResult: any);
}
} else {
value = initialState;
}
hookLog.push({
displayName: null,
primitive: 'FormState',
stackError: stackError,
value: value,
debugInfo: debugInfo,
dispatcherHookName: 'FormState',
});
if (error !== null) {
throw error;
}
// value being a Thenable is equivalent to error being not null
// i.e. we only reach this point with Awaited<S>
const state = ((value: any): Awaited<S>);
// TODO: support displaying pending value
return [state, (payload: P) => {}, false];
}
function useActionState<S, P>(
action: (Awaited<S>, P) => S,
initialState: Awaited<S>,
permalink?: string,
): [Awaited<S>, (P) => void, boolean] {
const hook = nextHook(); // FormState
nextHook(); // PendingState
nextHook(); // ActionQueue
const stackError = new Error();
let value;
let debugInfo = null;
let error = null;
if (hook !== null) {
const actionResult = hook.memoizedState;
if (
typeof actionResult === 'object' &&
actionResult !== null &&
// $FlowFixMe[method-unbinding]
typeof actionResult.then === 'function'
) {
const thenable: Thenable<Awaited<S>> = (actionResult: any);
switch (thenable.status) {
case 'fulfilled': {
value = thenable.value;
debugInfo =
thenable._debugInfo === undefined ? null : thenable._debugInfo;
break;
}
case 'rejected': {
const rejectedError = thenable.reason;
error = rejectedError;
break;
}
default:
// If this was an uncached Promise we have to abandon this attempt
// but we can still emit anything up until this point.
error = SuspenseException;
debugInfo =
thenable._debugInfo === undefined ? null : thenable._debugInfo;
value = thenable;
}
} else {
value = (actionResult: any);
}
} else {
value = initialState;
}
hookLog.push({
displayName: null,
primitive: 'ActionState',
stackError: stackError,
value: value,
debugInfo: debugInfo,
dispatcherHookName: 'ActionState',
});
if (error !== null) {
throw error;
}
// value being a Thenable is equivalent to error being not null
// i.e. we only reach this point with Awaited<S>
const state = ((value: any): Awaited<S>);
// TODO: support displaying pending value
return [state, (payload: P) => {}, false];
}
function useHostTransitionStatus(): TransitionStatus {
const status = readContext<TransitionStatus>(
// $FlowFixMe[prop-missing] `readContext` only needs _currentValue
({
// $FlowFixMe[incompatible-cast] TODO: Incorrect bottom value without access to Fiber config.
_currentValue: null,
}: ReactContext<TransitionStatus>),
);
hookLog.push({
displayName: null,
primitive: 'HostTransitionStatus',
stackError: new Error(),
value: status,
debugInfo: null,
dispatcherHookName: 'HostTransitionStatus',
});
return status;
}
function useEffectEvent<Args, F: (...Array<Args>) => mixed>(callback: F): F {
nextHook();
hookLog.push({
displayName: null,
primitive: 'EffectEvent',
stackError: new Error(),
value: callback,
debugInfo: null,
dispatcherHookName: 'EffectEvent',
});
return callback;
}
function useSwipeTransition<T>(
previous: T,
current: T,
next: T,
): [T, StartGesture] {
nextHook();
hookLog.push({
displayName: null,
primitive: 'SwipeTransition',
stackError: new Error(),
value: current,
debugInfo: null,
dispatcherHookName: 'SwipeTransition',
});
return [current, () => () => {}];
}
const Dispatcher: DispatcherType = {
readContext,
use,
useCallback,
useContext,
useEffect,
useImperativeHandle,
useLayoutEffect,
useInsertionEffect,
useMemo,
useReducer,
useRef,
useState,
useDebugValue,
useDeferredValue,
useTransition,
useSyncExternalStore,
useId,
useHostTransitionStatus,
useFormState,
useActionState,
useOptimistic,
useMemoCache,
useCacheRefresh,
useEffectEvent,
useSwipeTransition,
};
// create a proxy to throw a custom error
// in case future versions of React adds more hooks
const DispatcherProxyHandler = {
get(target: DispatcherType, prop: string) {
if (target.hasOwnProperty(prop)) {
// $FlowFixMe[invalid-computed-prop]
return target[prop];
}
const error = new Error('Missing method in Dispatcher: ' + prop);
// Note: This error name needs to stay in sync with react-devtools-shared
// TODO: refactor this if we ever combine the devtools and debug tools packages
error.name = 'ReactDebugToolsUnsupportedHookError';
throw error;
},
};
// `Proxy` may not exist on some platforms
const DispatcherProxy =
typeof Proxy === 'undefined'
? Dispatcher
: new Proxy(Dispatcher, DispatcherProxyHandler);
// Inspect
export type HookSource = {
lineNumber: number | null,
columnNumber: number | null,
fileName: string | null,
functionName: string | null,
};
export type HooksNode = {
id: number | null,
isStateEditable: boolean,
name: string,
value: mixed,
subHooks: Array<HooksNode>,
debugInfo: null | ReactDebugInfo,
hookSource: null | HookSource,
};
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.
//
// 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: any, rootStack: any, rootIndex: number) {
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: any, hookStack: any) {
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: any, wrapperName: string) {
const hookName = parseHookName(functionName);
if (wrapperName === 'HostTransitionStatus') {
return hookName === wrapperName || hookName === 'FormStatus';
}
return hookName === wrapperName;
}
function findPrimitiveIndex(hookStack: any, hook: HookLogEntry) {
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++) {
// Note: there is no guarantee that we will find the top-most primitive frame in the stack
// For React Native (uses Hermes), these source fields will be identical and skipped
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 package or other packages adds around the dispatcher.
if (
i < hookStack.length - 1 &&
isReactWrapper(hookStack[i].functionName, hook.dispatcherHookName)
) {
i++;
}
if (
i < hookStack.length - 1 &&
isReactWrapper(hookStack[i].functionName, hook.dispatcherHookName)
) {
i++;
}
return i;
}
}
return -1;
}
function parseTrimmedStack(rootStack: any, hook: HookLogEntry) {
// 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
) {
if (primitiveIndex === -1) {
// Something went wrong. Give up.
return [null, null];
} else {
return [hookStack[primitiveIndex - 1], null];
}
}
return [
hookStack[primitiveIndex - 1],
hookStack.slice(primitiveIndex, rootIndex - 1),
];
}
function parseHookName(functionName: void | string): string {
if (!functionName) {
return '';
}
let startIndex = functionName.lastIndexOf('[as ');
if (startIndex !== -1) {
// Workaround for sourcemaps in Jest and Chrome.
// In `node --enable-source-maps`, we don't see "Object.useHostTransitionStatus [as useFormStatus]" but "Object.useFormStatus"
// "Object.useHostTransitionStatus [as useFormStatus]" -> "useFormStatus"
return parseHookName(functionName.slice(startIndex + '[as '.length, -1));
}
startIndex = functionName.lastIndexOf('.');
if (startIndex === -1) {
startIndex = 0;
} else {
startIndex += 1;
}
if (functionName.slice(startIndex).startsWith('unstable_')) {
startIndex += 'unstable_'.length;
}
if (functionName.slice(startIndex).startsWith('experimental_')) {
startIndex += 'experimental_'.length;
}
if (functionName.slice(startIndex, startIndex + 3) === 'use') {
if (functionName.length - startIndex === 3) {
return 'Use';
}
startIndex += 3;
}