foundation.ts 30 KB

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