-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathrenderer.js
1617 lines (1474 loc) · 51.9 KB
/
renderer.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
// @flow
import { gte } from 'semver';
import {
ElementTypeClass,
ElementTypeFunction,
ElementTypeContext,
ElementTypeEventComponent,
ElementTypeEventTarget,
ElementTypeForwardRef,
ElementTypeMemo,
ElementTypeOtherOrUnknown,
ElementTypeProfiler,
ElementTypeRoot,
ElementTypeSuspense,
} from 'src/devtools/types';
import { getDisplayName, utfEncodeString } from '../utils';
import { cleanForBridge, copyWithSet, setInObject } from './utils';
import {
__DEBUG__,
TREE_OPERATION_ADD,
TREE_OPERATION_REMOVE,
TREE_OPERATION_RESET_CHILDREN,
TREE_OPERATION_UPDATE_TREE_BASE_DURATION,
} from '../constants';
import { getUID } from '../utils';
import { inspectHooksOfFiber } from './ReactDebugHooks';
import type {
CommitDetails,
DevToolsHook,
Fiber,
FiberData,
Interaction,
Interactions,
InteractionWithCommits,
ProfilingSummary,
ReactRenderer,
RendererInterface,
} from './types';
import type { InspectedElement } from 'src/devtools/views/elements/types';
function getInternalReactConstants(version) {
const ReactSymbols = {
CONCURRENT_MODE_NUMBER: 0xeacf,
CONCURRENT_MODE_SYMBOL_STRING: 'Symbol(react.concurrent_mode)',
DEPRECATED_ASYNC_MODE_SYMBOL_STRING: 'Symbol(react.async_mode)',
CONTEXT_CONSUMER_NUMBER: 0xeace,
CONTEXT_CONSUMER_SYMBOL_STRING: 'Symbol(react.context)',
CONTEXT_PROVIDER_NUMBER: 0xeacd,
CONTEXT_PROVIDER_SYMBOL_STRING: 'Symbol(react.provider)',
EVENT_COMPONENT_NUMBER: 0xead5,
EVENT_COMPONENT_STRING: 'Symbol(react.event_component)',
EVENT_TARGET_NUMBER: 0xead6,
EVENT_TARGET_STRING: 'Symbol(react.event_target)',
EVENT_TARGET_TOUCH_HIT_NUMBER: 0xead7,
EVENT_TARGET_TOUCH_HIT_STRING: 'Symbol(react.event_target.touch_hit)',
FORWARD_REF_NUMBER: 0xead0,
FORWARD_REF_SYMBOL_STRING: 'Symbol(react.forward_ref)',
MEMO_NUMBER: 0xead3,
MEMO_SYMBOL_STRING: 'Symbol(react.memo)',
PROFILER_NUMBER: 0xead2,
PROFILER_SYMBOL_STRING: 'Symbol(react.profiler)',
STRICT_MODE_NUMBER: 0xeacc,
STRICT_MODE_SYMBOL_STRING: 'Symbol(react.strict_mode)',
SUSPENSE_NUMBER: 0xead1,
SUSPENSE_SYMBOL_STRING: 'Symbol(react.suspense)',
DEPRECATED_PLACEHOLDER_SYMBOL_STRING: 'Symbol(react.placeholder)',
};
const ReactTypeOfSideEffect = {
NoEffect: 0b00,
PerformedWork: 0b01,
Placement: 0b10,
};
let ReactTypeOfWork;
// **********************************************************
// The section below is copied from files in React repo.
// Keep it in sync, and add version guards if it changes.
// **********************************************************
if (gte(version, '16.6.0-beta.0')) {
ReactTypeOfWork = {
ClassComponent: 1,
ContextConsumer: 9,
ContextProvider: 10,
CoroutineComponent: -1, // Removed
CoroutineHandlerPhase: -1, // Removed
EventComponent: 19, // Added in 16.9
EventTarget: 20, // Added in 16.9
ForwardRef: 11,
Fragment: 7,
FunctionComponent: 0,
HostComponent: 5,
HostPortal: 4,
HostRoot: 3,
HostText: 6,
IncompleteClassComponent: 17,
IndeterminateComponent: 2,
LazyComponent: 16,
MemoComponent: 14,
Mode: 8,
Profiler: 12,
SimpleMemoComponent: 15,
SuspenseComponent: 13,
YieldComponent: -1, // Removed
};
} else if (gte(version, '16.4.3-alpha')) {
ReactTypeOfWork = {
ClassComponent: 2,
ContextConsumer: 11,
ContextProvider: 12,
CoroutineComponent: -1, // Removed
CoroutineHandlerPhase: -1, // Removed
EventComponent: -1, // Doesn't exist yet
EventTarget: -1, // Doesn't exist yet
ForwardRef: 13,
Fragment: 9,
FunctionComponent: 0,
HostComponent: 7,
HostPortal: 6,
HostRoot: 5,
HostText: 8,
IncompleteClassComponent: -1, // Doesn't exist yet
IndeterminateComponent: 4,
LazyComponent: -1, // Doesn't exist yet
MemoComponent: -1, // Doesn't exist yet
Mode: 10,
Profiler: 15,
SimpleMemoComponent: -1, // Doesn't exist yet
SuspenseComponent: 16,
YieldComponent: -1, // Removed
};
} else {
ReactTypeOfWork = {
ClassComponent: 2,
ContextConsumer: 12,
ContextProvider: 13,
CoroutineComponent: 7,
CoroutineHandlerPhase: 8,
EventComponent: -1, // Doesn't exist yet
EventTarget: -1, // Doesn't exist yet
ForwardRef: 14,
Fragment: 10,
FunctionComponent: 1,
HostComponent: 5,
HostPortal: 4,
HostRoot: 3,
HostText: 6,
IncompleteClassComponent: -1, // Doesn't exist yet
IndeterminateComponent: 0,
LazyComponent: -1, // Doesn't exist yet
MemoComponent: -1, // Doesn't exist yet
Mode: 11,
Profiler: 15,
SimpleMemoComponent: -1, // Doesn't exist yet
SuspenseComponent: 16,
YieldComponent: 9,
};
}
// **********************************************************
// End of copied code.
// **********************************************************
return {
ReactTypeOfWork,
ReactSymbols,
ReactTypeOfSideEffect,
};
}
export function attach(
hook: DevToolsHook,
rendererID: number,
renderer: ReactRenderer,
global: Object
): RendererInterface {
const {
ReactTypeOfWork,
ReactSymbols,
ReactTypeOfSideEffect,
} = getInternalReactConstants(renderer.version);
const { NoEffect, PerformedWork, Placement } = ReactTypeOfSideEffect;
const {
FunctionComponent,
ClassComponent,
ContextConsumer,
EventComponent,
EventTarget,
Fragment,
ForwardRef,
HostRoot,
HostPortal,
HostComponent,
HostText,
IncompleteClassComponent,
IndeterminateComponent,
MemoComponent,
SimpleMemoComponent,
} = ReactTypeOfWork;
const {
CONCURRENT_MODE_NUMBER,
CONCURRENT_MODE_SYMBOL_STRING,
DEPRECATED_ASYNC_MODE_SYMBOL_STRING,
CONTEXT_CONSUMER_NUMBER,
CONTEXT_CONSUMER_SYMBOL_STRING,
CONTEXT_PROVIDER_NUMBER,
CONTEXT_PROVIDER_SYMBOL_STRING,
EVENT_TARGET_TOUCH_HIT_NUMBER,
EVENT_TARGET_TOUCH_HIT_STRING,
PROFILER_NUMBER,
PROFILER_SYMBOL_STRING,
STRICT_MODE_NUMBER,
STRICT_MODE_SYMBOL_STRING,
SUSPENSE_NUMBER,
SUSPENSE_SYMBOL_STRING,
DEPRECATED_PLACEHOLDER_SYMBOL_STRING,
} = ReactSymbols;
const { overrideHookState, overrideProps } = renderer;
const debug = (name: string, fiber: Fiber, parentFiber: ?Fiber): void => {
if (__DEBUG__) {
const fiberData = getDataForFiber(fiber);
const fiberDisplayName = (fiberData && fiberData.displayName) || 'null';
const parentFiberData =
parentFiber == null ? null : getDataForFiber(parentFiber);
const parentFiberDisplayName =
(parentFiberData && parentFiberData.displayName) || 'null';
console.log(
`[renderer] %c${name} %c${getFiberID(
getPrimaryFiber(fiber)
)}:${fiberDisplayName} %c${
parentFiber
? getFiberID(getPrimaryFiber(parentFiber)) +
':' +
parentFiberDisplayName
: ''
}`,
'color: red; font-weight: bold;',
'color: blue;',
'color: purple;'
);
}
};
// Keep this function in sync with getDataForFiber()
function shouldFilterFiber(fiber: Fiber): boolean {
const { tag } = fiber;
switch (tag) {
case ClassComponent:
case FunctionComponent:
case IncompleteClassComponent:
case IndeterminateComponent:
case ForwardRef:
case HostRoot:
case MemoComponent:
case SimpleMemoComponent:
return false;
case EventComponent:
case HostPortal:
case HostComponent:
case HostText:
case Fragment:
return true;
default:
const typeSymbol = getTypeSymbol(fiber.type);
switch (typeSymbol) {
case CONCURRENT_MODE_NUMBER:
case CONCURRENT_MODE_SYMBOL_STRING:
case DEPRECATED_ASYNC_MODE_SYMBOL_STRING:
case STRICT_MODE_NUMBER:
case STRICT_MODE_SYMBOL_STRING:
return true;
case CONTEXT_PROVIDER_NUMBER:
case CONTEXT_PROVIDER_SYMBOL_STRING:
case CONTEXT_CONSUMER_NUMBER:
case CONTEXT_CONSUMER_SYMBOL_STRING:
case SUSPENSE_NUMBER:
case SUSPENSE_SYMBOL_STRING:
case DEPRECATED_PLACEHOLDER_SYMBOL_STRING:
case PROFILER_NUMBER:
case PROFILER_SYMBOL_STRING:
return false;
default:
return false;
}
}
}
function getTypeSymbol(type: any): Symbol | number {
const symbolOrNumber =
typeof type === 'object' && type !== null ? type.$$typeof : type;
return typeof symbolOrNumber === 'symbol'
? symbolOrNumber.toString()
: symbolOrNumber;
}
// TODO: we might want to change the data structure once we no longer suppport Stack versions of `getData`.
// TODO: Keep in sync with getElementType()
function getDataForFiber(fiber: Fiber): FiberData {
const { elementType, type, key, tag } = fiber;
// This is to support lazy components with a Promise as the type.
// see https://github.com/facebook/react/pull/13397
let resolvedType = type;
if (typeof type === 'object' && type !== null) {
if (typeof type.then === 'function') {
resolvedType = type._reactResult;
}
}
let fiberData: FiberData = ((null: any): FiberData);
let displayName: string = ((null: any): string);
let resolvedContext: any = null;
switch (tag) {
case ClassComponent:
case IncompleteClassComponent:
fiberData = {
displayName: getDisplayName(resolvedType),
key,
type: ElementTypeClass,
};
break;
case FunctionComponent:
case IndeterminateComponent:
fiberData = {
displayName: getDisplayName(resolvedType),
key,
type: ElementTypeFunction,
};
break;
case EventComponent:
fiberData = {
displayName: null,
key,
type: ElementTypeEventComponent,
};
break;
case EventTarget:
switch (getTypeSymbol(elementType.type)) {
case EVENT_TARGET_TOUCH_HIT_NUMBER:
case EVENT_TARGET_TOUCH_HIT_STRING:
displayName = 'TouchHitTarget';
break;
default:
displayName = 'EventTarget';
break;
}
fiberData = {
displayName,
key,
type: ElementTypeEventTarget,
};
break;
case ForwardRef:
const functionName = getDisplayName(resolvedType.render, '');
displayName =
resolvedType.displayName ||
(functionName !== '' ? `ForwardRef(${functionName})` : 'ForwardRef');
fiberData = {
displayName,
key,
type: ElementTypeForwardRef,
};
break;
case HostRoot:
return {
displayName: null,
key: null,
type: ElementTypeRoot,
};
case HostPortal:
case HostComponent:
case HostText:
case Fragment:
return {
displayName: null,
key,
type: ElementTypeOtherOrUnknown,
};
case MemoComponent:
case SimpleMemoComponent:
if (elementType.displayName) {
displayName = elementType.displayName;
} else {
displayName = type.displayName || type.name;
displayName = displayName ? `Memo(${displayName})` : 'Memo';
}
fiberData = {
displayName,
key,
type: ElementTypeMemo,
};
break;
default:
const typeSymbol = getTypeSymbol(type);
switch (typeSymbol) {
case CONCURRENT_MODE_NUMBER:
case CONCURRENT_MODE_SYMBOL_STRING:
case DEPRECATED_ASYNC_MODE_SYMBOL_STRING:
return {
displayName: null,
key: null,
type: ElementTypeOtherOrUnknown,
};
case CONTEXT_PROVIDER_NUMBER:
case CONTEXT_PROVIDER_SYMBOL_STRING:
// 16.3.0 exposed the context object as "context"
// PR #12501 changed it to "_context" for 16.3.1+
// NOTE Keep in sync with inspectElement()
resolvedContext = fiber.type._context || fiber.type.context;
displayName = `${resolvedContext.displayName ||
'Context'}.Provider`;
fiberData = {
displayName,
key,
type: ElementTypeContext,
};
break;
case CONTEXT_CONSUMER_NUMBER:
case CONTEXT_CONSUMER_SYMBOL_STRING:
// 16.3-16.5 read from "type" because the Consumer is the actual context object.
// 16.6+ should read from "type._context" because Consumer can be different (in DEV).
// NOTE Keep in sync with inspectElement()
resolvedContext = fiber.type._context || fiber.type;
// NOTE: TraceUpdatesBackendManager depends on the name ending in '.Consumer'
// If you change the name, figure out a more resilient way to detect it.
displayName = `${resolvedContext.displayName ||
'Context'}.Consumer`;
fiberData = {
displayName,
key,
type: ElementTypeContext,
};
break;
case STRICT_MODE_NUMBER:
case STRICT_MODE_SYMBOL_STRING:
fiberData = {
displayName: null,
key,
type: ElementTypeOtherOrUnknown,
};
break;
case SUSPENSE_NUMBER:
case SUSPENSE_SYMBOL_STRING:
case DEPRECATED_PLACEHOLDER_SYMBOL_STRING:
fiberData = {
displayName: 'Suspense',
key,
type: ElementTypeSuspense,
};
break;
case PROFILER_NUMBER:
case PROFILER_SYMBOL_STRING:
fiberData = {
displayName: `Profiler(${fiber.memoizedProps.id})`,
key,
type: ElementTypeProfiler,
};
break;
default:
// Unknown element type.
// This may mean a new element type that has not yet been added to DevTools.
fiberData = {
displayName: null,
key,
type: ElementTypeOtherOrUnknown,
};
break;
}
break;
}
return fiberData;
}
// This is a slightly annoying indirection.
// It is currently necessary because DevTools wants to use unique objects as keys for instances.
// However fibers have two versions.
// We use this set to remember first encountered fiber for each conceptual instance.
function getPrimaryFiber(fiber: Fiber): Fiber {
if (primaryFibers.has(fiber)) {
return fiber;
}
const { alternate } = fiber;
if (alternate != null && primaryFibers.has(alternate)) {
return alternate;
}
primaryFibers.add(fiber);
return fiber;
}
const fiberToIDMap: Map<Fiber, number> = new Map();
const idToFiberMap: Map<number, Fiber> = new Map();
const primaryFibers: Set<Fiber> = new Set();
// When profiling is supported, we store the latest tree base durations for each Fiber.
// This is so that we can quickly capture a snapshot of those values if profiling starts.
// If we didn't store these values, we'd have to crawl the tree when profiling started,
// and use a slow path to find each of the current Fibers.
const idToTreeBaseDurationMap: Map<number, number> = new Map();
// When profiling is supported, we store the latest tree base durations for each Fiber.
// This map enables us to filter these times by root when sending them to the frontend.
const idToRootMap: Map<number, number> = new Map();
// When a mount or update is in progress, this value tracks the root that is being operated on.
let currentRootID: number = -1;
function getFiberID(primaryFiber: Fiber): number {
if (!fiberToIDMap.has(primaryFiber)) {
const id = getUID();
fiberToIDMap.set(primaryFiber, id);
idToFiberMap.set(id, primaryFiber);
}
return ((fiberToIDMap.get(primaryFiber): any): number);
}
// eslint-disable-next-line no-unused-vars
function hasDataChanged(prevFiber: Fiber, nextFiber: Fiber): boolean {
switch (nextFiber.tag) {
case ClassComponent:
case FunctionComponent:
case ContextConsumer:
case MemoComponent:
case SimpleMemoComponent:
// For types that execute user code, we check PerformedWork effect.
// We don't reflect bailouts (either referential or sCU) in DevTools.
// eslint-disable-next-line no-bitwise
return (nextFiber.effectTag & PerformedWork) === PerformedWork;
// Note: ContextConsumer only gets PerformedWork effect in 16.3.3+
// so it won't get highlighted with React 16.3.0 to 16.3.2.
default:
// For host components and other types, we compare inputs
// to determine whether something is an update.
return (
prevFiber.memoizedProps !== nextFiber.memoizedProps ||
prevFiber.memoizedState !== nextFiber.memoizedState ||
prevFiber.ref !== nextFiber.ref
);
}
}
// eslint-disable-next-line no-unused-vars
function haveProfilerTimesChanged(
prevFiber: Fiber,
nextFiber: Fiber
): boolean {
return (
prevFiber.actualDuration !== undefined && // Short-circuit check for non-profiling builds
(prevFiber.actualDuration !== nextFiber.actualDuration ||
prevFiber.actualStartTime !== nextFiber.actualStartTime ||
prevFiber.treeBaseDuration !== nextFiber.treeBaseDuration)
);
}
let pendingOperations: Uint32Array = new Uint32Array(0);
function addOperation(
newAction: Uint32Array,
addToStartOfQueue: boolean = false
): void {
const oldActions = pendingOperations;
pendingOperations = new Uint32Array(oldActions.length + newAction.length);
if (addToStartOfQueue) {
pendingOperations.set(newAction);
pendingOperations.set(oldActions, newAction.length);
} else {
pendingOperations.set(oldActions);
pendingOperations.set(newAction, oldActions.length);
}
}
function flushPendingEvents(root: Object): void {
if (pendingOperations.length === 0) {
// If we're currently profiling, send an "operations" method even if there are no mutations to the tree.
// The frontend needs this no-op info to know how to reconstruct the tree for each commit,
// even if a particular commit didn't change the shape of the tree.
if (!isProfiling) {
return;
}
}
// Identify which renderer this update is coming from.
// This enables roots to be mapped to renderers,
// Which in turn enables fiber props, states, and hooks to be inspected.
const idArray = new Uint32Array(2);
idArray[0] = rendererID;
idArray[1] = getFiberID(getPrimaryFiber(root.current));
addOperation(idArray, true);
// Let the frontend know about tree operations.
// The first value in this array will identify which root it corresponds to,
// so we do no longer need to dispatch a separate root-committed event.
hook.emit('operations', pendingOperations);
pendingOperations = new Uint32Array(0);
}
function enqueueMount(fiber: Fiber, parentFiber: Fiber | null) {
const isRoot = fiber.tag === HostRoot;
const id = getFiberID(getPrimaryFiber(fiber));
const isProfilingSupported = fiber.hasOwnProperty('treeBaseDuration');
if (isProfilingSupported) {
idToRootMap.set(id, currentRootID);
idToTreeBaseDurationMap.set(id, fiber.treeBaseDuration);
}
if (isRoot) {
const operation = new Uint32Array(4);
operation[0] = TREE_OPERATION_ADD;
operation[1] = id;
operation[2] = ElementTypeRoot;
operation[3] = isProfilingSupported ? 1 : 0;
addOperation(operation);
} else {
const { displayName, key, type } = getDataForFiber(fiber);
const { _debugOwner } = fiber;
const ownerID =
_debugOwner != null ? getFiberID(getPrimaryFiber(_debugOwner)) : 0;
const parentID = getFiberID(getPrimaryFiber(parentFiber));
let encodedDisplayName = ((null: any): Uint8Array);
let encodedKey = ((null: any): Uint8Array);
if (displayName !== null) {
encodedDisplayName = utfEncodeString(displayName);
}
if (key !== null) {
// React$Key supports string and number types as inputs,
// But React converts numeric keys to strings, so we only have to handle that type here.
// https://github.com/facebook/react/blob/0e67969cb1ad8c27a72294662e68fa5d7c2c9783/packages/react/src/ReactElement.js#L187
encodedKey = utfEncodeString(((key: any): string));
}
const encodedDisplayNameSize =
displayName === null ? 0 : encodedDisplayName.length;
const encodedKeySize = key === null ? 0 : encodedKey.length;
const operation = new Uint32Array(
7 + encodedDisplayNameSize + encodedKeySize
);
operation[0] = TREE_OPERATION_ADD;
operation[1] = id;
operation[2] = type;
operation[3] = parentID;
operation[4] = ownerID;
operation[5] = encodedDisplayNameSize;
if (displayName !== null) {
operation.set(encodedDisplayName, 6);
}
operation[6 + encodedDisplayNameSize] = encodedKeySize;
if (key !== null) {
operation.set(encodedKey, 6 + encodedDisplayNameSize + 1);
}
addOperation(operation);
}
if (isProfiling) {
// Tree base duration updates are included in the operations typed array.
// So we have to convert them from milliseconds to microseconds so we can send them as ints.
const treeBaseDuration = Math.floor(fiber.treeBaseDuration * 1000);
const operation = new Uint32Array(3);
operation[0] = TREE_OPERATION_UPDATE_TREE_BASE_DURATION;
operation[1] = id;
operation[2] = treeBaseDuration;
addOperation(operation);
const { actualDuration } = fiber;
if (actualDuration > 0) {
// If profiling is active, store durations for elements that were rendered during the commit.
const metadata = ((currentCommitProfilingMetadata: any): CommitProfilingData);
metadata.actualDurations.push(id, actualDuration);
metadata.maxActualDuration = Math.max(
metadata.maxActualDuration,
actualDuration
);
}
}
}
function enqueueUnmount(fiber) {
const isRoot = fiber.tag === HostRoot;
const primaryFiber = getPrimaryFiber(fiber);
const id = getFiberID(primaryFiber);
if (isRoot) {
const operation = new Uint32Array(2);
operation[0] = TREE_OPERATION_REMOVE;
operation[1] = id;
addOperation(operation);
} else if (!shouldFilterFiber(fiber)) {
// Non-root fibers are deleted during the commit phase.
// They are deleted in the child-first order. However
// DevTools currently expects deletions to be parent-first.
// This is why we unshift deletions rather tha
const operation = new Uint32Array(2);
operation[0] = TREE_OPERATION_REMOVE;
operation[1] = id;
addOperation(operation, true);
}
fiberToIDMap.delete(primaryFiber);
idToFiberMap.delete(id);
primaryFibers.delete(primaryFiber);
const isProfilingSupported = fiber.hasOwnProperty('treeBaseDuration');
if (isProfilingSupported) {
idToRootMap.delete(id);
idToTreeBaseDurationMap.delete(id);
}
}
function mountFiber(fiber: Fiber, parentFiber: Fiber | null) {
debug('mountFiber()', fiber, parentFiber);
const shouldEnqueueMount = !shouldFilterFiber(fiber);
if (shouldEnqueueMount) {
enqueueMount(fiber, parentFiber);
}
if (fiber.child !== null) {
mountFiber(fiber.child, shouldEnqueueMount ? fiber : parentFiber);
}
if (fiber.sibling) {
mountFiber(fiber.sibling, parentFiber);
}
}
function enqueueUpdateIfNecessary(
fiber: Fiber,
hasChildOrderChanged: boolean
) {
debug('enqueueUpdateIfNecessary()', fiber);
const isProfilingSupported = fiber.hasOwnProperty('treeBaseDuration');
if (isProfilingSupported) {
const id = getFiberID(getPrimaryFiber(fiber));
const { actualDuration, treeBaseDuration } = fiber;
idToTreeBaseDurationMap.set(id, fiber.treeBaseDuration);
if (isProfiling) {
if (treeBaseDuration !== fiber.alternate.treeBaseDuration) {
// Tree base duration updates are included in the operations typed array.
// So we have to convert them from milliseconds to microseconds so we can send them as ints.
const treeBaseDuration = Math.floor(fiber.treeBaseDuration * 1000);
const operation = new Uint32Array(3);
operation[0] = TREE_OPERATION_UPDATE_TREE_BASE_DURATION;
operation[1] = getFiberID(getPrimaryFiber(fiber));
operation[2] = treeBaseDuration;
addOperation(operation);
}
if (haveProfilerTimesChanged(fiber.alternate, fiber)) {
if (actualDuration > 0) {
// If profiling is active, store durations for elements that were rendered during the commit.
const metadata = ((currentCommitProfilingMetadata: any): CommitProfilingData);
metadata.actualDurations.push(id, actualDuration);
metadata.maxActualDuration = Math.max(
metadata.maxActualDuration,
actualDuration
);
}
}
}
}
// The frontend only really cares about the displayName, key, and children.
// The first two don't really change, so we are only concerned with the order of children here.
// This is trickier than a simple comparison though, since certain types of fibers are filtered.
if (hasChildOrderChanged) {
const nextChildren: Array<number> = [];
// This is a naive implimentation that shallowly recurses children.
// We might want to revisit this if it proves to be too inefficient.
let child = fiber.child;
while (child !== null) {
findReorderedChildren(child, nextChildren);
child = child.sibling;
}
const numChildren = nextChildren.length;
const operation = new Uint32Array(3 + numChildren);
operation[0] = TREE_OPERATION_RESET_CHILDREN;
operation[1] = getFiberID(getPrimaryFiber(fiber));
operation[2] = numChildren;
operation.set(nextChildren, 3);
addOperation(operation);
}
}
function findReorderedChildren(fiber: Fiber, nextChildren: Array<number>) {
if (!shouldFilterFiber(fiber)) {
nextChildren.push(getFiberID(getPrimaryFiber(fiber)));
} else {
let child = fiber.child;
while (child !== null) {
findReorderedChildren(child, nextChildren);
child = child.sibling;
}
}
}
function updateFiber(
nextFiber: Fiber,
prevFiber: Fiber,
parentFiber: Fiber | null
) {
debug('enqueueUpdateIfNecessary()', nextFiber, parentFiber);
const shouldEnqueueUpdate = !shouldFilterFiber(nextFiber);
// Suspense components only have a non-null memoizedState if they're timed-out.
const isTimedOutSuspense =
nextFiber.tag === ReactTypeOfWork.SuspenseComponent &&
nextFiber.memoizedState !== null;
if (isTimedOutSuspense) {
// The behavior of timed-out Suspense trees is unique.
// Rather than unmount the timed out content (and possibly lose important state),
// React re-parents this content within a hidden Fragment while the fallback is showing.
// This behavior doesn't need to be observable in the DevTools though.
// It might even result in a bad user experience for e.g. node selection in the Elements panel.
// The easiest fix is to strip out the intermediate Fragment fibers,
// so the Elements panel and Profiler don't need to special case them.
const primaryChildFragment = nextFiber.child;
const fallbackChildFragment = primaryChildFragment.sibling;
const fallbackChild = fallbackChildFragment.child;
// The primary, hidden child is never actually updated in this case,
// so we can skip any updates to its tree.
// We only need to track updates to the Fallback UI for now.
if (fallbackChild.alternate) {
updateFiber(fallbackChild, fallbackChild.alternate, nextFiber);
} else {
mountFiber(fallbackChild, nextFiber);
}
if (shouldEnqueueUpdate) {
enqueueUpdateIfNecessary(nextFiber, false);
}
} else {
let hasChildOrderChanged = false;
if (nextFiber.child !== prevFiber.child) {
// If the first child is different, we need to traverse them.
// Each next child will be either a new child (mount) or an alternate (update).
let nextChild = nextFiber.child;
let prevChildAtSameIndex = prevFiber.child;
while (nextChild) {
// We already know children will be referentially different because
// they are either new mounts or alternates of previous children.
// Schedule updates and mounts depending on whether alternates exist.
// We don't track deletions here because they are reported separately.
if (nextChild.alternate) {
const prevChild = nextChild.alternate;
updateFiber(
nextChild,
prevChild,
shouldEnqueueUpdate ? nextFiber : parentFiber
);
// However we also keep track if the order of the children matches
// the previous order. They are always different referentially, but
// if the instances line up conceptually we'll want to know that.
if (!hasChildOrderChanged && prevChild !== prevChildAtSameIndex) {
hasChildOrderChanged = true;
}
} else {
mountFiber(
nextChild,
shouldEnqueueUpdate ? nextFiber : parentFiber
);
if (!hasChildOrderChanged) {
hasChildOrderChanged = true;
}
}
// Try the next child.
nextChild = nextChild.sibling;
// Advance the pointer in the previous list so that we can
// keep comparing if they line up.
if (!hasChildOrderChanged && prevChildAtSameIndex != null) {
prevChildAtSameIndex = prevChildAtSameIndex.sibling;
}
}
// If we have no more children, but used to, they don't line up.
if (!hasChildOrderChanged && prevChildAtSameIndex != null) {
hasChildOrderChanged = true;
}
}
if (shouldEnqueueUpdate) {
enqueueUpdateIfNecessary(nextFiber, hasChildOrderChanged);
}
}
}
function cleanup() {
// We don't patch any methods so there is no cleanup.
}
function walkTree() {
// Hydrate all the roots for the first time.
hook.getFiberRoots(rendererID).forEach(root => {
currentRootID = getFiberID(getPrimaryFiber(root.current));
if (isProfiling) {
// If profiling is active, store commit time and duration, and the current interactions.
// The frontend may request this information after profiling has stopped.
currentCommitProfilingMetadata = {
actualDurations: [],
commitTime: performance.now() - profilingStartTime,
interactions: Array.from(root.memoizedInteractions).map(
(interaction: Interaction) => ({
...interaction,
timestamp: interaction.timestamp - profilingStartTime,
})
),
maxActualDuration: 0,
};
}
mountFiber(root.current, null);
flushPendingEvents(root);
currentRootID = -1;
});
}
function handleCommitFiberUnmount(fiber) {
// This is not recursive.
// We can't traverse fibers after unmounting so instead
// we rely on React telling us about each unmount.
enqueueUnmount(fiber);
}
function handleCommitFiberRoot(root) {
const current = root.current;
const alternate = current.alternate;
currentRootID = getFiberID(getPrimaryFiber(current));
if (isProfiling) {
// If profiling is active, store commit time and duration, and the current interactions.
// The frontend may request this information after profiling has stopped.
currentCommitProfilingMetadata = {
actualDurations: [],
commitTime: performance.now() - profilingStartTime,
interactions: Array.from(root.memoizedInteractions).map(
(interaction: Interaction) => ({
...interaction,
timestamp: interaction.timestamp - profilingStartTime,
})
),
maxActualDuration: 0,
};
}
if (alternate) {
// TODO: relying on this seems a bit fishy.
const wasMounted =
alternate.memoizedState != null &&
alternate.memoizedState.element != null;
const isMounted =
current.memoizedState != null && current.memoizedState.element != null;
if (!wasMounted && isMounted) {
// Mount a new root.
mountFiber(current, null);
} else if (wasMounted && isMounted) {
// Update an existing root.
updateFiber(current, alternate, null);
} else if (wasMounted && !isMounted) {
// Unmount an existing root.
enqueueUnmount(current);
}
} else {
// Mount a new root.
mountFiber(current, null);
}
if (isProfiling) {
const commitProfilingMetadata = ((rootToCommitProfilingMetadataMap: any): CommitProfilingMetadataMap).get(
currentRootID
);
if (commitProfilingMetadata != null) {
commitProfilingMetadata.push(
((currentCommitProfilingMetadata: any): CommitProfilingData)