1
0

treeNode.tsx 15 KB

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