@@ -3,45 +3,35 @@ import type { DataNode, SimpleModeConfig } from '../interface';
3
3
import { convertChildrenToData } from '../utils/legacyUtil' ;
4
4
import type { DefaultOptionType } from '../TreeSelect' ;
5
5
6
- function parseSimpleTreeData (
7
- treeData : DataNode [ ] ,
8
- { id, pId, rootPId } : SimpleModeConfig ,
9
- ) : DataNode [ ] {
10
- const keyNodes = { } ;
11
- const rootNodeList = [ ] ;
12
-
13
- // Fill in the map
14
- const nodeList = treeData . map ( node => {
15
- const clone = { ...node } ;
16
- const key = clone [ id ] ;
17
- keyNodes [ key ] = clone ;
18
- clone . key = clone . key || key ;
19
- return clone ;
6
+ function buildTreeStructure ( nodes : DataNode [ ] , config : SimpleModeConfig ) : DataNode [ ] {
7
+ const { id, pId, rootPId } = config ;
8
+ const nodeMap = new Map < string , DataNode > ( ) ;
9
+ const rootNodes : DataNode [ ] = [ ] ;
10
+
11
+ nodes . forEach ( node => {
12
+ const nodeKey = node [ id ] ;
13
+ const clonedNode = { ...node , key : node . key || nodeKey } ;
14
+ nodeMap . set ( nodeKey , clonedNode ) ;
20
15
} ) ;
21
16
22
- // Connect tree
23
- nodeList . forEach ( node => {
17
+ nodeMap . forEach ( node => {
24
18
const parentKey = node [ pId ] ;
25
- const parent = keyNodes [ parentKey ] ;
19
+ const parent = nodeMap . get ( parentKey ) ;
26
20
27
- // Fill parent
28
21
if ( parent ) {
29
22
parent . children = parent . children || [ ] ;
30
23
parent . children . push ( node ) ;
31
- }
32
-
33
- // Fill root tree node
34
- if ( parentKey === rootPId || ( ! parent && rootPId === null ) ) {
35
- rootNodeList . push ( node ) ;
24
+ } else if ( parentKey === rootPId || rootPId === null ) {
25
+ rootNodes . push ( node ) ;
36
26
}
37
27
} ) ;
38
28
39
- return rootNodeList ;
29
+ return rootNodes ;
40
30
}
41
31
42
32
/**
43
- * Convert `treeData` or `children` into formatted `treeData`.
44
- * Will not re-calculate if `treeData` or `children` not change.
33
+ * 将 `treeData` 或 `children` 转换为格式化的 `treeData`。
34
+ * 如果 `treeData` 或 `children` 没有变化,则不会重新计算。
45
35
*/
46
36
export default function useTreeData (
47
37
treeData : DataNode [ ] ,
@@ -50,14 +40,16 @@ export default function useTreeData(
50
40
) : DefaultOptionType [ ] {
51
41
return React . useMemo ( ( ) => {
52
42
if ( treeData ) {
53
- return simpleMode
54
- ? parseSimpleTreeData ( treeData , {
55
- id : 'id' ,
56
- pId : 'pId' ,
57
- rootPId : null ,
58
- ...( simpleMode !== true ? simpleMode : { } ) ,
59
- } )
60
- : treeData ;
43
+ if ( simpleMode ) {
44
+ const config : SimpleModeConfig = {
45
+ id : 'id' ,
46
+ pId : 'pId' ,
47
+ rootPId : null ,
48
+ ...( typeof simpleMode === 'object' ? simpleMode : { } ) ,
49
+ } ;
50
+ return buildTreeStructure ( treeData , config ) ;
51
+ }
52
+ return treeData ;
61
53
}
62
54
63
55
return convertChildrenToData ( children ) ;
0 commit comments