treeUtil.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  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. 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 ancestorKeys = findAncestorKeys([key], keyEntities, false);
  294. halfCheckedKeys = new Set([...halfCheckedKeys, ...ancestorKeys]);
  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 ancestorKeys = findAncestorKeys(keyList, keyEntities, true);
  323. return new Set(ancestorKeys);
  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. const 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. keyList.forEach(key => {
  399. if (keyEntities[key] && !isValid(keyEntities[key].children)) {
  400. res.push(key);
  401. }
  402. });
  403. }
  404. return res;
  405. }
  406. export function getMotionKeys(eventKey: string, expandedKeys: Set<string>, keyEntities: KeyEntities) {
  407. const res: any[] = [];
  408. const getChild = (itemKey: string) => {
  409. keyEntities[itemKey].children &&
  410. keyEntities[itemKey].children.forEach((item: any) => {
  411. const { key } = item;
  412. res.push(key);
  413. if (expandedKeys.has(key)) {
  414. getChild(key);
  415. }
  416. });
  417. };
  418. getChild(eventKey);
  419. return res;
  420. }
  421. // eslint-disable-next-line max-len
  422. export function calcCheckedKeysForChecked(key: string, keyEntities: KeyEntities, checkedKeys: Set<string>, halfCheckedKeys: Set<string>) {
  423. const descendantKeys = findDescendantKeys([key], keyEntities, true);
  424. const nodeItem = keyEntities[key];
  425. checkedKeys = new Set([...checkedKeys, key]);
  426. const calcCurrLevel = (node: any) => {
  427. if (!node.parent) {
  428. return;
  429. }
  430. // eslint-disable-next-line @typescript-eslint/no-shadow
  431. const { key } = node;
  432. const siblingKeys = findSiblingKeys([key], keyEntities);
  433. // eslint-disable-next-line @typescript-eslint/no-shadow
  434. const allChecked = siblingKeys.every(key => checkedKeys.has(key));
  435. if (!allChecked) {
  436. const ancestorKeys = findAncestorKeys([key], keyEntities, false);
  437. halfCheckedKeys = new Set([...halfCheckedKeys, ...ancestorKeys]);
  438. } else {
  439. const par = node.parent;
  440. checkedKeys.add(par.key);
  441. calcCurrLevel(par);
  442. }
  443. };
  444. calcCurrLevel(nodeItem);
  445. return {
  446. checkedKeys: new Set([...checkedKeys, ...descendantKeys]),
  447. halfCheckedKeys,
  448. };
  449. }
  450. // eslint-disable-next-line max-len
  451. export function calcCheckedKeysForUnchecked(key: string, keyEntities: KeyEntities, checkedKeys: Set<string>, halfCheckedKeys: Set<string>) {
  452. const descendantKeys = findDescendantKeys([key], keyEntities, true);
  453. const nodeItem = keyEntities[key];
  454. descendantKeys.forEach(descendantKey => {
  455. if (checkedKeys.has(descendantKey)) {
  456. checkedKeys.delete(descendantKey);
  457. }
  458. if (halfCheckedKeys.has(descendantKey)) {
  459. halfCheckedKeys.delete(descendantKey);
  460. }
  461. });
  462. const calcCurrLevel = (node: any) => {
  463. const par = node.parent;
  464. // no parent
  465. if (!par) {
  466. return;
  467. }
  468. // Has a parent node, and the parent node is not checked or halfChecked
  469. if (!checkedKeys.has(par.key) && !halfCheckedKeys.has(par.key)) {
  470. return;
  471. }
  472. // Has a parent node, and the parent node is checked or halfChecked
  473. // eslint-disable-next-line @typescript-eslint/no-shadow
  474. const { key } = node;
  475. const siblingKeys = findSiblingKeys([key], keyEntities);
  476. // eslint-disable-next-line @typescript-eslint/no-shadow
  477. const anyChecked = siblingKeys.some(key => checkedKeys.has(key) || halfCheckedKeys.has(key));
  478. const ancestorKeys = findAncestorKeys([key], keyEntities, false);
  479. // If there is checked or halfChecked in the sibling node, you need to change the parent node to halfChecked
  480. if (anyChecked) {
  481. ancestorKeys.forEach(itemKey => {
  482. if (checkedKeys.has(itemKey)) {
  483. checkedKeys.delete(itemKey);
  484. halfCheckedKeys.add(itemKey);
  485. }
  486. });
  487. // If there is no checked or halfChecked in the sibling node, you need to change the parent node to unchecked
  488. } else {
  489. if (checkedKeys.has(par.key)) {
  490. checkedKeys.delete(par.key);
  491. }
  492. if (halfCheckedKeys.has(par.key)) {
  493. halfCheckedKeys.delete(par.key);
  494. }
  495. calcCurrLevel(par);
  496. }
  497. };
  498. calcCurrLevel(nodeItem);
  499. return {
  500. checkedKeys,
  501. halfCheckedKeys,
  502. };
  503. }
  504. export function filterTreeData(info: any) {
  505. const {
  506. showFilteredOnly,
  507. keyEntities,
  508. inputValue,
  509. treeData,
  510. filterTreeNode,
  511. filterProps,
  512. prevExpandedKeys,
  513. } = info;
  514. let filteredOptsKeys = [];
  515. filteredOptsKeys = Object.values(keyEntities)
  516. .filter((item: any) => filter(inputValue, item.data, filterTreeNode, filterProps))
  517. .map((item: any) => item.key);
  518. let expandedOptsKeys = findAncestorKeys(filteredOptsKeys, keyEntities, false);
  519. if (prevExpandedKeys.length) {
  520. const prevExpandedValidKeys = prevExpandedKeys.filter((key: string) => Boolean(keyEntities[key]));
  521. expandedOptsKeys = expandedOptsKeys.concat(prevExpandedValidKeys);
  522. }
  523. const shownChildKeys = findDescendantKeys(filteredOptsKeys, keyEntities, true);
  524. const filteredShownKeys = new Set([...shownChildKeys, ...expandedOptsKeys]);
  525. const flattenNodes = flattenTreeData(treeData, new Set(expandedOptsKeys), showFilteredOnly && filteredShownKeys);
  526. return {
  527. flattenNodes,
  528. filteredKeys: new Set(filteredOptsKeys),
  529. filteredExpandedKeys: new Set(expandedOptsKeys),
  530. filteredShownKeys,
  531. };
  532. }
  533. // return data.value if data.value exist else fall back to key
  534. export function getValueOrKey(data: any) {
  535. if (Array.isArray(data)) {
  536. return data.map(item => get(item, 'value', item.key));
  537. }
  538. return get(data, 'value', data.key);
  539. }
  540. /* Convert value to string */
  541. export function normalizeValue(value: any, withObject: boolean) {
  542. if (withObject && isValid(value)) {
  543. return getValueOrKey(value);
  544. } else {
  545. return value;
  546. }
  547. }
  548. export function updateKeys(keySet: Set<string> | string[], keyEntities: KeyEntities) {
  549. const keyArr = [...keySet];
  550. return keyArr.filter(key => key in keyEntities);
  551. }
  552. export function calcDisabledKeys(keyEntities: KeyEntities) {
  553. const disabledKeys = Object.keys(keyEntities).filter(key => keyEntities[key].data.disabled);
  554. const { checkedKeys } = calcCheckedKeys(disabledKeys, keyEntities);
  555. return checkedKeys;
  556. }
  557. export function calcDropRelativePosition(event: any, treeNode: any) {
  558. const { clientY } = event;
  559. const { top, bottom, height } = treeNode.nodeInstance.getBoundingClientRect();
  560. // eslint-disable-next-line @typescript-eslint/restrict-plus-operands
  561. if (clientY <= top + height * DRAG_OFFSET) {
  562. return -1;
  563. }
  564. if (clientY >= bottom - height * DRAG_OFFSET) {
  565. return 1;
  566. }
  567. return 0;
  568. }
  569. export function getDragNodesKeys(key: string, keyEntities: KeyEntities) {
  570. return findDescendantKeys([key], keyEntities, true);
  571. }
  572. export function calcDropActualPosition(pos: string, relativeDropPos: any) {
  573. const posArr = pos.split('-');
  574. // eslint-disable-next-line @typescript-eslint/restrict-plus-operands
  575. return relativeDropPos + Number(posArr[posArr.length - 1]);
  576. }