1
0

treeNode.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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. itemIcon = expanded ? <IconFolderOpen className={`${prefixcls}-item-icon`} /> : <IconFolder className={`${prefixcls}-item-icon`} />;
  229. }
  230. }
  231. }
  232. return itemIcon;
  233. }
  234. renderEmptyNode() {
  235. const { emptyContent } = this.props;
  236. const wrapperCls = cls(prefixcls, {
  237. [`${prefixcls}-empty`]: true,
  238. });
  239. return (
  240. <ul className={wrapperCls}>
  241. <li className={`${prefixcls}-label ${prefixcls}-label-empty`} x-semi-prop="emptyContent">
  242. {emptyContent}
  243. </li>
  244. </ul>
  245. );
  246. }
  247. renderRealLabel = () => {
  248. const { renderLabel } = this.context;
  249. const { label, keyword, data, filtered, treeNodeFilterProp } = this.props;
  250. if (isFunction(renderLabel)) {
  251. return renderLabel(label, data);
  252. } else if (isString(label) && filtered && keyword) {
  253. return getHighLightTextHTML({
  254. sourceString: label,
  255. searchWords: [keyword],
  256. option: {
  257. highlightTag: 'span',
  258. highlightClassName: `${prefixcls}-highlight`,
  259. },
  260. } as any);
  261. } else {
  262. return label;
  263. }
  264. };
  265. setRef = (node: HTMLElement) => {
  266. this.refNode = node;
  267. };
  268. render() {
  269. const {
  270. eventKey,
  271. expanded,
  272. selected,
  273. checked,
  274. halfChecked,
  275. loading,
  276. active,
  277. level,
  278. empty,
  279. filtered,
  280. treeNodeFilterProp,
  281. display,
  282. style,
  283. ...rest
  284. } = this.props;
  285. if (empty) {
  286. return this.renderEmptyNode();
  287. }
  288. const {
  289. multiple,
  290. draggable,
  291. renderFullLabel,
  292. dragOverNodeKey,
  293. dropPosition,
  294. labelEllipsis
  295. } = this.context;
  296. const disabled = this.isDisabled();
  297. const dragOver = dragOverNodeKey === eventKey && dropPosition === 0;
  298. const dragOverGapTop = dragOverNodeKey === eventKey && dropPosition === -1;
  299. const dragOverGapBottom = dragOverNodeKey === eventKey && dropPosition === 1;
  300. const nodeCls = cls(prefixcls, {
  301. [`${prefixcls}-level-${level + 1}`]: true,
  302. [`${prefixcls}-collapsed`]: !expanded,
  303. [`${prefixcls}-disabled`]: Boolean(disabled),
  304. [`${prefixcls}-selected`]: selected,
  305. [`${prefixcls}-active`]: !multiple && active,
  306. [`${prefixcls}-ellipsis`]: labelEllipsis,
  307. [`${prefixcls}-drag-over`]: !disabled && dragOver,
  308. [`${prefixcls}-draggable`]: !disabled && draggable && !renderFullLabel,
  309. // When draggable + renderFullLabel is enabled, the default style
  310. [`${prefixcls}-fullLabel-draggable`]: !disabled && draggable && renderFullLabel,
  311. // When draggable + renderFullLabel is turned on, the style of dragover
  312. [`${prefixcls}-fullLabel-drag-over-gap-top`]: !disabled && dragOverGapTop && renderFullLabel,
  313. [`${prefixcls}-fullLabel-drag-over-gap-bottom`]: !disabled && dragOverGapBottom && renderFullLabel,
  314. });
  315. const labelProps = {
  316. onClick: this.onClick,
  317. onContextMenu: this.onContextMenu,
  318. onDoubleClick: this.onDoubleClick,
  319. className: nodeCls,
  320. onExpand: this.onExpand,
  321. data: rest.data,
  322. level,
  323. onCheck: this.onCheck,
  324. style,
  325. expandIcon: this.renderArrow(),
  326. checkStatus: {
  327. checked,
  328. halfChecked,
  329. },
  330. expandStatus: {
  331. expanded,
  332. loading,
  333. },
  334. filtered,
  335. searchWord: rest.keyword,
  336. };
  337. const dragProps = {
  338. onDoubleClick: this.onDoubleClick,
  339. onDragStart: draggable ? this.onDragStart : undefined,
  340. onDragEnter: draggable ? this.onDragEnter : undefined,
  341. onDragOver: draggable ? this.onDragOver : undefined,
  342. onDragLeave: draggable ? this.onDragLeave : undefined,
  343. onDrop: draggable ? this.onDrop : undefined,
  344. onDragEnd: draggable ? this.onDragEnd : undefined,
  345. draggable: (!disabled && draggable) || undefined,
  346. };
  347. if (renderFullLabel) {
  348. const customLabel = renderFullLabel({ ...labelProps });
  349. if (draggable) {
  350. // @ts-ignore skip cloneElement type check
  351. return React.cloneElement(customLabel, {
  352. ref: this.setRef,
  353. ...dragProps
  354. });
  355. } else {
  356. if (isEmpty(style)) {
  357. return customLabel;
  358. } else {
  359. // In virtualization, props.style will contain location information
  360. // @ts-ignore skip cloneElement type check
  361. return React.cloneElement(customLabel, {
  362. style: { ...get(customLabel, ['props', 'style']), ...style }
  363. });
  364. }
  365. }
  366. }
  367. const labelCls = cls(`${prefixcls}-label`, {
  368. [`${prefixcls}-drag-over-gap-top`]: !disabled && dragOverGapTop,
  369. [`${prefixcls}-drag-over-gap-bottom`]: !disabled && dragOverGapBottom,
  370. });
  371. const setsize = get(rest, ['data', 'children', 'length']);
  372. const posinset = isString(rest.pos) ? Number(rest.pos.split('-')[level+1]) + 1 : 1;
  373. return (
  374. <li
  375. className={nodeCls}
  376. role="treeitem"
  377. aria-disabled={disabled}
  378. aria-checked={checked}
  379. aria-selected={selected}
  380. aria-setsize={setsize}
  381. aria-posinset={posinset}
  382. aria-expanded={expanded}
  383. aria-level={level+1}
  384. data-key={eventKey}
  385. onClick={this.onClick}
  386. onKeyPress={this.handleliEnterPress}
  387. onContextMenu={this.onContextMenu}
  388. onDoubleClick={this.onDoubleClick}
  389. ref={this.setRef}
  390. style={style}
  391. {...dragProps}
  392. >
  393. {this.renderArrow()}
  394. <span
  395. className={labelCls}
  396. >
  397. {multiple ? this.renderCheckbox() : null}
  398. {this.renderIcon()}
  399. <span className={`${prefixcls}-label-text`}>{this.renderRealLabel()}</span>
  400. </span>
  401. </li>
  402. );
  403. }
  404. }