treeNode.tsx 16 KB

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