util.go

 1package util
 2
 3import (
 4	"time"
 5
 6	tea "github.com/charmbracelet/bubbletea/v2"
 7)
 8
 9type Model interface {
10	tea.Model
11	tea.Viewable
12}
13
14func CmdHandler(msg tea.Msg) tea.Cmd {
15	return func() tea.Msg {
16		return msg
17	}
18}
19
20func ReportError(err error) tea.Cmd {
21	return CmdHandler(InfoMsg{
22		Type: InfoTypeError,
23		Msg:  err.Error(),
24	})
25}
26
27type InfoType int
28
29const (
30	InfoTypeInfo InfoType = iota
31	InfoTypeWarn
32	InfoTypeError
33)
34
35func ReportInfo(info string) tea.Cmd {
36	return CmdHandler(InfoMsg{
37		Type: InfoTypeInfo,
38		Msg:  info,
39	})
40}
41
42func ReportWarn(warn string) tea.Cmd {
43	return CmdHandler(InfoMsg{
44		Type: InfoTypeWarn,
45		Msg:  warn,
46	})
47}
48
49type (
50	InfoMsg struct {
51		Type InfoType
52		Msg  string
53		TTL  time.Duration
54	}
55	ClearStatusMsg struct{}
56)
57
58func Clamp(v, low, high int) int {
59	if high < low {
60		low, high = high, low
61	}
62	return min(high, max(low, v))
63}