1package termui
2
3import (
4 "errors"
5 "fmt"
6
7 text "github.com/MichaelMure/go-term-text"
8 "github.com/awesome-gocui/gocui"
9)
10
11const msgPopupView = "msgPopupView"
12
13const msgPopupErrorTitle = "Error"
14
15type msgPopup struct {
16 active bool
17 title string
18 message string
19}
20
21func newMsgPopup() *msgPopup {
22 return &msgPopup{
23 message: "",
24 }
25}
26
27func (ep *msgPopup) keybindings(g *gocui.Gui) error {
28 if err := g.SetKeybinding(msgPopupView, gocui.KeySpace, gocui.ModNone, ep.close); err != nil {
29 return err
30 }
31 if err := g.SetKeybinding(msgPopupView, gocui.KeyEnter, gocui.ModNone, ep.close); err != nil {
32 return err
33 }
34 if err := g.SetKeybinding(msgPopupView, 'q', gocui.ModNone, ep.close); err != nil {
35 return err
36 }
37
38 return nil
39}
40
41func (ep *msgPopup) layout(g *gocui.Gui) error {
42 if !ep.active {
43 return nil
44 }
45
46 maxX, maxY := g.Size()
47
48 width := minInt(60, maxX)
49 wrapped, lines := text.Wrap(ep.message, width-2)
50 height := minInt(lines+1, maxY-3)
51 x0 := (maxX - width) / 2
52 y0 := (maxY - height) / 2
53
54 v, err := g.SetView(msgPopupView, x0, y0, x0+width, y0+height, 0)
55 if err != nil {
56 if !errors.Is(err, gocui.ErrUnknownView) {
57 return err
58 }
59
60 v.Frame = true
61 v.Autoscroll = true
62 }
63
64 v.Title = ep.title
65
66 v.Clear()
67 _, _ = fmt.Fprint(v, wrapped)
68
69 if _, err := g.SetCurrentView(msgPopupView); err != nil {
70 return err
71 }
72
73 return nil
74}
75
76func (ep *msgPopup) close(g *gocui.Gui, v *gocui.View) error {
77 ep.active = false
78 ep.message = ""
79 return g.DeleteView(msgPopupView)
80}
81
82func (ep *msgPopup) Activate(title string, message string) {
83 ep.active = true
84 ep.title = title
85 ep.message = message
86}
87
88func (ep *msgPopup) UpdateMessage(message string) {
89 ep.message = message
90}