object-oriented ascii tree renderer
npm install oo-ascii-treeRenders ASCII trees from an object-oriented object graph.
Features:
* Multiline text
* Multiple root nodes
Roadmap:
* Customization of tree formatting and indentation size
``console`
$ npm i oo-ascii-tree
`ts
import { AsciiTree } from '../lib';
const tree = new AsciiTree('root');
tree.add(new AsciiTree('child1'));
tree.add(new AsciiTree('child2',
new AsciiTree('grandchild1'),
new AsciiTree('grandchild2')
));
tree.add(new AsciiTree('child3'));
tree.printTree();
`
Prints the following tree to stdout:
``
root
├── child1
├─┬ child2
│ ├── grandchild1
│ └── grandchild2
└── child3
You can also subclass AsciiTree to encapsulate some model. The followingTitleNode
example declares a which formats a title with "====" underline and aKeyValueNode which formats text as key: value:
`ts
class TitleNode extends AsciiTree {
constructor(title: string, ...children: AsciiTree[]) {
super([
title.toLocaleUpperCase(),
'='.repeat(title.length)
].join('\n'), ...children);
}
}
class KeyValueNode extends AsciiTree {
constructor(key: string, value: string) {
super(${key}: ${value});
}
}
const tree = new AsciiTree();
tree.add(new TitleNode('props',
new KeyValueNode('shape', 'circle'),
new KeyValueNode('color', 'red'),
new KeyValueNode('background', 'blue')
));
tree.add(new TitleNode('dimensions',
new KeyValueNode('width', '30px'),
new KeyValueNode('height', '40px')
));
`
Will emit the following output:
``
PROPS
=====
├── shape: circle
├── color: red
└── background: blue
DIMENSIONS
==========
├── width: 30px
└── height: 40px
The AsciiTree class represents a tree/node/subtree. Each node in the treetext
includes and children and can be printed to a Writable viaprintTree(stream).
Creates a new node with the specified text and optionally adds child nodes to it.
If text is not specified, the children of this node will all be considered
roots (level 0) and the root node will get level -1. This allows modeling trees
with a single root or with multiple roots.
Adds one or more children to the node.
Emits an ASCII print out of the tree to the specified Writable stream. Theprocess.stdout
default is .
Returns a string representation of the tree.
The node's text. If the text contains multiple line separated by \n, new lines
will be aligned to the node's indentation.
Returns a copy of the array of children of this node. Use asciiTree.add to add
children.
Returns true if this is the root node.
Returns true if this is the last child of a node.
Returns the node level. Root node(s) will have a level of 0.
If the root AsciiTree has text, it's level will be 0 and its children will getAsciiTree
level 1. If the root does not have text, it's level will be -1 and
all it's children will get level 0.
Returns true` if this node does not have any children.
Returns all the nodes that are ancestors of this node ordered from root to the
direct parent.
Distributed under the Apache License, Version 2.0.