forked from waku-org/go-waku
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathui.go
344 lines (280 loc) · 7.41 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
package main
import (
"fmt"
"strings"
"time"
"github.com/charmbracelet/bubbles/key"
"github.com/charmbracelet/bubbles/spinner"
"github.com/charmbracelet/bubbles/textarea"
"github.com/charmbracelet/bubbles/viewport"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/muesli/reflow/wordwrap"
"github.com/waku-org/go-waku/waku/v2/utils"
)
const viewportMargin = 6
var (
appStyle = lipgloss.NewStyle().Padding(1, 2)
titleStyle = func() lipgloss.Style {
b := lipgloss.RoundedBorder()
b.Right = "├"
return lipgloss.NewStyle().BorderStyle(b).Padding(0, 1)
}().Render
errorStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("9")).Render
infoStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("4")).Render
senderStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("5")).Render
)
type errMsg error
type sending bool
type quit bool
type MessageType int
const (
ChatMessageType MessageType = iota
InfoMessageType
ErrorMessageType
)
type message struct {
mType MessageType
err error
author string
clock time.Time
content string
}
type UI struct {
ready bool
err error
quitChan chan struct{}
readyChan chan<- struct{}
inputChan chan<- string
messageChan chan message
messages []message
isSendingChan chan sending
isSending bool
width int
height int
viewport viewport.Model
textarea textarea.Model
spinner spinner.Model
}
func NewUIModel(readyChan chan<- struct{}, inputChan chan<- string) UI {
width, height := GetTerminalDimensions()
ta := textarea.New()
ta.Placeholder = "Send a message..."
ta.Focus()
ta.Prompt = "┃ "
ta.CharLimit = 2000
// Remove cursor line styling
ta.FocusedStyle.CursorLine = lipgloss.NewStyle()
ta.SetHeight(3)
ta.SetWidth(width)
ta.ShowLineNumbers = false
ta.KeyMap.InsertNewline.SetEnabled(false)
s := spinner.New()
s.Spinner = spinner.Jump
s.Style = lipgloss.NewStyle().Foreground(lipgloss.Color("205"))
m := UI{
messageChan: make(chan message, 100),
isSendingChan: make(chan sending, 100),
quitChan: make(chan struct{}),
readyChan: readyChan,
inputChan: inputChan,
width: width,
height: height,
textarea: ta,
spinner: s,
err: nil,
}
return m
}
func (m UI) Init() tea.Cmd {
return tea.Batch(
recvQuitSignal(m.quitChan),
recvMessages(m.messageChan),
recvSendingState(m.isSendingChan),
textarea.Blink,
spinner.Tick,
)
}
func (m UI) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var (
tiCmd tea.Cmd
vpCmd tea.Cmd
)
m.textarea, tiCmd = m.textarea.Update(msg)
m.viewport, vpCmd = m.viewport.Update(msg)
var cmdToReturn []tea.Cmd = []tea.Cmd{tiCmd, vpCmd}
headerHeight := lipgloss.Height(m.headerView())
printMessages := false
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.width, m.height = msg.Width, msg.Height
if !m.ready {
// Since this program is using the full size of the viewport we
// need to wait until we've received the window dimensions before
// we can initialize the viewport. The initial dimensions come in
// quickly, though asynchronously, which is why we wait for them
// here.
m.viewport = viewport.New(msg.Width, msg.Height-headerHeight-viewportMargin)
m.viewport.SetContent("")
m.viewport.YPosition = headerHeight + 1
m.viewport.KeyMap = DefaultKeyMap()
m.ready = true
close(m.readyChan)
} else {
m.viewport.Width = msg.Width
m.viewport.Height = msg.Height - headerHeight - viewportMargin
}
printMessages = true
case tea.KeyMsg:
switch msg.Type {
case tea.KeyCtrlC, tea.KeyEsc:
return m, tea.Quit
case tea.KeyEnter:
line := m.textarea.Value()
if len(line) != 0 {
m.inputChan <- line
m.textarea.Reset()
}
}
// We handle errors just like any other message
case errMsg:
m.err = msg
return m, nil
case message:
m.messages = append(m.messages, msg)
printMessages = true
cmdToReturn = append(cmdToReturn, recvMessages(m.messageChan))
case quit:
fmt.Println("Bye!")
return m, tea.Quit
case sending:
m.isSending = bool(msg)
cmdToReturn = append(cmdToReturn, recvSendingState(m.isSendingChan))
case spinner.TickMsg:
var cmd tea.Cmd
m.spinner, cmd = m.spinner.Update(msg)
return m, cmd
}
if printMessages {
var sb strings.Builder
for i, msg := range m.messages {
line := ""
switch msg.mType {
case ChatMessageType:
line += m.breaklineIfNeeded(i, ChatMessageType)
msgLine := "[" + msg.clock.Format("Jan 02 15:04") + " " + senderStyle(msg.author) + "] "
msgLine += msg.content
line += wordwrap.String(line+msgLine, m.width-10)
case ErrorMessageType:
line += m.breaklineIfNeeded(i, ErrorMessageType)
line += wordwrap.String(errorStyle("ERROR:")+" "+msg.err.Error(), m.width-10)
utils.Logger().Error(msg.content)
case InfoMessageType:
line += m.breaklineIfNeeded(i, InfoMessageType)
line += wordwrap.String(infoStyle("INFO:")+" "+msg.content, m.width-10)
utils.Logger().Info(msg.content)
}
sb.WriteString(line + "\n")
}
m.viewport.SetContent(sb.String())
m.viewport.GotoBottom()
}
return m, tea.Batch(cmdToReturn...)
}
func (m UI) breaklineIfNeeded(i int, mt MessageType) string {
result := ""
if i > 0 {
if (mt == ChatMessageType && m.messages[i-1].mType != ChatMessageType) || (mt != ChatMessageType && m.messages[i-1].mType == ChatMessageType) {
result += "\n"
}
}
return result
}
func (m UI) headerView() string {
title := titleStyle("Chat2 •")
line := strings.Repeat("─", max(0, m.viewport.Width-lipgloss.Width(title)-4))
return lipgloss.JoinHorizontal(lipgloss.Center, title, line)
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func (m UI) View() string {
spinnerStr := ""
inputStr := ""
if m.isSending {
spinnerStr = m.spinner.View() + " Sending message..."
} else {
inputStr = m.textarea.View()
}
return appStyle.Render(fmt.Sprintf(
"%s\n%s\n%s%s\n",
m.headerView(),
m.viewport.View(),
inputStr,
spinnerStr,
),
)
}
func recvMessages(sub chan message) tea.Cmd {
return func() tea.Msg {
return <-sub
}
}
func recvSendingState(sub chan sending) tea.Cmd {
return func() tea.Msg {
return <-sub
}
}
func recvQuitSignal(q chan struct{}) tea.Cmd {
return func() tea.Msg {
<-q
return quit(true)
}
}
func (m UI) Quit() {
m.quitChan <- struct{}{}
}
func (m UI) SetSending(isSending bool) {
m.isSendingChan <- sending(isSending)
}
func (m UI) ErrorMessage(err error) {
m.messageChan <- message{mType: ErrorMessageType, err: err}
}
func (m UI) InfoMessage(text string) {
m.messageChan <- message{mType: InfoMessageType, content: text}
}
func (m UI) ChatMessage(clock int64, author string, text string) {
m.messageChan <- message{mType: ChatMessageType, author: author, content: text, clock: time.Unix(clock, 0)}
}
// DefaultKeyMap returns a set of pager-like default keybindings.
func DefaultKeyMap() viewport.KeyMap {
return viewport.KeyMap{
PageDown: key.NewBinding(
key.WithKeys("pgdown"),
key.WithHelp("pgdn", "page down"),
),
PageUp: key.NewBinding(
key.WithKeys("pgup"),
key.WithHelp("pgup", "page up"),
),
HalfPageUp: key.NewBinding(
key.WithKeys("ctrl+u"),
key.WithHelp("ctrl+u", "½ page up"),
),
HalfPageDown: key.NewBinding(
key.WithKeys("ctrl+d"),
key.WithHelp("ctrl+d", "½ page down"),
),
Up: key.NewBinding(
key.WithKeys("up"),
key.WithHelp("↑", "up"),
),
Down: key.NewBinding(
key.WithKeys("down"),
key.WithHelp("↓", "down"),
),
}
}