Tree

  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import classNames from 'classnames';
  4. import warning from 'warning';
  5. import toArray from 'rc-util/lib/Children/toArray';
  6. import { polyfill } from 'react-lifecycles-compat';
  7. import { treeContextTypes } from './contextTypes';
  8. import {
  9. convertTreeToEntities,
  10. convertDataToTree,
  11. getDataAndAria,
  12. getPosition,
  13. getDragNodesKeys,
  14. parseCheckedKeys,
  15. conductExpandParent,
  16. calcSelectedKeys,
  17. calcDropPosition,
  18. arrAdd,
  19. arrDel,
  20. posToArr,
  21. mapChildren,
  22. conductCheck,
  23. warnOnlyTreeNode,
  24. } from './util';
  25. class Tree extends React.Component {
  26. static propTypes = {
  27. prefixCls: PropTypes.string,
  28. className: PropTypes.string,
  29. style: PropTypes.object,
  30. tabIndex: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  31. children: PropTypes.any,
  32. treeData: PropTypes.array, // Generate treeNode by children
  33. showLine: PropTypes.bool,
  34. showIcon: PropTypes.bool,
  35. icon: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),
  36. focusable: PropTypes.bool,
  37. selectable: PropTypes.bool,
  38. disabled: PropTypes.bool,
  39. multiple: PropTypes.bool,
  40. checkable: PropTypes.oneOfType([PropTypes.bool, PropTypes.node]),
  41. checkStrictly: PropTypes.bool,
  42. draggable: PropTypes.bool,
  43. defaultExpandParent: PropTypes.bool,
  44. autoExpandParent: PropTypes.bool,
  45. defaultExpandAll: PropTypes.bool,
  46. defaultExpandedKeys: PropTypes.arrayOf(PropTypes.string),
  47. expandedKeys: PropTypes.arrayOf(PropTypes.string),
  48. defaultCheckedKeys: PropTypes.arrayOf(PropTypes.string),
  49. checkedKeys: PropTypes.oneOfType([
  50. PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.string, PropTypes.number])),
  51. PropTypes.object,
  52. ]),
  53. defaultSelectedKeys: PropTypes.arrayOf(PropTypes.string),
  54. selectedKeys: PropTypes.arrayOf(PropTypes.string),
  55. onClick: PropTypes.func,
  56. onDoubleClick: PropTypes.func,
  57. onExpand: PropTypes.func,
  58. onCheck: PropTypes.func,
  59. onSelect: PropTypes.func,
  60. onLoad: PropTypes.func,
  61. loadData: PropTypes.func,
  62. loadedKeys: PropTypes.arrayOf(PropTypes.string),
  63. onMouseEnter: PropTypes.func,
  64. onMouseLeave: PropTypes.func,
  65. onRightClick: PropTypes.func,
  66. onDragStart: PropTypes.func,
  67. onDragEnter: PropTypes.func,
  68. onDragOver: PropTypes.func,
  69. onDragLeave: PropTypes.func,
  70. onDragEnd: PropTypes.func,
  71. onDrop: PropTypes.func,
  72. filterTreeNode: PropTypes.func,
  73. motion: PropTypes.object,
  74. switcherIcon: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),
  75. };
  76. static childContextTypes = treeContextTypes;
  77. static defaultProps = {
  78. prefixCls: 'rc-tree',
  79. showLine: false,
  80. showIcon: true,
  81. selectable: true,
  82. multiple: false,
  83. checkable: false,
  84. disabled: false,
  85. checkStrictly: false,
  86. draggable: false,
  87. defaultExpandParent: true,
  88. autoExpandParent: false,
  89. defaultExpandAll: false,
  90. defaultExpandedKeys: [],
  91. defaultCheckedKeys: [],
  92. defaultSelectedKeys: [],
  93. };
  94. constructor(props) {
  95. super(props);
  96. this.state = {
  97. // TODO: Remove this eslint
  98. posEntities: {}, // eslint-disable-line react/no-unused-state
  99. keyEntities: {},
  100. selectedKeys: [],
  101. checkedKeys: [],
  102. halfCheckedKeys: [],
  103. loadedKeys: [],
  104. loadingKeys: [],
  105. treeNode: [],
  106. };
  107. // Internal usage for `rc-tree-select`, we don't promise it will not change.
  108. this.domTreeNodes = {};
  109. }
  110. getChildContext() {
  111. const {
  112. prefixCls,
  113. selectable,
  114. showIcon,
  115. icon,
  116. draggable,
  117. checkable,
  118. checkStrictly,
  119. disabled,
  120. loadData,
  121. filterTreeNode,
  122. motion,
  123. switcherIcon,
  124. } = this.props;
  125. return {
  126. rcTree: {
  127. // root: this,
  128. prefixCls,
  129. selectable,
  130. showIcon,
  131. icon,
  132. switcherIcon,
  133. draggable,
  134. checkable,
  135. checkStrictly,
  136. disabled,
  137. motion,
  138. loadData,
  139. filterTreeNode,
  140. renderTreeNode: this.renderTreeNode,
  141. isKeyChecked: this.isKeyChecked,
  142. onNodeClick: this.onNodeClick,
  143. onNodeDoubleClick: this.onNodeDoubleClick,
  144. onNodeExpand: this.onNodeExpand,
  145. onNodeSelect: this.onNodeSelect,
  146. onNodeCheck: this.onNodeCheck,
  147. onNodeLoad: this.onNodeLoad,
  148. onNodeMouseEnter: this.onNodeMouseEnter,
  149. onNodeMouseLeave: this.onNodeMouseLeave,
  150. onNodeContextMenu: this.onNodeContextMenu,
  151. onNodeDragStart: this.onNodeDragStart,
  152. onNodeDragEnter: this.onNodeDragEnter,
  153. onNodeDragOver: this.onNodeDragOver,
  154. onNodeDragLeave: this.onNodeDragLeave,
  155. onNodeDragEnd: this.onNodeDragEnd,
  156. onNodeDrop: this.onNodeDrop,
  157. registerTreeNode: this.registerTreeNode,
  158. },
  159. };
  160. }
  161. static getDerivedStateFromProps(props, prevState) {
  162. const { prevProps } = prevState;
  163. const newState = {
  164. prevProps: props,
  165. };
  166. function needSync(name) {
  167. return (!prevProps && name in props) || (prevProps && prevProps[name] !== props[name]);
  168. }
  169. // ================== Tree Node ==================
  170. let treeNode = null;
  171. // Check if `treeData` or `children` changed and save into the state.
  172. if (needSync('treeData')) {
  173. treeNode = convertDataToTree(props.treeData);
  174. } else if (needSync('children')) {
  175. treeNode = toArray(props.children);
  176. }
  177. // Tree support filter function which will break the tree structure in the vdm.
  178. // We cache the treeNodes in state so that we can return the treeNode in event trigger.
  179. if (treeNode) {
  180. newState.treeNode = treeNode;
  181. // Calculate the entities data for quick match
  182. const entitiesMap = convertTreeToEntities(treeNode);
  183. newState.posEntities = entitiesMap.posEntities;
  184. newState.keyEntities = entitiesMap.keyEntities;
  185. }
  186. const keyEntities = newState.keyEntities || prevState.keyEntities;
  187. // ================ expandedKeys =================
  188. if (needSync('expandedKeys') || (prevProps && needSync('autoExpandParent'))) {
  189. newState.expandedKeys =
  190. props.autoExpandParent || (!prevProps && props.defaultExpandParent)
  191. ? conductExpandParent(props.expandedKeys, keyEntities)
  192. : props.expandedKeys;
  193. } else if (!prevProps && props.defaultExpandAll) {
  194. newState.expandedKeys = Object.keys(keyEntities);
  195. } else if (!prevProps && props.defaultExpandedKeys) {
  196. newState.expandedKeys =
  197. props.autoExpandParent || props.defaultExpandParent
  198. ? conductExpandParent(props.defaultExpandedKeys, keyEntities)
  199. : props.defaultExpandedKeys;
  200. }
  201. // ================ selectedKeys =================
  202. if (props.selectable) {
  203. if (needSync('selectedKeys')) {
  204. newState.selectedKeys = calcSelectedKeys(props.selectedKeys, props);
  205. } else if (!prevProps && props.defaultSelectedKeys) {
  206. newState.selectedKeys = calcSelectedKeys(props.defaultSelectedKeys, props);
  207. }
  208. }
  209. // ================= checkedKeys =================
  210. if (props.checkable) {
  211. let checkedKeyEntity;
  212. if (needSync('checkedKeys')) {
  213. checkedKeyEntity = parseCheckedKeys(props.checkedKeys) || {};
  214. } else if (!prevProps && props.defaultCheckedKeys) {
  215. checkedKeyEntity = parseCheckedKeys(props.defaultCheckedKeys) || {};
  216. } else if (treeNode) {
  217. // If treeNode changed, we also need check it
  218. checkedKeyEntity = parseCheckedKeys(props.checkedKeys) || {
  219. checkedKeys: prevState.checkedKeys,
  220. halfCheckedKeys: prevState.halfCheckedKeys,
  221. };
  222. }
  223. if (checkedKeyEntity) {
  224. let { checkedKeys = [], halfCheckedKeys = [] } = checkedKeyEntity;
  225. if (!props.checkStrictly) {
  226. const conductKeys = conductCheck(checkedKeys, true, keyEntities);
  227. checkedKeys = conductKeys.checkedKeys;
  228. halfCheckedKeys = conductKeys.halfCheckedKeys;
  229. }
  230. newState.checkedKeys = checkedKeys;
  231. newState.halfCheckedKeys = halfCheckedKeys;
  232. }
  233. }
  234. // ================= loadedKeys ==================
  235. if (needSync('loadedKeys')) {
  236. newState.loadedKeys = props.loadedKeys;
  237. }
  238. return newState;
  239. }
  240. onNodeDragStart = (event, node) => {
  241. const { expandedKeys } = this.state;
  242. const { onDragStart } = this.props;
  243. const { eventKey, children } = node.props;
  244. this.dragNode = node;
  245. this.setState({
  246. dragNodesKeys: getDragNodesKeys(children, node),
  247. expandedKeys: arrDel(expandedKeys, eventKey),
  248. });
  249. if (onDragStart) {
  250. onDragStart({ event, node });
  251. }
  252. };
  253. /**
  254. * [Legacy] Select handler is less small than node,
  255. * so that this will trigger when drag enter node or select handler.
  256. * This is a little tricky if customize css without padding.
  257. * Better for use mouse move event to refresh drag state.
  258. * But let's just keep it to avoid event trigger logic change.
  259. */
  260. onNodeDragEnter = (event, node) => {
  261. const { expandedKeys } = this.state;
  262. const { onDragEnter } = this.props;
  263. const { pos, eventKey } = node.props;
  264. if (!this.dragNode) return;
  265. const dropPosition = calcDropPosition(event, node);
  266. // Skip if drag node is self
  267. if (this.dragNode.props.eventKey === eventKey && dropPosition === 0) {
  268. this.setState({
  269. dragOverNodeKey: '',
  270. dropPosition: null,
  271. });
  272. return;
  273. }
  274. // Ref: https://github.com/react-component/tree/issues/132
  275. // Add timeout to let onDragLevel fire before onDragEnter,
  276. // so that we can clean drag props for onDragLeave node.
  277. // Macro task for this:
  278. // https://html.spec.whatwg.org/multipage/webappapis.html#clean-up-after-running-script
  279. setTimeout(() => {
  280. // Update drag over node
  281. this.setState({
  282. dragOverNodeKey: eventKey,
  283. dropPosition,
  284. });
  285. // Side effect for delay drag
  286. if (!this.delayedDragEnterLogic) {
  287. this.delayedDragEnterLogic = {};
  288. }
  289. Object.keys(this.delayedDragEnterLogic).forEach(key => {
  290. clearTimeout(this.delayedDragEnterLogic[key]);
  291. });
  292. this.delayedDragEnterLogic[pos] = setTimeout(() => {
  293. const newExpandedKeys = arrAdd(expandedKeys, eventKey);
  294. if (!('expandedKeys' in this.props)) {
  295. this.setState({
  296. expandedKeys: newExpandedKeys,
  297. });
  298. }
  299. if (onDragEnter) {
  300. onDragEnter({ event, node, expandedKeys: newExpandedKeys });
  301. }
  302. }, 400);
  303. }, 0);
  304. };
  305. onNodeDragOver = (event, node) => {
  306. const { onDragOver } = this.props;
  307. const { eventKey } = node.props;
  308. // Update drag position
  309. if (this.dragNode && eventKey === this.state.dragOverNodeKey) {
  310. const dropPosition = calcDropPosition(event, node);
  311. if (dropPosition === this.state.dropPosition) return;
  312. this.setState({
  313. dropPosition,
  314. });
  315. }
  316. if (onDragOver) {
  317. onDragOver({ event, node });
  318. }
  319. };
  320. onNodeDragLeave = (event, node) => {
  321. const { onDragLeave } = this.props;
  322. this.setState({
  323. dragOverNodeKey: '',
  324. });
  325. if (onDragLeave) {
  326. onDragLeave({ event, node });
  327. }
  328. };
  329. onNodeDragEnd = (event, node) => {
  330. const { onDragEnd } = this.props;
  331. this.setState({
  332. dragOverNodeKey: '',
  333. });
  334. if (onDragEnd) {
  335. onDragEnd({ event, node });
  336. }
  337. this.dragNode = null;
  338. };
  339. onNodeDrop = (event, node) => {
  340. const { dragNodesKeys = [], dropPosition } = this.state;
  341. const { onDrop } = this.props;
  342. const { eventKey, pos } = node.props;
  343. this.setState({
  344. dragOverNodeKey: '',
  345. });
  346. if (dragNodesKeys.indexOf(eventKey) !== -1) {
  347. warning(false, "Can not drop to dragNode(include it's children node)");
  348. return;
  349. }
  350. const posArr = posToArr(pos);
  351. const dropResult = {
  352. event,
  353. node,
  354. dragNode: this.dragNode,
  355. dragNodesKeys: dragNodesKeys.slice(),
  356. dropPosition: dropPosition + Number(posArr[posArr.length - 1]),
  357. };
  358. if (dropPosition !== 0) {
  359. dropResult.dropToGap = true;
  360. }
  361. if (onDrop) {
  362. onDrop(dropResult);
  363. }
  364. this.dragNode = null;
  365. };
  366. onNodeClick = (e, treeNode) => {
  367. const { onClick } = this.props;
  368. if (onClick) {
  369. onClick(e, treeNode);
  370. }
  371. };
  372. onNodeDoubleClick = (e, treeNode) => {
  373. const { onDoubleClick } = this.props;
  374. if (onDoubleClick) {
  375. onDoubleClick(e, treeNode);
  376. }
  377. };
  378. onNodeSelect = (e, treeNode) => {
  379. let { selectedKeys } = this.state;
  380. const { keyEntities } = this.state;
  381. const { onSelect, multiple } = this.props;
  382. const { selected, eventKey } = treeNode.props;
  383. const targetSelected = !selected;
  384. // Update selected keys
  385. if (!targetSelected) {
  386. selectedKeys = arrDel(selectedKeys, eventKey);
  387. } else if (!multiple) {
  388. selectedKeys = [eventKey];
  389. } else {
  390. selectedKeys = arrAdd(selectedKeys, eventKey);
  391. }
  392. // [Legacy] Not found related usage in doc or upper libs
  393. const selectedNodes = selectedKeys
  394. .map(key => {
  395. const entity = keyEntities[key];
  396. if (!entity) return null;
  397. return entity.node;
  398. })
  399. .filter(node => node);
  400. this.setUncontrolledState({ selectedKeys });
  401. if (onSelect) {
  402. const eventObj = {
  403. event: 'select',
  404. selected: targetSelected,
  405. node: treeNode,
  406. selectedNodes,
  407. nativeEvent: e.nativeEvent,
  408. };
  409. onSelect(selectedKeys, eventObj);
  410. }
  411. };
  412. onNodeCheck = (e, treeNode, checked) => {
  413. const {
  414. keyEntities,
  415. checkedKeys: oriCheckedKeys,
  416. halfCheckedKeys: oriHalfCheckedKeys,
  417. } = this.state;
  418. const { checkStrictly, onCheck } = this.props;
  419. const {
  420. props: { eventKey },
  421. } = treeNode;
  422. // Prepare trigger arguments
  423. let checkedObj;
  424. const eventObj = {
  425. event: 'check',
  426. node: treeNode,
  427. checked,
  428. nativeEvent: e.nativeEvent,
  429. };
  430. if (checkStrictly) {
  431. const checkedKeys = checked
  432. ? arrAdd(oriCheckedKeys, eventKey)
  433. : arrDel(oriCheckedKeys, eventKey);
  434. const halfCheckedKeys = arrDel(oriHalfCheckedKeys, eventKey);
  435. checkedObj = { checked: checkedKeys, halfChecked: halfCheckedKeys };
  436. eventObj.checkedNodes = checkedKeys
  437. .map(key => keyEntities[key])
  438. .filter(entity => entity)
  439. .map(entity => entity.node);
  440. this.setUncontrolledState({ checkedKeys });
  441. } else {
  442. const { checkedKeys, halfCheckedKeys } = conductCheck([eventKey], checked, keyEntities, {
  443. checkedKeys: oriCheckedKeys,
  444. halfCheckedKeys: oriHalfCheckedKeys,
  445. });
  446. checkedObj = checkedKeys;
  447. // [Legacy] This is used for `rc-tree-select`
  448. eventObj.checkedNodes = [];
  449. eventObj.checkedNodesPositions = [];
  450. eventObj.halfCheckedKeys = halfCheckedKeys;
  451. checkedKeys.forEach(key => {
  452. const entity = keyEntities[key];
  453. if (!entity) return;
  454. const { node, pos } = entity;
  455. eventObj.checkedNodes.push(node);
  456. eventObj.checkedNodesPositions.push({ node, pos });
  457. });
  458. this.setUncontrolledState({
  459. checkedKeys,
  460. halfCheckedKeys,
  461. });
  462. }
  463. if (onCheck) {
  464. onCheck(checkedObj, eventObj);
  465. }
  466. };
  467. onNodeLoad = treeNode =>
  468. new Promise(resolve => {
  469. // We need to get the latest state of loading/loaded keys
  470. this.setState(({ loadedKeys = [], loadingKeys = [] }) => {
  471. const { loadData, onLoad } = this.props;
  472. const { eventKey } = treeNode.props;
  473. if (
  474. !loadData ||
  475. loadedKeys.indexOf(eventKey) !== -1 ||
  476. loadingKeys.indexOf(eventKey) !== -1
  477. ) {
  478. // react 15 will warn if return null
  479. return {};
  480. }
  481. // Process load data
  482. const promise = loadData(treeNode);
  483. promise.then(() => {
  484. const newLoadedKeys = arrAdd(this.state.loadedKeys, eventKey);
  485. const newLoadingKeys = arrDel(this.state.loadingKeys, eventKey);
  486. // onLoad should trigger before internal setState to avoid `loadData` trigger twice.
  487. // https://github.com/ant-design/ant-design/issues/12464
  488. if (onLoad) {
  489. const eventObj = {
  490. event: 'load',
  491. node: treeNode,
  492. };
  493. onLoad(newLoadedKeys, eventObj);
  494. }
  495. this.setUncontrolledState({
  496. loadedKeys: newLoadedKeys,
  497. });
  498. this.setState({
  499. loadingKeys: newLoadingKeys,
  500. });
  501. resolve();
  502. });
  503. return {
  504. loadingKeys: arrAdd(loadingKeys, eventKey),
  505. };
  506. });
  507. });
  508. onNodeExpand = (e, treeNode) => {
  509. let { expandedKeys } = this.state;
  510. const { onExpand, loadData } = this.props;
  511. const { eventKey, expanded } = treeNode.props;
  512. // Update selected keys
  513. const index = expandedKeys.indexOf(eventKey);
  514. const targetExpanded = !expanded;
  515. warning(
  516. (expanded && index !== -1) || (!expanded && index === -1),
  517. 'Expand state not sync with index check',
  518. );
  519. if (targetExpanded) {
  520. expandedKeys = arrAdd(expandedKeys, eventKey);
  521. } else {
  522. expandedKeys = arrDel(expandedKeys, eventKey);
  523. }
  524. this.setUncontrolledState({ expandedKeys });
  525. if (onExpand) {
  526. onExpand(expandedKeys, {
  527. node: treeNode,
  528. expanded: targetExpanded,
  529. nativeEvent: e.nativeEvent,
  530. });
  531. }
  532. // Async Load data
  533. if (targetExpanded && loadData) {
  534. const loadPromise = this.onNodeLoad(treeNode);
  535. return loadPromise
  536. ? loadPromise.then(() => {
  537. // [Legacy] Refresh logic
  538. this.setUncontrolledState({ expandedKeys });
  539. })
  540. : null;
  541. }
  542. return null;
  543. };
  544. onNodeMouseEnter = (event, node) => {
  545. const { onMouseEnter } = this.props;
  546. if (onMouseEnter) {
  547. onMouseEnter({ event, node });
  548. }
  549. };
  550. onNodeMouseLeave = (event, node) => {
  551. const { onMouseLeave } = this.props;
  552. if (onMouseLeave) {
  553. onMouseLeave({ event, node });
  554. }
  555. };
  556. onNodeContextMenu = (event, node) => {
  557. const { onRightClick } = this.props;
  558. if (onRightClick) {
  559. event.preventDefault();
  560. onRightClick({ event, node });
  561. }
  562. };
  563. /**
  564. * Only update the value which is not in props
  565. */
  566. setUncontrolledState = state => {
  567. let needSync = false;
  568. const newState = {};
  569. Object.keys(state).forEach(name => {
  570. if (name in this.props) return;
  571. needSync = true;
  572. newState[name] = state[name];
  573. });
  574. if (needSync) {
  575. this.setState(newState);
  576. }
  577. };
  578. registerTreeNode = (key, node) => {
  579. if (node) {
  580. this.domTreeNodes[key] = node;
  581. } else {
  582. delete this.domTreeNodes[key];
  583. }
  584. };
  585. isKeyChecked = key => {
  586. const { checkedKeys = [] } = this.state;
  587. return checkedKeys.indexOf(key) !== -1;
  588. };
  589. /**
  590. * [Legacy] Original logic use `key` as tracking clue.
  591. * We have to use `cloneElement` to pass `key`.
  592. */
  593. renderTreeNode = (child, index, level = 0) => {
  594. console.log('renderTreeNode');
  595. const {
  596. keyEntities,
  597. expandedKeys = [],
  598. selectedKeys = [],
  599. halfCheckedKeys = [],
  600. loadedKeys = [],
  601. loadingKeys = [],
  602. dragOverNodeKey,
  603. dropPosition,
  604. } = this.state;
  605. const pos = getPosition(level, index);
  606. const key = child.key || pos;
  607. if (!keyEntities[key]) {
  608. warnOnlyTreeNode();
  609. return null;
  610. }
  611. return React.cloneElement(child, {
  612. key,
  613. eventKey: key,
  614. expanded: expandedKeys.indexOf(key) !== -1,
  615. selected: selectedKeys.indexOf(key) !== -1,
  616. loaded: loadedKeys.indexOf(key) !== -1,
  617. loading: loadingKeys.indexOf(key) !== -1,
  618. checked: this.isKeyChecked(key),
  619. halfChecked: halfCheckedKeys.indexOf(key) !== -1,
  620. pos,
  621. // [Legacy] Drag props
  622. dragOver: dragOverNodeKey === key && dropPosition === 0,
  623. dragOverGapTop: dragOverNodeKey === key && dropPosition === -1,
  624. dragOverGapBottom: dragOverNodeKey === key && dropPosition === 1,
  625. });
  626. };
  627. render() {
  628. const { treeNode } = this.state;
  629. const { prefixCls, className, focusable, style, showLine, tabIndex = 0 } = this.props;
  630. const domProps = getDataAndAria(this.props);
  631. if (focusable) {
  632. domProps.tabIndex = tabIndex;
  633. domProps.onKeyDown = this.onKeyDown;
  634. }
  635. console.log('treeNode', this.props.treeData);
  636. return (
  637. <ul
  638. {...domProps}
  639. className={classNames(prefixCls, className, {
  640. [`${prefixCls}-show-line`]: showLine,
  641. })}
  642. style={style}
  643. role="tree"
  644. unselectable="on"
  645. id="123"
  646. >
  647. {mapChildren(treeNode, (node, index) => this.renderTreeNode(node, index))}
  648. </ul>
  649. );
  650. }
  651. }
  652. polyfill(Tree);
  653. export default Tree;

TreeNode

  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import classNames from 'classnames';
  4. import CSSMotion from 'rc-animate/lib/CSSMotion';
  5. import toArray from 'rc-util/lib/Children/toArray';
  6. import { polyfill } from 'react-lifecycles-compat';
  7. import { nodeContextTypes } from './contextTypes';
  8. import { getNodeChildren, getDataAndAria, mapChildren, warnOnlyTreeNode } from './util';
  9. const ICON_OPEN = 'open';
  10. const ICON_CLOSE = 'close';
  11. const defaultTitle = '---';
  12. class TreeNode extends React.Component {
  13. static propTypes = {
  14. eventKey: PropTypes.string, // Pass by parent `cloneElement`
  15. prefixCls: PropTypes.string,
  16. className: PropTypes.string,
  17. style: PropTypes.object,
  18. root: PropTypes.object,
  19. onSelect: PropTypes.func,
  20. // By parent
  21. expanded: PropTypes.bool,
  22. selected: PropTypes.bool,
  23. checked: PropTypes.bool,
  24. loaded: PropTypes.bool,
  25. loading: PropTypes.bool,
  26. halfChecked: PropTypes.bool,
  27. children: PropTypes.node,
  28. title: PropTypes.node,
  29. pos: PropTypes.string,
  30. dragOver: PropTypes.bool,
  31. dragOverGapTop: PropTypes.bool,
  32. dragOverGapBottom: PropTypes.bool,
  33. // By user
  34. isLeaf: PropTypes.bool,
  35. checkable: PropTypes.bool,
  36. selectable: PropTypes.bool,
  37. disabled: PropTypes.bool,
  38. disableCheckbox: PropTypes.bool,
  39. icon: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),
  40. switcherIcon: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),
  41. };
  42. static contextTypes = nodeContextTypes;
  43. static childContextTypes = nodeContextTypes;
  44. static defaultProps = {
  45. title: defaultTitle,
  46. };
  47. constructor(props) {
  48. super(props);
  49. this.state = {
  50. dragNodeHighlight: false,
  51. };
  52. }
  53. getChildContext() {
  54. return {
  55. ...this.context,
  56. rcTreeNode: {
  57. // onUpCheckConduct: this.onUpCheckConduct,
  58. },
  59. };
  60. }
  61. // Isomorphic needn't load data in server side
  62. componentDidMount() {
  63. const { eventKey } = this.props;
  64. const {
  65. rcTree: { registerTreeNode },
  66. } = this.context;
  67. this.syncLoadData(this.props);
  68. registerTreeNode(eventKey, this);
  69. }
  70. componentDidUpdate() {
  71. this.syncLoadData(this.props);
  72. }
  73. componentWillUnmount() {
  74. const { eventKey } = this.props;
  75. const {
  76. rcTree: { registerTreeNode },
  77. } = this.context;
  78. registerTreeNode(eventKey, null);
  79. }
  80. onSelectorClick = e => {
  81. // Click trigger before select/check operation
  82. const {
  83. rcTree: { onNodeClick },
  84. } = this.context;
  85. onNodeClick(e, this);
  86. if (this.isSelectable()) {
  87. this.onSelect(e);
  88. } else {
  89. this.onCheck(e);
  90. }
  91. };
  92. onSelectorDoubleClick = e => {
  93. const {
  94. rcTree: { onNodeDoubleClick },
  95. } = this.context;
  96. onNodeDoubleClick(e, this);
  97. };
  98. onSelect = e => {
  99. if (this.isDisabled()) return;
  100. const {
  101. rcTree: { onNodeSelect },
  102. } = this.context;
  103. e.preventDefault();
  104. onNodeSelect(e, this);
  105. };
  106. onCheck = e => {
  107. if (this.isDisabled()) return;
  108. const { disableCheckbox, checked } = this.props;
  109. const {
  110. rcTree: { onNodeCheck },
  111. } = this.context;
  112. if (!this.isCheckable() || disableCheckbox) return;
  113. e.preventDefault();
  114. const targetChecked = !checked;
  115. onNodeCheck(e, this, targetChecked);
  116. };
  117. onMouseEnter = e => {
  118. const {
  119. rcTree: { onNodeMouseEnter },
  120. } = this.context;
  121. onNodeMouseEnter(e, this);
  122. };
  123. onMouseLeave = e => {
  124. const {
  125. rcTree: { onNodeMouseLeave },
  126. } = this.context;
  127. onNodeMouseLeave(e, this);
  128. };
  129. onContextMenu = e => {
  130. const {
  131. rcTree: { onNodeContextMenu },
  132. } = this.context;
  133. onNodeContextMenu(e, this);
  134. };
  135. onDragStart = e => {
  136. const {
  137. rcTree: { onNodeDragStart },
  138. } = this.context;
  139. e.stopPropagation();
  140. this.setState({
  141. dragNodeHighlight: true,
  142. });
  143. onNodeDragStart(e, this);
  144. try {
  145. // ie throw error
  146. // firefox-need-it
  147. e.dataTransfer.setData('text/plain', '');
  148. } catch (error) {
  149. // empty
  150. }
  151. };
  152. onDragEnter = e => {
  153. const {
  154. rcTree: { onNodeDragEnter },
  155. } = this.context;
  156. e.preventDefault();
  157. e.stopPropagation();
  158. onNodeDragEnter(e, this);
  159. };
  160. onDragOver = e => {
  161. const {
  162. rcTree: { onNodeDragOver },
  163. } = this.context;
  164. e.preventDefault();
  165. e.stopPropagation();
  166. onNodeDragOver(e, this);
  167. };
  168. onDragLeave = e => {
  169. const {
  170. rcTree: { onNodeDragLeave },
  171. } = this.context;
  172. e.stopPropagation();
  173. onNodeDragLeave(e, this);
  174. };
  175. onDragEnd = e => {
  176. const {
  177. rcTree: { onNodeDragEnd },
  178. } = this.context;
  179. e.stopPropagation();
  180. this.setState({
  181. dragNodeHighlight: false,
  182. });
  183. onNodeDragEnd(e, this);
  184. };
  185. onDrop = e => {
  186. const {
  187. rcTree: { onNodeDrop },
  188. } = this.context;
  189. e.preventDefault();
  190. e.stopPropagation();
  191. this.setState({
  192. dragNodeHighlight: false,
  193. });
  194. onNodeDrop(e, this);
  195. };
  196. // Disabled item still can be switch
  197. onExpand = e => {
  198. const {
  199. rcTree: { onNodeExpand },
  200. } = this.context;
  201. onNodeExpand(e, this);
  202. };
  203. // Drag usage
  204. setSelectHandle = node => {
  205. this.selectHandle = node;
  206. };
  207. getNodeChildren = () => {
  208. const { children } = this.props;
  209. const originList = toArray(children).filter(node => node);
  210. const targetList = getNodeChildren(originList);
  211. if (originList.length !== targetList.length) {
  212. warnOnlyTreeNode();
  213. }
  214. return targetList;
  215. };
  216. getNodeState = () => {
  217. const { expanded } = this.props;
  218. if (this.isLeaf()) {
  219. return null;
  220. }
  221. return expanded ? ICON_OPEN : ICON_CLOSE;
  222. };
  223. isLeaf = () => {
  224. const { isLeaf, loaded } = this.props;
  225. const {
  226. rcTree: { loadData },
  227. } = this.context;
  228. const hasChildren = this.getNodeChildren().length !== 0;
  229. if (isLeaf === false) {
  230. return false;
  231. }
  232. return isLeaf || (!loadData && !hasChildren) || (loadData && loaded && !hasChildren);
  233. };
  234. isDisabled = () => {
  235. const { disabled } = this.props;
  236. const {
  237. rcTree: { disabled: treeDisabled },
  238. } = this.context;
  239. // Follow the logic of Selectable
  240. if (disabled === false) {
  241. return false;
  242. }
  243. return !!(treeDisabled || disabled);
  244. };
  245. isCheckable = () => {
  246. const { checkable } = this.props;
  247. const {
  248. rcTree: { checkable: treeCheckable },
  249. } = this.context;
  250. // Return false if tree or treeNode is not checkable
  251. if (!treeCheckable || checkable === false) return false;
  252. return treeCheckable;
  253. };
  254. isSelectable() {
  255. const { selectable } = this.props;
  256. const {
  257. rcTree: { selectable: treeSelectable },
  258. } = this.context;
  259. // Ignore when selectable is undefined or null
  260. if (typeof selectable === 'boolean') {
  261. return selectable;
  262. }
  263. return treeSelectable;
  264. }
  265. // Load data to avoid default expanded tree without data
  266. syncLoadData = props => {
  267. const { expanded, loading, loaded } = props;
  268. const {
  269. rcTree: { loadData, onNodeLoad },
  270. } = this.context;
  271. if (loading) return;
  272. // read from state to avoid loadData at same time
  273. if (loadData && expanded && !this.isLeaf()) {
  274. // We needn't reload data when has children in sync logic
  275. // It's only needed in node expanded
  276. const hasChildren = this.getNodeChildren().length !== 0;
  277. if (!hasChildren && !loaded) {
  278. onNodeLoad(this);
  279. }
  280. }
  281. };
  282. // Switcher
  283. renderSwitcher = () => {
  284. const { expanded, switcherIcon: switcherIconFromProps } = this.props;
  285. const {
  286. rcTree: { prefixCls, switcherIcon: switcherIconFromCtx },
  287. } = this.context;
  288. const switcherIcon = switcherIconFromProps || switcherIconFromCtx;
  289. if (this.isLeaf()) {
  290. return (
  291. <span className={classNames(`${prefixCls}-switcher`, `${prefixCls}-switcher-noop`)}>
  292. {typeof switcherIcon === 'function'
  293. ? switcherIcon({ ...this.props, isLeaf: true })
  294. : switcherIcon}
  295. </span>
  296. );
  297. }
  298. const switcherCls = classNames(
  299. `${prefixCls}-switcher`,
  300. `${prefixCls}-switcher_${expanded ? ICON_OPEN : ICON_CLOSE}`,
  301. );
  302. return (
  303. <span onClick={this.onExpand} className={switcherCls}>
  304. {typeof switcherIcon === 'function'
  305. ? switcherIcon({ ...this.props, isLeaf: false })
  306. : switcherIcon}
  307. </span>
  308. );
  309. };
  310. // Checkbox
  311. renderCheckbox = () => {
  312. const { checked, halfChecked, disableCheckbox } = this.props;
  313. const {
  314. rcTree: { prefixCls },
  315. } = this.context;
  316. const disabled = this.isDisabled();
  317. const checkable = this.isCheckable();
  318. if (!checkable) return null;
  319. // [Legacy] Custom element should be separate with `checkable` in future
  320. const $custom = typeof checkable !== 'boolean' ? checkable : null;
  321. return (
  322. <span
  323. className={classNames(
  324. `${prefixCls}-checkbox`,
  325. checked && `${prefixCls}-checkbox-checked`,
  326. !checked && halfChecked && `${prefixCls}-checkbox-indeterminate`,
  327. (disabled || disableCheckbox) && `${prefixCls}-checkbox-disabled`,
  328. )}
  329. onClick={this.onCheck}
  330. >
  331. {$custom}
  332. </span>
  333. );
  334. };
  335. renderIcon = () => {
  336. const { loading } = this.props;
  337. const {
  338. rcTree: { prefixCls },
  339. } = this.context;
  340. return (
  341. <span
  342. className={classNames(
  343. `${prefixCls}-iconEle`,
  344. `${prefixCls}-icon__${this.getNodeState() || 'docu'}`,
  345. loading && `${prefixCls}-icon_loading`,
  346. )}
  347. />
  348. );
  349. };
  350. // Icon + Title
  351. renderSelector = () => {
  352. const { dragNodeHighlight } = this.state;
  353. const { title, selected, icon, loading } = this.props;
  354. const {
  355. rcTree: { prefixCls, showIcon, icon: treeIcon, draggable, loadData },
  356. } = this.context;
  357. const disabled = this.isDisabled();
  358. const wrapClass = `${prefixCls}-node-content-wrapper`;
  359. // Icon - Still show loading icon when loading without showIcon
  360. let $icon;
  361. if (showIcon) {
  362. const currentIcon = icon || treeIcon;
  363. $icon = currentIcon ? (
  364. <span className={classNames(`${prefixCls}-iconEle`, `${prefixCls}-icon__customize`)}>
  365. {typeof currentIcon === 'function'
  366. ? React.createElement(currentIcon, {
  367. ...this.props,
  368. })
  369. : currentIcon}
  370. </span>
  371. ) : (
  372. this.renderIcon()
  373. );
  374. } else if (loadData && loading) {
  375. $icon = this.renderIcon();
  376. }
  377. // Title
  378. const $title = <span className={`${prefixCls}-title`}>{title}</span>;
  379. return (
  380. <span
  381. ref={this.setSelectHandle}
  382. title={typeof title === 'string' ? title : ''}
  383. className={classNames(
  384. `${wrapClass}`,
  385. `${wrapClass}-${this.getNodeState() || 'normal'}`,
  386. !disabled && (selected || dragNodeHighlight) && `${prefixCls}-node-selected`,
  387. !disabled && draggable && 'draggable',
  388. )}
  389. draggable={(!disabled && draggable) || undefined}
  390. aria-grabbed={(!disabled && draggable) || undefined}
  391. onMouseEnter={this.onMouseEnter}
  392. onMouseLeave={this.onMouseLeave}
  393. onContextMenu={this.onContextMenu}
  394. onClick={this.onSelectorClick}
  395. onDoubleClick={this.onSelectorDoubleClick}
  396. onDragStart={draggable ? this.onDragStart : undefined}
  397. >
  398. {$icon}
  399. {$title}
  400. </span>
  401. );
  402. };
  403. // Children list wrapped with `Animation`
  404. renderChildren = () => {
  405. const { expanded, pos } = this.props;
  406. const {
  407. rcTree: { prefixCls, motion, renderTreeNode },
  408. } = this.context;
  409. // Children TreeNode
  410. const nodeList = this.getNodeChildren();
  411. if (nodeList.length === 0) {
  412. return null;
  413. }
  414. return (
  415. <CSSMotion visible={expanded} {...motion}>
  416. {({ style, className }) => {
  417. return (
  418. <ul
  419. className={classNames(
  420. className,
  421. `${prefixCls}-child-tree`,
  422. expanded && `${prefixCls}-child-tree-open`,
  423. )}
  424. style={style}
  425. data-expanded={expanded}
  426. role="group"
  427. >
  428. {mapChildren(nodeList, (node, index) => renderTreeNode(node, index, pos))}
  429. </ul>
  430. );
  431. }}
  432. </CSSMotion>
  433. );
  434. };
  435. render() {
  436. const { loading } = this.props;
  437. const {
  438. className,
  439. style,
  440. dragOver,
  441. dragOverGapTop,
  442. dragOverGapBottom,
  443. isLeaf,
  444. expanded,
  445. selected,
  446. checked,
  447. halfChecked,
  448. ...otherProps
  449. } = this.props;
  450. const {
  451. rcTree: { prefixCls, filterTreeNode, draggable },
  452. } = this.context;
  453. const disabled = this.isDisabled();
  454. const dataOrAriaAttributeProps = getDataAndAria(otherProps);
  455. return (
  456. <li
  457. className={classNames(className, {
  458. [`${prefixCls}-treenode-disabled`]: disabled,
  459. [`${prefixCls}-treenode-switcher-${expanded ? 'open' : 'close'}`]: !isLeaf,
  460. [`${prefixCls}-treenode-checkbox-checked`]: checked,
  461. [`${prefixCls}-treenode-checkbox-indeterminate`]: halfChecked,
  462. [`${prefixCls}-treenode-selected`]: selected,
  463. [`${prefixCls}-treenode-loading`]: loading,
  464. 'drag-over': !disabled && dragOver,
  465. 'drag-over-gap-top': !disabled && dragOverGapTop,
  466. 'drag-over-gap-bottom': !disabled && dragOverGapBottom,
  467. 'filter-node': filterTreeNode && filterTreeNode(this),
  468. })}
  469. style={style}
  470. role="treeitem"
  471. onDragEnter={draggable ? this.onDragEnter : undefined}
  472. onDragOver={draggable ? this.onDragOver : undefined}
  473. onDragLeave={draggable ? this.onDragLeave : undefined}
  474. onDrop={draggable ? this.onDrop : undefined}
  475. onDragEnd={draggable ? this.onDragEnd : undefined}
  476. {...dataOrAriaAttributeProps}
  477. >
  478. {this.renderSwitcher()}
  479. {this.renderCheckbox()}
  480. {this.renderSelector()}
  481. {this.renderChildren()}
  482. </li>
  483. );
  484. }
  485. }
  486. TreeNode.isTreeNode = 1;
  487. polyfill(TreeNode);
  488. export default TreeNode;

contextTypes

  1. /**
  2. * Webpack has bug for import loop, which is not the same behavior as ES module.
  3. * When util.js imports the TreeNode for tree generate will cause treeContextTypes be empty.
  4. */
  5. import PropTypes from 'prop-types';
  6. /**
  7. * Thought we still use `cloneElement` to pass `key`,
  8. * other props can pass with context for future refactor.
  9. */
  10. export const treeContextTypes = {
  11. rcTree: PropTypes.shape({
  12. root: PropTypes.object,
  13. prefixCls: PropTypes.string,
  14. selectable: PropTypes.bool,
  15. showIcon: PropTypes.bool,
  16. icon: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),
  17. draggable: PropTypes.bool,
  18. checkable: PropTypes.oneOfType([PropTypes.bool, PropTypes.node]),
  19. checkStrictly: PropTypes.bool,
  20. disabled: PropTypes.bool,
  21. openTransitionName: PropTypes.string,
  22. openAnimation: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
  23. loadData: PropTypes.func,
  24. filterTreeNode: PropTypes.func,
  25. renderTreeNode: PropTypes.func,
  26. isKeyChecked: PropTypes.func,
  27. onNodeClick: PropTypes.func,
  28. onNodeDoubleClick: PropTypes.func,
  29. onNodeExpand: PropTypes.func,
  30. onNodeSelect: PropTypes.func,
  31. onNodeCheck: PropTypes.func,
  32. onNodeMouseEnter: PropTypes.func,
  33. onNodeMouseLeave: PropTypes.func,
  34. onNodeContextMenu: PropTypes.func,
  35. onNodeDragStart: PropTypes.func,
  36. onNodeDragEnter: PropTypes.func,
  37. onNodeDragOver: PropTypes.func,
  38. onNodeDragLeave: PropTypes.func,
  39. onNodeDragEnd: PropTypes.func,
  40. onNodeDrop: PropTypes.func,
  41. // TODO: Remove this
  42. // onBatchNodeCheck: PropTypes.func,
  43. // onCheckConductFinished: PropTypes.func,
  44. // Tree will store the entities when the treeNode refresh.
  45. // User can pass the func to add more info to customize the additional info.
  46. // processTreeEntity: PropTypes.func,
  47. }),
  48. };
  49. export const nodeContextTypes = {
  50. ...treeContextTypes,
  51. rcTreeNode: PropTypes.shape({
  52. onUpCheckConduct: PropTypes.func,
  53. }),
  54. };

Utils

  1. import React, { Children } from 'react';
  2. import toArray from 'rc-util/lib/Children/toArray';
  3. import warning from 'warning';
  4. import TreeNode from './TreeNode';
  5. const DRAG_SIDE_RANGE = 0.25;
  6. const DRAG_MIN_GAP = 2;
  7. let onlyTreeNodeWarned = false;
  8. export function warnOnlyTreeNode() {
  9. if (onlyTreeNodeWarned) return;
  10. onlyTreeNodeWarned = true;
  11. warning(false, 'Tree only accept TreeNode as children.');
  12. }
  13. export function arrDel(list, value) {
  14. const clone = list.slice();
  15. const index = clone.indexOf(value);
  16. if (index >= 0) {
  17. clone.splice(index, 1);
  18. }
  19. return clone;
  20. }
  21. export function arrAdd(list, value) {
  22. const clone = list.slice();
  23. if (clone.indexOf(value) === -1) {
  24. clone.push(value);
  25. }
  26. return clone;
  27. }
  28. export function posToArr(pos) {
  29. return pos.split('-');
  30. }
  31. export function getPosition(level, index) {
  32. return `${level}-${index}`;
  33. }
  34. export function isTreeNode(node) {
  35. return node && node.type && node.type.isTreeNode;
  36. }
  37. export function getNodeChildren(children) {
  38. return toArray(children).filter(isTreeNode);
  39. }
  40. export function isCheckDisabled(node) {
  41. const { disabled, disableCheckbox } = node.props || {};
  42. return !!(disabled || disableCheckbox);
  43. }
  44. export function traverseTreeNodes(treeNodes, callback) {
  45. function processNode(node, index, parent) {
  46. const children = node ? node.props.children : treeNodes;
  47. const pos = node ? getPosition(parent.pos, index) : 0;
  48. // Filter children
  49. const childList = getNodeChildren(children);
  50. // Process node if is not root
  51. if (node) {
  52. const data = {
  53. node,
  54. index,
  55. pos,
  56. key: node.key || pos,
  57. parentPos: parent.node ? parent.pos : null,
  58. };
  59. callback(data);
  60. }
  61. // Process children node
  62. Children.forEach(childList, (subNode, subIndex) => {
  63. processNode(subNode, subIndex, { node, pos });
  64. });
  65. }
  66. processNode(null);
  67. }
  68. /**
  69. * Use `rc-util` `toArray` to get the children list which keeps the key.
  70. * And return single node if children is only one(This can avoid `key` missing check).
  71. */
  72. export function mapChildren(children, func) {
  73. const list = toArray(children).map(func);
  74. if (list.length === 1) {
  75. return list[0];
  76. }
  77. return list;
  78. }
  79. export function getDragNodesKeys(treeNodes, node) {
  80. const { eventKey, pos } = node.props;
  81. const dragNodesKeys = [];
  82. traverseTreeNodes(treeNodes, ({ key }) => {
  83. dragNodesKeys.push(key);
  84. });
  85. dragNodesKeys.push(eventKey || pos);
  86. return dragNodesKeys;
  87. }
  88. // Only used when drag, not affect SSR.
  89. export function calcDropPosition(event, treeNode) {
  90. const { clientY } = event;
  91. const { top, bottom, height } = treeNode.selectHandle.getBoundingClientRect();
  92. const des = Math.max(height * DRAG_SIDE_RANGE, DRAG_MIN_GAP);
  93. if (clientY <= top + des) {
  94. return -1;
  95. } else if (clientY >= bottom - des) {
  96. return 1;
  97. }
  98. return 0;
  99. }
  100. /**
  101. * Return selectedKeys according with multiple prop
  102. * @param selectedKeys
  103. * @param props
  104. * @returns [string]
  105. */
  106. export function calcSelectedKeys(selectedKeys, props) {
  107. if (!selectedKeys) return undefined;
  108. const { multiple } = props;
  109. if (multiple) {
  110. return selectedKeys.slice();
  111. }
  112. if (selectedKeys.length) {
  113. return [selectedKeys[0]];
  114. }
  115. return selectedKeys;
  116. }
  117. /**
  118. * Since React internal will convert key to string,
  119. * we need do this to avoid `checkStrictly` use number match
  120. */
  121. function keyListToString(keyList) {
  122. if (!keyList) return keyList;
  123. return keyList.map(key => String(key));
  124. }
  125. const internalProcessProps = props => props;
  126. export function convertDataToTree(treeData, processer) {
  127. if (!treeData) return [];
  128. const { processProps = internalProcessProps } = processer || {};
  129. const list = Array.isArray(treeData) ? treeData : [treeData];
  130. return list.map(({ children, ...props }) => {
  131. const childrenNodes = convertDataToTree(children, processer);
  132. return <TreeNode {...processProps(props)}>{childrenNodes}</TreeNode>;
  133. });
  134. }
  135. // TODO: ========================= NEW LOGIC =========================
  136. /**
  137. * Calculate treeNodes entities. `processTreeEntity` is used for `rc-tree-select`
  138. * @param treeNodes
  139. * @param processTreeEntity User can customize the entity
  140. */
  141. export function convertTreeToEntities(
  142. treeNodes,
  143. { initWrapper, processEntity, onProcessFinished } = {},
  144. ) {
  145. const posEntities = {};
  146. const keyEntities = {};
  147. let wrapper = {
  148. posEntities,
  149. keyEntities,
  150. };
  151. if (initWrapper) {
  152. wrapper = initWrapper(wrapper) || wrapper;
  153. }
  154. traverseTreeNodes(treeNodes, item => {
  155. const { node, index, pos, key, parentPos } = item;
  156. const entity = { node, index, key, pos };
  157. posEntities[pos] = entity;
  158. keyEntities[key] = entity;
  159. // Fill children
  160. entity.parent = posEntities[parentPos];
  161. if (entity.parent) {
  162. entity.parent.children = entity.parent.children || [];
  163. entity.parent.children.push(entity);
  164. }
  165. if (processEntity) {
  166. processEntity(entity, wrapper);
  167. }
  168. });
  169. if (onProcessFinished) {
  170. onProcessFinished(wrapper);
  171. }
  172. return wrapper;
  173. }
  174. /**
  175. * Parse `checkedKeys` to { checkedKeys, halfCheckedKeys } style
  176. */
  177. export function parseCheckedKeys(keys) {
  178. if (!keys) {
  179. return null;
  180. }
  181. // Convert keys to object format
  182. let keyProps;
  183. if (Array.isArray(keys)) {
  184. // [Legacy] Follow the api doc
  185. keyProps = {
  186. checkedKeys: keys,
  187. halfCheckedKeys: undefined,
  188. };
  189. } else if (typeof keys === 'object') {
  190. keyProps = {
  191. checkedKeys: keys.checked || undefined,
  192. halfCheckedKeys: keys.halfChecked || undefined,
  193. };
  194. } else {
  195. warning(false, '`checkedKeys` is not an array or an object');
  196. return null;
  197. }
  198. keyProps.checkedKeys = keyListToString(keyProps.checkedKeys);
  199. keyProps.halfCheckedKeys = keyListToString(keyProps.halfCheckedKeys);
  200. return keyProps;
  201. }
  202. /**
  203. * Conduct check state by the keyList. It will conduct up & from the provided key.
  204. * If the conduct path reach the disabled or already checked / unchecked node will stop conduct.
  205. * @param keyList list of keys
  206. * @param isCheck is check the node or not
  207. * @param keyEntities parsed by `convertTreeToEntities` function in Tree
  208. * @param checkStatus Can pass current checked status for process (usually for uncheck operation)
  209. * @returns {{checkedKeys: [], halfCheckedKeys: []}}
  210. */
  211. export function conductCheck(keyList, isCheck, keyEntities, checkStatus = {}) {
  212. const checkedKeys = {};
  213. const halfCheckedKeys = {}; // Record the key has some child checked (include child half checked)
  214. (checkStatus.checkedKeys || []).forEach(key => {
  215. checkedKeys[key] = true;
  216. });
  217. (checkStatus.halfCheckedKeys || []).forEach(key => {
  218. halfCheckedKeys[key] = true;
  219. });
  220. // Conduct up
  221. function conductUp(key) {
  222. if (checkedKeys[key] === isCheck) return;
  223. const entity = keyEntities[key];
  224. if (!entity) return;
  225. const { children, parent, node } = entity;
  226. if (isCheckDisabled(node)) return;
  227. // Check child node checked status
  228. let everyChildChecked = true;
  229. let someChildChecked = false; // Child checked or half checked
  230. (children || [])
  231. .filter(child => !isCheckDisabled(child.node))
  232. .forEach(({ key: childKey }) => {
  233. const childChecked = checkedKeys[childKey];
  234. const childHalfChecked = halfCheckedKeys[childKey];
  235. if (childChecked || childHalfChecked) someChildChecked = true;
  236. if (!childChecked) everyChildChecked = false;
  237. });
  238. // Update checked status
  239. if (isCheck) {
  240. checkedKeys[key] = everyChildChecked;
  241. } else {
  242. checkedKeys[key] = false;
  243. }
  244. halfCheckedKeys[key] = someChildChecked;
  245. if (parent) {
  246. conductUp(parent.key);
  247. }
  248. }
  249. // Conduct down
  250. function conductDown(key) {
  251. if (checkedKeys[key] === isCheck) return;
  252. const entity = keyEntities[key];
  253. if (!entity) return;
  254. const { children, node } = entity;
  255. if (isCheckDisabled(node)) return;
  256. checkedKeys[key] = isCheck;
  257. (children || []).forEach(child => {
  258. conductDown(child.key);
  259. });
  260. }
  261. function conduct(key) {
  262. const entity = keyEntities[key];
  263. if (!entity) {
  264. warning(false, `'${key}' does not exist in the tree.`);
  265. return;
  266. }
  267. const { children, parent, node } = entity;
  268. checkedKeys[key] = isCheck;
  269. if (isCheckDisabled(node)) return;
  270. // Conduct down
  271. (children || [])
  272. .filter(child => !isCheckDisabled(child.node))
  273. .forEach(child => {
  274. conductDown(child.key);
  275. });
  276. // Conduct up
  277. if (parent) {
  278. conductUp(parent.key);
  279. }
  280. }
  281. (keyList || []).forEach(key => {
  282. conduct(key);
  283. });
  284. const checkedKeyList = [];
  285. const halfCheckedKeyList = [];
  286. // Fill checked list
  287. Object.keys(checkedKeys).forEach(key => {
  288. if (checkedKeys[key]) {
  289. checkedKeyList.push(key);
  290. }
  291. });
  292. // Fill half checked list
  293. Object.keys(halfCheckedKeys).forEach(key => {
  294. if (!checkedKeys[key] && halfCheckedKeys[key]) {
  295. halfCheckedKeyList.push(key);
  296. }
  297. });
  298. return {
  299. checkedKeys: checkedKeyList,
  300. halfCheckedKeys: halfCheckedKeyList,
  301. };
  302. }
  303. /**
  304. * If user use `autoExpandParent` we should get the list of parent node
  305. * @param keyList
  306. * @param keyEntities
  307. */
  308. export function conductExpandParent(keyList, keyEntities) {
  309. const expandedKeys = {};
  310. function conductUp(key) {
  311. if (expandedKeys[key]) return;
  312. const entity = keyEntities[key];
  313. if (!entity) return;
  314. expandedKeys[key] = true;
  315. const { parent, node } = entity;
  316. if (isCheckDisabled(node)) return;
  317. if (parent) {
  318. conductUp(parent.key);
  319. }
  320. }
  321. (keyList || []).forEach(key => {
  322. conductUp(key);
  323. });
  324. return Object.keys(expandedKeys);
  325. }
  326. /**
  327. * Returns only the data- and aria- key/value pairs
  328. * @param {object} props
  329. */
  330. export function getDataAndAria(props) {
  331. return Object.keys(props).reduce((prev, key) => {
  332. if (key.substr(0, 5) === 'data-' || key.substr(0, 5) === 'aria-') {
  333. prev[key] = props[key];
  334. }
  335. return prev;
  336. }, {});
  337. }