git-bug/termui/input_popup.go

109 lines
1.9 KiB
Go
Raw Normal View History

2018-08-12 03:42:03 +03:00
package termui
import (
2022-02-15 23:52:36 +03:00
"errors"
2018-08-12 03:42:03 +03:00
"io/ioutil"
"github.com/awesome-gocui/gocui"
2018-08-12 03:42:03 +03:00
)
const inputPopupView = "inputPopupView"
2018-09-11 20:28:32 +03:00
// inputPopup is a simple popup with an input field
2018-08-12 03:42:03 +03:00
type inputPopup struct {
2018-09-11 20:28:32 +03:00
active bool
title string
preload string
c chan string
2018-08-12 03:42:03 +03:00
}
func newInputPopup() *inputPopup {
return &inputPopup{}
}
func (ip *inputPopup) keybindings(g *gocui.Gui) error {
// Close
if err := g.SetKeybinding(inputPopupView, gocui.KeyEsc, gocui.ModNone, ip.close); err != nil {
return err
}
// Validate
if err := g.SetKeybinding(inputPopupView, gocui.KeyEnter, gocui.ModNone, ip.validate); err != nil {
return err
}
return nil
}
func (ip *inputPopup) layout(g *gocui.Gui) error {
if !ip.active {
return nil
}
maxX, maxY := g.Size()
width := minInt(30, maxX)
height := 2
x0 := (maxX - width) / 2
y0 := (maxY - height) / 2
v, err := g.SetView(inputPopupView, x0, y0, x0+width, y0+height, 0)
2018-08-12 03:42:03 +03:00
if err != nil {
2022-02-15 23:52:36 +03:00
if !errors.Is(err, gocui.ErrUnknownView) {
2018-08-12 03:42:03 +03:00
return err
}
v.Frame = true
v.Title = ip.title
v.Editable = true
2018-09-13 13:43:47 +03:00
_, err = v.Write([]byte(ip.preload))
if err != nil {
return err
}
2018-08-12 03:42:03 +03:00
}
if _, err := g.SetCurrentView(inputPopupView); err != nil {
return err
}
return nil
}
func (ip *inputPopup) close(g *gocui.Gui, v *gocui.View) error {
ip.title = ""
ip.active = false
return g.DeleteView(inputPopupView)
}
func (ip *inputPopup) validate(g *gocui.Gui, v *gocui.View) error {
ip.title = ""
content, err := ioutil.ReadAll(v)
if err != nil {
return err
}
ip.title = ""
ip.active = false
err = g.DeleteView(inputPopupView)
if err != nil {
return err
}
ip.c <- string(content)
return nil
}
2018-09-11 20:28:32 +03:00
func (ip *inputPopup) ActivateWithContent(title string, content string) <-chan string {
ip.preload = content
return ip.Activate(title)
}
2018-08-12 03:42:03 +03:00
func (ip *inputPopup) Activate(title string) <-chan string {
ip.title = title
ip.active = true
ip.c = make(chan string)
return ip.c
}