Browse Source

refactor(tree): rewrite with hook (#23550)

* refactor(tree): rewrite with hook

* fix codecov

* Update directory.test.js

* Update README.md

* 🆙 upgrade intersection-observer

* refactor(tree): rewrite with hook

* fix codecov

* Update directory.test.js

Co-authored-by: 偏右 <afc163@gmail.com>
pull/23586/head
Tom Xu 5 years ago
committed by GitHub
parent
commit
54f2abfe47
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 244
      components/tree/DirectoryTree.tsx
  2. 114
      components/tree/Tree.tsx
  3. 61
      components/tree/__tests__/directory.test.js

244
components/tree/DirectoryTree.tsx

@ -1,6 +1,5 @@
import * as React from 'react';
import classNames from 'classnames';
import omit from 'omit.js';
import debounce from 'lodash/debounce';
import { conductExpandParent } from 'rc-tree/lib/util';
import { EventDataNode, DataNode, Key } from 'rc-tree/lib/interface';
@ -8,7 +7,7 @@ import { convertDataToEntities, convertTreeToData } from 'rc-tree/lib/utils/tree
import FileOutlined from '@ant-design/icons/FileOutlined';
import FolderOpenOutlined from '@ant-design/icons/FolderOpenOutlined';
import FolderOutlined from '@ant-design/icons/FolderOutlined';
import { ConfigConsumer, ConfigConsumerProps } from '../config-provider';
import { ConfigContext } from '../config-provider';
import Tree, { TreeProps, AntdTreeNodeAttribute } from './Tree';
import { calcRangeKeys, convertDirectoryKeysToNodes } from './utils/dictUtil';
@ -36,109 +35,116 @@ function getTreeData({ treeData, children }: DirectoryTreeProps) {
return treeData || convertTreeToData(children);
}
class DirectoryTree extends React.Component<DirectoryTreeProps, DirectoryTreeState> {
static defaultProps = {
showIcon: true,
expandAction: 'click' as DirectoryTreeProps['expandAction'],
};
static getDerivedStateFromProps(nextProps: DirectoryTreeProps) {
const newState: DirectoryTreeState = {};
if ('expandedKeys' in nextProps) {
newState.expandedKeys = nextProps.expandedKeys;
}
if ('selectedKeys' in nextProps) {
newState.selectedKeys = nextProps.selectedKeys;
}
return newState;
}
state: DirectoryTreeState;
tree: Tree;
onDebounceExpand: (event: React.MouseEvent<HTMLElement>, node: EventDataNode) => void;
const DirectoryTree: React.FC<DirectoryTreeProps> = ({
defaultExpandAll,
defaultExpandParent,
defaultExpandedKeys,
...props
}) => {
// Shift click usage
lastSelectedKey?: Key;
const lastSelectedKey = React.useRef<Key>();
cachedSelectedKeys?: Key[];
const cachedSelectedKeys = React.useRef<Key[]>();
constructor(props: DirectoryTreeProps) {
super(props);
const ref = React.createRef<any>();
const { defaultExpandAll, defaultExpandParent, expandedKeys, defaultExpandedKeys } = props;
const getInitExpandedKeys = () => {
const { keyEntities } = convertDataToEntities(getTreeData(props));
// Selected keys
this.state = {
selectedKeys: props.selectedKeys || props.defaultSelectedKeys || [],
};
let initExpandedKeys: any;
// Expanded keys
if (defaultExpandAll) {
this.state.expandedKeys = Object.keys(keyEntities);
initExpandedKeys = Object.keys(keyEntities);
} else if (defaultExpandParent) {
this.state.expandedKeys = conductExpandParent(
expandedKeys || defaultExpandedKeys,
initExpandedKeys = conductExpandParent(
props.expandedKeys || defaultExpandedKeys,
keyEntities,
);
} else {
this.state.expandedKeys = expandedKeys || defaultExpandedKeys;
initExpandedKeys = props.expandedKeys || defaultExpandedKeys;
}
return initExpandedKeys;
};
this.onDebounceExpand = debounce(this.expandFolderNode, 200, {
leading: true,
});
}
const [selectedKeys, setSelectedKeys] = React.useState(
props.selectedKeys || props.defaultSelectedKeys || [],
);
const [expandedKeys, setExpandedKeys] = React.useState(getInitExpandedKeys());
React.useEffect(() => {
if ('selectedKeys' in props) {
setSelectedKeys(props.selectedKeys!);
}
}, [props.selectedKeys]);
React.useEffect(() => {
if ('expandedKeys' in props) {
setExpandedKeys(props.expandedKeys);
}
}, [props.expandedKeys]);
const expandFolderNode = (event: React.MouseEvent<HTMLElement>, node: any) => {
const { isLeaf } = node;
if (isLeaf || event.shiftKey || event.metaKey || event.ctrlKey) {
return;
}
// Call internal rc-tree expand function
// https://github.com/ant-design/ant-design/issues/12567
ref.current.onNodeExpand(event, node);
};
onExpand = (
expandedKeys: Key[],
const onDebounceExpand = debounce(expandFolderNode, 200, {
leading: true,
});
const onExpand = (
keys: Key[],
info: {
node: EventDataNode;
expanded: boolean;
nativeEvent: MouseEvent;
},
) => {
const { onExpand } = this.props;
this.setUncontrolledState({ expandedKeys });
if (!('expandedKeys' in props)) {
setExpandedKeys(keys);
}
// Call origin function
if (onExpand) {
return onExpand(expandedKeys, info);
if (props.onExpand) {
return props.onExpand(keys, info);
}
return undefined;
};
onClick = (event: React.MouseEvent<HTMLElement>, node: EventDataNode) => {
const { onClick, expandAction } = this.props;
const onClick = (event: React.MouseEvent<HTMLElement>, node: EventDataNode) => {
const { expandAction } = props;
// Expand the tree
if (expandAction === 'click') {
this.onDebounceExpand(event, node);
onDebounceExpand(event, node);
}
if (onClick) {
onClick(event, node);
if (props.onClick) {
props.onClick(event, node);
}
};
onDoubleClick = (event: React.MouseEvent<HTMLElement>, node: EventDataNode) => {
const { onDoubleClick, expandAction } = this.props;
const onDoubleClick = (event: React.MouseEvent<HTMLElement>, node: EventDataNode) => {
const { expandAction } = props;
// Expand the tree
if (expandAction === 'doubleClick') {
this.onDebounceExpand(event, node);
onDebounceExpand(event, node);
}
if (onDoubleClick) {
onDoubleClick(event, node);
if (props.onDoubleClick) {
props.onDoubleClick(event, node);
}
};
onSelect = (
const onSelect = (
keys: Key[],
event: {
event: 'select';
@ -148,13 +154,12 @@ class DirectoryTree extends React.Component<DirectoryTreeProps, DirectoryTreeSta
nativeEvent: MouseEvent;
},
) => {
const { onSelect, multiple } = this.props;
const { expandedKeys = [] } = this.state;
const { multiple } = props;
const { node, nativeEvent } = event;
const { key = '' } = node;
const treeData = getTreeData(this.props);
const newState: DirectoryTreeState = {};
const treeData = getTreeData(props);
// const newState: DirectoryTreeState = {};
// We need wrap this event since some value is not same
const newEvent: any = {
@ -171,90 +176,63 @@ class DirectoryTree extends React.Component<DirectoryTreeProps, DirectoryTreeSta
if (multiple && ctrlPick) {
// Control click
newSelectedKeys = keys;
this.lastSelectedKey = key;
this.cachedSelectedKeys = newSelectedKeys;
lastSelectedKey.current = key;
cachedSelectedKeys.current = newSelectedKeys;
newEvent.selectedNodes = convertDirectoryKeysToNodes(treeData, newSelectedKeys);
} else if (multiple && shiftPick) {
// Shift click
newSelectedKeys = Array.from(
new Set([
...(this.cachedSelectedKeys || []),
...calcRangeKeys(treeData, expandedKeys, key, this.lastSelectedKey),
...(cachedSelectedKeys.current || []),
...calcRangeKeys(treeData, expandedKeys, key, lastSelectedKey.current),
]),
);
newEvent.selectedNodes = convertDirectoryKeysToNodes(treeData, newSelectedKeys);
} else {
// Single click
newSelectedKeys = [key];
this.lastSelectedKey = key;
this.cachedSelectedKeys = newSelectedKeys;
lastSelectedKey.current = key;
cachedSelectedKeys.current = newSelectedKeys;
newEvent.selectedNodes = convertDirectoryKeysToNodes(treeData, newSelectedKeys);
}
newState.selectedKeys = newSelectedKeys;
if (onSelect) {
onSelect(newSelectedKeys, newEvent);
if (props.onSelect) {
props.onSelect(newSelectedKeys, newEvent);
}
this.setUncontrolledState(newState);
};
setTreeRef = (node: Tree) => {
this.tree = node;
};
expandFolderNode = (event: React.MouseEvent<HTMLElement>, node: any) => {
const { isLeaf } = node;
if (isLeaf || event.shiftKey || event.metaKey || event.ctrlKey) {
return;
if (!('selectedKeys' in props)) {
setSelectedKeys(newSelectedKeys);
}
// Get internal rc-tree
const internalTree = this.tree.tree;
// Call internal rc-tree expand function
// https://github.com/ant-design/ant-design/issues/12567
internalTree.onNodeExpand(event, node);
};
setUncontrolledState = (state: DirectoryTreeState) => {
const newState = omit(state, Object.keys(this.props));
if (Object.keys(newState).length) {
this.setState(newState);
}
};
renderDirectoryTree = ({ getPrefixCls, direction }: ConfigConsumerProps) => {
const { prefixCls: customizePrefixCls, className, ...props } = this.props;
const { expandedKeys, selectedKeys } = this.state;
const prefixCls = getPrefixCls('tree', customizePrefixCls);
const connectClassName = classNames(`${prefixCls}-directory`, className, {
[`${prefixCls}-directory-rtl`]: direction === 'rtl',
});
return (
<Tree
icon={getIcon}
ref={this.setTreeRef}
blockNode
{...props}
prefixCls={prefixCls}
className={connectClassName}
expandedKeys={expandedKeys}
selectedKeys={selectedKeys}
onSelect={this.onSelect}
onClick={this.onClick}
onDoubleClick={this.onDoubleClick}
onExpand={this.onExpand}
/>
);
};
render() {
return <ConfigConsumer>{this.renderDirectoryTree}</ConfigConsumer>;
}
}
const { getPrefixCls, direction } = React.useContext(ConfigContext);
const { prefixCls: customizePrefixCls, className, ...otherProps } = props;
const prefixCls = getPrefixCls('tree', customizePrefixCls);
const connectClassName = classNames(`${prefixCls}-directory`, className, {
[`${prefixCls}-directory-rtl`]: direction === 'rtl',
});
return (
<Tree
icon={getIcon}
ref={ref}
blockNode
{...otherProps}
prefixCls={prefixCls}
className={connectClassName}
expandedKeys={expandedKeys}
selectedKeys={selectedKeys}
onSelect={onSelect}
onClick={onClick}
onDoubleClick={onDoubleClick}
onExpand={onExpand}
/>
);
};
DirectoryTree.defaultProps = {
showIcon: true,
expandAction: 'click' as DirectoryTreeProps['expandAction'],
};
export default DirectoryTree;

114
components/tree/Tree.tsx

@ -4,7 +4,7 @@ import classNames from 'classnames';
import { DataNode, Key } from 'rc-tree/lib/interface';
import DirectoryTree from './DirectoryTree';
import { ConfigConsumer, ConfigConsumerProps } from '../config-provider';
import { ConfigContext } from '../config-provider';
import collapseMotion from '../_util/motion';
import renderSwitcherIcon from './utils/iconUtil';
@ -135,62 +135,58 @@ export interface TreeProps extends Omit<RcTreeProps, 'prefixCls'> {
blockNode?: boolean;
}
export default class Tree extends React.Component<TreeProps, any> {
static TreeNode = TreeNode;
static DirectoryTree = DirectoryTree;
static defaultProps = {
checkable: false,
showIcon: false,
motion: {
...collapseMotion,
motionAppear: false,
},
blockNode: false,
};
tree: any;
setTreeRef = (node: any) => {
this.tree = node;
};
renderTree = ({ getPrefixCls, direction }: ConfigConsumerProps) => {
const { props } = this;
const {
prefixCls: customizePrefixCls,
className,
showIcon,
showLine,
switcherIcon,
blockNode,
children,
} = props;
const { checkable } = props;
const prefixCls = getPrefixCls('tree', customizePrefixCls);
return (
<RcTree
itemHeight={20}
ref={this.setTreeRef}
{...props}
prefixCls={prefixCls}
className={classNames(className, {
[`${prefixCls}-icon-hide`]: !showIcon,
[`${prefixCls}-block-node`]: blockNode,
[`${prefixCls}-rtl`]: direction === 'rtl',
})}
checkable={checkable ? <span className={`${prefixCls}-checkbox-inner`} /> : checkable}
switcherIcon={(nodeProps: AntTreeNodeProps) =>
renderSwitcherIcon(prefixCls, switcherIcon, showLine, nodeProps)
}
>
{children}
</RcTree>
);
};
render() {
return <ConfigConsumer>{this.renderTree}</ConfigConsumer>;
}
interface CompoundedComponent
extends React.ForwardRefExoticComponent<TreeProps & React.RefAttributes<RcTree>> {
TreeNode: typeof TreeNode;
DirectoryTree: typeof DirectoryTree;
}
const Tree = React.forwardRef<RcTree, TreeProps>((props, ref) => {
const { getPrefixCls, direction } = React.useContext(ConfigContext);
const {
prefixCls: customizePrefixCls,
className,
showIcon,
showLine,
switcherIcon,
blockNode,
children,
checkable,
} = props;
const prefixCls = getPrefixCls('tree', customizePrefixCls);
return (
<RcTree
itemHeight={20}
ref={ref}
{...props}
prefixCls={prefixCls}
className={classNames(className, {
[`${prefixCls}-icon-hide`]: !showIcon,
[`${prefixCls}-block-node`]: blockNode,
[`${prefixCls}-rtl`]: direction === 'rtl',
})}
checkable={checkable ? <span className={`${prefixCls}-checkbox-inner`} /> : checkable}
switcherIcon={(nodeProps: AntTreeNodeProps) =>
renderSwitcherIcon(prefixCls, switcherIcon, showLine, nodeProps)
}
>
{children}
</RcTree>
);
}) as CompoundedComponent;
Tree.TreeNode = TreeNode;
Tree.DirectoryTree = DirectoryTree;
Tree.defaultProps = {
checkable: false,
showIcon: false,
motion: {
...collapseMotion,
motionAppear: false,
},
blockNode: false,
};
export default Tree;

61
components/tree/__tests__/directory.test.js

@ -46,36 +46,20 @@ describe('Directory Tree', () => {
it('click', () => {
const wrapper = mount(createTree());
wrapper
.find(TreeNode)
.find('.ant-tree-node-content-wrapper')
.at(0)
.simulate('click');
wrapper.find(TreeNode).find('.ant-tree-node-content-wrapper').at(0).simulate('click');
expect(wrapper.render()).toMatchSnapshot();
jest.runAllTimers();
wrapper
.find(TreeNode)
.find('.ant-tree-node-content-wrapper')
.at(0)
.simulate('click');
wrapper.find(TreeNode).find('.ant-tree-node-content-wrapper').at(0).simulate('click');
expect(wrapper.render()).toMatchSnapshot();
});
it('double click', () => {
const wrapper = mount(createTree({ expandAction: 'doubleClick' }));
wrapper
.find(TreeNode)
.find('.ant-tree-node-content-wrapper')
.at(0)
.simulate('doubleClick');
wrapper.find(TreeNode).find('.ant-tree-node-content-wrapper').at(0).simulate('doubleClick');
expect(wrapper.render()).toMatchSnapshot();
jest.runAllTimers();
wrapper
.find(TreeNode)
.find('.ant-tree-node-content-wrapper')
.at(0)
.simulate('doubleClick');
wrapper.find(TreeNode).find('.ant-tree-node-content-wrapper').at(0).simulate('doubleClick');
expect(wrapper.render()).toMatchSnapshot();
});
@ -106,11 +90,7 @@ describe('Directory Tree', () => {
it(action, () => {
const wrapper = mount(<StateDirTree expandAction={action} />);
wrapper
.find(TreeNode)
.find('.ant-tree-node-content-wrapper')
.at(0)
.simulate(action);
wrapper.find(TreeNode).find('.ant-tree-node-content-wrapper').at(0).simulate(action);
jest.runAllTimers();
expect(wrapper.render()).toMatchSnapshot();
});
@ -179,20 +159,12 @@ describe('Directory Tree', () => {
}),
);
wrapper
.find(TreeNode)
.find('.ant-tree-node-content-wrapper')
.at(0)
.simulate('click');
wrapper.find(TreeNode).find('.ant-tree-node-content-wrapper').at(0).simulate('click');
expect(onSelect.mock.calls[0][1].selected).toBeTruthy();
expect(onSelect.mock.calls[0][1].selectedNodes.length).toBe(1);
// Click twice should keep selected
wrapper
.find(TreeNode)
.find('.ant-tree-node-content-wrapper')
.at(0)
.simulate('click');
wrapper.find(TreeNode).find('.ant-tree-node-content-wrapper').at(0).simulate('click');
expect(onSelect.mock.calls[1][1].selected).toBeTruthy();
expect(onSelect.mock.calls[0][0]).toEqual(onSelect.mock.calls[1][0]);
expect(onSelect.mock.calls[1][1].selectedNodes.length).toBe(1);
@ -201,11 +173,7 @@ describe('Directory Tree', () => {
// Ref: https://github.com/facebook/react/blob/master/packages/react-dom/src/test-utils/ReactTestUtils.js#L360
nativeEventProto.ctrlKey = true;
wrapper
.find(TreeNode)
.find('.ant-tree-node-content-wrapper')
.at(1)
.simulate('click');
wrapper.find(TreeNode).find('.ant-tree-node-content-wrapper').at(1).simulate('click');
expect(wrapper.render()).toMatchSnapshot();
expect(onSelect.mock.calls[2][0].length).toBe(2);
expect(onSelect.mock.calls[2][1].selected).toBeTruthy();
@ -214,11 +182,7 @@ describe('Directory Tree', () => {
delete nativeEventProto.ctrlKey;
nativeEventProto.shiftKey = true;
wrapper
.find(TreeNode)
.find('.ant-tree-node-content-wrapper')
.at(4)
.simulate('click');
wrapper.find(TreeNode).find('.ant-tree-node-content-wrapper').at(4).simulate('click');
expect(wrapper.render()).toMatchSnapshot();
expect(onSelect.mock.calls[3][0].length).toBe(5);
expect(onSelect.mock.calls[3][1].selected).toBeTruthy();
@ -226,4 +190,11 @@ describe('Directory Tree', () => {
delete nativeEventProto.shiftKey;
});
it('onDoubleClick', () => {
const onDoubleClick = jest.fn();
const wrapper = mount(createTree({ onDoubleClick }));
wrapper.find(TreeNode).find('.ant-tree-node-content-wrapper').at(0).simulate('doubleclick');
expect(onDoubleClick).toBeCalled();
});
});

Loading…
Cancel
Save