cview/demos/treeview/main.go

63 lines
1.5 KiB
Go
Raw Normal View History

// Demo code for the TreeView primitive.
2018-06-20 08:06:05 +00:00
package main
import (
"io/ioutil"
"path/filepath"
2020-08-30 15:36:03 +00:00
"github.com/gdamore/tcell/v2"
2020-01-22 23:28:19 +00:00
"gitlab.com/tslocum/cview"
2018-06-20 08:06:05 +00:00
)
// Show a navigable tree view of the current directory.
func main() {
rootDir := "."
root := cview.NewTreeNode(rootDir).
2020-08-30 15:36:03 +00:00
SetColor(tcell.ColorRed.TrueColor())
tree := cview.NewTreeView().
2018-06-20 08:06:05 +00:00
SetRoot(root).
SetCurrentNode(root)
// A helper function which adds the files and directories of the given path
// to the given target node.
add := func(target *cview.TreeNode, path string) {
2018-06-20 08:06:05 +00:00
files, err := ioutil.ReadDir(path)
if err != nil {
panic(err)
}
for _, file := range files {
node := cview.NewTreeNode(file.Name()).
2018-06-20 08:06:05 +00:00
SetReference(filepath.Join(path, file.Name())).
SetSelectable(file.IsDir())
if file.IsDir() {
2020-08-30 15:36:03 +00:00
node.SetColor(tcell.ColorGreen.TrueColor())
2018-06-20 08:06:05 +00:00
}
target.AddChild(node)
}
}
// Add the current directory to the root node.
add(root, rootDir)
// If a directory was selected, open it.
tree.SetSelectedFunc(func(node *cview.TreeNode) {
2018-06-20 08:06:05 +00:00
reference := node.GetReference()
if reference == nil {
return // Selecting the root node does nothing.
}
children := node.GetChildren()
if len(children) == 0 {
// Load and show files in this directory.
path := reference.(string)
add(node, path)
} else {
// Collapse if visible, expand if collapsed.
node.SetExpanded(!node.IsExpanded())
}
})
if err := cview.NewApplication().SetRoot(tree, true).EnableMouse(true).Run(); err != nil {
2018-06-20 08:06:05 +00:00
panic(err)
}
}