tree.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { CascaderOption, CascaderConfig, CascaderValue } from './types';
  2. import { formatTree, eachTree } from './helper';
  3. class Tree {
  4. nodes: CascaderOption[];
  5. readonly config: CascaderConfig;
  6. constructor(nodes: CascaderOption[], config?: CascaderConfig) {
  7. this.config = {
  8. value: 'value',
  9. text: 'text',
  10. children: 'children',
  11. ...(config || {})
  12. };
  13. this.nodes = formatTree(nodes, null, this.config);
  14. }
  15. updateChildren(nodes: CascaderOption[], parent: CascaderOption | null): void {
  16. if (!parent) {
  17. this.nodes = formatTree(nodes, null, this.config);
  18. } else {
  19. parent.children = formatTree(nodes, parent, this.config);
  20. }
  21. }
  22. getNodeByValue(value: CascaderOption['value']): CascaderOption | void {
  23. let foundNode;
  24. eachTree(this.nodes, (node: CascaderOption) => {
  25. if (node.value === value) {
  26. foundNode = node;
  27. return true;
  28. }
  29. });
  30. return foundNode;
  31. }
  32. getPathNodesByNode(node: CascaderOption): CascaderOption[] {
  33. const nodes = [];
  34. while (node) {
  35. nodes.unshift(node);
  36. node = node._parent;
  37. }
  38. return nodes;
  39. }
  40. getPathNodesByValue(value: CascaderValue): CascaderOption[] {
  41. if (Array.isArray(value) && !value.length) {
  42. return [];
  43. }
  44. const tail = Array.isArray(value) ? value[value.length - 1] : value;
  45. const node = this.getNodeByValue(tail);
  46. if (!node) {
  47. return [];
  48. }
  49. return this.getPathNodesByNode(node);
  50. }
  51. isLeaf(node: CascaderOption, lazy: boolean): boolean {
  52. const { leaf, children } = node;
  53. const hasChildren = Array.isArray(children) && Boolean(children.length);
  54. return leaf || (!hasChildren && !lazy);
  55. }
  56. hasChildren(node: CascaderOption, lazy: boolean): boolean {
  57. const isLeaf = this.isLeaf(node, lazy);
  58. if (isLeaf) {
  59. return false;
  60. }
  61. const { children } = node;
  62. return Array.isArray(children) && Boolean(children.length);
  63. }
  64. }
  65. export default Tree;