1
0

treeNode.tsx 15 KB

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