1
0

treeNode.tsx 15 KB

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