refactor to make arrow key handlers into methods of *View

Signed-off-by: Jakub Sokołowski <jakub@status.im>
This commit is contained in:
Jakub Sokołowski 2019-06-26 18:18:34 -04:00 committed by Jakub
parent ccad242463
commit 176330a41f
2 changed files with 58 additions and 51 deletions

12
keys.go
View File

@ -12,8 +12,15 @@ type Binding struct {
Handler func(g *gocui.Gui, v *gocui.View) error Handler func(g *gocui.Gui, v *gocui.View) error
} }
func HandlerCursorDispenser(mod int) func(g *gocui.Gui, v *gocui.View) error { func (vc *View) CursorUp(g *gocui.Gui, v *gocui.View) error {
return func(g *gocui.Gui, v *gocui.View) error { return MoveCursor(-1, g, v)
}
func (vc *View) CursorDown(g *gocui.Gui, v *gocui.View) error {
return MoveCursor(1, g, v)
}
func MoveCursor(mod int, g *gocui.Gui, v *gocui.View) error {
if v == nil { if v == nil {
return nil return nil
} }
@ -34,4 +41,3 @@ func HandlerCursorDispenser(mod int) func(g *gocui.Gui, v *gocui.View) error {
} }
return nil return nil
} }
}

21
main.go
View File

@ -28,8 +28,7 @@ func main() {
} }
defer g.Close() defer g.Close()
views := []*View{ mainView := &View{
&View{
Name: "main", Name: "main",
Title: "Peers", Title: "Peers",
Placeholder: "Loading peers...", Placeholder: "Loading peers...",
@ -38,19 +37,20 @@ func main() {
Current: true, Current: true,
SelFgColor: gocui.ColorBlack, SelFgColor: gocui.ColorBlack,
SelBgColor: gocui.ColorGreen, SelBgColor: gocui.ColorGreen,
Keybindings: []Binding{
Binding{gocui.KeyCtrlC, gocui.ModNone, quit},
Binding{gocui.KeyArrowUp, gocui.ModNone, HandlerCursorDispenser(-1)},
Binding{gocui.KeyArrowDown, gocui.ModNone, HandlerCursorDispenser(1)},
},
TopLeft: func(mx, my int) (int, int) { TopLeft: func(mx, my int) (int, int) {
return 0, 0 return 0, 0
}, },
BotRight: func(mx, my int) (int, int) { BotRight: func(mx, my int) (int, int) {
return mx - 1, my / 2 return mx - 1, my / 2
}, },
}, }
&View{ // bindings defined separately so handlers can reference mainView
mainView.Keybindings = []Binding{
Binding{gocui.KeyCtrlC, gocui.ModNone, quit},
Binding{gocui.KeyArrowUp, gocui.ModNone, mainView.CursorUp},
Binding{gocui.KeyArrowDown, gocui.ModNone, mainView.CursorDown},
}
infoView := &View{
Name: "info", Name: "info",
Title: "Details", Title: "Details",
Placeholder: "Loading details...", Placeholder: "Loading details...",
@ -60,9 +60,10 @@ func main() {
BotRight: func(mx, my int) (int, int) { BotRight: func(mx, my int) (int, int) {
return mx - 1, my - 1 return mx - 1, my - 1
}, },
},
} }
views := []*View{mainView, infoView}
vm := NewViewManager(g, views) vm := NewViewManager(g, views)
g.SetManagerFunc(vm.Layout) g.SetManagerFunc(vm.Layout)