mirror of
https://gitee.com/ant-design/ant-design.git
synced 2024-12-16 01:41:02 +08:00
a802a72d56
* use new life cycle * filter support inner value maps * update snapshot * update test case * simple code
81 lines
2.0 KiB
TypeScript
81 lines
2.0 KiB
TypeScript
import * as React from 'react';
|
|
import { ColumnFilterItem } from './interface';
|
|
|
|
export function flatArray(data: any[] = [], childrenName = 'children') {
|
|
const result: any[] = [];
|
|
const loop = (array: any[]) => {
|
|
array.forEach(item => {
|
|
if (item[childrenName]) {
|
|
const newItem = { ...item };
|
|
delete newItem[childrenName];
|
|
result.push(newItem);
|
|
if (item[childrenName].length > 0) {
|
|
loop(item[childrenName]);
|
|
}
|
|
} else {
|
|
result.push(item);
|
|
}
|
|
});
|
|
};
|
|
loop(data);
|
|
return result;
|
|
}
|
|
|
|
export function treeMap<Node>(
|
|
tree: Node[],
|
|
mapper: (node: Node, index: number) => any,
|
|
childrenName = 'children',
|
|
) {
|
|
return tree.map((node: any, index) => {
|
|
const extra: any = {};
|
|
if (node[childrenName]) {
|
|
extra[childrenName] = treeMap(node[childrenName], mapper, childrenName);
|
|
}
|
|
return {
|
|
...mapper(node as Node, index),
|
|
...extra,
|
|
};
|
|
});
|
|
}
|
|
|
|
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;
|
|
}, []);
|
|
}
|
|
|
|
export function normalizeColumns(elements: React.ReactChildren) {
|
|
const columns: any[] = [];
|
|
React.Children.forEach(elements, element => {
|
|
if (!React.isValidElement(element)) {
|
|
return;
|
|
}
|
|
const column: any = {
|
|
...element.props,
|
|
};
|
|
if (element.key) {
|
|
column.key = element.key;
|
|
}
|
|
if (element.type && (element.type as any).__ANT_TABLE_COLUMN_GROUP) {
|
|
column.children = normalizeColumns(column.children);
|
|
}
|
|
columns.push(column);
|
|
});
|
|
return columns;
|
|
}
|
|
|
|
export function generateValueMaps(items?: ColumnFilterItem[], maps: { [name: string]: any } = {}) {
|
|
(items || []).forEach(({ value, children }) => {
|
|
maps[value.toString()] = value;
|
|
generateValueMaps(children, maps);
|
|
});
|
|
return maps;
|
|
}
|