index.tsx 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  1. /* eslint-disable max-lines-per-function */
  2. import React, { MouseEvent, KeyboardEvent } from 'react';
  3. import cls from 'classnames';
  4. import PropTypes from 'prop-types';
  5. import ConfigContext, { ContextValue } from '../configProvider/context';
  6. import TreeFoundation, { TreeAdapter } from '@douyinfe/semi-foundation/tree/foundation';
  7. import {
  8. convertDataToEntities,
  9. flattenTreeData,
  10. calcExpandedKeysForValues,
  11. calcMotionKeys,
  12. convertJsonToData,
  13. findKeysForValues,
  14. calcCheckedKeys,
  15. calcExpandedKeys,
  16. filterTreeData,
  17. normalizeValue,
  18. updateKeys,
  19. calcDisabledKeys
  20. } from '@douyinfe/semi-foundation/tree/treeUtil';
  21. import { cssClasses, strings } from '@douyinfe/semi-foundation/tree/constants';
  22. import BaseComponent from '../_base/baseComponent';
  23. import { isEmpty, isEqual, get, isFunction } from 'lodash';
  24. import { cloneDeep } from './treeUtil';
  25. import Input from '../input/index';
  26. import { FixedSizeList as VirtualList } from 'react-window';
  27. import AutoSizer from './autoSizer';
  28. import TreeContext from './treeContext';
  29. import TreeNode from './treeNode';
  30. import NodeList from './nodeList';
  31. import LocaleConsumer from '../locale/localeConsumer';
  32. import '@douyinfe/semi-foundation/tree/tree.scss';
  33. import { IconSearch } from '@douyinfe/semi-icons';
  34. import { Locale as LocaleObject } from '../locale/interface';
  35. import {
  36. TreeProps,
  37. TreeState,
  38. TreeNodeProps,
  39. TreeNodeData,
  40. FlattenNode,
  41. KeyEntity,
  42. OptionProps,
  43. ScrollData,
  44. } from './interface';
  45. import CheckboxGroup from '../checkbox/checkboxGroup';
  46. export * from './interface';
  47. export type { AutoSizerProps } from './autoSizer';
  48. const prefixcls = cssClasses.PREFIX;
  49. class Tree extends BaseComponent<TreeProps, TreeState> {
  50. static contextType = ConfigContext;
  51. static propTypes = {
  52. blockNode: PropTypes.bool,
  53. className: PropTypes.string,
  54. showClear: PropTypes.bool,
  55. defaultExpandAll: PropTypes.bool,
  56. defaultExpandedKeys: PropTypes.array,
  57. defaultValue: PropTypes.oneOfType([PropTypes.string, PropTypes.array]),
  58. directory: PropTypes.bool,
  59. disabled: PropTypes.bool,
  60. emptyContent: PropTypes.node,
  61. expandAll: PropTypes.bool,
  62. expandedKeys: PropTypes.array,
  63. filterTreeNode: PropTypes.oneOfType([PropTypes.func, PropTypes.bool]),
  64. icon: PropTypes.node,
  65. onChangeWithObject: PropTypes.bool,
  66. motion: PropTypes.bool,
  67. multiple: PropTypes.bool,
  68. onChange: PropTypes.func,
  69. onExpand: PropTypes.func,
  70. onSearch: PropTypes.func,
  71. onSelect: PropTypes.func,
  72. onContextMenu: PropTypes.func,
  73. onDoubleClick: PropTypes.func,
  74. searchClassName: PropTypes.string,
  75. searchPlaceholder: PropTypes.string,
  76. searchStyle: PropTypes.object,
  77. selectedKey: PropTypes.string,
  78. showFilteredOnly: PropTypes.bool,
  79. style: PropTypes.object,
  80. treeData: PropTypes.arrayOf(
  81. PropTypes.shape({
  82. key: PropTypes.string.isRequired,
  83. value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  84. label: PropTypes.any,
  85. isLeaf: PropTypes.bool,
  86. })
  87. ),
  88. treeDataSimpleJson: PropTypes.object,
  89. treeNodeFilterProp: PropTypes.string,
  90. value: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.array, PropTypes.object]),
  91. virtualize: PropTypes.object,
  92. autoExpandParent: PropTypes.bool,
  93. expandAction: PropTypes.oneOf(strings.EXPAND_ACTION),
  94. searchRender: PropTypes.oneOfType([PropTypes.func, PropTypes.bool]),
  95. renderLabel: PropTypes.func,
  96. renderFullLabel: PropTypes.func,
  97. leafOnly: PropTypes.bool,
  98. loadedKeys: PropTypes.array,
  99. loadData: PropTypes.func,
  100. onLoad: PropTypes.func,
  101. disableStrictly: PropTypes.bool,
  102. draggable: PropTypes.bool,
  103. autoExpandWhenDragEnter: PropTypes.bool,
  104. hideDraggingNode: PropTypes.bool,
  105. renderDraggingNode: PropTypes.func,
  106. onDragEnd: PropTypes.func,
  107. onDragEnter: PropTypes.func,
  108. onDragLeave: PropTypes.func,
  109. onDragOver: PropTypes.func,
  110. onDragStart: PropTypes.func,
  111. onDrop: PropTypes.func,
  112. labelEllipsis: PropTypes.bool,
  113. checkRelation: PropTypes.string,
  114. 'aria-label': PropTypes.string,
  115. preventScroll: PropTypes.bool,
  116. };
  117. static defaultProps = {
  118. showClear: true,
  119. disabled: false,
  120. blockNode: true,
  121. multiple: false,
  122. filterTreeNode: false,
  123. autoExpandParent: false,
  124. treeNodeFilterProp: 'label',
  125. defaultExpandAll: false,
  126. expandAll: false,
  127. onChangeWithObject: false,
  128. motion: true,
  129. leafOnly: false,
  130. showFilteredOnly: false,
  131. expandAction: false,
  132. disableStrictly: false,
  133. draggable: false,
  134. autoExpandWhenDragEnter: true,
  135. checkRelation: 'related',
  136. };
  137. static TreeNode: typeof TreeNode;
  138. inputRef: React.RefObject<typeof Input>;
  139. optionsRef: React.RefObject<any>;
  140. dragNode: any;
  141. onNodeClick: any;
  142. onMotionEnd: any;
  143. context: ContextValue;
  144. virtualizedListRef: React.RefObject<any>;
  145. constructor(props: TreeProps) {
  146. super(props);
  147. this.state = {
  148. inputValue: '',
  149. keyEntities: {},
  150. treeData: [],
  151. flattenNodes: [],
  152. selectedKeys: [],
  153. checkedKeys: new Set(),
  154. halfCheckedKeys: new Set(),
  155. realCheckedKeys: new Set([]),
  156. motionKeys: new Set([]),
  157. motionType: 'hide',
  158. expandedKeys: new Set(props.expandedKeys),
  159. filteredKeys: new Set(),
  160. filteredExpandedKeys: new Set(),
  161. filteredShownKeys: new Set(),
  162. prevProps: null,
  163. loadedKeys: new Set(),
  164. loadingKeys: new Set(),
  165. cachedFlattenNodes: undefined,
  166. cachedKeyValuePairs: {},
  167. disabledKeys: new Set(),
  168. dragging: false,
  169. dragNodesKeys: new Set(),
  170. dragOverNodeKey: null,
  171. dropPosition: null,
  172. };
  173. this.inputRef = React.createRef();
  174. this.optionsRef = React.createRef();
  175. this.foundation = new TreeFoundation(this.adapter);
  176. this.dragNode = null;
  177. this.virtualizedListRef = React.createRef();
  178. }
  179. /**
  180. * Process of getDerivedStateFromProps was inspired by rc-tree
  181. * https://github.com/react-component/tree
  182. */
  183. static getDerivedStateFromProps(props: TreeProps, prevState: TreeState) {
  184. const { prevProps } = prevState;
  185. let treeData;
  186. let keyEntities = prevState.keyEntities || {};
  187. let valueEntities = prevState.cachedKeyValuePairs || {};
  188. const isSeaching = Boolean(props.filterTreeNode && prevState.inputValue && prevState.inputValue.length);
  189. const newState: Partial<TreeState> = {
  190. prevProps: props,
  191. };
  192. const isExpandControlled = 'expandedKeys' in props;
  193. // Accept a props field as a parameter to determine whether to update the field
  194. const needUpdate = (name: string) => {
  195. const firstInProps = !prevProps && name in props;
  196. const nameHasChange = prevProps && !isEqual(prevProps[name], props[name]);
  197. return firstInProps || nameHasChange;
  198. };
  199. // Determine whether treeData has changed
  200. const needUpdateData = () => {
  201. const firstInProps = !prevProps && 'treeData' in props;
  202. const treeDataHasChange = prevProps && prevProps.treeData !== props.treeData;
  203. return firstInProps || treeDataHasChange;
  204. };
  205. // Update the data of tree in state
  206. if (needUpdate('treeData') || (props.draggable && needUpdateData())) {
  207. // eslint-disable-next-line prefer-destructuring
  208. treeData = props.treeData;
  209. newState.treeData = treeData;
  210. const entitiesMap = convertDataToEntities(treeData);
  211. newState.keyEntities = {
  212. ...entitiesMap.keyEntities,
  213. };
  214. keyEntities = newState.keyEntities;
  215. newState.cachedKeyValuePairs = { ...entitiesMap.valueEntities };
  216. valueEntities = newState.cachedKeyValuePairs;
  217. } else if (needUpdate('treeDataSimpleJson')) {
  218. // Convert treeDataSimpleJson to treeData
  219. treeData = convertJsonToData(props.treeDataSimpleJson);
  220. newState.treeData = treeData;
  221. const entitiesMap = convertDataToEntities(treeData);
  222. newState.keyEntities = {
  223. ...entitiesMap.keyEntities,
  224. };
  225. keyEntities = newState.keyEntities;
  226. newState.cachedKeyValuePairs = { ...entitiesMap.valueEntities };
  227. valueEntities = newState.cachedKeyValuePairs;
  228. }
  229. // If treeData keys changes, we won't show animation
  230. if (treeData && props.motion) {
  231. if (prevProps && props.motion) {
  232. newState.motionKeys = new Set([]);
  233. newState.motionType = null;
  234. }
  235. }
  236. const dataUpdated = needUpdate('treeDataSimpleJson') || needUpdate('treeData');
  237. const expandAllWhenDataChange = dataUpdated && props.expandAll;
  238. if (!isSeaching) {
  239. // Update expandedKeys
  240. if (needUpdate('expandedKeys') || (prevProps && needUpdate('autoExpandParent'))) {
  241. newState.expandedKeys = calcExpandedKeys(
  242. props.expandedKeys,
  243. keyEntities,
  244. props.autoExpandParent || !prevProps
  245. );
  246. // only show animation when treeData does not change
  247. if (prevProps && props.motion && !treeData) {
  248. const { motionKeys, motionType } = calcMotionKeys(
  249. prevState.expandedKeys,
  250. newState.expandedKeys,
  251. keyEntities
  252. );
  253. newState.motionKeys = new Set(motionKeys);
  254. newState.motionType = motionType;
  255. if (motionType === 'hide') {
  256. // cache flatten nodes: expandedKeys changed may not be triggered by interaction
  257. newState.cachedFlattenNodes = cloneDeep(prevState.flattenNodes);
  258. }
  259. }
  260. } else if ((!prevProps && (props.defaultExpandAll || props.expandAll)) || expandAllWhenDataChange) {
  261. newState.expandedKeys = new Set(Object.keys(keyEntities));
  262. } else if (!prevProps && props.defaultExpandedKeys) {
  263. newState.expandedKeys = calcExpandedKeys(props.defaultExpandedKeys, keyEntities);
  264. } else if (!prevProps && props.defaultValue) {
  265. newState.expandedKeys = calcExpandedKeysForValues(
  266. props.defaultValue,
  267. keyEntities,
  268. props.multiple,
  269. valueEntities
  270. );
  271. } else if (!prevProps && props.value) {
  272. newState.expandedKeys = calcExpandedKeysForValues(
  273. props.value,
  274. keyEntities,
  275. props.multiple,
  276. valueEntities
  277. );
  278. } else if ((!isExpandControlled && dataUpdated) && props.value) {
  279. // 当 treeData 已经设置具体的值,并且设置了 props.loadData ,则认为 treeData 的更新是因为 loadData 导致的
  280. // 如果是因为 loadData 导致 treeData改变, 此时在这里重新计算 key 会导致为未选中的展开项目被收起
  281. // 所以此时不需要重新计算 expandedKeys,因为在点击展开按钮时候已经把被展开的项添加到 expandedKeys 中
  282. // When treeData has a specific value and props.loadData is set, it is considered that the update of treeData is caused by loadData
  283. // If the treeData is changed because of loadData, recalculating the key here will cause the unselected expanded items to be collapsed
  284. // So there is no need to recalculate expandedKeys at this time, because the expanded item has been added to expandedKeys when the expand button is clicked
  285. if (!(prevState.treeData && prevState.treeData?.length > 0 && props.loadData)) {
  286. newState.expandedKeys = calcExpandedKeysForValues(
  287. props.value,
  288. keyEntities,
  289. props.multiple,
  290. valueEntities
  291. );
  292. }
  293. }
  294. if (!newState.expandedKeys) {
  295. delete newState.expandedKeys;
  296. }
  297. // Update flattenNodes
  298. if (treeData || newState.expandedKeys) {
  299. const flattenNodes = flattenTreeData(
  300. treeData || prevState.treeData,
  301. newState.expandedKeys || prevState.expandedKeys
  302. );
  303. newState.flattenNodes = flattenNodes;
  304. }
  305. } else {
  306. let filteredState;
  307. // treeData changed while searching
  308. if (treeData) {
  309. // Get filter data
  310. filteredState = filterTreeData({
  311. treeData,
  312. inputValue: prevState.inputValue,
  313. filterTreeNode: props.filterTreeNode,
  314. filterProps: props.treeNodeFilterProp,
  315. showFilteredOnly: props.showFilteredOnly,
  316. keyEntities: newState.keyEntities,
  317. prevExpandedKeys: [...prevState.filteredExpandedKeys],
  318. });
  319. newState.flattenNodes = filteredState.flattenNodes;
  320. newState.motionKeys = new Set([]);
  321. newState.filteredKeys = filteredState.filteredKeys;
  322. newState.filteredShownKeys = filteredState.filteredShownKeys;
  323. newState.filteredExpandedKeys = filteredState.filteredExpandedKeys;
  324. }
  325. // expandedKeys changed while searching
  326. if (props.expandedKeys) {
  327. newState.filteredExpandedKeys = calcExpandedKeys(
  328. props.expandedKeys,
  329. keyEntities,
  330. props.autoExpandParent || !prevProps
  331. );
  332. if (prevProps && props.motion) {
  333. const prevKeys = prevState ? prevState.filteredExpandedKeys : new Set([]);
  334. // only show animation when treeData does not change
  335. if (!treeData) {
  336. const motionResult = calcMotionKeys(
  337. prevKeys,
  338. newState.filteredExpandedKeys,
  339. keyEntities
  340. );
  341. let { motionKeys } = motionResult;
  342. const { motionType } = motionResult;
  343. if (props.showFilteredOnly) {
  344. motionKeys = motionKeys.filter(key => prevState.filteredShownKeys.has(key));
  345. }
  346. if (motionType === 'hide') {
  347. // cache flatten nodes: expandedKeys changed may not be triggered by interaction
  348. newState.cachedFlattenNodes = cloneDeep(prevState.flattenNodes);
  349. }
  350. newState.motionKeys = new Set(motionKeys);
  351. newState.motionType = motionType;
  352. }
  353. }
  354. newState.flattenNodes = flattenTreeData(
  355. treeData || prevState.treeData,
  356. newState.filteredExpandedKeys || prevState.filteredExpandedKeys,
  357. props.showFilteredOnly && prevState.filteredShownKeys
  358. );
  359. }
  360. }
  361. // Handle single selection and multiple selection in controlled mode
  362. const withObject = props.onChangeWithObject;
  363. const isMultiple = props.multiple;
  364. if (!isMultiple) {
  365. // When getting single selection, the selected node
  366. if (needUpdate('value')) {
  367. newState.selectedKeys = findKeysForValues(
  368. // In both cases whether withObject is turned on, the value is standardized to string
  369. normalizeValue(props.value, withObject),
  370. valueEntities,
  371. isMultiple
  372. );
  373. } else if (!prevProps && props.defaultValue) {
  374. newState.selectedKeys = findKeysForValues(
  375. normalizeValue(props.defaultValue, withObject),
  376. valueEntities,
  377. isMultiple
  378. );
  379. } else if (treeData) {
  380. // If `treeData` changed, we also need check it
  381. if (props.value) {
  382. newState.selectedKeys = findKeysForValues(
  383. normalizeValue(props.value, withObject) || '',
  384. valueEntities,
  385. isMultiple
  386. );
  387. }
  388. }
  389. } else {
  390. let checkedKeyValues;
  391. // Get the selected node during multiple selection
  392. if (needUpdate('value')) {
  393. checkedKeyValues = findKeysForValues(
  394. normalizeValue(props.value, withObject),
  395. valueEntities,
  396. isMultiple
  397. );
  398. } else if (!prevProps && props.defaultValue) {
  399. checkedKeyValues = findKeysForValues(
  400. normalizeValue(props.defaultValue, withObject),
  401. valueEntities,
  402. isMultiple
  403. );
  404. } else if (treeData) {
  405. // If `treeData` changed, we also need check it
  406. if (props.value) {
  407. checkedKeyValues = findKeysForValues(
  408. normalizeValue(props.value, withObject) || [],
  409. valueEntities,
  410. isMultiple
  411. );
  412. } else {
  413. checkedKeyValues = updateKeys(prevState.checkedKeys, keyEntities);
  414. }
  415. }
  416. if (checkedKeyValues) {
  417. if (props.checkRelation === 'unRelated') {
  418. newState.realCheckedKeys = new Set(checkedKeyValues);
  419. } else if (props.checkRelation === 'related') {
  420. const { checkedKeys, halfCheckedKeys } = calcCheckedKeys(checkedKeyValues, keyEntities);
  421. newState.checkedKeys = checkedKeys;
  422. newState.halfCheckedKeys = halfCheckedKeys;
  423. }
  424. }
  425. }
  426. // update loadedKeys
  427. if (needUpdate('loadedKeys')) {
  428. newState.loadedKeys = new Set(props.loadedKeys);
  429. }
  430. // update disableStrictly
  431. if (treeData && props.disableStrictly && props.checkRelation === 'related') {
  432. newState.disabledKeys = calcDisabledKeys(keyEntities);
  433. }
  434. return newState;
  435. }
  436. get adapter(): TreeAdapter {
  437. const filterAdapter: Pick<TreeAdapter, 'updateInputValue' | 'focusInput'> = {
  438. updateInputValue: value => {
  439. this.setState({ inputValue: value });
  440. },
  441. focusInput: () => {
  442. const { preventScroll } = this.props;
  443. if (this.inputRef && this.inputRef.current) {
  444. (this.inputRef.current as any).focus({ preventScroll });
  445. }
  446. },
  447. };
  448. return {
  449. ...super.adapter,
  450. ...filterAdapter,
  451. updateState: states => {
  452. this.setState({ ...states } as TreeState);
  453. },
  454. notifyExpand: (expandedKeys, { expanded: bool, node }) => {
  455. this.props.onExpand && this.props.onExpand([...expandedKeys], { expanded: bool, node });
  456. if (bool && this.props.loadData) {
  457. this.onNodeLoad(node);
  458. }
  459. },
  460. notifySelect: (selectKey, bool, node) => {
  461. this.props.onSelect && this.props.onSelect(selectKey, bool, node);
  462. },
  463. notifyChange: value => {
  464. this.props.onChange && this.props.onChange(value);
  465. },
  466. notifySearch: input => {
  467. this.props.onSearch && this.props.onSearch(input);
  468. },
  469. notifyRightClick: (e, node) => {
  470. this.props.onContextMenu && this.props.onContextMenu(e, node);
  471. },
  472. notifyDoubleClick: (e, node) => {
  473. this.props.onDoubleClick && this.props.onDoubleClick(e, node);
  474. },
  475. cacheFlattenNodes: bool => {
  476. this.setState({ cachedFlattenNodes: bool ? cloneDeep(this.state.flattenNodes) : undefined });
  477. },
  478. setDragNode: treeNode => {
  479. this.dragNode = treeNode;
  480. },
  481. };
  482. }
  483. search = (value: string) => {
  484. this.foundation.handleInputChange(value);
  485. };
  486. scrollTo = (scrollData: ScrollData) => {
  487. const { key, align = 'center' } = scrollData;
  488. const { flattenNodes } = this.state;
  489. if (key) {
  490. const index = flattenNodes?.findIndex((node) => {
  491. return node.key === key;
  492. });
  493. index >= 0 && (this.virtualizedListRef.current as any)?.scrollToItem(index, align);
  494. }
  495. }
  496. renderInput() {
  497. const {
  498. searchClassName,
  499. searchStyle,
  500. searchRender,
  501. searchPlaceholder,
  502. showClear
  503. } = this.props;
  504. const inputcls = cls(`${prefixcls}-input`);
  505. const { inputValue } = this.state;
  506. const inputProps = {
  507. value: inputValue,
  508. className: inputcls,
  509. onChange: (value: string) => this.search(value),
  510. prefix: <IconSearch />,
  511. showClear,
  512. placeholder: searchPlaceholder,
  513. };
  514. const wrapperCls = cls(`${prefixcls}-search-wrapper`, searchClassName);
  515. return (
  516. <div className={wrapperCls} style={searchStyle}>
  517. <LocaleConsumer componentName="Tree">
  518. {(locale: LocaleObject) => {
  519. inputProps.placeholder = searchPlaceholder || get(locale, 'searchPlaceholder');
  520. if (isFunction(searchRender)) {
  521. return searchRender({ ...inputProps });
  522. }
  523. if (searchRender === false) {
  524. return null;
  525. }
  526. return (
  527. <Input
  528. aria-label='Filter Tree'
  529. ref={this.inputRef as any}
  530. {...inputProps}
  531. />
  532. );
  533. }}
  534. </LocaleConsumer>
  535. </div>
  536. );
  537. }
  538. renderEmpty = () => {
  539. const { emptyContent } = this.props;
  540. if (emptyContent) {
  541. return <TreeNode empty emptyContent={this.props.emptyContent} />;
  542. } else {
  543. return (
  544. <LocaleConsumer componentName="Tree">
  545. {(locale: LocaleObject) => <TreeNode empty emptyContent={get(locale, 'emptyText')} />}
  546. </LocaleConsumer>
  547. );
  548. }
  549. };
  550. onNodeSelect = (e: MouseEvent | KeyboardEvent, treeNode: TreeNodeProps) => {
  551. this.foundation.handleNodeSelect(e, treeNode);
  552. };
  553. onNodeLoad = (data: TreeNodeData) => (
  554. new Promise(resolve => {
  555. // We need to get the latest state of loading/loaded keys
  556. this.setState(({ loadedKeys = new Set([]), loadingKeys = new Set([]) }) => (
  557. this.foundation.handleNodeLoad(loadedKeys, loadingKeys, data, resolve)
  558. ));
  559. })
  560. );
  561. onNodeCheck = (e: MouseEvent | KeyboardEvent, treeNode: TreeNodeProps) => {
  562. this.foundation.handleNodeSelect(e, treeNode);
  563. };
  564. onNodeExpand = (e: MouseEvent | KeyboardEvent, treeNode: TreeNodeProps) => {
  565. this.foundation.handleNodeExpand(e, treeNode);
  566. };
  567. onNodeRightClick = (e: MouseEvent, treeNode: TreeNodeProps) => {
  568. this.foundation.handleNodeRightClick(e, treeNode);
  569. };
  570. onNodeDoubleClick = (e: MouseEvent, treeNode: TreeNodeProps) => {
  571. this.foundation.handleNodeDoubleClick(e, treeNode);
  572. };
  573. onNodeDragStart = (e: React.DragEvent<HTMLLIElement>, treeNode: TreeNodeProps) => {
  574. this.foundation.handleNodeDragStart(e, treeNode);
  575. };
  576. onNodeDragEnter = (e: React.DragEvent<HTMLLIElement>, treeNode: TreeNodeProps) => {
  577. this.foundation.handleNodeDragEnter(e, treeNode, this.dragNode);
  578. };
  579. onNodeDragOver = (e: React.DragEvent<HTMLLIElement>, treeNode: TreeNodeProps) => {
  580. this.foundation.handleNodeDragOver(e, treeNode, this.dragNode);
  581. };
  582. onNodeDragLeave = (e: React.DragEvent<HTMLLIElement>, treeNode: TreeNodeProps) => {
  583. this.foundation.handleNodeDragLeave(e, treeNode);
  584. };
  585. onNodeDragEnd = (e: React.DragEvent<HTMLLIElement>, treeNode: TreeNodeProps) => {
  586. this.foundation.handleNodeDragEnd(e, treeNode);
  587. };
  588. onNodeDrop = (e: React.DragEvent<HTMLLIElement>, treeNode: TreeNodeProps) => {
  589. this.foundation.handleNodeDrop(e, treeNode, this.dragNode);
  590. };
  591. getTreeNodeRequiredProps = () => {
  592. const { expandedKeys, selectedKeys, checkedKeys, halfCheckedKeys, keyEntities, filteredKeys } = this.state;
  593. return {
  594. expandedKeys: expandedKeys || new Set(),
  595. selectedKeys: selectedKeys || [],
  596. checkedKeys: checkedKeys || new Set(),
  597. halfCheckedKeys: halfCheckedKeys || new Set(),
  598. filteredKeys: filteredKeys || new Set(),
  599. keyEntities,
  600. };
  601. };
  602. getTreeNodeKey = (treeNode: TreeNodeData) => {
  603. const { data } = treeNode;
  604. const { key } = data;
  605. return key;
  606. };
  607. renderTreeNode = (treeNode: FlattenNode, ind?: number, style?: React.CSSProperties) => {
  608. const { data } = treeNode;
  609. const { key } = data;
  610. const treeNodeProps = this.foundation.getTreeNodeProps(key);
  611. if (!treeNodeProps) {
  612. return null;
  613. }
  614. return <TreeNode {...treeNodeProps} {...data} key={key} data={data} style={isEmpty(style) ? {} : style} />;
  615. };
  616. itemKey = (index: number, data: KeyEntity) => {
  617. // Find the item at the specified index.
  618. const item = data[index];
  619. // Return a value that uniquely identifies this item.
  620. return item.key;
  621. };
  622. renderNodeList() {
  623. const { flattenNodes, cachedFlattenNodes, motionKeys, motionType } = this.state;
  624. const { virtualize, motion } = this.props;
  625. const { direction } = this.context;
  626. if (isEmpty(flattenNodes)) {
  627. return undefined;
  628. }
  629. if (!virtualize || isEmpty(virtualize)) {
  630. return (
  631. <NodeList
  632. flattenNodes={flattenNodes}
  633. flattenList={cachedFlattenNodes}
  634. motionKeys={motion ? motionKeys : new Set([])}
  635. motionType={motionType}
  636. onMotionEnd={this.onMotionEnd}
  637. renderTreeNode={this.renderTreeNode}
  638. />
  639. );
  640. }
  641. const option = ({ index, style, data }: OptionProps) => (
  642. this.renderTreeNode(data[index], index, style)
  643. );
  644. return (
  645. <AutoSizer defaultHeight={virtualize.height} defaultWidth={virtualize.width}>
  646. {({ height, width }: { width: string | number; height: string | number }) => (
  647. <VirtualList
  648. ref={this.virtualizedListRef}
  649. itemCount={flattenNodes.length}
  650. itemSize={virtualize.itemSize}
  651. height={height}
  652. width={width}
  653. itemKey={this.itemKey}
  654. itemData={flattenNodes as any}
  655. className={`${prefixcls}-virtual-list`}
  656. style={{ direction }}
  657. >
  658. {option}
  659. </VirtualList>
  660. )}
  661. </AutoSizer>
  662. );
  663. }
  664. render() {
  665. const {
  666. keyEntities,
  667. motionKeys,
  668. motionType,
  669. inputValue,
  670. filteredKeys,
  671. dragOverNodeKey,
  672. dropPosition,
  673. checkedKeys,
  674. realCheckedKeys,
  675. } = this.state;
  676. const {
  677. blockNode,
  678. className,
  679. style,
  680. filterTreeNode,
  681. disabled,
  682. icon,
  683. directory,
  684. multiple,
  685. showFilteredOnly,
  686. motion,
  687. expandAction,
  688. loadData,
  689. renderLabel,
  690. draggable,
  691. renderFullLabel,
  692. labelEllipsis,
  693. virtualize,
  694. checkRelation,
  695. ...rest
  696. } = this.props;
  697. const wrapperCls = cls(`${prefixcls}-wrapper`, className);
  698. const listCls = cls(`${prefixcls}-option-list`, {
  699. [`${prefixcls}-option-list-block`]: blockNode,
  700. });
  701. const searchNoRes = Boolean(inputValue) && !filteredKeys.size;
  702. const noData = isEmpty(keyEntities) || (showFilteredOnly && searchNoRes);
  703. const ariaAttr = {
  704. role: noData ? 'none' : 'tree'
  705. };
  706. if (ariaAttr.role === 'tree') {
  707. ariaAttr['aria-multiselectable'] = multiple ? true : false;
  708. }
  709. return (
  710. <TreeContext.Provider
  711. value={{
  712. treeDisabled: disabled,
  713. treeIcon: icon,
  714. motion,
  715. motionKeys,
  716. motionType,
  717. filterTreeNode,
  718. keyEntities,
  719. onNodeClick: this.onNodeClick,
  720. onNodeExpand: this.onNodeExpand,
  721. onNodeSelect: this.onNodeSelect,
  722. onNodeCheck: this.onNodeCheck,
  723. onNodeRightClick: this.onNodeRightClick,
  724. onNodeDoubleClick: this.onNodeDoubleClick,
  725. renderTreeNode: this.renderTreeNode,
  726. onNodeDragStart: this.onNodeDragStart,
  727. onNodeDragEnter: this.onNodeDragEnter,
  728. onNodeDragOver: this.onNodeDragOver,
  729. onNodeDragLeave: this.onNodeDragLeave,
  730. onNodeDragEnd: this.onNodeDragEnd,
  731. onNodeDrop: this.onNodeDrop,
  732. expandAction,
  733. directory,
  734. multiple,
  735. showFilteredOnly,
  736. isSearching: Boolean(inputValue),
  737. loadData,
  738. onNodeLoad: this.onNodeLoad,
  739. renderLabel,
  740. draggable,
  741. renderFullLabel,
  742. dragOverNodeKey,
  743. dropPosition,
  744. labelEllipsis: typeof labelEllipsis === 'undefined' ? virtualize : labelEllipsis,
  745. }}
  746. >
  747. <div aria-label={this.props['aria-label']} className={wrapperCls} style={style} {...this.getDataAttr(rest)}>
  748. {filterTreeNode ? this.renderInput() : null}
  749. <div className={listCls} {...ariaAttr}>
  750. {noData ? this.renderEmpty() : (multiple ?
  751. (<CheckboxGroup value={Array.from(checkRelation === 'related' ? checkedKeys : realCheckedKeys)}>
  752. {this.renderNodeList()}
  753. </CheckboxGroup>) :
  754. this.renderNodeList()
  755. )}
  756. </div>
  757. </div>
  758. </TreeContext.Provider>
  759. );
  760. }
  761. }
  762. Tree.TreeNode = TreeNode;
  763. export default Tree;