-
-
Notifications
You must be signed in to change notification settings - Fork 619
Expand file tree
/
Copy pathuseFlattenRecords.ts
More file actions
91 lines (80 loc) · 2.16 KB
/
useFlattenRecords.ts
File metadata and controls
91 lines (80 loc) · 2.16 KB
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
import * as React from 'react';
import type { GetRowKey, Key } from '../interface';
// recursion (flat tree structure)
function fillRecords<T>(
list: FlattenData<T>[],
record: T,
indent: number,
childrenColumnName: string,
expandedKeys: Set<Key>,
getRowKey: GetRowKey<T>,
index: number,
) {
list.push({
record,
indent,
index,
rowKey: getRowKey(record, index),
});
const key = getRowKey(record);
const expanded = expandedKeys?.has(key);
if (record && Array.isArray(record[childrenColumnName]) && expanded) {
// expanded state, flat record
for (let i = 0; i < record[childrenColumnName].length; i += 1) {
fillRecords(
list,
record[childrenColumnName][i],
indent + 1,
childrenColumnName,
expandedKeys,
getRowKey,
i,
);
}
}
}
export interface FlattenData<RecordType> {
record: RecordType;
indent: number;
index: number;
rowKey: Key;
}
/**
* flat tree data on expanded state
*
* @export
* @template T
* @param {*} data : table data
* @param {string} childrenColumnName : 指定树形结构的列名
* @param {Set<Key>} expandedKeys : 展开的行对应的keys
* @param {GetRowKey<T>} getRowKey : 获取当前rowKey的方法
* @returns flattened data
*/
export default function useFlattenRecords<T>(
data: T[] | readonly T[],
childrenColumnName: string,
expandedKeys: Set<Key>,
getRowKey: GetRowKey<T>,
): FlattenData<T>[] {
const arr: FlattenData<T>[] = React.useMemo(() => {
if (expandedKeys?.size) {
const list: FlattenData<T>[] = [];
// collect flattened record
for (let i = 0; i < data?.length; i += 1) {
const record = data[i];
// using array.push or spread operator may cause "Maximum call stack size exceeded" exception if array size is big enough.
fillRecords(list, record, 0, childrenColumnName, expandedKeys, getRowKey, i);
}
return list;
}
return data?.map((item, index) => {
return {
record: item,
indent: 0,
index,
rowKey: getRowKey(item, index),
};
});
}, [data, childrenColumnName, expandedKeys, getRowKey]);
return arr;
}