2017-11-17 14:38:54 +08:00
|
|
|
import * as React from 'react';
|
2016-11-22 10:11:12 +08:00
|
|
|
|
2017-11-21 13:48:37 +08:00
|
|
|
export function flatArray(data: any[] = [], childrenName = 'children') {
|
|
|
|
const result: any[] = [];
|
|
|
|
const loop = (array: any[]) => {
|
2016-03-16 16:39:53 +08:00
|
|
|
array.forEach(item => {
|
2017-08-07 15:33:18 +08:00
|
|
|
if (item[childrenName]) {
|
|
|
|
const newItem = { ...item };
|
|
|
|
delete newItem[childrenName];
|
|
|
|
result.push(newItem);
|
|
|
|
if (item[childrenName].length > 0) {
|
|
|
|
loop(item[childrenName]);
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
result.push(item);
|
2016-03-16 16:39:53 +08:00
|
|
|
}
|
|
|
|
});
|
|
|
|
};
|
|
|
|
loop(data);
|
|
|
|
return result;
|
|
|
|
}
|
2016-09-09 13:55:41 +08:00
|
|
|
|
2018-12-07 20:02:01 +08:00
|
|
|
export function treeMap<Node>(
|
|
|
|
tree: Node[],
|
|
|
|
mapper: (node: Node, index: number) => any,
|
|
|
|
childrenName = 'children',
|
|
|
|
) {
|
2017-11-21 13:48:37 +08:00
|
|
|
return tree.map((node: any, index) => {
|
|
|
|
const extra: any = {};
|
2016-09-09 13:55:41 +08:00
|
|
|
if (node[childrenName]) {
|
|
|
|
extra[childrenName] = treeMap(node[childrenName], mapper, childrenName);
|
|
|
|
}
|
2017-07-03 16:57:11 +08:00
|
|
|
return {
|
2017-11-21 13:48:37 +08:00
|
|
|
...mapper(node as Node, index),
|
2017-07-03 16:57:11 +08:00
|
|
|
...extra,
|
|
|
|
};
|
2016-09-09 13:55:41 +08:00
|
|
|
});
|
|
|
|
}
|
2016-11-22 10:11:12 +08:00
|
|
|
|
2017-03-10 14:52:28 +08:00
|
|
|
export function flatFilter(tree: any[], callback: Function) {
|
|
|
|
return tree.reduce((acc, node) => {
|
|
|
|
if (callback(node)) {
|
|
|
|
acc.push(node);
|
|
|
|
}
|
|
|
|
if (node.children) {
|
|
|
|
const children = flatFilter(node.children, callback);
|
|
|
|
acc.push(...children);
|
|
|
|
}
|
|
|
|
return acc;
|
|
|
|
}, []);
|
|
|
|
}
|
|
|
|
|
2017-11-21 13:48:37 +08:00
|
|
|
export function normalizeColumns(elements: React.ReactChildren) {
|
2016-11-22 10:11:12 +08:00
|
|
|
const columns: any[] = [];
|
2018-12-07 20:02:01 +08:00
|
|
|
React.Children.forEach(elements, element => {
|
2017-01-11 19:52:43 +08:00
|
|
|
if (!React.isValidElement(element)) {
|
2016-11-22 10:11:12 +08:00
|
|
|
return;
|
|
|
|
}
|
2017-07-03 16:57:11 +08:00
|
|
|
const column: any = {
|
|
|
|
...element.props,
|
|
|
|
};
|
2016-11-22 10:11:12 +08:00
|
|
|
if (element.key) {
|
|
|
|
column.key = element.key;
|
|
|
|
}
|
2017-06-01 15:07:37 +08:00
|
|
|
if (element.type && (element.type as any).__ANT_TABLE_COLUMN_GROUP) {
|
2016-11-22 10:11:12 +08:00
|
|
|
column.children = normalizeColumns(column.children);
|
|
|
|
}
|
|
|
|
columns.push(column);
|
|
|
|
});
|
|
|
|
return columns;
|
|
|
|
}
|