-
Notifications
You must be signed in to change notification settings - Fork 0
/
ui.go
109 lines (87 loc) · 2 KB
/
ui.go
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package main
import (
"fmt"
"log"
"strings"
tea "github.com/charmbracelet/bubbletea"
"github.com/fatih/color"
"github.com/muesli/reflow/wordwrap"
"golang.org/x/term"
)
type model struct {
users []string
messages []string
input string
}
func (m model) Init() tea.Cmd {
authenticate()
go listen()
return nil
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.Type {
case tea.KeyCtrlC, tea.KeyEscape:
return m, tea.Quit
case tea.KeyEnter:
m.messages = append(m.messages, fmt.Sprintf("\033[34m%s:\033[0m %s", USERNAME, m.input))
IRC.Say(CHANNEL, m.input)
m.input = ""
return m, nil
case tea.KeyBackspace, tea.KeyDelete:
if len(m.input) > 0 {
m.input = m.input[:len(m.input)-1]
}
return m, nil
case tea.KeyCtrlW:
s := strings.TrimRight(m.input, " ")
i := strings.LastIndex(s, " ")
if i == -1 {
m.input = ""
} else {
m.input = s[:i]
}
return m, nil
case tea.KeyCtrlU:
m.input = ""
return m, nil
case tea.KeyTab:
m.input += "\t"
default:
m.input += msg.String()
return m, nil
}
case string:
if idx := strings.Index(msg, USERNAME); idx != -1 {
l := msg[:idx]
r := msg[idx+len(USERNAME):]
msg = l + color.New(color.FgBlack, color.BgYellow).Sprint(USERNAME) + r
}
m.messages = append(m.messages, msg)
return m, nil
}
return m, nil
}
func (m model) View() string {
var b strings.Builder
terminalWidth, terminalHeight, err := term.GetSize(0)
if err != nil {
log.Fatal("error getting terminal size: ", err)
}
numMessages := terminalHeight - 2 // -2 for the input prompt and cursor
padding := numMessages - len(m.messages)
if padding < 0 {
padding = 0
}
for i := 0; i < padding; i++ {
b.WriteRune('\n')
}
for _, msg := range m.messages {
b.WriteString(wordwrap.String(msg, terminalWidth))
b.WriteRune('\n')
}
b.WriteString("\033[32m>\033[0m ")
b.WriteString(wordwrap.String(m.input, terminalWidth-2))
return b.String()
}