UNPKG

2.92 kBJavaScriptView Raw
1"use strict";
2
3var _typeof = require("@babel/runtime/helpers/typeof");
4Object.defineProperty(exports, "__esModule", {
5 value: true
6});
7exports.default = useFlattenRecords;
8var React = _interopRequireWildcard(require("react"));
9function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
10function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
11// recursion (flat tree structure)
12function fillRecords(list, record, indent, childrenColumnName, expandedKeys, getRowKey, index) {
13 list.push({
14 record: record,
15 indent: indent,
16 index: index
17 });
18 var key = getRowKey(record);
19 var expanded = expandedKeys === null || expandedKeys === void 0 ? void 0 : expandedKeys.has(key);
20 if (record && Array.isArray(record[childrenColumnName]) && expanded) {
21 // expanded state, flat record
22 for (var i = 0; i < record[childrenColumnName].length; i += 1) {
23 fillRecords(list, record[childrenColumnName][i], indent + 1, childrenColumnName, expandedKeys, getRowKey, i);
24 }
25 }
26}
27/**
28 * flat tree data on expanded state
29 *
30 * @export
31 * @template T
32 * @param {*} data : table data
33 * @param {string} childrenColumnName : 指定树形结构的列名
34 * @param {Set<Key>} expandedKeys : 展开的行对应的keys
35 * @param {GetRowKey<T>} getRowKey : 获取当前rowKey的方法
36 * @returns flattened data
37 */
38function useFlattenRecords(data, childrenColumnName, expandedKeys, getRowKey) {
39 var arr = React.useMemo(function () {
40 if (expandedKeys !== null && expandedKeys !== void 0 && expandedKeys.size) {
41 var list = [];
42
43 // collect flattened record
44 for (var i = 0; i < (data === null || data === void 0 ? void 0 : data.length); i += 1) {
45 var record = data[i];
46
47 // using array.push or spread operator may cause "Maximum call stack size exceeded" exception if array size is big enough.
48 fillRecords(list, record, 0, childrenColumnName, expandedKeys, getRowKey, i);
49 }
50 return list;
51 }
52 return data === null || data === void 0 ? void 0 : data.map(function (item, index) {
53 return {
54 record: item,
55 indent: 0,
56 index: index
57 };
58 });
59 }, [data, childrenColumnName, expandedKeys, getRowKey]);
60 return arr;
61}
\No newline at end of file