foundation.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  1. /**
  2. * The drag and drop handler implementation is referenced from rc-tree
  3. * https://github.com/react-component/tree
  4. */
  5. import { isUndefined, difference, pick, cloneDeep, get } from 'lodash';
  6. import BaseFoundation, { DefaultAdapter } from '../base/foundation';
  7. import {
  8. flattenTreeData,
  9. findDescendantKeys,
  10. findAncestorKeys,
  11. filter,
  12. normalizedArr,
  13. normalizeKeyList,
  14. getMotionKeys,
  15. calcCheckedKeysForChecked,
  16. calcCheckedKeysForUnchecked,
  17. calcCheckedKeys,
  18. getValueOrKey,
  19. getDragNodesKeys,
  20. calcDropRelativePosition,
  21. calcDropActualPosition
  22. } from './treeUtil';
  23. export interface BasicTreeNodeProps {
  24. [x: string]: any;
  25. expanded?: boolean;
  26. selected?: boolean;
  27. checked?: boolean;
  28. halfChecked?: boolean;
  29. active?: boolean;
  30. disabled?: boolean;
  31. loaded?: boolean;
  32. loading?: boolean;
  33. isLeaf?: boolean;
  34. pos?: string;
  35. children?: BasicTreeNodeData[];
  36. icon?: any;
  37. directory?: boolean;
  38. selectedKey?: string;
  39. motionKey?: string[] | string;
  40. eventKey?: string;
  41. }
  42. export interface BasicTreeNodeData {
  43. [x: string]: any;
  44. key: string;
  45. value?: number | string;
  46. label?: any;
  47. icon?: any;
  48. disabled?: boolean;
  49. isLeaf?: boolean;
  50. children?: BasicTreeNodeData[];
  51. }
  52. export interface BasicKeyEntities {
  53. [key: string]: BasicKeyEntity;
  54. }
  55. export interface BasicKeyEntity {
  56. children?: BasicKeyEntities;
  57. data?: BasicTreeNodeData;
  58. ind?: number;
  59. key?: string;
  60. level?: number;
  61. parent?: undefined | BasicKeyEntity;
  62. parentPos?: null | string;
  63. pos?: string;
  64. }
  65. export interface BasicDragTreeNode extends BasicTreeNodeData {
  66. expanded: boolean;
  67. /**
  68. * The positional relationship of the current node in the entire
  69. * treeData, such as the 0th node of the 2nd node of the 1st node
  70. * of the 0th layer: '0-1-2-0'
  71. */
  72. pos: string;
  73. }
  74. export interface BasicFlattenNode {
  75. _innerDataTag?: boolean;
  76. children?: BasicFlattenNode[];
  77. data?: BasicTreeNodeData;
  78. key?: string;
  79. label?: any;
  80. parent?: null | BasicFlattenNode;
  81. pos?: string;
  82. value?: string;
  83. }
  84. export interface BasicDragProps {
  85. event: any;
  86. node: BasicDragTreeNode;
  87. }
  88. export interface BasicDragEnterProps extends BasicDragProps {
  89. expandedKeys?: string[];
  90. }
  91. export type ExpandAction = false | 'click' | 'doubleClick';
  92. export type BasicValue = string | number | BasicTreeNodeData | Array<BasicTreeNodeData | string | number>;
  93. export interface BasicOnDragProps {
  94. event: any;
  95. node: BasicDragTreeNode;
  96. dragNode: BasicDragTreeNode;
  97. dragNodesKeys: string[];
  98. /**
  99. * dropPosition represents the position of the dragged node being
  100. * dropped in the current level. If inserted before the 0th node
  101. * of the same level, it is -1, after the 0th node, it is 1, and
  102. * it is 0 when it falls on it. And so on. With dropToGap, a more
  103. * complete judgment can be obtained.
  104. */
  105. dropPosition: number;
  106. /**
  107. * Indicates whether the dragged node is dropped between nodes, if
  108. * it is false, it is dropped above a node
  109. */
  110. dropToGap: boolean;
  111. }
  112. export interface BasicRenderFullLabelProps {
  113. /* Click the callback of the entire row to control the expansion behavior and selection */
  114. onClick: (e: any) => void;
  115. /* Right-click the callback for the entire row */
  116. onContextMenu: (e: any) => void;
  117. /* Double-click the entire line of callback */
  118. onDoubleClick: (e: any) => void;
  119. /* Class name, including built-in styles such as indentation, expand button, filter, disable, select, etc. */
  120. className: string;
  121. /* Expand callback */
  122. onExpand: (e: any) => void;
  123. /* The original data of the row */
  124. data: BasicTreeNodeData;
  125. /* The level of the line can be used to customize the indentation value */
  126. level: number;
  127. /* The style required for virtualization, if virtualization is used, the style must be assigned to the DOM element */
  128. style: any;
  129. /* Multi-select click callback */
  130. onCheck: (e: any) => void;
  131. /* icon of Expand button */
  132. expandIcon: any;
  133. /* Selected state */
  134. checkStatus: {
  135. /* Whether to select in the multi-select state */
  136. checked: boolean;
  137. /* Whether to half-select in the multi-select state */
  138. halfChecked: boolean;
  139. };
  140. /* Expand status */
  141. expandStatus: {
  142. /* Has it been expanded */
  143. expanded: boolean;
  144. /* Is it unfolding */
  145. loading: boolean;
  146. };
  147. }
  148. export interface BasicSearchRenderProps {
  149. className: string;
  150. placeholder: string;
  151. prefix: any;
  152. showClear?: boolean;
  153. value: string;
  154. onChange: (value: string) => void;
  155. }
  156. export interface TreeDataSimpleJson {
  157. [x: string]: string | TreeDataSimpleJson;
  158. }
  159. export interface Virtualize {
  160. itemSize: number;
  161. height?: number | string;
  162. width?: number | string;
  163. }
  164. export interface BasicTreeProps {
  165. autoExpandParent?: boolean;
  166. autoExpandWhenDragEnter?: boolean;
  167. blockNode?: boolean;
  168. children?: any;
  169. className?: string;
  170. expandAll?: boolean;
  171. defaultExpandAll?: boolean;
  172. defaultExpandedKeys?: string[];
  173. defaultValue?: BasicValue;
  174. directory?: boolean;
  175. disabled?: boolean;
  176. disableStrictly?: boolean;
  177. draggable?: boolean;
  178. emptyContent?: any;
  179. expandAction?: ExpandAction;
  180. expandedKeys?: string[];
  181. filterTreeNode?: boolean | ((inputValue: string, treeNodeString: string) => boolean);
  182. hideDraggingNode?: boolean;
  183. labelEllipsis?: boolean;
  184. leafOnly?: boolean;
  185. loadData?: (treeNode?: BasicTreeNodeData) => Promise<void>;
  186. loadedKeys?: string[];
  187. motion?: boolean;
  188. multiple?: boolean;
  189. onChange?: (value?: BasicValue) => void;
  190. onChangeWithObject?: boolean;
  191. onDoubleClick?: (e: any, node: BasicTreeNodeData) => void;
  192. onDragEnd?: (dragProps: BasicDragProps) => void;
  193. onDragEnter?: (dragEnterProps: BasicDragEnterProps) => void;
  194. onDragLeave?: (dragProps: BasicDragProps) => void;
  195. onDragOver?: (dragProps: BasicDragProps) => void;
  196. onDragStart?: (dragProps: BasicDragProps) => void;
  197. onDrop?: (onDragProps: BasicOnDragProps) => void;
  198. onExpand?: (expandedKeys: string[], expandedOtherProps: BasicExpandedOtherProps) => void;
  199. onLoad?: (loadedKeys?: Set<string>, treeNode?: BasicTreeNodeData) => void;
  200. onContextMenu?: (e: any, node: BasicTreeNodeData) => void;
  201. onSearch?: (sunInput: string) => void;
  202. onSelect?: (selectedKeys: string, selected: boolean, selectedNode: BasicTreeNodeData) => void;
  203. renderDraggingNode?: (nodeInstance: HTMLElement, node: BasicTreeNodeData) => HTMLElement;
  204. renderFullLabel?: (renderFullLabelProps: BasicRenderFullLabelProps) => any;
  205. renderLabel?: (label?: any, treeNode?: BasicTreeNodeData) => any;
  206. searchClassName?: string;
  207. searchPlaceholder?: string;
  208. searchRender?: ((searchRenderProps: BasicSearchRenderProps) => any) | false;
  209. searchStyle?: any;
  210. showClear?: boolean;
  211. showFilteredOnly?: boolean;
  212. style?: any;
  213. treeData?: BasicTreeNodeData[];
  214. treeDataSimpleJson?: TreeDataSimpleJson;
  215. treeNodeFilterProp?: string;
  216. value?: BasicValue;
  217. virtualize?: Virtualize;
  218. icon?: any;
  219. 'aria-label'?: string;
  220. }
  221. /* Data maintained internally. At the React framework level, corresponding to state */
  222. export interface BasicTreeInnerData {
  223. /* The input content of the input box */
  224. inputValue: string;
  225. /* keyEntities */
  226. keyEntities: BasicKeyEntities;
  227. /* treeData */
  228. treeData: BasicTreeNodeData[];
  229. /* Expanded node */
  230. flattenNodes: BasicFlattenNode[];
  231. /* The selected node when single-selected */
  232. selectedKeys: string[];
  233. /* Select all nodes in multiple selection */
  234. checkedKeys: Set<string>;
  235. /* Half-selected node when multiple selection */
  236. halfCheckedKeys: Set<string>;
  237. /* Animation node */
  238. motionKeys: Set<string>;
  239. /* Animation type */
  240. motionType: string;
  241. /* Expand node */
  242. expandedKeys: Set<string>;
  243. /* Searched node */
  244. filteredKeys: Set<string>;
  245. /* The ancestor node expanded because of the searched node*/
  246. filteredExpandedKeys: Set<string>;
  247. /* Because of the searched node, the expanded ancestor node + the searched node + the descendant nodes of the searched node */
  248. filteredShownKeys: Set<string>;
  249. /* Prev props */
  250. prevProps: null | BasicTreeProps;
  251. /* loaded nodes */
  252. loadedKeys: Set<string>;
  253. /* loading nodes */
  254. loadingKeys: Set<string>;
  255. /* cache */
  256. cachedFlattenNodes: BasicFlattenNode[] | undefined;
  257. cachedKeyValuePairs: { [x: string]: string };
  258. /* Strictly disabled node */
  259. disabledKeys: Set<string>;
  260. /* Is dragging */
  261. dragging: boolean;
  262. /* Dragged node */
  263. dragNodesKeys: Set<string>;
  264. /* DragOver node */
  265. dragOverNodeKey: string[] | string | null;
  266. /* Drag position */
  267. dropPosition: number | null;
  268. }
  269. export interface BasicExpandedOtherProps {
  270. expanded: boolean;
  271. node: BasicTreeNodeData;
  272. }
  273. export interface TreeAdapter extends DefaultAdapter<BasicTreeProps, BasicTreeInnerData> {
  274. updateInputValue: (value: string) => void;
  275. focusInput: () => void;
  276. updateState: (states: Partial<BasicTreeInnerData>) => void;
  277. notifyExpand: (expandedKeys: Set<string>, { expanded: bool, node }: BasicExpandedOtherProps) => void;
  278. notifySelect: (selectKey: string, bool: boolean, node: BasicTreeNodeData) => void;
  279. notifyChange: (value: BasicValue) => void;
  280. notifySearch: (input: string) => void;
  281. notifyRightClick: (e: any, node: BasicTreeNodeData) => void;
  282. notifyDoubleClick: (e: any, node: BasicTreeNodeData) => void;
  283. cacheFlattenNodes: (bool: boolean) => void;
  284. setDragNode: (treeNode: any) => void;
  285. }
  286. export default class TreeFoundation extends BaseFoundation<TreeAdapter, BasicTreeProps, BasicTreeInnerData> {
  287. delayedDragEnterLogic: any;
  288. constructor(adapter: TreeAdapter) {
  289. super({
  290. ...adapter,
  291. });
  292. }
  293. _isMultiple() {
  294. return this.getProp('multiple');
  295. }
  296. _isAnimated() {
  297. return this.getProp('motion');
  298. }
  299. _isDisabled(treeNode: BasicTreeNodeProps = {}) {
  300. return this.getProp('disabled') || treeNode.disabled;
  301. }
  302. _isExpandControlled() {
  303. return !isUndefined(this.getProp('expandedKeys'));
  304. }
  305. _isLoadControlled() {
  306. return !isUndefined(this.getProp('loadedKeys'));
  307. }
  308. _isFilterable() {
  309. // filter can be boolean or function
  310. return Boolean(this.getProp('filterTreeNode'));
  311. }
  312. _showFilteredOnly() {
  313. const { inputValue } = this.getStates();
  314. const { showFilteredOnly } = this.getProps();
  315. return Boolean(inputValue) && showFilteredOnly;
  316. }
  317. getCopyFromState(items: string[] | string) {
  318. const res: Partial<BasicTreeInnerData> = {};
  319. normalizedArr(items).forEach(key => {
  320. res[key] = cloneDeep(this.getState(key));
  321. });
  322. return res;
  323. }
  324. getTreeNodeProps(key: string) {
  325. const {
  326. expandedKeys = new Set([]),
  327. selectedKeys = [],
  328. checkedKeys = new Set([]),
  329. halfCheckedKeys = new Set([]),
  330. keyEntities = {},
  331. filteredKeys = new Set([]),
  332. inputValue = '',
  333. loadedKeys = new Set([]),
  334. loadingKeys = new Set([]),
  335. filteredExpandedKeys = new Set([]),
  336. disabledKeys = new Set([]),
  337. } = this.getStates();
  338. const { treeNodeFilterProp } = this.getProps();
  339. const entity = keyEntities[key];
  340. const notExist = !entity;
  341. if (notExist) {
  342. return null;
  343. }
  344. const isSearching = Boolean(inputValue);
  345. const treeNodeProps: BasicTreeNodeProps = {
  346. eventKey: key,
  347. expanded: isSearching ? filteredExpandedKeys.has(key) : expandedKeys.has(key),
  348. selected: selectedKeys.includes(key),
  349. checked: checkedKeys.has(key),
  350. halfChecked: halfCheckedKeys.has(key),
  351. pos: String(entity ? entity.pos : ''),
  352. level: entity.level,
  353. filtered: filteredKeys.has(key),
  354. loading: loadingKeys.has(key) && !loadedKeys.has(key),
  355. loaded: loadedKeys.has(key),
  356. keyword: inputValue,
  357. treeNodeFilterProp,
  358. };
  359. if (this.getProp('disableStrictly') && disabledKeys.has(key)) {
  360. treeNodeProps.disabled = true;
  361. }
  362. return treeNodeProps;
  363. }
  364. notifyJsonChange(key: string[] | string, e: any) {
  365. const data = this.getProp('treeDataSimpleJson');
  366. const selectedPath = normalizedArr(key).map(i => i.replace('-', '.'));
  367. const value = pick(data, selectedPath);
  368. this._adapter.notifyChange(value as BasicValue);
  369. }
  370. notifyMultipleChange(key: string[] | string, e: any) {
  371. const { keyEntities } = this.getStates();
  372. const { leafOnly } = this.getProps();
  373. let value;
  374. const keyList = normalizeKeyList(key, keyEntities, leafOnly);
  375. if (this.getProp('onChangeWithObject')) {
  376. value = keyList.map((itemKey: string) => keyEntities[itemKey].data);
  377. } else {
  378. value = getValueOrKey(keyList.map((itemKey: string) => keyEntities[itemKey].data));
  379. }
  380. this._adapter.notifyChange(value);
  381. }
  382. notifyChange(key: string[] | string, e: any) {
  383. const isMultiple = this._isMultiple();
  384. const { keyEntities } = this.getStates();
  385. if (this.getProp('treeDataSimpleJson')) {
  386. this.notifyJsonChange(key, e);
  387. } else if (isMultiple) {
  388. this.notifyMultipleChange(key, e);
  389. } else {
  390. let value;
  391. if (this.getProp('onChangeWithObject')) {
  392. value = get(keyEntities, key).data;
  393. } else {
  394. const { data } = get(keyEntities, key);
  395. value = getValueOrKey(data);
  396. }
  397. this._adapter.notifyChange(value);
  398. }
  399. }
  400. handleInputChange(sugInput: string) {
  401. // Input is a controlled component, so the value value needs to be updated
  402. this._adapter.updateInputValue(sugInput);
  403. const { expandedKeys, selectedKeys, keyEntities, treeData } = this.getStates();
  404. const { showFilteredOnly, filterTreeNode, treeNodeFilterProp } = this.getProps();
  405. let filteredOptsKeys: string[] = [];
  406. let expandedOptsKeys: string[] = [];
  407. let flattenNodes: BasicFlattenNode[] = [];
  408. let filteredShownKeys = new Set([]);
  409. if (!sugInput) {
  410. expandedOptsKeys = findAncestorKeys(selectedKeys, keyEntities);
  411. expandedOptsKeys.forEach(item => expandedKeys.add(item));
  412. flattenNodes = flattenTreeData(treeData, expandedKeys);
  413. } else {
  414. filteredOptsKeys = Object.values(keyEntities)
  415. .filter((item: BasicKeyEntity) => filter(sugInput, item.data, filterTreeNode, treeNodeFilterProp))
  416. .map((item: BasicKeyEntity) => item.key);
  417. expandedOptsKeys = findAncestorKeys(filteredOptsKeys, keyEntities, false);
  418. const shownChildKeys = findDescendantKeys(filteredOptsKeys, keyEntities, true);
  419. filteredShownKeys = new Set([...shownChildKeys, ...expandedOptsKeys]);
  420. flattenNodes = flattenTreeData(
  421. treeData,
  422. new Set(expandedOptsKeys),
  423. showFilteredOnly && filteredShownKeys
  424. );
  425. }
  426. this._adapter.notifySearch(sugInput);
  427. this._adapter.updateState({
  428. expandedKeys,
  429. flattenNodes,
  430. motionKeys: new Set([]),
  431. filteredKeys: new Set(filteredOptsKeys),
  432. filteredExpandedKeys: new Set(expandedOptsKeys),
  433. filteredShownKeys,
  434. });
  435. }
  436. handleNodeSelect(e: any, treeNode: BasicTreeNodeProps) {
  437. const isDisabled = this._isDisabled(treeNode);
  438. if (isDisabled) {
  439. return;
  440. }
  441. if (!this._isMultiple()) {
  442. this.handleSingleSelect(e, treeNode);
  443. } else {
  444. this.handleMultipleSelect(e, treeNode);
  445. }
  446. }
  447. handleNodeRightClick(e: any, treeNode: BasicTreeNodeProps) {
  448. this._adapter.notifyRightClick(e, treeNode.data);
  449. }
  450. handleNodeDoubleClick(e: any, treeNode: BasicTreeNodeProps) {
  451. this._adapter.notifyDoubleClick(e, treeNode.data);
  452. }
  453. handleSingleSelect(e: any, treeNode: BasicTreeNodeProps) {
  454. let { selectedKeys } = this.getCopyFromState('selectedKeys');
  455. const { selected, eventKey, data } = treeNode;
  456. const targetSelected = !selected;
  457. this._adapter.notifySelect(eventKey, true, data);
  458. if (!targetSelected) {
  459. return;
  460. }
  461. if (!selectedKeys.includes(eventKey)) {
  462. selectedKeys = [eventKey];
  463. this.notifyChange(eventKey, e);
  464. if (!this._isControlledComponent()) {
  465. this._adapter.updateState({ selectedKeys });
  466. }
  467. }
  468. }
  469. calcCheckedKeys(eventKey: string, targetStatus: boolean) {
  470. const { keyEntities } = this.getStates();
  471. const { checkedKeys, halfCheckedKeys } = this.getCopyFromState(['checkedKeys', 'halfCheckedKeys']);
  472. return targetStatus ?
  473. calcCheckedKeysForChecked(eventKey, keyEntities, checkedKeys, halfCheckedKeys) :
  474. calcCheckedKeysForUnchecked(eventKey, keyEntities, checkedKeys, halfCheckedKeys);
  475. }
  476. /*
  477. * Compute the checked state of the node
  478. */
  479. calcChekcedStatus(targetStatus: boolean, eventKey: string) {
  480. // From checked to unchecked, you can change it directly
  481. if (!targetStatus) {
  482. return targetStatus;
  483. }
  484. // Starting from unchecked, you need to judge according to the descendant nodes
  485. const { checkedKeys, keyEntities, disabledKeys } = this.getStates();
  486. const descendantKeys = normalizeKeyList(findDescendantKeys([eventKey], keyEntities, false), keyEntities, true);
  487. const hasDisabled = descendantKeys.some((key: string) => disabledKeys.has(key));
  488. // If the descendant nodes are not disabled, they will be directly changed to checked
  489. if (!hasDisabled) {
  490. return targetStatus;
  491. }
  492. // If all descendant nodes that are not disabled are selected, return unchecked, otherwise, return checked
  493. const nonDisabledKeys = descendantKeys.filter((key: string) => !disabledKeys.has(key));
  494. const allChecked = nonDisabledKeys.every((key: string) => checkedKeys.has(key));
  495. return !allChecked;
  496. }
  497. /*
  498. * In strict disable mode, calculate the nodes of checked and halfCheckedKeys and return their corresponding keys
  499. */
  500. calcNonDisabedCheckedKeys(eventKey: string, targetStatus: boolean) {
  501. const { keyEntities, disabledKeys } = this.getStates();
  502. const { checkedKeys } = this.getCopyFromState(['checkedKeys']);
  503. const descendantKeys = normalizeKeyList(findDescendantKeys([eventKey], keyEntities, false), keyEntities, true);
  504. const hasDisabled = descendantKeys.some((key: string) => disabledKeys.has(key));
  505. // If none of the descendant nodes are disabled, follow the normal logic
  506. if (!hasDisabled) {
  507. return this.calcCheckedKeys(eventKey, targetStatus);
  508. }
  509. const nonDisabled = descendantKeys.filter((key: string) => !disabledKeys.has(key));
  510. const newCheckedKeys = targetStatus ?
  511. [...nonDisabled, ...checkedKeys] :
  512. difference(normalizeKeyList([...checkedKeys], keyEntities, true), nonDisabled);
  513. return calcCheckedKeys(newCheckedKeys, keyEntities);
  514. }
  515. /*
  516. * Handle the selection event in the case of multiple selection
  517. */
  518. handleMultipleSelect(e: any, treeNode: BasicTreeNodeProps) {
  519. const { disableStrictly } = this.getProps();
  520. // eventKey: The key value of the currently clicked node
  521. const { checked, eventKey, data } = treeNode;
  522. // Find the checked state of the current node
  523. const targetStatus = disableStrictly ? this.calcChekcedStatus(!checked, eventKey) : !checked;
  524. const { checkedKeys, halfCheckedKeys } = disableStrictly ?
  525. this.calcNonDisabedCheckedKeys(eventKey, targetStatus) :
  526. this.calcCheckedKeys(eventKey, targetStatus);
  527. this._adapter.notifySelect(eventKey, targetStatus, data);
  528. this.notifyChange([...checkedKeys], e);
  529. if (!this._isControlledComponent()) {
  530. this._adapter.updateState({ checkedKeys, halfCheckedKeys });
  531. }
  532. }
  533. setExpandedStatus(treeNode: BasicTreeNodeProps) {
  534. const { inputValue, treeData, filteredShownKeys, keyEntities } = this.getStates();
  535. const isSearching = Boolean(inputValue);
  536. const showFilteredOnly = this._showFilteredOnly();
  537. const expandedStateKey = isSearching ? 'filteredExpandedKeys' : 'expandedKeys';
  538. const expandedKeys = this.getCopyFromState(expandedStateKey)[expandedStateKey];
  539. let motionType = 'show';
  540. const { eventKey, expanded, data } = treeNode;
  541. if (!expanded) {
  542. expandedKeys.add(eventKey);
  543. } else if (expandedKeys.has(eventKey)) {
  544. expandedKeys.delete(eventKey);
  545. motionType = 'hide';
  546. }
  547. this._adapter.cacheFlattenNodes(motionType === 'hide' && this._isAnimated());
  548. if (!this._isExpandControlled()) {
  549. const flattenNodes = flattenTreeData(
  550. treeData,
  551. expandedKeys,
  552. isSearching && showFilteredOnly && filteredShownKeys
  553. );
  554. const motionKeys = this._isAnimated() ? getMotionKeys(eventKey, expandedKeys, keyEntities) : [];
  555. const newState = {
  556. [expandedStateKey]: expandedKeys,
  557. flattenNodes,
  558. motionKeys: new Set(motionKeys),
  559. motionType,
  560. };
  561. this._adapter.updateState(newState);
  562. }
  563. return {
  564. expandedKeys,
  565. expanded: !expanded,
  566. data,
  567. };
  568. }
  569. handleNodeExpand(e: any, treeNode: BasicTreeNodeProps) {
  570. const { loadData } = this.getProps();
  571. if (!loadData && (!treeNode.children || !treeNode.children.length)) {
  572. return;
  573. }
  574. const { expandedKeys, data, expanded } = this.setExpandedStatus(treeNode);
  575. this._adapter.notifyExpand(expandedKeys, {
  576. expanded,
  577. node: data,
  578. });
  579. }
  580. // eslint-disable-next-line max-len
  581. handleNodeLoad(loadedKeys: Set<string>, loadingKeys: Set<string>, data: BasicTreeNodeData, resolve: (value?: any) => void) {
  582. const { loadData, onLoad } = this.getProps();
  583. const { key } = data;
  584. if (!loadData || loadedKeys.has(key) || loadingKeys.has(key)) {
  585. return {};
  586. }
  587. // Process the loaded data
  588. loadData(data).then(() => {
  589. const {
  590. loadedKeys: prevLoadedKeys,
  591. loadingKeys: prevLoadingKeys
  592. } = this.getCopyFromState(['loadedKeys', 'loadingKeys']);
  593. const newLoadedKeys = prevLoadedKeys.add(key);
  594. const newLoadingKeys = new Set([...prevLoadingKeys]);
  595. newLoadingKeys.delete(key);
  596. // onLoad should be triggered before internal setState to avoid `loadData` being triggered twice
  597. onLoad && onLoad(newLoadedKeys, data);
  598. if (!this._isLoadControlled()) {
  599. this._adapter.updateState({
  600. loadedKeys: newLoadedKeys,
  601. });
  602. }
  603. this._adapter.setState({
  604. loadingKeys: newLoadingKeys,
  605. } as any);
  606. resolve();
  607. });
  608. return {
  609. loadingKeys: loadingKeys.add(key),
  610. };
  611. }
  612. // Drag and drop related processing logic
  613. getDragEventNodeData(node: BasicTreeNodeData) {
  614. return {
  615. ...node.data,
  616. ...pick(node, ['expanded', 'pos', 'children']),
  617. };
  618. }
  619. triggerDragEvent(name: string, event: any, node: BasicTreeNodeData, extra = {}) {
  620. const callEvent = this.getProp(name);
  621. callEvent &&
  622. callEvent({
  623. event,
  624. node: this.getDragEventNodeData(node),
  625. ...extra,
  626. });
  627. }
  628. clearDragState = () => {
  629. this._adapter.updateState({
  630. dragOverNodeKey: '',
  631. dragging: false,
  632. });
  633. };
  634. handleNodeDragStart(e: any, treeNode: BasicTreeNodeData) {
  635. const { keyEntities } = this.getStates();
  636. const { hideDraggingNode, renderDraggingNode } = this.getProps();
  637. const { eventKey, nodeInstance, data } = treeNode;
  638. if (hideDraggingNode || renderDraggingNode) {
  639. let dragImg;
  640. if (typeof renderDraggingNode === 'function') {
  641. dragImg = renderDraggingNode(nodeInstance, data);
  642. } else if (hideDraggingNode) {
  643. dragImg = nodeInstance.cloneNode(true);
  644. dragImg.style.opacity = 0;
  645. }
  646. document.body.appendChild(dragImg);
  647. e.dataTransfer.setDragImage(dragImg, 0, 0);
  648. }
  649. this._adapter.setDragNode(treeNode);
  650. this._adapter.updateState({
  651. dragging: true,
  652. dragNodesKeys: new Set(getDragNodesKeys(eventKey, keyEntities)),
  653. });
  654. this.triggerDragEvent('onDragStart', e, treeNode);
  655. }
  656. handleNodeDragEnter(e: any, treeNode: BasicTreeNodeData, dragNode: any) {
  657. const { dragging, dragNodesKeys } = this.getStates();
  658. const { autoExpandWhenDragEnter } = this.getProps();
  659. const { pos, eventKey, expanded } = treeNode;
  660. if (!dragNode || dragNodesKeys.has(eventKey)) {
  661. return;
  662. }
  663. const dropPosition = calcDropRelativePosition(e, treeNode);
  664. // If the drag node is itself, skip
  665. if (dragNode.eventKey === eventKey && dropPosition === 0) {
  666. this._adapter.updateState({
  667. dragOverNodeKey: '',
  668. dropPosition: null,
  669. });
  670. return;
  671. }
  672. // Trigger dragenter after clearing the prev state in dragleave
  673. setTimeout(() => {
  674. this._adapter.updateState({
  675. dragOverNodeKey: eventKey,
  676. dropPosition,
  677. });
  678. // If autoExpand is already expanded or not allowed, trigger the event and return
  679. if (!autoExpandWhenDragEnter || expanded) {
  680. this.triggerDragEvent('onDragEnter', e, treeNode);
  681. return;
  682. }
  683. // Side effects of delayed drag
  684. if (!this.delayedDragEnterLogic) {
  685. this.delayedDragEnterLogic = {};
  686. }
  687. Object.keys(this.delayedDragEnterLogic).forEach(key => {
  688. clearTimeout(this.delayedDragEnterLogic[key]);
  689. });
  690. this.delayedDragEnterLogic[pos] = window.setTimeout(() => {
  691. if (!dragging) {
  692. return;
  693. }
  694. const { expandedKeys: newExpandedKeys } = this.setExpandedStatus(treeNode);
  695. this.triggerDragEvent('onDragEnter', e, treeNode, { expandedKeys: [...newExpandedKeys] });
  696. }, 400);
  697. }, 0);
  698. }
  699. handleNodeDragOver(e: any, treeNode: BasicTreeNodeData, dragNode: any) {
  700. const { dropPosition, dragNodesKeys, dragOverNodeKey } = this.getStates();
  701. const { eventKey } = treeNode;
  702. if (dragNodesKeys.has(eventKey)) {
  703. return;
  704. }
  705. // Update the drag position
  706. if (dragNode && eventKey === dragOverNodeKey) {
  707. const newPos = calcDropRelativePosition(e, treeNode);
  708. if (dropPosition === newPos) {
  709. return;
  710. }
  711. this._adapter.updateState({
  712. dropPosition: newPos,
  713. });
  714. }
  715. this.triggerDragEvent('onDragOver', e, treeNode);
  716. }
  717. handleNodeDragLeave(e: any, treeNode: BasicTreeNodeData) {
  718. this._adapter.updateState({
  719. dragOverNodeKey: '',
  720. });
  721. this.triggerDragEvent('onDragLeave', e, treeNode);
  722. }
  723. handleNodeDragEnd(e: any, treeNode: BasicTreeNodeData) {
  724. this.clearDragState();
  725. this.triggerDragEvent('onDragEnd', e, treeNode);
  726. this._adapter.setDragNode(null);
  727. }
  728. handleNodeDrop(e: any, treeNode: BasicTreeNodeData, dragNode: any) {
  729. const { dropPosition, dragNodesKeys } = this.getStates();
  730. const { eventKey, pos } = treeNode;
  731. this.clearDragState();
  732. if (dragNodesKeys.has(eventKey)) {
  733. return;
  734. }
  735. const dropRes = {
  736. dragNode: dragNode ? this.getDragEventNodeData(dragNode) : null,
  737. dragNodesKeys: [...dragNodesKeys],
  738. dropPosition: calcDropActualPosition(pos, dropPosition),
  739. dropToGap: dropPosition !== 0,
  740. };
  741. this.triggerDragEvent('onDrop', e, treeNode, dropRes);
  742. this._adapter.setDragNode(null);
  743. }
  744. }