store.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import Node from './node';
  2. import { coerceTruthyValueToArray, valueEquals } from 'element-ui/src/utils/util';
  3. const flatNodes = (data, leafOnly) => {
  4. return data.reduce((res, node) => {
  5. if (node.isLeaf) {
  6. res.push(node);
  7. } else {
  8. !leafOnly && res.push(node);
  9. res = res.concat(flatNodes(node.children, leafOnly));
  10. }
  11. return res;
  12. }, []);
  13. };
  14. export default class Store {
  15. constructor(data, config) {
  16. this.config = config;
  17. this.initNodes(data);
  18. }
  19. initNodes(data) {
  20. data = coerceTruthyValueToArray(data);
  21. this.nodes = data.map(nodeData => new Node(nodeData, this.config));
  22. this.flattedNodes = this.getFlattedNodes(false, false);
  23. this.leafNodes = this.getFlattedNodes(true, false);
  24. }
  25. appendNode(nodeData, parentNode) {
  26. const node = new Node(nodeData, this.config, parentNode);
  27. const children = parentNode ? parentNode.children : this.nodes;
  28. children.push(node);
  29. }
  30. appendNodes(nodeDataList, parentNode) {
  31. nodeDataList = coerceTruthyValueToArray(nodeDataList);
  32. nodeDataList.forEach(nodeData => this.appendNode(nodeData, parentNode));
  33. }
  34. getNodes() {
  35. return this.nodes;
  36. }
  37. getFlattedNodes(leafOnly, cached = true) {
  38. const cachedNodes = leafOnly ? this.leafNodes : this.flattedNodes;
  39. return cached
  40. ? cachedNodes
  41. : flatNodes(this.nodes, leafOnly);
  42. }
  43. getNodeByValue(value) {
  44. if (value) {
  45. const nodes = this.getFlattedNodes(false, !this.config.lazy)
  46. .filter(node => (valueEquals(node.path, value) || node.value === value));
  47. return nodes && nodes.length ? nodes[0] : null;
  48. }
  49. return null;
  50. }
  51. }