termui/_examples/tree.go

128 lines
2.0 KiB
Go
Raw Normal View History

2019-04-16 19:57:06 +08:00
/// +build ignore
package main
import (
"log"
ui "github.com/gizak/termui/v3"
"github.com/gizak/termui/v3/widgets"
)
type nodeValue string
func (nv nodeValue) String() string {
return string(nv)
}
func main() {
if err := ui.Init(); err != nil {
log.Fatalf("failed to initialize termui: %v", err)
}
defer ui.Close()
nodes := []*widgets.TreeNode{
{
Value: nodeValue("Key 1"),
Nodes: []*widgets.TreeNode{
{
Value: nodeValue("Key 1.1"),
Nodes: []*widgets.TreeNode{
{
Value: nodeValue("Key 1.1.1"),
Nodes: nil,
},
{
Value: nodeValue("Key 1.1.2"),
Nodes: nil,
},
},
},
{
Value: nodeValue("Key 1.2"),
Nodes: nil,
},
},
},
{
Value: nodeValue("Key 2"),
Nodes: []*widgets.TreeNode{
{
Value: nodeValue("Key 2.1"),
Nodes: nil,
},
{
Value: nodeValue("Key 2.2"),
Nodes: nil,
},
{
Value: nodeValue("Key 2.3"),
Nodes: nil,
},
},
},
{
Value: nodeValue("Key 3"),
Nodes: nil,
},
}
l := widgets.NewTree()
l.TextStyle = ui.NewStyle(ui.ColorYellow)
l.WrapText = false
2019-05-02 20:50:48 +08:00
l.SetNodes(nodes)
2019-04-16 19:57:06 +08:00
x, y := ui.TerminalDimensions()
l.SetRect(0, 0, x, y)
ui.Render(l)
previousKey := ""
uiEvents := ui.PollEvents()
for {
e := <-uiEvents
switch e.ID {
case "q", "<C-c>":
return
case "j", "<Down>":
l.ScrollDown()
case "k", "<Up>":
l.ScrollUp()
case "<C-d>":
l.ScrollHalfPageDown()
case "<C-u>":
l.ScrollHalfPageUp()
case "<C-f>":
l.ScrollPageDown()
case "<C-b>":
l.ScrollPageUp()
case "g":
if previousKey == "g" {
l.ScrollTop()
}
case "<Home>":
l.ScrollTop()
case "<Enter>":
l.ToggleExpand()
case "G", "<End>":
l.ScrollBottom()
case "E":
l.ExpandAll()
case "C":
l.CollapseAll()
case "<Resize>":
x, y := ui.TerminalDimensions()
l.SetRect(0, 0, x, y)
}
if previousKey == "g" {
previousKey = ""
} else {
previousKey = e.ID
}
ui.Render(l)
}
}