/* * @license * Copyright Akveo. All Rights Reserved. * Licensed under the MIT License. See License.txt in the project root for license information. */ import { Injectable } from '@angular/core'; import { NbGetters, NB_DEFAULT_ROW_LEVEL, NbTreeGridPresentationNode } from './tree-grid.model'; @Injectable() export class NbTreeGridDataService { private defaultGetters: NbGetters = { dataGetter: node => node.data, childrenGetter: d => d.children || undefined, expandedGetter: d => !!d.expanded, }; toPresentationNodes( nodes: N[], customGetters?: NbGetters, level: number = NB_DEFAULT_ROW_LEVEL, ): NbTreeGridPresentationNode[] { const getters: NbGetters = { ...this.defaultGetters, ...customGetters }; return this.mapNodes(nodes, getters, level); } private mapNodes(nodes: N[], getters: NbGetters, level: number): NbTreeGridPresentationNode[] { const { dataGetter, childrenGetter, expandedGetter } = getters; return nodes.map(node => { const childrenNodes = childrenGetter(node); let children: NbTreeGridPresentationNode[]; if (childrenNodes) { children = this.toPresentationNodes(childrenNodes, getters, level + 1); } return new NbTreeGridPresentationNode(dataGetter(node), children, expandedGetter(node), level); }); } flattenExpanded(nodes: NbTreeGridPresentationNode[]): NbTreeGridPresentationNode[] { return nodes.reduce((res: NbTreeGridPresentationNode[], node: NbTreeGridPresentationNode) => { res.push(node); if (node.expanded && node.hasChildren()) { res.push(...this.flattenExpanded(node.children)); } return res; }, []); } copy(nodes: NbTreeGridPresentationNode[]): NbTreeGridPresentationNode[] { return nodes.map((node: NbTreeGridPresentationNode) => { let children: NbTreeGridPresentationNode[]; if (node.hasChildren()) { children = this.copy(node.children); } return new NbTreeGridPresentationNode(node.data, children, node.expanded, node.level); }); } }