treeNode.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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. };
  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, level } = 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. // when leaf node 's level is 0, no switcher
  193. if (showLine && level) {
  194. return this.renderSwitcher();
  195. }
  196. return (
  197. <span className={`${prefixcls}-empty-icon`} />
  198. );
  199. }
  200. renderCheckbox() {
  201. const { checked, halfChecked, eventKey } = this.props;
  202. const disabled = this.isDisabled();
  203. return (
  204. <div
  205. role='none'
  206. onClick={this.onCheck}
  207. onKeyPress={this.handleCheckEnterPress}
  208. >
  209. <Checkbox
  210. aria-label='Toggle the checked state of checkbox'
  211. value={eventKey}
  212. indeterminate={halfChecked}
  213. checked={checked}
  214. disabled={Boolean(disabled)}
  215. />
  216. </div>
  217. );
  218. }
  219. // Switcher
  220. renderSwitcher = () => {
  221. if (this.isLeaf()) {
  222. // if switcherIconDom is null, no render switcher span
  223. return (<span className={cls(`${prefixcls}-switcher`)} >
  224. <span className={`${prefixcls}-switcher-leaf-line`} />
  225. </span>);
  226. }
  227. return null;
  228. };
  229. renderIcon() {
  230. const {
  231. directory,
  232. treeIcon
  233. } = this.context;
  234. const { expanded, icon, data } = this.props;
  235. if (icon) {
  236. return icon;
  237. }
  238. if (treeIcon) {
  239. return typeof treeIcon === 'function' ? treeIcon(this.props) : treeIcon;
  240. }
  241. if (directory) {
  242. const hasChild = !this.isLeaf();
  243. if (!hasChild) {
  244. return <IconFile className={`${prefixcls}-item-icon`} />;
  245. } else {
  246. return expanded ? <IconFolderOpen className={`${prefixcls}-item-icon`} /> : <IconFolder className={`${prefixcls}-item-icon`} />;
  247. }
  248. }
  249. return null;
  250. }
  251. renderEmptyNode() {
  252. const { emptyContent } = this.props;
  253. const wrapperCls = cls(prefixcls, {
  254. [`${prefixcls}-empty`]: true,
  255. });
  256. return (
  257. <ul className={wrapperCls}>
  258. <li className={`${prefixcls}-label ${prefixcls}-label-empty`} x-semi-prop="emptyContent">
  259. {emptyContent}
  260. </li>
  261. </ul>
  262. );
  263. }
  264. renderRealLabel = () => {
  265. const { renderLabel } = this.context;
  266. const { label, keyword, data, filtered, treeNodeFilterProp } = this.props;
  267. if (isFunction(renderLabel)) {
  268. return renderLabel(label, data, keyword);
  269. } else if (isString(label) && filtered && keyword) {
  270. return (
  271. <Highlight
  272. highlightClassName={`${prefixcls}-highlight`}
  273. component='span'
  274. sourceString={label}
  275. searchWords={[keyword]}
  276. />
  277. );
  278. } else {
  279. return label;
  280. }
  281. };
  282. setRef = (node: HTMLElement) => {
  283. this.refNode = node;
  284. };
  285. render() {
  286. const {
  287. eventKey,
  288. expanded,
  289. selected,
  290. checked,
  291. halfChecked,
  292. loading,
  293. active,
  294. level,
  295. empty,
  296. filtered,
  297. treeNodeFilterProp,
  298. display,
  299. style,
  300. isEnd,
  301. showLine,
  302. ...rest
  303. } = this.props;
  304. if (empty) {
  305. return this.renderEmptyNode();
  306. }
  307. const {
  308. multiple,
  309. draggable,
  310. renderFullLabel,
  311. dragOverNodeKey,
  312. dropPosition,
  313. labelEllipsis
  314. } = this.context;
  315. const isEndNode = isEnd[isEnd.length - 1];
  316. const disabled = this.isDisabled();
  317. const dragOver = dragOverNodeKey === eventKey && dropPosition === 0;
  318. const dragOverGapTop = dragOverNodeKey === eventKey && dropPosition === -1;
  319. const dragOverGapBottom = dragOverNodeKey === eventKey && dropPosition === 1;
  320. const nodeCls = cls(prefixcls, {
  321. [`${prefixcls}-level-${level + 1}`]: true,
  322. [`${prefixcls}-fullLabel-level-${level + 1}`]: renderFullLabel,
  323. [`${prefixcls}-collapsed`]: !expanded,
  324. [`${prefixcls}-disabled`]: Boolean(disabled),
  325. [`${prefixcls}-selected`]: selected,
  326. [`${prefixcls}-active`]: !multiple && active,
  327. [`${prefixcls}-ellipsis`]: labelEllipsis,
  328. [`${prefixcls}-drag-over`]: !disabled && dragOver,
  329. [`${prefixcls}-draggable`]: !disabled && draggable && !renderFullLabel,
  330. // When draggable + renderFullLabel is enabled, the default style
  331. [`${prefixcls}-fullLabel-draggable`]: !disabled && draggable && renderFullLabel,
  332. // When draggable + renderFullLabel is turned on, the style of dragover
  333. [`${prefixcls}-fullLabel-drag-over-gap-top`]: !disabled && dragOverGapTop && renderFullLabel,
  334. [`${prefixcls}-fullLabel-drag-over-gap-bottom`]: !disabled && dragOverGapBottom && renderFullLabel,
  335. [`${prefixcls}-tree-node-last-leaf`]: isEndNode,
  336. });
  337. const labelProps = {
  338. onClick: this.onClick,
  339. onContextMenu: this.onContextMenu,
  340. onDoubleClick: this.onDoubleClick,
  341. className: nodeCls,
  342. onExpand: this.onExpand,
  343. data: rest.data,
  344. level,
  345. onCheck: this.onCheck,
  346. style,
  347. expandIcon: this.renderArrow(),
  348. checkStatus: {
  349. checked,
  350. halfChecked,
  351. },
  352. expandStatus: {
  353. expanded,
  354. loading,
  355. },
  356. filtered,
  357. searchWord: rest.keyword,
  358. };
  359. const dragProps = {
  360. onDoubleClick: this.onDoubleClick,
  361. onDragStart: draggable ? this.onDragStart : undefined,
  362. onDragEnter: draggable ? this.onDragEnter : undefined,
  363. onDragOver: draggable ? this.onDragOver : undefined,
  364. onDragLeave: draggable ? this.onDragLeave : undefined,
  365. onDrop: draggable ? this.onDrop : undefined,
  366. onDragEnd: draggable ? this.onDragEnd : undefined,
  367. draggable: (!disabled && draggable) || undefined,
  368. };
  369. if (renderFullLabel) {
  370. const customLabel = renderFullLabel({ ...labelProps });
  371. if (draggable) {
  372. // @ts-ignore skip cloneElement type check
  373. return React.cloneElement(customLabel, {
  374. ref: this.setRef,
  375. ...dragProps
  376. });
  377. } else {
  378. if (isEmpty(style)) {
  379. return customLabel;
  380. } else {
  381. // In virtualization, props.style will contain location information
  382. // @ts-ignore skip cloneElement type check
  383. return React.cloneElement(customLabel, {
  384. style: { ...get(customLabel, ['props', 'style']), ...style }
  385. });
  386. }
  387. }
  388. }
  389. const labelCls = cls(`${prefixcls}-label`, {
  390. [`${prefixcls}-drag-over-gap-top`]: !disabled && dragOverGapTop,
  391. [`${prefixcls}-drag-over-gap-bottom`]: !disabled && dragOverGapBottom,
  392. });
  393. const setsize = get(rest, ['data', 'children', 'length']);
  394. const posinset = isString(rest.pos) ? Number(rest.pos.split('-')[level + 1]) + 1 : 1;
  395. return (
  396. <li
  397. className={nodeCls}
  398. role="treeitem"
  399. aria-disabled={disabled}
  400. aria-checked={checked}
  401. aria-selected={selected}
  402. aria-setsize={setsize}
  403. aria-posinset={posinset}
  404. aria-expanded={expanded}
  405. aria-level={level + 1}
  406. data-key={eventKey}
  407. onClick={this.onClick}
  408. onKeyPress={this.handleliEnterPress}
  409. onContextMenu={this.onContextMenu}
  410. onDoubleClick={this.onDoubleClick}
  411. ref={this.setRef}
  412. style={style}
  413. {...dragProps}
  414. >
  415. <Indent showLine={showLine} prefixcls={prefixcls} level={level} isEnd={isEnd} />
  416. {this.renderArrow()}
  417. <span
  418. className={labelCls}
  419. >
  420. {multiple ? this.renderCheckbox() : null}
  421. {this.renderIcon()}
  422. <span className={`${prefixcls}-label-text`}>{this.renderRealLabel()}</span>
  423. </span>
  424. </li>
  425. );
  426. }
  427. }