forked from nosferatu500/react-sortable-tree
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree-data-utils.ts
1044 lines (924 loc) · 25.3 KB
/
tree-data-utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @ts-nocheck
import {
FullTree,
GetTreeItemChildren,
NodeData,
SearchData,
TreeIndex,
TreeItem,
TreeNode,
TreePath,
} from '..'
export type WalkAndMapFunctionParameters = FullTree & {
callback: Function
ignoreCollapsed?: boolean | undefined
}
export interface FlatDataItem extends TreeNode, TreePath {
lowerSiblingCounts: number[]
parentNode: TreeItem
}
/**
* Performs a depth-first traversal over all of the node descendants,
* incrementing currentIndex by 1 for each
*/
const getNodeDataAtTreeIndexOrNextIndex = ({
targetIndex,
node,
currentIndex,
path = [],
lowerSiblingCounts = [],
ignoreCollapsed = true,
isPseudoRoot = false,
}: {
targetIndex: number
node: TreeItem
currentIndex: number
path: number[]
lowerSiblingCounts: number[]
ignoreCollapsed: boolean
isPseudoRoot: boolean
}) => {
// The pseudo-root is not considered in the path
const selfPath = isPseudoRoot ? [] : [...path, node.nodeId]
// 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,
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 const getDescendantCount = ({
node,
ignoreCollapsed = true,
}: TreeNode & { ignoreCollapsed?: boolean | undefined }): number => {
return (
getNodeDataAtTreeIndexOrNextIndex({
ignoreCollapsed,
node,
currentIndex: 0,
targetIndex: -1,
}).nextIndex - 1
)
}
const walkDescendants = ({
callback,
ignoreCollapsed,
isPseudoRoot = false,
node,
parentNode = undefined,
currentIndex,
path = [],
lowerSiblingCounts = [],
}) => {
// The pseudo-root is not considered in the path
const selfPath = isPseudoRoot ? [] : [...path, node.nodeId]
const selfInfo = isPseudoRoot
? undefined
: {
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,
ignoreCollapsed,
node: node.children[i],
parentNode: isPseudoRoot ? undefined : 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
}
const mapDescendants = ({
callback,
ignoreCollapsed,
isPseudoRoot = false,
node,
parentNode = undefined,
currentIndex,
path = [],
lowerSiblingCounts = [],
}) => {
const nextNode = { ...node }
// The pseudo-root is not considered in the path
const selfPath = isPseudoRoot ? [] : [...path, nextNode.nodeId]
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,
ignoreCollapsed,
node: child,
parentNode: isPseudoRoot ? undefined : nextNode,
currentIndex: childIndex + 1,
lowerSiblingCounts: [...lowerSiblingCounts, childCount - i - 1],
path: selfPath,
})
childIndex = mapResult.treeIndex
return mapResult.node
})
}
return {
node: callback(selfInfo),
treeIndex: childIndex,
}
}
export const getVisibleNodeCount = ({ treeData }: FullTree): number => {
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
)
}
export const getVisibleNodeInfoAtIndex = ({
treeData,
index: targetIndex,
}: FullTree & {
index: number
}): (TreeNode & TreePath & { lowerSiblingCounts: number[] }) | null => {
if (!treeData || treeData.length === 0) {
return undefined
}
// Call the tree traversal with a pseudo-root node
const result = getNodeDataAtTreeIndexOrNextIndex({
targetIndex,
node: {
children: treeData,
expanded: true,
},
currentIndex: -1,
path: [],
lowerSiblingCounts: [],
isPseudoRoot: true,
})
if (result.node) {
return result
}
return undefined
}
export const walk = ({
treeData,
callback,
ignoreCollapsed = true,
}: WalkAndMapFunctionParameters): void => {
if (!treeData || treeData.length === 0) {
return
}
walkDescendants({
callback,
ignoreCollapsed,
isPseudoRoot: true,
node: { children: treeData },
currentIndex: -1,
path: [],
lowerSiblingCounts: [],
})
}
export const map = ({
treeData,
callback,
ignoreCollapsed = true,
}: WalkAndMapFunctionParameters): TreeItem[] => {
if (!treeData || treeData.length === 0) {
return []
}
return mapDescendants({
callback,
ignoreCollapsed,
isPseudoRoot: true,
node: { children: treeData },
currentIndex: -1,
path: [],
lowerSiblingCounts: [],
}).node.children
}
export const toggleExpandedForAll = ({
treeData,
expanded = true,
}: FullTree & {
expanded?: boolean | undefined
}): TreeItem[] => {
return map({
treeData,
callback: ({ node }) => ({ ...node, expanded }),
ignoreCollapsed: false,
})
}
export const changeNodeAtPath = ({
treeData,
path,
newNode,
ignoreCollapsed = true,
}: FullTree &
TreePath & {
newNode: Function | any
ignoreCollapsed?: boolean | undefined
}): TreeItem[] => {
const RESULT_MISS = 'RESULT_MISS'
const traverse = ({
isPseudoRoot = false,
node,
currentTreeIndex,
pathIndex,
}) => {
if (!isPseudoRoot && node.nodeId !== 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
}
export const removeNodeAtPath = ({
treeData,
path,
ignoreCollapsed = true,
}: FullTree &
TreePath & {
ignoreCollapsed?: boolean | undefined
}): TreeItem[] => {
return changeNodeAtPath({
treeData,
path,
ignoreCollapsed,
newNode: undefined, // Delete the node
})
}
export const removeNode = ({
treeData,
path,
ignoreCollapsed = true,
}: FullTree &
TreePath & {
ignoreCollapsed?: boolean | undefined
}): (FullTree & TreeNode & TreeIndex) | undefined => {
let removedNode
let removedTreeIndex
const nextTreeData = changeNodeAtPath({
treeData,
path,
ignoreCollapsed,
newNode: ({ node, treeIndex }) => {
// Store the target node and delete it from the tree
removedNode = node
removedTreeIndex = treeIndex
return undefined
},
})
return {
treeData: nextTreeData,
node: removedNode,
treeIndex: removedTreeIndex,
}
}
export const getNodeAtPath = ({
treeData,
path,
ignoreCollapsed = true,
}: FullTree &
TreePath & {
ignoreCollapsed?: boolean | undefined
}): (TreeNode & TreeIndex) | null => {
let foundNodeInfo
try {
changeNodeAtPath({
treeData,
path,
ignoreCollapsed,
newNode: ({ node, treeIndex }: GetTreeItemChildren) => {
foundNodeInfo = { node, treeIndex }
return node
},
})
} catch {
// Ignore the error -- the null return will be explanation enough
}
return foundNodeInfo
}
export const addNodeUnderParent = ({
treeData,
newNode,
parentKey = undefined,
ignoreCollapsed = true,
expandParent = false,
addAsFirstChild = false,
}: FullTree & {
newNode: TreeItem
parentKey?: number | string | undefined | null
ignoreCollapsed?: boolean | undefined
expandParent?: boolean | undefined
addAsFirstChild?: boolean | undefined
}): FullTree & TreeIndex => {
if (parentKey === null || parentKey === undefined) {
return addAsFirstChild
? {
treeData: [newNode, ...(treeData || [])],
treeIndex: 0,
}
: {
treeData: [...(treeData || []), newNode],
treeIndex: (treeData || []).length,
}
}
let insertedTreeIndex
let hasBeenAdded = false
const changedTreeData = map({
treeData,
ignoreCollapsed,
callback: ({ node, treeIndex, path }: GetTreeItemChildren) => {
const key = path ? path.at(-1) : undefined
// 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 TypeError('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,
}
}
const addNodeAtDepthAndIndex = ({
targetDepth,
minimumTreeIndex,
newNode,
ignoreCollapsed,
expandParent,
isPseudoRoot = false,
isLastChild,
node,
currentIndex,
currentDepth,
path = [],
}) => {
const selfPath = (n) => (isPseudoRoot ? [] : [...path, n.nodeId])
// If the current position is the only possible place to add, add it
if (
currentIndex >= minimumTreeIndex - 1 ||
(isLastChild && !(node.children && node.children.length > 0))
) {
if (typeof node.children === 'function') {
throw new TypeError('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 ? undefined : 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
let insertIndex
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 || insertIndex === undefined) {
// 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 ? undefined : 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
let pathFragment
let parentNode
let childIndex = currentIndex + 1
let newChildren = node.children
if (typeof newChildren !== 'function') {
newChildren = newChildren.map((child, i) => {
if (insertedTreeIndex !== null && insertedTreeIndex !== undefined) {
return child
}
const mapResult = addNodeAtDepthAndIndex({
targetDepth,
minimumTreeIndex,
newNode,
ignoreCollapsed,
expandParent,
isLastChild: isLastChild && i === newChildren.length - 1,
node: child,
currentIndex: childIndex,
currentDepth: currentDepth + 1,
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 && insertedTreeIndex !== undefined) {
result.insertedTreeIndex = insertedTreeIndex
result.parentPath = [...selfPath(nextNode), ...pathFragment]
result.parentNode = parentNode
}
return result
}
export const insertNode = ({
treeData,
depth: targetDepth,
minimumTreeIndex,
newNode,
draggedNodes,
ignoreCollapsed = true,
expandParent = false,
}: FullTree & {
depth: number
newNode: TreeItem
minimumTreeIndex: number
ignoreCollapsed?: boolean | undefined
expandParent?: boolean | undefined
}): FullTree & TreeIndex & TreePath & { parentNode: TreeItem | null } => {
if (draggedNodes && draggedNodes.length > 0) {
let multipleNodesTree = [...treeData]
let multipleNodesInsertResult
for (const draggedNodeInfo of draggedNodes) {
const insertResult = addNodeAtDepthAndIndex({
targetDepth,
minimumTreeIndex,
newNode: draggedNodeInfo.node,
ignoreCollapsed,
expandParent,
isPseudoRoot: true,
isLastChild: true,
node: { children: multipleNodesTree },
currentIndex: -1,
currentDepth: -1,
})
multipleNodesTree = insertResult.node.children
multipleNodesInsertResult = insertResult
}
const treeIndex = multipleNodesInsertResult.insertedTreeIndex
return {
treeData: multipleNodesInsertResult.node.children,
treeIndex,
path: [...multipleNodesInsertResult.parentPath, newNode.nodeId],
parentNode: multipleNodesInsertResult.parentNode,
}
}
if (!treeData && targetDepth === 0) {
return {
treeData: [newNode],
treeIndex: 0,
path: [newNode.nodeId],
parentNode: undefined,
}
}
const insertResult = addNodeAtDepthAndIndex({
targetDepth,
minimumTreeIndex,
newNode,
ignoreCollapsed,
expandParent,
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, newNode.nodeId],
parentNode: insertResult.parentNode,
}
}
export const getFlatDataFromTree = ({
treeData,
ignoreCollapsed = true,
}: FullTree & {
ignoreCollapsed?: boolean | undefined
}): FlatDataItem[] => {
if (!treeData || treeData.length === 0) {
return []
}
const flattened = []
walk({
treeData,
ignoreCollapsed,
callback: (nodeInfo) => {
flattened.push(nodeInfo)
},
})
return flattened
}
export const getTreeFromFlatData = ({
flatData,
rootKey = '0',
}: {
flatData: any
rootKey: string | null
}) => {
if (!flatData) {
return []
}
const childrenToParents = {}
for (const child of flatData) {
const parentKey = child.parentId
if (parentKey in childrenToParents) {
childrenToParents[parentKey].push(child)
} else {
childrenToParents[parentKey] = [child]
}
}
if (!(rootKey in childrenToParents)) {
return []
}
const trav = (parent) => {
const parentKey = parent.nodeId
if (parentKey in childrenToParents) {
return {
...parent,
children: childrenToParents[parentKey].map((child) => trav(child)),
}
}
return { ...parent }
}
return childrenToParents[rootKey].map((child) => trav(child))
}
export const isDescendant = (older: TreeItem, younger: TreeItem): boolean => {
return (
!!older.children &&
typeof older.children !== 'function' &&
older.children.some(
(child) => child === younger || isDescendant(child, younger)
)
)
}
export const getDepth = (node: TreeItem, depth = 0): number => {
if (!node.children) {
return depth
}
if (typeof node.children === 'function') {
return depth + 1
}
return node.children.reduce(
(deepest, child) => Math.max(deepest, getDepth(child, depth + 1)),
depth
)
}
export const find = ({
treeData,
searchQuery,
searchMethod,
searchFocusOffset,
expandAllMatchPaths = false,
expandFocusMatchPaths = true,
}: FullTree & {
searchQuery?: string | number | undefined
searchMethod: (data: SearchData) => boolean
searchFocusOffset?: number | undefined
expandAllMatchPaths?: boolean | undefined
expandFocusMatchPaths?: boolean | undefined
}): { matches: NodeData[] } & FullTree => {
let matchCount = 0
const trav = ({ isPseudoRoot = false, node, currentIndex, path = [] }) => {
let matches: any[] = []
let isSelfMatch = false
let hasFocusMatch = false
// The pseudo-root is not considered in the path
const selfPath = isPseudoRoot ? [] : [...path, node.nodeId]
const extraInfo = isPseudoRoot
? undefined
: {
path: selfPath,
treeIndex: currentIndex,
}
// Nodes with with children that aren't lazy
const hasChildren =
node.children &&
typeof node.children !== 'function' &&
node.children.length > 0
// Examine the current node to see if it is a match
if (!isPseudoRoot && searchMethod({ ...extraInfo, node, searchQuery })) {
if (matchCount === searchFocusOffset) {
hasFocusMatch = true
}
// Keep track of the number of matching nodes, so we know when the searchFocusOffset
// is reached
matchCount += 1
// We cannot add this node to the matches right away, as it may be changed
// during the search of the descendants. The entire node is used in
// comparisons between nodes inside the `matches` and `treeData` results
// of this method (`find`)
isSelfMatch = true
}
let childIndex = currentIndex
const newNode = { ...node }
if (hasChildren) {
// Get all descendants
newNode.children = newNode.children.map((child) => {
const mapResult = trav({
node: child,
currentIndex: childIndex + 1,
path: selfPath,
})
// Ignore hidden nodes by only advancing the index counter to the returned treeIndex
// if the child is expanded.
//
// The child could have been expanded from the start,
// or expanded due to a matching node being found in its descendants
if (mapResult.node.expanded) {
childIndex = mapResult.treeIndex
} else {
childIndex += 1
}
if (mapResult.matches.length > 0 || mapResult.hasFocusMatch) {
matches = [...matches, ...mapResult.matches]
if (mapResult.hasFocusMatch) {
hasFocusMatch = true
}
// Expand the current node if it has descendants matching the search
// and the settings are set to do so.
if (
(expandAllMatchPaths && mapResult.matches.length > 0) ||