2018-10-17 23:40:28 +08:00
|
|
|
// Demo code for the TreeView primitive.
|
2018-06-20 16:06:05 +08:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2023-10-06 04:26:32 +08:00
|
|
|
"os"
|
2018-06-20 16:06:05 +08:00
|
|
|
"path/filepath"
|
|
|
|
|
2020-10-18 20:15:57 +08:00
|
|
|
"github.com/gdamore/tcell/v2"
|
2018-06-20 16:06:05 +08:00
|
|
|
"github.com/rivo/tview"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Show a navigable tree view of the current directory.
|
|
|
|
func main() {
|
|
|
|
rootDir := "."
|
|
|
|
root := tview.NewTreeNode(rootDir).
|
|
|
|
SetColor(tcell.ColorRed)
|
|
|
|
tree := tview.NewTreeView().
|
|
|
|
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 *tview.TreeNode, path string) {
|
2023-10-06 04:26:32 +08:00
|
|
|
files, err := os.ReadDir(path)
|
2018-06-20 16:06:05 +08:00
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
for _, file := range files {
|
|
|
|
node := tview.NewTreeNode(file.Name()).
|
|
|
|
SetReference(filepath.Join(path, file.Name())).
|
|
|
|
SetSelectable(file.IsDir())
|
|
|
|
if file.IsDir() {
|
|
|
|
node.SetColor(tcell.ColorGreen)
|
|
|
|
}
|
|
|
|
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 *tview.TreeNode) {
|
|
|
|
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())
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
2020-03-28 04:13:03 +08:00
|
|
|
if err := tview.NewApplication().SetRoot(tree, true).EnableMouse(true).Run(); err != nil {
|
2018-06-20 16:06:05 +08:00
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
}
|