foundation.ts 30 KB

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