-
Notifications
You must be signed in to change notification settings - Fork 907
/
tree-data-utils.js
1205 lines (1092 loc) · 33.4 KB
/
tree-data-utils.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
/**
* Performs a depth-first traversal over all of the node descendants,
* incrementing currentIndex by 1 for each
*/
function getNodeDataAtTreeIndexOrNextIndex({
targetIndex,
node,
currentIndex,
getNodeKey,
path = [],
lowerSiblingCounts = [],
ignoreCollapsed = true,
isPseudoRoot = false,
}) {
// The pseudo-root is not considered in the path
const selfPath = !isPseudoRoot
? [...path, getNodeKey({ node, treeIndex: currentIndex })]
: [];
// Return target node when found
if (currentIndex === targetIndex) {
return {
node,
lowerSiblingCounts,
path: selfPath,
};
}
// Add one and continue for nodes with no children or hidden children
if (!node.children || (ignoreCollapsed && node.expanded !== true)) {
return { nextIndex: currentIndex + 1 };
}
// Iterate over each child and their descendants and return the
// target node if childIndex reaches the targetIndex
let childIndex = currentIndex + 1;
const childCount = node.children.length;
for (let i = 0; i < childCount; i += 1) {
const result = getNodeDataAtTreeIndexOrNextIndex({
ignoreCollapsed,
getNodeKey,
targetIndex,
node: node.children[i],
currentIndex: childIndex,
lowerSiblingCounts: [...lowerSiblingCounts, childCount - i - 1],
path: selfPath,
});
if (result.node) {
return result;
}
childIndex = result.nextIndex;
}
// If the target node is not found, return the farthest traversed index
return { nextIndex: childIndex };
}
export function getDescendantCount({ node, ignoreCollapsed = true }) {
return (
getNodeDataAtTreeIndexOrNextIndex({
getNodeKey: () => {},
ignoreCollapsed,
node,
currentIndex: 0,
targetIndex: -1,
}).nextIndex - 1
);
}
/**
* Walk all descendants of the given node, depth-first
*
* @param {Object} args - Function parameters
* @param {function} args.callback - Function to call on each node
* @param {function} args.getNodeKey - Function to get the key from the nodeData and tree index
* @param {boolean} args.ignoreCollapsed - Ignore children of nodes without `expanded` set to `true`
* @param {boolean=} args.isPseudoRoot - If true, this node has no real data, and only serves
* as the parent of all the nodes in the tree
* @param {Object} args.node - A tree node
* @param {Object=} args.parentNode - The parent node of `node`
* @param {number} args.currentIndex - The treeIndex of `node`
* @param {number[]|string[]} args.path - Array of keys leading up to node to be changed
* @param {number[]} args.lowerSiblingCounts - An array containing the count of siblings beneath the
* previous nodes in this path
*
* @return {number|false} nextIndex - Index of the next sibling of `node`,
* or false if the walk should be terminated
*/
function walkDescendants({
callback,
getNodeKey,
ignoreCollapsed,
isPseudoRoot = false,
node,
parentNode = null,
currentIndex,
path = [],
lowerSiblingCounts = [],
}) {
// The pseudo-root is not considered in the path
const selfPath = isPseudoRoot
? []
: [...path, getNodeKey({ node, treeIndex: currentIndex })];
const selfInfo = isPseudoRoot
? null
: {
node,
parentNode,
path: selfPath,
lowerSiblingCounts,
treeIndex: currentIndex,
};
if (!isPseudoRoot) {
const callbackResult = callback(selfInfo);
// Cut walk short if the callback returned false
if (callbackResult === false) {
return false;
}
}
// Return self on nodes with no children or hidden children
if (
!node.children ||
(node.expanded !== true && ignoreCollapsed && !isPseudoRoot)
) {
return currentIndex;
}
// Get all descendants
let childIndex = currentIndex;
const childCount = node.children.length;
if (typeof node.children !== 'function') {
for (let i = 0; i < childCount; i += 1) {
childIndex = walkDescendants({
callback,
getNodeKey,
ignoreCollapsed,
node: node.children[i],
parentNode: isPseudoRoot ? null : node,
currentIndex: childIndex + 1,
lowerSiblingCounts: [...lowerSiblingCounts, childCount - i - 1],
path: selfPath,
});
// Cut walk short if the callback returned false
if (childIndex === false) {
return false;
}
}
}
return childIndex;
}
/**
* Perform a change on the given node and all its descendants, traversing the tree depth-first
*
* @param {Object} args - Function parameters
* @param {function} args.callback - Function to call on each node
* @param {function} args.getNodeKey - Function to get the key from the nodeData and tree index
* @param {boolean} args.ignoreCollapsed - Ignore children of nodes without `expanded` set to `true`
* @param {boolean=} args.isPseudoRoot - If true, this node has no real data, and only serves
* as the parent of all the nodes in the tree
* @param {Object} args.node - A tree node
* @param {Object=} args.parentNode - The parent node of `node`
* @param {number} args.currentIndex - The treeIndex of `node`
* @param {number[]|string[]} args.path - Array of keys leading up to node to be changed
* @param {number[]} args.lowerSiblingCounts - An array containing the count of siblings beneath the
* previous nodes in this path
*
* @return {number|false} nextIndex - Index of the next sibling of `node`,
* or false if the walk should be terminated
*/
function mapDescendants({
callback,
getNodeKey,
ignoreCollapsed,
isPseudoRoot = false,
node,
parentNode = null,
currentIndex,
path = [],
lowerSiblingCounts = [],
}) {
const nextNode = { ...node };
// The pseudo-root is not considered in the path
const selfPath = isPseudoRoot
? []
: [...path, getNodeKey({ node: nextNode, treeIndex: currentIndex })];
const selfInfo = {
node: nextNode,
parentNode,
path: selfPath,
lowerSiblingCounts,
treeIndex: currentIndex,
};
// Return self on nodes with no children or hidden children
if (
!nextNode.children ||
(nextNode.expanded !== true && ignoreCollapsed && !isPseudoRoot)
) {
return {
treeIndex: currentIndex,
node: callback(selfInfo),
};
}
// Get all descendants
let childIndex = currentIndex;
const childCount = nextNode.children.length;
if (typeof nextNode.children !== 'function') {
nextNode.children = nextNode.children.map((child, i) => {
const mapResult = mapDescendants({
callback,
getNodeKey,
ignoreCollapsed,
node: child,
parentNode: isPseudoRoot ? null : nextNode,
currentIndex: childIndex + 1,
lowerSiblingCounts: [...lowerSiblingCounts, childCount - i - 1],
path: selfPath,
});
childIndex = mapResult.treeIndex;
return mapResult.node;
});
}
return {
node: callback(selfInfo),
treeIndex: childIndex,
};
}
/**
* Count all the visible (expanded) descendants in the tree data.
*
* @param {!Object[]} treeData - Tree data
*
* @return {number} count
*/
export function getVisibleNodeCount({ treeData }) {
const traverse = node => {
if (
!node.children ||
node.expanded !== true ||
typeof node.children === 'function'
) {
return 1;
}
return (
1 +
node.children.reduce(
(total, currentNode) => total + traverse(currentNode),
0
)
);
};
return treeData.reduce(
(total, currentNode) => total + traverse(currentNode),
0
);
}
/**
* Get the <targetIndex>th visible node in the tree data.
*
* @param {!Object[]} treeData - Tree data
* @param {!number} targetIndex - The index of the node to search for
* @param {!function} getNodeKey - Function to get the key from the nodeData and tree index
*
* @return {{
* node: Object,
* path: []string|[]number,
* lowerSiblingCounts: []number
* }|null} node - The node at targetIndex, or null if not found
*/
export function getVisibleNodeInfoAtIndex({
treeData,
index: targetIndex,
getNodeKey,
}) {
if (!treeData || treeData.length < 1) {
return null;
}
// Call the tree traversal with a pseudo-root node
const result = getNodeDataAtTreeIndexOrNextIndex({
targetIndex,
getNodeKey,
node: {
children: treeData,
expanded: true,
},
currentIndex: -1,
path: [],
lowerSiblingCounts: [],
isPseudoRoot: true,
});
if (result.node) {
return result;
}
return null;
}
/**
* Walk descendants depth-first and call a callback on each
*
* @param {!Object[]} treeData - Tree data
* @param {!function} getNodeKey - Function to get the key from the nodeData and tree index
* @param {function} callback - Function to call on each node
* @param {boolean=} ignoreCollapsed - Ignore children of nodes without `expanded` set to `true`
*
* @return void
*/
export function walk({
treeData,
getNodeKey,
callback,
ignoreCollapsed = true,
}) {
if (!treeData || treeData.length < 1) {
return;
}
walkDescendants({
callback,
getNodeKey,
ignoreCollapsed,
isPseudoRoot: true,
node: { children: treeData },
currentIndex: -1,
path: [],
lowerSiblingCounts: [],
});
}
/**
* Perform a depth-first transversal of the descendants and
* make a change to every node in the tree
*
* @param {!Object[]} treeData - Tree data
* @param {!function} getNodeKey - Function to get the key from the nodeData and tree index
* @param {function} callback - Function to call on each node
* @param {boolean=} ignoreCollapsed - Ignore children of nodes without `expanded` set to `true`
*
* @return {Object[]} changedTreeData - The changed tree data
*/
export function map({
treeData,
getNodeKey,
callback,
ignoreCollapsed = true,
}) {
if (!treeData || treeData.length < 1) {
return [];
}
return mapDescendants({
callback,
getNodeKey,
ignoreCollapsed,
isPseudoRoot: true,
node: { children: treeData },
currentIndex: -1,
path: [],
lowerSiblingCounts: [],
}).node.children;
}
/**
* Expand or close every node in the tree
*
* @param {!Object[]} treeData - Tree data
* @param {?boolean} expanded - Whether the node is expanded or not
*
* @return {Object[]} changedTreeData - The changed tree data
*/
export function toggleExpandedForAll({ treeData, expanded = true }) {
return map({
treeData,
callback: ({ node }) => ({ ...node, expanded }),
getNodeKey: ({ treeIndex }) => treeIndex,
ignoreCollapsed: false,
});
}
/**
* Replaces node at path with object, or callback-defined object
*
* @param {!Object[]} treeData
* @param {number[]|string[]} path - Array of keys leading up to node to be changed
* @param {function|any} newNode - Node to replace the node at the path with, or a function producing the new node
* @param {!function} getNodeKey - Function to get the key from the nodeData and tree index
* @param {boolean=} ignoreCollapsed - Ignore children of nodes without `expanded` set to `true`
*
* @return {Object[]} changedTreeData - The changed tree data
*/
export function changeNodeAtPath({
treeData,
path,
newNode,
getNodeKey,
ignoreCollapsed = true,
}) {
const RESULT_MISS = 'RESULT_MISS';
const traverse = ({
isPseudoRoot = false,
node,
currentTreeIndex,
pathIndex,
}) => {
if (
!isPseudoRoot &&
getNodeKey({ node, treeIndex: currentTreeIndex }) !== path[pathIndex]
) {
return RESULT_MISS;
}
if (pathIndex >= path.length - 1) {
// If this is the final location in the path, return its changed form
return typeof newNode === 'function'
? newNode({ node, treeIndex: currentTreeIndex })
: newNode;
}
if (!node.children) {
// If this node is part of the path, but has no children, return the unchanged node
throw new Error('Path referenced children of node with no children.');
}
let nextTreeIndex = currentTreeIndex + 1;
for (let i = 0; i < node.children.length; i += 1) {
const result = traverse({
node: node.children[i],
currentTreeIndex: nextTreeIndex,
pathIndex: pathIndex + 1,
});
// If the result went down the correct path
if (result !== RESULT_MISS) {
if (result) {
// If the result was truthy (in this case, an object),
// pass it to the next level of recursion up
return {
...node,
children: [
...node.children.slice(0, i),
result,
...node.children.slice(i + 1),
],
};
}
// If the result was falsy (returned from the newNode function), then
// delete the node from the array.
return {
...node,
children: [
...node.children.slice(0, i),
...node.children.slice(i + 1),
],
};
}
nextTreeIndex +=
1 + getDescendantCount({ node: node.children[i], ignoreCollapsed });
}
return RESULT_MISS;
};
// Use a pseudo-root node in the beginning traversal
const result = traverse({
node: { children: treeData },
currentTreeIndex: -1,
pathIndex: -1,
isPseudoRoot: true,
});
if (result === RESULT_MISS) {
throw new Error('No node found at the given path.');
}
return result.children;
}
/**
* Removes the node at the specified path and returns the resulting treeData.
*
* @param {!Object[]} treeData
* @param {number[]|string[]} path - Array of keys leading up to node to be deleted
* @param {!function} getNodeKey - Function to get the key from the nodeData and tree index
* @param {boolean=} ignoreCollapsed - Ignore children of nodes without `expanded` set to `true`
*
* @return {Object[]} changedTreeData - The tree data with the node removed
*/
export function removeNodeAtPath({
treeData,
path,
getNodeKey,
ignoreCollapsed = true,
}) {
return changeNodeAtPath({
treeData,
path,
getNodeKey,
ignoreCollapsed,
newNode: null, // Delete the node
});
}
/**
* Removes the node at the specified path and returns the resulting treeData.
*
* @param {!Object[]} treeData
* @param {number[]|string[]} path - Array of keys leading up to node to be deleted
* @param {!function} getNodeKey - Function to get the key from the nodeData and tree index
* @param {boolean=} ignoreCollapsed - Ignore children of nodes without `expanded` set to `true`
*
* @return {Object} result
* @return {Object[]} result.treeData - The tree data with the node removed
* @return {Object} result.node - The node that was removed
* @return {number} result.treeIndex - The previous treeIndex of the removed node
*/
export function removeNode({
treeData,
path,
getNodeKey,
ignoreCollapsed = true,
}) {
let removedNode = null;
let removedTreeIndex = null;
const nextTreeData = changeNodeAtPath({
treeData,
path,
getNodeKey,
ignoreCollapsed,
newNode: ({ node, treeIndex }) => {
// Store the target node and delete it from the tree
removedNode = node;
removedTreeIndex = treeIndex;
return null;
},
});
return {
treeData: nextTreeData,
node: removedNode,
treeIndex: removedTreeIndex,
};
}
/**
* Gets the node at the specified path
*
* @param {!Object[]} treeData
* @param {number[]|string[]} path - Array of keys leading up to node to be deleted
* @param {!function} getNodeKey - Function to get the key from the nodeData and tree index
* @param {boolean=} ignoreCollapsed - Ignore children of nodes without `expanded` set to `true`
*
* @return {Object|null} nodeInfo - The node info at the given path, or null if not found
*/
export function getNodeAtPath({
treeData,
path,
getNodeKey,
ignoreCollapsed = true,
}) {
let foundNodeInfo = null;
try {
changeNodeAtPath({
treeData,
path,
getNodeKey,
ignoreCollapsed,
newNode: ({ node, treeIndex }) => {
foundNodeInfo = { node, treeIndex };
return node;
},
});
} catch (err) {
// Ignore the error -- the null return will be explanation enough
}
return foundNodeInfo;
}
/**
* Adds the node to the specified parent and returns the resulting treeData.
*
* @param {!Object[]} treeData
* @param {!Object} newNode - The node to insert
* @param {number|string} parentKey - The key of the to-be parentNode of the node
* @param {!function} getNodeKey - Function to get the key from the nodeData and tree index
* @param {boolean=} ignoreCollapsed - Ignore children of nodes without `expanded` set to `true`
* @param {boolean=} expandParent - If true, expands the parentNode specified by parentPath
* @param {boolean=} addAsFirstChild - If true, adds new node as first child of tree
*
* @return {Object} result
* @return {Object[]} result.treeData - The updated tree data
* @return {number} result.treeIndex - The tree index at which the node was inserted
*/
export function addNodeUnderParent({
treeData,
newNode,
parentKey = null,
getNodeKey,
ignoreCollapsed = true,
expandParent = false,
addAsFirstChild = false,
}) {
if (parentKey === null) {
return addAsFirstChild
? {
treeData: [newNode, ...(treeData || [])],
treeIndex: 0,
}
: {
treeData: [...(treeData || []), newNode],
treeIndex: (treeData || []).length,
};
}
let insertedTreeIndex = null;
let hasBeenAdded = false;
const changedTreeData = map({
treeData,
getNodeKey,
ignoreCollapsed,
callback: ({ node, treeIndex, path }) => {
const key = path ? path[path.length - 1] : null;
// Return nodes that are not the parent as-is
if (hasBeenAdded || key !== parentKey) {
return node;
}
hasBeenAdded = true;
const parentNode = {
...node,
};
if (expandParent) {
parentNode.expanded = true;
}
// If no children exist yet, just add the single newNode
if (!parentNode.children) {
insertedTreeIndex = treeIndex + 1;
return {
...parentNode,
children: [newNode],
};
}
if (typeof parentNode.children === 'function') {
throw new Error('Cannot add to children defined by a function');
}
let nextTreeIndex = treeIndex + 1;
for (let i = 0; i < parentNode.children.length; i += 1) {
nextTreeIndex +=
1 +
getDescendantCount({ node: parentNode.children[i], ignoreCollapsed });
}
insertedTreeIndex = nextTreeIndex;
const children = addAsFirstChild
? [newNode, ...parentNode.children]
: [...parentNode.children, newNode];
return {
...parentNode,
children,
};
},
});
if (!hasBeenAdded) {
throw new Error('No node found with the given key.');
}
return {
treeData: changedTreeData,
treeIndex: insertedTreeIndex,
};
}
function addNodeAtDepthAndIndex({
targetDepth,
minimumTreeIndex,
newNode,
ignoreCollapsed,
expandParent,
isPseudoRoot = false,
isLastChild,
node,
currentIndex,
currentDepth,
getNodeKey,
path = [],
}) {
const selfPath = n =>
isPseudoRoot
? []
: [...path, getNodeKey({ node: n, treeIndex: currentIndex })];
// If the current position is the only possible place to add, add it
if (
currentIndex >= minimumTreeIndex - 1 ||
(isLastChild && !(node.children && node.children.length))
) {
if (typeof node.children === 'function') {
throw new Error('Cannot add to children defined by a function');
} else {
const extraNodeProps = expandParent ? { expanded: true } : {};
const nextNode = {
...node,
...extraNodeProps,
children: node.children ? [newNode, ...node.children] : [newNode],
};
return {
node: nextNode,
nextIndex: currentIndex + 2,
insertedTreeIndex: currentIndex + 1,
parentPath: selfPath(nextNode),
parentNode: isPseudoRoot ? null : nextNode,
};
}
}
// If this is the target depth for the insertion,
// i.e., where the newNode can be added to the current node's children
if (currentDepth >= targetDepth - 1) {
// Skip over nodes with no children or hidden children
if (
!node.children ||
typeof node.children === 'function' ||
(node.expanded !== true && ignoreCollapsed && !isPseudoRoot)
) {
return { node, nextIndex: currentIndex + 1 };
}
// Scan over the children to see if there's a place among them that fulfills
// the minimumTreeIndex requirement
let childIndex = currentIndex + 1;
let insertedTreeIndex = null;
let insertIndex = null;
for (let i = 0; i < node.children.length; i += 1) {
// If a valid location is found, mark it as the insertion location and
// break out of the loop
if (childIndex >= minimumTreeIndex) {
insertedTreeIndex = childIndex;
insertIndex = i;
break;
}
// Increment the index by the child itself plus the number of descendants it has
childIndex +=
1 + getDescendantCount({ node: node.children[i], ignoreCollapsed });
}
// If no valid indices to add the node were found
if (insertIndex === null) {
// If the last position in this node's children is less than the minimum index
// and there are more children on the level of this node, return without insertion
if (childIndex < minimumTreeIndex && !isLastChild) {
return { node, nextIndex: childIndex };
}
// Use the last position in the children array to insert the newNode
insertedTreeIndex = childIndex;
insertIndex = node.children.length;
}
// Insert the newNode at the insertIndex
const nextNode = {
...node,
children: [
...node.children.slice(0, insertIndex),
newNode,
...node.children.slice(insertIndex),
],
};
// Return node with successful insert result
return {
node: nextNode,
nextIndex: childIndex,
insertedTreeIndex,
parentPath: selfPath(nextNode),
parentNode: isPseudoRoot ? null : nextNode,
};
}
// Skip over nodes with no children or hidden children
if (
!node.children ||
typeof node.children === 'function' ||
(node.expanded !== true && ignoreCollapsed && !isPseudoRoot)
) {
return { node, nextIndex: currentIndex + 1 };
}
// Get all descendants
let insertedTreeIndex = null;
let pathFragment = null;
let parentNode = null;
let childIndex = currentIndex + 1;
let newChildren = node.children;
if (typeof newChildren !== 'function') {
newChildren = newChildren.map((child, i) => {
if (insertedTreeIndex !== null) {
return child;
}
const mapResult = addNodeAtDepthAndIndex({
targetDepth,
minimumTreeIndex,
newNode,
ignoreCollapsed,
expandParent,
isLastChild: isLastChild && i === newChildren.length - 1,
node: child,
currentIndex: childIndex,
currentDepth: currentDepth + 1,
getNodeKey,
path: [], // Cannot determine the parent path until the children have been processed
});
if ('insertedTreeIndex' in mapResult) {
({
insertedTreeIndex,
parentNode,
parentPath: pathFragment,
} = mapResult);
}
childIndex = mapResult.nextIndex;
return mapResult.node;
});
}
const nextNode = { ...node, children: newChildren };
const result = {
node: nextNode,
nextIndex: childIndex,
};
if (insertedTreeIndex !== null) {
result.insertedTreeIndex = insertedTreeIndex;
result.parentPath = [...selfPath(nextNode), ...pathFragment];
result.parentNode = parentNode;
}
return result;
}
/**
* Insert a node into the tree at the given depth, after the minimum index
*
* @param {!Object[]} treeData - Tree data
* @param {!number} depth - The depth to insert the node at (the first level of the array being depth 0)
* @param {!number} minimumTreeIndex - The lowest possible treeIndex to insert the node at
* @param {!Object} newNode - The node to insert into the tree
* @param {boolean=} ignoreCollapsed - Ignore children of nodes without `expanded` set to `true`
* @param {boolean=} expandParent - If true, expands the parent of the inserted node
* @param {!function} getNodeKey - Function to get the key from the nodeData and tree index
*
* @return {Object} result
* @return {Object[]} result.treeData - The tree data with the node added
* @return {number} result.treeIndex - The tree index at which the node was inserted
* @return {number[]|string[]} result.path - Array of keys leading to the node location after insertion
* @return {Object} result.parentNode - The parent node of the inserted node
*/
export function insertNode({
treeData,
depth: targetDepth,
minimumTreeIndex,
newNode,
getNodeKey = () => {},
ignoreCollapsed = true,
expandParent = false,
}) {
if (!treeData && targetDepth === 0) {
return {
treeData: [newNode],
treeIndex: 0,
path: [getNodeKey({ node: newNode, treeIndex: 0 })],
parentNode: null,
};
}
const insertResult = addNodeAtDepthAndIndex({
targetDepth,
minimumTreeIndex,
newNode,
ignoreCollapsed,
expandParent,
getNodeKey,
isPseudoRoot: true,
isLastChild: true,
node: { children: treeData },
currentIndex: -1,
currentDepth: -1,
});
if (!('insertedTreeIndex' in insertResult)) {
throw new Error('No suitable position found to insert.');
}
const treeIndex = insertResult.insertedTreeIndex;
return {
treeData: insertResult.node.children,
treeIndex,
path: [
...insertResult.parentPath,
getNodeKey({ node: newNode, treeIndex }),
],
parentNode: insertResult.parentNode,
};
}
/**
* Get tree data flattened.
*
* @param {!Object[]} treeData - Tree data
* @param {!function} getNodeKey - Function to get the key from the nodeData and tree index
* @param {boolean=} ignoreCollapsed - Ignore children of nodes without `expanded` set to `true`
*
* @return {{
* node: Object,
* path: []string|[]number,
* lowerSiblingCounts: []number
* }}[] nodes - The node array
*/
export function getFlatDataFromTree({
treeData,
getNodeKey,
ignoreCollapsed = true,
}) {
if (!treeData || treeData.length < 1) {
return [];
}
const flattened = [];
walk({
treeData,
getNodeKey,
ignoreCollapsed,
callback: nodeInfo => {
flattened.push(nodeInfo);
},
});
return flattened;
}
/**
* Generate a tree structure from flat data.
*
* @param {!Object[]} flatData
* @param {!function=} getKey - Function to get the key from the nodeData
* @param {!function=} getParentKey - Function to get the parent key from the nodeData
* @param {string|number=} rootKey - The value returned by `getParentKey` that corresponds to the root node.
* For example, if your nodes have id 1-99, you might use rootKey = 0
*
* @return {Object[]} treeData - The flat data represented as a tree
*/
export function getTreeFromFlatData({
flatData,
getKey = node => node.id,
getParentKey = node => node.parentId,
rootKey = '0',
}) {
if (!flatData) {
return [];
}
const childrenToParents = {};
flatData.forEach(child => {
const parentKey = getParentKey(child);
if (parentKey in childrenToParents) {
childrenToParents[parentKey].push(child);
} else {