|
| 1 | +// Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +// Licensed under the MIT license. |
| 3 | + |
| 4 | +import { INodeData, NodeKind } from "./nodeData"; |
| 5 | + |
| 6 | +export class HierachicalPackageNodeData implements INodeData { |
| 7 | + |
| 8 | + public static createHierachicalNodeDataByPackageList(packageList: INodeData[]): HierachicalPackageNodeData { |
| 9 | + const result = new HierachicalPackageNodeData("", ""); |
| 10 | + packageList.forEach((nodeData) => result.addSubPackage(nodeData.name.split("."), nodeData)); |
| 11 | + result.compressTree(); |
| 12 | + return result; |
| 13 | + } |
| 14 | + |
| 15 | + public name: string; |
| 16 | + public children = []; |
| 17 | + public displayName: string; |
| 18 | + private nodeData: INodeData = null; |
| 19 | + |
| 20 | + public get uri() { |
| 21 | + return this.nodeData.uri; |
| 22 | + } |
| 23 | + |
| 24 | + public get moduleName() { |
| 25 | + return this.nodeData.moduleName; |
| 26 | + } |
| 27 | + |
| 28 | + public get path() { |
| 29 | + return this.nodeData.path; |
| 30 | + } |
| 31 | + |
| 32 | + public get kind() { |
| 33 | + return this.nodeData ? this.nodeData.kind : NodeKind.Package; |
| 34 | + } |
| 35 | + |
| 36 | + public get isPackage() { |
| 37 | + return this.nodeData !== null; |
| 38 | + } |
| 39 | + |
| 40 | + private constructor(displayName: string, parentName: string) { |
| 41 | + this.displayName = displayName; |
| 42 | + this.name = parentName === "" ? displayName : parentName + "." + displayName; |
| 43 | + } |
| 44 | + |
| 45 | + private compressTree(): void { |
| 46 | + // Don't compress the root node |
| 47 | + while (this.name !== "" && this.children.length === 1 && !this.isPackage) { |
| 48 | + const child = this.children[0]; |
| 49 | + this.name = this.name + "." + child.displayName; |
| 50 | + this.displayName = this.displayName + "." + child.displayName; |
| 51 | + this.children = child.children; |
| 52 | + this.nodeData = child.nodeData; |
| 53 | + } |
| 54 | + this.children.forEach((child) => child.compressTree()); |
| 55 | + } |
| 56 | + |
| 57 | + private addSubPackage(packages: string[], nodeData: INodeData): void { |
| 58 | + if (!packages.length) { |
| 59 | + this.nodeData = nodeData; |
| 60 | + return; |
| 61 | + } |
| 62 | + const subPackageDisplayName = packages.shift(); |
| 63 | + const childNode = this.children.find((child) => child.displayName === subPackageDisplayName); |
| 64 | + if (childNode) { |
| 65 | + childNode.addSubPackage(packages); |
| 66 | + } else { |
| 67 | + const newNode = new HierachicalPackageNodeData(subPackageDisplayName, this.name); |
| 68 | + newNode.addSubPackage(packages, nodeData); |
| 69 | + this.children.push(newNode); |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments