aboutsummaryrefslogtreecommitdiffstats
path: root/termui/msg_popup.go
blob: d0e31634e1de63ce6e0f116101eb5958c4215c62 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package termui

import (
	"fmt"

	"github.com/MichaelMure/go-term-text"
	"github.com/awesome-gocui/gocui"
)

const msgPopupView = "msgPopupView"

const msgPopupErrorTitle = "Error"

type msgPopup struct {
	active  bool
	title   string
	message string
}

func newMsgPopup() *msgPopup {
	return &msgPopup{
		message: "",
	}
}

func (ep *msgPopup) keybindings(g *gocui.Gui) error {
	if err := g.SetKeybinding(msgPopupView, gocui.KeySpace, gocui.ModNone, ep.close); err != nil {
		return err
	}
	if err := g.SetKeybinding(msgPopupView, gocui.KeyEnter, gocui.ModNone, ep.close); err != nil {
		return err
	}
	if err := g.SetKeybinding(msgPopupView, 'q', gocui.ModNone, ep.close); err != nil {
		return err
	}

	return nil
}

func (ep *msgPopup) layout(g *gocui.Gui) error {
	if !ep.active {
		return nil
	}

	maxX, maxY := g.Size()

	width := minInt(60, maxX)
	wrapped, lines := text.Wrap(ep.message, width-2)
	height := minInt(lines+1, maxY-3)
	x0 := (maxX - width) / 2
	y0 := (maxY - height) / 2

	v, err := g.SetView(msgPopupView, x0, y0, x0+width, y0+height, 0)
	if err != nil {
		if !gocui.IsUnknownView(err) {
			return err
		}

		v.Frame = true
		v.Autoscroll = true
	}

	v.Title = ep.title

	v.Clear()
	_, _ = fmt.Fprint(v, wrapped)

	if _, err := g.SetCurrentView(msgPopupView); err != nil {
		return err
	}

	return nil
}

func (ep *msgPopup) close(g *gocui.Gui, v *gocui.View) error {
	ep.active = false
	ep.message = ""
	return g.DeleteView(msgPopupView)
}

func (ep *msgPopup) Activate(title string, message string) {
	ep.active = true
	ep.title = title
	ep.message = message
}

func (ep *msgPopup) UpdateMessage(message string) {
	ep.message = message
}