UNPKG

1.91 kBJavaScriptView Raw
1import * as React from 'react';
2// recursion (flat tree structure)
3function fillRecords(list, record, indent, childrenColumnName, expandedKeys, getRowKey, index) {
4 list.push({
5 record: record,
6 indent: indent,
7 index: index
8 });
9 var key = getRowKey(record);
10 var expanded = expandedKeys === null || expandedKeys === void 0 ? void 0 : expandedKeys.has(key);
11 if (record && Array.isArray(record[childrenColumnName]) && expanded) {
12 // expanded state, flat record
13 for (var i = 0; i < record[childrenColumnName].length; i += 1) {
14 fillRecords(list, record[childrenColumnName][i], indent + 1, childrenColumnName, expandedKeys, getRowKey, i);
15 }
16 }
17}
18/**
19 * flat tree data on expanded state
20 *
21 * @export
22 * @template T
23 * @param {*} data : table data
24 * @param {string} childrenColumnName : 指定树形结构的列名
25 * @param {Set<Key>} expandedKeys : 展开的行对应的keys
26 * @param {GetRowKey<T>} getRowKey : 获取当前rowKey的方法
27 * @returns flattened data
28 */
29export default function useFlattenRecords(data, childrenColumnName, expandedKeys, getRowKey) {
30 var arr = React.useMemo(function () {
31 if (expandedKeys !== null && expandedKeys !== void 0 && expandedKeys.size) {
32 var list = [];
33
34 // collect flattened record
35 for (var i = 0; i < (data === null || data === void 0 ? void 0 : data.length); i += 1) {
36 var record = data[i];
37
38 // using array.push or spread operator may cause "Maximum call stack size exceeded" exception if array size is big enough.
39 fillRecords(list, record, 0, childrenColumnName, expandedKeys, getRowKey, i);
40 }
41 return list;
42 }
43 return data === null || data === void 0 ? void 0 : data.map(function (item, index) {
44 return {
45 record: item,
46 indent: 0,
47 index: index
48 };
49 });
50 }, [data, childrenColumnName, expandedKeys, getRowKey]);
51 return arr;
52}
\No newline at end of file