UNPKG

es-grid-template

Version:

es-grid-template

97 lines (92 loc) 2.21 kB
import isLeafNode from "../isLeafNode"; import { arrayUtils } from "../others"; class Wrapper { constructor(input) { Object.assign(this, input); } /** Whether this is a root node */ root; /** Array of child nodes */ children; /** Parent node (parent wrapper node) */ parent; /** Reference to the corresponding original node */ // @ts-ignore node; /** Whether the node is checked (selected) */ checked; } export default class StrictTreeDataHelper { opts; valueSet; // @ts-ignore wrapperMap; // @ts-ignore rootWrapper; constructor(opts) { this.opts = opts; this.valueSet = new Set(opts.value); this.initWrapperTree(); } initWrapperTree() { const { getNodeValue } = this.opts; this.rootWrapper = new Wrapper({ root: true, children: [] }); this.wrapperMap = new Map(); const dfs = (parentWrapper, nodes) => { for (const node of nodes) { const wrapper = new Wrapper({ parent: parentWrapper, node, checked: this.valueSet.has(getNodeValue(node)) }); this.wrapperMap.set(getNodeValue(node), wrapper); // @ts-ignore parentWrapper.children.push(wrapper); if (!isLeafNode(node)) { wrapper.children = []; dfs(wrapper, node.children); } } }; dfs(this.rootWrapper, this.opts.tree); } get value() { return this.opts.value; } isIndeterminate() { return false; } isChecked(nodeValue) { return this.valueSet.has(nodeValue); } getValueAfterCheck(nodeValue) { if (!this.isChecked(nodeValue)) { return arrayUtils.merge(this.value, [nodeValue]); } return this.value; } getValueAfterUncheck(nodeValue) { if (this.isChecked(nodeValue)) { return arrayUtils.diff(this.value, [nodeValue]); } return this.value; } getValueAfterToggle(nodeValue) { if (this.isChecked(nodeValue)) { return this.getValueAfterUncheck(nodeValue); } else { return this.getValueAfterCheck(nodeValue); } } getNode(nodeValue) { return this.wrapperMap.get(nodeValue)?.node; } getCleanValue() { return this.value; } }