treeUtil.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. /**
  2. * Part of the utils function implementation process reference
  3. * https://github.com/react-component/tree/blob/master/src/util.tsx
  4. */
  5. import { difference, uniq, max, isObject, isNull, isUndefined, isEmpty, pick, get } from 'lodash-es';
  6. export interface KeyEntities {
  7. [x: string]: any;
  8. }
  9. export interface TreeDataSimpleJson {
  10. [x: string]: string | TreeDataSimpleJson;
  11. }
  12. export interface NodeData {
  13. key: any;
  14. label: any;
  15. value: any;
  16. children?: any;
  17. }
  18. const DRAG_OFFSET = 0.45;
  19. function getPosition(level: any, index: any) {
  20. return `${level}-${index}`;
  21. }
  22. function isValid(val: any) {
  23. return !isNull(val) && !isUndefined(val);
  24. }
  25. /**
  26. * Flat nest tree data into flatten list. This is used for virtual list render.
  27. * @param treeNodeList Origin data node list
  28. * @param expandedKeys
  29. * @param filteredShownKeys
  30. * need expanded keys, provides `true` means all expanded
  31. */
  32. // eslint-disable-next-line max-len
  33. export function flattenTreeData(treeNodeList: any[], expandedKeys: Set<string>, filteredShownKeys: boolean | Set<any> = false) {
  34. const flattenList: any[] = [];
  35. const filterSearch = Boolean(filteredShownKeys);
  36. function flatten(list: any[], parent: any = null) {
  37. return list.map((treeNode, index) => {
  38. const pos = getPosition(parent ? parent.pos : '0', index);
  39. const mergedKey = treeNode.key;
  40. // Add FlattenDataNode into list
  41. const flattenNode: any = {
  42. ...pick(treeNode, ['key', 'label', 'value', 'icon', 'disabled', 'isLeaf']),
  43. parent,
  44. pos,
  45. children: null,
  46. data: treeNode,
  47. _innerDataTag: true,
  48. };
  49. const isBooleanFilteredShownKeys = typeof filteredShownKeys === 'boolean';
  50. if (!filterSearch || (!isBooleanFilteredShownKeys && filteredShownKeys.has(mergedKey))) {
  51. flattenList.push(flattenNode);
  52. }
  53. // Loop treeNode children
  54. // eslint-disable-next-line max-len
  55. if (expandedKeys.has(mergedKey) && (!filterSearch || (!isBooleanFilteredShownKeys && filteredShownKeys.has(mergedKey)))) {
  56. flattenNode.children = flatten(treeNode.children || [], flattenNode);
  57. } else {
  58. flattenNode.children = [];
  59. }
  60. return flattenNode;
  61. });
  62. }
  63. flatten(treeNodeList);
  64. return flattenList;
  65. }
  66. export function convertJsonToData(treeJson: TreeDataSimpleJson) {
  67. const treeData: any[] = [];
  68. const traverseNode = (key: string, children: any, path: any, res: any[]) => {
  69. const currPath = [...path, key];
  70. const itemKey = currPath.join('-');
  71. const newNode: NodeData = {
  72. key: itemKey,
  73. label: key,
  74. value: children,
  75. };
  76. if (isObject(children)) {
  77. const childres: any[] = [];
  78. Object.entries(children).forEach(c => {
  79. traverseNode(c[0], c[1], currPath, childres);
  80. });
  81. newNode.children = childres;
  82. }
  83. res.push(newNode);
  84. };
  85. Object.entries(treeJson).forEach(item => traverseNode(item[0], item[1], [], treeData));
  86. return treeData;
  87. }
  88. /**
  89. * Traverse all the data by `treeData`.
  90. */
  91. export function traverseDataNodes(treeNodes: any[], callback: (data: any) => void) {
  92. const processNode = (node: any, ind?: number, parent?: any) => {
  93. const children = node ? node.children : treeNodes;
  94. const pos = node ? getPosition(parent.pos, ind) : '0';
  95. // Process node if is not root
  96. if (node) {
  97. const data = {
  98. data: { ...node },
  99. ind,
  100. pos,
  101. key: node.key !== null ? node.key : pos,
  102. parentPos: parent.node ? parent.pos : null,
  103. level: Number(parent.level) + 1,
  104. };
  105. callback(data);
  106. }
  107. // Process children node
  108. if (children) {
  109. children.forEach((subNode: any, subIndex: number) => {
  110. processNode(subNode, subIndex, {
  111. node,
  112. pos,
  113. level: parent ? Number(parent.level) + 1 : -1,
  114. });
  115. });
  116. }
  117. };
  118. processNode(null);
  119. }
  120. /* Convert data to entities map */
  121. export function convertDataToEntities(dataNodes: any[]) {
  122. const posEntities = {};
  123. const keyEntities = {};
  124. const valueEntities = {};
  125. const wrapper = {
  126. posEntities,
  127. keyEntities,
  128. valueEntities,
  129. };
  130. traverseDataNodes(dataNodes, (data: any) => {
  131. const { pos, key, parentPos } = data;
  132. const entity = { ...data };
  133. const value = get(entity, 'data.value', null);
  134. if (value !== null) {
  135. valueEntities[value] = key;
  136. }
  137. posEntities[pos] = entity;
  138. keyEntities[key] = entity;
  139. // Fill children
  140. entity.parent = posEntities[parentPos];
  141. if (entity.parent) {
  142. entity.parent.children = entity.parent.children || [];
  143. entity.parent.children.push(entity);
  144. }
  145. });
  146. return wrapper;
  147. }
  148. /* Get key by value */
  149. export function findKeysForValues(valueList: any, valueEntities: any, isMultiple = false) {
  150. if (!isValid(valueList)) {
  151. return [];
  152. }
  153. if (!isMultiple && Array.isArray(valueList)) {
  154. valueList = valueList.length ? [valueList[0]] : [];
  155. } else if (!Array.isArray(valueList)) {
  156. valueList = [valueList];
  157. }
  158. if (isEmpty(valueEntities)) {
  159. return valueList;
  160. }
  161. const res: any[] = [];
  162. valueList.forEach((val: string) => {
  163. if (val in valueEntities) {
  164. res.push(valueEntities[val]);
  165. }
  166. });
  167. return res;
  168. }
  169. export function findDescendantKeys(selectedKeys: string[], options: KeyEntities, self = true) {
  170. const res: string[] = [];
  171. const findChild = (item: any) => {
  172. if (!item) {
  173. return;
  174. }
  175. const { children } = item;
  176. const hasChildren = isValid(children);
  177. if (hasChildren) {
  178. children.forEach((child: any) => {
  179. res.push(child.key);
  180. findChild(options[child.key]);
  181. });
  182. }
  183. };
  184. selectedKeys.forEach(item => {
  185. if (self) {
  186. res.push(item);
  187. }
  188. findChild(options[item]);
  189. });
  190. return res;
  191. }
  192. export function findChildKeys(keys: string[], options: any, omitKeys: any[] = []) {
  193. const res: any[] = [];
  194. keys &&
  195. keys.forEach(key => {
  196. const opts = options[key];
  197. opts &&
  198. opts.children &&
  199. opts.children.forEach((child: any) => {
  200. if (!omitKeys.length || !omitKeys.includes(child.key)) {
  201. res.push(child.key);
  202. }
  203. });
  204. });
  205. return res;
  206. }
  207. export function findLeafKeys(keys: string[], options: any) {
  208. const res: any[] = [];
  209. const findChild = (item: any) => {
  210. if (!item) {
  211. return;
  212. }
  213. const { children } = item;
  214. const isLeaf = !isValid(children);
  215. if (isLeaf) {
  216. res.push(item.key);
  217. } else {
  218. children.forEach((child: any) => {
  219. findChild(options[child.key]);
  220. });
  221. }
  222. };
  223. keys.forEach(item => {
  224. findChild(options[item]);
  225. });
  226. return res;
  227. }
  228. export function findSiblingKeys(selectedKeys: string[], options: any, self = true) {
  229. const par: any[] = [];
  230. selectedKeys.forEach(item => {
  231. if (options[item] && options[item].parent) {
  232. par.push(options[item].parent.key);
  233. }
  234. });
  235. const res = findChildKeys(uniq(par), options, self ? [] : selectedKeys);
  236. return res;
  237. }
  238. export function findAncestorKeys(selectedKeys: string[], options: any, self = true) {
  239. const res: any[] = [];
  240. // Recursively find the parent element
  241. const findPar = (item: any) => {
  242. if (item.parent) {
  243. res.push(item.parent.key);
  244. findPar(item.parent);
  245. }
  246. };
  247. selectedKeys.forEach(item => {
  248. options[item] && findPar(options[item]);
  249. if (self) {
  250. res.push(item);
  251. }
  252. });
  253. return res;
  254. }
  255. function getSortedKeyList(keyList: any[], keyEntities: KeyEntities) {
  256. const levelMap = {};
  257. keyList.forEach(key => {
  258. if (!keyEntities[key]) {
  259. return;
  260. }
  261. const { level } = keyEntities[key];
  262. if (levelMap[level]) {
  263. levelMap[level].push(key);
  264. } else {
  265. levelMap[level] = [key];
  266. }
  267. });
  268. return levelMap;
  269. }
  270. export function calcCheckedKeys(values: any, keyEntities: KeyEntities) {
  271. const keyList = Array.isArray(values) ? values : [values];
  272. const descendantKeys = findDescendantKeys(keyList, keyEntities, true);
  273. /**
  274. * Recursively find the parent element. Because the incoming nodes are all checked,
  275. * their descendants must be checked. That is to say, if the descendant nodes have
  276. * disabled+unchecked nodes, their ancestor nodes will definitely not be checked
  277. */
  278. const checkedKeys = new Set([...descendantKeys]);
  279. let halfCheckedKeys = new Set([]);
  280. let visited: any[] = [];
  281. const levelMap = getSortedKeyList(keyList, keyEntities);
  282. const calcCurrLevel = (node: any) => {
  283. const { key, parent, level } = node;
  284. // If the node does not have a parent node, or the node has been processed just now, no processing is done
  285. if (!parent || visited.includes(key)) {
  286. return;
  287. }
  288. const siblingKeys = findSiblingKeys([key], keyEntities);
  289. // visited for caching to avoid double counting
  290. visited = [...visited, ...siblingKeys];
  291. const allChecked = siblingKeys.every((siblingKey: string) => checkedKeys.has(siblingKey));
  292. if (!allChecked) {
  293. const ancesterKeys = findAncestorKeys([key], keyEntities, false);
  294. halfCheckedKeys = new Set([...halfCheckedKeys, ...ancesterKeys]);
  295. } else {
  296. checkedKeys.add(parent.key);
  297. // IMPORTANT! parent level may not exist in original level map; if add to the end directly may destroy the hierarchical order
  298. if (level - 1 in levelMap && level) {
  299. levelMap[level - 1].push(parent.key);
  300. } else {
  301. levelMap[level - 1] = [parent.key];
  302. }
  303. }
  304. };
  305. // Loop keyList from deepest Level to topLevel, bottom up
  306. while (!isEmpty(levelMap)) {
  307. const maxLevel = max(Object.keys(levelMap).map(key => Number(key)));
  308. levelMap[maxLevel].forEach((key: string) => calcCurrLevel(keyEntities[key]));
  309. delete levelMap[maxLevel];
  310. }
  311. return {
  312. checkedKeys,
  313. halfCheckedKeys,
  314. };
  315. }
  316. /* Calculate the expanded node by key */
  317. export function calcExpandedKeys(keyList: any[] = [], keyEntities: KeyEntities, autoExpandParent = true) {
  318. if (!Array.isArray(keyList)) {
  319. keyList = [keyList];
  320. }
  321. if (autoExpandParent) {
  322. const ancesterKeys = findAncestorKeys(keyList, keyEntities, true);
  323. return new Set(ancesterKeys);
  324. }
  325. return new Set(keyList);
  326. }
  327. /* Calculate the expanded node by value */
  328. // eslint-disable-next-line max-len
  329. export function calcExpandedKeysForValues(value: any, keyEntities: KeyEntities, isMultiple: boolean, valueEntities: any) {
  330. const keys = findKeysForValues(value, valueEntities, isMultiple);
  331. return new Set(findAncestorKeys(keys, keyEntities, false));
  332. }
  333. export function calcMotionKeys(oldKeySet: Set<string>, newKeySet: Set<string>, keyEntities: KeyEntities) {
  334. let motionType = 'show';
  335. const oldKeys = [...oldKeySet];
  336. const newKeys = [...newKeySet];
  337. if (Math.abs(oldKeys.length - newKeys.length) !== 1) {
  338. return { motionType, motionKeys: [] };
  339. }
  340. let diffKeys = [];
  341. if (oldKeys.length > newKeys.length) {
  342. motionType = 'hide';
  343. diffKeys = difference(oldKeys, newKeys);
  344. } else {
  345. diffKeys = difference(newKeys, oldKeys);
  346. }
  347. return {
  348. motionType: diffKeys.length === 1 ? motionType : 'show',
  349. motionKeys: diffKeys.length === 1 ? findDescendantKeys(diffKeys, keyEntities, false) : [],
  350. };
  351. }
  352. /**
  353. * @returns whether option includes sugInput.
  354. * When filterTreeNode is a function,returns the result of filterTreeNode which called with (sugInput, option).
  355. */
  356. export function filter(sugInput: string, option: any, filterTreeNode: any, filterProps: any) {
  357. if (!filterTreeNode) {
  358. return true;
  359. }
  360. let filterFn = filterTreeNode;
  361. let target = option;
  362. if (typeof filterTreeNode === 'boolean') {
  363. filterFn = (targetVal: string, val: any) => {
  364. const input = targetVal.toLowerCase();
  365. return val
  366. .toString()
  367. .toLowerCase()
  368. .includes(input);
  369. };
  370. }
  371. if (filterProps) {
  372. target = option[filterProps];
  373. }
  374. return filterFn(sugInput, target);
  375. }
  376. export function normalizedArr(val: any) {
  377. if (!Array.isArray(val)) {
  378. return [val];
  379. } else {
  380. return val;
  381. }
  382. }
  383. export function normalizeKeyList(keyList: any, keyEntities: KeyEntities, leafOnly = false) {
  384. let res: string[] = [];
  385. const keyListSet = new Set(keyList);
  386. if (!leafOnly) {
  387. keyList.forEach((key: string) => {
  388. if (!keyEntities[key]) {
  389. return;
  390. }
  391. const { parent } = keyEntities[key];
  392. if (parent && keyListSet.has(parent.key)) {
  393. return;
  394. }
  395. res.push(key);
  396. });
  397. } else {
  398. res = keyList.filter((key: string) => keyEntities[key] && !isValid(keyEntities[key].children));
  399. }
  400. return res;
  401. }
  402. export function getMotionKeys(eventKey: string, expandedKeys: Set<string>, keyEntities: KeyEntities) {
  403. const res: any[] = [];
  404. const getChild = (itemKey: string) => {
  405. keyEntities[itemKey].children &&
  406. keyEntities[itemKey].children.forEach((item: any) => {
  407. const { key } = item;
  408. res.push(key);
  409. if (expandedKeys.has(key)) {
  410. getChild(key);
  411. }
  412. });
  413. };
  414. getChild(eventKey);
  415. return res;
  416. }
  417. // eslint-disable-next-line max-len
  418. export function calcCheckedKeysForChecked(key: string, keyEntities: KeyEntities, checkedKeys: Set<string>, halfCheckedKeys: Set<string>) {
  419. const descendantKeys = findDescendantKeys([key], keyEntities, true);
  420. const nodeItem = keyEntities[key];
  421. checkedKeys = new Set([...checkedKeys, key]);
  422. const calcCurrLevel = (node: any) => {
  423. if (!node.parent) {
  424. return;
  425. }
  426. // eslint-disable-next-line @typescript-eslint/no-shadow
  427. const { key } = node;
  428. const siblingKeys = findSiblingKeys([key], keyEntities);
  429. // eslint-disable-next-line @typescript-eslint/no-shadow
  430. const allChecked = siblingKeys.every(key => checkedKeys.has(key));
  431. if (!allChecked) {
  432. const ancesterKeys = findAncestorKeys([key], keyEntities, false);
  433. halfCheckedKeys = new Set([...halfCheckedKeys, ...ancesterKeys]);
  434. } else {
  435. const par = node.parent;
  436. checkedKeys.add(par.key);
  437. calcCurrLevel(par);
  438. }
  439. };
  440. calcCurrLevel(nodeItem);
  441. return {
  442. checkedKeys: new Set([...checkedKeys, ...descendantKeys]),
  443. halfCheckedKeys,
  444. };
  445. }
  446. // eslint-disable-next-line max-len
  447. export function calcCheckedKeysForUnchecked(key: string, keyEntities: KeyEntities, checkedKeys: Set<string>, halfCheckedKeys: Set<string>) {
  448. const descendantKeys = findDescendantKeys([key], keyEntities, true);
  449. const nodeItem = keyEntities[key];
  450. descendantKeys.forEach(descendantKey => {
  451. if (checkedKeys.has(descendantKey)) {
  452. checkedKeys.delete(descendantKey);
  453. }
  454. if (halfCheckedKeys.has(descendantKey)) {
  455. halfCheckedKeys.delete(descendantKey);
  456. }
  457. });
  458. const calcCurrLevel = (node: any) => {
  459. const par = node.parent;
  460. // no parent
  461. if (!par) {
  462. return;
  463. }
  464. // Has a parent node, and the parent node is not checked or halfChecked
  465. if (!checkedKeys.has(par.key) && !halfCheckedKeys.has(par.key)) {
  466. return;
  467. }
  468. // Has a parent node, and the parent node is checked or halfChecked
  469. // eslint-disable-next-line @typescript-eslint/no-shadow
  470. const { key } = node;
  471. const siblingKeys = findSiblingKeys([key], keyEntities);
  472. // eslint-disable-next-line @typescript-eslint/no-shadow
  473. const anyChecked = siblingKeys.some(key => checkedKeys.has(key) || halfCheckedKeys.has(key));
  474. const ancesterKeys = findAncestorKeys([key], keyEntities, false);
  475. // If there is checked or halfChecked in the sibling node, you need to change the parent node to halfChecked
  476. if (anyChecked) {
  477. ancesterKeys.forEach(itemKey => {
  478. if (checkedKeys.has(itemKey)) {
  479. checkedKeys.delete(itemKey);
  480. halfCheckedKeys.add(itemKey);
  481. }
  482. });
  483. // If there is no checked or halfChecked in the sibling node, you need to change the parent node to unchecked
  484. } else {
  485. if (checkedKeys.has(par.key)) {
  486. checkedKeys.delete(par.key);
  487. }
  488. if (halfCheckedKeys.has(par.key)) {
  489. halfCheckedKeys.delete(par.key);
  490. }
  491. calcCurrLevel(par);
  492. }
  493. };
  494. calcCurrLevel(nodeItem);
  495. return {
  496. checkedKeys,
  497. halfCheckedKeys,
  498. };
  499. }
  500. export function filterTreeData(info: any) {
  501. const {
  502. showFilteredOnly,
  503. keyEntities,
  504. inputValue,
  505. treeData,
  506. filterTreeNode,
  507. filterProps,
  508. prevExpandedKeys,
  509. } = info;
  510. let filteredOptsKeys = [];
  511. filteredOptsKeys = Object.values(keyEntities)
  512. .filter((item: any) => filter(inputValue, item.data, filterTreeNode, filterProps))
  513. .map((item: any) => item.key);
  514. let expandedOptsKeys = findAncestorKeys(filteredOptsKeys, keyEntities, false);
  515. if (prevExpandedKeys.length) {
  516. const prevExpandedValidKeys = prevExpandedKeys.filter((key: string) => Boolean(keyEntities[key]));
  517. expandedOptsKeys = expandedOptsKeys.concat(prevExpandedValidKeys);
  518. }
  519. const shownChildKeys = findDescendantKeys(filteredOptsKeys, keyEntities, true);
  520. const filteredShownKeys = new Set([...shownChildKeys, ...expandedOptsKeys]);
  521. const flattenNodes = flattenTreeData(treeData, new Set(expandedOptsKeys), showFilteredOnly && filteredShownKeys);
  522. return {
  523. flattenNodes,
  524. filteredKeys: new Set(filteredOptsKeys),
  525. filteredExpandedKeys: new Set(expandedOptsKeys),
  526. filteredShownKeys,
  527. };
  528. }
  529. // return data.value if data.value exist else fall back to key
  530. export function getValueOrKey(data: any) {
  531. if (Array.isArray(data)) {
  532. return data.map(item => get(item, 'value', item.key));
  533. }
  534. return get(data, 'value', data.key);
  535. }
  536. /* Convert value to string */
  537. export function normalizeValue(value: any, withObject: boolean) {
  538. if (withObject && isValid(value)) {
  539. return getValueOrKey(value);
  540. } else {
  541. return value;
  542. }
  543. }
  544. export function updateKeys(keySet: Set<string>, keyEntities: KeyEntities) {
  545. const keyArr = [...keySet];
  546. return keyArr.filter(key => key in keyEntities);
  547. }
  548. export function calcDisabledKeys(keyEntities: KeyEntities) {
  549. const disabledKeys = Object.keys(keyEntities).filter(key => keyEntities[key].data.disabled);
  550. const { checkedKeys } = calcCheckedKeys(disabledKeys, keyEntities);
  551. return checkedKeys;
  552. }
  553. export function calcDropRelativePosition(event: any, treeNode: any) {
  554. const { clientY } = event;
  555. const { top, bottom, height } = treeNode.nodeInstance.getBoundingClientRect();
  556. // eslint-disable-next-line @typescript-eslint/restrict-plus-operands
  557. if (clientY <= top + height * DRAG_OFFSET) {
  558. return -1;
  559. }
  560. if (clientY >= bottom - height * DRAG_OFFSET) {
  561. return 1;
  562. }
  563. return 0;
  564. }
  565. export function getDragNodesKeys(key: string, keyEntities: KeyEntities) {
  566. return findDescendantKeys([key], keyEntities, true);
  567. }
  568. export function calcDropActualPosition(pos: string, relativeDropPos: any) {
  569. const posArr = pos.split('-');
  570. // eslint-disable-next-line @typescript-eslint/restrict-plus-operands
  571. return relativeDropPos + Number(posArr[posArr.length - 1]);
  572. }