2 export class TreeNode {
9 // True if child nodes should be visible
20 // Optional link to user-provided stuff.
21 // This field is ignored by the tree.
24 constructor(values: {[key: string]: any}) {
28 this.selected = false;
30 if (!values) { return; }
32 if ('id' in values) { this.id = values.id; }
33 if ('label' in values) { this.label = values.label; }
34 if ('children' in values) { this.children = values.children; }
35 if ('expanded' in values) { this.expanded = values.expanded; }
36 if ('callerData' in values) { this.callerData = values.callerData; }
40 this.expanded = !this.expanded;
47 idMap: {[id: string]: TreeNode};
49 constructor(rootNode?: TreeNode) {
50 this.rootNode = rootNode;
54 // Returns a depth-first list of tree nodes
55 // Tweaks node attributes along the way to match the shape of the tree.
56 nodeList(filterHidden?: boolean): TreeNode[] {
61 (node: TreeNode, depth: number, hidden: boolean) => {
62 if (!node) { return; }
65 this.idMap[node.id + ''] = node;
68 // it could be confusing for a hidden node to be selected.
69 node.selected = false;
72 if (hidden && filterHidden) {
73 // Avoid adding hidden child nodes to the list.
76 node.children.forEach(n => recurseTree(n, depth, !node.expanded));
80 recurseTree(this.rootNode, 0, false);
84 findNode(id: any): TreeNode {
85 if (this.idMap[id + '']) {
86 return this.idMap[id + ''];
88 // nodeList re-indexes all the nodes.
90 return this.idMap[id + ''];
94 findParentNode(node: TreeNode) {
95 const list = this.nodeList();
96 for (let idx = 0; idx < list.length; idx++) {
97 const pnode = list[idx];
98 if (pnode.children.filter(c => c.id === node.id).length) {
105 removeNode(node: TreeNode) {
106 if (!node) { return; }
107 const pnode = this.findParentNode(node);
109 pnode.children = pnode.children.filter(n => n.id !== node.id);
111 this.rootNode = null;
116 this.nodeList().forEach(node => node.expanded = true);
120 this.nodeList().forEach(node => node.expanded = false);
123 selectedNode(): TreeNode {
124 return this.nodeList().filter(node => node.selected)[0];
127 selectNode(node: TreeNode) {
128 this.nodeList().forEach(n => n.selected = false);
129 node.selected = true;