Add ability to render more than one tree

This commit is contained in:
Nick Krichevsky 2019-05-19 20:05:20 -04:00
parent 9253e4f0df
commit 456f817d67
2 changed files with 10 additions and 5 deletions

View file

@ -42,7 +42,7 @@ func main() {
}
defer termui.Close()
tree := NewTreeWidget([]*Node{buildTree(0)})
tree := NewTreeWidget([]*Node{buildTree(0), buildTree(0)})
width, height := termui.TerminalDimensions()
tree.SetRect(0, 0, width, height)
tree.Block.Border = true

13
tree.go
View file

@ -41,8 +41,9 @@ func NewTreeWidget(rootNodes []*Node) *TreeWidget {
// Draw draws the tree widget
func (tree *TreeWidget) Draw(buffer *termui.Buffer) {
tree.Block.Draw(buffer)
row := tree.Block.Inner.Min.Y
for _, item := range tree.rootNodes {
tree.renderSingleTree(item, buffer)
row = tree.renderSingleTree(item, buffer, row)
}
}
@ -50,7 +51,7 @@ func (tree *TreeWidget) Draw(buffer *termui.Buffer) {
func (tree *TreeWidget) AddRootNode(node *Node) {
tree.rootNodes = append(tree.rootNodes, node)
if len(tree.rootNodes) == 1 {
tree.selectedNode = node
tree.selectedNode = node.children[0]
}
node.setTree(tree)
}
@ -74,12 +75,14 @@ func (tree *TreeWidget) SelectNext() {
}
}
func (tree *TreeWidget) renderSingleTree(root *Node, buffer *termui.Buffer) {
// renderSingleTree renders a node and all its descendents
// Returns the number of rows needed to render it (inculding wrapping)
func (tree *TreeWidget) renderSingleTree(root *Node, buffer *termui.Buffer, startRow int) int {
baseWidth := tree.Inner.Max.X - tree.Inner.Min.X
depths := map[*Node]int{root: 0}
toVisit := []*Node{root}
row := tree.Inner.Min.Y
row := startRow
for len(toVisit) > 0 {
var node *Node
toVisit, node = toVisit[:len(toVisit)-1], toVisit[len(toVisit)-1]
@ -97,6 +100,8 @@ func (tree *TreeWidget) renderSingleTree(root *Node, buffer *termui.Buffer) {
startingCol := tree.Inner.Min.X + currentDepth*indentWidth
row += node.render(buffer, row, startingCol, width)
}
return row
}
// render renders this node in the term ui, and return the number of rows that were required to render it