-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogram_tui.go
More file actions
435 lines (386 loc) · 11.9 KB
/
Copy pathprogram_tui.go
File metadata and controls
435 lines (386 loc) · 11.9 KB
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
//go:build !js
package wui
import (
"fmt"
"net/http"
"strings"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
zone "github.com/lrstanley/bubblezone"
"github.com/suprbdev/wui/webserver"
)
type platformState struct {
teaProgram *tea.Program
adapter *teaAdapter
}
func newProgram(m Model, cfg config) *Program {
zones := zone.New()
adapter := &teaAdapter{
model: m,
renderer: newTUIRenderer(80, 24, zones),
focus: newTUIFocusManager(),
zones: zones,
}
p := &Program{
model: m,
cfg: cfg,
platformState: platformState{
adapter: adapter,
},
}
// The adapter needs the Program to resolve the status line, which
// depends on the live model and on config.
adapter.program = p
opts := []tea.ProgramOption{}
if !cfg.noAltScreen {
opts = append(opts, tea.WithAltScreen())
}
if !cfg.noMouse {
opts = append(opts, tea.WithMouseCellMotion())
}
p.teaProgram = tea.NewProgram(adapter, opts...)
return p
}
func (p *Program) run() error {
if p.cfg.serveEnabled {
ln, err := webserver.Listen(p.cfg.serveAddr)
if err != nil {
return fmt.Errorf("wui: web server: %w", err)
}
defer ln.Close()
go http.Serve(ln, http.FileServer(http.Dir(p.cfg.webDir)))
p.adapter.serveURL = webserver.URL(ln.Addr())
}
final, err := p.teaProgram.Run()
if a, ok := final.(*teaAdapter); ok {
p.model = a.model
}
return err
}
// webStatusURL returns the URL of the served web build, including the
// model's current path, or "" when WithWebServer is not active.
func (p *Program) webStatusURL() string {
if p.adapter == nil || p.adapter.serveURL == "" {
return ""
}
return p.adapter.serveURL + p.pathSuffix()
}
// teaAdapter bridges a wui.Model into a tea.Model.
type teaAdapter struct {
model Model
renderer *tuiRenderer
focus *tuiFocusManager
zones *zone.Manager
serveURL string // non-empty when WithWebServer is active
program *Program
}
func (a *teaAdapter) Init() tea.Cmd {
cmds := []tea.Cmd{wuiCmdToTea(a.model.Init())}
if a.program != nil && a.program.cfg.title != "" {
cmds = append(cmds, tea.SetWindowTitle(a.program.cfg.title))
}
return tea.Batch(cmds...)
}
func (a *teaAdapter) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch m := msg.(type) {
case tea.WindowSizeMsg:
a.renderer.Width = m.Width
a.renderer.Height = m.Height
return a, a.apply(ResizeMsg{Width: m.Width, Height: m.Height})
case tea.KeyMsg:
return a.handleKey(m)
case tea.MouseMsg:
return a.handleMouse(m)
case QuitMsg:
return a, tea.Quit
case BatchMsg:
// Deliver each batched Msg through Update in order, collecting
// the Cmds they return.
var cmds []tea.Cmd
for _, sub := range unpackBatch(m) {
if _, isQuit := sub.(QuitMsg); isQuit {
return a, tea.Quit
}
cmds = append(cmds, a.apply(sub))
}
return a, tea.Batch(cmds...)
default:
// Anything else (including app-defined Msg values returned
// from a Cmd and sent back via tea) goes straight to the
// user's Update.
return a, a.apply(m)
}
}
// apply runs one Msg through the user's Update, stores the new model,
// and converts the returned Cmd. It is the single funnel every message
// path goes through, so model replacement never gets skipped.
func (a *teaAdapter) apply(msg Msg) tea.Cmd {
newModel, cmd := a.model.Update(msg)
a.model = newModel
a.syncProgramModel()
return wuiCmdToTea(cmd)
}
// syncProgramModel keeps Program.model pointing at the live model, so
// StatusFunc and Pather see current state.
func (a *teaAdapter) syncProgramModel() {
if a.program != nil {
a.program.model = a.model
}
}
func (a *teaAdapter) handleKey(m tea.KeyMsg) (tea.Model, tea.Cmd) {
key := m.String()
if key == "ctrl+c" {
return a, tea.Quit
}
focusables := collectFocusables(a.model.View(), a.renderer.Width)
if key == "tab" {
a.focus.SetIDs(focusableIDs(focusables))
a.focus.Next()
a.renderer.FocusedID = a.focus.FocusedID()
return a, nil
}
if key == "shift+tab" {
a.focus.SetIDs(focusableIDs(focusables))
a.focus.Prev()
a.renderer.FocusedID = a.focus.FocusedID()
return a, nil
}
focusedID := a.focus.FocusedID()
// Esc always escapes the focused element: blur it, then let the app
// see the key too. Without this an input (which consumes every
// printable key as text) would trap the keyboard with no way back to
// app-level shortcuts.
if key == "esc" && focusedID != "" {
a.focus.Blur()
a.renderer.FocusedID = ""
return a, a.apply(KeyMsg{Key: key, Rune: firstRune(key)})
}
if focusedID != "" {
if newModel, cmd, handled := a.routeKeyToFocused(focusedID, focusables, m); handled {
a.model = newModel
a.syncProgramModel()
return a, cmd
}
}
return a, a.apply(KeyMsg{Key: key, Rune: firstRune(key)})
}
// handleMouse activates the clickable element (button, link, input)
// under the mouse cursor on left-button release. Clicking any
// focusable also moves keyboard focus to it, so a click followed by
// typing behaves like the browser. Zones are recorded during View by
// the bubblezone Scan pass, so hit-testing uses the previous frame's
// layout — correct, since that is the frame the user clicked on.
func (a *teaAdapter) handleMouse(m tea.MouseMsg) (tea.Model, tea.Cmd) {
if m.Action != tea.MouseActionRelease || m.Button != tea.MouseButtonLeft {
return a, nil
}
focusables := collectFocusables(a.model.View(), a.renderer.Width)
for _, f := range focusables {
z := a.zones.Get(f.ID)
if z == nil || z.IsZero() || !z.InBounds(m) {
continue
}
a.focus.SetIDs(focusableIDs(focusables))
a.focus.Focus(f.ID)
a.renderer.FocusedID = f.ID
if f.IsInput {
return a, nil
}
if f.Activate != nil {
return a, a.apply(f.Activate())
}
if msg := a.submitForm(f.Form); msg != nil {
return a, a.apply(msg)
}
return a, nil
}
return a, nil
}
// routeKeyToFocused dispatches a key event to whichever element holds
// focus: text inputs get the key forwarded to their bubbles model;
// buttons and links activate on Enter via their Activate closure;
// elements inside a Form fall back to submitting the form on Enter,
// matching native browser behaviour in the HTML renderer.
func (a *teaAdapter) routeKeyToFocused(focusedID string, focusables []focusable, m tea.KeyMsg) (Model, tea.Cmd, bool) {
var target *focusable
for i := range focusables {
if focusables[i].ID == focusedID {
target = &focusables[i]
break
}
}
if target == nil {
return a.model, nil, false
}
if target.Cycle != nil {
// A Select: left/right (and up/down) step through the options,
// Enter and Space advance — the terminal analogue of opening a
// dropdown and picking the next entry. Keys a Select has no use
// for fall through to the app's Update.
delta := 0
switch m.String() {
case "left", "up":
delta = -1
case "right", "down", "enter", " ", "space":
delta = 1
}
if delta == 0 {
return a.model, nil, false
}
newModel, cmd := a.model.Update(target.Cycle(delta))
return newModel, wuiCmdToTea(cmd), true
}
if !target.IsInput {
// Enter or Space activates, matching native browser buttons
// and checkboxes. Every other key falls through to the app's
// Update — a focused button must not trap the keyboard.
if key := m.String(); key == "enter" || key == " " || key == "space" {
if target.Activate != nil {
newModel, cmd := a.model.Update(target.Activate())
return newModel, wuiCmdToTea(cmd), true
}
if msg := a.submitForm(target.Form); msg != nil {
newModel, cmd := a.model.Update(msg)
return newModel, wuiCmdToTea(cmd), true
}
return a.model, nil, true
}
return a.model, nil, false
}
if area := findAreaByID(a.model.View(), focusedID); area != nil {
return a.routeKeyToArea(*area, m)
}
el := findInputByID(a.model.View(), focusedID)
if el == nil {
return a.model, nil, false
}
in := a.renderer.ensureInput(*el)
prevValue := in.Value()
updated, _ := in.Update(m)
a.renderer.setInput(focusedID, updated)
if m.String() == "enter" {
if el.OnSubmit != nil {
newModel, cmd := a.model.Update(el.OnSubmit(updated.Value()))
return newModel, wuiCmdToTea(cmd), true
}
if msg := a.submitForm(target.Form); msg != nil {
newModel, cmd := a.model.Update(msg)
return newModel, wuiCmdToTea(cmd), true
}
return a.model, nil, true
}
if updated.Value() != prevValue {
if el.OnChange != nil {
newModel, cmd := a.model.Update(el.OnChange(updated.Value()))
return newModel, wuiCmdToTea(cmd), true
}
// No callback — emit generic InputMsg so app can still react.
newModel, cmd := a.model.Update(InputMsg{ID: focusedID, Value: updated.Value()})
return newModel, wuiCmdToTea(cmd), true
}
return a.model, nil, true
}
// routeKeyToArea edits a focused TextArea's buffer. Unlike a single
// line input, Enter inserts a newline rather than submitting — matching
// <textarea> in the browser — so a form containing one is submitted
// from its submit button.
func (a *teaAdapter) routeKeyToArea(el TextAreaEl, m tea.KeyMsg) (Model, tea.Cmd, bool) {
value := a.renderer.ensureArea(el)
next := value
switch m.String() {
case "enter":
next = value + "\n"
case "backspace":
if r := []rune(value); len(r) > 0 {
next = string(r[:len(r)-1])
}
case "ctrl+u":
next = ""
case " ", "space":
next = value + " "
case "tab", "shift+tab", "up", "down", "left", "right", "home", "end":
// Navigation keys are not text; leave the buffer untouched.
// (Esc never reaches here — handleKey blurs on esc first.)
return a.model, nil, true
default:
if r := []rune(m.String()); len(r) == 1 {
next = value + string(r)
} else {
return a.model, nil, true
}
}
if next == value {
return a.model, nil, true
}
a.renderer.setArea(el.ID, next)
if el.OnChange != nil {
newModel, cmd := a.model.Update(el.OnChange(next))
return newModel, wuiCmdToTea(cmd), true
}
// No callback — emit a generic InputMsg so the app can still react.
newModel, cmd := a.model.Update(InputMsg{ID: el.ID, Value: next})
return newModel, wuiCmdToTea(cmd), true
}
// submitForm collects the form's current input values and produces the
// form's OnSubmit Msg, or nil when there is no form or no handler.
func (a *teaAdapter) submitForm(form *FormEl) Msg {
if form == nil || form.OnSubmit == nil {
return nil
}
return form.OnSubmit(a.renderer.formValues(*form))
}
func (a *teaAdapter) View() string {
a.focus.SetIDs(focusableIDs(collectFocusables(a.model.View(), a.renderer.Width)))
a.renderer.FocusedID = a.focus.FocusedID()
// The bar is built before the body so Fill-height layouts know how
// many rows remain for them.
bar := a.statusBar()
a.renderer.Reserved = 0
if bar != "" {
a.renderer.Reserved = 1
}
view := a.renderer.Render(a.model.View())
if bar != "" {
view = a.withStatusBar(view, bar)
}
// Scan strips the zero-width zone markers and records each zone's
// on-screen rectangle for mouse hit-testing. It must run on the
// final composed frame so coordinates match what the user sees.
return a.zones.Scan(view)
}
// statusBar renders the one-line status strip, or "" when there is
// nothing to show. Content comes from the app's StatusFunc when set,
// else wui's default (web link plus key map help).
func (a *teaAdapter) statusBar() string {
if a.program == nil || a.program.cfg.noStatusBar {
return ""
}
a.syncProgramModel()
s := a.program.buildStatus()
if s.Hidden || s.Empty() {
return ""
}
line := plainStatusLine(s, a.renderer.Width)
style := styleToLipgloss(s.Style).Width(a.renderer.Width)
if s.Style == (Style{}) {
style = lipgloss.NewStyle().Reverse(true).Width(a.renderer.Width)
}
return style.Render(line)
}
// withStatusBar pins the bar to the bottom row of the screen, clipping
// and padding the body so the bar always sits on the last line.
func (a *teaAdapter) withStatusBar(view, bar string) string {
body := lipgloss.NewStyle().MaxHeight(a.renderer.Height - 1).Render(view)
if pad := a.renderer.Height - 1 - lipgloss.Height(body); pad > 0 {
body += strings.Repeat("\n", pad)
}
return body + "\n" + bar
}
func wuiCmdToTea(cmd Cmd) tea.Cmd {
if cmd == nil {
return nil
}
return func() tea.Msg {
return cmd()
}
}