-
Notifications
You must be signed in to change notification settings - Fork 46.9k
/
store.js
1556 lines (1297 loc) · 48.1 KB
/
store.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 {copy} from 'clipboard-js';
import EventEmitter from '../events';
import {inspect} from 'util';
import {
PROFILING_FLAG_BASIC_SUPPORT,
PROFILING_FLAG_TIMELINE_SUPPORT,
TREE_OPERATION_ADD,
TREE_OPERATION_REMOVE,
TREE_OPERATION_REMOVE_ROOT,
TREE_OPERATION_REORDER_CHILDREN,
TREE_OPERATION_SET_SUBTREE_MODE,
TREE_OPERATION_UPDATE_ERRORS_OR_WARNINGS,
TREE_OPERATION_UPDATE_TREE_BASE_DURATION,
} from '../constants';
import {ElementTypeRoot} from '../frontend/types';
import {
getSavedComponentFilters,
setSavedComponentFilters,
shallowDiffers,
utfDecodeStringWithRanges,
parseElementDisplayNameFromBackend,
} from '../utils';
import {localStorageGetItem, localStorageSetItem} from '../storage';
import {__DEBUG__} from '../constants';
import {printStore} from './utils';
import ProfilerStore from './ProfilerStore';
import {
BRIDGE_PROTOCOL,
currentBridgeProtocol,
} from 'react-devtools-shared/src/bridge';
import {StrictMode} from 'react-devtools-shared/src/frontend/types';
import type {
Element,
ComponentFilter,
ElementType,
} from 'react-devtools-shared/src/frontend/types';
import type {
FrontendBridge,
BridgeProtocol,
} from 'react-devtools-shared/src/bridge';
import UnsupportedBridgeOperationError from 'react-devtools-shared/src/UnsupportedBridgeOperationError';
import type {DevToolsHookSettings} from '../backend/types';
const debug = (methodName: string, ...args: Array<string>) => {
if (__DEBUG__) {
console.log(
`%cStore %c${methodName}`,
'color: green; font-weight: bold;',
'font-weight: bold;',
...args,
);
}
};
const LOCAL_STORAGE_COLLAPSE_ROOTS_BY_DEFAULT_KEY =
'React::DevTools::collapseNodesByDefault';
const LOCAL_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY =
'React::DevTools::recordChangeDescriptions';
type ErrorAndWarningTuples = Array<{id: number, index: number}>;
export type Config = {
checkBridgeProtocolCompatibility?: boolean,
isProfiling?: boolean,
supportsInspectMatchingDOMElement?: boolean,
supportsClickToInspect?: boolean,
supportsReloadAndProfile?: boolean,
supportsTimeline?: boolean,
supportsTraceUpdates?: boolean,
};
export type Capabilities = {
supportsBasicProfiling: boolean,
hasOwnerMetadata: boolean,
supportsStrictMode: boolean,
supportsTimeline: boolean,
};
/**
* The store is the single source of truth for updates from the backend.
* ContextProviders can subscribe to the Store for specific things they want to provide.
*/
export default class Store extends EventEmitter<{
backendVersion: [],
collapseNodesByDefault: [],
componentFilters: [],
error: [Error],
hookSettings: [$ReadOnly<DevToolsHookSettings>],
settingsUpdated: [$ReadOnly<DevToolsHookSettings>],
mutated: [[Array<number>, Map<number, number>]],
recordChangeDescriptions: [],
roots: [],
rootSupportsBasicProfiling: [],
rootSupportsTimelineProfiling: [],
supportsNativeStyleEditor: [],
supportsReloadAndProfile: [],
unsupportedBridgeProtocolDetected: [],
unsupportedRendererVersionDetected: [],
}> {
// If the backend version is new enough to report its (NPM) version, this is it.
// This version may be displayed by the frontend for debugging purposes.
_backendVersion: string | null = null;
_bridge: FrontendBridge;
// Computed whenever _errorsAndWarnings Map changes.
_cachedComponentWithErrorCount: number = 0;
_cachedComponentWithWarningCount: number = 0;
_cachedErrorAndWarningTuples: ErrorAndWarningTuples | null = null;
// Should new nodes be collapsed by default when added to the tree?
_collapseNodesByDefault: boolean = true;
_componentFilters: Array<ComponentFilter>;
// Map of ID to number of recorded error and warning message IDs.
_errorsAndWarnings: Map<number, {errorCount: number, warningCount: number}> =
new Map();
// At least one of the injected renderers contains (DEV only) owner metadata.
_hasOwnerMetadata: boolean = false;
// Map of ID to (mutable) Element.
// Elements are mutated to avoid excessive cloning during tree updates.
// The InspectedElement Suspense cache also relies on this mutability for its WeakMap usage.
_idToElement: Map<number, Element> = new Map();
// Should the React Native style editor panel be shown?
_isNativeStyleEditorSupported: boolean = false;
_nativeStyleEditorValidAttributes: $ReadOnlyArray<string> | null = null;
// Older backends don't support an explicit bridge protocol,
// so we should timeout eventually and show a downgrade message.
_onBridgeProtocolTimeoutID: TimeoutID | null = null;
// Map of element (id) to the set of elements (ids) it owns.
// This map enables getOwnersListForElement() to avoid traversing the entire tree.
_ownersMap: Map<number, Set<number>> = new Map();
_profilerStore: ProfilerStore;
_recordChangeDescriptions: boolean = false;
// Incremented each time the store is mutated.
// This enables a passive effect to detect a mutation between render and commit phase.
_revision: number = 0;
// This Array must be treated as immutable!
// Passive effects will check it for changes between render and mount.
_roots: $ReadOnlyArray<number> = [];
_rootIDToCapabilities: Map<number, Capabilities> = new Map();
// Renderer ID is needed to support inspection fiber props, state, and hooks.
_rootIDToRendererID: Map<number, number> = new Map();
// These options may be initially set by a configuration option when constructing the Store.
_supportsInspectMatchingDOMElement: boolean = false;
_supportsClickToInspect: boolean = false;
_supportsTimeline: boolean = false;
_supportsTraceUpdates: boolean = false;
_isReloadAndProfileFrontendSupported: boolean = false;
_isReloadAndProfileBackendSupported: boolean = false;
// These options default to false but may be updated as roots are added and removed.
_rootSupportsBasicProfiling: boolean = false;
_rootSupportsTimelineProfiling: boolean = false;
_bridgeProtocol: BridgeProtocol | null = null;
_unsupportedBridgeProtocolDetected: boolean = false;
_unsupportedRendererVersionDetected: boolean = false;
// Total number of visible elements (within all roots).
// Used for windowing purposes.
_weightAcrossRoots: number = 0;
_shouldCheckBridgeProtocolCompatibility: boolean = false;
_hookSettings: $ReadOnly<DevToolsHookSettings> | null = null;
_shouldShowWarningsAndErrors: boolean = false;
constructor(bridge: FrontendBridge, config?: Config) {
super();
if (__DEBUG__) {
debug('constructor', 'subscribing to Bridge');
}
this._collapseNodesByDefault =
localStorageGetItem(LOCAL_STORAGE_COLLAPSE_ROOTS_BY_DEFAULT_KEY) ===
'true';
this._recordChangeDescriptions =
localStorageGetItem(LOCAL_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY) ===
'true';
this._componentFilters = getSavedComponentFilters();
let isProfiling = false;
if (config != null) {
isProfiling = config.isProfiling === true;
const {
supportsInspectMatchingDOMElement,
supportsClickToInspect,
supportsReloadAndProfile,
supportsTimeline,
supportsTraceUpdates,
checkBridgeProtocolCompatibility,
} = config;
if (supportsInspectMatchingDOMElement) {
this._supportsInspectMatchingDOMElement = true;
}
if (supportsClickToInspect) {
this._supportsClickToInspect = true;
}
if (supportsReloadAndProfile) {
this._isReloadAndProfileFrontendSupported = true;
}
if (supportsTimeline) {
this._supportsTimeline = true;
}
if (supportsTraceUpdates) {
this._supportsTraceUpdates = true;
}
if (checkBridgeProtocolCompatibility) {
this._shouldCheckBridgeProtocolCompatibility = true;
}
}
this._bridge = bridge;
bridge.addListener('operations', this.onBridgeOperations);
bridge.addListener(
'overrideComponentFilters',
this.onBridgeOverrideComponentFilters,
);
bridge.addListener('shutdown', this.onBridgeShutdown);
bridge.addListener(
'isReloadAndProfileSupportedByBackend',
this.onBackendReloadAndProfileSupported,
);
bridge.addListener(
'isNativeStyleEditorSupported',
this.onBridgeNativeStyleEditorSupported,
);
bridge.addListener(
'unsupportedRendererVersion',
this.onBridgeUnsupportedRendererVersion,
);
this._profilerStore = new ProfilerStore(bridge, this, isProfiling);
bridge.addListener('backendVersion', this.onBridgeBackendVersion);
bridge.addListener('saveToClipboard', this.onSaveToClipboard);
bridge.addListener('hookSettings', this.onHookSettings);
bridge.addListener('backendInitialized', this.onBackendInitialized);
}
// This is only used in tests to avoid memory leaks.
assertExpectedRootMapSizes() {
if (this.roots.length === 0) {
// The only safe time to assert these maps are empty is when the store is empty.
this.assertMapSizeMatchesRootCount(this._idToElement, '_idToElement');
this.assertMapSizeMatchesRootCount(this._ownersMap, '_ownersMap');
}
// These maps should always be the same size as the number of roots
this.assertMapSizeMatchesRootCount(
this._rootIDToCapabilities,
'_rootIDToCapabilities',
);
this.assertMapSizeMatchesRootCount(
this._rootIDToRendererID,
'_rootIDToRendererID',
);
}
// This is only used in tests to avoid memory leaks.
assertMapSizeMatchesRootCount(map: Map<any, any>, mapName: string) {
const expectedSize = this.roots.length;
if (map.size !== expectedSize) {
this._throwAndEmitError(
Error(
`Expected ${mapName} to contain ${expectedSize} items, but it contains ${
map.size
} items\n\n${inspect(map, {
depth: 20,
})}`,
),
);
}
}
get backendVersion(): string | null {
return this._backendVersion;
}
get collapseNodesByDefault(): boolean {
return this._collapseNodesByDefault;
}
set collapseNodesByDefault(value: boolean): void {
this._collapseNodesByDefault = value;
localStorageSetItem(
LOCAL_STORAGE_COLLAPSE_ROOTS_BY_DEFAULT_KEY,
value ? 'true' : 'false',
);
this.emit('collapseNodesByDefault');
}
get componentFilters(): Array<ComponentFilter> {
return this._componentFilters;
}
set componentFilters(value: Array<ComponentFilter>): void {
if (this._profilerStore.isProfilingBasedOnUserInput) {
// Re-mounting a tree while profiling is in progress might break a lot of assumptions.
// If necessary, we could support this- but it doesn't seem like a necessary use case.
this._throwAndEmitError(
Error('Cannot modify filter preferences while profiling'),
);
}
// Filter updates are expensive to apply (since they impact the entire tree).
// Let's determine if they've changed and avoid doing this work if they haven't.
const prevEnabledComponentFilters = this._componentFilters.filter(
filter => filter.isEnabled,
);
const nextEnabledComponentFilters = value.filter(
filter => filter.isEnabled,
);
let haveEnabledFiltersChanged =
prevEnabledComponentFilters.length !== nextEnabledComponentFilters.length;
if (!haveEnabledFiltersChanged) {
for (let i = 0; i < nextEnabledComponentFilters.length; i++) {
const prevFilter = prevEnabledComponentFilters[i];
const nextFilter = nextEnabledComponentFilters[i];
if (shallowDiffers(prevFilter, nextFilter)) {
haveEnabledFiltersChanged = true;
break;
}
}
}
this._componentFilters = value;
// Update persisted filter preferences stored in localStorage.
setSavedComponentFilters(value);
// Notify the renderer that filter preferences have changed.
// This is an expensive operation; it unmounts and remounts the entire tree,
// so only do it if the set of enabled component filters has changed.
if (haveEnabledFiltersChanged) {
this._bridge.send('updateComponentFilters', value);
}
this.emit('componentFilters');
}
get bridgeProtocol(): BridgeProtocol | null {
return this._bridgeProtocol;
}
get componentWithErrorCount(): number {
if (!this._shouldShowWarningsAndErrors) {
return 0;
}
return this._cachedComponentWithErrorCount;
}
get componentWithWarningCount(): number {
if (!this._shouldShowWarningsAndErrors) {
return 0;
}
return this._cachedComponentWithWarningCount;
}
get displayingErrorsAndWarningsEnabled(): boolean {
return this._shouldShowWarningsAndErrors;
}
get hasOwnerMetadata(): boolean {
return this._hasOwnerMetadata;
}
get nativeStyleEditorValidAttributes(): $ReadOnlyArray<string> | null {
return this._nativeStyleEditorValidAttributes;
}
get numElements(): number {
return this._weightAcrossRoots;
}
get profilerStore(): ProfilerStore {
return this._profilerStore;
}
get recordChangeDescriptions(): boolean {
return this._recordChangeDescriptions;
}
set recordChangeDescriptions(value: boolean): void {
this._recordChangeDescriptions = value;
localStorageSetItem(
LOCAL_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY,
value ? 'true' : 'false',
);
this.emit('recordChangeDescriptions');
}
get revision(): number {
return this._revision;
}
get rootIDToRendererID(): Map<number, number> {
return this._rootIDToRendererID;
}
get roots(): $ReadOnlyArray<number> {
return this._roots;
}
// At least one of the currently mounted roots support the Legacy profiler.
get rootSupportsBasicProfiling(): boolean {
return this._rootSupportsBasicProfiling;
}
// At least one of the currently mounted roots support the Timeline profiler.
get rootSupportsTimelineProfiling(): boolean {
return this._rootSupportsTimelineProfiling;
}
get supportsInspectMatchingDOMElement(): boolean {
return this._supportsInspectMatchingDOMElement;
}
get supportsClickToInspect(): boolean {
return this._supportsClickToInspect;
}
get supportsNativeStyleEditor(): boolean {
return this._isNativeStyleEditorSupported;
}
get supportsReloadAndProfile(): boolean {
return (
this._isReloadAndProfileFrontendSupported &&
this._isReloadAndProfileBackendSupported
);
}
// This build of DevTools supports the Timeline profiler.
// This is a static flag, controlled by the Store config.
get supportsTimeline(): boolean {
return this._supportsTimeline;
}
get supportsTraceUpdates(): boolean {
return this._supportsTraceUpdates;
}
get unsupportedBridgeProtocolDetected(): boolean {
return this._unsupportedBridgeProtocolDetected;
}
get unsupportedRendererVersionDetected(): boolean {
return this._unsupportedRendererVersionDetected;
}
containsElement(id: number): boolean {
return this._idToElement.has(id);
}
getElementAtIndex(index: number): Element | null {
if (index < 0 || index >= this.numElements) {
console.warn(
`Invalid index ${index} specified; store contains ${this.numElements} items.`,
);
return null;
}
// Find which root this element is in...
let root;
let rootWeight = 0;
for (let i = 0; i < this._roots.length; i++) {
const rootID = this._roots[i];
root = this._idToElement.get(rootID);
if (root === undefined) {
this._throwAndEmitError(
Error(
`Couldn't find root with id "${rootID}": no matching node was found in the Store.`,
),
);
return null;
}
if (root.children.length === 0) {
continue;
}
if (rootWeight + root.weight > index) {
break;
} else {
rootWeight += root.weight;
}
}
if (root === undefined) {
return null;
}
// Find the element in the tree using the weight of each node...
// Skip over the root itself, because roots aren't visible in the Elements tree.
let currentElement: Element = root;
let currentWeight = rootWeight - 1;
while (index !== currentWeight) {
const numChildren = currentElement.children.length;
for (let i = 0; i < numChildren; i++) {
const childID = currentElement.children[i];
const child = this._idToElement.get(childID);
if (child === undefined) {
this._throwAndEmitError(
Error(
`Couldn't child element with id "${childID}": no matching node was found in the Store.`,
),
);
return null;
}
const childWeight = child.isCollapsed ? 1 : child.weight;
if (index <= currentWeight + childWeight) {
currentWeight++;
currentElement = child;
break;
} else {
currentWeight += childWeight;
}
}
}
return currentElement || null;
}
getElementIDAtIndex(index: number): number | null {
const element = this.getElementAtIndex(index);
return element === null ? null : element.id;
}
getElementByID(id: number): Element | null {
const element = this._idToElement.get(id);
if (element === undefined) {
console.warn(`No element found with id "${id}"`);
return null;
}
return element;
}
// Returns a tuple of [id, index]
getElementsWithErrorsAndWarnings(): ErrorAndWarningTuples {
if (!this._shouldShowWarningsAndErrors) {
return [];
}
if (this._cachedErrorAndWarningTuples !== null) {
return this._cachedErrorAndWarningTuples;
}
const errorAndWarningTuples: ErrorAndWarningTuples = [];
this._errorsAndWarnings.forEach((_, id) => {
const index = this.getIndexOfElementID(id);
if (index !== null) {
let low = 0;
let high = errorAndWarningTuples.length;
while (low < high) {
const mid = (low + high) >> 1;
if (errorAndWarningTuples[mid].index > index) {
high = mid;
} else {
low = mid + 1;
}
}
errorAndWarningTuples.splice(low, 0, {id, index});
}
});
// Cache for later (at least until the tree changes again).
this._cachedErrorAndWarningTuples = errorAndWarningTuples;
return errorAndWarningTuples;
}
getErrorAndWarningCountForElementID(id: number): {
errorCount: number,
warningCount: number,
} {
if (!this._shouldShowWarningsAndErrors) {
return {errorCount: 0, warningCount: 0};
}
return this._errorsAndWarnings.get(id) || {errorCount: 0, warningCount: 0};
}
getIndexOfElementID(id: number): number | null {
const element = this.getElementByID(id);
if (element === null || element.parentID === 0) {
return null;
}
// Walk up the tree to the root.
// Increment the index by one for each node we encounter,
// and by the weight of all nodes to the left of the current one.
// This should be a relatively fast way of determining the index of a node within the tree.
let previousID = id;
let currentID = element.parentID;
let index = 0;
while (true) {
const current = this._idToElement.get(currentID);
if (current === undefined) {
return null;
}
const {children} = current;
for (let i = 0; i < children.length; i++) {
const childID = children[i];
if (childID === previousID) {
break;
}
const child = this._idToElement.get(childID);
if (child === undefined) {
return null;
}
index += child.isCollapsed ? 1 : child.weight;
}
if (current.parentID === 0) {
// We found the root; stop crawling.
break;
}
index++;
previousID = current.id;
currentID = current.parentID;
}
// At this point, the current ID is a root (from the previous loop).
// We also need to offset the index by previous root weights.
for (let i = 0; i < this._roots.length; i++) {
const rootID = this._roots[i];
if (rootID === currentID) {
break;
}
const root = this._idToElement.get(rootID);
if (root === undefined) {
return null;
}
index += root.weight;
}
return index;
}
getOwnersListForElement(ownerID: number): Array<Element> {
const list: Array<Element> = [];
const element = this._idToElement.get(ownerID);
if (element !== undefined) {
list.push({
...element,
depth: 0,
});
const unsortedIDs = this._ownersMap.get(ownerID);
if (unsortedIDs !== undefined) {
const depthMap: Map<number, number> = new Map([[ownerID, 0]]);
// Items in a set are ordered based on insertion.
// This does not correlate with their order in the tree.
// So first we need to order them.
// I wish we could avoid this sorting operation; we could sort at insertion time,
// but then we'd have to pay sorting costs even if the owners list was never used.
// Seems better to defer the cost, since the set of ids is probably pretty small.
const sortedIDs = Array.from(unsortedIDs).sort(
(idA, idB) =>
(this.getIndexOfElementID(idA) || 0) -
(this.getIndexOfElementID(idB) || 0),
);
// Next we need to determine the appropriate depth for each element in the list.
// The depth in the list may not correspond to the depth in the tree,
// because the list has been filtered to remove intermediate components.
// Perhaps the easiest way to do this is to walk up the tree until we reach either:
// (1) another node that's already in the tree, or (2) the root (owner)
// at which point, our depth is just the depth of that node plus one.
sortedIDs.forEach(id => {
const innerElement = this._idToElement.get(id);
if (innerElement !== undefined) {
let parentID = innerElement.parentID;
let depth = 0;
while (parentID > 0) {
if (parentID === ownerID || unsortedIDs.has(parentID)) {
// $FlowFixMe[unsafe-addition] addition with possible null/undefined value
depth = depthMap.get(parentID) + 1;
depthMap.set(id, depth);
break;
}
const parent = this._idToElement.get(parentID);
if (parent === undefined) {
break;
}
parentID = parent.parentID;
}
if (depth === 0) {
this._throwAndEmitError(Error('Invalid owners list'));
}
list.push({...innerElement, depth});
}
});
}
}
return list;
}
getRendererIDForElement(id: number): number | null {
let current = this._idToElement.get(id);
while (current !== undefined) {
if (current.parentID === 0) {
const rendererID = this._rootIDToRendererID.get(current.id);
return rendererID == null ? null : rendererID;
} else {
current = this._idToElement.get(current.parentID);
}
}
return null;
}
getRootIDForElement(id: number): number | null {
let current = this._idToElement.get(id);
while (current !== undefined) {
if (current.parentID === 0) {
return current.id;
} else {
current = this._idToElement.get(current.parentID);
}
}
return null;
}
isInsideCollapsedSubTree(id: number): boolean {
let current = this._idToElement.get(id);
while (current != null) {
if (current.parentID === 0) {
return false;
} else {
current = this._idToElement.get(current.parentID);
if (current != null && current.isCollapsed) {
return true;
}
}
}
return false;
}
// TODO Maybe split this into two methods: expand() and collapse()
toggleIsCollapsed(id: number, isCollapsed: boolean): void {
let didMutate = false;
const element = this.getElementByID(id);
if (element !== null) {
if (isCollapsed) {
if (element.type === ElementTypeRoot) {
this._throwAndEmitError(Error('Root nodes cannot be collapsed'));
}
if (!element.isCollapsed) {
didMutate = true;
element.isCollapsed = true;
const weightDelta = 1 - element.weight;
let parentElement = this._idToElement.get(element.parentID);
while (parentElement !== undefined) {
// We don't need to break on a collapsed parent in the same way as the expand case below.
// That's because collapsing a node doesn't "bubble" and affect its parents.
parentElement.weight += weightDelta;
parentElement = this._idToElement.get(parentElement.parentID);
}
}
} else {
let currentElement: ?Element = element;
while (currentElement != null) {
const oldWeight = currentElement.isCollapsed
? 1
: currentElement.weight;
if (currentElement.isCollapsed) {
didMutate = true;
currentElement.isCollapsed = false;
const newWeight = currentElement.isCollapsed
? 1
: currentElement.weight;
const weightDelta = newWeight - oldWeight;
let parentElement = this._idToElement.get(currentElement.parentID);
while (parentElement !== undefined) {
parentElement.weight += weightDelta;
if (parentElement.isCollapsed) {
// It's important to break on a collapsed parent when expanding nodes.
// That's because expanding a node "bubbles" up and expands all parents as well.
// Breaking in this case prevents us from over-incrementing the expanded weights.
break;
}
parentElement = this._idToElement.get(parentElement.parentID);
}
}
currentElement =
currentElement.parentID !== 0
? this.getElementByID(currentElement.parentID)
: null;
}
}
// Only re-calculate weights and emit an "update" event if the store was mutated.
if (didMutate) {
let weightAcrossRoots = 0;
this._roots.forEach(rootID => {
const {weight} = ((this.getElementByID(rootID): any): Element);
weightAcrossRoots += weight;
});
this._weightAcrossRoots = weightAcrossRoots;
// The Tree context's search reducer expects an explicit list of ids for nodes that were added or removed.
// In this case, we can pass it empty arrays since nodes in a collapsed tree are still there (just hidden).
// Updating the selected search index later may require auto-expanding a collapsed subtree though.
this.emit('mutated', [[], new Map()]);
}
}
}
_adjustParentTreeWeight: (
parentElement: ?Element,
weightDelta: number,
) => void = (parentElement, weightDelta) => {
let isInsideCollapsedSubTree = false;
while (parentElement != null) {
parentElement.weight += weightDelta;
// Additions and deletions within a collapsed subtree should not bubble beyond the collapsed parent.
// Their weight will bubble up when the parent is expanded.
if (parentElement.isCollapsed) {
isInsideCollapsedSubTree = true;
break;
}
parentElement = this._idToElement.get(parentElement.parentID);
}
// Additions and deletions within a collapsed subtree should not affect the overall number of elements.
if (!isInsideCollapsedSubTree) {
this._weightAcrossRoots += weightDelta;
}
};
_recursivelyUpdateSubtree(
id: number,
callback: (element: Element) => void,
): void {
const element = this._idToElement.get(id);
if (element) {
callback(element);
element.children.forEach(child =>
this._recursivelyUpdateSubtree(child, callback),
);
}
}
onBridgeNativeStyleEditorSupported: ({
isSupported: boolean,
validAttributes: ?$ReadOnlyArray<string>,
}) => void = ({isSupported, validAttributes}) => {
this._isNativeStyleEditorSupported = isSupported;
this._nativeStyleEditorValidAttributes = validAttributes || null;
this.emit('supportsNativeStyleEditor');
};
onBridgeOperations: (operations: Array<number>) => void = operations => {
if (__DEBUG__) {
console.groupCollapsed('onBridgeOperations');
debug('onBridgeOperations', operations.join(','));
}
let haveRootsChanged = false;
let haveErrorsOrWarningsChanged = false;
// The first two values are always rendererID and rootID
const rendererID = operations[0];
const addedElementIDs: Array<number> = [];
// This is a mapping of removed ID -> parent ID:
const removedElementIDs: Map<number, number> = new Map();
// We'll use the parent ID to adjust selection if it gets deleted.
let i = 2;
// Reassemble the string table.
const stringTable: Array<string | null> = [
null, // ID = 0 corresponds to the null string.
];
const stringTableSize = operations[i];
i++;
const stringTableEnd = i + stringTableSize;
while (i < stringTableEnd) {
const nextLength = operations[i];
i++;
const nextString = utfDecodeStringWithRanges(
operations,
i,
i + nextLength - 1,
);
stringTable.push(nextString);
i += nextLength;
}
while (i < operations.length) {
const operation = operations[i];
switch (operation) {
case TREE_OPERATION_ADD: {
const id = operations[i + 1];
const type = ((operations[i + 2]: any): ElementType);
i += 3;
if (this._idToElement.has(id)) {
this._throwAndEmitError(
Error(
`Cannot add node "${id}" because a node with that id is already in the Store.`,
),
);
}
if (type === ElementTypeRoot) {
if (__DEBUG__) {
debug('Add', `new root node ${id}`);
}
const isStrictModeCompliant = operations[i] > 0;
i++;
const supportsBasicProfiling =
(operations[i] & PROFILING_FLAG_BASIC_SUPPORT) !== 0;
const supportsTimeline =
(operations[i] & PROFILING_FLAG_TIMELINE_SUPPORT) !== 0;
i++;
let supportsStrictMode = false;
let hasOwnerMetadata = false;
// If we don't know the bridge protocol, guess that we're dealing with the latest.
// If we do know it, we can take it into consideration when parsing operations.
if (
this._bridgeProtocol === null ||