ant-design/components/tree/util.ts

116 lines
2.7 KiB
TypeScript
Raw Normal View History

import * as React from 'react';
2018-07-30 12:05:29 +08:00
import { getNodeChildren, convertTreeToEntities } from 'rc-tree/lib/util';
2019-04-09 14:20:59 +08:00
import { AntTreeNodeProps, AntTreeNode } from './Tree';
enum Record {
None,
Start,
End,
}
2018-07-30 12:05:29 +08:00
// TODO: Move this logic into `rc-tree`
2018-12-07 16:17:45 +08:00
function traverseNodesKey(
rootChildren: React.ReactNode | React.ReactNode[],
2019-04-09 14:20:59 +08:00
callback: (key: string | number | null, node: AntTreeNode) => boolean,
2018-12-07 16:17:45 +08:00
) {
const nodeList: React.ReactNode[] = getNodeChildren(rootChildren) || [];
2018-07-30 12:05:29 +08:00
function processNode(node: React.ReactElement<AntTreeNodeProps>) {
2018-12-07 16:17:45 +08:00
const {
key,
props: { children },
} = node;
2019-04-09 14:20:59 +08:00
if (callback(key, node as any) !== false) {
2018-07-30 12:05:29 +08:00
traverseNodesKey(children, callback);
}
}
nodeList.forEach(processNode);
}
export function getFullKeyList(children: React.ReactNode | React.ReactNode[]) {
const { keyEntities } = convertTreeToEntities(children);
return Object.keys(keyEntities);
}
/** 计算选中范围只考虑expanded情况以优化性能 */
2018-12-07 16:17:45 +08:00
export function calcRangeKeys(
rootChildren: React.ReactNode | React.ReactNode[],
expandedKeys: string[],
startKey?: string,
endKey?: string,
): string[] {
const keys: string[] = [];
let record: Record = Record.None;
if (startKey && startKey === endKey) {
return [startKey];
}
if (!startKey || !endKey) {
return [];
}
function matchKey(key: string) {
return key === startKey || key === endKey;
}
2018-07-30 12:05:29 +08:00
traverseNodesKey(rootChildren, (key: string) => {
if (record === Record.End) {
return false;
}
if (matchKey(key)) {
// Match test
keys.push(key);
if (record === Record.None) {
record = Record.Start;
} else if (record === Record.Start) {
record = Record.End;
return false;
}
} else if (record === Record.Start) {
// Append selection
keys.push(key);
}
if (expandedKeys.indexOf(key) === -1) {
return false;
}
2018-07-30 12:05:29 +08:00
return true;
});
return keys;
}
2019-04-09 14:20:59 +08:00
2019-05-07 14:57:32 +08:00
export function convertDirectoryKeysToNodes(
rootChildren: React.ReactNode | React.ReactNode[],
keys: string[],
) {
2019-04-09 14:20:59 +08:00
const restKeys: string[] = [...keys];
const nodes: AntTreeNode[] = [];
traverseNodesKey(rootChildren, (key: string, node: AntTreeNode) => {
const index = restKeys.indexOf(key);
if (index !== -1) {
nodes.push(node);
restKeys.splice(index, 1);
}
return !!restKeys.length;
});
return nodes;
2019-05-07 14:57:32 +08:00
}
export function getFullKeyListByTreeData(treeData: any[]): any[] {
let keys: string[] = [];
(treeData || []).forEach(item => {
keys.push(item.key);
if (item.children) {
keys = [...keys, ...getFullKeyListByTreeData(item.children)];
}
});
return keys;
}