treeNode.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. import React, { PureComponent } from 'react';
  2. import cls from 'classnames';
  3. import PropTypes from 'prop-types';
  4. import { cssClasses } from '@douyinfe/semi-foundation/tree/constants';
  5. import isEnterPress from '@douyinfe/semi-foundation/utils/isEnterPress';
  6. import { debounce, isFunction, isString, get } from 'lodash';
  7. import { IconTreeTriangleDown, IconFile, IconFolder, IconFolderOpen } from '@douyinfe/semi-icons';
  8. import { Checkbox } from '../checkbox';
  9. import TreeContext from './treeContext';
  10. import Spin from '../spin';
  11. import { TreeNodeProps, TreeNodeState } from './interface';
  12. const prefixcls = cssClasses.PREFIX_OPTION;
  13. export default class TreeNode extends PureComponent<TreeNodeProps, TreeNodeState> {
  14. static contextType = TreeContext;
  15. static propTypes = {
  16. expanded: PropTypes.bool,
  17. selected: PropTypes.bool,
  18. checked: PropTypes.bool,
  19. halfChecked: PropTypes.bool,
  20. active: PropTypes.bool,
  21. disabled: PropTypes.bool,
  22. loaded: PropTypes.bool,
  23. loading: PropTypes.bool,
  24. isLeaf: PropTypes.bool,
  25. pos: PropTypes.string,
  26. children: PropTypes.oneOfType([PropTypes.array, PropTypes.object]),
  27. icon: PropTypes.node,
  28. directory: PropTypes.bool,
  29. keyword: PropTypes.string,
  30. treeNodeFilterProp: PropTypes.string,
  31. selectedKey: PropTypes.string,
  32. motionKey: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)])
  33. };
  34. static defaultProps = {
  35. selectedKey: '',
  36. motionKey: '',
  37. };
  38. debounceSelect: any;
  39. refNode: HTMLElement;
  40. constructor(props: TreeNodeProps) {
  41. super(props);
  42. this.state = {};
  43. this.debounceSelect = debounce(this.onSelect, 500, {
  44. leading: true,
  45. trailing: false
  46. });
  47. }
  48. onSelect = (e: React.MouseEvent | React.KeyboardEvent) => {
  49. const { onNodeSelect } = this.context;
  50. onNodeSelect(e, this.props);
  51. };
  52. onExpand = (e: React.MouseEvent | React.KeyboardEvent) => {
  53. const { onNodeExpand } = this.context;
  54. e && e.stopPropagation();
  55. e.nativeEvent.stopImmediatePropagation();
  56. onNodeExpand(e, this.props);
  57. };
  58. onCheck = (e: React.MouseEvent | React.KeyboardEvent) => {
  59. if (this.isDisabled()) {
  60. return;
  61. }
  62. const { onNodeCheck } = this.context;
  63. e.stopPropagation();
  64. e.nativeEvent.stopImmediatePropagation();
  65. onNodeCheck(e, this.props);
  66. };
  67. /**
  68. * A11y: simulate checkbox click
  69. */
  70. handleCheckEnterPress = (e: React.KeyboardEvent) => {
  71. if (isEnterPress(e)) {
  72. this.onCheck(e);
  73. }
  74. }
  75. onContextMenu = (e: React.MouseEvent) => {
  76. const { onNodeRightClick } = this.context;
  77. onNodeRightClick(e, this.props);
  78. };
  79. onClick = (e: React.MouseEvent | React.KeyboardEvent) => {
  80. const { expandAction } = this.context;
  81. if (expandAction === 'doubleClick') {
  82. this.debounceSelect(e);
  83. return;
  84. }
  85. this.onSelect(e);
  86. if (expandAction === 'click') {
  87. this.onExpand(e);
  88. }
  89. };
  90. /**
  91. * A11y: simulate li click
  92. */
  93. handleliEnterPress = (e: React.KeyboardEvent) => {
  94. if (isEnterPress(e)) {
  95. this.onClick(e);
  96. }
  97. }
  98. onDoubleClick = (e: React.MouseEvent) => {
  99. const { expandAction, onNodeDoubleClick } = this.context;
  100. e.stopPropagation();
  101. e.nativeEvent.stopImmediatePropagation();
  102. if (isFunction(onNodeDoubleClick)) {
  103. onNodeDoubleClick(e, this.props);
  104. }
  105. if (expandAction === 'doubleClick') {
  106. this.onExpand(e);
  107. }
  108. };
  109. onDragStart = (e: React.DragEvent) => {
  110. const { onNodeDragStart } = this.context;
  111. e.stopPropagation();
  112. onNodeDragStart(e, { ...this.props, nodeInstance: this.refNode });
  113. try {
  114. // ie throw error
  115. // firefox-need-it
  116. e.dataTransfer.setData('text/plain', '');
  117. } catch (error) {
  118. // empty
  119. }
  120. };
  121. onDragEnter = (e: React.DragEvent) => {
  122. const { onNodeDragEnter } = this.context;
  123. e.preventDefault();
  124. e.stopPropagation();
  125. onNodeDragEnter(e, { ...this.props, nodeInstance: this.refNode });
  126. };
  127. onDragOver = (e: React.DragEvent) => {
  128. const { onNodeDragOver } = this.context;
  129. e.preventDefault();
  130. e.stopPropagation();
  131. onNodeDragOver(e, { ...this.props, nodeInstance: this.refNode });
  132. };
  133. onDragLeave = (e: React.DragEvent) => {
  134. const { onNodeDragLeave } = this.context;
  135. e.stopPropagation();
  136. onNodeDragLeave(e, { ...this.props, nodeInstance: this.refNode });
  137. };
  138. onDragEnd = (e: React.DragEvent) => {
  139. const { onNodeDragEnd } = this.context;
  140. e.stopPropagation();
  141. onNodeDragEnd(e, { ...this.props, nodeInstance: this.refNode });
  142. };
  143. onDrop = (e: React.DragEvent) => {
  144. const { onNodeDrop } = this.context;
  145. e.preventDefault();
  146. e.stopPropagation();
  147. onNodeDrop(e, { ...this.props, nodeInstance: this.refNode });
  148. };
  149. getNodeChildren = () => {
  150. const { children } = this.props;
  151. return children || [];
  152. };
  153. isLeaf = () => {
  154. const { isLeaf, loaded } = this.props;
  155. const { loadData } = this.context;
  156. const hasChildren = this.getNodeChildren().length !== 0;
  157. if (isLeaf === false) {
  158. return false;
  159. }
  160. return isLeaf || (!loadData && !hasChildren) || (loadData && loaded && !hasChildren);
  161. };
  162. isDisabled = () => {
  163. const { disabled } = this.props;
  164. const { treeDisabled } = this.context;
  165. if (disabled === false) {
  166. return false;
  167. }
  168. return Boolean(treeDisabled || disabled);
  169. };
  170. renderArrow() {
  171. const showIcon = !this.isLeaf();
  172. const { loading, expanded } = this.props;
  173. if (loading) {
  174. return <Spin wrapperClassName={`${prefixcls}-spin-icon`} />;
  175. }
  176. if (showIcon) {
  177. return (
  178. <IconTreeTriangleDown
  179. role='button'
  180. aria-label={`${expanded ? 'Expand' : 'Collapse'} the tree item`}
  181. className={`${prefixcls}-expand-icon`}
  182. size="small"
  183. onClick={this.onExpand}
  184. />
  185. );
  186. }
  187. return (
  188. <span className={`${prefixcls}-empty-icon`} />
  189. );
  190. }
  191. renderCheckbox() {
  192. const { checked, halfChecked } = this.props;
  193. const disabled = this.isDisabled();
  194. return (
  195. <div
  196. role='none'
  197. onClick={this.onCheck}
  198. onKeyPress={this.handleCheckEnterPress}
  199. >
  200. <Checkbox
  201. aria-label='Toggle the checked state of checkbox'
  202. indeterminate={halfChecked}
  203. checked={checked}
  204. disabled={Boolean(disabled)}
  205. />
  206. </div>
  207. );
  208. }
  209. renderIcon() {
  210. const {
  211. directory,
  212. treeIcon
  213. } = this.context;
  214. const { expanded, icon } = this.props;
  215. const hasChild = !this.isLeaf();
  216. const hasIcon = icon || treeIcon;
  217. let itemIcon;
  218. if (hasIcon || directory) {
  219. if (hasIcon) {
  220. itemIcon = icon || treeIcon;
  221. } else {
  222. if (!hasChild) {
  223. itemIcon = <IconFile className={`${prefixcls}-item-icon`} />;
  224. } else {
  225. // eslint-disable-next-line max-len
  226. itemIcon = expanded ? <IconFolderOpen className={`${prefixcls}-item-icon`} /> : <IconFolder className={`${prefixcls}-item-icon`} />;
  227. }
  228. }
  229. }
  230. return itemIcon;
  231. }
  232. renderEmptyNode() {
  233. const { emptyContent } = this.props;
  234. const wrapperCls = cls(prefixcls, {
  235. [`${prefixcls}-empty`]: true,
  236. });
  237. return (
  238. <ul className={wrapperCls}>
  239. <li className={`${prefixcls}-label ${prefixcls}-label-empty`}>
  240. {emptyContent}
  241. </li>
  242. </ul>
  243. );
  244. }
  245. renderRealLabel = () => {
  246. const { renderLabel } = this.context;
  247. const { label, keyword, data, filtered, treeNodeFilterProp } = this.props;
  248. if (isFunction(renderLabel)) {
  249. return renderLabel(label, data);
  250. } else if (isString(label) && filtered && keyword && treeNodeFilterProp === 'label') {
  251. const content: React.ReactNode[] = [];
  252. label.split(keyword).forEach((node, index) => {
  253. if (index > 0) {
  254. content.push(
  255. <span className={`${prefixcls}-highlight`} key={index}>
  256. {keyword}
  257. </span>
  258. );
  259. }
  260. content.push(node);
  261. });
  262. return content;
  263. } else {
  264. return label;
  265. }
  266. };
  267. setRef = (node: HTMLElement) => {
  268. this.refNode = node;
  269. };
  270. // eslint-disable-next-line max-lines-per-function
  271. render() {
  272. const {
  273. eventKey,
  274. expanded,
  275. selected,
  276. checked,
  277. halfChecked,
  278. loading,
  279. active,
  280. level,
  281. empty,
  282. filtered,
  283. treeNodeFilterProp,
  284. // eslint-disable-next-line no-unused-vars
  285. display,
  286. style,
  287. ...rest
  288. } = this.props;
  289. if (empty) {
  290. return this.renderEmptyNode();
  291. }
  292. const {
  293. multiple,
  294. draggable,
  295. renderFullLabel,
  296. dragOverNodeKey,
  297. dropPosition,
  298. labelEllipsis
  299. } = this.context;
  300. const disabled = this.isDisabled();
  301. const dragOver = dragOverNodeKey === eventKey && dropPosition === 0;
  302. const dragOverGapTop = dragOverNodeKey === eventKey && dropPosition === -1;
  303. const dragOverGapBottom = dragOverNodeKey === eventKey && dropPosition === 1;
  304. const nodeCls = cls(prefixcls, {
  305. [`${prefixcls}-level-${level + 1}`]: true,
  306. [`${prefixcls}-collapsed`]: !expanded,
  307. [`${prefixcls}-disabled`]: Boolean(disabled),
  308. [`${prefixcls}-selected`]: selected,
  309. [`${prefixcls}-active`]: !multiple && active,
  310. [`${prefixcls}-ellipsis`]: labelEllipsis,
  311. [`${prefixcls}-filtered`]: filtered && treeNodeFilterProp !== 'label',
  312. [`${prefixcls}-drag-over`]: !disabled && dragOver,
  313. [`${prefixcls}-draggable`]: !disabled && draggable && !renderFullLabel,
  314. // When draggable + renderFullLabel is enabled, the default style
  315. [`${prefixcls}-fullLabel-draggable`]: !disabled && draggable && renderFullLabel,
  316. // When draggable + renderFullLabel is turned on, the style of dragover
  317. [`${prefixcls}-fullLabel-drag-over-gap-top`]: !disabled && dragOverGapTop && renderFullLabel,
  318. [`${prefixcls}-fullLabel-drag-over-gap-bottom`]: !disabled && dragOverGapBottom && renderFullLabel,
  319. });
  320. const labelProps = {
  321. onClick: this.onClick,
  322. onContextMenu: this.onContextMenu,
  323. onDoubleClick: this.onDoubleClick,
  324. className: nodeCls,
  325. onExpand: this.onExpand,
  326. data: rest.data,
  327. level,
  328. onCheck: this.onCheck,
  329. style,
  330. expandIcon: this.renderArrow(),
  331. checkStatus: {
  332. checked,
  333. halfChecked,
  334. },
  335. expandStatus: {
  336. expanded,
  337. loading,
  338. },
  339. };
  340. const dragProps = {
  341. onDoubleClick: this.onDoubleClick,
  342. onDragStart: draggable ? this.onDragStart : undefined,
  343. onDragEnter: draggable ? this.onDragEnter : undefined,
  344. onDragOver: draggable ? this.onDragOver : undefined,
  345. onDragLeave: draggable ? this.onDragLeave : undefined,
  346. onDrop: draggable ? this.onDrop : undefined,
  347. onDragEnd: draggable ? this.onDragEnd : undefined,
  348. draggable: (!disabled && draggable) || undefined,
  349. };
  350. if (renderFullLabel) {
  351. const customLabel = renderFullLabel({ ...labelProps });
  352. if (draggable) {
  353. return React.cloneElement(customLabel, {
  354. ref: this.setRef,
  355. ...dragProps
  356. });
  357. } else {
  358. return customLabel;
  359. }
  360. }
  361. const labelCls = cls(`${prefixcls}-label`, {
  362. [`${prefixcls}-drag-over-gap-top`]: !disabled && dragOverGapTop,
  363. [`${prefixcls}-drag-over-gap-bottom`]: !disabled && dragOverGapBottom,
  364. });
  365. const setsize = get(rest, ['data', 'children', 'length']);
  366. const posinset = isString(rest.pos) ? Number(rest.pos.split('-')[level+1]) + 1 : 1;
  367. return (
  368. <li
  369. className={nodeCls}
  370. role="treeitem"
  371. aria-disabled={disabled}
  372. aria-checked={checked}
  373. aria-selected={selected}
  374. aria-setsize={setsize}
  375. aria-posinset={posinset}
  376. aria-expanded={expanded}
  377. aria-level={level+1}
  378. data-key={eventKey}
  379. onClick={this.onClick}
  380. onKeyPress={this.handleliEnterPress}
  381. onContextMenu={this.onContextMenu}
  382. onDoubleClick={this.onDoubleClick}
  383. ref={this.setRef}
  384. style={style}
  385. {...dragProps}
  386. >
  387. {this.renderArrow()}
  388. <span
  389. className={labelCls}
  390. >
  391. {multiple ? this.renderCheckbox() : null}
  392. {this.renderIcon()}
  393. <span className={`${prefixcls}-label-text`}>{this.renderRealLabel()}</span>
  394. </span>
  395. </li>
  396. );
  397. }
  398. }