foundation.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  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-es';
  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[], expanedOtherProps: 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. }
  220. /* Data maintained internally. At the React framework level, corresponding to state */
  221. export interface BasicTreeInnerData {
  222. /* The input content of the input box */
  223. inputValue: string;
  224. /* keyEntities */
  225. keyEntities: BasicKeyEntities;
  226. /* treeData */
  227. treeData: BasicTreeNodeData[];
  228. /* Expanded node */
  229. flattenNodes: BasicFlattenNode[];
  230. /* The selected node when single-selected */
  231. selectedKeys: string[];
  232. /* Select all nodes in multiple selection */
  233. checkedKeys: Set<string>;
  234. /* Half-selected node when multiple selection */
  235. halfCheckedKeys: Set<string>;
  236. /* Animation node */
  237. motionKeys: Set<string>;
  238. /* Animation type */
  239. motionType: string;
  240. /* Expand node */
  241. expandedKeys: Set<string>;
  242. /* Searched node */
  243. filteredKeys: Set<string>;
  244. /* The ancestor node expanded because of the searched node*/
  245. filteredExpandedKeys: Set<string>;
  246. /* Because of the searched node, the expanded ancestor node + the searched node + the descendant nodes of the searched node */
  247. filteredShownKeys: Set<string>;
  248. /* Prev props */
  249. prevProps: null | BasicTreeProps;
  250. /* loaded nodes */
  251. loadedKeys: Set<string>;
  252. /* loading nodes */
  253. loadingKeys: Set<string>;
  254. /* cache */
  255. cachedFlattenNodes: BasicFlattenNode[] | undefined;
  256. cachedKeyValuePairs: { [x: string]: string };
  257. /* Strictly disabled node */
  258. disabledKeys: Set<string>;
  259. /* Is dragging */
  260. dragging: boolean;
  261. /* Dragged node */
  262. dragNodesKeys: Set<string>;
  263. /* DragOver node */
  264. dragOverNodeKey: string[] | string | null;
  265. /* Drag position */
  266. dropPosition: number | null;
  267. }
  268. export interface BasicExpandedOtherProps {
  269. expanded: boolean;
  270. node: BasicTreeNodeData;
  271. }
  272. export interface TreeAdapter extends DefaultAdapter<BasicTreeProps, BasicTreeInnerData> {
  273. updateInputValue: (value: string) => void;
  274. focusInput: () => void;
  275. updateState: (states: Partial<BasicTreeInnerData>) => void;
  276. notifyExpand: (expandedKeys: Set<string>, { expanded: bool, node }: BasicExpandedOtherProps) => void;
  277. notifySelect: (selectKey: string, bool: boolean, node: BasicTreeNodeData) => void;
  278. notifyChange: (value: BasicValue) => void;
  279. notifySearch: (input: string) => void;
  280. notifyRightClick: (e: any, node: BasicTreeNodeData) => void;
  281. notifyDoubleClick: (e: any, node: BasicTreeNodeData) => void;
  282. cacheFlattenNodes: (bool: boolean) => void;
  283. setDragNode: (treeNode: any) => void;
  284. }
  285. export default class TreeFoundation extends BaseFoundation<TreeAdapter, BasicTreeProps, BasicTreeInnerData> {
  286. delayedDragEnterLogic: any;
  287. constructor(adapter: TreeAdapter) {
  288. super({
  289. ...adapter,
  290. });
  291. }
  292. _isMultiple() {
  293. return this.getProp('multiple');
  294. }
  295. _isAnimated() {
  296. return this.getProp('motion');
  297. }
  298. _isDisabled(treeNode: BasicTreeNodeProps = {}) {
  299. return this.getProp('disabled') || treeNode.disabled;
  300. }
  301. _isExpandControlled() {
  302. return !isUndefined(this.getProp('expandedKeys'));
  303. }
  304. _isLoadControlled() {
  305. return !isUndefined(this.getProp('loadedKeys'));
  306. }
  307. _isFilterable() {
  308. // filter can be boolean or function
  309. return Boolean(this.getProp('filterTreeNode'));
  310. }
  311. _showFilteredOnly() {
  312. const { inputValue } = this.getStates();
  313. const { showFilteredOnly } = this.getProps();
  314. return Boolean(inputValue) && showFilteredOnly;
  315. }
  316. getCopyFromState(items: string[] | string) {
  317. const res: Partial<BasicTreeInnerData> = {};
  318. normalizedArr(items).forEach(key => {
  319. res[key] = cloneDeep(this.getState(key));
  320. });
  321. return res;
  322. }
  323. getTreeNodeProps(key: string) {
  324. const {
  325. expandedKeys = new Set([]),
  326. selectedKeys = [],
  327. checkedKeys = new Set([]),
  328. halfCheckedKeys = new Set([]),
  329. keyEntities = {},
  330. filteredKeys = new Set([]),
  331. inputValue = '',
  332. loadedKeys = new Set([]),
  333. loadingKeys = new Set([]),
  334. filteredExpandedKeys = new Set([]),
  335. disabledKeys = new Set([]),
  336. } = this.getStates();
  337. const { treeNodeFilterProp } = this.getProps();
  338. const entity = keyEntities[key];
  339. const notExist = !entity;
  340. if (notExist) {
  341. return null;
  342. }
  343. const isSearching = Boolean(inputValue);
  344. const treeNodeProps: BasicTreeNodeProps = {
  345. eventKey: key,
  346. expanded: isSearching ? filteredExpandedKeys.has(key) : expandedKeys.has(key),
  347. selected: selectedKeys.includes(key),
  348. checked: checkedKeys.has(key),
  349. halfChecked: halfCheckedKeys.has(key),
  350. pos: String(entity ? entity.pos : ''),
  351. level: entity.level,
  352. filtered: filteredKeys.has(key),
  353. loading: loadingKeys.has(key) && !loadedKeys.has(key),
  354. loaded: loadedKeys.has(key),
  355. keyword: inputValue,
  356. treeNodeFilterProp,
  357. };
  358. if (this.getProp('disableStrictly') && disabledKeys.has(key)) {
  359. treeNodeProps.disabled = true;
  360. }
  361. return treeNodeProps;
  362. }
  363. notifyJsonChange(key: string[] | string, e: any) {
  364. const data = this.getProp('treeDataSimpleJson');
  365. const selectedPath = normalizedArr(key).map(i => i.replace('-', '.'));
  366. const value = pick(data, selectedPath);
  367. this._adapter.notifyChange(value as BasicValue);
  368. }
  369. notifyMultipleChange(key: string[] | string, e: any) {
  370. const { keyEntities } = this.getStates();
  371. const { leafOnly } = this.getProps();
  372. let value;
  373. const keyList = normalizeKeyList(key, keyEntities, leafOnly);
  374. if (this.getProp('onChangeWithObject')) {
  375. value = keyList.map((itemKey: string) => keyEntities[itemKey].data);
  376. } else {
  377. value = getValueOrKey(keyList.map((itemKey: string) => keyEntities[itemKey].data));
  378. }
  379. this._adapter.notifyChange(value);
  380. }
  381. notifyChange(key: string[] | string, e: any) {
  382. const isMultiple = this._isMultiple();
  383. const { keyEntities } = this.getStates();
  384. if (this.getProp('treeDataSimpleJson')) {
  385. this.notifyJsonChange(key, e);
  386. } else if (isMultiple) {
  387. this.notifyMultipleChange(key, e);
  388. } else {
  389. let value;
  390. if (this.getProp('onChangeWithObject')) {
  391. value = get(keyEntities, key).data;
  392. } else {
  393. const { data } = get(keyEntities, key);
  394. value = getValueOrKey(data);
  395. }
  396. this._adapter.notifyChange(value);
  397. }
  398. }
  399. handleInputChange(sugInput: string) {
  400. // Input is a controlled component, so the value value needs to be updated
  401. this._adapter.updateInputValue(sugInput);
  402. const { expandedKeys, selectedKeys, keyEntities, treeData } = this.getStates();
  403. const { showFilteredOnly, filterTreeNode, treeNodeFilterProp } = this.getProps();
  404. let filteredOptsKeys: string[] = [];
  405. let expandedOptsKeys: string[] = [];
  406. let flattenNodes: BasicFlattenNode[] = [];
  407. let filteredShownKeys = new Set([]);
  408. if (!sugInput) {
  409. expandedOptsKeys = findAncestorKeys(selectedKeys, keyEntities);
  410. expandedOptsKeys.forEach(item => expandedKeys.add(item));
  411. flattenNodes = flattenTreeData(treeData, expandedKeys);
  412. } else {
  413. filteredOptsKeys = Object.values(keyEntities)
  414. .filter((item: BasicKeyEntity) => filter(sugInput, item.data, filterTreeNode, treeNodeFilterProp))
  415. .map((item: BasicKeyEntity) => item.key);
  416. expandedOptsKeys = findAncestorKeys(filteredOptsKeys, keyEntities, false);
  417. const shownChildKeys = findDescendantKeys(filteredOptsKeys, keyEntities, true);
  418. filteredShownKeys = new Set([...shownChildKeys, ...expandedOptsKeys]);
  419. flattenNodes = flattenTreeData(
  420. treeData,
  421. new Set(expandedOptsKeys),
  422. showFilteredOnly && filteredShownKeys
  423. );
  424. }
  425. this._adapter.notifySearch(sugInput);
  426. this._adapter.updateState({
  427. expandedKeys,
  428. flattenNodes,
  429. motionKeys: new Set([]),
  430. filteredKeys: new Set(filteredOptsKeys),
  431. filteredExpandedKeys: new Set(expandedOptsKeys),
  432. filteredShownKeys,
  433. });
  434. }
  435. handleNodeSelect(e: any, treeNode: BasicTreeNodeProps) {
  436. const isDisabled = this._isDisabled(treeNode);
  437. if (isDisabled) {
  438. return;
  439. }
  440. if (!this._isMultiple()) {
  441. this.handleSingleSelect(e, treeNode);
  442. } else {
  443. this.handleMultipleSelect(e, treeNode);
  444. }
  445. }
  446. handleNodeRightClick(e: any, treeNode: BasicTreeNodeProps) {
  447. this._adapter.notifyRightClick(e, treeNode.data);
  448. }
  449. handleNodeDoubleClick(e: any, treeNode: BasicTreeNodeProps) {
  450. this._adapter.notifyDoubleClick(e, treeNode.data);
  451. }
  452. handleSingleSelect(e: any, treeNode: BasicTreeNodeProps) {
  453. let { selectedKeys } = this.getCopyFromState('selectedKeys');
  454. const { selected, eventKey, data } = treeNode;
  455. const targetSelected = !selected;
  456. this._adapter.notifySelect(eventKey, true, data);
  457. if (!targetSelected) {
  458. return;
  459. }
  460. if (!selectedKeys.includes(eventKey)) {
  461. selectedKeys = [eventKey];
  462. this.notifyChange(eventKey, e);
  463. if (!this._isControlledComponent()) {
  464. this._adapter.updateState({ selectedKeys });
  465. }
  466. }
  467. }
  468. calcCheckedKeys(eventKey: string, targetStatus: boolean) {
  469. const { keyEntities } = this.getStates();
  470. const { checkedKeys, halfCheckedKeys } = this.getCopyFromState(['checkedKeys', 'halfCheckedKeys']);
  471. return targetStatus ?
  472. calcCheckedKeysForChecked(eventKey, keyEntities, checkedKeys, halfCheckedKeys) :
  473. calcCheckedKeysForUnchecked(eventKey, keyEntities, checkedKeys, halfCheckedKeys);
  474. }
  475. /*
  476. * Compute the checked state of the node
  477. */
  478. calcChekcedStatus(targetStatus: boolean, eventKey: string) {
  479. // From checked to unchecked, you can change it directly
  480. if (!targetStatus) {
  481. return targetStatus;
  482. }
  483. // Starting from unchecked, you need to judge according to the descendant nodes
  484. const { checkedKeys, keyEntities, disabledKeys } = this.getStates();
  485. const descendantKeys = normalizeKeyList(findDescendantKeys([eventKey], keyEntities, false), keyEntities, true);
  486. const hasDisabled = descendantKeys.some((key: string) => disabledKeys.has(key));
  487. // If the descendant nodes are not disabled, they will be directly changed to checked
  488. if (!hasDisabled) {
  489. return targetStatus;
  490. }
  491. // If all descendant nodes that are not disabled are selected, return unchecked, otherwise, return checked
  492. const nonDisabledKeys = descendantKeys.filter((key: string) => !disabledKeys.has(key));
  493. const allChecked = nonDisabledKeys.every((key: string) => checkedKeys.has(key));
  494. return !allChecked;
  495. }
  496. /*
  497. * In strict disable mode, calculate the nodes of checked and halfCheckedKeys and return their corresponding keys
  498. */
  499. calcNonDisabedCheckedKeys(eventKey: string, targetStatus: boolean) {
  500. const { keyEntities, disabledKeys } = this.getStates();
  501. const { checkedKeys } = this.getCopyFromState(['checkedKeys']);
  502. const descendantKeys = normalizeKeyList(findDescendantKeys([eventKey], keyEntities, false), keyEntities, true);
  503. const hasDisabled = descendantKeys.some((key: string) => disabledKeys.has(key));
  504. // If none of the descendant nodes are disabled, follow the normal logic
  505. if (!hasDisabled) {
  506. return this.calcCheckedKeys(eventKey, targetStatus);
  507. }
  508. const nonDisabled = descendantKeys.filter((key: string) => !disabledKeys.has(key));
  509. const newCheckedKeys = targetStatus ?
  510. [...nonDisabled, ...checkedKeys] :
  511. difference(normalizeKeyList([...checkedKeys], keyEntities, true), nonDisabled);
  512. return calcCheckedKeys(newCheckedKeys, keyEntities);
  513. }
  514. /*
  515. * Handle the selection event in the case of multiple selection
  516. */
  517. handleMultipleSelect(e: any, treeNode: BasicTreeNodeProps) {
  518. const { disableStrictly } = this.getProps();
  519. // eventKey: The key value of the currently clicked node
  520. const { checked, eventKey, data } = treeNode;
  521. // Find the checked state of the current node
  522. const targetStatus = disableStrictly ? this.calcChekcedStatus(!checked, eventKey) : !checked;
  523. const { checkedKeys, halfCheckedKeys } = disableStrictly ?
  524. this.calcNonDisabedCheckedKeys(eventKey, targetStatus) :
  525. this.calcCheckedKeys(eventKey, targetStatus);
  526. this._adapter.notifySelect(eventKey, targetStatus, data);
  527. this.notifyChange([...checkedKeys], e);
  528. if (!this._isControlledComponent()) {
  529. this._adapter.updateState({ checkedKeys, halfCheckedKeys });
  530. }
  531. }
  532. setExpandedStatus(treeNode: BasicTreeNodeProps) {
  533. const { inputValue, treeData, filteredShownKeys, keyEntities } = this.getStates();
  534. const isSearching = Boolean(inputValue);
  535. const showFilteredOnly = this._showFilteredOnly();
  536. const expandedStateKey = isSearching ? 'filteredExpandedKeys' : 'expandedKeys';
  537. const expandedKeys = this.getCopyFromState(expandedStateKey)[expandedStateKey];
  538. let motionType = 'show';
  539. const { eventKey, expanded, data } = treeNode;
  540. if (!expanded) {
  541. expandedKeys.add(eventKey);
  542. } else if (expandedKeys.has(eventKey)) {
  543. expandedKeys.delete(eventKey);
  544. motionType = 'hide';
  545. }
  546. this._adapter.cacheFlattenNodes(motionType === 'hide' && this._isAnimated());
  547. if (!this._isExpandControlled()) {
  548. const flattenNodes = flattenTreeData(
  549. treeData,
  550. expandedKeys,
  551. isSearching && showFilteredOnly && filteredShownKeys
  552. );
  553. const motionKeys = this._isAnimated() ? getMotionKeys(eventKey, expandedKeys, keyEntities) : [];
  554. const newState = {
  555. [expandedStateKey]: expandedKeys,
  556. flattenNodes,
  557. motionKeys: new Set(motionKeys),
  558. motionType,
  559. };
  560. this._adapter.updateState(newState);
  561. }
  562. return {
  563. expandedKeys,
  564. expanded: !expanded,
  565. data,
  566. };
  567. }
  568. handleNodeExpand(e: any, treeNode: BasicTreeNodeProps) {
  569. const { loadData } = this.getProps();
  570. if (!loadData && (!treeNode.children || !treeNode.children.length)) {
  571. return;
  572. }
  573. const { expandedKeys, data, expanded } = this.setExpandedStatus(treeNode);
  574. this._adapter.notifyExpand(expandedKeys, {
  575. expanded,
  576. node: data,
  577. });
  578. }
  579. // eslint-disable-next-line max-len
  580. handleNodeLoad(loadedKeys: Set<string>, loadingKeys: Set<string>, data: BasicTreeNodeData, resolve: (value?: any) => void) {
  581. const { loadData, onLoad } = this.getProps();
  582. const { key } = data;
  583. if (!loadData || loadedKeys.has(key) || loadingKeys.has(key)) {
  584. return {};
  585. }
  586. // Process the loaded data
  587. loadData(data).then(() => {
  588. const {
  589. loadedKeys: prevLoadedKeys,
  590. loadingKeys: prevLoadingKeys
  591. } = this.getCopyFromState(['loadedKeys', 'loadingKeys']);
  592. const newLoadedKeys = prevLoadedKeys.add(key);
  593. const newLoadingKeys = new Set([...prevLoadingKeys]);
  594. newLoadingKeys.delete(key);
  595. // onLoad should be triggered before internal setState to avoid `loadData` being triggered twice
  596. onLoad && onLoad(newLoadedKeys, data);
  597. if (!this._isLoadControlled()) {
  598. this._adapter.updateState({
  599. loadedKeys: newLoadedKeys,
  600. });
  601. }
  602. this._adapter.setState({
  603. loadingKeys: newLoadingKeys,
  604. } as any);
  605. resolve();
  606. });
  607. return {
  608. loadingKeys: loadingKeys.add(key),
  609. };
  610. }
  611. // Drag and drop related processing logic
  612. getDragEventNodeData(node: BasicTreeNodeData) {
  613. return {
  614. ...node.data,
  615. ...pick(node, ['expanded', 'pos', 'children']),
  616. };
  617. }
  618. triggerDragEvent(name: string, event: any, node: BasicTreeNodeData, extra = {}) {
  619. const callEvent = this.getProp(name);
  620. callEvent &&
  621. callEvent({
  622. event,
  623. node: this.getDragEventNodeData(node),
  624. ...extra,
  625. });
  626. }
  627. clearDragState = () => {
  628. this._adapter.updateState({
  629. dragOverNodeKey: '',
  630. dragging: false,
  631. });
  632. };
  633. handleNodeDragStart(e: any, treeNode: BasicTreeNodeData) {
  634. const { keyEntities } = this.getStates();
  635. const { hideDraggingNode, renderDraggingNode } = this.getProps();
  636. const { eventKey, nodeInstance, data } = treeNode;
  637. if (hideDraggingNode || renderDraggingNode) {
  638. let dragImg;
  639. if (typeof renderDraggingNode === 'function') {
  640. dragImg = renderDraggingNode(nodeInstance, data);
  641. } else if (hideDraggingNode) {
  642. dragImg = nodeInstance.cloneNode(true);
  643. dragImg.style.opacity = 0;
  644. }
  645. document.body.appendChild(dragImg);
  646. e.dataTransfer.setDragImage(dragImg, 0, 0);
  647. }
  648. this._adapter.setDragNode(treeNode);
  649. this._adapter.updateState({
  650. dragging: true,
  651. dragNodesKeys: new Set(getDragNodesKeys(eventKey, keyEntities)),
  652. });
  653. this.triggerDragEvent('onDragStart', e, treeNode);
  654. }
  655. handleNodeDragEnter(e: any, treeNode: BasicTreeNodeData, dragNode: any) {
  656. const { dragging, dragNodesKeys } = this.getStates();
  657. const { autoExpandWhenDragEnter } = this.getProps();
  658. const { pos, eventKey, expanded } = treeNode;
  659. if (!dragNode || dragNodesKeys.has(eventKey)) {
  660. return;
  661. }
  662. const dropPosition = calcDropRelativePosition(e, treeNode);
  663. // If the drag node is itself, skip
  664. if (dragNode.eventKey === eventKey && dropPosition === 0) {
  665. this._adapter.updateState({
  666. dragOverNodeKey: '',
  667. dropPosition: null,
  668. });
  669. return;
  670. }
  671. // Trigger dragenter after clearing the prev state in dragleave
  672. setTimeout(() => {
  673. this._adapter.updateState({
  674. dragOverNodeKey: eventKey,
  675. dropPosition,
  676. });
  677. // If autoExpand is already expanded or not allowed, trigger the event and return
  678. if (!autoExpandWhenDragEnter || expanded) {
  679. this.triggerDragEvent('onDragEnter', e, treeNode);
  680. return;
  681. }
  682. // Side effects of delayed drag
  683. if (!this.delayedDragEnterLogic) {
  684. this.delayedDragEnterLogic = {};
  685. }
  686. Object.keys(this.delayedDragEnterLogic).forEach(key => {
  687. clearTimeout(this.delayedDragEnterLogic[key]);
  688. });
  689. this.delayedDragEnterLogic[pos] = window.setTimeout(() => {
  690. if (!dragging) {
  691. return;
  692. }
  693. const { expandedKeys: newExpandedKeys } = this.setExpandedStatus(treeNode);
  694. this.triggerDragEvent('onDragEnter', e, treeNode, { expandedKeys: [...newExpandedKeys] });
  695. }, 400);
  696. }, 0);
  697. }
  698. handleNodeDragOver(e: any, treeNode: BasicTreeNodeData, dragNode: any) {
  699. const { dropPosition, dragNodesKeys, dragOverNodeKey } = this.getStates();
  700. const { eventKey } = treeNode;
  701. if (dragNodesKeys.has(eventKey)) {
  702. return;
  703. }
  704. // Update the drag position
  705. if (dragNode && eventKey === dragOverNodeKey) {
  706. const newPos = calcDropRelativePosition(event, treeNode);
  707. if (dropPosition === newPos) {
  708. return;
  709. }
  710. this._adapter.updateState({
  711. dropPosition: newPos,
  712. });
  713. }
  714. this.triggerDragEvent('onDragOver', e, treeNode);
  715. }
  716. handleNodeDragLeave(e: any, treeNode: BasicTreeNodeData) {
  717. this._adapter.updateState({
  718. dragOverNodeKey: '',
  719. });
  720. this.triggerDragEvent('onDragLeave', e, treeNode);
  721. }
  722. handleNodeDragEnd(e: any, treeNode: BasicTreeNodeData) {
  723. this.clearDragState();
  724. this.triggerDragEvent('onDragEnd', e, treeNode);
  725. this._adapter.setDragNode(null);
  726. }
  727. handleNodeDrop(e: any, treeNode: BasicTreeNodeData, dragNode: any) {
  728. const { dropPosition, dragNodesKeys } = this.getStates();
  729. const { eventKey, pos } = treeNode;
  730. this.clearDragState();
  731. if (dragNodesKeys.has(eventKey)) {
  732. return;
  733. }
  734. const dropRes = {
  735. dragNode: dragNode ? this.getDragEventNodeData(dragNode) : null,
  736. dragNodesKeys: [...dragNodesKeys],
  737. dropPosition: calcDropActualPosition(pos, dropPosition),
  738. dropToGap: dropPosition !== 0,
  739. };
  740. this.triggerDragEvent('onDrop', e, treeNode, dropRes);
  741. this._adapter.setDragNode(null);
  742. }
  743. }