-
Notifications
You must be signed in to change notification settings - Fork 36
/
devtools-hook-handlers.ts
1447 lines (1255 loc) · 43.6 KB
/
devtools-hook-handlers.ts
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
import { separateDisplayNameAndHOCs } from "./utils/separateDisplayNameAndHOCs";
import {
ElementTypeClass,
ElementTypeFunction,
ElementTypeMemo,
ElementTypeForwardRef,
ElementTypeProvider,
ElementTypeConsumer,
ElementTypeHostRoot,
ElementTypeHostComponent,
ElementTypeHostText,
} from "../../common/constants";
import type { CoreApi } from "./core";
import {
Fiber,
MemoizedState,
TransferFiber,
TransferFiberChanges,
TransferContextChange,
FiberRoot,
FiberType,
ReactDevtoolsHookHandlers,
RecordEventHandler,
ReactContext,
ReactDispatcherTrapApi,
FiberDispatchCall,
CommitTrigger,
HookInfo,
TransferHookInfo,
TransferPropChange,
TransferStateChange,
ClassComponentUpdateCall,
} from "../types";
import { simpleValueSerialization } from "./utils/simpleValueSerialization";
import { objectDiff } from "./utils/objectDiff";
import { arrayDiff } from "./utils/arrayDiff";
import { getDisplayName } from "./utils/getDisplayName";
import { extractCallLoc } from "./utils/stackTrace";
type CommitUpdateInfo = {
providerId: number;
valueChangedEventId: number | null;
};
function valueDiff(prev: any, next: any) {
return Array.isArray(prev) ? arrayDiff(prev, next) : objectDiff(prev, next);
}
const PATCHED_UPDATER = Symbol("react-render-tracker-patched-updater");
export function createReactDevtoolsHookHandlers(
{
ReactTypeOfWork,
// ReactPriorityLevels,
getFiberTypeId,
getOrGenerateFiberId,
getFiberIdThrows,
getFiberIdUnsafe,
getFiberOwnerId,
getFiberById,
removeFiber,
getElementTypeForFiber,
getDisplayNameForFiber,
setRootPseudoKey,
didFiberRender,
removeRootPseudoKey,
shouldFilterFiber,
}: CoreApi,
{
getDispatchHookIndex,
getFiberTypeHookInfo,
flushDispatchCalls,
}: ReactDispatcherTrapApi,
recordEvent: RecordEventHandler
): ReactDevtoolsHookHandlers {
const { HostRoot, SuspenseComponent, OffscreenComponent, ContextProvider } =
ReactTypeOfWork;
// const {
// ImmediatePriority,
// UserBlockingPriority,
// NormalPriority,
// LowPriority,
// IdlePriority,
// NoPriority,
// } = ReactPriorityLevels;
const idToOwnerId = new Map<number, number>();
const commitUpdatedFiberId = new Map<number, number | undefined>();
const commitTriggeredFiberId = new Set<number>();
const commitClassFiberUpdateCalls = new Map<
number,
ClassComponentUpdateCall[]
>();
const commitFiberUpdateCalls = new Map<any, FiberDispatchCall[]>();
const commitContext = new Map<ReactContext<any>, CommitUpdateInfo>();
let currentRootId = -1;
let currentCommitId = -1;
let commitIdSeed = 0;
let classComponentUpdateCalls: Array<ClassComponentUpdateCall> = [];
const classComponentInstanceToFiber = new WeakMap<
any,
{ rootId: number; fiberId: number }
>();
const recordedTypeDef = new Map<
number,
{
hookContextIndecies: Map<ReactContext<any>, number>;
hookMemoIndecies: number[];
hooks: TransferHookInfo[];
}
>();
const unmountedFiberIds = new Set<number>();
const unmountedFiberIdsByOwnerId = new Map<number, Set<number>>();
const unmountedFiberIdBeforeSiblingId = new Map<number, number>();
const unmountedFiberIdForParentId = new Map<number, number>();
const unmountedFiberRefs = new WeakMap<
Fiber,
{
stateNode: unknown;
alternate: Fiber | null;
memoizedState: Fiber["memoizedState"] | null;
}
>();
const untrackFibersSet = new Set<Fiber>();
let untrackFibersTimer: ReturnType<typeof setTimeout> | null = null;
// Removes a Fiber (and its alternate) from the Maps used to track their id.
// This method should always be called when a Fiber is unmounting.
function untrackFiber(fiber: Fiber) {
// Untrack Fibers after a slight delay in order to support a Fast Refresh edge case:
// 1. Component type is updated and Fast Refresh schedules an update+remount.
// 2. flushPendingErrorsAndWarningsAfterDelay() runs, sees the old Fiber is no longer mounted
// (it's been disconnected by Fast Refresh), and calls untrackFiber() to clear it from the Map.
// 3. React flushes pending passive effects before it runs the next render,
// which logs an error or warning, which causes a new ID to be generated for this Fiber.
// 4. DevTools now tries to unmount the old Component with the new ID.
//
// The underlying problem here is the premature clearing of the Fiber ID,
// but DevTools has no way to detect that a given Fiber has been scheduled for Fast Refresh.
// (The "_debugNeedsRemount" flag won't necessarily be set.)
//
// The best we can do is to delay untracking by a small amount,
// and give React time to process the Fast Refresh delay.
untrackFibersSet.add(fiber);
if (untrackFibersTimer === null) {
untrackFibersTimer = setTimeout(untrackFibers, 900);
}
}
function untrackFibers() {
if (untrackFibersTimer !== null) {
clearTimeout(untrackFibersTimer);
untrackFibersTimer = null;
}
for (const fiber of untrackFibersSet) {
removeFiber(fiber, unmountedFiberRefs.get(fiber));
unmountedFiberRefs.delete(fiber);
}
untrackFibersSet.clear();
}
function getComponentChange(
prevFiber: Fiber,
nextFiber: Fiber
): TransferFiberChanges | null {
const type = getElementTypeForFiber(nextFiber);
if (type === ElementTypeHostComponent) {
return {
props: getPropsChanges(
prevFiber.memoizedProps,
nextFiber.memoizedProps
),
};
}
if (type === ElementTypeHostText) {
if (prevFiber.memoizedProps === nextFiber.memoizedProps) {
return null;
}
return {
props: getPropsChanges(
{ "#text": prevFiber.memoizedProps },
{ "#text": nextFiber.memoizedProps }
),
};
}
if (
type !== ElementTypeClass &&
type !== ElementTypeFunction &&
type !== ElementTypeMemo &&
type !== ElementTypeForwardRef &&
type !== ElementTypeProvider &&
type !== ElementTypeConsumer
) {
return null;
}
const isElementTypeClass = prevFiber.stateNode !== null;
const data: TransferFiberChanges = {
props: getPropsChanges(prevFiber.memoizedProps, nextFiber.memoizedProps),
...(isElementTypeClass
? {
// Class component
context: getClassContextChanges(nextFiber),
state: getStateChanges(
prevFiber.memoizedState,
nextFiber.memoizedState,
prevFiber
),
}
: {
// Functional component
context: getFunctionContextChanges(nextFiber),
state: getStateHooksChanges(
prevFiber.memoizedState,
nextFiber.memoizedState
),
memos: getMemoHookChanges(nextFiber),
}),
};
return data;
}
function getContextsForClassFiber(fiber: Fiber): ReactContext<any> | null {
const instance = fiber.stateNode || null;
if (instance !== null) {
return instance.constructor?.contextType || null;
}
return null;
}
function getClassContextChanges(
fiber: Fiber
): TransferContextChange[] | undefined {
const context = getContextsForClassFiber(fiber);
if (context !== null) {
const valueChangedEventId =
commitContext.get(context)?.valueChangedEventId || null;
if (valueChangedEventId !== null) {
return [
{
context: 0,
valueChangedEventId,
},
];
}
}
return;
}
function getContextsForFunctionFiber(
fiber: Fiber
): Array<ReactContext<any>> | null {
let cursor =
fiber.dependencies?.firstContext ||
fiber.contextDependencies?.first ||
null;
if (cursor !== null) {
const contexts = [];
while (cursor !== null) {
contexts.push(cursor.context);
cursor = cursor.next;
}
return contexts;
}
return null;
}
function getFunctionContextChanges(
fiber: Fiber
): TransferContextChange[] | undefined {
const contexts = getContextsForFunctionFiber(fiber);
if (contexts !== null) {
const seenContexts = new Set<number>();
const changes = [];
const typeId = getFiberTypeId(fiber.type, fiber.tag);
const hookContextIndecies =
recordedTypeDef.get(typeId)?.hookContextIndecies;
for (const context of contexts) {
const contextIndex = hookContextIndecies?.get(context);
const valueChangedEventId =
commitContext.get(context)?.valueChangedEventId || null;
if (
typeof contextIndex === "number" &&
valueChangedEventId !== null &&
!seenContexts.has(contextIndex)
) {
// React adds extra entries to dependencies list in some cases,
// e.g. useContext(A) -> useContext(B) -> useContext(A) will produce
// 3 entries on dependencies list instead of 2. Moreover re-renders
// might double count of entries on the list.
// It's not clear that's a bug or a feature, so just we exclude
// context reference duplicates for now
seenContexts.add(contextIndex);
changes.push({
context: contextIndex,
valueChangedEventId,
});
}
}
if (changes.length > 0) {
return changes;
}
}
return;
}
function getStateHooksChanges(
prev: MemoizedState = null,
next: MemoizedState = null
): TransferStateChange[] | undefined {
if (prev === null || next === null || prev === next) {
return;
}
const changes: TransferStateChange[] = [];
while (next !== null && prev !== null) {
// We only interested in useState/useReducer hooks, since only these
// hooks can be a trigger for an update. Such hooks have a special
// signature in the form of the presence of the "queue" property.
// So filter hooks by this attribute. With hookNames can distinguish
// these hooks.
if (next.queue) {
const prevValue = prev.memoizedState;
const nextValue = next.memoizedState;
if (!Object.is(prevValue, nextValue)) {
let dispatch = next.queue.dispatch || next.queue.getSnapshot;
let hookIdx = getDispatchHookIndex(dispatch);
// useTransition stores start function in next queue node
if (
hookIdx === null &&
next.next &&
typeof next.next.memoizedState === "function"
) {
next = next.next;
prev = prev.next;
dispatch = next.memoizedState;
hookIdx = getDispatchHookIndex(dispatch);
}
const dispatchCalls = commitFiberUpdateCalls.get(dispatch);
changes.push({
hook: hookIdx,
prev: simpleValueSerialization(prevValue),
next: simpleValueSerialization(nextValue),
diff: valueDiff(prevValue, nextValue),
calls: dispatchCalls?.map(entry => ({
name: entry.dispatchName,
loc: entry.loc,
})),
});
}
}
next = next.next;
prev = prev.next;
}
return changes.length > 0 ? changes : undefined;
}
function getPropsChanges(prev: MemoizedState, next: MemoizedState) {
if (prev == null || next == null || prev === next) {
return undefined;
}
const keys = new Set([...Object.keys(prev), ...Object.keys(next)]);
const changedProps: TransferPropChange[] = [];
for (const key of keys) {
if (!Object.is(prev[key], next[key])) {
changedProps.push({
name: key,
prev: simpleValueSerialization(prev[key]),
next: simpleValueSerialization(next[key]),
diff: valueDiff(prev[key], next[key]),
});
}
}
return changedProps;
}
function getStateChanges(
prev: MemoizedState,
next: MemoizedState,
fiber: Fiber
) {
if (prev == null || next == null || Object.is(prev, next)) {
return undefined;
}
const fiberId = getFiberIdUnsafe(fiber);
const calls =
fiberId !== null ? commitClassFiberUpdateCalls.get(fiberId) : null;
const setStateCall = calls?.find(call => call.type === "setState");
const changes: TransferStateChange = {
hook: null,
prev: simpleValueSerialization(prev),
next: simpleValueSerialization(next),
diff: valueDiff(prev, next),
calls: setStateCall
? [
{
name: "setState",
loc: setStateCall.loc,
},
]
: null,
};
return [changes];
}
function getMemoHookChanges(fiber: Fiber) {
const hookMemoIndecies =
recordedTypeDef.get(getFiberTypeId(fiber.type, fiber.tag))
?.hookMemoIndecies || [];
const changes = [];
let nextState = fiber.memoizedState || null;
let prevState = fiber.alternate?.memoizedState || null;
let stateIndex = 0;
while (nextState !== null && prevState !== null) {
if (nextState.queue === null && Array.isArray(nextState.memoizedState)) {
const [prevValue, prevDeps] = prevState.memoizedState;
const [nextValue, nextDeps] = nextState.memoizedState;
const memoHookIndex = hookMemoIndecies[stateIndex++];
const changedDeps = [];
if (prevDeps !== nextDeps) {
// recompute
if (prevDeps !== null && nextDeps !== null) {
for (let i = 0; i < prevDeps.length; i++) {
if (!Object.is(prevDeps[i], nextDeps[i])) {
changedDeps.push({
index: i,
prev: simpleValueSerialization(prevDeps[i]),
next: simpleValueSerialization(nextDeps[i]),
diff: valueDiff(prevDeps[i], nextDeps[i]),
});
}
}
}
changes.push({
hook: memoHookIndex,
prev: simpleValueSerialization(prevValue),
next: simpleValueSerialization(nextValue),
diff: valueDiff(prevValue, nextValue),
deps: changedDeps,
});
}
}
nextState = nextState.next || null;
prevState = prevState.next || null;
}
return changes.length > 0 ? changes : undefined;
}
function getFiberContexts(
fiber: Fiber,
fiberType: number,
fiberHooks: HookInfo[]
) {
if (fiber.stateNode !== null) {
const context = getContextsForClassFiber(fiber);
if (context === null) {
return null;
}
return [
{
name: getDisplayName(context, "Context"),
providerId: commitContext.get(context)?.providerId,
},
];
}
if (fiberType === ElementTypeConsumer) {
const context =
fiber.type._context ||
fiber.type.context ||
// in profiling/prod mode
fiber.type;
return [
{
name: getDisplayName(context, "Context"),
providerId: commitContext.get(context)?.providerId,
},
];
}
const hookContexts = fiberHooks.reduce(
(contexts, hook) =>
hook.context != null ? contexts.add(hook.context) : contexts,
new Set<ReactContext<any>>()
);
if (hookContexts.size) {
return [...hookContexts].map(context => ({
name: getDisplayName(context, "Context"),
providerId: commitContext.get(context)?.providerId,
}));
}
return null;
}
function recordFiberTypeDefIfNeeded(
fiber: Fiber,
typeId: number,
fiberType: FiberType,
typeDisplayName: string | null
) {
if (recordedTypeDef.has(typeId)) {
return;
}
const hooks = getFiberTypeHookInfo(typeId);
const contexts = getFiberContexts(fiber, fiberType, hooks);
const hookContextIndecies = new Map<ReactContext<any>, number>();
const hookMemoIndecies: number[] = [];
const transferHooks: TransferHookInfo[] = [];
for (const hook of hooks) {
let hookContext = null;
if (hook.context) {
hookContext = hookContextIndecies.get(hook.context);
if (hookContext === undefined) {
hookContextIndecies.set(
hook.context,
(hookContext = hookContextIndecies.size)
);
}
}
if (hook.name === "useMemo" || hook.name === "useCallback") {
hookMemoIndecies.push(transferHooks.length);
}
transferHooks.push({
...hook,
context: hookContext,
});
}
if (fiberType === ElementTypeClass) {
const { updater } = fiber.stateNode;
if (updater.enqueueForceUpdate.patched !== PATCHED_UPDATER) {
const { enqueueForceUpdate, enqueueSetState } = updater;
Object.defineProperties(updater, {
enqueueForceUpdate: {
value: Object.assign(
function (inst: any, callback: any) {
const classComponentInstance =
classComponentInstanceToFiber.get(inst);
if (classComponentInstance !== undefined) {
const { fiberId, rootId } = classComponentInstance;
classComponentUpdateCalls.push({
type: "forceUpdate",
fiberId,
rootId,
loc: extractCallLoc(2),
});
}
return enqueueForceUpdate(inst, callback);
},
{ patched: PATCHED_UPDATER }
),
},
enqueueSetState: {
value(inst: any, payload: any, callback: any) {
const classComponentInstance =
classComponentInstanceToFiber.get(inst);
if (classComponentInstance !== undefined) {
const { fiberId, rootId } = classComponentInstance;
classComponentUpdateCalls.push({
type: "setState",
fiberId,
rootId,
loc: extractCallLoc(1),
});
}
return enqueueSetState(inst, payload, callback);
},
},
});
}
}
recordedTypeDef.set(typeId, {
hookContextIndecies,
hookMemoIndecies,
hooks: transferHooks,
});
recordEvent({
op: "fiber-type-def",
commitId: currentCommitId,
typeId,
displayName: typeDisplayName,
definition: {
contexts,
hooks: transferHooks,
},
});
}
function locFromDebugSource({
fileName,
lineNumber,
columnNumber,
}: {
fileName: string;
lineNumber: number;
columnNumber?: number;
}) {
return typeof fileName === "string" &&
typeof lineNumber === "number" &&
lineNumber > 0
? `${fileName}:${lineNumber}${
typeof columnNumber === "number" && columnNumber > 0
? ":" + columnNumber
: ""
}`
: null;
}
function recordMount(fiber: Fiber, parentFiber: Fiber | null) {
const isRoot = fiber.tag === HostRoot;
const fiberId = getOrGenerateFiberId(fiber);
let props: string[] = [];
let transferFiber: TransferFiber;
let triggerEventId: number | undefined;
let typeDisplayName: string | null = null;
if (isRoot) {
transferFiber = {
id: fiberId,
type: ElementTypeHostRoot,
typeId: 0,
rootMode: fiber.stateNode.tag || 0,
key: fiber.stateNode.containerInfo.id || null,
ownerId: 0,
parentId: 0,
displayName: null,
hocDisplayNames: null,
loc: null,
};
} else {
const { key, type, tag } = fiber;
const elementType = getElementTypeForFiber(fiber);
const parentId = parentFiber ? getFiberIdThrows(parentFiber) : 0;
const ownerIdCandidate = getFiberOwnerId(fiber);
const ownerId =
ownerIdCandidate !== -1 ? ownerIdCandidate : currentRootId;
const { displayName, hocDisplayNames } = separateDisplayNameAndHOCs(
getDisplayNameForFiber(fiber),
elementType
);
typeDisplayName = displayName;
triggerEventId = commitUpdatedFiberId.get(ownerId);
transferFiber = {
id: fiberId,
type: elementType,
typeId: getFiberTypeId(type, tag),
key: key === null ? null : String(key),
ownerId,
parentId,
displayName,
hocDisplayNames,
loc: fiber._debugSource ? locFromDebugSource(fiber._debugSource) : null,
};
props = Object.keys(
elementType !== ElementTypeHostText
? fiber.memoizedProps
: { "#text": fiber.memoizedProps }
);
}
recordFiberTypeDefIfNeeded(
fiber,
transferFiber.typeId,
transferFiber.type,
typeDisplayName
);
const { selfTime, totalTime } = getDurations(fiber);
const eventId = recordEvent({
op: "mount",
commitId: currentCommitId,
fiberId,
fiber: transferFiber,
props,
selfTime,
totalTime,
trigger: triggerEventId,
});
idToOwnerId.set(fiberId, transferFiber.ownerId);
commitUpdatedFiberId.set(fiberId, triggerEventId ?? eventId);
if (transferFiber.type === ElementTypeClass) {
classComponentInstanceToFiber.set(fiber.stateNode, {
rootId: currentRootId,
fiberId,
});
}
}
function recordUnmount(fiberId: number) {
const ownerId = idToOwnerId.get(fiberId);
const triggerEventId = commitUpdatedFiberId.get(ownerId as number);
const fiber = getFiberById(fiberId);
if (fiber !== null) {
// removeFiber(fiber, unmountedFiberRefs.get(fiber));
untrackFiber(fiber);
if (fiber.stateNode || fiber.alternate) {
unmountedFiberRefs.set(fiber, {
stateNode: fiber.stateNode,
alternate: fiber.alternate,
memoizedState: fiber.memoizedState,
});
}
}
const eventId = recordEvent({
op: "unmount",
commitId: currentCommitId,
fiberId,
trigger: triggerEventId,
});
commitUpdatedFiberId.set(fiberId, triggerEventId ?? eventId);
idToOwnerId.delete(fiberId);
}
function recordSubtreeUnmount(fiberId: number) {
unmountedFiberIds.delete(fiberId);
recordUnmount(fiberId);
const ownerUnmountedFiberIds = unmountedFiberIdsByOwnerId.get(fiberId);
if (ownerUnmountedFiberIds !== undefined) {
unmountedFiberIdsByOwnerId.delete(fiberId);
for (const fiberId of ownerUnmountedFiberIds) {
recordSubtreeUnmount(fiberId);
}
}
}
function recordPreviousSiblingUnmount(fiberId: number) {
const siblingUnmountId = unmountedFiberIdBeforeSiblingId.get(fiberId);
if (siblingUnmountId !== undefined) {
recordPreviousSiblingUnmount(siblingUnmountId);
recordSubtreeUnmount(siblingUnmountId);
}
}
function recordLastChildUnmounts(fiberId: number) {
const lastChildUnmountId = unmountedFiberIdForParentId.get(fiberId);
if (lastChildUnmountId !== undefined) {
recordPreviousSiblingUnmount(lastChildUnmountId);
recordSubtreeUnmount(lastChildUnmountId);
}
}
function unmountFiber(fiber: Fiber) {
const id = getFiberIdUnsafe(fiber);
if (id === null) {
// If we've never seen this Fiber, it might be inside of a legacy render Suspense fragment (so the store is not even aware of it).
// In that case we can just ignore it or it will cause errors later on.
// One example of this is a Lazy component that never resolves before being unmounted.
//
// This also might indicate a Fast Refresh force-remount scenario.
//
// TODO: This is fragile and can obscure actual bugs.
return;
}
const isRoot = fiber.tag === HostRoot;
if (isRoot || !shouldFilterFiber(fiber)) {
if (currentCommitId !== -1) {
// If unmount occurs in a commit, then record it immediatelly.
recordSubtreeUnmount(id);
} else {
// If an unmount occurs outside of a commit then just remember it not record.
// React reports about an unmount before a commit, so we will flush
// events on a commit processing. A various maps are using here to record
// unmount events in more natural way (since we don't know the right order
// of events anyway and simulate it on component's tree traversal).
const ownerId = idToOwnerId.get(id) || 0;
const siblingId = fiber.sibling
? getFiberIdUnsafe(fiber.sibling)
: null;
if (siblingId !== null) {
unmountedFiberIdBeforeSiblingId.set(siblingId, id);
} else {
const parentId = fiber.return ? getFiberIdUnsafe(fiber.return) : null;
if (parentId !== null) {
unmountedFiberIdForParentId.set(parentId, id);
}
}
if (unmountedFiberIdsByOwnerId.has(ownerId)) {
unmountedFiberIdsByOwnerId.get(ownerId)?.add(id);
} else {
unmountedFiberIdsByOwnerId.set(ownerId, new Set([id]));
}
unmountedFiberIds.add(id);
if (fiber.stateNode || fiber.alternate) {
unmountedFiberRefs.set(fiber, {
stateNode: fiber.stateNode,
alternate: fiber.alternate,
memoizedState: fiber.memoizedState,
});
}
}
} else {
removeFiber(fiber);
unmountedFiberRefs.delete(fiber);
}
if (!fiber._debugNeedsRemount) {
// ???
// unmountedFiberIds.delete(id);
}
}
function mountFiberRecursively(
firstChild: Fiber | null,
parentFiber: Fiber | null,
traverseSiblings: boolean
) {
// Iterate over siblings rather than recursing.
// This reduces the chance of stack overflow for wide trees (e.g. lists with many items).
let fiber = firstChild;
while (fiber !== null) {
const shouldIncludeInTree = !shouldFilterFiber(fiber);
const isSuspense = fiber.tag === SuspenseComponent;
const isProvider = fiber.tag === ContextProvider;
const context = isProvider
? fiber.type._context || fiber.type.context
: null;
let prevCommitContextValue: any;
// Generate an ID even for filtered Fibers, in case it's needed later (e.g. for Profiling).
const fiberId = getOrGenerateFiberId(fiber);
if (context !== null) {
prevCommitContextValue = commitContext.get(context);
commitContext.set(context, {
providerId: fiberId,
valueChangedEventId: null,
});
}
if (shouldIncludeInTree) {
recordMount(fiber, parentFiber);
}
if (isSuspense) {
const isTimedOut = fiber.memoizedState !== null;
if (isTimedOut) {
// Special case: if Suspense mounts in a timed-out state,
// get the fallback child from the inner fragment and mount
// it as if it was our own child. Updates handle this too.
const primaryChildFragment = fiber.child;
const fallbackChildFragment = primaryChildFragment?.sibling;
const fallbackChild = fallbackChildFragment?.child || null;
if (fallbackChild !== null) {
mountFiberRecursively(
fallbackChild,
shouldIncludeInTree ? fiber : parentFiber,
true
);
}
} else {
let primaryChild = null;
const areSuspenseChildrenConditionallyWrapped =
OffscreenComponent === -1;
if (areSuspenseChildrenConditionallyWrapped) {
primaryChild = fiber.child;
} else if (fiber.child !== null) {
primaryChild = fiber.child.child;
}
if (primaryChild !== null) {
mountFiberRecursively(
primaryChild,
shouldIncludeInTree ? fiber : parentFiber,
true
);
}
}
} else {
if (fiber.child !== null) {
mountFiberRecursively(
fiber.child,
shouldIncludeInTree ? fiber : parentFiber,
true
);
}
}
if (context !== null) {
commitContext.set(context, prevCommitContextValue);
}
fiber = traverseSiblings ? fiber.sibling : null;
}
}
// We use this to simulate unmounting for Suspense trees
// when we switch from primary to fallback.
function unmountFiberChildrenRecursively(fiber: Fiber) {
// We might meet a nested Suspense on our way.
const isTimedOutSuspense =
fiber.tag === SuspenseComponent && fiber.memoizedState !== null;
let child = fiber.child;
if (isTimedOutSuspense) {
// If it's showing fallback tree, let's traverse it instead.
const primaryChildFragment = fiber.child;
const fallbackChildFragment = primaryChildFragment?.sibling || null;
// Skip over to the real Fiber child.
child = fallbackChildFragment?.child || null;
}
while (child !== null) {
// Record simulated unmounts children-first.
// We skip nodes without return because those are real unmounts.
if (child.return !== null) {
unmountFiber(child);
unmountFiberChildrenRecursively(child);
}
child = child.sibling;
}
}