treeUtil.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  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';
  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 newChildren: any[] = [];
  78. Object.entries(children).forEach(c => {
  79. traverseNode(c[0], c[1], currPath, newChildren);
  80. });
  81. newNode.children = newChildren;
  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. /* istanbul ignore next */
  208. export function findLeafKeys(keys: string[], options: any) {
  209. const res: any[] = [];
  210. const findChild = (item: any) => {
  211. if (!item) {
  212. return;
  213. }
  214. const { children } = item;
  215. const isLeaf = !isValid(children);
  216. if (isLeaf) {
  217. res.push(item.key);
  218. } else {
  219. children.forEach((child: any) => {
  220. findChild(options[child.key]);
  221. });
  222. }
  223. };
  224. keys.forEach(item => {
  225. findChild(options[item]);
  226. });
  227. return res;
  228. }
  229. export function findSiblingKeys(selectedKeys: string[], options: any, self = true) {
  230. const par: any[] = [];
  231. selectedKeys.forEach(item => {
  232. if (options[item] && options[item].parent) {
  233. par.push(options[item].parent.key);
  234. }
  235. });
  236. const res = findChildKeys(uniq(par), options, self ? [] : selectedKeys);
  237. return res;
  238. }
  239. export function findAncestorKeys(selectedKeys: string[], options: any, self = true) {
  240. const res: any[] = [];
  241. // Recursively find the parent element
  242. const findPar = (item: any) => {
  243. if (item.parent) {
  244. res.push(item.parent.key);
  245. findPar(item.parent);
  246. }
  247. };
  248. selectedKeys.forEach(item => {
  249. options[item] && findPar(options[item]);
  250. if (self) {
  251. res.push(item);
  252. }
  253. });
  254. return res;
  255. }
  256. function getSortedKeyList(keyList: any[], keyEntities: KeyEntities) {
  257. const levelMap = {};
  258. keyList.forEach(key => {
  259. if (!keyEntities[key]) {
  260. return;
  261. }
  262. const { level } = keyEntities[key];
  263. if (levelMap[level]) {
  264. levelMap[level].push(key);
  265. } else {
  266. levelMap[level] = [key];
  267. }
  268. });
  269. return levelMap;
  270. }
  271. export function calcCheckedKeys(values: any, keyEntities: KeyEntities) {
  272. const keyList = Array.isArray(values) ? values : [values];
  273. const descendantKeys = findDescendantKeys(keyList, keyEntities, true);
  274. /**
  275. * Recursively find the parent element. Because the incoming nodes are all checked,
  276. * their descendants must be checked. That is to say, if the descendant nodes have
  277. * disabled+unchecked nodes, their ancestor nodes will definitely not be checked
  278. */
  279. const checkedKeys = new Set([...descendantKeys]);
  280. let halfCheckedKeys = new Set([]);
  281. let visited: any[] = [];
  282. const levelMap:{[key: number]: string[]} = getSortedKeyList(keyList, keyEntities);
  283. const calcCurrLevel = (node: any) => {
  284. const { key, parent, level } = node;
  285. // If the node does not have a parent node, or the node has been processed just now, no processing is done
  286. if (!parent || visited.includes(key)) {
  287. return;
  288. }
  289. const siblingKeys = findSiblingKeys([key], keyEntities);
  290. // visited for caching to avoid double counting
  291. visited = [...visited, ...siblingKeys];
  292. const allChecked = siblingKeys.every((siblingKey: string) => checkedKeys.has(siblingKey));
  293. if (!allChecked) {
  294. const ancestorKeys = findAncestorKeys([key], keyEntities, false);
  295. halfCheckedKeys = new Set([...halfCheckedKeys, ...ancestorKeys]);
  296. } else {
  297. checkedKeys.add(parent.key);
  298. // IMPORTANT! parent level may not exist in original level map; if add to the end directly may destroy the hierarchical order
  299. if (level - 1 in levelMap && level) {
  300. levelMap[level - 1].push(parent.key);
  301. } else {
  302. levelMap[level - 1] = [parent.key];
  303. }
  304. }
  305. };
  306. // Loop keyList from deepest Level to topLevel, bottom up
  307. while (!isEmpty(levelMap)) {
  308. const maxLevel = max(Object.keys(levelMap).map(key => Number(key)));
  309. levelMap[maxLevel].forEach((key: string) => calcCurrLevel(keyEntities[key]));
  310. delete levelMap[maxLevel];
  311. }
  312. return {
  313. checkedKeys,
  314. halfCheckedKeys,
  315. };
  316. }
  317. /* Calculate the expanded node by key */
  318. export function calcExpandedKeys(keyList: any[] = [], keyEntities: KeyEntities, autoExpandParent = true) {
  319. if (!Array.isArray(keyList)) {
  320. keyList = [keyList];
  321. }
  322. if (autoExpandParent) {
  323. const ancestorKeys = findAncestorKeys(keyList, keyEntities, true);
  324. return new Set(ancestorKeys);
  325. }
  326. return new Set(keyList);
  327. }
  328. /* Calculate the expanded node by value */
  329. // eslint-disable-next-line max-len
  330. export function calcExpandedKeysForValues(value: any, keyEntities: KeyEntities, isMultiple: boolean, valueEntities: any) {
  331. const keys = findKeysForValues(value, valueEntities, isMultiple);
  332. return new Set(findAncestorKeys(keys, keyEntities, false));
  333. }
  334. export function calcMotionKeys(oldKeySet: Set<string>, newKeySet: Set<string>, keyEntities: KeyEntities) {
  335. let motionType = 'show';
  336. const oldKeys = [...oldKeySet];
  337. const newKeys = [...newKeySet];
  338. if (Math.abs(oldKeys.length - newKeys.length) !== 1) {
  339. return { motionType, motionKeys: [] };
  340. }
  341. let diffKeys = [];
  342. if (oldKeys.length > newKeys.length) {
  343. motionType = 'hide';
  344. diffKeys = difference(oldKeys, newKeys);
  345. } else {
  346. diffKeys = difference(newKeys, oldKeys);
  347. }
  348. return {
  349. motionType: diffKeys.length === 1 ? motionType : 'show',
  350. motionKeys: diffKeys.length === 1 ? findDescendantKeys(diffKeys, keyEntities, false) : [],
  351. };
  352. }
  353. /**
  354. * @returns whether option includes sugInput.
  355. * When filterTreeNode is a function,returns the result of filterTreeNode which called with (sugInput, option).
  356. */
  357. export function filter(sugInput: string, option: any, filterTreeNode: any, filterProps: any) {
  358. if (!filterTreeNode) {
  359. return true;
  360. }
  361. let filterFn = filterTreeNode;
  362. let target = option;
  363. if (typeof filterTreeNode === 'boolean') {
  364. filterFn = (targetVal: string, val: any) => {
  365. const input = targetVal.toLowerCase();
  366. return val
  367. .toString()
  368. .toLowerCase()
  369. .includes(input);
  370. };
  371. }
  372. if (filterProps) {
  373. target = option[filterProps];
  374. }
  375. return filterFn(sugInput, target);
  376. }
  377. export function normalizedArr(val: any) {
  378. if (!Array.isArray(val)) {
  379. return [val];
  380. } else {
  381. return val;
  382. }
  383. }
  384. export function normalizeKeyList(keyList: any, keyEntities: KeyEntities, leafOnly = false) {
  385. const res: string[] = [];
  386. const keyListSet = new Set(keyList);
  387. if (!leafOnly) {
  388. keyList.forEach((key: string) => {
  389. if (!keyEntities[key]) {
  390. return;
  391. }
  392. const { parent } = keyEntities[key];
  393. if (parent && keyListSet.has(parent.key)) {
  394. return;
  395. }
  396. res.push(key);
  397. });
  398. } else {
  399. keyList.forEach(key => {
  400. if (keyEntities[key] && !isValid(keyEntities[key].children)) {
  401. res.push(key);
  402. }
  403. });
  404. }
  405. return res;
  406. }
  407. export function getMotionKeys(eventKey: string, expandedKeys: Set<string>, keyEntities: KeyEntities) {
  408. const res: any[] = [];
  409. const getChild = (itemKey: string) => {
  410. keyEntities[itemKey].children &&
  411. keyEntities[itemKey].children.forEach((item: any) => {
  412. const { key } = item;
  413. res.push(key);
  414. if (expandedKeys.has(key)) {
  415. getChild(key);
  416. }
  417. });
  418. };
  419. getChild(eventKey);
  420. return res;
  421. }
  422. // eslint-disable-next-line max-len
  423. export function calcCheckedKeysForChecked(key: string, keyEntities: KeyEntities, checkedKeys: Set<string>, halfCheckedKeys: Set<string>) {
  424. const descendantKeys = findDescendantKeys([key], keyEntities, true);
  425. const nodeItem = keyEntities[key];
  426. checkedKeys = new Set([...checkedKeys, key]);
  427. const calcCurrLevel = (node: any) => {
  428. if (!node.parent) {
  429. return;
  430. }
  431. // eslint-disable-next-line @typescript-eslint/no-shadow
  432. const { key } = node;
  433. const siblingKeys = findSiblingKeys([key], keyEntities);
  434. // eslint-disable-next-line @typescript-eslint/no-shadow
  435. const allChecked = siblingKeys.every(key => checkedKeys.has(key));
  436. if (!allChecked) {
  437. const ancestorKeys = findAncestorKeys([key], keyEntities, false);
  438. halfCheckedKeys = new Set([...halfCheckedKeys, ...ancestorKeys]);
  439. } else {
  440. const par = node.parent;
  441. checkedKeys.add(par.key);
  442. calcCurrLevel(par);
  443. }
  444. };
  445. calcCurrLevel(nodeItem);
  446. return {
  447. checkedKeys: new Set([...checkedKeys, ...descendantKeys]),
  448. halfCheckedKeys,
  449. };
  450. }
  451. // eslint-disable-next-line max-len
  452. export function calcCheckedKeysForUnchecked(key: string, keyEntities: KeyEntities, checkedKeys: Set<string>, halfCheckedKeys: Set<string>) {
  453. const descendantKeys = findDescendantKeys([key], keyEntities, true);
  454. const nodeItem = keyEntities[key];
  455. descendantKeys.forEach(descendantKey => {
  456. if (checkedKeys.has(descendantKey)) {
  457. checkedKeys.delete(descendantKey);
  458. }
  459. if (halfCheckedKeys.has(descendantKey)) {
  460. halfCheckedKeys.delete(descendantKey);
  461. }
  462. });
  463. const calcCurrLevel = (node: any) => {
  464. const par = node.parent;
  465. // no parent
  466. if (!par) {
  467. return;
  468. }
  469. // Has a parent node, and the parent node is not checked or halfChecked
  470. if (!checkedKeys.has(par.key) && !halfCheckedKeys.has(par.key)) {
  471. return;
  472. }
  473. // Has a parent node, and the parent node is checked or halfChecked
  474. // eslint-disable-next-line @typescript-eslint/no-shadow
  475. const { key } = node;
  476. const siblingKeys = findSiblingKeys([key], keyEntities);
  477. // eslint-disable-next-line @typescript-eslint/no-shadow
  478. const anyChecked = siblingKeys.some(key => checkedKeys.has(key) || halfCheckedKeys.has(key));
  479. const ancestorKeys = findAncestorKeys([key], keyEntities, false);
  480. // If there is checked or halfChecked in the sibling node, you need to change the parent node to halfChecked
  481. if (anyChecked) {
  482. ancestorKeys.forEach(itemKey => {
  483. if (checkedKeys.has(itemKey)) {
  484. checkedKeys.delete(itemKey);
  485. halfCheckedKeys.add(itemKey);
  486. }
  487. });
  488. // If there is no checked or halfChecked in the sibling node, you need to change the parent node to unchecked
  489. } else {
  490. if (checkedKeys.has(par.key)) {
  491. checkedKeys.delete(par.key);
  492. }
  493. if (halfCheckedKeys.has(par.key)) {
  494. halfCheckedKeys.delete(par.key);
  495. }
  496. calcCurrLevel(par);
  497. }
  498. };
  499. calcCurrLevel(nodeItem);
  500. return {
  501. checkedKeys,
  502. halfCheckedKeys,
  503. };
  504. }
  505. export function filterTreeData(info: any) {
  506. const {
  507. showFilteredOnly,
  508. keyEntities,
  509. inputValue,
  510. treeData,
  511. filterTreeNode,
  512. filterProps,
  513. prevExpandedKeys,
  514. } = info;
  515. let filteredOptsKeys = [];
  516. filteredOptsKeys = Object.values(keyEntities)
  517. .filter((item: any) => filter(inputValue, item.data, filterTreeNode, filterProps))
  518. .map((item: any) => item.key);
  519. let expandedOptsKeys = findAncestorKeys(filteredOptsKeys, keyEntities, false);
  520. if (prevExpandedKeys.length) {
  521. const prevExpandedValidKeys = prevExpandedKeys.filter((key: string) => Boolean(keyEntities[key]));
  522. expandedOptsKeys = expandedOptsKeys.concat(prevExpandedValidKeys);
  523. }
  524. const shownChildKeys = findDescendantKeys(filteredOptsKeys, keyEntities, true);
  525. const filteredShownKeys = new Set([...shownChildKeys, ...expandedOptsKeys]);
  526. const flattenNodes = flattenTreeData(treeData, new Set(expandedOptsKeys), showFilteredOnly && filteredShownKeys);
  527. return {
  528. flattenNodes,
  529. filteredKeys: new Set(filteredOptsKeys),
  530. filteredExpandedKeys: new Set(expandedOptsKeys),
  531. filteredShownKeys,
  532. };
  533. }
  534. // return data.value if data.value exist else fall back to key
  535. export function getValueOrKey(data: any) {
  536. if (Array.isArray(data)) {
  537. return data.map(item => get(item, 'value', item.key));
  538. }
  539. return get(data, 'value', data.key);
  540. }
  541. /* Convert value to string */
  542. export function normalizeValue(value: any, withObject: boolean) {
  543. if (withObject && isValid(value)) {
  544. return getValueOrKey(value);
  545. } else {
  546. return value;
  547. }
  548. }
  549. export function updateKeys(keySet: Set<string> | string[], keyEntities: KeyEntities) {
  550. const keyArr = [...keySet];
  551. return keyArr.filter(key => key in keyEntities);
  552. }
  553. export function calcDisabledKeys(keyEntities: KeyEntities) {
  554. const disabledKeys = Object.keys(keyEntities).filter(key => keyEntities[key].data.disabled);
  555. const { checkedKeys } = calcCheckedKeys(disabledKeys, keyEntities);
  556. return checkedKeys;
  557. }
  558. export function calcDropRelativePosition(event: any, treeNode: any) {
  559. const { clientY } = event;
  560. const { top, bottom, height } = treeNode.nodeInstance.getBoundingClientRect();
  561. // eslint-disable-next-line @typescript-eslint/restrict-plus-operands
  562. if (clientY <= top + height * DRAG_OFFSET) {
  563. return -1;
  564. }
  565. if (clientY >= bottom - height * DRAG_OFFSET) {
  566. return 1;
  567. }
  568. return 0;
  569. }
  570. export function getDragNodesKeys(key: string, keyEntities: KeyEntities) {
  571. return findDescendantKeys([key], keyEntities, true);
  572. }
  573. export function calcDropActualPosition(pos: string, relativeDropPos: any) {
  574. const posArr = pos.split('-');
  575. // eslint-disable-next-line @typescript-eslint/restrict-plus-operands
  576. return relativeDropPos + Number(posArr[posArr.length - 1]);
  577. }