Debian Codegraph @

demos/treeview/main.go

raw symbols SCIP
1 // Demo code for the TreeView primitive.
2 package main
3
4 import (
5 "os"
6 "path/filepath"
7
8 "github.com/gdamore/tcell/v2"
9 "github.com/rivo/tview"
10 )
11
12 // Show a navigable tree view of the current directory.
13 func main() {
14 rootDir := "."
15 root := tview.NewTreeNode(rootDir).
16 SetColor(tcell.ColorRed)
17 tree := tview.NewTreeView().
18 SetRoot(root).
19 SetCurrentNode(root)
20
21 // A helper function which adds the files and directories of the given path
22 // to the given target node.
23 add := func(target *tview.TreeNode, path string) {
24 files, err := os.ReadDir(path)
25 if err != nil {
26 panic(err)
27 }
28 for _, file := range files {
29 node := tview.NewTreeNode(file.Name()).
30 SetReference(filepath.Join(path, file.Name())).
31 SetSelectable(file.IsDir())
32 if file.IsDir() {
33 node.SetColor(tcell.ColorGreen)
34 }
35 target.AddChild(node)
36 }
37 }
38
39 // Add the current directory to the root node.
40 add(root, rootDir)
41
42 // If a directory was selected, open it.
43 tree.SetSelectedFunc(func(node *tview.TreeNode) {
44 reference := node.GetReference()
45 if reference == nil {
46 return // Selecting the root node does nothing.
47 }
48 children := node.GetChildren()
49 if len(children) == 0 {
50 // Load and show files in this directory.
51 path := reference.(string)
52 add(node, path)
53 } else {
54 // Collapse if visible, expand if collapsed.
55 node.SetExpanded(!node.IsExpanded())
56 }
57 })
58
59 if err := tview.NewApplication().SetRoot(tree, true).EnableMouse(true).Run(); err != nil {
60 panic(err)
61 }
62 }