-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
mct-tree.vue
1033 lines (901 loc) · 36.5 KB
/
mct-tree.vue
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
<template>
<div
ref="treeContainer"
class="c-tree-and-search"
:class="{
'c-selector': isSelectorTree
}"
>
<div
ref="search"
class="c-tree-and-search__search"
>
<search
v-show="isSelectorTree"
ref="shell-search"
class="c-search"
:value="searchValue"
@input="searchTree"
@clear="searchTree"
/>
</div>
<!-- search loading -->
<div
v-if="searchLoading && activeSearch"
class="c-tree__item c-tree-and-search__loading loading"
>
<span class="c-tree__item__label">Searching...</span>
</div>
<!-- no results -->
<div
v-if="showNoSearchResults"
class="c-tree-and-search__no-results"
>
No results found
</div>
<!-- main tree -->
<div
ref="mainTree"
class="c-tree-and-search__tree c-tree"
role="tree"
:aria-label="getAriaLabel"
aria-expanded="true"
>
<div
ref="dummyItem"
class="c-tree__item-h"
style="left: -1000px; position: absolute; visibility: hidden"
>
<div class="c-tree__item">
<span class="c-tree__item__view-control c-nav__up is-enabled"></span>
<a
class="c-tree__item__label c-object-label"
draggable="true"
href="#"
>
<div class="c-tree__item__type-icon c-object-label__type-icon icon-folder">
<span title="Open MCT"></span>
</div>
<div class="c-tree__item__name c-object-label__name">
Open MCT
</div>
</a>
<span class="c-tree__item__view-control c-nav__down"></span>
</div>
</div>
<div
ref="scrollable"
class="c-tree__scrollable"
:style="scrollableStyles"
@scroll="updateVisibleItems()"
>
<div :style="childrenHeightStyles">
<tree-item
v-for="(treeItem, index) in visibleItems"
:key="`${treeItem.navigationPath}-${index}`"
:node="treeItem"
:is-selector-tree="isSelectorTree"
:selected-item="selectedItem"
:active-search="activeSearch"
:left-offset="!activeSearch ? treeItem.leftOffset : '0px'"
:is-new="treeItem.isNew"
:item-offset="itemOffset"
:item-index="index"
:item-height="itemHeight"
:open-items="openTreeItems"
:loading-items="treeItemLoading"
:targeted-path="targetedPath"
@tree-item-mounted="scrollToCheck($event)"
@tree-item-destroyed="removeCompositionListenerFor($event)"
@tree-item-action="treeItemAction(treeItem, $event)"
@tree-item-selection="treeItemSelection(treeItem)"
@targeted-path-animation-end="targetedPathAnimationEnd()"
/>
<!-- main loading -->
<div
v-if="isLoading"
class="c-tree__item c-tree-and-search__loading loading"
>
<span class="c-tree__item__label">Loading...</span>
</div>
<!-- end loading -->
<div
v-if="showNoItems"
class="c-tree__item c-tree__item--empty"
>
No items
</div>
</div>
</div>
</div>
<!-- end main tree -->
</div>
</template>
<script>
import _ from 'lodash';
import treeItem from './tree-item.vue';
import search from '../components/search.vue';
const ITEM_BUFFER = 25;
const LOCAL_STORAGE_KEY__TREE_EXPANDED = 'mct-tree-expanded';
const SORT_MY_ITEMS_ALPH_ASC = true;
const TREE_ITEM_INDENT_PX = 18;
const LOCATOR_ITEM_COUNT_HEIGHT = 10; // how many tree items to make the locator selection box show
export default {
name: 'MctTree',
components: {
search,
treeItem
},
inject: ['openmct'],
props: {
isSelectorTree: {
type: Boolean,
required: false,
default() {
return false;
}
},
initialSelection: {
type: Object,
required: false,
default() {
return {};
}
},
syncTreeNavigation: {
type: Boolean,
required: false
},
resetTreeNavigation: {
type: Boolean,
required: false
}
},
data() {
return {
isLoading: false,
treeItemLoading: {},
mainTreeHeight: undefined,
searchLoading: false,
searchValue: '',
treeItems: [],
openTreeItems: [],
compositionCollections: {},
searchResultItems: [],
visibleItems: [],
updatingView: false,
itemHeight: 27,
itemOffset: 0,
activeSearch: false,
mainTreeTopMargin: undefined,
selectedItem: {},
targetedPath: ''
};
},
computed: {
childrenHeight() {
const childrenCount = this.focusedItems.length || 1;
return (this.itemHeight * childrenCount) - this.mainTreeTopMargin; // 5px margin
},
childrenHeightStyles() {
return { height: `${this.childrenHeight}px` };
},
focusedItems() {
return this.activeSearch ? this.searchResultItems : this.treeItems;
},
getAriaLabel() {
return this.isSelectorTree ? "Create Modal Tree" : "Main Tree";
},
pageThreshold() {
return Math.ceil(this.mainTreeHeight / this.itemHeight) + ITEM_BUFFER;
},
scrollableStyles() {
return { height: `${this.mainTreeHeight}px` };
},
showNoItems() {
return this.visibleItems.length === 0 && !this.activeSearch && this.searchValue === '' && !this.isLoading;
},
showNoSearchResults() {
return this.searchValue && this.searchResultItems.length === 0 && !this.searchLoading;
},
treeHeight() {
if (!this.isSelectorTree) {
return {};
} else {
return { minHeight: `${this.itemHeight * LOCATOR_ITEM_COUNT_HEIGHT}px`};
}
}
},
watch: {
syncTreeNavigation() {
this.searchValue = '';
// if there is an abort controller, then a search is in progress and will need to be canceled
if (this.abortSearchController) {
this.abortSearchController.abort();
delete this.abortSearchController;
}
if (!this.openmct.router.path) {
return;
}
this.$nextTick(this.showCurrentPathInTree);
},
resetTreeNavigation() {
[...this.openTreeItems].reverse().map(this.closeTreeItemByPath);
},
searchValue() {
if (this.searchValue !== '' && !this.activeSearch) {
this.activeSearch = true;
this.$refs.scrollable.scrollTop = 0;
} else if (this.searchValue === '') {
this.activeSearch = false;
}
},
mainTreeHeight() {
this.updateVisibleItems();
},
focusedItems() {
this.updateVisibleItems();
},
openTreeItems() {
this.setSavedOpenItems();
}
},
async mounted() {
await this.initialize();
await this.loadRoot();
this.isLoading = false;
if (!this.isSelectorTree) {
await this.syncTreeOpenItems();
} else {
if (this.initialSelection.identifier) {
const objectPath = await this.openmct.objects.getOriginalPath(this.initialSelection.identifier);
const navigationPath = this.buildNavigationPath(objectPath);
this.openAndScrollTo(navigationPath);
}
}
},
created() {
this.getSearchResults = _.debounce(this.getSearchResults, 400);
this.handleTreeResize = _.debounce(this.handleTreeResize, 300);
this.scrollEndEvent = _.debounce(this.scrollEndEvent, 100);
},
destroyed() {
if (this.treeResizeObserver) {
this.treeResizeObserver.disconnect();
}
this.destroyObservers();
this.destroyMutables();
},
methods: {
async initialize() {
this.observers = {};
this.mutables = {};
this.isLoading = true;
this.getSavedOpenItems();
this.treeResizeObserver = new ResizeObserver(this.handleTreeResize);
this.treeResizeObserver.observe(this.$el);
await this.calculateHeights();
return;
},
async loadRoot() {
this.treeItems = [];
const root = await this.openmct.objects.get('ROOT');
if (!root.identifier) {
return false;
}
// will need to listen for root composition changes as well
this.treeItems = await this.loadAndBuildTreeItemsFor(root, []);
},
treeItemAction(parentItem, type) {
if (type === 'close') {
this.closeTreeItem(parentItem);
} else {
this.openTreeItem(parentItem);
}
},
targetedPathAnimationEnd() {
this.targetedPath = undefined;
},
treeItemSelection(item) {
this.selectedItem = item;
this.$emit('tree-item-selection', item);
},
async openTreeItem(parentItem) {
let parentPath = parentItem.navigationPath;
this.startItemLoad(parentPath);
// pass in abort signal when functional
let childrenItems = await this.loadAndBuildTreeItemsFor(parentItem.object, parentItem.objectPath);
let parentIndex = this.treeItems.indexOf(parentItem);
// if it's not loading, it was aborted
if (!this.isItemLoading(parentPath) || parentIndex === -1) {
return;
}
this.endItemLoad(parentPath);
this.treeItems.splice(parentIndex + 1, 0, ...childrenItems);
if (!this.isTreeItemOpen(parentItem)) {
this.openTreeItems.push(parentPath);
}
for (let item of childrenItems) {
if (this.isTreeItemOpen(item)) {
this.openTreeItem(item);
}
}
return;
},
closeTreeItemByPath(path) {
// if actively loading, abort
if (this.isItemLoading(path)) {
this.abortItemLoad(path);
}
let pathIndex = this.openTreeItems.indexOf(path);
if (pathIndex === -1) {
return;
}
this.treeItems = this.treeItems.filter((checkItem) => {
if (checkItem.navigationPath !== path
&& checkItem.navigationPath.includes(path)) {
this.destroyObserverByPath(checkItem.navigationPath);
this.destroyMutableByPath(checkItem.navigationPath);
return false;
}
return true;
});
this.openTreeItems.splice(pathIndex, 1);
this.removeCompositionListenerFor(path);
},
closeTreeItem(item) {
this.closeTreeItemByPath(item.navigationPath);
},
// returns an AbortController signal to be passed on to requests
startItemLoad(path) {
if (this.isItemLoading(path)) {
this.abortItemLoad(path);
}
this.$set(this.treeItemLoading, path, new AbortController());
return this.treeItemLoading[path].signal;
},
endItemLoad(path) {
this.$set(this.treeItemLoading, path, undefined);
delete this.treeItemLoading[path];
},
abortItemLoad(path) {
if (this.treeItemLoading[path]) {
this.treeItemLoading[path].abort();
this.endItemLoad(path);
}
},
isItemLoading(path) {
return this.treeItemLoading[path] instanceof AbortController;
},
showCurrentPathInTree() {
const currentPath = this.buildNavigationPath(this.openmct.router.path);
if (this.getTreeItemByPath(currentPath)) {
this.scrollTo(currentPath);
} else {
this.openAndScrollTo(currentPath);
}
},
async syncTreeOpenItems() {
const items = [...this.treeItems];
for (let item of items) {
if (this.isTreeItemOpen(item)) {
await this.openTreeItem(item);
}
}
},
openAndScrollTo(navigationPath) {
if (navigationPath.includes('/ROOT')) {
navigationPath = navigationPath.split('/ROOT').join('');
}
let idArray = navigationPath.split('/');
let fullPathArray = [];
let pathsToOpen;
this.scrollToPath = navigationPath;
// skip root
idArray.splice(0, 2);
idArray[0] = 'browse/' + idArray[0];
idArray.reduce((parentPath, childPath) => {
let fullPath = [parentPath, childPath].join('/');
fullPathArray.push(fullPath);
return fullPath;
}, '');
pathsToOpen = fullPathArray.filter(fullPath => !this.isTreeItemPathOpen(fullPath) && fullPath !== navigationPath);
pathsToOpen.reduce(async (parentLoaded, childPath) => {
await parentLoaded;
return this.openTreeItem(this.getTreeItemByPath(childPath));
}, Promise.resolve()).then(() => {
if (this.isSelectorTree) {
// If item is missing due to error in object creation,
// walk up the navigationPath until we find an item
let item = this.getTreeItemByPath(navigationPath);
while (!item) {
const startIndex = 0;
const endIndex = navigationPath.lastIndexOf('/');
navigationPath = navigationPath.substring(startIndex, endIndex);
item = this.getTreeItemByPath(navigationPath);
}
this.treeItemSelection(item);
}
this.scrollToCheck(navigationPath);
this.scrollToPath = null;
});
},
scrollToCheck(navigationPath) {
if (this.scrollToPath && this.scrollToPath === navigationPath) {
this.scrollTo(navigationPath);
}
},
scrollTo(navigationPath) {
if (!this.$refs.scrollable || this.isItemInView(navigationPath)) {
return;
}
const indexOfScroll = this.treeItems.findIndex(item => item.navigationPath === navigationPath);
if (indexOfScroll !== -1) {
const scrollTopAmount = indexOfScroll * this.itemHeight;
this.$refs.scrollable.scrollTo({
top: scrollTopAmount,
behavior: 'smooth'
});
} else if (this.scrollToPath) {
this.scrollToPath = null;
}
},
scrollEndEvent() {
if (!this.$refs.scrollable) {
return;
}
this.$nextTick(() => {
if (this.scrollToPath) {
if (!this.isItemInView(this.scrollToPath)) {
this.scrollTo(this.scrollToPath);
} else {
this.scrollToPath = null;
}
}
});
},
setTargetedItem(navigationPath) {
this.targetedItem = navigationPath;
},
isItemInView(navigationPath) {
const indexOfScroll = this.treeItems.findIndex(item => item.navigationPath === navigationPath);
const scrollTopAmount = indexOfScroll * this.itemHeight;
const treeStart = this.$refs.scrollable.scrollTop;
const treeEnd = treeStart + this.mainTreeHeight;
return scrollTopAmount >= treeStart && scrollTopAmount < treeEnd;
},
getLowercaseObjectName(domainObject) {
let objectName;
if (!domainObject) {
return objectName;
}
if (domainObject.name) {
objectName = domainObject.name.toLowerCase();
}
if (domainObject.object && domainObject.object.name) {
objectName = domainObject.object.name.toLowerCase();
}
return objectName;
},
sortNameAscending(a, b) {
// sorting tree children items
let objectAName = this.getLowercaseObjectName(a);
let objectBName = this.getLowercaseObjectName(b);
if (!objectAName || !objectBName) {
return 0;
}
// sorting composition items
if (objectAName > objectBName) {
return 1;
}
if (objectBName > objectAName) {
return -1;
}
return 0;
},
isSortable(parentObjectPath) {
// determine if any part of the parent's path includes a key value of mine; aka My Items
return Boolean(parentObjectPath.find(path => path.identifier.key === 'mine'));
},
async loadAndBuildTreeItemsFor(domainObject, parentObjectPath, abortSignal) {
let collection = this.openmct.composition.get(domainObject);
let composition = await collection.load(abortSignal);
if (SORT_MY_ITEMS_ALPH_ASC && this.isSortable(parentObjectPath)) {
const sortedComposition = composition.slice().sort(this.sortNameAscending);
composition = sortedComposition;
}
if (parentObjectPath.length && !this.isSelectorTree) {
let navigationPath = this.buildNavigationPath(parentObjectPath);
if (this.compositionCollections[navigationPath]) {
this.removeCompositionListenerFor(navigationPath);
}
this.compositionCollections[navigationPath] = {};
this.compositionCollections[navigationPath].collection = collection;
this.compositionCollections[navigationPath].addHandler = this.compositionAddHandler(navigationPath);
this.compositionCollections[navigationPath].removeHandler = this.compositionRemoveHandler(navigationPath);
this.compositionCollections[navigationPath].collection.on('add',
this.compositionCollections[navigationPath].addHandler);
this.compositionCollections[navigationPath].collection.on('remove',
this.compositionCollections[navigationPath].removeHandler);
}
return composition.map((object) => {
// Only add observers and mutables if this is NOT a selector tree
if (!this.isSelectorTree) {
if (this.openmct.objects.supportsMutation(object.identifier)) {
object = this.openmct.objects.toMutable(object);
this.addMutable(object, parentObjectPath);
}
this.addTreeItemObserver(object, parentObjectPath);
}
return this.buildTreeItem(object, parentObjectPath);
});
},
buildTreeItem(domainObject, parentObjectPath, isNew = false) {
let objectPath = [domainObject].concat(parentObjectPath);
let navigationPath = this.buildNavigationPath(objectPath);
return {
id: this.openmct.objects.makeKeyString(domainObject.identifier),
object: domainObject,
leftOffset: ((objectPath.length - 1) * TREE_ITEM_INDENT_PX) + 'px',
isNew,
objectPath,
navigationPath
};
},
addMutable(mutableDomainObject, parentObjectPath) {
const objectPath = [mutableDomainObject].concat(parentObjectPath);
const navigationPath = this.buildNavigationPath(objectPath);
// If the mutable already exists, destroy it.
this.destroyMutableByPath(navigationPath);
this.mutables[navigationPath] = () => this.openmct.objects.destroyMutable(mutableDomainObject);
},
addTreeItemObserver(domainObject, parentObjectPath) {
const objectPath = [domainObject].concat(parentObjectPath);
const navigationPath = this.buildNavigationPath(objectPath);
if (this.observers[navigationPath]) {
this.observers[navigationPath]();
}
this.observers[navigationPath] = this.openmct.objects.observe(
domainObject,
'name',
this.sortTreeItems.bind(this, parentObjectPath)
);
},
sortTreeItems(parentObjectPath) {
const navigationPath = this.buildNavigationPath(parentObjectPath);
const parentItem = this.getTreeItemByPath(navigationPath);
// If the parent is not sortable, skip sorting
if (!this.isSortable(parentObjectPath)) {
return;
}
// Sort the renamed object and its siblings (direct descendants of the parent)
const directDescendants = this.getChildrenInTreeFor(parentItem, false);
directDescendants.sort(this.sortNameAscending);
// Take a copy of the sorted descendants array
const sortedTreeItems = directDescendants.slice();
directDescendants.forEach(descendant => {
const parent = this.getTreeItemByPath(descendant.navigationPath);
// If descendant is not open, skip
if (!this.isTreeItemOpen(parent)) {
return;
}
// If descendant is open but has no children, skip
const children = this.getChildrenInTreeFor(parent, true);
if (children.length === 0) {
return;
}
// Splice in the children of the descendant
const parentIndex = sortedTreeItems.map(item => item.navigationPath).indexOf(parent.navigationPath);
sortedTreeItems.splice(parentIndex + 1, 0, ...children);
});
// Splice in all of the sorted descendants
this.treeItems.splice(this.treeItems.indexOf(parentItem) + 1, sortedTreeItems.length, ...sortedTreeItems);
},
buildNavigationPath(objectPath) {
return '/browse/' + [...objectPath].reverse()
.map((object) => this.openmct.objects.makeKeyString(object.identifier))
.join('/');
},
compositionAddHandler(navigationPath) {
return (domainObject) => {
const parentItem = this.getTreeItemByPath(navigationPath);
const newItem = this.buildTreeItem(domainObject, parentItem.objectPath, true);
const descendants = this.getChildrenInTreeFor(parentItem, true);
const directDescendants = this.getChildrenInTreeFor(parentItem);
if (domainObject.isMutable) {
this.addMutable(domainObject, parentItem.objectPath);
}
this.addTreeItemObserver(domainObject, parentItem.objectPath);
if (directDescendants.length === 0) {
this.addItemToTreeAfter(newItem, parentItem);
return;
}
if (SORT_MY_ITEMS_ALPH_ASC && this.isSortable(parentItem.objectPath)) {
const newItemIndex = directDescendants
.findIndex(descendant => this.sortNameAscending(descendant, newItem) > 0);
const shouldInsertFirst = newItemIndex === 0;
const shouldInsertLast = newItemIndex === -1;
if (shouldInsertFirst) {
this.addItemToTreeAfter(newItem, parentItem);
} else if (shouldInsertLast) {
this.addItemToTreeAfter(newItem, descendants.pop());
} else {
this.addItemToTreeBefore(newItem, directDescendants[newItemIndex]);
}
return;
}
this.addItemToTreeAfter(newItem, descendants.pop());
};
},
compositionRemoveHandler(navigationPath) {
return (identifier) => {
const removeKeyString = this.openmct.objects.makeKeyString(identifier);
const parentItem = this.getTreeItemByPath(navigationPath);
const directDescendants = this.getChildrenInTreeFor(parentItem);
const removeItem = directDescendants.find(item => item.id === removeKeyString);
// Remove the item from the tree, unobserve it, and clean up any mutables
this.removeItemFromTree(removeItem);
this.destroyObserverByPath(removeItem.navigationPath);
this.destroyMutableByPath(removeItem.navigationPath);
};
},
removeCompositionListenerFor(navigationPath) {
if (this.compositionCollections[navigationPath]) {
this.compositionCollections[navigationPath].collection.off('add',
this.compositionCollections[navigationPath].addHandler);
this.compositionCollections[navigationPath].collection.off('remove',
this.compositionCollections[navigationPath].removeHandler);
this.compositionCollections[navigationPath] = undefined;
delete this.compositionCollections[navigationPath];
}
},
removeItemFromTree(item) {
if (this.isTreeItemOpen(item)) {
this.closeTreeItem(item);
}
const removeIndex = this.getTreeItemIndex(item.navigationPath);
this.treeItems.splice(removeIndex, 1);
},
addItemToTreeBefore(addItem, beforeItem) {
const addIndex = this.getTreeItemIndex(beforeItem.navigationPath);
this.addItemToTree(addItem, addIndex);
},
addItemToTreeAfter(addItem, afterItem) {
const addIndex = this.getTreeItemIndex(afterItem.navigationPath);
this.addItemToTree(addItem, addIndex + 1);
},
addItemToTree(addItem, index) {
this.treeItems.splice(index, 0, addItem);
if (this.isTreeItemOpen(addItem)) {
this.openTreeItem(addItem);
}
},
searchTree(value) {
// if an abort controller exists, regardless of the value passed in,
// there is an active search that should be canceled
if (this.abortSearchController) {
this.abortSearchController.abort();
delete this.abortSearchController;
}
this.searchValue = value;
this.searchLoading = true;
if (this.searchValue !== '') {
// clear any previous search results
this.searchResultItems = [];
this.getSearchResults();
} else {
this.searchLoading = false;
}
},
getSearchResults() {
// an abort controller will be passed in that will be used
// to cancel an active searches if necessary
this.abortSearchController = new AbortController();
const abortSignal = this.abortSearchController.signal;
const searchPromises = this.openmct.objects.search(this.searchValue, abortSignal);
searchPromises.map(promise => promise
.then(results => {
this.aggregateSearchResults(results, abortSignal);
}
));
Promise.all(searchPromises).catch(reason => {
// search aborted
}).finally(() => {
this.searchLoading = false;
if (this.abortSearchController) {
delete this.abortSearchController;
}
});
},
aggregateSearchResults(results, abortSignal) {
let resultPromises = [];
for (const result of results) {
if (!abortSignal.aborted) {
// Don't show deleted objects in search results
if (result.location === null) {
continue;
}
resultPromises.push(this.openmct.objects.getOriginalPath(result.identifier).then((objectPath) => {
// removing the item itself, as the path we pass to buildTreeItem is a parent path
objectPath.shift();
// if root, remove, we're not using in object path for tree
const lastObject = objectPath.length ? objectPath[objectPath.length - 1] : false;
if (lastObject && lastObject.type === 'root') {
objectPath.pop();
}
this.searchResultItems.push(this.buildTreeItem(result, objectPath));
}));
}
}
return resultPromises;
},
updateVisibleItems() {
this.scrollEndEvent();
if (this.updatingView) {
return;
}
this.updatingView = true;
requestAnimationFrame(() => {
let start = 0;
let end = this.pageThreshold;
let allItemsCount = this.focusedItems.length;
if (allItemsCount < this.pageThreshold) {
end = allItemsCount;
} else {
let firstVisible = this.calculateFirstVisibleItem();
let lastVisible = this.calculateLastVisibleItem();
let totalVisible = lastVisible - firstVisible;
let numberOffscreen = this.pageThreshold - totalVisible;
start = firstVisible - Math.floor(numberOffscreen / 2);
end = lastVisible + Math.ceil(numberOffscreen / 2);
if (start < 0) {
start = 0;
end = Math.min(this.pageThreshold, allItemsCount);
} else if (end >= allItemsCount) {
end = allItemsCount;
start = end - this.pageThreshold + 1;
}
}
this.itemOffset = start;
this.visibleItems = this.focusedItems.slice(start, end);
this.updatingView = false;
});
},
calculateFirstVisibleItem() {
if (!this.$refs.scrollable) {
return;
}
let scrollTop = this.$refs.scrollable.scrollTop;
return Math.floor(scrollTop / this.itemHeight);
},
calculateLastVisibleItem() {
if (!this.$refs.scrollable) {
return;
}
let scrollBottom = this.$refs.scrollable.scrollTop + this.$refs.scrollable.offsetHeight;
return Math.ceil(scrollBottom / this.itemHeight);
},
calculateHeights() {
const RECHECK = 100;
return new Promise((resolve, reject) => {
let checkHeights = () => {
let treeTopMargin = this.getElementStyleValue(this.$refs.mainTree, 'marginTop');
let paddingOffset = 0;
if (
this.$el
&& this.$refs.search
&& this.$refs.mainTree
&& this.$refs.treeContainer
&& this.$refs.dummyItem
&& this.$el.offsetHeight !== 0
&& treeTopMargin > 0
) {
if (this.isSelectorTree) {
paddingOffset = this.getElementStyleValue(this.$refs.treeContainer, 'padding');
}
this.mainTreeTopMargin = treeTopMargin;
this.mainTreeHeight = this.$el.offsetHeight
- this.$refs.search.offsetHeight
- this.mainTreeTopMargin
- (paddingOffset * 2);
this.itemHeight = this.getElementStyleValue(this.$refs.dummyItem, 'height');
resolve();
} else {
setTimeout(checkHeights, RECHECK);
}
};
checkHeights();
});
},
getTreeItemByPath(path) {
return this.treeItems.find(item => item.navigationPath === path);
},
getTreeItemIndex(indexItem) {
let path = typeof indexItem === 'string' ? indexItem : indexItem.navigationPath;
return this.treeItems.findIndex(item => item.navigationPath === path);
},
getChildrenInTreeFor(parent, allDescendants = false) {
const parentPath = typeof parent === 'string' ? parent : parent.navigationPath;
const parentDepth = parentPath.split('/').length;
return this.treeItems.filter((childItem) => {
const childDepth = childItem.navigationPath.split('/').length;
if (!allDescendants && childDepth > parentDepth + 1) {
return false;
}
return childItem.navigationPath !== parentPath
&& childItem.navigationPath.includes(parentPath);
});
},
isTreeItemOpen(item) {
return this.isTreeItemPathOpen(item.navigationPath);
},
isTreeItemPathOpen(path) {
return this.openTreeItems.includes(path);
},
getElementStyleValue(el, style) {
if (!el) {
return;
}
let styleString = window.getComputedStyle(el)[style];
let index = styleString.indexOf('px');
return Number(styleString.slice(0, index));
},
getSavedOpenItems() {
if (this.isSelectorTree) {
return;
}
let openItems = localStorage.getItem(LOCAL_STORAGE_KEY__TREE_EXPANDED);
this.openTreeItems = openItems ? JSON.parse(openItems) : [];
},
setSavedOpenItems() {
if (this.isSelectorTree) {
return;
}
localStorage.setItem(LOCAL_STORAGE_KEY__TREE_EXPANDED, JSON.stringify(this.openTreeItems));
},
handleTreeResize() {
this.calculateHeights();
},
/**
* Destroy an observer for the given navigationPath.
*/
destroyObserverByPath(navigationPath) {
if (this.observers[navigationPath]) {
this.observers[navigationPath]();
delete this.observers[navigationPath];
}
},
/**
* Destroy all observers.
*/